GPU data

Streaming assets in the background

Reading a model or a texture from disk can take hundreds of milliseconds. A frame has about 16. So an engine loads assets on other threads, while it keeps drawing, and brings each one in when it is ready. This page explains how that works: workers, the hand-off to the main thread, a time budget per frame, what to show until the data arrives, caching, failures, and when to free memory. The last part shows how RASM does it.

CPU work (main thread or worker) GPU work memory: buffers, results, caches

In short

  • A load call returns a handle at once. The object is in the loading state until its data is in.
  • Worker threads read and decode the file. They work on their own memory and never touch the renderer's state.
  • The main thread picks up finished results at one fixed point in the frame. Only it creates GPU objects and makes the asset visible.
  • A budget per frame (time or bytes) limits how much it picks up, so many loads that finish together do not make one long frame.
  • Until the data is in, the engine shows nothing, a placeholder, or a low-detail version.
  • Loads are cached by path, so one file is loaded once. A failure is a state, not a crash.
  • After the upload, the CPU copy is usually not needed. Free it.

1Why not load on the main thread

The main thread runs the frame loop: input, game logic, and recording the GPU's work. If it stops to load a file, no new frame is made until the load is done. The picture freezes.

All on the main thread main thread read + decode + upload: 300 ms no new frame for 300 ms: the picture freezes With a worker thread main thread worker read + decode: 300 ms this frame picks up the result
Each small box is one frame of about 16 ms. With a worker, the frames keep coming while the file loads. The object appears a few frames after the load ends.

Not every part of a load can move to another thread, though. To see which parts can, split the load into its steps.

2What a load is made of

A load is five steps in a row. The first three are most of the time, and they only need the file and some memory.

  1. Readfile bytes from disk
  2. Parse, decodeJSON, PNG, JPEG…
  3. ProcessLODs, mips, tangents
  4. Uploadcopy to GPU memory
  5. Publishmark it ready

Can run on a worker: plain data in, plain data out

file on disk 89 50 4E 47 … bytes in memory

Read

Only a file name and a byte array. Any thread can do it.

Bottleneck: the disk

89 50 4E … bytes pixels

Parse, decode

A pure function of the bytes. Any thread can do it, if the library has no global state.

Bottleneck: the CPU

mip 0, 1, 2, 3: built from the image

Process

Same as decode: plain data in, plain data out. It builds what the renderer wants: coarser versions of a mesh, the smaller mip levels of a texture, missing normals.

Bottleneck: the CPU

Usually the main thread: graphics API and engine state

CPU decoded data the bus GPU buffer, texture

Upload

It creates GPU objects and records copies. Graphics APIs let several threads do this, but each command buffer and pool belongs to one thread at a time. Many engines keep it on the main thread, which is simpler.

Bottleneck: the bus to the GPU

mesh 5ready mesh 6ready mesh 7loading → ready the engine's table

Publish

It changes the engine's tables, which the main thread reads all the time. Doing it at one fixed point avoids locks.

Bottleneck: nothing

3Worker threads and job queues

A worker is a thread that runs jobs given to it by another thread. A job here is "load this file": it gets a path and returns the decoded data. There are three common ways to run them.

Main thread load(a), load(b), … Job queue c d e f worker 1: job a worker 2: job b worker 3: idle Done queue finished results wait here the main thread takes them out, once per frame
A thread pool with two queues. The queues are the only things both sides touch, so only they need a lock.
100 loads: up to 100 threads 4 CPU cores

One task per load

Start a new task (a thread, or a library task like a future) for each load. The task's result is the hand-off.

Good: very little code. No queue to write.

Bad: 100 loads at once start up to 100 threads, which fight for the CPU and the disk. No order, no priorities, hard to cancel.

job queue worker worker worker

Fixed thread pool with a job queue

A few threads (often the core count minus one or two) take jobs from a shared queue.

Good: the CPU is never oversubscribed. The queue can be sorted by priority (near objects first), and a job can be removed before it starts.

