At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
41 KiB
AGENTS.md
Guidance for coding agents and contributors working on Crafter.Graphics itself. The README is the user-facing manual, the example READMEs hold the driver investigations, and AGENTS.consumer.md is what agents working in a consumer of this library read: crafter-build copies it into the dependency-notes section of the consumer's AGENTS.md on every build. When any of them disagrees with the code, the code wins; the interfaces in interfaces/ are the reference.
Project overview
Crafter.Graphics is the Crafter engine's graphics library: one C++ module, Crafter.Graphics, with 41 partitions, built with crafter-build from project.cpp. On native targets it is a Vulkan 1.3+ renderer built around VK_EXT_descriptor_heap (bindless, no descriptor-set layouts, push data through vkCmdPushDataEXT), with a bindless-descriptor-set fallback for drivers without the heap, hardware ray tracing, a compute-shader UI, a Wayland or Win32 window, and input. On wasm32-* targets the same C++ surface runs in a browser over WebGPU through a JS bridge, with a software wavefront ray tracer. It depends on Crafter.Event (events), Crafter.Math (vectors, matrices) and Crafter.Asset (.cmesh, .ctex), all pulled from forgejo.catcrafts.net unpinned, and, on native targets, on the Khronos Vulkan-Headers and Vulkan-Utility-Libraries from GitHub as header-only ExternalDependency entries. Its consumers are the examples under examples/ (each a LocalProject of ../../project.cpp) and the maintainer's applications, which pull master.
| Path | What lives there |
|---|---|
interfaces/Crafter.Graphics.cppm |
The umbrella: export imports every partition, unconditionally. |
interfaces/Crafter.Graphics-<Partition>.cppm |
One partition per file, see below. The Vulkan header and the platform headers (wayland-client.h, windows.h, stb_truetype.h, the Linux input headers) go in the global module fragment behind the backend's #ifdef. |
implementations/Crafter.Graphics-<Partition>.cpp |
Implementation units, in two sets chosen by project.cpp: 15 native and 17 DOM units. Clipboard, Font, FontAtlas, Gamepad, Input, InputField, UI-Shared, UIComponents and Window are in both; -Device-Features.cpp is a second unit of :Device; -UI-WebGPU.cpp, -Mesh-WebGPU.cpp and -RenderingElement3D-WebGPU.cpp are the DOM halves; -GamepadWin32.c and .h are the C binding to Windows.Gaming.Input. |
shaders/ |
The five standard UI compute kernels (ui-quads, ui-circles, ui-images, ui-text, ui-fused) and ui-shared.glsl, the GLSL contract user shaders #include. Each kernel is compiled twice, see "Design rules". |
additional/dom-env.js, additional/dom-webgpu.js |
The JS half of the DOM backend: the wasm env imports for the window, DOM, router and clipboard, and the WebGPU bridge with the WGSL of the UI kernels, the TLAS build and the wavefront tracer baked in. Shipped as cfg.files of every wasm build. |
lib/ |
Vendored: stb_image, stb_image_write, stb_truetype; the generated Wayland protocol C files (xdg-shell, xdg-decoration, fractional-scale, viewporter, text-input-v3); libevdev/ with its kernel headers. Not edited. |
examples/<Name>/ |
Standalone projects, MIT, each with its own project.cpp, main.cpp and shaders in GLSL and WGSL side by side. examples/README.md is the index. |
tests/<Name>/main.cpp |
One test per directory, plus the GLSL and the font.ttf some need. Declared in project.cpp. |
project.cpp |
The build description: the dependencies, the backend switch on the target, the partition and implementation lists, the shader builds, libevdev, and every test. |
README.md, examples/*/README.md |
The manual, and the NVIDIA driver investigations (VulkanTriangle, Sponza). |
AGENTS.consumer.md |
Notes for consumers' agents; crafter-build injects them into consumers' AGENTS.md. |
bin/, build/, pipeline_cache.bin |
Generated and gitignored. build/test-logs/ keeps the output of failed tests; pipeline_cache.bin is written by any example or test run from here. |
.review-gates/ |
The pre-push review's config.json and this repository's lens sections (lenses/), read by Crafter.Review. Its push/ and trees/ are generated and gitignored. |
Partitions, by what they are for. Every partition file exists on every target; one that does not apply compiles to an empty module behind #ifdef CRAFTER_GRAPHICS_WINDOW_DOM (or #ifndef), and several hold both halves in one file (Window, Device, UI, Mesh, RenderingElement3D, RTPass, RenderPass, Image2D, FontAtlas, RT).
- Both backends:
:Types(FrameTime,TouchPoint,CrafterKeys,AlignUp),:Keys(consteval Key(CrafterKeys)to the platform's raw code),:Window,:Device,:Input(named actions, rebinding),:Gamepad,:Clipboard,:Animation,:Font(stb_truetype),:FontAtlas(the SDF atlas),:UI(UIRenderer, the item structs,Rect),:UIComponents(Tier 3),:InputField,:RenderPass,:RTPass,:Mesh,:RenderingElement3D,:Image2D,:RT(portable RT PODs and flag constants),:GraphicsTypes(theusingaliasesGraphicsBuffer,GraphicsDescriptorHeap,GraphicsComputeShader,GraphicsCommandBuffer),:ForwardDeclarations. - Vulkan only:
:VulkanBuffer,:ImageVulkan,:SamplerVulkan,:DescriptorHeapVulkan(heap and descriptor-set mode, the RAII slots),:ComputeShader(Tier 1),:ShaderVulkan(VulkanShaderand the NVIDIA SPIR-V rewrite),:ShaderBindingTableVulkan,:PipelineRTVulkan,:VulkanTransition,:Decompress(VK_EXT_memory_decompression). - DOM only:
:WebGPU(theextern "C"bridge declarations),:WebGPUBuffer,:DescriptorHeapWebGPU,:WebGPUComputeShader,:PlainComputeShader,:ShaderBindingTableWebGPU,:PipelineRTWebGPU,:Dom,:DomEvents,:Router.
Dev environment
crafter-build, 3.0.0 or later (project.cpp uses its ShellQuote), is the only build tool: the Flatpak (alias crafter-build='flatpak run net.catcrafts.CrafterBuild'; a locally built one runs with --branch=local) or a native build of the sibling checkout. crafter-build --version prints the compiler it resolved. Loading project.cpp clones Crafter.Event, Crafter.Math and Crafter.Asset into the crafter-build cache and, since they are unpinned, git pulls them on every invocation, and clones the two Khronos header repositories, and for a Win32 target Vulkan-Loader as well, so a build needs the network. --local takes the sibling checkouts (../Crafter.Event, ../Crafter.Math, ../Crafter.Asset) instead and hands the flag on, so Crafter.Asset picks the sibling Crafter.Math too; two copies of one module on the path do not link.
The host is Linux on Wayland. The native Linux backend is Wayland only (no X11), so every test that calls Device::Initialize needs WAYLAND_DISPLAY: it connects to the display right after creating the Vulkan instance, window or no window. The build links wayland-client, xkbcommon, udev and the Vulkan loader from the host or the sysroot; for a Win32 target it links the loader through an import library that project.cpp makes with llvm-dlltool from Vulkan-Loader's loader/vulkan-1.def, into build/vulkan-1-<target>/, since the MinGW toolchains ship none. libevdev is vendored and built as its own static library, Crafter.Graphics-libevdev, once per build. A Vulkan 1.3 driver is the floor; VK_EXT_descriptor_heap (with shaderUntypedPointers), ray tracing and swapchain_maintenance1 (with the instance's surface_maintenance1, for per-present-mode image counts) are optional groups detected at start-up. Recent Mesa's llvmpipe advertises the heap, so a machine without a GPU runs the UI path. The Khronos validation layer is optional and off by default.
Targets, picked with --target= and passed down to the dependencies:
| Target | Backend | Notes |
|---|---|---|
native (x86_64-unknown-linux-gnu) |
Wayland + Vulkan | the development loop |
x86_64-w64-mingw32 |
Win32 + Vulkan | cross-compiled; links vulkan-1 (an import library made from Vulkan-Loader's loader/vulkan-1.def), kernel32, user32, gdi32, runtimeobject, uuid; gamepads through Windows.Gaming.Input |
wasm32-wasip1 |
DOM + WebGPU | no Vulkan loader, no Wayland; dom-env.js and dom-webgpu.js ship beside the .wasm; --no-webgpu drops the WebGPU bridge for DOM-only apps |
aarch64-alpine-linux-musl with --sysroot=, --march=armv8-a --mtune=generic |
Wayland + Vulkan | the Mesa Turnip phone target: no descriptor heap, no ray tracing, the descriptor-set path |
Project flags, before or after test: --local, --timing (defines CRAFTER_TIMING for Window::LogTiming and per-listener update timings; the gated code references Window members that no longer exist, so the build fails, issue #178), --no-webgpu (wasm only), and crafter-build's --target=, --march=, --mtune=, --sysroot=, --debug. Flags ApplyStandardArgs does not interpret are part of the variant hash, so each combination has its own bin/Crafter.Graphics-<target>-<march>-<mtune>-<hash>/ with libCrafter.Graphics.a, the PCMs and the shaders (ui-*.comp.spv and ui-*.comp.sets.spv); earlier variants stay until clean. Glob for a variant directory rather than predicting its hash.
The Flatpak sandbox sees the host filesystem but not the host PATH: the host's binaries are under /run/host/usr/bin, from where statically linked tools (wine, qemu-aarch64-static) run and dynamically linked ones often do not, and it has its own /tmp. A --runner=cmd:<tool> is probed with which inside the sandbox; a missing runner fails those tests rather than skipping them, and skips their build.
Build, test and style commands
crafter-build # the native library and its shaders
crafter-build --local # against ../Crafter.Event, ../Crafter.Math, ../Crafter.Asset
crafter-build --target=wasm32-wasip1 # the DOM/WebGPU library
crafter-build --target=x86_64-w64-mingw32 # the Win32 library
crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:true Win32Link # links a Win32 executable, without Wine
crafter-build test # build and run every test for the host
crafter-build test 'TLAS*' # name glob
crafter-build test --list
crafter-build test --jobs=1 --timeout=120
CRAFTER_GRAPHICS_VALIDATION=1 crafter-build test # with the validation layer; the tests' validation checks only count then
cd examples/HelloUI && crafter-build -r # build an example against this checkout and run it from its bin dir
crafter-build clean
project.cpp registers no lint rules, so crafter-build lint and format have nothing to do here; style is kept by hand (see "Code style"). There is no CI. Before a change is done: crafter-build test passes on the host with CRAFTER_GRAPHICS_VALIDATION set; the examples whose API you touched build (cd examples/<Name> && crafter-build), since they are the in-tree consumers; crafter-build --target=wasm32-wasip1 still compiles when you touched a partition with a DOM half or a backend-agnostic one; and crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:true Win32Link still links when you touched Window, Device, Gamepad, Clipboard or the link flags in project.cpp.
Testing instructions
Tests are declared in project.cpp, not discovered, through the LibraryTest(name) lambda: it copies the library's settings field by field (Configuration is not copyable) and compiles the library's sources plus tests/<name>/main.cpp into one executable, so a test reaches non-exported internals the way the library does. A new test is a directory, a cfg.tests.push_back(LibraryTest("Name")); and a comment above it saying what it covers and what it needs (a GPU, ray tracing, a compositor, a tool). A test that needs shaders adds them to test.config.shaders with the same ShaderType lines the examples use; a font or asset goes in test.config.files; a tool it runs goes in requires_ ({"tool:glslang", "tool:spirv-val"}), which turns the test into a skip when the tool is missing. The declarations sit in the native branch of project.cpp: wasm runs no tests. Wayland-only tests sit in if (!windows); the Win32 tests, PointerWin32 and TextWin32, sit in if (windows), with requires_ = {"tool:wine"} when built on Linux. Win32Link beside them has no requires_, since its link is the test: where there is no Wine it runs as --runner=cmd:true, which builds it and runs nothing. A requires_ would skip the build as well, and a test cannot pick its own runner, as the harness derives every test's from its target.
A test is an int main(): exit 0 passes, nonzero fails, 77 skips (for a missing capability, never for a failed check). Each runs in its own process, in parallel, with a 60 s default timeout, and the output of a failed, crashed or timed-out test is in build/test-logs/<name>.log; a later pass does not delete the log, so check its timestamp. What the tests need, in three groups:
- Pure logic, no GPU: they stage
Device's statics or feed synthetic data to the decision functions that were factored out for them (Device::ResolveFeatures,ChooseDevice,CheckShaderCapabilities,GetMemoryType,PreferDirectDeviceWrite,PipelineCacheDataCompatible,AlignMappedFlushRange,BuildMipChainFinalBarriers,SwapchainStageUnion,BuildTlasWriteBarrier,UIRenderer::ClipFlags,Window::SwapchainMinImageCount,WorkaroundNvidiaAS::Patch,DescriptorHeapVulkan::ComputeLayout,FontAtlas::Packer, the font and input-field helpers).PushConstantRewriteandUIFusedShadercompile GLSL with glslang and check the SPIR-V with spirv-val at runtime, andExampleShaderscompiles every GLSL shader underexamples/the way crafter-build would, the descriptor-set build included, so a shader contract change that breaks an example fails here without building the example;FontAtlasDecodereadsui-shared.glslanddom-webgpu.jsand holds their copies of the SDF encoding constants toFontAtlas's;MouseScroll,PointerEnterLeaveandInputTimedrive the Wayland listener callbacks directly,TitleWaylandreads the requests a window sends off awl_displayconnected to a socketpair, andToplevelStatedoes both: it feeds thexdg_toplevelandxdg_surfaceconfigure callbacks of a window whose surfaces are proxies on such a display, and reads the versionxdg_wm_baseis bound at off the wire.ConfigureResizedoes the same for a configure's size: with a made-up swapchain handle it steps the two ends of a frame (TakeDeferredSizeandMatchSizesToScale,SendFrameSurfaceState) and reads which commit gets the viewport's destination and the acknowledgement, and what the destination is when the scale changes in between. - A headless device:
Device::Initialize()and noWindow(HeapSlotReuse,DeferredDeletion,MeshLifetime,ImageStagingRelease,BLASBuildOptions, theTLAS*tests, ...). Headless still means a Wayland display on Linux. Most of the RT ones checkDevice::rayTracingSupportedand return 77 without it;BLASBuildOptions,TLASInstanceDirtyTrackingandMeshDecompressStagingReleasedo not, and crash on a GPU without ray tracing (Device::RequireRayTracingthrows out ofmain).DeviceSelectionskips with one GPU. - A window and a live compositor:
FrameLoopSync,SetupCmdBufferReuse,UIFallbackParity,SwapchainTransferDst,WindowUpdateClock,HeapASRead,HeapDynamicIndexHit,RTPassPushData,WindowOptionalGlobals(hides xdg-decoration, viewporter and fractional scale from the window in turn),SwapchainImageCount(every present mode, and swapchains with more images than frames in flight, in child processes on llvmpipe where the host's GPU never makes one),TextAntialiasing(text throughDispatchTextandDispatchFusedagainst stb_truetype's own antialiased rasterizer, at 14 and 64 px and stretched, plus a glyph mirrored by its UVs and empty texels shrunk below 4 px),ResizeViewport(aResizeand a configured size, got by maximizing its window for a moment, against the connection itself: it runs withWAYLAND_DEBUGset and stderr in a file and replays the log, which has the driver's attach and commit too), andFeatureRequestsfor its retry case.UIFallbackParity,SwapchainTransferDst,HeapASRead,HeapDynamicIndexHit,RTPassPushDataandTextAntialiasingread the frame back withWindow::CaptureNextFrame(a PNG, decoded with a privateSTB_IMAGE_STATICcopy of stb_image),SwapchainImageCountwith a transfer pass of its own, and check pixels. The others read no frame back: they check what the frame loop, the device and the window report (their counts and members, the validation layer's count, the connection's protocol errors), andResizeViewportthe connection's log.
Conventions the existing tests follow:
- Open
main.cppwith a comment that states the behaviour under test, the failure it guards against and what it needs.tests/HeapSlotReuse/main.cppandtests/UIFallbackParity/main.cppshow the shape. Check(ok, what)printsPASSorFAILwith the description and counts;mainprints a summary and returnsEXIT_FAILUREwhen any failed. Do not stop at the first failure unless later steps are meaningless without it.- A validation check reads
Device::validationErrorCount(the debug messenger only counts, it never aborts) and is gated onstd::getenv("CRAFTER_GRAPHICS_VALIDATION"), since without the layer the count is always zero. - Process-wide state is tested in a child process:
UIFallbackParitystarts itself twice with--render <png>, once withCRAFTER_GRAPHICS_NO_DESCRIPTOR_HEAPset, and compares the frames;FeatureRequestsruns its Vulkan 1.3 case underCRAFTER_GRAPHICS_NO_VULKAN_1_4the same way. - Files go under
fs::temp_directory_path(), named per test. HeapASRead --no-workaroundis the manual probe for whether a new NVIDIA driver still has the descriptor-heap AS fault; run it after a driver update and update the README's status note.
A bug fix ships with a test that fails before the fix and passes after it. A change to a UI kernel keeps UIFallbackParity green: the heap and descriptor-set builds of one source must stay pixel-identical. A category drawn fused must also match the same category drawn standalone. TextAntialiasing compares the two for text, and keeps the text's edge ramp at one screen pixel; for quads, circles and images no test does (UIFusedShader only pins the push-constant layout): check those by eye, or add the comparison.
Cross targets: the Win32 tests run under Wine from the native crafter-build on the host, which has wine on its PATH and finds the host's mingw-w64 itself: WINEPREFIX=<scratch prefix> crafter-build test --target=x86_64-w64-mingw32 PointerWin32 TextWin32 Win32Link. The Flatpak has no wine, so there PointerWin32 and TextWin32 skip and only Win32Link's link is checked. A Flatpak before crafter-build 5.0.0 links no Win32 executable: it gave clang the host's /usr as the MinGW sysroot, which put glibc's headers on the MinGW include path, and libstdc++'s shared_ptr, inlined from nlohmann/json in Crafter.Asset's GLB loader, then read glibc's __libc_single_threaded (Crafter.Build #43). For an aarch64 device, crafter-build test --target=... tries qemu, which has no Vulkan: build with the sysroot, copy the test's whole bin directory (binary, *.spv, *.sets.spv, fonts) to the device and run it there, unlocked and with the window visible, since a locked phone's compositor sends no frame callbacks and the FIFO present then blocks forever.
Code style
Nothing enforces it here, so match the surrounding code:
- The first two lines of every first-party source are
//SPDX-License-Identifier: LGPL-3.0-onlyand//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®, no space after the slashes, then a blank line. Examples areMIT. Shaders carry the same two lines as//comments. Vendored files keep their own headers. import std;everywhere. Standard headers are never#included; the Vulkan header, the Wayland and Win32 headers,stb_truetype.hand the Linux input headers go in the global module fragment aftermodule;, each behind its backend's#ifdef. Tests may#include <cstdlib>,<cstring>or<cstddef>for the macrosimport std;does not provide.- Four-space indentation in new code. A few files have tab-indented blocks (
SemaphoresinWindow.cppm, parts ofWindow.cppandVulkanBuffer.cppm); match the block you are in and do not reindent. Eight files have no final newline; leave that alone too. There is no.editorconfigor.gitattributes. PascalCasefor types, functions and statics,camelCasefor members and variables, a trailing_on private members in the newer classes (heap_,shapedRuns_),k-prefixed constants (kUIFlagClip,kSwapchainWriterStages,kRTGeometryInstanceForceOpaque). Wayland and Win32 callbacks keep the protocol'ssnake_casenames. Vulkan structs are filled with designated initialisers.- Fixed-width types (
std::uint32_t;std::uint16_tfor slot indices);intonly at C boundaries.std::printlnandstd::format;std::runtime_errorwith a message naming the file or the field for anything a user can get wrong,std::invalid_argumentfor a precondition. - Comments explain why: the failure mode, the constraint, the rejected alternative, the issue number (
#118) on the Forgejo tracker. The codebase carries long comments on purpose, and the recent commit bodies have the voice. Keep them, and write them for new non-obvious code. - GLSL:
#version 460,#extension GL_GOOGLE_include_directive : enable,#include "ui-shared.glsl"(crafter-build putsshaders/on the include path throughcfg.buildFiles), theUI_HEAP_*macros instead ofdescriptor_heap,std430structs mirrored by a C++ struct with astatic_asserton its size. Examples ship a.wgslbeside every.glsl.
Design rules
These were decided deliberately. Do not undo them without the maintainer's say-so.
- The target picks the backend, and there is no abstraction layer.
project.cppdefines exactly one ofCRAFTER_GRAPHICS_WINDOW_WAYLAND,CRAFTER_GRAPHICS_WINDOW_WIN32andCRAFTER_GRAPHICS_WINDOW_DOMfrom the target triple; there is no runtime backend switch and no X11.:GraphicsTypesholdsusingaliases, not virtual interfaces. Where the two backends' APIs differ, portable code#ifdefs at the call site, as the examples do, rather than the library inventing a shared signature that is a no-op on one side. - Every partition exists on every target. crafter-build's dependency scanner does not respect
#ifdefaround animport :X;, so a partition file is never left out of the list; its body is gated instead, and the umbrella imports everything unconditionally. Backend-specific implementation units are chosen inproject.cpp. - One binding model in two builds. On the heap path pipelines are created with
VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT, no pipeline layout, and push data throughvkCmdPushDataEXT. On a driver without the heap the same slots live in one bindless descriptor set per frame (bindings 0 to 3: storage images, sampled images, samplers, storage buffers) and push constants go throughvkCmdPushConstants. Slot handles, item structs,UIDispatchHeaderand theUIRendererAPI mean the same in both. Every compute kernel is compiled twice from one source (CRAFTER_GRAPHICS_DESCRIPTOR_SETSselects theUI_HEAP_*macros; the variant issets),ComputeShader::Loadpicks the file, andUIFallbackParityproves the two render identically. Push blocks stay within 256 bytes. Ray tracing is heap-only. - The UI contracts are frozen.
UIDispatchHeaderis 48 bytes and starts every UI push block;QuadItemis 64,CircleItem48,ImageItem64 andGlyphItem48 bytes, byte for byte withui-shared.glslunderstd430. They grow only through the reservedflagsbits and_pad.UIFusedHeader(128 bytes) is a separate contract forDispatchFused. - Three tiers, and the source is the customisation API. Tier 1 is
ComputeShaderandUIRenderer::Dispatch; Tier 2 the standard kernels, item structs andUIRendererhelpers; Tier 3 stateless functions that append items to user-owned buffers and never dispatch. No libraryThemetype (colours come as*Colorsaggregates), no widget tree, no layout engine beyondRect::SubRectandInset, no hit-testing, no focus management; state lives in user-owned PODs (InputFieldis the model). A component that does not fit is copied and edited, not hooked: no virtual overrides, no extension points. Additive changes (another kernel, another stateless component) are fine. - Standard kernels dispatch one workgroup per 8x8 screen tile, each thread owning one pixel and iterating every item in array order into a local accumulator, stored once. Array order is draw order and there is no inter-workgroup race. Never go back to a workgroup per item: Vulkan orders nothing between the workgroups of one dispatch, and overlapping items then race on the image (striped fills, stale pixels). The cost is
O(W*H*N)and documented as such; the shared-memory tile cull inui-shared.glslmust stay a strict superset of the per-pixel test. - Three frames in flight, a fence per frame, no steady-state wait-idle. Frames in flight are not swapchain images: the swapchain has as many images as its present mode needs, what lives per frame (command buffer, fence, acquire semaphore, heap copy, TLAS) is keyed by
Window::currentFrameand what lives per image bycurrentImage, and the image a frame draws into reaches shaders through the heap's swapchain slots (DescriptorHeapVulkan::AddSwapchainSlot, #160). The owners of buffers, acceleration structures, shader modules and pipelines (VulkanBuffer,Mesh,TlasWithBuffer,VulkanShader,ComputeShader,PipelineRTVulkan) release them throughDevice::EnqueueDeletion, which has overloads for exactly those handle kinds;ReclaimDeletionsfrees an entryframesInFlightframes later andDrainDeletionsafter a wait-idle. Owners of handles the queue has no overload for wait for the GPU first and then destroy directly:~DescriptorHeapVulkanin descriptor-set mode,~Window,~FontAtlasthroughImageVulkan::Destroy. A destructor never destroys a handle without one or the other: a frame in flight may still use it, and a static owner of a queued kind is destroyed after the driver has gone, which only the queue survives.Clear()is for a GPU known to be idle. The deletion queue, its mutex andRenderingElement3D::tlasesare leaked on purpose for the same reason. Staged re-uploads go through the per-frame staging ring inVulkanBuffer::Stage. - The library enables only the device features its own shaders use. Everything an application's shaders need (
shaderInt16for auint16_tspec constant, fp16, 16-bit storage,scalarBlockLayout) is the application's to ask for throughDevice::Initialize(required, optional), andVulkanShaderrefuses a module whose capabilities nothing enabled, naming the field. Do not add a feature to thelibraryset for an example's convenience; have the example ask. - Barriers are scoped and derived. A
RenderPassreports itsSwapchainStage(); the frame loop's acquire, inter-pass and present barriers take their stage and access masks from the passes (SwapchainStageUnion,SwapchainWriterAccess,BuildSwapchainInterPassBarrier), masked byDevice::stageMaskso the RT stage never appears on a device without it. In the frame loop there is noALL_COMMANDSand no queue-wide memory barrier, and a ranged flush rounds tononCoherentAtomSize. The acceleration-structure builds and the GPU decompression do use globalVkMemoryBarriers on purpose (BuildTlasWriteBarrier,BuildTlasReadBarrier,Decompress::DecompressOnGPU): execution order alone never makes a build's writes visible to the shaders that read them. The window never clears the swapchain image (TRANSFER_DSTis not on every surface); passes draw their own background. - Driver workarounds are fenced and written to be deleted. The NVIDIA descriptor-heap AS-read rewrite is one block in
ShaderVulkan.cppmgated onDevice::workaroundDescriptorHeapAS, with its push-data hook inRTPassandComputeShader, a kill switch (CRAFTER_GRAPHICS_NO_AS_WORKAROUND), a probe test and a status note in the README andexamples/VulkanTriangle/README.md. A new workaround gets the same: aDeviceflag, one fenced block, a probe, a note. A fault the library cannot hide (dynamic descriptor indexing in hit shaders) is documented with the consumer-side pattern instead (examples/Sponza/README.md). - Prefer the clean breaking change. When a fix can be a backward-compatible patch or a cleaner API change, make the API change and update the examples and tests in the same commit; the consumers are in this tree or the maintainer's. Do not stage a compat shim "for now".
lib/is vendored and untouched. libevdev is built as its own static library configuration so it compiles once, not once per test; its include path and the kernel headers are absolute because thisproject.cppis also loaded from a consumer's directory.
Commit and PR guidelines
- Branch from
master; PRs go tomasteronforgejo.catcrafts.net/Catcrafts/Crafter.Graphics. Agent branches areclaude/<topic>, issue workclaude/issue-<n>. The fetch URL is HTTPS and the push URL SSH (forgejo@forgejo.catcrafts.net:Catcrafts/Crafter.Graphics.git); the server refuses HTTPS pushes. - Subject:
type(scope): imperative summary, withfeat,fix,perf,refactor,docsortestand the area as the scope (device,rt,ui,window,wayland,win32,webgpu,font-atlas,compute,gamepad). The body is grouped under the components it touches (Device,Shaders,Window,Tests) and says what was wrong, why, and why the fix has this shape;git log -3shows the voice. - Update the README (and the example README that holds the investigation) in the same change when user-visible behaviour changes, and
AGENTS.consumer.mdwhen a convention, a signature, a contract or an environment variable consumers lean on changes. Consumers pick the new notes up on their next build. - Crafter.Event, Crafter.Math and Crafter.Asset are pulled unpinned, so a change that needs one of them lands there first and is built here with
--localmeanwhile. Pushing is per repository: land the sibling, then this one. - Every push of new commits goes through Crafter.Review's pre-push review first, and goes out only once the owner approves the frozen hash. Run
flatpak run net.catcrafts.CrafterReview initonce in a fresh checkout or worktree: it writes the/prepushskill that drives the review, and the skill stays untracked. There is no CI, so the review's gate0, the commands in.review-gates/config.json, is the check before the push: the "Before a change is done" checks above, with every example built, andnode --checkon the two JS files inadditional/.freezerefuses merge commits, so the merge of a reviewed branch intomasteris pushed without a freeze of its own. - Every commit of a pushed range is GPG-signed, has
jorijnvdgraaf@catcrafts.netas its author and committer, and carries no AI attribution trailer in its message, neitherCo-Authored-By:norAssisted-by:.freezerefuses a range with a commit that breaks any of these (requireSigned,authorsandaiTrailersin.review-gates/config.json). - Never commit
bin/,build/orpipeline_cache.bin, and never editlib/. - A second worktree of this repository may sit beside it (
git worktree list); its branch shows with a+ingit branch. Leave it to whoever opened it.
Security considerations
project.cppis compiled and run by crafter-build; it clones and pulls three sibling repositories from their default branch and two Khronos repositories from GitHub on every invocation, for a Win32 target also clones and pulls Vulkan-Loader, unpinned, and runsllvm-dlltoolon itsloader/vulkan-1.defwhen the import library underbuild/was made from another.defor command, and the Sponza exampleGitFetches a 280 MB asset repository (pinned to a commit). Pin acommitin aGitProjectspec when that matters.- The validation layer, GPU-assisted validation included, is a developer tool and off by default;
CRAFTER_GRAPHICS_VALIDATIONturns it on. GPU-AV has crashed a vendor SPIR-V compiler on the heap pipelines before, which is why it is opt-in. - Shaders are read from disk relative to the working directory and checked for the SPIR-V magic and word alignment before they reach the driver; the NVIDIA rewrite edits SPIR-V in memory and
PushConstantRewritevalidates its output with spirv-val. pipeline_cache.binis written to the working directory at exit and read back only when its header matches the device; it is gitignored here and should be in a consumer.- The environment switches (
CRAFTER_GRAPHICS_VALIDATION,CRAFTER_GRAPHICS_DEVICE,CRAFTER_GRAPHICS_NO_DESCRIPTOR_HEAP,CRAFTER_GRAPHICS_NO_AS_WORKAROUND,CRAFTER_GRAPHICS_NO_VULKAN_1_4,CRAFTER_PRESENT_IMMEDIATE) are read withstd::getenvinDevice.cppandWindow.cpp. A new one takes theCRAFTER_GRAPHICS_prefix, means "set to any value", and is listed in the README and inAGENTS.consumer.md. dom-env.jsanddom-webgpu.jsare shipped to browsers as they are.dom-webgpu.jsreplacesdocument.bodywith an error whennavigator.gpuis absent, which is why--no-webgpuexists for DOM-only pages.- Tests write only under
fs::temp_directory_path()and their own bin directory.
Gotchas
- A new partition is three edits: the interface file, the
ifacesarray inproject.cpp(astd::arraywith a literal size, so bump it) and the umbrellaCrafter.Graphics.cppm. An implementation unit goes inimpls(native),domImpls(DOM) or both, again with literal sizes; a test's sources are built fromimpls, so a native unit missing there fails every test link. Device::Initializeon the Wayland backend connects to the display and throws without one; "headless" tests still need a compositor.- Buffer slot indices:
AllocateBufferSlotsreturns an index relative to the heap's buffer region, while GLSLdescriptor_heapSSBO arrays index in buffer-descriptor units from heap byte 0.BufferSlotconverts tobufferStartElement + raw; raw code (the RT examples) passesheap.bufferStartElementas auint16_tspec constant, which needsshaderInt16. In descriptor-set modebufferStartElementis 0. Image and sampler slots are used as they are. A wrong index reads zeros, which looks like "every item field is zero". UIRenderer::RegisterBufferrefuses a buffer created withoutVK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT. Freed slots are handed out again at once, so a slot may only be freed when no frame in flight reads it (aftervkQueueWaitIdle, or at a scene switch). In descriptor-set mode a slot write destroys the previous view immediately.- The swapchain image stays in
VK_IMAGE_LAYOUT_GENERALacross the pass list and is never cleared;Window::clearColoris unused.swapchainUsagesays whetherTRANSFER_DSTwas available.onResizefires after a swapchain rebuild; slots listed withAddSwapchainSlotfollow by themselves, and anything else holding the old images is made again there. A rebuild asked for during a frame (ResizeorSetPresentModefrom a listener) waits for that frame's present, since the rest of the frame indexes the swapchain it acquired from.RenderPass::Record'sframeIdxis the frame slot, not the image. - On Wayland the configure listener only keeps a size (
deferredLogicalWidth) and a serial (unackedConfigure):Render()rebuilds at its boundaries (RebuildIfDeferred), so a compositor's resize, where it changes the pixels, firesonResizefrom inside it, and a rebuild that throws stays pending for the next one. The window has two sizes,widthxheight(the buffers' pixels) andlogicalWidthxlogicalHeight(the surface's size: a configured size unchanged,logicalConfigured, or what the application's pixels come to), andscaleties them only where one is worked out from the other: when a configured size is taken and before every swapchain (MatchSizesToScale). Nothing works the surface's size back fromwidth / scaleat another moment: the scale changes in any dispatch, in the middle of a frame too (a listener that dispatches events), and for a configured size the two roundings land above it wherever the size times the scale is not a whole number (#201: 392x796 at 2.85 came back as 393x797). Of aResizeand a configured size the one asked for last waits, each clearing the other's. What the surface takes with a buffer goes out inSendFrameSurfaceState, right before the present: the viewport's destination when the surface's size is not the one last sent (sentLogicalWidth), which is sent nowhere else, and the acknowledgement of a configure that waits for a frame (one that asks for nothing new while nothing is owed is acknowledged in the listener). Both are state the nextwl_surface.commitapplies, and commits that are no frame's happen all the time: the listener's own, a consumer's request for a frame callback, and the second commit the NVIDIA driver makes in a FIFO present where the compositor haswp_fifo_v1(seen on615.78.08under KWin 6.8.0). So a destination sent at the rebuild is applied to the old buffer, which is then shown scaled (#199), and an acknowledgement sent in the listener for a new size names that frame as the answer. A change that touches the surface's size (the scale of #165, the buffers' rounding of #201) keeps to that. The cue for a window that draws on demand isonFrameOwed. Device::frameCounteris one clock for every window, so the deletion queue and the staging rings assume one rendering window. The font atlas evicts on it too, on both backends: without aWindowadvancing it nothing is ever evicted, and a full atlas leaves new glyphs blank, so a headless test steps it itself (FontAtlasEviction).ImageVulkan::Create's defaultconsumerStageis the RT stage, corrected to compute on a device without ray tracing; the font atlas passes compute explicitly.VulkanTransition'sGENERALmapping does the same.UIRenderer::ShapeTextandFontAtlaskey their caches on theFont*: callUIRenderer::InvalidateFont, which clears both, before destroying aFont, or a new one at the same address aliases stale runs and glyphs. The atlas also keeps theFont*of a glyph waiting for a cell until the next frame's first call, where it rasterises from it.RenderingElement3D::elementsstores raw pointers; astd::vector<RenderingElement3D>that grows afterAdddangles them (Sponza reserves up front).BuildTLASon an index whose earlier submission has not completed overwrites a TLAS in use; buildingtlases[window.currentFrame]fromonUpdateis safe, andtlases[i].addresschanges when a TLAS outgrows its storage.PipelineRTVulkan::InitdefaultsmaxRecursionDepthto 1; a closest-hit that traces needs 2, and tracing deeper than the pipeline allows loses the device.BuildTlasWriteBarrier's source access mask carries no read bit on purpose: synchronization validation 1.4.363 otherwise reports two builds in one command buffer as a write-after-write hazard.- NVIDIA, as of driver
615.78.08: reading a TLAS through the heap still faults (worked around); dynamic descriptor indexing in hit shaders works there and faulted on610.43.02, so the Sponza pattern (a spec-constant slot, a dynamic index within the resource) stays the portable one.HeapDynamicIndexHitskips on the older drivers. - The README links
WAVEFRONT-DESIGN.md, which was removed with the stale docs (15ce47f); the wavefront tracer is described in the README's WebGPU section and inadditional/dom-webgpu.js. - The text kernels decode
FontAtlas's SDF in one place,ui-shared.glsl(UI_SDF_ON_EDGE,UI_SDF_PIXEL_DIST_SCALE,uiGlyphRamp,uiGlyphCoverage), and the WGSL text kernel indom-webgpu.jsrepeats it;FontAtlasDecodeholds both copies of the constants toFontAtlas's, and nothing renders the WGSL, so check a change to it by hand (examples/HelloUIbuilt with--target=wasm32-wasip1, in a browser, or the kernel run through Deno's WebGPU). The WGSL lives inString.rawliterals: a backtick in a WGSL comment ends the literal and breaks the whole backend, which onlynode --check additional/dom-webgpu.jsnotices. - Crafter.Math's misspelled identifiers (
Quanternion*,MulitplyAdd,CollumSize) are its API; do not correct them here. - Dependency notes: crafter-build 3.0.0 or newer keeps a section at the end of this file holding the
AGENTS.consumer.mdof every dependency that ships one (2.2.0 leaves the file alone), rewritten on everycrafter-buildandcrafter-build test. As of that date Crafter.Math's notes are on itsmaster, Crafter.Asset's only on itsclaude/glb-loaderbranch, and Crafter.Event has none, so a plain build adds Math's and a--localbuild whatever the sibling checkouts hold. Edits inside the section's markers are lost on the next build; a change to those notes belongs in their repositories. Commit the section when it changes.