API
glTF structs
This section contains all types fastgltf provides to represent data from a glTF asset.
DataSource
-
using fastgltf::DataSource = std::variant<std::monostate, sources::BufferView, sources::URI, sources::Vector, sources::CustomBuffer, sources::ByteView, sources::Fallback>
Represents the data source of a buffer or image.
These could be a buffer view, a file path (including offsets), a ordinary vector (if Options::LoadExternalBuffers or Options::LoadGLBBuffers was specified), or the ID of a custom buffer.
Note
As a user, you should never encounter this variant holding the std::monostate, as that would be a ill-formed glTF, which fastgltf already checks for while parsing.
Note
For buffers, this variant will never hold a sources::BufferView, as only images are able to reference buffer views as a source.
AssetInfo
-
struct AssetInfo
Accessor
-
struct Accessor
Public Members
-
std::size_t byteOffset
-
std::size_t count
-
AccessorType type
-
ComponentType componentType
-
bool normalized
-
std::variant<std::monostate, ::std::vector<double>, ::std::vector<std::int64_t>> max
-
std::variant<std::monostate, ::std::vector<double>, ::std::vector<std::int64_t>> min
-
::std::string name
-
std::size_t byteOffset
Animation
-
struct Animation
Buffer
-
struct Buffer
BufferView
-
struct BufferView
Camera
-
struct Camera
Public Members
-
std::variant<Perspective, Orthographic> camera
Variant holding either a perspective or a orthographic camera.
Use std::holds_alternative and/or std::get_if to figure out which camera type is being used.
-
::std::string name
-
struct Orthographic
-
struct Perspective
-
std::variant<Perspective, Orthographic> camera
Image
-
struct Image
Light
-
struct Light
Material
-
struct Material
Public Members
-
PBRData pbrData
A set of parameter values that are used to define the metallic-roughness material model from Physically Based Rendering (PBR) methodology.
-
std::array<num, 3> emissiveFactor
The factors for the emissive color of the material.
Defaults to 0,0,0
-
AlphaMode alphaMode
The values used to determine the transparency of the material.
Defaults to AlphaMode::Opaque.
-
num alphaCutoff
The alpha value that determines the upper limit for fragments that should be discarded for transparency.
Defaults to 0.5.
-
bool doubleSided
Determines whether back-face culling should be disabled when using this material.
-
std::unique_ptr<MaterialAnisotropy> anisotropy
-
std::unique_ptr<MaterialClearcoat> clearcoat
-
std::unique_ptr<MaterialIridescence> iridescence
Iridescence information from KHR_materials_iridescence.
-
std::unique_ptr<MaterialSheen> sheen
-
std::unique_ptr<MaterialSpecular> specular
Specular information from KHR_materials_specular.
-
std::unique_ptr<MaterialTransmission> transmission
Specular information from KHR_materials_transmission.
-
std::unique_ptr<MaterialVolume> volume
Volume information from KHR_materials_volume.
-
Optional<num> emissiveStrength
The emissive strength from the KHR_materials_emissive_strength extension.
-
bool unlit
Only applicable if KHR_materials_unlit is enabled.
-
::std::string name
-
PBRData pbrData
Mesh
-
struct Mesh
Node
-
struct Node
Public Types
-
using TransformMatrix = std::array<num, 16>
Public Functions
-
inline auto findInstancingAttribute(std::string_view attributeName) noexcept
-
inline auto findInstancingAttribute(std::string_view attributeName) const noexcept
Public Members
-
Optional<std::size_t> lightIndex
Only ever non-empty when KHR_lights_punctual is enabled and used by the asset.
-
::fastgltf::MaybeSmallVector<std::size_t> children
-
::fastgltf::MaybeSmallVector<num> weights
-
std::variant<TRS, TransformMatrix> transform
Variant holding either the three TRS components; transform, rotation, and scale, or a transformation matrix, which cannot skew or shear.
The latter can be decomposed into the TRS components by specifying Options::DecomposeNodeMatrices.
-
::std::vector<std::pair<::std::string, std::size_t>> instancingAttributes
Only ever non-empty when EXT_mesh_gpu_instancing is enabled and used by the asset.
-
::std::string name
-
struct TRS
-
using TransformMatrix = std::array<num, 16>
Sampler
-
struct Sampler
Scene
-
struct Scene
Skin
-
struct Skin
Texture
-
struct Texture
Public Members
-
Optional<std::size_t> samplerIndex
If no sampler is specified, use a default sampler with repeat wrap and auto filter.
-
Optional<std::size_t> imageIndex
The index of the image used by this texture.
Either this will have a value, or one of the following extensions will define a texture index. If no extensions were enabled while parsing, this will always have a value.
-
Optional<std::size_t> basisuImageIndex
An optional texture index from the KHR_texture_basisu extension.
-
Optional<std::size_t> webpImageIndex
An optional texture index from the EXT_texture_webp extension.
-
::std::string name
-
Optional<std::size_t> samplerIndex
Asset
Parser
This section contains all types that one requires to load a glTF file using fastgltf. This includes the Parser class, options, and data buffers.
Error
-
enum class fastgltf::Error : std::uint64_t
Values:
-
enumerator None
-
enumerator InvalidPath
The glTF directory passed to load*GLTF is invalid.
-
enumerator MissingExtensions
One or more extensions are required by the glTF but not enabled in the Parser.
-
enumerator UnknownRequiredExtension
An extension required by the glTF is not supported by fastgltf.
-
enumerator InvalidJson
An error occurred while parsing the JSON.
-
enumerator InvalidGltf
The glTF is either missing something or has invalid data.
-
enumerator InvalidOrMissingAssetField
The glTF asset object is missing or invalid.
-
enumerator InvalidGLB
The GLB container is invalid.
-
enumerator MissingField
A field is missing in the JSON.
Note
This is only used internally.
-
enumerator MissingExternalBuffer
With Options::LoadExternalBuffers, an external buffer was not found.
-
enumerator UnsupportedVersion
The glTF version is not supported by fastgltf.
-
enumerator None
Extensions
-
enum class fastgltf::Extensions : std::uint64_t
Values:
-
enumerator None
-
enumerator KHR_texture_transform
-
enumerator KHR_texture_basisu
-
enumerator MSFT_texture_dds
-
enumerator KHR_mesh_quantization
-
enumerator EXT_meshopt_compression
-
enumerator KHR_lights_punctual
-
enumerator EXT_texture_webp
-
enumerator KHR_materials_specular
-
enumerator KHR_materials_ior
-
enumerator KHR_materials_iridescence
-
enumerator KHR_materials_volume
-
enumerator KHR_materials_transmission
-
enumerator KHR_materials_clearcoat
-
enumerator KHR_materials_emissive_strength
-
enumerator KHR_materials_sheen
-
enumerator KHR_materials_unlit
-
enumerator KHR_materials_anisotropy
-
enumerator EXT_mesh_gpu_instancing
-
enumerator None
-
inline std::string_view fastgltf::stringifyExtension(Extensions extensions)
Returns the name of the passed glTF extension.
Note
If
extensions
has more than one bit set (multiple extensions), this will return the name of the first set bit.
Category
-
enum class fastgltf::Category : std::uint32_t
Values:
-
enumerator None
-
enumerator Buffers
-
enumerator BufferViews
-
enumerator Accessors
-
enumerator Images
-
enumerator Samplers
-
enumerator Textures
-
enumerator Animations
-
enumerator Cameras
-
enumerator Materials
-
enumerator Meshes
-
enumerator Skins
-
enumerator Nodes
-
enumerator Scenes
-
enumerator Asset
-
enumerator All
-
enumerator OnlyRenderable
-
enumerator OnlyAnimations
-
enumerator None
Options
-
enum class fastgltf::Options : std::uint64_t
Values:
-
enumerator None
-
enumerator AllowDouble
This allows 5130 as an accessor component type.
5130 is the OpenGL constant GL_DOUBLE, which is by default not listed as an allowed component type in the glTF spec.
The glTF normally only allows these component types: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#accessor-data-types
-
enumerator DontRequireValidAssetMember
This skips validating the asset field, as it is usually there and not used anyway.
-
enumerator LoadGLBBuffers
Loads all the GLB buffers into CPU memory.
If disabled, fastgltf will only provide a byte offset and length into the GLB file, which can be useful when using APIs like DirectStorage or Metal IO.
-
enumerator LoadExternalBuffers
Loads all external buffers into CPU memory.
If disabled, fastgltf will only provide a full file path to the file holding the buffer, which can be useful when using APIs like DirectStorage or Metal IO. For images, LoadExternalImages has to be explicitly specified, too, if required.
-
enumerator DecomposeNodeMatrices
This option makes fastgltf automatically decompose the transformation matrices of nodes into the translation, rotation, and scale components.
This might be useful to have only TRS components, instead of matrices or TRS, which should simplify working with nodes, especially with animations.
-
enumerator MinimiseJsonBeforeParsing
This option makes fastgltf minimise the JSON file before parsing.
In most cases, minimising it beforehand actually reduces the time spent. However, there are plenty of cases where this option slows down parsing drastically, which from my testing seem to all be glTFs which contain embedded buffers and/or are already minimised. Note that fastgltf only minimises the string if the data was loaded using GltfDataBuffer::loadFromFile or GltfDataBuffer::copyBytes, and that the bytes will also be overwritten.
-
enumerator LoadExternalImages
Loads all external images into CPU memory.
It does not decode any texture data. Complementary to LoadExternalBuffers.
-
enumerator GenerateMeshIndices
Lets fastgltf generate indices for all mesh primitives without indices.
This currently does not de-duplicate the vertices. This is entirely for compatibility and simplifying the loading process.
-
enumerator None
Expected
-
template<typename T>
class Expected A type that stores an error together with an expected value.
To use this type, first call error() to inspect if any errors have occurred. If error() is not fastgltf::Error::None, calling get(), operator->(), and operator*() is undefined behaviour.
Public Functions
-
inline T &get() noexcept
Returns a reference to the value of T.
When error() returns anything but Error::None, the returned value is undefined.
-
inline T *get_if() noexcept
Returns the address of the value of T, or nullptr if error() returns anything but Error::None.
-
template<std::size_t I>
inline auto &get() noexcept
-
template<std::size_t I>
inline const auto &get() const noexcept
-
inline T *operator->() noexcept
Returns the address of the value of T.
When error() returns anything but Error::None, the returned value is undefined.
-
inline const T *operator->() const noexcept
Returns the address of the const value of T.
When error() returns anything but Error::None, the returned value is undefined.
-
inline operator bool() const noexcept
-
inline T &get() noexcept
GltfDataBuffer
-
std::size_t fastgltf::getGltfBufferPadding() noexcept
Gets the amount of byte padding required on the GltfDataBuffer, as simdjson requires to be able to overflow as it uses SIMD to load N bytes at a time.
-
class GltfDataBuffer
This class holds a chunk of data that makes up a JSON string that the glTF parser will use and read from.
Public Functions
-
explicit GltfDataBuffer() noexcept
-
explicit GltfDataBuffer(span<std::byte> data) noexcept
Constructs a new GltfDataBuffer from a span object, copying its data as there is no guarantee for the allocation size to have the adequate padding.
-
virtual ~GltfDataBuffer() noexcept
-
bool fromByteView(std::uint8_t *bytes, std::size_t byteCount, std::size_t capacity) noexcept
Saves the pointer including its range.
Does not copy any data. This requires the original allocation to outlive the parsing of the glTF, so after the last relevant call to fastgltf::Parser::loadGLTF. However, this function asks for a capacity size, as the JSON parsing requires some padding. See fastgltf::getGltfBufferPadding for more information. If the capacity does not have enough padding, the function will instead copy the bytes with the copyBytes method. Also, it will set the padding bytes all to 0, so be sure to not use that for any other data.
-
bool copyBytes(const std::uint8_t *bytes, std::size_t byteCount) noexcept
This will create a copy of the passed bytes and allocate an adequately sized buffer.
-
bool loadFromFile(const std::filesystem::path &path, std::uint64_t byteOffset = 0) noexcept
Loads the file with a optional byte offset into a memory buffer.
-
inline std::size_t getBufferSize() const noexcept
Returns the size, in bytes,.
- Returns:
-
explicit GltfDataBuffer() noexcept
Parser
-
class Parser
A parser for one or more glTF files.
It uses a SIMD based JSON parser to maximize efficiency and performance at runtime.
Note
This class is not thread-safe.
Public Functions
-
explicit Parser(Extensions extensionsToLoad = Extensions::None) noexcept
-
~Parser()
-
Expected<Asset> loadGLTF(GltfDataBuffer *buffer, std::filesystem::path directory, Options options = Options::None, Category categories = Category::All)
Loads a glTF file from pre-loaded bytes representing a JSON file.
-
Expected<Asset> loadBinaryGLTF(GltfDataBuffer *buffer, std::filesystem::path directory, Options options = Options::None, Category categories = Category::All)
Loads a glTF file embedded within a GLB container, which may contain the first buffer of the glTF asset.
-
void setBufferAllocationCallback(BufferMapCallback *mapCallback, BufferUnmapCallback *unmapCallback = nullptr) noexcept
This function can be used to set callbacks so that you can control memory allocation for large buffers and images that are loaded from a glTF file.
For example, one could use the callbacks to map a GPU buffer through Vulkan or DirectX so that fastgltf can write the buffer directly to the GPU to avoid a copy into RAM first. To remove the callbacks for a specific load, call this method with both parameters as nullptr before load*GLTF. Using Parser::setUserPointer you can also set a user pointer to access your own class or other data you may need.
Note
This is likely only useful for advanced users who know what they’re doing.
- Parameters:
mapCallback – function called when the parser requires a buffer to write data embedded in a GLB file or decoded from a base64 URI, cannot be nullptr.
unmapCallback – function called when the parser is done with writing into a buffer, can be nullptr.
-
void setBase64DecodeCallback(Base64DecodeCallback *decodeCallback) noexcept
Allows setting callbacks for base64 decoding.
This can be useful if you have another base64 decoder optimised for a certain platform or architecture, or want to use your own scheduler to schedule multiple threads for working on decoding individual chunks of the data. Using Parser::setUserPointer you can also set a user pointer to access your own class or other data you may need.
It is still recommended to use fastgltf’s base64 decoding features as they’re highly optimised for SSE4, AVX2, and ARM Neon.
- Parameters:
decodeCallback – function called when the parser tries to decode a base64 buffer
-
void setUserPointer(void *pointer) noexcept
-
explicit Parser(Extensions extensionsToLoad = Extensions::None) noexcept
-
GltfType fastgltf::determineGltfFileType(GltfDataBuffer *buffer)
This function starts reading into the buffer and tries to determine what type of glTF container it is.
This should be used to know whether to call Parser::loadGLTF or Parser::loadBinaryGLTF.
- Returns:
The type of the glTF file, either glTF, GLB, or Invalid if it was not determinable. If this function returns Invalid it is highly likely that the buffer does not actually represent a valid glTF file.
-
struct BufferInfo
Utility
This sections contains various types used by fastgltf to simplify & process glTF data, and for types used to enhance performance & minimize memory usage.
URIView
-
class URIView
Custom URI class for fastgltf’s needs.
glTF 2.0 only allows two types of URIs: (1) Data URIs as specified in RFC 2397. (2) Relative paths as specified in RFC 3986.
See https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#uris for details. However, the glTF spec allows more broader URIs in client implementations. Therefore, this supports all types of URIs as defined in RFC 3986.
This class, unlike fastgltf::URI, only holds a std::string_view to the URI and therefore doesn’t own the allocation.
Public Functions
-
explicit URIView() noexcept
-
explicit URIView(std::string_view uri) noexcept
-
auto string() const noexcept -> std::string_view
-
auto scheme() const noexcept -> std::string_view
-
auto userinfo() const noexcept -> std::string_view
-
auto host() const noexcept -> std::string_view
-
auto port() const noexcept -> std::string_view
-
auto path() const noexcept -> std::string_view
-
auto query() const noexcept -> std::string_view
-
auto fragment() const noexcept -> std::string_view
-
auto fspath() const -> std::filesystem::path
-
bool valid() const noexcept
-
bool isLocalPath() const noexcept
-
bool isDataUri() const noexcept
-
explicit URIView() noexcept
URI
-
class URI
Custom URI class for fastgltf’s needs.
glTF 2.0 only allows two types of URIs: (1) Data URIs as specified in RFC 2397. (2) Relative paths as specified in RFC 3986.
See https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#uris for details. However, the glTF spec allows more broader URIs in client implementations. Therefore, this supports all types of URIs as defined in RFC 3986.
This class, unlike fastgltf::URIView, holds a std::string which contains the URI. It also decodes any percent-encoded characters.
Public Functions
-
explicit URI() noexcept
-
explicit URI(std::string uri) noexcept
-
explicit URI(std::string_view uri) noexcept
-
auto string() const noexcept -> std::string_view
-
auto scheme() const noexcept -> std::string_view
-
auto userinfo() const noexcept -> std::string_view
-
auto host() const noexcept -> std::string_view
-
auto port() const noexcept -> std::string_view
-
auto path() const noexcept -> std::string_view
-
auto query() const noexcept -> std::string_view
-
auto fragment() const noexcept -> std::string_view
-
auto fspath() const -> std::filesystem::path
-
bool valid() const noexcept
-
bool isLocalPath() const noexcept
-
bool isDataUri() const noexcept
Public Static Functions
-
static void decodePercents(std::string &x) noexcept
-
explicit URI() noexcept
span
-
template<typename T, std::size_t Extent = dynamic_extent>
class span Custom span class imitating C++20’s std::span for referencing bytes without owning the allocation.
Can also directly be converted to a std::span or used by itself.
Public Functions
-
constexpr span() noexcept = default
-
inline constexpr reference operator[](size_type idx) const
-
inline constexpr pointer data() const noexcept
-
inline constexpr size_type size() const noexcept
-
inline constexpr size_type size_bytes() const noexcept
-
inline constexpr bool empty() const noexcept
-
constexpr span() noexcept = default
SmallVector
-
template<typename T, std::size_t N = initialSmallVectorStorage, typename Allocator = std::allocator<T>>
class SmallVector A custom vector class for fastgltf, which can store up to N objects within itself.
This is useful for cases where the vector is expected to only ever hold a tiny amount of small objects, such as a node’s children. SmallVector is also mostly conformant to C++17’s std::vector, and can therefore be used as a drop-in replacement.
Note
It is also available with polymorphic allocators in the fastgltf::pmr namespace.
Public Functions
-
inline SmallVector()
-
inline SmallVector(const SmallVector &other) noexcept
-
inline SmallVector(SmallVector &&other) noexcept
-
inline SmallVector &operator=(const SmallVector &other)
-
inline SmallVector &operator=(SmallVector &&other) noexcept
-
inline ~SmallVector()
-
inline const_iterator begin() const noexcept
-
inline const_iterator cbegin() const noexcept
-
inline const_iterator end() const noexcept
-
inline const_iterator cend() const noexcept
-
inline std::size_t size() const noexcept
-
inline std::size_t size_in_bytes() const noexcept
-
inline std::size_t capacity() const noexcept
-
inline bool empty() const noexcept
-
inline bool isUsingStack() const noexcept
-
inline void reserve(std::size_t newCapacity)
-
inline void resize(std::size_t newSize)
-
inline void shrink_to_fit()
-
inline void clear() noexcept
-
inline SmallVector()
Optional
-
template<typename T>
using fastgltf::Optional = std::conditional_t<!std::is_same_v<std::nullopt_t, std::remove_const_t<decltype(OptionalFlagValue<T>::missing_value)>>, OptionalWithFlagValue<T>, std::optional<T>> A type alias which checks if there is a specialization of OptionalFlagValue for T and “switches” between fastgltf::OptionalWithFlagValue and std::optional.
OptionalFlagValue
OptionalWithFlagValue
-
template<typename T>
class OptionalWithFlagValue A custom optional class for fastgltf, which uses so-called “flag values” which are specific values of T that will never be present as an actual value.
We can therefore use those values as flags for whether there is an actual value stored, instead of the additional bool used by std::optional.
These flag values are obtained from the specializations of OptionalFlagValue. If no specialization for T of OptionalFlagValue is provided, a static assert will be triggered. In those cases, use std::optional or fastgltf::Optional instead.
Public Functions
-
inline OptionalWithFlagValue() noexcept
-
inline OptionalWithFlagValue(std::nullopt_t) noexcept
-
template<typename U = T, std::enable_if_t<std::is_copy_constructible_v<T>, int> = 0>
inline OptionalWithFlagValue(const OptionalWithFlagValue<U> &other)
-
template<typename U = T, std::enable_if_t<std::is_move_constructible_v<T>, int> = 0>
inline OptionalWithFlagValue(OptionalWithFlagValue<U> &&other)
-
template<typename ...Args, std::enable_if_t<std::is_constructible_v<T, Args...>, int> = 0>
inline explicit OptionalWithFlagValue(std::in_place_t, Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args...>)
-
template<typename U = T, std::enable_if_t<std::is_constructible_v<T, U&&>, int> = 0>
inline OptionalWithFlagValue(U &&_new) noexcept(std::is_nothrow_assignable_v<T&, U> && std::is_nothrow_constructible_v<T, U>)
-
inline ~OptionalWithFlagValue()
-
inline OptionalWithFlagValue &operator=(std::nullopt_t) noexcept
-
template<typename U = T, std::enable_if_t<std::is_constructible_v<T, U&&>, int> = 0>
inline OptionalWithFlagValue &operator=(U &&_new) noexcept(std::is_nothrow_assignable_v<T&, U> && std::is_nothrow_constructible_v<T, U>)
-
template<typename U, std::enable_if_t<std::conjunction_v<std::is_constructible<T, const U&>, std::is_assignable<T&, const U&>>, int> = 0>
inline OptionalWithFlagValue &operator=(const OptionalWithFlagValue<U> &other)
-
template<typename U, std::enable_if_t<std::conjunction_v<std::is_constructible<T, U>, std::is_assignable<T&, U>>, int> = 0>
inline OptionalWithFlagValue &operator=(OptionalWithFlagValue<U> &&other) noexcept(std::is_nothrow_assignable_v<T&, T> && std::is_nothrow_constructible_v<T, T>)
-
inline bool has_value() const
-
inline void swap(OptionalWithFlagValue<T> &other) noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_swappable_v<T>)
-
inline void reset() noexcept
-
template<typename U, typename ...Args>
inline T &emplace(std::initializer_list<U> list, Args&&... args)
-
inline explicit operator bool() const noexcept
-
inline OptionalWithFlagValue() noexcept