Bad: more code: the queue, its lock, and shutting the threads down.

OS reads the file bytes worker decodes only no thread waits on the disk

Asynchronous I/O plus a pool

The OS reads the file in the background (overlapped I/O, io_uring); only decoding uses a worker.

Good: no thread waits on the disk.

Bad: platform-specific code.

A pool also lets one load split into smaller jobs (one per image of a model), and hold loads back when their decoded data would not fit in memory. Job systems and worker pools explains both, and how a job waits for its parts without blocking a worker.

4The hand-off between threads

The worker and the main thread run at the same time. If both touch the same data, the result depends on timing: a data race. The safe pattern is that data moves between threads and is never shared. The worker gets a copy of what it needs (a path, some options), builds its result in its own memory, and hands the whole result over in one step. Click through one load (or use the arrow keys).

1. The request returns at once

main thread worker GPU frame 1 load(path) frame 2 frame 3 frame 4 frame 5 job: the path returns a handle at once, state: loading

The caller can use the handle right away, for example to place the object in the scene. The renderer knows the object is not ready and skips it.

2. The worker decodes; frames go on

main thread worker GPU frame 1 load(path) frame 2 not ready: go on frame 3 not ready: go on frame 4 not ready: go on frame 5 read · decode · process in the worker's own memory

Each frame asks "is it done?" without waiting. That check must be cheap and must never block.

3. The result waits

main thread worker GPU frame 1 frame 2 frame 3 frame 4 not ready: go on frame 5 read · decode · process result waits in a slot

Once it has handed over its result, the worker forgets it. Nothing in the engine has changed yet, so there is no race.

4. The main thread picks it up

main thread worker GPU frame 1 frame 2 frame 3 frame 4 frame 5 create, upload, mark ready read · decode · process result

This happens at one fixed point, usually the start of the frame, before anything reads the engine's tables. So the new asset is either fully in for the whole frame, or not at all.

5. The GPU copies it, then draws it

main thread worker GPU frame 1 frame 2 frame 3 frame 4 frame 5 submit read · decode · process copies draws, with it

The copies are recorded before the draws that use them, with a barrier between, so the same frame can already draw the asset. See GPU memory and GPU synchronization.

the worker's own memory path (copy) options (copy) its result thread-safe libraries

What the worker may touch

Its inputs (copied in), its own memory, and thread-safe libraries.

worker ✗ ✗ ✗ the engine's tables the graphics device main-thread data

What it must not touch

The engine's tables, the graphics device, or anything the main thread may change.

Libraries with global settings

Careful with libraries that keep global settings: an image loader with a global "flip vertically" switch gives different results depending on which thread set it last.

Shutting down

When the program exits while a load runs, the worker still writes into memory that the program is about to free. So shutdown must first wait for (or cancel) every running job, and then free what the finished ones returned.

5A budget per frame

Workers finish at random times. Often many finish together, for example when a level starts. If the main thread picked them all up in one frame, that frame would be long again: the freeze from section 1, only shorter. So the main thread works under a budget: it picks up results until the budget is used, and leaves the rest for the next frame.

budget: 4 ms 0 ms frame A 4 results ready result 1 result 2 started before the line over budget: 3 and 4 wait · the rest of the frame frame B 2 results left result 3 result 4 nothing left · the rest of the frame
A time budget of a few milliseconds per frame. Each result here takes 3 ms to finish on the main thread. Before each result the main thread asks: is the budget used up? Then it stops. A result that has started always finishes, so a frame can go a little over.

The budget can count different things:

4 ms the rest waits time in the frame →

Time

Stop when the clock passes the limit.

Follows the real cost. One big item can still go over, because work is not split.

N MiB bytes uploaded →

Bytes

Stop after N MiB of uploads.

Predictable for the bus and the staging memory. Ignores CPU work such as building mips.

1 2 3 N = 3: large and small count the same

Count

Stop after N items.

Simplest. A large and a small texture count the same.

