[WebGL2] Growing a Field of Animated Grass: Combining Skinned Meshes with GPU Instancing
Hello!
I'm Fukasawa, a front-end engineer on the hyper-casual games team.
I made a demo in WebGL2 that uses GPU Instancing to draw large numbers of skinned glTF models. Even with shadow casting, it seems to handle about 30,000 of them at 60 FPS in Chrome on my work Mac, and about 2,000 to 3,000 in Safari on my personal iPhone X.
Here are the URLs.
Demo site: https://takumifukasawa.github.io/PaleGL/demos/grass-skinning-gpu-instancing/
Demo on GitHub: https://github.com/takumifukasawa/PaleGL/tree/master/demos/grass-skinning-gpu-instancing

Number of instances: about 700

Number of instances: about 25,000

In this article, I'll focus on how to implement skinning and how to combine it with GPU Instancing, walking through samples that break the implementation down step by step. There are four samples in all, one per section.
Sample repository: https://github.com/takumifukasawa/webgl-skinning-gpu-instancing
Finished sample: https://takumifukasawa.github.io/webgl-skinning-gpu-instancing/skinning-gpu-instancing.html

Motivation
Unity has a feature called GPU Skinning. According to the documentation, the supported devices/APIs are DX11, DX12, OpenGL ES 3.1, Xbox One, PS4, Nintendo Switch and Vulkan (Windows, Mac and Linux), and internally it performs skinning with a ComputeShader.
PlayerSettings-gpuSkinning - Unity Scripting Reference
The article below also covers combining GPU Skinning with Skinned Meshes to draw them in large numbers.
Animation Instancing – Instancing for SkinnedMeshRenderer | Unity Blog
Reading that article made me think, "I want to try drawing lots of skinned meshes in WebGL too," and that's how this started.
I'm using WebGL2 here, but neither WebGL1 nor WebGL2 has ComputeShaders in the first place. ComputeShaders are apparently going to be standard in WebGPU, but broad browser support for WebGPU itself still looks a long way off.
That means the approach necessarily has to differ from Unity's GPU Skinning, but I wanted to explore an implementation that, with instancing in mind, hands as much of the skinning as possible to the GPU (and off the CPU), even in WebGL, so I built this demo.
How it's implemented
The skinning data for every frame is packed into an RGBA32F texture in advance; the vertex shader fetches the skinning data from that texture and performs the skinning in the shader.
Also, I want each instance's skinning animation to be offset in time, so the number of frames to offset each animation by is passed as an attribute.
Another way to "draw lots of animated things" is to "pack the vertex data (positions and normals) for every frame into a texture and read that texture in the vertex shader," but depending on the number of vertices and frames, that's likely to be very heavy at load time, so I decided to pack the skinning data instead.
1. Implementing skinning
For the samples, I prepared a model shaped like the one below. It's five stacked boxes with five bones. Each box has sides of length 1, and the bones sit at the centers of the boxes, each 1 unit farther along the Y axis from the root bone.

These are the positions of the vertices and bones seen from the front.

And finally, here's the motion we're aiming for.

