GPU data

Color spaces: sRGB and linear

A color value can mean two different things: an amount of light, or a code chosen to look even to the eye. Images are stored as codes (sRGB). Light must be computed as amounts (linear). This page explains the sRGB curve, why the math must happen in linear, which textures are colors and which are data, and how the GPU converts between the two for free. The last part shows how RASM does it.

In short

  • A linear value is proportional to the light: 0.5 is half as much light as 1.0.
  • An sRGB value is a code on a curve that spends more of the 256 steps on dark tones, where eyes are sensitive. Linear 0.5 is sRGB 0.735 (byte 188); sRGB 0.5 is only 21% of the light.
  • Lighting, blending, filtering and averaging must use linear values. Doing them on sRGB codes gives wrong, usually too dark, results.
  • Color textures (base color, emissive) are sRGB. Data textures (normals, roughness, metalness, occlusion) are plain numbers and must not be converted.
  • Formats ending in _SRGB make the GPU decode on read and encode on write, in hardware. The shader sees and writes linear values only.
  • Light can be brighter than 1.0. Tone mapping squeezes it into 0 to 1 before the final encode.

1Two kinds of numbers

The same number can be read by physics or by the eye. The two do not agree.

+ = 1 1 2

Light adds up: linear

Light is made of photons. Twice the photons is twice the light, and two lamps together give the sum of both. A number that works like that is linear: it is proportional to the physical amount of light. All of physics, and so all lighting math, works on linear numbers.

1% 2% 50% 51% ×2 a big step ×1.02: no visible step

Eyes notice ratios

Eyes do not work like that. Going from 1% to 2% of the light looks like a big step, going from 50% to 51% looks like nothing.

If an 8-bit image stored linear values, most of its 256 steps would be spent on bright tones that look the same, and the dark tones would show visible bands.

8-bit linear codes 8-bit sRGB codes the dark tones: below 10% of the light
0 (black) 1 (full light) amount of light (linear) → linear codes evenly spaced sRGB codes dense in the dark below 10% of the light: 26 of the 256 linear codes, but 90 of the 256 sRGB codes
Each mark is every 16th code (0, 16, 32 … 255), placed at the amount of light it stands for. sRGB puts its steps where eyes can tell them apart. Same 8 bits, same 256 codes. sRGB is a smarter way to spend them, not a different set of colors.

So images are stored as codes on a curve that roughly matches the eye. The curve used by almost every screen, photo and web page is sRGB. A program that wants to do math on light must first decode the code to a linear value, do the math, and encode the result for the screen.

  1. sRGB codewhat the image stores
  2. decodecode → linear value
  3. mathon amounts of light
  4. encodelinear value → code
  5. screenshows the code

2The sRGB curve

The sRGB standard (IEC 61966-2-1) defines the curve exactly. It is a power curve with a short straight piece near black, so that the slope at 0 is not infinite. Values are between 0 and 1 (divide a byte by 255).

decode (sRGB code s → linear light L):
    L = s / 12.92                          if s ≤ 0.04045
    L = ((s + 0.055) / 1.055) ^ 2.4        otherwise

encode (linear light L → sRGB code s):
    s = 12.92 · L                          if L ≤ 0.0031308
    s = 1.055 · L ^ (1 / 2.4) − 0.055      otherwise
0.5 0.735 0.214 0.5 01 1 linear light L code s s = L encode The light a stored byte shows 128 21% of full light 188 50% 255 100% Blue and orange are the same two points as on the curve.
The two directions are exact inverses. The knee at L = 0.0031308 and s = 0.04045 is where the straight piece meets the power curve.

The value people find surprising: a pixel stored as byte 128, "half" of 255, shows only 21% of full light. And half of full light is byte 188.

Try any byte. The picture below runs the decode formula on it.

Find the byte that shows half of full light. Then go below byte 10, where the curve is a straight line, and compare the last two numbers.

