API reference

RenderContext and resources

RenderContext is the engine's thin, backend-neutral layer over the GPU. It creates buffers, textures and pipelines, and records commands into a command buffer. Inside a render graph pass you get it as the callback's argument; elsewhere from engine.getRenderContext(). Everything is addressed by handles.

CPU work GPU work GPU buffer

In short

  • Record into engine.getCurrentFrameResources().commandBuffer, between beginFrame and endFrame. The engine begins, ends and submits it. Fetch it inside each pass: with async compute the graph moves it between the queues.
  • Draws go inside a render pass, dispatches and barriers outside. Calls in the wrong place are refused.
  • Shaders read buffers through device addresses (getBufferDeviceAddress), passed in the 16-byte push constant. There are no vertex buffers.
  • fillBuffer writes mapped buffers at once and queues the others for the next submit.
  • Nothing is destroyed for you, and buffers and textures are never shared: each create call makes a new one.

1How errors are reported

ProblemWhat happens
Unknown handle (never created, destroyed)Logs <function>: buffer handle not found. (or texture, pipeline, …). The call does nothing and returns false, 0 or an invalid handle.
Invalid use: a wrong argument, or a call in the wrong place (a draw outside a pass, a dispatch inside one)Logs the reason. In debug builds an assert stops in the debugger; in release builds the call fails as above.
The backend fails (out of memory, device limit)Logs the backend's error and returns an invalid handle or false.

2Getting at it

RenderContext& getRenderContext();

The engine's one RenderContext. It lives as long as the engine.

const FrameResources& getCurrentFrameResources();

The resources of the current frame slot (0 or 1): the commandBuffer being recorded and the slot's fence values. The swapchain has no depth: a pass that needs one draws into a render target. See FrameResources. Between beginFrame and endFrame the command buffer is recording; record your commands into it. The slot changes in endFrame, so fetch it every frame. With EngineConfig::asyncCompute the command buffer also changes from pass to pass (an async compute pass records into one of the compute queue), so fetch it inside the pass that records.

DescriptorSetHandle getBindlessDescriptorSet();

The renderer's bindless texture set, which its RenderContext made (RenderContext::getBindlessDescriptorSet returns the same handle, and getBindlessDescriptorSetLayout its layout): RendererConfig::maxBindlessTextures combined image samplers (getBindlessTextureCapacity) at set 0, binding 0, visible to every shader stage (ShaderType::ALL). Pipelines from createPipeline and createComputePipeline use its layout. Bind it with bindDescriptorSet(commandBuffer, pipeline, set, 0) before drawing or dispatching with a pipeline that samples textures. See Materials and textures for how textures get a slot.

3Recording commands

beginRendering (Renderer::beginPass) Outside a render pass compute pass callback, or between passes dispatch memoryBarrier transitionImageLayout dispatch needs a compute pipeline bound Inside a render pass graphics pass callback (beginPass … endPass) draw drawIndexed drawIndexedIndirect(Count) skipped while the bound pipeline is rejected endRendering (Renderer::endPass) Allowed in both bindPipeline · bindDescriptorSet · pushConstants · bindIndexBuffer setViewport · setScissor · setCullMode · writeTimestamp
A draw outside a pass, or a dispatch or barrier inside one, is refused with an error. bindPipeline also checks that a graphics pipeline matches the pass's attachment formats; if not, the pass's draws are skipped until a matching pipeline is bound.
void bindPipeline(const CommandBufferHandle& commandBuffer,
                  const PipelineHandle& pipeline);

Binds a graphics or compute pipeline. A compute pipeline makes dispatch possible and leaves the graphics pipeline alone.

