Foundations

Deferred destruction

A program that streams content (map tiles, game levels) destroys textures and buffers all the time. But when the CPU destroys an object, the GPU may still be running a frame that reads it. Deferred destruction splits destroy in two: the name of the object dies at once, and its memory dies later, when the GPU has finished every frame that may use it. This page explains how to know when that is. The last part shows how RASM does it.

In short

  • The CPU is one or two frames ahead of the GPU. An object destroyed in frame n may still be read by frames n − 1 and n.
  • Destroy has two parts. The handle dies now, so no new work can use the object. The memory dies later.
  • "Later" is a fence value: the value the queues signal when the frame that was recorded at the destroy is done. Every queue counts, and so do uploads.
  • A release queue holds what waits. Each frame end gives the new entries their values; each frame start frees the entries whose values the fences reached. Nothing waits on the CPU.
  • What the GPU finds by a number (a bindless slot, a pool range, a table row with one copy) waits too. Data with one copy per frame slot can be reused at once.
  • Freed ranges of a pool go on a free list that joins neighbours. Reuse brings fragmentation: free space split into holes.
  • Users of a destroyed object fall back to a default, objects made for one owner die with it, and what a renderer still draws is refused.
  • When nothing was destroyed, the queue is empty and costs nothing.

1The problem: the GPU is behind

With frames in flight, the CPU records frame 12 while the GPU still runs frame 11. Look at texture T: frame 11 samples it, and frame 12 has already recorded draws that sample it. Now the program destroys T in frame 12.

CPU GPU record 10 record 11 record 12: uses T record 13 run 10: uses T run 11: uses T run 12: uses T destroy T frame 12 done: free T freed at the red line: frame 11 reads freed memory now, and frame 12 later. Garbage, or a lost device. The red line is the destroy call. Two frames still read T after it: the one the GPU runs, and the one being recorded.
The recorded frame matters too: its draws were recorded before the destroy, and they run after it.

Waiting until the GPU is idle at every destroy would work, but it stops the CPU for a whole frame. A program that destroys ten tiles a frame would never overlap the CPU and the GPU again.

2The idea: two deaths

Destroy frees at once

handle T image memory both die at the call the GPU still reads the memory

Simple, and wrong whenever a frame in flight uses the object.

The handle dies now, the memory later

handle T image memory dies now dies when the GPU is done with it

New code can't use T: its generational handle is stale. Old frames still can.

The rule

An object may be freed only when every piece of GPU work that was submitted, or recorded, before the destroy has finished.

3When is "later"? Fence values

A timeline fence is a counter on the GPU. Each submit signals the next value when its work is done, and the CPU can read the counter without waiting (frames in flight). So "later" is a list of values, one per counter that work on the object may be behind:

draws, copies, readbacks signals graphics value v

The graphics queue

The frame's last graphics submit. It covers everything the frame drew.

culling, Hi-Z on compute signals compute value c

Every other queue

Work on a second queue can run after the graphics work. Its own counter says when it is done.

staging copies into it signals upload value u

Uploads

A copy into the object may have been sent after the frame. It must finish before the memory goes.

The values to wait for are the ones the counters signal after the destroy: the end of the frame being recorded. They are not known at the destroy call, only once that frame is submitted. So the frame end hands them out:

  1. destroyThe handle dies. The free waits, with no values yet.
  2. end of the frameAfter the submits: each waiting free gets the values the counters signal last.
  3. the GPU runsThe counters reach those values, one by one.
  4. start of a frameRead the counters; free every entry whose values they all reached.
A frame that is dropped

A frame whose submit failed, or that was never submitted, runs nothing. Its frees take the values the counters signaled last, from the frames before. They cover all work that was ever sent, so the frees are still safe.

4The release queue, step by step

The release queue is a list of frees in order. New ones wait at the back with no values. Since the values only grow, the queue is sorted by them, and the frame start stops at the first entry that is not done.

Frame 12: destroy T

release queue free Tno values yet GPU: runs frame 11 (graphics counter at 10)

The handle of T is stale from now on. The image and its slot stay as they are.

End of frame 12: tag

release queue free Tgraphics 12, upload 40 frame 12 is submitted; it will signal 12

The entry gets the values of frame 12's submits, and the uploads' last ones.

Start of frame 13: not yet

release queue free Tgraphics 12, upload 40 counters read: graphics 11, upload 40. 11 < 12: it stays.

Reading a counter does not wait. The frame goes on.

Start of frame 14: free

release queue empty counters read: graphics 12, upload 40. Free T. Its image is destroyed, its slot can take a new texture.

With two frames in flight, an object is freed about two frame starts after its destroy.

Try it. Destroy a texture, then make a new one, and press "Next frame" until the GPU is done. Then turn the queue off and do the same.

Destroy a texture, then create one: with the queue on, the new texture waits for a free slot. With the queue off, it takes the slot at once, and a frame in flight samples the wrong texture.

5What waits, and what can be reused at once

Memory is not the only thing the GPU finds again later. Anything the GPU looks up by a number must not change its meaning while a frame in flight may look it up.

one image frames 11 and 12 read it