Values to remember

LinearsRGB codeByte
0.00.0000
0.010.10025
0.180.461118"middle gray"
0.2140.500128
0.50.735188
1.01.000255
The 2.2 shortcut

A plain power of 2.2 is a common shortcut: 0.5 ^ (1/2.2) = 0.730, close to 0.735. It differs most near black, where the real curve is a straight line.

3Why the math must be linear

Lighting is adding and scaling amounts of light: a surface under two lamps gets the sum of both, a surface turned away gets a fraction. That is only true for linear values. On sRGB codes, "half" and "plus" mean something else, and every result comes out wrong.

Follow one texel from the texture to the screen. The texture says the surface is gray, stored as byte 128. Two lamps each give it half of full light.

1. The texel: byte 128, an sRGB code

texel 128 → s = 0.502 decode light encode The number is a code, not an amount of light. Nothing can be computed with it yet.

This is what the artist's image file holds: a code chosen so that it looks like a mid gray on screen.

2. Decode to linear

texel s = 0.502 decode L = 0.216 light encode ((0.502 + 0.055) / 1.055) ^ 2.4 = 0.216: the surface reflects 21.6% of the light.

Now the number means something physical: the fraction of light the surface reflects (its albedo).

3. Light it: two lamps, half light each

texel s = 0.502 decode L = 0.216 light A: 0.216 · 0.5 = 0.108 + B: 0.108 = 0.216 encode Two half lamps make one full lamp, and the surface sends back exactly its albedo: 0.216.

Adding and scaling linear values is just physics. This is the part the shader does.

4. Encode for the screen

texel s = 0.502 decode L = 0.216 light 0.216 encode 0.502 → 128 Full light gives back the texture's own color, as it should. With lamp A alone: encode(0.108) = 0.362 → byte 92.

The screen's own curve then turns the code back into light. The round trip is exact.

Now the same with one lamp, done wrong and done right. One lamp must give half the light of two:

two lamps 21.6% one lamp 5.1% half

Wrong: math on codes

0.502 × 0.5 = 0.251, written as is. Byte on screen: 64. Light on screen: 5.1%. A quarter, not half.

two lamps 21.6% one lamp 10.8% half

Right: linear math

Decode 128 → 0.216, × 0.5 = 0.108, encode → 0.362. Byte on screen: 92. Light on screen: 10.8%, half of 21.6%.

What math on codes looks like

Every shadow and every falloff is too dark. Light sources add up wrongly: two lamps that each give a mid gray do not add to the brightness one lamp twice as strong would give. The look is harsh, with sudden dark edges. Linear lighting gives soft, physically plausible falloff.

4Color textures and data textures

Only textures that hold colors meant to be seen are stored as sRGB. Many textures hold numbers: a direction, a roughness, a mask. Those are already linear, and decoding them as sRGB changes the numbers.

Colors: store as sRGB

Base color

Also called albedo or diffuse. Holds a color.

Store as sRGB

Emissive

Holds a color: the light the surface gives off.

Store as sRGB

OK

UI images, sprites, photos

Hold colors.

Store as sRGB

Numbers: store as linear

Normal map

A direction: (x, y, z) mapped from −1…1 to 0…1.

Store as linear (UNORM)

metallic roughness 0 1

Metallic-roughness

Two factors from 0 to 1.

Store as linear (UNORM)

Ambient occlusion

A fraction of light.

Store as linear (UNORM)

Height, masks, lookup tables

Hold numbers.

Store as linear (UNORM)

Two special cases

Alpha channel of any texture

Holds coverage.

Always linear, even in an sRGB format

1.0

HDR images, light maps

Hold amounts of light above 1.

Store as linear float (16-bit)

What happens when a normal map is loaded as sRGB by mistake:

the stored byte read as UNORM: the stored normal decoded as sRGB: a bent normal
stored byte read as UNORM (right) decoded as sRGB (wrong) 128 "flat": x = 0 128/255 = 0.502 · 2 − 1 x = 0.004 decode → 0.216 · 2 − 1 x = −0.568 200 tilted 200/255 = 0.784 · 2 − 1 x = 0.569 decode → 0.578 · 2 − 1 x = 0.155
Dashed: the normal that was stored. A flat surface now leans strongly to one side. The whole model looks lit from the wrong direction. The same mistake on a roughness map makes every surface shinier than intended, because decoding pushes values toward 0.

5The GPU converts for free

Modern GPUs do the sRGB curve in hardware. The format of an image says whether its bytes are sRGB codes. A format ending in _SRGB (for example R8G8B8A8_SRGB) means: decode when read, encode when written. The same bytes in a _UNORM format are read as plain numbers divided by 255.

images: bytes in memory fixed hardware steps the shader
color texture …_SRGB bytes data texture …_UNORM bytes sampler decode, then filter sampler ÷ 255, filter shader linear only target …_SRGB blend, encode display code → light the only place values are linear: the shader never sees an sRGB code
The decode happens before filtering, and the encode after blending. That order is what makes filtering and blending correct.

What the hardware does with an _SRGB format, step by step:

code code decode linear linear filter

Sample

Decodes each texel it reads to linear, then filters (bilinear, trilinear) the linear values. Alpha is not decoded.

linear encode code

Write

Encodes the shader's linear output to sRGB codes as it stores them.

shader code linear blend code decode encode

Blend

Reads the stored code, decodes it, blends in linear, encodes the result.

code copy: same bytes code linear clear: encode code

Copy, clear

A copy moves bytes unchanged. A clear color is given in linear and encoded.

Can the shader convert instead: read a UNORM texture and call pow? That works for a single read but is wrong with filtering. Take a sample halfway between a black texel and a white one:

0 255 filter 128 decode 0.216 light 21%

UNORM format, pow in the shader

The GPU filters the codes, before the shader can decode them.

0 255 decode 0, 1 filter 0.5 light 50%

_SRGB format

The sampler decodes first, then filters. Use the _SRGB format and let the sampler do it.

6Filtering and blending are math too

Any operation that mixes colors must mix linear values. The same black-and-white example comes up again and again. Each picture mixes white and black 50/50:

0 255 the sample, halfway

Bilinear filtering

A sample between a black and a white texel.

On codes: 128 · In linear: 188

1 texel

Mipmap generation

A 2×2 block of black and white (see mipmaps).

On codes: 128 · In linear: 188

white, 50% opacity

Alpha blending

White at 50% opacity over black.

On codes: 128 · In linear: 188

1 pixel, 4 samples

Anti-aliasing (MSAA resolve)

An edge pixel half covered.

On codes: 128 · In linear: 188

128the mix computed on codes21% light: too dark
188the mix computed in linear50% light: correct

The same mix at any ratio, and with colors. Both bars below go from the first color to the second in small steps; only the space of the math differs.

Keep black + white at 50 % and read the two bytes: they are the 128 and 188 from above. Then try red + green and look at the middle of the top bar.

On codes, every mix is too dark. Thin bright lines (text, wires, stars) look thinner and darker than they should, and edges look jagged even with anti-aliasing.

7Light above 1.0: tone mapping

Linear light has no upper limit. A lamp-lit white wall can be 4.0, a spot of sunlight 20.0. The screen's codes stop at 1.0. Simply clipping everything above 1 turns all bright areas into the same flat white. Tone mapping is a curve that squeezes the whole range into 0 to 1, keeping the order of brightness. It runs on linear values, before the sRGB encode.

clip: everything above 1 is the same white Reinhard: x / (1 + x)
0.5 0.667 0.8 0.889 clipped: one flat white 01 01248 linear light → a lamp-lit white wall display
Reinhard is the simplest tone map. Film-like curves (filmic, ACES, AgX) keep more contrast in the mid tones and handle saturated colors better. Most also multiply by an exposure first, like a camera. The tone mapping guide explains exposure and these curves in full.