Exporting model data and so on would mean more to implement, so I typed the model data in by hand on the JS side to build the shape above.
const boxPositions = [
// tier 0
[-0.5, 0, 0.5], // p0
[0.5, 0, 0.5], // p1
[-0.5, 0, -0.5], // p2
[0.5, 0, -0.5], // p3
// tier 1
...
];
const boxIndices = [
// bottom face
[0, 2, 1, 1, 2, 3], // bottom
// tier 1
[4, 0, 5, 5, 0, 1], // front
[5, 1, 7, 7, 1, 3], // right
[7, 3, 6, 6, 3, 2], // back
[6, 2, 4, 4, 2, 0], // left
// tier 2
...
];
...
A quick aside: in Blender, you can set a bone's position and rotation by dragging its head and tail around, but the head of the bone (the joint) is what the implementation calls a "bone." Those are the orange circles in the diagram above. Being able to move the head and tail in Blender is, roughly speaking, just "how that tool chooses to let you edit bones," and some implementations may take that into account, but in this one, "the head is the bone" and nothing else is considered.
How skinning works
So how does skinning work in the first place?
First, to display anything on screen in WebGL, you have to convert points in the local coordinate system into clip coordinates. Whatever falls within -1 to 1 in clip space appears on screen.
The basic approach is to convert vertex positions in the local coordinate system into clip space by passing them through the world, view and projection transforms, as shown below. When converting local vertices to clip space in a vertex shader, the code usually looks something like this.
gl_Position = uProjectionMatrix * uViewMatrix * uWorldMatrix * vec4(aPosition, 1.);
We'll add the skinning transform to this, but first, let's reframe the question as "how do we express the vertices in the local coordinate system?"
That's because, given how skinned meshes are actually used ("a skinned mesh, such as a human or animal, should work no matter where or how it's placed in world space"), the skinning itself can be considered separately from the transform into world space.
In other words, when thinking about implementing skinning, the conversion to clip space above can be rewritten like this.
gl_Position = uProjectionMatrix * uViewMatrix * uWorldMatrix * skinMatrix * vec4(aPosition, 1.);
The only difference from the previous code is the added skinMatrix, a transform matrix that performs the skinning. In other words, the idea behind skinning is "vertex in the local coordinate system -> apply skinning -> new vertex in the local coordinate system."
Here, I'm assuming the skinning happens in the shader. If aPosition were a local vertex that had already been skinned on the CPU, you of course wouldn't need skinMatrix. Setting performance aside for a moment, the only difference is whether you calculate it on the CPU or the GPU.
Making the matrices for skinning
Let's think about the skinMatrix above, that is, the transform matrix that performs the skinning. Setting aside how the vertices move, let's focus only on how the bones move.
The basic way to determine a pose is to move the bones according to Forward Kinematics (FK). FK applies each bone's rotation, translation and so on in order, from the root to the tip. If the shoulder is the root, think "shoulder -> elbow -> wrist...". So the closer a bone is to the tip, the more ancestor bones influence it. Moving the bones starting from the tip instead is Inverse Kinematics (IK).
Since we're using FK, of the sample's five bones, the 4x4 matrix for the pose of b0, the bone closest to the root, takes only b0 into account; b1's is b0 * b1, and b2's is b0 * b1 * b2. Be careful about the order of multiplication: you multiply from right to left.
In other words, a bone's pose in local space is the product of the matrices representing "each ancestor bone's own pose" for every ancestor that influences it, and the matrix representing "the bone's own pose." I deliberately wrote "the bone's own pose" because a bone's position and orientation are the result of applying a pose (translation and rotation) relative to its parent bone.
I'll call each bone's pose (position and orientation) at its starting position its initial pose. It's the pose with no animation applied, and every bone has one. Since this is a skinned mesh, in most cases you'd expect it to have some kind of animation. In other words, we need to work out how to transform from the "initial pose" to "the pose at a given frame." I'll call these pose0 and pose1 respectively.
To give the method up front: you can calculate a bone's pose at each frame with the transform multiply by the inverse of "the bone's initial pose in local coordinates (pose0)" -> move to the bone's current pose in local coordinates (pose1).
The reason for doing it this way is that inserting a step that returns the bone to the origin of local coordinates puts it at (0,0,0) first, which makes the pose calculation for pose1 easier to follow. If you didn't return it to the origin, you'd need to store the difference (pose1 - pose0) for every frame. With the method above, the data you store for each frame is "the pose in bone space," which is easier to reason about (that's my understanding, anyway). For example, if you parse glTF data and look inside, that's how it's specified.
To recap, here are the steps for calculating each bone's pose at every frame:
For every bone:
1. Make the inverse of the initial pose in the local coordinate system (called the "bone offset matrix") in advance
2. Multiply by the bone offset matrix to return it to the origin of the local coordinate system
3. Move it to each bone's pose in the local coordinate system
4. Repeat 2 and 3 every frame
The diagram below shows the idea.

A new term has appeared here: bone offset matrix. To flesh out the idea of the "initial pose" a bit more: initial bone poses like the T-Pose you often hear about when working with human models are exactly what you need to calculate this bone offset matrix.
Since it just returns the initial pose to the origin of local space, it's enough to calculate it once at load time. For example, for bone b2 of the sample model, the matrix representing its pose in local space is b0 * b1 * b2, so its inverse is the bone offset matrix.
The diagram below shows the idea of the bone offset matrix.

The bones that influence each vertex
We've looked at how each bone moves. Now, at last, let's think about transforming the vertices.
Now that we know how to move the bones, we need some way to link the vertices to them. Let's look at the method first.
1. Number the bones with indices
2. For every bone, send "the transform matrix to the current pose in local coordinates x the bone offset matrix" to the shader as a uniform array
- In the order of the indices from step 1
- Watch the order of matrix multiplication. Multiply from the right.
3. For each vertex, list the indices of the bones that influence it, and send them as vertex data
4. Give each influencing bone a weight (blend ratio) for how strongly it influences the vertex, and send the weights as vertex data. Make the blend ratios add up to 1.
5. Multiply each influencing bone's transform matrix to its current pose by its blend ratio, and add them all up
We want to specify "which bones influence" each vertex, so we give the bones indices. In this sample, they're numbered 0, 1, 2, 3, 4 from the root.
As for step 3, "list the indices of the bones that influence it": I let each vertex be influenced by multiple bones. The main reason is to prevent extreme bending or stretching.
Picture a bone with a wide range of motion, like a human elbow: if a vertex can be influenced by several bones, you can fine-tune how it stretches and shrinks by adjusting which bones influence it and their weights. That's hard with a hand-typed model like this sample, but in Blender you can paint the weights with a brush. In general, the standard practice is to make the weights of the influencing bones add up to 1, but it doesn't strictly have to be that way.
Example: if the transform matrix to each bone's current pose is pose[bone_index], and a vertex is influenced 0.5 each by bone0 and bone1, it looks like this.
mat4 skinMatrix = pose[0] * 0.5 + pose[1] * 0.5;
We've now seen how to specify the influencing bones and their weights. As for "how many influencing bones to allow," there's no fixed rule for that either. The sample allows four. The reason is that the influencing bone indices are sent in a uvec4 buffer and the weights in a vec4 buffer, and each of those types can hold up to four values. By the way, in Unity you can choose 1, 2, 4 or auto for the number of influencing bones.
Here's the working demo.
https://takumifukasawa.github.io/webgl-skinning-gpu-instancing/skinning-uniform-matrix.html

Below are excerpts of the JS and GLSL, adapted for the article.
First, I made a Bone class. The index could be stored in the class itself or managed by the parent. Since this is a sample, I've prioritized clarity and managed it on the parent side.
import {Matrix4} from "./Matrix4.js";
export class Bone {
parent = null;
children = [];
offsetMatrix; // position relative to the parent bone
#poseMatrix; // initial pose matrix in local space
#boneOffsetMatrix; // inverse of the initial pose matrix in local space (= bone offset matrix)
#jointMatrix = Matrix4.identity(); // current pose matrix in local space
get childCount() {
return this.children.length;
}
get hasChild() {
return this.childCount > 0;
}
addChild(child) {
this.children.push(child);
child.parent = this;
}
get boneOffsetMatrix() {
return this.#boneOffsetMatrix;
}
get poseMatrix() {
return this.#poseMatrix;
}
get jointMatrix() {
return this.#jointMatrix;
}
calcBoneOffsetMatrix(parentBone) {
this.#poseMatrix = !!parentBone
? Matrix4.multiplyMatrices(parentBone.poseMatrix, this.offsetMatrix)
: this.offsetMatrix;
this.#boneOffsetMatrix = this.#poseMatrix.clone().invert();
this.children.forEach(childBone => childBone.calcBoneOffsetMatrix(this));
}
calcJointMatrix(parentBone) {
this.#jointMatrix = !!parentBone
? Matrix4.multiplyMatrices(parentBone.jointMatrix, this.offsetMatrix)
: this.offsetMatrix;
this.children.forEach(childBone => childBone.calcJointMatrix(this));
}
}
Next is the code for creating the bones, setting the weights, binding to WebGL and so on.
// ------------------------------------
// vertex information
// ------------------------------------
// indices of the bones that affect the vertex
// allow up to four
const boneIndices = new Uint16Array[
// tier 0
[0, 0, 0, 0], // b0
[0, 0, 0, 0], // b0
[0, 0, 0, 0], // b0
[0, 0, 0, 0], // b0
// tier 1
[0, 1, 0, 0], // b0, b1
[0, 1, 0, 0], // b0, b1
[0, 1, 0, 0], // b0, b1
[0, 1, 0, 0], // b0, b1
...
].flat());
// weight for each affecting bone index
// sent as a Float32Array
const boneWeights = new Float32Array([
// tier 0
[1, 0, 0, 0], // b0 * 1
[1, 0, 0, 0], // b0 * 1
[1, 0, 0, 0], // b0 * 1
[1, 0, 0, 0], // b0 * 1
// tier 1
[0.5, 0.5, 0, 0], // b0 * 0.5, b1 * 0.5
[0.5, 0.5, 0, 0], // b0 * 0.5, b1 * 0.5
[0.5, 0.5, 0, 0], // b0 * 0.5, b1 * 0.5
[0.5, 0.5, 0, 0], // b0 * 0.5, b1 * 0.5
...
].flat());
...
// ------------------------------------
// creating the bones
// parent-child relationships are managed by the Bone class
// offsetMatrix ... pose relative to the parent bone
// ------------------------------------
const bone0 = new Bone();
bone0.offsetMatrix = Matrix4.translationMatrix(new Vector3(0, 0.5, 0)); // offset
const bone1 = new Bone();
bone1.offsetMatrix = Matrix4.translationMatrix(new Vector3(0, 1, 0));; // offset from parent (bone0)
bone0.addChild(bone1);
const bone2 = new Bone();
bone2.offsetMatrix = Matrix4.translationMatrix(new Vector3(0, 1, 0)); // offset from parent (bone1)
bone1.addChild(bone2);
const bone3 = new Bone();
bone3.offsetMatrix = Matrix4.translationMatrix(new Vector3(0, 1, 0)); // offset from parent (bone2)
bone2.addChild(bone3);
const bone4 = new Bone();
bone4.offsetMatrix = Matrix4.translationMatrix(new Vector3(0, 1, 0)); // offset from parent (bone3)
bone3.addChild(bone4);
// the order of the uniform array is managed by the parent side
const bones = [
bone0,
bone1,
bone2,
bone3,
bone4,
];
// recursively create the offset matrices of all the bones
bones[0].calcBoneOffsetMatrix();
...
// called inside the animation loop. rotates bone1, bone2 and bone3
const updateBone = (time) => {
const rot = Math.sin(Math.PI * 2 * (time / 2)) * 30 * Math.PI / 180;
bone1.offsetMatrix = Matrix4.multiplyMatrices(
Matrix4.translationMatrix(new Vector3(0, 1, 0)),
Matrix4.rotationZMatrix(rot)
);
bone2.offsetMatrix = Matrix4.multiplyMatrices(
Matrix4.translationMatrix(new Vector3(0, 1, 0)),
Matrix4.rotationZMatrix(rot)
);
bone3.offsetMatrix = Matrix4.multiplyMatrices(
Matrix4.translationMatrix(new Vector3(0, 1, 0)),
Matrix4.rotationZMatrix(rot)
);
}
const tick = (time) => {
...
updateBone(time / 1000);
// create the matrices representing every bone's current pose in local space
// child bones are calculated recursively too
bones[0].calcJointMatrix();
// current pose matrix (jointMatrix) x bone offset matrix
// multiplyMatrices multiplies from the right. the bone offset matrix is applied before the pose matrix, so the bone offset matrix goes on the right
// when setting the uniform, flatten into a one-dimensional Float32Array
const jointMatrices = [
Matrix4.multiplyMatrices(bones[0].jointMatrix, bones[0].boneOffsetMatrix), // b0
Matrix4.multiplyMatrices(bones[1].jointMatrix, bones[1].boneOffsetMatrix), // b1
Matrix4.multiplyMatrices(bones[2].jointMatrix, bones[2].boneOffsetMatrix), // b2
Matrix4.multiplyMatrices(bones[3].jointMatrix, bones[3].boneOffsetMatrix), // b3
Matrix4.multiplyMatrices(bones[4].jointMatrix, bones[4].boneOffsetMatrix), // b4
];
...
}
...
// ------------------------------------
// inside the function that sets a vertex buffer
// ------------------------------------
...
const vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); // always static draw. data ... the data to set on the vertices
gl.enableVertexAttribArray(location);
switch(data.constructor) {
case Float32Array:
gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
break;
case Uint16Array:
gl.vertexAttribIPointer(location, size, gl.UNSIGNED_SHORT, 0, 0);
break;
}
...
// ------------------------------------
// the part that sets the array of bone matrices on the uniform
// ------------------------------------
...
const shader = gl.createProgram();
gl.useProgram(shader);
...
const location = gl.getUniformLocation(shader, "uJointMatrices");
gl.uniformMatrix4fv(location, false, data); // data ... filled with each bone's transform matrix as a Float32Array. five matrices in the sample
...
GLSL
#version 300 es
layout (location = 0) in vec3 aPosition;
layout (location = 1) in vec3 aColor;
layout (location = 2) in uvec4 aBoneIndices;
layout (location = 3) in vec4 aBoneWeights;
uniform mat4 uWorldMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;
uniform mat4[5] uJointMatrices;
out vec3 vColor;
void main() {
vColor = aColor;
mat4 skinMatrix =
uJointMatrices[aBoneIndices.x] * aBoneWeights.x +
uJointMatrices[aBoneIndices.y] * aBoneWeights.y +
uJointMatrices[aBoneIndices.z] * aBoneWeights.z +
uJointMatrices[aBoneIndices.w] * aBoneWeights.w;
gl_Position = uProjectionMatrix * uViewMatrix * uWorldMatrix * skinMatrix * vec4(aPosition, 1.);
}
The more influencing bones there are, the heavier the load on the vertex shader. So if you limited each vertex to two influencing bones, for example, and packed them into a single vec4 as vec4(boneIndex0, boneIndex1, boneWeight0, boneWeight1);, you'd also need only one buffer instead of two, which would optimize things further.
2. Using vertex texture fetch
Uniform limits
We now have a basic skinning implementation.
But with this implementation, you may get shader errors depending on the model data. The cause is a limit on uniforms.
Specifically, there's a limit called MAX_VERTEX_UNIFORM_VECTORS. It's the maximum number of vectors a vertex shader can handle, and it varies from device to device. It was 256 in Safari on my personal iPhone X, and 1024 in Chrome on my work Mac. This limit depends on the combination of settings and specs of each device's GPU, OS and browser. (Uniform Buffer Objects should let you handle many more vectors, but I don't know enough about them, so I'll leave them out here.)
A site called WebGL Report is handy: open it, and it lists the current device's WebGL support all at once, not just MAX_VERTEX_UNIFORM_VECTORS. As an aside, back when WebGL1 was still mainstream, I wanted to use float textures, which were an extension, but quite a few devices didn't support them, and this site was invaluable for checking float texture support across all sorts of devices.
...Anyway, back to the topic: there's a limit on the number of vectors you can pass in uniforms. A mat4 counts as four vectors. So if MAX_VERTEX_UNIFORM_VECTORS is 256, then without any special tricks you can pass at most 256 / 4 = 64 mat4s.
You'll almost always have some other uniforms to pass besides the skinning matrices, but in plenty of cases, being able to handle roughly that many bones is enough for a smartphone website. You can also reduce the number of bones.
However, there's a problem: "if you fix the length of the uniform array in the shader to the number of bones, meshes with a different number of bones need separate shaders." If the meshes look the same, it's more convenient to be able to use the same shader regardless of bone count.
Packing it into a texture
So let's try baking each bone's transform matrix into a texture and reading it with vertex texture fetch. The uniform you send is now a texture rather than an array, so the shader can be shared across meshes.
This time I'll use an RGBA32F texture. In RGBA32F, each channel is a 32-bit float, so 4 channels = 128 bits per pixel.
In WebGL2 you can also use RGBA16F. Half precision would be accurate enough, but TypedArray has no Float16, so I'll use a Float32Array for the texture data and RGBA32F for the texture itself. * If anyone knows a way to create a Float16 data array on the JS side, I'd be grateful if you'd let me know.
How to pack it
Store every bone's transform matrix in a Float32Array. The texture format is 32-bit RGBA and the data is a Float32Array, so each element of the data array goes straight into a channel.
Let's make the texture 4 pixels wide. 4 channels x 4 pixels = one matrix, so picture each bone's matrix stacked vertically. Of course, you could also make it wider, say 8 or 12 pixels. So why 4 px? Because it keeps things simple in the shader. In the demo at the top, the width in pixels is adjustable.
The sample has five bones, so it generates a 4 x 5 = 20 pixel texture. The size is 20 x 128 bit = 2,560 bits. The diagram below illustrates the idea.