take everything, wait for the rest draw a loading screen

No budget

Take everything that is ready, and wait for the rest.

For a loading screen: the first frame shows the full scene.

Worked example

30 textures finish at the same moment. Finishing one on the main thread (creating it, copying it, building its mips) takes 3 ms. The frame rate is 60 Hz, so a frame is 16.7 ms.

90 ms of loading one frame: over 100 ms each box is one frame; its width is its time

No budget

30 × 3 = 90 ms of main-thread work, in one frame. One frame takes over 100 ms: a visible hitch of about 5 frames.

15 frames, 6 ms of loading in each all 30 are in after 0.25 s

4 ms, checked before each texture

A texture starts at 0 ms and at 3 ms, so 2 textures = 6 ms per frame. Every frame stays smooth. All 30 are in after 15 frames, 0.25 s.

Play with it. The picture below loads 30 textures. Reading and decoding one takes 100 ms; finishing it on the main thread takes 3 ms, as above. A frame's own work takes 10 ms here, so 6.7 ms are free for loading.

CPU work: a worker reads and decodes; a frame's own work ready, waits for the main thread in the scene loading work in a frame a frame that is too long
The clock runs slower than real time. Try the three ways to load. With workers and no budget, raise the number of workers until a frame goes over the line. Then turn the budget on, and find the largest budget that keeps every frame on time.

A smaller budget gives smoother frames, but the scene fills in more slowly. A big item that cannot be split, such as one huge texture, needs to be split into pieces (one mip level or one tile at a time) to stay under the budget.

6What to show until the data arrives

Four ways to show an object that is still loading. The grid lines stand for texture detail: a placeholder has none, a small mip a little, the full texture all of it.

not drawn

Hide it

Simple, and it never looks wrong. Things pop in late.

white texture

Placeholder

The shape is there at once. Its surface changes later.

Low detail first

Small mips or a coarse mesh first, sharper later.

Full

All data in.

Which one is right depends on the program. A game behind a loading screen hides things. An open world or a map viewer shows something early and refines it.

What is one unit?

An object often needs a mesh and several textures. Each part can appear on its own, or the object can wait until all parts are in:

mesh only + color + normal map frame 1 frame 2 frame 3

Each part on its own

The object can show up with a wrong surface for a few frames, for example without its normal map.

waits waits all parts frame 1 frame 2 frame 3

All parts together

No half-loaded look, at the cost of a little more delay.

A placeholder must be ready before anything can use the asset

When a material points at a texture whose pixels are not there yet, and the renderer may sample it, the texture must hold something defined: a plain color, not uninitialized memory.

7Caching by path, and failures

The same file is often requested many times: a tree model used by a thousand trees, a texture shared by many materials. The loader keeps a cache: a map from the file's path to its handle. A second request returns the first handle, also while the first load still runs.

models/tree.glb ./models/../models/tree.glb normalize full path, no "." or ".." cache: key → handle /game/models/tree.glb → 7 both requests get handle 7 not loaded load loading success error ready failed load again: retry drawn never drawn, error logged
The key must be normalized, or two spellings of one file load it twice. If the same file can be loaded in two ways (for example a texture as color data and as plain data), that choice belongs in the key too.

Errors come in two kinds, and they reach the caller in different ways:

load(path) at once invalid handle no job starts

Early

The file does not exist, the file type is not supported, bad arguments.

Found in the load call, before any job starts. The caller learns it from an invalid handle, at once.

load(path) handle: loading later decode or pick-up fails failed

Late

The file is corrupt, the decoder fails, there is no GPU memory left for it.

Found on the worker, or when the main thread picks it up. The caller learns it when the handle's state becomes failed; the caller can ask for it.

Should a failed path stay in the cache?

Keep it as "failed"

Every later request fails fast, which is cheap.

Let a request retry

A file that was fixed on disk loads on the next try.

No half-made assets

Either way, a failure must never leave a half-made asset behind: check that everything fits (memory, table slots) before creating the first part, or undo the parts on failure.

