Plan-2026-11-24-editor-step3-shell
Editor step 3, the editor shell: 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: The first PrimalEditor program: pick or create a project, see its scenes' structure in an outliner, look
around the active scene with an editor camera over a grid and part markers, and read the log. Read-only.
Architecture: Three layers under Editor/ plus the program: Model/ (no ImGui: project/scene reading with
pugixml, recent projects, new project, editor camera, log view, selection), UI/ (ui::, the only code that includes
imgui.h), Panels/ (outliner, viewport, log, project browser, menu; model + ui:: only), App/ (the main loop,
graphics, the camera entity). Model and Panels build as the static library EditorCore that UnitTests links; the
program is PrimalEditor. The viewport is step 2's offscreen surface; grid and markers are 2D lines the viewport
panel projects with the model's camera and draws through ui::.
Tech Stack: C++23, Dear ImGui 1.93.0-docking (step 1), pugixml 1.16 (new, downloaded), SDL3 3.4 dialogs (Linux),
IFileOpenDialog (Windows), doctest, CMake + Ninja / MSBuild.
Spec: Docs/Editor.md, section 9, "Step 3, the editor shell: design (user, 2026-11-24)" (and sections 5.1, 5.2,
5.5, 5.10). Rules: CLAUDE.md, Docs/Preferences.md.
Global Constraints
- Read-only: no code path writes a
.primalfile or a scene, except creating a new project;ProjectData.xml(the editor's own) may be written. - Panels and Model never include
imgui.h/imgui_internal.h; Model never includesEditor/UIorEditor/Panels(checked byTools/check_layers.py, Task 2). - The editor is not in
PrimalEngine: engine additions are only theplatform::helpers of Task 1 andlog::Category::editor. - Files are the WPF editor's (
DataContractSerializer): element names from the C#DataMembers; namespace prefixes vary (a:,b:), so elements are matched by local name. Rotations in files are Euler angles in degrees (EngineDLL/EntityAPI.cppto_quat(..., true)→math::quat_from_euler(math::to_radians(v))). - The project folder is the
.primalfile's folder, never the XML'sPath. - Old scenes'
GameEntitiesare dropped with one warning per scene (log::warning(log::Category::editor, ...)). - Recent projects:
ProjectData.xml(ProjectDataList/Projects/ProjectDatawithDate,ProjectName,ProjectPath),ProjectPathwith a trailing separator; folder%APPDATA%\PrimalEditor\(Windows),$XDG_CONFIG_HOME/PrimalEditor/else~/.config/PrimalEditor/(Linux). Missing projects stay listed, greyed out. - New project: as
PrimalEditor/GameProject/NewProject.csCreateProject(); templates fromPrimalEditor/Resources/ProjectTemplates/, copied tox64/<Config>/ProjectTemplates/at build time; default location<documents>/PrimalProjects/; refuses empty names, names with<>:"/\|?*or control characters, and an existing non-empty folder. - Viewport shows the active scene only; double-click on a scene node makes it active; F frames the selected actor only when it is in the active scene.
PrimalEditorbuilds in Debug and Release (not the*Editorconfigurations);Editor/Editor.vcxproj+Editor/EditorCore.vcxproj; outputx64/<Config>/PrimalEditor[.exe].- Downloaded third-party code is pinned in both build systems: pugixml 1.16,
https://github.com/zeux/pugixml/releases/download/v1.16/pugixml-1.16.tar.gz, SHA-2564cee1ca4aad395170f4c7a07824f3bdd41f28316c6e1e1090a1425b278ec0b4b. - Project rules: trailing return types,
const, braces, west const, designated initializers,std::expectedfor fallible functions (never.value()),primal::logonly, copyright header// Copyright (c) 2026 Charles Smith- MIT line, no issue numbers in comments,
PRIMAL_APIon new engine exports, 0 warnings (clang, GCC, MSVC/W4 /WX), clang-tidy 0,ci.sh checksgreen. Nevergit commit(the user commits): "Commit" steps below mean "leave in the working tree and record in the ledger".
- MIT line, no issue numbers in comments,
Review Focus
- A project made on Windows opened on Linux (backslashes in
PathandProjectPath, CRLF): opens, folder taken from the file's location. Test in Task 3 (fixture written in the VM) and Task 5. - A
.primalthat isn't a project or is truncated XML: an error message in the log and the browser, no crash, no write. Test in Task 3 (bad_xml,not_a_project). - A scene whose actor names a part guid that doesn't exist (
AttachedTo) or a part cycle: world transforms fall back to the actor's own, no infinite loop. Test in Task 4. - The viewport panel at zero size (collapsed, docked away) and the camera looking straight up/down: no surface resize to 0, no NaN in the projection. Tests in Task 7 (pitch clamp) and Task 10 (zero size request ignored).
- Non-ASCII project names and paths (UTF-8,
ä, spaces): created, listed and opened on both OSes. Test in Task 6.
Task 1: platform helpers and the editor log category
Files:
- Modify:
Engine/Platform/PlatformTypes.h,Engine/Platform/PlatformLinux.cpp,Engine/Platform/PlatformWin32.cpp(blind; VM),Engine/Core/Log.h,Engine/Core/Log.cpp(to_string) - Test:
UnitTests/PlatformTests.cpp(new; add toUnitTests/CMakeLists.txtandUnitTests.vcxproj)
Interfaces:
-
Produces (namespace
primal::platform, allPRIMAL_API):auto documents_folder() -> std::filesystem::path;(LinuxSDL_GetUserFolder(SDL_FOLDER_DOCUMENTS), falling back to$HOME; WindowsSHGetKnownFolderPath(FOLDERID_Documents))auto user_config_folder() -> std::filesystem::path;(Linux$XDG_CONFIG_HOMEif set and absolute, else$HOME/.config; WindowsFOLDERID_RoamingAppData)auto set_hidden(const std::filesystem::path &path) -> void;(WindowsFILE_ATTRIBUTE_HIDDEN; Linux nothing)struct FileFilter { const char *name; const char *pattern; };(pattern"primal",;-separated extensions)using file_dialog_callback = std::function<void(std::optional<std::filesystem::path>)>;auto show_open_file_dialog(Window parent, std::span<const FileFilter> filters, const std::filesystem::path &start, file_dialog_callback callback) -> void;auto show_choose_folder_dialog(Window parent, const std::filesystem::path &start, file_dialog_callback callback) -> void;The callback runs on the main thread insidepump_events()(Linux: SDL calls back on any thread; queue the result and run it inpump_events(); Windows: run the dialog modally and call back before returning).nullopt= cancelled.
-
Produces:
log::Category::editor(beforecount),to_string()→"editor". -
Step 1: Write the failing tests (
TEST_SUITE("platform"))
TEST_CASE("the user's folders are absolute")
{
CHECK(platform::documents_folder().is_absolute());
CHECK(platform::user_config_folder().is_absolute());
}
#if PRIMAL_PLATFORM_LINUX
TEST_CASE("the config folder follows XDG_CONFIG_HOME")
{
// save, set "/tmp/primal-xdg-test", check equality, set "relative/path" -> falls back to $HOME/.config, restore
}
#endif
TEST_CASE("the editor log category has a name")
{
CHECK(log::to_string(log::Category::editor) == "editor");
}
- Step 2: Run, expect a compile failure —
cmake --build --preset linux-debug --target UnitTests:no member named 'documents_folder'. - Step 3: Implement the declarations above (dialogs: SDL
SDL_ShowOpenFileDialog/SDL_ShowOpenFolderDialogwithSDL_DialogFileFilter; the window'sSDL_Window*as parent). - Step 4: Run
x64/Debug/UnitTests -ts=platform→ all pass; fullx64/Debug/UnitTests→ pass. - Step 5: VM —
winvm.sh sync, Debug build,UnitTests.exe -ts=platform→ pass. Dialogs are checked by hand in Task 11 / A61.
Task 2: the editor targets, pugixml, templates and the layer check
Files:
- Create:
Editor/Model/andEditor/Panels/(folders),Editor/EditorCoresources list inEditor/CMakeLists.txt,Editor/App/Main.cpp(a stub that opens a themed window with an empty dockspace and exits afterPRIMAL_EDITOR_FRAMES),Editor/EditorCore.vcxproj(+.filters),Editor/Editor.vcxproj(+.filters),Editor/ThirdParty.targets(pugixml download +CopyProjectTemplates) - Modify:
cmake/PrimalDependencies.cmake(pugixml),Editor/CMakeLists.txt,Primal.slnx(both projects, Debug and Release only),Tools/check_layers.py,UnitTests/CMakeLists.txt+UnitTests.vcxproj(linkEditorCore) - Test:
Tools/test_check_layers.py(new, run fromci.sh checks)
Interfaces:
-
Produces: CMake targets
EditorCore(STATIC;pugixml.cppcompiled into it with warnings off, pugixml's folder a SYSTEM include; linksEditorUI,Engine),PrimalEditor(executable; linksEditorCore,ShaderCompiler; outputx64/<Config>),EditorProjectTemplates(custom target copyingPrimalEditor/Resources/ProjectTemplates/tox64/<Config>/ProjectTemplates/, a dependency ofPrimalEditorandUnitTests). Shaders are compiled at start asEngineTest/TestEditorUi.hdoes (compile_shaders(); the vcxproj compilesEngineDLL/ShaderCompilation.cpplikeEngineTest.vcxproj). -
Produces:
check_layers.pychecksEditor/too, with the table{"Model": {"Engine"}, "UI": {"Engine"}, "Panels": {"Model", "UI", "Engine"}, "App": {"Model", "UI", "Panels", "Engine"}}(an include resolving intoEngine/counts asEngine), plus:imgui.h/imgui_internal.honly fromEditor/UI/,pugixml.hpponly fromEditor/Model/.--graphprints the editor's edges too. -
Step 1: Write the failing test
Tools/test_check_layers.py: copiesTools/check_layers.py's inputs into a temporary repo (Engine/stub +Editor/Model/Bad.hwith#include <imgui.h>,Editor/Panels/Bad.cppwith#include "../App/X.h"), runs the script, asserts exit code 1 and both file names in the output; a clean tree (Editor/Panels/Good.cppincluding"../Model/Y.h"and<imgui.h>-free) exits 0. -
Step 2: Run
python3 Tools/test_check_layers.py→ FAIL (the script ignoresEditor/). -
Step 3: Implement the
check_layers.pychanges; add the test tojob_checksinTools/CI/ci.sh. -
Step 4: Run
python3 Tools/test_check_layers.py→ PASS;python3 Tools/check_layers.py .→ exit 0. -
Step 5: Build targets. Add pugixml,
EditorCore,PrimalEditor, the templates copy. Runcmake --preset linux-debug && cmake --build --preset linux-debug→ 0 warnings;ls x64/Debug/ProjectTemplates/EmptyProject/project.primalexists;PRIMAL_EDITOR_FRAMES=30 x64/Debug/PrimalEditor; echo $?→0, log has no errors, onPRIMAL_GRAPHICS=vulkanwith validation. -
Step 6: VM —
winvm.sh sync; MSBuild the solution Debug and Release → 0 warnings;Invoke-GuiProgram x64\Debug\PrimalEditor.exewithPRIMAL_EDITOR_FRAMES=30on D3D12 and Vulkan → exit 0.
Task 3: reading projects and scenes
Files:
- Create:
Editor/Model/DataContract.h/.cpp(pugixml helpers),Editor/Model/Project.h/.cpp - Create (fixtures):
PrimalEditor.Tests/FixtureWriter.cs(a test that runs only whenPRIMAL_WRITE_FIXTURESnames an output folder),UnitTests/Data/Editor/Fixture/Fixture.primal,UnitTests/Data/Editor/ProjectData.xml,UnitTests/Data/Editor/PlainEntities.primal - Test:
UnitTests/EditorModelTests.cpp(new; both build systems)
Interfaces:
- Produces (
Editor/Model/DataContract.h, namespaceprimal::editor::model::dc):auto child(pugi::xml_node node, std::string_view local_name) -> pugi::xml_node;(first child whose name after the:matches)auto text(pugi::xml_node node, std::string_view local_name) -> std::string_view;class RefTable { public: explicit RefTable(const pugi::xml_document &); auto resolve(pugi::xml_node node) const -> pugi::xml_node; };(resolvereturns the node itself, or the node whosez:Idequals itsz:Ref)auto type_of(pugi::xml_node node) -> std::string_view;(thei:typevalue without prefix)
- Produces (
Editor/Model/Project.h, namespaceprimal::editor::model):
struct Transform { math::v3 position{}; math::v3 rotation_degrees{}; math::v3 scale{1.f, 1.f, 1.f}; };
struct Field { std::string name; std::string value; }; // reflected values as text, for step 4
struct Part { std::string guid; std::string name; std::string class_name; std::string parent_guid; Transform transform; };
struct Behavior { std::string type_name; std::vector<Field> fields; };
struct Actor
{
std::string guid; std::string name; std::string class_name; std::string prefab_name;
bool is_enabled{true}; std::string attached_to; // part guid, empty for none (Guid.Empty is stored as empty)
std::vector<Part> parts; // file order; parts[0] is the root
std::vector<Behavior> behaviors;
};
struct Scene { std::string name; bool is_active{false}; bool adds_default_light{false}; std::vector<Actor> actors; };
struct Project
{
std::string name; std::filesystem::path file; std::filesystem::path folder; std::vector<Scene> scenes;
[[nodiscard]] auto active_scene() -> Scene *; [[nodiscard]] auto active_scene() const -> const Scene *;
auto set_active_scene(u32 index) -> void; // exactly one active
};
enum class LoadError : u8 { missing_file, bad_xml, not_a_project };
[[nodiscard]] auto load_project(const std::filesystem::path &primal_file) -> std::expected<Project, LoadError>;
- Step 1: Make the fixtures.
FixtureWriter.cs(anEditorTest,#nullableon) builds with the FakeEngine types: projectFixture, pathC:\Projects\Fixture\; sceneMain(active): actorShip(test::Ship; default partsHullroot,Turretchild of Hull) with Hull position (1,2,3), rotation (0,90,0), Turret position (0,1,0), behaviortest::Spinwithrate=2.5; actorDrone(actor::Actor) attached to Ship's Turret, root position (0,0,2). SceneOther(inactive, second): actorLamp(actor::Actor). WritesFixture.primalwithSerializer.ToFile, andProjectData.xmlwith two entries (FixtureatC:\Projects\Fixture\,GoneatC:\Projects\Gone\, dates 2026-11-20 and 2026-11-21). Run in the VM:PRIMAL_WRITE_FIXTURES=C:\primal\fixtures PrimalEditor.Tests.exe -method "*FixtureWriter*", copy the files back withwinvm.shintoUnitTests/Data/Editor/.PlainEntities.primal: one scene with twoGameEntitiesand no actors (trim~/Documents/PrimalProject/NewProject/NewProject.primal: keep the structure, drop material blobs). Check none contains a user name or host path (grep -i users). - Step 2: Write the failing tests (
TEST_SUITE("editor model"), data fromPRIMAL_TEST_DATA_DIR "/Editor"):
TEST_CASE("a project written by the WPF editor loads")
{
const auto project{model::load_project(data / "Fixture" / "Fixture.primal")};
REQUIRE(project.has_value());
CHECK(project->name == "Fixture");
CHECK(project->folder == data / "Fixture"); // the file's folder, not the XML's C:\ path
REQUIRE(project->scenes.size() == 2);
CHECK(project->scenes[0].name == "Main"); CHECK(project->scenes[0].is_active);
CHECK_FALSE(project->scenes[1].is_active);
const model::Actor &ship{project->scenes[0].actors[0]};
CHECK(ship.name == "Ship"); CHECK(ship.class_name == "test::Ship");
REQUIRE(ship.parts.size() == 2);
CHECK(ship.parts[0].name == "Hull"); CHECK(ship.parts[0].parent_guid.empty());
CHECK(ship.parts[1].parent_guid == ship.parts[0].guid);
CHECK(ship.parts[0].transform.position.x == doctest::Approx(1.f)); // and y 2, z 3, rotation_degrees.y 90
REQUIRE(ship.behaviors.size() == 1); CHECK(ship.behaviors[0].type_name == "test::Spin");
// a field named "rate" with value "2.5"
const model::Actor &drone{project->scenes[0].actors[1]};
CHECK(drone.attached_to == ship.parts[1].guid);
CHECK(project->scenes[1].actors[0].name == "Lamp");
}
TEST_CASE("plain entities of old scenes are dropped with a warning") // 0 actors, one log warning naming the scene
TEST_CASE("a missing project file is an error") // LoadError::missing_file
TEST_CASE("broken XML is an error") // temp file "<Game><Name>x" -> bad_xml
TEST_CASE("XML that isn't a project is an error") // temp file "<Other/>" -> not_a_project
TEST_CASE("setting the active scene leaves one active")
The warning check reads log::read_recent() after log::flush() (or the test's existing log helper) for a
warning with category editor containing "Main" or the old scene's name.
- Step 3: Run
x64/Debug/UnitTests -ts="editor model"→ compile failure (model::load_projectmissing). - Step 4: Implement
DataContract.*andProject.*. Parts are thePartschildren of anActor; a part's transform is itsComponentschild ofi:typeTransform(Position/Rotation/ScalewithX/Y/Z); itsParentis az:Refresolved to that part'sGuid. Behaviors areBehaviorschildren; fields fromReflectedFieldsComponent'sFields(name and text value as stored). Unknown elements are ignored. - Step 5: Run
x64/Debug/UnitTests -ts="editor model"→ PASS; full UnitTests → PASS.
Task 4: world transforms
Files: Create Editor/Model/WorldTransforms.h/.cpp; Test: UnitTests/EditorModelTests.cpp
Interfaces:
- Consumes:
model::Scene,model::Part,model::Transform(Task 3). - Produces:
struct WorldTransform { math::v3 position{}; math::v4 rotation{0.f, 0.f, 0.f, 1.f}; math::v3 scale{1.f, 1.f, 1.f}; };
// Every part of every actor of the scene, keyed by part guid. Parent chain first, then the actor's AttachedTo part.
[[nodiscard]] auto world_transforms(const Scene &scene) -> std::unordered_map<std::string, WorldTransform>;
Composition as the engine's (math:: functions only): child world = parent world ∘ local (scale, then rotation, then
translation); rotation from math::quat_from_euler(math::to_radians(rotation_degrees)). An unknown parent or
attachment guid, or a cycle, treats the part as a root (logged once per scene, Category::editor, warning).
- Step 1: Failing tests:
TEST_CASE("parts follow their parent and attached actors follow the part")
{ // Fixture.primal, scene Main
// Hull world position (1,2,3); Turret (1,3,3); Drone's root (3,3,3) (Turret yaws 90 degrees: +Z becomes +X)
}
TEST_CASE("an attachment to a missing part leaves the actor where it is") // edit attached_to = "nope" in memory
TEST_CASE("a parent cycle doesn't hang") // two parts naming each other as parent: both get their local transform
- Step 2: Run → FAIL (no
world_transforms). Step 3: Implement. Step 4: Run-ts="editor model"→ PASS.
Task 5: recent projects
Files: Create Editor/Model/RecentProjects.h/.cpp; Test: UnitTests/EditorModelTests.cpp
Interfaces:
struct RecentProject { std::string name; std::filesystem::path folder; std::string date; // as stored (xs:dateTime)
[[nodiscard]] auto primal_file() const -> std::filesystem::path; // folder / (name + ".primal")
[[nodiscard]] auto exists() const -> bool; };
[[nodiscard]] auto editor_settings_folder() -> std::filesystem::path; // platform::user_config_folder() / "PrimalEditor"
[[nodiscard]] auto read_recent_projects(const std::filesystem::path &file) -> std::vector<RecentProject>; // newest first; missing/broken file -> empty + log
auto add_recent_project(const std::filesystem::path &file, const Project &project) -> std::expected<void, SaveError>;
enum class SaveError : u8 { cannot_write };
add_recent_project moves the project to the top with the current local time (std::chrono::zoned_time, format
YYYY-MM-DDTHH:MM:SS.fffffff±hh:mm), keeps the others (also missing ones), writes the WPF layout
(ProjectDataList in namespace http://schemas.datacontract.org/2004/07/PrimalEditor.GameProject, elements in
Date, ProjectName, ProjectPath order), ProjectPath = folder with a trailing separator (\ on Windows, / on
Linux). A folder read from the file has its trailing separator removed and \ converted to the native separator
only when on Linux.
- Step 1: Failing tests: reading the VM's
ProjectData.xmlgivesGonefirst (newest), thenFixture, folder without trailing separator,exists()false for both; adding a project to a copy in a temp folder puts it first, keeps 3 entries, and a second read returns it withprimal_file()equal to the project's file; adding the same project twice keeps one entry; a missing file reads as empty; the written file'sProjectPathends in a separator (string check on the XML). - Step 2: Run → FAIL. Step 3: Implement. Step 4: Run
-ts="editor model"→ PASS.
Task 6: new projects from templates
Files: Create Editor/Model/NewProject.h/.cpp; Test: UnitTests/EditorModelTests.cpp
Interfaces:
struct ProjectTemplate { std::string type; std::filesystem::path folder; std::vector<std::string> folders;
std::filesystem::path icon; std::filesystem::path screenshot; };
[[nodiscard]] auto read_templates(const std::filesystem::path &templates_folder) -> std::vector<ProjectTemplate>; // sorted by type
enum class NewProjectError : u8 { empty_name, invalid_name, folder_not_empty, cannot_write };
[[nodiscard]] auto validate_new_project(std::string_view name, const std::filesystem::path &location) -> std::expected<void, NewProjectError>;
[[nodiscard]] auto create_project(const ProjectTemplate &t, std::string_view name, const std::filesystem::path &location)
-> std::expected<std::filesystem::path, NewProjectError>; // the new .primal file
// C#'s string.Format: {n} -> args[n], {{ -> {, }} -> }
[[nodiscard]] auto format_template(std::string_view text, std::span<const std::string> args) -> std::string;
create_project does what NewProject.cs CreateProject() + CreateMSVCSolution() do: <location>/<name>/, the
template's folders, .Primal/Icon.png + Screenshot.png (platform::set_hidden on .Primal), <name>.primal
from project.primal with {0} = name, {1} = project folder with a trailing separator; <name>.sln from
MSVCSolution with {0} name, {1} a new {GUID} (upper case), {2} another; GameCode/<name>.vcxproj from
MSVCProject with {0} name, {1} the same project GUID as the solution's {1}, {2} $(PRIMAL_ENGINE)Engine\EngineAPI\,
{3} $(PRIMAL_ENGINE). GUIDs from std::random_device.
- Step 1: Failing tests:
format_template("a{0}b{{c}}{1}", {"X","Y"}) == "aXb{c}Y";read_templatesoverx64/<Config>/ProjectTemplates(path from a test define likePRIMAL_TEST_DATA_DIR) returns 4 with non-empty folders; validation:""→empty_name,"a/b","a:b","a\x01"→invalid_name, a non-empty existing folder →folder_not_empty; creating"Spiel ä 1"in a temp folder makes the.primalfile,load_project()of it succeeds with name"Spiel ä 1"and one active sceneDefault Scene; the.slnand.vcxprojexist and contain the same project GUID; no{0}left in any written file. Temp folders are removed at the end. - Step 2: Run → FAIL. Step 3: Implement. Step 4: Run
-ts="editor model"→ PASS.
Task 7: the editor camera and the view math
Files: Create Editor/Model/EditorCamera.h/.cpp, Editor/Model/ViewMath.h/.cpp; Test: UnitTests/EditorModelTests.cpp
Interfaces:
struct EditorCamera
{
math::v3 focus{0.f, 0.f, 0.f}; f32 yaw{0.f}; f32 pitch{-0.35f}; f32 distance{10.f}; // radians; pitch up is positive
f32 fly_speed{5.f}; f32 field_of_view{0.25f}; f32 near_z{0.1f}; f32 far_z{1000.f}; // fov as a fraction of pi
[[nodiscard]] auto front() const -> math::v3; // (sin yaw cos pitch, sin pitch, cos yaw cos pitch)
[[nodiscard]] auto position() const -> math::v3; // focus - front * distance
[[nodiscard]] auto rotation() const -> math::v4; // math::quat_from_euler({-pitch, yaw, 0}): rotates +Z to front()
auto orbit(f32 delta_yaw, f32 delta_pitch) -> void; // around focus; pitch clamped to +-(pi/2 - 0.01)
auto look(f32 delta_yaw, f32 delta_pitch) -> void; // in place: position fixed, focus moves
auto pan(f32 right, f32 up) -> void; // world units along the camera's right and up
auto zoom(f32 steps) -> void; // distance *= 0.9^steps, clamped to [0.05, 10000]
auto fly(math::v3 move, f32 seconds) -> void; // move: x right, y up, z forward; speed fly_speed
auto frame(math::v3 center, f32 radius) -> void; // focus = center, distance = max(1, 1.1 * radius / sin(fov * pi / 2))
[[nodiscard]] auto view_projection(f32 aspect_ratio) const -> math::m4x4; // as Engine/Graphics/Camera.cpp: look_to_rh(position, front, {0,1,0}) * perspective_fov_rh(fov * pi, aspect, far, near)
};
// ViewMath.h
[[nodiscard]] auto project_point(const math::m4x4 &view_projection, math::v3 world, math::v2 size) -> std::optional<math::v2>; // nullopt when w <= 1e-4
[[nodiscard]] auto project_line(const math::m4x4 &view_projection, math::v3 a, math::v3 b, math::v2 size)
-> std::optional<std::array<math::v2, 2>>; // clipped to w >= 1e-4; nullopt when wholly behind
Screen space: pixels from the top-left, y down.
- Step 1: Failing tests:
rotate3({0,0,1}, rotation())equalsfront()(1e-5) for yaw/pitch in {(0,0), (1,0.3), (-2,-1.2)};position()isdistancefromfocus;orbit(0, 10)leaves pitch atpi/2 - 0.01andfront()finite;zoom(1)from 10 gives 9;zoom(-1000)gives 10000;frame({1,2,3}, 1)puts focus at (1,2,3);fly({0,0,1}, 1)moves position by 5 along front and keeps distance;project_pointoffocuslands at the centre of an 800x600 view (0.5 px); a point behind the camera isnullopt; a line from in front to behind the camera returns its visible endpoint unchanged and a finite clipped one; a line wholly behind isnullopt. - Step 2: Run → FAIL. Step 3: Implement. Step 4: Run
-ts="editor model"→ PASS.
Task 8: the log view and the editor state
Files: Create Editor/Model/LogView.h/.cpp, Editor/Model/EditorState.h; Test: UnitTests/EditorModelTests.cpp
Interfaces:
struct LogFilter { std::array<bool, 4> levels{true, true, true, true}; // indexed by log::Level
std::array<bool, std::to_underlying(log::Category::count)> categories; // all true by default
std::string text; }; // case-insensitive substring; empty = all
class LogView
{
public:
static constexpr u32 capacity{10'000};
auto update() -> u32; // reads log::read_recent(); returns the number of new messages
auto clear() -> void; // forgets what it has; older messages never come back
[[nodiscard]] auto messages() const -> std::span<const log::StoredMessage>;
[[nodiscard]] auto visible(const LogFilter &filter) const -> std::vector<u32>; // indices into messages()
};
struct ViewportState { graphics::Surface surface{}; math::u32v2 wanted_size{}; bool is_hovered{false}; };
struct EditorState
{
std::optional<Project> project;
std::string selected_actor; // actor guid; empty for none
EditorCamera camera;
LogView log; LogFilter log_filter; bool log_follows_end{true};
ViewportState viewport;
std::filesystem::path recent_projects_file; std::filesystem::path templates_folder;
bool show_project_browser{true};
std::string status; // the last error to show (browser / status bar)
};
auto open_project(EditorState &state, const std::filesystem::path &primal_file) -> bool; // load, select nothing,
// frame the active scene's parts (or default camera), add to recent projects; on error sets status + logs
- Step 1: Failing tests: after
log::info(log::Category::editor, "view test {}", 1)and the log's flush,update()returns ≥ 1 and the last message's text is"view test 1"; a filter withlevels[info] = falsehides it; text"VIEW TEST"keeps it,"nothing"hides it;clear()emptiesmessages()and a laterupdate()brings only newer messages; pushingcapacity + 10messages keepscapacity.open_projecton the fixture setsproject, clears selection, points the camera's focus at the active scene's parts' centre; onPlainEntities.primalit opens with no actors; on a missing file it returns false,projectstays empty andstatusis non-empty. The recent file is a temp path. - Step 2: Run → FAIL. Step 3: Implement. Step 4: Run
-ts="editor model"→ PASS.
Task 9: panels: log and outliner, and the headless smoke test
Files:
- Create:
Editor/UI/Widgets.h/.cpp(theui::functions the panels need: panel begin/end, tree nodes with selected/leaf/double-click, text, coloured and disabled text, check boxes, text input intostd::string, buttons, same line, child regions with scrolling, menu bar items, modal popups, tables,draw_line()on the current panel, item and mouse/keyboard queries,image(graphics::Surface, math::v2), dockspace + default layout); add toEditorUI(CMake + vcxproj) - Create:
Editor/Panels/LogPanel.h/.cpp,Editor/Panels/Outliner.h/.cpp,Editor/Panels/EditorUi.h/.cpp,Editor/Panels/Registry.h/.cpp - Test:
UnitTests/EditorPanelTests.cpp(new; both build systems)
Interfaces:
- Consumes:
EditorState(Task 8),imgui_backend(step 1/2). - Produces (
Editor/Panels/Registry.h, namespaceprimal::editor::panels):
using panel_function = void (*)(EditorState &);
struct PanelInfo { const char *title; const char *icon; panel_function draw; bool open_by_default{true}; };
struct MenuItem { const char *path; panel_function run; }; // "File/Open...": menu "File", item "Open..."
auto register_panel(const PanelInfo &info) -> void; // a title registered twice: error logged, first stays
auto register_menu_item(const MenuItem &item) -> void;
[[nodiscard]] auto registered_panels() -> std::span<const PanelInfo>;
auto register_editor_panels() -> void; // the editor's own: Outliner, Viewport, Log, menus
draw_editor_ui() draws the menu bar from the registered items (in registration order, grouped by menu) and every
registered panel (the "Window" menu toggles them); it names no panel. Our panels register through
register_editor_panels(), the path a user's panels will take later.
-
Produces:
auto draw_log_panel(EditorState &) -> void;,auto draw_outliner(EditorState &) -> void;,auto draw_editor_ui(EditorState &) -> void;(main menu, dockspace, every registered panel; the program calls only this). Panel titles (the dock layout and tests use them):"Outliner","Viewport","Log","Projects". Outliner: one node per scene (label = name, the active one open by default and marked), actor nodes with their part trees (part name, class in grey), clicking an actor (or one of its parts) setsselected_actor, double-clicking a scene callsproject->set_active_scene(). Log panel: level toggles (icons), category menu, text filter, Clear, follow-the-end; rows coloured by level (warning_colorfor warnings). -
Step 0: Failing tests for the registry: after
register_editor_panels(),registered_panels()holds"Outliner","Viewport","Log"; registering a test panel"Test panel"makesdraw_editor_ui()call its function once per frame; registering"Log"again logs an error and keeps one"Log"; a test menu item"Test/Run"is called when activated through the widgets' test hook (or, if ImGui can't click headless, check that it appears in the built menu modelmenu_items_of("Test")). Run → compile failure. -
Step 1: Failing test
TEST_CASE("every panel draws over the fixture project"): initialiseimgui_backendwith{.create_textures = false},set_display_size_for_tests(1280, 720, 1),open_projecton the fixture (temp recent file), then 3 frames ofnew_frame(1/60),draw_editor_ui(state),render(); then selectShipviastate.selected_actorand 1 more frame;CHECKno ImGui assert fired (the backend's assert hook, asUnitTests/EditorUiTests.cppdoes) and thatrender()produced at least one draw list. A second case draws with no project open (browser only). -
Step 2: Run
x64/Debug/UnitTests -ts="editor panels"→ compile failure. -
Step 3: Implement the widgets, both panels and
draw_editor_ui(viewport and browser panels as empty stubs until Tasks 10-11). -
Step 4: Run
-ts="editor panels"→ PASS;python3 Tools/check_layers.py .→ exit 0.
Task 10: the viewport panel
(Registered by register_editor_panels() as "Viewport"; Task 11's File menu items through register_menu_item.)
Files: Create Editor/Panels/Viewport.h/.cpp; Modify Editor/Panels/EditorUi.cpp; Test: UnitTests/EditorPanelTests.cpp
Interfaces:
-
Consumes:
EditorCamera,project_line,world_transforms,ViewportState. -
Produces:
auto draw_viewport(EditorState &) -> void;It setsstate.viewport.wanted_sizeto the panel's content size in pixels (never 0: a 0 size leaves the last wanted size), showsstate.viewport.surfacewithui::image, then draws on top: the ground grid (y = 0, lines every 1 unit from -50 to 50, every 10th brighter, the X axis red and Z axis blue through the origin) and, for each part of the active scene, its world axes (0.5 units; X red, Y green, Z blue), the selected actor's parts thicker and in the theme accent. Camera input only while the image is hovered or a drag started on it: Alt + left drag or middle drag orbits (0.005 rad per pixel), Shift + middle drag pans (distance * 0.0015 per pixel), wheel zooms (one step per notch) or, while right-dragging, multipliesfly_speedby 1.2 per notch, right drag looks (0.004 rad per pixel) and WASD/QE fly (Shift x3), F frames the selected actor when it is in the active scene (centre and radius from its parts' world positions, radius ≥ 0.5). -
Produces (testable helper):
auto viewport_lines(const EditorState &, math::v2 size) -> std::vector<ViewportLine>;withstruct ViewportLine { math::v2 a; math::v2 b; u32 color; f32 thickness; };(whatdraw_viewportdraws). -
Step 1: Failing tests: with the fixture open and the camera framed on
Ship,viewport_lines(state, {800, 600})is non-empty, every point is finite; the selected actor's lines have the larger thickness; with the camera inside looking straight down (pitch = -pi/2, clamped) the lines are still finite; selectingLamp(sceneOther) and pressing F leaves the camera unchanged (call the F handler functionframe_selected(state)→ returns false); a frame drawn at a 0-size panel leaveswanted_sizeunchanged. -
Step 2: Run → FAIL. Step 3: Implement. Step 4: Run
-ts="editor panels"→ PASS.
Task 11: the project browser
Files: Create Editor/Panels/ProjectBrowser.h/.cpp; Modify Editor/Panels/EditorUi.cpp; Test: UnitTests/EditorPanelTests.cpp
Interfaces:
-
Produces:
auto draw_project_browser(EditorState &, platform::Window window) -> void;A centred modal"Projects"whileshow_project_browser(shown at start and from File > Open… / New…; closable only when a project is open) with two tabs. Open: the recent list (name, folder, date; missing ones greyed and not openable), Open on double-click or button, and "Browse…" (platform::show_open_file_dialogwith filter{"Primal project", "primal"}). New: template list (icon and screenshot as textures are step 5: show the type names), name, location (text + "…" →show_choose_folder_dialog), the validation message live (validate_new_project), Create →create_projectthenopen_project. File menu: Open…, New…, Exit (platform::post_quit). -
Dialog callbacks only store the chosen path into
EditorState(apending_open/pending_locationfield added toEditorState); the next frame acts on it. -
Step 1: Failing tests: with a recent file listing the fixture and
Gone, a browser frame draws without asserts; settingstate.pending_opento the fixture's file and drawing one frame opens it and hides the browser; setting it to a missing file keeps the browser and setsstatus; a frame with the New tab's name"a/b"shows the invalid-name message (check via a returnedBrowserFramevalue:auto draw_project_browser(...) -> BrowserFramewithstd::optional<NewProjectError> validation). -
Step 2: Run → FAIL. Step 3: Implement. Step 4: Run
-ts="editor panels"→ PASS.
Task 12: the program, the dock layout, runs on both OSes, docs
Files: Modify Editor/App/Main.cpp; Create Editor/App/EditorApp.h/.cpp; Modify UnitTests/CMakeLists.txt
(CTest editor_program, label graphics), Tools/CI/ci.sh if needed, .forgejo/workflows/windows.yml (run
PrimalEditor.exe with a frame limit like the EngineTest variants), CLAUDE.md, Docs/Editor.md,
Docs/LinuxVulkanPort.md (A61), issue #13 (comment).
Interfaces:
-
Consumes: everything above.
-
Produces the loop of
Docs/Editor.md5.2:platform::pump_events()→imgui_backend::new_frame(dt)→draw_editor_ui(state)(+draw_project_browser) → resize the viewport surface towanted_sizewhen it differs (Surface::resize()) → write the camera entity'stransform::Position/Rotationandrender::Camera(aspect_ratio,field_of_view,near_z,far_z) fromstate.camera→logupdate →graphics::scene::prepare()→graphics::render_frame({viewport frame with camera_entity, window frame with the UI}). The camera entity is a plain entity ingame_entity::world()(created aftergraphics::initialize, removed before shutdown). Window caption"<project> - Primal Editor". ImGui's settings file iseditor_settings_folder() / "imgui.ini"; with no file the default layout is built (Outliner left 20%, Log bottom 25%, Viewport centre). Display scale:apply_theme(scale)at start and on the window's scale-change event. Environment:PRIMAL_EDITOR_FRAMES=<n>stops after n frames;PRIMAL_EDITOR_PROJECT=<file>opens it at start (browser hidden). -
Step 1: Add the CTest
editor_program: runsPrimalEditorwithPRIMAL_EDITOR_FRAMES=60andPRIMAL_EDITOR_PROJECT=<fixture>and fails on a non-zero exit or a logerrorline (validation errors are errors). Runctest --test-dir build/linux-debug -R editor_program→ FAIL (the stub doesn't open projects). -
Step 2: Implement
EditorApp. -
Step 3: Run
ctest --test-dir build/linux-debug -R editor_program→ PASS on Vulkan; again withPRIMAL_GRAPHICS=vulkan PRIMAL_VULKAN_VALIDATION=1andVK_KHRONOS_VALIDATIONsync validation → no validation messages. -
Step 4: Full Linux verification:
cmake --build --preset linux-debugandlinux-release,linux-gcc-debug(0 warnings);Tools/CI/ci.sh checks;Tools/CI/ci.sh tidy; Windows-database tidy over the new files; sanitizers (ci.sh sanitizers);x64/Debug/UnitTestsall pass;x64/Debug/GraphicsTestsall pass;header_checktarget. -
Step 5: VM:
winvm.sh sync; MSBuild Debug, Release, DebugEditor, ReleaseEditor → 0 warnings;UnitTests.exe -ts="editor*"and-ts=platformpass;PrimalEditor.exewith the two variables on D3D12 and Vulkan → exit 0, log clean;winvm.sh screenshotof a run without the frame limit shows the docked layout; the file dialogs open (driven by hand or byInvoke-Interactive+ a screenshot).winvm.sh shutdown. -
Step 6: Docs:
CLAUDE.mdcurrent state (step 3 done, uncommitted, plan doc A61);Docs/Editor.md"Step 3 done" with what was built, rulings and known limits; plan doc A61 for the desktop (both OSes: open a real project, orbit/pan/zoom/fly, F, the dialogs incl. the XDG portal on KDE/GNOME, the look, creating a project and opening it in the WPF editor on Windows); a progress comment on #13 (no personal paths).