GPU data
Struct layout rules
The CPU writes a struct into a buffer, and a shader reads it. Two different compilers decide where each field goes, and they must agree on every byte. This page explains the rules each side uses, where they differ, and how to check that they match. The last part shows how RASM does it.
In short
- Every type has a size and an alignment. A field goes at the next offset that is a multiple of its alignment; the gap before it is padding.
- C++ aligns each type to its own size (a float to 4, a double to 8). A vec3 of floats is 12 bytes, aligned to 4.
- GPU languages have several rule sets. std140 aligns a vec3 to 16 and pads arrays to 16. std430 drops the array padding. scalar aligns everything to its scalar, like C++.
- The same struct can be 112, 96 or 72 bytes depending on the rules. A mismatch does not crash; the shader just reads the wrong bytes.
- Check it: static_assert the C++ offsets, and compare them with the shader compiler's reflection at startup.
1The problem: two compilers, one buffer
A C++ compiler lays out the CPU struct. A shader compiler lays out the GPU struct. Nothing connects the two. The bytes in the buffer are whatever the CPU wrote; the shader reads each field at the offset its compiler chose.
The shader's b is (c, next, next). The values are real floats from the wrong place, so there is no error and no crash. The picture is simply wrong, or, if a pointer field moves, the GPU follows a garbage address and the device is lost.
2Size, alignment and offset
Every layout rule set, CPU or GPU, uses the same algorithm. Only the numbers in it differ. Here are its five words, on an array of a struct with a float a and a double b:
| Word | Meaning |
|---|---|
| size | how many bytes the value takes |
| alignment | its offset must be a multiple of this number |
| offset | where the field starts, from the start of the struct |
| padding | unused bytes added so the next field is aligned, or so the struct size is |
| stride | the distance from one array element to the next |
offset = 0
maxAlign = 1
for each field:
offset = roundUp(offset, align(field)) // padding goes here
field.offset = offset
offset = offset + size(field)
maxAlign = max(maxAlign, align(field))
structSize = roundUp(offset, maxAlign) // padding at the end
structAlign = maxAlign
roundUp(x, a) is the smallest multiple of a that is ≥ x. The padding at the end makes the size a multiple of the alignment, so that in an array every element is aligned too: the array stride is the struct size.
3C++ layout
On every desktop platform, C++ aligns each scalar to its size: int32_t and float to 4, double, int64_t and pointers to 8. A struct aligns to its largest member. Order matters: the same fields can need more or less padding.
Math libraries follow the same rules. In glm (by default):
Some libraries (and glm with special options) align vec4, or even vec3, to 16 for SIMD; that changes every offset after them.
The C++ side can be pinned with checks the compiler runs:
struct Light
{
glm::vec3 position;
float intensity;
};
static_assert(sizeof(Light) == 16);
static_assert(offsetof(Light, intensity) == 12);
4GPU layouts: std140, std430, scalar
Vulkan GLSL and SPIR-V know three rule sets for buffer memory. They differ in two places: how a three-component vector aligns, and whether arrays and structs are rounded up to 16 bytes.
| Type | std140 | std430 | scalar |
|---|---|---|---|
| float, int, uint | size 4, align 4 | size 4, align 4 | size 4, align 4 |
| vec2 | size 8, align 8 | size 8, align 8 | size 8, align 4 |
| vec3 | size 12, align 16 | size 12, align 16 | size 12, align 4 |
| vec4 | size 16, align 16 | size 16, align 16 | size 16, align 4 |
| array of T | stride and align rounded up to 16 | stride = size of T (rounded to its align) | stride = size of T |
| struct | align = largest member, rounded up to 16 | align = largest member | align = largest member |
| matrix (column-major) | an array of column vectors: mat3 = 3 × 16 = 48 bytes | the same: mat3 = 48 bytes | 3 × 12 = 36 bytes |
| 64-bit (uint64_t, double, a pointer) | size 8, align 8 | size 8, align 8 | size 8, align 8 |
| Rule set | Where it is used |
|---|---|
| std140 | The oldest. The default for uniform buffers in GLSL. Wastes the most space. |
| std430 | The default for storage buffers and push constants in Vulkan GLSL. |
| scalar | Needs the Vulkan feature scalarBlockLayout (core in 1.2 as an optional feature, required since 1.4). Can be turned on per block, or for a whole shader by a compiler option. Closest to C++. |
5One struct, three layouts
Here is one struct, laid out under all three rule sets. d is an array of two vec2; m is a 3 × 3 matrix stored as three columns (c0, c1, c2).
struct Example
{
float a;
float3 b;
float c;
float2 d[2];
float3x3 m;
};
Click through the std430 row, field by field, with the algorithm of section 2.
1. a: float
The first field always starts at 0.
2. b: float3
The only padding between fields in this struct: 12 bytes before b.
3. c: float
No padding: a scalar fits right after a float3.
4. d: float2[2]
In std140, each float2 would take 16 bytes, and d would end at 64.
5. m: float3x3
Each column of a float3x3 wastes 4 bytes in std430 and std140, but not in scalar layout.
6. The end: size and alignment
The size is 96. The C++ struct is 72, so the two sides disagree from b on.
Now try it yourself. The picture below runs the same algorithm twice on these five fields: with the C++ rules, and with the shader rules you pick.
6The usual traps
Four traps you can see in the bytes. Blue is the C++ struct, purple is what the shader expects.
Two vec3 in a row
std430: the second starts at 16, not 12. A vec3 after a scalar moves in the same way (section 1).
Fix: use scalar layout, or put a float after each vec3 (a vec3 + float pair fills 16 bytes in every rule set), or use vec4.
Arrays of scalars in std140
float x[4] has a stride of 16: 64 bytes, not 16.
Fix: use vec4 x[1], or std430/scalar.
mat3
48 bytes in std140/std430, 36 in C++.
Fix: scalar layout, or store a mat3x4 / three vec4.
bool
1 byte in C++, 4 bytes in GLSL, HLSL and Slang.
Fix: use uint32_t on the CPU side.
And six more, without a picture:
- Row-major vs column-major
- The matrix arrives transposed. Pick one majorness for the shader compiler and match the math library (glm is column-major).
- size_t, long, int
- Their size depends on the platform. Use fixed-size types: uint32_t, int32_t, uint64_t.
- A 64-bit field after an odd number of 4-byte fields
- Both sides insert 4 hidden padding bytes. Fine if both do it, but a hand-written offset table forgets them. Keep 64-bit fields at offsets that are multiples of 8, with explicit padding fields.
- The struct's end
- A struct with a 64-bit field rounds its size up to 8 in C++. A GPU rule may round differently. Add an explicit padding field so the size is a multiple of 8 (or 16) on both sides.
- Enums
- The size of a plain C++ enum is up to the compiler. Use enum class E : uint32_t on both sides.
- vec3 after a scalar
- std140/std430 move it to the next 16; C++ does not (section 1). The fix is the same as for two vec3 in a row.
7Other APIs
| API, memory kind | Rule | Our Example: where is b? |
|---|---|---|
| Vulkan GLSL, uniform buffer | std140 | 16 |
| Vulkan GLSL, storage buffer | std430 | 16 |
| Vulkan with scalar layout | scalar | 4 |
| HLSL constant buffer | 16-byte "registers": a vector may not cross a 16-byte boundary; arrays and structs start a new register | 4 (4 + 12 = 16 does not cross) |
| HLSL structured buffer | packed, like scalar | 4 |
| Metal | float3 is 16 bytes, aligned to 16; packed_float3 is 12, aligned to 4 | 16 (or 4 with packed_float3) |
| WGSL (WebGPU) | vec3 aligned to 16; uniform buffers add std140-like array rules | 16 |
8Push constants
Push constants are a few bytes written straight into the command buffer, the fastest way to give a draw small per-draw values. Their layout follows the same rules (std430 by default in Vulkan GLSL). Extra limits apply:
The Direct3D 12 equivalent is root constants: the whole root signature is 64 DWORDs (256 bytes), shared with root descriptors and tables.
Because the space is small, a common design puts just one pointer (8 bytes) and a couple of indices there, and everything else in buffers. See Buffer device addresses.
9Making sure both sides agree
A layout mismatch gives no error by itself. So each project picks one or more ways to catch it:
Generate one side from the other: a tool writes the C++ header from the shader's reflection, or the shader from a shared description. Or write the struct once in a header that both compilers read (HLSL and C++ can share simple structs).
10In RASM
RASM uses scalar layout for everything, so its C++ structs (with glm's default packing) and its Slang structs follow the same rules. The structs live twice: in src/renderer/uberMaterialTypes.h (namespace rasm::gfx) and in shaders/lib/core.slang. Two checks hold them together.
fieldStruct). A shader whose pc.scene is not SceneData is skipped.The shared structs
| Struct | Bytes | Read through |
|---|---|---|
PushConstants | 16 | the push constant pc |
SceneData | 2224 | pc.scene |
Light | 68 | lightsPtr, the light table |
ShadowMap | 72 | SceneData::shadowMaps, 16 of them |
VertexFull | 64 | vertsPtr; also tied to rasm::Vertex |
DrawInfo | 20 | drawInfoPtr, allDrawsPtr; also the indirect draw command |
InstanceData | 160 | instancesPtr |
GeometryData, GeometryLod, MorphDelta | 200, 20, 24 | geometryPtr; MorphDelta through AnimationFrame::morphs |
MaterialData, Material, TextureTransform | 312, 84, 24 | materialsPtr |
MetallicRoughnessMaterial, NormalMaterial, OcclusionMaterial, EmissiveMaterial | 40, 12, 12, 20 | the four parts of Material |
What scalar layout buys: two real structs
| Struct | Scalar (used) | std430 would give | Where the difference comes from |
|---|---|---|---|
GeometryData | 200 bytes | 224 bytes | boundsCenter (a float3 at offset 4) would move to 16, and the size would round up to 16 |
InstanceData | 156 bytes | 176 bytes | normalMatrix (a float3x3) would be 48 bytes, not 36, and previousWorld (three float4s) would move from 108 to 128 |
SceneData, byte by byte
forcedLod at 448. shadowMaps (sixteen ShadowMaps of 72 bytes: a float4x4, a texture index and a split) fills 452 to 1604. The four ShadowedLights (12 bytes each), the two light counts, nearZ and depthSamples end at 1720. TAA's fields follow: previousViewProjection (a float4x4), jitter, textureLodBias and the 4-byte debugView end at 1800, so the last three pointers, animatedTransformsPtr (the Animate pass's matrices), skinnedVertsPtr and previousSkinnedVertsPtr (the Skin pass's vertices of this frame and the frame before), sit 8-aligned from 1800 and end at 1824. The nine pointers of meshlet culling follow, 1824 to 1896, then cullViewPoint, the three per-run arrays, meshletRuns, coneRuns and a padding word to 2008, and meshletDataPtr to 2016. The render space's originLow and the 4-byte zero (large worlds) end at 2032, and environmentOrientation, a float4, at 2048. labelsPtr, the view's label alphas (labels), ends at 2056. The camera's GridData (reference grid, 168 bytes of 4-byte values, its own zero last) ends at 2224, a multiple of 8: the next view's SceneData keeps its pointers aligned too (a static_assert checks it).Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Rule set | std140, std430 or scalar | Scalar for every buffer and the push constant: the Slang session option GLSLForceScalarLayout, and the device feature scalarBlockLayout. |
| Matrices | pick one majorness | Column-major on both sides: MatrixLayoutColumn in the session, glm on the CPU. |
| C++ side | a math library's default packing | glm with no alignment options: vec3 is 12 bytes, mat3 36. |
| One definition or two | generate, or share, or check | Two hand-written copies, checked. Field names may differ: C++ Material::pbr is Slang metallicRoughness. |
| Compile-time check | static_assert | The static_asserts at the end of uberMaterialTypes.h, more in geometryPool.cpp (tying rasm::Vertex to VertexFull), and one per push-constant struct. |
| Reflection check | at startup, refuse on mismatch | validateRasmStructs, in ShaderCompiler::compileFromString, on the layouts Slang reported after the link, or on the ones a shader cache entry stored with them, so a cached shader is checked like a compiled one. It checks a program whose push constants hold the scene (SceneData and every struct behind its pointers), and the engine passes' own push constants, found by name: ToneMapPushConstants, ResolvePushConstants, TaaPushConstants, BloomPushConstants, UiPushConstants, InspectPushConstants (with the InspectParams behind it), EnvironmentPushConstants and AnimatePushConstants. An application's own pipelines are not checked. It logs each mismatch, and the shader is not compiled, so its pipeline is not created and nothing reads the wrong layout. It runs in every build. |
| Layouts for tools | read the layout from the compiler | Each compile keeps the fields of every struct its push constants reach, with the same walk (collectStructLayouts), and the shader cache stores them. The RASM window's GPU tables section prints rows with them, so no field list is written by hand (Inspecting GPU resources). |
| Type check | also compare types | Not done (C11): a uint32_t against a float passes. |
| Explicit padding | keep the end a multiple of 8 | Smaller structs have padding fields. In SceneData, the 4-byte debugView after textureLodBias also keeps animatedTransformsPtr 8-aligned: the size is 1824, a multiple of 8, which a static_assert checks. A new 4-byte field there needs a padding word with it. |
| Push constants | ≤ 128 or 256 bytes | 16 bytes, PUSH_CONSTANTS_SIZE: one range that the vertex, fragment and compute stages all see (and the task and mesh stages where the GPU has them), in the one pipeline layout every pipeline shares. RenderContext::pushConstants refuses a push past it. The stats overlay's OverlayPushConstants is 16 bytes too. |
| Shared constants | — | MAX_VIEW_SHADOWS, MAX_CLUSTER_LIGHTS, MAX_VERTEX_UV_SETS, MAX_MESH_LODS, MAX_DRAW_RUNS, MaterialId, LightType are written on both sides with the same values. Nothing checks them. |
A mismatch shows up at startup, in any build, with messages in this form (from validateStruct), and the shader is not compiled:
Size mismatch for <struct>: C++ <bytes>, shader <bytes>
Offset mismatch for <struct>.<field>: C++ <offset>, shader <offset>
Shaders are compiled at startup
RASM compiles its Slang shaders when the engine starts, from EngineConfig::shaderDir, or reads them from its shader cache, whose key holds every shader file. So the check runs on every start, and a shader edit needs no build step. tools/compile-shaders.bat compiles every pass offline with the same flags (-force-glsl-scalar-layout, -matrix-layout-column-major), only as a syntax check; the engine does not use its output.
Where it lives in code
| What | Where |
|---|---|
C++ structs and static_asserts | src/renderer/uberMaterialTypes.h |
| Slang structs | shaders/lib/core.slang |
| Session options | ShaderCompiler::initialize in src/renderer/shaderCompiler.cpp |
| The reflection check | validateRasmStructs, validateStruct, fieldStruct in src/renderer/shaderCompiler.cpp |
| Vertex ties | src/renderer/geometryPool.cpp |
| Push-constant size | PUSH_CONSTANTS_SIZE in include/rasm/types.h; createPipelineLayout in src/rhi/vulkan/vulkanDevice.cpp; RenderContext::pushConstants in src/rhi/renderContext.cpp |
| Offline compile check | tools/compile-shaders.bat |
- Change a shared struct on both sides in the same change: the C++ struct, the Slang struct, the
static_asserts, and the table invalidateRasmStructs. Thegpu-struct-syncskill lists every place. - Run an example after the change: the reflection check runs at startup and logs any mismatch.
- Never use bool, size_t, int or glm's aligned types in a shared struct.
- Keep 64-bit fields at offsets that are multiples of 8, and the struct size a multiple of 8.
- Compare the two definitions field by field by eye: types are not checked.
C11: the reflection check compares sizes and offsets, not types. The shared constants and enums are not checked at all.
Further reading
- The Vulkan specification: "Offset and Stride Assignment" in the chapter on shader interfaces (std140, std430 and scalar alignment).
- The OpenGL 4.6 specification, section 7.6.2.2 "Standard Uniform Block Layout": the original std140 and std430 rules.
- The Vulkan extension VK_EXT_scalar_block_layout.
- Microsoft, "Packing Rules for Constant Variables" in the HLSL documentation.
- The Slang user guide: reflection, and target-specific layout options.