8Freeing the CPU copy

During a load the same data exists several times. Most copies are only needed for a short time.

CPU memory GPU-visible memory
time → read decoded uploaded GPU copy done file bytes decoded data kept by mistake staging copy GPU copy
Each copy can go as soon as the next one exists. The one exception is the staging copy: it can be reused only after the GPU has finished reading it, which a fence tells the CPU (see GPU synchronization).

The decoded data is the big one:

16 MiBone decoded 2048 × 2048 RGBA texture2048 · 2048 · 4 bytes
21.3 MiBthe same texture with all its mips
2×the memory of a program that keeps every decoded texture after the upload, for nothing

Keep a CPU copy only when the CPU really reads it later:

KeepBecause
positions and indices, as a separate copyphysics, ray picking, CPU culling of individual triangles
small metadata: sizes, bounds, ranges in the GPU buffersthe renderer needs them every frame
nothing elseif the GPU copy is lost, load the file again

9File formats, just enough

Two common mesh formats need different work before the data is GPU-ready:

glTF: bytes, then views, then accessors buffer: raw bytes (.bin or inside .glb) buffer view offset, length, stride xyz xyz xyz xyz xyz xyz stride accessor: VEC3 float × 2400 primitive: POSITION = accessor 3 OBJ: three indices per corner f 1/1/1 2/2/1 3/3/1 position / UV / normal, each its own list positions UVs normals one GPU vertex per triple The GPU has one index per vertex, so each distinct (position, UV, normal) triple must become one vertex.
glTF is close to what the GPU wants already: typed arrays in binary buffers, plus a node tree with transforms, materials and images (PNG or JPEG, decoded by the loader). In the enlarged view, blue is the accessor's data and grey is another attribute stored between its elements, so the stride is larger than one element. OBJ is text and must be rebuilt into vertices. A simple OBJ loader makes one vertex per face corner and merges equal ones afterwards.
glTF data is not aligned
A float may start at any byte. Read it with a byte copy, not a pointer cast.
A glTF buffer view has a stride
Attributes can be interleaved. Element i starts at offset + i × stride, not i × element size.
OBJ and glTF put the UV origin in different corners
OBJ's v runs up from the bottom; images and glTF start at the top. Flip one of them (v' = 1 − v).
Paths with non-ASCII characters
Some C libraries open files in the system's code page. Open the file yourself (as UTF-8 or wide characters) and pass the bytes or a stream.

10In RASM

RASM loads meshes, textures and environments as jobs on one pool of worker threads, under a memory budget (job systems explains the pool). The main thread picks up the finished results at the start of each frame, inside a 4 ms budget. An entity is drawn only when its mesh and all its textures are in.

