GPU data

Texture uploads

A PNG on disk is a few megabytes. In video memory the same texture is a chain of mip levels, in a tiled order only the GPU knows. This page follows a texture through the four steps that get it there: decode, make the mips, reorder the texels, place them in memory. It compares the two ways to do the copy (a staging buffer, or host image copy), the places a program can make the mips, and how many textures share memory. The last part shows how RASM does it.

In short

  • Four steps: decode the file, make the mips, reorder the texels into the GPU's tiling, put them in video memory. Only the last two need the GPU or its driver.
  • Staging: the CPU writes rows into a buffer, and a GPU copy command tiles them into the image. It works everywhere.
  • Host image copy (Vulkan 1.4): the driver tiles on the CPU, with no command buffer. It is good only where the image can live in the same memory as any other texture, and keeps the GPU's best layout. Ask the device both.
  • Mips can come from the file, a CPU worker, GPU blits or a GPU compute pass. Filter color in linear light, weight it by alpha, and make normals unit length again.
  • Thousands of textures should share a few large memory blocks (sub-allocation): a separate allocation per texture is slow to make and slow to free.
  • A model's textures are many megabytes: copy them a few per frame, not all in one frame.

1Four steps from file to GPU

Follow one 2048 × 2048 color texture. Two steps are plain CPU work on bytes; two need to know the GPU.

plain CPU work · any thread needs the GPU or its driver file PNG, JPEG 3 MB 1 decode rows, 16 MiB 2 mips + a third: 21.3 MiB 3 reorder tiles, not rows 4 place video memory sampled by shaders for many frames The texture is read every frame for minutes; it is written once. Any cost at load time is fine, a slower read is not.
Steps 1 and 2 need no GPU, so a worker thread can do them. Steps 3 and 4 are the upload: a copy command, or the driver on the CPU. A block-compressed file (KTX2) skips step 2: it stores its mips.

2Two ways to reorder and place

The CPU cannot write the tiled order itself: it is the vendor's secret. Two paths hand the rows to someone who knows it.

Staging copy

CPU writes rows staging buffer image tiles copy command barrier, copy, barrier: in a command buffer the buffer is reused once the GPU is done

Works on every GPU and every format. Costs a command buffer, barriers, a fence before the buffer is reused, and a little GPU copy time.

Host image copy

CPU calls the driver tiles on the CPU image tiles layout change and copy: host calls ready when the call returns

Vulkan 1.4 (VK_EXT_host_image_copy before). No staging memory, no commands. The CPU must be able to write the image's memory, which is the catch (next section).

3Where a host-copied image may live

The CPU writes a host-copied image directly. So the driver may allow such an image only in memory the CPU can reach. Each image asks for a set of memory types (a bit mask). Compare the set of an image filled by a copy with the set of the same image made for host copy. This is a real discrete GPU with resizable BAR:

heap 0 · video memory, 12 GiB heap 1 · system RAM, 16 GiB type 1 device-local type 2 device-local type 5 + host-visible (BAR) type 0 none type 3 host type 4 host, cached image filled by a copy: 1, 2 made for host copy: 3, 4, 5 The two sets share no type. A host-copy image goes to type 5 (video memory, reached through the BAR) or to system RAM. Without resizable BAR, type 5 is a 256 MiB heap of its own, which fills fast. Measured on this GPU with BAR: while a model's textures load by host copy, the GPU stalls for 50 to 185 ms. The same textures through staging: no stall.
An RTX 3060 (driver 610), from vkGetDeviceImageMemoryRequirements with and without the host-transfer usage. On lavapipe there is one memory type, and both sets are that type.

So a program should ask the device, per format, before it picks host copy:

  1. Featurethe device has host image copy
  2. Formatit lists host image transfer
  3. Best layoutthe GPU reads it as fast as any image
  4. Copy layoutthe shader-read layout is allowed
  5. Memorya device-local type both sets share

If any answer is no, the format uses staging. A device without the feature then still starts and draws: it only loses a shortcut. In Vulkan the checks are the hostImageCopy feature, the format's host-image-transfer feature bit, optimalDeviceAccess in VkHostImageCopyDevicePerformanceQuery, pCopyDstLayouts, and the memory type bits.

Pick a kind of GPU and see which memory types each image may use. Turn off "keeps its best layout" to see the second check. Find a device where host copy is safe, and one where it would cost the GPU.