errors A graphics pipeline whose color or depth format differs from the current pass's attachments logs Pipeline '…' does not match the formats or the sample count of the pass's attachments, so its draws are skipped. (a sample count that differs from the attachments' counts too) Then every draw is skipped until a matching pipeline is bound. An unknown pipeline also skips draws and dispatches.

void bindDescriptorSet(const CommandBufferHandle& commandBuffer,
                       const PipelineHandle& pipeline,
                       const DescriptorSetHandle& descriptorSet,
                       uint32_t setIndex = 0);

Binds a descriptor set for pipeline's bind point. Every pipeline has exactly one set, at index 0, so setIndex is 0. In practice the set is getBindlessDescriptorSet().

void pushConstants(const CommandBufferHandle& commandBuffer,
                   const PipelineHandle& pipeline,
                   const void* data, uint32_t size, uint32_t offset = 0);

Copies up to 16 bytes into the push constants, which the next draws or dispatches read. Every pipeline, graphics or compute, has the same pipeline layout, with one push-constant range that every stage sees, so a push needs no stage (Bindless resources).

size, offset
Bytes. offset + size must be at most PUSH_CONSTANTS_SIZE (16); a bigger push logs an error and is dropped. A typical layout is one 8-byte buffer address and two 4-byte values.
void bindIndexBuffer(const CommandBufferHandle& commandBuffer,
                     const BufferHandle& buffer, uint64_t offset,
                     Format indexType);

Binds an index buffer for drawIndexed and the indirect indexed draws. The buffer needs BufferUsage::INDEX.

offset
Bytes from the start of the buffer.
indexType
Format::U16_UINT or Format::U32_UINT.
bool setViewport(const CommandBufferHandle& commandBuffer, float x, float y,
                 float width, float height,
                 float minDepth = 0.0f, float maxDepth = 1.0f);

Sets the viewport, in pixels, with x, y at the top-left corner. RASM flips it (negative height) so that clip space is Y-up. beginPass already sets it to the whole target; change it to draw into a part of it, as examples/01_render_graph does to keep the image's shape.

The scene passes set no viewport: they draw with the one beginPass sets, over the whole target, and their Hi-Z covers the whole target too (occlusion culling).

const Viewport& getViewport() const;

The last viewport given to setViewport, on any command buffer. See Viewport. Nothing in the engine reads it.

bool setScissor(const CommandBufferHandle& commandBuffer, int32_t x,
                int32_t y, uint32_t width, uint32_t height);

Sets the scissor rectangle in pixels, top-left origin. beginPass sets it to the whole target.

bool setCullMode(const CommandBufferHandle& commandBuffer, CullMode cullMode);

Sets which faces the next draws skip. Every pipeline takes its cull mode from here. Front faces are counter-clockwise. beginPass sets CullMode::NONE, and the scene's draw passes change it for each run of draws and set it back.

void draw(const CommandBufferHandle& commandBuffer,
          const uint32_t vertexCount, uint32_t instanceCount = 1);

Draws vertexCount vertices with no vertex buffer; the vertex shader uses SV_VertexID, which counts from 0. Must be inside a render pass with a graphics pipeline bound. draw(commandBuffer, 3) with a full-screen triangle is the usual post-process pass.

void drawIndexed(const CommandBufferHandle& commandBuffer,
                 uint32_t indexCount, uint32_t instanceCount = 1,
                 uint32_t vertexOffset = 0, uint32_t firstIndex = 0,
                 uint32_t firstInstance = 0);

Draws with the bound index buffer. vertexOffset is added to each index. Inside a render pass only.

void drawIndexedIndirect(const CommandBufferHandle& commandBuffer,
                         const BufferHandle& drawInfoBuffer, uint32_t offset,
                         uint32_t drawCount, uint32_t stride);

Draws drawCount indexed draws whose parameters the GPU reads from drawInfoBuffer (usage INDIRECT). Each record starts with five 32-bit values: index count, instance count, first index, vertex offset, first instance.

offset
Byte offset of the first record.
stride
Bytes from one record to the next; at least 20.
void drawIndexedIndirectCount(const CommandBufferHandle& commandBuffer,
                              const BufferHandle& drawInfoBuffer,
                              uint64_t offset,
                              const BufferHandle& countBuffer,
                              uint64_t countOffset, uint32_t maxDrawCount,
                              uint32_t stride);

The same, but the GPU also reads the number of draws, a uint32_t at countOffset in countBuffer, and draws at most maxDrawCount. This is how the scene's draw passes draw what culling kept.

void drawMeshTasksIndirect(const CommandBufferHandle& commandBuffer, const BufferHandle& buffer, uint64_t offset,
                           uint32_t drawCount, uint32_t stride);

Runs the bound mesh pipeline (PipelineDesc::meshShader) drawCount times. Each command is three uint32_t task workgroup counts at offset, then every stride bytes, read by the GPU when it draws. Each task workgroup launches its own mesh workgroups. The scene's draw passes draw a run's visible meshlets this way, with the group counts culling wrote for its chunks.

errors Refused outside a render pass, when no mesh pipeline is bound, where the device has no mesh shaders (hasMeshShaders), for an offset or a stride that is not a multiple of 4 or a stride under 12, for a buffer that is not BufferUsage::INDIRECT, and for commands that reach past the buffer.

void dispatch(const CommandBufferHandle& commandBuffer, uint32_t groupCountX,
              uint32_t groupCountY = 1, uint32_t groupCountZ = 1);

Runs the bound compute pipeline on groupCountX × groupCountY × groupCountZ work groups. The group size is the shader's [numthreads], so for N items use (N + size − 1) / size groups.

errors Refused inside a render pass (dispatches must be recorded outside a render pass (use RenderGraph::addComputePass).) and when no compute pipeline is bound.

void dispatchIndirect(const CommandBufferHandle& commandBuffer, const BufferHandle& buffer, uint64_t offset);

Like dispatch, but the GPU reads the three group counts, uint32_ts at offset in buffer, when the dispatch runs: for work whose size only an earlier pass knows. The scene's meshlet culling dispatches one group per chunk of meshlets this way. Each count must stay within the device's limit (65,535 in x is always allowed). A memoryBarrier from PipelineStage::COMPUTE to PipelineStage::COMPUTE covers a compute shader that wrote the counts.

errors Refused inside a render pass, when no compute pipeline is bound, for an offset that is not a multiple of 4, and for a buffer that is not BufferUsage::INDIRECT.

void memoryBarrier(const CommandBufferHandle& commandBuffer,
                   PipelineStage before, PipelineStage after);

Makes buffer writes of the before stages finish and become visible to the after stages. It covers every way shaders, indirect draws, index fetch and the CPU touch buffers. It does not change texture layouts (use transitionImageLayout). Outside a render pass only.

before, after
One or more PipelineStage flags, combined with |.

The render graph already puts one around compute passes. Record your own between two dependent dispatches (COMPUTE → COMPUTE), and before reading a buffer on the CPU (… → HOST).

A command buffer of the compute queue has no graphics stages. There, GRAPHICS in before waits for all earlier commands instead, and GRAPHICS in after is dropped. Work of the graphics queue is ordered by the submit's waits (SubmitInfo), not by a barrier. transitionImageLayout and aliasingBarrier fit their stages to the compute queue the same way.

void aliasingBarrier(const CommandBufferHandle& commandBuffer);

For textures that share memory. The attachment writes after it wait for every earlier use of any texture: attachment writes, and reads in fragment and compute shaders. A layout transition covers only its own texture, so it does not order the writes of another texture placed in the same memory. Outside a render pass only.

RenderGraph::execute records one before the first pass of each transient render target. Record your own only if you place textures in shared memory yourself.

enum class PipelineStage : uint32_t
{
    COMPUTE  = 1u << 0,
    GRAPHICS = 1u << 1,
    HOST     = 1u << 2,
};

constexpr PipelineStage operator|(PipelineStage a, PipelineStage b);
constexpr bool          hasStage(PipelineStage stages, PipelineStage stage);

Flags for memoryBarrier. operator| combines them; hasStage tests one.

COMPUTE
Compute shaders.
GRAPHICS
Indirect argument reads, index fetch, vertex and fragment shaders.
HOST
The CPU: readBuffer after the barrier, or CPU writes before it.
enum class QueueType : uint32_t
{
    GRAPHICS,
    COMPUTE,
    TRANSFER,
};

constexpr uint32_t QUEUE_COUNT = 2;

The GPU queue a command buffer is made for and a submit goes to. QUEUE_COUNT counts the queues a frame records on, GRAPHICS and COMPUTE.

GRAPHICS
The queue every GPU has. It draws, dispatches, copies the uploads and presents.
COMPUTE
A second queue that runs compute work next to the graphics queue. It exists only with EngineConfig::asyncCompute on a GPU with a compute queue family without graphics (hasAsyncCompute). Without it, COMPUTE command buffers and submits use the graphics queue.
TRANSFER
The engine's queue for the loads' copies, from a family that only copies, with EngineConfig::transferQueue on a GPU that has one. createCommandBuffer and submit refuse it: the uploads own it. See transfer queues.

What a second queue is for, and what it costs: the guide Async compute and multiple queues.

void beginEmptyPass();
void beginSwapchainFrame();

beginEmptyPass starts a pass with nothing to draw into, which Renderer::beginPass uses for a window with no image this frame: its draws record nothing, and endRendering ends it. beginSwapchainFrame runs before a frame's acquires: only the windows acquired after it take part in that frame's submits and presents, so a window that kept an image from a frame that never went out (a failed submit) is presented only once it is acquired again.

bool beginRendering(const CommandBufferHandle& commandBuffer,
                    const TextureHandle* colorAttachments,
                    uint32_t colorCount,
                    TextureHandle depthAttachment,
                    const glm::vec4& clearColor,
                    const AttachmentOps& ops = {},
                    uint32_t face = 0);

Starts a render pass into colorCount color textures (1 to MAX_COLOR_ATTACHMENTS) and one depth texture. By default every color is cleared to clearColor and depth to 0; one load op serves all colors. Color is kept (stored) at the end of the pass; depth only with ops.storeDepth. Pass an invalid depthAttachment for a pass without depth; its pipelines must then have Format::UNKNOWN as their depth format.

ops
See AttachmentOps. loadColor / loadDepth keep what an attachment holds instead of clearing it. Use them to draw on top of an earlier pass, as the scene's Scene 2 pass does after Scene 1 and the Hi-Z build. Before a load, transition the attachment to COLOR_ATTACHMENT or DEPTH_STENCIL_ATTACHMENT without discard, even when it is already in that layout: the barrier orders the earlier writes before the load. storeDepth keeps depth for a later load or a read; without it depth may be thrown away, which saves memory bandwidth.
face
Of a cube depth (TextureDesc::cube): the face to draw into, 0 to CUBE_FACES − 1. Must be 0 for any other depth.

Every attachment must have the same samples per pixel (TextureDesc::samples); a mix logs an error and returns false. Pipelines bound in the pass need that count too.

Renderer::beginPass calls this after the layout transitions, with its ops (a render graph sets them for each pass), and also sets the viewport, scissor and cull mode, so use beginPass unless you build the whole frame yourself.

bool endRendering(const CommandBufferHandle& commandBuffer);

Ends the render pass. Renderer::endPass calls it.

bool copyTextureToBuffer(const CommandBufferHandle& commandBuffer, const TextureHandle& texture, uint32_t layer, uint32_t mip, const BufferHandle& buffer);
bool copyTextureToBuffer(const CommandBufferHandle& commandBuffer, const TextureHandle& texture, uint32_t width, uint32_t height, const BufferHandle& buffer, uint64_t bufferOffset);

Records a copy of one layer and mip of a readable texture (TextureDesc::readable) into the start of buffer, rows tightly packed (width × texel size bytes each; a depth gives its depth). The texture keeps its tracked use: it moves to a copy layout and back inside the copy. The bytes are visible to the host once the submit's fence is reached; then readBuffer them from a buffer made with hostReadable. Refused with an error inside a render pass, and for a texture that is not readable, a multisampled one, a layer or mip it does not have, or one that holds nothing yet. Renderer::readTexture does all of it for you, at the end of a frame. The second form copies only the width × height texels at the corner (0, 0) of mip 0 and layer 0, rows packed at that width, to bufferOffset: a pick copies the corner its rects used this way (Renderer::pick). It is refused for a size past the texture's, or a buffer too small for the copy at that offset.

bool transitionImageLayout(const CommandBufferHandle& commandBuffer, TextureHandle texture, TextureUsage newUsage, bool discard = false);

Records a barrier that moves a texture from the use it is in now to newUsage. The context remembers each texture's use, so you name only the new one. The barrier waits for the old use and blocks the new one. SAMPLED covers fragment and compute shaders. The attachment usages cover reads too, for a beginRendering with load.

newUsage
COLOR_ATTACHMENT, DEPTH_STENCIL_ATTACHMENT, SAMPLED, PRESENT_SRC, or STORAGE for a SAMPLED_STORAGE texture that compute writes (the GENERAL layout; any other texture is refused with an error). STORAGE to STORAGE records a barrier, like an attachment, since it is written.
discard
true drops the contents: the barrier starts from UNKNOWN, which still waits for every earlier use. Use it before a pass that clears the texture. beginPass does it for its attachments.
UNKNOWN created, or a swapchain image just acquired barrier COLOR / DEPTH attachment barrier: written again barrier SAMPLED no barrier fillTexture leaves a texture here PRESENT endFrame
Every arrow can go the other way too, except into UNKNOWN. Only SAMPLED to SAMPLED records nothing: reads after reads need no barrier.

The use changes when the barrier is recorded. A successful submit keeps it; for commands that will not run, call discardRecording. Command buffers that touch the same texture must be submitted in the order they were recorded.

errors Another usage logs an error, records nothing and returns false. Inside a render pass it records nothing (barriers are not allowed there). beginPass moves its attachments, endPass moves a render target's color to SAMPLED, endFrame moves the swapchain image to PRESENT_SRC, and a render graph pass that reads a texture, or a target's depth (readDepth), gets it in SAMPLED. Call it yourself only for your own textures outside those steps.

bool beginCommandBuffer(const CommandBufferHandle& commandBuffer);
bool endCommandBuffer(const CommandBufferHandle& commandBuffer);

Start and finish recording. beginFrame and endFrame do this for the frame's command buffer; call them only for a command buffer of your own. beginCommandBuffer also resets the context's recording state (in a pass or not, pipeline bound or not), which is shared by all command buffers, so record one at a time.

4Buffers

fillBuffer range and size checked Mapped memory? hostVisible, ReBAR, not staged yes CPU copy now memcpy into the buffer The buffer later submits see it no Staging ring 64 MiB, CPU copy now next submit GPU copy before the frame runs
Either way the data is in place for the next submitted frame. A mapped buffer is written at once, so it must not be in use by a frame the GPU is still running.
BufferDesc flagsMemoryfillBufferreadBuffer
none (default)device-local; mapped too when the GPU has ReBAR or shared memorystaging ring, or at once when mappedrefused
stageddevice-local only on a discrete GPU; as the default elsewherestaging ring (at once when mapped)refused
hostVisibleCPU-writable, mappedat oncerefused
hostReadableCPU-cached, mappedat onceyes
BufferHandle createBuffer(const BufferDesc& desc);

The Engine method: forwards to RenderContext::createBuffer. Usable at once.

BufferHandle createBuffer(const BufferDesc& desc);

Creates a new buffer every time (no sharing, B1). Every buffer has a device address and can be a copy source and destination, whatever its usage. Its contents start undefined.

errors A failed allocation logs Failed to create buffer '…' and returns an invalid handle.

struct BufferDesc
{
    std::string name;
    BufferUsage usage        = BufferUsage::STORAGE;
    uint64_t    size         = 0;
    bool        hostVisible  = false;
    bool        hostReadable = false;
    bool        staged       = false;

    bool operator==(const BufferDesc&) const = default;
};
name
Shown in logs and GPU debuggers.
usage
See BufferUsage.
size
Bytes, greater than 0.
hostVisible
Put it in memory the CPU writes directly. For data you change often from the CPU, with one buffer per frame slot.
hostReadable
Put it in cached memory the CPU reads, for readBuffer.
staged
A big buffer the CPU fills once, like a geometry pool. On a discrete GPU it is never mapped: it is in device-local-only memory and fillBuffer goes through the staging ring. New video memory is cleared before the next submit runs, much more slowly when it is host-visible (GPU memory, P35). Ignored with hostVisible or hostReadable.
enum class BufferUsage
{
    INDEX,
    INDIRECT,
    UNIFORM,
    STORAGE,
    DEVICE_ADDRESS,
    TRANSFER,
};

The main use, added on top of device address and copy use, which every buffer but a TRANSFER one has.

INDEX
For bindIndexBuffer.
INDIRECT
Draw records or counts for the indirect draws.
UNIFORM
A uniform buffer.
STORAGE
A storage buffer (the default). Shaders usually reach it by address anyway.
DEVICE_ADDRESS
Only the address and copies.
TRANSFER
Only copies, and no device address (getBufferDeviceAddress is 0): a staging buffer. A host-visible one goes to system memory, or to video memory where all of it is host-visible (resizable BAR), never to a small BAR heap (P10).
bool fillBuffer(const BufferHandle& buffer, const void* data, size_t size,
                size_t offset = 0);

Writes size bytes from data at offset (bytes). Your data is copied before the call returns, so you can free it. See the picture above for when the GPU sees it.

errors data null, size 0, or a range past the end of the buffer is refused and returns false.

// Upload 4096 start positions once, before the loop.
// The buffer is device-local: the data goes out with the first submit.
std::vector<glm::vec2> positions(4096);
engine.getRenderContext().fillBuffer(particles, positions.data(),
                                     positions.size() * sizeof(glm::vec2));
bool readBuffer(const BufferHandle& buffer, void* data, size_t size,
                size_t offset = 0);

Copies size bytes at offset from a hostReadable buffer into data. It does not wait for the GPU. Follow these steps so the bytes are the GPU's results:

  1. Write on the GPU A pass writes the buffer, for example with a dispatch.
  2. Barrier to the CPU Record memoryBarrier(commandBuffer, PipelineStage::COMPUTE, PipelineStage::HOST), outside a render pass.
  3. Wait Wait until that frame is done. The simplest way: read it MAX_FRAMES_IN_FLIGHT frames later, after beginFrame has waited for the same frame slot (as the frame stats do). Use one buffer per frame slot.
  4. Read Call readBuffer.

errors A buffer without hostReadable, null data, size 0 or a range past the end is refused and returns false.

uint64_t getBufferDeviceAddress(const BufferHandle& buffer);

The buffer's GPU address. Put it in a push constant (or in another buffer) and use it as a pointer in Slang, e.g. float2* positions;. The address stays the same until resizeBuffer. Returns 0 with an error for an unknown handle.

BufferDesc getBufferDesc(const BufferHandle& buffer);

The desc the buffer was created with. An unknown handle logs an error and returns BufferDesc{}.

bool resizeBuffer(const BufferHandle& buffer, uint64_t size);

Replaces the buffer with a new one of size bytes, made from the same desc, under the same handle. So whatever holds the handle stays valid, for example a render graph's read and write declarations. The scene passes grow their culling buffers this way.

  • The contents are not copied: the new buffer starts undefined.
  • The device address changes: fetch it again with getBufferDeviceAddress.
  • The old buffer is freed once the GPU has finished the frames that may use it, as for destroyBuffer.

errors An unknown handle logs resizeBuffer: buffer handle not found. and returns false. When the new buffer cannot be created it returns false, and the old buffer stays.

void destroyBuffer(const BufferHandle& buffer);

The handle is invalid at once: a later call with it logs an error, even when a new buffer took its index. The buffer itself, with any upload still queued for it, is freed once the GPU has finished every frame that may use it (deferred destruction), so the call never waits. Renderer::destroyBuffer calls it.

5Textures

TextureHandle createTexture(const TextureDesc& desc);

The Engine method: forwards to RenderContext::createTexture. For image files use loadTexture instead, which decodes, uploads and makes the texture bindless.

TextureHandle createTexture(const TextureDesc& desc);

Creates a new 2D texture every time (B1). With mipLevels 0, a SAMPLED texture in an RGBA8 format (R8G8B8A8_UNORM, R8G8B8A8_SRGB, B8G8R8A8_SRGB) gets a full mip chain and every other texture one level. Fill a sampled texture with fillTexture.

errors A size above the device's limit, a SAMPLED texture in a format the device can't sample (supportsTextureFormat), or a failed allocation, logs an error and returns an invalid handle.

struct TextureDesc
{
    std::string  name;
    uint32_t     width  = 0;
    uint32_t     height = 0;
    Format       format = Format::UNKNOWN;
    TextureUsage usage     = TextureUsage::SAMPLED;
    bool         cube      = false;
    uint32_t     mipLevels = 0;
    uint32_t     samples   = 1;
    bool         readable    = false;
    bool         encodedView = false;

    bool operator==(const TextureDesc&) const = default;
};
width, height
Pixels.
format
See Format. Color data uses R8G8B8A8_SRGB; normal, metallic-roughness and occlusion data R8G8B8A8_UNORM.
usage
What the texture is created for, see TextureUsage.
cube
true: CUBE_FACES square layers, one per face of a cube, in Vulkan's order +X, −X, +Y, −Y, +Z, −Z. Its bindless slot holds a cube view, which a shader reads as a SamplerCube; each face also has its own view, which beginRendering draws into. A render target with RenderTargetDesc::cube makes one for its depth. Only a depth attachment (DEPTH_STENCIL_ATTACHMENT or SAMPLED_DEPTH_ATTACHMENT) or a SAMPLED_STORAGE texture can be a cube: createTexture rejects any other usage with an error.
mipLevels
0: the rule above. Any other count makes that many levels, at most the full chain down to 1 × 1. Only a SAMPLED_STORAGE texture (compute writes its mips) or a SAMPLED one (fillTexture copies them, or makes them for RGBA8) may ask for more than 1: createTexture refuses any other with an error, since an attachment is drawn into one mip.
samples
Samples per pixel: 1, or 2, 4 or 8 for a color or depth attachment of one mip, not a cube, in a count the device has (supportsSampleCount); createTexture refuses anything else with an error. A render target sets it from RenderTargetDesc::samples. A shader reads such a texture sample by sample, as a Sampler2DMS.
readable
true adds copy-source usage (VK_IMAGE_USAGE_TRANSFER_SRC_BIT), so copyTextureToBuffer and Renderer::readTexture can copy it. RenderTargetDesc::readable sets it on a target's textures.
encodedView
For an R8G8B8A8_SRGB attachment that is not a cube: the texture also gets an R8G8B8A8_UNORM view of mip 0, which a pass with AttachmentOps::encodedColor draws through (its pipelines are made for R8G8B8A8_UNORM), so blending works on the stored sRGB codes. A headless engine's offscreen swapchain images have it, so the UI blends as on a window. Other formats ignore it.
constexpr uint32_t CUBE_FACES = 6;

The faces of a cube texture (rasm/render/resource.h).

enum class TextureUsage
{
    TRANSFER_SRC,
    TRANSFER_DST,
    SAMPLED,
    STORAGE,
    COLOR_ATTACHMENT,
    DEPTH_STENCIL_ATTACHMENT,
    SAMPLED_COLOR_ATTACHMENT,
    SAMPLED_DEPTH_ATTACHMENT,
    SAMPLED_STORAGE,
    TRANSIENT_ATTACHMENT,
    INPUT_ATTACHMENT,
    PRESENT_SRC,
    UNKNOWN,
};

Two jobs: in TextureDesc it says what a texture can be used for; in transitionImageLayout it names the state it moves to.

ValueAt creationAs a texture's state
SAMPLEDread by shaders, filled from the CPU with fillTextureyes
COLOR_ATTACHMENTdrawn intoyes
DEPTH_STENCIL_ATTACHMENTdepth bufferyes
SAMPLED_COLOR_ATTACHMENTdrawn into, then read (render target color)–
SAMPLED_STORAGEwritten by compute shaders as a storage image, one mip per slot (updateBindlessStorageImage), then read by shaders–
STORAGEonly passed on to the backendyes: compute reads and writes it (GENERAL); only for a SAMPLED_STORAGE texture
SAMPLED_DEPTH_ATTACHMENTdepth buffer that shaders can also read: with EngineConfig::occlusionCulling, a render target's depth in D32_SFLOAT; always, a depth-only target's depth and that of a target with a MOTION_FORMAT color (readDepth)–
TRANSFER_SRC, TRANSFER_DST, TRANSIENT_ATTACHMENT, INPUT_ATTACHMENTonly passed on to the backend; no RASM call uses them–
PRESENT_SRC–yes (swapchain image before present)
UNKNOWN–the start; never a target (contents thrown away)
bool fillTexture(const TextureHandle& texture, const void* data);
bool fillTexture(const TextureHandle& texture, const TextureLevel* levels, uint32_t levelCount);

Fills a SAMPLED texture from the CPU and leaves it ready for sampling. The first form takes mip 0 and, for an RGBA8 texture, builds the rest of the chain on the CPU (sRGB-aware for sRGB formats); any other format must have one mip. The second takes every mip, for instance the levels of a block-compressed file.

data
width × height pixels of the texture's format (4 bytes for RGBA8, 8 for R16G16B16A16_SFLOAT), rows top to bottom, no padding.
levels, levelCount
One TextureLevel per mip, levelCount equal to the texture's mip count. Each must be exactly the level's size: whole 4 × 4 blocks for a block-compressed format (a level of w × h is ⌈w/4⌉ × ⌈h/4⌉ blocks of 8 or 16 bytes).

The first form makes the mips in the calling thread; the engine's own loads hand over every level from a worker instead. Where the device copies the format on the host at no cost to the GPU (host image copy, see texture uploads), the data is in the texture when the call returns. Otherwise, or with EngineConfig::hostImageCopy false, it goes into the staging ring and a copy on the graphics queue with the next submit, which comes before any frame that samples it. Either way the CPU data may be freed once the call returns. The texture must not be in use by a frame the GPU is still running, nor be filled by a load that has not finished (refused with an error). Returns false with an error for a wrong level count or size, or when a copy step fails.

bool fillTexturePart(const TextureHandle& texture, const TextureLevel* levels, uint32_t levelCount, TextureFillProgress& progress, uint64_t maxBytes);

One part of a fill: the rows from progress on, about maxBytes of them (at least one row), fewer where the staging ring is full, so a big texture's copy spreads over frames without a long one. It moves progress on, and sets done with the last row. The texture has all its data only then: sample it after that, and after its copies are done. maxBytes = UINT64_MAX copies everything and waits for ring space, as fillTexture does. A host-copied texture is filled whole. The engine's loads fill in 4 MiB parts between beginLoadUploads and endLoadUploads.

struct TextureFillProgress
{
    uint32_t mip  = 0;
    uint32_t row  = 0;
    bool     done = false;
};

Where a fill in parts stands: the next mip, the next row of blocks in it, and whether every row is queued. Start from {}.

void beginLoadUploads();
uint64_t endLoadUploads();
void updateLoadUploadsDone();
bool isLoadUploadDone(uint64_t value) const;
bool waitForLoadUploads(uint64_t value);
float takeUploadGpuMs();

The load uploads, which Engine drives; an application does not. Fills between beginLoadUploads and endLoadUploads are a load's: they go on the transfer queue where there is one, else on the graphics queue, and wait for no frame, since they write new memory. endLoadUploads submits them at once and returns the value they are done at. updateLoadUploadsDone reads, without waiting, how far the copies are; from then on isLoadUploadDone(value) says whether that load's data may be used, and the next graphics and compute submits wait for it (it is done, so the wait costs nothing) and acquire the textures it released. waitForLoadUploads blocks until a submitted value is done, for waitForLoads. takeUploadGpuMs returns the GPU time of the copies done since the last call (FrameStats::uploadGpuMs). See transfer queues.

struct TextureLevel
{
    const void* data = nullptr;
    uint64_t    size = 0;
};

One mip of a texture's data, tightly packed: rows of texels, or rows of 4 × 4 blocks for a block-compressed format. Mip 0 comes first.

bool supportsTextureFormat(Format format) const;

True when the device can sample format with linear filtering and fill it, so a SAMPLED texture can be created in it. Block-compressed formats depend on the GPU: BC on desktop GPUs and Apple Silicon, ASTC and ETC2 on mobile GPUs. False without a device. loadTexture uses it to pick a KTX2 file's format.

bool supportsSampleCount(uint32_t samples) const;

True when a render target or pipeline can have samples per pixel: 1, 2, 4 or 8, a count that the device can draw into and sample, for color and for depth (Vulkan: framebufferColorSampleCounts, framebufferDepthSampleCounts, sampledImageColorSampleCounts, sampledImageDepthSampleCounts). Desktop GPUs have 1, 2, 4 and 8. False without a device.

uint32_t getMaxImageSize() const;

The widest and tallest 2D texture or render target the device makes, in pixels (Vulkan: maxImageDimension2D, often 16 384 or 32 768); 0 without a device. createTexture refuses a larger one. exportView keeps its tiles and their guard band under it.

TextureUsage getTextureState(const TextureHandle& texture);

The use the recorded commands leave the texture in: what the next transitionImageLayout starts from. Commands that are dropped without a submit put the state back (discardRecording), so after a frame this tells whether its barriers went out. An unknown handle logs an error and returns UNKNOWN.

const TextureDesc& getTextureDesc(const TextureHandle& texture);

The desc the texture was created with, by reference, so reading one field copies no name string (a frame that calls it allocates nothing, heap memory in the frame). An unknown handle logs an error and returns an empty desc.

lifetime The reference is valid until the texture is destroyed, its render target is resized (resizeRenderTargets makes new textures), or, for a swapchain image, the swapchain is made again. Do not keep it across a destroy: copy the desc to keep it. A new texture does not move it.

void destroyTexture(const TextureHandle& texture);

The handle is invalid at once. The texture and its bindless slot are freed once the GPU has finished every frame that may sample them; then a new texture can take the slot. A render target's texture is refused: destroy the render target. Materials keep the slot number, so use Renderer::destroyTexture for a texture a material may use: it removes it from the materials first.

errors Swapchain images are refused: Swapchain images belong to the swapchain and can't be destroyed.

uint32_t getBindlessTextureIndex(const TextureHandle& texture) const;

The texture's slot in binding 0 of the bindless set, or UINT32_MAX (the same value as INVALID_TEXTURE_INDEX) for a texture without one, or one that was destroyed. One array access, no hash. Renderer::getBindlessTextureIndex calls it.

uint32_t updateBindlessDescriptorSet(
    const DescriptorSetHandle& bindlessSet,
    const TextureHandle& texture,
    SamplerType sampler = SamplerType::LINEAR_REPEAT,
    uint32_t slot = MAX_BINDLESS_TEXTURES);

Writes texture with sampler into a slot of the bindless set and returns the slot, which shaders use as the array index. The descriptor promises the sampled layout, so the texture must be in it when a shader reads it. A texture holds one slot until it is destroyed; getBindlessTextureIndex gives it. Renderer::addBindlessTexture calls this.

slot
MAX_BINDLESS_TEXTURES (the default): the texture's own slot when it has one, unchanged (a frame in flight may sample it; another sampler logs an error: make a second texture), else a freed slot, else the next one never used. A smaller value takes that slot: the texture that held it loses it, and the texture gives back the slot it had. A slot that waits for the GPU after a destroy is refused. Only name a slot no frame in flight samples.

errors When every slot is held or still waits for the GPU, it logs how many wait and returns UINT32_MAX, as does a slot past the set's slots (other than MAX_BINDLESS_TEXTURES) or an unknown set or texture.

bool updateBindlessStorageImage(const DescriptorSetHandle& bindlessSet, uint32_t slot, const TextureHandle& texture, uint32_t mip);

Writes one mip of a SAMPLED_STORAGE texture into slot slot of binding 1 of the bindless set, for compute shaders to write. A cube's mip has all 6 faces, so shaders declare the binding as an array of 2D arrays, with the texture's format:

[[vk::binding(1, 0)]]
[format("rgba16f")] RWTexture2DArray<float4> gStorageImages[];

Move the texture to STORAGE with transitionImageLayout before the dispatches, and to SAMPLED after them. A dispatch that reads a mip another one wrote needs memoryBarrier(COMPUTE, COMPUTE) between them. The slot is overwritten even while earlier frames are on the GPU, so it must not be one they still use: wait for those frames (getFenceValue) before you reuse a slot.

errors A slot at or past the set layout's storageImageCount (MAX_BINDLESS_STORAGE_IMAGES for the engine's set; 0 for a layout without binding 1), a texture that is not SAMPLED_STORAGE, a mip it does not have, or an unknown set or texture logs an error and returns false.

