Renderer¶
| Type | Module |
| Namespace | conjure::renderer |
| Include Folder Path | engine/include/conjure/renderer |
| Source Folder Path | engine/src/renderer |
conjure::renderer (target conjure_renderer, alias conjure::renderer) is the module that turns a
render_scene into one command list per frame through a render graph over conjure::rhi. It owns the GPU
mirrors of its asset types, the off-screen render targets and, in editor builds, the Dear ImGui backend. This
chapter is for people changing the module or wiring it into the engine: the frame, the graph, the resource cache,
threading, implementation details and the tests.
See engine/src/renderer/README.md for additional implementation notes.
Dependency Graph¶
Headers¶
Breakdown¶
Shape of the module¶
engine/src/renderer/CMakeLists.txt: conjure_add_module(renderer... PUBLIC_DEPS conjure::core conjure::rhi
conjure::assets PRIVATE_DEPS nvrhi cgltf stb jxl [imgui]), guarded by CONJURE_WITH_RENDERER and the presence of
conjure::rhi and conjure::assets. Never ecs or scene: the components in components.h are plain
reflected structs the engine's renderer_subsystem registers and extracts from. imgui/imgui_renderer.cpp is
compiled only with CONJURE_BUILD_EDITOR (never in Distribution). conjure_renderer depends on conjure_shaders
so index.json exists before the renderer is used.
| Area | Public headers | Private sources |
|---|---|---|
| Budgets, errors, logging | limits.h, renderer_error.h, log_category.h |
renderer_error.cpp, log_category.cpp |
| Handles | gpu_ids.h |
gpu_resource_cache.* (slot maps, fallbacks, graveyard) |
| Extraction contract | render_scene.h, camera.h, light.h, render_settings.h |
one .cpp each |
| 2D and debug | sprite_batch.h, debug_draw.h |
sprite_batcher.cpp, debug_draw.cpp, passes/sprite_pass.cpp, passes/debug_draw_pass.cpp |
| Assets | mesh_asset.h, texture_asset.h, material_asset.h, model_asset.h, environment_asset.h, shader_asset.h, gltf_importer.h, jpeg_xl.h |
assets/*.cpp, import/* (tangents, mips, image decoding, JPEG XL codec, IBL bake, cgltf) |
| Components | components.h |
components.cpp |
| The frame | renderer.h, render_target.h |
renderer.cpp, renderer_impl.h, render_graph.*, transient_pool.*, framebuffer_cache.*, binding_layouts.*, pipeline_cache.*, shader_program_loader.*, frame_resources.*, timer_ring.*, warn_latch.h, gpu_types.*, culling.*, draw_list_builder.*, exposure_math.*, display_encoding.*, shadows/*, passes/* |
| ImGui | imgui_renderer.h |
imgui/imgui_renderer.cpp |
Shaders live in engine/shaders/ and are compiled by conjure_add_shaders (the permutation list in
engine/shaders/CMakeLists.txt) into <build>/bin/shaders/index.json. The structs in shared/gpu_types.hlsli are
mirrored in gpu_types.h with static-asserted sizes; the tests re-read the HLSL defines to keep the two in step.
What the renderer loads is a second list, and there is no third: the table behind
shader_asset::built_in_programs() (assets/shader_asset.cpp). pipeline_cache maps every graphics
and compute variant, the two blit permutations (blit.hlsl with ENCODE_SRGB=0 and ENCODE_SRGB=1) and the
back-buffer clear (clear.hlsl) to one program of that table, and imgui_renderer takes the imgui program;
both resolve it through shader_program_loader.h (shader_asset::find_built_in, then validate against the
shader library, then one device shader per stage). No other renderer source names a shader blob.
Important
A new shader permutation needs three edits: the entry in engine/shaders/CMakeLists.txt, its row in the table
of assets/shader_asset.cpp, and the variant that maps to it in pipeline_cache.cpp (key_of).
test_shader_asset fails when the CMake list and the table disagree in either direction, test_pipeline_cache
when a variant does not resolve or a table row is used by nothing.
The frame¶
renderer::render(scene) does, in order:
- Before the acquire: the scene's settings groups (
postProcess,shadows,ssao,antiAliasing) are clamped into their ranges on the renderer's copy, so a frame the acquire then skips has still countedsettingsClampedand logged its WARNs; then the anti-aliasing in effect (theset_anti_aliasingoverride, else the scene's group) is settled: the MSAA sample count is lowered to the largest the device supports and the renderer has not refused, and the pipelines of a count not built yet are created. Nothing of the frame is recorded yet, so a refused count never leaves a half-recorded frame, and a scene that changes the group renders the new count from its own frame on. begin_frame: acquire the back buffer (when a swapchain exists), open the frame command list, clear the back buffer whenset_back_buffer_cleargave a colour (see The back-buffer clear), flush the queued asset uploads under the 64 MB budget, collect the graveyard.prepare: build sprites and debug lines once (pastMAX_SPRITES_PER_FRAME,sprite_batcherkeeps everySCREENsprite it can and drops theWORLDsprites last in sort order first), allocate the local-light shadow atlas scene-wide (importance measured from view 0; casters culled withatlasLayerMask, the union of the layer masks of the views withoutSKIP_SHADOWS, so the first shadowing view that renders it does not decide what the others see), then per view: cull on jobs, build instanced draw lists (opaque / masked sorted by material and mesh, blended far to near), sort the lights (directional first), build the cascades of the first shadowing sun (culled with the view's own mask), fill the view constants.render_view_graph: one render graph per view, passes added only when they have work:shadow_cascade_0..3,shadow_atlas,depth_prepass,light_cull,ssao_gtao,ssao_blur_h/v,forward_opaque,skybox,forward_blend,world_sprites,debug_draw,exposure_histogram,exposure_adapt,bloom_down_0..5,bloom_up_4..0,tonemap,screen_spritesandblit(only when the target is notRGBA8_SRGB; into anRGBA8_UNORMtarget with theENCODE_SRGB=1permutation, see Display encoding). The graph validates (a read before write asserts in Debug, logs an ERROR and skips the pass), culls backwards, computes lifetimes and takes its transients from the pool (no aliasing, NVRHI automatic barriers).- ImGui into the swapchain (editor builds), after every view, so the panels cover the views of the back buffer.
end_frame: close, execute, present, evict idle transients and binding sets, fillrender_stats.
world_sprites and debug_draw run before exposure, bloom and the tonemapper, so world sprites and debug lines
are post-processed like the 3D scene; screen_sprites runs after the tonemapper. A 2D project that wants its
sprites' authored colours sets the camera's postProcess = false (NO_POST_PROCESS on its view).
Conventions: reverse-Z everywhere (near = 1, far = 0, GreaterOrEqual), classic NVRHI binding sets with
registerSpaceIsDescriptorSet, a volatile constant buffer at b0 and 16 bytes of push constants at b1 in
space 0 (32 for imgui.hlsl, whose own block mirrors gpu::imgui_constants: the display rectangle and a flags
word, compared with the C++ side by test_gpu_types.cpp), the material set in space 1, matrices uploaded verbatim
from glm and consumed with mul(vector, matrix) under -Zpr.
The back-buffer clear¶
renderer::set_back_buffer_clear(colour) stores the display-referred colour and, once, its value in the
swapchain's encoding (display_clear_value, below), so the frame only records the clear. Right after the frame
command list opens, and only when a back buffer was acquired and a colour is set, record_back_buffer_clear
writes it under the marker clear_back_buffer, before the uploads, every view and the ImGui pass:
- Where
rhi::swapchain::back_buffer_transfer_destination()holds (always on D3D12, on Vulkan when the surface offeredTRANSFER_DSTat the last create or resize), it is aclearTextureFloatof the back buffer. - Otherwise it is a render pass:
pipeline_cache::clearbuilds, per target format, a pipeline fromclear.hlsl(the fullscreen triangle, no blending, no depth) over binding layoutclear, whose only item is 16 bytes of push constants. The frame binds the back buffer's framebuffer from the framebuffer cache, pushes the colour and draws three vertices;render_stats::drawCallscounts that draw. The pixel shader returns the pushed value unchanged, which is exactly what a clear would store.
renderer::create builds the clear pipeline and its binding set for every swapchain, whatever the capability says
then, because the capability is read each frame and a Vulkan resize may change it. Either path sets
render_stats::backBufferCleared. The null device runs the render-pass path headless when it is created with
device_desc::nullBackBufferTransferDestination = false: its command list then reports any transfer into one of
its back buffers as an ERROR (and still counts it), so a test holding a log_capture fails if the renderer took the
wrong path.
Display encoding¶
display_encoding.h holds the encoding decisions as pure functions, so they are tested without a GPU. A colour
target stores linear values (the float formats), linear values the hardware encodes on write (the *_SRGB
formats) or display values the hardware leaves alone (RGBA8_UNORM, the editor's swapchain, which the engine's
rhi_subsystem picks so ImGui's display-referred colours blend in sRGB space). shader_encodes_srgb(format) names
the last kind, and everything that writes linear values into such a target encodes in the shader:
- The view's final image. The LDR image (
pass_shared::ldr_output, written bytonemap, or byfxaawhen the view filters) is the target itself only when the target isRGBA8_SRGB(ldrIsTarget); for every other format it is anRGBA8_SRGBtransient thatblitcopies into the target.pipeline_cache::blitbuilds the blit into anRGBA8_UNORMtarget fromblit.hlslwithENCODE_SRGB=1, which applieslinear_to_srgbto the sample, and every other blit fromENCODE_SRGB=0. So anRGBA8_UNORMback buffer or render target never holds linear values, andread_backof one returns the same bytes as anRGBA8_SRGBtarget of the same view.render_view::background, an 8-bit display colour linearised before the tonemap pass adds it, reads back as the same bytes from both. - ImGui's textures. When
imgui_rendererbuilds a texture's binding set it records whether the resolved texture samples as linear values (texture_samples_linear: an*_SRGBformat, which the sampler decodes, or a float format). A draw setsCONJURE_IMGUI_FLAG_ENCODE_SRGBin its push constants when that holds and the target stores display values (imgui_encodes_texture), andimgui.hlslencodes the texel before it multiplies by the vertex colour. The font atlas and every UNORM texture, anRGBA8_UNORMrender target included, already hold display values and pass through; ImGui's vertex colours are never converted, and on an*_SRGBtarget nothing is (the hardware encodes).imgui_render_stats::srgbEncodedDrawscounts the encoded draws. - The back-buffer clear.
display_clear_value(colour, format)keeps the display-referred colour for a target that stores display values and linearises it for every other format; alpha is never converted, every channel is clamped to [0, 1] and a NaN channel reads 0.
An RGBA8_UNORM render target therefore holds display values: ImGui and read_back show it right, but a sprite
that samples it takes them as linear and encodes them a second time, which render_target_desc::colourFormat
documents. shared/colour.hlsli carries srgb_to_linear and linear_to_srgb; test_display_encoding.cpp
compiles it through hlsl_shim.h and compares both with the CPU reference of import/mip_generator.
The tonemap pass makes every view's final image opaque: it adds the linear render_view::background by the
coverage the HDR alpha carries (0 where nothing drew, the blended coverage elsewhere, 1 under a solid surface or the
sky), after exposure, bloom and the tonemap curve, and writes alpha 1. A view with
view_flags::KEEP_COVERAGE_ALPHA (CONJURE_VIEW_FLAG_KEEP_COVERAGE_ALPHA in the view constants) writes the
saturated coverage as alpha instead and adds no background, so its image is transparent where nothing drew. The
editor's Scene panel sets it to show its picture over its themed backdrop and grid.
Resource cache and uploads¶
gpu_resource_cache keeps one slot map per mirror type plus the fallbacks (unit cube, white texture, magenta
unlit material, grey environment) and a graveyard. upload_* copies the payload at enqueue time, reserves
the slot under a mutex and returns the id; the GPU objects are created in flush_uploads at the start of the
next frame, never elsewhere. Releasing a texture only marks the materials that used it; the next flush rebinds
them. An entry released during a frame is retired (its GPU handles get an extra graveyard reference) and freed at
the next collect(), so every reference the frame resolved stays valid until the frame is submitted; the mirrors
live in heap entries whose addresses survive table growth, and resolve_* lock per call.
A render target's colour texture is an external entry (register_external_texture; the cache never destroys it).
resize_render_target builds the replacement target, waits for the GPU to go idle, then points the old entry at
the new texture with replace_external_texture and unregisters the replacement's own id, so colour_texture()
keeps its id across a resize. ImGui and the sprite pass resolve the id every frame (ImGui rebuilds its binding set
when the texture changes), so a handle taken before the resize follows it.
Assets and importers¶
The five asset types (mesh, texture, material, model, environment) have CPU-only loaders (no device
in finalise) and four importers (glTF with cgltf, textures with stb and libjxl, .cmat JSON, .hdr with the CPU
IBL bake). register_asset_types(types, importers, jobs) registers them; the engine's renderer_subsystem
subscribes to asset_manager events and calls upload_* on LOADED / RELOADED and release_* on UNLOADED.
The glTF adapter makes the model the primary asset with meshes, materials and textures as sub-assets with stable
uuids and declared dependencies, so a blocking load of the model brings everything
(tests/integration/test_assets_renderer_headless.cpp proves the whole path on the null device).
A point or spot light without a glTF range gets sqrt(intensity / GLTF_LIGHT_RANGE_CUTOFF), clamped to
[GLTF_MIN_LIGHT_RANGE, GLTF_MAX_LIGHT_RANGE] (range_from_intensity in import/gltf_importer.cpp), with a
warning; a sampler whose wrapT differs from wrapS is a warning (texture_asset holds one wrap mode). Any
change to what the importer produces bumps GLTF_IMPORTER_VERSION (2 since the derived range, 3 since
generateTangents = false took effect), which re-imports cached models. The same rule holds for the IBL bake:
ENVIRONMENT_IMPORTER_VERSION is 3 since the bake reads NaN and negative radiance as 0 and anything above
MAX_ENVIRONMENT_RADIANCE as that bound, integrating brighter-than-half radiance unclipped (only the stored
cubemaps clamp to 65504).
Tangents: the packed vertex always has one, and import_mesh decides where it
comes from. A mesh whose primitives all have a usable TANGENT (one per vertex) keeps them; a primitive without
gets one from the UV derivatives (tangent_generation::FROM_UVS, detail::generate_tangents) or, with
generateTangents = false, from the normal alone (FROM_NORMAL, detail::normal_tangents in
import/tangent_generator.*). A mesh with no TANGENT at all is left to mesh_asset::from_geometry. A mesh
with it on some primitives keeps it there with the option off and is filled in by import_mesh through
detail::missing_tangents; with the option on it keeps the whole-mesh rule from before and all its
tangents come from the UVs. A mixed mesh in which a primitive lacks NORMAL keeps none of the file's tangents
under either value: its normals are generated inside from_geometry. Nothing in the vertex, the material or the
shaders knows where a tangent came from, so normal_tangent_warning reports, once per mesh, the lit
normal-mapped materials that a primitive with normal-only tangents draws with. The warning is tied to the
option: a primitive without TEXCOORD_0 gets the same tangents under the default and is not reported.
Important
A new caller of from_geometry gets FROM_UVS unless it says otherwise. Pass FROM_NORMAL only where the
caller can also tell the user that normal maps will not work on the result, as the importer does.
Every source image goes through import/image_loader.cpp, which routes by signature: JPEG XL to libjxl
(import/jpeg_xl_decoder.cpp), the rest to stb_image. The JPEG XL decoder converts an SRGB texture's colour
profile to sRGB through skcms and keeps a LINEAR texture's samples as stored, puts PQ and HLG reference white
(203 nits) at 1.0, reduces deeper colour and alpha to their high byte like a 16-bit PNG, applies orientation,
divides premultiplied alpha out before converting, keeps the first animation frame, and checks the image size, the
extra channels and every layer's size from the headers while holding libjxl to a memory budget derived from the
image size, the same on any number of workers; the texture and environment importers run it on the job system.
TEXTURE_IMPORTER_VERSION is 2 since JPEG XL. The codec's internals (allocation and threading hooks, the colour
plan, libjxl's XYB-to-ICC limitation, the resource limits, the binary cost) are in
JPEG XL.
Implementation details¶
draw_list_builderpacks the opaque key as[variant:8][material:22][mesh:22][submesh:4][depth:8]and asserts the ranges; the material and mesh fields leave four bits for the submesh; the blended key carries a 24-bit depth.- PCSS estimates its penumbra in world units; search and filter radii are clamped to 8 texels. The shadow raster
bias is negated for reverse-Z. Shadow comparison samplers use
Lessto account for reverse-Z linearisation. light::entityId(never reflected) keeps a local light's atlas tile stable.- The AO upsample is a 4-tap bilateral filter over the half-resolution AO and a half-resolution view depth
(
ao_depth_half,t9of the mesh view set). - The exposure histogram meters the view's viewport rectangle only.
camera::ray_from_viewporttakes the aspect ratio the caller measured;alpha_mode::SOLIDnames glTF's opaque mode (OPAQUEis a Windows macro).
Failure model¶
renderer::create fails at start-up with SHADER_NOT_FOUND (naming the shader key), PIPELINE_CREATION_FAILED
or RESOURCE_CREATION_FAILED; nothing is created mid-frame except a blit pipeline the first time a new target
format appears (outside frames). A program is validated whole before any of its shaders is created, so a stage
missing from index.json stops creation at the program that needs it; a blob file the index lists but the
directory lacks is found when that stage is loaded, with the same code. render fails only with
rhi_error::DEVICE_LOST; everything else about a scene is clamped and counted (views beyond MAX_VIEWS, lights
beyond MAX_LIGHTS_PER_VIEW, sprite and debug caps, atlas overflow). A stale gpu id draws the fallback and WARNs
once per id (for the first 1024 such ids).
Warnings of the frame path follow one rule: a WARN is logged when its condition
starts, not again while it lasts, and is armed again once a frame has seen the condition end. The condition is
"over the budget", never the count, so an overflow whose size moves every frame logs one line. The state is a
warn_latch (or a view_warn_latch, one bit per view index) in renderer_state, declared in
engine/src/renderer/warn_latch.h: update(holds) answers true exactly when the caller should log.
| Warning | Latch | Looked at | Counter that stays live |
|---|---|---|---|
views beyond MAX_VIEWS |
viewOverflowWarning |
every frame not skipped at the acquire | viewsSkipped |
lights beyond MAX_LIGHTS_PER_VIEW |
lightOverflowWarning (one for all views) |
when a view is prepared | lightsDropped |
sprites beyond MAX_SPRITES_PER_FRAME |
a flag inside the public sprite_batcher |
every build, so every frame not skipped at the acquire (clear leaves it) |
spritesDropped, dropped_count() |
| unknown render target | unknownTargetWarning, per view index |
every view within MAX_VIEWS of such a frame |
viewsSkipped |
| clamped camera | invalidCameraWarning, per view index |
every view that is drawn | none |
| acquire refused, device not lost | acquireFailureWarning |
every frame of a renderer with a swapchain, until the device is lost | viewsSkipped (all views) |
| present refused, device not lost | presentFailureWarning |
every frame that reaches the present | none |
A latch learns only from a frame that looks: a frame skipped at the acquire touches no other latch, a frame
without views leaves the light and per-view latches alone, and a view index the scene does not have keeps its
state. Three warnings are not latched and are never armed again: a view of the swapchain on a headless renderer
(once per renderer, also when the scene stops and later resumes doing so), a stale gpu id (once per id, for the
first 1024 ids) and the timer ring's refused query (once per ring). Debug vertices and shadow tiles over their
budget are counted without a WARN. The rule is about WARNs: the render graph still logs an ERROR for each of its
first 8 skipped passes, and the transient pool an ERROR for every texture or buffer the device refuses. A new
frame-path warning takes a latch in renderer_state; do not compare counts. The two swapchain latches are tested
headless: null_fault::ACQUIRE_OUT_OF_DATE and null_fault::PRESENT_FAILED make the null swapchain refuse one
acquire or present without losing the device (test_renderer_failures.cpp).
Open items¶
- Dear ImGui is pinned at 1.91.9b-docking; the
ImTextureDatatexture protocol path ofimgui_renderer(IMGUI_HAS_TEXTURES) is written but only compiles against ImGui 1.92 or later. tests/benchmarks/bench_render_null_frame.cpp(renderer.null_frame_10k,engine.full_frame_10k_transform_render) guards the 10k-instance frame on the null device.- The real-device image of the
feature_testearly scene is a local check until the golden pipeline exists.
Related¶
- 📘 API: Rendering
- 🛠Handbook: RHI module, Assets module, Building and Configuration
Threading Model¶
create, render, render_frame, begin_extract / end_extract, find_*, render targets and read_back
belong to the render thread (the main thread in v1). upload_* and release_* may be called from any thread.
Culling and draw-list building run on job_system::parallel_for when a job system is given; the render thread
helps with queued jobs while it waits, so a job may call upload_* / release_* in the middle of render(),
which is why the cache never hands its mutex to the frame. No NVRHI object is created outside flush_uploads.
Extension Points¶
The renderer_subsystem has everything it needs: renderer::register_asset_types(types, importers,
jobs) for the asset manager, components.h register_components(type_registry) for the ECS registration (the
CONJURE_COMPONENT specialisations live in the subsystem), begin_extract / end_extract / render_frame
around the EXTRACT phase, set_imgui_draw_data / imgui() for imgui_layer (which calls
imgui()->attach_to_current_context() once its context exists, so the backend's name and
ImGuiBackendFlags_RendererHasVtxOffset hold from the first frame), set_back_buffer_clear for whoever owns the
window's look (the engine gives the editor's renderer a dark default and the editor's theme replaces it with its
panel colour; the runtime clears nothing), and resize_swapchain / on_device_lost for the window and device
events. model_asset -> prefab is the engine's job over
scene::prefab_builder (add_node, add_component_json by registered name).
Testing¶
tests/renderer/ holds one file per public header plus the topic files (culling,
draw_list_builder, cascade_builder, shadow_atlas_allocator, render_graph, transient_pool,
gpu_types, tonemap_reference, exposure_math, pipeline_cache, gpu_resource_cache, warn_latch,
display_encoding, renderer_null_frame, renderer_failures, renderer_gpu). Everything runs on the null device;
the [gpu] cases use WARP and skip without precondition::SOFTWARE_GPU_ADAPTER.
The display encoding is covered at three levels. test_display_encoding.cpp checks the pure decisions and the
shader's sRGB functions. On the null device, test_renderer.cpp checks the back-buffer clear (its order, the
colour recorded in the swapchain's encoding through null_device_stats::lastTextureClearColour, and the
render-pass path through lastPushConstants), test_pipeline_cache.cpp the blit and clear programs, and
test_imgui_renderer.cpp which draws set the encode flag. On WARP, test_renderer_gpu.cpp reads an RGBA8_UNORM
target back against an RGBA8_SRGB one, the background and KEEP_COVERAGE_ALPHA images, and a UNORM swapchain
that clears, blits and presents under the D3D12 debug layer; test_imgui_renderer.cpp reads ImGui's colours and
sRGB images back from a UNORM target. Test glTF, PNG, HDR, JPEG XL and ICC inputs
are generated in the tests (no binary assets); test_jpeg_xl.cpp covers the JPEG XL codec through the public
header and the private import/jpeg_xl_codec.h. tests/integration/test_assets_renderer_headless.cpp covers the
asset pipeline into the renderer.
The null command list only counts what it records, so renderer_test_support (make_device,
make_headless_renderer) creates the null device with enableDebugLayer: NVRHI's validation layer then logs
misuse (recording on a closed list, a draw without a graphics state, a binding set whose resource does not fit
its slot) as an ERROR, which fails every case holding a log_capture. The allocation gates use make_raw_device /
make_raw_headless_renderer instead, so they measure the renderer and not the validation layer's bookkeeping.