4Where to make the mips

A full mip chain adds a third to the texture. Each level is the one above, half the size, filtered. Four places can make it:

.ktx2 every level made by a tool, once

In the file

KTX2 and DDS store the levels, already block-compressed. Best quality and no load-time work.

Needs an offline tool step.

worker decode → level 1 → 2 → … main frames keep their pace any filter, exact control

A CPU worker

Same code on every GPU and API. Any filter: linear light, alpha weighting, renormalized normals.

About 10 ms of CPU per 2048² texture; a third more bytes to copy.

blit, linear filter a 2 × 2 box per level

GPU blits

A few commands, almost no GPU time. The filter is a fixed box; colors are not weighted by alpha, and normals are not renormalized.

Vulkan and Metal have blits; D3D12 and WebGPU do not.

compute any filter, on the GPU needs a storage view

GPU compute

Fast and any filter. The image needs storage usage, and an sRGB image a second, UNORM view.

Storage usage can turn off the GPU's texture compression (AFBC, DCC): slower reads for the texture's life.

Filter what the numbers mean

A mip is an average. What to average depends on the texture:

128 188 sRGB numbers are not light: decode, average, encode

Color: linear light

Decode sRGB to light, average, encode again. Averaging the stored numbers darkens every edge.

dark rim leaf a transparent texel has no color: weight colors by alpha

Cut-outs: weight by alpha

A transparent texel's color is never seen, so it must not count. Without the weight, leaves get dark rims far away.

mean: 0.71 long renormalized: 1 x, y, z each from 0..255 → −1..1

Normal maps: renormalize

Average the directions, then make each unit length again, so every level stores a direction. A two-channel map (z rebuilt from x and y) needs it most.

5Many textures, few allocations

A scene has hundreds of textures; a streaming map has thousands over its life. Giving each its own device allocation is simple, but each allocation is an OS call, drivers limit how many exist, and freeing one can take milliseconds.

One allocation per texture

vkAllocateMemory per texture a free can take ms; a count limit

Sub-allocated

one block, many textures make and free: a range in a list

Keep a dedicated allocation for the few large render targets that a driver asks to have one. The block size also changes what "memory in use" means: the OS counts whole blocks, so count the bytes of the textures inside them too.

6Pitfalls

Far textures look too dark, edges have dark lines
The mips averaged sRGB numbers, not light. Filter sRGB textures in linear light.
Leaves and fences get dark or bright rims in the distance
The mips averaged the hidden color of transparent texels. Weight color by alpha.
Bumps look flat or bright far away
Averaged normals are shorter than 1; a two-channel map rebuilds a wrong z from them. Renormalize each mip.
Loading a level freezes one frame for 200 ms
Mips are made on the main thread, or all of a model's textures are copied in one frame. Make mips on a worker, and copy a few textures per frame.
Frames drop while textures load, the CPU is idle
The GPU stalls on host-copied images in special memory. Use host copy only where the image can use the same memory types as a copied one.
A GPU without host image copy cannot start the program
The feature was required. Make it optional: the staging path serves every device.
Destroying a big model makes one long frame
Each texture had its own allocation, and each free is an OS call. Sub-allocate.

7In RASM

The worker decodes and makes every level; the main thread only creates the texture and copies the levels, in parts of 4 MiB under a budget per frame; the device copies through the staging ring, on the transfer queue where there is one, unless host copy is safe for the format. The texture counts as loaded once its copies are done (transfer queues).

worker thread decodeTexture or runImageWork PNG, JPEG → RGBA8 rows buildTextureLevels sRGB, alpha weights, normals TextureRaw every level in one block main thread · finishLoads, every frame pendingTextures, filled in 4 MiB parts until LOAD_BUDGET (4 ms): tex 1 tex 2 4 ms: next frame tex 3 tex 4 fillTexturePart copies only staging ring → copy, transfer queue UploadManager::uploadTexture host copy, where it is safe VulkanDevice::fillTexture either way into a VMA block shared with other textures
A glTF's textures are created with its mesh in finishMeshLoad and wait in pendingTextures with their levels; loadTexture's wait for their worker. finishLoads fills both kinds after the meshes, under the same budget.

Where RASM follows the page, and where it differs