Memory: waits

Buffers, images, the heaps they are placed in.

4 a record says "slot 4"

Numbers with one copy: wait

A bindless slot, a range of a shared pool, a row of a table with one copy.

copy 0 copy 1 CPU writesGPU reads

One copy per frame slot: at once

A row may take a new object now. The frame in flight reads its own copy, which is written only after its fence.

pipeline shared, kept

Shared immutable objects: kept

A deduplicated pipeline or shader may have other holders. They are few, so they live as long as the device.

6Reusing ranges of a pool

A GPU-driven engine keeps all meshes in a few big buffers: one for vertices, one for indices, a table with a row per sub-mesh. A mesh takes a range of each. When meshes only come, a counter at the end is enough. When they also go, the freed ranges must come back, or a streaming program fills the pool in minutes.

1. A, B, C, D in the pool; the rest is free A 8 B 6 C 5 D 9 free 12 40 units 2. B and D are freed: holes, kept in a list sorted by offset A free 6 C free 21 (D and the end joined) 3. C is freed and joins both neighbours; E (14) takes the first range that fits A E 14 free 18 Joining neighbours keeps the list short, so a big mesh still finds one range long enough.
Offsets and sizes in the pool's own unit: vertices, indices, rows or bytes. The same allocator serves every stream.
taken

First fit

Walk the free list from the start; take the first range that is large enough. Simple, and keeps the end free.

taken

Best fit

Take the smallest range that fits. Leaves big ranges whole, but needs the free ranges sorted by size too.

A second index to keep.

Size classes

Round each request up to a power of two, one free list per size. Fast, never searches, but wastes up to half of a range.

Fragmentation is the cost of reuse: the free space is split into holes. A request can fail although the holes add up to more than it needs. Try it: free every other range, then ask for a large one.

Stream ranges in and out and watch the free list. Then free every other range and request a big one: the pool has room in total, but no single hole is large enough.
What to do about fragmentation

Size the pool with room to spare, so a hole is usually found. Keep ranges of one object together, so they go together. Report the largest free range when a request fails, not only the total, or the error looks impossible. Moving live ranges to close the holes (defragmenting) needs every user of an offset to be updated, and is a step most engines take only when a pool is close to full.

7What uses a destroyed object

An object can be destroyed while other objects still name it: a material that entities use, a mesh with entities on it, a texture in a material. There are three answers, and an engine usually mixes them:

entity new obj

Leave it

The user keeps a stale number. If the slot is reused, it uses the new object: the ABA bug, on the GPU.

entity default

Fall back

Users let go and take a default: no material, no texture, nothing to draw. The engine must find them, so it counts them.

mesh materials textures destroyed together

Own it

What an import made belongs to what was imported, and is destroyed with it. Nobody else is expected to keep it.

Refusing is a fourth answer, for objects whose users are few and important: a camera or a scene that a render graph still draws. A clear error that says what holds it is better than a frame that silently draws nothing.

8Pitfalls

Garbage or a lost device a frame after a destroy
The memory was freed while a frame in flight read it. Free through the queue, never at the call.
The wrong texture flickers on old objects for one or two frames
A slot or a range was reused before the frames that knew the old meaning were done. Its release must wait too, not only the memory.
A free that never happens
It waits for a value nothing will signal: taken before the submit, or for a submit that failed. Tag at the end of the frame with the values the counters really signaled last.
Memory grows while the window is minimized
No frame runs, so a queue that is tagged and collected only inside a frame never moves. Between frames nothing is being recorded, so a free may take the values signaled last at once: tag and collect also where a skipped frame still passes.
A copy writes into freed memory
An upload sent after the frame still writes the object. Its counter is one of the values to wait for.
A full pool, although half of it is free
Fragmentation: no single hole is large enough. Join neighbours when freeing, size the pool with room to spare, and report the largest free range.
The frame stalls at a destroy
A wait for the device to be idle at each destroy. Read counters, never wait on them, to decide what to free.

9In RASM

Every object can be destroyed. RenderContext::destroyTexture, destroyBuffer and destroyRenderTargets (and Renderer::destroyTexture, Renderer::destroyBuffer, Renderer::destroyRenderTarget for applications) release the handle at once and give the free to a rhi::ReleaseQueue; the other destroy* calls give it what the GPU reads by number through RenderContext::releaseAfterGpu. Renderer::endFrame tags the queue after submitBatches, and Renderer::beginFrame collects it after the fence wait of the frame slot. Nothing waits on the CPU.

destroyTexture(T) pool: release, generation + 1 T's handle is stale at once ReleaseQueue::release free the image, give back the slot: untagged endFrame submitBatches, then tagReleases values: frameFenceValue, computeFenceValue, the uploads' lastSubmit (a dropped frame too) beginFrame: start, after wait collectReleases reads the 3 fences, never waits every entry whose values all four reached: textureStates.forget, cancelUploads, destroyTexture; the bindless slot goes on freeBindlessSlots, and the next texture that needs a slot takes it
The graphics value covers the frame's compute work, because the frame's last graphics batch waits for it (async compute). The compute value still counts, for a frame whose later batches failed after a compute one went out.