enum class SamplerType
{
    LINEAR_REPEAT,
    LINEAR_MIRRORED_REPEAT,
    LINEAR_CLAMP,
    NEAREST_REPEAT,
    NEAREST_MIRRORED_REPEAT,
    NEAREST_CLAMP,
    COUNT,
};

One of six fixed samplers, shared by all bindless textures. LINEAR_* filters linearly between pixels and mip levels, with 8× anisotropy. NEAREST_* takes the nearest pixel and mip level. The suffix is what happens outside [0, 1]: repeat, mirror, or clamp to the edge. Render targets use LINEAR_CLAMP. COUNT is not a sampler.

6Shaders, pipelines and descriptors

Most applications use Renderer::createPipeline and Renderer::createComputePipeline, which compile Slang source and call the functions below. Use these directly only for a pipeline with other attachment formats or topology.

ShaderHandle createShader(const ShaderDesc& desc);

Creates a shader module from compiled code (SPIR-V for Vulkan). An equal ShaderDesc gives back the existing handle.

errors Empty code or an empty entryPoint is refused.

struct ShaderDesc
{
    std::string          name;
    ShaderType           type = ShaderType::VERTEX;
    std::string          entryPoint;
    std::vector<uint8_t> code;

    bool operator==(const ShaderDesc&) const = default;
};
type
VERTEX, FRAGMENT or COMPUTE, see ShaderType.
entryPoint
The function name inside code, e.g. vertMain.
code
The compiled bytes.
PipelineHandle createPipeline(const PipelineDesc& desc);