Reinhard, then encode

LightMappedByteByte if clipped
0.50.333156188
1.00.500188255
2.00.667213255
4.00.800231255
8.00.889242255

Every brightness keeps its own value. The price: mid tones get darker and colors lose saturation.

To have values above 1 to map, the scene must be rendered into a target that can store them: a 16-bit float format, not an 8-bit one. A typical frame:

  1. Render the scenein linear float
  2. Exposure and tone mappingin one full-screen pass
  3. sRGB swapchainthe result is written to it

8Pitfalls

Washed out, gray, low contrast
Encode twice: the shader applies the curve, and the _SRGB target encodes again. Linear 0.5 → 0.735 → 0.873 (byte 223 instead of 188).
Too dark, harsh shadows
Never encode: linear output to a UNORM target. Linear 0.5 stored as 128, shown as 21% light.
Bent normals, too-shiny surfaces
Data texture loaded as sRGB. See section 4.
Pale, washed-out materials
Color texture loaded as UNORM. Byte 128 used as 0.502 albedo instead of 0.216.
Tints too bright
Color from a color picker used as a linear factor. The picker's 128 is 0.216 linear, not 0.5; decode it first.
Banding in dark gradients
Lighting into an 8-bit linear target. Only 26 codes below 10% light (section 1).
Wrong contrast
Tone mapping after the encode. Tone map in linear, then encode.
sRGB is also a set of colors

This page is about the transfer function: the curve between light and code. A color space also fixes its primaries: which exact red, green and blue the channels mean. sRGB shares its primaries with Rec. 709 (HDTV). Wide-gamut and HDR displays use other primaries (Display P3, Rec. 2020) and other curves (PQ for HDR10). The rule stays the same: decode to linear, compute, encode for the display.

9In RASM

RASM follows the textbook pipeline with 8-bit textures, a 16-bit float scene target and an 8-bit sRGB swapchain. The GPU decodes color textures and encodes the output. Shaders work in linear only. The material shaders write unbounded light, and one tone-map pass brings it to the swapchain.

images and their formats the sampler shader functions
CPU · texture formats R8G8B8A8_SRGB base color, emissive R8G8B8A8_UNORM metallic-roughness, normal, AO mips in linear light sampler decodes _SRGB GPU · fragMain shadePBR linear light, no upper limit shadeUnlit factor × texture scene_hdr 16-bit float, linear Tone Map × exposure, AgX swapchain B8G8R8A8_SRGB encodes on write
glTF factors (base color, emissive, metallic, roughness) are linear in the file and are copied as they are. No scene shader applies the sRGB curve: the formats do it. The see-through materials blend in the float scene target, so in linear. Only the UI's shader and the debug views' display convert, by hand (rows below). A headless engine's swapchain is R8G8B8A8_SRGB, which encodes the same way.

Where RASM follows the textbook, and where it differs

