package navbake
import "github.com/nsgo-dev/game/pkg/navbake"Overview
Package navbake bakes 2D navigation meshes for game/ai from level geometry: an outline with concave obstacles and holes, or a tilemap's solid cells, shrunk by an agent's radius and divided into the convex polygons ai.NavMesh searches.
A bake snaps the geometry to a fine grid and works with exact integer predicates, so it never fails on touching or overlapping obstacles and gives the same polygons for the same input on every platform. Its result, a Mesh, saves to a versioned YAML file that loads back and saves to the same bytes, and Draw shows it as a debug overlay.
Index
- Constants
- func Draw(d *core.Drawing, m *Mesh, fill, edge, portal core.Color, lineWidth float32)
- type Agent
- type Mesh
- func Bake(src Source, agent Agent, opts Options) (*Mesh, error)
- func BakeAll(src Source, agents []Agent, opts Options) ([]*Mesh, error)
- func Parse(data []byte) (*Mesh, error)
- func (m *Mesh) Encode() ([]byte, error)
- func (m *Mesh) NavMesh() *ai.NavMesh
- func (m *Mesh) Portals() []Portal
- func (m *Mesh) TiledNavMesh(tileSize float32) *ai.TiledNavMesh
- func (m *Mesh) Validate() error
- type OffMeshLink
- type Options
- type Point
- type Polygon
- type Portal
- type Source
Constants
const DefaultPrecision = 1.0 / 256DefaultPrecision is the grid step, in world units, that Options.Precision defaults to.
const FormatVersion = 1FormatVersion is the baked mesh file schema version this package reads and writes.
Functions
func Draw(d *core.Drawing, m *Mesh, fill, edge, portal core.Color, lineWidth float32)Draw fills every polygon of m in fill, outlines it in edge and strokes the portals between polygons in portal, at lineWidth world units under whatever camera transform d already has. It is meant for debug overlays; a transparent color skips that layer. It finds the portals with Mesh.Portals on every call.
Types
type Agent struct {
// Name identifies the agent type, such as "small" or "tank"; BakeAll needs it unique and not empty.
Name string
// Radius is how far the agent's center keeps from every obstacle and from the outline's edges, in world units.
Radius float32
}Agent is a kind of agent a mesh is baked for.
type Mesh struct {
// Version is the schema version; it must be FormatVersion.
Version int `yaml:"version"`
// Agent names the agent type the mesh was baked for; empty for an unnamed agent.
Agent string `yaml:"agent,omitempty"`
// Radius is the agent radius the mesh was baked for, in world units.
Radius float32 `yaml:"radius"`
// Polygons are the mesh's convex polygons.
Polygons []Polygon `yaml:"polygons"`
// Links are optional point-to-point off-mesh connections (jumps, drops, ladders, teleports) applied by NavMesh.
Links []OffMeshLink `yaml:"links,omitempty"`
}Mesh is a baked navigation mesh: convex polygons for one agent type, kept in YAML so it can be committed beside the level it was baked from and reviewed as a diff.
version: 1 agent: small radius: 4 polygons: - [[4, 4], [60, 4], [60, 28], [4, 28]] - [[60, 4], [124, 4], [124, 28], [60, 28]]
Each polygon is a list of [x, y] vertices in world units, counter-clockwise in a y-up frame (clockwise on a y-down screen), starting from its lowest vertex. A bake writes its polygons in a fixed order, so baking the same input gives the same bytes.
func Bake(src Source, agent Agent, opts Options) (*Mesh, error)Bake builds the navigation mesh of src for one agent: the walkable area, shrunk by the agent's radius, divided into convex polygons.
Obstacles are inflated by the radius with their convex corners rounded, the result is triangulated with a constrained Delaunay triangulation and the triangles are merged into convex polygons. A path that NavMesh.FindPath finds on the result keeps at least Radius from every obstacle and outline edge. Baking the same input gives the same mesh, so its YAML is byte for byte the same.
func BakeAll(src Source, agents []Agent, opts Options) ([]*Mesh, error)BakeAll bakes one mesh per agent type from the same source, in the order of agents, sharing the work that does not depend on the radius.
func Parse(data []byte) (*Mesh, error)Parse decodes and validates a baked mesh file. Unknown fields, a second YAML document and any value Validate refuses are errors.
func (m *Mesh) Encode() ([]byte, error)Encode validates m and writes it as YAML with two-space indentation, fields in a fixed order and one polygon per line, so encoding a parsed file gives back the same bytes for files written in that form.
func (m *Mesh) NavMesh() *ai.NavMeshNavMesh builds the ai.NavMesh of m, ready for FindPath; polygons that touch along an edge are connected there, and any OffMeshLinks stored in m.Links are registered via AddOffMeshLink.
func (m *Mesh) Portals() []PortalPortals returns the shared edges between the polygons of m, ordered by From then To. It buckets the polygons' bounds on a uniform grid and compares only polygons whose bounds touch, so it takes time near linear in the number of polygons for a baked mesh; a game that draws them every frame should still keep the result.
func (m *Mesh) TiledNavMesh(tileSize float32) *ai.TiledNavMeshTiledNavMesh builds an ai.TiledNavMesh partitioned into fixed square tiles of size tileSize from m's baked polygons, ready for runtime tile replacement and dynamic obstacle carving.
func (m *Mesh) Validate() errorValidate reports the first problem with m: a version other than FormatVersion, a radius that is negative or not finite, or a polygon with fewer than three vertices, a coordinate that is not finite, or a shape that is not convex, wound counter-clockwise in a y-up frame with a positive area.
type OffMeshLink struct {
// ID is an optional game-defined link identifier.
ID int `yaml:"id,omitempty"`
// Start is the world-space [x, y] entry point of the link.
Start Point `yaml:"start"`
// End is the world-space [x, y] exit point of the link.
End Point `yaml:"end"`
// Radius is the optional endpoint snap and entry tolerance in world units (>= 0).
Radius float32 `yaml:"radius,omitempty"`
// Bidirectional allows traversal from End to Start as well as Start to End when true.
Bidirectional bool `yaml:"bidirectional,omitempty"`
// Cost overrides the A* traversal cost when positive; 0 uses 2D Euclidean distance.
Cost float32 `yaml:"cost,omitempty"`
// Area is the link's navigation area ID (0 for default).
Area ai.NavArea `yaml:"area,omitempty"`
// Flags holds optional custom link flag bits; ai.NavLinkOffMesh is always added on load.
Flags uint32 `yaml:"flags,omitempty"`
// UserData holds optional game-defined metadata (such as "jump", "ladder", or "teleport").
UserData string `yaml:"userData,omitempty"`
}OffMeshLink is a point-to-point off-mesh connection stored in a baked 2D navigation mesh, such as a jump, drop-down, ladder, or teleporter.
type Options struct {
// Precision is the grid step that the bake snaps every point to, in world units; zero means DefaultPrecision. Coordinates, and the obstacles once grown by an agent's radius, must stay within 2^24 steps of the origin (65536 world units at DefaultPrecision), the largest grid that the float32 coordinates of a Mesh hold exactly; a gap or sliver of an obstacle thinner than one step may close or vanish.
Precision float32
}Options tunes a bake. The zero value is ready to use.
type Point [2]float32Point is a 2D position in world space, written as a flow [x, y] list.
func (p Point) CorePoint() core.PointCorePoint returns p as a core.Point.
func (p Point) MarshalYAML() (any, error)MarshalYAML writes p as a flow [x, y] sequence, each coordinate in the shortest form that reads back as the same float32.
type Polygon []core.PointPolygon is one convex polygon of a Mesh. In YAML it is a flow sequence of [x, y] pairs on one line.
func (p Polygon) MarshalYAML() (any, error)MarshalYAML writes p as a flow sequence of [x, y] pairs, each coordinate in the shortest form that reads back as the same float32.
func (p *Polygon) UnmarshalYAML(node *yaml.Node) errorUnmarshalYAML reads p from a sequence of [x, y] pairs.
type Portal struct {
// A and B are the ends of the shared stretch.
A, B core.Point
// From and To are the indices of the two polygons, From < To.
From, To int
}Portal is the stretch of edge two polygons of a Mesh share, which an agent crosses to go from one to the other.
type Source struct {
// Outlines are the walkable areas, such as a level's outer boundary.
Outlines [][]core.Point
// Obstacles are the blocked areas inside the outlines, such as walls, pillars and holes.
Obstacles [][]core.Point
// Links are optional point-to-point off-mesh connections (jumps, drops, ladders, teleports) stored on every baked Mesh.
Links []OffMeshLink
}Source is the level geometry a navigation mesh is baked from: the areas agents may walk and the obstacles inside them, as polygons in world units.
Polygons may be concave, may overlap and may be wound either way: a point is walkable when it is inside the outlines and outside the obstacles under the nonzero winding rule. Two overlapping polygons wound in opposite directions cancel where they overlap, which is how a tilemap's walkable pocket inside a solid block is described.
func FromTilemap(m *tilemap.Tilemap, mask tilemap.TileFlags) (Source, error)FromTilemap returns the source of a tilemap's navigation mesh in world space: the map's area is the outline and every cell whose flags match mask (across all tile layers, as Tilemap.FlagsAt combines them) is an obstacle, such as mask = tilemap.TileSolid.
Cells are the shapes the map's Orientation gives them: squares on an orthogonal map, diamonds on an isometric or staggered one and hexagons on a hexagonal one, so the mesh lines up with the tiles drawn. Neighbouring solid cells merge into one obstacle when the mesh is baked.