package gltf
import "github.com/nsgo-dev/game/pkg/gltf"Overview
Package gltf implements a pure-Go glTF 2.0 (.gltf) and binary GLB (.glb) asset loader using only the Go standard library and pkg/math3d.
Supported features:
- Auto-detection of JSON .gltf and binary .glb containers via Load and LoadFS
- Embedded base64 data URIs, GLB BIN chunks, and external fs.FS buffers/images
- Full typed accessor decoding (SCALAR, VEC2, VEC3, VEC4, MAT4, indices, joints, weights) with all component types, normalized integer unpacking, interleaved byteStride buffers, zero-initialized accessors, and sparse accessors
- Scene graph and node hierarchy with matrix/TRS transforms, cycle detection, and world matrix computation
- PBR metallic-roughness materials, textures, samplers, PNG/JPEG image decoding, KHR_materials_unlit, KHR_texture_transform, and KHR_materials_variants
- Mesh primitives with bounds, morph targets with CPU position/normal blending, skins with inverse bind matrices, and STEP/LINEAR/CUBICSPLINE keyframe animations
- Compressed geometry: KHR_draco_mesh_compression primitives (Draco bitstream 2.2, sequential and edgebreaker connectivity), EXT_meshopt_compression and KHR_meshopt_compression buffer views (attribute, triangle and index codecs with the octahedral, quaternion, exponential and color filters, never fetching fallback buffers), and KHR_mesh_quantization; every reader returns the decoded data
Index
- Constants
- func EvaluateMorphNormals(prim Primitive, weights []float32, out []math3d.Vec3) []math3d.Vec3
- func EvaluateMorphPositions(prim Primitive, weights []float32, out []math3d.Vec3) []math3d.Vec3
- func EvaluateMorphTangents(prim Primitive, weights []float32, out []math3d.Vec4) []math3d.Vec4
- func ParseLODNodeName(name string) (baseName string, level int, ok bool)
- func PrimitiveLightmapUVs(prim Primitive) (uvs []math3d.Vec2, usedFallback bool)
- func ResolveWeights(doc *Document, nodeIndex int) []float32
- func ResolveWeightsInto(doc *Document, nodeIndex int, dst []float32) []float32
- func SampleMorphWeights(anim Animation, nodeIndex int, t float32, dst []float32) ([]float32, bool)
- type Accessor
- type AccessorSparse
- type AccessorSparseIndices
- type AccessorSparseValues
- type AccessorType
- type AlphaMode
- type Animation
- type AnimationChannel
- type Asset
- type Buffer
- type BufferResolver
- type BufferView
- type Camera
- type CameraType
- type ChannelSample
- type Clearcoat
- type ColliderKind
- type ComponentType
- type Document
- func Load(data []byte, resolver BufferResolver) (*Document, error)
- func LoadFS(fsys fs.FS, path string) (*Document, error)
- func (d *Document) ColliderNodes() ([]NodeCollider, error)
- func (d *Document) ComputeWorldMatrices() error
- func (d *Document) DecodeImage(index int) (image.Image, error)
- func (d *Document) DrawableNodes() []int
- func (d *Document) ImageBytes(index int) ([]byte, error)
- func (d *Document) LightmapTexCoords(prim Primitive, ref *LightmapRef) (uvs []math3d.Vec2, usedFallback bool, err error)
- func (d *Document) MaterialForPrimitive(prim Primitive, variantIndex int) int
- func (d *Document) MaterialForVariant(prim Primitive, variantName string) int
- func (d *Document) MaterialLightmap(materialIndex int) (*LightmapRef, error)
- func (d *Document) MeshMaterials(meshIndex, variantIndex int) ([]int, error)
- func (d *Document) PrimitiveTexCoords(prim Primitive, texCoord int) ([]math3d.Vec2, error)
- func (d *Document) ReadIndices(accessorIndex int) ([]uint32, error)
- func (d *Document) ReadJoints(accessorIndex int) ([][4]uint16, error)
- func (d *Document) ReadMat4(accessorIndex int) ([]math3d.Mat4, error)
- func (d *Document) ReadScalar(accessorIndex int) ([]float32, error)
- func (d *Document) ReadVec2(accessorIndex int) ([]math3d.Vec2, error)
- func (d *Document) ReadVec3(accessorIndex int) ([]math3d.Vec3, error)
- func (d *Document) ReadVec4(accessorIndex int) ([]math3d.Vec4, error)
- func (d *Document) ReadWeights(accessorIndex int) ([]math3d.Vec4, error)
- func (d *Document) ResolveVariantMaterials(variantIndex int) [][]int
- func (d *Document) SceneColliderNodes(sceneIdx int) ([]NodeCollider, error)
- func (d *Document) SceneDrawableNodes(sceneIdx int) []int
- func (d *Document) TransformTexCoords(prim Primitive, ref *TextureRef, out []math3d.Vec2) ([]math3d.Vec2, error)
- func (d *Document) VariantIndex(name string) int
- type FilterMode
- type Image
- type Interpolation
- type LightmapRef
- type Material
- type MaterialVariant
- type Mesh
- type MorphResult
- type MorphTarget
- type Node
- type NodeCollider
- type Primitive
- type PrimitiveMode
- type Sampler
- type Scene
- type Skin
- type TargetPath
- type Texture
- type TextureRef
- type TextureTransform
- type Transmission
- type WrapMode
Constants
const (
// ExtMOZLightmap is the Mozilla Hubs / Blender glTF material extension name for baked lightmaps.
ExtMOZLightmap = "MOZ_lightmap"
// ExtLightmap is the generic EXT_lightmap glTF material extension name for baked lightmaps.
ExtLightmap = "EXT_lightmap"
)Functions
func EvaluateMorphNormals(prim Primitive, weights []float32, out []math3d.Vec3) []math3d.Vec3EvaluateMorphNormals computes the morphed and re-normalized vertex normals for prim given morph target weights. If out has sufficient capacity it is reused without allocation.
func EvaluateMorphPositions(prim Primitive, weights []float32, out []math3d.Vec3) []math3d.Vec3EvaluateMorphPositions computes the morphed vertex positions for prim given morph target weights:
out[i] = prim.Positions[i] + sum_k(weights[k] * prim.Targets[k].Positions[i])
If out has sufficient capacity it is reused without allocation; otherwise a new slice is allocated and returned.
func EvaluateMorphTangents(prim Primitive, weights []float32, out []math3d.Vec4) []math3d.Vec4EvaluateMorphTangents computes the morphed vertex tangents for prim given morph target weights:
out[i].xyz = normalize(prim.Tangents[i].xyz + sum_k(weights[k] * prim.Targets[k].Tangents[i])) out[i].w = prim.Tangents[i].w
Per glTF 2.0, morph target TANGENT deltas displace only the XYZ components and leave the W handedness sign unchanged. If out has sufficient capacity it is reused without allocation; otherwise a new slice is allocated and returned.
func ParseLODNodeName(name string) (baseName string, level int, ok bool)ParseLODNodeName inspects a glTF node or mesh name for the case-insensitive _LOD<N> suffix convention (such as "Tree_LOD0", "Tree_LOD1", "Tree_lod2"), tolerating Blender's optional trailing ".001" duplicate numbering.
When name carries a recognized suffix with a non-empty base name and a non-negative integer level, ParseLODNodeName returns (baseName, level, true). Otherwise it returns ("", 0, false).
func PrimitiveLightmapUVs(prim Primitive) (uvs []math3d.Vec2, usedFallback bool)PrimitiveLightmapUVs returns the lightmap UV channel for prim: prim.TexCoords1 (TEXCOORD_1) when present, falling back to prim.TexCoords0 (TEXCOORD_0) when TEXCOORD_1 is absent. The second return value reports whether the fallback path was used.
func ResolveWeights(doc *Document, nodeIndex int) []float32ResolveWeights returns the effective morph target weights for doc.Nodes[nodeIndex] following glTF 2.0 precedence: non-empty node.Weights override mesh.Weights, and missing weights default to zeros matching the mesh's morph target count. Returns nil when doc is nil, nodeIndex is out of range, the node has no mesh, or the mesh has no morph targets.
func ResolveWeightsInto(doc *Document, nodeIndex int, dst []float32) []float32ResolveWeightsInto resolves the effective morph target weights for doc.Nodes[nodeIndex] into dst following glTF 2.0 precedence (node.Weights overrides mesh.Weights, else zeros matching the target count). If dst has sufficient capacity it is reused without allocation.
func SampleMorphWeights(anim Animation, nodeIndex int, t float32, dst []float32) ([]float32, bool)SampleMorphWeights evaluates the PathWeights channel targeting nodeIndex in anim at time t (in seconds) into dst and reports whether a matching channel was found and sampled.
It supports InterpolationStep, InterpolationLinear, and InterpolationCubicSpline (unpacking 3*N values per keyframe in glTF order: in-tangent, value, out-tangent), clamping outside the channel's keyframe time range. If dst has sufficient capacity it is reused without allocation.
Types
type Accessor struct {
Name string
BufferView int
ByteOffset int
ComponentType ComponentType
Normalized bool
Count int
Type AccessorType
Min []float32
Max []float32
Sparse *AccessorSparse
Extras json.RawMessage
// contains filtered or unexported fields
}Accessor defines typed view metadata over a BufferView (or zero-initialized storage). BufferView is -1 when omitted (zero-initialized per glTF 2.0 spec).
type AccessorSparse struct {
Count int
Indices AccessorSparseIndices
Values AccessorSparseValues
}AccessorSparse describes sparse overrides applied on top of a base accessor.
type AccessorSparseIndices struct {
BufferView int
ByteOffset int
ComponentType ComponentType
}AccessorSparseIndices describes the index buffer of a sparse accessor.
type AccessorSparseValues struct {
BufferView int
ByteOffset int
}AccessorSparseValues describes the replacement values buffer of a sparse accessor.
type AccessorType stringAccessorType identifies the element structure of an accessor.
const (
AccessorScalar AccessorType = "SCALAR"
AccessorVec2 AccessorType = "VEC2"
AccessorVec3 AccessorType = "VEC3"
AccessorVec4 AccessorType = "VEC4"
AccessorMat2 AccessorType = "MAT2"
AccessorMat3 AccessorType = "MAT3"
AccessorMat4 AccessorType = "MAT4"
)func (t AccessorType) Components() intComponents returns the number of scalar components in an element of type t, or 0 if t is unknown.
type AlphaMode stringAlphaMode controls how a material's alpha channel is interpreted.
const (
AlphaOpaque AlphaMode = "OPAQUE"
AlphaMask AlphaMode = "MASK"
AlphaBlend AlphaMode = "BLEND"
)type Animation struct {
Name string
Duration float32
Channels []AnimationChannel
Extras json.RawMessage
}Animation represents a glTF 2.0 keyframe animation clip.
func (a *Animation) Apply(doc *Document, t float32)Apply evaluates the animation at time t and writes sampled translation, rotation, scale, and morph target weights directly onto matching nodes in doc. Call doc.ComputeWorldMatrices afterwards to propagate updated transforms.
func (a *Animation) Sample(t float32) []ChannelSampleSample evaluates all channels of the animation at time t (in seconds) and returns one ChannelSample per channel with a valid TargetNode (>= 0).
type AnimationChannel struct {
TargetNode int
Path TargetPath
Interpolation Interpolation
Times []float32
Values []float32
Stride int
}AnimationChannel holds a single decoded keyframe track targeting one node property. For InterpolationCubicSpline, Values stores 3*Stride floats per keyframe in glTF order: [inTangent, value, outTangent].
func (ch *AnimationChannel) Sample(t float32) ChannelSampleSample evaluates this channel at time t (in seconds), clamping to the first and last keyframes outside the channel's time range.
type Asset struct {
Version string
MinVersion string
Generator string
Copyright string
Extras json.RawMessage
}Asset holds metadata about the glTF asset.
type Buffer struct {
Name string
URI string
ByteLength int
Data []byte
Extras json.RawMessage
}Buffer holds resolved binary buffer bytes. For a buffer that meshopt-compressed bufferViews decode into (an EXT_meshopt_compression or KHR_meshopt_compression fallback or placeholder buffer), Data holds the decompressed views and the buffer's own URI is never fetched.
type BufferResolver func(uri string) ([]byte, error)BufferResolver resolves relative external URIs (for .bin buffers and images) to their raw bytes.
type BufferView struct {
Name string
Buffer int
ByteOffset int
ByteLength int
ByteStride int
Target int
Extras json.RawMessage
// Extensions keeps unsupported optional extension payloads by name.
Extensions map[string]json.RawMessage
}BufferView defines a slice of a Buffer with an optional interleaved ByteStride.
type Camera struct {
Name string
Type CameraType
AspectRatio float32 // perspective only; 0 means unspecified
YFOV float32 // perspective vertical field of view in radians
XMag float32 // orthographic horizontal magnification
YMag float32 // orthographic vertical magnification
ZNear float32
ZFar float32 // perspective: 0 means infinite far plane
Extras json.RawMessage
}Camera describes a glTF 2.0 perspective or orthographic camera.
type CameraType stringCameraType identifies the projection model of a glTF camera.
const (
CameraPerspective CameraType = "perspective"
CameraOrthographic CameraType = "orthographic"
)type ChannelSample struct {
Node int
Path TargetPath
Translation math3d.Vec3
Rotation math3d.Quat
Scale math3d.Vec3
Weights []float32
}ChannelSample holds the evaluated value of one animation channel at time t.
type Clearcoat struct {
// Factor is clearcoatFactor in [0, 1] (default 0). Multiplied by Texture's R channel when present.
Factor float32
// Texture is clearcoatTexture (optional, linear; R channel modulates Factor).
Texture *TextureRef
// RoughnessFactor is clearcoatRoughnessFactor in [0, 1] (default 0). Multiplied by RoughnessTexture's G channel when present.
RoughnessFactor float32
// RoughnessTexture is clearcoatRoughnessTexture (optional, linear; G channel modulates RoughnessFactor).
RoughnessTexture *TextureRef
// NormalTexture is clearcoatNormalTexture (optional, tangent-space normal map; Scale defaults to 1).
NormalTexture *TextureRef
}Clearcoat represents the Khronos KHR_materials_clearcoat material extension, describing a dielectric coating layer (IOR 1.5, F0 = 0.04) on top of the base PBR metallic-roughness material.
type ColliderKind stringColliderKind identifies the physics collision shape declared on a glTF node through naming conventions or extras.collider metadata.
const (
// ColliderNone indicates that a node carries no collider annotation.
ColliderNone ColliderKind = ""
// ColliderTriMesh builds a static triangle-mesh collider from the node's mesh.
ColliderTriMesh ColliderKind = "trimesh"
// ColliderBox builds a box collider from explicit extras dimensions or the
// node mesh's local bounds.
ColliderBox ColliderKind = "box"
// ColliderSphere builds a sphere collider from explicit extras dimensions or
// the node mesh's local bounds.
ColliderSphere ColliderKind = "sphere"
// ColliderCapsule builds a capsule collider from explicit extras dimensions
// or the node mesh's local bounds.
ColliderCapsule ColliderKind = "capsule"
// ColliderConvex marks a convex hull collider (falling back to a triangle
// mesh collider until native convex hulls are available).
ColliderConvex ColliderKind = "convex"
)type ComponentType intComponentType identifies the binary storage type of an accessor component.
const (
ComponentByte ComponentType = 5120 // int8
ComponentUnsignedByte ComponentType = 5121 // uint8
ComponentShort ComponentType = 5122 // int16
ComponentUnsignedShort ComponentType = 5123 // uint16
ComponentUnsignedInt ComponentType = 5125 // uint32
ComponentFloat ComponentType = 5126 // float32
)func (c ComponentType) ByteSize() intByteSize returns the size in bytes of a single component, or 0 if unknown.
type Document struct {
Asset Asset
ExtensionsUsed []string
ExtensionsRequired []string
Scene int // default scene index, or -1 if unspecified
Scenes []Scene
Nodes []Node
Cameras []Camera
Buffers []Buffer
BufferViews []BufferView
Accessors []Accessor
Samplers []Sampler
Images []Image
Textures []Texture
Materials []Material
Variants []MaterialVariant
Meshes []Mesh
Skins []Skin
Animations []Animation
Extras json.RawMessage
// contains filtered or unexported fields
}Document is a parsed glTF 2.0 / GLB asset with resolved buffers, decoded meshes, materials, scene hierarchy, skins, and animations.
func Load(data []byte, resolver BufferResolver) (*Document, error)Load parses a glTF 2.0 JSON (.gltf) or binary GLB (.glb) document from data. External buffer/image URIs are resolved via resolver (which may be nil when all resources are embedded via GLB BIN chunks or base64 data URIs).
Its errors are *loaderr.Error values that give the field of the problem, the line in the JSON (in a GLB, the line in its JSON chunk) and how to fix it; a caller that read data from a file names it with loaderr.WithFile, as LoadFS does.
func LoadFS(fsys fs.FS, path string) (*Document, error)LoadFS loads a .gltf or .glb file at path from fsys, automatically resolving relative external .bin buffers and image URIs against path's directory in fsys. Its errors are *loaderr.Error values that name path.
func (d *Document) ColliderNodes() ([]NodeCollider, error)ColliderNodes returns all collider annotations found on nodes in the document's default scene (or all nodes when no scenes are defined), in deterministic scene traversal order.
func (d *Document) ComputeWorldMatrices() errorComputeWorldMatrices validates the node hierarchy (rejecting out-of-range child indices, multiple parents, and cycles), updates LocalMatrix from TRS for non-matrix nodes, and computes exact parent-to-child WorldMatrix values for every node in the document.
func (d *Document) DecodeImage(index int) (image.Image, error)DecodeImage decodes the PNG or JPEG image at index from its bufferView, data URI, or external URI (resolved via the loader's BufferResolver / fs.FS).
func (d *Document) DrawableNodes() []intDrawableNodes returns the deterministic slice of node indices in the document's default scene (or all nodes when no scenes are defined) that reference a valid mesh and should be drawn visually, excluding collider-only nodes such as *-colonly and extras.collider.draw == false.
func (d *Document) ImageBytes(index int) ([]byte, error)ImageBytes returns the raw encoded bytes (e.g. PNG or JPEG) for image index.
func (d *Document) LightmapTexCoords(prim Primitive, ref *LightmapRef) (uvs []math3d.Vec2, usedFallback bool, err error)LightmapTexCoords resolves the baked lightmap UVs for prim using ref (or TEXCOORD_1 when ref is nil). When TEXCOORD_1 is requested but absent on prim, it falls back to prim.TexCoords0 and reports usedFallback = true. A primitive with neither TEXCOORD_1 nor TEXCOORD_0 is an error, since every vertex would sample the same lightmap texel.
func (d *Document) MaterialForPrimitive(prim Primitive, variantIndex int) intMaterialForPrimitive returns the material index to use for prim under the specified KHR_materials_variants variantIndex. If variantIndex is negative, out of range, or unmapped on prim, it falls back to prim.Material.
func (d *Document) MaterialForVariant(prim Primitive, variantName string) intMaterialForVariant returns the material index to use for prim under the named KHR_materials_variants variant. If name does not match any variant or is unmapped on prim, it falls back to prim.Material.
func (d *Document) MaterialLightmap(materialIndex int) (*LightmapRef, error)MaterialLightmap extracts baked lightmap metadata from d.Materials[materialIndex], checking MOZ_lightmap, EXT_lightmap, and extras.lightmap in that order. It returns (nil, nil) when the material carries no lightmap metadata.
func (d *Document) MeshMaterials(meshIndex, variantIndex int) ([]int, error)MeshMaterials returns the resolved material index for each primitive of d.Meshes[meshIndex] under variantIndex, falling back to each primitive's default Material when variantIndex is negative, out of range, or unmapped.
func (d *Document) PrimitiveTexCoords(prim Primitive, texCoord int) ([]math3d.Vec2, error)PrimitiveTexCoords returns the raw texture coordinates for UV set texCoord (TEXCOORD_<texCoord>) on prim. Sets 0 and 1 return prim.TexCoords0 and prim.TexCoords1 directly when loaded; higher sets (TEXCOORD_2, ...) are decoded on demand from prim.Attributes.
func (d *Document) ReadIndices(accessorIndex int) ([]uint32, error)ReadIndices decodes a SCALAR index accessor (UNSIGNED_BYTE, UNSIGNED_SHORT, or UNSIGNED_INT) as []uint32.
func (d *Document) ReadJoints(accessorIndex int) ([][4]uint16, error)ReadJoints decodes a VEC4 JOINTS_n accessor (UNSIGNED_BYTE or UNSIGNED_SHORT) as [][4]uint16.
func (d *Document) ReadMat4(accessorIndex int) ([]math3d.Mat4, error)ReadMat4 decodes a MAT4 accessor as column-major []math3d.Mat4.
func (d *Document) ReadScalar(accessorIndex int) ([]float32, error)ReadScalar decodes a SCALAR accessor as []float32, supporting all glTF component types, normalized unpacking, byteStride, and sparse accessors.
func (d *Document) ReadVec2(accessorIndex int) ([]math3d.Vec2, error)ReadVec2 decodes a VEC2 accessor as []math3d.Vec2.
func (d *Document) ReadVec3(accessorIndex int) ([]math3d.Vec3, error)ReadVec3 decodes a VEC3 accessor as []math3d.Vec3.
func (d *Document) ReadVec4(accessorIndex int) ([]math3d.Vec4, error)ReadVec4 decodes a VEC4 accessor as []math3d.Vec4.
func (d *Document) ReadWeights(accessorIndex int) ([]math3d.Vec4, error)ReadWeights decodes a VEC4 WEIGHTS_n accessor (FLOAT, normalized UNSIGNED_BYTE, or normalized UNSIGNED_SHORT) as []math3d.Vec4.
func (d *Document) ResolveVariantMaterials(variantIndex int) [][]intResolveVariantMaterials returns resolved material indices [mesh][primitive] for every mesh in d under variantIndex without modifying Primitive.Material, so switching variants or reverting to defaults (variantIndex < 0) is repeatable.
func (d *Document) SceneColliderNodes(sceneIdx int) ([]NodeCollider, error)SceneColliderNodes returns all collider annotations found on nodes in d.Scenes[sceneIdx] (or all nodes when sceneIdx < 0), in deterministic scene traversal order.
func (d *Document) SceneDrawableNodes(sceneIdx int) []intSceneDrawableNodes returns the deterministic slice of node indices in d.Scenes[sceneIdx] (or all nodes when sceneIdx < 0) that reference a valid mesh and should be drawn visually, excluding collider-only nodes.
func (d *Document) TransformTexCoords(prim Primitive, ref *TextureRef, out []math3d.Vec2) ([]math3d.Vec2, error)TransformTexCoords evaluates the final UV coordinates for ref on prim, selecting ref.EffectiveTexCoord() and applying ref.Transform when present. If out has sufficient capacity it is reused without allocation; otherwise a new slice is allocated and returned.
func (d *Document) VariantIndex(name string) intVariantIndex returns the index of the first KHR_materials_variants entry whose Name equals name, or -1 when no variant matches.
type FilterMode intFilterMode defines glTF texture minification/magnification filtering modes.
const (
FilterNearest FilterMode = 9728
FilterLinear FilterMode = 9729
FilterNearestMipmapNearest FilterMode = 9984
FilterLinearMipmapNearest FilterMode = 9985
FilterNearestMipmapLinear FilterMode = 9986
FilterLinearMipmapLinear FilterMode = 9987
)type Image struct {
Name string
URI string
MimeType string
BufferView int
Extras json.RawMessage
}Image represents an embedded or external texture image. BufferView is -1 when the image is referenced via URI.
type Interpolation stringInterpolation defines the keyframe interpolation mode for an animation channel.
const (
InterpolationLinear Interpolation = "LINEAR"
InterpolationStep Interpolation = "STEP"
InterpolationCubicSpline Interpolation = "CUBICSPLINE"
)type LightmapRef struct {
// Texture points to the lightmap texture in Document.Textures and its UV channel (defaulting to 1 for TEXCOORD_1). A KHR_texture_transform on the lightmap is folded into UVScale and UVOffset, so Texture.Transform carries only its texCoord override (if any) and passing Texture to [Document.TransformTexCoords] never applies the scale and offset a second time.
Texture TextureRef
// Intensity scales the decoded lightmap irradiance (defaults to 1).
Intensity float32
// Encoding is an optional encoding hint such as "linear", "srgb", "rgbm", or "rgbd", normalized to lower case. Empty when unspecified.
Encoding string
// RGBMMaxRange is an optional peak HDR scale hint for RGBM lightmaps (0 when unspecified, letting the renderer apply its default range).
RGBMMaxRange float32
// UVScale scales lightmap UVs when mapping into a shared lightmap atlas (defaults to [1, 1]). UVScale and UVOffset are the authoritative atlas transform: pass them to render3d's LightmapMaterial.SetUVTransform. They come from, in increasing precedence, the lightmap's KHR_texture_transform (scale and offset; a non-zero rotation is refused), a scaleOffset [sx, sy, ox, oy] field, and separate uvScale and uvOffset fields.
UVScale [2]float32
// UVOffset offsets scaled lightmap UVs when mapping into a shared lightmap atlas (defaults to [0, 0]). See UVScale for precedence.
UVOffset [2]float32
}LightmapRef describes a baked lightmap binding extracted from a glTF material's MOZ_lightmap extension, EXT_lightmap extension, or extras.lightmap metadata.
func DefaultLightmapRef(textureIndex int) LightmapRefDefaultLightmapRef returns a LightmapRef referencing textureIndex on TEXCOORD_1 with unit intensity and identity atlas UV transform.
type Material struct {
Name string
BaseColorFactor math3d.Vec4
BaseColorTexture *TextureRef
MetallicFactor float32
RoughnessFactor float32
MetallicRoughnessTexture *TextureRef
NormalTexture *TextureRef
OcclusionTexture *TextureRef
EmissiveFactor math3d.Vec3
EmissiveTexture *TextureRef
AlphaMode AlphaMode
AlphaCutoff float32
DoubleSided bool
Unlit bool // KHR_materials_unlit
Clearcoat *Clearcoat // KHR_materials_clearcoat
Transmission *Transmission // KHR_materials_transmission
Extras json.RawMessage
// Extensions keeps unsupported optional extension payloads by name.
Extensions map[string]json.RawMessage
}Material defines a glTF 2.0 PBR metallic-roughness material.
func (m Material) EmissiveStrength() (float32, error)EmissiveStrength returns the KHR_materials_emissive_strength multiplier for m, defaulting to 1.0 when the extension or its emissiveStrength property is omitted. A payload that is not an object, or an emissiveStrength that is not a finite number >= 0, returns an error.
func (m Material) IOR() (float32, error)IOR returns the KHR_materials_ior dielectric index of refraction for m, defaulting to 1.5 when the extension or its ior property is omitted. A non-object payload or an ior that is not a finite number >= 1.0 (or 0 per spec) returns an error.
type MaterialVariant struct {
Name string
Extras json.RawMessage
}MaterialVariant represents an entry in KHR_materials_variants.
type Mesh struct {
Name string
Primitives []Primitive
Weights []float32
Extras json.RawMessage
}Mesh groups one or more geometry primitives and optional default morph weights.
type MorphResult struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
Tangents []math3d.Vec4
Bounds math3d.AABB
}MorphResult holds the evaluated vertex attributes and object-space bounding box for a morphed Primitive. Reuse one MorphResult across frames to evaluate morph targets with zero steady-state allocations.
func ApplyMorphWeights(base Primitive, weights []float32, dst *MorphResult) *MorphResultApplyMorphWeights evaluates base's morph targets with weights into dst and returns dst (allocating one if dst is nil). It blends Positions, renormalizes blended Normals, blends and renormalizes Tangents.xyz while preserving Tangents.w handedness, and recomputes Bounds from the resulting Positions. Reusing dst across calls performs zero heap allocations once its slices are sized.
type MorphTarget struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
Tangents []math3d.Vec3
}MorphTarget holds vertex attribute displacement deltas for a single morph target.
type Node struct {
Name string
Parent int
Children []int
Translation math3d.Vec3
Rotation math3d.Quat
Scale math3d.Vec3
LocalMatrix math3d.Mat4
WorldMatrix math3d.Mat4
// HasMatrix reports whether this node's transform is governed directly by
// LocalMatrix (authored via the glTF "matrix" property) rather than TRS.
// When false, ComputeWorldMatrices recomputes LocalMatrix from Translation,
// Rotation, and Scale.
HasMatrix bool
// MatrixNotTRS reports that the authored matrix has shear or another part a translation, rotation and scale cannot express. Translation then holds the matrix's translation, Rotation and Scale stay identity, and LocalMatrix is the only exact transform (#546).
MatrixNotTRS bool
Mesh int
Skin int
Camera int
Weights []float32
Extras json.RawMessage
Extensions map[string]json.RawMessage
}Node represents a node in the glTF 2.0 scene graph. Index fields (Parent, Mesh, Skin, Camera) are -1 when unset.
func (n Node) IsDrawable() boolIsDrawable reports whether n should be rendered visually. It returns false when n has no mesh (Mesh < 0) or when n is marked as a collider-only / non-drawn node via a *-colonly name suffix or extras ("draw": false, "collider": {"draw": false | "only": true | "visible": false}).
func (n *Node) SetTransform(t math3d.Transform)SetTransform updates the node's local TRS properties, clears HasMatrix, and refreshes LocalMatrix.
func (n *Node) Transform() math3d.TransformTransform returns the node's local TRS transform.
type NodeCollider struct {
// NodeIndex is the node's index in Document.Nodes (-1 when parsed from a
// standalone Node outside a Document).
NodeIndex int
// NodeName is the original Node.Name.
NodeName string
// BaseName is Node.Name with any recognized collider suffix removed.
BaseName string
// MeshIndex is Node.Mesh (-1 if the node has no mesh).
MeshIndex int
// Kind is the resolved collider shape kind.
Kind ColliderKind
// Draw reports whether the node's mesh should still be rendered visually.
// It is false for *-colonly suffixes, extras.collider.draw == false,
// extras.collider.only == true, extras.collider.visible == false, or nodes
// without a mesh.
Draw bool
// IsTrigger marks a sensor/trigger volume rather than a solid obstacle.
IsTrigger bool
// Tag is the resolved physics tag (extras.collider.tag when provided,
// otherwise BaseName, falling back to NodeName).
Tag string
// WorldMatrix is the node's world transform matrix (identity when unset).
WorldMatrix math3d.Mat4
// Optional local-space shape overrides supplied via extras.collider.
HasCenter bool
Center math3d.Vec3
HasHalfExtents bool
HalfExtents math3d.Vec3
HasRadius bool
Radius float32
HasHeight bool
Height float32
// Optional physics material and layer filter overrides from extras.collider.
HasFriction bool
Friction float32
HasRestitution bool
Restitution float32
HasLayer bool
Layer uint32
HasMask bool
Mask uint32
}NodeCollider describes the collider metadata resolved from a glTF node's name suffix and/or extras.collider object.
func ParseNodeCollider(node Node) (NodeCollider, bool, error)ParseNodeCollider inspects a glTF node's name suffix and extras.collider metadata to determine whether it defines a physics collider and whether its mesh should be drawn visually.
Recognized Godot-style node name suffixes (case-insensitive, with optional trailing Blender ".001" numbering):
- -col / -colonly: triangle mesh collider (drawn / collider-only)
- -boxcol / -boxcolonly: box collider (drawn / collider-only)
- -spherecol / -spherecolonly: sphere collider (drawn / collider-only)
- -capsulecol / -capsulecolonly: capsule collider (drawn / collider-only)
- -convcol / -convcolonly: convex collider (drawn / collider-only)
Recognized node extras metadata:
- {"collider": "box"|"sphere"|"capsule"|"trimesh"|"convex"|"none"}
- {"collider": true|false}
- {"collider": {"shape"|"type": ..., "draw": bool, "only": bool, "trigger": bool, "tag": string, "center": [x,y,z], "halfExtents"|"size": [x,y,z], "radius": r, "height": h, "friction": f, "restitution": r, "layer": u32, "mask": u32}}
- optional top-level {"draw": false} paired with a shorthand collider.
When extras.collider is present it takes precedence over name-suffix defaults. It returns (info, true, nil) when the node defines a collider, (zero, false, nil) when the node is not a collider, or an error when extras.collider is malformed.
type Primitive struct {
Mode PrimitiveMode
Material int
Positions []math3d.Vec3
Normals []math3d.Vec3
Tangents []math3d.Vec4
TexCoords0 []math3d.Vec2
TexCoords1 []math3d.Vec2
Colors0 []math3d.Vec4
Joints0 [][4]uint16
Weights0 []math3d.Vec4
Indices []uint32
Bounds math3d.AABB
Targets []MorphTarget
VariantMappings map[int]int
Attributes map[string]int
Extras json.RawMessage
}Primitive holds decoded geometry attributes, indices, bounding volume, morph targets, and KHR_materials_variants mappings for a single draw primitive. Material is -1 when no default material is assigned.
type PrimitiveMode intPrimitiveMode specifies the topology of a mesh primitive.
const (
ModePoints PrimitiveMode = 0
ModeLines PrimitiveMode = 1
ModeLineLoop PrimitiveMode = 2
ModeLineStrip PrimitiveMode = 3
ModeTriangles PrimitiveMode = 4
ModeTriangleStrip PrimitiveMode = 5
ModeTriangleFan PrimitiveMode = 6
)type Sampler struct {
Name string
MagFilter FilterMode
MinFilter FilterMode
WrapS WrapMode
WrapT WrapMode
Extras json.RawMessage
}Sampler describes filtering and wrapping properties for a texture.
type Scene struct {
Name string
Roots []int
Extras json.RawMessage
}Scene represents a glTF 2.0 scene with its root node indices.
type Skin struct {
Name string
Joints []int
Skeleton int
InverseBindMatrices []math3d.Mat4
Extras json.RawMessage
}Skin defines skeletal joints and their inverse bind matrices. Skeleton is -1 when unset.
type TargetPath stringTargetPath identifies which node property an animation channel drives.
const (
PathTranslation TargetPath = "translation"
PathRotation TargetPath = "rotation"
PathScale TargetPath = "scale"
PathWeights TargetPath = "weights"
)type Texture struct {
Name string
Sampler int
Source int
Extras json.RawMessage
Extensions map[string]json.RawMessage
}Texture binds an Image source with an optional Sampler. Sampler and Source are -1 when unset.
type TextureRef struct {
TextureIndex int
TexCoord int
Scale float32
Strength float32
Transform *TextureTransform
}TextureRef references a Texture in Document.Textures along with UV channel, normal scale / occlusion strength, and optional KHR_texture_transform.
func (r TextureRef) ApplyUV(uv math3d.Vec2) math3d.Vec2ApplyUV transforms uv with r.Transform if present, or returns uv unchanged.
func (r TextureRef) EffectiveTexCoord() intEffectiveTexCoord returns Transform.TexCoord if KHR_texture_transform overrides the UV set, otherwise TexCoord.
type TextureTransform struct {
Offset [2]float32
Rotation float32
Scale [2]float32
TexCoord *int
}TextureTransform represents the Khronos KHR_texture_transform extension. Transforms are applied in exact spec order: T(Offset) * R(Rotation) * S(Scale) in glTF UV space (origin top-left, +U right, +V down, positive rotation counter-clockwise).
func DefaultTextureTransform() TextureTransformDefaultTextureTransform returns the identity KHR_texture_transform value (offset [0, 0], rotation 0, scale [1, 1], no texCoord override).
func (t TextureTransform) Apply(uv math3d.Vec2) math3d.Vec2Apply transforms a 2D texture coordinate using the exact KHR_texture_transform matrix order M = T * R * S.
func (t TextureTransform) ApplyUV(u, v float32) (float32, float32)ApplyUV transforms texture coordinates (u, v) using the exact KHR_texture_transform matrix order M = T * R * S:
su = u * Scale[0] sv = v * Scale[1] u' = cos(Rotation)*su + sin(Rotation)*sv + Offset[0] v' = -sin(Rotation)*su + cos(Rotation)*sv + Offset[1]
func (t TextureTransform) IsIdentity() boolIsIdentity reports whether t leaves UV coordinates unchanged (offset [0, 0], rotation 0, and scale [1, 1]).
func (t TextureTransform) Matrix() math3d.Mat3Matrix returns the column-major 3x3 homogeneous UV transform matrix T * R * S matching the Khronos KHR_texture_transform specification.
type Transmission struct {
// Factor is transmissionFactor in [0, 1] (default 0). Multiplied by Texture's R channel when present.
Factor float32
// Texture is transmissionTexture (optional, linear; R channel modulates Factor).
Texture *TextureRef
}Transmission represents the Khronos KHR_materials_transmission material extension, describing optical transmission through thin dielectric surfaces.
type WrapMode intWrapMode defines glTF texture coordinate wrapping modes.
const (
WrapClampToEdge WrapMode = 33071
WrapMirroredRepeat WrapMode = 33648
WrapRepeat WrapMode = 10497
)