glTF Animations
local graph
Chapter 9 — glTF Animations
Section titled “Chapter 9 — glTF Animations”In this chapter, we will explore advanced glTF core specification features, including animations, skinning, and morphing. We will cover the basics of each technique and implement skinning animations and morphing using compute shaders. In the final recipe, we will introduce animation blending, showing how to create complex animation sequences.
Most of the C++ code provided here can be applied not only to these recipes but also throughout the rest of the book.
In this chapter, we will cover the following recipes:
- Introduction to node-based animations
- Introduction to skeletal animations
- Importing skeleton and animation data
- Implementing the glTF animation player
- Doing skeletal animations in compute shaders
- Introduction to morph targets
- Loading glTF morph target data
- Adding morph targets support
- Animation blending Note We use the official Khronos Sample Viewer as a reference for applying glTF skinning and morphing data, though our implementation doesn’t rely on this project. The official Khronos Sample Viewer uses JavaScript and vertex shaders to implement animation features, while in our recipes, we use compute shaders and a streamlined approach that favors simplicity of implementation over feature completeness.
Technical requirements
Section titled “Technical requirements”We assume readers have a basic understanding of linear algebra and calculus, and we recommend becoming familiar with the glTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#animations.
In this chapter, we continue refining our unified glTF Viewer sample code that we built in previous chapters. The variations in each recipe’s main.cpp file include using different model files to demonstrate the specific glTF animation feature covered in each recipe, adjusting initial camera positions for optimal model presentation, and making minor UI changes to highlight the glTF features explored in each recipe.
The source code for our glTF Viewer is located in shared/UtilsGLTF.cpp. The GLSL vertex and fragment shaders can be found in the data/shaders/gltf/ folder. The code for animation-specific utilities can be found in shared/UtilsAnim.cpp and shared/UtilsAnim.h.
Introduction to node-based animations
Section titled “Introduction to node-based animations”In this recipe, we will explore node-based animations, how they’re organized, and what the key principles of the glTF specification are. This builds on the code from Chapters 6 and 7. Let’s start with an overview of computer animation. At its core, computer animation is the process of creating moving images. This can be achieved in different ways, from playing a sequence of still images to using physics-based simulations for each pixel. Our focus will be on real-time computer graphics, which typically use efficient methods such as scene hierarchy transformations, skeletal animation, and morphing. Efficiency is key, as it allows the data to be represented and processed in real time on today’s hardware.
In Chapters 6 and 7, we looked at different scene graph representations and how a scene is represented in the glTF specification. Each scene is structured like a tree, with transformations applied to each node. By changing these node transformations, we can create motion, which is the basis of node-based animation. In addition to the scene graph hierarchy, glTF includes a way to store animation data. All animations in glTF are stored in the asset’s animations array.
An animation is defined by channels and samplers. Samplers refers to accessors that contain keyframe data and specify interpolation methods. Channels link these keyframe outputs to specific nodes in the hierarchy.
Keyframes assign specific transformations to particular time points. glTF supports translations, quaternion-based rotations, scaling, and weights to represent these transformations.
In glTF, animation interpolation is the process of calculating the intermediate parameter values between keyframes, which creates specific transitions between distinct animation poses.
glTF supports several interpolation types:
- LINEAR: This is the simplest type, where the value at a given time is linearly interpolated between the values of the previous and next keyframes.
- STEP: In this type, the value stays constant until the next keyframe, at which point it jumps to the new value.
- CUBICSPLINE: This interpolation type uses cubic splines for smoother, more natural-looking animations and requires extra control points to shape the curve.
Note
Unfortunately, Assimp only supports linear interpolation at the time of this book’s writing; thus, our examples use this mode.
The glTF animation interpolation process works as follows:
- Identify the keyframes surrounding the current time.
- Calculate the weights for each keyframe based on the current time and the distance between them.
- Interpolate the keyframe values using the specified interpolation type and calculated weights.
Here’s a simple example with two keyframes:
Keyframe 1: Time = 0, Value = 10
Keyframe 2: Time = 1, Value = 20
If the current time is 0.4, the interpolated value would be (1 - 0.4) * 10 + 0.4 * 20 = 14.
glTF animations can contain multiple channels, each controlling a different property of a node (such as translation, rotation, or scale). Interpolation is applied independently to each channel. In hierarchical animations, transformations of parent nodes influence the transformations of child nodes, with interpolation applied recursively throughout the hierarchy.
Before diving into the code, let’s take a look at how glTF handles skeletal animations.
Introduction to skeletal animations
Section titled “Introduction to skeletal animations”Vertex skinning animation is a technique for animating 3D characters by linking a polygonal mesh to a hierarchical skeleton. Bones in the skeleton control the mesh deformation, allowing for realistic movement. This method is widely used in animation, enabling animators to control complex characters through intuitive tools.
The process begins with creating a skeleton of bones, each with a defined position, scale, and orientation. These bones are arranged hierarchically, resembling a human or animal skeleton. The mesh is then associated with specific bones, often using weights to indicate how much influence each bone has on particular vertices of the mesh. As the bones move, the mesh deforms naturally, resulting in lifelike animations.
To animate a mesh, we need to dynamically transform its vertices. Each bone defines a transformation, and the most flexible method is to store a 4x4 affine transformation matrix for each bone. This matrix encapsulates the combined effects of scaling, rotation, and translation. While it’s possible to store separate translation, rotation, and scaling components, using a matrix simplifies shader operations, particularly when dealing with multiples of 4 components.
These transformations should already account for the effects of parent bones. We’ll refer to these as global transforms, in contrast to local transforms, which are relative to their parent and do not take a parent transform into account. The global transform of a bone is calculated recursively as follows:
If a bone has no parent, its global transform is the same as its local transform.
Local bone transformations are usually defined in a specific coordinate system rather than in world coordinates. For example, when rotating an arm, it makes sense to use a local coordinate system centered around the shoulder joint, which eliminates the need for explicit translation.
Each bone has its own local coordinate system. To transform vertices from the model’s coordinate system into bone-local space, we use an inverse bind matrix. This matrix effectively repositions the vertices relative to the origin of the bone.
To render hierarchical mesh data after applying the animation transformation in the bone-local coordinate system, we need to transform the vertices back to the parent bone’s local coordinate system. This can be done using inverse bind matrices, as follows:
This process effectively transforms vertices from one bone-local coordinate system to another. Additionally, bones can be connected to vertices in a transformed state known as the bind pose.
Note
It is a pose, in which the mesh is in its original, undeformed state, typically serving as the basis for skinning (attaching the mesh to a skeleton).
This requires an extra transformation to position the vertices correctly in the expected local coordinate system for each bone.
To transform each vertex, we follow these steps:
- Transform it to the model’s bind pose.
- Use the inverse bind matrix to convert the vertex to the bone-local coordinate system.
- Apply the animation transformations in the bone-local coordinate system.
- Transform the vertex back from the bone-local space to the model’s coordinate system.
- If the bone has a parent, repeat steps 2-4 for the parent bone.
As discussed in Chapter 6, a glTF scene consists of nodes, which can represent various elements, like meshes, cameras, light sources, and skeleton bones, or simply act as parent containers for other nodes. Each node has its own transformation, defining its position, rotation, and scale relative to its parent or the world origin.
If a mesh node uses skeletal animation, it includes a list of joints, which are glTF node IDs representing the skeleton’s bones. These joints form a hierarchy. Note that there is no explicit armature or skeleton node; instead, bone nodes are used directly.
For a mesh primitive using skeletal animation, each vertex requires bone ID and weight attributes. Alongside the skinned mesh data, glTF files can include animations, which provide instructions for updating transformations in the node hierarchy.
glTF organizes transformations in the following way:
- Model Bind Pose: This is either applied to the model directly or pre-multiplied into the inverse bind matrices. In glTF, the bind pose can essentially be ignored.
- Inverse Bind Matrices: These are provided as an accessor containing an array of 4x4 matrices.
- Animations: Animations can be defined externally or stored as keyframe splines for rotation, translation, and scale. These animations are combined with the transformation from their local coordinate system to the parent’s local coordinate system.
- Parent Relationships: While parent nodes are defined in the node hierarchy, the conversion to the parent’s coordinate system has already been applied. Therefore, you only need to repeat steps 3-5 above for parent nodes if they exist.
Thus, the final global transform for a glTF bone is constructed as follows:

