Editor step 1: Dear ImGui in the engine — Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Draw Dear ImGui (docking branch) over an engine surface on both backends, fed by the engine's own platform events, shown by a new EngineTest variant and covered by unit and graphics tests.
Architecture: The renderer gets a UI-library-agnostic overlay: graphics::UiDrawData (vertices, 16-bit indices,
commands with clip rects and engine texture ids) on SurfaceFrame, drawn after post-process into the back buffer by
a new engine shader pair, on Vulkan and D3D12. The platform layer reports mouse, wheel, text and focus events and
offers cursor shapes, clipboard, text input and the display scale. A new static library EditorUI (Editor/UI/)
owns the ImGui context and is the only code that includes imgui.h: it feeds platform events into ImGui, turns ImGui's
texture requests into engine textures and converts ImDrawData into graphics::UiDrawData.
Tech Stack: C++23, Dear ImGui v1.93.0-docking (MIT), HLSL/DXC, Vulkan + D3D12, SDL3 (Linux), Win32, doctest,
CMake + MSBuild.
Spec: Docs/Editor.md (sections 5.1, 5.3, 5.4, 5.9, 5.10; step 1 of section 6).
Global Constraints
- The user commits. No
git commit, no staging. Every "Commit" step of the template is replaced by "leave in the working tree". - Rules of
Docs/Preferences.mdapply: trailing return types,const, braces,PRIMAL_APIon engine API other binaries call, logging throughprimal::log, no issue numbers in comments, copyright header// Copyright (c) 2026 Charles Smith+ MIT line on new files, designated initializers,std::to_underlying. - Dear ImGui is downloaded, never committed: tag
v1.93.0-docking, pinned by SHA-256 incmake/PrimalDependencies.cmakeand aEditor/UI/ThirdParty.targetsfor MSBuild (same version and hashes). imgui.his included only underEditor/UI/. Engine code (Engine/) never includes it.- Both build systems: every new source goes in a
CMakeLists.txtand the matching.vcxproj(+.filters). - Windows-only code is written blind on Linux and checked in the VM (
Tools/WinVM/winvm.sh). - Verification standard of
CLAUDE.md: 0 warnings (clang, GCC, MSVC), clang-tidy 0, UnitTests, GraphicsTests in Debug with validation clean, the EngineTest variant exits 0; the user does the visual check. - New engine shaders: a row in
Engine/Graphics/Shaders/EngineShaders.h; a new struct shared with HLSL: a row inShaderCompilerTool/ShaderLayoutCheck.cpp'sshared_structs.
Review Focus
- A clip rect partly or fully outside the surface (a window dragged off-screen): the scissor is clamped to the surface, a command with an empty clipped rect is skipped, no validation error. Test in Task 3.
- More than 65,535 vertices in one list (a large demo window, big tables):
vertex_offsetper command is honoured (ImGuiBackendFlags_RendererHasVtxOffset), nothing is drawn from the wrong vertices. Test in Task 3 and Task 5. - A surface resized or minimized between ImGui's frame and the render: a minimized surface sits the frame out without touching UI buffers; the next frame uses the new size for the projection. Test in Task 3.
- Texture requests while frames are in flight (a new font size rasterized): the old engine texture is removed only through the renderer's deferred release, never while a frame in flight samples it. Test in Task 5.
- Non-ASCII text input (an IME commit,
é, emoji): text arrives as UTF-8 in onetextevent and reaches ImGui unchanged. Tests in Task 2 and Task 5.
Task 1: Dear ImGui dependency and the EditorUI library
Files:
- Modify:
cmake/PrimalDependencies.cmake(FetchContent of the ImGuiv1.93.0-dockingsource archive, SHA-256 pinned) - Create:
Editor/CMakeLists.txt,Editor/UI/CMakeLists.txt(static libraryEditorUI: the ImGui core sourcesimgui.cpp,imgui_draw.cpp,imgui_tables.cpp,imgui_widgets.cpp,imgui_demo.cpp+ ours; ImGui's folder is a SYSTEM include so its warnings don't fail-Werror) - Create:
Editor/UI/EditorUI.vcxproj(+.filters),Editor/UI/ThirdParty.targets(download +VerifyFileHash, likeContentTools/ThirdParty.targets), add the project toPrimal.slnx - Create:
Editor/UI/ImGuiConfig.h(passed asIMGUI_USER_CONFIG:#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS,IM_ASSERT→ the engine'sassert) - Modify: root
CMakeLists.txt(add_subdirectory(Editor)),UnitTests/CMakeLists.txt+UnitTests.vcxproj(linkEditorUI) - Test:
UnitTests/EditorUiTests.cpp(new; in both build files)
Interfaces:
-
Produces: CMake target
EditorUI(static, linksPrimalEngine), MSBuild projectEditorUI.vcxprojproducingEditorUI.lib; ImGui headers reachable as<imgui.h>for targets linkingEditorUI. -
Step 1: Write the failing test
TEST_CASE("imgui: a frame without a backend")inEditorUiTests.cpp(suiteeditor_ui): create a context, setio.DisplaySize = {640, 480}, build the font atlas (io.Fonts->Build()),NewFrame(),ImGui::ShowDemoWindow(),Render();CHECK(ImGui::GetDrawData()->Valid),CHECK(ImGui::GetDrawData()->TotalVtxCount > 0); destroy the context. -
Step 2: Configure and build; expect failure —
cmake --preset linux-debug && cmake --build --preset linux-debugfails:imgui.hnot found. -
Step 3: Add the download, the library and the MSBuild project as listed under Files.
-
Step 4: Run
x64/Debug/UnitTests -ts="editor_ui"→ passes; fullUnitTestspasses;ci.sh tidy0 warnings (tidy skips ImGui's own sources); GCC preset builds with 0 warnings. -
Step 5: VM —
winvm.sh sync, build Debug + Release with MSBuild (the download target runs),UnitTests.exe -ts="editor_ui"passes. -
Step 6: Leave in the working tree.
Task 2: Platform events, cursor, clipboard, text input, display scale (Linux)
Files:
- Modify:
Engine/Platform/PlatformTypes.h(newWindowEventtypes and fields,CursorShape, the new functions) - Modify:
Engine/Platform/Window.h,Engine/Platform/Window.cpp,Engine/Platform/PlatformLinux.cpp - Test:
GraphicsTests/WindowTests.cpp
Interfaces:
-
Produces (in
primal::platform):WindowEvent::Typegainsmouse_move,mouse_button_down,mouse_button_up,mouse_wheel,mouse_left(the pointer left the window),text,focus_gained,focus_lost.WindowEventgainsf32 x{0}, y{0}(pointer in the window's client area, pixels),u32 button{0}(0 left, 1 right, 2 middle, 3 x1, 4 x2),f32 wheel_x{0}, wheel_y{0}(notches; positive y = away from the user),const char *text{nullptr}(UTF-8, valid only during the callback).key_down/key_upstay as they are.enum class CursorShape : u32 { arrow, text_input, resize_all, resize_ns, resize_ew, resize_nesw, resize_nwse, hand, not_allowed, hidden };PRIMAL_API auto set_cursor(CursorShape shape) -> void;PRIMAL_API auto set_clipboard_text(const char *text) -> void;(UTF-8)[[nodiscard]] PRIMAL_API auto clipboard_text() -> std::string;(UTF-8, empty when none)Window::start_text_input() const -> void,Window::stop_text_input() const -> void(textevents arrive only between them; Win32: no-ops),Window::display_scale() const -> f32(1.0 at 96 DPI / 100 %), allPRIMAL_API.
-
Step 1: Write the failing tests in
WindowTests.cpp(they push synthetic SDL events withSDL_PushEventon Linux; on WindowsPostMessageW— written in Task 4):"window: mouse events reach the callback": push a motion to (10, 20) in points, a left button down/up and a wheel of +1; afterpump_events(), the callback sawmouse_movewithx == 10 * density,y == 20 * density(density =SDL_GetWindowPixelDensity),mouse_button_down/upwithbutton == 0,mouse_wheelwithwheel_y == 1.f."window: text events carry UTF-8":start_text_input(), push anSDL_EVENT_TEXT_INPUTwith"é😀"; the callback'stextcompares equal to"é😀"; afterstop_text_input()(and no push) notextevent."window: focus and leave events": push focus gained/lost and mouse leave; the callback seesfocus_gained,focus_lost,mouse_left."window: clipboard round trip":set_clipboard_text("Primal ✓"),CHECK(clipboard_text() == "Primal ✓")(skip with aMESSAGEwhen the display has no clipboard owner, as under some Xvfb setups: checkSDL_HasClipboardText()after setting)."window: display scale is positive":CHECK(window.display_scale() > 0.f).
-
Step 2: Run
xvfb-run -a x64/Debug/GraphicsTests -tc="window:*"→ the new cases fail to compile. -
Step 3: Implement on Linux in
PlatformLinux.cpp: translateSDL_EVENT_MOUSE_MOTION,_BUTTON_DOWN/_UP,_WHEEL,SDL_EVENT_WINDOW_MOUSE_LEAVE,SDL_EVENT_TEXT_INPUT,SDL_EVENT_WINDOW_FOCUS_GAINED/_LOSTintoWindowEvents for the event's window (points ×SDL_GetWindowPixelDensity= pixels);set_cursorwithSDL_CreateSystemCursor(cached per shape) /SDL_HideCursor; clipboard withSDL_SetClipboardText/SDL_GetClipboardText+SDL_free;SDL_StartTextInput/SDL_StopTextInput;SDL_GetWindowDisplayScale. The engine's input state (InputSDL.cpp) keeps receiving the same events as before. -
Step 4: Run the window tests and the whole
GraphicsTestsunderxvfb-run(Debug) and on the desktop session → pass;UnitTestspass; tidy 0; GCC build 0 warnings. -
Step 5: Leave in the working tree.
Task 3: Renderer UI pass — API, shaders, Vulkan
Files:
- Create:
Engine/Graphics/UiDrawData.h(the types below; included byRenderer.h) - Modify:
Engine/Graphics/Renderer.h(SurfaceFramegainsconst UiDrawData *ui{nullptr};— drawn after post-process;nullptr= no UI) - Create:
Engine/Graphics/Shaders/UiPass.hlsl(UiPassVS,UiPassPS) - Modify:
Engine/Graphics/Shaders/EngineShaders.h(idsui_pass_vs,ui_pass_ps+ rows),Engine/Graphics/Shaders/CommonTypes.hlsli(UiPassConstants),ShaderCompilerTool/ShaderLayoutCheck.cpp(row) - Create:
Engine/Graphics/Vulkan/VulkanUiPass.h/.cpp(namespaceprimal::graphics::vulkan::ui_pass); modifyVulkanCore.cpp(record_surface()after post-process; constant buffer reservation counts the UI bytes),VulkanCore.cpp's init/shutdown andreload_shaderspath (the pipeline is rebuilt like the others),Engine/CMakeLists.txt - Test:
GraphicsTests/UiPassTests.cpp(new; CMake +GraphicsTests.vcxproj)
Interfaces:
-
Produces (
Engine/Graphics/UiDrawData.h, namespaceprimal::graphics):struct UiVertex { math::v2 position; math::v2 uv; u32 color; }; // 20 bytes; color RGBA8, R in the low byte, sRGB using ui_index = u16; struct UiDrawCommand { math::v4 clip_rect{}; // left, top, right, bottom, in pixels relative to UiDrawData::display_position id::id_type texture_id{id::invalid_id}; // a graphics::add_texture() id; must be valid u32 index_offset{0}; // into the list's indices u32 index_count{0}; u32 vertex_offset{0}; // added to each index }; struct UiDrawList { std::span<const UiVertex> vertices; std::span<const ui_index> indices; std::span<const UiDrawCommand> commands; }; struct UiDrawData { std::span<const UiDrawList> lists; math::v2 display_position{}; // top-left of the UI space that maps to the surface's (0, 0) math::v2 display_size{}; // in pixels; (0, 0) = the surface's size };static_assert(sizeof(UiVertex) == 20). The data must stay valid untilrender_frame()returns (it is copied into the frame's GPU memory there). -
UiPassConstants(HLSL + C++ throughSharedTypes.h):float2 Scale; float2 Translate; uint TextureIndex; uint VertexOffset; uint IndexOffset; uint Padding;(root constants / push constants). -
Shader contract: the vertex shader pulls vertices and indices (no vertex or index buffer binding): indices from a
ByteAddressBuffer(16-bit,IndexOffset + SV_VertexID), vertices from aStructuredBuffer<UiVertex>(VertexOffset + index), both bound like the gpass's per-frame buffers (root SRVs / push descriptors) and filled from the frame's constant buffer. The pixel shader samplesTexture2D<float4>(ResourceDescriptorHeap[TextureIndex])with the linear clamp sampler, converts the vertex colour from sRGB to linear, outputscolor * texel(linear; the back buffer is linear scRGB or an_SRGBformat). Blending:src_alpha,inv_src_alphafor colour;one,inv_src_alphafor alpha. No depth. -
Recording per command: scissor =
clip_rect - display_position, clamped to the surface; skip when empty;Draw(index_count, 1, 0, 0)withIndexOffset/VertexOffset= the list's base in the frame buffer + the command's offsets. -
Step 1: Write the failing tests in
UiPassTests.cpp(suite"ui pass", each withgraphics_test::Sessionandshutdown_and_check(), a white 1×1 texture fromTestContent.h's helpers):"ui pass: one quad": one list, 4 vertices, 6 indices, one command; 3 frames; validation clean."ui pass: clip rects outside the surface": commands with rects fully outside, partly outside, zero-size and negative; 3 frames; validation clean."ui pass: vertex offset over 65535": one list with 70,000 vertices and two commands, the second withvertex_offset = 65,536; validation clean."ui pass: empty and absent":ui == nullptr,listsempty, a list with no commands; validation clean."ui pass: two surfaces and a resize": two views with UI, resize one between frames, minimize-like size (resize to 0×0 is not allowed: use the smallest the window manager allows) — validation clean."ui pass: shader reload": draw,graphics::reload_shaders(), draw again; validation clean.
-
Step 2: Run
xvfb-run -a x64/Debug/GraphicsTests -ts="ui pass"→ fails to compile (UiDrawDataunknown). -
Step 3: Implement the API, the shaders, the table rows and the layout check row. Build → the layout check passes (
ShaderCompilerToolruns on build). -
Step 4: Implement
vulkan::ui_pass:initialize() -> bool,shutdown() -> void,prepare(const UiDrawData &, ConstantBuffer &) -> PreparedUi(copies vertices and indices into the frame's buffer, returns the GPU addresses and per-list bases),record(VkCommandBuffer, const PreparedUi &, const VulkanFrameInfo &, VkImageView back_buffer, VkFormat) -> void(dynamic rendering, load-op load),rebuild_pipelines() -> voidforreload_shaders(). One pipeline per back-buffer format, created on first use. Recording follows post-process insiderecord_surface(), before the transition to present, with avkx::ScopedMarker{cmd, "UI"}. -
Step 5: Run the new suite and the whole
GraphicsTests(Debug, Xvfb + lavapipe and RADV, validation +VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1once) → pass;UnitTests, tidy, GCC: clean. The renderer test (linux-debug-renderer) still exits 0 (no UI there). -
Step 6: Leave in the working tree.
Task 4: D3D12 UI pass and the Win32 platform events
Files:
- Create:
Engine/Graphics/Direct3D12/D3D12UiPass.h/.cpp(namespaceprimal::graphics::d3d12::ui_pass, same functions as Task 3 with D3D12 types); modifyD3D12Core.cpp(after post-process, before the transition to present),Engine.vcxproj+.filters - Modify:
Engine/Platform/PlatformWin32.cpp,Engine/Platform/Window.cpp(Win32 parts of Task 2) - Modify:
GraphicsTests/WindowTests.cpp(Win32 branch of the synthetic events)
Interfaces:
-
Consumes:
UiDrawData,UiPassConstants, the shader ids from Task 3; theWindowEvent/CursorShape/clipboard API from Task 2. -
Win32 mapping:
WM_MOUSEMOVE(+TrackMouseEventforWM_MOUSELEAVE→mouse_left),WM_[LRM]BUTTONDOWN/UP,WM_XBUTTONDOWN/UP,WM_MOUSEWHEEL(/ WHEEL_DELTA),WM_MOUSEHWHEEL,WM_CHAR(UTF-16 surrogate pairs joined, converted to UTF-8),WM_SETFOCUS/WM_KILLFOCUS; cursor viaLoadCursorW+SetCursor(answerWM_SETCURSORwith the current shape in the client area); clipboard viaOpenClipboard/CF_UNICODETEXT;display_scale()=GetDpiForWindow(hwnd) / 96.f. -
Step 1: Write the Win32 branch of Task 2's window tests (
PostMessageWof the messages above; text as twoWM_CHARs for a surrogate pair). -
Step 2: Implement the Win32 platform parts and
d3d12::ui_pass(root signature: two root SRVs + root constants; PSO per back-buffer format; scissor rects;DrawInstanced). -
Step 3: VM —
winvm.sh sync; MSBuild Debug + Release + DebugEditor + ReleaseEditor, 0 warnings; inInvoke-Interactive:GraphicsTests.exe -ts="ui pass"and-tc="window:*"withPRIMAL_GRAPHICS=d3d12(WARP) andvulkan(lavapipe) → pass, validation clean; the wholeGraphicsTestson both. -
Step 4: Linux — clang-tidy with
Tools/WindowsCompileDbon the changed Windows files → 0. -
Step 5: Leave in the working tree.
Task 5: The ImGui backend in EditorUI
Files:
- Create:
Editor/UI/ImGuiBackend.h/.cpp(namespaceprimal::editor::ui::imgui_backend) - Modify:
Editor/UI/CMakeLists.txt,Editor/UI/EditorUI.vcxproj(+.filters) - Test:
UnitTests/EditorUiTests.cpp(no GPU),GraphicsTests/UiPassTests.cpp(with GPU;GraphicsTestslinksEditorUI)
Interfaces:
-
Consumes: Task 2's platform API, Task 3's
UiDrawData,graphics::add_texture()/remove_texture(). -
Produces:
namespace primal::editor::ui::imgui_backend { struct InitInfo { platform::Window window; bool create_textures{true}; }; // false: unit tests without a renderer [[nodiscard]] auto initialize(const InitInfo &info) -> bool; // context, docking on, ini file off for tests auto shutdown() -> void; // removes the engine textures it made auto on_window_event(const platform::WindowEvent &event) -> void; // call from the window's callback auto new_frame(f32 delta_seconds) -> void; // display size + scale from the window, cursor shape [[nodiscard]] auto render() -> const graphics::UiDrawData &; // ImGui::Render() + conversion; valid until the next new_frame() } -
Behaviour:
- Backend flags:
RendererHasVtxOffset,RendererHasTextures,HasMouseCursors. NotPlatformHasViewports(later). - Textures: for each
ImTextureDatainWantCreateorWantUpdates, build an RGBA8 (DXGI_FORMAT_R8G8B8A8_UNORM) engine texture blob in the formatgraphics::add_texture()expects (layout inVulkanContent.cpp'stexture::addcomment) from the whole pixel buffer, add it,SetTexID(new id), remove the previous id (the renderer defers the release),SetStatus(OK);WantDestroy→ remove,SetStatus(Destroyed). A partial update re-creates the whole texture (atlas updates are rare). - Events →
ImGuiIO:AddMousePosEvent(pixels),AddMouseButtonEvent,AddMouseWheelEvent,mouse_left→AddMousePosEvent(-FLT_MAX, -FLT_MAX),AddFocusEvent,AddInputCharactersUTF8,key_down/up→AddKeyEventvia a tableinput::InputCode → ImGuiKey(letters, digits, F1–F12, arrows, navigation, editing keys, modifiers) +ImGuiMod_*frommodifiers. io.WantTextInputedges callstart_text_input()/stop_text_input();ImGui::GetMouseCursor()→set_cursor();io.ConfigFlags |= DockingEnable; clipboard throughImGuiPlatformIO::Platform_SetClipboardTextFn/Platform_GetClipboardTextFn(the get keeps thestd::stringalive until the next call).- Font: ImGui's default font,
style.FontScaleDpi = window.display_scale(). - Conversion: one
UiDrawListperImDrawList, vertices copied into ownedutl::vector<UiVertex>(no reinterpretation ofImDrawVert), indices copied,ImDrawCmd::GetTexID()→texture_id,UserCallbackcommands are not supported (assert).
- Backend flags:
-
Step 1: Write the failing unit tests (suite
editor_ui,create_textures = false, a hidden window is not needed:InitInfo{.window = {}}with display size set through a test hookset_display_size_for_tests(w, h, scale)— add it to the header under a// For tests:comment):"imgui backend: mouse and keys reach ImGuiIO": feedmouse_move(12, 34),mouse_button_down0,key_downInputCode::key_awith ctrl; afternew_frame(1/60.f):io.MousePos == (12, 34),io.MouseDown[0],ImGui::IsKeyDown(ImGuiKey_A),io.KeyCtrl."imgui backend: UTF-8 text": atextevent"é😀"→io.InputQueueCharactersholds U+00E9 and U+1F600."imgui backend: conversion keeps offsets": draw a demo window,render(); for every list the command count, index counts,vertex_offsets and clip rects equal ImGui'sImDrawData; vertex bytes equal (std::memcmpof the 20-byte records)."imgui backend: mouse leave":mouse_left→!ImGui::IsMousePosValid().
-
Step 2: Run
x64/Debug/UnitTests -ts=editor_ui→ fails to compile. -
Step 3: Implement
imgui_backend. -
Step 4: Write the GPU tests in
UiPassTests.cpp:"ui pass: imgui demo"(initialize with a real window, 10 frames ofShowDemoWindow()+ a docking space, render throughSurfaceFrame::ui; validation clean) and"ui pass: imgui texture recreation"(changestyle.FontScaleDpi/ push a new font size each frame for 5 frames so ImGui requests texture updates while frames are in flight; validation clean, no leaked textures at shutdown). -
Step 5: Run both suites on Linux (Debug, Xvfb + desktop) and in the VM (both backends) → pass; tidy, GCC, ASan/UBSan (
-DPRIMAL_ENABLE_SANITIZERS=ON) clean. -
Step 6: Leave in the working tree.
Task 6: EngineTest EDITOR_UI, docs, issue
Files:
- Create:
EngineTest/TestEditorUi.h(the test class, likeTestSurfaces.h) - Modify:
EngineTest/Main.cpp(#elif TEST_EDITOR_UI),EngineTest/CMakeLists.txt(EDITOR_UIin the test list, linksEditorUI),EngineTest.vcxproj(PrimalEngineTest=EDITOR_UI),CMakePresets.json(linux-debug-editor-ui) - Modify:
CLAUDE.md(building/running the variant; state bullet),Docs/Editor.md(step 1 "done" note with findings),Docs/LinuxVulkanPort.mdOpen items A (desktop check of the variant on both backends)
Interfaces:
-
Consumes: everything above.
-
Step 1: Implement the variant: one 1280×720 window, a surface with no camera (like
SURFACES), ImGui with a full-window dock space,ShowDemoWindow()and a small "Primal" window showing the frame time and the backend name;Escor closing the window quits;PRIMAL_TEST_FRAMES=<n>(optional) quits after n frames so scripts can run it. -
Step 2: Run
cmake --preset linux-debug-editor-ui && cmake --build --preset linux-debug-editor-ui, thenPRIMAL_TEST_FRAMES=300 x64/Debug/EngineTest→ exits 0, the log shows no validation messages; ask the user to look at it interactively (typing into the demo's text fields, docking a window, resizing). -
Step 3: VM —
/p:PrimalEngineTest=EDITOR_UI, run withInvoke-GuiProgramon D3D12 and Vulkan, exit 0. -
Step 4: Update the docs and issue #13 (comment: step 1 done in the code, what was checked, the desktop check left as an open item; tick step 1 only after the user's visual check).
-
Step 5: Leave in the working tree.