Creates a graphics pipeline (vertex + fragment shader) or a compute pipeline (compute shader). An equal PipelineDesc gives back the existing handle. Every pipeline has one descriptor set (the layout in the desc) and a 16-byte push constant range. A graphics pipeline has no vertex input, no blending, depth test and write with GREATER_OR_EQUAL, counter-clockwise front faces, and dynamic viewport, scissor and cull mode.

errors A desc with both a compute shader and a vertex or fragment shader is refused, as are shaders of the wrong type. An unknown layout or shader returns an invalid handle.

struct PipelineDesc
{
    std::string               name;
    ShaderHandle              vertexShader;
    ShaderHandle              fragmentShader;
    ShaderHandle              computeShader;
    ShaderHandle              taskShader;
    ShaderHandle              meshShader;
    DescriptorSetLayoutHandle descriptorSetLayout;
    PrimitiveTopology         topology = PrimitiveTopology::TRIANGLE_LIST;
    Format                    colorAttachmentFormats[MAX_COLOR_ATTACHMENTS] = {};
    Format                    depthStencilAttachmentFormat = Format::UNKNOWN;
    BlendMode                 blendMode = BlendMode::NONE;
    bool                      depthWrite = true;
    bool                      depthTest = true;
    uint32_t                  samples = 1;
    bool                      alphaToCoverage = false;

