La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.
package worldmap
import "github.com/nsgo-dev/game/pkg/worldmap"Resumen
Package worldmap keeps track of which rooms of a game world the player has discovered and draws them as a minimap of the current area and a world map, with markers.
Map Definitions
A map is defined in a versioned YAML document (Doc): rooms with an ID, an optional name and area, world-space bounds and links to neighbouring rooms, plus fixed markers such as save points or bosses. Parse refuses unknown fields, unsupported versions, duplicate IDs, links to missing rooms and rooms that overlap inside one area; Encode writes deterministic 2-space YAML that parses back to an equal Doc and encodes again to the same bytes; comments and hand-written formatting are not preserved.
Discovery
New builds a Map from a Doc. Visit finds the room under the player's position and marks it visited, Enter marks a room by ID (for room transitions), and Reveal marks rooms as known without visiting them (for a map item). Players can also place their own markers with AddMarker.
State returns the discovered rooms, the current room and the player's markers as a value with sorted lists that encodes to the same JSON every time, so it can be stored in a save.Store slot; Restore validates such a value against the map and applies it, or changes nothing.
Drawing
DrawMinimap draws the discovered rooms of the current room's area around the player at a fixed scale, clipped to a rectangle. DrawWorldMap fits a whole area into a rectangle and draws its discovered rooms. Rooms that are neither visited nor revealed, and the markers in them, are never drawn. Both views take a Style and use a Projection, which also converts a point on the drawn map back to world coordinates (to place a marker where the player taps).
Tile Minimap
TileMinimap renders a tilemap.Tilemap's layers into a compact cached RGBA image with one color per tile (from a tile custom property, or else the average color of its tileset image), updating only cells changed via Tilemap.SetTile. It overlays a team's fog.Fog cached by fog.Revision so unchanged frames skip recompositing, draws unit and point-of-interest markers and a tilemap.Camera's visible rectangle, supports both orthogonal maps and diamond isometric maps, and converts clicks back to world coordinates with MinimapToWorld and PanCamera.
Índice
- Constantes
- Variables
- func Encode(doc *Doc) ([]byte, error)
- func Validate(doc *Doc) error
- type Discovery
- type Doc
- type Map
- func Load(data []byte) (*Map, error)
- func New(doc *Doc) (*Map, error)
- func (m *Map) AddMarker(mk Marker) error
- func (m *Map) AreaBounds(area string) (math2d.Rect, bool)
- func (m *Map) Areas() []string
- func (m *Map) Current() (string, bool)
- func (m *Map) DrawMinimap(d *core.Drawing, dst core.Bounds, player math2d.Vec2, scale float32, style *Style)
- func (m *Map) DrawWorldMap(d *core.Drawing, dst core.Bounds, area string, player *math2d.Vec2, style *Style)
- func (m *Map) Enter(id string) (first bool, err error)
- func (m *Map) Explored(area string) (visited, total int)
- func (m *Map) Markers() []Marker
- func (m *Map) PlayerMarkers() []Marker
- func (m *Map) RemoveMarker(id string) bool
- func (m *Map) Reset()
- func (m *Map) Restore(s State) error
- func (m *Map) Reveal(ids ...string) error
- func (m *Map) RevealArea(area string) error
- func (m *Map) Revealed() []string
- func (m *Map) Room(id string) (Room, bool)
- func (m *Map) RoomAt(p math2d.Vec2) (string, bool)
- func (m *Map) Rooms() []Room
- func (m *Map) State() State
- func (m *Map) Status(id string) Discovery
- func (m *Map) VisibleMarkers() []Marker
- func (m *Map) Visit(p math2d.Vec2) (id string, first bool)
- func (m *Map) Visited() []string
- func (m *Map) WorldMapProjection(dst core.Bounds, area string, padding float32) (Projection, bool)
- type Marker
- type Projection
- type Room
- type RoomDoc
- type State
- type Style
- type TileMarker
- type TileMinimap
- func NewTileMinimap(m *tilemap.Tilemap, opts *TileMinimapOptions) *TileMinimap
- func (tm *TileMinimap) Draw(d *core.Drawing, dst core.Bounds, overlay *TileMinimapOverlay, style *TileMinimapStyle)
- func (tm *TileMinimap) Image() *image.RGBA
- func (tm *TileMinimap) Invalidate()
- func (tm *TileMinimap) MinimapToWorld(dst core.Bounds, pos math2d.Vec2, style *TileMinimapStyle) (math2d.Vec2, bool)
- func (tm *TileMinimap) PanCamera(cam *tilemap.Camera, dst core.Bounds, click math2d.Vec2, style *TileMinimapStyle) bool
- func (tm *TileMinimap) Projection(dst core.Bounds, padding float32) (Projection, bool)
- func (tm *TileMinimap) Sync(f *fog.Fog, team fog.Team, style *TileMinimapStyle) core.ImageSource
- func (tm *TileMinimap) TerrainImage() *image.RGBA
- func (tm *TileMinimap) WorldToMinimap(dst core.Bounds, world math2d.Vec2, style *TileMinimapStyle) (math2d.Vec2, bool)
- type TileMinimapOptions
- type TileMinimapOverlay
- type TileMinimapStyle
Constantes
const DefaultTileColorProperty = "minimap_color"DefaultTileColorProperty is the tile custom property name checked first when choosing a tile's minimap color.
const StateVersion = 1StateVersion is the schema version of State values written by Map.State and accepted by Map.Restore.
const Version = 1Version is the map definition schema version this package reads and writes.
Variables
var (
// ErrUnknownRoom reports a room ID that the map does not define.
ErrUnknownRoom = errors.New("worldmap: unknown room")
// ErrInvalidMarker reports a marker that is malformed, outside its room or whose ID is already taken.
ErrInvalidMarker = errors.New("worldmap: invalid marker")
// ErrInvalidState reports a State that does not match the map or the state schema.
ErrInvalidState = errors.New("worldmap: invalid state")
)Funciones
func Encode(doc *Doc) ([]byte, error)Encode validates doc and writes it as deterministic 2-space YAML that Parse reads back to an equal Doc, and that encodes again to the same bytes. Comments, flow style and other formatting of a hand-written file are not preserved.
func Validate(doc *Doc) errorValidate checks doc against the version 1 schema: a supported version, at least one room, unique non-empty IDs, finite coordinates, positive sizes that survive float32 rounding at the room's position, areas whose combined bounds fit in float32, links to other existing rooms with no pair listed twice, no overlapping rooms within an area, and fixed markers inside existing rooms.
Tipos
type Discovery uint8Discovery is how much the player knows about a room.
const (
// Unknown rooms are not drawn.
Unknown Discovery = iota
// Revealed rooms are known, for example from a map item, but have not been entered; they are drawn in Style.Revealed.
Revealed
// Visited rooms have been entered; they are drawn in Style.Visited.
Visited
)func (d Discovery) String() stringString returns "unknown", "revealed" or "visited".
type Doc struct {
// Version is the schema version; it must equal Version (1).
Version int `yaml:"version"`
// Rooms are the map's rooms. Their order decides which room wins a lookup when rooms of different areas overlap, and the order they are drawn in.
Rooms []RoomDoc `yaml:"rooms"`
// Markers are fixed markers placed by the map's author, shown once their room is discovered.
Markers []Marker `yaml:"markers,omitempty"`
}Doc is the root of a versioned YAML map definition.
func Parse(data []byte) (*Doc, error)Parse decodes a YAML map definition and validates it. Unknown fields and trailing YAML documents are refused.
type Map struct {
// contains filtered or unexported fields
}Map holds a map definition and what the player has discovered of it. It is not safe for concurrent use.
func Load(data []byte) (*Map, error)Load parses a YAML map definition and builds a Map from it.
func New(doc *Doc) (*Map, error)New validates doc and builds a Map with nothing discovered. The Map keeps its own copy of the definition, so later changes to doc do not affect it.
func (m *Map) AddMarker(mk Marker) errorAddMarker places a player marker. The marker needs a non-empty ID not used by any other marker, a kind, and a position inside an existing room; otherwise AddMarker returns an error wrapping ErrInvalidMarker and changes nothing.
func (m *Map) AreaBounds(area string) (math2d.Rect, bool)AreaBounds returns the smallest rectangle holding every room of area, discovered or not.
func (m *Map) Areas() []stringAreas returns the names of the map's areas, sorted.
func (m *Map) Current() (string, bool)Current returns the ID of the room the player was last in, if any.
func (m *Map) DrawMinimap(d *core.Drawing, dst core.Bounds, player math2d.Vec2, scale float32, style *Style)DrawMinimap draws the discovered rooms of the current room's area (the default area when there is no current room) around the player's world position, at scale map points per world unit, clipped to dst. The player's square is drawn at the center of dst. It draws nothing when the projection is not finite (see MinimapProjection), such as for a NaN or infinite player position.
func (m *Map) DrawWorldMap(d *core.Drawing, dst core.Bounds, area string, player *math2d.Vec2, style *Style)DrawWorldMap draws the discovered rooms of area fitted into dst (see WorldMapProjection). When player is not nil and finite and the current room is in area, the player's square is drawn at that world position. It draws nothing when the map has no such area.
func (m *Map) Enter(id string) (first bool, err error)Enter marks the room as visited and makes it the current room, as when a room transition moves the player into it. It reports whether this is the first visit.
func (m *Map) Explored(area string) (visited, total int)Explored returns how many rooms of area are visited and how many it has, for a completion percentage.
func (m *Map) Markers() []MarkerMarkers returns every marker, fixed and player-placed, sorted by ID, whether or not its room is discovered.
func (m *Map) PlayerMarkers() []MarkerPlayerMarkers returns the markers placed with AddMarker, sorted by ID.
func (m *Map) RemoveMarker(id string) boolRemoveMarker removes the player marker with the given ID and reports whether there was one. Fixed markers from the definition cannot be removed.
func (m *Map) Reset()Reset forgets everything discovered, the current room and the player's markers.
func (m *Map) Restore(s State) errorRestore replaces the map's discovery, current room and player markers with s. It checks s first and, on any problem (another version, an unknown or repeated room, a current room that is not visited, an invalid marker), returns an error wrapping ErrInvalidState and changes nothing.
A save that names a room the definition no longer has is refused; when a game renames or removes rooms, add a save.Store migration that rewrites the saved IDs.
func (m *Map) Reveal(ids ...string) errorReveal marks unknown rooms as revealed, as a map item would. Visited rooms stay visited. It changes nothing and returns an error wrapping ErrUnknownRoom if any ID is unknown.
func (m *Map) RevealArea(area string) errorRevealArea reveals every unknown room of area. It returns an error wrapping ErrUnknownRoom when the map has no such area.
func (m *Map) Revealed() []stringRevealed returns the IDs of the rooms that are revealed but not visited, sorted.
func (m *Map) Room(id string) (Room, bool)Room returns the room with the given ID.
func (m *Map) RoomAt(p math2d.Vec2) (string, bool)RoomAt returns the ID of the room containing p (half-open bounds, as math2d.Rect.Contains). When rooms of different areas overlap, the current room wins, then rooms of the current area, then the first room in definition order; with no current room, the first room in definition order wins.
func (m *Map) Rooms() []RoomRooms returns every room in definition order. The returned slice is a copy.
func (m *Map) State() StateState returns what the map has discovered and the player's markers.
func (m *Map) Status(id string) DiscoveryStatus returns how much the player knows about the room; Unknown for an ID the map does not define.
func (m *Map) VisibleMarkers() []MarkerVisibleMarkers returns the markers whose room is revealed or visited, sorted by ID.
func (m *Map) Visit(p math2d.Vec2) (id string, first bool)Visit marks the room under the player's position p (chosen as RoomAt does) as visited and makes it the current room. It returns that room's ID and whether this is the first visit; when p is in no room, it returns "" and false and keeps the current room.
func (m *Map) Visited() []stringVisited returns the IDs of the visited rooms, sorted.
func (m *Map) WorldMapProjection(dst core.Bounds, area string, padding float32) (Projection, bool)WorldMapProjection fits every room of area, discovered or not, into dst inset by padding, keeping the aspect ratio and centering it, so the layout does not shift as rooms are discovered. It returns false when the map has no such area or the inset dst is empty.
type Marker struct {
// ID uniquely identifies the marker among the map's fixed markers and the player's markers.
ID string `yaml:"id" json:"id"`
// Kind says what the marker is, such as "save" or "boss"; Style.MarkerKinds can color each kind.
Kind string `yaml:"kind" json:"kind"`
// Room is the ID of the room the marker is in; the marker is shown once that room is discovered.
Room string `yaml:"room" json:"room"`
// X and Y are the marker's position in world coordinates, inside the room's bounds (edges included).
X float32 `yaml:"x" json:"x"`
Y float32 `yaml:"y" json:"y"`
// Label is optional text for the marker, such as a player's note.
Label string `yaml:"label,omitempty" json:"label,omitempty"`
}Marker is a point of interest inside a room: fixed in a Doc, or placed by the player with Map.AddMarker.
type Projection struct {
// Scale is map points per world unit; always positive for projections this package returns.
Scale float32
// Offset is where the world origin lands on the map.
Offset math2d.Vec2
}Projection maps world coordinates onto a drawn map: a map point is world*Scale + Offset.
func MinimapProjection(dst core.Bounds, center math2d.Vec2, scale float32) ProjectionMinimapProjection centers the world point center in dst at scale map points per world unit; a scale that is not positive and finite behaves as 1. The Offset is not finite when center is not, or when center*scale overflows float32.
func (p Projection) RectToMap(r math2d.Rect) math2d.RectRectToMap converts a world rectangle to the drawn map.
func (p Projection) ToMap(v math2d.Vec2) math2d.Vec2ToMap converts a world point to a point on the drawn map.
func (p Projection) ToWorld(v math2d.Vec2) math2d.Vec2ToWorld converts a point on the drawn map, such as a tap, back to world coordinates. It returns the world origin when Scale is 0.
type Room struct {
// ID uniquely identifies the room.
ID string
// Name is the room's display name, possibly empty.
Name string
// Area is the area the room belongs to; empty is the default area.
Area string
// Bounds is the room's rectangle in world coordinates.
Bounds math2d.Rect
// Links are the IDs of the rooms connected to this one, in both directions, sorted.
Links []string
}Room is a room of a built Map.
type RoomDoc struct {
// ID uniquely identifies the room; it is what saves refer to.
ID string `yaml:"id"`
// Name is an optional display name.
Name string `yaml:"name,omitempty"`
// Area groups rooms that share one map, such as a floor or a region. Rooms in the same area must not overlap. Empty is the default area.
Area string `yaml:"area,omitempty"`
// X and Y are the room's top-left corner in world coordinates.
X float32 `yaml:"x"`
Y float32 `yaml:"y"`
// Width and Height are the room's size in world units; both must be positive.
Width float32 `yaml:"width"`
Height float32 `yaml:"height"`
// Links are the IDs of rooms this room connects to, such as through a door. Links are undirected, so each pair is listed once, on either room.
Links []string `yaml:"links,omitempty,flow"`
}RoomDoc describes one room of a map definition.
type State struct {
// Version is the state schema version; Map.State writes StateVersion.
Version int `json:"version" yaml:"version"`
// Current is the ID of the room the player was last in, or empty.
Current string `json:"current,omitempty" yaml:"current,omitempty"`
// Visited holds the IDs of the visited rooms, sorted.
Visited []string `json:"visited" yaml:"visited"`
// Revealed holds the IDs of the rooms revealed but not visited, sorted.
Revealed []string `json:"revealed,omitempty" yaml:"revealed,omitempty"`
// Markers holds the player's markers, sorted by ID; fixed markers come from the definition and are not saved.
Markers []Marker `json:"markers,omitempty" yaml:"markers,omitempty"`
}State is what a Map has discovered, in a form a save.Store slot (JSON) or a YAML file can hold. Lists are sorted, so equal states encode to equal bytes. Decoding from either format refuses unknown fields.
func (s *State) UnmarshalJSON(data []byte) errorUnmarshalJSON decodes a State, refusing unknown fields and trailing data so a mistyped or foreign save is reported instead of silently dropped.
func (s *State) UnmarshalYAML(n *yaml.Node) errorUnmarshalYAML decodes a State from YAML, refusing unknown fields as UnmarshalJSON does.
type Style struct {
// Background fills the whole destination rectangle first.
Background core.Color
// Visited, Revealed and Current fill visited rooms, revealed rooms and the current room. A transparent Current fills the current room with Visited, so it is drawn like any other visited room.
Visited, Revealed, Current core.Color
// Border outlines every drawn room with BorderWidth.
Border core.Color
BorderWidth float32
// Link draws a line of LinkWidth between the centers of two linked rooms when both are discovered and in the drawn area.
Link core.Color
LinkWidth float32
// Marker is the color of markers whose kind is not in MarkerKinds; each marker is a square MarkerSize points wide.
Marker core.Color
MarkerKinds map[string]core.Color
MarkerSize float32
// Player is the color of the square PlayerSize points wide drawn at the player's position.
Player core.Color
PlayerSize float32
// Padding insets the world map from the destination rectangle, in points.
Padding float32
}Style sets the colors and sizes DrawMinimap and DrawWorldMap use. A zero (fully transparent) color leaves that part out, except Current (see below), and a zero size uses DefaultStyle's.
func DefaultStyle() StyleDefaultStyle returns a dark style with lighter visited rooms, dim revealed rooms and a highlighted current room.
type TileMarker struct {
// Position is the marker's location in world coordinates.
Position math2d.Vec2
// Kind selects a color from TileMinimapStyle.MarkerKinds when Color is transparent.
Kind string
// Color, when non-transparent, overrides Kind and TileMinimapStyle.Marker for this marker.
Color core.Color
// Size is the marker square's width and height in minimap points; <= 0 uses TileMinimapStyle.MarkerSize.
Size float32
// RequireVisible, when true and a fog.Fog is drawn, hides this marker unless its map cell is currently fog.Visible to the drawn team.
RequireVisible bool
}TileMarker is a unit blip or point of interest drawn on a TileMinimap in world coordinates.
type TileMinimap struct {
// contains filtered or unexported fields
}TileMinimap renders a tilemap.Tilemap's tile layers to a compact cached RGBA image with one color per tile, incrementally updating only cells changed via Tilemap.SetTile (or small FillRect calls), optionally overlaying a team's fog.Fog cached by fog.Revision, and drawing unit/POI markers and the camera's visible rectangle.
Orthogonal maps render 1 pixel per tile; isometric maps render as a solid diamond aligned with Tilemap.WorldBounds. A TileMinimap is not safe for concurrent use.
func NewTileMinimap(m *tilemap.Tilemap, opts *TileMinimapOptions) *TileMinimapNewTileMinimap builds a TileMinimap for m and renders its initial terrain image.
func (tm *TileMinimap) Draw(d *core.Drawing, dst core.Bounds, overlay *TileMinimapOverlay, style *TileMinimapStyle)Draw updates the minimap image incrementally and draws the terrain, optional fog, unit/POI markers, and camera rectangle into d, clipped to dst.
func (tm *TileMinimap) Image() *image.RGBAImage returns the latest rendered minimap image: the fog-composited image when the last Sync or Draw used a fog.Fog, otherwise the terrain image.
func (tm *TileMinimap) Invalidate()Invalidate clears cached tile colors and forces the next Sync or Draw to rebuild the full terrain image. Call this after mutating layer.Data directly, toggling layer.Visible/Opacity, or editing tile properties/tilesets.
func (tm *TileMinimap) MinimapToWorld(dst core.Bounds, pos math2d.Vec2, style *TileMinimapStyle) (math2d.Vec2, bool)MinimapToWorld converts a point in dst's coordinate space (such as a pointer click) into world coordinates using style's Padding.
func (tm *TileMinimap) PanCamera(cam *tilemap.Camera, dst core.Bounds, click math2d.Vec2, style *TileMinimapStyle) boolPanCamera centers cam on the world point under click when click lies inside dst, then calls cam.Clamp(). It returns false without modifying cam when cam is nil, click is outside dst or non-finite, or the minimap projection is empty.
func (tm *TileMinimap) Projection(dst core.Bounds, padding float32) (Projection, bool)Projection fits the tilemap's WorldBounds into dst inset by padding, preserving aspect ratio and centering it. It returns false when the tilemap is empty or the inset dst is empty.
func (tm *TileMinimap) Sync(f *fog.Fog, team fog.Team, style *TileMinimapStyle) core.ImageSourceSync brings the cached terrain image (incrementally for SetTile edits) and optional fog overlay (skipping unchanged fog.Revision frames) up to date, returning the core.ImageSource ready to draw.
func (tm *TileMinimap) TerrainImage() *image.RGBATerrainImage returns the cached fog-free terrain image, or nil for an empty map.
func (tm *TileMinimap) WorldToMinimap(dst core.Bounds, world math2d.Vec2, style *TileMinimapStyle) (math2d.Vec2, bool)WorldToMinimap converts a world-space point into minimap coordinates inside dst using style's Padding.
type TileMinimapOptions struct {
// ColorProperty names the tile custom property providing an explicit minimap color (parsed via tilemap.Properties.Color). Empty uses DefaultTileColorProperty.
ColorProperty string
// Images maps tileset image URIs (with or without an "asset:" prefix) or tileset names to decoded image.Image pixel data for average-color sampling. Tilesets whose Image.Pixels or Image.Data is already populated do not need an entry.
Images map[string]image.Image
// Layers limits rendering to these tile layer indices in order; nil or empty composites every visible tile layer in map order.
Layers []int
// TileColor optionally overrides color lookup for a stripped tile GID; returning ok=false falls back to ColorProperty and then the tile's average tileset image color.
TileColor func(tileID uint32) (core.Color, bool)
}TileMinimapOptions configures how NewTileMinimap resolves tile colors and selects layers.
type TileMinimapOverlay struct {
// Fog, when non-nil, overlays Team's fog of war on the minimap image, skipping recomposition when Fog.Revision(Team) has not changed.
Fog *fog.Fog
// Team selects which team's fog of war to display.
Team fog.Team
// Camera, when non-nil, draws the camera's visible rectangle over the minimap.
Camera *tilemap.Camera
// Markers are unit blips and points of interest drawn in world coordinates.
Markers []TileMarker
}TileMinimapOverlay holds the per-frame overlays drawn on top of a TileMinimap's terrain.
type TileMinimapStyle struct {
// Background fills the destination rectangle before drawing the terrain image.
Background core.Color
// Border outlines the destination rectangle with BorderWidth.
Border core.Color
BorderWidth float32
// Fog sets the colors laid over Unseen and Explored cells when a fog.Fog is attached. When both are transparent, fog.DefaultStyle() is used.
Fog fog.Style
// Camera outlines the camera's visible rectangle with CameraWidth.
Camera core.Color
CameraWidth float32
// Marker is the default color for markers that do not set Color or match MarkerKinds.
Marker core.Color
MarkerKinds map[string]core.Color
MarkerSize float32
// Padding insets the fitted map inside the destination rectangle, in points.
Padding float32
}TileMinimapStyle sets the colors, stroke widths, marker sizes, and padding used by TileMinimap.Draw.
A zero (transparent) color leaves that element out, except Fog: when both Fog.Unseen and Fog.Explored are transparent, fog.DefaultStyle() is used. Non-positive widths or sizes use DefaultTileMinimapStyle's.
func DefaultTileMinimapStyle() TileMinimapStyleDefaultTileMinimapStyle returns a dark style with a white camera frame, gold default markers, and fog.DefaultStyle().