Foundations
Graphics APIs and the RHI
A graphics API is how a program talks to the GPU. The modern ones (Vulkan, Direct3D 12, Metal, WebGPU) share one model, with different names and different details. An engine that wants to run on several of them puts its own thin layer on top: a render hardware interface, or RHI. This page explains the shared model, the differences, and the choices an RHI has to make. The last part shows RASM's RHI.
In short
- Explicit APIs move work from the driver to the application: memory, synchronization, pipeline creation and command recording.
- All four have the same pieces: a device, queues, command buffers, pipelines, resources, a binding model, sync objects and a swapchain.
- They differ most in binding, barriers, shader language and the platforms they run on.
- An RHI is one interface above all of them. The engine is written once, against it. Each API gets a backend below it.
- The main choices: how thin the layer is, virtual interfaces or a compile-time backend, how resources are named (handles or pointers), and who places the barriers.
- A good RHI exposes what every planned backend can do, and never lets native types leak above it.
1What a graphics API does
A GPU is a separate processor with its own memory and its own command stream. A program cannot call it like a function. It writes commands into memory, hands them to the driver, and the GPU runs them later. The graphics API is the contract for this: how to create objects on the GPU, how to record commands, and how to know when they are done.
An older driver has to guess. When a texture is drawn into and then sampled, it must notice that, and flush caches in between. It does not know which shader combinations will be used, so it compiles them on the first draw, and the frame stutters.
Explicit APIs remove the guessing: the application says what it needs, when it needs it. That makes the driver smaller and faster, and it makes the application longer. An engine absorbs that extra code once, so games and tools built on it do not have to.
2The shared model
Vulkan, Direct3D 12, Metal and WebGPU were designed in the same years, for the same GPUs. Underneath their names, they have the same parts:
| Concept | Vulkan | Direct3D 12 | Metal | WebGPU |
|---|---|---|---|---|
| Device | VkDevice | ID3D12Device | MTLDevice | GPUDevice |
| Queue | VkQueue | ID3D12CommandQueue | MTLCommandQueue | GPUQueue |
| Command recording | VkCommandBuffer, from a VkCommandPool | ID3D12GraphicsCommandList, from an allocator | MTLCommandBuffer with encoders | GPUCommandEncoder with pass encoders |
| Pipeline | VkPipeline + pipeline layout | pipeline state object + root signature | MTLRenderPipelineState | GPURenderPipeline |
| Binding | descriptor sets | descriptor heaps and tables | argument buffers, or direct set calls | bind groups |
| Resources | VkBuffer, VkImage + memory | ID3D12Resource in heaps | MTLBuffer, MTLTexture | GPUBuffer, GPUTexture |
| CPU waits for GPU | VkFence, timeline semaphore | ID3D12Fence (a counter) | MTLSharedEvent, completion handlers | onSubmittedWorkDone (a promise) |
| Ordering between uses | pipeline barriers, image layouts | resource barriers, resource states | automatic by default | automatic, always |
| Window output | VkSwapchainKHR | DXGI swap chain | CAMetalLayer drawables | canvas context |
| Shader format | SPIR-V | DXIL (from HLSL) | MSL, or compiled metallib | WGSL |
The same picture, read in one API at a time. The parts and the arrows stay; only the names change, and one box.
One frame, in any of them
- At load time. Create resources, upload data, and build pipelines from shaders.
- Wait. Each frame, wait until the GPU is done with the memory this frame will reuse (see frames in flight).
- Get an image. Take one from the swapchain to draw into (see the swapchain).
- Record. Fill a command buffer: begin a render pass, bind a pipeline and its resources, draw, end. Put barriers between uses of the same memory (see GPU synchronization).
- Submit and present. Hand the command buffer to a queue, with a fence to signal. Then present the image.
3Where they differ
The shared model hides real differences. Four of them at a glance:
These are the ones an engine feels most:
| Area | How they differ | What it means for an engine |
|---|---|---|
| Binding model | Vulkan has descriptor sets and layouts. D3D12 has one big descriptor heap and a root signature. Metal binds by slot or through argument buffers. WebGPU has fixed bind groups with strict limits. | The hardest part to abstract. Many engines go bindless on the APIs that allow it, so there is little to bind per draw. |
| Synchronization | Vulkan and D3D12 make the application place every barrier. Metal tracks hazards itself unless a resource opts out. WebGPU always tracks them. | The interface needs barriers for two backends, and the other two can ignore them. |
| GPU pointers | Vulkan (buffer device address) and Metal let a shader follow a raw 64-bit buffer address. HLSL on D3D12 and WGSL on WebGPU have no pointers: buffers are reached through descriptors or bindings. | A data layout built on pointers needs another way to reach buffers on D3D12 and WebGPU, such as indices into a bindless array. |
| Shader language | Four different formats. | Write shaders once and cross-compile (Slang, HLSL with a converter, or similar). |
| Render passes | Metal and WebGPU need explicit pass objects with load and store actions. Vulkan has render pass objects and, since 1.3, the simpler dynamic rendering. D3D12 has optional render passes. | Model passes with load and store actions: that maps to every API. |
| Memory | Vulkan lists memory types and heaps. D3D12 has heap types. Metal has storage modes. WebGPU hides memory. | Ask for intent ("GPU only", "CPU writes often", "CPU reads back") and let each backend pick. |
| Platforms | Vulkan: Windows, Linux, Android (macOS through a layer). D3D12: Windows, Xbox. Metal: Apple only. WebGPU: browsers and native libraries. | Covering every platform natively needs more than one backend. |
4Why put a layer on top
Vulkan calls everywhere
Every renderer feature, every pass and every upload is written in Vulkan terms. A second API means rewriting all of them.
A line through the engine
Above the line, code knows only neutral types: a buffer, a texture, a pipeline, a command buffer. Below it, one backend per API turns them into native objects. That line is the RHI.
What an RHI gives
- Portability: one engine, several APIs.
- One place for the API's rules, so passes do not each get them slightly wrong.
- A smaller surface: only the features the engine uses.
- Tests: a fake backend can stand in for the GPU.
What it costs
- A feature can only be used once every backend can implement it, or behind a "supported?" check.
- Each backend is real code to write, test and keep in step.
- A bad split (Vulkan ideas in the interface) makes the next backend hard.
- A small cost per call, usually much less than the driver's.
5Design choices
How thin?
The first choice is the level of the interface. It ranges from "the same objects as the APIs" to "draw this mesh with this material".
Thin: mirror the APIs
createBuffer, createPipeline, barrier, draw, submit. Full control, little overhead.
But: the engine places barriers, and the layer is close to one API's shape.
Middle: resources and passes
"This pass reads A, writes B": barriers come from that. Hard to get sync wrong, and it maps well to every API.
But: some tracking cost.
Thick: a renderer
drawMesh, setMaterial, addLight. Each backend can optimize.
But: every feature is written N times. Not really a hardware layer.
Most engines pick the thin end or the middle. The thick end is a renderer per API, which is exactly the duplication an RHI should avoid.
A common mix: a thin RHI with explicit barriers, and above it a render graph that turns "reads" and "writes" into those barriers. The RHI stays simple, and passes still do not write barriers by hand.
Virtual interfaces or a compile-time backend?
Describing and naming resources
Almost every RHI creates objects from a plain descriptor struct: a list of fields such as size, format and usage. It is easy to read, easy to hash (for caches) and easy to store for debugging. The object it creates can be named in two ways:
Pointer
The engine holds a pointer to the RHI object. No lookup, simple. But a stale pointer crashes, or worse, works on a new object.
Handle
The engine holds a small integer, looked up in a table. It can be checked; it is safe to copy and store; it fits in GPU data. Costs one lookup per use.
A handle with a generation counter can tell a live object from a destroyed one: see generational handles. Under the handle, a backend usually keeps a neutral base struct and derives its own from it, adding the native members:
Recording commands
Direct
Each RHI call records the native command at once: draw becomes the API's draw. Simple and fast. The RHI's command buffer is a thin wrapper around the native one.
Deferred
RHI calls write a compact list of the engine's own commands. Later, often on another thread, the backend translates the list. Costs a second pass, but the list can be sorted, merged, or replayed, and the engine does not depend on the API's threading rules.
Who places the barriers?
The caller
The RHI has a barrier call, close to Vulkan's.
Fast and flexible. Every caller must know the rules from GPU synchronization.
The RHI tracks state
Each resource remembers its last use. Each use records a barrier if needed.
Hard to get wrong. Costs a lookup per use, and knows only the past, not the future.
A render graph
Passes declare reads and writes up front. The graph places barriers for the whole frame.
Sees the whole frame, so it can batch and move barriers. Needs a graph. See render graphs.
6How to add a backend
- Check the shaders first. Can the shader compiler target the new API, and does the shader code use only features it has (pointers, bindless arrays, subgroup operations)? This is usually the biggest job.
- Implement each interface. Device, command buffer, queue, swapchain, and one derived struct per resource. Keep native types in the backend's own files.
- Map the enums. Formats, usages, stages, filter modes: one function per enum, in one file, with an error for values the API does not have.
- Keep the contracts. The interface promises things the native API may not: for example "a fence is a growing 64-bit value". Build that from what the API has.
- Hook up the window. Each API connects to a window in its own way (a surface, a swap chain, a layer).
- Register it. Add it to the place that picks the backend, and to the build.
- Compare images. Render the same frames on the old and the new backend and diff them. Run each API's validation layer.
7Pitfalls
- One API's shape in the interface
- Vulkan's layouts or descriptor sets appear above the line. The next backend has to fake them. Instead: design each call from what all planned APIs can do. Ask "how would Metal do this?"
- Native types leak up
- A VkImage in an engine header. Now the engine depends on Vulkan again. Instead: native types only in the backend's files.
- Lowest common denominator
- The engine cannot use a feature because one API lacks it. Instead: capability tiers: a "supported?" query, and a fallback path.
- Hidden work in the RHI
- A simple-looking call allocates, waits or flushes. Instead: make expensive things look expensive: separate calls, clear names.
- Only one backend tested
- The interface "works", but only for the API that exists. Instead: a fake backend in unit tests, image tests per backend.
8In RASM
RASM has a thin RHI with virtual interfaces and one backend, Vulkan 1.4. Above it sits RenderContext, which turns handles into RHI pointers and checks every call. The engine and the render graph use only RenderContext.
EngineConfig::preferredBackend picks the backend when the engine starts. Vulkan headers stay in the Vulkan files, with three exceptions: src/rhi/device.cpp, the KTX2 format constants in src/assets/ktxImage.cpp, and src/thirdparty_impl.cpp. The platform layer hands the device a NativeWindow, which has no Vulkan type.Here is one buffer, from creation to use. The handle lives above the line; the native buffer lives below it.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Thickness | thin, middle or thick | Thin, shaped like Vulkan 1.3+ with dynamic rendering. Two things are simpler than Vulkan: barriers name three coarse PipelineStage sets, and textures name a TextureUsage instead of a layout. |
| Polymorphism | virtual or compile time | Virtual: Device, CommandBuffer, Queue and Swapchain are abstract classes. rhi::createDevice switches on Backend at runtime. |
| Resources | descriptor struct, derived backend struct | The same. rhi::Buffer keeps its BufferDesc; VulkanBuffer adds VkBuffer and its VmaAllocation. The backend casts back with static_cast. |
| Naming | pointers or handles | Both: handles (BufferHandle) above RenderContext, pointers below it. A destroyed object's handle is invalid at once, and the object is freed after the frames in flight (deferred destruction). |
| Recording | direct or deferred | Direct. Each VulkanCommandBuffer owns its own command pool, reset in begin. |
| Barriers | caller, state tracking, or graph | All three, in layers. The RHI has explicit memoryBarrier and transitionTexture. RenderContext tracks each texture's state (TextureStates). RenderGraph derives barriers from declared reads and writes. See GPU synchronization. |
| CPU–GPU sync | fences or counters | Only counters: an rhi::Fence is a timeline, a Vulkan timeline semaphore. A submit signals one and can wait for up to four others, three on the compute queue, which keeps one for the uploads (SubmitInfo::waits, FenceValue, MAX_SUBMIT_WAITS), which is how the two queues wait for each other. See frames in flight. |
| Swapchain sync | semaphores in the interface | None cross it. VulkanSwapchain owns its semaphores, and a SubmitDesc just names the swapchains: acquireSwapchains to wait for their images, presentSwapchains to present them, one per window. See the swapchain. |
| Queues | graphics, compute, transfer | Graphics, and compute when asked. QueueType has GRAPHICS, COMPUTE and TRANSFER. With EngineConfig::asyncCompute, VulkanDevice takes a compute queue from a family without graphics, and hasAsyncCompute says whether it found one. Without one, compute command buffers and submits use the graphics queue. With one, every buffer and image is shared by both families, so no ownership moves. With EngineConfig::transferQueue it also takes a queue of a family that only copies, for the loads' copies (transfer queues). See async compute. |
| Shaders | one language, cross-compiled | Slang, compiled at runtime and kept in a shader cache. getShaderCompilerTarget in src/renderer/renderer.cpp maps each backend to SPIR-V, HLSL, MSL or WGSL. But the shaders use device addresses and spirv_asm, so only SPIR-V works today (D12). |
| Window | one hook per API | The window and its input are behind a private Platform interface (src/platform/platform.h): SDL, the application's own window, or headless (EngineConfig::platform). Every window reaches the device as the same API-neutral NativeWindow (DeviceDesc::window): an HWND, a CAMetalLayer, an X11 window or a Wayland surface. The Vulkan backend makes its surface from it in createVulkanSurface (src/rhi/vulkan/vulkanSurface.cpp); a D3D12 or Metal backend reads the same handle (The platform layer). A headless engine has no surface: RenderContext renders into an OffscreenSwapchain, a Swapchain made of plain Device textures, so every backend gets it for free (headless rendering). |
| Checks | one place for the rules | RenderContext checks public API misuse with checkArgument: an error log, an assert in debug builds, and the call does nothing. For example, no draw outside a rendering scope and no barrier or dispatch inside one. |
| Tests | a fake backend | tests/uploadManagerTests.cpp and tests/textureStatesTests.cpp implement a fake Device or CommandBuffer, with no GPU. |
Where it lives in code
| What | Where |
|---|---|
| The interface | src/rhi/device.h |
Descriptor structs, TextureUsage, PipelineStage | include/rasm/render/resource.h; their hashes in src/rhi/resource.cpp |
| Backend choice | rhi::createDevice in src/rhi/device.cpp |
| Handle tables, checks, caches | RenderContext in src/rhi/renderContext.cpp, public header include/rasm/render/renderContext.h |
| Native structs | src/rhi/vulkan/vulkanTypes.h |
| Device and resources | VulkanDevice in src/rhi/vulkan/vulkanDevice.cpp |
| Loading Vulkan, the device's function table | loadVulkan and VulkanDevice::initialize in src/rhi/vulkan/vulkanDevice.cpp; see the Vulkan loader |
| Recording | VulkanCommandBuffer in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| Queue types | QueueType, QUEUE_COUNT in include/rasm/render/resource.h; the compute queue in VulkanDevice::initialize |
| Submit | SubmitInfo, RenderContext::submit in include/rasm/render/renderContext.h; SubmitDesc in src/rhi/device.h; VulkanQueue::submit in src/rhi/vulkan/vulkanQueue.cpp |
| Shader target per backend | getShaderCompilerTarget in src/renderer/renderer.cpp |
- Vulkan calls and types stay under
src/rhi/vulkan/. From outside, onlysrc/rhi/device.cpp, the surface hook insrc/platform/, the KTX2 readersrc/assets/ktxImage.cpp(for the file'sVkFormatnumbers) andsrc/thirdparty_impl.cpp(the VMA implementation) include them. - A new GPU feature goes into
src/rhi/device.hin terms that Vulkan, D3D12, Metal and WebGPU can all implement, never as a Vulkan-only path above the RHI. - Public API misuse is checked in
RenderContextwithcheckArgument. Inside the backend, use plainassert. - Check every
VkResultand log it withtoVkResultString. Every Vulkan object gets a debug name (setObjectName). - Test with
enableValidationon. A change that adds validation messages is not done.
A second backend needs, in this order: shaders without raw pointers and spirv_asm (D12), a window hook that takes native handles (D7), and its own copy queue, or the graphics queue in its place, for the loads' uploads (transfer queues). Buffers, textures and render targets are freed once the frame fences pass the frames that may use them (deferred destruction); the other objects live as long as the device. There is no pipeline cache (P8).
Further reading
- The Khronos Group, Vulkan 1.4 Specification; Microsoft, Direct3D 12 Programming Guide; Apple, Metal Programming Guide; W3C, WebGPU specification.
- Branimir Karadžić, bgfx: an open-source, cross-API rendering library with a deferred command model.
- NVIDIA, NVRHI: an open-source RHI over Vulkan and D3D12 with automatic state tracking.
- Epic Games, Unreal Engine documentation on its RHI and render dependency graph.