    bool operator==(const PipelineDesc&) const = default;
};
computeShader
Valid for a compute pipeline; then leave the vertex and fragment shaders invalid.
taskShader, meshShader
Both valid, with fragmentShader and no vertexShader, for a mesh pipeline (ShaderType::TASK, ShaderType::MESH), drawn with drawMeshTasksIndirect. It has no vertex input and no topology: the mesh shader writes the triangles. Only where hasMeshShaders is true.
descriptorSetLayout
Required. Usually the engine's bindless layout (the one Renderer::createPipeline uses).
topology
See PrimitiveTopology.
colorAttachmentFormats
One per color attachment, ending at the first UNKNOWN (count them with colorAttachmentCount). Must equal the color formats of the pass the pipeline is used in, in order, or bindPipeline rejects it. Every attachment gets the same blend state, from blendMode.
depthStencilAttachmentFormat
The same for the depth format. With a depth format the depth test is on (reversed-Z, GREATER_OR_EQUAL).
blendMode
See BlendMode. Renderer::createPipeline always uses NONE.
depthWrite
Writes depth when there is a depth format. false keeps the test but not the write, as see-through draws need.
depthTest
Tests depth when there is a depth format. false draws over everything, as the culling view's ghosts do; depth is then not written either.
samples
The sample count of the attachments it draws into: 1, 2, 4 or 8, of those the device has (createPipeline refuses any other with an error); bindPipeline rejects it in a pass with another. Renderer::createPipeline(name, source, renderTarget) takes the target's.
alphaToCoverage
Color 0's alpha decides which samples a fragment covers, for cut-outs with several samples per pixel (alpha-to-coverage). Both fields take part in equality and the hash.
uint32_t colorAttachmentCount(const Format* formats);