Here's the sample. It looks exactly the same as before.
https://takumifukasawa.github.io/webgl-skinning-gpu-instancing/skinning-joint-texture.html

Below is the flow of the sample's JS and GLSL, excerpted and adapted.
const boneNum = 5;
const width = 4;
const height = width * boneNum;
// create texture
const texture = gl.createTexture();
...
// loop function
const tick = () => {
...
// bind
gl.bindTexture(gl.TEXTURE_2D, texture);
// set data
// data ... in the sample, holds the transform matrices to the bones' current poses x5
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, width, height, 0, gl.RGBA, gl.FLOAT, data);
// unbind
gl.bindTexture(gl.TEXTURE_2D, null);
...
// set on the uniform
...
}
GLSL
#version 300 es
layout (location = 0) in vec3 aPosition;
layout (location = 1) in uvec4 aBoneIndices;
layout (location = 2) in vec4 aBoneWeights;
...
uniform sampler2D uJointTexture; // 4 x 5 texture
mat4 getJointMatrix(uint boneIndex) {
return mat4(
texelFetch(uJointTexture, ivec2(0, boneIndex), 0),
texelFetch(uJointTexture, ivec2(1, boneIndex), 0),
texelFetch(uJointTexture, ivec2(2, boneIndex), 0),
texelFetch(uJointTexture, ivec2(3, boneIndex), 0)
);
}
void main() {
...
mat4 skinMatrix =
getJointMatrix(aBoneIndices.x) * aBoneWeights.x +
getJointMatrix(aBoneIndices.y) * aBoneWeights.y +
getJointMatrix(aBoneIndices.z) * aBoneWeights.z +
getJointMatrix(aBoneIndices.w) * aBoneWeights.w;
gl_Position = uProjectionMatrix * uViewMatrix * uWorldMatrix * skinMatrix * vec4(aPosition, 1.);
}
3. Packing the animation data into the texture too
Approach
In the implementation so far, the CPU side (JS) calculated each bone's matrix and packed the data into the texture. Now, at last, let's think about an implementation designed with GPU Instancing in mind.
The reason we want GPU Instancing in the first place is speed: normally, drawing more things means more draw calls, but GPU Instancing hands the job of drawing many copies to the GPU and does it all in a single draw call. Also, as I'll explain in detail later, the shader can look up its own instance ID with gl_InstanceID, and you can pass per-instance data in buffers.
However, with the current implementation, the instances' animations will look synchronized even with GPU Instancing. That's because the bones' poses have already been determined by the time each bone's data reaches the shader. But when you're drawing lots of skinned meshes, you really want each mesh's animation to be offset, right?
So we'll pack the animation data into the texture in advance as well. In other words, where the texture used to hold "each bone's transform matrix at a given frame," it will now hold "each bone's transform matrix at every frame." That means the amount of data is multiplied by the number of frames.
Packing every bone's matrix for every frame into the texture
Until now, the texture's size in pixels was "width: 4 px (one matrix of data) x height: number of bones." From here on, we also pack in the matrices for every frame in advance, so it becomes "width: 4 px (one matrix of data) x height: (number of bones x number of frames)."
In the sample, the animation has 60 frames. The size is 4 x 5 x 60 x 128 bit = 153,600 bits = about 19 KB. To repeat, the width is 4 px only to keep things simple in the shader; it doesn't have to be 4 px. With lots of frames, a wider texture lets you pack in more data.
Here's the sample so far. It still looks the same when it runs.
https://takumifukasawa.github.io/webgl-skinning-gpu-instancing/skinning-bake-bone-animation.html