Each destroy call

CallWaits for the GPU (release queue)Reused at onceUsers fall back
destroyEntitynothingits instance rows; its animated row and its ranges of the animation buffers (written as stopped, clip −1, which the passes skip)its scenes rebuild their draw lists without it
destroyMeshits ranges of the five geometry streams, its geometry table rows, its animation pool rangeits indexentities on it draw nothing (searched only while Mesh::users is not 0); its import's materials and textures are destroyed with it
destroyMaterialnothingits row of the material tableentities made with it, and its mesh's sub-meshes, take the entity's or the default material; their rows are rewritten (searched only when something uses it)
destroyTexturethe image and its bindless slotits indexmaterials that use it lose it
destroyLightnothingits row of the light tableits scenes rebuild their light lists; a shadow made for it casts nothing
destroyEnvironmentits image, cubes and four slotsits indexscenes that use it have none
destroyCamera, destroyScenea scene's draw list and light list buffersthe index (the scene's bit in every entity and light is cleared first)refused while a render graph draws a view of them; Renderer::render's graph lets go first

The pools are RangeAllocators (src/core/rangeAllocator.cpp): a std::map of free ranges by offset, first fit, joining neighbours on free. The geometry pool has one per stream and one for its table rows; a mesh takes every range of every sub-mesh before it writes anything, and gives all back if one does not fit. The instance table, the animated entity table's ranges and the animation pool have one each. examples/17_streaming pushes thousands of tiles through pools sized for about two windows of them, and Renderer::getPoolStats stays flat.

Where RASM follows this page, and where it differs

PartThis pageRASM
Handledies at the callThe same: the HandlePool of the object's table bumps the generation, so a lookup with the old handle logs an error and fails (generational handles).
Countersone per queue, and the uploads'RELEASE_TIMELINES = 4: frameFence, computeFence (only with async compute), the frames' upload fence and the loads' upload fence (on the transfer queue, transfer queues).
Tagat the end of the frametagReleases in endFrame, right after submitBatches, also when the frame was dropped.
Collectat the start of a frame, by reading the countersbeginFrame tags and collects first thing, before it may skip the frame (a minimized window), and collects again after the slot's fence wait. With nothing tagged it returns at once.
Freea free function per entryA std::function per entry, in order. RenderContext::cleanup waits for the device and runs them all (releaseAll).
Bindless slotswait like memoryThe same. A texture holds one slot; its destroy gives it back through the queue, and updateBindlessDescriptorSet takes freed slots first. Bindless resources has the details.
Materials that use a destroyed texturemust stop using its slotRenderer::destroyTexture removes the texture from every material that has it and rewrites their rows, so the slot samples nothing before it is reused.
Per-slot table rowsreusable at onceThe rows of a GpuTable (instances, materials, lights, animated entities) have one copy per frame slot, written only in syncGpuScene after the slot's fence.
Range allocatorfirst fit, best fit or size classesFirst fit over a std::map, neighbours joined. No defragmenting: a refused mesh logs every stream's use and the largest free ranges.
Usersleave, fall back, own or refuseFall back for entities, materials and textures; own for a glTF import's materials and textures; refuse for cameras and scenes a graph draws. Counted: Mesh::users and Registry::materialUsers, so the usual order (entities first) searches nothing.

Code map

WhatWhere
The queue: release, tag, collect, releaseAllsrc/rhi/releaseQueue.h, src/rhi/releaseQueue.cpp
Deferred frees of textures, buffers (also the old buffer of resizeBuffer), heaps and storage slots; tagReleases, collectReleasessrc/rhi/renderContext.cpp
Tag and collect in the frameRenderer::endFrame, Renderer::beginFrame in src/renderer/renderer.cpp
Destroy callsdestroyTexture in src/assets/texture.cpp, destroyMesh in src/assets/mesh.cpp, destroyMaterial in src/assets/material.cpp, destroyEnvironment in src/assets/environment.cpp, destroyEntity in src/scene/entity.cpp, destroyLight in src/scene/light.cpp, destroyCamera in src/scene/camera.cpp, destroyScene and the remove*FromScene calls in src/scene/scene.cpp
RangesRangeAllocator in src/core/rangeAllocator.cpp; GeometryPool::allocate, write, free; releaseEntityRows in src/renderer/gpuScene.cpp; releaseEntityAnimation, releaseMeshAnimation in src/renderer/animation.cpp
A user: Dear ImGui's texturesreleaseUiTexture in src/renderer/ui.cpp
Unit teststests/releaseQueueTests.cpp, tests/rangeAllocatorTests.cpp
Example: tiles streamed in and out around a moving cameraexamples/17_streaming
Rules to keep

Never free a GPU object, a bindless slot or a shared range at the call that destroys it: give the free to the release queue. Never wait on a fence to decide what to free. A table with one copy per frame slot is written only in its slot's frame, so its rows need no queue.

Still open: graph teardown (releaseSceneView), re-placing transient render targets and growing the animation buffers still wait for the GPU (D35). No pool is defragmented.

Further reading