How many of the MAX_COLOR_ATTACHMENTS formats at formats come before the first UNKNOWN: the number of color attachments a PipelineDesc or RenderTargetDesc describes. A format after a gap does not count.

DescriptorSetLayoutHandle createBindlessDescriptorSetLayout(
    const BindlessDescriptorSetLayoutDesc& desc);

Creates a set layout with one binding (0) holding an array of count descriptors, and with storageImageCount above 0 a second binding (1) of that many storage images. Both may be partly empty and may be updated while bound. An equal desc gives back the existing handle. The engine makes one at start-up; you rarely need another.

struct BindlessDescriptorSetLayoutDesc
{
    std::string    name;
    ShaderType     stage = ShaderType::FRAGMENT;
    uint32_t       count = 0;
    DescriptorType type  = DescriptorType::COMBINED_IMAGE_SAMPLER;
    uint32_t       storageImageCount = 0;

    bool operator==(const BindlessDescriptorSetLayoutDesc&) const = default;
};
stage
Which shaders see the array. The engine's layout uses ALL, so compute shaders can sample too.
count
Array size. The engine's layout uses getBindlessTextureCapacity.
storageImageCount
Size of binding 1, of STORAGE_IMAGEs; 0 leaves it out. The engine's layout uses MAX_BINDLESS_STORAGE_IMAGES.
enum class DescriptorType
{
    UNIFORM_BUFFER,
    SAMPLER,
    COMBINED_IMAGE_SAMPLER,
    STORAGE_IMAGE,
};

Descriptor kinds. The engine uses COMBINED_IMAGE_SAMPLER (a texture with its sampler) in binding 0 and STORAGE_IMAGE (one mip a compute shader writes) in binding 1; its pool has MAX_DESCRIPTOR_TYPES (2) sizes, one for each.

DescriptorPoolHandle createDescriptorPool(const DescriptorPoolDesc& desc);

Creates a pool that descriptor sets are allocated from. Always a new pool.

struct DescriptorPoolDesc
{
    std::string        name;
    DescriptorPoolSize sizes[MAX_DESCRIPTOR_TYPES] = {};
    uint32_t           maxSets                     = 0;

    bool operator==(const DescriptorPoolDesc&) const = default;
};

How many descriptors of each type the pool holds (MAX_DESCRIPTOR_TYPES = 1 entry) and how many sets can be allocated from it.

struct DescriptorPoolSize
{
    DescriptorType type  = DescriptorType::COMBINED_IMAGE_SAMPLER;
    uint32_t       count = 0;

    bool operator==(const DescriptorPoolSize&) const = default;
};

One entry of DescriptorPoolDesc::sizes.

DescriptorSetHandle allocateDescriptorSet(
    const std::string& name,
    const DescriptorPoolHandle& pool,
    const DescriptorSetLayoutHandle& layout);

Allocates a set with layout from pool. Unknown handles or a full pool return an invalid handle.

struct ShaderDescHash
{
    std::size_t operator()(const ShaderDesc& desc) const;
};

struct PipelineDescHash
{
    std::size_t operator()(const PipelineDesc& desc) const;
};

struct BindlessDescriptorSetLayoutDescHash
{
    std::size_t operator()(
        const BindlessDescriptorSetLayoutDesc& desc) const;
};

Hash functions for the three descs that RenderContext deduplicates (shaders, pipelines, set layouts). Each hashes every field with hashCombine. A new field in one of these descs must be added to its hash in src/rhi/resource.cpp too.

7Render targets

RenderTargetHandle createRenderTarget(const RenderTargetDesc& desc);

What Renderer::createRenderTarget calls: a color and a depth texture, or one pair per frame slot with history, the colors made bindless with LINEAR_CLAMP. See RenderTargetDesc. The copies of a history target are cleared to clearColor by clearNewHistory at the start of the next frame.

errors These stop in the debugger in a debug build and return an invalid handle: a gap in colorFormats (a render target's color formats can't have a gap.), or no depth format (a render target needs a depth format.). createTransientRenderTarget checks the same.

RenderTargetHandle createTransientRenderTarget(const RenderTargetDesc& desc);

What PassBuilder::createRenderTarget calls for a target without history. The handle and the target's size and formats exist at once; the textures only after placeTransientRenderTargets. You rarely call it yourself: the render graph does.

errors A desc with history stops in the debugger in a debug build and returns an invalid handle: a history render target lives across frames, so it can't be transient.