main thread · the app's call loadMesh(path) cache, checks, handle: LOADING workers · WorkerPool parseMeshFile then a job per image and LODs MeshLoadJob: GLTFRaw ticket DONE, in pendingMeshes main thread · every beginFrame finishLoads(false) ready ones only, 4 ms budget finishMeshLoad fit check · materials · upload geometry pool + the model's textures mesh READY, CPU copy freed on a worker syncGpuScene waiting entities join draw lists drawn this frame copies go out with the submit loadTexture and loadEnvironment work the same way: a decode on the worker, a finish… on the main thread.
The jobs get a path and write a plain GLTFRaw. Everything that touches the renderer runs in the AssetLoader's finishLoads, which the renderer's beginFrame calls through LoadHooks before anything binds the geometry pool or the bindless set. The loader lives in the rasm library, the renderer in rasm::renderer: the renderer only knows the hooks, and an application without a loader links none of the file libraries.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Workersa thread pool with a job queue, or one task per loadOne WorkerPool per AssetLoader, of AssetLoaderConfig::loadThreads threads (0: the hardware threads minus one), FIFO, a glTF's images and LODs as child jobs that run first. A load starts only when its bytes fit AssetLoaderConfig::loadMemoryBudget (an Engine takes both from its EngineConfig). Destroying a loading object drops its load. No priorities (job systems).
Hand-offa result slot, checked without blockingA MeshLoadJob, TextureLoadJob or EnvironmentLoadJob that the jobs write and PendingMeshLoad or PendingTextureLoad holds; its LoadTicket state turns DONE, an atomic the main thread reads without blocking. A glTF's textures wait in PendingTextureLoad with their levels already made (levels), so they are ready at once. Job code (parseMeshFile, runImageWork, buildMeshLods, decodeTexture, buildTextureLevels) never touches the engine.
When results are picked upone fixed point per frameThe start of beginFrame, before the minimized-window check, so loads also finish while the window is minimized.
Budgettime, bytes or countTime: LOAD_BUDGET = 4 ms, checked before each result. Meshes, then environments, then textures, at least one part of a texture per frame. A glTF file's finishMeshLoad creates its textures and queues their fills as texture results of their own, so a big model's copies spread over frames (texture uploads), and a texture is filled in 4 MiB parts. One step is never split: a model's geometry goes in one finishMeshLoad (P24). waitForLoads takes everything, with no budget. The decoded data that waits holds part of the load workers' memory budget until it is used.
Uploadthrough staging memoryGeometry (vertices, indices, and the streams only some meshes have: colors, skin weights, morph deltas) and animation data: the pools are BufferDesc::staged, so on a discrete GPU fillBuffer puts the data into a 64 MiB staging ring (on an integrated GPU it writes straight into the pool), and the copies go out at once on the transfer queue, or on the graphics queue without one (see transfer queues). A mesh and a texture count as loaded only once their copies are on the GPU, so the frames never wait for them. Textures: fillTexturePart copies through the same staging ring, or on the host (host image copy) where that costs the GPU nothing. Every level comes from the worker: an image's mips are made there (buildTextureLevels), a KTX2 file brings its own (texture compression), so the main thread only copies. The longest frame while the Flight Helmet loads is 5 ms as KTX2 and 9 ms as PNG, against 28 and 206 ms when the mips were made on the main thread and a model's textures were copied in one frame (Release, RTX 3060; texture uploads).
Placeholdershide, placeholder, low detail firstHide: an entity waits in entitiesWaitingForMesh, then in entitiesWaitingForTextures, until its mesh and every texture of its materials are in. No low-detail-first. A texture whose decode fails is filled white, because a material may already use it.
Cachenormalized path → handleresolveAssetPath joins the path to AssetLoaderConfig::assetRoot and normalizes it. Meshes: loadedMeshes, by path. Textures: loadedTextures, by path and format. glTF images: GltfImportCache, once per image, sampler and color space, per model.
Failuresearly or late; fail fast or retryEarly (missing file, unsupported extension, out of handles): invalid handle. Late (decode fails, a pool is full): MeshState::FAILED. Loading a failed path again retries, on the same handle, and destroyMesh frees it. GeometryPool::allocate takes every range of every sub-mesh, and the animation pool's largest free range (EngineConfig::animationPoolBytes) is checked, before anything is created, so a mesh that does not fit takes nothing.
Freeingfree the CPU copy after uploadglTF buffers go on the worker, once every accessor is read. The vertex, index, LOD, skin and morph arrays, the animation keys and the glTF model go at the end of finishMeshLoad. The decoded pixels go on the worker once their mips are made (stbi_image_free in decodeTexture and runImageWork; a glTF's image file bytes in finishImageWork), and the levels when their texture is filled (P6). Nothing is kept for the CPU.
FormatsglTF and OBJglTF through tinygltf, OBJ through tinyobjloader. An OBJ file becomes one sub-mesh with one vertex per face corner and no material; buildMeshLods merges equal vertices later. OBJ's v is flipped.

Textures: two ways in

loadTexture

The main thread reads only the image header (stbi_info) and creates the texture at full size at once, so a material can use the handle before the pixels exist. The worker runs decodeTexture (stbi_load, always 4 channels, then every mip with buildTextureLevels). finishTextureLoad copies the levels and sets texturesFinished, so syncGpuScene checks the waiting entities.

Images inside a glTF file

tinygltf keeps each image's file bytes. Each image a material reads is a job of its own (runImageWork): it decodes the image to RGBA once and makes its mips, once per kind of slot (a normal map's are renormalized), on any free worker. loadMaterial creates each texture inside finishMeshLoad and queues its fill in pendingTextures; isLoaded(mesh) waits for them.

