Plan-2026-11-24-editor-step1-imgui

Chuck Smith edited this page 2026-11-25 01:11:23 +00:00 · 1 commit

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.md apply: trailing return types, const, braces, PRIMAL_API on engine API other binaries call, logging through primal::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 in cmake/PrimalDependencies.cmake and a Editor/UI/ThirdParty.targets for MSBuild (same version and hashes).
  • imgui.h is included only under Editor/UI/. Engine code (Engine/) never includes it.
  • Both build systems: every new source goes in a CMakeLists.txt and 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 in ShaderCompilerTool/ShaderLayoutCheck.cpp's shared_structs.

Review Focus

  1. 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.
  2. More than 65,535 vertices in one list (a large demo window, big tables): vertex_offset per command is honoured (ImGuiBackendFlags_RendererHasVtxOffset), nothing is drawn from the wrong vertices. Test in Task 3 and Task 5.
  3. 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.
  4. 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.
  5. Non-ASCII text input (an IME commit, é, emoji): text arrives as UTF-8 in one text event 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 ImGui v1.93.0-docking source archive, SHA-256 pinned)
  • Create: Editor/CMakeLists.txt, Editor/UI/CMakeLists.txt (static library EditorUI: the ImGui core sources imgui.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, like ContentTools/ThirdParty.targets), add the project to Primal.slnx
  • Create: Editor/UI/ImGuiConfig.h (passed as IMGUI_USER_CONFIG: #define IMGUI_DISABLE_OBSOLETE_FUNCTIONS, IM_ASSERT → the engine's assert)
  • Modify: root CMakeLists.txt (add_subdirectory(Editor)), UnitTests/CMakeLists.txt + UnitTests.vcxproj (link EditorUI)
  • Test: UnitTests/EditorUiTests.cpp (new; in both build files)

Interfaces:

  • Produces: CMake target EditorUI (static, links PrimalEngine), MSBuild project EditorUI.vcxproj producing EditorUI.lib; ImGui headers reachable as <imgui.h> for targets linking EditorUI.

  • Step 1: Write the failing test TEST_CASE("imgui: a frame without a backend") in EditorUiTests.cpp (suite editor_ui): create a context, set io.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-debug fails: imgui.h not 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; full UnitTests passes; ci.sh tidy 0 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 (new WindowEvent types 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::Type gains mouse_move, mouse_button_down, mouse_button_up, mouse_wheel, mouse_left (the pointer left the window), text, focus_gained, focus_lost.
    • WindowEvent gains f32 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_up stay 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 (text events arrive only between them; Win32: no-ops), Window::display_scale() const -> f32 (1.0 at 96 DPI / 100 %), all PRIMAL_API.
  • Step 1: Write the failing tests in WindowTests.cpp (they push synthetic SDL events with SDL_PushEvent on Linux; on Windows PostMessageW — 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; after pump_events(), the callback saw mouse_move with x == 10 * density, y == 20 * density (density = SDL_GetWindowPixelDensity), mouse_button_down/up with button == 0, mouse_wheel with wheel_y == 1.f.
    • "window: text events carry UTF-8": start_text_input(), push an SDL_EVENT_TEXT_INPUT with "é😀"; the callback's text compares equal to "é😀"; after stop_text_input() (and no push) no text event.
    • "window: focus and leave events": push focus gained/lost and mouse leave; the callback sees focus_gained, focus_lost, mouse_left.
    • "window: clipboard round trip": set_clipboard_text("Primal ✓"), CHECK(clipboard_text() == "Primal ✓") (skip with a MESSAGE when the display has no clipboard owner, as under some Xvfb setups: check SDL_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: translate SDL_EVENT_MOUSE_MOTION, _BUTTON_DOWN/_UP, _WHEEL, SDL_EVENT_WINDOW_MOUSE_LEAVE, SDL_EVENT_TEXT_INPUT, SDL_EVENT_WINDOW_FOCUS_GAINED/_LOST into WindowEvents for the event's window (points × SDL_GetWindowPixelDensity = pixels); set_cursor with SDL_CreateSystemCursor (cached per shape) / SDL_HideCursor; clipboard with SDL_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 GraphicsTests under xvfb-run (Debug) and on the desktop session → pass; UnitTests pass; 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 by Renderer.h)
  • Modify: Engine/Graphics/Renderer.h (SurfaceFrame gains const UiDrawData *ui{nullptr}; — drawn after post-process; nullptr = no UI)
  • Create: Engine/Graphics/Shaders/UiPass.hlsl (UiPassVS, UiPassPS)
  • Modify: Engine/Graphics/Shaders/EngineShaders.h (ids ui_pass_vs, ui_pass_ps + rows), Engine/Graphics/Shaders/CommonTypes.hlsli (UiPassConstants), ShaderCompilerTool/ShaderLayoutCheck.cpp (row)
  • Create: Engine/Graphics/Vulkan/VulkanUiPass.h/.cpp (namespace primal::graphics::vulkan::ui_pass); modify VulkanCore.cpp (record_surface() after post-process; constant buffer reservation counts the UI bytes), VulkanCore.cpp's init/shutdown and reload_shaders path (the pipeline is rebuilt like the others), Engine/CMakeLists.txt
  • Test: GraphicsTests/UiPassTests.cpp (new; CMake + GraphicsTests.vcxproj)

Interfaces:

  • Produces (Engine/Graphics/UiDrawData.h, namespace primal::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 until render_frame() returns (it is copied into the frame's GPU memory there).

  • UiPassConstants (HLSL + C++ through SharedTypes.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 a StructuredBuffer<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 samples Texture2D<float4>(ResourceDescriptorHeap[TextureIndex]) with the linear clamp sampler, converts the vertex colour from sRGB to linear, outputs color * texel (linear; the back buffer is linear scRGB or an _SRGB format). Blending: src_alpha, inv_src_alpha for colour; one, inv_src_alpha for alpha. No depth.

  • Recording per command: scissor = clip_rect - display_position, clamped to the surface; skip when empty; Draw(index_count, 1, 0, 0) with IndexOffset/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 with graphics_test::Session and shutdown_and_check(), a white 1×1 texture from TestContent.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 with vertex_offset = 65,536; validation clean.
    • "ui pass: empty and absent": ui == nullptr, lists empty, 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 (UiDrawData unknown).

  • Step 3: Implement the API, the shaders, the table rows and the layout check row. Build → the layout check passes (ShaderCompilerTool runs 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() -> void for reload_shaders(). One pipeline per back-buffer format, created on first use. Recording follows post-process inside record_surface(), before the transition to present, with a vkx::ScopedMarker{cmd, "UI"}.

  • Step 5: Run the new suite and the whole GraphicsTests (Debug, Xvfb + lavapipe and RADV, validation + VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 once) → 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 (namespace primal::graphics::d3d12::ui_pass, same functions as Task 3 with D3D12 types); modify D3D12Core.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; the WindowEvent/CursorShape/clipboard API from Task 2.

  • Win32 mapping: WM_MOUSEMOVE (+ TrackMouseEvent for WM_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 via LoadCursorW + SetCursor (answer WM_SETCURSOR with the current shape in the client area); clipboard via OpenClipboard/CF_UNICODETEXT; display_scale() = GetDpiForWindow(hwnd) / 96.f.

  • Step 1: Write the Win32 branch of Task 2's window tests (PostMessageW of the messages above; text as two WM_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; in Invoke-Interactive: GraphicsTests.exe -ts="ui pass" and -tc="window:*" with PRIMAL_GRAPHICS=d3d12 (WARP) and vulkan (lavapipe) → pass, validation clean; the whole GraphicsTests on both.

  • Step 4: Linux — clang-tidy with Tools/WindowsCompileDb on 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 (namespace primal::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; GraphicsTests links EditorUI)

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. Not PlatformHasViewports (later).
    • Textures: for each ImTextureData in WantCreate or WantUpdates, build an RGBA8 (DXGI_FORMAT_R8G8B8A8_UNORM) engine texture blob in the format graphics::add_texture() expects (layout in VulkanContent.cpp's texture::add comment) 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 → AddKeyEvent via a table input::InputCode → ImGuiKey (letters, digits, F1–F12, arrows, navigation, editing keys, modifiers) + ImGuiMod_* from modifiers.
    • io.WantTextInput edges call start_text_input()/stop_text_input(); ImGui::GetMouseCursor() → set_cursor(); io.ConfigFlags |= DockingEnable; clipboard through ImGuiPlatformIO::Platform_SetClipboardTextFn / Platform_GetClipboardTextFn (the get keeps the std::string alive until the next call).
    • Font: ImGui's default font, style.FontScaleDpi = window.display_scale().
    • Conversion: one UiDrawList per ImDrawList, vertices copied into owned utl::vector<UiVertex> (no reinterpretation of ImDrawVert), indices copied, ImDrawCmd::GetTexID() → texture_id, UserCallback commands are not supported (assert).
  • 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 hook set_display_size_for_tests(w, h, scale) — add it to the header under a // For tests: comment):

    • "imgui backend: mouse and keys reach ImGuiIO": feed mouse_move (12, 34), mouse_button_down 0, key_down InputCode::key_a with ctrl; after new_frame(1/60.f): io.MousePos == (12, 34), io.MouseDown[0], ImGui::IsKeyDown(ImGuiKey_A), io.KeyCtrl.
    • "imgui backend: UTF-8 text": a text event "é😀" → io.InputQueueCharacters holds 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's ImDrawData; vertex bytes equal (std::memcmp of 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 of ShowDemoWindow() + a docking space, render through SurfaceFrame::ui; validation clean) and "ui pass: imgui texture recreation" (change style.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, like TestSurfaces.h)
  • Modify: EngineTest/Main.cpp (#elif TEST_EDITOR_UI), EngineTest/CMakeLists.txt (EDITOR_UI in the test list, links EditorUI), 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.md Open 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; Esc or 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, then PRIMAL_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 with Invoke-GuiProgram on 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.

Pages 19

View all

Clone this repository