bool placeTransientRenderTargets(const RenderTargetHandle* renderTargets,
                                 const uint32_t* firstPasses,
                                 const uint32_t* lastPasses,
                                 uint32_t count);

Creates the textures of count transient targets in shared heaps. Target i is in use from pass position firstPasses[i] to lastPasses[i], both included. Targets whose ranges do not overlap may get the same memory (see Transient render targets). The textures keep their bindless slots, and the call logs the heap size against the size without sharing.

If one of the targets was placed before, its old group is replaced: the call first waits for the device to be idle, then frees the old heaps. RenderGraph::execute calls this after a compile that changed the targets' lifetimes. Returns false and logs an error if a heap or texture cannot be created; those targets then have no textures, and the graph tries again the next frame.

void destroyRenderTargets(const RenderTargetHandle* renderTargets, uint32_t count);
void destroyRenderTarget(const RenderTargetHandle& renderTarget);

Destroys render targets, transient or with history: their handles at once, and their textures, bindless and storage slots and the heaps of each transient group that has no target left once the GPU has finished the frames that may use them. Nothing waits. Unknown handles are skipped; destroyRenderTarget logs one. The RenderGraph destructor (and a move assignment over a graph) calls it for the targets the graph made with RenderGraph::createRenderTarget.

void clearNewHistory(const CommandBufferHandle& commandBuffer);

Records a clear to clearColor of every history copy made since the last call, and leaves the colors in the sampled layout. So the previous frame's copy can be read on the first frame, and after a resize. Renderer::beginFrame calls it, before any pass. If the frame is not submitted, discardRecording keeps the clears for the next call.

void resizeRenderTargets();

Rebuilds every render target with a swapchainScale at the swapchain's current size, and places each transient group that holds one again. The handles and bindless slots stay the same. The engine calls it after the swapchain is created again, with the device idle. Do not call it while the GPU may use the targets.

const RenderTarget& getRenderTarget(const RenderTargetHandle& handle);

The target's textures (attachments[slot].color[i] for each of its colorCount color attachments, and .depth, per frame slot; without history every slot holds the same textures), size, formats, clear color and history. See RenderTarget. An unknown handle logs Render target handle not found. and returns an empty target with invalid handles.

RenderTargetDesc getRenderTargetDesc(const RenderTargetHandle& handle);

The RenderTargetDesc the target was made with, including its name and swapchainScale. An unknown handle logs Render target handle not found. and returns an empty desc.

8Frames, fences and the swapchain

The engine runs these for you

beginFrame and endFrame wait for the frame slot, acquire, begin and end the command buffers, submit and present. Call the functions below yourself only for extra work outside the frame, and never acquireNextImage, present or recreateSwapchain while the engine runs frames.

CommandBufferHandle createCommandBuffer(const std::string& name, QueueType queue = QueueType::GRAPHICS);

Creates a command buffer for queue. Submit it only to that queue. Record only compute work into a COMPUTE one: dispatches and barriers, no render pass. Its barriers have no graphics stages (see memoryBarrier). Without a compute queue (hasAsyncCompute is false), a COMPUTE command buffer is made for the graphics queue.

FenceHandle createFence(const std::string& name, uint64_t initialValue = 0);

Creates a timeline fence: a 64-bit counter that a submit sets to a value when its work is done.

bool waitForFence(FenceHandle fence, uint64_t value,
                  uint64_t timeout = UINT64_MAX);

Blocks until the fence reaches value. timeout is in nanoseconds. Returns false with an error on timeout or failure.

uint64_t getFenceValue(FenceHandle fence);

The value the fence has reached now, without waiting. An unknown handle logs an error and returns 0.

struct FenceValue
{
    FenceHandle fence;
    uint64_t    value = 0;
};

One value of one timeline fence. A submit waits until fence reaches value, or sets fence to value when its work is done.

struct SubmitInfo
{
    QueueType                  queue                  = QueueType::GRAPHICS;
    const CommandBufferHandle* commandBuffers         = nullptr;
    uint32_t                   commandBufferCount     = 0;
    const FenceValue*          waits                  = nullptr;
    uint32_t                   waitCount              = 0;
    FenceValue                 signal                 = {};
    bool                       waitsForSwapchainImage = false;
    bool                       presentsSwapchainImage = false;
};

What one submit sends.

queue
The queue that runs the command buffers. COMPUTE without a compute queue goes to the graphics queue.
commandBuffers
commandBufferCount command buffers, at most 8, made for queue. They run in array order, as one submission.
waits
waitCount fence values, at most 3. The command buffers start only when each fence has reached its value. The wait blocks all commands, barriers included. Use it to wait for work on the other queue.
signal
The fence is set to signal.value when the work is done. An invalid fence signals nothing.
waitsForSwapchainImage
true for a submit that may use the acquired swapchain images: it waits for the image of every window that has one acquired. Only the first such submit after an acquire really waits for that image.
presentsSwapchainImage
true only for the frame's last submit that uses the swapchain images: it signals the present of every window that has one acquired. Then call present for each window.
bool submit(const SubmitInfo& info);

Sends info.commandBuffers to info.queue as one submission. Pending fillBuffer uploads are submitted first, on the graphics queue, so these command buffers see their data. A graphics submit sees them through the copies' barriers, a compute submit by waiting for the copies. The copies also wait for the last compute submit, which may still read what they overwrite.

graphics queue compute queue submit A submit C submit B signal 5 → wait 5 signal 3 → wait 3
Each queue has its own timeline fence. A submit signals its fence; a submit on the other queue lists that value in waits. The engine's frame does this for its async compute passes.

On success the texture states the commands recorded are kept (see transitionImageLayout). On failure it returns false: call discardRecording. More than 8 command buffers, or more than 4 waits (3 on the compute queue, which keeps one for the uploads), log an error and submit nothing.

bool hasAsyncCompute() const;

true when the device has a compute queue of its own, next to the graphics queue. That needs EngineConfig::asyncCompute and a GPU with a compute queue family without graphics, whose timestamps have as many valid bits as the graphics queue's. Then every buffer and texture is shared by both queues, so either queue can use it with no ownership transfer.

bool hasBufferInt64Atomics() const;

true when the device has 64-bit atomics on buffers (shaderBufferInt64Atomics, Vulkan 1.2), which the engine turns on whenever the GPU has it. The compute path of small points needs it (Renderer::setComputePoints); without it every point is drawn by triangles. Desktop GPUs and lavapipe have it; MoltenVK and some mobile GPUs may not.

bool hasIndependentBlend() const;

true when pipelines may blend each color target differently (independentBlend, Vulkan 1.0), which the engine turns on whenever the GPU has it: BlendMode::WEIGHTED, WEIGHTED_MOTION and ADDITIVE_COLOR need it. Without it, weighted and additive materials are drawn sorted (BlendMethod). Desktop GPUs, MoltenVK, lavapipe and current mobile GPUs have it.

bool hasSampleRateShading() const;

true when a fragment shader may run once per sample of a multisampled target (sampleRateShading, Vulkan 1.0; a shader that reads SV_SampleIndex), which the engine turns on whenever the GPU has it. The weighted composite uses it to composite each sample with its own sums (weighted blended transparency); without it, each pixel takes the mean of its samples.

bool hasMeshShaders() const;

true when the device has task and mesh shaders (VK_EXT_mesh_shader) with limits that hold the engine's meshlet passes: workgroups of 64 threads, 64 vertices and 124 triangles per mesh workgroup, 65,535 task workgroups in x and y. They are turned on whenever the GPU has them; MoltenVK has none. Then every pipeline's push constants also reach the task and mesh stages, and barriers on PipelineStage::GRAPHICS cover them.

