Foundations
Generational handles
An engine has many objects: meshes, textures, entities, buffers. Code outside the engine needs a way to name one of them, and to find out when the object it names is gone. A generational handle does both with two small numbers. This page explains how it works. The last part shows how RASM does it.
In short
- A raw pointer breaks when the object moves or is freed. A plain index breaks when its slot is reused for a new object.
- A handle is an index into a table of slots plus a generation: a counter that goes up each time the slot is freed.
- A lookup checks that the handle's generation equals the slot's generation. If not, the handle is stale and the lookup fails safely.
- Freed slots go on a free list and are reused, so the table does not grow forever.
- A tag type makes a mesh handle and a texture handle different types, so the compiler stops you from mixing them.
- A handle does not own its object. The table does. Destroying an object the GPU still uses must wait until the GPU is done.
1The problem: naming an object
An application asks the engine to load a mesh. The engine must give back something the application can keep and pass back later: "draw this mesh". There are three common choices.
Pointer
The address of the object. Good: the fastest, no lookup at all.
Breaks when the object moves (an array grows, a level is compacted) or is freed. Using it then is undefined behaviour: a crash, or worse, wrong data.
Index
A position in a table. Good: small (4 bytes), survives moves, easy to send to the GPU.
Breaks when the slot is reused. The old index now names a different object, and nothing notices. This is called the ABA problem.
Generational handle
An index plus a generation. Good: small, survives moves, and detects reuse.
Breaks only when the generation counter wraps around (section 4).
The picture shows how each one fails. Follow B: it is named, then it goes away.
2The idea: index plus generation
The engine keeps each kind of object in a table of slots. Each slot stores the object and a generation number. A handle stores two numbers: the slot's index, and the generation the slot had when the handle was made.
The lookup in pseudo-code:
lookup(handle):
if handle.index >= slots.size:
return null // never made
slot = slots[handle.index]
if slot.generation != handle.generation:
return null // stale: freed, maybe reused
return slot.object
Two more rules make this complete:
Destroying adds 1 to the generation
Every handle made before is now stale, at once, without finding them.
Generation 0 means "no object"
Slots start at generation 1. So a handle that is all zeros, which is what a default-constructed handle is, never matches a slot. It is the handle version of a null pointer.
3Reusing slots: the free list
Without reuse, the table grows by one slot for every object ever made. A game that spawns and removes bullets would grow it forever. So a destroyed slot goes on a free list, and the next create takes a slot from it. The generation is what makes this reuse safe. Click through an example (or use the arrow keys).
1. Create A, B and C
Each handle copies its slot's current generation.
2. Destroy B
The object is destroyed, the generation goes up, the index goes on the free list.
3. Create D: it reuses slot 1
Create pops an index from the free list and uses the slot's current generation.
4. Look up B and D
The stale lookup fails in a defined way. The caller can log it, skip the work, or treat it as a bug.
Now run the same table by hand. It starts where step 1 ends.
Where the free list lives
A free slot holds no object, so its memory can store the index of the next free slot. The free list then needs no extra memory: one "first free" index, and a chain through the free slots. This is an intrusive free list.
Which slot to reuse first
A stack (last freed, first reused) is simplest and keeps memory warm in the cache. A queue (first freed, first reused) spreads reuse over all free slots, so each generation grows more slowly. That delays the wrap-around of section 4.
4How many bits
Handles are often packed into one 32-bit or 64-bit integer, so they are cheap to copy, hash and store in GPU buffers. The bits are split between the index and the generation. The index bits limit how many objects can live at once. The generation bits limit how many times one slot can be reused before its generation wraps back to an old value.
| Split | Objects alive at once | Reuses of one slot before a wrap | Worst case: one slot reused every frame at 60 fps |
|---|---|---|---|
| 20 + 12 bits | 220 = 1,048,576 | 212 = 4,096 | wraps after 68 seconds |
| 24 + 8 bits | 224 = 16,777,216 | 28 = 256 | wraps after 4.3 seconds |
| 32 + 32 bits | 232 ≈ 4.3 billion | 232 ≈ 4.3 billion | wraps after 2.3 years |
A wrap only causes a bug if old code still holds a handle from exactly one full cycle ago, and uses it. That is rare, but a small generation makes it possible. Two common fixes:
Retire the slot
When its generation reaches the maximum, do not put it on the free list again. It is lost, but no handle can ever alias.
Spread the reuse
A queue-ordered free list (section 3) reuses each slot less often.
5Dense storage for fast loops
A table with holes is slow to loop over: the loop must skip the free slots, and the live objects are spread out in memory. Systems that loop over every object each frame (all entities, all particles) often add one more layer. This is usually called a slot map.
Removing an object moves the last dense object into the hole ("swap and pop"), and the back array says which slot to repoint. The order of the dense array is not kept.
Before
D sits in the middle of the dense array. Its slot is slot 3.
After "swap and pop"
C fills the hole, slot 2 is repointed, and slot 3 is free with a new generation. No object is skipped in a loop.
6Type-safe handles
A mesh handle and a texture handle are both "two integers". If they are the same C++ type, nothing stops code from passing a mesh handle to a function that wants a texture. The lookup then reads the wrong table, and may even pass the generation check by luck.
One type for every handle
The compiler sees two integers. The mistake shows up at runtime, as the wrong texture.
A tag per kind of handle
The mistake never runs. The table is not touched.
The fix is a tag type: an empty type that is never defined and never used at runtime. It is only there to make each kind of handle a different type.
struct MeshTag;
struct TextureTag;
template <typename Tag>
struct Handle
{
uint32_t index = 0;
uint32_t generation = 0;
};
using MeshHandle = Handle<MeshTag>;
using TextureHandle = Handle<TextureTag>;
void bindTexture(TextureHandle texture);
Now bindTexture(mesh) is a compile error. The tag costs nothing: both types have the same two fields and the same size. This pattern is also called a phantom type or a strong typedef.
7Who owns the object
A handle is a weak reference. Holding it does not keep the object alive. The object belongs to its table, and it lives until someone calls destroy. This is different from a reference-counted pointer.
| Raw pointer | Reference count (shared_ptr) | Generational handle | |
|---|---|---|---|
| Who decides when it dies | Whoever calls delete | The last holder to let go | The owner of the table, by an explicit destroy |
| Using it after the object died | Undefined behaviour | Cannot happen: it is still alive | Detected: the lookup fails |
| Cost of a copy | Free | An atomic add and later an atomic sub | Free |
| Can go into a GPU buffer or a file | No, the address means nothing there | No | Yes, it is just numbers |
The GPU makes "destroy" harder
The CPU is usually one or two frames ahead of the GPU (see Frames in flight). When the CPU destroys a buffer, a frame that the GPU has not finished yet may still read it. Freeing the memory at once would let the GPU read garbage, or crash it. So engines split destroy into two parts:
The same delay matters for the slot. If the slot is reused too early, and the GPU still reads the old object's index from a buffer, the GPU reads the new object. So a slot whose index the GPU knows should also go back on the free list only after that fence.
8Handles for things made from a description
Some objects are fully described by their creation settings, and never change after. A compiled shader, a pipeline, a sampler and a descriptor layout are like this. If two parts of the program ask for the same one, they can share it. The table then keeps a second map: from the description to the handle. This is called interning or a dedup cache.
Dedup is right for immutable objects
Shaders, pipelines, samplers, layouts. Nobody writes into them after creation, so sharing one is the same as having two. It saves memory and creation time; a pipeline can take milliseconds to compile.
Dedup is wrong for mutable objects
Buffers and textures. Two users that ask for "a 1 MiB storage buffer" want two buffers, because each will write its own data. Sharing one would make them overwrite each other.
A field that is left out of the compare makes two different descriptions look equal, and one user silently gets the other's object. A field left out of only the hash is still correct, just slower (more collisions).
Asset loading often uses the same idea one level up: a map from the file path to the handle. Loading the same file twice then gives the same mesh, and the file is read once.
9Pitfalls
- Lookup checks only the index
- Stale handles find the new object: the ABA bug is back. Fix: always compare the generation.
- Slots start at generation 0
- A zero-initialized handle matches slot 0. Fix: start at 1; keep 0 for "invalid".
- Keeping a reference to the object across a create
- The table may grow and move every object; the reference dangles. Fix: look the handle up again after anything that can create.
- Freeing memory the GPU still reads
- Garbage on screen, or a lost device. Fix: deferred destruction, tied to the frame fence.
- Reusing a slot whose index is in a GPU buffer
- The GPU reads the new object for one or two frames. Fix: return the slot to the free list after the fence, too.
- Using a counter as the index (never reusing)
- Simple, and stale handles are found by a hash-map miss. But a table indexed by it grows forever. Fine for objects that are rarely made. Use a free list for objects made every frame.
10In RASM
RASM uses one handle type for every object, Handle in include/rasm/handle.h, with an index and a generation. It has the type-safe tags of section 6. Every table hands out its handles from a HandlePool: the free list and the generation bump of sections 2 and 3.
P4). A destroyed buffer or texture is freed later, when the GPU is done with it: see deferred destruction.Two kinds of owner
CPU objects: Engine's registry
createEntity: registry.entityHandles.allocate() gives {3, 1}, or index 0 when MAX_ENTITIES − 1 entities are alive: then it warns and returns an invalid handle. registry.entities grows to the pool's size. The handle is the position in a vector, as in section 2, and isLive compares the generation.
GPU objects: RenderContext's tables
createBuffer: rhi::Device::createBuffer makes the object first (null on failure: an invalid handle). Then the table's pool gives a handle, and the object goes at its index. destroyBuffer releases the handle at once and frees the object once the GPU is done with it.
| Owner | Type | Limit | Where the limit is |
|---|---|---|---|
Engine registry | Entity | MAX_ENTITIES = 262,144 (218) (262,143 alive at once) | include/rasm/entity.h |
Mesh | no count limit; its sub-meshes take rows of the geometry table (EngineConfig::geometryPoolSubMeshes = 16384) and ranges of the geometry pool | include/rasm/types.h | |
Material | EngineConfig::maxMaterials = 4096 alive at once | include/rasm/types.h | |
Camera | MAX_CAMERAS = 32 (31 alive at once) | include/rasm/renderer.h | |
Light | EngineConfig::maxLights = 16384 | include/rasm/types.h | |
Scene | MAX_SCENES = 16 (15 alive at once) | include/rasm/scene.h | |
Engine readbacks | PendingReadback | no count limit; takeReadback releases its handle | src/renderer/readback.h |
RenderContext tables | buffers, textures, pipelines, ... | no count limit; at most RendererConfig::maxBindlessTextures (16384 by default) textures hold a bindless slot at once | include/rasm/types.h |
Indices start at 1, so slot 0 is never used. That is why a pool with a cap holds one less than its limit: 31 cameras fit in 32. The cap counts live objects, since a released index comes back.
Meshes have no count cap. A mesh is refused only when its sub-meshes do not fit the geometry pool: one row of the geometry table per sub-mesh, and ranges of the vertex and index pools. The whole mesh is checked before anything is created.
EngineConfig::geometryPool* fields. A mesh that does not fit logs what it needs and what is in use. createMesh then returns an invalid handle and uses no index; loadMesh has already returned a handle, so its mesh becomes failed.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Handle layout | index + generation, often packed in 32 or 64 bits | Two separate uint64_t fields: 16 bytes per handle. The C API packs them into one 64-bit id, generation << 32 | index (A stable C ABI). |
| Invalid handle | generation 0 | The same: isValid is generation != 0, so {} is invalid. |
| Type safety | tag types | The same: Handle<Tag> with 23 tags, from MeshHandle to TileHandle. It is the only template RASM code may define. |
| Making a handle | pop the free list, or add a slot | The same: HandlePool::allocate pops the free list (last released, first reused), or adds an index. The stack keeps the indices low, so the tables indexed by handle stay short. |
| Generation bump on destroy | yes | The same: HandlePool::release adds 1. A slot whose generation reaches MAX_HANDLE_GENERATION (232 − 1) is retired, never reused, so every generation fits in 32 bits. |
| Stale handle detection | compare generations | The same: isAlive (also false for a free slot). RenderContext lookups log an error and fail; Engine's public calls check isLive. |
| Storage | slot array, or a slot map | A slot array: a std::vector per type, indexed by index, for CPU objects and for the rhi:: pointers. Render targets are in a std::deque, so a reference survives a new target. |
| Deferred destruction | a delete queue tied to the frame fence | The same: destroyBuffer, destroyTexture and destroyRenderTargets release the handle at once and give the free, and a texture's bindless slot, to a release queue (deferred destruction). |
| Dedup cache | immutable objects only | shaderDescCache, pipelineDescCache, descriptorSetLayoutDescCache. Buffers and textures are always new (B1). |
| Path cache | file path → handle | loadedMeshes (by path) and loadedTextures (by path and format) in the registry. |
The dedup caches
Every creation descriptor in include/rasm/render/resource.h (ShaderDesc, PipelineDesc, BindlessDescriptorSetLayoutDesc, ...) has a defaulted operator==, so equality always compares every field. The hashes are written by hand in src/rhi/resource.cpp. ShaderDescHash hashes the name, the type, the entry point and the SPIR-V bytes; PipelineDescHash hashes the name, the four handles (with HandleHash), the topology, the color and depth formats, the blend mode, depth write and depth test, the sample count and alpha-to-coverage.
Because a pipeline's description holds shader handles, and equal shader descriptions give the same shader handle, two equal pipeline descriptions find each other too.
Two more details
- A texture handle can come before its pixels.
loadTexturecreates the texture and returns its handle at once; the file is decoded in the background.isLoadedsays when it is ready. See Streaming assets in the background. - Swapchain images are texture handles too.
registerSwapchainImagesgives each image a handle, anddestroyTexturerefuses them: they belong to the swapchain.
Where it lives in code
| What | Where |
|---|---|
| The handle, tags, aliases, hash | Handle, HandleHash, hashCombine in include/rasm/handle.h |
| Making handles | HandlePool, HandleSlot in include/rasm/handle.h; src/core/handle.cpp; tests in tests/handleTests.cpp |
| CPU objects | Renderer::Registry in include/rasm/renderer.h; createEntity in src/scene/entity.cpp, loadMesh in src/assets/mesh.cpp, createMaterial in src/assets/material.cpp |
| GPU objects and lookups | RenderContext::Impl, lookup in src/rhi/renderContext.cpp |
| Destroy | RenderContext::destroyBuffer, RenderContext::destroyTexture in src/rhi/renderContext.cpp; Renderer::destroyTexture in src/assets/texture.cpp |
| Dedup caches | createShader, createPipeline, createBindlessDescriptorSetLayout in src/rhi/renderContext.cpp |
| Descriptor hashes | ShaderDescHash, PipelineDescHash, BindlessDescriptorSetLayoutDescHash in src/rhi/resource.cpp |
- A new field in
ShaderDesc,PipelineDescorBindlessDescriptorSetLayoutDescis compared by the defaultedoperator==on its own, but must also be added to its hash insrc/rhi/resource.cpp. - Never add dedup to
createBufferorcreateTexture(B1). Cache at the asset level, and destroy what you replace. - Free GPU objects and bindless slots through the release queue, never at the destroy call.
- A default handle (
{}) means "none". CheckisValidbefore using a handle that a create may have failed to fill.
Every table frees and reuses its indices. A generation never passes MAX_HANDLE_GENERATION: a slot that reaches it is retired, which costs one index after four billion reuses of that slot, and never wraps. loadMesh needs its handle before the file is parsed (it returns at once), so a file that does not parse keeps its index until destroyMesh frees it.
Further reading
- Jason Gregory, Game Engine Architecture, 3rd edition: the chapters on resource management and on handles.
- Scott Bilas, A Generic Handle-Based Resource Manager, in Game Programming Gems (2000): handles with a "magic number" check, the ancestor of the generation.
- The Bitsquid / Stingray engine blog, Building a Data-Oriented Entity System (2014): index plus generation for entities.
- Allan Deutsch, the C++ standards proposal P0661, slot_map (2017): the dense slot map of section 5.