Here's an excerpt of the sample's shader.
...
// frame number of the current animation
uniform int uFrameIndex;
...
// there are 5 bones, so shift by 5 for each frame
mat4 getJointMatrix(uint boneIndex) {
int frameNum = 5;
uint targetIndex = uint(uFrameIndex * frameNum) + boneIndex;
return mat4(
texelFetch(uJointTexture, ivec2(0, targetIndex), 0),
texelFetch(uJointTexture, ivec2(1, targetIndex), 0),
texelFetch(uJointTexture, ivec2(2, targetIndex), 0),
texelFetch(uJointTexture, ivec2(3, targetIndex), 0)
);
}
...
4. Implementing GPU Instancing
Now we finally get to implementing GPU Instancing. It's also sometimes called just Instancing, or Geometry Instancing, but I'll stick with GPU Instancing here.
In WebGL1, GPU Instancing was an extension, but WebGL2 promoted it to a standard feature. Switching over to GPU Instancing itself is surprisingly easy.
Required: replacing the draw methods
This is the bare minimum, and it's always required. WebGL has two draw call methods, drawArrays and drawElements. The latter uses an IndexBuffer.
Replace these draw methods with drawArraysInstanced and drawElementsInstanced respectively. The number of instances goes in the last argument.
gl.drawArrays(mode, first, count, instanceCount);
↓
gl.drawArraysInstanced(mode, first, count, instanceCount);
gl.drawElements(mode, count, type, offset);
↓
gl.drawElementsInstanced(mode, count, type, offset, instanceCount)
Pattern 1: putting per-instance data in uniforms
For example, with 10 instances, you send an array of 10 elements to the uniform. Then you look up each instance's data with gl_InstanceID.
If you wanted to change the color per instance, the code would look like this.
const shader = gl.getProgram();
...
const location = gl.getUniformLocation(shader, "uColor");
// pack 10 colours
gl.uniform4fv(location, [
1, 0, 0, 1, // red
0, 1, 0, 1, // blue
...
]);
uniform vec4[10] uColor;
...
void main() {
...
vec4 instanceColor = uColor[gl_InstanceID];
...
}
But, as mentioned earlier, you can't send all that much data in uniforms. If the device's MAX_VERTEX_UNIFORM_VECTORS is 256 and you store per-instance colors in vertex shader uniforms, you can have 256 at most.
Pattern 2: putting per-instance data in the vertices
You need these two things:
- Add the data you want to vary per instance to a VertexBufferObject
- Specify how the per-instance data is laid out with vertexAttribDivisor
For example, if there are 10 instances and you want a different color for each, put 10 colors into the vertexBufferObject.
const data = new Float32Array([
1, 0, 0, 1, // red
0, 1, 0, 1, // blue
...
]);
const location = 0;
const vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
if(divisor) {
// specify that the per-instance data is laid out one per instance, in order
gl.vertexAttribDivisor(location, 1);
}
In this sample, I'll put the per-instance data in the VertexBufferObject.
Offsetting the animation time per instance
Now everything's in place. The animation time offset is a single float, so the length of the Float32Array passed to the VertexBufferObject is simply the number of instances.
I also passed a per-instance color and position offset to the vertices. aInstanceOffsetPosition, aInstanceFrameOffset and aInstanceColor in the vertex shader below are the buffers holding per-instance data.
Here's the sample.
https://takumifukasawa.github.io/webgl-skinning-gpu-instancing/skinning-gpu-instancing.html