void discardRecording();

Says that the commands recorded since the last successful submit will not run, a failed submit included. Every texture they moved goes back to the usage it had before them, which is still the GPU's layout. The engine calls it when a submit of the frame fails, or when it drops a frame. A successful submit keeps only what its own command buffers recorded, so in a frame of several submits, the textures go back to the states the submitted ones left. Without it, the next barrier on such a texture would start from a layout the texture never reached.

[[nodiscard]] SwapchainStatus acquireNextImage(uint32_t& imageIndex, const WindowHandle& window = {});
[[nodiscard]] SwapchainStatus present(const WindowHandle& window = {});
[[nodiscard]] SwapchainStatus recreateSwapchain(const Window& window);

The swapchain steps of beginFrame, endFrame and a resize, for one window (an invalid handle: the main window). Each returns a SwapchainStatus. An acquired image makes the window part of the next submits' waits and presents (SubmitInfo) until its present. recreateSwapchain sizes the swapchain from the window's pixel size; on success the swapchain image handles change. Use Renderer::recreateSwapchain, which also rebuilds what is sized from the main window.

bool createSwapchain(const Window& window);
void destroySwapchain(const WindowHandle& window);

A window's swapchain, which Renderer::addWindow and removeWindow call. createSwapchain and recreateSwapchain take the Window itself (its handle, NativeWindow and pixel size), since the context knows no renderer. The main window's uses the surface the device was made with; another window's makes a surface of its own from its NativeWindow, and fails, logged, when the GPU's graphics queue can't present to it. A headless engine gets an offscreen swapchain of the window's pixel size. destroySwapchain waits for the device to be idle, since the frames in flight may still use the images, and the surface goes with the swapchain.

Format getSwapchainEncodedFormat(const WindowHandle& window = {});

The format of the swapchain's second view, B8G8R8A8_UNORM, or UNKNOWN when it has none. The view sees the same image, but stores and blends the sRGB numbers as they are, without encoding: what Dear ImGui's colors are made for. A pass draws through it with AttachmentOps::encodedColor, and a pipeline for it uses this format. The swapchain has it when the device has VK_KHR_swapchain_mutable_format and the swapchain is B8G8R8A8_SRGB. How it works: Color spaces.

std::vector<TextureHandle> getSwapchainImages(const WindowHandle& window = {});
Format                     getSwapchainImageFormat(const WindowHandle& window = {});
glm::uvec2                 getSwapchainExtent(const WindowHandle& window = {});

A window's swapchain (an invalid handle: the main window's): its image handles (they change when it is re-created), its color format (RASM asks for B8G8R8A8_SRGB), and its size in pixels. Use the format for render targets and pipelines that should match the swapchain.

9GPU timestamps and memory

For timing inside a frame, beginGpuTimer is simpler: it uses the engine's own query pools and shows up in the frame stats.

QueryPoolHandle createTimestampQueryPool(const std::string& name,
                                         uint32_t count);

Creates count timestamp queries, already reset. Returns an invalid handle, with a warning, when the GPU's queue has no timestamps.

void writeTimestamp(const CommandBufferHandle& commandBuffer,
                    const QueryPoolHandle& pool, uint32_t index);

Records the GPU time into query index when the GPU reaches this point. index must be below the pool's count.

void resetQueries(const QueryPoolHandle& pool);

Resets all queries of the pool, from the CPU, at once. The GPU must be done with the pool.

bool getTimestamps(const QueryPoolHandle& pool, uint32_t firstQuery, uint32_t count,
                   uint64_t* nanoseconds);

Reads count queries from firstQuery into nanoseconds, as nanoseconds after the first of them; a query before it reads 0. Queries written on another queue may count from another origin, so read a compute timer's two queries on their own. It does not wait: it returns false if any of them has not been written since the last reset.

VRAMStats queryVRAMStats();

The memory budget and usage of the GPU heaps, from the driver, right now. See VRAMStats. Renderer::queryMemoryStats returns the same.

10Lifetime

     RenderContext();
     ~RenderContext();
bool initialize(const RenderContextDesc& desc);
void cleanup();

struct RenderContextDesc
{
    Backend       backend                 = Backend::VULKAN;
    std::string   appName                 = {};
    const Window* window                  = nullptr;
    bool          headless                = false;
    bool          enableValidation        = false;
    bool          enableSyncValidation    = false;
    bool          enableGpuValidation     = false;
    bool          asyncCompute            = false;
    bool          transferQueue           = true;
    bool          hostImageCopy           = true;
    bool          sampledDepth            = true;
    std::string   cacheDir                = {};
};

The Renderer owns its RenderContext, initializes it in its constructor and cleans it up in its destructor. Do not create another one or call these. The context knows no renderer: initialize gets everything from the RenderContextDesc, the main window (whose NativeWindow makes the device's surface), headless (no surface; every window gets an offscreen swapchain) and sampledDepth (render target depths are SAMPLED and bindless, for Hi-Z culling: RendererConfig::occlusionCulling). It creates the device for the backend (only VULKAN exists), the main window's swapchain, the six samplers and the bindless set (getBindlessDescriptorSetLayout, getBindlessDescriptorSet), which it fills itself for render targets. cleanup waits until the GPU is idle and destroys every object it still holds.

void tagReleases(const FenceValue& graphics, const FenceValue& compute);
void collectReleases();

The two halves of deferred destruction, which Engine calls; an application does not. endFrame calls tagReleases after the frame's submits, dropped or not: what was destroyed since the last call then waits for the graphics and compute values the queues signaled last, and the last ones of the frames' and the loads' uploads. beginFrame calls collectReleases after the slot's fence wait: it reads the four fences, without waiting, and frees every entry they all reached, in order. With nothing tagged it returns at once. See deferred destruction.

void releaseAfterGpu(std::function<void()> free);
uint32_t getReleasesWaiting() const;
uint32_t getTextureCount() const;
uint32_t getBindlessTextureCount() const;
uint32_t getBindlessTextureCapacity() const;
uint32_t getFreeBindlessTextureSlots() const;
uint64_t getTextureMemoryBytes(const TextureHandle& texture) const;

releaseAfterGpu runs free once the GPU has finished every frame that may still use what it frees, through the same release queue as the destroy* calls: for your own ranges of a buffer, for example. getReleasesWaiting counts what waits; getTextureCount the live textures; getBindlessTextureCount the bindless slots a texture holds; getBindlessTextureCapacity the slots the set has (RendererConfig::maxBindlessTextures, lowered to the device's limit); getFreeBindlessTextureSlots the slots a texture can take now (a destroyed texture's slot waits for the GPU first). getTextureMemoryBytes is the size of a texture's own memory allocation, its alignment and padding included (0 for a transient target placed in a shared heap): what a TileStreamer counts for a tile's textures.

bool isAlive(const TextureHandle& texture) const;
bool isAlive(const BufferHandle& buffer) const;

True while the texture or buffer exists: false once it is destroyed, also when a new object took its index, and for an invalid handle. Logs nothing.

Known limits
  • Buffers, textures and render targets can be destroyed. Shaders, pipelines and descriptor layouts are shared through the dedup caches, so they live as long as the device. Graph teardown and re-placing transient targets still wait for the GPU (D35).
  • There is a graphics queue, with EngineConfig::asyncCompute a compute queue, and with EngineConfig::transferQueue a transfer queue for the loads' copies. Uploads are still recorded on the main thread (D13).
  • Async compute does not make the scene passes faster yet, so it is off by default (P11).

How these calls reach Vulkan: the guide Graphics APIs and the RHI, for uploads GPU memory and uploads, and for the compute queue Async compute and multiple queues.