API reference
Engine and Renderer
Your program creates one of two objects. rasm::Renderer is the renderer alone: it owns every scene object and GPU resource and runs the frame, in your window or into images, and opens no window itself. rasm::Engine is a Renderer that also opens its window with SDL and reads its events. Every method on this page is a Renderer method, and an Engine has them all. This page covers how to create them, the frame functions, loading, frame stats, paths and the window. The table below lists every method and the page that documents it.
1Every method
| Method | Task | Page |
|---|---|---|
Renderer / Engine / ~Renderer | create and shut down | this page |
running | false after quit or a failed start | this page |
getConfig | the config, with resolved paths | this page |
resolveAssetPath | where an asset path points | this page |
render | a whole frame, one scene | this page |
render(views, count) | a whole frame of several views: split screen, a map, view textures | this page |
beginFrame / endFrame | start and finish a frame | this page |
beginPass / endPass | start and finish a render pass | this page |
addScenePasses | add a scene's culling and draw passes to a graph | this page |
addShadowPasses | add a light's shadow passes to a graph | this page |
addMsaaResolvePass | resolve a multisampled HDR target in a pass of the graph | this page |
addTaaPass | anti-alias an HDR target over frames (TAA) | this page |
addBloomPasses | add the bloom of an HDR target to a graph | this page |
addToneMapPass | map an HDR target, with its bloom, into the window | this page |
addUiPass | draw the ImGui windows over the image | this page |
setUiCallback | your own ImGui windows, every frame | this page |
getUiTexture | a texture as an ImTextureID for ImGui::Image | this page |
getUiContext | the Dear ImGui context, for another copy of ImGui (a DLL, a binding) | this page |
setDebugView, getDebugView | show normals, UVs, overdraw, LODs, culling, light counts or meshlets | this page |
setCullingFrozen | keep the culling of one frame while the camera moves | this page |
setMeshletPath, getMeshletPath | cull and draw big meshes by meshlets, or whole | this page |
setComputePoints, getComputePoints | small points by the compute path, or every point by triangles | this page |
setInspection, getInspection | show a render target, depth, Hi-Z level, light clusters or an entity's GPU table rows in the RASM window | this page |
getCurrentFrameResources | this frame's command buffer and depth | this page |
recreateSwapchain | rebuild after a resize | this page |
waitForLoads | finish every background load now | this page |
AssetLoader / getAssetLoader | load files on worker threads, for a Renderer or an Engine | this page |
TileStreamer | keep a map's or a world's tiles in memory under a byte budget | this page |
readFrame / readTexture | copy the frame or a texture to the CPU (screenshots, thumbnails, tests) | this page |
isReadbackReady / takeReadback | is the copy done, take its pixels | this page |
pick / isPickReady / takePick | what is under a pixel or a rect of a view: entity, feature, world position | this page |
isAlive | is an entity (a pick's, say) still there | this page |
exportView / getExportProgress / takeExport / cancelExport | a still of a view at any size (8K, 16K, a poster) in tiles, to a PNG or EXR file | this page |
getFrameStats | frame times, draws, memory | this page |
beginGpuTimer / endGpuTimer | time your own GPU work | this page |
queryMemoryStats | GPU memory budget and use | this page |
getMainWindow | window size and state | this page |
addInputEvent | send the input of a window you own | this page |
setWindowSize / setWindowContentScale | the size and scale of a window you own | this page |
addWindow / removeWindow / getWindow | more windows, each with its own swapchain | this page |
createBuffer / createTexture | raw GPU resources | this page |
createScene | new scene | scene.html |
addEntityToScene, addCameraToScene, addLightToScene | put objects in a scene | scene.html |
createEntity | new entity | scene.html |
updateTransform / getTransform | move an entity | scene.html |
createLight | new light | scene.html |
updateLight / getLight | change or move a light | scene.html |
loadEnvironment / isLoaded(EnvironmentHandle) | an HDR sky photo that lights scenes, in the background | scene.html |
setSceneEnvironment | light a scene with an environment, show its sky | scene.html |
createMesh | mesh from your vertices | scene.html |
createMesh(MeshBuild&&) | upload a mesh built on another thread | scene.html |
loadFont / createFont | a font's distance atlas, for labels | this page, scene.html |
loadPointCloud | a LAS or LAZ file's points in doubles, for an octree | this page |
createColormap | a colormap for point clouds' values, from colors or a preset | scene.html |
createTerrainTile | a terrain tile from its heights and image | scene.html |
getTerrainMesh | the grid terrain tiles share | scene.html |
loadMesh / loadGLTF | mesh from a file, in the background | scene.html |
isLoaded(MeshHandle) | is the mesh ready | scene.html |
getMeshByteSize | bytes of a mesh's geometry | scene.html |
setAnimationTime | the animation clock, once per frame | scene.html |
playAnimation / stopAnimation | play a mesh's clip on an entity, or stop it | scene.html |
getAnimations / findAnimation | a mesh's clips, a clip by name | scene.html |
setMorphWeights / clearMorphWeights | set an entity's morph weights, or give them back to its clip | scene.html |
getMorphTargetNames | the name of each morph weight of a mesh | scene.html |
createMaterial | new material | materials.html |
getMaterial / updateMaterial | read and change a material | materials.html |
loadTexture | texture from a file, in the background | materials.html |
isLoaded(TextureHandle) | are the pixels uploaded | materials.html |
addBindlessTexture / getBindlessTextureIndex | texture slots for shaders | materials.html |
createCamera | new camera | camera.html |
getCameraTransform / setCameraTransform | camera position and rotation | camera.html |
getCameraProjection / setCameraProjection | perspective or orthographic | camera.html |
getCameraExposure / setCameraExposure | brightness before tone mapping | camera.html |
getCameraBloomStrength / setCameraBloomStrength | how much bright light glows | camera.html |
getCameraGrid / setCameraGrid | a reference grid in the camera's views | camera.html |
resetCameraHistory | start TAA over on a camera cut | camera.html |
getCameraController / setCameraController | trackball or free-fly | camera.html |
getProjectionMatrix, getProjectionMatrix(camera, aspect), getViewMatrix | camera matrices | camera.html |
updateCameraAspectRatio | aspect of every camera | camera.html |
pollEvents / updateCamera | the frame's input, and the camera control it drives | camera.html |
getCameraInput, getInputEvents, getUiInputCapture, getDeltaTime | read the frame's input, to move cameras yourself | camera.html |
setCameraButtons | which mouse button orbits and which pans | camera.html |
setMouseGrab | a camera drag goes on past the window's edge | camera.html |
createRenderGraph | new render graph | render-graph.html |
createPipeline / createComputePipeline | your own Slang shaders | render-graph.html |
createRenderTarget | offscreen color + depth | render-graph.html |
destroyTexture / destroyBuffer / destroyRenderTarget | free GPU resources, once the GPU is done with them | engine.html |
resizeRenderTarget | a fixed-size target at a new size, keeping its texture handles | engine.html |
destroyEntity, destroyMesh, destroyMaterial, destroyLight, destroyEnvironment, destroyCamera, destroyScene | destroy what you made; rows, ranges and indices are reused | scene.html, materials.html, camera.html |
removeEntityFromScene / removeLightFromScene | take an entity or light out of a scene | scene.html |
getPoolStats | live objects and pool use, for streaming budgets | engine.html |
getLoadStats | load workers, queued loads, decoded memory | engine.html |
setRenderTarget / resetRenderTarget | where the next pass draws | render-graph.html |
getRenderTargetTexture | read a target in a later pass | render-graph.html |
getPreviousRenderTargetTexture | read last frame's copy of a history target | render-graph.html |
getRenderTargetDepthTexture | read a target's depth in a later pass | render-graph.html |
getRenderTargetStorageIndex | write a storage target's color in a compute pass | render-graph.html |
getRenderContext | the low-level API | low-level.html |
getBindlessDescriptorSet | the texture set to bind | low-level.html |
2Create and shut down
Pick the object by who owns the window and the files:
Engine adds only the platform it picks (EngineConfig::platform): with SDL it opens its window and reads the events; NATIVE and HEADLESS do what a Renderer does. examples/21_renderer uses a Renderer with no window, examples/19_embedding one on its own SDL3 windows.explicit Renderer(const RendererConfig& config);
The renderer alone. With config.nativeWindow set it draws into that window (yours, which must outlive the renderer); without one it draws into offscreen images of windowWidth × windowHeight pixels, which readFrame copies back. It opens no window, reads no events (send yours with addInputEvent), and never stops by itself. RendererConfig has the fields of EngineConfig but platform. Then it starts like an Engine (below), and running() says whether it did.
rasm::RendererConfig config = {
.appName = "tiles",
.windowWidth = 1280,
.windowHeight = 720,
.shaderDir = "shaders"};
rasm::Renderer renderer(config);
if (!renderer.running())
return 1;
running() right after the constructor, like every example does. When it is false, the reason is in the log; do not use the engine further.Engine(const EngineConfig& config);
A Renderer on the platform of config.platform: SDL opens the main window and reads its events, NATIVE draws into config.nativeWindow, HEADLESS into offscreen images. It opens the main window and sets up the whole renderer. It also resolves shaderDir, assetRoot and cacheDir (see paths) and creates the default material. On any failure it logs an error and returns early, and running() stays false. A window width or height of 0 or less fails at once with "Window dimensions must be positive.".
- config
- Copied into the engine. Fields are in the EngineConfig table below (also on types.html).
rasm::Engine engine(config);
if (!engine.running())
return 1;
virtual ~Renderer();
An Engine's destructor too, so deleting an Engine through a Renderer* is safe; no other method is virtual. It waits for background loads that are still running, frees every GPU resource, destroys the window and shuts SDL down. Objects can be destroyed earlier, one by one: see destroyEntity, destroyMesh and the other destroy* calls in the table above.
bool running() const;
True while the engine works. With the SDL platform it becomes false when the window is closed or Esc is pressed (both handled in pollEvents, which beginFrame calls unless you did); with NATIVE or HEADLESS the application decides when to stop, and it stays true. It is false from the start when the constructor failed. Use it as the main loop condition.
struct EngineConfig // include/rasm/types.h
All settings of the engine. Pass it to the constructor; later changes to your copy have no effect. Use designated initializers and leave out what you do not need.
| Field | Default | Meaning |
|---|---|---|
appName | empty | Vulkan application name (rasm_app when empty). The window title is always "RASM Engine". |
platform | SDL | Who owns the window and the input (PlatformType). NATIVE: your window and your event loop (your own window). HEADLESS: no window; frames go to an offscreen swapchain (headless). |
windowWidth, windowHeight | 0, 0 | Window size in logical units (screen points), the unit of mouse positions, or the offscreen swapchain's size in pixels when headless. Must be greater than 0. |
nativeWindow | empty | With NATIVE: your window's handles, its size in pixels and its display's scale (NativeWindow). Ignored otherwise. |
enableValidation | false | Turns on the Vulkan validation layers, if they are installed. Keep it on while you develop. |
enableSyncValidation | false | With enableValidation: also reports missing or wrong barriers and read/write hazards between passes. Slow. Without enableValidation it is ignored, with a warning in the log. VK_LAYER_VALIDATE_SYNC=1 does the same without a rebuild. |
enableGpuValidation | false | With enableValidation: GPU-assisted validation checks shader accesses while they run, such as an out-of-bounds bindless index, bad indirect draw arguments or a bad buffer device address. Slow. Without enableValidation it is ignored, with a warning in the log. VK_LAYER_GPUAV_ENABLE=1 does the same without a rebuild. |
preferredBackend | Backend::VULKAN | Only VULKAN works. The others log "not implemented yet" and the engine does not start. |
assetRoot | empty | Folder that relative loadMesh and loadTexture paths start from. A relative assetRoot starts beside the executable. Empty: paths are used as given (relative to the working directory). |
shaderDir | empty | Folder with the engine's lib/ and passes/ shaders. Empty: the build-time default, shaders beside the executable (CMake -DRASM_SHADER_DIR=<path> changes it). A relative path starts beside the executable. |
cacheDir | "cache" | Folder of the shader and pipeline caches: compiled shaders in shaders/, and the Vulkan pipeline cache, one file per GPU. A relative path starts beside the executable; if that folder cannot be made or written (an installed application), the caches go to the user's local cache folder (%LOCALAPPDATA% on Windows, ~/Library/Caches on macOS, $XDG_CACHE_HOME or ~/.cache on Linux) plus rasm/<executable name>, with one log line. An absolute path is used as it is, with no fallback. If neither works, a warning, and the engine runs without caches. Empty: no disk caches, every shader is compiled and every pipeline built (tests, repeatable runs). The examples' --no-cache sets it. |
shaderThreads | 0 | Threads that compile shaders in the background (Shader warm-up): at startup every pipeline a frame can need has its shaders queued for them, so no frame compiles one. 0 takes half the hardware threads, at most 8; a larger count is kept to the hardware threads. Each thread that compiles holds a Slang global session of about 100 MB, only on a cold cache (the first run after a shader change, or a machine without a shipped cache) and only for about 1 s, until the queue is empty; a warm run makes none. Set fewer to cap that memory, at the cost of a longer cold start. |
geometryPoolVertices | 221 = 2,097,152 | Vertices of all meshes together, 64 bytes each (128 MiB). Fixed for the engine's life. |
geometryPoolColors | 220 = 1,048,576 | Vertex colors of the meshes that have them (glTF COLOR_0, or createMesh's colors), 4 bytes each (4 MiB). A mesh without colors uses none. Fixed for the engine's life. |
geometryPoolSkins | 220 = 1,048,576 | Joints and weights of the skinned vertices (glTF JOINTS_0 / WEIGHTS_0, a SkinVertex each), 16 bytes each (16 MiB). A mesh that is not skinned uses none. Fixed for the engine's life. The posed vertices go to buffers that grow by themselves (64 bytes per vertex per frame slot, per playing entity). |
geometryPoolMorphs | 220 = 1,048,576 | Morph target deltas (a MorphDelta per vertex and target), 24 bytes each (24 MiB). A mesh without morph targets uses none. Fixed for the engine's life. A mesh that does not fit fails to load with an error that names this setting. |
geometryPoolIndices | 224 = 16,777,216 | Indices of all meshes together, LODs included, 4 bytes each (64 MiB). The LODs take up to as many again as LOD 0. |
geometryPoolSubMeshes | 214 = 16,384 | Sub-meshes of all meshes together (200 bytes each: about 3.1 MiB). |
geometryPoolMeshlets | 217 = 131,072 | Meshlets of all meshes together, every LOD included, 48 bytes each (6 MiB). Every sub-mesh of 1024 triangles or more that is not skinned or morphed gets about one per 124 triangles of each LOD as it loads. A sub-mesh whose meshlets do not fit loads without them and is drawn whole, with one warning that names this setting. See meshlets. |
geometryPoolPoints | 220 = 1,048,576 | Point cloud chunks (point clouds), in units of 8 bytes (8 MiB): a point takes one unit, one and a half with colors, and a chunk six more for its header. Made with the first chunk, so a program without point clouds has none; 0 refuses every chunk. Fixed for the engine's life; a chunk that does not fit fails with an error that names this setting. |
maxInstances | 216 = 65,536 | Instance rows: one per sub-mesh of every entity. 164 bytes each, two copies (one per frame slot). Each scene view with occlusion culling also keeps this many words of meshlet visibility bits (4 bytes each). |
maxLights | 214 = 16,384 | Lights in total (createLight). 56 bytes each, two copies (about 1.8 MiB). 0, or a table larger than the GPU allows, logs an error and the engine does not start. |
maxBindlessTextures | 214 = 16,384 | Sampled textures at once: slots of the bindless set, which materials, glTF images, render targets and the UI take. Lowered with a warning to what the device allows and to MAX_BINDLESS_TEXTURES; getConfig gives the count the renderer got. A texture past it logs an error that names this setting and samples nothing. |
maxMaterials | 212 = 4,096 | Materials alive at once (createMaterial, and each glTF material), one material table row each: 304 bytes, two copies. A material past it is refused with an error that names this setting. 0 logs an error and the engine does not start. |
maxAnimatedEntities | 214 = 16,384 | Entities that have played a clip (playAnimation), and entities of a skinned or morphed mesh, which are posed at rest; each keeps its row. 120 bytes each, two copies. A play past it is refused with an error. 0, or more than 65,535 (one Animate group per row), logs an error and the engine does not start. |
animationPoolBytes | 16 MiB | The kept nodes, samplers, channel tables and keys of every loaded mesh with clips, uploaded once per mesh. A mesh that does not fit fails to load with an error that names this setting. |
loadThreads | 0 | Threads of the load worker pool, which reads and decodes every loadMesh, loadTexture and loadEnvironment. 0 takes the hardware threads minus one, for the main thread (at least 1). The workers run below the main thread's priority (lowerThreadPriority). A game with threads of its own (physics, audio, its own jobs) sets fewer, so the loads do not take the cores those need. See Job systems. |
loadMemoryBudget | 512 MiB | Decoded load data in memory at once: what running loads hold and the results that wait for upload. A load whose estimate (from the file's header) would pass it waits in the queue, as a path, until earlier results are uploaded. One load bigger than the budget still runs, alone. getLoadStats shows the use. |
maxMorphWeights | 216 = 65,536 | Morph weights of all posed entities together (setMorphWeights); each entity of a morphed mesh keeps its range. 4 bytes each, four times: a weight buffer and an override table, each with one copy per frame slot (1 MiB). An entity past it is not posed, with an error that names this setting. 0 logs an error and the engine does not start. |
showStats | false | Shows the stats from the first frame: the RASM window with ui, the stats overlay without. F1 toggles it at runtime. |
fixedDeltaTime | 0.0f | Seconds per frame for the cameras' movement and easing, Dear ImGui and the refresh of the stats (every 0.25 s of these steps). 0: the measured time since the last frame, at most 0.1 s. A fixed step makes frame N the same in every run, for screenshots and image checks; the examples' --fixed-step sets 1/60. FrameStats::cpuFrameMs stays measured. |
occlusionCulling | true | Two-pass Hi-Z occlusion culling in the scene passes: draws hidden behind others are not drawn. It also makes D32_SFLOAT depth textures sampleable, which readDepth needs (a depth-only target's depth always is, and so is that of a target with a MOTION_FORMAT color, for TAA). false keeps frustum culling only. See occlusion culling. |
meshLods | true | Builds coarser levels of detail (LODs) of every sub-mesh with 1024 triangles or more as meshes load, on the worker thread for loadMesh. false: meshes have LOD 0 only. |
lodErrorPixels | 1.0f | Culling draws the coarsest LOD whose error stays under this many pixels on screen. Larger is faster and coarser; 0 always draws LOD 0. See level of detail. |
forcedLod | -1 | For debugging. From 0 up, every draw uses this LOD (or its mesh's coarsest one), whatever the distance. -1 picks by distance. F2 cycles it at runtime. |
meshletPath | MeshletPath::AUTO | How the scene passes draw a visible mesh whose LOD has 8 meshlets or more (MeshletPath). OFF: whole. VERTEX_PULLING: compute culls each meshlet (frustum, back faces, Hi-Z) and draws the visible ones by indirect draws. MESH_SHADERS: a task shader culls them inside the draw, and mesh shaders draw them (vertex pulling where the GPU has none). The image is the same either way. AUTO takes the mesh shaders where the GPU has them and is off elsewhere: on the RTX 3060 they cost about 1% when LODs already cut the triangles and save up to 30% on dense meshes, while vertex pulling costs 11% in the first case (P28). setMeshletPath changes it at run time. See meshlets. |
geometryPoolMeshletData | 223 = 8,388,608 | Where the GPU has mesh shaders: the words the mesh shaders read, 4 bytes each (32 MiB, about 50k meshlets): each meshlet's vertices, then its triangles packed a word each. Not made without mesh shaders; 0 leaves it out and turns the mesh-shader path off (MESH_SHADERS then draws by vertex pulling, AUTO whole). A sub-mesh whose words do not fit loads without meshlets and is drawn whole, with one warning that names this setting. |
maxViewMeshlets | 216 = 65,536 | With VERTEX_PULLING: meshlet draws per scene view and frame slot, 20 bytes each (1.3 MiB), made only for views that draw meshlets and only as large as their meshes can need. A draw past it is drawn whole, and FrameStats::meshletDrawsWhole counts it. |
asyncCompute | false | Runs the scene's culling and Hi-Z passes, and every pass added with addAsyncComputePass, on a second GPU queue next to the graphics work. Needs a GPU with a compute queue family without graphics; without one, everything stays on the graphics queue, as with false. Off by default: today it does not make the scene passes faster (P11). examples/03_instances turns it on. See async compute. |
transferQueue | true | Loads copy their textures and geometry on the GPU's copy engine, a queue family that only copies, next to the graphics work; a load counts as loaded once its copies are done, so the frames never wait for them. Without such a family (lavapipe, MoltenVK, most Intel GPUs), and with false, the copies run on the graphics queue, by the same code. On by default: with a busy GPU loads end sooner, with an idle one nothing changes (D13). The examples' --transfer-queue on|off sets it. See transfer queues and ownership transfers. |
clusteredLighting | true | Each shaded view sorts its lights with a range into clusters, and each pixel shades only its cluster's lights (about 6.8 MiB per view and frame slot). false: every pixel shades every light of the scene, with the same image and a much higher cost; for comparison and debugging. See clustered lighting. |
hostImageCopy | true | Fills textures on the CPU through host image copy where the GPU allows it for the format. false copies every texture from the staging ring instead (on the transfer queue for a load's), as on a GPU without host image copy: for testing that path, or to compare the two. Formats without host image copy use the staging ring either way. See GPU memory and uploads. |
computePoints | true | Point cloud chunks whose points are up to 6 pixels (8 at their nearest point; 4 in an orthographic view, 2 in a view with MSAA), and dense enough on screen, are written by a compute pass with 64-bit atomics instead of drawn by triangles, two (6 pixels) to twelve (1 pixel) times faster per point, where the GPU has shaderBufferInt64Atomics (RenderContext::hasBufferInt64Atomics; MoltenVK may not). Both take the same pixels. false: every point by triangles. setComputePoints changes it at run time. See point clouds. |
antiAliasing | NONE | How render smooths edges (AntiAliasing): MSAA_2X, MSAA_4X or MSAA_8X draws the scene with that many samples per pixel and resolves them with addMsaaResolvePass; cut-out (MASK) materials then use alpha-to-coverage. A count the device does not have falls back to the most it has, with a warning. TAA gives the scene target a motion color and adds addTaaPass. See MSAA and alpha-to-coverage and Temporal anti-aliasing. |
bloom | false | render adds the bloom passes and mixes them in by the camera's bloom strength. Off by default, so an engine update does not change how an application looks. See bloom. |
ui | false | Runs Dear ImGui: F1 shows the RASM window instead of the stats overlay, and setUiCallback adds your windows. Needs a rasm built with the CMake option RASM_IMGUI (on by default); without it, a warning and no UI. Off: ImGui does nothing and costs nothing. See UI with Dear ImGui. |
A destroyed mesh gives its geometry ranges back, and a destroyed entity its instance rows (deferred destruction). When a pool is full, the next mesh or entity fails with an error that names the EngineConfig field to raise and the largest free range. Size the pools for what is alive at once, with room for fragmentation.
3Run a frame
A frame is beginFrame, then one or more passes, then endFrame. render does all of it for one view, or for a list of views, through a render graph with the scenes' passes. Here is what each part does inside:
beginFrame returns false, record nothing and do not call endFrame. Try again next loop. A resize is handled inside beginFrame: it rebuilds the swapchain and the render targets sized from it.void render(SceneHandle scene, CameraHandle camera);
One whole frame of the scene, drawn into the window: render(views, count) with one View of the whole window. The engine keeps a render graph with the scene's passes (addScenePasses into a 16-bit float target, scene_hdr, with EngineConfig::bloom addBloomPasses, then addToneMapPass into the swapchain, and with EngineConfig::ui addUiPass over it) and runs it with RenderGraph::execute: beginFrame(camera), the passes, endFrame. It builds the graph again only when scene, camera or the window's size in pixels changes, also after a failure: a view whose passes could not be added is not tried again until one of them changes. When beginFrame returns false, no pass runs.
- scene
- The scene to draw. Invalid: an error is logged once, and the window is only cleared.
- camera
- Gets this frame's input (mouse, keys) and is the view. It does not need to be in the scene.
while (engine.running())
engine.render(scene, camera);
void render(const View* views, uint32_t viewCount);
One frame of several views: split screen, a map over the scene, editor viewports, a camera's picture as a texture. Each View is a scene, a camera and an output: a rect of the window, or a rect of a color target (a view texture that a material or ImGui::Image shows). How it works: Many views of one scene.
- Each view gets the scene passes into an HDR target of its rect's size in pixels, an MSAA resolve or TAA by its anti-aliasing, its bloom, and a tone map into its rect. The UI pass comes last.
- Views draw in list order: a later view's rect goes over an earlier one, and a view's scene passes see this frame's picture of the view textures listed before it (the views before it, and its own, see the last frame's).
- A view keeps its HDR target, its culling history (Hi-Z, visibility) and its TAA history while its camera and
output.targetstay in the list, wherever it is in the list. Another view's insertion, removal or move does not reset it. - The graph is built again only when the list or a view's size in pixels changes; a frame with the same list and sizes allocates nothing. A view that changed size makes its targets again at the new size (
resizeRenderTarget: one wait for the frames in flight). - A view with
shadowsdraws them before its scene passes, fitted to its own camera. Views of different cameras draw one set of maps per light, map size and count in turn, so the maps' memory does not grow with the views; each view's maps still take scene views (MAX_SCENE_VIEWS). A view without shadows costs what it did before. - The camera of the first view in the window (no
output.target) takes the built-in controller, throughbeginFrame; a list of view textures only gives it the first view's camera.CameraController::Type::NONEturns it off. Give each other view's camera its own input withgetInputArea.
- views, viewCount
- The list, read during the call only. A view with an invalid scene or camera, or with the camera and output target of an earlier view, is left out with an error, and the others draw. A view whose passes cannot be added (the
MAX_SCENE_VIEWSlimit, a target that is not one color with no depth and one sample, a destroyed target) is left out until the list changes; nothing is made for it. 0 views: the window shows the clear color and the UI.
// From examples/20_views/main.cpp: the TV's picture first, then split screen and a map in the corner.
views.clear();
views.push_back({.scene = scene, .camera = security, .output = {.target = tv}, .bloom = rasm::ViewToggle::OFF, .antiAliasing = rasm::AntiAliasing::NONE});
views.push_back({.scene = scene, .camera = main.camera, .output = {.rect = rects.rects[0]}});
views.push_back({.scene = scene, .camera = side.camera, .output = {.rect = rects.rects[1]}});
views.push_back({.scene = scene, .camera = map, .output = {.rect = rects.rects[2]}, .bloom = rasm::ViewToggle::OFF, .antiAliasing = rasm::AntiAliasing::NONE});
engine.render(views.data(), static_cast<uint32_t>(views.size()));
struct View
{
SceneHandle scene;
CameraHandle camera;
ViewOutput output = {};
ViewToggle bloom = ViewToggle::DEFAULT; // DEFAULT: EngineConfig::bloom
AntiAliasing antiAliasing = AntiAliasing::DEFAULT; // DEFAULT: EngineConfig::antiAliasing
ShadowDesc shadows[MAX_VIEW_SHADOWS] = {}; // lights of the scene, one shadow each
uint32_t shadowCount = 0;
bool operator==(const View&) const = default;
};
One view of render(views, count), in rasm/view.h. bloom and antiAliasing override the engine's settings for this view: a small map skips bloom and TAA and costs less. A change of antiAliasing makes the view's targets again, so its TAA history starts over.
The first shadowCount of shadows (up to MAX_VIEW_SHADOWS, 4, of different lights) are ShadowDescs the view draws as addShadowPasses does, each frame, from its camera: cascades fitted to its frustum and LODs from its camera. A changed list builds the graph again. exportView draws no shadows (D58). How the maps are shared: Shadows per view.
// From examples/20_views/main.cpp: the sun's shadow in four cascades, fitted to the main camera.
const rasm::ShadowDesc sunShadow = {.light = sun, .cascadeCount = 4, .size = 2048, .distance = 30.0f};
views.push_back({.scene = scene, .camera = main.camera, .output = {.rect = rects.rects[0]}, .shadows = {sunShadow}, .shadowCount = shadowCount});
struct ViewOutput
{
ViewRect rect = {};
RenderTargetHandle target; // valid: into this target, one color and no depth (R8G8B8A8_SRGB for a picture)
WindowHandle window; // without a target: this window (Renderer::addWindow); invalid: the main window
bool operator==(const ViewOutput&) const = default;
};
Where the tone map draws a view: rect of the main window or of window (addWindow), or with target set, rect of that target. A view whose window was removed draws nothing. A view texture is a target you make with createRenderTarget: one color, no depth, one sample. Make it R8G8B8A8_SRGB, the format of a color texture: the tone map writes linear light, and the sRGB format encodes it. It starts cleared to its clearColor, so it can be sampled before its first frame. Its texture (getRenderTargetTexture) is one handle for both frame slots, kept across resizeRenderTarget: give it to a material's textures (the emissive slot for a screen) or to getUiTexture.
// From examples/20_views/main.cpp
const rasm::RenderTargetHandle tv = engine.createRenderTarget({.name = "tv",
.width = TV_WIDTH,
.height = TV_HEIGHT,
.colorFormats = {rasm::Format::R8G8B8A8_SRGB},
.clearColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)});
const rasm::TextureHandle tvPicture = engine.getRenderTargetTexture(tv);
struct ViewRect
{
float x = 0.0f;
float y = 0.0f;
float width = 1.0f;
float height = 1.0f;
bool operator==(const ViewRect&) const = default;
};
A part of the window or of a target, as fractions of its size from the top-left corner: {} is all of it, {.x = 0.5f, .width = 0.5f} the right half. Fractions follow a resize. getViewPixels turns it into pixels.
enum class ViewToggle : uint8_t
{
DEFAULT, // the EngineConfig value
OFF,
ON,
};
A view's choice for a setting EngineConfig also has (View::bloom). View::antiAliasing uses AntiAliasing::DEFAULT the same way; in EngineConfig, DEFAULT means NONE.
ViewPixels getViewPixels(const ViewRect& rect, uint32_t width, uint32_t height);
The pixels rect covers in an image of width × height, as a ViewPixels (x, y, width, height, all uint32_t). Each edge is rounded on its own, so rects that touch share their edge: no gap and no overlap. Edges are kept inside the image, and the result is at least 1 × 1 (0 × 0 for an empty image). The tone map uses it for its viewport and scissor, and render for each view's target size.
const rasm::ViewPixels pip = rasm::getViewPixels({.x = 0.75f, .y = 0.0f, .width = 0.25f, .height = 0.25f}, 1280, 720);
// pip is {960, 0, 320, 180}
bool getViewPixel(const Window& window, const ViewRect& rect, float x, float y, uint32_t& pixelX, uint32_t& pixelY);
The pixel of a window view (the view at rect of window) under a point in the window's points, such as the mouse's, counted from the view's top-left corner: what pick takes. It turns points into pixels with the window's pixel size, so it holds on a HiDPI display. False when the point is outside the view.
InputArea getInputArea(const Window& window, const ViewRect& rect);
The view's rect in the window's points, as an InputArea for the view's own CameraInputState: a drag that starts in it moves only this view's camera.
// From examples/20_views/main.cpp
const rasm::InputArea area = rasm::getInputArea(engine.getMainWindow(), rect);
const rasm::UiInputCapture capture = engine.getUiInputCapture();
uint32_t count = 0;
const rasm::InputEvent *events = engine.getInputEvents(count);
for (uint32_t i = 0; i < count; ++i)
rasm::addCameraInputEvent(view.input, events[i], area, capture);
rasm::updateCameraRig(view.rig, rasm::takeCameraInput(view.input, capture, engine.getDeltaTime()));
engine.setCameraTransform(view.camera, view.rig.transform);
[[nodiscard]] bool beginFrame(CameraHandle camera);
Starts a frame (steps in the diagram above). It handles window events and moves camera with the input, finishes background loads for up to 4 ms, waits until this frame slot is free, uploads changed scene data, acquires a window image and starts the frame's command buffer.
- camera
- The camera that the mouse and keyboard move. Invalid: "Invalid camera handle." is logged every frame, and the frame still runs.
- returns
falsewhen the frame must be skipped: window minimized or 0 pixels wide, swapchain rebuild failed, fence wait failed, or the image could not be acquired. Then record nothing and do not callendFrame.
may block It waits for the GPU when the CPU is 2 frames ahead.
void endFrame();
Ends the frame's command buffers and sends the frame to the GPU, then shows it in the window. If no pass drew to the window this frame (for example, all passes drew to render targets), it adds a pass that clears the window first. With the stats overlay shown, it draws the overlay in a pass of its own on top. Without async compute the frame is one command buffer: culling is recorded in it as ordinary scene passes. With EngineConfig::asyncCompute it is a few batches, each one command buffer and one submit on one queue. They are all submitted here, in the order they were closed. The last graphics batch waits for all of the frame's compute work, and presents.
Call it only after a beginFrame that returned true, and after the last endPass.
void beginPass(const std::string& name = "Pass", const AttachmentOps& ops = {});
Starts rendering into the current target: the window, or the render target set with setRenderTarget. By default it clears color and depth (their old contents are dropped), sets the viewport and scissor to the whole target, and sets cull mode to none. Only between beginFrame and endFrame. A pass on a window with no image this frame (the main window minimized while another window shows) draws nothing: beginFrame returns true while any window has an image.
- name
- Label of the pass. It names the pass's GPU timer in
getFrameStatsand the stats overlay. - ops
- Which attachments to keep instead of clearing, and whether to keep depth at the end. See AttachmentOps. A render graph sets them for you.
The window is cleared to a dark gray and has no depth: draw anything that needs a depth test into a render target. A render target is cleared to its own clearColor.
struct AttachmentOps
{
bool loadColor = false;
bool loadDepth = false;
bool storeDepth = false;
bool firstWrite = false;
bool encodedColor = false;
};
What a pass does with its attachments. The defaults clear both and throw depth away at the end.
- loadColor, loadDepth
true: keep what the attachment holds, and draw on top.false: clear it (color to the target's clear color, depth to 0).- storeDepth
true: keep depth at the end of the pass, for a later pass that loads it or samples it. Color is always kept. A render graph sets it on the pass before one that loads the target or reads its depth (readDepth).- firstWrite
true: no earlier pass drew into the target this frame. For a cube target (RenderTargetDesc::cube) a pass draws one face, but the layout change before it covers all six. Only with this set doesbeginPasslet a clearing pass drop the whole cube's old contents; otherwise it keeps the other faces. A render graph sets it on a target's first pass of the frame. Leave itfalsewhen you draw a cube's faces by hand: every face you draw stays.- encodedColor
true: draw the swapchain through its UNORM view, where the device has one (getSwapchainEncodedFormat). The pass then writes and blends the stored sRGB numbers as they are, and its pipelines must be made for that view's format. A render graph sets it for the UI pass. It has no effect on render targets or on a swapchain without the view.
// A hand-written frame: two passes on the window, the second on top of the first
engine.beginPass("Background");
// ... draw the background
engine.endPass();
engine.beginPass("UI", {.loadColor = true});
// ... draw the UI
engine.endPass();
void endPass();
Ends the pass. On a render target, it moves the color image to the sampled layout, so later passes can sample it (see getRenderTargetTexture). The depth image stays a depth attachment; in a graph, a later pass that declares readDepth gets it moved to the sampled layout. endFrame moves the swapchain image to the present layout.
bool addScenePasses(RenderGraph& graph, SceneHandle scene, CameraHandle camera, const RenderTargetHandle& renderTarget, const SceneShadow* shadows = nullptr, uint32_t shadowCount = 0,
const RenderTargetHandle* sampled = nullptr, uint32_t sampledCount = 0);
Adds the passes that draw scene from camera to graph. They are ordinary graph passes: the graph sorts them with your passes, records their barriers from what they declare, and times each one under its name. render calls it for you; call it yourself when you build your own graph. The culling passes and Hi-Z are async compute passes: with EngineConfig::asyncCompute they run on the compute queue.
- graph
- The graph to add to, before its
compile. Add your own passes before or after. - scene
- Invalid: logs
addScenePasses needs a valid scene handle., adds nothing and returnsfalse. - camera
- The view. Its projection is fitted to the target's aspect ratio every frame; the camera itself does not change. Invalid: logs an error, adds nothing and returns
false. - renderTarget
- Where the scene is drawn. A target needs one color in
SCENE_COLOR_FORMATandD32_SFLOATdepth, the formats of the scene's pipeline. The color is linear light with no upper limit: draw it to the window withaddToneMapPass. A second color ofMOTION_FORMAT(one sample only) takes each pixel's motion, foraddTaaPass. The target may have several samples per pixel (samples, MSAA): the scene's pipelines are made for its count, cut-out materials use alpha-to-coverage, and the Hi-Z reads every depth sample; resolve it withaddMsaaResolvePass. Invalid: logs an error, adds nothing and returnsfalse. A target withD32_SFLOATdepth and no color is depth-only: the scene's depth is drawn and nothing else, in passes namedShadow 1,Shadow 2, … (a depth pre-pass, for example; shadows come fromaddShadowPasses). Make it withRenderGraph::createRenderTargetbefore this call. - shadows, shadowCount
- Up to
MAX_VIEW_SHADOWS(4) shadows (SceneShadow), of different lights, thataddShadowPassesreturned for the same scene and camera in this graph. Each darkens its own light. The draw passes read every map's depth, so the graph runs them after the map passes.nullptrand 0 (the default): no shadow. More than 4, two of one light, a shadow thataddShadowPassesdid not make for this scene and camera in this graph, a shadow that another view in the graph already reads (cascades are fitted to one view's aspect ratio), or shadows on a depth-only view, log an error, add nothing and returnfalse. A cube render target (RenderTargetDesc::cube) is not a validrenderTarget. - sampled, sampledCount
- View textures (color targets that other passes of the graph draw, see
ViewOutput) that the scene's materials sample. The draw passes read them, so the graph runs them after those textures' writers and the materials see this frame's picture. Without it a material sees this frame's or the last frame's, whichever the graph's order gives; it is never read while it is drawn. The view's own target, an invalid target or one without a color logs an error, adds nothing and returnsfalse. - returns
truewhen the passes were added. Onfalsenothing was added.
Cull 1 keeps the draws that were visible last frame, Scene 1 draws them, Hi-Z builds a depth pyramid from their depth, Cull 2 tests the other draws against it, and Scene 2 draws the ones it found visible. See occlusion culling.Cull 1 waits only for its own slot's last frame. It can run on the compute queue while the frame before still draws. That is the only overlap today, so the option is off by default (P11). See async compute.// From examples/01_render_graph/main.cpp: the scene into an offscreen target
const rasm::RenderTargetHandle rtHandle = graph.createRenderTarget({
.name = "offscreen_rt",
.swapchainScale = 1.0f,
.colorFormats = {rasm::SCENE_COLOR_FORMAT},
.depthFormat = rasm::Format::D32_SFLOAT,
.clearColor = glm::vec4(0.0f), // alpha 0 marks the background
});
// The scene's culling and draw passes, into offscreen_rt. The passes below read what they drew.
if (!engine.addScenePasses(graph, scene, camera, rtHandle))
{
return 1;
}
SceneShadow addShadowPasses(RenderGraph& graph, SceneHandle scene, CameraHandle camera, const ShadowDesc& desc);
Adds a light's shadow to graph: depth-only maps of the scene, each drawn by a scene view of camera. Give the returned SceneShadow to addScenePasses for the same scene and camera. The maps depend on the light's type:
| Light | Maps | Scene views | Guide |
|---|---|---|---|
DIRECTIONAL | cascadeCount cascades, shadow_cascade_0, …, each covering a slice of the camera's view out to distance, fitted every frame | cascadeCount | Cascaded shadow maps |
SPOT | one perspective map at the light along its cone, shadow_spot_<light index> | 1 | Spot and point light shadows |
POINT | one cube map, shadow_cube_<light index> | 6 (one per face) |
- graph
- The graph to add to, before its
compile. It owns the maps' targets, so they live as long as the graph. - scene
- The scene whose depth the maps hold. Invalid: logs an error and returns an empty shadow.
- camera
- The camera you then give
addScenePasses. A directional light's cascades follow its view. Every map's view takes its level of detail from this camera, so a mesh is drawn at the same level in both. Invalid: logs an error and returns an empty shadow. - desc
- The light and its maps (
ShadowDesc). An invalid light or asizeof 0 logs an error and returns an empty shadow. So does, for a directional light, 0 or more thanMAX_SHADOW_CASCADES(4) cascades, adistancenot beyond the camera's near plane or asplitLambdaoutside 0 to 1, and for a spot or point light adistancethat is not finite and above 0. So do fewer free scene views than the shadow needs: nothing is added then. - returns
- The shadow, with
mapCount0 on failure. Each map's depth ismaps[i], which a pass of yours can read withreadDepth.
Shadows. Call addShadowPasses for each light, then addScenePasses with the shadows it returned. The order of the passes does not matter: the graph sorts them by the depth reads. Each cascade, spot map and cube face is one scene view: a sun with 4 cascades, a spot light, a point light and the shaded view take 12 of the MAX_SCENE_VIEWS (32).
// From examples/06_shadows/main.cpp
const rasm::SceneShadow shadow = engine.addShadowPasses(graph, scene, camera, rasm::ShadowDesc{.light = sun, .cascadeCount = CASCADE_COUNT, .size = 2048, .distance = 60.0f, .splitLambda = 0.7f});
if (shadow.mapCount == 0 || !engine.addScenePasses(graph, scene, camera, sceneTarget, &shadow, 1))
return 1;
// From examples/07_lights/main.cpp: three lights, each with its own shadow, read by one view.
const rasm::SceneShadow shadows[] = {
engine.addShadowPasses(graph, scene, camera, rasm::ShadowDesc{.light = moon, .cascadeCount = 4, .size = 2048, .distance = 40.0f}),
engine.addShadowPasses(graph, scene, camera, rasm::ShadowDesc{.light = lamp, .size = 2048, .distance = 40.0f}),
engine.addShadowPasses(graph, scene, camera, rasm::ShadowDesc{.light = lantern, .size = 1024, .distance = 14.0f}),
};
if (!engine.addScenePasses(graph, scene, camera, sceneTarget, shadows, 3))
return 1;
A light taken out of the scene casts no shadow, and its maps draw nothing; so does a directional light's shadow when the camera's near plane is moved to distance or beyond. Points farther than distance from the camera are lit; a directional shadow fades out over the last tenth of it. Casters up to distance toward the sun from a slice are in its map. A spot or point light shadows up to distance from the light. Every shadow uses 3x3 PCF. Each shadow darkens only its own light; lights without one and the ambient term are not shadowed. How it works: Shadow mapping, Cascaded shadow maps and Spot and point light shadows.
Scene views. Each (scene, camera, target, face, shadows) is a scene view, with its own culling buffers on the GPU; the face is a cube's, for a point light's map. A view lives while a graph holds it: graphs built for the same five share it, and when the last of them is destroyed or replaced, the view's buffers are freed. Views let one frame draw several scenes, cameras or targets. The scene's lights are read every frame. Nothing is drawn, with no error, while the scene is empty or all its entities still load: the target keeps its clear color.
Culling also picks each visible draw's level of detail from its distance to the camera and EngineConfig::lodErrorPixels. A view drawn without culling draws LOD 0.
| Rule | What happens otherwise |
|---|---|
At most MAX_SCENE_VIEWS (32) scene views held by graphs at once | An error ("All 32 scene views (MAX_SCENE_VIEWS) are held by render graphs ...; this view is not drawn."), nothing added, false |
| One graph adds each scene view once | An error, nothing added, false |
A valid render target with a SCENE_COLOR_FORMAT color (and a MOTION_FORMAT second color only with one sample) and D32_SFLOAT depth, or D32_SFLOAT depth only | An error, nothing added, false |
The scene shader passes/rasm.slang must compile | An error is logged; the engine tries again next frame, so a fixed shader file is picked up while the program runs |
The culling shader passes/cull.slang should compile | The scene is still drawn, only without culling. Without passes/hiz.slang, or when the view's occlusion buffers cannot be made, it is frustum culled only. |
RenderTargetHandle addMsaaResolvePass(RenderGraph& graph, const RenderTargetHandle& source, CameraHandle camera);
Adds a compute pass named MSAA Resolve that turns the samples of each pixel of source's color 0 into one color, in a new single-sample target. Each sample is weighted by 1 / (1 + its brightness × the camera's exposure), so an edge between a bright sky and a dark roof keeps its in-between shade after tone mapping, where a plain mean would look almost like the sky. Give the target it returns to addBloomPasses and addToneMapPass. render adds it when EngineConfig::antiAliasing is an MSAA mode. How it works: MSAA and alpha-to-coverage.
- graph
- The graph to add to, before its
compile. The pass readssource, so the graph runs it after the passes that draw it. - source
- A target with
samplesabove 1 and a color, usually the oneaddScenePassesdrew. Invalid, single-sample or depth-only: logs an error, adds nothing and returns an invalid handle. - camera
- Its exposure is read each time the pass runs. Invalid: logs an error, adds nothing and returns an invalid handle.
- returns
- The resolved target, <source name>_resolved: a transient storage target of
SCENE_COLOR_FORMAT, the source's size, one sample. Invalid when the target can't be made (no free storage slot, for example; the error says why). The pipeline is made the first time the pass runs; ifpasses/msaaResolve.slangdoes not compile, it logs an error and tries again next frame.
At 1920 × 1080 on an RTX 3060 it takes 0.12 ms at 2 samples, 0.14 ms at 4 and 0.38 ms at 8.
// From examples/09_gltf_materials/main.cpp
rasm::RenderTargetHandle resolved = sceneTarget;
if (samples > 1)
resolved = engine.addMsaaResolvePass(graph, sceneTarget, camera);
RenderTargetHandle addTaaPass(RenderGraph& graph, const RenderTargetHandle& source, CameraHandle camera);
Temporal anti-aliasing. The scene view that draws source in this graph is jittered by a sub-pixel offset each frame, reads its textures one mip sharper, and writes each pixel's motion into source's second color. The compute pass TAA then blends each frame into a history: it reads the history where each pixel was last frame, clips it to the colors around the pixel, and keeps about 10 frames. Give the target it returns to addBloomPasses and addToneMapPass. render adds it with EngineConfig::antiAliasing = AntiAliasing::TAA. How it works: Temporal anti-aliasing.
- graph
- The graph to add to, after
addScenePassesdrewsourcein it, before itscompile. - source
- A single-sample target with colors
{SCENE_COLOR_FORMAT, MOTION_FORMAT}andD32_SFLOATdepth. A multisampled one logs that TAA and MSAA exclude each other; any other, or one no scene view of this graph draws, logs an error. Then it adds nothing and returns an invalid handle. - camera
- Its exposure weighs bright pixels down; its moves decide when the history is dropped. Invalid: logs an error, adds nothing and returns an invalid handle.
- returns
- The history target, <source name>_taa: a storage target with history (two copies of
SCENE_COLOR_FORMAT, the source's size), owned by the graph. Invalid when it can't be made. The pipeline is made the first time the pass runs; ifpasses/taa.slangdoes not compile, it logs an error and tries again next frame.
The history is dropped in the first frame, after a resize, after resetCameraHistory, and when the camera turns more than 30° or moves more than 100 near planes (half its width, for an orthographic camera) in one frame. The same frames give the same pixels. At 1920 × 1080 on an RTX 3060 the pass takes 0.37 ms, and writing the motion adds about 0.13 ms to the draw passes.
// As examples/09_gltf_materials/main.cpp does with --aa taa
const rasm::RenderTargetHandle sceneTarget = graph.createRenderTarget({
.name = "scene_hdr",
.swapchainScale = 1.0f,
.colorFormats = {rasm::SCENE_COLOR_FORMAT, rasm::MOTION_FORMAT},
.depthFormat = rasm::Format::D32_SFLOAT,
});
// ... addShadowPasses, addScenePasses(graph, scene, camera, sceneTarget, &shadow, 1)
const rasm::RenderTargetHandle resolved = engine.addTaaPass(graph, sceneTarget, camera);
RenderTargetHandle addBloomPasses(RenderGraph& graph, const RenderTargetHandle& source, CameraHandle camera);
Adds the bloom of source: 11 compute passes, Bloom Down 1 to Bloom Down 6 and Bloom Up 5 to Bloom Up 1, that blur its light at six sizes, from half the source down to 1/64. Give the target it returns to addToneMapPass, which mixes it into the image. render adds it when EngineConfig::bloom is on (off by default). How it works: Bloom.
- graph
- The graph to add to, before its
compile. The passes readsource, so the graph runs them after the passes that draw it. They make 11 transient storage targets in the graph, which share memory with the graph's other transient targets. - source
- Color 0 is read, as linear light: the target
addScenePassesdrew. The levels are sized from it: a target sized from the window gives levels that follow the window. A small source runs fewer levels: the chain stops at the last level of at least 2 × 2. Invalid, a depth-only target, or a multisampled one (resolve it first withaddMsaaResolvePass): logs an error, adds nothing and returns an invalid handle. - camera
- Its bloom strength is read each time the passes run. At 0 they dispatch nothing (the graph still records their barriers). Invalid: logs an error, adds nothing and returns an invalid handle.
- returns
- The bloom target, half the size of
source, or an invalid handle when the passes could not be added, for example when the storage slots ran out (the error names the limit). The pipelines are made the first time the passes run. Ifpasses/bloom.slangdoes not compile, they log an error, the frame has no bloom, and they try again next frame.
The passes share one GPU timer, Bloom. In examples/09_gltf_materials (RTX 3060, Release) it takes about 0.2 ms at 1280 × 720 (0.10 to 0.27 ms from run to run), 0.37 ms at 1920 × 1080 and 0.75 ms at 3840 × 2160.
// From examples/09_gltf_materials/main.cpp
// resolved: the scene target, or what addMsaaResolvePass or addTaaPass returned
const rasm::RenderTargetHandle bloomTarget = bloom ? engine.addBloomPasses(graph, resolved, camera) : rasm::RenderTargetHandle{};
if ((bloom && !bloomTarget.isValid()) || !engine.addToneMapPass(graph, resolved, camera, bloomTarget))
return 1;
With Renderer::render, one line turns it on: config.bloom = true; before the engine is made.
bool addToneMapPass(RenderGraph& graph, const RenderTargetHandle& source, CameraHandle camera, const RenderTargetHandle& bloom = {}, const ViewOutput& output = {});
Adds a graphics pass named Tone Map that draws source into the window, or into a rect of it or of a view texture. It mixes in the bloom, multiplies the color by the camera's exposure and maps it to the range the screen shows with AgX; the sRGB swapchain then encodes it. render calls it after the scene passes; call it yourself as the last pass of your own graph that draws the scene. How it works: Tone mapping.
- graph
- The graph to add to, before its
compile. The pass readssourceandbloom, so the graph runs it after the passes that draw them. - source
- Color 0 is read, as linear light. Usually a
SCENE_COLOR_FORMATtarget thataddScenePassesor your post passes drew. Invalid, a depth-only target, or a multisampled one (resolve it first withaddMsaaResolvePass): logs an error, adds nothing and returnsfalse. - camera
- Its exposure and bloom strength are read each time the pass runs, so changing them needs no new graph. Invalid: logs an error, adds nothing and returns
false. - bloom
- What
addBloomPassesreturned, or invalid (the default) for no bloom. The pass drawslerp(source, bloom, strength). A depth-only target: logs an error, adds nothing and returnsfalse. - output
- Where it draws (
ViewOutput): by default the whole window.rectis fitted to the window's or the target's size when the pass runs (getViewPixels) and sets the viewport and the scissor. Passes that draw one output run in the order they were added: the first clears all of it, a later one loads it and draws over its rect. Withtargetset it draws into that target: one color, no depth, one sample, not storage, and notsourceorbloom; otherwise it logs an error, adds nothing and returnsfalse. One pipeline is kept per output format, at mostMAX_TONE_MAP_FORMATS(4) formats. - returns
truewhen the pass was added. The pipeline is made the first time the pass runs. Ifpasses/toneMap.slangdoes not compile, the pass logs an error, draws nothing (the window shows the clear color) and tries again next frame, so a fixed shader file is picked up while the program runs.
// From examples/06_shadows/main.cpp: post_rt holds the vignetted HDR image
if (!engine.addToneMapPass(graph, postTarget, camera))
return 1;
const FrameResources& getCurrentFrameResources();
The current frame slot's FrameResources: commandBuffer (the one being recorded: record your own draws and dispatches into it), fenceValue and computeFenceValue. Fetch it every frame, because the slot changes every frame. With EngineConfig::asyncCompute fetch it inside each pass, because the command buffer changes when a pass runs on the other queue.
auto commandBuffer = engine.getCurrentFrameResources().commandBuffer;
ctx.bindPipeline(commandBuffer, pipeline);
ctx.draw(commandBuffer, 3);
bool recreateSwapchain();
Rebuilds the swapchain, the render targets sized from it, and the aspect ratio of every camera, from the window's current pixel size. beginFrame already calls it after a resize or an out-of-date swapchain, so a program does not need to.
- returns
falsewhile the window has 0 pixels, or when the rebuild failed.beginFramethen tries again next frame.
4Loading and waiting
finishLoads is the AssetLoader's; the renderer calls it at the start of beginFrame.AssetLoader(Renderer& renderer, const AssetLoaderConfig& config = {});
~AssetLoader();
MeshHandle loadMesh(const std::string& path);
MeshHandle loadGLTF(const std::string& path);
TextureHandle loadTexture(const std::string& path, Format format = Format::R8G8B8A8_SRGB);
EnvironmentHandle loadEnvironment(const std::string& path);
bool loadFont(const std::string& path, FontAtlas& atlas, const FontLoadOptions& options = {});
bool loadPointCloud(const std::string& path, PointCloudData& cloud, const PointCloudLoadOptions& options = {});
void waitForLoads();
LoadStats getLoadStats() const;
std::string resolveAssetPath(const std::string& path) const;
AssetLoaderConfig getConfig() const;
Loads files into a Renderer on worker threads: glTF and OBJ meshes with their materials and textures, PNG, JPEG and KTX2 textures, HDR environments. Every load returns a handle at once, and the renderer finishes the ready loads at the start of each frame. An Engine has one (getAssetLoader), and its loadMesh, loadGLTF, loadTexture, loadEnvironment and resolveAssetPath call it. A Renderer alone gets one by making it; the loader is in the rasm::rasm library with the file libraries, so a program that links only rasm::renderer has none. Its settings are AssetLoaderConfig.
main thread The renderer must outlive its loader: make the loader after the renderer and destroy it first, as an Engine does with its own. A renderer destroyed first logs an error, the loader drops its loads, and every later call of the loader logs an error and returns an invalid handle; destroying the loader then is safe. One loader per renderer: a second one refuses every call. Destroying a loader while its renderer lives ends what it started: the copies on their way to the GPU are waited for and published, then the meshes and environments still loading fail (isLoaded stays false, as for a file that does not parse) and the textures still loading are destroyed, so their materials lose them. A new loader can then attach to the renderer.
// From examples/19_embedding/main.cpp: a Renderer on the application's window, with a loader for its files.
rasm::Renderer renderer(config);
rasm::AssetLoader loader(renderer, {.assetRoot = RASM_EXAMPLE_ASSET_ROOT});
const rasm::MeshHandle helmet = loader.loadGLTF("models/gltf/DamagedHelmet/DamagedHelmet.gltf");
bool loadFont(const std::string& path, FontAtlas& atlas, const FontLoadOptions& options = {});
Reads a TrueType or OpenType file (the path resolved like the other loads) and builds its distance atlas with buildFontAtlas, on the calling thread: it takes a few milliseconds for the 190 glyphs of ASCII and Latin-1. Upload the atlas with createFont and keep it to lay labels out (addVectorLabels). False, with an error, when the file cannot be read or is no font. AssetLoader and Engine.
rasm::FontAtlas atlas;
if (!engine.loadFont("fonts/Roboto-Medium.ttf", atlas))
return 1;
const rasm::FontHandle font = engine.createFont(atlas);
bool buildFontAtlas(const uint8_t* data, size_t size, const FontLoadOptions& options, FontAtlas& atlas);
struct FontLoadOptions
{
float emSize = 32.0f;
float distanceRange = 16.0f;
const uint32_t* codepoints = nullptr;
uint32_t codepointCount = 0;
};
A font file's bytes into a FontAtlas, with stb_truetype: each codepoint's signed distance glyph, its metrics, and the kerning of every pair the atlas holds (the font's kern table or GPOS pairs). Any thread. emSize is the atlas's pixels per em (8 to 256): larger is sharper for very large text and a larger atlas. distanceRange is the atlas pixels the stored distance spans (1 to emSize): a halo reaches half of it, scaled to the text's size. codepoints: the characters to hold; null gives ASCII and Latin-1 (32 to 126, 160 to 255). The fallback ? is always added. The atlas is 512 texels wide (1024 past 64 texels per em), packed in rows, and twice as wide while a glyph or the rows do not fit; past 4096 × 4096 the call fails. Kerning is looked up for every pair, so thousands of codepoints take seconds. stb_truetype trusts the font's tables: load only fonts you trust (B34). In rasm::rasm; a rasm::renderer program brings its own atlas.
bool loadPointCloud(const std::string& path, PointCloudData& cloud, const PointCloudLoadOptions& options = {});
Reads a LAS file (1.0 to 1.4, point formats 0 to 10) with RASM's own reader, or a LAZ file through LASzip (Apache-2.0), on the calling thread, any thread: about 48 M points a second for an uncompressed file in Release. The positions are the file's integers times its scale plus its offset, in doubles, so ECEF and projected coordinates keep their millimetres. Colors (formats 2, 3, 5, 7, 8, 10) become RGBA8: their high byte, or the value itself when no channel passes 255 (files that store 8-bit colors). The coordinate system is the OGC WKT of the LASF_Projection records, when there is one. False, with an error, for a file that cannot be read, is no LAS file, has an unknown format or ends early. Build an octree of it with buildPointCloudOctree. AssetLoader and Engine; in rasm::rasm.
rasm::PointCloudData cloud;
if (!engine.loadPointCloud("scans/tile.laz", cloud, {.scalar = rasm::PointCloudScalar::CLASSIFICATION}))
return 1;
enum class PointCloudScalar : uint32_t
{
NONE,
INTENSITY,
CLASSIFICATION,
ELEVATION,
GPS_TIME,
RETURN_NUMBER,
};
struct PointCloudLoadOptions
{
PointCloudScalar scalar = PointCloudScalar::INTENSITY;
bool zUpToYUp = false;
};
struct PointCloudData
{
std::vector<glm::dvec3> positions;
std::vector<uint32_t> colors;
std::vector<float> scalars;
glm::dvec3 boundsMin = glm::dvec3(0.0);
glm::dvec3 boundsMax = glm::dvec3(0.0);
std::string coordinateSystem;
uint32_t pointFormat = 0;
uint32_t versionMinor = 0;
bool compressed = false;
};
- scalar
- The value
scalarsholds for each point, for a colormap:ELEVATIONis its height (z, or y withzUpToYUp);NONEleavesscalarsempty. - zUpToYUp
- (x, y, z) to (x, z, −y): a projected file's east, north and up to RASM's east, up and south. Leave it off for ECEF.
- colors
- Empty for a format without color.
- boundsMin, boundsMax
- The header's, turned like the points.
- pointFormat, versionMinor, compressed
- The file's point format (0 to 10), its LAS 1.x version, and LAZ.
AssetLoader& getAssetLoader();
An Engine's own loader, made with the EngineConfig's assetRoot, loadThreads and loadMemoryBudget (toAssetLoaderConfig). Engine only.
void waitForLoads();
Finishes every pending mesh and texture load of the attached AssetLoader now (a renderer without one returns at once): it uploads each result as soon as its workers are done, which frees its part of AssetLoaderConfig::loadMemoryBudget for the loads that wait for it, with no time limit. After it returns, isLoaded is true for every successful load. Entities that use them join their scenes' draw lists at the next beginFrame, so the first frame after it shows everything.
Then it waits for the shader workers to finish the shaders queued so far (Shader warm-up): with a cold shader cache that is up to about a second at startup, and the next frames make their pipelines without waiting. A debug view chosen before it (setDebugView) is ready in the first frame.
blocks the main thread Use it before the main loop to avoid objects popping in, or in tests. Do not call it every frame.
auto mesh = engine.loadGLTF("models/gltf/coffee-room/scene.gltf");
engine.waitForLoads();
bool ok = engine.isLoaded(mesh); // false if the file failed to parse
Streaming tiles under a memory budget
A map, a globe or an open world too big for memory is cut into tiles, and a TileStreamer keeps one scene's tiles in GPU memory under a byte budget. Your application owns its tree and what a tile is; each frame it sets the views, walks its tree with getScreenError, and passes the tiles it wants drawn (its cut) to update. The streamer decides what loads, what is dropped and what is drawn, and hands you the tiles to load. The ideas, with labs: Tile streaming under a memory budget.
TileStreamer(Renderer& renderer, SceneHandle scene, const TileStreamerConfig& config = {});
~TileStreamer();
TileHandle createTile(const TileDesc& desc);
void destroyTile(TileHandle tile);
void setViews(const View* views, uint32_t viewCount);
double getScreenError(const glm::dvec3& center, double radius, double geometricError) const;
double getScreenError(TileHandle tile) const;
void update(const TileHandle* wanted, uint32_t wantedCount);
const TileHandle* getTilesToLoad(uint32_t& count) const;
bool setTileContent(TileHandle tile, const TileContent& content);
TileState getTileState(TileHandle tile) const;
bool isTileDrawn(TileHandle tile) const;
const TileStreamerStats& getStats() const;
TileStreamerConfig getConfig() const;
In rasm/tileStreamer.h and the rasm::renderer library: it works on a Renderer alone, and with an AssetLoader. main thread The renderer must outlive the streamer; destroying the streamer destroys every tile's content.
createTilemakes a record of your tree (TileDesc);destroyTiledestroys its content and the record, and its children become roots. At mostTileStreamerConfig::maxTiles.setViews: the views that draw the scene this frame (views of other scenes are skipped).getScreenErroris then a sphere's or a tile's geometric error in pixels, the largest over the views whose frustum touches it, 0 outside all of them: the number your walk compares with its limit.updatetakes the cut. The cut's ancestors are wanted too. It polls the loads, reads the budget and the pools, drops and hands out tiles within the config's limits, and adds or removes the drawn tiles' entities in the scene. Call it beforerender; with no tile change it allocates nothing.getTilesToLoad: the tiles the lastupdatehanded out (TileState::REQUESTED), valid until the nextupdate. Make each one's content, now or in a later frame, and give it withsetTileContent(TileContent). The streamer owns it from then on, also when the call returns false (then it destroys it): false for a tile that is notREQUESTED(the streamer cancelled it since, so a late answer of a server costs nothing, or it has content), an invalid tile, or an invalid handle in the content (the tile then fails).- A tile is
READYwhen the renderer's own state says so: every meshREADYwith its import's textures filled, every texture filled, every entity with its instance rows and textures. A failed mesh, or an entity that gets no instance rows within 4 updates of its mesh being in (a full instance table), fails the tile (FAILED), which is handed out again afterTileStreamerConfig::retryFailedAfterupdates.isTileDrawn: drawn now, as itself or in place of children.
// A sketch of a frame with glTF files as tiles; examples/24_map_tiles is a whole program.
rasm::TileStreamer streamer(engine, scene, {.memoryBudget = 48ull << 20});
// each frame:
streamer.setViews(views.data(), static_cast<uint32_t>(views.size()));
world.cut.clear();
visit(world, streamer, 0, 0, 0, rasm::TileHandle{}); // refine while getScreenError(tile) > 24 px
streamer.update(world.cut.data(), static_cast<uint32_t>(world.cut.size()));
uint32_t count = 0;
const rasm::TileHandle *toLoad = streamer.getTilesToLoad(count);
for (uint32_t i = 0; i < count; ++i)
{
const rasm::MeshHandle mesh = engine.loadGLTF(pathOf(toLoad[i]));
const rasm::EntityHandle entity = engine.createEntity("tile", mesh, {}, placeOf(toLoad[i]));
streamer.setTileContent(toLoad[i], {.entities = &entity, .entityCount = 1, .meshes = &mesh, .meshCount = 1});
}
engine.render(views.data(), static_cast<uint32_t>(views.size()));
enum class TileRefine { REPLACE, ADD };
enum class TileState { EMPTY, REQUESTED, LOADING, READY, FAILED };
struct TileDesc
{
TileHandle parent;
glm::dvec3 center = glm::dvec3(0.0);
double radius = 0.0;
double geometricError = 0.0;
TileRefine refine = TileRefine::REPLACE;
uint64_t estimatedBytes = 0;
};
A node of your tree: its parent (invalid for a root), the bounding sphere of its content in world space (in doubles, so a tile at Earth-centred coordinates works), and its geometric error: how many world units it is off from the full detail (a leaf's is 0). A tile is ranked by its parent's error seen at its own bounds, and a parent at least as high as its wanted children, so parents load first and are dropped last. REPLACE: the children stand in for the tile, which is drawn only while one of them is not ready (terrain, imagery). ADD: the children add to it, and it stays drawn with them (buildings on a district). estimatedBytes: what the tile will hold, used until it is measured once; 0 takes the mean of the tiles measured so far.
struct TileContent
{
const EntityHandle* entities = nullptr;
uint32_t entityCount = 0;
const MeshHandle* meshes = nullptr;
uint32_t meshCount = 0;
const MaterialHandle* materials = nullptr;
uint32_t materialCount = 0;
const TextureHandle* textures = nullptr;
uint32_t textureCount = 0;
};
What a tile owns: the streamer adds the entities to its scene while the tile is drawn (so do not add them yourself), and destroys everything listed, the entities first, when it drops the tile. List only what is the tile's own: content several tiles share (one tree mesh, a common material) stays outside. A mesh from loadGLTF brings its import's materials and textures, which count with it; destroying a mesh that still loads drops its load, so a tile dropped while it loads cancels it. The same file loaded by two tiles is one mesh (the loader caches by path): give such a file to one tile only.
struct TileStreamerConfig
{
uint64_t memoryBudget = 0;
float deviceShare = 0.8f;
uint32_t maxTiles = 1u << 16;
uint32_t maxLoadsPerFrame = 4;
uint32_t maxLoadsInFlight = 16;
uint32_t maxDropsPerFrame = 32;
uint32_t retryFailedAfter = 120;
};
memoryBudget: bytes the tiles may hold in GPU memory: their textures' allocations (getTextureMemoryBytes) and their meshes' share of the geometry pools. 0: deviceShare of the device-local memory budget left after everything that is not a tile (queryMemoryStats, VK_EXT_memory_budget), read every 30 updates. The fixed pools are limits too: vertices, indices, sub-meshes, meshlets, instance rows, materials and bindless slots, each its capacity minus what is not a tile's content (bindless slots that wait for the GPU count as taken). maxTiles and maxLoadsInFlight are at least 1, as getConfig shows. The limits per update: tiles handed out, tiles REQUESTED or LOADING at once (a load nobody wants any more gives its place up), and tiles dropped. retryFailedAfter: updates before a failed tile is handed out again (0: never).
struct TileStreamerStats
{
uint32_t tiles, wanted, ready, loading, failed, drawn;
uint32_t fallbacks, holes, waitingForBudget, loadsStarted, dropped;
uint64_t bytes, peakBytes, budget, deviceBudget, deviceUsage, totalLoads, totalDrops;
};
After the last update: the records, the wanted tiles (the cut and its ancestors), the ready and loading ones (REQUESTED and LOADING), the wanted ones that failed, the drawn ones, the parents drawn in place of children (fallbacks), the wanted tiles with nothing drawn in their place (holes), the wanted tiles that did not fit (waitingForBudget), and the loads and drops of that update. bytes: the ready tiles' measured bytes and the loading ones' reserved bytes, which the update keeps under budget; deviceBudget and deviceUsage are the device-local heaps' budget and the process's use.
void lowerThreadPriority(); // rasm/threadPriority.h
Runs the calling thread below the main thread, as RASM's own load and shader workers do. Call it first thing in a worker thread of your own. When the main thread wakes a worker that runs at its own priority, Windows gives the worker a wake boost, and the worker can take the main thread's core for its whole job: the main thread then waits inside notify_all. One level lower, the worker takes a free core instead. Windows: THREAD_PRIORITY_BELOW_NORMAL; Linux: the thread's nice value plus 5; macOS: the default QoS class at relative priority -5, which keeps the same cores. A free core runs a lowered thread at full speed, so loads are not slower. See Job systems.
5Frame stats
const FrameStats& getFrameStats() const;
The latest measured frame. The first call turns measuring on for every later frame, so the values fill in a few frames later. The reference stays valid; read it every frame.
const rasm::FrameStats &stats = engine.getFrameStats();
for (uint32_t i = 0; i < stats.gpuTimerCount; ++i)
std::printf("%s: %.2f ms\n", stats.gpuTimers[i].name.c_str(), stats.gpuTimers[i].milliseconds);
struct FrameStats
- cpuFrameMs
- Time between the last two frames on the CPU, in ms. Capped at 100 ms. Updated every frame, even when not measuring.
- gpuFrameMs
- GPU time of the frame on the graphics queue, in ms: from the frame's start to the latest end of a timer there. Timers on the compute queue are left out, because the timestamps of two queues may not share a clock. 0 on a GPU without timestamps.
- uploadGpuMs
- GPU time of the upload copies whose batches finished since the last frame, in ms, on the queue each ran on (the graphics queue, or the transfer queue for a load's). The stats overlay and the RASM window show it as uploads. Updated every frame, even when not measuring; 0 on a queue without timestamps.
- gpuTimers
- One
GpuTimerper pass (graphics or compute, the scene passes included) and per timer of your own, in the order they were recorded. The bloom passes share one,Bloom. Room forMAX_GPU_TIMERS - 1(255). - gpuTimerCount
- How many entries of
gpuTimersare filled. - draws
- Draws of all scene views the frame drew, before culling (one per sub-mesh of each entity).
- drawsVisible
- Draws that passed culling: inside the view, and with occlusion culling also not hidden. Draws of a view drawn without culling all count.
- triangles
- Triangles before culling, at LOD 0.
- trianglesVisible
- Triangles of the visible draws, at the LOD culling picked for each.
- trianglesVisibleLod0
- Triangles of the same visible draws at LOD 0.
- trianglesVisibleLod
- Triangles of the same visible draws at their LOD, whole: before meshlet culling.
trianglesVisibleLod0 - trianglesVisibleLodis what LODs saved this frame, andtrianglesVisibleLod - trianglesVisiblewhat meshlet culling saved; the RASM window and the stats overlay show both ("LOD saved", "Meshlets saved"). - drawsPerLod
- Visible draws at each LOD, from LOD 0 to
MAX_MESH_LODS - 1. They add up todrawsVisible. - meshletsVisible
- Meshlets drawn in all views, by either meshlet path. For a draw drawn by meshlets,
trianglesVisiblecounts their triangles only. - meshletsCulled
- Meshlets of visible draws that the frustum, their normal cone or the Hi-Z culled.
- meshletDrawsWhole
- Draws past a view's
EngineConfig::maxViewMeshlets, drawn whole instead of by meshlets (vertex pulling only: the mesh shaders have no budget). - lightsGlobal
- Global lights (directional, or
range0) of the frame's shaded views: each one is shaded at every pixel. - lightsVisible
- Lights with a range in the shaded views' frustums. A view without clusters counts all of them.
- lightsDropped
- Lights left out of a cluster that already held
MAX_CLUSTER_LIGHTS(counted once per cluster), or of a screen tile that already held 24 × 256: their pixels miss them. Above 0, the log also warns (once, then at most every 10 s). - glyphs
- Glyphs of the glyph chunks culling kept in all views: each one tested against the frustum and the Hi-Z.
- glyphsVisible
- Of them, the glyphs drawn. Their triangles, at the LOD each took, count in
trianglesVisible. - memory
VRAMStatsof that frame (seequeryMemoryStats).
struct GpuTimer
- name
- The pass name (for the scene passes: "Cull 1", "Scene 1", "Hi-Z", "Cull 2", "Scene 2", "Transparent", or "Cull" and "Scene"; inside them "Light Clusters", "Blend Sort", "Glyph Cull" and "Glyphs"; "Bloom" for all the bloom passes), or the name you gave
beginGpuTimer. - milliseconds
- GPU time between the timer's start and end, in ms.
uint32_t beginGpuTimer(const CommandBufferHandle& commandBuffer, const std::string& name);
Writes a start timestamp into the frame's command buffer. The GPU time until the matching endGpuTimer appears in getFrameStats and the overlay. Passes and render graph compute passes are already timed for you.
- commandBuffer
- The frame's command buffer, from
getCurrentFrameResources. - name
- Label in the stats.
- returns
- The timer id, or
UINT32_MAXwhen nothing is measured: measuring is off, the GPU has no timestamps, or the frame used all its timers (a warning is logged once).
A frame has MAX_GPU_TIMERS (256) timers: one for the whole frame, and 255 for passes and your timers together. Begin and end a timer in the same pass, so both timestamps are on one queue.
void endGpuTimer(const CommandBufferHandle& commandBuffer, uint32_t timer);
Writes the end timestamp of timer. It does nothing for UINT32_MAX, so you can always pass what beginGpuTimer returned.
const uint32_t timer = engine.beginGpuTimer(commandBuffer, "Particles");
ctx.dispatch(commandBuffer, groupCount);
engine.endGpuTimer(commandBuffer, timer);
VRAMStats queryMemoryStats();
Asks the GPU memory allocator now. Returns vramBudget, vramUsage and vramAllocated (device-local memory) and hostBudget and hostUsage (host-visible memory), all in bytes. See VRAMStats.
6UI with Dear ImGui
With EngineConfig::ui the engine runs Dear ImGui: F1 shows the RASM window (the frame stats, the forced LOD, the debug views, the graph dump), and the application adds windows of its own in a callback. How it works: Immediate-mode UI.
| Switch | Off | On |
|---|---|---|
CMake RASM_IMGUI (default ON) | vcpkg does not install ImGui and nothing links it. EngineConfig::ui logs a warning and stays off. | rasm links ImGui and defines RASM_IMGUI for itself and for the application. |
EngineConfig::ui (default false) | No ImGui context, no font texture, no pipeline, no UI pass: nothing runs. F1 shows the stats overlay. | ImGui is set up at startup. A frame builds a UI only while the RASM window is shown or a callback is set. |
rasm links Dear ImGui PUBLIC, as a static library (vcpkg's plain imgui port, with no backend: RASM feeds it input and draws it), and owns the context. find_package(rasm) finds it for you and links it into your program, so your code includes imgui.h and calls ImGui:: functions on that same library. Do not build or link a second copy of ImGui (another version, or its source files in your project): that gives two contexts, or two definitions of the same functions.
RASM's Dear ImGui is built with IMGUI_DISABLE_OBSOLETE_FUNCTIONS (the overlay port ports/imgui), so ImGui's old names are gone: use the current ones. An application of an installed RASM links the ImGui of its own vcpkg, which must be the same version built the same way, with that define in its imconfig.h. When it is not, the engine logs which struct size differs and starts with the UI off; it never asserts.
void setUiCallback(std::function<void()> callback);
Your UI. The engine calls callback once per frame between ImGui::NewFrame and ImGui::Render, inside beginFrame: after the input was read and the frame slot's fence was waited for, before the scene is uploaded. So a light or a transform you change in it shows in the same frame. Call ImGui:: functions in it; do not render or begin a frame from it. An empty function removes the callback.
Without EngineConfig::ui: logs a warning and the callback never runs. Draw callbacks of ImGui (ImDrawList::AddCallback) run while the UI is built, not while it is drawn.
ImGui saves no imgui.ini: ImGuiIO::IniFilename is nullptr, so nothing is written into the working directory and every run starts the same. To keep window positions between runs, set your own path in the callback's first frame (ImGui::GetIO().IniFilename = path;, with a string that lives as long as the engine).
// From examples/15_debug_ui/main.cpp
engine.setUiCallback(
[&]()
{
ImGui::Begin("Scene");
rasm::Light light = engine.getLight(sun);
if (ImGui::SliderFloat("Sun intensity", &light.intensity, 0.0f, 10.0f))
engine.updateLight(sun, light);
ImGui::End();
});
bool addUiPass(RenderGraph& graph, const RenderTargetHandle* shown = nullptr, uint32_t shownCount = 0);
Adds a graphics pass named UI that draws the frame's ImGui windows into the swapchain, over what the passes before it drew. It keeps the image and has no depth. render adds it after the tone map; in your own graph, add it after addToneMapPass (or after your last pass on the swapchain).
- graph
- The graph to add to, before its
compile. - shown, shownCount
- View textures the UI shows with
ImGui::Image(getUiTexture). The pass reads them, so it runs after the passes that draw them and shows this frame's picture.render(views, count)passes every view texture of its list. - returns
truewhen the pass was added;false, with nothing added, when the UI is off.
A frame whose graph has no UI pass still shows the UI: endFrame draws it in a render pass of its own, so F1 works in every program. That costs one more load and store of the swapchain image, only on frames that have something to draw; the first time, a debug-level log line says so. addUiPass draws in a pass the graph already orders, so it is the cheaper way.
The pass draws through the swapchain's UNORM view where the device has one (getSwapchainEncodedFormat), so ImGui's colors blend as the sRGB numbers ImGui is designed for; elsewhere they blend in linear light (D31).
// From examples/08_ibl/main.cpp
if (shadow.mapCount == 0 || !engine.addScenePasses(graph, scene, camera, sceneTarget, &shadow, 1) || !engine.addToneMapPass(graph, sceneTarget, camera))
return 1;
// The RASM window (F1) over the finished image.
engine.addUiPass(graph);
uint64_t getUiTexture(const TextureHandle& texture);
The ImTextureID that shows a sampled texture with ImGui::Image: its bindless slot, plus a bit that says whether its format is sRGB. The image shows the texture's stored colors either way. A loaded texture that no material samples yet gets a bindless slot here. Returns 0, which ImGui draws as nothing, while the texture still loads or for an invalid handle.
if (engine.isLoaded(albedo))
ImGui::Image(ImTextureRef(engine.getUiTexture(albedo)), ImVec2(256.0f, 256.0f));
ImGuiContext* getUiContext() const;
The renderer's Dear ImGui context, or null while the UI is off. Your own ImGui:: calls already use it. Another copy of Dear ImGui in the process, in a DLL or a language binding, draws into it after its own SetCurrentContext with this pointer and SetAllocatorFunctions with the values of ImGui::GetAllocatorFunctions (Two copies of one library). From C: rasm_get_imgui_context.
7Debug views
A debug view shows a value of each pixel instead of its shading: the normal, the UVs, how many fragments were shaded, the LOD, what culling did, or how many lights were shaded. The RASM window (F1) has a View list and a Freeze culling box under Debug views; without the UI, call the two functions below. How each view is made and how to read it: Debug views.
DebugView | Each pixel shows | Shown as |
|---|---|---|
NONE | the shaded scene | tone mapped |
NORMALS | the shading normal, after the normal map, in world space | x, y, z as red, green, blue (0.5 is 0) |
UVS | the fraction of UV set 0 | u red, v green, over a checker of 8 squares per unit |
OVERDRAW | the fragments shaded there, in every draw pass | heat color |
LODS | the LOD the draw uses, 0 to 7 | a color per LOD |
CULLING | drawn in the early or the late pass; culled draws as see-through ghosts | green, yellow; red ghost: occluded, blue ghost: outside the frustum |
LIGHT_COUNT | the lights the shading loops over there | heat color |
MESHLETS | which meshlet of a draw drawn by meshlets, or which draw | a color per meshlet (per draw for a mesh drawn whole) |
void setDebugView(DebugView view); DebugView getDebugView() const;
Every shaded scene view draws view from the next frame on, until you set DebugView::NONE again. A debug view replaces the shading in the scene passes; the tone map then shows the values as they are (or a count as a heat color), without exposure, and the bloom passes dispatch nothing. MSAA and TAA stay on, so edges are smooth, and a new view starts TAA's history over. Shadow maps are drawn as usual. A value outside the enum logs an error and changes nothing. getDebugView returns the last view set.
The debug views' shaders go to the shader workers when setDebugView first chooses one; until they are ready the scene is drawn shaded, so the frames go on and nothing is missing (Shader warm-up). waitForLoads waits for them. With DebugView::NONE nothing of it runs: the normal shaders have no debug branch.
// From examples/15_debug_ui/main.cpp: --debug-view overdraw
for (int i = 1; i + 1 < argc; ++i)
{
if (std::strcmp(argv[i], "--debug-view") == 0)
engine.setDebugView(parseDebugView(argv[i + 1]));
}
void setComputePoints(bool on); bool getComputePoints() const;
Whether, from the next frame on, each view sends its point cloud chunks whose points are up to 6 pixels at the chunk's centre and 8 at its nearest point (4 in an orthographic view, 2 in a view with MSAA) that draw at least one point of 2 pixels per 8 pixels of their rect on screen (a point of s pixels at the centre counts as (s / 2)²) to the compute path (point clouds): a 64-bit atomic max per pixel, then a resolve into the view's color, depth and motion. It starts as EngineConfig::computePoints. Where the GPU has no 64-bit buffer atomics (RenderContext::hasBufferInt64Atomics) every point is drawn by triangles whatever the setting, and turning it on logs a warning. Both paths take the same pixels, so the image does not change (under MSAA, a view without the compute path leaves out a few samples at a small point's edge); only the cost does. Picks always use the triangles.
// Compare the two paths' cost in the stats.
engine.setComputePoints(false);
void setMeshletPath(MeshletPath path); MeshletPath getMeshletPath() const;
How the scene passes draw big meshes from the next frame on: MeshletPath::OFF draws each visible draw whole; MeshletPath::VERTEX_PULLING and MeshletPath::MESH_SHADERS split a visible draw whose LOD has 8 meshlets or more and draw only its visible meshlets, by indirect draws or by task and mesh shaders; MeshletPath::AUTO is MESH_SHADERS where the GPU has them, else OFF (meshlets). MESH_SHADERS on a GPU without them logs a warning and draws by vertex pulling. It starts as EngineConfig::meshletPath. Every mesh has its meshlets either way, and both paths draw the same triangles, so the image does not change; only the cost does. The RASM window has it under "Culling and LODs". A value outside the enum logs an error and changes nothing.
// Dense meshes near the camera: cull them by meshlets, with mesh shaders where the GPU has them.
engine.setMeshletPath(rasm::MeshletPath::MESH_SHADERS);
void setCullingFrozen(bool frozen);
While frozen is true, each shaded scene view culls as in the frame it froze in: with that frame's frustum, LOD camera and occlusion results. The camera still moves and draws, so you can fly out and look at what was kept. With the UI on, the frozen frustum is drawn as orange lines. Best seen with DebugView::CULLING.
- Only the early culling pass runs. The Hi-Z and the late pass record nothing.
- See-through (BLEND) draws are culled in the early pass too, and drawn in list order, not sorted.
- Shadow maps are not frozen: they follow the camera, with the frozen LOD camera.
- What the frozen visibility never saw stays hidden until you unfreeze: an entity added after the freeze, or a mesh that finished loading after it.
- Freeze after a few frames of normal culling: a view's first frame has seen nothing yet.
Buffers and GPU tables
The RASM window has two more sections. Buffers lists the resources of the graph that runs this frame (each render target's colors and depth, each scene view's Hi-Z and light clusters) and shows the one you pick, with a face, sample, channel, Hi-Z level or cluster slice where it has them. GPU tables lists the GPU scene tables (rows used, bytes, rows sent this frame) and one entity's rows field by field. How the picture is made: Inspecting GPU resources.
void setInspection(const Inspection& inspection);
Picks what the two sections show, as picking it in the window does, and opens them in the next frame (the other sections close once). A target is found by its RenderTargetDesc::name in the graph that runs; one the graph does not use shows "not in this frame". Needs EngineConfig::ui: without it the call logs a warning and only stores the value.
- While the Buffers section is open with a pick, the graph holds one more compute pass, Inspect <resource>, right after the pass that last writes the resource. It copies the resource into a 1024 × 1024
R16G16B16A16_SFLOATstorage target that the UI pass reads. The pass is added from the next frame on; a new pick or a closed section changes the graph again, so the first frame after it recompiles the graph (and lays its transient targets out again). - With no pick, or the section closed, nothing is added: the graph, its barriers and its GPU timers are the ones without the UI.
- The graph needs a UI pass (
addUiPass) to show the copy.
// What examples/09_gltf_materials does for --inspect shadow_cascade_0 depth 0
rasm::Inspection inspection;
inspection.target = "shadow_cascade_0";
inspection.kind = rasm::InspectKind::DEPTH;
engine.setInspection(inspection);
const Inspection& getInspection() const;
What the sections show now, with the changes made in the window.
8Paths and config
| Config assetRoot | You pass | Resolved path |
|---|---|---|
| empty | models/a.obj | models/a.obj, relative to the working directory |
| assets (relative) | models/a.obj | <executable folder>/assets/models/a.obj |
| D:/game/data (absolute) | models/../a.obj | D:/game/data/a.obj (normalized) |
| any | D:/other/a.obj (absolute) | D:/other/a.obj: an absolute path is kept |
shaderDir follows the same rule against the executable's folder, with the build-time default when empty. (The folder is that of the binary that holds RASM: the executable for a C++ program, the shared library for the C API.) So does a relative cacheDir, which falls back to the user's cache folder when it cannot be written (see the table above). Paths are UTF-8, so folders with non-Latin names work.
std::string resolveAssetPath(const std::string& path) const;
Joins path to the resolved assetRoot, as every loader does, and returns it as UTF-8 with forward slashes. Useful to check where a file is looked for, or to open your own files from the same folder.
RendererConfig getConfig() const; // Renderer EngineConfig getConfig() const; // Engine
A copy of the config. A Renderer's is its RendererConfig; an Engine's own getConfig gives the whole EngineConfig again, the platform and the loader's fields included (toEngineConfig). assetRoot is the loader's. shaderDir and assetRoot are the resolved paths (an empty assetRoot stays empty), and showStats is its current value (F1 changes it). Changing the copy changes nothing in the engine.
9The window
Built-in keys
Esc or closing the window, SDL platform only: running() becomes false.
F1: shows or hides the stats: the RASM window with EngineConfig::ui, else the overlay.
F2: cycles forcedLod: by distance, LOD 0, 1, … 7, by distance.
F3: logs the dump of the next render graph that runs (RenderGraph::dump), and shows it in the RASM window.
While a UI window is under the mouse or has the keyboard, the camera gets none of it, and while a text field takes typing these keys do nothing.
Mouse and WASD (by position, also on AZERTY): move the camera passed to beginFrame, unless its controller is NONE (see camera.html; to move cameras yourself, Drive a camera yourself).
The keys work the same from the SDL window and from addInputEvent.
Two sizes
width, height: logical size, the unit of mouse positions.pixelWidth, pixelHeight: the drawable size. They differ on HiDPI screens. The swapchain, the render targets sized from it and the viewports use the pixel size.
Three platforms (EngineConfig::platform), each with more windows if you ask (below): SDL opens a window and reads its events for you; NATIVE draws into your window, and your program runs the event loop and sends the input; HEADLESS has no window. In all three, the input goes through the same InputEvents, to the camera, Dear ImGui and the keys above, and getInputEvents gives them back after pollEvents. How it works: The platform layer.
Your own window
Give a Renderer (or an Engine with PlatformType::NATIVE) your window's native handles, its size in points and pixels, and the display's scale. Each frame, send it your window's events and size changes before render (or beginFrame). Your window must live longer than the renderer. examples/19_embedding does this with an SDL3 window of its own; its --headless run opens the window hidden and plays a scripted input.
rasm::RendererConfig config = {
.appName = "editor",
.windowWidth = 1280,
.windowHeight = 720,
.nativeWindow = {.type = rasm::NativeWindowType::WINDOWS, .window = hwnd, .pixelWidth = 1920, .pixelHeight = 1080, .contentScale = 1.5f},
.ui = true};
rasm::Renderer renderer(config);
while (editorRunning)
{
// Your loop: turn each of your window's events into an InputEvent.
renderer.addInputEvent({.type = rasm::InputEventType::MOUSE_MOVE, .x = 640.0f, .y = 360.0f});
renderer.render(scene, camera);
}
void addInputEvent(const InputEvent& event);
Queues one input event (InputEvent). The next pollEvents (first thing in beginFrame, unless you called it) applies the queue in order, before the platform's own events: to Dear ImGui while it builds frames, to the built-in keys, and to the input of the camera passed to beginFrame, without what the last UI frame took. An event added after this frame's poll goes into the next frame. Use it with NATIVE, or to script the input of a headless engine. The queue keeps its capacity, so a steady frame makes no heap allocation.
main thread Mouse positions are in window points from the top-left corner, like windowWidth. Escape does not stop a NATIVE or headless engine.
void setWindowSize(uint32_t width, uint32_t height, uint32_t pixelWidth, uint32_t pixelHeight); void setWindowSize(WindowHandle window, uint32_t width, uint32_t height, uint32_t pixelWidth, uint32_t pixelHeight);
A window's new size (the main window's, or window's), in points and in pixels, for NATIVE and HEADLESS. A new pixel size rebuilds the swapchain and everything sized from it in the next beginFrame; the points place the mouse and the UI. A pixel size of 0 leaves that window out of the frames, as for a minimized window: send it while your window is minimized. A frame is skipped only when no window can show. Headless, it changes the size of the offscreen images. With SDL it logs a warning and does nothing, since the SDL platform reads its window's size itself.
void setWindowContentScale(float scale); void setWindowContentScale(WindowHandle window, float scale);
The display's scale setting (1.5 at 150 % in Windows' settings), without the pixel density, for NATIVE and HEADLESS. The UI's sizes and fonts follow it from the next UI frame. Call it when your window moves to a display of another scale. A scale of 0 or less is refused with an error; with SDL it logs a warning and does nothing.
Headless: no window
A Renderer without nativeWindow is headless (examples/21_renderer), and so is an Engine with EngineConfig::platform = PlatformType::HEADLESS. It opens no window, starts no SDL and reads no events of its own. The device has no surface. Each frame renders into one of two offscreen images of windowWidth × windowHeight pixels, which take the place of the swapchain: the tone map and every pass that writes "the swapchain" write there, and readFrame copies one back. With EngineConfig::ui the UI runs with no input unless you send some with addInputEvent: the RASM window and the windows of setUiCallback are drawn as with a window, and readFrame copies them. running() stays true until the engine is destroyed, so the program decides how many frames to render. examples/16_headless renders a scene and writes a PNG, and every example takes --headless --frames N --out file.png (examples/exampleArgs.h): it renders N frames with no window, writes frame N and exits.
rasm::EngineConfig config = {
.appName = "thumbnails",
.platform = rasm::PlatformType::HEADLESS,
.windowWidth = 512,
.windowHeight = 288,
.assetRoot = "assets"};
rasm::Engine engine(config);
const Window& getMainWindow() const;
The main window, with its handle, current sizes, content scale and state (minimized, resized); getWindow gives the others. It updates in beginFrame. Use the pixel size for viewports, like examples/01_render_graph/main.cpp does. Fields are in types.html.
const auto &window = engine.getMainWindow();
const float width = static_cast<float>(window.pixelWidth);
const float height = static_cast<float>(window.pixelHeight);
const float aspect = width / height;
More windows
An engine draws into up to MAX_WINDOWS − 1 (7) windows, the main one included. Each has a swapchain of its own; one submit waits for every window's image and presents them all. Put a view into a window with ViewOutput::window, or a pass with writeSwapchain(window). The UI, the stats overlay, the built-in keys and the engine's own camera input stay in the main window. How it works: Many views of one scene.
| Platform | addWindow gives | Its events |
|---|---|---|
SDL | an SDL window of width × height points, with title (hidden for a script) | the SDL platform tags them with the window (InputEvent::window); closing it is a WINDOW_CLOSE event, closing the main window quits |
NATIVE | a surface on your window (WindowDesc::native), which must outlive it | you send them with addInputEvent, tagged with the window; and its size with setWindowSize(window, ...) |
HEADLESS | an offscreen image of width × height pixels | none, unless you send some |
WindowHandle addWindow(const WindowDesc& desc);
Opens or wraps another window and makes its swapchain: on NATIVE a surface of its own, which the GPU's graphics queue must be able to present to. Returns an invalid handle, with an error, when the platform and desc.native disagree (only NATIVE takes a native window), a size is 0 where it is needed, MAX_WINDOWS are open, a frame is being recorded, or the window or its swapchain cannot be made.
// From examples/20_views/main.cpp: an SDL window, or an offscreen image under --headless.
const rasm::WindowDesc secondDesc = {.title = "RASM: a second window", .width = SECOND_WIDTH, .height = SECOND_HEIGHT};
rasm::WindowHandle second = engine.addWindow(secondDesc);
// ...
views.push_back({.scene = scene, .camera = orbit.camera, .output = {.window = second}});
struct WindowDesc
{
const char* title = "RASM"; // SDL
uint32_t width = 0; // points; HEADLESS: pixels; NATIVE: used when native has no pixel size
uint32_t height = 0;
NativeWindow native = {}; // NATIVE only
bool hidden = false; // SDL: opened hidden, as a script or a test does
};
What addWindow opens or wraps, in rasm/window.h. native is a NativeWindow, as for EngineConfig::nativeWindow.
void removeWindow(WindowHandle window);
Waits for the device to be idle, destroys the window's swapchain (and its surface), and closes the SDL window. The handle dies. A view or a pass that still names it draws nothing: render(views, count) leaves such a view out (logged once, at info level), and the graph skips such a pass. A readback of it that is not done fails. The main window, an invalid handle, or a call while a frame is being recorded logs an error and does nothing. On NATIVE, destroy your window after this call.
// From examples/20_views/main.cpp: the user closed the second window.
if (event.type == rasm::InputEventType::WINDOW_CLOSE && event.window == second)
{
engine.removeWindow(second);
second = {};
}
const Window& getWindow(WindowHandle window) const;
A window's state (Window): its sizes, scale and minimized. An invalid handle gives the main window, a removed one an empty Window. Use its points for a view's getInputArea.
10Reading images back
A readback copies an image from the GPU to the CPU, for a screenshot, a thumbnail or an image test. The copy is recorded at the end of a frame and is done when the GPU has finished that frame, so asking never stalls the frame. With two frames in flight the pixels are ready about two frames later. The idea, with pictures of the frames: Headless rendering and readback.
isReadbackReady while you keep rendering; takeReadback before that blocks until the GPU is done.ReadbackHandle readFrame(ReadbackFormat format = ReadbackFormat::RGBA8_SRGB); ReadbackHandle readFrame(WindowHandle window, ReadbackFormat format = ReadbackFormat::RGBA8_SRGB);
Asks for a copy of the image the frame shows in the main window (with the UI and the overlay), or in window: the offscreen image of a headless engine, or the window's swapchain image. A window with no image in that frame (minimized) is copied in the next frame that has one; one removed before the copy fails. Call it before render or graph.execute (or inside the frame, from the UI callback): the copy goes into the next endFrame. Returns an invalid handle when the window's surface does not allow copies from its images (logged); a headless engine can always be read.
const rasm::ReadbackHandle shot = engine.readFrame();
engine.render(scene, camera);
ReadbackHandle readTexture(const TextureHandle& texture, ReadbackFormat format = ReadbackFormat::RGBA8_SRGB, uint32_t layer = 0, uint32_t mip = 0);
The same for one layer (a cube face) and mip of a readable texture, as it is at the end of the frame. A render target is readable when it is made with RenderTargetDesc::readable; take its texture for the frame with getRenderTargetTexture. Returns an invalid handle, with an error that names the reason, for a texture that is not readable, a multisampled one (read its resolve), a block-compressed or 3-channel format, a depth asked for as RGBA8_SRGB, or a layer it does not have. A mip it does not have makes the copy fail at the end of the frame, and takeReadback returns false.
// The HDR scene color as floats, e.g. for its average brightness.
const rasm::ReadbackHandle hdr = engine.readTexture(engine.getRenderTargetTexture(sceneTarget), rasm::ReadbackFormat::RGBA32_FLOAT);
bool isReadbackReady(ReadbackHandle readback);
True once takeReadback would not wait: the GPU has finished the frame that copied it, or the copy failed. Poll it each frame so the program never stalls. False for a readback no frame has copied yet, and for an unknown handle.
bool takeReadback(ReadbackHandle readback, ReadbackImage& image);
Converts the copy into image and frees it; the handle is then used up. may block When the copy is recorded but the GPU has not finished it, it waits for that frame's fence. Returns false when the copy failed, or when no frame has copied it yet: then it does not wait, and the readback stays pending for the next frame.
if (engine.isReadbackReady(shot))
{
rasm::ReadbackImage image;
if (engine.takeReadback(shot, image))
rasm::writePng("frame.png", image);
}
Picking: what is under a pixel
A pick asks a view what it drew under a rect of its pixels: the entity and its sub-mesh, a vector feature's id, the world position in doubles and the normal. It is drawn at the end of the next frame through the rect's own small frustum, so it costs a cull of the draw list and the few draws that touch the rect, and nothing at all while nobody picks; its answer comes a couple of frames later, like a readback. The idea, step by step: Picking. examples/26_picking hovers, clicks and box-picks in two views.
// Every frame: the pixel under the mouse, then the newest answer that is in.
uint32_t x = 0;
uint32_t y = 0;
if (rasm::getViewPixel(engine.getMainWindow(), view.output.rect, mouseX, mouseY, x, y))
pending = engine.pick(view, {.rect = {.x = x, .y = y, .width = 1, .height = 1}});
if (pending.isValid() && engine.isPickReady(pending))
{
rasm::PickHit hit;
uint32_t count = 0;
if (engine.takePick(pending, &hit, 1, count) && count > 0)
std::printf("entity %llu at %.3f %.3f %.3f\n", static_cast<unsigned long long>(hit.entity.index), hit.position.x, hit.position.y, hit.position.z);
pending = {};
}
PickHandle pick(const View& view, const PickDesc& desc); PickHandle pick(SceneHandle scene, CameraHandle camera, const RenderTargetHandle& renderTarget, const PickDesc& desc);
Asks what view, a view of render(views, count), drew under desc.rect; the second form asks the scene view of your own graph that addScenePasses draws into renderTarget. Call it before or during the frame you want: the next endFrame draws it, as that frame drew the view, at the pixels' centres, without TAA's jitter and with one sample per pixel (MSAA does not change the answer). If the view did not draw in that frame, the pick fails. Returns an invalid handle, with an error, for a rect of 0 or more than MAX_PICK_SIZE (256) pixels on a side, a skip with unknown bits, or a scene or camera that is not alive. Several picks a frame are fine: up to 8 go out in one frame, side by side, and the others in the next.
constexpr uint32_t MAX_PICK_SIZE = 256;
constexpr uint32_t PICK_SKIP_MESHES = 1u << 0; // opaque and cut-out (MASK) meshes, not terrain
constexpr uint32_t PICK_SKIP_BLEND = 1u << 1; // see-through (BLEND) meshes, not vector features
constexpr uint32_t PICK_SKIP_TERRAIN = 1u << 2;
constexpr uint32_t PICK_SKIP_VECTORS = 1u << 3; // lines, polygons and points
constexpr uint32_t PICK_SKIP_LABELS = 1u << 4;
constexpr uint32_t PICK_SKIP_OVERLAYS = 1u << 5; // VectorDepth::OVERLAY features, labels too
constexpr uint32_t PICK_SKIP_POINTS = 1u << 6; // point cloud chunks
constexpr uint32_t PICK_SKIP_GLYPHS = 1u << 7;
constexpr uint32_t PICK_SKIP_ALL = (1u << 8) - 1;
struct PickDesc
{
ViewPixels rect = {.x = 0, .y = 0, .width = 1, .height = 1};
float minAlpha = 0.5f;
uint32_t skip = 0; // PICK_SKIP_*
};
rect is in the view's pixels from its top-left corner (a ViewPixels; getViewPixel turns a mouse position into one); a rect that reaches past the view is cut to it. minAlpha: a see-through surface (a BLEND material, and every vector feature: lines, polygons, points, labels) is picked where its alpha as drawn is at least this, else the pick sees what is behind it. 0.5 puts a line's pick edge on its drawn edge; a polygon filled at alpha 0.4 needs less. Cut-outs (MASK) cut where the image does. skip leaves kinds out, so the pick looks through them: PICK_SKIP_LABELS to select under the names, PICK_SKIP_ALL & ~PICK_SKIP_TERRAIN for "where on the ground", PICK_SKIP_GLYPHS to look through a field of glyphs.
constexpr uint32_t PICK_HIT_FEATURE = 1u << 0; // a vector feature (a label too): PickHit::feature is its id
constexpr uint32_t PICK_HIT_LABEL = 1u << 1;
constexpr uint32_t PICK_HIT_OVERLAY = 1u << 2;
constexpr uint32_t PICK_HIT_TERRAIN = 1u << 3;
constexpr uint32_t PICK_HIT_BACK_FACE = 1u << 4; // the back of a double-sided surface; the normal faces the camera
constexpr uint32_t PICK_HIT_POINT = 1u << 5; // a point of a point cloud chunk: PickHit::feature is its index (with PICK_HIT_FEATURE)
constexpr uint32_t PICK_HIT_GLYPH = 1u << 6;
struct PickHit
{
EntityHandle entity;
uint32_t subMesh = 0;
uint32_t feature = 0;
uint32_t flags = 0; // PICK_HIT_*
uint32_t pixels = 0;
uint32_t x = 0;
uint32_t y = 0;
glm::dvec3 position = glm::dvec3(0.0);
glm::vec3 normal = glm::vec3(0.0f, 1.0f, 0.0f);
double distance = 0.0;
};
One thing the rect covers: an entity's sub-mesh (a glTF primitive), and for a vector feature the id it was built with (addVectorLines' featureIds, LabelDesc::featureId), for a point or a glyph (PICK_HIT_GLYPH) its index in the arrays it was built from. pixels is how many of the rect show it; x, y is its pixel nearest the rect's centre, and position (world space, exact far from the origin), normal (the surface's or the terrain's, not a normal map's) and distance (from the camera) are that pixel's. A vector feature gives its own point under the pixel without its depth bias, so an overlay or a label gives the ground under it; a line or point that faces the screen is within about half its width of the ground point. entity is the entity the frame drew: one destroyed since keeps its old handle, which isAlive calls dead.
bool isPickReady(PickHandle pick);
True once takePick would not wait: the GPU has finished the frame that drew the pick, or it failed. Poll it each frame. False for a pick no frame has drawn yet and for an unknown handle.
bool takePick(PickHandle pick, PickHit* hits, uint32_t capacity, uint32_t& hitCount);
Writes up to capacity hits, nearest the rect's centre first, then nearest the camera; hitCount is how many there are (0: the rect shows only the background). The handle is then used up. may block When the GPU has not finished the frame that drew it, it waits for that frame's fence. Returns false when the pick failed (its view did not draw in that frame), or no frame has drawn it yet: then it does not wait, and the pick stays pending. A pick every frame allocates nothing.
bool isAlive(EntityHandle entity) const;
False for an entity that was destroyed, or a handle that never named one. A pick's answer comes frames after its frame, so its entity may be gone.
Exporting a still at any size
An export draws a view far larger than the window, or than the device's largest image, in tiles with an off-center projection, and writes it to a file as it goes (Tiled offscreen export). It runs in the frames of render, one jittered sample of one tile a frame, after your views, so the application keeps running and polls its progress.
rasm::ExportDesc desc{.width = 15360, .height = 8640, .path = "poster.png", .format = rasm::ExportFormat::PNG16, .pixelScale = 4.0f};
const rasm::ExportHandle poster = engine.exportView(view, desc);
while (engine.getExportProgress(poster).state == rasm::ExportState::RUNNING)
engine.render(&view, 1);
rasm::ReadbackImage none;
engine.takeExport(poster, none);
ExportHandle exportView(const View& view, const ExportDesc& desc);
Starts a still of view (its scene, camera, bloom and antiAliasing; its output is not used) at desc.width × desc.height. It starts with the next frame of render, after the exports before it. The camera is copied then, so yours may move; the scene must hold still (hold your animation time). While it runs, a TileStreamer of the scene counts the export's view in its screen error, waits until its cut is in, then changes nothing drawn until the last tile. Each tile takes desc.samples frames (plus one survey frame per tile when the scene has labels or weighted surfaces). Returns an invalid handle, with an error, for a bad scene or camera, an empty size, samples outside 1 to MAX_EXPORT_SAMPLES, a pixelScale not above 0, toneMap false with a PNG, an in-memory image that does not fit, or a device whose largest image cannot hold a tile and its guard. An application with its own render graph runs exports by calling render(nullptr, 0) between its frames. The export FAILED (and its file removed) when its scene is destroyed, when its view can't be added to the frame (all MAX_SCENE_VIEWS scene views in use), or when a write fails.
constexpr uint32_t DEFAULT_EXPORT_TILE_SIZE = 2048;
constexpr uint32_t MAX_EXPORT_SAMPLES = 256;
enum class ExportFormat
{
PNG8,
PNG16,
EXR_HALF,
EXR_FLOAT,
};
struct ExportDesc
{
uint32_t width = 0;
uint32_t height = 0;
std::string path; // UTF-8; empty: kept in memory for takeExport
ExportFormat format = ExportFormat::PNG8;
uint32_t samples = 16; // jittered frames averaged per pixel, 1 to MAX_EXPORT_SAMPLES (a square count is a stratified grid)
float pixelScale = 1.0f; // output pixels per pixel of every size given in pixels (lines, text, points, the grid) and of the LOD error
bool toneMap = true; // false: the scene's linear HDR color (exposure and bloom, no AgX), for an EXR only
bool transparent = false; // no sky or background: alpha is what covers each pixel
bool msaa = false; // also the view's MSAA in each sample (the samples already smooth edges)
uint32_t tileSize = 0; // 0: DEFAULT_EXPORT_TILE_SIZE; smaller tiles use less memory and cost more guard band
};
A PNG is sRGB with straight alpha (8 or 16 bits a channel, written through one deflate stream); an EXR is linear, premultiplied, channels A, B, G, R in half or float, ZIP compressed. Without a path the image stays in memory: PNG8 as an RGBA8_SRGB ReadbackImage, the others as RGBA32_FLOAT, linear and premultiplied. A file is written a row of tiles at a time on a thread of its own, so memory holds at most three bands (image width × tile height each: one being written, one waiting, one filling) and a few tiles: about 0.7 GB for a 16K PNG16 with 2048-pixel tiles. samples replaces TAA: each pixel is the mean of that many frames moved by sub-pixel offsets. pixelScale 4 with an image four times the window's width gives the window's look, four times sharper; 1 keeps every size in output pixels. Bloom keeps its reach in output pixels at any pixelScale. With transparent there is no sky, the background is alpha 0 and the bloom adds only over what covers a pixel; a PNG's color where alpha is below 1e-6 is 0. Tiles are cut on a grid of 64 pixels, each drawn with a guard band of 64 pixels (384 with bloom) on its inner sides, so screen-space effects match a single render.
enum class ExportState
{
RUNNING, // waiting for the scene to settle, or drawing its tiles
DONE,
FAILED,
};
struct ExportProgress
{
ExportState state = ExportState::FAILED;
uint32_t tilesDone = 0; // written to the file, or into the image
uint32_t tileCount = 0;
float fraction = 0.0f; // of the export's frames, 0 to 1
};
ExportProgress getExportProgress(ExportHandle exportHandle) const;
Never waits. DONE once the last tile is written and the file closed. An unknown, cancelled or taken handle gives FAILED.
bool takeExport(ExportHandle exportHandle, ReadbackImage& image);
For a DONE export: moves its image into image (an export to a file gives an empty image) and forgets the export. False while it runs or when it failed. Its camera copy, targets and buffers go with the next frame of render.
bool cancelExport(ExportHandle exportHandle);
Stops a running export (the file it was writing is removed) or forgets a finished one. False for an unknown handle.
11Raw GPU resources
For your own passes you may need buffers and textures that are not part of a scene. These functions forward to RenderContext. The descriptors (BufferDesc, TextureDesc) and how to fill, read and bind the resources are on RenderContext and resources.
BufferHandle createBuffer(const BufferDesc& desc);
Creates a new GPU buffer, every call (two equal descriptors give two buffers). Returns an invalid handle and logs an error on failure. It is device-local unless hostVisible is set. destroyBuffer frees it.
rasm::BufferHandle particles = engine.createBuffer({.name = "Particle Positions",
.usage = rasm::BufferUsage::STORAGE,
.size = PARTICLE_COUNT * 2 * sizeof(float)});
const uint64_t address = engine.getRenderContext().getBufferDeviceAddress(particles);
From examples/04_compute/main.cpp: a shader reads and writes the buffer through its device address.
TextureHandle createTexture(const TextureDesc& desc);
Creates a new, empty texture. Fill it with RenderContext::fillTexture, and add it to the bindless set (addBindlessTexture) to sample it in a shader, or give it to a material. For image files use loadTexture instead. Returns an invalid handle on failure. destroyTexture frees it.
void destroyTexture(const TextureHandle& texture);
Destroys a texture from loadTexture or createTexture. The handle is invalid at once: a later call with it logs an error, even when a new texture took its index. The texture and its bindless slot are freed once the GPU has finished every frame that may sample them, so the call never waits, and a new texture then reuses the slot.
- Every material that uses the texture loses it: that texture slot of the material samples nothing from the next frame on (the material's factor alone, as with no texture). An entity that waited for it to load is drawn.
- A load that has not finished is dropped at once: a decode still in the queue never runs, and a running one gives its result up.
loadTextureof the same path then loads it again. - Swapchain images and render target textures are refused: they belong to the swapchain and to their render target.
// A tile's material gets a new texture; the old one goes once no frame in flight samples it.
rasm::Material values = engine.getMaterial(tile.material);
values.textures[static_cast<uint32_t>(rasm::PbrSlot::ALBEDO)] = texture;
engine.updateMaterial(tile.material, values);
engine.destroyTexture(tile.texture);
From examples/17_streaming/main.cpp, which pushes far more textures through the bindless set than it has slots. How the wait works: Deferred destruction.
PoolStats getPoolStats() const;
The live objects and the used part of each engine-wide pool (PoolStats). It walks no object: every number is kept as things are made and destroyed, except the bindless slot count (1024 slots). examples/17_streaming prints it every 120 frames.
LoadStats getLoadStats() const;
The load workers now (LoadStats): how many there are, the jobs that wait and run, and the decoded bytes held now and at most since the start. The RASM window (F1) shows it on its Loads line. examples/17_streaming --burst and examples/10_ktx2_textures --measure print the workers and the peak. See Job systems.
void destroyBuffer(const BufferHandle& buffer);
Destroys a buffer from createBuffer: the handle at once, the buffer and any upload still queued for it once the GPU has finished every frame that may use it. Calls RenderContext::destroyBuffer.
bool resizeRenderTarget(const RenderTargetHandle& renderTarget, uint32_t width, uint32_t height);
Gives a fixed-size target (no swapchainScale, not a cube) a new size: a view texture that follows a UI panel, or the HDR target of a view whose rect changed. Its texture handles and bindless slots stay, so a material or a UI image that shows it keeps working; its contents do not (a TAA history starts over). A graph's transient target is placed again with its group.
The same size costs nothing. A new size waits once for the frames in flight (the values both queues signaled last), since they may still read the slots, the same short wait a window resize has; the old textures go once the GPU is done with them. Call it between frames: during a frame (between beginFrame and endFrame) it logs an error and returns false, as for an invalid target, a swapchainScale or cube target, or a size of 0.
// From examples/20_views/main.cpp: the TV's texture at 1.5 times its size, between two frames.
if (!engine.resizeRenderTarget(tv, TV_WIDTH * 3 / 2, TV_HEIGHT * 3 / 2))
return 1;
void destroyRenderTarget(const RenderTargetHandle& renderTarget);
Destroys a render target from createRenderTarget: the handle at once, its textures and bindless slots once the GPU is done with them. Materials that sample its colors (a view texture) lose them, as with destroyTexture; a view of render(views, count) that still names it as its output is left out. A render graph destroys the targets it made itself. Calls RenderContext::destroyRenderTarget.