Writing a sprite batcher: from one draw call per sprite to one
A sprite batcher is the part of a 2D renderer that turns "draw these four thousand little pictures" into a handful
of instructions the GPU is happy to receive. Every 2D engine has one somewhere, usually hidden behind a friendly
draw_sprite call. Writing your own is a good weekend project because it touches almost every idea in real-time
graphics in a small space: vertex layouts, buffers, textures, blending and order.
I am going to build it three times. Each version works, and each one fixes the specific thing that makes the previous one slow. The GPU code is WGSL; the CPU side is plain Rust with the graphics API calls written as comments, because the exact names depend on your wrapper and version. If you have not set up a device and a render pass yet, the wgpu getting started piece covers that ground.
What a sprite actually is
On the GPU, a sprite is two triangles forming a rectangle, a region of a texture, a colour tint and a position. That is all. Rotation and scale are optional maths on the corners. Here is the CPU description I will use throughout:
#[derive(Clone, Copy)]
pub struct Sprite {
pub pos: [f32; 2], // centre in world units
pub size: [f32; 2], // width and height in world units
pub uv_rect: [f32; 4], // u0, v0, u1, v1 inside the texture
pub colour: [f32; 4], // linear RGBA tint, multiplied in the shader
pub texture: u32, // which texture or atlas page
pub layer: i32, // draw order, lower first
}
Game code fills a Vec<Sprite> every frame and hands it to the renderer. Everything below is about what the
renderer does with that vector.
Version 1: one draw call per sprite
The first version is the one everybody writes. For each sprite, write four vertices into a small buffer, bind the sprite's texture, set the uniforms and issue a draw of six indices.
It works, and for a menu screen with forty sprites it is perfectly fine. The trouble shows up with numbers. Each draw call costs CPU time in the driver and the API layer: validating state, recording commands, sometimes switching bind groups. The exact figure varies hugely between machines, so let me use a deliberately vague budget instead of a fake benchmark. Say a draw call with a texture switch costs somewhere around a few microseconds on a mid-range laptop. At 60 frames per second you have 16.6 milliseconds per frame. If rendering may use a quarter of that, about 4 milliseconds, and each sprite costs 4 microseconds of overhead, you can draw roughly 1,000 sprites before anything else happens. A particle burst or a busy tilemap crosses that easily.
The GPU is not the bottleneck here. It could shade those pixels in a fraction of the time. The bottleneck is the conversation.
Version 2: one big vertex buffer
The fix is to stop talking so much. Instead of a draw per sprite, write every sprite's four corners into one large vertex buffer, upload it once, and draw everything with one call. A vertex now carries what used to be uniforms:
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Vertex {
pub pos: [f32; 2],
pub uv: [f32; 2],
pub colour: [f32; 4],
}
pub fn push_quad(out: &mut Vec<Vertex>, s: &Sprite) {
let (hx, hy) = (s.size[0] * 0.5, s.size[1] * 0.5);
let [u0, v0, u1, v1] = s.uv_rect;
let c = s.colour;
let (x, y) = (s.pos[0], s.pos[1]);
out.push(Vertex { pos: [x - hx, y - hy], uv: [u0, v1], colour: c });
out.push(Vertex { pos: [x + hx, y - hy], uv: [u1, v1], colour: c });
out.push(Vertex { pos: [x + hx, y + hy], uv: [u1, v0], colour: c });
out.push(Vertex { pos: [x - hx, y + hy], uv: [u0, v0], colour: c });
}
The index buffer never changes: for quad n it is 4n, 4n+1, 4n+2, 4n, 4n+2, 4n+3. Build it once at startup for
the largest batch you expect and reuse it forever.
A Vertex is 32 bytes, so a sprite is 128 bytes of vertex data. Ten thousand sprites is about 1.3 MB per frame.
That is a comfortable upload on any desktop GPU, and the draw count has dropped from ten thousand to one.
There is one condition. A single draw call can only sample the textures that are bound for it. If sprite 1 uses the player texture and sprite 2 uses the enemy texture, they cannot share a call. Which brings us to atlases.
Atlases: making textures stop mattering
A texture atlas packs many images into one large texture, and each sprite remembers its rectangle inside it. That is
what the uv_rect field is for. If all your characters, tiles and effects live on one 2048 by 2048 page, every
sprite uses the same texture and the whole frame can be one batch.
Atlas packing is a solved problem for our purposes. A simple shelf packer, which places images left to right in rows sorted by height, wastes a bit of space but is about thirty lines of code and fine for a jam. Do two things however you pack:
- Add padding of one or two pixels around each image and repeat the edge pixels into it. Without that, linear filtering or slightly off camera positions sample the neighbour and you get thin coloured lines at sprite edges.
- Compute UVs from pixel coordinates divided by the atlas size, and keep the atlas size a power of two if you plan to generate mipmaps for scaled sprites.
Pixel art usually wants nearest-neighbour filtering, which hides some padding mistakes but not all of them. Pad anyway. If you are still deciding how your sprites are drawn and laid out, the character sprites guide shows sheet layouts that pack nicely.
Sorting: the part that decides how many batches you get
With atlases you will still end up with more than one texture: a font page, a UI page, a big background. So the batcher sorts sprites and starts a new batch whenever the texture changes. The sort key decides how often that happens, and it also decides what looks right.
For opaque, pixel-art sprites without partial transparency you could sort purely by texture and let a depth buffer fix order. Most 2D games use alpha blending though, and blended sprites must be drawn back to front. So the key is layer first, then texture inside each layer:
pub fn sort_key(s: &Sprite) -> u64 {
// layer in the high bits, offset so negatives sort first
let layer = (s.layer as i64 + (1 << 31)) as u64;
(layer << 32) | s.texture as u64
}
// sprites.sort_by_key(sort_key); stable sort keeps submission order inside a key
Here is a worked example of why this matters. Imagine a frame with 3,000 sprites on three layers (ground, actors, UI) and three textures (tiles atlas, character atlas, font). Submitted in random order, texture changes happen on nearly every sprite, so you get close to 3,000 batches. Sorted by layer then texture, you get at most one batch per texture per layer, which here is a maximum of nine and in practice four or five, since the font only appears on the UI layer and tiles only on the ground.
Use a stable sort. Two sprites with the same layer and texture should keep the order the game submitted them in, or overlapping enemies will flicker as they swap places from frame to frame.
Version 3: instancing
Version 2 is already good. Version 3 trims the data. Every quad in version 2 repeats its colour four times and recomputes corners on the CPU. With instancing, you upload one record per sprite and let the vertex shader build the corners from the vertex index:
struct Instance {
@location(0) pos: vec2<f32>,
@location(1) size: vec2<f32>,
@location(2) uv_rect: vec4<f32>,
@location(3) colour: vec4<f32>,
};
struct VsOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) colour: vec4<f32>,
};
@group(0) @binding(0) var<uniform> view_proj: mat4x4<f32>;
@vertex
fn vs_main(@builtin(vertex_index) vi: u32, inst: Instance) -> VsOut {
// corners for a triangle strip: (0,0) (1,0) (0,1) (1,1)
let corner = vec2<f32>(f32(vi & 1u), f32(vi >> 1u));
let world = inst.pos + (corner - vec2<f32>(0.5)) * inst.size;
var out: VsOut;
out.clip = view_proj * vec4<f32>(world, 0.0, 1.0);
out.uv = mix(inst.uv_rect.xw, inst.uv_rect.zy, corner);
out.colour = inst.colour;
return out;
}
The instance buffer is declared with a per-instance step mode, and you draw four vertices times N instances as a triangle strip. No index buffer at all. An instance is 48 bytes, so ten thousand sprites is 480 KB, well under half of version 2.
The UV line deserves a word. Texture V usually grows downward while my world Y grows upward, so the bottom corner
(corner.y = 0) takes v1 and the top takes v0. If your sprites come out upside down, this is the line to look
at, not the projection matrix.
The fragment shader is short: sample, multiply by the tint, return. Keep the tint in linear colour if your surface is sRGB, or tinted sprites will look muddier than the artist intended. The HDR and bloom piece has more on keeping colour linear through the pipeline.
The three versions side by side
| Version | Draw calls for 10,000 sprites | Bytes per sprite uploaded | CPU work per sprite |
|---|---|---|---|
| 1: one call each | 10,000 | 128 plus uniforms | Bind, set, draw |
| 2: shared vertex buffer | 1 per texture run | 128 | Four corners on the CPU |
| 3: instancing | 1 per texture run | 48 | Copy one record |
The jump from version 1 to version 2 is the one that matters. Version 3 is a tidy-up that pays off when sprite counts get large or when you want per-sprite data the vertex layout cannot comfortably repeat four times.
Where the layer number comes from
In a side-on platformer the layer is usually fixed per kind of thing: background 0, tiles 10, enemies 20, player 25, particles 30, UI 100. Leave gaps so you can slot things in later without renumbering.
Top-down games are different, because a character standing lower on the screen should cover one standing higher. The usual trick is to derive the order from the sprite's feet: inside the actors layer, sort by the y coordinate of the bottom edge, descending if y grows upward. You can fold it into the key by giving actors a layer value computed from that y, quantised to whole pixels so that tiny movements do not reshuffle the order every frame. Trees and buildings then sort correctly against the player for free, as long as their sprite origin sits at the base of the trunk or wall rather than at the centre.
Practical details that bite
- Reuse buffers. Allocate the instance buffer with room to spare and grow it by doubling when a frame exceeds it. Creating a fresh buffer every frame wastes the gains.
- Flush on state changes, not only texture. Blend mode and shader changes also split a batch. Put them in the sort key above texture if you use several.
- Keep a counter on screen. Show sprites drawn and batches issued in a debug overlay. When batches jump from five to five hundred, someone added a texture that is not in the atlas.
- Cull before sorting. Dropping off-screen sprites first makes the sort cheaper and the upload smaller.
For a next step, add rotation: pass an angle per instance, build a 2 by 2 rotation from its sine and cosine in the
vertex shader, and apply it to (corner - 0.5) * size before adding the position. It is four lines, and it is a nice test of whether you
really understand where each corner comes from.
Filed in Graphics & Shaders

Written by Odalys Brisco
Odalys covers graphics programming: wgpu, shaders, lighting and the maths behind a good-looking 2D frame. She came to it from technical art and still sketches every effect on paper before writing a line of WGSL. Based in Valencia.