PartThis pageRASM
Decodea workerdecodeTexture (stb_image) for loadTexture; runImageWork for a glTF's images, one job per image, so a model's images decode and get their mips on several workers at once (job systems). Every job runs on the engine's WorkerPool.
Mipsfile, CPU worker, GPU blits or computeKTX2: from the file (or made on the worker for a Basis file without them). PNG and JPEG: buildTextureLevels on the worker, with stb_image_resize2's default filter (Mitchell), each level from the one above. GPU mip generation is not used: it would need storage usage on every texture, and blits have no alpha weighting.
Filteringlinear light, alpha, renormalizeR8G8B8A8_SRGB: linear light, alpha-weighted. R8G8B8A8_UNORM: the stored numbers. A glTF normal texture (KtxSlot::NORMAL): renormalized; loadTexture does not know the slot, so it does not renormalize.
Copystaging or host copyHost copy only for a format where VulkanDevice::queryFormatSupport found the feature, host transfer, optimalDeviceAccess, SHADER_READ_ONLY_OPTIMAL among the copy layouts, and a device-local type in both sets (getHostCopyMemoryTypes); the image is then made with only those types. Every other format, and every format with EngineConfig::hostImageCopy false, goes through the staging ring. The log says which: Host image copy: off on the RTX 3060, and on for 13 formats on lavapipe.
Per framea few textures per frameEach texture is its own entry in pendingTextures, filled after the meshes inside LOAD_BUDGET, in parts of 4 MiB (RenderContext::fillTexturePart, TextureFillProgress), at least one part per frame, the textures begun first; a part stops at a full staging ring instead of waiting. The longest frame while the PNG Flight Helmet loads is 5 ms (9 ms with a texture in one go). A glTF texture whose fill fails is taken out of its materials, which then read their defaults. A texture is loaded once its last part's copies are done; isLoaded(mesh) is true once its glTF's textures are (transfer queues).
Memorysub-allocate, dedicated for big targetsSampled textures are sub-allocated by VMA, with no host-access flags. Attachments and storage textures keep a dedicated allocation. VRAMStats::vramAllocated counts the bytes of the allocations, vramUsage the whole blocks.
App-filled textures—RenderContext::fillTexture(texture, data) with one RGBA8 level still makes the mips in the caller's thread (buildMipChain), as the application asked for.

Measured

examples/10_ktx2_textures --measure --model <file>, Release, headless, RTX 3060, the median of three runs. "Longest frame" is the longest frame while the model loads.

206 → 10 msFlight Helmet PNG, longest frame15 textures; mips on the worker, fills spread over frames
280 → 6 msSponza, longest frame69 JPEG and PNG textures
28 → 5 msFlight Helmet KTX2, longest frameno mips to make; the copy is spread
0.61 → 0.02 ms17_streaming, freeing per framemean of collectReleases; the max 1.42 → 0.15 ms

Each image of a model is a job of its own, so its decode and its mips run on every free worker at once: the whole PNG helmet loads in 191 ms and Sponza in 200 ms (23 workers; job systems).

Where it lives in code

WhatWhere
MipsbuildTextureLevels, buildMipChain, getFullMipCount in src/rhi/mipChain.cpp
Worker: texturesdecodeTexture, AssetLoader::loadTexture, finishTextureLoad in src/assets/texture.cpp
Worker: glTF imagesplanImageLevels, runImageWork, getImageLevelsKey in src/assets/meshImport.cpp; GLTFRaw::imageLevels in include/rasm/mesh.h
Queued fillsAssetLoader::Impl::loadMaterial in src/assets/material.cpp; PendingTextureLoad in src/assets/assetLoaderImpl.h; finishLoads in src/assets/assetLoader.cpp
Host copy or stagingVulkanDevice::queryFormatSupport, createTexture, fillTexture in src/rhi/vulkan/vulkanDevice.cpp; getHostCopyMemoryTypes in src/rhi/vulkan/vulkanUtils.cpp; UploadManager::uploadTexture in src/rhi/uploadManager.cpp
Measureexamples/10_ktx2_textures (--measure, --staging, --model)
Teststests/textureUploadTests.cpp
Rules to keep
  • No image asks VMA for host access: a host-copied image uses only the memory types queryFormatSupport found.
  • The main thread never makes mips for a load. A worker hands over every level.
  • Every texture fill of a load goes through pendingTextures, so the budget sees it.
  • The worker's level count is the texture's mip count (getFullMipCount), or fillTexture refuses the levels.

Further reading