A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.
package navbake3d
import "github.com/nsgo-dev/game/pkg/navbake3d"Visão geral
Package navbake3d bakes 3D navigation meshes from level geometry, as Recast, Godot's NavigationRegion3D and Unity's NavMeshSurface do, so a 3D game no longer authors world3d.NavMesh polygons by hand. Package navbake bakes the 2D ai.NavMesh instead.
A Geometry collects the level's triangles from glTF models, scene3d scenes and sceneformat scene files, world3d terrain heightmaps and GridMaps, and physics3d static colliders, each on layers a Settings.LayerMask selects from. Bake rasterizes them into a heightfield, keeps the surfaces an agent type can stand on (no steeper than its MaxSlope, with its Height of clearance), lets it step up and down its MaxClimb, keeps its Radius from walls and ledges, partitions the walkable area into regions, traces and simplifies their outlines and splits them into convex polygons with triangles that follow the height of the ground. Each AgentType gets a mesh of its own.
The result is a File, a versioned YAML document a sceneformat scene names in its navMesh field: Encode writes the same bytes for the same level every time, and Parse then Encode changes nothing. Mesh.NavMesh turns one agent type's mesh into the world3d.NavMesh that finds paths, DrawDebug and Mesh.DebugLines show it, and the game navmesh command bakes a scene from the command line.
Índice
- Constantes
- Variáveis
- func BakeTile(g *Geometry, settings Settings, agent AgentType, coord world3d.ChunkCoord, tileSize float32, origin math3d.Vec3) (*world3d.NavTile, error)
- func ColliderMesh(n *scene3d.Node) ([]math3d.Vec3, error)
- func DrawDebug(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds, m *Mesh, style DebugStyle)
- func Encode(f *File) ([]byte, error)
- func GLTFTriangles(doc *gltf.Document) []math3d.Vec3
- func IsModelPath(p string) bool
- func Validate(f *File) error
- type AgentType
- type DebugStyle
- type File
- type Geometry
- func (g *Geometry) AddGLTF(doc *gltf.Document, world math3d.Mat4, layer uint32)
- func (g *Geometry) AddGridMap(gm *world3d.GridMap, layer uint32)
- func (g *Geometry) AddGridMapFile(fsys fs.FS, name string, layer uint32) error
- func (g *Geometry) AddHeightmap(h *world3d.Heightmap, layer uint32)
- func (g *Geometry) AddMesh(positions []math3d.Vec3, indices []uint32, world math3d.Mat4, layer uint32)
- func (g *Geometry) AddOffMeshLink(link OffMeshLink)
- func (g *Geometry) AddPhysicsWorld(w *physics3d.World, mask uint32)
- func (g *Geometry) AddPrimitive(name string, world math3d.Mat4, layer uint32) error
- func (g *Geometry) AddScene(s *scene3d.Scene, mask uint32, mesh NodeMesh) error
- func (g *Geometry) AddSceneFile(doc *sceneformat.SceneDoc, fsys fs.FS) error
- func (g *Geometry) AddTerrainFile(fsys fs.FS, name string, layer uint32) error
- func (g *Geometry) AddTriangle(a, b, c math3d.Vec3, layer uint32)
- func (g *Geometry) OffMeshLinks() []OffMeshLink
- func (g *Geometry) TriangleCount() int
- type Mesh
- func BakeMesh(g *Geometry, settings Settings, agent AgentType) (*Mesh, error)
- func (m *Mesh) DebugLines(polygonsOnly bool) [][2]math3d.Vec3
- func (m *Mesh) NavMesh() *world3d.NavMesh
- func (m *Mesh) TiledNavMesh(tileSize float32) *world3d.TiledNavMesh
- func (m *Mesh) TriangleVertices(p *Polygon, t Triangle) [3]math3d.Vec3
- type NodeMesh
- type OffMeshLink
- type Point
- type Polygon
- type Settings
- type Triangle
Constantes
const (
// DefaultCellSize is the default width and depth of one heightfield cell.
DefaultCellSize float32 = 0.3
// DefaultCellHeight is the default height of one heightfield cell.
DefaultCellHeight float32 = 0.2
// DefaultMinRegionArea is the default smallest area of an island of walkable surface that is kept.
DefaultMinRegionArea float32 = 1
// DefaultMaxEdgeLength is the default longest a polygon edge along a wall may be before it is split.
DefaultMaxEdgeLength float32 = 12
// DefaultMaxSimplificationError is the default farthest a simplified wall outline may stray from the walkable area's cell outline.
DefaultMaxSimplificationError float32 = 0.4
// DefaultMaxVertsPerPoly is the default largest number of vertices in one convex polygon.
DefaultMaxVertsPerPoly = 6
// DefaultDetailSampleDistance is the default spacing of the height samples the detail mesh is built from.
DefaultDetailSampleDistance float32 = 1.8
// DefaultDetailSampleMaxError is the default farthest the detail mesh may stray from the sampled height of the surface.
DefaultDetailSampleMaxError float32 = 0.2
)Default bake settings, in world units unless noted, as Recast's sample uses them for a human-sized agent.
const (
// DefaultAgentRadius is the default radius of an agent.
DefaultAgentRadius float32 = 0.6
// DefaultAgentHeight is the default height of an agent.
DefaultAgentHeight float32 = 2
// DefaultAgentMaxSlope is the default steepest walkable slope in degrees.
DefaultAgentMaxSlope float32 = 45
// DefaultAgentMaxClimb is the default highest step an agent climbs.
DefaultAgentMaxClimb float32 = 0.9
)Defaults of an agent type whose fields are zero.
const FormatVersion = 1FormatVersion is the navigation mesh file schema version this package reads and writes.
const MaxCells = 1 << 24MaxCells is the most heightfield cells (columns across times rows deep) one bake allocates; a larger level needs a larger CellSize.
const MaxVertsPerPolyLimit = 12MaxVertsPerPolyLimit is the largest MaxVertsPerPoly a bake accepts.
const SchemaURL = "https://game.nsgo.dev/schemas/navmesh.v1.json"SchemaURL is where the JSON Schema of version 1 navigation mesh files is published.
Variáveis
var ErrNoGeometry = errors.New("navbake3d: no level geometry on the selected layers")ErrNoGeometry is returned by Bake and BakeMesh when no triangle of the geometry is on a layer the settings select.
Funções
func BakeTile(g *Geometry, settings Settings, agent AgentType, coord world3d.ChunkCoord, tileSize float32, origin math3d.Vec3) (*world3d.NavTile, error)BakeTile bakes one independent world3d.NavTile for chunk coordinate coord from g's triangles overlapping that tile (expanded by an erosion border so wall clearance near tile edges matches a full-level bake). Resulting walkable triangles are clipped cleanly to the tile's exact XZ bounds so neighboring tiles link seamlessly when installed in a world3d.TiledNavMesh.
When no selected geometry overlaps the tile, BakeTile returns an empty *world3d.NavTile and a nil error.
func ColliderMesh(n *scene3d.Node) ([]math3d.Vec3, error)ColliderMesh is the NodeMesh that reads a node's *scene3d.MeshCollider.
func DrawDebug(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds, m *Mesh, style DebugStyle)DrawDebug strokes m's polygon outlines and, unless style.HideDetail is set, its detail triangles onto d, projected by viewProj, a [0, 1] depth projection such as math3d.Perspective or a render3d camera's, into viewport, clipped at the near plane. Zero style fields take DefaultDebugStyle's. In a release build it draws nothing.
func Encode(f *File) ([]byte, error)Encode validates f and writes it as deterministic 2-space YAML that Parse reads back unchanged.
func GLTFTriangles(doc *gltf.Document) []math3d.Vec3GLTFTriangles returns the triangles AddGLTF would add from doc with an identity world matrix, three vertices per triangle.
func IsModelPath(p string) boolIsModelPath reports whether p names a glTF model, a .gltf or .glb file, as a scene object's model does (sceneformat.IsModelPath).
func Validate(f *File) errorValidate checks that f conforms to the version 1 schema: positive settings, distinct valid agent types, finite coordinates, and polygons and triangles whose indices are in range.
Tipos
type AgentType struct {
// Name uniquely identifies the agent type, such as "humanoid".
Name string `yaml:"name" schema:"required,minLength=1"`
// Radius is how far the mesh keeps from walls and ledges; 0 uses DefaultAgentRadius.
Radius float32 `yaml:"radius" schema:"minimum=0"`
// Height is the clearance the agent needs; spaces under ceilings lower than it are left out. 0 uses DefaultAgentHeight.
Height float32 `yaml:"height" schema:"minimum=0"`
// MaxSlope is the steepest surface the agent walks on, in degrees from horizontal, below 90; 0 uses DefaultAgentMaxSlope.
MaxSlope float32 `yaml:"maxSlope" schema:"minimum=0,exclusiveMaximum=90"`
// MaxClimb is the highest step, such as a stair's riser, the agent walks up or down; 0 uses DefaultAgentMaxClimb.
MaxClimb float32 `yaml:"maxClimb" schema:"minimum=0"`
}AgentType is a named kind of agent a navigation mesh is baked for, such as a humanoid or a large creature. A level bakes one mesh per agent type, as Unity's agent types and Godot's per-agent navigation meshes do.
type DebugStyle struct {
// PolygonColor strokes the polygons' outlines; 0 uses DefaultDebugStyle's.
PolygonColor core.Color
// DetailColor strokes the detail triangles' inner edges; 0 uses DefaultDebugStyle's.
DetailColor core.Color
// LineWidth is the stroke width in points; 0 or less uses DefaultDebugStyle's.
LineWidth float32
// HideDetail leaves the detail triangles out, drawing only the polygons.
HideDetail bool
// Lift raises every line by this many world units so it is not hidden in the ground it lies on.
Lift float32
}DebugStyle sets how DrawDebug draws a mesh.
func DefaultDebugStyle() DebugStyleDefaultDebugStyle returns a DebugStyle with high-contrast colors for drawing a mesh over a 3D scene.
type File struct {
// Version is the schema version; it must be FormatVersion (1).
Version int `yaml:"version" schema:"required"`
// Settings are the values the meshes were baked with, every field set.
Settings Settings `yaml:"settings"`
// Meshes holds one mesh per agent type, in the order the agent types were baked.
Meshes []Mesh `yaml:"meshes,omitempty"`
}File is a versioned YAML navigation mesh file, such as levels/level1.navmesh.yaml, that a scene names in its navMesh field: the settings it was baked with and one Mesh per agent type.
func Bake(g *Geometry, settings Settings, agents []AgentType) (*File, error)Bake bakes one navigation mesh per agent type from g's triangles on the layers settings.LayerMask selects, in the order agents lists them, and returns them as a File ready to Encode. Zero fields of settings and of each agent type take their defaults, and the File records the values used.
The same geometry, settings and agent types always bake the same File, so encoding it twice writes the same bytes.
func LoadFS(fsys fs.FS, path string) (*File, error)LoadFS reads and parses the navigation mesh file at path in fsys, such as the one a scene's navMesh field names from the project root.
func Parse(data []byte) (*File, error)Parse decodes and validates a YAML navigation mesh file. Unknown fields and trailing YAML documents are refused; errors are *loaderr.Error values with the line, column and field of the problem.
func ParseWith(data []byte, file string) (*File, error)ParseWith is Parse with the file's name attached to errors.
func (f *File) Mesh(agent string) (*Mesh, bool)Mesh returns the mesh baked for the agent type called agent.
type Geometry struct {
// contains filtered or unexported fields
}Geometry is the level geometry a bake reads: world-space triangles, each on one or more layers that Settings.LayerMask selects from. Triangles wind counter-clockwise seen from their front, as glTF's and this module's meshes do; a triangle facing up is a floor, and every triangle is solid to the agents whatever way it faces. Triangles are surfaces, as in Recast, so a closed mesh tall enough to stand in is hollow; the collider shapes AddPhysicsWorld and AddGridMap add are filled instead.
The Add methods read the level from the sources a 3D game builds it from: glTF models, scene3d scenes and sceneformat scene files, world3d terrain heightmaps and GridMaps, and physics3d static colliders.
func (g *Geometry) AddGLTF(doc *gltf.Document, world math3d.Mat4, layer uint32)AddGLTF adds the triangles of every mesh in doc's default scene (its first scene when it names none, or every node without a parent when it has no scenes), each at its node's world transform and then at world, on layer. Point and line primitives add nothing; skins and morph targets are left at their bind pose.
func (g *Geometry) AddGridMap(gm *world3d.GridMap, layer uint32)AddGridMap adds the collider boxes of every occupied cell of gm, on layer, each baked as a solid. A tile without ColliderBoxes adds nothing, so a GridMap's floors and walls need collider boxes to be baked.
func (g *Geometry) AddGridMapFile(fsys fs.FS, name string, layer uint32) errorAddGridMapFile loads the versioned YAML 3D grid map at name in fsys (world3d.LoadGridMapFS) and adds its occupied cells' collider boxes on layer.
func (g *Geometry) AddHeightmap(h *world3d.Heightmap, layer uint32)AddHeightmap adds the terrain h, triangulated as its own BuildMesh does, on layer.
func (g *Geometry) AddMesh(positions []math3d.Vec3, indices []uint32, world math3d.Mat4, layer uint32)AddMesh adds the indexed triangle list positions and indices, transformed by world, on layer. Nil indices take the positions three at a time. A world matrix that mirrors (negative determinant) flips the triangles' winding back, as glTF requires.
func (g *Geometry) AddOffMeshLink(link OffMeshLink)AddOffMeshLink registers a point-to-point off-mesh connection to be stored on every Mesh baked from g. Links with non-finite coordinates or negative/non-finite Radius or Cost are skipped.
func (g *Geometry) AddPhysicsWorld(w *physics3d.World, mask uint32)AddPhysicsWorld adds the static bodies, triangle meshes, heightfields and voxel colliders of w whose collision layers share a bit with mask. A collider's layer of 0 counts as every layer, as in physics3d. Boxes add their 12 triangles, and spheres and capsules a faceted approximation of their surface, each baked as a solid that fills the space inside it; every solid voxel of a voxel collider whose grid implements physics3d.VoxelBoundsGrid adds a solid box, and a grid that does not report its bounds adds nothing; dynamic and kinematic bodies and triggers are not level geometry and add nothing.
func (g *Geometry) AddPrimitive(name string, world math3d.Mat4, layer uint32) errorAddPrimitive adds the built-in 3D primitive named name (one of sceneformat.MeshPrimitives: "box", "plane", "sphere", "capsule", or "cylinder") transformed by world on layer. Closed primitives are baked as solids; "plane" is baked as a surface.
func (g *Geometry) AddScene(s *scene3d.Scene, mask uint32, mesh NodeMesh) errorAddScene adds the geometry of every enabled node of s, outside the subtree of a disabled node, whose Layer shares a bit with mask, transformed by the node's world matrix and on the node's Layer. mesh gives each node's triangles; nil reads a *scene3d.MeshCollider. A node mesh returns an error, it is returned with the node's name.
func (g *Geometry) AddSceneFile(doc *sceneformat.SceneDoc, fsys fs.FS) errorAddSceneFile adds the static 3D geometry and authored nav_link off-mesh links of a sceneformat scene: it resolves the scenes doc instances and inherits from fsys, builds the scene's 3D node tree, skips screen-space layers and dynamic or kinematic body3d objects (along with their descendants), adds each remaining object's glTF model (respecting ModelNode and ModelMesh), built-in 3D primitive Mesh, and static non-trigger collider3d shapes on scene3d.LayerDefault, and extracts every nav_link component into the geometry's off-mesh links.
func (g *Geometry) AddTerrainFile(fsys fs.FS, name string, layer uint32) errorAddTerrainFile loads the versioned YAML terrain definition at name in fsys (world3d.LoadTerrainFS) and adds its heightmap on layer.
func (g *Geometry) AddTriangle(a, b, c math3d.Vec3, layer uint32)AddTriangle adds the triangle (a, b, c) on layer, skipping a degenerate one or one with a non-finite coordinate. A layer of 0 counts as every layer.
func (g *Geometry) OffMeshLinks() []OffMeshLinkOffMeshLinks returns a copy of all off-mesh links added to g in insertion order.
func (g *Geometry) TriangleCount() intTriangleCount returns the number of triangles g holds.
type Mesh struct {
// Agent is the agent type the mesh was baked for, every field set.
Agent AgentType `yaml:"agent"`
// Vertices are the polygons' corners in world space, shared between neighbouring polygons.
Vertices []Point `yaml:"vertices,omitempty"`
// Polygons are the mesh's convex walkable polygons.
Polygons []Polygon `yaml:"polygons,omitempty"`
// Links are optional point-to-point off-mesh connections (jumps, drops, ladders, teleports) applied by NavMesh.
Links []OffMeshLink `yaml:"links,omitempty"`
}Mesh is the navigation mesh baked for one agent type: convex polygons over shared vertices, each with triangles that follow the height of the ground under it, plus any point-to-point off-mesh links.
func BakeMesh(g *Geometry, settings Settings, agent AgentType) (*Mesh, error)BakeMesh bakes the navigation mesh of one agent type, as Bake does for each.
func (m *Mesh) DebugLines(polygonsOnly bool) [][2]math3d.Vec3DebugLines returns the line segments that show m: first every polygon edge once, in polygon order, then, unless polygonsOnly is set, every edge inside a polygon's detail triangulation once. Edges shared by two polygons appear once.
func (m *Mesh) NavMesh() *world3d.NavMeshNavMesh builds the world3d.NavMesh agents path find on from m: each detail triangle becomes one of its walkable polygons, linked to its neighbours across shared edges, so paths follow ramps, stairs and terrain at the baked heights and keep stacked floors apart. Any OffMeshLinks stored in m.Links are registered via AddOffMeshLink. The bake already decided what is walkable, so no triangle is dropped for its slope. m must be valid, as Parse and Bake return it.
func (m *Mesh) TiledNavMesh(tileSize float32) *world3d.TiledNavMeshTiledNavMesh builds a world3d.TiledNavMesh partitioned into fixed square XZ tiles of size tileSize from m's detail triangles, ready for runtime tile replacement, dynamic obstacle carving, and chunk streaming.
func (m *Mesh) TriangleVertices(p *Polygon, t Triangle) [3]math3d.Vec3TriangleVertices returns the world-space corners of triangle t of polygon p.
type NodeMesh func(n *scene3d.Node) ([]math3d.Vec3, error)NodeMesh returns the triangles of a scene3d node in its local space, three vertices per triangle, or nil when the node has no geometry to bake.
func SceneMeshes(fsys fs.FS) NodeMeshSceneMeshes returns the NodeMesh for nodes built by sceneformat.BuildNodes3D: an object whose Model names a glTF model in fsys (respecting ModelNode and ModelMesh), by its slash-separated path from the project root, bakes that model's triangles, each model loaded once; an object whose Mesh names a built-in primitive bakes that primitive; objects with a dynamic or kinematic body3d component (and their descendants) are skipped; any other node bakes its *scene3d.MeshCollider.
type OffMeshLink struct {
// ID is an optional game-defined link identifier.
ID int `yaml:"id,omitempty"`
// Start is the world-space [x, y, z] entry point of the link.
Start Point `yaml:"start" schema:"required"`
// End is the world-space [x, y, z] exit point of the link.
End Point `yaml:"end" schema:"required"`
// Radius is the optional endpoint snap and entry tolerance in world units (>= 0).
Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
// 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 3D Euclidean distance.
Cost float32 `yaml:"cost,omitempty" schema:"minimum=0"`
// Area is the link's navigation area ID (0 for default).
Area world3d.NavArea `yaml:"area,omitempty"`
// Flags holds optional custom link flag bits; world3d.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 3D navigation mesh, such as a jump, drop-down, ladder, or teleporter.
type Point [3]float32Point is a position in world space, written as a [x, y, z] list.
func (p Point) MarshalYAML() (any, error)MarshalYAML writes p on one line, as [x, y, z].
type Polygon struct {
// Vertices index Mesh.Vertices, from 3 to Settings.MaxVertsPerPoly of them, in order around the polygon.
Vertices []int `yaml:"vertices,flow"`
// Detail holds the extra vertices sampled on the polygon's edges and inside it where the ground is uneven.
Detail []Point `yaml:"detail,omitempty"`
// Triangles cover the polygon, winding counter-clockwise seen from above. An index below len(Vertices) names that polygon vertex, and index len(Vertices)+i names Detail[i].
Triangles []Triangle `yaml:"triangles"`
}Polygon is one convex walkable polygon of a Mesh with its height detail.
type Settings struct {
// CellSize is the width and depth of one heightfield cell; smaller cells follow the level more closely and take longer to bake. 0 uses DefaultCellSize.
CellSize float32 `yaml:"cellSize" schema:"minimum=0"`
// CellHeight is the height of one heightfield cell, the precision of heights, clearances and step heights. 0 uses DefaultCellHeight.
CellHeight float32 `yaml:"cellHeight" schema:"minimum=0"`
// MinRegionArea is the smallest area of a connected island of walkable surface that is kept, which drops specks on tables and ledges. 0 uses DefaultMinRegionArea.
MinRegionArea float32 `yaml:"minRegionArea" schema:"minimum=0"`
// MaxEdgeLength is the longest a polygon edge along a wall may be before it is split. 0 uses DefaultMaxEdgeLength.
MaxEdgeLength float32 `yaml:"maxEdgeLength" schema:"minimum=0"`
// MaxSimplificationError is the farthest a simplified wall outline may stray from the walkable area's cell outline. 0 uses DefaultMaxSimplificationError.
MaxSimplificationError float32 `yaml:"maxSimplificationError" schema:"minimum=0"`
// MaxVertsPerPoly is the largest number of vertices in one convex polygon, from 3 to MaxVertsPerPolyLimit. 0 uses DefaultMaxVertsPerPoly.
MaxVertsPerPoly int `yaml:"maxVertsPerPoly" schema:"minimum=0,maximum=12"`
// DetailSampleDistance is the spacing of the height samples a polygon's detail triangles follow uneven ground with, at least CellSize. 0 uses DefaultDetailSampleDistance, or CellSize when that is larger.
DetailSampleDistance float32 `yaml:"detailSampleDistance" schema:"minimum=0"`
// DetailSampleMaxError is how far the detail triangles may stray from the sampled height before a sample is added. 0 uses DefaultDetailSampleMaxError.
DetailSampleMaxError float32 `yaml:"detailSampleMaxError" schema:"minimum=0"`
// LayerMask selects the geometry baked: a triangle is baked when its layers share a bit with the mask. 0 uses LayerAll.
LayerMask uint32 `yaml:"layerMask"`
}Settings are the voxel resolution and polygon building parameters of a bake, shared by every agent type. A zero field uses its default, and a baked File records every value it was baked with.
type Triangle [3]intTriangle is three vertex indices of a Polygon's height detail, written as a [a, b, c] list.
func (t Triangle) MarshalYAML() (any, error)MarshalYAML writes t on one line, as [a, b, c].