Where it lives in code

WhatWhere
Mesh loadsAssetLoader::Impl::loadMesh, finishMeshLoad in src/assets/meshLoad.cpp; Renderer::createMesh, isLoaded in src/assets/mesh.cpp
Texture loadsAssetLoader::Impl::loadTexture, decodeTexture, finishTextureLoad in src/assets/textureLoad.cpp; the renderer's loadingTextures, which Renderer::isLoaded and the waiting entities read
Worker poolWorkerPool, LoadTicket in src/core/workerPool.cpp; the load jobs, runMeshImport in src/assets/meshLoad.cpp, MeshLoadJob in src/assets/loadJobs.h (job systems)
Worker importparseMeshFile, importGltf, importObj, runImageWork, finishImageWork in src/assets/meshImport.cpp; animations, skins and morph targets in src/assets/animationImport.cpp, src/assets/skinImport.cpp, src/assets/morphImport.cpp
glTF materials and imagesAssetLoader::Impl::loadMaterial in src/assets/materialImport.cpp; the images' work, planImageLevels and planKtxImages in src/assets/meshImport.cpp
Mips on the workerbuildTextureLevels in src/rhi/mipChain.cpp (texture uploads)
Budget and pick-upfinishLoads, finishReadyLoads, waitForLoads, LOAD_BUDGET, resolveAssetPath in src/assets/assetLoader.cpp; the hooks, LoadHooks in src/renderer/loadHooks.h
Pending loadsPendingMeshLoad, PendingTextureLoad, pendingMeshes, pendingTextures in AssetLoader::Impl, src/assets/assetLoaderImpl.h
Result types and statesGLTFRaw, ObjRaw in src/assets/meshData.h (private); MeshState in include/rasm/mesh.h; TextureRaw in include/rasm/types.h
Fit check and appendGeometryPool::fits, GeometryPool::upload in src/renderer/geometryPool.cpp; Renderer::uploadMeshAnimation in src/renderer/animation.cpp
Entities that waitsyncGpuScene in src/renderer/gpuScene.cpp
Staging ringUploadManager in src/rhi/uploadManager.cpp
APIloadMesh, loadTexture, waitForLoads
Keep these true
  • Worker code gets a path and returns a plain result. It must not touch the renderer, the registry or the device.
  • Anything that creates GPU objects, writes the registry or fills a buffer for a load runs in finishLoads, on the main thread.
  • Check that the whole mesh fits (GeometryPool::fits, the animation pool) before creating any part of it.
  • A texture a material may already use is always filled, even when its decode fails.
  • Free the CPU copy after the upload (P6). Do not keep vertex arrays, the glTF model or pixels in the registry.
  • Shutdown drops every pending load and joins the workers, in ~AssetLoader, which runs before the renderer goes (an Engine holds its loader as a member). A job holds its load's job struct by shared_ptr, never the engine.
  • Every byte a load takes from the budget goes back once: by the main thread when it uses or drops a done result, by the job when it ends dropped.
  • The main thread makes no mips for a load: the worker hands over every level.
Not done yet

No priority per load: the queue is FIFO. A tile streamer ranks whole tiles instead, and keeps few loads in flight, so the FIFO matters little there. A model's geometry and each texture are finished in one step, however big (P24). A 16-bit image loads as 8 bits (D36). A texture, mesh or environment can be destroyed while it loads: its load is dropped (a queued job never runs), and a mesh's pool ranges come back (deferred destruction).

Further reading