Here's the shader for the finished sample.
#version 300 es
layout (location = 0) in vec3 aPosition;
layout (location = 1) in vec3 aColor;
layout (location = 2) in uvec4 aBoneIndices;
layout (location = 3) in vec4 aBoneWeights;
layout (location = 4) in vec3 aInstanceOffsetPosition;
layout (location = 5) in uint aInstanceFrameOffset;
layout (location = 6) in vec3 aInstanceColor;
uniform mat4 uWorldMatrix;
uniform mat4 uViewMatrix;
uniform mat4 uProjectionMatrix;
uniform sampler2D uJointTexture;
uniform float uTime;
out vec3 vColor;
mat4 getJointMatrix(uint boneIndex) {
return mat4(
texelFetch(uJointTexture, ivec2(0, boneIndex), 0),
texelFetch(uJointTexture, ivec2(1, boneIndex), 0),
texelFetch(uJointTexture, ivec2(2, boneIndex), 0),
texelFetch(uJointTexture, ivec2(3, boneIndex), 0)
);
}
void main() {
vColor = aInstanceColor;
// loop frames 0-59 for each instance
float fps = 30.;
float frameCount = 60.;
int frameIndex = int(mod(floor(uTime * fps) + float(aInstanceFrameOffset), frameCount));
int boneCount = 5;
uint b0 = uint(frameIndex * boneCount) + aBoneIndices.x;
uint b1 = uint(frameIndex * boneCount) + aBoneIndices.y;
uint b2 = uint(frameIndex * boneCount) + aBoneIndices.z;
uint b3 = uint(frameIndex * boneCount) + aBoneIndices.w;
mat4 skinMatrix =
getJointMatrix(b0) * aBoneWeights.x +
getJointMatrix(b1) * aBoneWeights.y +
getJointMatrix(b2) * aBoneWeights.z +
getJointMatrix(b3) * aBoneWeights.w;
mat4 instanceOffsetMatrix = mat4(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
aInstanceOffsetPosition, 1
);
gl_Position = uProjectionMatrix * uViewMatrix * instanceOffsetMatrix * uWorldMatrix * skinMatrix * vec4(aPosition, 1.);
}
Summary
Let's look at the pros and cons, compared with the "pack vertex data into a texture" approach I briefly mentioned at the start.
Advantages
The texture size no longer depends on the number of vertices. The number of pixels is "4 px (one matrix) x number of bones x number of frames", so the texture size doesn't change whether there are 1,000 vertices or 10,000.
Say a model with 10 bones has a 4-second animation. At 30 fps, it needs 4px x 10bone x 4sec x 30fps = 4,800 pixels. The number of bits is 4,800 * 32 * 4 = 614,400, which is 75 KB.
With the "pack vertex data into a texture" approach, a model with 1,000 vertices needs 1000vertex * 4sec * 30fps = 120,000 pixels. Using RGB32F, that's 120,000 x 32 x 3 = 11,520,000 bits, or about 1.37 MB. And that's multiplied again by the number of attributes you want to pass (vertex positions, normals and so on...).
Disadvantages
The number of texture reads in the vertex shader grows with the number of bones that influence each vertex. With four bones, you need at least 16 reads. With the "pack vertex data into a texture" approach, if you bake, say, the vertex positions and normals into textures, there are only two texture reads.
Closing
Thank you for reading this far!
Demo site: https://takumifukasawa.github.io/PaleGL/demos/grass-skinning-gpu-instancing/

References
Part 61: A fully white-box explanation of skin mesh animation