PartThis pageRASM
Color vs data texturessection 4glTF: base color and emissive are uploaded as R8G8B8A8_SRGB, metallic-roughness, normal and occlusion as R8G8B8A8_UNORM (loadMaterial). loadTexture takes the format from the caller, R8G8B8A8_SRGB by default, and refuses any other format than these two. A KTX2 texture follows the slot too, not the file: a color slot gets an sRGB format (BC7_SRGB, ASTC_4x4_SRGB, …), a data slot a UNORM one, whatever transfer function the file names (texture compression).
Decodingby the format, before filteringThe same: the sampler decodes _SRGB textures. No shader calls the curve.
Mipsaveraged in linearYes, for sRGB formats (see mipmaps).
FactorslinearglTF factors are linear and copied as they are. Hand-made materials start with white base color (createMaterial); a color typed in by hand must be linear.
LightinglinearYes: shadePBR in shaders/lib/pbr.slang.
HDR target16-bit float, tone map in a final passThe same: the scene passes draw into a SCENE_COLOR_FORMAT (R16G16B16A16_SFLOAT) target, and Renderer::addToneMapPass maps it to the swapchain in a pass of its own.
Tone mappingexposure + a curve, before the encodeThe camera's exposure, then AgX (tone mapping). Unlit materials and the clear color go through the same curve, so an unlit texture does not show its exact colors.
Output and encodean _SRGB target encodesThe swapchain asks for VK_FORMAT_B8G8R8A8_SRGB with VK_COLOR_SPACE_SRGB_NONLINEAR_KHR. The scene targets are float, with no curve; only the swapchain encodes. A headless engine draws into an OffscreenSwapchain of R8G8B8A8_SRGB images instead (headless rendering).
Blendingin linear, by the _SRGB targetThe Transparent pass blends in the float scene target, so in linear light.
UI colorscodes, meant to be blended as codesDear ImGui's colors are sRGB codes. The UI pass draws through the swapchain's B8G8R8A8_UNORM view (headless, the OffscreenSwapchain images' R8G8B8A8_UNORM view, TextureDesc::encodedView), which stores and blends the codes as they are; an sRGB texture in an image is encoded back to codes in ui.slang. Without the view (D31) the shader decodes the colors and the blend is in linear light. See Immediate-mode UI.
Debug viewsshow values, not lightA debug view (Renderer::setDebugView) writes display values (a normal as a color, a count) into scene_hdr. The tone map then draws fragDebug or fragDebugHeat in shaders/passes/toneMap.slang: no exposure, no curve, and decodeSrgb first, so the swapchain's encode gives back the value as it is.
Linear constantsclear colors are linearRenderer::render clears scene_hdr to BACKGROUND_COLOR, 0.018 linear, which then goes through the tone map. The same constant clears passes that draw straight to the swapchain, not tone mapped; the encode turns it into byte 36. The stats overlay's colors in statsOverlay.slang are linear too, and are not tone mapped.

Where it lives in code

WhatWhere
FormatsFormat in include/rasm/types.h
glTF color vs dataAssetLoader::Impl::loadMaterial (its texture upload, with an sRGB flag per texture) in src/assets/material.cpp
Loading a texture fileAssetLoader::loadTexture in src/assets/texture.cpp; its default format in include/rasm/renderer.h
sRGB-correct mipsVulkanDevice::fillTexture in src/rhi/vulkan/vulkanDevice.cpp
Swapchain formatbuildSwapchain in src/rhi/vulkan/vulkanSwapchain.cpp; headless, OffscreenSwapchain::FORMAT in src/rhi/offscreenSwapchain.h
LightingshadePBR in shaders/lib/pbr.slang; shadeUnlit in shaders/lib/unlit.slang
Tone mappingRenderer::addToneMapPass in src/renderer/toneMap.cpp; the curve in shaders/lib/agx.slang, the debug views' display (fragDebug) in shaders/passes/toneMap.slang
Hand-made textures, both kindscreateFilledTexture calls in examples/05_city/main.cpp
Keep these true
  • Normal, metallic-roughness and occlusion textures are R8G8B8A8_UNORM; color and emissive textures are R8G8B8A8_SRGB.
  • Shaders output linear color. Never apply the sRGB curve in a shader: the swapchain format encodes.
  • The swapchain must be an sRGB format; with a UNORM one, the image comes out too dark.
  • Tone map once, in the tone-map pass. Material shaders write unbounded linear light.
  • Material factors are linear. Convert a color from an sRGB color picker before storing it.
Not done yet

No automatic exposure and no output to HDR displays. The swapchain format is a request: set_desired_format asks vk-bootstrap for VK_FORMAT_B8G8R8A8_SRGB, and nothing checks the format it really chose.

Further reading