Rendering backends (render package)
render draws the toolkit's frames on the GPU. Most things are instanced quads of one shader (rect.bento); Slug text, filters,
mips and video have shaders of their own. It has two backends behind one interface:
| Backend | TOOLKIT_RENDER | Systems | Files |
|---|---|---|---|
| Direct3D 12 + Vulkan fallback | auto (default on Windows) | Windows (Direct3D 12 when SM 6.9 is available, else Vulkan at runtime) | d12_*.fm, dcomp.fm, vk_*.fm |
| Direct3D 12 only | d3d12 (Windows override) | Windows | d12_*.fm, dcomp.fm |
| Vulkan 1.3 only | vulkan (only backend off Windows; Windows override) | Linux (Wayland and X11 windows), Windows (Win32 windows, opaque), offscreen renderers | vk_*.fm |
On a non-Windows target TOOLKIT_RENDER=d3d12 and auto are ignored and the Vulkan backend is used: the Direct3D files are
built behind when HAS_D3D12 (and #+build windows), so they contribute nothing to a Linux build. HAS_VULKAN and
HAS_D3D12 say which backends are compiled in; render.renderer_backend(&r) and render.backend_name(&r) say which backend
a renderer uses.
Direct3D 12 needs shader model 6.9. The program carries the Agility SDK's runtime compressed with trame:flate
(D3D12Core.dll.zlib, embedded and pinned by the raw DLL's SHA-256): the first device of a process verifies an existing copy
in %LOCALAPPDATA%\gui_toolkit\d3d12\<sha256>\ by SHA-256 without decompressing, or decompresses and writes it once (flushed
with FlushFileBuffers before closing), and loads it through ID3D12SDKConfiguration1::CreateDeviceFactory. No DLL stands
beside the program. Adapter enumeration checks DXGI descriptions and EnumOutputs(0) before creating a device so sleeping
Optimus discrete GPUs are not woken and display-driving GPUs are preferred over display-less iGPUs. If hardware Direct3D 12
lacks shader model 6.9, render.backend_choose() switches to Vulkan at runtime when render.vulkan_can_draw() succeeds (and
calls platform.set_gdi_presents(true) before the first window opens); if Vulkan is also unavailable, init fails with
Init_Error.Shader_Model and a sentence that names the driver. render.d3d12_runtime() says which runtime made the device.
Tests and CI put WARP 1.0.22 (d3d10warp.dll, fetched by trame fetch_d3d12) beside their executables; programs never ship it.
The Vulkan backend is Linux's renderer, Windows' runtime fallback when Direct3D 12 lacks Shader Model 6.9, and Windows' sole
renderer with -define:TOOLKIT_RENDER=vulkan (src/md/infrastructure/gpu-backends.md). It draws into offscreen renderers
(init_offscreen) and into windows (init, surface_init for a second one: Wayland, X11, Win32):
textures, layers, filters, Slug text, pictures, read-back, capture, partial redraw, video planes, application shaders, GPU times. A
frame of a region is drawn alone, and its present names the region to the compositor where the device has
VK_KHR_incremental_present (present_regions_supported, present_rects_sent). The 2D canvas is Direct3D 12's only. It needs a
Vulkan 1.3 device with VK_KHR_push_descriptor, dynamic rendering and synchronization2 (and VK_KHR_swapchain for a window);
software = true asks for a software device (lavapipe). On Windows, Vulkan windows keep their GDI
surface (platform.gdi_presents() / platform.set_gdi_presents(bool)): they omit WS_EX_NOREDIRECTIONBITMAP and are opaque,
with no DirectComposition. render.vulkan_can_draw(software) says whether a device can draw, without making one; render.backend_choose(software) probes Direct3D 12 and switches to Vulkan before the first window opens (host.host_open calls it automatically). Its shaders are SPIR-V that tools/shaders writes from the Bento sources with Shokado
(src/render/shaders/*.spv; Direct3D 12's are the *.dxil beside them). TOOLKIT_VULKAN_VALIDATION=1 turns on VK_LAYER_KHRONOS_validation with its synchronization checks
(=gpu adds GPU-assisted validation); each message it says is logged as an error on the thread whose call made it, which fails a
test. TOOLKIT_FORCE_NO_SM69=1 forces Direct3D 12 shader model probes to report 6.8 to test runtime fallback to Vulkan.
The neutral public API
A program never names Direct3D, DXGI or Win32 to the renderer. It opens the renderer on a window's native handles, which the platform package fills:
#import "trame:platform"
#import "trame:render"
w := platform.open_window("App", {1280, 800})
r: render.Renderer
render.init_window(&r, w, w.size) // or:
render.init(&r, platform.native_surface_handles(w), w.size, transparent = false, space = .Linear)platform.Surface_Handles is a neutral struct the renderer reads: on Windows the HWND (and module handle), on Linux
the Wayland wl_display + wl_surface or the XCB connection + window id (platform.Surface_Backend says which). An
offscreen renderer has no window:
render.init_offscreen(&r, {w, h}, software = true, space = .Srgb) // tests, image export; WARP on Direct3D, lavapipe on VulkanWhen init fails. init, init_window and init_offscreen return false and keep why in the renderer; the rest of it
is released. render.init_failure(&r) gives an Init_Error and the driver's words; render.init_failure_text(&r, allocator)
gives the sentence for a person:
if !render.init_window(&r, w, w.size) {
fmt.eprintfln("myapp: %s", render.init_failure_text(&r, context.temp_allocator))
// no graphics device this program can draw with (Vulkan): vkCreateInstance: ERROR_INCOMPATIBLE_DRIVER.
// Install your system's Vulkan driver (the package mesa-vulkan-drivers on Debian and Ubuntu).
return 1
}Init_Error | |
|---|---|
No_Driver | the graphics API found no device: no driver, one the program cannot load, a virtual machine without one |
No_Window | a device exists but cannot draw into this window |
Failed | the device, its swap chain or its pipelines failed after the driver answered |
render.graphics_api() names the API ("Vulkan", "Direct3D 12"). A machine without a driver never ends the process. On
Direct3D 12 a window falls back to WARP, the software rasterizer, when no hardware device can be made. On Vulkan a machine with
no driver for its graphics card draws with lavapipe, Mesa's software device, which the package the sentence names installs. Why: src/md/infrastructure/no-graphics.md.
host.host_open reports it by itself (getting-started.md).
The device can be made before the window exists, on a thread of its own: the first device of a process loads the graphics
driver, the longest step of a renderer's start. The init of the same kind (hardware, or software with software = true) takes it,
waiting for the thread if it has not finished, and makes only the swap chain or the offscreen target:
render.preload_device() // first thing: Not_Started -> Creating -> Ready (or Failed)
// ... the window, the program's own start ...
render.init_window(&r, w, w.size) // takes it; render.device_preload_state() is Not_Started againA program whose loop sleeps until an event (one living in the notification area, its windows opened later) passes
done: render.preload_device(done = wake, user = app) calls it on the thread once the device is Ready or Failed, and
the loop opens its window then, hidden, so that showing it later costs no driver load.
On Vulkan the thread also makes the shaders, then the two pipelines of a window's first frame (its rectangles and its text)
in the frame format that window will have (preload_device(transparent, space) says which window; by default a host's:
transparent, linear light), then the depth pass's. host.host_open asks for the device itself before it opens its first window (the device, the
window and the font are then made side by side); a program that asked earlier keeps its device. Measured on lavapipe (a
small window, -o:speed, Xvfb): the first frame shown 592 ms after the process started before, 205 ms after
(src/md/infrastructure/fast-start.md).
The first frame on the CPU (Linux; Windows on Direct3D 12). init_window(..., cpu_first = true) returns at once
while the device made early is still being made: the renderer is in its CPU stage (render.cpu_stage_active). Its
first frame is drawn on the CPU, with the shaders' formulas, and shown on the window: through the platform on Linux
(platform.show_pixels: a wl_shm buffer on Wayland, PutImage on X11, a layered popup over the client area on Windows). A program with its own loop asks
render.cpu_stage_next(&r) after each frame: owed, its next frame must come at once; failed, the device did not come. The next frame_begin ends the stage (render.cpu_stage_end, which a program may also
call itself): it waits for the device, makes the surface and the pipelines, gives every texture and retained heap made
meanwhile its GPU object in the same handle, and that frame is drawn on the GPU. If the device does not come, the frames
stay on the CPU and render.init_failure says why. host.host_open asks for the stage and asks for the second frame at
once. During the stage the renderer gives no layer (acquire_target returns 0, and trame:draw draws a layer's content
with its alpha), and the CPU leaves out filters, blend modes, planes, pictures and application shaders:
render.cpu_frame_exact(&r) says whether the last CPU frame had none of them. The stage starts only once the device's
thread knows it has a Vulkan device (milliseconds; with none, init fails at once with the no-graphics sentence). Measured on lavapipe (hello, -o:speed, Xvfb, a loaded machine): the first picture at a median
of 88 ms after the process started, where it came at 392 ms with the stage off. TOOLKIT_CPU_FIRST=0 in the
environment turns the stage off; -define:TOOLKIT_CPU_FIRST=false removes it from the program (64 KB of code).
TOOLKIT_CPU_SHADOW=1 makes a GPU renderer draw each frame on the CPU too, for a test that compares the two
(render.cpu_shadow_pixels). Why: src/md/infrastructure/cpu-first-frames.md.
host.program_start asks for the device (-define:TOOLKIT_EARLY_DEVICE=false or TOOLKIT_EARLY_DEVICE=0 in the
environment: not; in a test process only with TOOLKIT_EARLY_DEVICE=1). A process that never calls it (a command
line's answer, a plugin's child, a headless run) makes no device before its first host_open. render.preload_when_done(done, user) gives a device
being made a callback after the fact: done(user) on its thread once it is made, or at once when it is made already
(host.ahead_due wakes its loop with it).
A device of the other kind, or one that failed, is released and init makes its own as before; render.release_preloaded_device
lets an unused one go. On Vulkan the device is made without a surface; init makes the window's surface and makes its own
device when that one cannot present to it.
Second windows (the developer tools, a detached panel) use the same neutral handles:
render.surface_init(&r, &surface, platform.native_surface_handles(second_window), size, transparent, fixed_size, under_children, composition_only)
render.surface_use(&r, &surface) // the renderer now draws to the second window; call again to go back
render.surface_adopt(&r, &surface) // for good: the renderer's own window is released, the first window may close
render.set_under_children(&r, true) // place the current window's DirectComposition surface below native child HWNDshost.host_close of the first window calls surface_adopt with another open window's surface: that window becomes
Shared.main, paced, and the renderer goes on. With no other window (or a headless first window), it ends what is
shared, as before.
render.surface_drop(&r): the window of the current surface leaves the screen (platform.hide_window): the Vulkan surface
and its swap chain go before the window's native surface does (Wayland destroys it); frames are skipped until
render.surface_remake(&r, platform.native_surface_handles(win)) makes one on the window's handles again, configured at the
next frame. A Direct3D swap chain survives a hide (both do nothing). host.host_hide calls the first, host_frame the
second when Window.shown_again changed.
Everything else — frame_begin / frame_submit / frame_end, textures, pooled targets, capture
(src/render/capture.fm), the blend space, set_max_frame_latency, resize, DPI — is the same call on every system; each
dispatches to its backend through HAS_VULKAN / HAS_D3D12 and Renderer.backend.
render.adapter_info(&r) says what draws the frames, for a report of slowness: the adapter's name, the graphics api
("Direct3D 12", "Vulkan"), and software, true for a software rasterizer (WARP on Windows: DXGI's vendor 0x1414 and device
0x8C; lavapipe on Vulkan: a CPU device). It waits on nothing: Vulkan's names were read when the device was made,
Direct3D's come from the device's adapter object. render.adapter_description(&r) writes both as one line for a log. The settings' Diagnostics page shows it (prefs_page.md).
Staged upload
A large picture's upload (its premultiplication, the copy the driver makes, its mips) took one frame of the interface's
thread: a 186 MB picture held it 84 to 140 ms on the software device. render.Upload spreads it over frames, a band of
rows (UPLOAD_BAND_BYTES, 1 MiB) at a time, as many bands as a frame's budget holds (UPLOAD_BUDGET_DEFAULT, 2 ms),
one at least; the mip chain is made once, after the last band. The same picture then takes 15 to 19 frames of at most
2.7 ms each. trame:pictures does it for every picture of 16 MiB and more (pictures.md).
u, ok := render.upload_begin(r, pixels, w, h) // the texture made, nothing written; pixels stay the caller's
// each frame, on the interface's thread:
if render.upload_step(r, &u) { ready(u.texture) } // done: drawable (its mips come before its first draw)
render.upload_cancel(r, &u) // given up: the texture destroyedThe texture must not be drawn before upload_step says done: rows past u.row are undefined (Direct3D) or zero
(Vulkan). A device recovered during the upload (device_generation changed: the texture came back empty) starts its
bands again from the top at the next step. What each backend allows off the interface's thread, and why the toolkit spreads instead:
src/md/features/staged-upload.md.
Textures after a new device
A device recovered (render.recover, a driver reset) or the end of a rest (below) gives every texture back empty, in the
same handle; r.device_generation changes. An owner that keeps a texture across frames uploads its pixels again then.
render.Kept_Texture does it for an owner that keeps its pixels:
k: render.Kept_Texture // beside the pixels (straight RGBA8, w x h)
t := render.kept_texture(dc.renderer, &k, rgba, w, h) // at each draw: made at the first, uploaded again after a
// new device, made again on another renderer; 0: refused
render.kept_release(&k) // the texture goes; the pixels stay the owner'sThe toolkit's own owners use it (the program's logo, a menu's icons, the setup's marks, the file picker's preview, the
mark editor). An owner that frees its pixels once uploaded asks for them again at a new generation instead: the
thumbnails and trame:pictures do. The glyph pages of trame:draw are reset at draw.begin_frame.
The device at rest
A program whose windows are all hidden lets its graphics device go: NVIDIA's Linux driver keeps a thread that wakes
about 220 times a second for as long as a Vulkan device exists. render.rest(&r, others) releases the device, the
adapter, the instance and the surfaces of the renderer's window and of each Surface in others; the renderer, its
texture handles, its heaps and its settings stay. device_generation changes at once. render.wake(&r) starts making
a device on a thread; the next frame_begin (or surface_init) takes it, makes the current window's surface when that
window shows, and moves to it what was written during the rest. render.resting and render.has_device say where the
renderer is.
The host does it by itself: a Shared none of whose windows has shown for Shared.rest_after (0: 30 s; negative: never)
rests, and host.host_show wakes it (getting-started.md). Linux on Vulkan and Windows on Direct3D 12 only: elsewhere
render.rest answers false (render.REST_SUPPORTED). Why and how: src/md/infrastructure/device-rest.md.
A frame of any size
A frame holds as many instances as the program draws. Both backends write them into the frame's ring.
The tables an instance indexes (transforms, clips, points, gradients) are bound whole: past the device's limit for a
binding (maxStorageBufferRange on Vulkan) what is past it is not drawn, and the renderer says so once on
standard error. A retained heap that would pass its limit refuses the picture. An error in a frame's commands loses that
frame, never the process. trame:draw makes no instance of a rectangle or an image wholly outside the clip (draw.md,
"Clips"). Why: src/md/infrastructure/frame-limits.md.
What differs between the backends
- Present pacing. Direct3D uses a DXGI waitable swap chain (a frame-latency object) and DWM timing for the frame
statistics (shown / missed refreshes). Vulkan has no frame-latency object: the present mode paces frames at the
vblank, and
frame_beginacquires the next swap chain image. The statistics come from the display server (Wayland'swp_presentation, X11's Present: platform.md, "Vblank timing"); without its answers they stay off. Tearing (set_present_mode) maps to Vulkan'sIMMEDIATEwhere the surface offers it. Both backends take the decision fromrender.present_call(mode, tearing_ok, interval, vsync): the sync interval (0: at once), the tearing flag (only with no wait, only where the system and the swap chain allow it) and the mode the frame is presented in;src/render/present_test.fmchecks it as data. - Translucency. A translucent window (
transparent) goes through DirectComposition on Windows (premultiplied alpha). On Linux the compositor blends the alpha surface directly — there is no extra effect to turn on. The frame's clear decides whether the alpha is read: a frame cleared with an alpha of 1 (render.frame_begin, an opaque theme's background) is presented with its alpha ignored (DXGI_ALPHA_MODE_IGNORE, Vulkan'sOPAQUEcomposite alpha where the surface offers it), so nothing behind the window can show through it; a clear of alpha < 1 (a translucent theme, an overlay) keeps premultiplied alpha. The renderer changes mode by itself when the clear does (a theme switch): nothing to call. See src/md/infrastructure/window-alpha.md. - The 2D canvas (
canvas.fm) is Direct3D only for now;render.canvas_supportedreportsfalseon the Vulkan backend and the canvas procedures are no-ops there. - Device loss / recovery exists on both (
render.recover); on Vulkan it makes a new device and keeps the windows' surfaces (the instance's).
Partial redraw (damage regions)
When only a small part of the window changed since the last frame (a blinking caret, a hovered control, a progress bar,
a video, a local CSS animation), the renderer can rasterize only the changed rectangles instead of the whole
window. The application marks the changed boxes between frame_begin and frame_submit (src/render/damage.fm):
render.set_partial_redraw(r, true) // or draw.set_partial_redraw(c, true)
...
render.frame_begin(r, clear)
render.damage_begin(r) // open a region (once; nothing marked = draw nothing)
render.damage_add(r, {x0, y0, x1, y1}) // each changed rectangle, screen pixels, as many as needed
render.damage_scroll(r, rect, dx, dy) // a scrolled view: redraws where the content was and where it is
... draw ...
render.frame_submit(r, frame)
render.frame_end(r)The region is the union of the rectangles, with near ones merged so the list stays bounded (MAX_DAMAGE_RECTS); they
never overlap. The renderer draws every frame-target batch once per rectangle it touches (a batch that touches none is
skipped) and clears only the region; layers and filter passes run whole (they are intermediate images composed back
into the frame). A frame that opens a region and marks nothing presents nothing (wait_for_frame and wait_frame_slot then do
not wait again: the frame keeps its slot). Not calling damage_begin means the whole frame is
damaged, exactly as before: the default is lossless.
Three frames with a region are drawn whole all the same: the first one, one after a frame without a region (or with nothing
submitted, or a new size) since the kept target is behind then, and one that copies its own target while it is drawn (a
backdrop, a blend mode into the frame): the pixels it would read outside the region are the last frame's finished ones.
damage_stats says active false for those.
Correctness is checked by render.damage.verify (set_damage_verify, or the environment variable
TOOLKIT_DAMAGE_VERIFY=1): every partial frame is also rendered in full, on the side with all its steps, and compared; the
first differing pixel and the rectangle it lies in are printed, and damage_verify_differences(r) counts the frames. For
development only (it costs a full extra frame and read-backs).
-define:TOOLKIT_DAMAGE_CHECK=true proves it on a program that marks nothing (examples/whatsnew through tests/examples, the pixel
tests): each frame is drawn whole on the side, the tiles that differ from the last frame become its region, and the partial
frame must come out the same to the byte. render.destroy prints the counts and ends the program with exit code 1 on a
difference.
What shapes every pixel besides the instances damages the whole frame by itself: a frame with a region whose size, clear
colour, blend space, text rendering, corner smoothing, filter settings, transparency, subpixel text or device differ from the
last frame with a region is a whole region (damage_environment). A second source of damage checks damage_building(r)
and adds to the region open instead of beginning another one. texture_version(r, t) changes at each creation, upload,
canvas drawing or video frame of a texture: automatic damage (docs/draw.md "Automatic damage") compares it.
Counters for diagnostics: damage_stats(r) returns the rectangles added and kept, the pixels the
region covers and the pixels of the whole frame, and whether a region is in effect.
How each backend presents a partial frame
- Direct3D 12 / DXGI (
src/render/d12_window.fm,src/render/present.fm): the swap chain usesFLIP_SEQUENTIALand presents throughIDXGISwapChain1::Present1. A window draws into a frame image kept across frames; a partial frame draws only its rectangles there.frame_enddraws the frame image into the back buffer and passes the dirty rectangles inDXGI_PRESENT_PARAMETERS.pDirtyRects; DWM composes only them. A frame with no damage skipsPresent1and the back-buffer copy.render.present_damage_last(r)reports the damage handed to (or skipped by) the lastframe_end. - Vulkan (
src/render/vk_window.fm): a window draws into a frame image of its own, kept across frames; a partial frame draws only its rectangles there.frame_enddraws the frame image into the swap chain's image and presents it with the region (VkPresentRegionsKHR, where the device offersVK_KHR_incremental_present): the compositor composes only it (render.present_regions_supported,render.present_rects_sent). A frame with no damage presents nothing. Why: src/md/infrastructure/gpu-backends.md, "Step 2 as built".
Frame statistics and GPU profiling
render.frame_stats(&r) returns render.Frame_Stats for the last frame_submit: instance counts (insts, insts_uploaded, slug_insts, opaque_insts), polygon clip vertices (clip_points), draw batches and draw calls, and upload traffic in bytes (inst_bytes, table_bytes, const_bytes, upload_bytes).
render.gpu_timestamps_supported(&r) reports whether the active device supports GPU timestamp queries (true on Direct3D 12 once a device exists; true on Vulkan when the queue family's timestampValidBits is not 0). render.set_gpu_profile(&r, true) records timestamps per pass and render.gpu_profile(&r) returns the latest completed Gpu_Profile.
./build/trame render_bench renders fixed showcase and synthetic scenes headless at 1x and 2x and prints CPU time, instance counts, upload bytes, and per-pass GPU timestamps.
The depth pass. Opaque plain shapes are drawn front to back with a depth test before the rest, so the GPU skips what they cover. A window uses it once its depth pipelines are made (by the device made early, or by a pre-warming thread after a new device); its first frames draw without it. An offscreen renderer uses it only after render.set_depth_pass(&r, true): its pipelines are then compiled when it first draws.
Adding another backend
A new backend implements the dispatch set in api.fm (HAS_VULKAN / HAS_D3D12, Backend)
(<prefix>_init, _init_offscreen, _set_blend_space, _frame_begin / _submit / _end, the texture and heap
procedures, _recover). The shared types and the backend-agnostic procedures in render.fm, filter.fm,
damage.fm, present.fm, capture.fm do not change.