We will implement this approach in the following recipes. Now, let’s look into the actual code to learn how to store skeleton and animation data and load it from glTF files.
Note
Here’s a link to the glTF 2.0 specification, which provides a detailed explanation of skinning:
https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#skins
Importing skeleton and animation data
Section titled “Importing skeleton and animation data”This recipe introduces two key improvements to our glTF Viewer: it now supports storing data for skeletons and animations, and it includes functionality to load this data from glTF assets using Assimp.
These enhancements are put to use in the following recipes, where they enable the implementation of mesh skinning and animations.
Getting ready
Section titled “Getting ready”This recipe does not include a separate code example. Instead, it explains the modifications made to the utility code, located in the files shared/UtilsGLTF.h and shared/UtilsGLTF.cpp.
How to do it…
Section titled “How to do it…”Let’s begin with the skeleton by defining the essential data structures needed to store it.
- First, we should add a way to reference transformations. The identifier
modelMtxIdis used to point to a specific matrix within theGLTFContext::matricesBuffer. This approach generalizes how glTF transformations are managed and accessed.using GLTFNodeRef = uint32_t;using GLTFMeshRef = uint32_t;struct GLTFTransforms {uint32_t modelMtxId;uint32_t matId;GLTFNodeRef nodeRef; // for CPU onlyGLTFMeshRef meshRef; // for CPU onlyuint32_t sortingType;}; - We need a struct to store vertex skeleton attribution data, specifically the bone indices and bone weights. This data will allow us to define how each vertex is influenced by the skeleton’s bones. Here, we use
vec4for positions and normal vectors to ensure padding compatibility, as this structure will be shared between the CPU and GPU.#define MAX_BONES_PER_VERTEX 8struct VertexBoneData {vec4 position;vec4 normal;uint32_t boneId[MAX_BONES_PER_VERTEX] = {~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u };float weight[MAX_BONES_PER_VERTEX] = {};uint32_t meshId = ~0u;}; - Next, we need a way to store bone data. While we could reuse glTF nodes, we create an additional structure,
GLTFBone, to keep things simpler and more efficient.struct GLTFBone {uint32_t boneId = ~0u;mat4 transform = mat4(1.0f);}; - To store this data, we’ll need to add a few new member fields to
GLTFContextinshared/UtilsGLTF.h:class GLTFContext// …unordered_map<std::string, GLTFBone> bonesByName;std::vector<MorphTarget> morphTargets;Holder<BufferHandle> vertexSkinningBuffer;Holder<BufferHandle> vertexMorphingBuffer;// …};
Note
Here, we’re using a simpler approach with std::unordered_map to map bone names to unique GLTFBone objects. This choice was made to keep things straightforward and make the material in this chapter easier to follow. When performance becomes critical, it is recommended to replace string identifiers with indices and avoid accessing hash tables at runtime, similar to how scene nodes were managed in Chapter 8.
With the key data structures now declared, let’s examine the new code responsible for loading the bone data.
- This code, added to the
loadGLTF()function and located inshared/UtilsGLTF.cpp, will handle importing and organizing the bones.void loadGLTF(GLTFContext& gltf,const char* glTFName, const char* glTFDataPath){// …uint32_t numBones = 0;uint32_t vertOffset = 0;// …gltf.hasBones = mesh->mNumBones > 0;for (uint32_t id = 0; id < mesh->mNumBones;id++) {const aiBone& bone = *mesh->mBones[id];const char* boneName = bone.mName.C_Str(); - For convenience, all bones are stored in an
std::unordered_mapcontainer calledbonesByName.const bool hasBone = gltf.bonesByName.contains(boneName);const uint32_t boneId = hasBone ?gltf.bonesByName[boneName].boneId : numBones++;if (!hasBone)gltf.bonesByName[boneName] = {.boneId = boneId,.transform = aiMatrix4x4ToMat4(bone.mOffsetMatrix) }; - For each bone, we gather all weights provided by Assimp and store them in the
VertexBoneData::weightarray.for (uint32_t w = 0; w < bone.mNumWeights; w++) {const uint32_t vertexId = bone.mWeights[w].mVertexId;VertexBoneData& vtx = skinningData[vertexId + vertOffset];vtx.position = vec4(vertices[vertexId +vertOffset].position, 1.0f);vtx.normal = vec4(vertices[vertexId + vertOffset].normal, 0.0f);vtx.meshId = m;for (uint32_t i = 0; i < MAX_BONES_PER_VERTEX; i++) {if (vtx.boneId[i] == ~0u) {vtx.weight[i] = bone.mWeights[w].mWeight;vtx.boneId[i] = boneId;break;}}}}vertOffset += mesh->mNumVertices;
It’s a lengthy function but very straightforward. We store a vector of VertexBoneData structures, matching the base vertices from the glTF mesh. For each vertex, we store the meshId, copy the original positions, and assign the boneIds and weights. Assimp provides a list of bones, and we use the bone names to link them to the correct glTF mesh index. The entire VertexBoneData vector is then uploaded into a GPU buffer called vertexSkinningBuffer, ensuring that all vertex skinning data is accessible on the GPU.
- An additional modification in the
loadGLTF()function is the node matrix mapping. For each node, we assign a matrix ID and store its transformation, allowing efficient access to each node’s transformation matrix:uint32_t nonBoneMtxId = numBones;// …const char* rootName =scene->mRootNode->mName.C_Str() ?scene->mRootNode->mName.C_Str() : "root";gltf.nodesStorage.push_back({.name = rootName,.modelMtxId =getNextMtxId(gltf, rootName, nonBoneMtxId,aiMatrix4x4ToMat4(scene->mRootNode->mTransformation)),.transform = aiMatrix4x4ToMat4(scene->mRootNode->mTransformation),}); - The idea behind the
getNextMtxId()helper function is straightforward. If a node has an associated bone, we assign the bone ID as the node’s matrix position; otherwise, we allocate the next available ID, starting fromnumBonespassed asnextEmptyId.uint32_t getNextMtxId(GLTFContext& gltf,const char* name,uint32_t& nextEmptyId,const mat4& mtx){const auto it = gltf.bonesByName.find(name);const uint32_t mtxId =it == gltf.bonesByName.end() ?nextEmptyId++ : it->second.boneId;if (gltf.matrices.size() <= mtxId)gltf.matrices.resize(mtxId + 1);gltf.matrices[mtxId] = mtx;return mtxId;} - After the loading is complete, we can proceed to upload the corresponding data to a GPU buffer.
gltf.vertexSkinningBuffer = ctx->createBuffer({.usage = lvk::BufferUsageBits_Vertex |lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = sizeof(VertexBoneData) * skinningData.size(),.data = skinningData.data(),.debugName = "Buffer: skinning vertex data",});
With the skeleton data loaded, which is essential for mesh skinning, we can now move on to animations and see how the loading process works for them.
How it works…
Section titled “How it works…”Before we can start with the loading of glTF animations, let’s define various animation data structures that we will require. These declarations are located in shared/UtilsAnim.h.
- First, we define the structures for animation keyframes. These structures will serve as the building blocks for organizing and managing our animation data. Each
AnimationKey…structure represents a keyframe of transformation data linked to a specific timestamp.struct AnimationKeyPosition {vec3 pos;float time;};struct AnimationKeyRotation {quat rot;float time;};struct AnimationKeyScale {vec3 scale;float time;}; - Here we declare the
AnimationChannelstructure, which simply holds three collections of keyframes for position, rotation, and scale. It combines these keys into a complete transformation representation.struct AnimationChannel {std::vector<AnimationKeyPosition> pos;std::vector<AnimationKeyRotation> rot;std::vector<AnimationKeyScale> scale;}; - Lastly, we declare the
Animationstructure. To keep things simple, we utilize a hashmap to map the bones to their corresponding animation channels. TheAnimationstructure associates these channels with a particular glTF transformation node and includes additional metadata: the animation’s length in seconds asduration, the time unit for the animationticksPerSecond, and animationnamefor debugging purposes.struct Animation {unordered_map<int, AnimationChannel> channels;std::vector<MorphingChannel> morphChannels;float duration; // in secondsfloat ticksPerSecond;std::string name;};
The vector of morphChannels is used for animation blending and morph targets. We will explore this topic later in this chapter in the recipes Loading morph targets data and Adding morph targets support.
With these data structures established, the code for loading animations from Assimp becomes quite straightforward, as outlined below. Check shared/UtilsAnim.cpp for the complete source code:
- A helper function called
initAnimations()is responsible for loading and initializing all glTF animations from anaiSceneobject. This code is quite mechanical and straightforward; we simply load the data and attribute it according to the node names.void initAnimations(GLTFContext& glTF, const aiScene* scene) {glTF.animations.resize(scene->mNumAnimations);for (uint32_t i = 0; i < scene->mNumAnimations; ++i) {Animation& anim = glTF.animations[i];anim.name = scene->mAnimations[i]->mName.C_Str();anim.duration = scene->mAnimations[i]->mDuration;anim.ticksPerSecond = scene->mAnimations[i]->mTicksPerSecond;for (uint32_t c = 0;c < scene->mAnimations[i]->mNumChannels; c++) {const aiNodeAnim* channel = scene->mAnimations[i]->mChannels[c];uint32_t boneId = glTF.bonesByName[channel->mNodeName.data].boneId; - If a bone wasn’t already populated during the bones initialization process, we create it here. For now, we skip the morph targets loading code, which we will explore later in this chapter in the recipes Introduction to morph targets and Loading glTF morph targets data.
if (boneId == ~0u) {for (const GLTFNode& node : glTF.nodesStorage) {if (node.name != channel->mNodeName.data)continue;boneId = node.modelMtxId;glTF.bonesByName[boneName] = {.boneId = boneId,.transform = glTF.hasBones ?inverse(node.transform):mat4(1) };break;}}anim.channels[boneId] = initChannel(channel);}// … we skip the morph targets loading code here}}
- Another helper function mentioned above,
initChannel(), is also simple and mechanical. It retrieves the data from an Assimp objectaiNodeAnimand transforms it into ourAnimationChannelrepresentation.AnimationChannel initChannel(const aiNodeAnim* anim){AnimationChannel channel;channel.pos.resize(anim->mNumPositionKeys);for (uint32_t i = 0; i < anim->mNumPositionKeys; ++i) {channel.pos[i] = {.pos = aiVector3DToVec3(anim->mPositionKeys[i].mValue),.time = (float)anim->mPositionKeys[i].mTime };}channel.rot.resize(anim->mNumRotationKeys);for (uint32_t i = 0; i < anim->mNumRotationKeys; ++i) {channel.rot[i] = {.rot = aiQuaternionToQuat(anim->mRotationKeys[i].mValue),.time = (float)anim->mRotationKeys[i].mTime };}channel.scale.resize(anim->mNumScalingKeys);for (uint32_t i = 0; i < anim->mNumScalingKeys; ++i) {channel.scale[i] = {.scale = aiVector3DToVec3(anim->mScalingKeys[i].mValue),.time = (float)anim->mScalingKeys[i].mTime };}return channel;} - The final modification to
loadGLTF()is to callinitAnimations()immediately after loading the glTF nodes to load all the animation data.void loadGLTF(GLTFContext& gltf,const char* glTFName, const char* glTFDataPath){const aiScene* scene =aiImportFile(glTFName, aiProcess_Triangulate);// …traverseTree(scene->mRootNode, gltf.root);initAnimations(gltf, scene);// …}
This ensures that the animations are properly initialized and ready for use. Now, let’s learn how to implement an actual glTF animation player using the animation data we’ve just loaded.
Implementing the glTF animation player
Section titled “Implementing the glTF animation player”Let’s start by building a foundation for our glTF animation player. Before we do skinned animations, advanced morphing, or complex blending, we first need to implement the basic animation rendering capabilities using the glTF data we loaded in the previous recipes. Let’s walk through how to set up and extend our glTF viewer to support this essential animation rendering.
Getting ready
Section titled “Getting ready”Make sure to read the previous recipe, Importing skeleton and animation data, to recap the data structures we use to store glTF animation data.
The source code for this recipe is located in Chapter09/01_AnimationPlayer.
How to do it…
Section titled “How to do it…”To begin, let’s introduce the data structures and helper functions needed to support animation playback. We will use them to implement all further animation rendering functionality in our glTF viewer.
- First, we need a way to track the state of an active animation. This includes remembering the time of the last update, whether the animation should loop, and its active status. The struct
AnimationStatedeclared inshared/UtilsAnim.hkeeps track of this data.struct AnimationState {uint32_t animId = ~0u;float currentTime = 0.0f;bool playOnce = false;bool active = false;}; - We need a helper function,
updateAnimation(), which is responsible for applying changes to the animation over time. This function performs checks to ensure that the animation is active and valid before updating. The function is defined inshared/UtilsAnim.cpp.void updateAnimation(GLTFContext& glTF, AnimationState& anim, float dt) {if (!anim.active || (anim.animId == ~0u)) {glTF.morphing = false;glTF.skinning = false;return;} - The function calculates the next timestamp for the active animation by incrementing the
currentTimevariable by the time elapsed since the last frame. It then checks if this timestamp is within the animation’s total duration. If the animation is set to play only once,currentTimeis clamped to the duration, and the animation is disabled, updating it to its final state with no further advancement needed. For looping animations,currentTimeis wrapped back to the start using the floating-point modulo functionfmodf(), ensuring it consistently stays within the0...durationrange for smooth looping.const Animation& activeAnim = glTF.animations[anim.animId];anim.currentTime += activeAnim.ticksPerSecond *dt;if (anim.playOnce && anim.currentTime > activeAnim.duration) {anim.currentTime = activeAnim.duration;anim.active = false;} else {anim.currentTime =fmodf(anim.currentTime, activeAnim.duration);} - The next step is to apply the newly calculated animation timestamp
currentTimeto the actual glTF node transformations. To achieve this, we need to traverse the glTF scene, iterating through all registered nodes and channels, and then apply the corresponding transformations. We define a local lambda function,traverseTree(), to handle this recursive traversal. It takes the current node,gltfNode, and a parent node transformation,parentTransform.std::function<void(GLTFNodeRef gltfNode,const mat4& parentTransform)>traverseTree = [&](GLTFNodeRef gltfNode,const mat4& parentTransform){const GLTFBone& bone = glTF.bonesByName[glTF.nodesStorage[gltfNode].name];const uint32_t boneId = bone.boneId; - If this node is part of the bone hierarchy and has an active animation channel, we call the
animationTransform()function to calculate the appropriate transformation. If the node has no associated animation channels, its transformation doesn’t need updating. Instead, we simply inherit and apply the parent’s transformation. Theskinningflag will be explained in the next recipe, Doing skeletal animations in compute shaders.if (boneId != ~0u) {auto channel = activeAnim.channels.find(boneId);const bool hasActiveChannel =channel != activeAnim.channels.end();glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId] =parentTransform * (hasActiveChannel ?animationTransform(channel->second, anim.currentTime) :glTF.nodesStorage[gltfNode].transform);glTF.skinning = true;} else {glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId] = parentTransform *glTF.nodesStorage[gltfNode].transform;} - We then make a recursive call for all child nodes to continue applying transformations throughout the glTF nodes hierarchy.
for (uint32_t i = 0;i < glTF.nodesStorage[gltfNode].children.size(); i++) {const GLTFNodeRef child =glTF.nodesStorage[gltfNode].children[i];traverseTree(child,glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId]);}};
- The helper function
animationTransform(), which we just mentioned, is quite simple. It calculatesmat4transformations for each transformation channel and combines them into one final transformation.
Note
It is important to note that the order of these transformations is defined by the glTF specification, ensuring consistent application across the animations.
mat4 animationTransform( const AnimationChannel& channel, float time){ mat4 translation = glm::translate(mat4(1.0f), interpolatePosition(channel, time)); mat4 rotation = glm::toMat4( glm::normalize(interpolateRotation(channel, time))); mat4 scale = glm::scale(mat4(1.0f), interpolateScaling(channel, time)); return translation * rotation * scale;}- Before we dive into our interpolation functions, let’s introduce two more helper functions. The first one is called
getTimeIndex(), which performs a search within a vector of sorted keyframe data,t. We utilize binary search to locate the nearest element with a timestamp that is not less than the specifiedtimevalue and clamp it to the maximum index of elements. As a result, we obtain our starting interpolation index, which will be used for interpolation between keyframes.template <typename T> uint32_t getTimeIndex(const std::vector<T>& t, float time) {return std::max(0,(int)std::distance( t.begin(), std::lower_bound(t.begin(), t.end(), time,[&](const T& lhs, float rhs){ return lhs.time < rhs; })) - 1);} - The second function is
interpolationVal(), which returns the interpolation coefficient between two keyframe timestamps. This coefficient helps determine how to blend between the values of the two keyframes based on the current time within the animation. In our book, we use only linear interpolation for animations.float interpolationVal(float lastTimeStamp, float nextTimeStamp,float animationTime){return (animationTime - lastTimeStamp) /(nextTimeStamp - lastTimeStamp);}
Now, let’s dive into the implementation details for each transformation channel, beginning with translations.
- The function
interpolatePosition()is straightforward. If there is only one interpolation keyframe, we can simply use it as is. If there are many keyframes, we find two adjacent ones and calculate the interpolation factor between them usinginterpolationVal(). This value is then used to perform linear interpolation between the actual position data contained in the keyframes using theglm::mix()function.vec3 interpolatePosition(const AnimationChannel& channel, float time){if (channel.pos.size() == 1)return channel.pos[0].pos;const uint32_t start = getTimeIndex<>(channel.pos, time);const uint32_t end = start + 1;const float factor = interpolationVal(channel.pos[start].time,channel.pos[end].time, time);return glm::mix(channel.pos[start].pos,channel.pos[end ].pos, factor);} - Let’s take a look at a similar function,
interpolateRotation(). This function operates in a comparable manner to handle rotation keyframes.quat interpolateRotation(const AnimationChannel& channel, float time){if (channel.rot.size() == 1)return channel.rot[0].rot;const uint32_t start = getTimeIndex<>(channel.rot, time);const uint32_t end = start + 1;const float factor = interpolationVal(channel.rot[start].time,channel.rot[end].time, time); - Instead of linear interpolation between values, we use
slerp()to interpolate between the rotation quaternions. This approach ensures that the rotation transitions are smooth and maintain the correct orientation throughout the animation.return glm::slerp(channel.rot[start].rot,channel.rot[end ].rot, factor);}
Note
Slerp is a shorthand for spherical linear interpolation. It is an algorithm that interpolates a new quaternion between two given quaternions. https://en.wikipedia.org/wiki/Slerp.
- Here, we have the scale interpolator. It copies the structure of
interpolatePosition(); but, as expected, it utilizes scale keyframe data to perform the interpolation.vec3 interpolateScaling(const AnimationChannel& channel, float time){if (channel.scale.size() == 1)return channel.scale[0].scale;const uint32_t start = getTimeIndex<>(channel.scale, time);const uint32_t end = start + 1;const float factor = interpolationVal(channel.scale[start].time,channel.scale[end ].time, time);return glm::mix( channel.scale[start].scale,channel.scale[end].scale, factor );}
At this point, we have covered how we calculate the updated transformations. Let’s return to the function updateAnimation() where we still need to address one important step: updating by applying the parent inverse transform. This step is crucial for ensuring that the transformations are correctly applied relative to the parent node’s space.
We discussed the process of hierarchy updates earlier, in the recipe Introduction to skeletal animations. Here, we will apply the bind transformation.
void updateAnimation( GLTFContext& glTF, AnimationState& anim, float dt){ // … the skipped code here was explained in the step 5 traverseTree(glTF.root, mat4(1.0f)); for (const std::pair<std::string, GLTFBone>& b : glTF.bonesByName) { if (b.second.boneId != ~0u) glTF.matrices[b.second.boneId] = glTF.matrices[b.second.boneId] * b.second.transform; } // …}After this step, our matrices are updated and ready to be used for rendering.
How it works…
Section titled “How it works…”All that’s left to do now is modify the renderGLTF() function in shared/UtilsGLTF.cpp to upload the new matrices to the GPU buffer GLTFContext::matricesBuffer. The skinning and morphing code is not necessary here and will be explored in the next recipe, Doing skeletal animations in compute shaders.
void renderGLTF(GLTFContext& gltf, const mat4& model, const mat4& view, const mat4& proj, bool rebuildRenderList){ // … if (gltf.animated) buf.cmdUpdateBuffer(gltf.matricesBuffer, 0, gltf.matrices.size() * sizeof(mat4), gltf.matrices.data()); // …}We have all the necessary code to execute node-based animation. Now, all that’s left is to load a glTF file, data/meshes/medieval_fantasy_book/scene.gltf, that contains a 3D model with node-based animations, and run the animation player. Here’s the complete main() function from the sample app located in Chapter09/01_AnimationPlayer/src/main.cpp, which accomplishes this:
int main() { VulkanApp app( { .initialCameraPos = vec3(7.0f, 6.8f, -13.6f), .initialCameraTarget = vec3(1.7f, -1.0f, 0.0f), .showGLTFInspector = true }); GLTFContext gltf(app); loadGLTF(gltf, "data/meshes/medieval_fantasy_book/scene.gltf", "data/meshes/medieval_fantasy_book/"); gltf.enableMorphing = false; const mat4 t = glm::translate(mat4(1.0f), vec3(0.0f, 2.1f, 0.0f)) * glm::scale(mat4(1.0f), vec3(0.2f)); AnimationState anim = { .animId = 0, .currentTime = 0.0f, .playOnce = false, .active = true }; gltf.inspector = { .activeAnim = { 0 }, .showAnimations = true }; app.run([&](uint32_t width, uint32_t height, float aspectRatio, float deltaSeconds) { const mat4 m = t * glm::rotate( mat4(1.0f), glm::radians(180.0f), vec3(0, 1, 0)); const mat4 v = app.camera_.getViewMatrix(); const mat4 p = glm::perspective(45.f, aspectRatio, 0.01f, 100.f); animateGLTF(gltf, anim, deltaSeconds); renderGLTF(gltf, m, v, p); if (gltf.inspector.activeAnim[0] != anim.animId) anim = { .animId = gltf.inspector.activeAnim[0], .currentTime = 0.0f, .playOnce = false, .active = true }; }); return 0;}The running application should render an animated scene as in the following screenshot:

Figure 9.1: Node-based animations
In fact, we’ve already implemented much of the necessary C++ code to support not only node-based animations but also skeletal animations. However, we still need to implement skinning to calculate the mesh vertices based on an animated skeleton. Let’s move on to the next recipe and learn how to achieve this using compute shaders.
There’s more…
Section titled “There’s more…”The 3D model used in this recipe is based on “Medieval Fantasy Book” (https://sketchfab.com/3d-models/medieval-fantasy-book-06d5a80a04fc4c5ab552759e9a97d91a) by Pixel (https://sketchfab.com/stefan.lengyel1) licensed under CC-BY-4.0 (http://creativecommons.org/licenses/by/4.0/).
In addition to node-based animations, this 3D model includes morph targets for animating the flags. However, at the time of writing this chapter, Assimp lacks full support for loading morph targets from glTF files, making it impossible to animate the flags here.
Doing skeletal animations in compute shaders
Section titled “Doing skeletal animations in compute shaders”Skeletal animations imply moving vertices based on the weighted influence of multiple matrices, which represent a skeleton of bones. Each bone is represented as a matrix that influences nearby vertices based on its weight. For instance, the hand bone would heavily influence hand vertices, while it would have no effect on foot vertices. Vertices near the wrist might be affected by both the hand and arm bones. In essence, skinning requires bones, a hierarchy of matrices, and weights.
Weights, like vertex colors, are assigned per vertex and range from 0 to 1, indicating how much a specific bone influences that vertex’s position. These weights are stored in a buffer and passed as vertex attributes. In this recipe, we cover the final part of the animation player with skinning support.
In the recipe Importing skeleton and animation data, we learned how to load bone weights and hierarchy. Now, let’s look at how to use this data to skin a glTF mesh. We will do this with a compute shader that updates the vertex positions in our vertex buffer.
An older approach to applying skinning data to each vertex of a mesh is to use a vertex shader. This was once common practice, and the official Khronos glTF viewer still uses it. However, vertex shaders can be less efficient when vertices are reused multiple times with different indices, leading to redundant complex calculations. To improve efficiency, we can perform these calculations in a compute shader, avoiding the need to process each vertex instance individually. This reduces redundancy but adds complexity and requires an extra compute pass, which can create extra dependencies in the rendering pipeline. We chose this approach because traditional vertex shader implementations are more commonly seen, while compute shader-based solutions are less typical.
Getting ready
Section titled “Getting ready”Be sure to review the recipe Importing skeleton and animation data before moving forward.
The demo source code for this recipe is located in Chapter09/02_Skinning, and the compute shader is located in data/shaders/gltf/animation.comp.
How to do it…
Section titled “How to do it…”Before diving into our GLSL skinning and morphing compute shader code, let’s start with the C++ side and see how the data is passed into the shader. These changes are applied to shared/UtilsGLTF.h and shared/UtilsGLTF.cpp.
- Let’s add a compute pipeline state and an animation shader module to the
GLTFContextclass.struct GLTFContext {// …Holder<ComputePipelineHandle> pipelineComputeAnimations;// …Holder<ShaderModuleHandle> animation;// …}; - In the
loadGLTF()function, we load the compute shader:// …gltf.animation = loadShaderModule(ctx,"data/shaders/gltf/animation.comp");// … - The compute pipeline that uses this shader is created lazily in the
animateGLTF()function, only when animation is needed.void animateGLTF(GLTFContext& gltf, AnimationState& anim, float dt){if (gltf.transforms.empty()) return;if (gltf.pipelineComputeAnimations.empty())gltf.pipelineComputeAnimations =gltf.app.ctx_->createComputePipeline({.smComp = gltf.animation });anim.active = anim.animId != ~0;gltf.animated = anim.active;if (anim.active) updateAnimation(gltf, anim, dt);}
Now, let’s examine additions to the renderGLTF() function, which handles all the rendering. We need to add a new code snippet to update animation-related data and invoke the compute shader.
- First, we need to update the matrices buffer. We calculated these earlier in the previous recipe, Implementing the glTF animation player. The morphing data is also updated here. We will cover the missing morphing parts in the upcoming recipes, including Introduction to morph targets.
void renderGLTF(GLTFContext& gltf,const mat4& model, const mat4& view, const mat4& proj,bool rebuildRenderList){// …if (gltf.animated) {buf.cmdUpdateBuffer(gltf.matricesBuffer, 0,gltf.matrices.size() * sizeof(mat4), gltf.matrices.data());if (gltf.morphing){buf.cmdUpdateBuffer(gltf.morphStatesBuffer, 0,gltf.morphStates.size() * sizeof(MorphState),gltf.morphStates.data());}updateLights(gltf, buf);
- The compute shader should only be run if skinning is enabled with valid bones, or if mesh morphing is enabled. We use Vulkan push constants to pass all inputs to the compute shader, including the scene node matrices and input vertices. We prepared all these buffers in the recipes Importing skeleton and animation data and Implementing the glTF animation player. The output buffer is assigned to
gltf.vertexBuffer, which is then used as vertex input for our main rendering pass.if ((gltf.skinning && gltf.hasBones) ||gltf.morphing){struct ComputeSetup {uint64_t matrices;uint64_t morphStates;uint64_t morphVertexBuffer;uint64_t inBuffer;uint64_t outBuffer;uint32_t numMorphStates;} pc = {.matrices = ctx->gpuAddress(gltf.matricesBuffer),.morphStates = ctx->gpuAddress(gltf.morphStatesBuffer),.morphVertexBuffer = ctx->gpuAddress(gltf.vertexMorphingBuffer),.inBuffer = ctx->gpuAddress(gltf.vertexSkinningBuffer),.outBuffer = ctx->gpuAddress(gltf.vertexBuffer),.numMorphStates = gltf.morphStates.size(),};buf.cmdBindComputePipeline(gltf.pipelineComputeAnimations);buf.cmdPushConstants(pc); - Note that we specify all mutable buffers as dependencies in the dispatch command. This ensures that LightweightVK places all necessary Vulkan buffer memory barriers before and after buffers are used, based on their usage flags and previous use. We need to use barriers in this case to ensure the buffer for the previous frame is fully processed before we start preparing the next one. The size of our vertex buffer is always padded to
16vertices, so we don’t have to worry about alignment. Note Padding with dummy vertices is done inloadGLTF()right before we allocate the vertex buffer:gltf.maxVertices = (1 + (vertices.size() / 16)) * 16;vertices.resize(gltf.maxVertices);gltf.vertexBuffer = ctx->createBuffer({.usage = lvk::BufferUsageBits_Vertex |lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = sizeof(Vertex) * vertices.size(),.data = vertices.data(),.debugName = "Buffer: vertex" });
buf.cmdDispatchThreadGroups( { .width = gltf.maxVertices / 16, }, { .buffers = { BufferHandle(gltf.vertexBuffer), BufferHandle(gltf.morphStatesBuffer), BufferHandle(gltf.matricesBuffer), BufferHandle(gltf.vertexSkinningBuffer)} }); }}The output buffer gltf.vertexBuffer is never read back to the CPU; it is used solely as vertex input for subsequent rendering passes. This means we have completed the C++ code. Now, let’s take a look at the compute shader and see how everything works.
How it works…
Section titled “How it works…”The compute shader is located in data/shaders/gltf/animation.comp.
- It begins by declaring the necessary GLSL extensions because we want to avoid injecting any automatic LightweightVK preamble here. The
GL_EXT_buffer_referenceextension is used to handle buffer device addresses passed via push constants. The extensionGL_EXT_scalar_block_layoutis required to simplify access to tightly packed vertex data, which is stored as a combination of differentvec3and scalar values.#version 460#extension GL_EXT_buffer_reference : require#extension GL_EXT_scalar_block_layout : requirelayout (local_size_x=16, local_size_y=1, local_size_z=1) in; - The shader uses several structures that resemble the data in various buffers. Some of these structures correspond to their C++ counterparts described earlier in this chapter in the recipe Importing skeleton and animation data, while others should be familiar from previous chapters. We list them all here for your reference.
struct TransformsBuffer {uint mtxId;uint matId;uint nodeRef; // for CPU onlyuint meshRef; // for CPU onlyuint opaque; // for CPU only};struct VertexSkinningData {vec4 pos;vec4 norm;uint bones[8];float weights[8];uint meshId;};struct VertexData {vec3 pos;vec3 norm;vec4 color;vec4 uv;float padding[2];};#define MAX_WEIGHTS 8struct MorphState {uint meshId;uint morphTarget[MAX_WEIGHTS];float weights[MAX_WEIGHTS];};
- Now, let’s declare buffer references using these structures. This is where the
scalarGLSL block layout comes into play, ensuring thatvec3andfloatvalues are not padded to larger data sizes. This significantly simplifies our data storage scheme and interactions between the C++ and GLSL code. Each buffer here contains an unbounded array of the corresponding items.layout (std430, buffer_reference) readonly buffer Matrices {mat4 matrix[];};layout (scalar, buffer_reference) readonly buffer MorphStates {MorphState morphStates[];};layout (scalar, buffer_reference) readonly buffer VertexSkinningBuffer {VertexSkinningData vertices[];};layout (scalar, buffer_reference) writeonly buffer VertexBuffer {VertexData vertices[];};layout (scalar, buffer_reference) readonly buffer MorphVertexBuffer {VertexData vertices[];}; - The final piece of our input data is the push constants declaration, which combines all the buffers mentioned above. The
numMorphStatesparameter holds the number of morph targets.layout (push_constant) uniform PerFrameData {Matrices matrices;MorphStates morphStates;MorphVertexBuffer morphTargets;VertexSkinningBuffer inBufferId;VertexBuffer outBufferId;uint numMorphStates;} pc; - This is where the
main()function begins, starting by retrieving the bind pose vertices and normal vectors. The bind pose just holds the initial data loaded from the glTF file.void main() {uint index = gl_GlobalInvocationID.x;VertexSkinningData inVtx = pc.inBufferId.vertices[index];vec4 inPos = vec4(inVtx.pos.xyz, 1.0);vec4 inNorm = vec4(inVtx.norm.xyz, 0.0); - If vertex morphing is enabled for this
meshId, we handle it here. We will explore this further in the upcoming recipes, Introduction to morph targets and Adding morph targets support. We can skip it for now.if (inVtx.meshId < pc.numMorphStates) {MorphState ms = pc.morphStates.morphStates[inVtx.meshId];if (ms.meshId != ~0)for (int m = 0; m != MAX_WEIGHTS; m++)if (ms.weights[m] > 0) {VertexData mVtx = pc.morphTargets.vertices[ms.morphTarget[m] + index];inPos.xyz += mVtx.pos * ms.weights[m];inNorm.xyz += mVtx.norm * ms.weights[m];}} - The skinning process itself is straightforward. We iterate through all the bones associated with the vertex and accumulate the weighted sum of their transformed positions, which are obtained by applying the
boneMattransformation matrix.vec4 pos = vec4(0);vec4 norm = vec4(0);int i = 0;for (; i != MAX_WEIGHTS; i++) {if (inVtx.bones[i] == ~0) break;mat4 boneMat = pc.matrices.matrix[inVtx.bones[i]];pos += boneMat * inPos * inVtx.weights[i]; - Normal vectors are treated differently. We transform them using the inverse transpose of the bone matrices. This approach ensures that the normals retain their original unit length and direction, even under non-uniform scaling that can occur with bone transformations.
Note
For readers seeking a deeper understanding of normal transformation, you can refer to this resource: https://terathon.com/blog/transforming-normals.html.
norm += transpose(inverse(boneMat)) * inNorm * inVtx.weights[i];}- If there were no valid weights for this vertex, we fall back to the bind pose vertex position and normal vector. The calculated position and normal are then written to the output buffer.
if (i == 0) {pos.xyz = inPos.xyz;norm.xyz = inNorm.xyz;}pc.outBufferId.vertices[index].pos = pos.xyz;pc.outBufferId.vertices[index].norm = normalize(norm.xyz);}
Now we can run the demo application, Chapter09/02_Skinning, and observe the results of the vertex skinning process. We use the Khronos model located at deps/src/glTF-Sample-Assets/Models/Fox/glTF/Fox.gltf, which should be rendered walking, as shown in the following screenshot.

Figure 9.2: Skeletal animation with vertex skinning
Try switching between different animations: Survey, Walk, and Run. When you click to switch animations, you will notice that the transition occurs quite abruptly and in an unnatural way. This can be improved by interpolating between multiple animations using a floating-point transition factor. We will learn how to achieve this in the recipe Animation blending.
For now, let’s wrap up our animation player and learn how to implement morph targets in the upcoming recipes.
Introduction to morph targets
Section titled “Introduction to morph targets”A morph target is a deformed version of a mesh. In glTF, morph targets are used to create mesh deformations by blending different sets of vertex positions, or other attributes, like normal vectors, according to specified weights. They are especially useful for facial animations, character expressions, and other types of mesh deformation in 3D models.
- Base Mesh: This is the original, unaltered mesh defined by its vertices, normals, texture coordinates, and other attributes.
- Morph Targets: These are modified versions of the base mesh, where the positions of some or all vertices have been adjusted to create a specific deformation. Multiple morph targets can be defined for the same mesh, each representing a different shape variation.
- Vertex Data: Morph targets include offset data for vertices. A morph target usually adjusts the vertex positions (and sometimes other attributes like normals) of the base mesh. These offsets specify how much each vertex should move when the morph target is applied.
- Weights: Each morph target has an associated weight that controls its influence on the mesh. The weight is a floating-point value between
0and1, where0means no influence (the mesh appears identical to the base mesh);1means full influence (the mesh fully deforms to match the morph target); and values between0and1blend the base mesh with the morph target.
When multiple morph targets are used, the mesh’s final shape is calculated as a weighted sum of the morph targets. For each vertex, its final position is determined by blending the corresponding vertex positions from the base mesh and the morph targets, according to their weights.
The formula for calculating a vertex’s final position with applied morph targets is:
Where:
basePositionis the original position of the vertex in the base mesh.- w 1, w 2, …, w N are the weights for each morph target.
- offset 1, offset 2, …, offset N are the vertex offsets from the morph targets.
Now, let’s look at how to load glTF morph targets data using the Assimp library.
Loading glTF morph targets data
Section titled “Loading glTF morph targets data”Similar to the recipe Importing skeleton and animation data, this one doesn’t include a standalone example either. Instead, it focuses on the modifications needed in our glTF loading code to load morph target data from glTF files using the Assimp library.
Getting ready
Section titled “Getting ready”Refer to the recipe Importing skeleton and animation data for a quick refresher on the data structures needed to support animations. You can also review the recipe Doing skeletal animations in compute shaders and the shader code in data/shaders/gltf/animation.comp to revisit our animation compute shader.
How to do it…
Section titled “How to do it…”To load morph targets from glTF files, we will need to add some new data structures and update the loading code. Let’s go through how to do this.
- We begin, as usual, with the data structures.
MorphTargetrepresents a reference for all morph targets attached to a specific mesh. All morph targets are stored in a single buffer, needing only ameshIdand anoffsetin this buffer. The actual delta positions use the same base vertex format as the rest of our glTF code, so no new changes are necessary. The structure is declared inshared/UtilsGLTF.h.struct MorphTarget {uint32_t meshId = ~0u;std::vector<uint32_t> offset;}; - The
MorphStatestructure inshared/UtilsAnim.hholds the morphing state for a given mesh. The values ofmorphTarget[]andweights[]are updated at each animation frame in themorphTransform()function, which we will cover in the next recipe, Adding morph targets support.struct MorphState {uint32_t meshId = ~0u;uint32_t morphTarget[MAX_MORPH_WEIGHTS] = {};float weights[MAX_MORPH_WEIGHTS] = {};}; - Let’s add a few new member fields to the
GLTFContextclass. ThemorphTargetsvector indexed bymeshIdprovides the mapping information between meshes and thevertexMorphingBuffer. ThevertexMorphingBufferholds the vertex data for the morph targets.struct GLTFContext {// …std::vector<MorphTarget> morphTargets;// …Holder<BufferHandle> morphStatesBuffer;// …Holder<BufferHandle> vertexMorphingBuffer;// …std::vector<MorphState> morphStates;// …bool morphing = false;// …};
With all the data structures and declarations set up, let’s examine the loading code in loadGLTF() located in shared/UtilsGLTF.cpp.
- First, let’s load the morph target data for each mesh from the Assimp
aiSceneobject and store it inGLTFContext::morphTargets.void loadGLTF(GLTFContext& gltf,const char* glTFName, const char* glTFDataPath){const aiScene* scene = aiImportFile(glTFName, aiProcess_Triangulate);// …for (uint32_t meshId = 0;meshId != scene->mNumMeshes; meshId++) {const aiMesh* m = scene->mMeshes[meshId];if (!m->mNumAnimMeshes) continue;MorphTarget& morphTarget = gltf.morphTargets[meshId];morphTarget.meshId = meshId; - Next, we populate the vertex data for each morph target associated with the mesh. An
aiAnimMesh, which corresponds to a glTF morph target, is an attachment to anaiMeshand stores per-vertex animations for a specific frame.for (uint32_t a = 0; a<m->mNumAnimMeshes; a++) {const aiAnimMesh* mesh = m->mAnimMeshes[a];for (uint32_t i = 0; i < mesh->mNumVertices; i++) {const aiVector3D srcNorm = m->mNormals ?m->mNormals[i] : aiVector3D(0, 1, 0);const aiVector3D v = mesh->mVertices[i];const aiVector3D n = mesh->mNormals ?mesh->mNormals[i] : aiVector3D(0, 1, 0);const aiColor4D c = mesh->mColors[0] ?mesh->mColors[0][i] : aiColor4D(1);const aiVector3D uv0 = mesh->mTextureCoords[0] ?mesh->mTextureCoords[0][i] : aiVector3D(0);const aiVector3D uv1 = mesh->mTextureCoords[1] ?mesh->mTextureCoords[1][i] : aiVector3D(0); - We subtract the original vertex data from the
aiAnimMeshdata for two reasons. First, the glTF specification defines morph targets as deltas between original mesh attributes, whereas the Assimp library converts them into complete mesh data. Second, this simplification makes the shader computations a bit more efficient.morphData.push_back({.position = vec3(v.x - m->mVertices[i].x,v.y - m->mVertices[i].y,v.z - m->mVertices[i].z),.normal = vec3(n.x - srcNorm.x,n.y - srcNorm.y,n.z - srcNorm.z),.color = vec4(c.r, c.g, c.b, c.a),.uv0 = vec2(uv0.x, 1.0f - uv0.y),.uv1 = vec2(uv1.x, 1.0f - uv1.y),});}morphTarget.offset.push_back(morphTargetsOffset);morphTargetsOffset += mesh->mNumVertices;}}// …} - After extracting the data from Assimp, we can store the morph target vertices in a GPU buffer. It’s important to note that we always include a dummy value in this buffer for one vertex, even if there’s no morphing data in the mesh. This simplifies the shader code by eliminating the need for unnecessary range checking.
const bool hasMorphData = !morphData.empty();gltf.vertexMorphingBuffer = ctx->createBuffer({.usage = lvk::BufferUsageBits_Vertex |lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = hasMorphData ?sizeof(Vertex) * morphData.size() : sizeof(Vertex),.data = hasMorphData ? morphData.data() : nullptr,.debugName = "Buffer: morphing vertex data",});
While the morphData values are intended for the GPU to morph individual mesh vertices, the morphTargets values are used by the CPU to update animation states.
This concludes our code for loading morph targets data. Now, let’s explore how to use it for animations.
Adding morph targets support
Section titled “Adding morph targets support”In the previous recipe, we loaded the morph target data from glTF. Now, let’s use that data to create a demo application and render morphing meshes.
Getting ready
Section titled “Getting ready”Be sure to read the previous recipe, Loading glTF morph targets data, to review all the necessary data structures for morph targets.
The source code for this recipe is located in Chapter09/03_Morphing.
How to do it…
Section titled “How to do it…”To display the results rendered on the screen, we need to enable support for mesh morph targets in our glTF animation player and incorporate this functionality into our compute shader.
- Let’s begin with the rendering code in the
renderGLTF()function. Here’s the complete setup for our compute pass, which was mentioned earlier in the recipe Doing skeletal animations in compute shaders.if (gltf.animated) {buf.cmdUpdateBuffer(gltf.matricesBuffer, 0,gltf.matrices.size() * sizeof(mat4),gltf.matrices.data()); - The current value of
GLTFContext::morphStates, which we will learn how to calculate shortly, is uploaded to the GPU bufferGLTFContext::morphStatesBufferfor processing by our compute shader.if (gltf.morphing)buf.cmdUpdateBuffer(gltf.morphStatesBuffer, 0,gltf.morphStates.size() * sizeof(MorphState),gltf.morphStates.data());updateLights(gltf, buf);if ((gltf.skinning && gltf.hasBones) || gltf.morphing){struct ComputeSetup {uint64_t matrices;uint64_t morphStates;uint64_t morphVertexBuffer;uint64_t inBuffer;uint64_t outBuffer;uint32_t numMorphStates;} pc = {.matrices = ctx->gpuAddress(gltf.matricesBuffer),.morphStates = ctx->gpuAddress(gltf.morphStatesBuffer), - The
morphVertexBuffer, which contains all the base mesh morphing data described in the previous recipe, Loading glTF morph targets data, is passed to the compute shader..morphVertexBuffer = ctx->gpuAddress(gltf.vertexMorphingBuffer),.inBuffer = ctx->gpuAddress(gltf.vertexSkinningBuffer),.outBuffer = ctx->gpuAddress(gltf.vertexBuffer),.numMorphStates = static_cast<uint32_t>(gltf.morphStates.size()),};buf.cmdBindComputePipeline(gltf.pipelineComputeAnimations);buf.cmdPushConstants(pc);buf.cmdDispatchThreadGroups({ .width = gltf.maxVertices / 16, },{ .buffers = {BufferHandle(gltf.vertexBuffer),BufferHandle(gltf.morphStatesBuffer),BufferHandle(gltf.matricesBuffer),BufferHandle(gltf.vertexSkinningBuffer)}});}}
As you can see, the entire morphing code path is seamlessly integrated with the skinning code path described in the recipe Doing skeletal animations in compute shaders.
Let’s examine how the current morphing data, which goes into the morphStatesBuffer, is calculated based on the animation states.
- First, let’s declare the necessary data structures to hold interpolation values for our morphing animations in
shared/UtilsAnim.h. We support up to8meshes,8weights for vertex attributes, and100morph targets.#define MAX_MORPH_WEIGHTS 8#define MAX_MORPHS 100struct MorphingChannelKey {float time = 0.0f; // in secondsuint32_t mesh[MAX_MORPH_WEIGHTS] = {};float weight[MAX_MORPH_WEIGHTS] = {};};struct MorphingChannel {std::string name;std::vector<MorphingChannelKey> key;}; - We need to add a new member field,
morphChannels, to ourAnimationstructure. Each animation can include morphing channels, consisting of a vector of pairs that represent mesh and weight data, along with a key time.struct Animation {unordered_map<int, AnimationChannel> channels;std::vector<MorphingChannel> morphChannels;float duration;float ticksPerSecond;std::string name;}; - The
initAnimations()function inshared/UtilsAnim.cppneeds to initialize morphing channels data. Here’s the new code snippet that was added to it:void initAnimations(GLTFContext& glTF, const aiScene* scene) {glTF.animations.resize(scene->mNumAnimations);for (uint32_t i = 0; i < scene->mNumAnimations; ++i){// …const uint32_t numMorphTargetChannels =scene->mAnimations[i]->mNumMorphMeshChannels;anim.morphChannels.resize(numMorphTargetChannels); - Morph target channels are extracted from the
aiSceneobject in the same way as we handled node-based animations in the recipe Importing skeleton and animation data.for (int c = 0; c<numMorphTargetChannels; c++) {const aiMeshMorphAnim* channel =scene->mAnimations[i]->mMorphMeshChannels[c];MorphingChannel& morphChannel = anim.morphChannels[c]; - Assimp uses string names to bind channels to meshes, which doesn’t fully align with the glTF specification.
morphChannel.name = channel->mName.C_Str();morphChannel.key.resize(channel->mNumKeys);for (uint32_t k = 0; k < channel->mNumKeys; ++k){MorphingChannelKey& key = morphChannel.key[k];key.time = channel->mKeys[k].mTime;for (uint32_t v = 0;v < std::min(MAX_MORPH_WEIGHTS,channel->mKeys[k].mNumValuesAndWeights); v++){key.mesh[v] = channel->mKeys[k].mValues[v];key.weight[v] = channel->mKeys[k].mWeights[v];}}}}}
- To play morphing animations, we need a structure,
MorphStates, to maintain the state. This structure is used to run the player and upload data to the GPU. As mentioned above, we support a maximum of100states.struct MorphState {uint32_t meshId = ~0u;uint32_t morphTarget[MAX_MORPH_WEIGHTS] = {};float weights[MAX_MORPH_WEIGHTS] = {};}; - Let’s add code to the
updateAnimation()function inshared/UtilsAnim.cppto process morphing animations. This is much simpler than skinning, as we don’t need to update the actual scene hierarchy. All we need to do here is calculate newMorphStatedata:void updateAnimation(GLTFContext& glTF, AnimationState& anim, float dt){// …glTF.morphStates.resize(glTF.meshesStorage.size());if (glTF.enableMorphing) {if (!activeAnim.morphChannels.empty()) {for (size_t i = 0; i < activeAnim.morphChannels.size(); ++i) {const MorphingChannel& channel = activeAnim.morphChannels[i];const uint32_t meshId = glTF.meshesRemap[channel.name];const MorphTarget& morphTarget = glTF.morphTargets[meshId];if (morphTarget.meshId != ~0u)glTF.morphStates[morphTarget.meshId] =morphTransform(morphTarget, channel, anim.currentTime);}glTF.morphing = true;}}} - As usual, all the details are hidden in a helper function called
morphTransform():MorphState morphTransform(const MorphTarget& target,const MorphingChannel& channel,float time){MorphState ms;ms.meshId = target.meshId;float mix = 0.0f;int start = 0;int end = 0; - Here, we use the same helper function,
interpolationVal(), to find the blending coefficient, just as we did for skeletal animations in the recipe Implementing the glTF animation player.if (channel.key.size() > 0) {start = getTimeIndex(channel.key, time);end = start + 1;mix = interpolationVal(channel.key[start].time,channel.key[end].time, time);} - This function is quite similar to the other interpolation functions we described earlier, but instead of mixing transformations, we mix blend weights. Additionally, we copy the
offsetto the actual buffer along with the weights, which we use later in our shader to retrieve the actual morph target vertices.for (uint32_t i = 0;i < std::min((uint32_t)target.offset.size(),(uint32_t)MAX_MORPH_WEIGHTS); ++i){ms.morphTarget[i] = target.offset[channel.key[start].mesh[i]];ms.weights[i] =glm::mix(channel.key[start].weight[i],channel.key[end ].weight[i], mix);}return ms;}
That’s everything for the C++ portion. Now, let’s take a quick look at the modifications needed for our GLSL compute shader located in data/shaders/gltf/animation.comp.
- First, we assign the
inPosandinNormvalues to the corresponding base mesh values, regardless of whether morphing is enabled.void main() {uint index = gl_GlobalInvocationID.x;VertexSkinningData inVtx = pc.inBufferId.vertices[index];vec4 inPos = vec4(inVtx.pos.xyz, 1.0);vec4 inNorm = vec4(inVtx.norm.xyz, 0.0); - Then, we perform vertex morphing using the
MorphStatefor this mesh that we calculated earlier in C++. We check if each vertex matches a morph target’smeshIdand is valid. If it does, we calculate the weighted sum of the positions and normals using the active morph target offset and weight.if (inVtx.meshId < pc.numMorphStates) {MorphState ms =pc.morphStates.morphStates[inVtx.meshId];if (ms.meshId != ~0) {for (int m = 0; m != MAX_WEIGHTS; m++) {if (ms.weights[m] > 0) {VertexData mVtx = pc.morphTargets.vertices[ms.morphTarget[m] + index];inPos.xyz += mVtx.pos * ms.weights[m];inNorm.xyz += mVtx.norm * ms.weights[m];}}}}// …}
The shader then continues with vertex skinning, as described in the recipe Doing skeletal animations in compute shaders, using the morphed values of inPos and inNorm.
How it works…
Section titled “How it works…”Now, let’s take a quick look at the demo application Chapter09/03_Morphing/src/main.cpp, specifically focusing on its main() function.
- We use one of the sample Khronos 3D models,
AnimatedMorphCube.gltf, which is a simple example to demonstrate the morphing capabilities we’ve implemented.int main() {VulkanApp app({ .initialCameraPos = vec3(2.13f, 2.44f, -3.5f),.initialCameraTarget = vec3(0, 0, 2),.showGLTFInspector = true });GLTFContext gltf(app);loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/AnimatedMorphCube/glTF/AnimatedMorphCube.gltf","deps/src/glTF-Sample-Assets/Models/AnimatedMorphCube/glTF/");const mat4 t = glm::translate(mat4(1.0f), vec3(0.0f, 1.1f, 0.0f)); - Let’s play the very first morphing animation from the
.gltffile.AnimationState anim = { .animId = 0,.currentTime = 0.0f,.playOnce = false,.active = true };gltf.inspector = { .activeAnim = { 0 },.showAnimations = true };app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds){const mat4 m = t * glm::rotate(mat4(1.0f),glm::radians(180.0f), vec3(0, 1, 0));const mat4 v = app.camera_.getViewMatrix();const mat4 p = glm::perspective(45, aspectRatio, 0.01, 100);animateGLTF(gltf, anim, deltaSeconds);renderGLTF(gltf, m, v, p); - We reassign the current animation to our
GLTFIntrospectiveintrospector, allowing it to be controlled through the ImGui UI.if (gltf.inspector.activeAnim[0] != anim.animId) {anim = { .animId = gltf.inspector.activeAnim[0],.currentTime = 0.0f,.playOnce = false,.active = true };}});return 0;}
When we run this demo application, you should see an animated deforming cube, similar to the one shown in the following screenshot.

Figure 9.3: Morph targets animation
With this, we conclude our glTF morphing implementation. As you can see from all the code above, there are no differences in the API calls between skinning and morphing animations. In fact, skinning and morphing animations often complement each other, allowing for more dynamic and expressive character movements.
There’s more…
Section titled “There’s more…”It’s important to note that at the time this book was written, Assimp used string names to bind animation channels to meshes, which does not fully align with the glTF specification. Additionally, it lacks comprehensive support for loading morph targets from glTF files, making it impossible to animate them here using the Assimp library. This limitation affected how we handled morphing animations in our implementation.
For a deeper understanding of animation concepts, we recommend the book Computer Animation: Algorithms and Techniques by Rick Parent. This comprehensive guide covers the principles and methodologies of this dynamic field.
Animation blending
Section titled “Animation blending”In the recipes Implementing the glTF animation player and Doing skeletal animations in compute shaders, we implemented an animation player with the capability to switch between skeletal animations. However, when switching between animations, you may have noticed that the transition happens rather abruptly and unnaturally.
We can improve this by interpolating between animations using a floating-point transition factor. In this recipe, we’ll demonstrate a more advanced approach that enables smooth blending between two animations. This technique requires not only the interpolation of per-channel transformations but also a gradual blending between different animations, softening transitions and making them look more natural. Let’s dive in and learn how to implement it!
Getting ready
Section titled “Getting ready”Make sure to revisit the recipes Implementing the glTF animation player and Doing skeletal animations in compute shaders before proceeding further.
The source code for this recipe is located in Chapter09/04_AnimationBlending.
How to do it…
Section titled “How to do it…”The basic idea of this approach is straightforward: we have 2 different animations and a floating-point blending factor, 0…1, between them to calculate the resulting animation. If we can successfully blend 2 animations, this technique can be trivially extended to blend any number of animations.
This recipe consists of two main parts: the additional code in the animation player and the demo application code in Chapter09/04_AnimationBlending/src/main.cpp. This time, let’s start with the main() function.
- Here, we include the entire
main()function, as it is quite small. We enable theshowGLTFInspectorconfiguration flag forVulkanAppto add a simple UI that allows control over the running animations and the blend factor between them. We are using theFox.gltfmodel from Khronos, which includes multiple skeletal animations that we can blend together.int main() {VulkanApp app({ .initialCameraPos = vec3(2.13f, 2.44f, -3.5f),.initialCameraTarget = vec3(0, 0, 2),.showGLTFInspector = true });GLTFContext gltf(app);loadGLTF(gltf, "deps/src/glTF-Sample-Assets/Models/Fox/glTF/Fox.gltf","deps/src/glTF-Sample-Assets/Models/Fox/glTF/"); - Translate (
t) and scale (s) the model appropriately for convenience. Then, create twoAnimationStateobjects for the two animations we want to play.const mat4 t = glm::translate(mat4(1.0f), vec3(0.0f, 1.1f, 0.0f));const mat4 s = glm::scale(mat4(1.0f), vec3(0.01f, 0.01f, 0.01f));AnimationState anim1 = { .animId = 1,.currentTime = 0.0f,.playOnce = false,.active = true };AnimationState anim2 = { .animId = 2,.currentTime = 0.0f,.playOnce = false,.active = true }; - Enable skinning in our glTF player and register both animations in our GLTF inspector, allowing us to switch between them later using the ImGui UI and to manually adjust the blending factor.
gltf.skinning = true;gltf.inspector = { .activeAnim = {1, 2},.blend = 0.5f,.showAnimations = true,.showAnimationBlend = true };app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds){const mat4 m = t * glm::rotate(mat4(1.0f),glm::radians(90.0f), vec3(0, 1, 0)) * s;const mat4 v = app.camera_.getViewMatrix();const mat4 p = glm::perspective(45, aspectRatio, 0.01, 100);
- Call the helper function
animateBlendingGLTF(), which performs the animation blending and updates bothAnimationStateobjects,anim1andanim2. Use the blending factor set in the inspector UI. Then render our animated glTF mesh normally.animateBlendingGLTF(gltf, anim1, anim2,gltf.inspector.blend, deltaSeconds);renderGLTF(gltf, m, v, p); - If we switch animations in the inspector, assign the new animations to both
AnimationStateobjects.if (gltf.inspector.activeAnim[0]!=anim1.animId||gltf.inspector.activeAnim[1]!=anim2.animId) {anim1 = { .animId = gltf.inspector.activeAnim[0],.currentTime = 0.0f,.playOnce = false,.active = gltf.inspector.activeAnim[0] != ~0u };anim2 = { .animId = gltf.inspector.activeAnim[1],.currentTime = 0.0f,.playOnce = false,.active = gltf.inspector.activeAnim[1] != ~0u };}});return 0;}
That’s all for the demo application C++ code. As you will see, the real magic happens behind the animateBlendingGLTF() helper function in shared/UtilsGLTF.cpp. Let’s take a closer look at how it works.
How it works…
Section titled “How it works…”The function animateBlendingGLTF() is very similar to animateGLTF(), which we introduced earlier, in the recipe Doing skeletal animations in compute shaders.
- We use the same lazy-loaded compute shader and check the states of both provided animations.
void animateBlendingGLTF(GLTFContext& gltf,AnimationState& anim1,AnimationState& anim2,float weight, float dt){if (gltf.transforms.empty()) return;if (gltf.pipelineComputeAnimations.empty())gltf.pipelineComputeAnimations =gltf.app.ctx_->createComputePipeline({.smComp = gltf.animation });anim1.active = anim1.animId != ~0;anim2.active = anim2.animId != ~0;gltf.animated = anim1.active || anim2.active;
- We only do animation blending when both animations are assigned and active. If that’s not the case, we update only one of the remaining animations or none at all.
if (anim1.active && anim2.active) {updateAnimationBlending(gltf, anim1, anim2, weight, dt);} else if (anim1.active) {updateAnimation(gltf, anim1, dt);} else if (anim2.active) {updateAnimation(gltf, anim2, dt);}}
- The function
updateAnimationBlending()is the blending counterpart to theupdateAnimation()function, which we introduced earlier, in the recipe Implementing the glTF animation player. Both functions are located inshared/UtilsAnim.cpp. Based on the combination of active animations, we advance the animation time for both of them or just one, depending on the situation. Remember, we never enter this function if no animations are playing.void updateAnimationBlending(GLTFContext& glTF,AnimationState& anim1,AnimationState& anim2,float weight, float dt){if (anim1.active && anim2.active) {const Animation& activeAnim1 = glTF.animations[anim1.animId];anim1.currentTime += activeAnim1.ticksPerSecond * dt;if (anim1.playOnce && anim1.currentTime > activeAnim1.duration) {anim1.currentTime = activeAnim1.duration;anim1.active = false;} else {anim1.currentTime = fmodf(anim1.currentTime, activeAnim1.duration);}const Animation& activeAnim2 = glTF.animations[anim2.animId];anim2.currentTime += activeAnim2.ticksPerSecond * dt;if (anim2.playOnce && anim2.currentTime > activeAnim2.duration) {anim2.currentTime = activeAnim2.duration;anim2.active = false;} else {anim2.currentTime = fmodf(anim2.currentTime, activeAnim2.duration);} - Next, we update the skinning animation states in a way similar to how we did it in the recipe Implementing the glTF animation player.
std::function<void(GLTFNodeRef gltfNode,const mat4& parentTransform)> traverseTree =[&](GLTFNodeRef gltfNode,const mat4& parentTransform){const GLTFBone& bone = glTF.bonesByName[glTF.nodesStorage[gltfNode].name];const uint32_t boneId = bone.boneId;if (boneId != ~0u) {
- The main difference here is that we retrieve animation channels for both animations and blend them using the function
animationTransformBlending(), based on the providedweightand separate animation times for each animation. When one of the animations stops playing, we switch to using the helper functionanimationTransform(), described in the recipe Implementing the glTF animation player, which calculates the transformation for just one animation channel.auto channel1 = activeAnim1.channels.find(boneId);auto channel2 = activeAnim2.channels.find(boneId);if (channel1 != activeAnim1.channels.end() &&channel2 != activeAnim2.channels.end()){glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId] = parentTransform *animationTransformBlending(channel1->second, anim1.currentTime,channel2->second, anim2.currentTime, weight);} else if (channel1 != activeAnim1.channels.end()) {glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId] = parentTransform *animationTransform(channel1->second, anim1.currentTime);} else if (channel2 != activeAnim2.channels.end()) {glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId] = parentTransform *animationTransform(channel2->second, anim2.currentTime);} else {glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId] = parentTransform *glTF.nodesStorage[gltfNode].transform;}glTF.skinning = true;} - We make a recursive call to this same lambda
traverseTree()to process all child nodes.for (uint32_t i = 0;i < glTF.nodesStorage[gltfNode].children.size(); i++){const uint32_t child =glTF.nodesStorage[gltfNode].children[i];traverseTree(child,glTF.matrices[glTF.nodesStorage[gltfNode].modelMtxId]);}}; // the end of the local lambda declaration - We invoke the lambda function
traverseTree()from the root node to calculate all the transformations and update the bone matrices.traverseTree(glTF.root, mat4(1.0f));for (const std::pair<std::string, GLTFBone>& b : glTF.bonesByName) {if (b.second.boneId != ~0u)glTF.matrices[b.second.boneId] =glTF.matrices[b.second.boneId] * b.second.transform;}} else {glTF.morphing = false;glTF.skinning = false;}} - Last but not least, we have the
animationTransformBlending()helper function inshared/UtilsAnim.cpp. After all the concepts covered in this chapter, we hope this function is fairly self-explanatory – we retrieve the positions, rotations, and scales for each animation channel, and then use LERP and SLERP mixing operations to combine them based on the blend factorweight. For the individual interpolation functions, refer to the recipe Implementing the glTF animation player.mat4 animationTransformBlending(const AnimationChannel& channel1, float time1,const AnimationChannel& channel2, float time2,float weight){mat4 trans1 = glm::translate(mat4(1.0f),interpolatePosition(channel1, time1));mat4 trans2 = glm::translate(mat4(1.0f),interpolatePosition(channel2, time2));mat4 translation = glm::mix(trans1, trans2, weight);quat rot1 = interpolateRotation(channel1, time1);quat rot2 = interpolateRotation(channel2, time2);mat4 rotation = glm::toMat4(glm::normalize(glm::slerp(rot1, rot2, weight)));vec3 scl1 = interpolateScaling(channel1, time1);vec3 scl2 = interpolateScaling(channel2, time2);mat4 scale = glm::scale(mat4(1.0f), glm::mix(scl1, scl2, weight));return translation * rotation * scale;}
And that’s the complete implementation for the animation blending feature in our glTF animation player. You can now run the demo application Chapter09/04_AnimationBlending and see an animated fox, similar to the one shown in the following screenshot.

Figure 9.4: Animation blending
Feel free to experiment with the demo. For example, try selecting both the Survey and Run animations, then adjust the blending factor so that the fox slowly turns its head while running. Moving the Blend slider slowly from 0 to 1 will give you a smooth transition between surveying and running.
The main opportunity here, of course, is not just manual adjustment but the ability to automatically create smooth transitions between different animations. In a 3D game, you could have a state machine (commonly called a blend tree) to switch animations based on high-level game logic. This state machine would rely on the animation blending mechanism to ensure seamless, automatic transitions between animations.
With this chapter, we conclude our brief exploration of the glTF file format and its capabilities. Let’s now shift gears and go back to rendering, so we can learn more about image-based rendering techniques and post-processing effects.
There’s more…
Section titled “There’s more…”To round out our exploration of the glTF file format, we’ve added two more code examples. The first, Chapter09/05_ImportLights, demonstrates how to import lights from a glTF file. The second, Chapter09/06_ImportCameras, shows how to import cameras. Feel free to explore them on your own!
The 06_ImportCameras app is particularly interesting because it showcases how to import different camera definitions from a glTF file and switch between them within the app. Here’s a screenshot:

Figure 9.5: Switching between different glTF cameras