From 18c072d5a136aa7dcc616bc288b8abacef176a9d Mon Sep 17 00:00:00 2001 From: kindem Date: Sun, 15 Nov 2026 14:53:11 +0800 Subject: [PATCH 1/4] docs: add shared agent guidelines --- .gitignore | 4 ++-- AGENTS.md | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 AGENTS.md diff --git a/.gitignore b/.gitignore index 30a1b6063..fa5ddf84a 100644 --- a/.gitignore +++ b/.gitignore @@ -20,9 +20,9 @@ ThirdParty/ConanRecipes/**/CMakeUserPresets.json !ThirdParty/ConanRecipes/build_recipes.py aqtinstall.log -# Agents +# Local agent settings CLAUDE.md -AGENTS.md +/AGENTS.local.md # Test Project (generated from the editor's Default project template by CI / tooling) /TestProject diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..f523e2157 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,38 @@ +# Explosion + +Before starting any work, agents must read `AGENTS.local.md` at the repository root if it exists. + +## Code + +- Prioritize sound abstractions and a single source of truth over a minimal diff. +- Prefer clear names and small functions; comment only when intent cannot be expressed in code. +- Code has no line-length limit; wrap only for readability. Wrap comments at about 120 characters with roughly even lines. +- In headers, declare the complete interface first, then put out-of-line definitions in a second namespace block. + Do not put function bodies inside class definitions. Put helper types in `Common::Internal`. +- Repeat class template-heads on out-of-line definitions; add a second template-head for member templates. +- In `.cpp` files, put translation-unit-local helpers in named `Xxx::Internal` namespaces and mark functions `static` + to avoid unity-build ODR collisions. Namespace-scope `const`/`constexpr` variables need no `static`. +- Reference header layouts: `Delegate.h`, `Utility.h`, and `Result.h` in `Engine/Source/Common/Include/Common/`. + +## CMake + +- Keep global toolchain/compile settings in `CMake/Common.cmake` and target helpers in `CMake/Target.cmake`. +- Create targets through `exp_add_library`, `exp_add_executable`, `exp_add_test`, or `exp_add_benchmark`. + Extend helpers instead of appending ad hoc `target_*` calls to their targets. +- Helpers are lower_snake_case `exp_*` functions using `cmake_parse_arguments(arg ...)`; read values as `arg_`. +- Keywords are UPPER_SNAKE_CASE; use `PRIVATE_*` / `PUBLIC_*` pairs for include/link/lib/compile-option inputs. +- Project options and cache variables are UPPER_SNAKE_CASE. Ordinary/local variables, including compiler-flag check + results, are lower_snake_case without `EXP`/`EXP_` prefixes. +- Define platform/compiler flags as unprefixed 0/1 macros via `add_compile_definitions` in `Common.cmake`, + e.g. `PLATFORM_WINDOWS` and `COMPILER_MSVC`. + +## Build + +- Default to Debug in `cmake-build-debug` with Ninja. Use `cmake-build-` for other configurations when needed. +- Build incrementally; do not clear build directories or the Conan cache without a concrete reason. +- Never run concurrent configure/Conan processes against the same Conan cache. +- Keep machine-specific tool paths and parallelism in the ignored `AGENTS.local.md`. + +## Git + +- Commit subjects use `type: description` without a parenthesized scope, e.g. `fix: ...` or `refactor: ...`. From b8a060f916e998dfdafbc42d7fee9862b1458217 Mon Sep 17 00:00:00 2001 From: kindem Date: Sun, 15 Nov 2026 15:24:16 +0800 Subject: [PATCH 2/4] refactor: separate editor backends and project hub services --- Editor/CMakeLists.txt | 4 +- Editor/Include/Editor/EditorApplication.h | 17 +- Editor/Include/Editor/EditorWindow.h | 69 +-- Editor/Include/Editor/Frame/ProjectHubFrame.h | 56 +-- Editor/Include/Editor/ImGui/ImGuiDrawData.h | 23 + .../Editor/ImGui/ImGuiPlatformBackend.h | 27 ++ .../Include/Editor/ImGui/ImGuiRhiRenderer.h | 72 +++ .../Include/Editor/Project/ProjectLauncher.h | 31 ++ .../Include/Editor/Project/ProjectService.h | 32 ++ .../Editor/Project/RecentProjectStore.h | 27 ++ Editor/Src/EditorApplication.cpp | 151 ++---- Editor/Src/EditorWindow.cpp | 457 ++---------------- Editor/Src/Frame/ProjectHubFrame.cpp | 205 +++----- Editor/Src/ImGui/ImGuiDrawData.cpp | 39 ++ Editor/Src/ImGui/ImGuiPlatformBackend.cpp | 71 +++ Editor/Src/ImGui/ImGuiRhiRenderer.cpp | 413 ++++++++++++++++ Editor/Src/Project/ProjectLauncher.cpp | 21 + Editor/Src/Project/ProjectService.cpp | 122 +++++ Editor/Src/Project/RecentProjectStore.cpp | 84 ++++ Editor/Src/SceneClient.cpp | 4 +- Editor/Test/ImGuiDrawDataTest.cpp | 67 +++ Editor/Test/ProjectTest.cpp | 169 +++++++ Engine/Source/Common/Include/Common/Process.h | 3 + Engine/Source/Common/Src/Process.cpp | 91 +++- 24 files changed, 1442 insertions(+), 813 deletions(-) create mode 100644 Editor/Include/Editor/ImGui/ImGuiDrawData.h create mode 100644 Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h create mode 100644 Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h create mode 100644 Editor/Include/Editor/Project/ProjectLauncher.h create mode 100644 Editor/Include/Editor/Project/ProjectService.h create mode 100644 Editor/Include/Editor/Project/RecentProjectStore.h create mode 100644 Editor/Src/ImGui/ImGuiDrawData.cpp create mode 100644 Editor/Src/ImGui/ImGuiPlatformBackend.cpp create mode 100644 Editor/Src/ImGui/ImGuiRhiRenderer.cpp create mode 100644 Editor/Src/Project/ProjectLauncher.cpp create mode 100644 Editor/Src/Project/ProjectService.cpp create mode 100644 Editor/Src/Project/RecentProjectStore.cpp create mode 100644 Editor/Test/ImGuiDrawDataTest.cpp create mode 100644 Editor/Test/ProjectTest.cpp diff --git a/Editor/CMakeLists.txt b/Editor/CMakeLists.txt index ba710a82a..5b0a190d5 100644 --- a/Editor/CMakeLists.txt +++ b/Editor/CMakeLists.txt @@ -20,9 +20,11 @@ exp_add_executable( ) file(GLOB editor_test_sources Test/*.cpp) +file(GLOB editor_project_sources Src/Project/*.cpp) exp_add_test( NAME Editor.Test - SRC ${editor_test_sources} Src/Asset/AssetFileSystem.cpp + SRC ${editor_test_sources} Src/Asset/AssetFileSystem.cpp ${editor_project_sources} Src/ImGui/ImGuiDrawData.cpp + LIB imgui::imgui INC Include ) diff --git a/Editor/Include/Editor/EditorApplication.h b/Editor/Include/Editor/EditorApplication.h index 947acc765..afc70ffed 100644 --- a/Editor/Include/Editor/EditorApplication.h +++ b/Editor/Include/Editor/EditorApplication.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include namespace Editor { @@ -39,22 +41,23 @@ namespace Editor { void InitializeImGui(); void ShutdownImGui(); void InstallCallbacks(); - void BeginImGuiFrame(float inDeltaSeconds) const; void DrawDockSpace() const; - void RenderEditorFrame(float inDeltaSeconds); - void RenderProjectHubFrame(); - void HandleKey(int inKey, int inScancode, int inAction, int inMods); - void HandleChar(uint32_t inCodepoint) const; - void HandleMouseButton(int inButton, int inAction, int inMods); + void RenderEditorFrame(); + void HandleKey(int inKey, int inAction); + void HandleMouseButton(int inButton, int inAction); void HandleCursor(double inX, double inY); - void HandleScroll(double inXOffset, double inYOffset) const; float NextDeltaSeconds(); EditorApplicationDesc desc; std::string imguiIniFilename; Common::UniquePtr window; + Common::UniquePtr imguiPlatform; + Common::UniquePtr imguiRenderer; Common::UniquePtr context; Common::UniquePtr sceneRenderCanvas; + Common::UniquePtr projectService; + Common::UniquePtr recentProjects; + Common::UniquePtr projectLauncher; Common::UniquePtr projectHubFrame; EditorFrame editorFrame; double lastFrameSeconds; diff --git a/Editor/Include/Editor/EditorWindow.h b/Editor/Include/Editor/EditorWindow.h index 623a700d3..8658c917f 100644 --- a/Editor/Include/Editor/EditorWindow.h +++ b/Editor/Include/Editor/EditorWindow.h @@ -1,22 +1,15 @@ -// -// Created by johnk on 2026/7/7. -// - #pragma once -#include #include -#include -#include -#include -#include -#include -#include +#include #include struct GLFWwindow; -struct ImDrawData; + +namespace Render { + class RenderThread; +} namespace Editor { struct EditorWindowDesc { @@ -28,7 +21,7 @@ namespace Editor { class EditorWindow final : public Runtime::Window { public: - explicit EditorWindow(const EditorWindowDesc& inDesc); + EditorWindow(RHI::Device& inDevice, Render::RenderThread& inRenderThread, const EditorWindowDesc& inDesc); ~EditorWindow() override; NonCopyable(EditorWindow) @@ -43,56 +36,24 @@ namespace Editor { void RequestClose() const; void PollEvents() const; void SetTitle(const std::string& inTitle) const; - void SetDrawData(ImDrawData* inDrawData); + void SetCursorCaptured(bool inCaptured) const; void RecreateSwapChainIfNeeded(); void WaitRenderingIdle() const; - void RenderPendingUi(); - void RenderUiOnly(ImDrawData& inDrawData); + Common::Delegate onKey; + Common::Delegate onChar; + Common::Delegate onMouseButton; + Common::Delegate onCursor; + Common::Delegate onScroll; + Common::Delegate onFocus; private: - struct ImGuiPassParams { - Common::FVec2 displayPos; - Common::FVec2 displaySize; - }; - + void InstallCallbacks(); void* GetPlatformWindow() const; - void RenderUiPass(ImDrawData* inDrawData, RHI::LoadOp inLoadOp, const Common::LinearColor& inClearValue); - void RenderImGuiDrawData(ImDrawData& inDrawData, RHI::RasterPassCommandRecorder& inRecorder); - void CreateImGuiDeviceObjects(); - void CreateImGuiFontTexture(); - void CreateImGuiDynamicBuffers(int inVertexCount, int inIndexCount); - void UpdateImGuiBuffers(ImDrawData& inDrawData); - void UpdateImGuiPassParams(const ImDrawData& inDrawData); - RHI::BindGroup* GetOrCreateImGuiTextureBindGroup(RHI::TextureView& inTextureView); - ImDrawData* TakeDrawData(); - static void DestroyDrawData(ImDrawData* inDrawData); + Render::RenderThread& renderThread; GLFWwindow* window; - Common::UniquePtr uiFrameFence; - Common::UniquePtr uiCommandBuffer; - Render::ShaderCompileOutput imguiVertexShaderCompileOutput; - Render::ShaderCompileOutput imguiPixelShaderCompileOutput; - Common::UniquePtr imguiVertexShader; - Common::UniquePtr imguiPixelShader; - Common::UniquePtr imguiBindGroupLayout; - Common::UniquePtr imguiPipelineLayout; - Common::UniquePtr imguiPipeline; - Common::UniquePtr imguiFontTexture; - Common::UniquePtr imguiFontTextureView; - Common::UniquePtr imguiImageSampler; - Common::UniquePtr imguiPassParamsBuffer; - Common::UniquePtr imguiPassParamsBufferView; - std::unordered_map> imguiFrameTextureBindGroups; - Common::UniquePtr imguiVertexBuffer; - Common::UniquePtr imguiVertexBufferView; - Common::UniquePtr imguiIndexBuffer; - Common::UniquePtr imguiIndexBufferView; - int imguiVertexBufferCapacity; - int imguiIndexBufferCapacity; uint32_t framebufferWidth; uint32_t framebufferHeight; - mutable std::mutex drawDataMutex; - ImDrawData* pendingDrawData; }; } diff --git a/Editor/Include/Editor/Frame/ProjectHubFrame.h b/Editor/Include/Editor/Frame/ProjectHubFrame.h index 71f24b60e..425d45f3b 100644 --- a/Editor/Include/Editor/Frame/ProjectHubFrame.h +++ b/Editor/Include/Editor/Frame/ProjectHubFrame.h @@ -1,62 +1,34 @@ -// -// Created by johnk on 2026/7/8. -// - #pragma once #include #include -#include -#include +#include +#include +#include namespace Editor { - struct EClass() RecentProjectInfo { - EClassBody(RecentProjectInfo) - - EProperty() std::string name; - EProperty() std::string path; - }; - - struct EClass() ProjectTemplateInfo { - EClassBody(ProjectTemplateInfo) - - EProperty() std::string name; - EProperty() std::string path; - }; - - struct EClass() CreateProjectResult { - EClassBody(CreateProjectResult) - - EProperty() bool success; - EProperty() std::string error; - EProperty() std::string projectPath; - }; - - class EditorWindow; - class ProjectHubFrame final { public: - ProjectHubFrame(); + ProjectHubFrame(ProjectService& inProjectService, RecentProjectStore& inRecentProjects, ProjectLauncher& inProjectLauncher); ~ProjectHubFrame(); - void Render(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu); + bool Render(); private: - void RenderActionBar(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu); - void RenderRecentProjects(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu); - void RenderCreateProjectPopup(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu); - CreateProjectResult CreateProject(); - void OpenProject(EditorWindow& inWindow, const std::string& inProjectPath, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu); - void SaveRecentProjects() const; - void TouchRecentProject(const std::string& inProjectPath); - - Common::Path recentProjectsFile; + void RenderActionBar(); + void RenderRecentProjects(); + void RenderCreateProjectPopup(); + void OpenProject(const Common::Path& inProjectPath); + + ProjectService& projectService; + RecentProjectStore& recentProjects; + ProjectLauncher& projectLauncher; std::vector projectTemplates; - std::vector recentProjects; std::string projectName; std::string directory; int selectedTemplateIndex; std::string statusMessage; + bool requestClose; }; } diff --git a/Editor/Include/Editor/ImGui/ImGuiDrawData.h b/Editor/Include/Editor/ImGui/ImGuiDrawData.h new file mode 100644 index 000000000..a3cab4f9b --- /dev/null +++ b/Editor/Include/Editor/ImGui/ImGuiDrawData.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +#include + +namespace Editor { + // Owns draw buffers and copied callback payloads, resolving ImGui texture references before queueing. Texture + // views and external callback data are borrowed; their owners must drain rendering before releasing them. + class ImGuiDrawData final { + public: + explicit ImGuiDrawData(const ImDrawData& inDrawData); + ~ImGuiDrawData(); + + NonCopyable(ImGuiDrawData) + NonMovable(ImGuiDrawData) + + ImDrawData& Get(); + + private: + ImDrawData drawData; + }; +} diff --git a/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h b/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h new file mode 100644 index 000000000..9d2e95d6d --- /dev/null +++ b/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace Editor { + class EditorWindow; + + class ImGuiPlatformBackend final { + public: + explicit ImGuiPlatformBackend(EditorWindow& inWindow); + ~ImGuiPlatformBackend(); + + NonCopyable(ImGuiPlatformBackend) + NonMovable(ImGuiPlatformBackend) + + void NewFrame(float inDeltaSeconds) const; + + private: + EditorWindow& window; + Common::CallbackHandle keyHandle; + Common::CallbackHandle charHandle; + Common::CallbackHandle mouseButtonHandle; + Common::CallbackHandle cursorHandle; + Common::CallbackHandle scrollHandle; + Common::CallbackHandle focusHandle; + }; +} diff --git a/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h b/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h new file mode 100644 index 000000000..9639874bf --- /dev/null +++ b/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h @@ -0,0 +1,72 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +struct ImDrawData; + +namespace Common::Internal { + struct ImGuiPassParams { + Common::FVec2 displayPos; + Common::FVec2 displaySize; + }; +} + +namespace Editor { + class ImGuiDrawData; + + class ImGuiRhiRenderer final { + public: + ImGuiRhiRenderer(Runtime::Window& inWindow, Render::RenderThread& inRenderThread); + ~ImGuiRhiRenderer(); + + NonCopyable(ImGuiRhiRenderer) + NonMovable(ImGuiRhiRenderer) + + void NewFrame(); + void Submit(const ImDrawData& inDrawData); + void WaitIdle() const; + + private: + void RenderFrame(const Common::SharedPtr& inDrawData); + void RenderUiPass(ImDrawData& inDrawData); + void RenderImGuiDrawData(ImDrawData& inDrawData, RHI::RasterPassCommandRecorder& inRecorder); + void CreateImGuiDeviceObjects(); + void CreateImGuiFontTexture(); + void CreateImGuiDynamicBuffers(int inVertexCount, int inIndexCount); + void UpdateImGuiBuffers(ImDrawData& inDrawData); + void UpdateImGuiPassParams(const ImDrawData& inDrawData); + RHI::BindGroup* GetOrCreateImGuiTextureBindGroup(RHI::TextureView& inTextureView); + + Runtime::Window& window; + Render::RenderThread& renderThread; + RHI::PixelFormat pipelineFormat; + Common::SharedPtr inFlightDrawData; + Common::UniquePtr uiFrameFence; + Common::UniquePtr uiCommandBuffer; + Render::ShaderCompileOutput imguiVertexShaderCompileOutput; + Render::ShaderCompileOutput imguiPixelShaderCompileOutput; + Common::UniquePtr imguiVertexShader; + Common::UniquePtr imguiPixelShader; + Common::UniquePtr imguiBindGroupLayout; + Common::UniquePtr imguiPipelineLayout; + Common::UniquePtr imguiPipeline; + Common::UniquePtr imguiFontTexture; + Common::UniquePtr imguiFontTextureView; + Common::UniquePtr imguiImageSampler; + Common::UniquePtr imguiPassParamsBuffer; + Common::UniquePtr imguiPassParamsBufferView; + std::unordered_map> imguiFrameTextureBindGroups; + Common::UniquePtr imguiVertexBuffer; + Common::UniquePtr imguiVertexBufferView; + Common::UniquePtr imguiIndexBuffer; + Common::UniquePtr imguiIndexBufferView; + int imguiVertexBufferCapacity; + int imguiIndexBufferCapacity; + }; +} diff --git a/Editor/Include/Editor/Project/ProjectLauncher.h b/Editor/Include/Editor/Project/ProjectLauncher.h new file mode 100644 index 000000000..7eadbdd5e --- /dev/null +++ b/Editor/Include/Editor/Project/ProjectLauncher.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace Editor { + struct EditorLaunchOptions { + std::string executablePath; + std::string rhiType; + bool gpuDebug; + bool softwareGpu; + }; + + class ProjectLauncher final { + public: + using LaunchProcess = std::function(const std::string&, const std::vector&)>; + + explicit ProjectLauncher(EditorLaunchOptions inOptions, LaunchProcess inLaunchProcess = Common::Process::Launch); + + Common::Result Launch(const Common::Path& inProjectPath) const; + + private: + EditorLaunchOptions options; + LaunchProcess launchProcess; + }; +} diff --git a/Editor/Include/Editor/Project/ProjectService.h b/Editor/Include/Editor/Project/ProjectService.h new file mode 100644 index 000000000..cccd878cf --- /dev/null +++ b/Editor/Include/Editor/Project/ProjectService.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include + +#include +#include + +namespace Editor { + struct ProjectTemplateInfo { + std::string name; + Common::Path path; + }; + + struct CreateProjectDesc { + std::string name; + Common::Path parentDirectory; + Common::Path templateDirectory; + }; + + class ProjectService final { + public: + explicit ProjectService(Common::Path inTemplatesDirectory); + + Common::Result, std::string> ListTemplates() const; + Common::Result CreateProject(const CreateProjectDesc& inDesc) const; + static Common::Result ValidateProject(const Common::Path& inPath); + + private: + Common::Path templatesDirectory; + }; +} diff --git a/Editor/Include/Editor/Project/RecentProjectStore.h b/Editor/Include/Editor/Project/RecentProjectStore.h new file mode 100644 index 000000000..7206564f6 --- /dev/null +++ b/Editor/Include/Editor/Project/RecentProjectStore.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +#include +#include + +namespace Editor { + struct RecentProjectInfo { + std::string name; + std::string path; + }; + + class RecentProjectStore final { + public: + explicit RecentProjectStore(Common::Path inFile); + + Common::Result Load(); + Common::Result Record(const Common::Path& inProjectPath); + const std::vector& Projects() const; + + private: + Common::Path file; + std::vector projects; + }; +} diff --git a/Editor/Src/EditorApplication.cpp b/Editor/Src/EditorApplication.cpp index 6a30eef67..9355c9b4c 100644 --- a/Editor/Src/EditorApplication.cpp +++ b/Editor/Src/EditorApplication.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include @@ -16,7 +15,6 @@ #include #include #include -#include #include #include @@ -127,25 +125,6 @@ namespace Editor::Internal { ImGui::DockBuilderDockWindow(PanelNames::log, bottomNodeId); ImGui::DockBuilderFinish(inDockSpaceId); } - - static ImDrawData* CloneDrawData(const ImDrawData& inDrawData) - { - auto* result = IM_NEW(ImDrawData)(); - result->Valid = inDrawData.Valid; - result->CmdListsCount = inDrawData.CmdListsCount; - result->TotalIdxCount = inDrawData.TotalIdxCount; - result->TotalVtxCount = inDrawData.TotalVtxCount; - result->DisplayPos = inDrawData.DisplayPos; - result->DisplaySize = inDrawData.DisplaySize; - result->FramebufferScale = inDrawData.FramebufferScale; - result->OwnerViewport = inDrawData.OwnerViewport; - result->Textures = inDrawData.Textures; - result->CmdLists.resize(inDrawData.CmdListsCount); - for (int i = 0; i < inDrawData.CmdListsCount; i++) { - result->CmdLists[i] = inDrawData.CmdLists[i]->CloneOutput(); - } - return result; - } } namespace Editor { @@ -159,13 +138,17 @@ namespace Editor { , requestQuit(false) { InitializeImGui(); + auto& renderModule = Runtime::EngineHolder::Get().GetRenderModule(); window = Common::MakeUnique( + *renderModule.GetDevice(), renderModule.GetRenderThread(), EditorWindowDesc { .title = Internal::MakeWindowTitle(desc), .width = Internal::GetInitialWindowWidth(desc), .height = Internal::GetInitialWindowHeight(desc), .maximized = desc.mode == EditorApplicationMode::editor }); + imguiPlatform = Common::MakeUnique(*window); + imguiRenderer = Common::MakeUnique(*window, renderModule.GetRenderThread()); InstallCallbacks(); if (desc.mode == EditorApplicationMode::editor) { @@ -176,7 +159,15 @@ namespace Editor { sceneClient.SetRenderSurface(sceneRenderCanvas.Get()); sceneClient.OpenProjectLevel(); } else { - projectHubFrame = Common::MakeUnique(); + projectService = Common::MakeUnique(Core::Paths::EngineResDir() / "Editor" / "ProjectTemplates"); + recentProjects = Common::MakeUnique(Core::Paths::EngineCacheDir() / "Editor" / "ProjectHub" / "RecentProjects.json"); + projectLauncher = Common::MakeUnique(EditorLaunchOptions { + .executablePath = Core::Paths::ExecutablePath().String(), + .rhiType = desc.rhiType, + .gpuDebug = desc.gpuDebug, + .softwareGpu = desc.softwareGpu + }); + projectHubFrame = Common::MakeUnique(*projectService, *recentProjects, *projectLauncher); } } @@ -185,12 +176,12 @@ namespace Editor { if (context != nullptr) { context->GetSceneClient().SetRenderSurface(nullptr); } - if (window != nullptr) { - window->WaitRenderingIdle(); - } - sceneRenderCanvas.Reset(); + imguiRenderer->WaitIdle(); context.Reset(); + sceneRenderCanvas.Reset(); projectHubFrame.Reset(); + imguiPlatform.Reset(); + imguiRenderer.Reset(); window.Reset(); ShutdownImGui(); } @@ -201,13 +192,21 @@ namespace Editor { window->PollEvents(); window->RecreateSwapChainIfNeeded(); const float deltaSeconds = NextDeltaSeconds(); - BeginImGuiFrame(deltaSeconds); + imguiRenderer->NewFrame(); + imguiPlatform->NewFrame(deltaSeconds); + ImGui::NewFrame(); if (desc.mode == EditorApplicationMode::editor) { - RenderEditorFrame(deltaSeconds); + RenderEditorFrame(); } else { - RenderProjectHubFrame(); + requestQuit = projectHubFrame->Render(); } + if (requestQuit) { + window->RequestClose(); + } + ImGui::Render(); + Runtime::EngineHolder::Get().Tick(deltaSeconds); + imguiRenderer->Submit(*ImGui::GetDrawData()); } return 0; } @@ -218,8 +217,6 @@ namespace Editor { ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; - io.BackendPlatformName = "ExplosionGLFW"; - io.BackendRendererName = "ExplosionRHI"; if (desc.mode == EditorApplicationMode::editor) { const Common::Path iniFilePath = Core::Paths::GameCacheDir() / "Editor" / "Layout" / "Main.ini"; iniFilePath.Parent().MakeDir(); @@ -242,43 +239,21 @@ namespace Editor { void EditorApplication::InstallCallbacks() { - GLFWwindow* nativeWindow = window->GetNativeWindow(); - glfwSetWindowUserPointer(nativeWindow, this); - glfwSetKeyCallback(nativeWindow, [](GLFWwindow* inWindow, int inKey, int inScancode, int inAction, int inMods) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->HandleKey(inKey, inScancode, inAction, inMods); - }); - glfwSetCharCallback(nativeWindow, [](GLFWwindow* inWindow, unsigned int inCodepoint) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->HandleChar(inCodepoint); - }); - glfwSetMouseButtonCallback(nativeWindow, [](GLFWwindow* inWindow, int inButton, int inAction, int inMods) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->HandleMouseButton(inButton, inAction, inMods); + window->onKey.BindLambda([this](int inKey, int, int inAction, int) -> void { + HandleKey(inKey, inAction); }); - glfwSetCursorPosCallback(nativeWindow, [](GLFWwindow* inWindow, double inX, double inY) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->HandleCursor(inX, inY); + window->onMouseButton.BindLambda([this](int inButton, int inAction, int) -> void { + HandleMouseButton(inButton, inAction); }); - glfwSetScrollCallback(nativeWindow, [](GLFWwindow* inWindow, double inXOffset, double inYOffset) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->HandleScroll(inXOffset, inYOffset); + window->onCursor.BindMember<&EditorApplication::HandleCursor>(*this); + window->onFocus.BindLambda([this](bool inFocused) -> void { + if (!inFocused && context != nullptr) { + context->GetSceneClient().EndCameraLook(); + hasLastCursor = false; + } }); } - void EditorApplication::BeginImGuiFrame(float inDeltaSeconds) const - { - int windowWidth = 0; - int windowHeight = 0; - int framebufferWidth = 0; - int framebufferHeight = 0; - glfwGetWindowSize(window->GetNativeWindow(), &windowWidth, &windowHeight); - glfwGetFramebufferSize(window->GetNativeWindow(), &framebufferWidth, &framebufferHeight); - - ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize = ImVec2(static_cast(windowWidth), static_cast(windowHeight)); - io.DisplayFramebufferScale = ImVec2( - windowWidth > 0 ? static_cast(framebufferWidth) / static_cast(windowWidth) : 1.0f, - windowHeight > 0 ? static_cast(framebufferHeight) / static_cast(windowHeight) : 1.0f); - io.DeltaTime = std::max(inDeltaSeconds, 1.0f / 1000.0f); - ImGui::NewFrame(); - } - void EditorApplication::DrawDockSpace() const { const ImGuiViewport* mainViewport = ImGui::GetMainViewport(); @@ -307,46 +282,20 @@ namespace Editor { ImGui::End(); } - void EditorApplication::RenderEditorFrame(float inDeltaSeconds) + void EditorApplication::RenderEditorFrame() { DrawDockSpace(); context->GetSceneClient().GetWorld().EditorAccess([&](Runtime::ECRegistry& registry) -> void { editorFrame.Render(*context, registry, *sceneRenderCanvas, requestQuit); }); - if (requestQuit) { - window->RequestClose(); - } - if (ImGui::GetIO().KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_S, false)) { context->GetSceneClient().SaveLevel(); } - - ImGui::Render(); - window->SetDrawData(Internal::CloneDrawData(*ImGui::GetDrawData())); - Runtime::EngineHolder::Get().Tick(inDeltaSeconds); - window->RenderPendingUi(); } - void EditorApplication::RenderProjectHubFrame() + void EditorApplication::HandleKey(int inKey, int inAction) { - projectHubFrame->Render(*window, desc.rhiType, desc.gpuDebug, desc.softwareGpu); - ImGui::Render(); - Runtime::EngineHolder::Get().Tick(ImGui::GetIO().DeltaTime); - window->RenderUiOnly(*ImGui::GetDrawData()); - } - - void EditorApplication::HandleKey(int inKey, int inScancode, int inAction, int inMods) - { - std::ignore = inScancode; - ImGuiCompatibility::UpdateKeyModifiers(inMods); - - ImGuiIO& io = ImGui::GetIO(); - const ImGuiKey imguiKey = ImGuiCompatibility::ToImGuiKey(inKey); - if (imguiKey != ImGuiKey_None) { - io.AddKeyEvent(imguiKey, inAction != GLFW_RELEASE); - io.SetKeyEventNativeData(imguiKey, inKey, inScancode); - } - + const ImGuiIO& io = ImGui::GetIO(); if (context != nullptr) { auto& sceneClient = context->GetSceneClient(); if (inKey == GLFW_KEY_ESCAPE && inAction == GLFW_PRESS) { @@ -361,18 +310,8 @@ namespace Editor { } } - void EditorApplication::HandleChar(uint32_t inCodepoint) const + void EditorApplication::HandleMouseButton(int inButton, int inAction) { - ImGui::GetIO().AddInputCharacter(inCodepoint); - } - - void EditorApplication::HandleMouseButton(int inButton, int inAction, int inMods) - { - ImGuiCompatibility::UpdateKeyModifiers(inMods); - if (const auto imguiMouseButton = ImGuiCompatibility::ToImGuiMouseButton(inButton)) { - ImGui::GetIO().AddMouseButtonEvent(*imguiMouseButton, inAction == GLFW_PRESS); - } - if (context == nullptr || inButton != GLFW_MOUSE_BUTTON_RIGHT) { return; } @@ -387,7 +326,6 @@ namespace Editor { void EditorApplication::HandleCursor(double inX, double inY) { - ImGui::GetIO().AddMousePosEvent(static_cast(inX), static_cast(inY)); if (context != nullptr) { auto& sceneClient = context->GetSceneClient(); if (sceneClient.IsCameraLooking() && hasLastCursor) { @@ -399,11 +337,6 @@ namespace Editor { hasLastCursor = true; } - void EditorApplication::HandleScroll(double inXOffset, double inYOffset) const - { - ImGui::GetIO().AddMouseWheelEvent(static_cast(inXOffset), static_cast(inYOffset)); - } - float EditorApplication::NextDeltaSeconds() { const double now = Common::TimePoint::Now().ToSeconds(); diff --git a/Editor/Src/EditorWindow.cpp b/Editor/Src/EditorWindow.cpp index 45e535f38..eb7e0f20b 100644 --- a/Editor/Src/EditorWindow.cpp +++ b/Editor/Src/EditorWindow.cpp @@ -3,10 +3,7 @@ // #include -#include #include -#include -#include #if PLATFORM_WINDOWS #define GLFW_EXPOSE_NATIVE_WIN32 @@ -22,59 +19,23 @@ #endif #endif -#include - -#include #include -#include - -namespace Editor::Internal { - const Common::LinearColor uiOnlyClearColor = Common::LinearColor(0.08f, 0.08f, 0.09f, 1.0f); - constexpr int imguiVertexBufferInitialCapacity = 5000; - constexpr int imguiIndexBufferInitialCapacity = 10000; - constexpr RHI::IndexFormat imguiIndexFormat = sizeof(ImDrawIdx) == 2 - ? RHI::IndexFormat::uint16 - : RHI::IndexFormat::uint32; +#include +namespace Editor::Windowing::Internal { static uint32_t ClampExtent(int inValue) { return static_cast(std::max(1, inValue)); } - - static Render::ShaderCompileOutput CompileImGuiShader( - RHI::Device& inDevice, - const std::string& inEntryPoint, - RHI::ShaderStageBits inStage) - { - Render::ShaderCompileInput input; - input.source = Common::FileUtils::ReadTextFile("../Shader/Editor/ImGui.esl").Unwrap(); - input.entryPoint = inEntryPoint; - input.stage = inStage; - input.includeDirectories.emplace_back("../Shader/Explosion"); - - Render::ShaderCompileOptions options; - options.byteCodeType = inDevice.GetGpu().GetInstance().GetRHIType() == RHI::RHIType::directX12 - ? Render::ShaderByteCodeType::dxil - : Render::ShaderByteCodeType::spirv; - options.withDebugInfo = static_cast(BUILD_CONFIG_DEBUG); // NOLINT - - auto future = Render::ShaderCompiler::Get().Compile(input, options); - future.wait(); - return future.get(); - } } namespace Editor { - EditorWindow::EditorWindow(const EditorWindowDesc& inDesc) - : Runtime::Window(*Runtime::EngineHolder::Get().GetRenderModule().GetDevice()) + EditorWindow::EditorWindow(RHI::Device& inDevice, Render::RenderThread& inRenderThread, const EditorWindowDesc& inDesc) + : Runtime::Window(inDevice) + , renderThread(inRenderThread) , window(nullptr) - , uiFrameFence(GetDevice().CreateFence(true)) - , uiCommandBuffer(GetDevice().CreateCommandBuffer(RHI::QueueType::graphics)) - , imguiVertexBufferCapacity(0) - , imguiIndexBufferCapacity(0) , framebufferWidth(inDesc.width) , framebufferHeight(inDesc.height) - , pendingDrawData(nullptr) { glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); @@ -90,23 +51,19 @@ namespace Editor { int fbWidth = 0; int fbHeight = 0; glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - framebufferWidth = Internal::ClampExtent(fbWidth); - framebufferHeight = Internal::ClampExtent(fbHeight); + framebufferWidth = Windowing::Internal::ClampExtent(fbWidth); + framebufferHeight = Windowing::Internal::ClampExtent(fbHeight); InitializeSurface( GetDevice().CreateSurface(RHI::SurfaceCreateInfo(GetPlatformWindow())), framebufferWidth, framebufferHeight); - CreateImGuiDeviceObjects(); - CreateImGuiDynamicBuffers(Internal::imguiVertexBufferInitialCapacity, Internal::imguiIndexBufferInitialCapacity); + InstallCallbacks(); } EditorWindow::~EditorWindow() { - DestroyDrawData(pendingDrawData); - pendingDrawData = nullptr; WaitRenderingIdle(); - imguiFrameTextureBindGroups.clear(); DestroySurface(); glfwDestroyWindow(window); glfwTerminate(); @@ -157,11 +114,9 @@ namespace Editor { glfwSetWindowTitle(window, inTitle.c_str()); } - void EditorWindow::SetDrawData(ImDrawData* inDrawData) + void EditorWindow::SetCursorCaptured(bool inCaptured) const { - std::unique_lock lock(drawDataMutex); - DestroyDrawData(pendingDrawData); - pendingDrawData = inDrawData; + glfwSetInputMode(window, GLFW_CURSOR, inCaptured ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); } void EditorWindow::RecreateSwapChainIfNeeded() @@ -169,62 +124,45 @@ namespace Editor { int fbWidth = 0; int fbHeight = 0; glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - const uint32_t newWidth = Internal::ClampExtent(fbWidth); - const uint32_t newHeight = Internal::ClampExtent(fbHeight); + const uint32_t newWidth = Windowing::Internal::ClampExtent(fbWidth); + const uint32_t newHeight = Windowing::Internal::ClampExtent(fbHeight); if (newWidth == framebufferWidth && newHeight == framebufferHeight) { return; } framebufferWidth = newWidth; framebufferHeight = newHeight; - const RHI::PixelFormat previousFormat = GetSwapChainFormat(); WaitRenderingIdle(); Runtime::Window::Resize(framebufferWidth, framebufferHeight); - if (GetSwapChainFormat() != previousFormat) { - CreateImGuiDeviceObjects(); - } } void EditorWindow::WaitRenderingIdle() const { - Runtime::EngineHolder::Get().GetRenderModule().GetRenderThread().Flush(); + renderThread.Flush(); Runtime::Window::WaitRenderingIdle(); } - void EditorWindow::RenderPendingUi() + void EditorWindow::InstallCallbacks() { - ImDrawData* drawData = TakeDrawData(); - Runtime::EngineHolder::Get().GetRenderModule().GetRenderThread().EmplaceTask([this, drawData]() -> void { - uiFrameFence->Wait(); - AcquireBackTexture(); - uiFrameFence->Reset(); - - RenderUiPass(drawData, RHI::LoadOp::clear, Internal::uiOnlyClearColor); - GetDevice().GetQueue(RHI::QueueType::graphics, 0)->Submit( - uiCommandBuffer.Get(), - RHI::QueueSubmitInfo() - .AddWaitSemaphore(GetImageReadySemaphore()) - .AddSignalSemaphore(GetRenderFinishedSemaphore()) - .SetSignalFence(uiFrameFence.Get())); - Present(); - DestroyDrawData(drawData); + glfwSetWindowUserPointer(window, this); + glfwSetKeyCallback(window, [](GLFWwindow* inWindow, int inKey, int inScancode, int inAction, int inMods) -> void { + static_cast(glfwGetWindowUserPointer(inWindow))->onKey.Broadcast(inKey, inScancode, inAction, inMods); + }); + glfwSetCharCallback(window, [](GLFWwindow* inWindow, unsigned int inCodepoint) -> void { + static_cast(glfwGetWindowUserPointer(inWindow))->onChar.Broadcast(inCodepoint); + }); + glfwSetMouseButtonCallback(window, [](GLFWwindow* inWindow, int inButton, int inAction, int inMods) -> void { + static_cast(glfwGetWindowUserPointer(inWindow))->onMouseButton.Broadcast(inButton, inAction, inMods); + }); + glfwSetCursorPosCallback(window, [](GLFWwindow* inWindow, double inX, double inY) -> void { + static_cast(glfwGetWindowUserPointer(inWindow))->onCursor.Broadcast(inX, inY); + }); + glfwSetScrollCallback(window, [](GLFWwindow* inWindow, double inX, double inY) -> void { + static_cast(glfwGetWindowUserPointer(inWindow))->onScroll.Broadcast(inX, inY); + }); + glfwSetWindowFocusCallback(window, [](GLFWwindow* inWindow, int inFocused) -> void { + static_cast(glfwGetWindowUserPointer(inWindow))->onFocus.Broadcast(inFocused == GLFW_TRUE); }); - } - - void EditorWindow::RenderUiOnly(ImDrawData& inDrawData) - { - uiFrameFence->Wait(); - AcquireBackTexture(); - uiFrameFence->Reset(); - - RenderUiPass(&inDrawData, RHI::LoadOp::clear, Internal::uiOnlyClearColor); - GetDevice().GetQueue(RHI::QueueType::graphics, 0)->Submit( - uiCommandBuffer.Get(), - RHI::QueueSubmitInfo() - .AddWaitSemaphore(GetImageReadySemaphore()) - .AddSignalSemaphore(GetRenderFinishedSemaphore()) - .SetSignalFence(uiFrameFence.Get())); - Present(); } void* EditorWindow::GetPlatformWindow() const @@ -239,335 +177,4 @@ namespace Editor { #endif } - void EditorWindow::RenderUiPass( - ImDrawData* inDrawData, - RHI::LoadOp inLoadOp, - const Common::LinearColor& inClearValue) - { - auto* target = GetTexture(); - auto* targetView = GetRenderTargetView(); - Assert(target != nullptr && targetView != nullptr); - - const auto commandRecorder = uiCommandBuffer->Begin(); - { - commandRecorder->ResourceBarrier(RHI::Barrier::Transition(target, GetCurrentBackTextureState(), RHI::TextureState::renderTarget)); - const auto rasterRecorder = commandRecorder->BeginRasterPass( - RHI::RasterPassBeginInfo() - .AddColorAttachment(RHI::ColorAttachment(targetView, inLoadOp, RHI::StoreOp::store, inClearValue))); - if (inDrawData != nullptr) { - RenderImGuiDrawData(*inDrawData, *rasterRecorder); - } - rasterRecorder->EndPass(); - commandRecorder->ResourceBarrier(RHI::Barrier::Transition(target, RHI::TextureState::renderTarget, RHI::TextureState::present)); - } - commandRecorder->End(); - } - - void EditorWindow::RenderImGuiDrawData(ImDrawData& inDrawData, RHI::RasterPassCommandRecorder& inRecorder) - { - imguiFrameTextureBindGroups.clear(); - if (inDrawData.TotalVtxCount <= 0 || inDrawData.TotalIdxCount <= 0) { - return; - } - - if (inDrawData.TotalVtxCount > imguiVertexBufferCapacity || inDrawData.TotalIdxCount > imguiIndexBufferCapacity) { - CreateImGuiDynamicBuffers( - std::max(inDrawData.TotalVtxCount, imguiVertexBufferCapacity * 2), - std::max(inDrawData.TotalIdxCount, imguiIndexBufferCapacity * 2)); - } - - UpdateImGuiBuffers(inDrawData); - UpdateImGuiPassParams(inDrawData); - - const auto framebufferWidth = static_cast(inDrawData.DisplaySize.x * inDrawData.FramebufferScale.x); - const auto framebufferHeight = static_cast(inDrawData.DisplaySize.y * inDrawData.FramebufferScale.y); - if (framebufferWidth == 0 || framebufferHeight == 0) { - return; - } - - inRecorder.SetPipeline(imguiPipeline.Get()); - inRecorder.SetVertexBuffer(0, imguiVertexBufferView.Get()); - inRecorder.SetIndexBuffer(imguiIndexBufferView.Get()); - inRecorder.SetPrimitiveTopology(RHI::PrimitiveTopology::triangleList); - inRecorder.SetViewport(0.0f, 0.0f, static_cast(framebufferWidth), static_cast(framebufferHeight), 0.0f, 1.0f); - - const ImVec2 clipOffset = inDrawData.DisplayPos; - const ImVec2 clipScale = inDrawData.FramebufferScale; - int globalVertexOffset = 0; - int globalIndexOffset = 0; - for (int commandListIndex = 0; commandListIndex < inDrawData.CmdListsCount; commandListIndex++) { - const ImDrawList* commandList = inDrawData.CmdLists[commandListIndex]; - for (int commandIndex = 0; commandIndex < commandList->CmdBuffer.Size; commandIndex++) { - const ImDrawCmd* command = &commandList->CmdBuffer[commandIndex]; - if (command->UserCallback != nullptr) { - command->UserCallback(commandList, command); - continue; - } - - ImVec2 clipMin( - (command->ClipRect.x - clipOffset.x) * clipScale.x, - (command->ClipRect.y - clipOffset.y) * clipScale.y); - ImVec2 clipMax( - (command->ClipRect.z - clipOffset.x) * clipScale.x, - (command->ClipRect.w - clipOffset.y) * clipScale.y); - clipMin.x = std::clamp(clipMin.x, 0.0f, static_cast(framebufferWidth)); - clipMin.y = std::clamp(clipMin.y, 0.0f, static_cast(framebufferHeight)); - clipMax.x = std::clamp(clipMax.x, 0.0f, static_cast(framebufferWidth)); - clipMax.y = std::clamp(clipMax.y, 0.0f, static_cast(framebufferHeight)); - if (clipMax.x <= clipMin.x || clipMax.y <= clipMin.y) { - continue; - } - - inRecorder.SetScissor( - static_cast(clipMin.x), - static_cast(clipMin.y), - static_cast(clipMax.x), - static_cast(clipMax.y)); - ImTextureID textureId = command->GetTexID(); - auto* textureView = textureId == ImTextureID_Invalid - ? imguiFontTextureView.Get() - : reinterpret_cast(static_cast(textureId)); - Assert(textureView != nullptr); - inRecorder.SetBindGroup(0, GetOrCreateImGuiTextureBindGroup(*textureView)); - inRecorder.DrawIndexed( - command->ElemCount, - 1, - command->IdxOffset + globalIndexOffset, - command->VtxOffset + globalVertexOffset, - 0); - } - globalIndexOffset += commandList->IdxBuffer.Size; - globalVertexOffset += commandList->VtxBuffer.Size; - } - } - - void EditorWindow::CreateImGuiDeviceObjects() - { - RHI::Device& device = GetDevice(); - imguiFrameTextureBindGroups.clear(); - imguiVertexShaderCompileOutput = Internal::CompileImGuiShader(device, "VSMain", RHI::ShaderStageBits::sVertex); - imguiPixelShaderCompileOutput = Internal::CompileImGuiShader(device, "PSMain", RHI::ShaderStageBits::sPixel); - imguiVertexShader = device.CreateShaderModule(RHI::ShaderModuleCreateInfo("VSMain", imguiVertexShaderCompileOutput.byteCode)); - imguiPixelShader = device.CreateShaderModule(RHI::ShaderModuleCreateInfo("PSMain", imguiPixelShaderCompileOutput.byteCode)); - - CreateImGuiFontTexture(); - - imguiPassParamsBuffer = device.CreateBuffer( - RHI::BufferCreateInfo() - .SetSize(sizeof(ImGuiPassParams)) - .SetUsages(RHI::BufferUsageBits::uniform | RHI::BufferUsageBits::mapWrite) - .SetInitialState(RHI::BufferState::staging) - .SetDebugName("imguiPassParams")); - imguiPassParamsBufferView = imguiPassParamsBuffer->CreateBufferView( - RHI::BufferViewCreateInfo() - .SetType(RHI::BufferViewType::uniformBinding) - .SetSizeInBytes(sizeof(ImGuiPassParams)) - .SetOffsetInBytes(0)); - - imguiBindGroupLayout = device.CreateBindGroupLayout( - RHI::BindGroupLayoutCreateInfo(0, "imguiBindGroupLayout") - .AddEntry(RHI::BindGroupLayoutEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageTex").second, RHI::ShaderStageBits::sPixel)) - .AddEntry(RHI::BindGroupLayoutEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageSampler").second, RHI::ShaderStageBits::sPixel)) - .AddEntry(RHI::BindGroupLayoutEntry(imguiVertexShaderCompileOutput.reflectionData.QueryResourceBindingChecked("passParams").second, RHI::ShaderStageBits::sVertex))); - imguiPipelineLayout = device.CreatePipelineLayout( - RHI::PipelineLayoutCreateInfo() - .AddBindGroupLayout(imguiBindGroupLayout.Get())); - - const RHI::BlendComponent colorBlend(RHI::BlendOp::opAdd, RHI::BlendFactor::srcAlpha, RHI::BlendFactor::oneMinusSrcAlpha); - const RHI::BlendComponent alphaBlend(RHI::BlendOp::opAdd, RHI::BlendFactor::one, RHI::BlendFactor::oneMinusSrcAlpha); - const RHI::ColorTargetState colorTarget(GetSwapChainFormat(), RHI::ColorWriteBits::all, true, colorBlend, alphaBlend); - - imguiPipeline = device.CreateRasterPipeline( - RHI::RasterPipelineCreateInfo(imguiPipelineLayout.Get()) - .SetVertexShader(imguiVertexShader.Get()) - .SetPixelShader(imguiPixelShader.Get()) - .SetVertexState( - RHI::VertexState() - .AddVertexBufferLayout( - RHI::VertexBufferLayout(RHI::VertexStepMode::perVertex, sizeof(ImDrawVert)) - .AddAttribute(RHI::VertexAttribute(imguiVertexShaderCompileOutput.reflectionData.QueryVertexBindingChecked("POSITION"), RHI::VertexFormat::float32X2, offsetof(ImDrawVert, pos))) - .AddAttribute(RHI::VertexAttribute(imguiVertexShaderCompileOutput.reflectionData.QueryVertexBindingChecked("TEXCOORD"), RHI::VertexFormat::float32X2, offsetof(ImDrawVert, uv))) - .AddAttribute(RHI::VertexAttribute(imguiVertexShaderCompileOutput.reflectionData.QueryVertexBindingChecked("COLOR"), RHI::VertexFormat::unorm8X4, offsetof(ImDrawVert, col))))) - .SetFragmentState(RHI::FragmentState().AddColorTarget(colorTarget)) - .SetPrimitiveState(RHI::PrimitiveState(RHI::PrimitiveTopologyType::triangle, RHI::FillMode::solid, Internal::imguiIndexFormat, RHI::FrontFace::ccw, RHI::CullMode::none)) - .SetDepthStencilState(RHI::DepthStencilState())); - } - - void EditorWindow::CreateImGuiFontTexture() - { - RHI::Device& device = GetDevice(); - - unsigned char* pixels = nullptr; - int width = 0; - int height = 0; - ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - - imguiFontTexture = device.CreateTexture( - RHI::TextureCreateInfo() - .SetType(RHI::TextureType::t2D) - .SetWidth(static_cast(width)) - .SetHeight(static_cast(height)) - .SetDepthOrArraySize(1) - .SetFormat(RHI::PixelFormat::rgba8Unorm) - .SetUsages(RHI::TextureUsageBits::copyDst | RHI::TextureUsageBits::textureBinding) - .SetMipLevels(1) - .SetSamples(1) - .SetInitialState(RHI::TextureState::undefined) - .SetDebugName("imguiFontTexture")); - imguiFontTextureView = imguiFontTexture->CreateTextureView( - RHI::TextureViewCreateInfo() - .SetDimension(RHI::TextureViewDimension::tv2D) - .SetMipLevels(0, 1) - .SetArrayLayers(0, 1) - .SetAspect(RHI::TextureAspect::color) - .SetType(RHI::TextureViewType::textureBinding)); - imguiImageSampler = device.CreateSampler( - RHI::SamplerCreateInfo() - .SetAddressModeU(RHI::AddressMode::clampToEdge) - .SetAddressModeV(RHI::AddressMode::clampToEdge) - .SetAddressModeW(RHI::AddressMode::clampToEdge) - .SetMagFilter(RHI::FilterMode::linear) - .SetMinFilter(RHI::FilterMode::linear) - .SetMipFilter(RHI::FilterMode::linear) - .SetDebugName("imguiImageSampler")); - - const auto copyFootprint = device.GetTextureSubResourceCopyFootprint(*imguiFontTexture, RHI::TextureSubResourceInfo()); - auto stagingBuffer = device.CreateBuffer( - RHI::BufferCreateInfo() - .SetSize(static_cast(copyFootprint.totalBytes)) - .SetUsages(RHI::BufferUsageBits::mapWrite | RHI::BufferUsageBits::copySrc) - .SetInitialState(RHI::BufferState::staging) - .SetDebugName("imguiFontUpload")); - auto* mapped = stagingBuffer->Map(RHI::MapMode::write, 0, copyFootprint.totalBytes); - const size_t srcRowPitch = static_cast(width) * copyFootprint.bytesPerPixel; - for (int row = 0; row < height; row++) { - const auto* src = pixels + static_cast(row) * srcRowPitch; - auto* dst = static_cast(mapped) + static_cast(row) * copyFootprint.rowPitch; - memcpy(dst, src, srcRowPitch); - } - stagingBuffer->Unmap(); - - const auto commandBuffer = device.CreateCommandBuffer(RHI::QueueType::graphics); - const auto commandRecorder = commandBuffer->Begin(); - { - const auto copyRecorder = commandRecorder->BeginCopyPass(); - copyRecorder->ResourceBarrier(RHI::Barrier::Transition(imguiFontTexture.Get(), RHI::TextureState::undefined, RHI::TextureState::copyDst)); - copyRecorder->CopyBufferToTexture( - stagingBuffer.Get(), - imguiFontTexture.Get(), - RHI::BufferTextureCopyInfo( - 0, - RHI::TextureSubResourceInfo(), - Common::UVec3Consts::zero, - Common::UVec3(static_cast(width), static_cast(height), 1), - copyFootprint.rowPitch, - copyFootprint.slicePitch)); - copyRecorder->ResourceBarrier(RHI::Barrier::Transition(imguiFontTexture.Get(), RHI::TextureState::copyDst, RHI::TextureState::shaderReadOnly)); - copyRecorder->EndPass(); - } - commandRecorder->End(); - - const auto fence = device.CreateFence(false); - device.GetQueue(RHI::QueueType::graphics, 0)->Submit(commandBuffer.Get(), RHI::QueueSubmitInfo().SetSignalFence(fence.Get())); - fence->Wait(); - ImGui::GetIO().Fonts->SetTexID(static_cast(reinterpret_cast(imguiFontTextureView.Get()))); - } - - void EditorWindow::CreateImGuiDynamicBuffers(int inVertexCount, int inIndexCount) - { - RHI::Device& device = GetDevice(); - imguiVertexBufferCapacity = std::max(1, inVertexCount); - imguiIndexBufferCapacity = std::max(1, inIndexCount); - - const uint32_t vertexBufferSize = static_cast(imguiVertexBufferCapacity * sizeof(ImDrawVert)); - imguiVertexBuffer = device.CreateBuffer( - RHI::BufferCreateInfo() - .SetSize(vertexBufferSize) - .SetUsages(RHI::BufferUsageBits::vertex | RHI::BufferUsageBits::mapWrite | RHI::BufferUsageBits::copySrc) - .SetInitialState(RHI::BufferState::staging) - .SetDebugName("imguiVertexBuffer")); - imguiVertexBufferView = imguiVertexBuffer->CreateBufferView( - RHI::BufferViewCreateInfo() - .SetType(RHI::BufferViewType::vertex) - .SetSizeInBytes(vertexBufferSize) - .SetOffsetInBytes(0) - .SetExtendVertex(sizeof(ImDrawVert))); - - const uint32_t indexBufferSize = static_cast(imguiIndexBufferCapacity * sizeof(ImDrawIdx)); - imguiIndexBuffer = device.CreateBuffer( - RHI::BufferCreateInfo() - .SetSize(indexBufferSize) - .SetUsages(RHI::BufferUsageBits::index | RHI::BufferUsageBits::mapWrite | RHI::BufferUsageBits::copySrc) - .SetInitialState(RHI::BufferState::staging) - .SetDebugName("imguiIndexBuffer")); - imguiIndexBufferView = imguiIndexBuffer->CreateBufferView( - RHI::BufferViewCreateInfo() - .SetType(RHI::BufferViewType::index) - .SetSizeInBytes(indexBufferSize) - .SetOffsetInBytes(0) - .SetExtendIndex(Internal::imguiIndexFormat)); - } - - void EditorWindow::UpdateImGuiBuffers(ImDrawData& inDrawData) - { - auto* vertexDst = static_cast(imguiVertexBuffer->Map(RHI::MapMode::write, 0, inDrawData.TotalVtxCount * sizeof(ImDrawVert))); - auto* indexDst = static_cast(imguiIndexBuffer->Map(RHI::MapMode::write, 0, inDrawData.TotalIdxCount * sizeof(ImDrawIdx))); - for (int i = 0; i < inDrawData.CmdListsCount; i++) { - const ImDrawList* commandList = inDrawData.CmdLists[i]; - memcpy(vertexDst, commandList->VtxBuffer.Data, static_cast(commandList->VtxBuffer.Size) * sizeof(ImDrawVert)); - memcpy(indexDst, commandList->IdxBuffer.Data, static_cast(commandList->IdxBuffer.Size) * sizeof(ImDrawIdx)); - vertexDst += commandList->VtxBuffer.Size; - indexDst += commandList->IdxBuffer.Size; - } - imguiVertexBuffer->Unmap(); - imguiIndexBuffer->Unmap(); - } - - void EditorWindow::UpdateImGuiPassParams(const ImDrawData& inDrawData) - { - const ImGuiPassParams params { - Common::FVec2(inDrawData.DisplayPos.x, inDrawData.DisplayPos.y), - Common::FVec2(inDrawData.DisplaySize.x, inDrawData.DisplaySize.y) - }; - auto* data = imguiPassParamsBuffer->Map(RHI::MapMode::write, 0, sizeof(ImGuiPassParams)); - memcpy(data, ¶ms, sizeof(ImGuiPassParams)); - imguiPassParamsBuffer->Unmap(); - } - - RHI::BindGroup* EditorWindow::GetOrCreateImGuiTextureBindGroup(RHI::TextureView& inTextureView) - { - if (const auto iter = imguiFrameTextureBindGroups.find(&inTextureView); - iter != imguiFrameTextureBindGroups.end()) { - return iter->second.Get(); - } - - auto bindGroup = GetDevice().CreateBindGroup( - RHI::BindGroupCreateInfo(imguiBindGroupLayout.Get(), "imguiBindGroup") - .AddEntry(RHI::BindGroupEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageTex").second, RHI::ShaderStageBits::sPixel, &inTextureView)) - .AddEntry(RHI::BindGroupEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageSampler").second, RHI::ShaderStageBits::sPixel, imguiImageSampler.Get())) - .AddEntry(RHI::BindGroupEntry(imguiVertexShaderCompileOutput.reflectionData.QueryResourceBindingChecked("passParams").second, RHI::ShaderStageBits::sVertex, imguiPassParamsBufferView.Get()))); - auto* result = bindGroup.Get(); - imguiFrameTextureBindGroups.emplace(&inTextureView, std::move(bindGroup)); - return result; - } - - ImDrawData* EditorWindow::TakeDrawData() - { - std::unique_lock lock(drawDataMutex); - ImDrawData* result = pendingDrawData; - pendingDrawData = nullptr; - return result; - } - - void EditorWindow::DestroyDrawData(ImDrawData* inDrawData) - { - if (inDrawData == nullptr) { - return; - } - for (int i = 0; i < inDrawData->CmdLists.Size; i++) { - IM_DELETE(inDrawData->CmdLists[i]); - } - inDrawData->CmdLists.clear(); - IM_DELETE(inDrawData); - } } diff --git a/Editor/Src/Frame/ProjectHubFrame.cpp b/Editor/Src/Frame/ProjectHubFrame.cpp index 05de85b8a..6d84ab6cc 100644 --- a/Editor/Src/Frame/ProjectHubFrame.cpp +++ b/Editor/Src/Frame/ProjectHubFrame.cpp @@ -2,29 +2,19 @@ // Created by johnk on 2026/7/8. // -#include #include #include -#include -#include #include #include -#include -#include -#include -#include #include -#include #include #include #include #include namespace Editor::ProjectHub::Internal { - constexpr std::string_view templateFileExtension = ".tpl"; - constexpr std::string_view cmakeMinVersion = "3.25"; constexpr float actionButtonHeight = 58.0f; constexpr float recentProjectHeight = 68.0f; constexpr float contentSpacing = 12.0f; @@ -49,85 +39,33 @@ namespace Editor::ProjectHub::Internal { ImGui::PopID(); return ImGui::IsItemClicked(); } - - static Common::Path StripTemplateExtension(const Common::Path& inRelativePath) - { - const std::string str = inRelativePath.String(); - return { str.substr(0, str.size() - templateFileExtension.size()) }; - } - - static Common::Result RenderProjectTemplate(const Common::Path& inTemplateDir, const Common::Path& inProjectDir, const std::string& inProjectName) - { - Common::TemplateEngine templateEngine; - templateEngine - .Set("projectName", inProjectName) - .Set("cmakeMinVersion", std::string(cmakeMinVersion)); - - Common::Result result = Common::Ok(); - inTemplateDir.TraverseRecurse([&](const Common::Path& inPath) -> bool { - if (inPath.IsDirectory()) { - return true; - } - - const Common::Path relativePath = inPath.Relative(inTemplateDir); - const std::string extension = inPath.Extension(); - const bool isTemplate = std::string_view(extension) == templateFileExtension; - const Common::Path dstPath = inProjectDir / (isTemplate ? StripTemplateExtension(relativePath) : relativePath); - dstPath.Parent().MakeDir(); - - if (!isTemplate) { - inPath.CopyTo(dstPath); - return true; - } - if (auto renderResult = templateEngine.RenderFileTo(inPath.String(), dstPath.String()); - renderResult.IsErr()) { - result = Common::Err(renderResult.Error()); - return false; - } - return true; - }); - return result; - } - - static std::string LaunchCommand(const std::string& inExecutable, const std::string& inProjectPath, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu) - { - const std::string gpuDebugArg = inGpuDebug ? " -gpuDebug" : ""; - const std::string softwareGpuArg = inSoftwareGpu ? " -softwareGpu" : ""; -#if PLATFORM_WINDOWS - return std::format("start \"\" \"{}\" -project \"{}\" -rhi {}{}{}", inExecutable, inProjectPath, inRhiType, gpuDebugArg, softwareGpuArg); -#else - return std::format("\"{}\" -project \"{}\" -rhi {}{}{} &", inExecutable, inProjectPath, inRhiType, gpuDebugArg, softwareGpuArg); -#endif - } } namespace Editor { - ProjectHubFrame::ProjectHubFrame() - : recentProjectsFile(Core::Paths::EngineCacheDir() / "Editor" / "ProjectHub" / "RecentProjects.json") - , projectName() - , directory() + ProjectHubFrame::ProjectHubFrame(ProjectService& inProjectService, RecentProjectStore& inRecentProjects, ProjectLauncher& inProjectLauncher) + : projectService(inProjectService) + , recentProjects(inRecentProjects) + , projectLauncher(inProjectLauncher) , selectedTemplateIndex(0) + , requestClose(false) { - const Common::Path projectTemplatesRoot = Core::Paths::EngineResDir() / "Editor" / "ProjectTemplates"; - (void) projectTemplatesRoot.Traverse([this](const Common::Path& inPath) -> bool { - if (inPath.IsFile()) { - return true; + auto templatesResult = projectService.ListTemplates(); + if (templatesResult.IsOk()) { + projectTemplates = std::move(templatesResult.Value()); + } else { + statusMessage = templatesResult.Error(); + } + if (auto result = recentProjects.Load(); result.IsErr()) { + if (!statusMessage.empty()) { + statusMessage += "\n"; } - projectTemplates.emplace_back(ProjectTemplateInfo { inPath.DirName(), inPath.String() }); - return true; - }); - - if (recentProjectsFile.Exists()) { - Common::JsonDeserializeFromFile(recentProjectsFile.String(), recentProjects); + statusMessage += result.Error(); } } - ProjectHubFrame::~ProjectHubFrame() - { - SaveRecentProjects(); - } + ProjectHubFrame::~ProjectHubFrame() = default; - void ProjectHubFrame::Render(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu) + bool ProjectHubFrame::Render() { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); @@ -144,21 +82,22 @@ namespace Editor { | ImGuiWindowFlags_NoBringToFrontOnFocus); ImGui::PopStyleVar(2); - RenderActionBar(inWindow, inRhiType, inGpuDebug, inSoftwareGpu); + RenderActionBar(); ImGui::Dummy(ImVec2(0.0f, 22.0f)); - RenderRecentProjects(inWindow, inRhiType, inGpuDebug, inSoftwareGpu); - RenderCreateProjectPopup(inWindow, inRhiType, inGpuDebug, inSoftwareGpu); + RenderRecentProjects(); + RenderCreateProjectPopup(); ImGui::End(); + return requestClose; } - void ProjectHubFrame::RenderActionBar(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu) + void ProjectHubFrame::RenderActionBar() { const float spacing = ImGui::GetStyle().ItemSpacing.x; const float buttonWidth = (ImGui::GetContentRegionAvail().x - spacing) * 0.5f; const std::string openLabel = Widgets::Label(Icons::Tabler::folderOpen, "Open"); if (Widgets::PrimaryButton(openLabel.c_str(), ImVec2(buttonWidth, ProjectHub::Internal::actionButtonHeight))) { if (const auto selectedDirectory = PlatformUtils::SelectDirectory("Open Explosion Project")) { - OpenProject(inWindow, *selectedDirectory, inRhiType, inGpuDebug, inSoftwareGpu); + OpenProject(Common::Path(*selectedDirectory)); } } @@ -170,11 +109,11 @@ namespace Editor { } } - void ProjectHubFrame::RenderRecentProjects(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu) + void ProjectHubFrame::RenderRecentProjects() { const std::string recentProjectsLabel = Widgets::Label(Icons::Tabler::folder, "Recent projects"); ImGui::TextUnformatted(recentProjectsLabel.c_str()); - const std::string projectCount = std::to_string(recentProjects.size()); + const std::string projectCount = std::to_string(recentProjects.Projects().size()); ImGui::SameLine(ImGui::GetContentRegionMax().x - ImGui::CalcTextSize(projectCount.c_str()).x); ImGui::TextDisabled("%s", projectCount.c_str()); ImGui::Dummy(ImVec2(0.0f, 7.0f)); @@ -189,14 +128,14 @@ namespace Editor { ImGui::BeginChild("##RecentProjects", ImVec2(0.0f, 0.0f), false); std::string projectToOpen; - for (const auto& project : std::views::reverse(recentProjects)) { + for (const auto& project : std::views::reverse(recentProjects.Projects())) { if (ProjectHub::Internal::RenderRecentProject(project)) { projectToOpen = project.path; } ImGui::Dummy(ImVec2(0.0f, ProjectHub::Internal::contentSpacing)); } - if (recentProjects.empty()) { + if (recentProjects.Projects().empty()) { const ImVec2 emptyMin = ImGui::GetCursorScreenPos(); const ImVec2 emptyMax(emptyMin.x + ImGui::GetContentRegionAvail().x, emptyMin.y + 118.0f); ImGui::GetWindowDrawList()->AddRectFilled(emptyMin, emptyMax, ImGui::GetColorU32(ImGuiCol_FrameBg), 8.0f); @@ -210,11 +149,11 @@ namespace Editor { ImGui::EndChild(); if (!projectToOpen.empty()) { - OpenProject(inWindow, projectToOpen, inRhiType, inGpuDebug, inSoftwareGpu); + OpenProject(Common::Path(projectToOpen)); } } - void ProjectHubFrame::RenderCreateProjectPopup(EditorWindow& inWindow, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu) + void ProjectHubFrame::RenderCreateProjectPopup() { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); @@ -285,13 +224,21 @@ namespace Editor { ImGui::SameLine(); const std::string confirmLabel = Widgets::Label(Icons::Tabler::check, "Create##Confirm"); if (Widgets::PrimaryButton(confirmLabel.c_str(), ImVec2(88.0f, 36.0f))) { - const CreateProjectResult result = CreateProject(); - if (result.success) { - statusMessage.clear(); - ImGui::CloseCurrentPopup(); - OpenProject(inWindow, result.projectPath, inRhiType, inGpuDebug, inSoftwareGpu); + if (projectTemplates.empty()) { + statusMessage = "No project templates are available."; } else { - statusMessage = result.error; + const auto result = projectService.CreateProject(CreateProjectDesc { + .name = projectName, + .parentDirectory = Common::Path(directory), + .templateDirectory = projectTemplates[selectedTemplateIndex].path + }); + if (result.IsOk()) { + LogInfo(ProjectHub, "created project '{}' at '{}'", projectName, result.Value().String()); + ImGui::CloseCurrentPopup(); + OpenProject(result.Value()); + } else { + statusMessage = result.Error(); + } } } ImGui::EndPopup(); @@ -299,65 +246,21 @@ namespace Editor { ImGui::PopStyleVar(4); } - CreateProjectResult ProjectHubFrame::CreateProject() + void ProjectHubFrame::OpenProject(const Common::Path& inProjectPath) { - if (projectName.empty() || directory.empty() || projectTemplates.empty() - || selectedTemplateIndex < 0 || selectedTemplateIndex >= static_cast(projectTemplates.size())) { - return { .success = false, .error = "Project name, directory and template must not be empty.", .projectPath = {} }; - } - - const std::string templatePath = projectTemplates[selectedTemplateIndex].path; - const Common::Path templateDir(templatePath); - if (!templateDir.Exists() || !templateDir.IsDirectory()) { - return { .success = false, .error = std::format("Project template '{}' does not exist.", templatePath), .projectPath = {} }; - } - - const Common::Path projectDir = Common::Path(directory) / projectName; - if (projectDir.Exists()) { - return { .success = false, .error = std::format("Target directory '{}' already exists.", projectDir.String()), .projectPath = {} }; + const auto project = ProjectService::ValidateProject(inProjectPath); + if (project.IsErr()) { + statusMessage = project.Error(); + return; } - - if (const auto result = ProjectHub::Internal::RenderProjectTemplate(templateDir, projectDir, projectName); - result.IsErr()) { - return { .success = false, .error = result.Error(), .projectPath = {} }; + if (const auto result = recentProjects.Record(project.Value()); result.IsErr()) { + LogWarning(ProjectHub, "{}", result.Error()); } - - TouchRecentProject(projectDir.String()); - SaveRecentProjects(); - LogInfo(ProjectHub, "created project '{}' at '{}'", projectName, projectDir.String()); - return { .success = true, .error = {}, .projectPath = projectDir.String() }; - } - - void ProjectHubFrame::OpenProject(EditorWindow& inWindow, const std::string& inProjectPath, const std::string& inRhiType, bool inGpuDebug, bool inSoftwareGpu) - { - const Common::Path projectDir(inProjectPath); - if (!projectDir.Exists() || !projectDir.IsDirectory()) { - statusMessage = std::format("Project '{}' does not exist.", inProjectPath); + if (const auto result = projectLauncher.Launch(project.Value()); result.IsErr()) { + statusMessage = result.Error(); return; } - - TouchRecentProject(inProjectPath); - SaveRecentProjects(); - - const std::string command = ProjectHub::Internal::LaunchCommand(Core::Paths::ExecutablePath().String(), inProjectPath, inRhiType, inGpuDebug, inSoftwareGpu); - std::ignore = std::system(command.c_str()); - inWindow.RequestClose(); - } - - void ProjectHubFrame::SaveRecentProjects() const - { - recentProjectsFile.Parent().MakeDir(); - Common::JsonSerializeToFile(recentProjectsFile.String(), recentProjects); - } - - void ProjectHubFrame::TouchRecentProject(const std::string& inProjectPath) - { - std::string touchedProjectName = Common::Path(inProjectPath).DirName(); - if (const auto iter = std::ranges::find_if(recentProjects, [&](const RecentProjectInfo& info) -> bool { return info.path == inProjectPath; }); - iter != recentProjects.end()) { - touchedProjectName = iter->name; - recentProjects.erase(iter); - } - recentProjects.emplace_back(RecentProjectInfo { touchedProjectName, inProjectPath }); + statusMessage.clear(); + requestClose = true; } } diff --git a/Editor/Src/ImGui/ImGuiDrawData.cpp b/Editor/Src/ImGui/ImGuiDrawData.cpp new file mode 100644 index 000000000..4485a446d --- /dev/null +++ b/Editor/Src/ImGui/ImGuiDrawData.cpp @@ -0,0 +1,39 @@ +#include + +namespace Editor { + ImGuiDrawData::ImGuiDrawData(const ImDrawData& inDrawData) + { + drawData.Valid = inDrawData.Valid; + drawData.CmdListsCount = inDrawData.CmdListsCount; + drawData.TotalIdxCount = inDrawData.TotalIdxCount; + drawData.TotalVtxCount = inDrawData.TotalVtxCount; + drawData.DisplayPos = inDrawData.DisplayPos; + drawData.DisplaySize = inDrawData.DisplaySize; + drawData.FramebufferScale = inDrawData.FramebufferScale; + drawData.CmdLists.reserve(inDrawData.CmdListsCount); + for (int i = 0; i < inDrawData.CmdListsCount; ++i) { + const ImDrawList& source = *inDrawData.CmdLists[i]; + ImDrawList* cloned = source.CloneOutput(); + drawData.CmdLists.push_back(cloned); + cloned->_CallbacksDataBuf = source._CallbacksDataBuf; + for (ImDrawCmd& command : cloned->CmdBuffer) { + command.TexRef = ImTextureRef(command.TexRef.GetTexID()); + if (command.UserCallbackDataSize > 0) { + command.UserCallbackData = cloned->_CallbacksDataBuf.Data + command.UserCallbackDataOffset; + } + } + } + } + + ImGuiDrawData::~ImGuiDrawData() + { + for (ImDrawList* commandList : drawData.CmdLists) { + IM_DELETE(commandList); + } + } + + ImDrawData& ImGuiDrawData::Get() + { + return drawData; + } +} diff --git a/Editor/Src/ImGui/ImGuiPlatformBackend.cpp b/Editor/Src/ImGui/ImGuiPlatformBackend.cpp new file mode 100644 index 000000000..3755ccd6f --- /dev/null +++ b/Editor/Src/ImGui/ImGuiPlatformBackend.cpp @@ -0,0 +1,71 @@ +#include + +#include +#include + +#include +#include +#include + +namespace Editor { + ImGuiPlatformBackend::ImGuiPlatformBackend(EditorWindow& inWindow) + : window(inWindow) + { + ImGui::GetIO().BackendPlatformName = "ExplosionGLFW"; + keyHandle = window.onKey.BindLambda([](int inKey, int inScancode, int inAction, int inMods) -> void { + ImGuiCompatibility::UpdateKeyModifiers(inMods); + const ImGuiKey key = ImGuiCompatibility::ToImGuiKey(inKey); + if (key != ImGuiKey_None) { + ImGuiIO& io = ImGui::GetIO(); + io.AddKeyEvent(key, inAction != GLFW_RELEASE); + io.SetKeyEventNativeData(key, inKey, inScancode); + } + }); + charHandle = window.onChar.BindLambda([](uint32_t inCodepoint) -> void { + ImGui::GetIO().AddInputCharacter(inCodepoint); + }); + mouseButtonHandle = window.onMouseButton.BindLambda([](int inButton, int inAction, int inMods) -> void { + ImGuiCompatibility::UpdateKeyModifiers(inMods); + if (const auto button = ImGuiCompatibility::ToImGuiMouseButton(inButton)) { + ImGui::GetIO().AddMouseButtonEvent(*button, inAction == GLFW_PRESS); + } + }); + cursorHandle = window.onCursor.BindLambda([](double inX, double inY) -> void { + ImGui::GetIO().AddMousePosEvent(static_cast(inX), static_cast(inY)); + }); + scrollHandle = window.onScroll.BindLambda([](double inX, double inY) -> void { + ImGui::GetIO().AddMouseWheelEvent(static_cast(inX), static_cast(inY)); + }); + focusHandle = window.onFocus.BindLambda([](bool inFocused) -> void { + ImGui::GetIO().AddFocusEvent(inFocused); + }); + } + + ImGuiPlatformBackend::~ImGuiPlatformBackend() + { + window.onKey.Unbind(keyHandle); + window.onChar.Unbind(charHandle); + window.onMouseButton.Unbind(mouseButtonHandle); + window.onCursor.Unbind(cursorHandle); + window.onScroll.Unbind(scrollHandle); + window.onFocus.Unbind(focusHandle); + ImGui::GetIO().BackendPlatformName = nullptr; + } + + void ImGuiPlatformBackend::NewFrame(float inDeltaSeconds) const + { + int width = 0; + int height = 0; + int framebufferWidth = 0; + int framebufferHeight = 0; + glfwGetWindowSize(window.GetNativeWindow(), &width, &height); + glfwGetFramebufferSize(window.GetNativeWindow(), &framebufferWidth, &framebufferHeight); + + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize = ImVec2(static_cast(width), static_cast(height)); + io.DisplayFramebufferScale = ImVec2( + width > 0 ? static_cast(framebufferWidth) / static_cast(width) : 1.0f, + height > 0 ? static_cast(framebufferHeight) / static_cast(height) : 1.0f); + io.DeltaTime = std::max(inDeltaSeconds, 1.0f / 1000.0f); + } +} diff --git a/Editor/Src/ImGui/ImGuiRhiRenderer.cpp b/Editor/Src/ImGui/ImGuiRhiRenderer.cpp new file mode 100644 index 000000000..d1d48e6b6 --- /dev/null +++ b/Editor/Src/ImGui/ImGuiRhiRenderer.cpp @@ -0,0 +1,413 @@ +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +namespace Editor::ImGuiRendering::Internal { + const Common::LinearColor uiOnlyClearColor = Common::LinearColor(0.08f, 0.08f, 0.09f, 1.0f); + constexpr int imguiVertexBufferInitialCapacity = 5000; + constexpr int imguiIndexBufferInitialCapacity = 10000; + constexpr RHI::IndexFormat imguiIndexFormat = sizeof(ImDrawIdx) == 2 + ? RHI::IndexFormat::uint16 + : RHI::IndexFormat::uint32; + + static Render::ShaderCompileOutput CompileImGuiShader( + RHI::Device& inDevice, + const std::string& inEntryPoint, + RHI::ShaderStageBits inStage) + { + Render::ShaderCompileInput input; + input.source = Common::FileUtils::ReadTextFile("../Shader/Editor/ImGui.esl").Unwrap(); + input.entryPoint = inEntryPoint; + input.stage = inStage; + input.includeDirectories.emplace_back("../Shader/Explosion"); + + Render::ShaderCompileOptions options; + options.byteCodeType = inDevice.GetGpu().GetInstance().GetRHIType() == RHI::RHIType::directX12 + ? Render::ShaderByteCodeType::dxil + : Render::ShaderByteCodeType::spirv; + options.withDebugInfo = static_cast(BUILD_CONFIG_DEBUG); // NOLINT + + auto future = Render::ShaderCompiler::Get().Compile(input, options); + future.wait(); + return future.get(); + } +} + +namespace Editor { + ImGuiRhiRenderer::ImGuiRhiRenderer(Runtime::Window& inWindow, Render::RenderThread& inRenderThread) + : window(inWindow) + , renderThread(inRenderThread) + , pipelineFormat(window.GetSwapChainFormat()) + , uiFrameFence(window.GetDevice().CreateFence(true)) + , uiCommandBuffer(window.GetDevice().CreateCommandBuffer(RHI::QueueType::graphics)) + , imguiVertexBufferCapacity(0) + , imguiIndexBufferCapacity(0) + { + ImGui::GetIO().BackendRendererName = "ExplosionRHI"; + CreateImGuiDeviceObjects(); + CreateImGuiDynamicBuffers(ImGuiRendering::Internal::imguiVertexBufferInitialCapacity, ImGuiRendering::Internal::imguiIndexBufferInitialCapacity); + } + + ImGuiRhiRenderer::~ImGuiRhiRenderer() + { + WaitIdle(); + inFlightDrawData.Reset(); + imguiFrameTextureBindGroups.clear(); + ImGui::GetIO().Fonts->SetTexID(ImTextureID_Invalid); + ImGui::GetIO().BackendRendererName = nullptr; + } + + void ImGuiRhiRenderer::NewFrame() + { + if (pipelineFormat != window.GetSwapChainFormat()) { + WaitIdle(); + pipelineFormat = window.GetSwapChainFormat(); + CreateImGuiDeviceObjects(); + } + } + + void ImGuiRhiRenderer::Submit(const ImDrawData& inDrawData) + { + auto drawData = Common::MakeShared(inDrawData); + renderThread.EmplaceTask([this, drawData]() -> void { + RenderFrame(drawData); + }); + } + + void ImGuiRhiRenderer::WaitIdle() const + { + renderThread.Flush(); + window.WaitRenderingIdle(); + } + + void ImGuiRhiRenderer::RenderFrame(const Common::SharedPtr& inDrawData) + { + uiFrameFence->Wait(); + inFlightDrawData = inDrawData; + window.AcquireBackTexture(); + uiFrameFence->Reset(); + + RenderUiPass(inFlightDrawData->Get()); + window.GetDevice().GetQueue(RHI::QueueType::graphics, 0)->Submit( + uiCommandBuffer.Get(), + RHI::QueueSubmitInfo() + .AddWaitSemaphore(window.GetImageReadySemaphore()) + .AddSignalSemaphore(window.GetRenderFinishedSemaphore()) + .SetSignalFence(uiFrameFence.Get())); + window.Present(); + } + + void ImGuiRhiRenderer::RenderUiPass(ImDrawData& inDrawData) + { + auto* target = window.GetTexture(); + auto* targetView = window.GetRenderTargetView(); + Assert(target != nullptr && targetView != nullptr); + + const auto recorder = uiCommandBuffer->Begin(); + recorder->ResourceBarrier(RHI::Barrier::Transition(target, window.GetCurrentBackTextureState(), RHI::TextureState::renderTarget)); + const auto rasterRecorder = recorder->BeginRasterPass( + RHI::RasterPassBeginInfo() + .AddColorAttachment(RHI::ColorAttachment(targetView, RHI::LoadOp::clear, RHI::StoreOp::store, ImGuiRendering::Internal::uiOnlyClearColor))); + RenderImGuiDrawData(inDrawData, *rasterRecorder); + rasterRecorder->EndPass(); + recorder->ResourceBarrier(RHI::Barrier::Transition(target, RHI::TextureState::renderTarget, RHI::TextureState::present)); + recorder->End(); + } + + void ImGuiRhiRenderer::RenderImGuiDrawData(ImDrawData& inDrawData, RHI::RasterPassCommandRecorder& inRecorder) + { + imguiFrameTextureBindGroups.clear(); + if (inDrawData.TotalVtxCount <= 0 || inDrawData.TotalIdxCount <= 0) { + return; + } + + if (inDrawData.TotalVtxCount > imguiVertexBufferCapacity || inDrawData.TotalIdxCount > imguiIndexBufferCapacity) { + CreateImGuiDynamicBuffers( + std::max(inDrawData.TotalVtxCount, imguiVertexBufferCapacity * 2), + std::max(inDrawData.TotalIdxCount, imguiIndexBufferCapacity * 2)); + } + + UpdateImGuiBuffers(inDrawData); + UpdateImGuiPassParams(inDrawData); + + const auto framebufferWidth = static_cast(inDrawData.DisplaySize.x * inDrawData.FramebufferScale.x); + const auto framebufferHeight = static_cast(inDrawData.DisplaySize.y * inDrawData.FramebufferScale.y); + if (framebufferWidth == 0 || framebufferHeight == 0) { + return; + } + + inRecorder.SetPipeline(imguiPipeline.Get()); + inRecorder.SetVertexBuffer(0, imguiVertexBufferView.Get()); + inRecorder.SetIndexBuffer(imguiIndexBufferView.Get()); + inRecorder.SetPrimitiveTopology(RHI::PrimitiveTopology::triangleList); + inRecorder.SetViewport(0.0f, 0.0f, static_cast(framebufferWidth), static_cast(framebufferHeight), 0.0f, 1.0f); + + const ImVec2 clipOffset = inDrawData.DisplayPos; + const ImVec2 clipScale = inDrawData.FramebufferScale; + int globalVertexOffset = 0; + int globalIndexOffset = 0; + for (int commandListIndex = 0; commandListIndex < inDrawData.CmdListsCount; commandListIndex++) { + const ImDrawList* commandList = inDrawData.CmdLists[commandListIndex]; + for (int commandIndex = 0; commandIndex < commandList->CmdBuffer.Size; commandIndex++) { + const ImDrawCmd* command = &commandList->CmdBuffer[commandIndex]; + if (command->UserCallback != nullptr) { + command->UserCallback(commandList, command); + continue; + } + + ImVec2 clipMin( + (command->ClipRect.x - clipOffset.x) * clipScale.x, + (command->ClipRect.y - clipOffset.y) * clipScale.y); + ImVec2 clipMax( + (command->ClipRect.z - clipOffset.x) * clipScale.x, + (command->ClipRect.w - clipOffset.y) * clipScale.y); + clipMin.x = std::clamp(clipMin.x, 0.0f, static_cast(framebufferWidth)); + clipMin.y = std::clamp(clipMin.y, 0.0f, static_cast(framebufferHeight)); + clipMax.x = std::clamp(clipMax.x, 0.0f, static_cast(framebufferWidth)); + clipMax.y = std::clamp(clipMax.y, 0.0f, static_cast(framebufferHeight)); + if (clipMax.x <= clipMin.x || clipMax.y <= clipMin.y) { + continue; + } + + inRecorder.SetScissor( + static_cast(clipMin.x), + static_cast(clipMin.y), + static_cast(clipMax.x), + static_cast(clipMax.y)); + ImTextureID textureId = command->GetTexID(); + auto* textureView = textureId == ImTextureID_Invalid + ? imguiFontTextureView.Get() + : reinterpret_cast(static_cast(textureId)); + Assert(textureView != nullptr); + inRecorder.SetBindGroup(0, GetOrCreateImGuiTextureBindGroup(*textureView)); + inRecorder.DrawIndexed( + command->ElemCount, + 1, + command->IdxOffset + globalIndexOffset, + command->VtxOffset + globalVertexOffset, + 0); + } + globalIndexOffset += commandList->IdxBuffer.Size; + globalVertexOffset += commandList->VtxBuffer.Size; + } + } + + void ImGuiRhiRenderer::CreateImGuiDeviceObjects() + { + RHI::Device& device = window.GetDevice(); + imguiFrameTextureBindGroups.clear(); + imguiVertexShaderCompileOutput = ImGuiRendering::Internal::CompileImGuiShader(device, "VSMain", RHI::ShaderStageBits::sVertex); + imguiPixelShaderCompileOutput = ImGuiRendering::Internal::CompileImGuiShader(device, "PSMain", RHI::ShaderStageBits::sPixel); + imguiVertexShader = device.CreateShaderModule(RHI::ShaderModuleCreateInfo("VSMain", imguiVertexShaderCompileOutput.byteCode)); + imguiPixelShader = device.CreateShaderModule(RHI::ShaderModuleCreateInfo("PSMain", imguiPixelShaderCompileOutput.byteCode)); + + CreateImGuiFontTexture(); + + imguiPassParamsBuffer = device.CreateBuffer( + RHI::BufferCreateInfo() + .SetSize(sizeof(Common::Internal::ImGuiPassParams)) + .SetUsages(RHI::BufferUsageBits::uniform | RHI::BufferUsageBits::mapWrite) + .SetInitialState(RHI::BufferState::staging) + .SetDebugName("imguiPassParams")); + imguiPassParamsBufferView = imguiPassParamsBuffer->CreateBufferView( + RHI::BufferViewCreateInfo() + .SetType(RHI::BufferViewType::uniformBinding) + .SetSizeInBytes(sizeof(Common::Internal::ImGuiPassParams)) + .SetOffsetInBytes(0)); + + imguiBindGroupLayout = device.CreateBindGroupLayout( + RHI::BindGroupLayoutCreateInfo(0, "imguiBindGroupLayout") + .AddEntry(RHI::BindGroupLayoutEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageTex").second, RHI::ShaderStageBits::sPixel)) + .AddEntry(RHI::BindGroupLayoutEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageSampler").second, RHI::ShaderStageBits::sPixel)) + .AddEntry(RHI::BindGroupLayoutEntry(imguiVertexShaderCompileOutput.reflectionData.QueryResourceBindingChecked("passParams").second, RHI::ShaderStageBits::sVertex))); + imguiPipelineLayout = device.CreatePipelineLayout( + RHI::PipelineLayoutCreateInfo() + .AddBindGroupLayout(imguiBindGroupLayout.Get())); + + const RHI::BlendComponent colorBlend(RHI::BlendOp::opAdd, RHI::BlendFactor::srcAlpha, RHI::BlendFactor::oneMinusSrcAlpha); + const RHI::BlendComponent alphaBlend(RHI::BlendOp::opAdd, RHI::BlendFactor::one, RHI::BlendFactor::oneMinusSrcAlpha); + const RHI::ColorTargetState colorTarget(window.GetSwapChainFormat(), RHI::ColorWriteBits::all, true, colorBlend, alphaBlend); + + imguiPipeline = device.CreateRasterPipeline( + RHI::RasterPipelineCreateInfo(imguiPipelineLayout.Get()) + .SetVertexShader(imguiVertexShader.Get()) + .SetPixelShader(imguiPixelShader.Get()) + .SetVertexState( + RHI::VertexState() + .AddVertexBufferLayout( + RHI::VertexBufferLayout(RHI::VertexStepMode::perVertex, sizeof(ImDrawVert)) + .AddAttribute(RHI::VertexAttribute(imguiVertexShaderCompileOutput.reflectionData.QueryVertexBindingChecked("POSITION"), RHI::VertexFormat::float32X2, offsetof(ImDrawVert, pos))) + .AddAttribute(RHI::VertexAttribute(imguiVertexShaderCompileOutput.reflectionData.QueryVertexBindingChecked("TEXCOORD"), RHI::VertexFormat::float32X2, offsetof(ImDrawVert, uv))) + .AddAttribute(RHI::VertexAttribute(imguiVertexShaderCompileOutput.reflectionData.QueryVertexBindingChecked("COLOR"), RHI::VertexFormat::unorm8X4, offsetof(ImDrawVert, col))))) + .SetFragmentState(RHI::FragmentState().AddColorTarget(colorTarget)) + .SetPrimitiveState(RHI::PrimitiveState(RHI::PrimitiveTopologyType::triangle, RHI::FillMode::solid, ImGuiRendering::Internal::imguiIndexFormat, RHI::FrontFace::ccw, RHI::CullMode::none)) + .SetDepthStencilState(RHI::DepthStencilState())); + } + + void ImGuiRhiRenderer::CreateImGuiFontTexture() + { + RHI::Device& device = window.GetDevice(); + + unsigned char* pixels = nullptr; + int width = 0; + int height = 0; + ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + + imguiFontTexture = device.CreateTexture( + RHI::TextureCreateInfo() + .SetType(RHI::TextureType::t2D) + .SetWidth(static_cast(width)) + .SetHeight(static_cast(height)) + .SetDepthOrArraySize(1) + .SetFormat(RHI::PixelFormat::rgba8Unorm) + .SetUsages(RHI::TextureUsageBits::copyDst | RHI::TextureUsageBits::textureBinding) + .SetMipLevels(1) + .SetSamples(1) + .SetInitialState(RHI::TextureState::undefined) + .SetDebugName("imguiFontTexture")); + imguiFontTextureView = imguiFontTexture->CreateTextureView( + RHI::TextureViewCreateInfo() + .SetDimension(RHI::TextureViewDimension::tv2D) + .SetMipLevels(0, 1) + .SetArrayLayers(0, 1) + .SetAspect(RHI::TextureAspect::color) + .SetType(RHI::TextureViewType::textureBinding)); + imguiImageSampler = device.CreateSampler( + RHI::SamplerCreateInfo() + .SetAddressModeU(RHI::AddressMode::clampToEdge) + .SetAddressModeV(RHI::AddressMode::clampToEdge) + .SetAddressModeW(RHI::AddressMode::clampToEdge) + .SetMagFilter(RHI::FilterMode::linear) + .SetMinFilter(RHI::FilterMode::linear) + .SetMipFilter(RHI::FilterMode::linear) + .SetDebugName("imguiImageSampler")); + + const auto copyFootprint = device.GetTextureSubResourceCopyFootprint(*imguiFontTexture, RHI::TextureSubResourceInfo()); + auto stagingBuffer = device.CreateBuffer( + RHI::BufferCreateInfo() + .SetSize(static_cast(copyFootprint.totalBytes)) + .SetUsages(RHI::BufferUsageBits::mapWrite | RHI::BufferUsageBits::copySrc) + .SetInitialState(RHI::BufferState::staging) + .SetDebugName("imguiFontUpload")); + auto* mapped = stagingBuffer->Map(RHI::MapMode::write, 0, copyFootprint.totalBytes); + const size_t srcRowPitch = static_cast(width) * copyFootprint.bytesPerPixel; + for (int row = 0; row < height; row++) { + const auto* src = pixels + static_cast(row) * srcRowPitch; + auto* dst = static_cast(mapped) + static_cast(row) * copyFootprint.rowPitch; + memcpy(dst, src, srcRowPitch); + } + stagingBuffer->Unmap(); + + const auto commandBuffer = device.CreateCommandBuffer(RHI::QueueType::graphics); + const auto commandRecorder = commandBuffer->Begin(); + { + const auto copyRecorder = commandRecorder->BeginCopyPass(); + copyRecorder->ResourceBarrier(RHI::Barrier::Transition(imguiFontTexture.Get(), RHI::TextureState::undefined, RHI::TextureState::copyDst)); + copyRecorder->CopyBufferToTexture( + stagingBuffer.Get(), + imguiFontTexture.Get(), + RHI::BufferTextureCopyInfo( + 0, + RHI::TextureSubResourceInfo(), + Common::UVec3Consts::zero, + Common::UVec3(static_cast(width), static_cast(height), 1), + copyFootprint.rowPitch, + copyFootprint.slicePitch)); + copyRecorder->ResourceBarrier(RHI::Barrier::Transition(imguiFontTexture.Get(), RHI::TextureState::copyDst, RHI::TextureState::shaderReadOnly)); + copyRecorder->EndPass(); + } + commandRecorder->End(); + + const auto fence = device.CreateFence(false); + device.GetQueue(RHI::QueueType::graphics, 0)->Submit(commandBuffer.Get(), RHI::QueueSubmitInfo().SetSignalFence(fence.Get())); + fence->Wait(); + ImGui::GetIO().Fonts->SetTexID(static_cast(reinterpret_cast(imguiFontTextureView.Get()))); + } + + void ImGuiRhiRenderer::CreateImGuiDynamicBuffers(int inVertexCount, int inIndexCount) + { + RHI::Device& device = window.GetDevice(); + imguiVertexBufferCapacity = std::max(1, inVertexCount); + imguiIndexBufferCapacity = std::max(1, inIndexCount); + + const uint32_t vertexBufferSize = static_cast(imguiVertexBufferCapacity * sizeof(ImDrawVert)); + imguiVertexBuffer = device.CreateBuffer( + RHI::BufferCreateInfo() + .SetSize(vertexBufferSize) + .SetUsages(RHI::BufferUsageBits::vertex | RHI::BufferUsageBits::mapWrite | RHI::BufferUsageBits::copySrc) + .SetInitialState(RHI::BufferState::staging) + .SetDebugName("imguiVertexBuffer")); + imguiVertexBufferView = imguiVertexBuffer->CreateBufferView( + RHI::BufferViewCreateInfo() + .SetType(RHI::BufferViewType::vertex) + .SetSizeInBytes(vertexBufferSize) + .SetOffsetInBytes(0) + .SetExtendVertex(sizeof(ImDrawVert))); + + const uint32_t indexBufferSize = static_cast(imguiIndexBufferCapacity * sizeof(ImDrawIdx)); + imguiIndexBuffer = device.CreateBuffer( + RHI::BufferCreateInfo() + .SetSize(indexBufferSize) + .SetUsages(RHI::BufferUsageBits::index | RHI::BufferUsageBits::mapWrite | RHI::BufferUsageBits::copySrc) + .SetInitialState(RHI::BufferState::staging) + .SetDebugName("imguiIndexBuffer")); + imguiIndexBufferView = imguiIndexBuffer->CreateBufferView( + RHI::BufferViewCreateInfo() + .SetType(RHI::BufferViewType::index) + .SetSizeInBytes(indexBufferSize) + .SetOffsetInBytes(0) + .SetExtendIndex(ImGuiRendering::Internal::imguiIndexFormat)); + } + + void ImGuiRhiRenderer::UpdateImGuiBuffers(ImDrawData& inDrawData) + { + auto* vertexDst = static_cast(imguiVertexBuffer->Map(RHI::MapMode::write, 0, inDrawData.TotalVtxCount * sizeof(ImDrawVert))); + auto* indexDst = static_cast(imguiIndexBuffer->Map(RHI::MapMode::write, 0, inDrawData.TotalIdxCount * sizeof(ImDrawIdx))); + for (int i = 0; i < inDrawData.CmdListsCount; i++) { + const ImDrawList* commandList = inDrawData.CmdLists[i]; + memcpy(vertexDst, commandList->VtxBuffer.Data, static_cast(commandList->VtxBuffer.Size) * sizeof(ImDrawVert)); + memcpy(indexDst, commandList->IdxBuffer.Data, static_cast(commandList->IdxBuffer.Size) * sizeof(ImDrawIdx)); + vertexDst += commandList->VtxBuffer.Size; + indexDst += commandList->IdxBuffer.Size; + } + imguiVertexBuffer->Unmap(); + imguiIndexBuffer->Unmap(); + } + + void ImGuiRhiRenderer::UpdateImGuiPassParams(const ImDrawData& inDrawData) + { + const Common::Internal::ImGuiPassParams params { + Common::FVec2(inDrawData.DisplayPos.x, inDrawData.DisplayPos.y), + Common::FVec2(inDrawData.DisplaySize.x, inDrawData.DisplaySize.y) + }; + auto* data = imguiPassParamsBuffer->Map(RHI::MapMode::write, 0, sizeof(Common::Internal::ImGuiPassParams)); + memcpy(data, ¶ms, sizeof(Common::Internal::ImGuiPassParams)); + imguiPassParamsBuffer->Unmap(); + } + + RHI::BindGroup* ImGuiRhiRenderer::GetOrCreateImGuiTextureBindGroup(RHI::TextureView& inTextureView) + { + if (const auto iter = imguiFrameTextureBindGroups.find(&inTextureView); + iter != imguiFrameTextureBindGroups.end()) { + return iter->second.Get(); + } + + auto bindGroup = window.GetDevice().CreateBindGroup( + RHI::BindGroupCreateInfo(imguiBindGroupLayout.Get(), "imguiBindGroup") + .AddEntry(RHI::BindGroupEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageTex").second, RHI::ShaderStageBits::sPixel, &inTextureView)) + .AddEntry(RHI::BindGroupEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageSampler").second, RHI::ShaderStageBits::sPixel, imguiImageSampler.Get())) + .AddEntry(RHI::BindGroupEntry(imguiVertexShaderCompileOutput.reflectionData.QueryResourceBindingChecked("passParams").second, RHI::ShaderStageBits::sVertex, imguiPassParamsBufferView.Get()))); + auto* result = bindGroup.Get(); + imguiFrameTextureBindGroups.emplace(&inTextureView, std::move(bindGroup)); + return result; + } + +} diff --git a/Editor/Src/Project/ProjectLauncher.cpp b/Editor/Src/Project/ProjectLauncher.cpp new file mode 100644 index 000000000..700c04359 --- /dev/null +++ b/Editor/Src/Project/ProjectLauncher.cpp @@ -0,0 +1,21 @@ +#include + +namespace Editor { + ProjectLauncher::ProjectLauncher(EditorLaunchOptions inOptions, LaunchProcess inLaunchProcess) + : options(std::move(inOptions)) + , launchProcess(std::move(inLaunchProcess)) + { + } + + Common::Result ProjectLauncher::Launch(const Common::Path& inProjectPath) const + { + std::vector arguments { "-project", inProjectPath.String(), "-rhi", options.rhiType }; + if (options.gpuDebug) { + arguments.emplace_back("-gpuDebug"); + } + if (options.softwareGpu) { + arguments.emplace_back("-softwareGpu"); + } + return launchProcess(options.executablePath, arguments); + } +} diff --git a/Editor/Src/Project/ProjectService.cpp b/Editor/Src/Project/ProjectService.cpp new file mode 100644 index 000000000..097001426 --- /dev/null +++ b/Editor/Src/Project/ProjectService.cpp @@ -0,0 +1,122 @@ +#include +#include +#include +#include + +#include +#include + +namespace Editor::Project::Internal { + constexpr std::string_view templateFileExtension = ".tpl"; + constexpr std::string_view cmakeMinVersion = "3.25"; + + static bool IsValidProjectName(const std::string& inName) + { + return !inName.empty() && std::ranges::all_of(inName, [](unsigned char inCharacter) -> bool { + return (inCharacter >= 'a' && inCharacter <= 'z') || (inCharacter >= 'A' && inCharacter <= 'Z') + || (inCharacter >= '0' && inCharacter <= '9') || inCharacter == '_' || inCharacter == '-'; + }); + } + + static Common::Result RenderProjectTemplate(const Common::Path& inTemplateDirectory, const Common::Path& inProjectDirectory, const std::string& inName) + { + Common::TemplateEngine templateEngine; + templateEngine.Set("projectName", inName).Set("cmakeMinVersion", std::string(cmakeMinVersion)); + const std::filesystem::path templateDirectory(inTemplateDirectory.String()); + const std::filesystem::path projectDirectory(inProjectDirectory.String()); + for (const auto& entry : std::filesystem::recursive_directory_iterator(templateDirectory)) { + if (entry.is_symlink()) { + return Common::Err(std::string("Project templates cannot contain symbolic links.")); + } + const auto relativePath = entry.path().lexically_relative(templateDirectory); + auto destination = projectDirectory / relativePath; + if (entry.is_directory()) { + std::filesystem::create_directories(destination); + continue; + } + std::filesystem::create_directories(destination.parent_path()); + if (entry.path().extension() == templateFileExtension) { + destination.replace_extension(); + if (auto result = templateEngine.RenderFileTo(entry.path().string(), destination.string()); result.IsErr()) { + return result; + } + } else { + std::filesystem::copy_file(entry.path(), destination); + } + } + return Common::Ok(); + } +} + +namespace Editor { + ProjectService::ProjectService(Common::Path inTemplatesDirectory) + : templatesDirectory(std::move(inTemplatesDirectory)) + { + } + + Common::Result, std::string> ProjectService::ListTemplates() const + { + try { + std::vector result; + for (const auto& entry : std::filesystem::directory_iterator(templatesDirectory.String())) { + if (entry.is_directory() && std::filesystem::is_regular_file(entry.path() / "CMakeLists.txt.tpl") + && std::filesystem::is_directory(entry.path() / "Game")) { + result.emplace_back(ProjectTemplateInfo { entry.path().filename().string(), Common::Path(entry.path()) }); + } + } + std::ranges::sort(result, {}, &ProjectTemplateInfo::name); + return Common::Ok(std::move(result)); + } catch (const std::filesystem::filesystem_error& error) { + return Common::Err(std::format("Could not list project templates: {}", error.what())); + } + } + + Common::Result ProjectService::CreateProject(const CreateProjectDesc& inDesc) const + { + if (!Project::Internal::IsValidProjectName(inDesc.name) || inDesc.parentDirectory.Empty() || inDesc.templateDirectory.Empty()) { + return Common::Err(std::string("Choose a location and template. Project names may contain letters, digits, '_' and '-'.")); + } + + std::filesystem::path projectDirectory; + bool created = false; + auto cleanup = [&]() -> void { + if (created) { + std::error_code error; + std::filesystem::remove_all(projectDirectory, error); + } + }; + try { + const std::filesystem::path templateDirectory(inDesc.templateDirectory.String()); + if (!std::filesystem::is_regular_file(templateDirectory / "CMakeLists.txt.tpl") || !std::filesystem::is_directory(templateDirectory / "Game")) { + return Common::Err(std::string("The selected template must contain CMakeLists.txt.tpl and a Game directory.")); + } + projectDirectory = std::filesystem::absolute(std::filesystem::path(inDesc.parentDirectory.String()) / inDesc.name).lexically_normal(); + std::filesystem::create_directories(projectDirectory.parent_path()); + created = std::filesystem::create_directory(projectDirectory); + if (!created) { + return Common::Err(std::format("Target directory '{}' already exists.", projectDirectory.string())); + } + if (auto result = Project::Internal::RenderProjectTemplate(inDesc.templateDirectory, Common::Path(projectDirectory), inDesc.name); result.IsErr()) { + cleanup(); + return Common::Err(result.Error()); + } + return Common::Ok(Common::Path(projectDirectory)); + } catch (const std::filesystem::filesystem_error& error) { + cleanup(); + return Common::Err(std::format("Could not create project: {}", error.what())); + } + } + + Common::Result ProjectService::ValidateProject(const Common::Path& inPath) + { + try { + const std::filesystem::path path(inPath.String()); + if (!std::filesystem::is_regular_file(path / "CMakeLists.txt") || !std::filesystem::is_directory(path / "Game")) { + return Common::Err(std::string("Choose an Explosion project containing CMakeLists.txt and a Game directory.")); + } + return Common::Ok(Common::Path(std::filesystem::canonical(path))); + } catch (const std::filesystem::filesystem_error& error) { + return Common::Err(std::format("Could not open project: {}", error.what())); + } + } +} diff --git a/Editor/Src/Project/RecentProjectStore.cpp b/Editor/Src/Project/RecentProjectStore.cpp new file mode 100644 index 000000000..a7f57d5e2 --- /dev/null +++ b/Editor/Src/Project/RecentProjectStore.cpp @@ -0,0 +1,84 @@ +#include +#include +#include + +#include +#include + +namespace Editor { + RecentProjectStore::RecentProjectStore(Common::Path inFile) + : file(std::move(inFile)) + { + } + + Common::Result RecentProjectStore::Load() + { + try { + if (!file.Exists()) { + projects.clear(); + return Common::Ok(); + } + auto result = Common::FileUtils::ReadJsonFile(file.String()); + if (result.IsErr()) { + return Common::Err(result.Error()); + } + const auto& document = result.Value(); + if (!document.IsArray()) { + return Common::Err(std::string("Recent projects must be a JSON array.")); + } + std::vector loaded; + for (const auto& entry : document.GetArray()) { + if (!entry.IsObject() || !entry.HasMember("path") || !entry["path"].IsString() + || (entry.HasMember("name") && !entry["name"].IsString())) { + return Common::Err(std::string("Invalid recent project entry.")); + } + const std::string path = entry["path"].GetString(); + loaded.emplace_back(RecentProjectInfo { entry.HasMember("name") ? entry["name"].GetString() : Common::Path(path).DirName(), path }); + } + projects = std::move(loaded); + return Common::Ok(); + } catch (const std::filesystem::filesystem_error& error) { + return Common::Err(std::format("Could not load recent projects: {}", error.what())); + } + } + + Common::Result RecentProjectStore::Record(const Common::Path& inProjectPath) + { + try { + const Common::Path projectPath = inProjectPath.Canonical(); + std::vector updated = projects; + std::string name = projectPath.DirName(); + std::erase_if(updated, [&](const RecentProjectInfo& inProject) -> bool { + std::error_code error; + const bool same = inProject.path == projectPath.String() || std::filesystem::equivalent(inProject.path, projectPath.String(), error); + if (same) { + name = inProject.name; + } + return same; + }); + updated.emplace_back(RecentProjectInfo { name, projectPath.String() }); + + rapidjson::Document document; + document.SetArray(); + auto& allocator = document.GetAllocator(); + for (const auto& project : updated) { + rapidjson::Value entry(rapidjson::kObjectType); + entry.AddMember("name", rapidjson::Value(project.name.c_str(), allocator), allocator); + entry.AddMember("path", rapidjson::Value(project.path.c_str(), allocator), allocator); + document.PushBack(entry, allocator); + } + if (auto result = Common::FileUtils::WriteJsonFile(file.String(), document); result.IsErr()) { + return result; + } + projects = std::move(updated); + return Common::Ok(); + } catch (const std::filesystem::filesystem_error& error) { + return Common::Err(std::format("Could not save recent projects: {}", error.what())); + } + } + + const std::vector& RecentProjectStore::Projects() const + { + return projects; + } +} diff --git a/Editor/Src/SceneClient.cpp b/Editor/Src/SceneClient.cpp index c0ad230c7..c09d97803 100644 --- a/Editor/Src/SceneClient.cpp +++ b/Editor/Src/SceneClient.cpp @@ -315,7 +315,7 @@ namespace Editor { }); }); if (window != nullptr) { - glfwSetInputMode(window->GetNativeWindow(), GLFW_CURSOR, GLFW_CURSOR_DISABLED); + window->SetCursorCaptured(true); } } @@ -335,7 +335,7 @@ namespace Editor { }); }); if (window != nullptr) { - glfwSetInputMode(window->GetNativeWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); + window->SetCursorCaptured(false); } } diff --git a/Editor/Test/ImGuiDrawDataTest.cpp b/Editor/Test/ImGuiDrawDataTest.cpp new file mode 100644 index 000000000..4faab7d97 --- /dev/null +++ b/Editor/Test/ImGuiDrawDataTest.cpp @@ -0,0 +1,67 @@ +#include + +#include +#include + +namespace Editor::Test { + TEST(ImGuiDrawDataTest, SnapshotsTextureIdsAndOwnedCallbackPayloads) + { + ImTextureData texture; + texture.SetTexID(123); + ImDrawList source(nullptr); + source._CallbacksDataBuf.resize(sizeof(int)); + const int originalValue = 42; + std::memcpy(source._CallbacksDataBuf.Data, &originalValue, sizeof(int)); + ImDrawCmd command; + command.TexRef = texture.GetTexRef(); + command.UserCallback = [](const ImDrawList*, const ImDrawCmd*) -> void {}; + command.UserCallbackData = source._CallbacksDataBuf.Data; + command.UserCallbackDataSize = sizeof(int); + command.UserCallbackDataOffset = 0; + source.CmdBuffer.push_back(command); + ImDrawData sourceData; + sourceData.CmdListsCount = 1; + sourceData.CmdLists.push_back(&source); + + ImGuiDrawData snapshot(sourceData); + texture.SetTexID(456); + const int changedValue = 99; + std::memcpy(source._CallbacksDataBuf.Data, &changedValue, sizeof(int)); + const ImDrawCmd& cloned = snapshot.Get().CmdLists[0]->CmdBuffer[0]; + EXPECT_EQ(cloned.GetTexID(), 123); + EXPECT_EQ(cloned.TexRef._TexData, nullptr); + EXPECT_NE(cloned.UserCallbackData, command.UserCallbackData); + int clonedValue = 0; + std::memcpy(&clonedValue, cloned.UserCallbackData, sizeof(int)); + EXPECT_EQ(clonedValue, originalValue); + } + + TEST(ImGuiDrawDataTest, KeepsClonedCommandsAfterTheOriginalFrameIsReused) + { + ImGuiContext* context = ImGui::CreateContext(); + ImGuiIO& io = ImGui::GetIO(); + io.IniFilename = nullptr; + io.DisplaySize = ImVec2(640.0f, 480.0f); + unsigned char* pixels = nullptr; + int width = 0; + int height = 0; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + + ImGui::NewFrame(); + ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(10.0f, 20.0f), ImVec2(30.0f, 40.0f), IM_COL32_WHITE); + ImGui::Render(); + { + ImGuiDrawData snapshot(*ImGui::GetDrawData()); + ASSERT_EQ(snapshot.Get().CmdListsCount, 1); + EXPECT_NE(snapshot.Get().CmdLists[0], ImGui::GetDrawData()->CmdLists[0]); + const int vertexCount = snapshot.Get().TotalVtxCount; + ImGui::NewFrame(); + ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(100.0f, 200.0f), ImVec2(300.0f, 400.0f), IM_COL32_WHITE); + ImGui::Render(); + EXPECT_EQ(snapshot.Get().TotalVtxCount, vertexCount); + EXPECT_FLOAT_EQ(snapshot.Get().CmdLists[0]->VtxBuffer[0].pos.x, 10.0f); + EXPECT_FLOAT_EQ(snapshot.Get().CmdLists[0]->VtxBuffer[0].pos.y, 20.0f); + } + ImGui::DestroyContext(context); + } +} diff --git a/Editor/Test/ProjectTest.cpp b/Editor/Test/ProjectTest.cpp new file mode 100644 index 000000000..a185346e1 --- /dev/null +++ b/Editor/Test/ProjectTest.cpp @@ -0,0 +1,169 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Editor::Test { + class ProjectTest : public testing::Test { + protected: + void SetUp() override; + void TearDown() override; + void WriteFile(const std::filesystem::path& inPath, const std::string& inText) const; + CreateProjectDesc CreateDesc(const std::string& inName) const; + + std::filesystem::path directory; + std::filesystem::path templates; + std::filesystem::path projectTemplate; + }; +} + +namespace Editor::Test { + void ProjectTest::SetUp() + { + const auto uniqueId = std::chrono::steady_clock::now().time_since_epoch().count(); + directory = std::filesystem::temp_directory_path() / std::format("ExplosionProjectTest-{}", uniqueId); + templates = directory / "Templates"; + projectTemplate = templates / "Default"; + WriteFile(projectTemplate / "CMakeLists.txt.tpl", "cmake_minimum_required(VERSION @cmakeMinVersion@)\nproject(@projectName@)\n"); + WriteFile(projectTemplate / "Game" / "Src" / "Main.cpp", "int main() { return 0; }\n"); + } + + void ProjectTest::TearDown() + { + std::error_code error; + std::filesystem::remove_all(directory, error); + } + + void ProjectTest::WriteFile(const std::filesystem::path& inPath, const std::string& inText) const + { + std::filesystem::create_directories(inPath.parent_path()); + std::ofstream stream(inPath, std::ios::binary); + stream << inText; + } + + CreateProjectDesc ProjectTest::CreateDesc(const std::string& inName) const + { + return { inName, Common::Path(directory / "Projects with spaces"), Common::Path(projectTemplate) }; + } + + TEST_F(ProjectTest, CreatesAValidatedProjectFromTemplates) + { + ProjectService service { Common::Path(templates) }; + const auto result = service.CreateProject(CreateDesc("MyProject")); + ASSERT_TRUE(result.IsOk()) << result.Error(); + const auto project = result.Value(); + EXPECT_TRUE(ProjectService::ValidateProject(project).IsOk()); + EXPECT_EQ(Common::FileUtils::ReadTextFile((project / "CMakeLists.txt").String()).Unwrap(), "cmake_minimum_required(VERSION 3.25)\nproject(MyProject)\n"); + EXPECT_EQ(Common::FileUtils::ReadTextFile((project / "Game/Src/Main.cpp").String()).Unwrap(), "int main() { return 0; }\n"); + EXPECT_FALSE((project / "CMakeLists.txt.tpl").Exists()); + } + + TEST_F(ProjectTest, DoesNotOverwriteExistingProjectsOrAllowPathNames) + { + ProjectService service { Common::Path(templates) }; + const auto result = service.CreateProject(CreateDesc("Existing")); + ASSERT_TRUE(result.IsOk()); + WriteFile(std::filesystem::path(result.Value().String()) / "keep.txt", "keep"); + EXPECT_TRUE(service.CreateProject(CreateDesc("Existing")).IsErr()); + EXPECT_EQ(Common::FileUtils::ReadTextFile((result.Value() / "keep.txt").String()).Unwrap(), "keep"); + EXPECT_TRUE(service.CreateProject(CreateDesc("../Escape")).IsErr()); + EXPECT_TRUE(service.CreateProject(CreateDesc("My Project")).IsErr()); + EXPECT_TRUE(service.CreateProject(CreateDesc("")).IsErr()); + } + + TEST_F(ProjectTest, RollsBackAnIncompleteProjectWhenRenderingFails) + { + WriteFile(projectTemplate / "Game" / "Broken.tpl", "@missingVariable@"); + ProjectService service { Common::Path(templates) }; + EXPECT_TRUE(service.CreateProject(CreateDesc("Broken")).IsErr()); + EXPECT_FALSE((CreateDesc("Broken").parentDirectory / "Broken").Exists()); + std::filesystem::remove(projectTemplate / "Game" / "Broken.tpl"); + EXPECT_TRUE(service.CreateProject(CreateDesc("Broken")).IsOk()); + } + + TEST_F(ProjectTest, RejectsDirectoriesWithoutTheProjectStructure) + { + EXPECT_TRUE(ProjectService::ValidateProject(Common::Path(directory)).IsErr()); + EXPECT_TRUE(ProjectService::ValidateProject(Common::Path(directory / "Missing")).IsErr()); + ProjectService service { Common::Path(templates) }; + WriteFile(templates / "Invalid" / "readme.txt", "not a template"); + const auto result = service.ListTemplates(); + ASSERT_TRUE(result.IsOk()); + ASSERT_EQ(result.Value().size(), 1); + EXPECT_EQ(result.Value().front().name, "Default"); + } + + TEST_F(ProjectTest, RecentProjectsPreserveLegacyJsonAndDeduplicateCanonicalPaths) + { + const auto firstProject = directory / "First"; + const auto secondProject = directory / "Second"; + std::filesystem::create_directory(firstProject); + std::filesystem::create_directory(secondProject); + const Common::Path storeFile(directory / "RecentProjects.json"); + RecentProjectStore store(storeFile); + ASSERT_TRUE(store.Load().IsOk()); + ASSERT_TRUE(store.Record(Common::Path(firstProject)).IsOk()); + ASSERT_TRUE(store.Record(Common::Path(secondProject)).IsOk()); + ASSERT_TRUE(store.Record(Common::Path(firstProject / ".")).IsOk()); + ASSERT_EQ(store.Projects().size(), 2); + EXPECT_EQ(store.Projects().back().name, "First"); + + const auto document = Common::FileUtils::ReadJsonFile(storeFile.String()).Unwrap(); + ASSERT_TRUE(document.IsArray()); + EXPECT_STREQ(document[1]["name"].GetString(), "First"); + RecentProjectStore reloaded(storeFile); + ASSERT_TRUE(reloaded.Load().IsOk()); + ASSERT_EQ(reloaded.Projects().size(), 2); + EXPECT_EQ(reloaded.Projects().back().path, Common::Path(firstProject).Canonical().String()); + } + + TEST_F(ProjectTest, ReportsInvalidRecentProjectsAndWriteFailures) + { + const Common::Path storeFile(directory / "RecentProjects.json"); + WriteFile(storeFile.String(), "not JSON"); + RecentProjectStore store(storeFile); + EXPECT_TRUE(store.Load().IsErr()); + WriteFile(storeFile.String(), "[{\"path\": 42}]"); + EXPECT_TRUE(store.Load().IsErr()); + + RecentProjectStore unwritable { Common::Path(directory) }; + EXPECT_TRUE(unwritable.Record(Common::Path(directory)).IsErr()); + EXPECT_TRUE(unwritable.Projects().empty()); + } + + TEST_F(ProjectTest, LauncherPassesPathsAsArgumentsAndPropagatesFailures) + { + const Common::Path project("C:/Projects with spaces/A&B"); + bool launched = false; + ProjectLauncher launcher( + EditorLaunchOptions { "Editor with spaces.exe", "vulkan", true, true }, + [&](const std::string& inExecutable, const std::vector& inArguments) -> Common::Result { + launched = true; + EXPECT_EQ(inExecutable, "Editor with spaces.exe"); + EXPECT_EQ(inArguments, (std::vector { "-project", project.String(), "-rhi", "vulkan", "-gpuDebug", "-softwareGpu" })); + return Common::Err(std::string("launch failed")); + }); + const auto result = launcher.Launch(project); + EXPECT_TRUE(launched); + ASSERT_TRUE(result.IsErr()); + EXPECT_EQ(result.Error(), "launch failed"); + } + + TEST_F(ProjectTest, LauncherOmitsDisabledFlags) + { + ProjectLauncher launcher( + EditorLaunchOptions { "Editor.exe", "dx12", false, false }, + [](const std::string&, const std::vector& inArguments) -> Common::Result { + EXPECT_EQ(inArguments, (std::vector { "-project", "Project", "-rhi", "dx12" })); + return Common::Ok(); + }); + EXPECT_TRUE(launcher.Launch(Common::Path("Project")).IsOk()); + EXPECT_TRUE(Common::Process::Launch((directory / "MissingExecutable").string(), {}).IsErr()); + } +} diff --git a/Engine/Source/Common/Include/Common/Process.h b/Engine/Source/Common/Include/Common/Process.h index a77916f21..39fa5a605 100644 --- a/Engine/Source/Common/Include/Common/Process.h +++ b/Engine/Source/Common/Include/Common/Process.h @@ -5,9 +5,12 @@ #include #include +#include + namespace Common { class Process { public: static std::optional Run(const std::string& inExecutablePath, const std::vector& inArguments); + static Result Launch(const std::string& inExecutablePath, const std::vector& inArguments); }; } diff --git a/Engine/Source/Common/Src/Process.cpp b/Engine/Source/Common/Src/Process.cpp index 791bd208c..5ea1d46c3 100644 --- a/Engine/Source/Common/Src/Process.cpp +++ b/Engine/Source/Common/Src/Process.cpp @@ -1,5 +1,8 @@ #include +#include +#include + #if PLATFORM_WINDOWS #include @@ -8,6 +11,7 @@ #include #include #include +#include #if PLATFORM_MACOS #include @@ -42,6 +46,25 @@ namespace Common::Internal { outCommandLine.append(backslashCount * 2, L'\\'); outCommandLine.push_back(L'"'); } + + static Result CreateChildProcess(const std::string& inExecutablePath, const std::vector& inArguments, bool inDetached) + { + const std::wstring executablePath = StringUtils::ToWideString(inExecutablePath); + std::wstring commandLine; + AppendWindowsCommandLineArgument(commandLine, executablePath); + for (const auto& argument : inArguments) { + AppendWindowsCommandLineArgument(commandLine, StringUtils::ToWideString(argument)); + } + + STARTUPINFOW startupInfo {}; + startupInfo.cb = sizeof(startupInfo); + PROCESS_INFORMATION processInfo {}; + const DWORD flags = inDetached ? DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP : 0; + if (!CreateProcessW(executablePath.c_str(), commandLine.data(), nullptr, nullptr, FALSE, flags, nullptr, nullptr, &startupInfo, &processInfo)) { + return Err(std::format("Could not start '{}': {}", inExecutablePath, std::error_code(static_cast(GetLastError()), std::system_category()).message())); + } + return Ok(processInfo); + } #else static char** GetEnvironment() { @@ -68,6 +91,24 @@ namespace Common::Internal { } return std::nullopt; } + + static Result CreateChildProcess(const std::string& inExecutablePath, const std::vector& inArguments) + { + std::vector arguments; + arguments.reserve(inArguments.size() + 2); + arguments.push_back(const_cast(inExecutablePath.c_str())); + for (const auto& argument : inArguments) { + arguments.push_back(const_cast(argument.c_str())); + } + arguments.push_back(nullptr); + + pid_t processId = 0; + const int error = posix_spawn(&processId, inExecutablePath.c_str(), nullptr, nullptr, arguments.data(), GetEnvironment()); + if (error != 0) { + return Err(std::format("Could not start '{}': {}", inExecutablePath, std::error_code(error, std::generic_category()).message())); + } + return Ok(processId); + } #endif } @@ -75,20 +116,11 @@ namespace Common { std::optional Process::Run(const std::string& inExecutablePath, const std::vector& inArguments) { #if PLATFORM_WINDOWS - const std::wstring executablePath = StringUtils::ToWideString(inExecutablePath); - std::wstring commandLine; - Internal::AppendWindowsCommandLineArgument(commandLine, executablePath); - for (const auto& argument : inArguments) { - Internal::AppendWindowsCommandLineArgument(commandLine, StringUtils::ToWideString(argument)); - } - - STARTUPINFOW startupInfo {}; - startupInfo.cb = sizeof(startupInfo); - PROCESS_INFORMATION processInfo {}; - if (!CreateProcessW(executablePath.c_str(), commandLine.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startupInfo, &processInfo)) { + const auto result = Internal::CreateChildProcess(inExecutablePath, inArguments, false); + if (result.IsErr()) { return std::nullopt; } - + const auto& processInfo = result.Value(); const DWORD waitResult = WaitForSingleObject(processInfo.hProcess, INFINITE); DWORD exitCode = 0; const bool hasExitCode = waitResult == WAIT_OBJECT_0 && GetExitCodeProcess(processInfo.hProcess, &exitCode); @@ -96,19 +128,34 @@ namespace Common { CloseHandle(processInfo.hProcess); return hasExitCode ? std::optional(static_cast(exitCode)) : std::nullopt; #else - std::vector arguments; - arguments.reserve(inArguments.size() + 2); - arguments.push_back(const_cast(inExecutablePath.c_str())); - for (const auto& argument : inArguments) { - arguments.push_back(const_cast(argument.c_str())); + const auto result = Internal::CreateChildProcess(inExecutablePath, inArguments); + if (result.IsErr()) { + return std::nullopt; } - arguments.push_back(nullptr); + return Internal::WaitForProcess(result.Value()); +#endif + } - pid_t processId = 0; - if (posix_spawn(&processId, inExecutablePath.c_str(), nullptr, nullptr, arguments.data(), Internal::GetEnvironment()) != 0) { - return std::nullopt; + Result Process::Launch(const std::string& inExecutablePath, const std::vector& inArguments) + { +#if PLATFORM_WINDOWS + const auto result = Internal::CreateChildProcess(inExecutablePath, inArguments, true); + if (result.IsErr()) { + return Err(result.Error()); + } + CloseHandle(result.Value().hThread); + CloseHandle(result.Value().hProcess); +#else + const auto result = Internal::CreateChildProcess(inExecutablePath, inArguments); + if (result.IsErr()) { + return Err(result.Error()); } - return Internal::WaitForProcess(processId); + // Keep a waiter while the parent lives so completed children do not become zombies. The child remains + // independent of the launcher's lifetime and is reparented normally if the launcher exits first. + std::thread([processId = result.Value()]() -> void { + Internal::WaitForProcess(processId); + }).detach(); #endif + return Ok(); } } From 7a75cc2a9380d4cb29237bf20c3dfc46ec07eb63 Mon Sep 17 00:00:00 2001 From: kindem Date: Sun, 15 Nov 2026 15:58:01 +0800 Subject: [PATCH 3/4] refactor: unify editor tabs Extract a shared tab lifecycle and use tab descriptors to drive view menus and docking. Prefer Common::Path in the new editor interfaces. Keep Editor.Test focused on basic logic and document English-only, pragmatic coding guidelines. --- AGENTS.md | 3 + Editor/CMakeLists.txt | 3 +- Editor/Include/Editor/EditorApplication.h | 3 +- Editor/Include/Editor/EditorLog.h | 2 +- Editor/Include/Editor/Frame/EditorFrame.h | 42 +-- .../Include/Editor/Panel/EditorPanelNames.h | 13 - Editor/Include/Editor/Panel/EditorPanels.h | 24 -- .../{Panel/AssetsPanel.h => Tab/AssetsTab.h} | 10 +- Editor/Include/Editor/Tab/EditorTab.h | 52 +++ Editor/Include/Editor/Tab/EditorTabs.h | 32 ++ Editor/Include/Editor/Tab/InspectorTab.h | 22 ++ Editor/Include/Editor/Tab/LogTab.h | 17 + Editor/Include/Editor/Tab/OutlinerTab.h | 22 ++ Editor/Include/Editor/Tab/SceneTab.h | 23 ++ Editor/Src/EditorApplication.cpp | 89 +---- Editor/Src/Frame/EditorFrame.cpp | 351 +++--------------- Editor/Src/Panel/EditorPanelNames.cpp | 13 - Editor/Src/Panel/EditorPanels.cpp | 35 -- .../AssetsPanel.cpp => Tab/AssetsTab.cpp} | 77 ++-- Editor/Src/Tab/EditorTab.cpp | 73 ++++ Editor/Src/Tab/EditorTabs.cpp | 75 ++++ Editor/Src/Tab/InspectorTab.cpp | 138 +++++++ Editor/Src/Tab/LogTab.cpp | 70 ++++ Editor/Src/Tab/OutlinerTab.cpp | 88 +++++ Editor/Src/Tab/SceneTab.cpp | 45 +++ Editor/Test/ImGuiDrawDataTest.cpp | 67 ---- 26 files changed, 768 insertions(+), 621 deletions(-) delete mode 100644 Editor/Include/Editor/Panel/EditorPanelNames.h delete mode 100644 Editor/Include/Editor/Panel/EditorPanels.h rename Editor/Include/Editor/{Panel/AssetsPanel.h => Tab/AssetsTab.h} (89%) create mode 100644 Editor/Include/Editor/Tab/EditorTab.h create mode 100644 Editor/Include/Editor/Tab/EditorTabs.h create mode 100644 Editor/Include/Editor/Tab/InspectorTab.h create mode 100644 Editor/Include/Editor/Tab/LogTab.h create mode 100644 Editor/Include/Editor/Tab/OutlinerTab.h create mode 100644 Editor/Include/Editor/Tab/SceneTab.h delete mode 100644 Editor/Src/Panel/EditorPanelNames.cpp delete mode 100644 Editor/Src/Panel/EditorPanels.cpp rename Editor/Src/{Panel/AssetsPanel.cpp => Tab/AssetsTab.cpp} (90%) create mode 100644 Editor/Src/Tab/EditorTab.cpp create mode 100644 Editor/Src/Tab/EditorTabs.cpp create mode 100644 Editor/Src/Tab/InspectorTab.cpp create mode 100644 Editor/Src/Tab/LogTab.cpp create mode 100644 Editor/Src/Tab/OutlinerTab.cpp create mode 100644 Editor/Src/Tab/SceneTab.cpp delete mode 100644 Editor/Test/ImGuiDrawDataTest.cpp diff --git a/AGENTS.md b/AGENTS.md index f523e2157..74f5a4166 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,9 @@ Before starting any work, agents must read `AGENTS.local.md` at the repository r - Prioritize sound abstractions and a single source of truth over a minimal diff. - Prefer clear names and small functions; comment only when intent cannot be expressed in code. +- Avoid excessive defensive programming and validation. Write only meaningful tests. Do not overengineer compatibility + or guard against scenarios that will not occur in practice. +- Use English exclusively throughout this project. Code, comments, and documentation must not contain other languages. - Code has no line-length limit; wrap only for readability. Wrap comments at about 120 characters with roughly even lines. - In headers, declare the complete interface first, then put out-of-line definitions in a second namespace block. Do not put function bodies inside class definitions. Put helper types in `Common::Internal`. diff --git a/Editor/CMakeLists.txt b/Editor/CMakeLists.txt index 5b0a190d5..74d833741 100644 --- a/Editor/CMakeLists.txt +++ b/Editor/CMakeLists.txt @@ -23,8 +23,7 @@ file(GLOB editor_test_sources Test/*.cpp) file(GLOB editor_project_sources Src/Project/*.cpp) exp_add_test( NAME Editor.Test - SRC ${editor_test_sources} Src/Asset/AssetFileSystem.cpp ${editor_project_sources} Src/ImGui/ImGuiDrawData.cpp - LIB imgui::imgui + SRC ${editor_test_sources} Src/Asset/AssetFileSystem.cpp ${editor_project_sources} INC Include ) diff --git a/Editor/Include/Editor/EditorApplication.h b/Editor/Include/Editor/EditorApplication.h index afc70ffed..c184e17ff 100644 --- a/Editor/Include/Editor/EditorApplication.h +++ b/Editor/Include/Editor/EditorApplication.h @@ -41,7 +41,6 @@ namespace Editor { void InitializeImGui(); void ShutdownImGui(); void InstallCallbacks(); - void DrawDockSpace() const; void RenderEditorFrame(); void HandleKey(int inKey, int inAction); void HandleMouseButton(int inButton, int inAction); @@ -59,7 +58,7 @@ namespace Editor { Common::UniquePtr recentProjects; Common::UniquePtr projectLauncher; Common::UniquePtr projectHubFrame; - EditorFrame editorFrame; + Common::UniquePtr editorFrame; double lastFrameSeconds; double lastCursorX; double lastCursorY; diff --git a/Editor/Include/Editor/EditorLog.h b/Editor/Include/Editor/EditorLog.h index 7a7daba95..33ad63778 100644 --- a/Editor/Include/Editor/EditorLog.h +++ b/Editor/Include/Editor/EditorLog.h @@ -14,7 +14,7 @@ namespace Editor { // log stream attached to the engine logger that keeps a bounded history and forwards structured entries to - // listeners (the log panel backend), log calls arrive from arbitrary threads so everything is mutex-guarded and + // listeners (the log tab backend), log calls arrive from arbitrary threads so everything is mutex-guarded and // listeners must marshal to their own thread themselves class EditorLogStream final : public Core::LogStream { public: diff --git a/Editor/Include/Editor/Frame/EditorFrame.h b/Editor/Include/Editor/Frame/EditorFrame.h index 55194578b..682e81e9e 100644 --- a/Editor/Include/Editor/Frame/EditorFrame.h +++ b/Editor/Include/Editor/Frame/EditorFrame.h @@ -1,43 +1,29 @@ -// -// Created by johnk on 2026/7/7. -// - #pragma once -#include -#include +#include -#include -#include -#include +#include -namespace Editor::Internal { - struct EditorTabVisibility { - bool scene; - bool outliner; - bool inspector; - bool log; - }; +namespace Runtime { + class Canvas; } namespace Editor { + class EditorContext; + class EditorLogStream; + class EditorFrame final { public: - EditorFrame(); + EditorFrame(EditorContext& inContext, Runtime::Canvas& inSceneRenderCanvas, EditorLogStream& inLogStream, Common::Path inAssetDirectory); ~EditorFrame(); - void Render(EditorContext& inContext, Runtime::ECRegistry& inRegistry, Runtime::Canvas& inSceneRenderCanvas, bool& outRequestQuit); + void Render(bool& outRequestQuit); private: - void RenderMenuBar(EditorContext& inContext, bool& outRequestQuit); - void RenderSceneTab(EditorContext& inContext, Runtime::Canvas& inSceneRenderCanvas, bool& inOutOpen); - void RenderOutlinerTab(EditorContext& inContext, Runtime::ECRegistry& inRegistry, bool& inOutOpen); - void RenderInspectorTab(EditorContext& inContext, Runtime::ECRegistry& inRegistry, bool& inOutOpen); - void RenderLogTab(bool& inOutOpen); - - std::string createEntityName; - std::vector componentClasses; - Internal::EditorTabVisibility tabVisibility; - EditorPanels panels; + void DrawDockSpace() const; + void RenderMenuBar(bool& outRequestQuit); + + EditorContext& context; + EditorTabs tabs; }; } diff --git a/Editor/Include/Editor/Panel/EditorPanelNames.h b/Editor/Include/Editor/Panel/EditorPanelNames.h deleted file mode 100644 index 14cf5f941..000000000 --- a/Editor/Include/Editor/Panel/EditorPanelNames.h +++ /dev/null @@ -1,13 +0,0 @@ -// -// Created by johnk on 2026/7/18. -// - -#pragma once - -namespace Editor::PanelNames { - extern const char scene[]; - extern const char outliner[]; - extern const char inspector[]; - extern const char assets[]; - extern const char log[]; -} diff --git a/Editor/Include/Editor/Panel/EditorPanels.h b/Editor/Include/Editor/Panel/EditorPanels.h deleted file mode 100644 index 46de6f243..000000000 --- a/Editor/Include/Editor/Panel/EditorPanels.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// Created by johnk on 2026/7/18. -// - -#pragma once - -#include - -#include - -namespace Editor { - class EditorPanels final { - public: - EditorPanels(); - ~EditorPanels(); - - void Render(); - void RenderViewMenuItems(); - - private: - std::optional assetsPanel; - bool assetsVisible; - }; -} diff --git a/Editor/Include/Editor/Panel/AssetsPanel.h b/Editor/Include/Editor/Tab/AssetsTab.h similarity index 89% rename from Editor/Include/Editor/Panel/AssetsPanel.h rename to Editor/Include/Editor/Tab/AssetsTab.h index 12cf2e85f..2c6c74e8a 100644 --- a/Editor/Include/Editor/Panel/AssetsPanel.h +++ b/Editor/Include/Editor/Tab/AssetsTab.h @@ -7,15 +7,14 @@ #include #include +#include #include +#include namespace Editor { - class AssetsPanel final { + class AssetsTab final : public EditorTab { public: - AssetsPanel(); - ~AssetsPanel(); - - void Render(bool& inOutOpen); + explicit AssetsTab(Common::Path inAssetDirectory); private: enum class ClipboardMode : uint8_t { @@ -24,6 +23,7 @@ namespace Editor { move }; + void RenderContents() override; void RenderToolbar(); void RenderBreadcrumbs(); void RenderDirectoryTree(const std::filesystem::path& inDirectory, const char* inLabel); diff --git a/Editor/Include/Editor/Tab/EditorTab.h b/Editor/Include/Editor/Tab/EditorTab.h new file mode 100644 index 000000000..fd2481ee2 --- /dev/null +++ b/Editor/Include/Editor/Tab/EditorTab.h @@ -0,0 +1,52 @@ +#pragma once + +#include +#include + +#include + +#include + +namespace Editor { + enum class TabDockArea : uint8_t { + center, + rightTop, + rightBottom, + bottom + }; + + struct EditorTabDesc { + std::string id; + std::string title; + std::string icon; + TabDockArea defaultDockArea = TabDockArea::center; + ImGuiWindowFlags windowFlags = ImGuiWindowFlags_None; + bool contentPadding = true; + }; + + class EditorTab { + public: + virtual ~EditorTab(); + + NonCopyable(EditorTab) + NonMovable(EditorTab) + + const EditorTabDesc& GetDesc() const; + const std::string& GetWindowName() const; + bool IsOpen() const; + void SetOpen(bool inOpen); + void Render(); + void RenderViewMenuItem(); + + protected: + explicit EditorTab(EditorTabDesc inDesc); + + virtual void RenderContents() = 0; + virtual void OnHidden(); + + private: + EditorTabDesc desc; + std::string windowName; + bool open; + }; +} diff --git a/Editor/Include/Editor/Tab/EditorTabs.h b/Editor/Include/Editor/Tab/EditorTabs.h new file mode 100644 index 000000000..4b4b12206 --- /dev/null +++ b/Editor/Include/Editor/Tab/EditorTabs.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace Editor { + class EditorTabs final { + public: + template requires std::derived_from T& Emplace(Args&&... inArgs); + void Render(); + void RenderViewMenuItems(); + void BuildInitialDockLayout(ImGuiID inDockSpaceId, const ImVec2& inSize) const; + + private: + std::vector> tabs; + }; +} + +namespace Editor { + template requires std::derived_from + T& EditorTabs::Emplace(Args&&... inArgs) + { + auto tab = std::make_unique(std::forward(inArgs)...); + T& result = *tab; + tabs.emplace_back(std::move(tab)); + return result; + } +} diff --git a/Editor/Include/Editor/Tab/InspectorTab.h b/Editor/Include/Editor/Tab/InspectorTab.h new file mode 100644 index 000000000..a70b83ffe --- /dev/null +++ b/Editor/Include/Editor/Tab/InspectorTab.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +#include +#include + +namespace Editor { + class EditorContext; + + class InspectorTab final : public EditorTab { + public: + explicit InspectorTab(EditorContext& inContext); + + private: + void RenderContents() override; + void RenderComponents(Runtime::ECRegistry& inRegistry); + + EditorContext& context; + std::vector componentClasses; + }; +} diff --git a/Editor/Include/Editor/Tab/LogTab.h b/Editor/Include/Editor/Tab/LogTab.h new file mode 100644 index 000000000..e2a7b4354 --- /dev/null +++ b/Editor/Include/Editor/Tab/LogTab.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace Editor { + class EditorLogStream; + + class LogTab final : public EditorTab { + public: + explicit LogTab(EditorLogStream& inLogStream); + + private: + void RenderContents() override; + + EditorLogStream& logStream; + }; +} diff --git a/Editor/Include/Editor/Tab/OutlinerTab.h b/Editor/Include/Editor/Tab/OutlinerTab.h new file mode 100644 index 000000000..e828495f5 --- /dev/null +++ b/Editor/Include/Editor/Tab/OutlinerTab.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +#include +#include + +namespace Editor { + class EditorContext; + + class OutlinerTab final : public EditorTab { + public: + explicit OutlinerTab(EditorContext& inContext); + + private: + void RenderContents() override; + void RenderEntities(Runtime::ECRegistry& inRegistry); + + EditorContext& context; + std::string createEntityName; + }; +} diff --git a/Editor/Include/Editor/Tab/SceneTab.h b/Editor/Include/Editor/Tab/SceneTab.h new file mode 100644 index 000000000..89943d2f2 --- /dev/null +++ b/Editor/Include/Editor/Tab/SceneTab.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +namespace Runtime { + class Canvas; +} + +namespace Editor { + class SceneClient; + + class SceneTab final : public EditorTab { + public: + SceneTab(SceneClient& inSceneClient, Runtime::Canvas& inCanvas); + + private: + void RenderContents() override; + void OnHidden() override; + + SceneClient& sceneClient; + Runtime::Canvas& canvas; + }; +} diff --git a/Editor/Src/EditorApplication.cpp b/Editor/Src/EditorApplication.cpp index 9355c9b4c..bc06343d7 100644 --- a/Editor/Src/EditorApplication.cpp +++ b/Editor/Src/EditorApplication.cpp @@ -2,18 +2,16 @@ // Created by johnk on 2026/7/7. // -#include #include #include #include -#include #include #include #include #include -#include +#include #include #include #include @@ -24,20 +22,9 @@ namespace Editor::Internal { constexpr uint32_t projectHubWindowWidth = 560; constexpr uint32_t projectHubWindowHeight = 720; constexpr float defaultFontSize = 15.0f; - constexpr float defaultRightColumnRatio = 0.22f; - constexpr float minRightColumnWidth = 360.0f; - constexpr float maxRightColumnWidth = 480.0f; - constexpr float defaultBottomPanelRatio = 0.22f; - constexpr float minBottomPanelHeight = 200.0f; - constexpr float maxBottomPanelHeight = 300.0f; - constexpr float defaultOutlinerRatio = 0.35f; - constexpr float minOutlinerHeight = 280.0f; - constexpr float maxOutlinerHeight = 420.0f; constexpr uint32_t defaultSceneWidth = 1280; constexpr uint32_t defaultSceneHeight = 720; constexpr RHI::PixelFormat sceneColorFormat = RHI::PixelFormat::rgba8Unorm; - constexpr const char* editorDockSpaceName = "EditorDockSpace"; - constexpr const char* editorDockSpaceId = "EditorDockSpaceV3"; static Runtime::CanvasDesc CreateSceneRenderCanvasDesc() { @@ -87,50 +74,11 @@ namespace Editor::Internal { config.GlyphMaxAdvanceX = inSizePixels; Assert(inFontAtlas.AddFontFromFileTTF(fontPath.c_str(), inSizePixels, &config, glyphRanges.Data) != nullptr); } - - static float CalculatePanelRatio(float inAvailableSize, float inDefaultRatio, float inMinSize, float inMaxSize) - { - if (inAvailableSize <= 0.0f) { - return inDefaultRatio; - } - const float panelSize = std::clamp(inAvailableSize * inDefaultRatio, inMinSize, inMaxSize); - return std::min(panelSize / inAvailableSize, 0.5f); - } - - static void BuildInitialEditorDockLayout(ImGuiID inDockSpaceId, const ImVec2& inSize) - { - if (ImGui::DockBuilderGetNode(inDockSpaceId) != nullptr) { - return; - } - - ImGui::DockBuilderAddNode(inDockSpaceId, ImGuiDockNodeFlags_DockSpace); - ImGui::DockBuilderSetNodeSize(inDockSpaceId, inSize); - - ImGuiID sceneNodeId = 0; - ImGuiID rightColumnNodeId = 0; - ImGuiID outlinerNodeId = 0; - ImGuiID inspectorNodeId = 0; - ImGuiID bottomNodeId = 0; - const float rightColumnRatio = CalculatePanelRatio(inSize.x, defaultRightColumnRatio, minRightColumnWidth, maxRightColumnWidth); - const float bottomPanelRatio = CalculatePanelRatio(inSize.y, defaultBottomPanelRatio, minBottomPanelHeight, maxBottomPanelHeight); - const float outlinerRatio = CalculatePanelRatio(inSize.y, defaultOutlinerRatio, minOutlinerHeight, maxOutlinerHeight); - ImGui::DockBuilderSplitNode(inDockSpaceId, ImGuiDir_Right, rightColumnRatio, &rightColumnNodeId, &sceneNodeId); - ImGui::DockBuilderSplitNode(sceneNodeId, ImGuiDir_Down, bottomPanelRatio, &bottomNodeId, &sceneNodeId); - ImGui::DockBuilderSplitNode(rightColumnNodeId, ImGuiDir_Up, outlinerRatio, &outlinerNodeId, &inspectorNodeId); - - ImGui::DockBuilderDockWindow(PanelNames::scene, sceneNodeId); - ImGui::DockBuilderDockWindow(PanelNames::outliner, outlinerNodeId); - ImGui::DockBuilderDockWindow(PanelNames::inspector, inspectorNodeId); - ImGui::DockBuilderDockWindow(PanelNames::assets, bottomNodeId); - ImGui::DockBuilderDockWindow(PanelNames::log, bottomNodeId); - ImGui::DockBuilderFinish(inDockSpaceId); - } } namespace Editor { EditorApplication::EditorApplication(EditorApplicationDesc inDesc) : desc(std::move(inDesc)) - , editorFrame() , lastFrameSeconds(Common::TimePoint::Now().ToSeconds()) , lastCursorX(0.0) , lastCursorY(0.0) @@ -158,6 +106,7 @@ namespace Editor { sceneRenderCanvas = Common::MakeUnique(window->GetDevice(), Internal::CreateSceneRenderCanvasDesc()); sceneClient.SetRenderSurface(sceneRenderCanvas.Get()); sceneClient.OpenProjectLevel(); + editorFrame = Common::MakeUnique(*context, *sceneRenderCanvas, EditorLogStream::Get(), Core::Paths::GameAssetDir()); } else { projectService = Common::MakeUnique(Core::Paths::EngineResDir() / "Editor" / "ProjectTemplates"); recentProjects = Common::MakeUnique(Core::Paths::EngineCacheDir() / "Editor" / "ProjectHub" / "RecentProjects.json"); @@ -177,6 +126,7 @@ namespace Editor { context->GetSceneClient().SetRenderSurface(nullptr); } imguiRenderer->WaitIdle(); + editorFrame.Reset(); context.Reset(); sceneRenderCanvas.Reset(); projectHubFrame.Reset(); @@ -254,40 +204,9 @@ namespace Editor { }); } - void EditorApplication::DrawDockSpace() const - { - const ImGuiViewport* mainViewport = ImGui::GetMainViewport(); - ImGui::SetNextWindowPos(mainViewport->WorkPos); - ImGui::SetNextWindowSize(mainViewport->WorkSize); - ImGui::SetNextWindowViewport(mainViewport->ID); - - ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoDocking - | ImGuiWindowFlags_NoTitleBar - | ImGuiWindowFlags_NoCollapse - | ImGuiWindowFlags_NoResize - | ImGuiWindowFlags_NoMove - | ImGuiWindowFlags_NoBringToFrontOnFocus - | ImGuiWindowFlags_NoNavFocus - | ImGuiWindowFlags_NoBackground; - - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); - ImGui::Begin(Internal::editorDockSpaceName, nullptr, windowFlags); - ImGui::PopStyleVar(3); - - const ImGuiID dockSpaceId = ImGui::GetID(Internal::editorDockSpaceId); - Internal::BuildInitialEditorDockLayout(dockSpaceId, mainViewport->WorkSize); - ImGui::DockSpace(dockSpaceId, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None); - ImGui::End(); - } - void EditorApplication::RenderEditorFrame() { - DrawDockSpace(); - context->GetSceneClient().GetWorld().EditorAccess([&](Runtime::ECRegistry& registry) -> void { - editorFrame.Render(*context, registry, *sceneRenderCanvas, requestQuit); - }); + editorFrame->Render(requestQuit); if (ImGui::GetIO().KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_S, false)) { context->GetSceneClient().SaveLevel(); } diff --git a/Editor/Src/Frame/EditorFrame.cpp b/Editor/Src/Frame/EditorFrame.cpp index af1139d4f..dbeb0c132 100644 --- a/Editor/Src/Frame/EditorFrame.cpp +++ b/Editor/Src/Frame/EditorFrame.cpp @@ -1,111 +1,42 @@ -// -// Created by johnk on 2026/7/7. -// - -#include -#include -#include -#include -#include - #include -#include +#include -#include +#include #include -#include -#include +#include +#include +#include +#include +#include #include -#include #include -#include -#include -#include -#include - -namespace Editor::Internal { - static std::string ComponentDisplayName(const Mirror::Class& inClass) - { - const std::string& qualifiedName = inClass.GetName(); - const size_t namespaceSeparator = qualifiedName.rfind("::"); - return namespaceSeparator == std::string::npos - ? qualifiedName - : qualifiedName.substr(namespaceSeparator + 2); - } - static bool IsComponentVisibleInDetails(const Mirror::Class& inClass) - { - return !inClass.HasMeta(Runtime::MetaPresets::editorHide); - } - - static std::string EntityDisplayName(const Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity) - { - const auto* name = inRegistry.Find(inEntity); - return name != nullptr && !name->value.empty() - ? name->value - : std::format("Entity {}", inEntity); - } - - static std::string LevelString(Core::LogLevel inLevel) - { - switch (inLevel) { - case Core::LogLevel::verbose: - return "verbose"; - case Core::LogLevel::info: - return "info"; - case Core::LogLevel::warning: - return "warning"; - case Core::LogLevel::error: - return "error"; - default: - return "unknown"; - } - } +namespace Editor::Workspace::Internal { + constexpr const char* editorDockSpaceName = "EditorDockSpace"; + constexpr const char* editorDockSpaceId = "EditorDockSpaceV3"; } namespace Editor { - EditorFrame::EditorFrame() - : createEntityName("Entity") - , componentClasses(Mirror::Class::GetAll()) - , tabVisibility { - .scene = true, - .outliner = true, - .inspector = true, - .log = true - } + EditorFrame::EditorFrame(EditorContext& inContext, Runtime::Canvas& inSceneRenderCanvas, EditorLogStream& inLogStream, Common::Path inAssetDirectory) + : context(inContext) { - std::erase_if(componentClasses, [](Runtime::CompClass clazz) -> bool { - return !clazz->HasMeta("comp") || !Internal::IsComponentVisibleInDetails(*clazz); - }); - std::ranges::sort(componentClasses, [](Runtime::CompClass lhs, Runtime::CompClass rhs) -> bool { - return lhs->GetName() < rhs->GetName(); - }); + tabs.Emplace(context.GetSceneClient(), inSceneRenderCanvas); + tabs.Emplace(context); + tabs.Emplace(context); + tabs.Emplace(std::move(inAssetDirectory)); + tabs.Emplace(inLogStream); } EditorFrame::~EditorFrame() = default; - void EditorFrame::Render(EditorContext& inContext, Runtime::ECRegistry& inRegistry, Runtime::Canvas& inSceneRenderCanvas, bool& outRequestQuit) + void EditorFrame::Render(bool& outRequestQuit) { - RenderMenuBar(inContext, outRequestQuit); - if (tabVisibility.scene) { - RenderSceneTab(inContext, inSceneRenderCanvas, tabVisibility.scene); - } else { - inContext.GetSceneClient().SetSceneHovered(false); - inContext.GetSceneClient().SetSceneFocused(false); - } - if (tabVisibility.outliner) { - RenderOutlinerTab(inContext, inRegistry, tabVisibility.outliner); - } - if (tabVisibility.inspector) { - RenderInspectorTab(inContext, inRegistry, tabVisibility.inspector); - } - if (tabVisibility.log) { - RenderLogTab(tabVisibility.log); - } - panels.Render(); + DrawDockSpace(); + RenderMenuBar(outRequestQuit); + tabs.Render(); } - void EditorFrame::RenderMenuBar(EditorContext& inContext, bool& outRequestQuit) + void EditorFrame::RenderMenuBar(bool& outRequestQuit) { if (!ImGui::BeginMainMenuBar()) { return; @@ -114,7 +45,7 @@ namespace Editor { if (ImGui::BeginMenu(fileMenuLabel.c_str())) { const std::string saveLevelLabel = Widgets::Label(Icons::Tabler::deviceFloppy, "Save Level"); if (ImGui::MenuItem(saveLevelLabel.c_str(), "Ctrl+S")) { - inContext.GetSceneClient().SaveLevel(); + context.GetSceneClient().SaveLevel(); } ImGui::Separator(); const std::string exitLabel = Widgets::Label(Icons::Tabler::doorExit, "Exit"); @@ -125,227 +56,37 @@ namespace Editor { } const std::string viewMenuLabel = Widgets::Label(Icons::Tabler::layoutDashboard, "View"); if (ImGui::BeginMenu(viewMenuLabel.c_str())) { - const std::string sceneLabel = Widgets::Label(Icons::Tabler::viewportWide, PanelNames::scene); - ImGui::MenuItem(sceneLabel.c_str(), nullptr, &tabVisibility.scene); - const std::string outlinerLabel = Widgets::Label(Icons::Tabler::hierarchy2, PanelNames::outliner); - ImGui::MenuItem(outlinerLabel.c_str(), nullptr, &tabVisibility.outliner); - const std::string inspectorLabel = Widgets::Label(Icons::Tabler::adjustmentsHorizontal, PanelNames::inspector); - ImGui::MenuItem(inspectorLabel.c_str(), nullptr, &tabVisibility.inspector); - panels.RenderViewMenuItems(); - const std::string logLabel = Widgets::Label(Icons::Tabler::terminal2, PanelNames::log); - ImGui::MenuItem(logLabel.c_str(), nullptr, &tabVisibility.log); + tabs.RenderViewMenuItems(); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } - void EditorFrame::RenderSceneTab(EditorContext& inContext, Runtime::Canvas& inSceneRenderCanvas, bool& inOutOpen) + void EditorFrame::DrawDockSpace() const { - static const std::string label = Widgets::Label(Icons::Tabler::viewportWide, PanelNames::scene, PanelNames::scene); + const ImGuiViewport* mainViewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(mainViewport->WorkPos); + ImGui::SetNextWindowSize(mainViewport->WorkSize); + ImGui::SetNextWindowViewport(mainViewport->ID); + + ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoDocking + | ImGuiWindowFlags_NoTitleBar + | ImGuiWindowFlags_NoCollapse + | ImGuiWindowFlags_NoResize + | ImGuiWindowFlags_NoMove + | ImGuiWindowFlags_NoBringToFrontOnFocus + | ImGuiWindowFlags_NoNavFocus + | ImGuiWindowFlags_NoBackground; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); - auto& sceneClient = inContext.GetSceneClient(); - if (ImGui::Begin(label.c_str(), &inOutOpen, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { - ImVec2 sceneSize = ImGui::GetContentRegionAvail(); - sceneSize.x = std::max(sceneSize.x, 1.0f); - sceneSize.y = std::max(sceneSize.y, 1.0f); + ImGui::Begin(Workspace::Internal::editorDockSpaceName, nullptr, windowFlags); + ImGui::PopStyleVar(3); - const ImVec2 framebufferScale = ImGui::GetIO().DisplayFramebufferScale; - sceneClient.ResizeRenderSurface( - std::max(1u, static_cast(sceneSize.x * framebufferScale.x)), - std::max(1u, static_cast(sceneSize.y * framebufferScale.y))); - ImGui::Image(static_cast(reinterpret_cast(inSceneRenderCanvas.GetTextureView())), sceneSize); - sceneClient.SetSceneHovered(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)); - sceneClient.SetSceneFocused(ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)); - } else { - sceneClient.SetSceneHovered(false); - sceneClient.SetSceneFocused(false); - } - ImGui::End(); - ImGui::PopStyleVar(); - } - - void EditorFrame::RenderOutlinerTab(EditorContext& inContext, Runtime::ECRegistry& inRegistry, bool& inOutOpen) - { - static const std::string label = Widgets::Label(Icons::Tabler::hierarchy2, PanelNames::outliner, PanelNames::outliner); - if (!ImGui::Begin(label.c_str(), &inOutOpen)) { - ImGui::End(); - return; - } - const std::string newEntityLabel = Widgets::Label(Icons::Tabler::plus, "New Entity"); - if (ImGui::Button(newEntityLabel.c_str())) { - ImGui::OpenPopup("NewEntityMenu"); - } - ImGui::SetNextWindowSize(ImVec2(260.0f, 0.0f), ImGuiCond_Appearing); - if (ImGui::BeginPopup("NewEntityMenu")) { - ImGui::SetNextItemWidth(-1.0f); - ImGui::InputText("##EntityName", &createEntityName); - const std::string createLabel = Widgets::Label(Icons::Tabler::check, "Create"); - if (ImGui::Button(createLabel.c_str(), ImVec2(ImGui::GetContentRegionAvail().x, 0.0f))) { - const auto entity = inContext.CreateEntity(inRegistry, createEntityName); - inContext.SetSelectedEntity(entity); - ImGui::CloseCurrentPopup(); - } - ImGui::EndPopup(); - } - ImGui::Separator(); - - Runtime::Entity entityToDelete = Runtime::entityNull; - inRegistry.Each([&](Runtime::Entity entity) -> void { - if (inRegistry.Has(entity)) { - return; - } - const std::string label = Widgets::Label(Icons::Tabler::box, Internal::EntityDisplayName(inRegistry, entity)); - const bool selected = inContext.GetSelectedEntity() == entity; - ImGui::PushID(static_cast(entity)); - if (ImGui::Selectable(label.c_str(), selected)) { - inContext.SetSelectedEntity(entity); - } - if (ImGui::BeginPopupContextItem("EntityMenu")) { - inContext.SetSelectedEntity(entity); - const std::string deleteLabel = Widgets::Label(Icons::Tabler::trash, "Delete"); - if (ImGui::MenuItem(deleteLabel.c_str())) { - entityToDelete = entity; - } - ImGui::EndPopup(); - } - ImGui::PopID(); - }); - if (entityToDelete != Runtime::entityNull) { - inContext.DestroyEntity(inRegistry, entityToDelete); - } - ImGui::End(); - } - - void EditorFrame::RenderInspectorTab(EditorContext& inContext, Runtime::ECRegistry& inRegistry, bool& inOutOpen) - { - static const std::string label = Widgets::Label(Icons::Tabler::adjustmentsHorizontal, PanelNames::inspector, PanelNames::inspector); - if (!ImGui::Begin(label.c_str(), &inOutOpen)) { - ImGui::End(); - return; - } - const Runtime::Entity selectedEntity = inContext.GetSelectedEntity(); - if (selectedEntity == Runtime::entityNull || !inRegistry.Valid(selectedEntity)) { - ImGui::TextDisabled("No entity selected"); - ImGui::End(); - return; - } - ImGui::PushID(static_cast(selectedEntity)); - - std::vector addableComponents; - for (const auto* clazz : componentClasses) { - if (inContext.CanAddComponent(inRegistry, selectedEntity, clazz)) { - addableComponents.emplace_back(clazz); - } - } - - ImGui::BeginDisabled(addableComponents.empty()); - const std::string addComponentLabel = Widgets::Label(Icons::Tabler::plus, "Add Component"); - if (ImGui::Button(addComponentLabel.c_str())) { - ImGui::OpenPopup("AddComponentMenu"); - } - ImGui::EndDisabled(); - if (ImGui::BeginPopup("AddComponentMenu")) { - for (const auto* clazz : addableComponents) { - const std::string componentName = Internal::ComponentDisplayName(*clazz); - ImGui::PushID(clazz->GetName().c_str()); - const std::string componentLabel = Widgets::Label(Icons::Tabler::boxMultiple, componentName); - if (ImGui::MenuItem(componentLabel.c_str())) { - inContext.AddComponent(inRegistry, selectedEntity, clazz); - } - ImGui::PopID(); - } - ImGui::EndPopup(); - } - ImGui::Separator(); - - Runtime::CompClass componentToRemove = nullptr; - inRegistry.CompEach(selectedEntity, [&](Runtime::CompClass compClass) -> void { - if (!Internal::IsComponentVisibleInDetails(*compClass)) { - return; - } - ImGui::PushID(compClass->GetName().c_str()); - const std::string componentName = Internal::ComponentDisplayName(*compClass); - const std::string componentLabel = Widgets::Label(Icons::Tabler::boxMultiple, componentName); - const bool open = ImGui::CollapsingHeader(componentLabel.c_str(), ImGuiTreeNodeFlags_DefaultOpen); - if (inContext.CanRemoveComponent(inRegistry, selectedEntity, compClass) && ImGui::BeginPopupContextItem("ComponentMenu")) { - const std::string removeLabel = Widgets::Label(Icons::Tabler::trash, "Remove"); - if (ImGui::MenuItem(removeLabel.c_str())) { - componentToRemove = compClass; - } - ImGui::EndPopup(); - } - if (open && componentToRemove != compClass) { - const Mirror::Any compRef = inRegistry.GetDyn(compClass, selectedEntity); - for (const auto& memberVariable : compClass->GetMemberVariables() | std::views::values) { - const Mirror::Any memberRef = memberVariable.GetDyn(compRef); - Mirror::Any memberValue = memberRef.Value(); - if (RenderInputWidget(memberVariable.GetName(), memberValue)) { - inContext.SetComponentMember(inRegistry, selectedEntity, compClass, memberVariable, memberValue); - } - } - } - ImGui::PopID(); - }); - inRegistry.TagEach(selectedEntity, [&](Runtime::TagClass tagClass) -> void { - if (!Internal::IsComponentVisibleInDetails(*tagClass)) { - return; - } - ImGui::PushID(tagClass->GetName().c_str()); - const std::string tagName = Internal::ComponentDisplayName(*tagClass); - const std::string tagLabel = Widgets::Label(Icons::Tabler::box, tagName); - ImGui::TextUnformatted(tagLabel.c_str()); - if (inContext.CanRemoveComponent(inRegistry, selectedEntity, tagClass) && ImGui::BeginPopupContextItem("ComponentMenu")) { - const std::string removeLabel = Widgets::Label(Icons::Tabler::trash, "Remove"); - if (ImGui::MenuItem(removeLabel.c_str())) { - componentToRemove = tagClass; - } - ImGui::EndPopup(); - } - ImGui::PopID(); - }); - if (componentToRemove != nullptr) { - inContext.RemoveComponent(inRegistry, selectedEntity, componentToRemove); - } - ImGui::PopID(); - ImGui::End(); - } - - void EditorFrame::RenderLogTab(bool& inOutOpen) - { - static const std::string label = Widgets::Label(Icons::Tabler::terminal2, PanelNames::log, PanelNames::log); - if (!ImGui::Begin(label.c_str(), &inOutOpen)) { - ImGui::End(); - return; - } - const auto entries = EditorLogStream::Get().Snapshot(); - const std::string copyLabel = Widgets::Label(Icons::Tabler::copy, "Copy"); - if (ImGui::Button(copyLabel.c_str())) { - std::string text; - for (const auto& entry : entries) { - text += std::format("[{}][{}][{}] {}\n", entry.time, Internal::LevelString(entry.level), entry.tag, entry.content); - } - ImGui::SetClipboardText(text.c_str()); - } - ImGui::Separator(); - ImGui::BeginChild("LogEntries", ImVec2(0.0f, 0.0f), false, ImGuiWindowFlags_HorizontalScrollbar); - for (const auto& entry : entries) { - const char* levelIcon = Icons::Tabler::infoCircle; - if (entry.level == Core::LogLevel::warning) { - Widgets::PushWarningTextColor(); - levelIcon = Icons::Tabler::alertTriangle; - } else if (entry.level == Core::LogLevel::error) { - Widgets::PushErrorTextColor(); - levelIcon = Icons::Tabler::circleX; - } else { - ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_Text)); - } - ImGui::TextUnformatted(std::format("{} [{}][{}][{}] {}", levelIcon, entry.time, Internal::LevelString(entry.level), entry.tag, entry.content).c_str()); - ImGui::PopStyleColor(); - } - if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) { - ImGui::SetScrollHereY(1.0f); - } - ImGui::EndChild(); + const ImGuiID dockSpaceId = ImGui::GetID(Workspace::Internal::editorDockSpaceId); + tabs.BuildInitialDockLayout(dockSpaceId, mainViewport->WorkSize); + ImGui::DockSpace(dockSpaceId, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None); ImGui::End(); } } diff --git a/Editor/Src/Panel/EditorPanelNames.cpp b/Editor/Src/Panel/EditorPanelNames.cpp deleted file mode 100644 index 0b3c509d4..000000000 --- a/Editor/Src/Panel/EditorPanelNames.cpp +++ /dev/null @@ -1,13 +0,0 @@ -// -// Created by johnk on 2026/7/18. -// - -#include - -namespace Editor::PanelNames { - const char scene[] = "Scene"; - const char outliner[] = "Outliner"; - const char inspector[] = "Inspector"; - const char assets[] = "Assets"; - const char log[] = "Log"; -} diff --git a/Editor/Src/Panel/EditorPanels.cpp b/Editor/Src/Panel/EditorPanels.cpp deleted file mode 100644 index 6c895cb53..000000000 --- a/Editor/Src/Panel/EditorPanels.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// -// Created by johnk on 2026/7/18. -// - -#include - -#include -#include -#include -#include - -namespace Editor { - EditorPanels::EditorPanels() - : assetsVisible(true) - { - } - - EditorPanels::~EditorPanels() = default; - - void EditorPanels::Render() - { - if (assetsVisible) { - if (!assetsPanel) { - assetsPanel.emplace(); - } - assetsPanel->Render(assetsVisible); - } - } - - void EditorPanels::RenderViewMenuItems() - { - const std::string label = Widgets::Label(Icons::Tabler::folder, PanelNames::assets); - ImGui::MenuItem(label.c_str(), nullptr, &assetsVisible); - } -} diff --git a/Editor/Src/Panel/AssetsPanel.cpp b/Editor/Src/Tab/AssetsTab.cpp similarity index 90% rename from Editor/Src/Panel/AssetsPanel.cpp rename to Editor/Src/Tab/AssetsTab.cpp index f468aecad..7c19238ca 100644 --- a/Editor/Src/Panel/AssetsPanel.cpp +++ b/Editor/Src/Tab/AssetsTab.cpp @@ -9,14 +9,12 @@ #include #include -#include -#include -#include +#include #include #include #include -namespace Editor::Internal { +namespace Editor::Assets::Internal { constexpr float assetsFolderTreeWidth = 220.0f; constexpr const char* assetPathPayload = "EXPLOSION_ASSET_PATH"; @@ -51,8 +49,14 @@ namespace Editor::Internal { } namespace Editor { - AssetsPanel::AssetsPanel() - : fileSystem(Core::Paths::GameAssetDir().String()) + AssetsTab::AssetsTab(Common::Path inAssetDirectory) + : EditorTab(EditorTabDesc { + .id = "Assets", + .title = "Assets", + .icon = Icons::Tabler::folder, + .defaultDockArea = TabDockArea::bottom + }) + , fileSystem(inAssetDirectory.String()) , currentDirectory(fileSystem.Root()) , clipboardMode(ClipboardMode::none) , statusIsError(false) @@ -62,16 +66,8 @@ namespace Editor { { } - AssetsPanel::~AssetsPanel() = default; - - void AssetsPanel::Render(bool& inOutOpen) + void AssetsTab::RenderContents() { - static const std::string label = Widgets::Label(Icons::Tabler::folder, PanelNames::assets, PanelNames::assets); - if (!ImGui::Begin(label.c_str(), &inOutOpen)) { - ImGui::End(); - return; - } - std::error_code error; if (!std::filesystem::is_directory(currentDirectory, error) || !fileSystem.Contains(currentDirectory)) { NavigateTo(fileSystem.Root()); @@ -99,8 +95,8 @@ namespace Editor { } ImGui::Separator(); - ImGui::BeginChild("AssetFolders", ImVec2(Internal::assetsFolderTreeWidth, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX); - RenderDirectoryTree(fileSystem.Root(), PanelNames::assets); + ImGui::BeginChild("AssetFolders", ImVec2(Assets::Internal::assetsFolderTreeWidth, 0.0f), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX); + RenderDirectoryTree(fileSystem.Root(), GetDesc().title.c_str()); ImGui::EndChild(); ImGui::SameLine(); ImGui::BeginChild("AssetContents", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Borders); @@ -108,10 +104,9 @@ namespace Editor { ImGui::EndChild(); RenderModals(); - ImGui::End(); } - void AssetsPanel::RenderToolbar() + void AssetsTab::RenderToolbar() { const bool atRoot = currentDirectory == fileSystem.Root(); ImGui::BeginDisabled(atRoot); @@ -156,9 +151,9 @@ namespace Editor { ImGui::EndDisabled(); } - void AssetsPanel::RenderBreadcrumbs() + void AssetsTab::RenderBreadcrumbs() { - if (Widgets::IconButton("Asset Root", Icons::Tabler::home, PanelNames::assets)) { + if (Widgets::IconButton("Asset Root", Icons::Tabler::home, GetDesc().title.c_str())) { NavigateTo(fileSystem.Root()); } @@ -182,7 +177,7 @@ namespace Editor { } } - void AssetsPanel::RenderDirectoryTree(const std::filesystem::path& inDirectory, const char* inLabel) + void AssetsTab::RenderDirectoryTree(const std::filesystem::path& inDirectory, const char* inLabel) { ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth; if (inDirectory == currentDirectory) { @@ -216,7 +211,7 @@ namespace Editor { ImGui::PopID(); } - void AssetsPanel::RenderDirectoryContents() + void AssetsTab::RenderDirectoryContents() { if (ImGui::BeginTable("AssetEntries", 3, ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY)) { ImGui::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch); @@ -236,7 +231,7 @@ namespace Editor { RenderBackgroundMenu(); } - void AssetsPanel::RenderEntry(const AssetFileEntry& inEntry) + void AssetsTab::RenderEntry(const AssetFileEntry& inEntry) { ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); @@ -253,7 +248,7 @@ namespace Editor { } if (ImGui::BeginDragDropSource()) { - ImGui::SetDragDropPayload(Internal::assetPathPayload, pathId.c_str(), pathId.size() + 1); + ImGui::SetDragDropPayload(Assets::Internal::assetPathPayload, pathId.c_str(), pathId.size() + 1); ImGui::TextUnformatted(label.c_str()); ImGui::EndDragDropSource(); } @@ -263,17 +258,17 @@ namespace Editor { RenderEntryContextMenu(inEntry, "AssetEntryMenu"); ImGui::TableSetColumnIndex(1); - ImGui::TextUnformatted(Internal::EntryType(inEntry).c_str()); + ImGui::TextUnformatted(Assets::Internal::EntryType(inEntry).c_str()); ImGui::TableSetColumnIndex(2); if (inEntry.directory) { ImGui::TextDisabled("--"); } else { - ImGui::TextUnformatted(Internal::FormatFileSize(inEntry.size).c_str()); + ImGui::TextUnformatted(Assets::Internal::FormatFileSize(inEntry.size).c_str()); } ImGui::PopID(); } - void AssetsPanel::RenderEntryContextMenu(const AssetFileEntry& inEntry, const char* inPopupId) + void AssetsTab::RenderEntryContextMenu(const AssetFileEntry& inEntry, const char* inPopupId) { if (!ImGui::BeginPopupContextItem(inPopupId)) { return; @@ -303,7 +298,7 @@ namespace Editor { ImGui::EndPopup(); } - void AssetsPanel::RenderBackgroundMenu() + void AssetsTab::RenderBackgroundMenu() { if (!ImGui::BeginPopupContextWindow("AssetBackgroundMenu", ImGuiPopupFlags_MouseButtonRight | ImGuiPopupFlags_NoOpenOverItems)) { return; @@ -324,7 +319,7 @@ namespace Editor { ImGui::EndPopup(); } - void AssetsPanel::RenderModals() + void AssetsTab::RenderModals() { if (requestCreateFolderPopup) { ImGui::OpenPopup("Create Folder"); @@ -419,7 +414,7 @@ namespace Editor { } } - void AssetsPanel::HandleKeyboardShortcuts() + void AssetsTab::HandleKeyboardShortcuts() { if (!ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) || ImGui::GetIO().WantTextInput) { return; @@ -447,12 +442,12 @@ namespace Editor { } } - void AssetsPanel::HandleDropTarget(const std::filesystem::path& inDirectory) + void AssetsTab::HandleDropTarget(const std::filesystem::path& inDirectory) { if (!ImGui::BeginDragDropTarget()) { return; } - if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(Internal::assetPathPayload)) { + if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(Assets::Internal::assetPathPayload)) { const auto* pathText = static_cast(payload->Data); std::filesystem::path destination; std::string error; @@ -469,7 +464,7 @@ namespace Editor { ImGui::EndDragDropTarget(); } - void AssetsPanel::NavigateTo(const std::filesystem::path& inDirectory) + void AssetsTab::NavigateTo(const std::filesystem::path& inDirectory) { std::error_code error; if (!fileSystem.Contains(inDirectory) || !std::filesystem::is_directory(inDirectory, error)) { @@ -483,13 +478,13 @@ namespace Editor { selectedPath.clear(); } - void AssetsPanel::OpenCreateFolderPopup() + void AssetsTab::OpenCreateFolderPopup() { createFolderName = "New Folder"; requestCreateFolderPopup = true; } - void AssetsPanel::OpenRenamePopup(const std::filesystem::path& inPath) + void AssetsTab::OpenRenamePopup(const std::filesystem::path& inPath) { if (inPath.empty()) { return; @@ -499,7 +494,7 @@ namespace Editor { requestRenamePopup = true; } - void AssetsPanel::OpenDeletePopup(const std::filesystem::path& inPath) + void AssetsTab::OpenDeletePopup(const std::filesystem::path& inPath) { if (inPath.empty()) { return; @@ -508,14 +503,14 @@ namespace Editor { requestDeletePopup = true; } - void AssetsPanel::SetClipboard(const std::filesystem::path& inPath, ClipboardMode inMode) + void AssetsTab::SetClipboard(const std::filesystem::path& inPath, ClipboardMode inMode) { clipboardPath = inPath; clipboardMode = inMode; ReportResult(std::format("{} '{}'", inMode == ClipboardMode::copy ? "Copied" : "Cut", inPath.filename().string()), false); } - void AssetsPanel::PasteInto(const std::filesystem::path& inDirectory) + void AssetsTab::PasteInto(const std::filesystem::path& inDirectory) { if (clipboardMode == ClipboardMode::none || clipboardPath.empty()) { return; @@ -540,7 +535,7 @@ namespace Editor { } } - void AssetsPanel::ImportFiles() + void AssetsTab::ImportFiles() { const std::vector files = PlatformUtils::SelectFiles("Import Assets", currentDirectory.string()); size_t importedCount = 0; @@ -559,7 +554,7 @@ namespace Editor { } } - void AssetsPanel::ReportResult(const std::string& inMessage, bool inError) + void AssetsTab::ReportResult(const std::string& inMessage, bool inError) { if (statusMessage == inMessage && statusIsError == inError) { return; diff --git a/Editor/Src/Tab/EditorTab.cpp b/Editor/Src/Tab/EditorTab.cpp new file mode 100644 index 000000000..1227b0a42 --- /dev/null +++ b/Editor/Src/Tab/EditorTab.cpp @@ -0,0 +1,73 @@ +#include +#include + +namespace Editor { + EditorTab::EditorTab(EditorTabDesc inDesc) + : desc(std::move(inDesc)) + , windowName(Widgets::Label(desc.icon.c_str(), desc.title, desc.id)) + , open(true) + { + } + + EditorTab::~EditorTab() = default; + + const EditorTabDesc& EditorTab::GetDesc() const + { + return desc; + } + + const std::string& EditorTab::GetWindowName() const + { + return windowName; + } + + bool EditorTab::IsOpen() const + { + return open; + } + + void EditorTab::SetOpen(bool inOpen) + { + if (open == inOpen) { + return; + } + open = inOpen; + if (!open) { + OnHidden(); + } + } + + void EditorTab::Render() + { + if (!open) { + return; + } + if (!desc.contentPadding) { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + } + bool requestedOpen = open; + const bool contentsVisible = ImGui::Begin(windowName.c_str(), &requestedOpen, desc.windowFlags); + if (!desc.contentPadding) { + ImGui::PopStyleVar(); + } + SetOpen(requestedOpen); + if (contentsVisible && open) { + RenderContents(); + } else if (open) { + OnHidden(); + } + ImGui::End(); + } + + void EditorTab::RenderViewMenuItem() + { + bool requestedOpen = open; + if (ImGui::MenuItem(windowName.c_str(), nullptr, &requestedOpen)) { + SetOpen(requestedOpen); + } + } + + void EditorTab::OnHidden() + { + } +} diff --git a/Editor/Src/Tab/EditorTabs.cpp b/Editor/Src/Tab/EditorTabs.cpp new file mode 100644 index 000000000..d156bf0fa --- /dev/null +++ b/Editor/Src/Tab/EditorTabs.cpp @@ -0,0 +1,75 @@ +#include + +#include + +#include + +namespace Editor::TabLayout::Internal { + constexpr float defaultRightColumnRatio = 0.22f; + constexpr float minRightColumnWidth = 360.0f; + constexpr float maxRightColumnWidth = 480.0f; + constexpr float defaultBottomAreaRatio = 0.22f; + constexpr float minBottomAreaHeight = 200.0f; + constexpr float maxBottomAreaHeight = 300.0f; + constexpr float defaultRightTopRatio = 0.35f; + constexpr float minRightTopHeight = 280.0f; + constexpr float maxRightTopHeight = 420.0f; + + static float CalculateDockRatio(float inAvailableSize, float inDefaultRatio, float inMinSize, float inMaxSize) + { + if (inAvailableSize <= 0.0f) { + return inDefaultRatio; + } + const float areaSize = std::clamp(inAvailableSize * inDefaultRatio, inMinSize, inMaxSize); + return std::min(areaSize / inAvailableSize, 0.5f); + } +} + +namespace Editor { + void EditorTabs::Render() + { + for (const auto& tab : tabs) { + tab->Render(); + } + } + + void EditorTabs::RenderViewMenuItems() + { + for (const auto& tab : tabs) { + tab->RenderViewMenuItem(); + } + } + + void EditorTabs::BuildInitialDockLayout(ImGuiID inDockSpaceId, const ImVec2& inSize) const + { + if (ImGui::DockBuilderGetNode(inDockSpaceId) != nullptr) { + return; + } + ImGui::DockBuilderAddNode(inDockSpaceId, ImGuiDockNodeFlags_DockSpace); + ImGui::DockBuilderSetNodeSize(inDockSpaceId, inSize); + + ImGuiID centerNodeId = 0; + ImGuiID rightColumnNodeId = 0; + ImGuiID rightTopNodeId = 0; + ImGuiID rightBottomNodeId = 0; + ImGuiID bottomNodeId = 0; + const float rightColumnRatio = TabLayout::Internal::CalculateDockRatio(inSize.x, TabLayout::Internal::defaultRightColumnRatio, TabLayout::Internal::minRightColumnWidth, TabLayout::Internal::maxRightColumnWidth); + const float bottomRatio = TabLayout::Internal::CalculateDockRatio(inSize.y, TabLayout::Internal::defaultBottomAreaRatio, TabLayout::Internal::minBottomAreaHeight, TabLayout::Internal::maxBottomAreaHeight); + const float rightTopRatio = TabLayout::Internal::CalculateDockRatio(inSize.y, TabLayout::Internal::defaultRightTopRatio, TabLayout::Internal::minRightTopHeight, TabLayout::Internal::maxRightTopHeight); + ImGui::DockBuilderSplitNode(inDockSpaceId, ImGuiDir_Right, rightColumnRatio, &rightColumnNodeId, ¢erNodeId); + ImGui::DockBuilderSplitNode(centerNodeId, ImGuiDir_Down, bottomRatio, &bottomNodeId, ¢erNodeId); + ImGui::DockBuilderSplitNode(rightColumnNodeId, ImGuiDir_Up, rightTopRatio, &rightTopNodeId, &rightBottomNodeId); + + for (const auto& tab : tabs) { + ImGuiID nodeId = centerNodeId; + switch (tab->GetDesc().defaultDockArea) { + case TabDockArea::center: nodeId = centerNodeId; break; + case TabDockArea::rightTop: nodeId = rightTopNodeId; break; + case TabDockArea::rightBottom: nodeId = rightBottomNodeId; break; + case TabDockArea::bottom: nodeId = bottomNodeId; break; + } + ImGui::DockBuilderDockWindow(tab->GetWindowName().c_str(), nodeId); + } + ImGui::DockBuilderFinish(inDockSpaceId); + } +} diff --git a/Editor/Src/Tab/InspectorTab.cpp b/Editor/Src/Tab/InspectorTab.cpp new file mode 100644 index 000000000..39ce16765 --- /dev/null +++ b/Editor/Src/Tab/InspectorTab.cpp @@ -0,0 +1,138 @@ +#include +#include + +#include +#include +#include +#include +#include + +namespace Editor::Inspector::Internal { + static std::string ComponentDisplayName(const Mirror::Class& inClass) + { + const std::string& qualifiedName = inClass.GetName(); + const size_t namespaceSeparator = qualifiedName.rfind("::"); + return namespaceSeparator == std::string::npos + ? qualifiedName + : qualifiedName.substr(namespaceSeparator + 2); + } + + static bool IsComponentVisibleInDetails(const Mirror::Class& inClass) + { + return !inClass.HasMeta(Runtime::MetaPresets::editorHide); + } +} + +namespace Editor { + InspectorTab::InspectorTab(EditorContext& inContext) + : EditorTab(EditorTabDesc { + .id = "Inspector", + .title = "Inspector", + .icon = Icons::Tabler::adjustmentsHorizontal, + .defaultDockArea = TabDockArea::rightBottom + }) + , context(inContext) + , componentClasses(Mirror::Class::GetAll()) + { + std::erase_if(componentClasses, [](Runtime::CompClass inClass) -> bool { + return !inClass->HasMeta("comp") || !Inspector::Internal::IsComponentVisibleInDetails(*inClass); + }); + std::ranges::sort(componentClasses, [](Runtime::CompClass lhs, Runtime::CompClass rhs) -> bool { + return lhs->GetName() < rhs->GetName(); + }); + } + + void InspectorTab::RenderContents() + { + context.GetSceneClient().GetWorld().EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + RenderComponents(inRegistry); + }); + } + + void InspectorTab::RenderComponents(Runtime::ECRegistry& inRegistry) + { + const Runtime::Entity selectedEntity = context.GetSelectedEntity(); + if (selectedEntity == Runtime::entityNull || !inRegistry.Valid(selectedEntity)) { + ImGui::TextDisabled("No entity selected"); + return; + } + ImGui::PushID(static_cast(selectedEntity)); + + std::vector addableComponents; + for (const auto* clazz : componentClasses) { + if (context.CanAddComponent(inRegistry, selectedEntity, clazz)) { + addableComponents.emplace_back(clazz); + } + } + + ImGui::BeginDisabled(addableComponents.empty()); + const std::string addComponentLabel = Widgets::Label(Icons::Tabler::plus, "Add Component"); + if (ImGui::Button(addComponentLabel.c_str())) { + ImGui::OpenPopup("AddComponentMenu"); + } + ImGui::EndDisabled(); + if (ImGui::BeginPopup("AddComponentMenu")) { + for (const auto* clazz : addableComponents) { + const std::string componentName = Inspector::Internal::ComponentDisplayName(*clazz); + ImGui::PushID(clazz->GetName().c_str()); + const std::string componentLabel = Widgets::Label(Icons::Tabler::boxMultiple, componentName); + if (ImGui::MenuItem(componentLabel.c_str())) { + context.AddComponent(inRegistry, selectedEntity, clazz); + } + ImGui::PopID(); + } + ImGui::EndPopup(); + } + ImGui::Separator(); + + Runtime::CompClass componentToRemove = nullptr; + inRegistry.CompEach(selectedEntity, [&](Runtime::CompClass compClass) -> void { + if (!Inspector::Internal::IsComponentVisibleInDetails(*compClass)) { + return; + } + ImGui::PushID(compClass->GetName().c_str()); + const std::string componentName = Inspector::Internal::ComponentDisplayName(*compClass); + const std::string componentLabel = Widgets::Label(Icons::Tabler::boxMultiple, componentName); + const bool open = ImGui::CollapsingHeader(componentLabel.c_str(), ImGuiTreeNodeFlags_DefaultOpen); + if (context.CanRemoveComponent(inRegistry, selectedEntity, compClass) && ImGui::BeginPopupContextItem("ComponentMenu")) { + const std::string removeLabel = Widgets::Label(Icons::Tabler::trash, "Remove"); + if (ImGui::MenuItem(removeLabel.c_str())) { + componentToRemove = compClass; + } + ImGui::EndPopup(); + } + if (open && componentToRemove != compClass) { + const Mirror::Any compRef = inRegistry.GetDyn(compClass, selectedEntity); + for (const auto& memberVariable : compClass->GetMemberVariables() | std::views::values) { + const Mirror::Any memberRef = memberVariable.GetDyn(compRef); + Mirror::Any memberValue = memberRef.Value(); + if (RenderInputWidget(memberVariable.GetName(), memberValue)) { + context.SetComponentMember(inRegistry, selectedEntity, compClass, memberVariable, memberValue); + } + } + } + ImGui::PopID(); + }); + inRegistry.TagEach(selectedEntity, [&](Runtime::TagClass tagClass) -> void { + if (!Inspector::Internal::IsComponentVisibleInDetails(*tagClass)) { + return; + } + ImGui::PushID(tagClass->GetName().c_str()); + const std::string tagName = Inspector::Internal::ComponentDisplayName(*tagClass); + const std::string tagLabel = Widgets::Label(Icons::Tabler::box, tagName); + ImGui::TextUnformatted(tagLabel.c_str()); + if (context.CanRemoveComponent(inRegistry, selectedEntity, tagClass) && ImGui::BeginPopupContextItem("ComponentMenu")) { + const std::string removeLabel = Widgets::Label(Icons::Tabler::trash, "Remove"); + if (ImGui::MenuItem(removeLabel.c_str())) { + componentToRemove = tagClass; + } + ImGui::EndPopup(); + } + ImGui::PopID(); + }); + if (componentToRemove != nullptr) { + context.RemoveComponent(inRegistry, selectedEntity, componentToRemove); + } + ImGui::PopID(); + } +} diff --git a/Editor/Src/Tab/LogTab.cpp b/Editor/Src/Tab/LogTab.cpp new file mode 100644 index 000000000..c429af0a2 --- /dev/null +++ b/Editor/Src/Tab/LogTab.cpp @@ -0,0 +1,70 @@ +#include + +#include +#include +#include +#include + +namespace Editor::Log::Internal { + static std::string LevelString(Core::LogLevel inLevel) + { + switch (inLevel) { + case Core::LogLevel::verbose: + return "verbose"; + case Core::LogLevel::info: + return "info"; + case Core::LogLevel::warning: + return "warning"; + case Core::LogLevel::error: + return "error"; + default: + return "unknown"; + } + } +} + +namespace Editor { + LogTab::LogTab(EditorLogStream& inLogStream) + : EditorTab(EditorTabDesc { + .id = "Log", + .title = "Log", + .icon = Icons::Tabler::terminal2, + .defaultDockArea = TabDockArea::bottom + }) + , logStream(inLogStream) + { + } + + void LogTab::RenderContents() + { + const auto entries = logStream.Snapshot(); + const std::string copyLabel = Widgets::Label(Icons::Tabler::copy, "Copy"); + if (ImGui::Button(copyLabel.c_str())) { + std::string text; + for (const auto& entry : entries) { + text += std::format("[{}][{}][{}] {}\n", entry.time, Log::Internal::LevelString(entry.level), entry.tag, entry.content); + } + ImGui::SetClipboardText(text.c_str()); + } + ImGui::Separator(); + ImGui::BeginChild("LogEntries", ImVec2(0.0f, 0.0f), false, ImGuiWindowFlags_HorizontalScrollbar); + for (const auto& entry : entries) { + const char* levelIcon = Icons::Tabler::infoCircle; + if (entry.level == Core::LogLevel::warning) { + Widgets::PushWarningTextColor(); + levelIcon = Icons::Tabler::alertTriangle; + } else if (entry.level == Core::LogLevel::error) { + Widgets::PushErrorTextColor(); + levelIcon = Icons::Tabler::circleX; + } else { + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_Text)); + } + ImGui::TextUnformatted(std::format("{} [{}][{}][{}] {}", levelIcon, entry.time, Log::Internal::LevelString(entry.level), entry.tag, entry.content).c_str()); + ImGui::PopStyleColor(); + } + if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) { + ImGui::SetScrollHereY(1.0f); + } + ImGui::EndChild(); + } +} diff --git a/Editor/Src/Tab/OutlinerTab.cpp b/Editor/Src/Tab/OutlinerTab.cpp new file mode 100644 index 000000000..f1769ecd4 --- /dev/null +++ b/Editor/Src/Tab/OutlinerTab.cpp @@ -0,0 +1,88 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Editor::Outliner::Internal { + static std::string EntityDisplayName(const Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity) + { + const auto* name = inRegistry.Find(inEntity); + return name != nullptr && !name->value.empty() + ? name->value + : std::format("Entity {}", inEntity); + } +} + +namespace Editor { + OutlinerTab::OutlinerTab(EditorContext& inContext) + : EditorTab(EditorTabDesc { + .id = "Outliner", + .title = "Outliner", + .icon = Icons::Tabler::hierarchy2, + .defaultDockArea = TabDockArea::rightTop + }) + , context(inContext) + , createEntityName("Entity") + { + } + + void OutlinerTab::RenderContents() + { + context.GetSceneClient().GetWorld().EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + RenderEntities(inRegistry); + }); + } + + void OutlinerTab::RenderEntities(Runtime::ECRegistry& inRegistry) + { + const std::string newEntityLabel = Widgets::Label(Icons::Tabler::plus, "New Entity"); + if (ImGui::Button(newEntityLabel.c_str())) { + ImGui::OpenPopup("NewEntityMenu"); + } + ImGui::SetNextWindowSize(ImVec2(260.0f, 0.0f), ImGuiCond_Appearing); + if (ImGui::BeginPopup("NewEntityMenu")) { + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputText("##EntityName", &createEntityName); + const std::string createLabel = Widgets::Label(Icons::Tabler::check, "Create"); + if (ImGui::Button(createLabel.c_str(), ImVec2(ImGui::GetContentRegionAvail().x, 0.0f))) { + const auto entity = context.CreateEntity(inRegistry, createEntityName); + context.SetSelectedEntity(entity); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + ImGui::Separator(); + + Runtime::Entity entityToDelete = Runtime::entityNull; + inRegistry.Each([&](Runtime::Entity entity) -> void { + if (inRegistry.Has(entity)) { + return; + } + const std::string label = Widgets::Label(Icons::Tabler::box, Outliner::Internal::EntityDisplayName(inRegistry, entity)); + const bool selected = context.GetSelectedEntity() == entity; + ImGui::PushID(static_cast(entity)); + if (ImGui::Selectable(label.c_str(), selected)) { + context.SetSelectedEntity(entity); + } + if (ImGui::BeginPopupContextItem("EntityMenu")) { + context.SetSelectedEntity(entity); + const std::string deleteLabel = Widgets::Label(Icons::Tabler::trash, "Delete"); + if (ImGui::MenuItem(deleteLabel.c_str())) { + entityToDelete = entity; + } + ImGui::EndPopup(); + } + ImGui::PopID(); + }); + if (entityToDelete != Runtime::entityNull) { + context.DestroyEntity(inRegistry, entityToDelete); + } + } +} diff --git a/Editor/Src/Tab/SceneTab.cpp b/Editor/Src/Tab/SceneTab.cpp new file mode 100644 index 000000000..fc6a00a21 --- /dev/null +++ b/Editor/Src/Tab/SceneTab.cpp @@ -0,0 +1,45 @@ +#include +#include + +#include +#include +#include +#include + +namespace Editor { + SceneTab::SceneTab(SceneClient& inSceneClient, Runtime::Canvas& inCanvas) + : EditorTab(EditorTabDesc { + .id = "Scene", + .title = "Scene", + .icon = Icons::Tabler::viewportWide, + .defaultDockArea = TabDockArea::center, + .windowFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse, + .contentPadding = false + }) + , sceneClient(inSceneClient) + , canvas(inCanvas) + { + } + + void SceneTab::RenderContents() + { + ImVec2 size = ImGui::GetContentRegionAvail(); + size.x = std::max(size.x, 1.0f); + size.y = std::max(size.y, 1.0f); + + const ImVec2 framebufferScale = ImGui::GetIO().DisplayFramebufferScale; + sceneClient.ResizeRenderSurface( + std::max(1u, static_cast(size.x * framebufferScale.x)), + std::max(1u, static_cast(size.y * framebufferScale.y))); + ImGui::Image(static_cast(reinterpret_cast(canvas.GetTextureView())), size); + sceneClient.SetSceneHovered(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)); + sceneClient.SetSceneFocused(ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)); + } + + void SceneTab::OnHidden() + { + sceneClient.EndCameraLook(); + sceneClient.SetSceneHovered(false); + sceneClient.SetSceneFocused(false); + } +} diff --git a/Editor/Test/ImGuiDrawDataTest.cpp b/Editor/Test/ImGuiDrawDataTest.cpp deleted file mode 100644 index 4faab7d97..000000000 --- a/Editor/Test/ImGuiDrawDataTest.cpp +++ /dev/null @@ -1,67 +0,0 @@ -#include - -#include -#include - -namespace Editor::Test { - TEST(ImGuiDrawDataTest, SnapshotsTextureIdsAndOwnedCallbackPayloads) - { - ImTextureData texture; - texture.SetTexID(123); - ImDrawList source(nullptr); - source._CallbacksDataBuf.resize(sizeof(int)); - const int originalValue = 42; - std::memcpy(source._CallbacksDataBuf.Data, &originalValue, sizeof(int)); - ImDrawCmd command; - command.TexRef = texture.GetTexRef(); - command.UserCallback = [](const ImDrawList*, const ImDrawCmd*) -> void {}; - command.UserCallbackData = source._CallbacksDataBuf.Data; - command.UserCallbackDataSize = sizeof(int); - command.UserCallbackDataOffset = 0; - source.CmdBuffer.push_back(command); - ImDrawData sourceData; - sourceData.CmdListsCount = 1; - sourceData.CmdLists.push_back(&source); - - ImGuiDrawData snapshot(sourceData); - texture.SetTexID(456); - const int changedValue = 99; - std::memcpy(source._CallbacksDataBuf.Data, &changedValue, sizeof(int)); - const ImDrawCmd& cloned = snapshot.Get().CmdLists[0]->CmdBuffer[0]; - EXPECT_EQ(cloned.GetTexID(), 123); - EXPECT_EQ(cloned.TexRef._TexData, nullptr); - EXPECT_NE(cloned.UserCallbackData, command.UserCallbackData); - int clonedValue = 0; - std::memcpy(&clonedValue, cloned.UserCallbackData, sizeof(int)); - EXPECT_EQ(clonedValue, originalValue); - } - - TEST(ImGuiDrawDataTest, KeepsClonedCommandsAfterTheOriginalFrameIsReused) - { - ImGuiContext* context = ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - io.IniFilename = nullptr; - io.DisplaySize = ImVec2(640.0f, 480.0f); - unsigned char* pixels = nullptr; - int width = 0; - int height = 0; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - - ImGui::NewFrame(); - ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(10.0f, 20.0f), ImVec2(30.0f, 40.0f), IM_COL32_WHITE); - ImGui::Render(); - { - ImGuiDrawData snapshot(*ImGui::GetDrawData()); - ASSERT_EQ(snapshot.Get().CmdListsCount, 1); - EXPECT_NE(snapshot.Get().CmdLists[0], ImGui::GetDrawData()->CmdLists[0]); - const int vertexCount = snapshot.Get().TotalVtxCount; - ImGui::NewFrame(); - ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(100.0f, 200.0f), ImVec2(300.0f, 400.0f), IM_COL32_WHITE); - ImGui::Render(); - EXPECT_EQ(snapshot.Get().TotalVtxCount, vertexCount); - EXPECT_FLOAT_EQ(snapshot.Get().CmdLists[0]->VtxBuffer[0].pos.x, 10.0f); - EXPECT_FLOAT_EQ(snapshot.Get().CmdLists[0]->VtxBuffer[0].pos.y, 20.0f); - } - ImGui::DestroyContext(context); - } -} From 846380b27fb1e21179cf96faa327aa384c78a676 Mon Sep 17 00:00:00 2001 From: kindem Date: Sun, 15 Nov 2026 18:03:04 +0800 Subject: [PATCH 4/4] refactor: separate editor windows and runtime viewports --- Editor/Include/Editor/EditorApplication.h | 34 +- Editor/Include/Editor/EditorContext.h | 17 +- Editor/Include/Editor/EditorMainWindow.h | 34 ++ Editor/Include/Editor/EditorWindow.h | 59 --- Editor/Include/Editor/Frame/EditorFrame.h | 29 -- .../Editor/ImGui/ImGuiPlatformBackend.h | 19 +- .../Include/Editor/ImGui/ImGuiRhiRenderer.h | 11 +- Editor/Include/Editor/ImGui/ImGuiWindow.h | 59 +++ .../ProjectHubFrame.h => ProjectHubWindow.h} | 11 +- Editor/Include/Editor/SceneClient.h | 42 +-- Editor/Include/Editor/SceneViewport.h | 45 +++ Editor/Include/Editor/System/Camera.h | 2 +- Editor/Include/Editor/Tab/SceneTab.h | 11 +- Editor/Src/EditorApplication.cpp | 242 +----------- Editor/Src/EditorContext.cpp | 193 +++++++++- Editor/Src/EditorMainWindow.cpp | 163 ++++++++ Editor/Src/EditorWindow.cpp | 180 --------- Editor/Src/Frame/EditorFrame.cpp | 92 ----- Editor/Src/ImGui/ImGuiPlatformBackend.cpp | 67 +++- Editor/Src/ImGui/ImGuiRhiRenderer.cpp | 61 +-- Editor/Src/ImGui/ImGuiWindow.cpp | 181 +++++++++ ...ojectHubFrame.cpp => ProjectHubWindow.cpp} | 23 +- Editor/Src/SceneClient.cpp | 357 +----------------- Editor/Src/SceneViewport.cpp | 190 ++++++++++ Editor/Src/System/Camera.cpp | 26 +- Editor/Src/SystemGraphPresets.cpp | 6 +- Editor/Src/Tab/InspectorTab.cpp | 2 +- Editor/Src/Tab/OutlinerTab.cpp | 2 +- Editor/Src/Tab/SceneTab.cpp | 21 +- Engine/Source/Launch/CMakeLists.txt | 5 +- .../Launch/Include/Launch/GameApplication.h | 4 +- .../Source/Launch/Include/Launch/GameClient.h | 13 +- .../Launch/Include/Launch/GameViewport.h | 21 ++ .../Source/Launch/Include/Launch/GameWindow.h | 35 +- Engine/Source/Launch/Src/GameApplication.cpp | 20 +- Engine/Source/Launch/Src/GameClient.cpp | 17 +- Engine/Source/Launch/Src/GameViewport.cpp | 54 +++ Engine/Source/Launch/Src/GameWindow.cpp | 110 ++++-- .../Include/Render}/Canvas.h | 13 +- .../Render/Include/Render/RenderSurface.h | 40 ++ .../Render/Include/Render/SwapChainSurface.h | 48 +++ .../Source/{Runtime => Render}/Src/Canvas.cpp | 36 +- .../{Runtime => Render}/Src/RenderSurface.cpp | 4 +- Engine/Source/Render/Src/SwapChainSurface.cpp | 166 ++++++++ .../Source/Runtime/Include/Runtime/Client.h | 2 - .../Include/Runtime/Component/Camera.h | 5 - Engine/Source/Runtime/Include/Runtime/ECS.h | 2 - .../Source/Runtime/Include/Runtime/Engine.h | 4 + .../Runtime/Include/Runtime/RenderSurface.h | 28 -- .../Runtime/Include/Runtime/System/Render.h | 37 -- .../Source/Runtime/Include/Runtime/Viewport.h | 34 ++ .../Source/Runtime/Include/Runtime/Window.h | 58 +-- Engine/Source/Runtime/Include/Runtime/World.h | 6 +- .../Source/Runtime/Src/Component/Camera.cpp | 1 - Engine/Source/Runtime/Src/ECS.cpp | 1 - Engine/Source/Runtime/Src/Engine.cpp | 22 +- Engine/Source/Runtime/Src/System/Render.cpp | 154 -------- .../Source/Runtime/Src/SystemGraphPresets.cpp | 6 +- Engine/Source/Runtime/Src/Viewport.cpp | 97 +++++ Engine/Source/Runtime/Src/Window.cpp | 163 +------- Engine/Source/Runtime/Src/World.cpp | 3 +- Engine/Source/Runtime/Test/WorldTest.cpp | 6 +- Sample/Base/Application.cpp | 4 +- Sample/Base/Application.h | 2 +- Sample/Base/RenderTarget.cpp | 4 +- Sample/Base/RenderTarget.h | 2 +- 66 files changed, 1688 insertions(+), 1718 deletions(-) create mode 100644 Editor/Include/Editor/EditorMainWindow.h delete mode 100644 Editor/Include/Editor/EditorWindow.h delete mode 100644 Editor/Include/Editor/Frame/EditorFrame.h create mode 100644 Editor/Include/Editor/ImGui/ImGuiWindow.h rename Editor/Include/Editor/{Frame/ProjectHubFrame.h => ProjectHubWindow.h} (70%) create mode 100644 Editor/Include/Editor/SceneViewport.h create mode 100644 Editor/Src/EditorMainWindow.cpp delete mode 100644 Editor/Src/EditorWindow.cpp delete mode 100644 Editor/Src/Frame/EditorFrame.cpp create mode 100644 Editor/Src/ImGui/ImGuiWindow.cpp rename Editor/Src/{Frame/ProjectHubFrame.cpp => ProjectHubWindow.cpp} (94%) create mode 100644 Editor/Src/SceneViewport.cpp create mode 100644 Engine/Source/Launch/Include/Launch/GameViewport.h create mode 100644 Engine/Source/Launch/Src/GameViewport.cpp rename Engine/Source/{Runtime/Include/Runtime => Render/Include/Render}/Canvas.h (75%) create mode 100644 Engine/Source/Render/Include/Render/RenderSurface.h create mode 100644 Engine/Source/Render/Include/Render/SwapChainSurface.h rename Engine/Source/{Runtime => Render}/Src/Canvas.cpp (72%) rename Engine/Source/{Runtime => Render}/Src/RenderSurface.cpp (71%) create mode 100644 Engine/Source/Render/Src/SwapChainSurface.cpp delete mode 100644 Engine/Source/Runtime/Include/Runtime/RenderSurface.h delete mode 100644 Engine/Source/Runtime/Include/Runtime/System/Render.h create mode 100644 Engine/Source/Runtime/Include/Runtime/Viewport.h delete mode 100644 Engine/Source/Runtime/Src/System/Render.cpp create mode 100644 Engine/Source/Runtime/Src/Viewport.cpp diff --git a/Editor/Include/Editor/EditorApplication.h b/Editor/Include/Editor/EditorApplication.h index c184e17ff..099ea2964 100644 --- a/Editor/Include/Editor/EditorApplication.h +++ b/Editor/Include/Editor/EditorApplication.h @@ -1,17 +1,11 @@ -// -// Created by johnk on 2026/7/7. -// - #pragma once #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include namespace Editor { enum class EditorApplicationMode : uint8_t { @@ -38,31 +32,13 @@ namespace Editor { int Run(); private: - void InitializeImGui(); - void ShutdownImGui(); - void InstallCallbacks(); - void RenderEditorFrame(); - void HandleKey(int inKey, int inAction); - void HandleMouseButton(int inButton, int inAction); - void HandleCursor(double inX, double inY); float NextDeltaSeconds(); - EditorApplicationDesc desc; - std::string imguiIniFilename; - Common::UniquePtr window; - Common::UniquePtr imguiPlatform; - Common::UniquePtr imguiRenderer; Common::UniquePtr context; - Common::UniquePtr sceneRenderCanvas; Common::UniquePtr projectService; Common::UniquePtr recentProjects; Common::UniquePtr projectLauncher; - Common::UniquePtr projectHubFrame; - Common::UniquePtr editorFrame; + Common::UniquePtr mainWindow; double lastFrameSeconds; - double lastCursorX; - double lastCursorY; - bool hasLastCursor; - bool requestQuit; }; } diff --git a/Editor/Include/Editor/EditorContext.h b/Editor/Include/Editor/EditorContext.h index 9848ef9a7..4a6c3c7ac 100644 --- a/Editor/Include/Editor/EditorContext.h +++ b/Editor/Include/Editor/EditorContext.h @@ -5,7 +5,8 @@ #pragma once #include -#include +#include +#include #include namespace Editor { @@ -14,7 +15,9 @@ namespace Editor { EditorContext(); ~EditorContext(); - SceneClient& GetSceneClient() const; + Runtime::World& GetWorld(); + void OpenProjectLevel(); + void SaveLevel(); Runtime::Entity GetSelectedEntity() const; bool CanAddComponent(const Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity, Runtime::CompClass inClass) const; bool CanRemoveComponent(const Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity, Runtime::CompClass inClass) const; @@ -24,15 +27,11 @@ namespace Editor { void DestroyEntity(Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity); bool AddComponent(Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity, Runtime::CompClass inClass); bool RemoveComponent(Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity, Runtime::CompClass inClass); - bool SetComponentMember( - Runtime::ECRegistry& inRegistry, - Runtime::Entity inEntity, - Runtime::CompClass inClass, - const Mirror::MemberVariable& inMemberVariable, - const Mirror::Any& inValue); + bool SetComponentMember(Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity, Runtime::CompClass inClass, const Mirror::MemberVariable& inMemberVariable, const Mirror::Any& inValue); private: - Common::UniquePtr sceneClient; + Core::Uri levelUri; + Runtime::World world; Runtime::Entity selectedEntity; }; } diff --git a/Editor/Include/Editor/EditorMainWindow.h b/Editor/Include/Editor/EditorMainWindow.h new file mode 100644 index 000000000..6faf14203 --- /dev/null +++ b/Editor/Include/Editor/EditorMainWindow.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include +#include + +namespace Editor { + class EditorContext; + class EditorLogStream; + + class EditorMainWindow final : public ImGuiWindow { + public: + EditorMainWindow(EditorContext& inContext, EditorLogStream& inLogStream, Common::Path inAssetDirectory); + ~EditorMainWindow() override; + + void Render(float inDeltaSeconds) override; + + private: + void RenderContents() override; + void DrawDockSpace() const; + void RenderMenuBar(); + void HandleKey(int inKey, int inAction); + void HandleMouseButton(int inButton, int inAction); + void HandleCursor(double inX, double inY); + + EditorContext& context; + // Releasing viewport mouse capture during destruction can dispatch a cursor callback. + double lastCursorX; + double lastCursorY; + bool hasLastCursor; + SceneViewport sceneViewport; + EditorTabs tabs; + }; +} diff --git a/Editor/Include/Editor/EditorWindow.h b/Editor/Include/Editor/EditorWindow.h deleted file mode 100644 index 8658c917f..000000000 --- a/Editor/Include/Editor/EditorWindow.h +++ /dev/null @@ -1,59 +0,0 @@ -#pragma once - -#include - -#include -#include - -struct GLFWwindow; - -namespace Render { - class RenderThread; -} - -namespace Editor { - struct EditorWindowDesc { - std::string title; - uint32_t width; - uint32_t height; - bool maximized; - }; - - class EditorWindow final : public Runtime::Window { - public: - EditorWindow(RHI::Device& inDevice, Render::RenderThread& inRenderThread, const EditorWindowDesc& inDesc); - ~EditorWindow() override; - - NonCopyable(EditorWindow) - NonMovable(EditorWindow) - - GLFWwindow* GetNativeWindow() const; - uint32_t GetWidth() const; - uint32_t GetHeight() const; - uint32_t GetFramebufferWidth() const; - uint32_t GetFramebufferHeight() const; - bool ShouldClose() const; - void RequestClose() const; - void PollEvents() const; - void SetTitle(const std::string& inTitle) const; - void SetCursorCaptured(bool inCaptured) const; - void RecreateSwapChainIfNeeded(); - void WaitRenderingIdle() const; - - Common::Delegate onKey; - Common::Delegate onChar; - Common::Delegate onMouseButton; - Common::Delegate onCursor; - Common::Delegate onScroll; - Common::Delegate onFocus; - - private: - void InstallCallbacks(); - void* GetPlatformWindow() const; - - Render::RenderThread& renderThread; - GLFWwindow* window; - uint32_t framebufferWidth; - uint32_t framebufferHeight; - }; -} diff --git a/Editor/Include/Editor/Frame/EditorFrame.h b/Editor/Include/Editor/Frame/EditorFrame.h deleted file mode 100644 index 682e81e9e..000000000 --- a/Editor/Include/Editor/Frame/EditorFrame.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -#include - -namespace Runtime { - class Canvas; -} - -namespace Editor { - class EditorContext; - class EditorLogStream; - - class EditorFrame final { - public: - EditorFrame(EditorContext& inContext, Runtime::Canvas& inSceneRenderCanvas, EditorLogStream& inLogStream, Common::Path inAssetDirectory); - ~EditorFrame(); - - void Render(bool& outRequestQuit); - - private: - void DrawDockSpace() const; - void RenderMenuBar(bool& outRequestQuit); - - EditorContext& context; - EditorTabs tabs; - }; -} diff --git a/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h b/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h index 9d2e95d6d..56713b82b 100644 --- a/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h +++ b/Editor/Include/Editor/ImGui/ImGuiPlatformBackend.h @@ -1,13 +1,16 @@ #pragma once -#include +#include + +struct GLFWwindow; +struct ImGuiContext; namespace Editor { - class EditorWindow; + struct ImGuiWindowDesc; class ImGuiPlatformBackend final { public: - explicit ImGuiPlatformBackend(EditorWindow& inWindow); + ImGuiPlatformBackend(GLFWwindow* inWindow, const ImGuiWindowDesc& inDesc); ~ImGuiPlatformBackend(); NonCopyable(ImGuiPlatformBackend) @@ -16,12 +19,8 @@ namespace Editor { void NewFrame(float inDeltaSeconds) const; private: - EditorWindow& window; - Common::CallbackHandle keyHandle; - Common::CallbackHandle charHandle; - Common::CallbackHandle mouseButtonHandle; - Common::CallbackHandle cursorHandle; - Common::CallbackHandle scrollHandle; - Common::CallbackHandle focusHandle; + GLFWwindow* window; + const ImGuiWindowDesc& desc; + ImGuiContext* context; }; } diff --git a/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h b/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h index 9639874bf..2136c83c6 100644 --- a/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h +++ b/Editor/Include/Editor/ImGui/ImGuiRhiRenderer.h @@ -6,7 +6,8 @@ #include #include #include -#include +#include +#include struct ImDrawData; @@ -22,7 +23,7 @@ namespace Editor { class ImGuiRhiRenderer final { public: - ImGuiRhiRenderer(Runtime::Window& inWindow, Render::RenderThread& inRenderThread); + ImGuiRhiRenderer(RHI::Device& inDevice, Render::RenderSurface& inSurface, Render::RenderThread& inRenderThread); ~ImGuiRhiRenderer(); NonCopyable(ImGuiRhiRenderer) @@ -31,10 +32,11 @@ namespace Editor { void NewFrame(); void Submit(const ImDrawData& inDrawData); void WaitIdle() const; + void WaitForPreviousFrame() const; private: void RenderFrame(const Common::SharedPtr& inDrawData); - void RenderUiPass(ImDrawData& inDrawData); + void RenderUiPass(ImDrawData& inDrawData, const Render::SurfaceTarget& inTarget); void RenderImGuiDrawData(ImDrawData& inDrawData, RHI::RasterPassCommandRecorder& inRecorder); void CreateImGuiDeviceObjects(); void CreateImGuiFontTexture(); @@ -43,7 +45,8 @@ namespace Editor { void UpdateImGuiPassParams(const ImDrawData& inDrawData); RHI::BindGroup* GetOrCreateImGuiTextureBindGroup(RHI::TextureView& inTextureView); - Runtime::Window& window; + RHI::Device& device; + Render::RenderSurface& surface; Render::RenderThread& renderThread; RHI::PixelFormat pipelineFormat; Common::SharedPtr inFlightDrawData; diff --git a/Editor/Include/Editor/ImGui/ImGuiWindow.h b/Editor/Include/Editor/ImGui/ImGuiWindow.h new file mode 100644 index 000000000..27d8b68b7 --- /dev/null +++ b/Editor/Include/Editor/ImGui/ImGuiWindow.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +struct GLFWwindow; +struct ImGuiContext; + +namespace Editor { + struct ImGuiWindowDesc { + std::string title; + uint32_t width; + uint32_t height; + bool maximized = false; + Common::Path layoutFile; + std::function onKey; + std::function onChar; + std::function onMouseButton; + std::function onCursor; + std::function onScroll; + std::function onFocus; + }; + + class ImGuiWindow : public Runtime::Window { + public: + ~ImGuiWindow() override; + + bool ShouldClose() const override; + void RequestClose() const override; + void Tick(float inDeltaSeconds) override; + void Render(float inDeltaSeconds) override; + void WaitIdle() const override; + + protected: + explicit ImGuiWindow(ImGuiWindowDesc inDesc); + + GLFWwindow* GetNativeWindow() const; + Render::SwapChainSurface& GetSwapChainSurface(); + virtual void RenderContents() = 0; + + private: + void InitializeImGui(); + + ImGuiWindowDesc desc; + GLFWwindow* window; + Render::RenderThread& renderThread; + Common::UniquePtr swapChainSurface; + ImGuiContext* imguiContext; + std::string imguiIniFilename; + Common::UniquePtr imguiPlatform; + Common::UniquePtr imguiRenderer; + }; +} diff --git a/Editor/Include/Editor/Frame/ProjectHubFrame.h b/Editor/Include/Editor/ProjectHubWindow.h similarity index 70% rename from Editor/Include/Editor/Frame/ProjectHubFrame.h rename to Editor/Include/Editor/ProjectHubWindow.h index 425d45f3b..2f5042342 100644 --- a/Editor/Include/Editor/Frame/ProjectHubFrame.h +++ b/Editor/Include/Editor/ProjectHubWindow.h @@ -3,19 +3,19 @@ #include #include +#include #include #include #include namespace Editor { - class ProjectHubFrame final { + class ProjectHubWindow final : public ImGuiWindow { public: - ProjectHubFrame(ProjectService& inProjectService, RecentProjectStore& inRecentProjects, ProjectLauncher& inProjectLauncher); - ~ProjectHubFrame(); - - bool Render(); + ProjectHubWindow(ProjectService& inProjectService, RecentProjectStore& inRecentProjects, ProjectLauncher& inProjectLauncher); + ~ProjectHubWindow() override; private: + void RenderContents() override; void RenderActionBar(); void RenderRecentProjects(); void RenderCreateProjectPopup(); @@ -29,6 +29,5 @@ namespace Editor { std::string directory; int selectedTemplateIndex; std::string statusMessage; - bool requestClose; }; } diff --git a/Editor/Include/Editor/SceneClient.h b/Editor/Include/Editor/SceneClient.h index 36fe19ff1..90f649219 100644 --- a/Editor/Include/Editor/SceneClient.h +++ b/Editor/Include/Editor/SceneClient.h @@ -1,54 +1,16 @@ -// -// Created by johnk on 2026/7/4. -// - #pragma once -#include - -#include #include -#include namespace Editor { - class EditorWindow; - class SceneClient final : public Runtime::Client { public: - SceneClient(); + explicit SceneClient(Runtime::World& inWorld); ~SceneClient() override; - NonCopyable(SceneClient) - NonMovable(SceneClient) - Runtime::World& GetWorld() override; - Runtime::RenderSurface* GetRenderSurface() override; - void SetEditorWindow(EditorWindow& inWindow); - void SetRenderSurface(Runtime::RenderSurface* inRenderSurface); - void ResizeRenderSurface(uint32_t inWidth, uint32_t inHeight); - // loads the project's main level when present, otherwise authors the default level content (player start, - // ground and a cube using engine-default unlit assets materialized into the project) and saves it - void OpenProjectLevel(); - void SaveLevel(); - // the transient camera entity the editor scene renders through and moves, entityNull before the level is opened - Runtime::Entity GetEditorCamera() const; - void SetSceneHovered(bool inHovered); - void SetSceneFocused(bool inFocused); - bool IsSceneHovered() const; - bool IsCameraLooking(); - void OnKey(int inKey, bool inPressed); - void BeginCameraLook(); - void EndCameraLook(); - void AddCameraLookDelta(float inDeltaX, float inDeltaY); private: - void CreateEditorCamera(); - - Core::Uri levelUri; - Runtime::World world; - EditorWindow* window; - Runtime::RenderSurface* renderSurface; - Runtime::Entity editorCamera; - bool sceneHovered; + Runtime::World& world; }; } diff --git a/Editor/Include/Editor/SceneViewport.h b/Editor/Include/Editor/SceneViewport.h new file mode 100644 index 000000000..a8237f6ea --- /dev/null +++ b/Editor/Include/Editor/SceneViewport.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include + +struct GLFWwindow; + +namespace Editor { + class SceneViewport final : public Runtime::Viewport { + public: + SceneViewport(Runtime::World& inWorld, GLFWwindow* inWindow, RHI::Device& inDevice); + ~SceneViewport() override; + + NonCopyable(SceneViewport) + NonMovable(SceneViewport) + + void Render(float inDeltaSeconds) override; + void Resize(uint32_t inWidth, uint32_t inHeight); + RHI::TextureView* GetTextureView() const; + void SetVisible(bool inVisible); + void SetHovered(bool inHovered); + void SetFocused(bool inFocused); + bool IsHovered() const; + bool IsCameraLooking() const; + void OnKey(int inKey, bool inPressed); + void BeginCameraLook(); + void EndCameraLook(); + void AddCameraLookDelta(float inDeltaX, float inDeltaY); + + private: + Runtime::Client& GetClient() override; + Render::RenderSurface& GetRenderSurface() override; + std::vector BuildViews(Runtime::ECRegistry& inRegistry, Common::UVec2 inSize) override; + Runtime::Entity CreateCamera(); + + Runtime::World& world; + GLFWwindow* window; + SceneClient client; + Render::Canvas canvas; + Runtime::Entity camera; + bool visible; + bool hovered; + }; +} diff --git a/Editor/Include/Editor/System/Camera.h b/Editor/Include/Editor/System/Camera.h index 876e67b7e..f59c20fe2 100644 --- a/Editor/Include/Editor/System/Camera.h +++ b/Editor/Include/Editor/System/Camera.h @@ -5,7 +5,7 @@ #include namespace Editor { - struct EClass(globalComp, transient) EditorCameraInput final { + struct EClass(comp, transient) EditorCameraInput final { EClassBody(EditorCameraInput) EditorCameraInput(); diff --git a/Editor/Include/Editor/Tab/SceneTab.h b/Editor/Include/Editor/Tab/SceneTab.h index 89943d2f2..91238ca68 100644 --- a/Editor/Include/Editor/Tab/SceneTab.h +++ b/Editor/Include/Editor/Tab/SceneTab.h @@ -2,22 +2,17 @@ #include -namespace Runtime { - class Canvas; -} - namespace Editor { - class SceneClient; + class SceneViewport; class SceneTab final : public EditorTab { public: - SceneTab(SceneClient& inSceneClient, Runtime::Canvas& inCanvas); + explicit SceneTab(SceneViewport& inViewport); private: void RenderContents() override; void OnHidden() override; - SceneClient& sceneClient; - Runtime::Canvas& canvas; + SceneViewport& viewport; }; } diff --git a/Editor/Src/EditorApplication.cpp b/Editor/Src/EditorApplication.cpp index bc06343d7..42f7895b7 100644 --- a/Editor/Src/EditorApplication.cpp +++ b/Editor/Src/EditorApplication.cpp @@ -1,261 +1,43 @@ -// -// Created by johnk on 2026/7/7. -// - -#include - -#include -#include - -#include #include #include #include #include -#include -#include +#include +#include #include -namespace Editor::Internal { - constexpr uint32_t defaultWindowWidth = 1600; - constexpr uint32_t defaultWindowHeight = 900; - constexpr uint32_t projectHubWindowWidth = 560; - constexpr uint32_t projectHubWindowHeight = 720; - constexpr float defaultFontSize = 15.0f; - constexpr uint32_t defaultSceneWidth = 1280; - constexpr uint32_t defaultSceneHeight = 720; - constexpr RHI::PixelFormat sceneColorFormat = RHI::PixelFormat::rgba8Unorm; - - static Runtime::CanvasDesc CreateSceneRenderCanvasDesc() - { - Runtime::CanvasDesc result; - result.width = defaultSceneWidth; - result.height = defaultSceneHeight; - result.format = sceneColorFormat; - result.debugName = "editorSceneColor"; - return result; - } - - static std::string MakeWindowTitle(const EditorApplicationDesc& inDesc) - { - if (inDesc.mode == EditorApplicationMode::projectHub) { - return "Explosion Project Hub"; - } - const std::string projectName = Core::Paths::HasSetGameRoot() - ? Core::Paths::GameRootDir().DirName() - : "Untitled"; - return std::format("{} - Explosion Editor", projectName); - } - - static uint32_t GetInitialWindowWidth(const EditorApplicationDesc& inDesc) - { - return inDesc.mode == EditorApplicationMode::projectHub ? projectHubWindowWidth : defaultWindowWidth; - } - - static uint32_t GetInitialWindowHeight(const EditorApplicationDesc& inDesc) - { - return inDesc.mode == EditorApplicationMode::projectHub ? projectHubWindowHeight : defaultWindowHeight; - } - - static void LoadIconFonts(ImFontAtlas& inFontAtlas, float inSizePixels) - { - static ImVector glyphRanges; - if (glyphRanges.empty()) { - ImFontGlyphRangesBuilder builder; - builder.AddText(Icons::Tabler::allGlyphs); - builder.BuildRanges(&glyphRanges); - } - - const std::string fontPath = (Core::Paths::EngineResDir() / "Editor" / "Icons" / "Tabler" / "tabler-icons.ttf").String(); - ImFontConfig config; - config.MergeMode = true; - config.PixelSnapH = true; - config.GlyphMinAdvanceX = inSizePixels; - config.GlyphMaxAdvanceX = inSizePixels; - Assert(inFontAtlas.AddFontFromFileTTF(fontPath.c_str(), inSizePixels, &config, glyphRanges.Data) != nullptr); - } -} - namespace Editor { EditorApplication::EditorApplication(EditorApplicationDesc inDesc) - : desc(std::move(inDesc)) - , lastFrameSeconds(Common::TimePoint::Now().ToSeconds()) - , lastCursorX(0.0) - , lastCursorY(0.0) - , hasLastCursor(false) - , requestQuit(false) + : lastFrameSeconds(Common::TimePoint::Now().ToSeconds()) { - InitializeImGui(); - auto& renderModule = Runtime::EngineHolder::Get().GetRenderModule(); - window = Common::MakeUnique( - *renderModule.GetDevice(), renderModule.GetRenderThread(), - EditorWindowDesc { - .title = Internal::MakeWindowTitle(desc), - .width = Internal::GetInitialWindowWidth(desc), - .height = Internal::GetInitialWindowHeight(desc), - .maximized = desc.mode == EditorApplicationMode::editor - }); - imguiPlatform = Common::MakeUnique(*window); - imguiRenderer = Common::MakeUnique(*window, renderModule.GetRenderThread()); - InstallCallbacks(); - - if (desc.mode == EditorApplicationMode::editor) { + if (inDesc.mode == EditorApplicationMode::editor) { context = Common::MakeUnique(); - auto& sceneClient = context->GetSceneClient(); - sceneClient.SetEditorWindow(*window); - sceneRenderCanvas = Common::MakeUnique(window->GetDevice(), Internal::CreateSceneRenderCanvasDesc()); - sceneClient.SetRenderSurface(sceneRenderCanvas.Get()); - sceneClient.OpenProjectLevel(); - editorFrame = Common::MakeUnique(*context, *sceneRenderCanvas, EditorLogStream::Get(), Core::Paths::GameAssetDir()); + context->OpenProjectLevel(); + mainWindow.Reset(new EditorMainWindow(*context, EditorLogStream::Get(), Core::Paths::GameAssetDir())); } else { projectService = Common::MakeUnique(Core::Paths::EngineResDir() / "Editor" / "ProjectTemplates"); recentProjects = Common::MakeUnique(Core::Paths::EngineCacheDir() / "Editor" / "ProjectHub" / "RecentProjects.json"); projectLauncher = Common::MakeUnique(EditorLaunchOptions { .executablePath = Core::Paths::ExecutablePath().String(), - .rhiType = desc.rhiType, - .gpuDebug = desc.gpuDebug, - .softwareGpu = desc.softwareGpu + .rhiType = inDesc.rhiType, + .gpuDebug = inDesc.gpuDebug, + .softwareGpu = inDesc.softwareGpu }); - projectHubFrame = Common::MakeUnique(*projectService, *recentProjects, *projectLauncher); + mainWindow.Reset(new ProjectHubWindow(*projectService, *recentProjects, *projectLauncher)); } } - EditorApplication::~EditorApplication() - { - if (context != nullptr) { - context->GetSceneClient().SetRenderSurface(nullptr); - } - imguiRenderer->WaitIdle(); - editorFrame.Reset(); - context.Reset(); - sceneRenderCanvas.Reset(); - projectHubFrame.Reset(); - imguiPlatform.Reset(); - imguiRenderer.Reset(); - window.Reset(); - ShutdownImGui(); - } + EditorApplication::~EditorApplication() = default; int EditorApplication::Run() { - while (!window->ShouldClose()) { - window->PollEvents(); - window->RecreateSwapChainIfNeeded(); + while (!mainWindow->ShouldClose()) { const float deltaSeconds = NextDeltaSeconds(); - imguiRenderer->NewFrame(); - imguiPlatform->NewFrame(deltaSeconds); - ImGui::NewFrame(); - - if (desc.mode == EditorApplicationMode::editor) { - RenderEditorFrame(); - } else { - requestQuit = projectHubFrame->Render(); - } - if (requestQuit) { - window->RequestClose(); - } - ImGui::Render(); Runtime::EngineHolder::Get().Tick(deltaSeconds); - imguiRenderer->Submit(*ImGui::GetDrawData()); } return 0; } - void EditorApplication::InitializeImGui() - { - IMGUI_CHECKVERSION(); - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; - if (desc.mode == EditorApplicationMode::editor) { - const Common::Path iniFilePath = Core::Paths::GameCacheDir() / "Editor" / "Layout" / "Main.ini"; - iniFilePath.Parent().MakeDir(); - imguiIniFilename = iniFilePath.String(); - io.IniFilename = imguiIniFilename.c_str(); - } else { - io.IniFilename = nullptr; - } - ImFontConfig defaultFontConfig; - defaultFontConfig.SizePixels = Internal::defaultFontSize; - io.FontDefault = io.Fonts->AddFontDefaultVector(&defaultFontConfig); - Internal::LoadIconFonts(*io.Fonts, Internal::defaultFontSize); - ThemeSwitcher::ApplyCurrentTheme(); - } - - void EditorApplication::ShutdownImGui() - { - ImGui::DestroyContext(); - } - - void EditorApplication::InstallCallbacks() - { - window->onKey.BindLambda([this](int inKey, int, int inAction, int) -> void { - HandleKey(inKey, inAction); - }); - window->onMouseButton.BindLambda([this](int inButton, int inAction, int) -> void { - HandleMouseButton(inButton, inAction); - }); - window->onCursor.BindMember<&EditorApplication::HandleCursor>(*this); - window->onFocus.BindLambda([this](bool inFocused) -> void { - if (!inFocused && context != nullptr) { - context->GetSceneClient().EndCameraLook(); - hasLastCursor = false; - } - }); - } - - void EditorApplication::RenderEditorFrame() - { - editorFrame->Render(requestQuit); - if (ImGui::GetIO().KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_S, false)) { - context->GetSceneClient().SaveLevel(); - } - } - - void EditorApplication::HandleKey(int inKey, int inAction) - { - const ImGuiIO& io = ImGui::GetIO(); - if (context != nullptr) { - auto& sceneClient = context->GetSceneClient(); - if (inKey == GLFW_KEY_ESCAPE && inAction == GLFW_PRESS) { - sceneClient.EndCameraLook(); - } - if (inAction == GLFW_PRESS || inAction == GLFW_RELEASE) { - const bool canRouteToScene = sceneClient.IsCameraLooking() || (!io.WantCaptureKeyboard && sceneClient.IsSceneHovered()); - if (canRouteToScene || inAction == GLFW_RELEASE) { - sceneClient.OnKey(inKey, inAction == GLFW_PRESS); - } - } - } - } - - void EditorApplication::HandleMouseButton(int inButton, int inAction) - { - if (context == nullptr || inButton != GLFW_MOUSE_BUTTON_RIGHT) { - return; - } - auto& sceneClient = context->GetSceneClient(); - if (inAction == GLFW_PRESS && sceneClient.IsSceneHovered()) { - hasLastCursor = false; - sceneClient.BeginCameraLook(); - } else if (inAction == GLFW_RELEASE) { - sceneClient.EndCameraLook(); - } - } - - void EditorApplication::HandleCursor(double inX, double inY) - { - if (context != nullptr) { - auto& sceneClient = context->GetSceneClient(); - if (sceneClient.IsCameraLooking() && hasLastCursor) { - sceneClient.AddCameraLookDelta(static_cast(inX - lastCursorX), static_cast(inY - lastCursorY)); - } - } - lastCursorX = inX; - lastCursorY = inY; - hasLastCursor = true; - } - float EditorApplication::NextDeltaSeconds() { const double now = Common::TimePoint::Now().ToSeconds(); diff --git a/Editor/Src/EditorContext.cpp b/Editor/Src/EditorContext.cpp index e7c86c53f..d6256cae8 100644 --- a/Editor/Src/EditorContext.cpp +++ b/Editor/Src/EditorContext.cpp @@ -2,22 +2,200 @@ // Created by johnk on 2026/7/4. // +#include + +#include #include +#include +#include +#include +#include +#include +#include #include #include +namespace Editor::LevelEditing::Internal { + const Core::Uri mainLevelUri("asset://Game/Maps/Main"); + const Core::Uri defaultUnlitMaterialUri("asset://Game/Materials/DefaultUnlit"); + const Core::Uri lightGrayUnlitMaterialInstanceUri("asset://Game/Materials/LightGrayUnlit"); + const Core::Uri yellowUnlitMaterialInstanceUri("asset://Game/Materials/YellowUnlit"); + const Core::Uri cubeMeshUri("asset://Game/Meshes/Cube"); + static bool AssetExists(const Core::Uri& inUri) + { + return Core::AssetUriParser(inUri).Parse().Exists(); + } + + template + static void SaveAsset(const Runtime::AssetPtr& inAsset) + { + if (const Common::Path parentDir = Core::AssetUriParser(inAsset->Uri()).Parse().Parent(); + !parentDir.Exists()) { + parentDir.MakeDir(); + } + Runtime::AssetManager::Get().Save(inAsset); + } + + static Runtime::StaticMeshVertices BuildCubeVertices() + { + // 24 vertices (4 per face) so each face gets its own uv space, z-up unit cube centered at origin + static constexpr float h = 0.5f; + static const std::array, 6> facePositions = {{ + {{ { -h, -h, h }, { h, -h, h }, { h, h, h }, { -h, h, h } }}, // +z + {{ { -h, h, -h }, { h, h, -h }, { h, -h, -h }, { -h, -h, -h } }}, // -z + {{ { h, -h, -h }, { h, h, -h }, { h, h, h }, { h, -h, h } }}, // +x + {{ { -h, h, -h }, { -h, -h, -h }, { -h, -h, h }, { -h, h, h } }}, // -x + {{ { h, h, -h }, { -h, h, -h }, { -h, h, h }, { h, h, h } }}, // +y + {{ { -h, -h, -h }, { h, -h, -h }, { h, -h, h }, { -h, -h, h } }} // -y + }}; + + Runtime::StaticMeshVertices result; + for (const auto& face : facePositions) { + const auto baseVertex = static_cast(result.positions.size()); + for (size_t corner = 0; corner < 4; corner++) { + result.positions.emplace_back(face[corner]); + result.tangents.emplace_back(0.0f, 0.0f, 1.0f); + result.uv0.emplace_back(corner == 1 || corner == 2 ? 1.0f : 0.0f, corner >= 2 ? 1.0f : 0.0f); + } + for (const uint32_t index : { 0u, 1u, 2u, 0u, 2u, 3u }) { + result.indices.emplace_back(baseVertex + index); + } + } + result.vertexCount = static_cast(result.positions.size()); + result.indexCount = static_cast(result.indices.size()); + return result; + } + + static Runtime::AssetPtr EnsureDefaultUnlitMaterial() + { + auto& assetManager = Runtime::AssetManager::Get(); + if (AssetExists(defaultUnlitMaterialUri)) { + return assetManager.SyncLoad(defaultUnlitMaterialUri, Mirror::Class::Get()); + } + + Runtime::AssetPtr material = new Runtime::Material(defaultUnlitMaterialUri); + material->SetType(Runtime::MaterialType::surface); + material->SetSource("float4 GetBaseColor()\n{\n return baseColor;\n}\n"); + Runtime::MaterialFVec4ParameterField baseColorField; + baseColorField.defaultValue = Common::FVec4(1.0f, 1.0f, 1.0f, 1.0f); + material->EmplaceParameterField("baseColor") = baseColorField; + material->Update(); + SaveAsset(material); + return material; + } + + static Runtime::AssetPtr EnsureDefaultUnlitMaterialInstance( + const Core::Uri& inUri, + const Common::FVec4& inBaseColor, + const Runtime::AssetPtr& inMaterial) + { + auto& assetManager = Runtime::AssetManager::Get(); + if (AssetExists(inUri)) { + return assetManager.SyncLoad(inUri, Mirror::Class::Get()); + } + + Runtime::AssetPtr materialInstance = new Runtime::MaterialInstance(inUri); + materialInstance->SetMaterial(inMaterial); + materialInstance->SetParameter("baseColor", inBaseColor); + SaveAsset(materialInstance); + return materialInstance; + } + + static Runtime::AssetPtr EnsureDefaultCubeMesh( + const Runtime::AssetPtr& inMaterial) + { + auto& assetManager = Runtime::AssetManager::Get(); + if (AssetExists(cubeMeshUri)) { + return assetManager.SyncLoad(cubeMeshUri, Mirror::Class::Get()); + } + + Runtime::AssetPtr mesh = new Runtime::StaticMesh(cubeMeshUri); + mesh->SetMaterial(inMaterial); + mesh->EmplaceLOD().vertices = BuildCubeVertices(); + SaveAsset(mesh); + return mesh; + } + + static void AuthorDefaultLevelContent(Runtime::ECRegistry& inRegistry) + { + const Runtime::AssetPtr defaultUnlitMaterial = EnsureDefaultUnlitMaterial(); + const Runtime::AssetPtr lightGrayMaterial = EnsureDefaultUnlitMaterialInstance( + lightGrayUnlitMaterialInstanceUri, + Common::FVec4(0.75f, 0.75f, 0.75f, 1.0f), + defaultUnlitMaterial); + const Runtime::AssetPtr yellowMaterial = EnsureDefaultUnlitMaterialInstance( + yellowUnlitMaterialInstanceUri, + Common::FVec4(1.0f, 1.0f, 0.0f, 1.0f), + defaultUnlitMaterial); + const Runtime::AssetPtr cubeMesh = EnsureDefaultCubeMesh(yellowMaterial); + + // WorldTransform's reflected constructor takes an FTransform, other argument shapes would not match it + const auto ground = inRegistry.Create(); + inRegistry.Emplace(ground, std::string("Ground")); + Common::FTransform groundTransform; + groundTransform.scale = Common::FVec3(10.0f, 10.0f, 0.2f); + groundTransform.translation = Common::FVec3(0.0f, 0.0f, -0.1f); + inRegistry.Emplace(ground, groundTransform); + auto& groundPrimitive = inRegistry.Emplace(ground); + groundPrimitive.mesh = cubeMesh; + groundPrimitive.materialOverride = lightGrayMaterial; + + const auto cube = inRegistry.Create(); + inRegistry.Emplace(cube, std::string("Cube")); + Common::FTransform cubeTransform; + cubeTransform.translation = Common::FVec3(0.0f, 0.0f, 0.5f); + inRegistry.Emplace(cube, cubeTransform); + auto& cubePrimitive = inRegistry.Emplace(cube); + cubePrimitive.mesh = cubeMesh; + cubePrimitive.materialOverride = yellowMaterial; + + const auto playerStart = inRegistry.Create(); + inRegistry.Emplace(playerStart, std::string("Player Start")); + const Common::FTransform playerStartTransform = Common::FTransform::LookAt(Common::FVec3(-5.0f, -6.0f, 4.0f), Common::FVec3(0.0f, 0.0f, 0.5f)); + inRegistry.Emplace(playerStart, playerStartTransform); + inRegistry.Emplace(playerStart); + } +} + namespace Editor { EditorContext::EditorContext() - : sceneClient(Common::MakeUnique()) + : levelUri(LevelEditing::Internal::mainLevelUri) + , world("EditorWorld", Runtime::PlayType::editor) , selectedEntity(Runtime::entityNull) { + world.SetSystemGraph(EditorSystemGraphPresets::DefaultEditorWorld()); } - EditorContext::~EditorContext() = default; + EditorContext::~EditorContext() + { + if (!world.Stopped()) { + world.Stop(); + } + } + + Runtime::World& EditorContext::GetWorld() + { + return world; + } + + void EditorContext::OpenProjectLevel() + { + Assert(world.Stopped()); + if (LevelEditing::Internal::AssetExists(levelUri)) { + const auto level = Runtime::AssetManager::Get().SyncLoad(levelUri, Mirror::Class::Get()); + world.LoadFrom(level); + } else { + world.EditorAccess(LevelEditing::Internal::AuthorDefaultLevelContent); + SaveLevel(); + } + world.Play(); + } - SceneClient& EditorContext::GetSceneClient() const + void EditorContext::SaveLevel() { - return *sceneClient; + Runtime::AssetPtr level = new Runtime::Level(levelUri); + world.SaveTo(level); + LevelEditing::Internal::SaveAsset(level); } Runtime::Entity EditorContext::GetSelectedEntity() const @@ -104,12 +282,7 @@ namespace Editor { return true; } - bool EditorContext::SetComponentMember( - Runtime::ECRegistry& inRegistry, - Runtime::Entity inEntity, - Runtime::CompClass inClass, - const Mirror::MemberVariable& inMemberVariable, - const Mirror::Any& inValue) + bool EditorContext::SetComponentMember(Runtime::ECRegistry& inRegistry, Runtime::Entity inEntity, Runtime::CompClass inClass, const Mirror::MemberVariable& inMemberVariable, const Mirror::Any& inValue) { if (inClass == nullptr || !inRegistry.Valid(inEntity) diff --git a/Editor/Src/EditorMainWindow.cpp b/Editor/Src/EditorMainWindow.cpp new file mode 100644 index 000000000..f641d0366 --- /dev/null +++ b/Editor/Src/EditorMainWindow.cpp @@ -0,0 +1,163 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Editor::Workspace::Internal { + constexpr const char* editorDockSpaceName = "EditorDockSpace"; + constexpr const char* editorDockSpaceId = "EditorDockSpaceV3"; +} + +namespace Editor { + EditorMainWindow::EditorMainWindow(EditorContext& inContext, EditorLogStream& inLogStream, Common::Path inAssetDirectory) + : ImGuiWindow(ImGuiWindowDesc { + .title = Core::Paths::GameRootDir().DirName() + " - Explosion Editor", + .width = 1600, + .height = 900, + .maximized = true, + .layoutFile = Core::Paths::GameCacheDir() / "Editor" / "Layout" / "Main.ini", + .onKey = [this](int inKey, int, int inAction, int) -> void { HandleKey(inKey, inAction); }, + .onMouseButton = [this](int inButton, int inAction, int) -> void { HandleMouseButton(inButton, inAction); }, + .onCursor = [this](double inX, double inY) -> void { HandleCursor(inX, inY); }, + .onFocus = [this](bool inFocused) -> void { + if (!inFocused) { + sceneViewport.EndCameraLook(); + hasLastCursor = false; + } + } + }) + , context(inContext) + , lastCursorX(0.0) + , lastCursorY(0.0) + , hasLastCursor(false) + , sceneViewport(context.GetWorld(), GetNativeWindow(), GetSwapChainSurface().GetDevice()) + { + tabs.Emplace(sceneViewport); + tabs.Emplace(context); + tabs.Emplace(context); + tabs.Emplace(std::move(inAssetDirectory)); + tabs.Emplace(inLogStream); + } + + EditorMainWindow::~EditorMainWindow() + { + WaitIdle(); + } + + void EditorMainWindow::RenderContents() + { + DrawDockSpace(); + RenderMenuBar(); + tabs.Render(); + if (ImGui::GetIO().KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_S, false)) { + context.SaveLevel(); + } + } + + void EditorMainWindow::RenderMenuBar() + { + if (!ImGui::BeginMainMenuBar()) { + return; + } + const std::string fileMenuLabel = Widgets::Label(Icons::Tabler::file, "File"); + if (ImGui::BeginMenu(fileMenuLabel.c_str())) { + const std::string saveLevelLabel = Widgets::Label(Icons::Tabler::deviceFloppy, "Save Level"); + if (ImGui::MenuItem(saveLevelLabel.c_str(), "Ctrl+S")) { + context.SaveLevel(); + } + ImGui::Separator(); + const std::string exitLabel = Widgets::Label(Icons::Tabler::doorExit, "Exit"); + if (ImGui::MenuItem(exitLabel.c_str())) { + RequestClose(); + } + ImGui::EndMenu(); + } + const std::string viewMenuLabel = Widgets::Label(Icons::Tabler::layoutDashboard, "View"); + if (ImGui::BeginMenu(viewMenuLabel.c_str())) { + tabs.RenderViewMenuItems(); + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } + + void EditorMainWindow::DrawDockSpace() const + { + const ImGuiViewport* mainViewport = ImGui::GetMainViewport(); + ImGui::SetNextWindowPos(mainViewport->WorkPos); + ImGui::SetNextWindowSize(mainViewport->WorkSize); + ImGui::SetNextWindowViewport(mainViewport->ID); + + ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoDocking + | ImGuiWindowFlags_NoTitleBar + | ImGuiWindowFlags_NoCollapse + | ImGuiWindowFlags_NoResize + | ImGuiWindowFlags_NoMove + | ImGuiWindowFlags_NoBringToFrontOnFocus + | ImGuiWindowFlags_NoNavFocus + | ImGuiWindowFlags_NoBackground; + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); + ImGui::Begin(Workspace::Internal::editorDockSpaceName, nullptr, windowFlags); + ImGui::PopStyleVar(3); + + const ImGuiID dockSpaceId = ImGui::GetID(Workspace::Internal::editorDockSpaceId); + tabs.BuildInitialDockLayout(dockSpaceId, mainViewport->WorkSize); + ImGui::DockSpace(dockSpaceId, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None); + ImGui::End(); + } + + void EditorMainWindow::Render(float inDeltaSeconds) + { + sceneViewport.Render(inDeltaSeconds); + ImGuiWindow::Render(inDeltaSeconds); + } + + void EditorMainWindow::HandleKey(int inKey, int inAction) + { + if (inKey == GLFW_KEY_ESCAPE && inAction == GLFW_PRESS) { + sceneViewport.EndCameraLook(); + } + if (inAction == GLFW_PRESS || inAction == GLFW_RELEASE) { + const bool routeToScene = sceneViewport.IsCameraLooking() + || (!ImGui::GetIO().WantCaptureKeyboard && sceneViewport.IsHovered()); + if (routeToScene || inAction == GLFW_RELEASE) { + sceneViewport.OnKey(inKey, inAction == GLFW_PRESS); + } + } + } + + void EditorMainWindow::HandleMouseButton(int inButton, int inAction) + { + if (inButton != GLFW_MOUSE_BUTTON_RIGHT) { + return; + } + if (inAction == GLFW_PRESS && sceneViewport.IsHovered()) { + hasLastCursor = false; + sceneViewport.BeginCameraLook(); + } else if (inAction == GLFW_RELEASE) { + sceneViewport.EndCameraLook(); + } + } + + void EditorMainWindow::HandleCursor(double inX, double inY) + { + if (sceneViewport.IsCameraLooking() && hasLastCursor) { + sceneViewport.AddCameraLookDelta(static_cast(inX - lastCursorX), static_cast(inY - lastCursorY)); + } + lastCursorX = inX; + lastCursorY = inY; + hasLastCursor = true; + } +} diff --git a/Editor/Src/EditorWindow.cpp b/Editor/Src/EditorWindow.cpp deleted file mode 100644 index eb7e0f20b..000000000 --- a/Editor/Src/EditorWindow.cpp +++ /dev/null @@ -1,180 +0,0 @@ -// -// Created by johnk on 2026/7/7. -// - -#include -#include - -#if PLATFORM_WINDOWS -#define GLFW_EXPOSE_NATIVE_WIN32 -#elif PLATFORM_MACOS -#define GLFW_EXPOSE_NATIVE_COCOA -#endif -#include -#include - -#if PLATFORM_WINDOWS -#ifdef CreateSemaphore -#undef CreateSemaphore -#endif -#endif - -#include -#include - -namespace Editor::Windowing::Internal { - static uint32_t ClampExtent(int inValue) - { - return static_cast(std::max(1, inValue)); - } -} - -namespace Editor { - EditorWindow::EditorWindow(RHI::Device& inDevice, Render::RenderThread& inRenderThread, const EditorWindowDesc& inDesc) - : Runtime::Window(inDevice) - , renderThread(inRenderThread) - , window(nullptr) - , framebufferWidth(inDesc.width) - , framebufferHeight(inDesc.height) - { - glfwInit(); - glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - glfwWindowHint(GLFW_MAXIMIZED, inDesc.maximized ? GLFW_TRUE : GLFW_FALSE); - window = glfwCreateWindow( - static_cast(inDesc.width), - static_cast(inDesc.height), - inDesc.title.c_str(), - nullptr, - nullptr); - Assert(window != nullptr); - - int fbWidth = 0; - int fbHeight = 0; - glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - framebufferWidth = Windowing::Internal::ClampExtent(fbWidth); - framebufferHeight = Windowing::Internal::ClampExtent(fbHeight); - - InitializeSurface( - GetDevice().CreateSurface(RHI::SurfaceCreateInfo(GetPlatformWindow())), - framebufferWidth, - framebufferHeight); - InstallCallbacks(); - } - - EditorWindow::~EditorWindow() - { - WaitRenderingIdle(); - DestroySurface(); - glfwDestroyWindow(window); - glfwTerminate(); - } - - GLFWwindow* EditorWindow::GetNativeWindow() const - { - return window; - } - - uint32_t EditorWindow::GetWidth() const - { - return GetFramebufferWidth(); - } - - uint32_t EditorWindow::GetHeight() const - { - return GetFramebufferHeight(); - } - - uint32_t EditorWindow::GetFramebufferWidth() const - { - return framebufferWidth; - } - - uint32_t EditorWindow::GetFramebufferHeight() const - { - return framebufferHeight; - } - - bool EditorWindow::ShouldClose() const - { - return static_cast(glfwWindowShouldClose(window)); - } - - void EditorWindow::RequestClose() const - { - glfwSetWindowShouldClose(window, GLFW_TRUE); - } - - void EditorWindow::PollEvents() const - { - glfwPollEvents(); - } - - void EditorWindow::SetTitle(const std::string& inTitle) const - { - glfwSetWindowTitle(window, inTitle.c_str()); - } - - void EditorWindow::SetCursorCaptured(bool inCaptured) const - { - glfwSetInputMode(window, GLFW_CURSOR, inCaptured ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); - } - - void EditorWindow::RecreateSwapChainIfNeeded() - { - int fbWidth = 0; - int fbHeight = 0; - glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - const uint32_t newWidth = Windowing::Internal::ClampExtent(fbWidth); - const uint32_t newHeight = Windowing::Internal::ClampExtent(fbHeight); - if (newWidth == framebufferWidth && newHeight == framebufferHeight) { - return; - } - - framebufferWidth = newWidth; - framebufferHeight = newHeight; - WaitRenderingIdle(); - Runtime::Window::Resize(framebufferWidth, framebufferHeight); - } - - void EditorWindow::WaitRenderingIdle() const - { - renderThread.Flush(); - Runtime::Window::WaitRenderingIdle(); - } - - void EditorWindow::InstallCallbacks() - { - glfwSetWindowUserPointer(window, this); - glfwSetKeyCallback(window, [](GLFWwindow* inWindow, int inKey, int inScancode, int inAction, int inMods) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->onKey.Broadcast(inKey, inScancode, inAction, inMods); - }); - glfwSetCharCallback(window, [](GLFWwindow* inWindow, unsigned int inCodepoint) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->onChar.Broadcast(inCodepoint); - }); - glfwSetMouseButtonCallback(window, [](GLFWwindow* inWindow, int inButton, int inAction, int inMods) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->onMouseButton.Broadcast(inButton, inAction, inMods); - }); - glfwSetCursorPosCallback(window, [](GLFWwindow* inWindow, double inX, double inY) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->onCursor.Broadcast(inX, inY); - }); - glfwSetScrollCallback(window, [](GLFWwindow* inWindow, double inX, double inY) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->onScroll.Broadcast(inX, inY); - }); - glfwSetWindowFocusCallback(window, [](GLFWwindow* inWindow, int inFocused) -> void { - static_cast(glfwGetWindowUserPointer(inWindow))->onFocus.Broadcast(inFocused == GLFW_TRUE); - }); - } - - void* EditorWindow::GetPlatformWindow() const - { -#if PLATFORM_WINDOWS - return glfwGetWin32Window(window); -#elif PLATFORM_MACOS - return glfwGetCocoaView(window); -#else - Unimplement(); - return nullptr; -#endif - } - -} diff --git a/Editor/Src/Frame/EditorFrame.cpp b/Editor/Src/Frame/EditorFrame.cpp deleted file mode 100644 index dbeb0c132..000000000 --- a/Editor/Src/Frame/EditorFrame.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Editor::Workspace::Internal { - constexpr const char* editorDockSpaceName = "EditorDockSpace"; - constexpr const char* editorDockSpaceId = "EditorDockSpaceV3"; -} - -namespace Editor { - EditorFrame::EditorFrame(EditorContext& inContext, Runtime::Canvas& inSceneRenderCanvas, EditorLogStream& inLogStream, Common::Path inAssetDirectory) - : context(inContext) - { - tabs.Emplace(context.GetSceneClient(), inSceneRenderCanvas); - tabs.Emplace(context); - tabs.Emplace(context); - tabs.Emplace(std::move(inAssetDirectory)); - tabs.Emplace(inLogStream); - } - - EditorFrame::~EditorFrame() = default; - - void EditorFrame::Render(bool& outRequestQuit) - { - DrawDockSpace(); - RenderMenuBar(outRequestQuit); - tabs.Render(); - } - - void EditorFrame::RenderMenuBar(bool& outRequestQuit) - { - if (!ImGui::BeginMainMenuBar()) { - return; - } - const std::string fileMenuLabel = Widgets::Label(Icons::Tabler::file, "File"); - if (ImGui::BeginMenu(fileMenuLabel.c_str())) { - const std::string saveLevelLabel = Widgets::Label(Icons::Tabler::deviceFloppy, "Save Level"); - if (ImGui::MenuItem(saveLevelLabel.c_str(), "Ctrl+S")) { - context.GetSceneClient().SaveLevel(); - } - ImGui::Separator(); - const std::string exitLabel = Widgets::Label(Icons::Tabler::doorExit, "Exit"); - if (ImGui::MenuItem(exitLabel.c_str())) { - outRequestQuit = true; - } - ImGui::EndMenu(); - } - const std::string viewMenuLabel = Widgets::Label(Icons::Tabler::layoutDashboard, "View"); - if (ImGui::BeginMenu(viewMenuLabel.c_str())) { - tabs.RenderViewMenuItems(); - ImGui::EndMenu(); - } - ImGui::EndMainMenuBar(); - } - - void EditorFrame::DrawDockSpace() const - { - const ImGuiViewport* mainViewport = ImGui::GetMainViewport(); - ImGui::SetNextWindowPos(mainViewport->WorkPos); - ImGui::SetNextWindowSize(mainViewport->WorkSize); - ImGui::SetNextWindowViewport(mainViewport->ID); - - ImGuiWindowFlags windowFlags = ImGuiWindowFlags_NoDocking - | ImGuiWindowFlags_NoTitleBar - | ImGuiWindowFlags_NoCollapse - | ImGuiWindowFlags_NoResize - | ImGuiWindowFlags_NoMove - | ImGuiWindowFlags_NoBringToFrontOnFocus - | ImGuiWindowFlags_NoNavFocus - | ImGuiWindowFlags_NoBackground; - - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); - ImGui::Begin(Workspace::Internal::editorDockSpaceName, nullptr, windowFlags); - ImGui::PopStyleVar(3); - - const ImGuiID dockSpaceId = ImGui::GetID(Workspace::Internal::editorDockSpaceId); - tabs.BuildInitialDockLayout(dockSpaceId, mainViewport->WorkSize); - ImGui::DockSpace(dockSpaceId, ImVec2(0.0f, 0.0f), ImGuiDockNodeFlags_None); - ImGui::End(); - } -} diff --git a/Editor/Src/ImGui/ImGuiPlatformBackend.cpp b/Editor/Src/ImGui/ImGuiPlatformBackend.cpp index 3755ccd6f..8603156ba 100644 --- a/Editor/Src/ImGui/ImGuiPlatformBackend.cpp +++ b/Editor/Src/ImGui/ImGuiPlatformBackend.cpp @@ -3,16 +3,21 @@ #include #include -#include #include +#include #include namespace Editor { - ImGuiPlatformBackend::ImGuiPlatformBackend(EditorWindow& inWindow) + ImGuiPlatformBackend::ImGuiPlatformBackend(GLFWwindow* inWindow, const ImGuiWindowDesc& inDesc) : window(inWindow) + , desc(inDesc) + , context(ImGui::GetCurrentContext()) { ImGui::GetIO().BackendPlatformName = "ExplosionGLFW"; - keyHandle = window.onKey.BindLambda([](int inKey, int inScancode, int inAction, int inMods) -> void { + glfwSetWindowUserPointer(window, this); + glfwSetKeyCallback(window, [](GLFWwindow* inWindow, int inKey, int inScancode, int inAction, int inMods) -> void { + const auto& backend = *static_cast(glfwGetWindowUserPointer(inWindow)); + ImGui::SetCurrentContext(backend.context); ImGuiCompatibility::UpdateKeyModifiers(inMods); const ImGuiKey key = ImGuiCompatibility::ToImGuiKey(inKey); if (key != ImGuiKey_None) { @@ -20,35 +25,65 @@ namespace Editor { io.AddKeyEvent(key, inAction != GLFW_RELEASE); io.SetKeyEventNativeData(key, inKey, inScancode); } + if (backend.desc.onKey) { + backend.desc.onKey(inKey, inScancode, inAction, inMods); + } }); - charHandle = window.onChar.BindLambda([](uint32_t inCodepoint) -> void { + glfwSetCharCallback(window, [](GLFWwindow* inWindow, unsigned int inCodepoint) -> void { + const auto& backend = *static_cast(glfwGetWindowUserPointer(inWindow)); + ImGui::SetCurrentContext(backend.context); ImGui::GetIO().AddInputCharacter(inCodepoint); + if (backend.desc.onChar) { + backend.desc.onChar(inCodepoint); + } }); - mouseButtonHandle = window.onMouseButton.BindLambda([](int inButton, int inAction, int inMods) -> void { + glfwSetMouseButtonCallback(window, [](GLFWwindow* inWindow, int inButton, int inAction, int inMods) -> void { + const auto& backend = *static_cast(glfwGetWindowUserPointer(inWindow)); + ImGui::SetCurrentContext(backend.context); ImGuiCompatibility::UpdateKeyModifiers(inMods); if (const auto button = ImGuiCompatibility::ToImGuiMouseButton(inButton)) { ImGui::GetIO().AddMouseButtonEvent(*button, inAction == GLFW_PRESS); } + if (backend.desc.onMouseButton) { + backend.desc.onMouseButton(inButton, inAction, inMods); + } }); - cursorHandle = window.onCursor.BindLambda([](double inX, double inY) -> void { + glfwSetCursorPosCallback(window, [](GLFWwindow* inWindow, double inX, double inY) -> void { + const auto& backend = *static_cast(glfwGetWindowUserPointer(inWindow)); + ImGui::SetCurrentContext(backend.context); ImGui::GetIO().AddMousePosEvent(static_cast(inX), static_cast(inY)); + if (backend.desc.onCursor) { + backend.desc.onCursor(inX, inY); + } }); - scrollHandle = window.onScroll.BindLambda([](double inX, double inY) -> void { + glfwSetScrollCallback(window, [](GLFWwindow* inWindow, double inX, double inY) -> void { + const auto& backend = *static_cast(glfwGetWindowUserPointer(inWindow)); + ImGui::SetCurrentContext(backend.context); ImGui::GetIO().AddMouseWheelEvent(static_cast(inX), static_cast(inY)); + if (backend.desc.onScroll) { + backend.desc.onScroll(inX, inY); + } }); - focusHandle = window.onFocus.BindLambda([](bool inFocused) -> void { + glfwSetWindowFocusCallback(window, [](GLFWwindow* inWindow, int inFocused) -> void { + const auto& backend = *static_cast(glfwGetWindowUserPointer(inWindow)); + ImGui::SetCurrentContext(backend.context); ImGui::GetIO().AddFocusEvent(inFocused); + if (backend.desc.onFocus) { + backend.desc.onFocus(inFocused == GLFW_TRUE); + } }); } ImGuiPlatformBackend::~ImGuiPlatformBackend() { - window.onKey.Unbind(keyHandle); - window.onChar.Unbind(charHandle); - window.onMouseButton.Unbind(mouseButtonHandle); - window.onCursor.Unbind(cursorHandle); - window.onScroll.Unbind(scrollHandle); - window.onFocus.Unbind(focusHandle); + glfwSetKeyCallback(window, nullptr); + glfwSetCharCallback(window, nullptr); + glfwSetMouseButtonCallback(window, nullptr); + glfwSetCursorPosCallback(window, nullptr); + glfwSetScrollCallback(window, nullptr); + glfwSetWindowFocusCallback(window, nullptr); + glfwSetWindowUserPointer(window, nullptr); + ImGui::SetCurrentContext(context); ImGui::GetIO().BackendPlatformName = nullptr; } @@ -58,8 +93,8 @@ namespace Editor { int height = 0; int framebufferWidth = 0; int framebufferHeight = 0; - glfwGetWindowSize(window.GetNativeWindow(), &width, &height); - glfwGetFramebufferSize(window.GetNativeWindow(), &framebufferWidth, &framebufferHeight); + glfwGetWindowSize(window, &width, &height); + glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHeight); ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(static_cast(width), static_cast(height)); diff --git a/Editor/Src/ImGui/ImGuiRhiRenderer.cpp b/Editor/Src/ImGui/ImGuiRhiRenderer.cpp index d1d48e6b6..40893a174 100644 --- a/Editor/Src/ImGui/ImGuiRhiRenderer.cpp +++ b/Editor/Src/ImGui/ImGuiRhiRenderer.cpp @@ -42,12 +42,13 @@ namespace Editor::ImGuiRendering::Internal { } namespace Editor { - ImGuiRhiRenderer::ImGuiRhiRenderer(Runtime::Window& inWindow, Render::RenderThread& inRenderThread) - : window(inWindow) + ImGuiRhiRenderer::ImGuiRhiRenderer(RHI::Device& inDevice, Render::RenderSurface& inSurface, Render::RenderThread& inRenderThread) + : device(inDevice) + , surface(inSurface) , renderThread(inRenderThread) - , pipelineFormat(window.GetSwapChainFormat()) - , uiFrameFence(window.GetDevice().CreateFence(true)) - , uiCommandBuffer(window.GetDevice().CreateCommandBuffer(RHI::QueueType::graphics)) + , pipelineFormat(surface.GetFormat()) + , uiFrameFence(device.CreateFence(true)) + , uiCommandBuffer(device.CreateCommandBuffer(RHI::QueueType::graphics)) , imguiVertexBufferCapacity(0) , imguiIndexBufferCapacity(0) { @@ -67,9 +68,9 @@ namespace Editor { void ImGuiRhiRenderer::NewFrame() { - if (pipelineFormat != window.GetSwapChainFormat()) { + if (pipelineFormat != surface.GetFormat()) { WaitIdle(); - pipelineFormat = window.GetSwapChainFormat(); + pipelineFormat = surface.GetFormat(); CreateImGuiDeviceObjects(); } } @@ -85,40 +86,43 @@ namespace Editor { void ImGuiRhiRenderer::WaitIdle() const { renderThread.Flush(); - window.WaitRenderingIdle(); + WaitForPreviousFrame(); } void ImGuiRhiRenderer::RenderFrame(const Common::SharedPtr& inDrawData) { - uiFrameFence->Wait(); + WaitForPreviousFrame(); inFlightDrawData = inDrawData; - window.AcquireBackTexture(); uiFrameFence->Reset(); - RenderUiPass(inFlightDrawData->Get()); - window.GetDevice().GetQueue(RHI::QueueType::graphics, 0)->Submit( - uiCommandBuffer.Get(), - RHI::QueueSubmitInfo() - .AddWaitSemaphore(window.GetImageReadySemaphore()) - .AddSignalSemaphore(window.GetRenderFinishedSemaphore()) - .SetSignalFence(uiFrameFence.Get())); - window.Present(); + const auto target = surface.GetRenderTarget(); + RenderUiPass(inFlightDrawData->Get(), target); + RHI::QueueSubmitInfo submitInfo; + submitInfo.SetSignalFence(uiFrameFence.Get()); + if (target.waitSemaphore != nullptr) { + submitInfo.AddWaitSemaphore(target.waitSemaphore); + } + if (target.signalSemaphore != nullptr) { + submitInfo.AddSignalSemaphore(target.signalSemaphore); + } + device.GetQueue(RHI::QueueType::graphics, 0)->Submit(uiCommandBuffer.Get(), submitInfo); } - void ImGuiRhiRenderer::RenderUiPass(ImDrawData& inDrawData) + void ImGuiRhiRenderer::WaitForPreviousFrame() const { - auto* target = window.GetTexture(); - auto* targetView = window.GetRenderTargetView(); - Assert(target != nullptr && targetView != nullptr); + uiFrameFence->Wait(); + } + void ImGuiRhiRenderer::RenderUiPass(ImDrawData& inDrawData, const Render::SurfaceTarget& inTarget) + { const auto recorder = uiCommandBuffer->Begin(); - recorder->ResourceBarrier(RHI::Barrier::Transition(target, window.GetCurrentBackTextureState(), RHI::TextureState::renderTarget)); + recorder->ResourceBarrier(RHI::Barrier::Transition(inTarget.texture, inTarget.beforeRenderState, RHI::TextureState::renderTarget)); const auto rasterRecorder = recorder->BeginRasterPass( RHI::RasterPassBeginInfo() - .AddColorAttachment(RHI::ColorAttachment(targetView, RHI::LoadOp::clear, RHI::StoreOp::store, ImGuiRendering::Internal::uiOnlyClearColor))); + .AddColorAttachment(RHI::ColorAttachment(inTarget.renderTargetView, RHI::LoadOp::clear, RHI::StoreOp::store, ImGuiRendering::Internal::uiOnlyClearColor))); RenderImGuiDrawData(inDrawData, *rasterRecorder); rasterRecorder->EndPass(); - recorder->ResourceBarrier(RHI::Barrier::Transition(target, RHI::TextureState::renderTarget, RHI::TextureState::present)); + recorder->ResourceBarrier(RHI::Barrier::Transition(inTarget.texture, RHI::TextureState::renderTarget, inTarget.afterRenderState)); recorder->End(); } @@ -202,7 +206,6 @@ namespace Editor { void ImGuiRhiRenderer::CreateImGuiDeviceObjects() { - RHI::Device& device = window.GetDevice(); imguiFrameTextureBindGroups.clear(); imguiVertexShaderCompileOutput = ImGuiRendering::Internal::CompileImGuiShader(device, "VSMain", RHI::ShaderStageBits::sVertex); imguiPixelShaderCompileOutput = ImGuiRendering::Internal::CompileImGuiShader(device, "PSMain", RHI::ShaderStageBits::sPixel); @@ -234,7 +237,7 @@ namespace Editor { const RHI::BlendComponent colorBlend(RHI::BlendOp::opAdd, RHI::BlendFactor::srcAlpha, RHI::BlendFactor::oneMinusSrcAlpha); const RHI::BlendComponent alphaBlend(RHI::BlendOp::opAdd, RHI::BlendFactor::one, RHI::BlendFactor::oneMinusSrcAlpha); - const RHI::ColorTargetState colorTarget(window.GetSwapChainFormat(), RHI::ColorWriteBits::all, true, colorBlend, alphaBlend); + const RHI::ColorTargetState colorTarget(surface.GetFormat(), RHI::ColorWriteBits::all, true, colorBlend, alphaBlend); imguiPipeline = device.CreateRasterPipeline( RHI::RasterPipelineCreateInfo(imguiPipelineLayout.Get()) @@ -254,7 +257,6 @@ namespace Editor { void ImGuiRhiRenderer::CreateImGuiFontTexture() { - RHI::Device& device = window.GetDevice(); unsigned char* pixels = nullptr; int width = 0; @@ -334,7 +336,6 @@ namespace Editor { void ImGuiRhiRenderer::CreateImGuiDynamicBuffers(int inVertexCount, int inIndexCount) { - RHI::Device& device = window.GetDevice(); imguiVertexBufferCapacity = std::max(1, inVertexCount); imguiIndexBufferCapacity = std::max(1, inIndexCount); @@ -400,7 +401,7 @@ namespace Editor { return iter->second.Get(); } - auto bindGroup = window.GetDevice().CreateBindGroup( + auto bindGroup = device.CreateBindGroup( RHI::BindGroupCreateInfo(imguiBindGroupLayout.Get(), "imguiBindGroup") .AddEntry(RHI::BindGroupEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageTex").second, RHI::ShaderStageBits::sPixel, &inTextureView)) .AddEntry(RHI::BindGroupEntry(imguiPixelShaderCompileOutput.reflectionData.QueryResourceBindingChecked("imageSampler").second, RHI::ShaderStageBits::sPixel, imguiImageSampler.Get())) diff --git a/Editor/Src/ImGui/ImGuiWindow.cpp b/Editor/Src/ImGui/ImGuiWindow.cpp new file mode 100644 index 000000000..8d20b7a8c --- /dev/null +++ b/Editor/Src/ImGui/ImGuiWindow.cpp @@ -0,0 +1,181 @@ +#include + +#if PLATFORM_WINDOWS +#define GLFW_EXPOSE_NATIVE_WIN32 +#elif PLATFORM_MACOS +#define GLFW_EXPOSE_NATIVE_COCOA +#endif +#include +#include +#include + +#ifdef CreateSemaphore +#undef CreateSemaphore +#endif + +#include +#include +#include +#include +#include + +namespace Editor::WindowUi::Internal { + constexpr float fontSize = 15.0f; + uint32_t windowCount = 0; + + static GLFWwindow* CreateGlfwWindow(const ImGuiWindowDesc& inDesc) + { + if (windowCount == 0) { + const auto initialized = glfwInit(); + Assert(initialized == GLFW_TRUE); + } + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + glfwWindowHint(GLFW_MAXIMIZED, inDesc.maximized ? GLFW_TRUE : GLFW_FALSE); + auto* window = glfwCreateWindow(static_cast(inDesc.width), static_cast(inDesc.height), inDesc.title.c_str(), nullptr, nullptr); + Assert(window != nullptr); + ++windowCount; + return window; + } + + static void* NativeHandle(GLFWwindow* inWindow) + { +#if PLATFORM_WINDOWS + return glfwGetWin32Window(inWindow); +#elif PLATFORM_MACOS + return glfwGetCocoaView(inWindow); +#else + Unimplement(); + return nullptr; +#endif + } + + static Common::UVec2 FramebufferSize(GLFWwindow* inWindow) + { + int width = 0; + int height = 0; + glfwGetFramebufferSize(inWindow, &width, &height); + return { static_cast(std::max(1, width)), static_cast(std::max(1, height)) }; + } + + static void LoadIconFonts(ImFontAtlas& inFontAtlas) + { + static ImVector glyphRanges; + if (glyphRanges.empty()) { + ImFontGlyphRangesBuilder builder; + builder.AddText(Icons::Tabler::allGlyphs); + builder.BuildRanges(&glyphRanges); + } + const auto fontPath = (Core::Paths::EngineResDir() / "Editor" / "Icons" / "Tabler" / "tabler-icons.ttf").String(); + ImFontConfig config; + config.MergeMode = true; + config.PixelSnapH = true; + config.GlyphMinAdvanceX = fontSize; + config.GlyphMaxAdvanceX = fontSize; + Assert(inFontAtlas.AddFontFromFileTTF(fontPath.c_str(), fontSize, &config, glyphRanges.Data) != nullptr); + } +} + +namespace Editor { + ImGuiWindow::ImGuiWindow(ImGuiWindowDesc inDesc) + : desc(std::move(inDesc)) + , window(WindowUi::Internal::CreateGlfwWindow(desc)) + , renderThread(Runtime::EngineHolder::Get().GetRenderModule().GetRenderThread()) + , swapChainSurface(Common::MakeUnique( + *Runtime::EngineHolder::Get().GetRenderModule().GetDevice(), WindowUi::Internal::NativeHandle(window), + WindowUi::Internal::FramebufferSize(window).x, WindowUi::Internal::FramebufferSize(window).y)) + , imguiContext(nullptr) + { + InitializeImGui(); + imguiPlatform = Common::MakeUnique(window, desc); + imguiRenderer = Common::MakeUnique(swapChainSurface->GetDevice(), *swapChainSurface, renderThread); + } + + ImGuiWindow::~ImGuiWindow() + { + ImGui::SetCurrentContext(imguiContext); + WaitIdle(); + imguiPlatform.Reset(); + imguiRenderer.Reset(); + swapChainSurface.Reset(); + ImGui::DestroyContext(imguiContext); + glfwDestroyWindow(window); + if (--WindowUi::Internal::windowCount == 0) { + glfwTerminate(); + } + } + + bool ImGuiWindow::ShouldClose() const + { + return glfwWindowShouldClose(window) == GLFW_TRUE; + } + + void ImGuiWindow::RequestClose() const + { + glfwSetWindowShouldClose(window, GLFW_TRUE); + } + + void ImGuiWindow::Tick(float inDeltaSeconds) + { + glfwPollEvents(); + ImGui::SetCurrentContext(imguiContext); + const auto size = WindowUi::Internal::FramebufferSize(window); + if (size != swapChainSurface->GetSize()) { + WaitIdle(); + swapChainSurface->Resize(size.x, size.y); + } + imguiRenderer->NewFrame(); + imguiPlatform->NewFrame(inDeltaSeconds); + ImGui::NewFrame(); + RenderContents(); + } + + void ImGuiWindow::Render(float inDeltaSeconds) + { + ImGui::SetCurrentContext(imguiContext); + ImGui::Render(); + renderThread.EmplaceTask([this]() -> void { + imguiRenderer->WaitForPreviousFrame(); + swapChainSurface->AcquireBackTexture(); + }); + imguiRenderer->Submit(*ImGui::GetDrawData()); + renderThread.EmplaceTask([this]() -> void { + swapChainSurface->Present(); + }); + } + + void ImGuiWindow::WaitIdle() const + { + imguiRenderer->WaitIdle(); + swapChainSurface->WaitRenderingIdle(); + } + + GLFWwindow* ImGuiWindow::GetNativeWindow() const + { + return window; + } + + Render::SwapChainSurface& ImGuiWindow::GetSwapChainSurface() + { + return *swapChainSurface; + } + + void ImGuiWindow::InitializeImGui() + { + IMGUI_CHECKVERSION(); + imguiContext = ImGui::CreateContext(); + auto& io = ImGui::GetIO(); + io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; + if (!desc.layoutFile.Empty()) { + desc.layoutFile.Parent().MakeDir(); + imguiIniFilename = desc.layoutFile.String(); + io.IniFilename = imguiIniFilename.c_str(); + } else { + io.IniFilename = nullptr; + } + ImFontConfig fontConfig; + fontConfig.SizePixels = WindowUi::Internal::fontSize; + io.FontDefault = io.Fonts->AddFontDefaultVector(&fontConfig); + WindowUi::Internal::LoadIconFonts(*io.Fonts); + ThemeSwitcher::ApplyCurrentTheme(); + } +} diff --git a/Editor/Src/Frame/ProjectHubFrame.cpp b/Editor/Src/ProjectHubWindow.cpp similarity index 94% rename from Editor/Src/Frame/ProjectHubFrame.cpp rename to Editor/Src/ProjectHubWindow.cpp index 6d84ab6cc..969595dd4 100644 --- a/Editor/Src/Frame/ProjectHubFrame.cpp +++ b/Editor/Src/ProjectHubWindow.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -42,12 +42,12 @@ namespace Editor::ProjectHub::Internal { } namespace Editor { - ProjectHubFrame::ProjectHubFrame(ProjectService& inProjectService, RecentProjectStore& inRecentProjects, ProjectLauncher& inProjectLauncher) - : projectService(inProjectService) + ProjectHubWindow::ProjectHubWindow(ProjectService& inProjectService, RecentProjectStore& inRecentProjects, ProjectLauncher& inProjectLauncher) + : ImGuiWindow(ImGuiWindowDesc { .title = "Explosion Project Hub", .width = 560, .height = 720 }) + , projectService(inProjectService) , recentProjects(inRecentProjects) , projectLauncher(inProjectLauncher) , selectedTemplateIndex(0) - , requestClose(false) { auto templatesResult = projectService.ListTemplates(); if (templatesResult.IsOk()) { @@ -63,9 +63,9 @@ namespace Editor { } } - ProjectHubFrame::~ProjectHubFrame() = default; + ProjectHubWindow::~ProjectHubWindow() = default; - bool ProjectHubFrame::Render() + void ProjectHubWindow::RenderContents() { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->WorkPos); @@ -87,10 +87,9 @@ namespace Editor { RenderRecentProjects(); RenderCreateProjectPopup(); ImGui::End(); - return requestClose; } - void ProjectHubFrame::RenderActionBar() + void ProjectHubWindow::RenderActionBar() { const float spacing = ImGui::GetStyle().ItemSpacing.x; const float buttonWidth = (ImGui::GetContentRegionAvail().x - spacing) * 0.5f; @@ -109,7 +108,7 @@ namespace Editor { } } - void ProjectHubFrame::RenderRecentProjects() + void ProjectHubWindow::RenderRecentProjects() { const std::string recentProjectsLabel = Widgets::Label(Icons::Tabler::folder, "Recent projects"); ImGui::TextUnformatted(recentProjectsLabel.c_str()); @@ -153,7 +152,7 @@ namespace Editor { } } - void ProjectHubFrame::RenderCreateProjectPopup() + void ProjectHubWindow::RenderCreateProjectPopup() { const ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); @@ -246,7 +245,7 @@ namespace Editor { ImGui::PopStyleVar(4); } - void ProjectHubFrame::OpenProject(const Common::Path& inProjectPath) + void ProjectHubWindow::OpenProject(const Common::Path& inProjectPath) { const auto project = ProjectService::ValidateProject(inProjectPath); if (project.IsErr()) { @@ -261,6 +260,6 @@ namespace Editor { return; } statusMessage.clear(); - requestClose = true; + RequestClose(); } } diff --git a/Editor/Src/SceneClient.cpp b/Editor/Src/SceneClient.cpp index c09d97803..6e8c11261 100644 --- a/Editor/Src/SceneClient.cpp +++ b/Editor/Src/SceneClient.cpp @@ -1,366 +1,15 @@ -// -// Created by johnk on 2026/7/4. -// - -#include -#include - -#include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Editor::Internal { - const Core::Uri mainLevelUri("asset://Game/Maps/Main"); - const Core::Uri defaultUnlitMaterialUri("asset://Game/Materials/DefaultUnlit"); - const Core::Uri lightGrayUnlitMaterialInstanceUri("asset://Game/Materials/LightGrayUnlit"); - const Core::Uri yellowUnlitMaterialInstanceUri("asset://Game/Materials/YellowUnlit"); - const Core::Uri cubeMeshUri("asset://Game/Meshes/Cube"); - static bool AssetExists(const Core::Uri& inUri) - { - return Core::AssetUriParser(inUri).Parse().Exists(); - } - - template - static void SaveAsset(const Runtime::AssetPtr& inAsset) - { - if (const Common::Path parentDir = Core::AssetUriParser(inAsset->Uri()).Parse().Parent(); - !parentDir.Exists()) { - parentDir.MakeDir(); - } - Runtime::AssetManager::Get().Save(inAsset); - } - - static Runtime::StaticMeshVertices BuildCubeVertices() - { - // 24 vertices (4 per face) so each face gets its own uv space, z-up unit cube centered at origin - static constexpr float h = 0.5f; - static const std::array, 6> facePositions = {{ - {{ { -h, -h, h }, { h, -h, h }, { h, h, h }, { -h, h, h } }}, // +z - {{ { -h, h, -h }, { h, h, -h }, { h, -h, -h }, { -h, -h, -h } }}, // -z - {{ { h, -h, -h }, { h, h, -h }, { h, h, h }, { h, -h, h } }}, // +x - {{ { -h, h, -h }, { -h, -h, -h }, { -h, -h, h }, { -h, h, h } }}, // -x - {{ { h, h, -h }, { -h, h, -h }, { -h, h, h }, { h, h, h } }}, // +y - {{ { -h, -h, -h }, { h, -h, -h }, { h, -h, h }, { -h, -h, h } }} // -y - }}; - - Runtime::StaticMeshVertices result; - for (const auto& face : facePositions) { - const auto baseVertex = static_cast(result.positions.size()); - for (size_t corner = 0; corner < 4; corner++) { - result.positions.emplace_back(face[corner]); - result.tangents.emplace_back(0.0f, 0.0f, 1.0f); - result.uv0.emplace_back(corner == 1 || corner == 2 ? 1.0f : 0.0f, corner >= 2 ? 1.0f : 0.0f); - } - for (const uint32_t index : { 0u, 1u, 2u, 0u, 2u, 3u }) { - result.indices.emplace_back(baseVertex + index); - } - } - result.vertexCount = static_cast(result.positions.size()); - result.indexCount = static_cast(result.indices.size()); - return result; - } - - static Runtime::AssetPtr EnsureDefaultUnlitMaterial() - { - auto& assetManager = Runtime::AssetManager::Get(); - if (AssetExists(defaultUnlitMaterialUri)) { - return assetManager.SyncLoad(defaultUnlitMaterialUri, Mirror::Class::Get()); - } - - Runtime::AssetPtr material = new Runtime::Material(defaultUnlitMaterialUri); - material->SetType(Runtime::MaterialType::surface); - material->SetSource("float4 GetBaseColor()\n{\n return baseColor;\n}\n"); - Runtime::MaterialFVec4ParameterField baseColorField; - baseColorField.defaultValue = Common::FVec4(1.0f, 1.0f, 1.0f, 1.0f); - material->EmplaceParameterField("baseColor") = baseColorField; - material->Update(); - SaveAsset(material); - return material; - } - - static Runtime::AssetPtr EnsureDefaultUnlitMaterialInstance( - const Core::Uri& inUri, - const Common::FVec4& inBaseColor, - const Runtime::AssetPtr& inMaterial) - { - auto& assetManager = Runtime::AssetManager::Get(); - if (AssetExists(inUri)) { - return assetManager.SyncLoad(inUri, Mirror::Class::Get()); - } - - Runtime::AssetPtr materialInstance = new Runtime::MaterialInstance(inUri); - materialInstance->SetMaterial(inMaterial); - materialInstance->SetParameter("baseColor", inBaseColor); - SaveAsset(materialInstance); - return materialInstance; - } - - static Runtime::AssetPtr EnsureDefaultCubeMesh( - const Runtime::AssetPtr& inMaterial) - { - auto& assetManager = Runtime::AssetManager::Get(); - if (AssetExists(cubeMeshUri)) { - return assetManager.SyncLoad(cubeMeshUri, Mirror::Class::Get()); - } - - Runtime::AssetPtr mesh = new Runtime::StaticMesh(cubeMeshUri); - mesh->SetMaterial(inMaterial); - mesh->EmplaceLOD().vertices = BuildCubeVertices(); - SaveAsset(mesh); - return mesh; - } - - static void AuthorDefaultLevelContent(Runtime::ECRegistry& inRegistry) - { - const Runtime::AssetPtr defaultUnlitMaterial = EnsureDefaultUnlitMaterial(); - const Runtime::AssetPtr lightGrayMaterial = EnsureDefaultUnlitMaterialInstance( - lightGrayUnlitMaterialInstanceUri, - Common::FVec4(0.75f, 0.75f, 0.75f, 1.0f), - defaultUnlitMaterial); - const Runtime::AssetPtr yellowMaterial = EnsureDefaultUnlitMaterialInstance( - yellowUnlitMaterialInstanceUri, - Common::FVec4(1.0f, 1.0f, 0.0f, 1.0f), - defaultUnlitMaterial); - const Runtime::AssetPtr cubeMesh = EnsureDefaultCubeMesh(yellowMaterial); - - // WorldTransform's reflected constructor takes an FTransform, other argument shapes would not match it - const auto ground = inRegistry.Create(); - inRegistry.Emplace(ground, std::string("Ground")); - Common::FTransform groundTransform; - groundTransform.scale = Common::FVec3(10.0f, 10.0f, 0.2f); - groundTransform.translation = Common::FVec3(0.0f, 0.0f, -0.1f); - inRegistry.Emplace(ground, groundTransform); - auto& groundPrimitive = inRegistry.Emplace(ground); - groundPrimitive.mesh = cubeMesh; - groundPrimitive.materialOverride = lightGrayMaterial; - - const auto cube = inRegistry.Create(); - inRegistry.Emplace(cube, std::string("Cube")); - Common::FTransform cubeTransform; - cubeTransform.translation = Common::FVec3(0.0f, 0.0f, 0.5f); - inRegistry.Emplace(cube, cubeTransform); - auto& cubePrimitive = inRegistry.Emplace(cube); - cubePrimitive.mesh = cubeMesh; - cubePrimitive.materialOverride = yellowMaterial; - - const auto playerStart = inRegistry.Create(); - inRegistry.Emplace(playerStart, std::string("Player Start")); - const Common::FTransform playerStartTransform = Common::FTransform::LookAt(Common::FVec3(-5.0f, -6.0f, 4.0f), Common::FVec3(0.0f, 0.0f, 0.5f)); - inRegistry.Emplace(playerStart, playerStartTransform); - inRegistry.Emplace(playerStart); - } -} namespace Editor { - SceneClient::SceneClient() - : levelUri(Internal::mainLevelUri) - , world("EditorWorld", this, Runtime::PlayType::editor) - , window(nullptr) - , renderSurface(nullptr) - , editorCamera(Runtime::entityNull) - , sceneHovered(false) + SceneClient::SceneClient(Runtime::World& inWorld) + : world(inWorld) { - world.SetSystemGraph(EditorSystemGraphPresets::DefaultEditorWorld()); } - SceneClient::~SceneClient() - { - EndCameraLook(); - if (!world.Stopped()) { - world.Stop(); - } - } + SceneClient::~SceneClient() = default; Runtime::World& SceneClient::GetWorld() { return world; } - - Runtime::RenderSurface* SceneClient::GetRenderSurface() - { - return renderSurface; - } - - void SceneClient::SetEditorWindow(EditorWindow& inWindow) - { - window = &inWindow; - } - - void SceneClient::SetRenderSurface(Runtime::RenderSurface* inRenderSurface) - { - renderSurface = inRenderSurface; - } - - void SceneClient::ResizeRenderSurface(uint32_t inWidth, uint32_t inHeight) - { - if (renderSurface == nullptr) { - return; - } - if (const auto* texture = renderSurface->GetTexture(); - texture != nullptr - && texture->GetCreateInfo().width == inWidth - && texture->GetCreateInfo().height == inHeight) { - return; - } - if (window != nullptr) { - window->WaitRenderingIdle(); - } - renderSurface->Resize(inWidth, inHeight); - } - - void SceneClient::OpenProjectLevel() - { - Assert(world.Stopped()); - if (Internal::AssetExists(levelUri)) { - const auto level = Runtime::AssetManager::Get().SyncLoad(levelUri, Mirror::Class::Get()); - world.LoadFrom(level); - } else { - world.EditorAccess(Internal::AuthorDefaultLevelContent); - SaveLevel(); - } - CreateEditorCamera(); - world.Play(); - } - - void SceneClient::SaveLevel() - { - Runtime::AssetPtr level = new Runtime::Level(levelUri); - world.SaveTo(level); - Internal::SaveAsset(level); - } - - Runtime::Entity SceneClient::GetEditorCamera() const - { - return editorCamera; - } - - void SceneClient::SetSceneHovered(bool inHovered) - { - sceneHovered = inHovered; - } - - void SceneClient::SetSceneFocused(bool inFocused) - { - if (!inFocused && !IsCameraLooking() && world.Playing()) { - world.EditorAccess([](Runtime::ECRegistry& registry) -> void { - registry.GUpdate([](EditorCameraInput& input) -> void { - input.moveForward = false; - input.moveBackward = false; - input.moveLeft = false; - input.moveRight = false; - }); - }); - } - } - - bool SceneClient::IsSceneHovered() const - { - return sceneHovered; - } - - bool SceneClient::IsCameraLooking() - { - if (!world.Playing()) { - return false; - } - bool looking = false; - world.EditorAccess([&](Runtime::ECRegistry& registry) -> void { - looking = registry.GHas() - && registry.GGet().looking; - }); - return looking; - } - - void SceneClient::OnKey(int inKey, bool inPressed) - { - if (!world.Playing()) { - return; - } - if (inKey != GLFW_KEY_W && inKey != GLFW_KEY_S && inKey != GLFW_KEY_A && inKey != GLFW_KEY_D) { - return; - } - world.EditorAccess([&](Runtime::ECRegistry& registry) -> void { - if (!registry.GHas()) { - return; - } - registry.GUpdate([&](EditorCameraInput& input) -> void { - if (inKey == GLFW_KEY_W) { input.moveForward = inPressed; } - if (inKey == GLFW_KEY_S) { input.moveBackward = inPressed; } - if (inKey == GLFW_KEY_A) { input.moveLeft = inPressed; } - if (inKey == GLFW_KEY_D) { input.moveRight = inPressed; } - }); - }); - } - - void SceneClient::BeginCameraLook() - { - if (IsCameraLooking() || !sceneHovered || !world.Playing()) { - return; - } - world.EditorAccess([](Runtime::ECRegistry& registry) -> void { - registry.GUpdate([](EditorCameraInput& input) -> void { - input.looking = true; - input.lookDelta = Common::FVec2Consts::zero; - }); - }); - if (window != nullptr) { - window->SetCursorCaptured(true); - } - } - - void SceneClient::EndCameraLook() - { - if (!IsCameraLooking()) { - return; - } - world.EditorAccess([](Runtime::ECRegistry& registry) -> void { - registry.GUpdate([](EditorCameraInput& input) -> void { - input.moveForward = false; - input.moveBackward = false; - input.moveLeft = false; - input.moveRight = false; - input.looking = false; - input.lookDelta = Common::FVec2Consts::zero; - }); - }); - if (window != nullptr) { - window->SetCursorCaptured(false); - } - } - - void SceneClient::AddCameraLookDelta(float inDeltaX, float inDeltaY) - { - if (!IsCameraLooking()) { - return; - } - world.EditorAccess([&](Runtime::ECRegistry& registry) -> void { - registry.GUpdate([&](EditorCameraInput& input) -> void { - input.lookDelta += Common::FVec2(inDeltaX, inDeltaY); - }); - }); - } - - void SceneClient::CreateEditorCamera() - { - world.EditorAccess([&](Runtime::ECRegistry& registry) -> void { - editorCamera = registry.Create(); - registry.AddTag(editorCamera); - registry.Emplace(editorCamera); - registry.Emplace(editorCamera); - const Common::FTransform cameraTransform = Common::FTransform::LookAt(Common::FVec3(-5.0f, -6.0f, 4.0f), Common::FVec3(0.0f, 0.0f, 0.5f)); - registry.Emplace(editorCamera, cameraTransform); - }); - } - } diff --git a/Editor/Src/SceneViewport.cpp b/Editor/Src/SceneViewport.cpp new file mode 100644 index 000000000..c1094e683 --- /dev/null +++ b/Editor/Src/SceneViewport.cpp @@ -0,0 +1,190 @@ +#include + +#include +#include +#include +#include +#include + +namespace Editor::SceneViewing::Internal { + static Render::CanvasDesc SceneCanvasDesc() + { + Render::CanvasDesc desc; + desc.width = 1280; + desc.height = 720; + desc.debugName = "editorSceneColor"; + return desc; + } +} + +namespace Editor { + SceneViewport::SceneViewport(Runtime::World& inWorld, GLFWwindow* inWindow, RHI::Device& inDevice) + : world(inWorld) + , window(inWindow) + , client(world) + , canvas(inDevice, SceneViewing::Internal::SceneCanvasDesc()) + , camera(CreateCamera()) + , visible(false) + , hovered(false) + { + } + + SceneViewport::~SceneViewport() + { + EndCameraLook(); + WaitIdle(); + world.EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + inRegistry.Destroy(camera); + }); + } + + void SceneViewport::Render(float inDeltaSeconds) + { + if (visible) { + Runtime::Viewport::Render(inDeltaSeconds); + } + } + + void SceneViewport::Resize(uint32_t inWidth, uint32_t inHeight) + { + if (canvas.GetSize() == Common::UVec2(inWidth, inHeight)) { + return; + } + WaitIdle(); + canvas.Resize(inWidth, inHeight); + } + + RHI::TextureView* SceneViewport::GetTextureView() const + { + return canvas.GetTextureView(); + } + + void SceneViewport::SetVisible(bool inVisible) + { + visible = inVisible; + if (!visible) { + EndCameraLook(); + hovered = false; + SetFocused(false); + } + } + + void SceneViewport::SetHovered(bool inHovered) + { + hovered = inHovered; + } + + void SceneViewport::SetFocused(bool inFocused) + { + if (!inFocused && !IsCameraLooking()) { + world.EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + inRegistry.Update(camera, [](EditorCameraInput& input) -> void { + input.moveForward = false; + input.moveBackward = false; + input.moveLeft = false; + input.moveRight = false; + }); + }); + } + } + + bool SceneViewport::IsHovered() const + { + return hovered; + } + + bool SceneViewport::IsCameraLooking() const + { + bool looking = false; + world.EditorAccess([&](Runtime::ECRegistry& inRegistry) -> void { + looking = inRegistry.Get(camera).looking; + }); + return looking; + } + + void SceneViewport::OnKey(int inKey, bool inPressed) + { + if (inKey != GLFW_KEY_W && inKey != GLFW_KEY_S && inKey != GLFW_KEY_A && inKey != GLFW_KEY_D) { + return; + } + world.EditorAccess([&](Runtime::ECRegistry& inRegistry) -> void { + inRegistry.Update(camera, [&](EditorCameraInput& input) -> void { + if (inKey == GLFW_KEY_W) { input.moveForward = inPressed; } + if (inKey == GLFW_KEY_S) { input.moveBackward = inPressed; } + if (inKey == GLFW_KEY_A) { input.moveLeft = inPressed; } + if (inKey == GLFW_KEY_D) { input.moveRight = inPressed; } + }); + }); + } + + void SceneViewport::BeginCameraLook() + { + if (!hovered || IsCameraLooking()) { + return; + } + world.EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + inRegistry.Update(camera, [](EditorCameraInput& input) -> void { + input.looking = true; + input.lookDelta = Common::FVec2Consts::zero; + }); + }); + glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); + } + + void SceneViewport::EndCameraLook() + { + if (!IsCameraLooking()) { + return; + } + world.EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + inRegistry.Update(camera, [](EditorCameraInput& input) -> void { + input.moveForward = false; + input.moveBackward = false; + input.moveLeft = false; + input.moveRight = false; + input.looking = false; + input.lookDelta = Common::FVec2Consts::zero; + }); + }); + glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); + } + + void SceneViewport::AddCameraLookDelta(float inDeltaX, float inDeltaY) + { + world.EditorAccess([&](Runtime::ECRegistry& inRegistry) -> void { + inRegistry.Update(camera, [&](EditorCameraInput& input) -> void { + input.lookDelta += Common::FVec2(inDeltaX, inDeltaY); + }); + }); + } + + Runtime::Entity SceneViewport::CreateCamera() + { + Runtime::Entity entity = Runtime::entityNull; + world.EditorAccess([&](Runtime::ECRegistry& inRegistry) -> void { + entity = inRegistry.Create(); + inRegistry.AddTag(entity); + inRegistry.Emplace(entity); + inRegistry.Emplace(entity); + inRegistry.Emplace(entity); + inRegistry.Emplace(entity, Common::FTransform::LookAt( + Common::FVec3(-5.0f, -6.0f, 4.0f), Common::FVec3(0.0f, 0.0f, 0.5f))); + }); + return entity; + } + + Runtime::Client& SceneViewport::GetClient() + { + return client; + } + + Render::RenderSurface& SceneViewport::GetRenderSurface() + { + return canvas; + } + + std::vector SceneViewport::BuildViews(Runtime::ECRegistry& inRegistry, Common::UVec2 inSize) + { + return { BuildViewForCamera(inRegistry, camera, Common::URect::FromMinExtent(0, 0, inSize.x, inSize.y)) }; + } +} diff --git a/Editor/Src/System/Camera.cpp b/Editor/Src/System/Camera.cpp index c9ce6a36c..20469a1a3 100644 --- a/Editor/Src/System/Camera.cpp +++ b/Editor/Src/System/Camera.cpp @@ -43,23 +43,19 @@ namespace Editor { EditorCameraSystem::EditorCameraSystem(Runtime::ECRegistry& inRegistry, const Runtime::SystemSetupContext& inContext) : System(inRegistry, inContext) { - registry.GEmplace(); } - EditorCameraSystem::~EditorCameraSystem() - { - registry.GRemove(); - } + EditorCameraSystem::~EditorCameraSystem() = default; void EditorCameraSystem::Tick(float inDeltaTimeSeconds) { - auto& input = registry.GGet(); - const Common::FVec2 moveInput = input.looking ? Internal::GetMoveInput(input) : Common::FVec2Consts::zero; - const bool moving = moveInput.x != 0.0f || moveInput.y != 0.0f; - const bool looking = input.looking && (input.lookDelta.x != 0.0f || input.lookDelta.y != 0.0f); - - registry.View().Each( - [&](Runtime::Entity entity, EditorCameraController& controller, Runtime::WorldTransform& worldTransform) -> void { + registry.View().Each( + [&](Runtime::Entity entity, EditorCameraController& controller, EditorCameraInput& input, Runtime::WorldTransform& worldTransform) -> void { + const Common::FVec2 moveInput = input.looking ? Internal::GetMoveInput(input) : Common::FVec2Consts::zero; + const bool moving = moveInput.x != 0.0f || moveInput.y != 0.0f; + const bool looking = input.looking && (input.lookDelta.x != 0.0f || input.lookDelta.y != 0.0f); + const auto lookDelta = input.lookDelta; + input.lookDelta = Common::FVec2Consts::zero; if (!controller.anglesInitialized) { const auto forward = worldTransform.localToWorld.GetRotationMatrix().Col(0); controller.yaw = std::atan2(-forward.y, forward.x); @@ -69,8 +65,8 @@ namespace Editor { } if (looking) { - controller.yaw -= input.lookDelta.x * Internal::cameraLookSpeedDegrees * Internal::degToRad; - controller.pitch -= input.lookDelta.y * Internal::cameraLookSpeedDegrees * Internal::degToRad; + controller.yaw -= lookDelta.x * Internal::cameraLookSpeedDegrees * Internal::degToRad; + controller.pitch -= lookDelta.y * Internal::cameraLookSpeedDegrees * Internal::degToRad; const float maxPitch = Internal::maxCameraPitchDegrees * Internal::degToRad; controller.pitch = std::clamp(controller.pitch, -maxPitch, maxPitch); } @@ -90,7 +86,5 @@ namespace Editor { transform.localToWorld.rotation = orientation; }); }); - - input.lookDelta = Common::FVec2Consts::zero; } } diff --git a/Editor/Src/SystemGraphPresets.cpp b/Editor/Src/SystemGraphPresets.cpp index 6f29f9d74..a4096ce4a 100644 --- a/Editor/Src/SystemGraphPresets.cpp +++ b/Editor/Src/SystemGraphPresets.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include @@ -16,9 +15,8 @@ namespace Editor { auto& transformGroup = systemGraph.AddGroup("Transform", Runtime::SystemExecuteStrategy::sequential); transformGroup.EmplaceSystem(); - auto& sceneRenderingGroup = systemGraph.AddGroup("SceneRendering", Runtime::SystemExecuteStrategy::sequential); - sceneRenderingGroup.EmplaceSystem(); - sceneRenderingGroup.EmplaceSystem(); + auto& sceneGroup = systemGraph.AddGroup("Scene", Runtime::SystemExecuteStrategy::sequential); + sceneGroup.EmplaceSystem(); return systemGraph; }(); diff --git a/Editor/Src/Tab/InspectorTab.cpp b/Editor/Src/Tab/InspectorTab.cpp index 39ce16765..7a1246902 100644 --- a/Editor/Src/Tab/InspectorTab.cpp +++ b/Editor/Src/Tab/InspectorTab.cpp @@ -44,7 +44,7 @@ namespace Editor { void InspectorTab::RenderContents() { - context.GetSceneClient().GetWorld().EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + context.GetWorld().EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { RenderComponents(inRegistry); }); } diff --git a/Editor/Src/Tab/OutlinerTab.cpp b/Editor/Src/Tab/OutlinerTab.cpp index f1769ecd4..ff268d9db 100644 --- a/Editor/Src/Tab/OutlinerTab.cpp +++ b/Editor/Src/Tab/OutlinerTab.cpp @@ -35,7 +35,7 @@ namespace Editor { void OutlinerTab::RenderContents() { - context.GetSceneClient().GetWorld().EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { + context.GetWorld().EditorAccess([this](Runtime::ECRegistry& inRegistry) -> void { RenderEntities(inRegistry); }); } diff --git a/Editor/Src/Tab/SceneTab.cpp b/Editor/Src/Tab/SceneTab.cpp index fc6a00a21..095120e05 100644 --- a/Editor/Src/Tab/SceneTab.cpp +++ b/Editor/Src/Tab/SceneTab.cpp @@ -1,13 +1,12 @@ #include #include -#include +#include #include #include -#include namespace Editor { - SceneTab::SceneTab(SceneClient& inSceneClient, Runtime::Canvas& inCanvas) + SceneTab::SceneTab(SceneViewport& inViewport) : EditorTab(EditorTabDesc { .id = "Scene", .title = "Scene", @@ -16,8 +15,7 @@ namespace Editor { .windowFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse, .contentPadding = false }) - , sceneClient(inSceneClient) - , canvas(inCanvas) + , viewport(inViewport) { } @@ -28,18 +26,17 @@ namespace Editor { size.y = std::max(size.y, 1.0f); const ImVec2 framebufferScale = ImGui::GetIO().DisplayFramebufferScale; - sceneClient.ResizeRenderSurface( + viewport.SetVisible(true); + viewport.Resize( std::max(1u, static_cast(size.x * framebufferScale.x)), std::max(1u, static_cast(size.y * framebufferScale.y))); - ImGui::Image(static_cast(reinterpret_cast(canvas.GetTextureView())), size); - sceneClient.SetSceneHovered(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)); - sceneClient.SetSceneFocused(ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)); + ImGui::Image(static_cast(reinterpret_cast(viewport.GetTextureView())), size); + viewport.SetHovered(ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)); + viewport.SetFocused(ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)); } void SceneTab::OnHidden() { - sceneClient.EndCameraLook(); - sceneClient.SetSceneHovered(false); - sceneClient.SetSceneFocused(false); + viewport.SetVisible(false); } } diff --git a/Engine/Source/Launch/CMakeLists.txt b/Engine/Source/Launch/CMakeLists.txt index 03a8e62d1..dbf53c679 100644 --- a/Engine/Source/Launch/CMakeLists.txt +++ b/Engine/Source/Launch/CMakeLists.txt @@ -4,5 +4,6 @@ exp_add_library( TYPE STATIC SRC ${sources} PUBLIC_INC Include - PUBLIC_LIB Runtime glfw -) \ No newline at end of file + PUBLIC_LIB Runtime + PRIVATE_LIB glfw +) diff --git a/Engine/Source/Launch/Include/Launch/GameApplication.h b/Engine/Source/Launch/Include/Launch/GameApplication.h index 37e5b8600..a9156e6b3 100644 --- a/Engine/Source/Launch/Include/Launch/GameApplication.h +++ b/Engine/Source/Launch/Include/Launch/GameApplication.h @@ -9,6 +9,7 @@ #include #include #include +#include namespace Launch { class GameApplication { @@ -23,8 +24,9 @@ namespace Launch { double lastFrameTimeSeconds; double thisFrameTimeSeconds; float deltaTimeSeconds; - Common::UniquePtr window; + Common::UniquePtr world; Common::UniquePtr client; + Common::UniquePtr window; Runtime::Engine* engine; Runtime::GameModule* gameModule; }; diff --git a/Engine/Source/Launch/Include/Launch/GameClient.h b/Engine/Source/Launch/Include/Launch/GameClient.h index e21b08d65..cdf312098 100644 --- a/Engine/Source/Launch/Include/Launch/GameClient.h +++ b/Engine/Source/Launch/Include/Launch/GameClient.h @@ -1,25 +1,16 @@ -// -// Created by johnk on 2025/2/19. -// - #pragma once #include -#include namespace Launch { - class GameWindow; - class GameClient final : public Runtime::Client { public: - explicit GameClient(GameWindow& inWindow); + explicit GameClient(Runtime::World& inWorld); ~GameClient() override; Runtime::World& GetWorld() override; - Runtime::RenderSurface* GetRenderSurface() override; private: - GameWindow& window; - Runtime::World world; + Runtime::World& world; }; } diff --git a/Engine/Source/Launch/Include/Launch/GameViewport.h b/Engine/Source/Launch/Include/Launch/GameViewport.h new file mode 100644 index 000000000..9e77c3fb6 --- /dev/null +++ b/Engine/Source/Launch/Include/Launch/GameViewport.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +namespace Launch { + class GameViewport final : public Runtime::Viewport { + public: + GameViewport(GameClient& inClient, Render::RenderSurface& inSurface); + ~GameViewport() override; + + private: + Runtime::Client& GetClient() override; + Render::RenderSurface& GetRenderSurface() override; + std::vector BuildViews(Runtime::ECRegistry& inRegistry, Common::UVec2 inSize) override; + static Common::URect GetPlayerViewport(Common::UVec2 inSize, uint8_t inPlayerNum, uint8_t inPlayerIndex); + + GameClient& client; + Render::RenderSurface& surface; + }; +} diff --git a/Engine/Source/Launch/Include/Launch/GameWindow.h b/Engine/Source/Launch/Include/Launch/GameWindow.h index 63ab54326..57d59e708 100644 --- a/Engine/Source/Launch/Include/Launch/GameWindow.h +++ b/Engine/Source/Launch/Include/Launch/GameWindow.h @@ -1,21 +1,16 @@ -// -// Created by johnk on 2025/2/19. -// - #pragma once -#include -#if PLATFORM_WINDOWS -#define GLFW_EXPOSE_NATIVE_WIN32 -#elif PLATFORM_MACOS -#define GLFW_EXPOSE_NATIVE_COCOA -#endif -#include +#include -#include +#include +#include #include +struct GLFWwindow; + namespace Launch { + class GameClient; + struct GameWindowDesc { std::string title; uint32_t width; @@ -24,17 +19,19 @@ namespace Launch { class GameWindow final : public Runtime::Window { public: - explicit GameWindow(const GameWindowDesc& inDesc); + GameWindow(RHI::Device& inDevice, Render::RenderThread& inRenderThread, GameClient& inClient, const GameWindowDesc& inDesc); ~GameWindow() override; - void Resize(uint32_t inWidth, uint32_t inHeight) override; - - bool ShouldClose() const; - void PollEvents() const; - void WaitRenderingIdle() const; + bool ShouldClose() const override; + void RequestClose() const override; + void Tick(float inDeltaSeconds) override; + void Render(float inDeltaSeconds) override; + void WaitIdle() const override; private: - Render::RenderModule& renderModule; GLFWwindow* window; + Render::RenderThread& renderThread; + Common::UniquePtr swapChainSurface; + Common::UniquePtr viewport; }; } diff --git a/Engine/Source/Launch/Src/GameApplication.cpp b/Engine/Source/Launch/Src/GameApplication.cpp index 4aca50897..b994299c1 100644 --- a/Engine/Source/Launch/Src/GameApplication.cpp +++ b/Engine/Source/Launch/Src/GameApplication.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -42,25 +43,29 @@ namespace Launch { windowDesc.title = gameModule->GetGameName(); windowDesc.width = 1024; windowDesc.height = 768; - window = Common::MakeUnique(windowDesc); - client = Common::MakeUnique(*window); + auto& renderModule = engine->GetRenderModule(); + world = Common::MakeUnique("GameWorld", Runtime::PlayType::game); + world->SetSystemGraph(Runtime::SystemGraphPresets::Default3DWorld()); + client = Common::MakeUnique(*world); + window.Reset(new GameWindow(*renderModule.GetDevice(), renderModule.GetRenderThread(), *client, windowDesc)); auto& settingRegistry = Runtime::SettingsRegistry::Get(); settingRegistry.LoadAllSettings(); const auto& gameSettings = Runtime::SettingsRegistry::Get().GetSettings(); const auto startupLevel = Runtime::AssetManager::Get().SyncLoad(gameSettings.gameStartupLevel, Runtime::Level::GetStaticClass()); - client->GetWorld().LoadFrom(startupLevel); - client->GetWorld().Play(); + world->LoadFrom(startupLevel); + world->Play(); } GameApplication::~GameApplication() { - if (client.Valid() && !client->GetWorld().Stopped()) { - client->GetWorld().Stop(); + window.Reset(); + if (!world->Stopped()) { + world->Stop(); } client.Reset(); - window.Reset(); + world.Reset(); Runtime::EngineHolder::Unload(); } @@ -71,7 +76,6 @@ namespace Launch { lastFrameTimeSeconds = thisFrameTimeSeconds; engine->Tick(deltaTimeSeconds); - window->PollEvents(); } bool GameApplication::ShouldClose() const diff --git a/Engine/Source/Launch/Src/GameClient.cpp b/Engine/Source/Launch/Src/GameClient.cpp index 715ae3155..5aa78ed24 100644 --- a/Engine/Source/Launch/Src/GameClient.cpp +++ b/Engine/Source/Launch/Src/GameClient.cpp @@ -1,17 +1,9 @@ -// -// Created by johnk on 2025/2/19. -// - #include -#include -#include namespace Launch { - GameClient::GameClient(GameWindow& inWindow) - : window(inWindow) - , world("GameWorld", this, Runtime::PlayType::game) + GameClient::GameClient(Runtime::World& inWorld) + : world(inWorld) { - world.SetSystemGraph(Runtime::SystemGraphPresets::Default3DWorld()); } GameClient::~GameClient() = default; @@ -20,9 +12,4 @@ namespace Launch { { return world; } - - Runtime::RenderSurface* GameClient::GetRenderSurface() - { - return &window; - } } diff --git a/Engine/Source/Launch/Src/GameViewport.cpp b/Engine/Source/Launch/Src/GameViewport.cpp new file mode 100644 index 000000000..72659ef69 --- /dev/null +++ b/Engine/Source/Launch/Src/GameViewport.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include + +namespace Launch { + GameViewport::GameViewport(GameClient& inClient, Render::RenderSurface& inSurface) + : client(inClient) + , surface(inSurface) + { + } + + GameViewport::~GameViewport() = default; + + Runtime::Client& GameViewport::GetClient() + { + return client; + } + + Render::RenderSurface& GameViewport::GetRenderSurface() + { + return surface; + } + + std::vector GameViewport::BuildViews(Runtime::ECRegistry& inRegistry, Common::UVec2 inSize) + { + std::vector views; + const auto cameras = inRegistry.View(); + for (const auto& entry : cameras.All()) { + const auto entity = std::get<0>(entry); + auto rect = Common::URect::FromMinExtent(0, 0, inSize.x, inSize.y); + if (inRegistry.Has(entity)) { + const auto& players = inRegistry.GGet().players; + rect = GetPlayerViewport(inSize, static_cast(players.size()), inRegistry.Get(entity).localPlayerIndex); + } + views.emplace_back(BuildViewForCamera(inRegistry, entity, rect)); + } + return views; + } + + Common::URect GameViewport::GetPlayerViewport(Common::UVec2 inSize, uint8_t inPlayerNum, uint8_t inPlayerIndex) + { + Assert(inPlayerNum > 0 && inPlayerIndex < inPlayerNum); + if (inPlayerNum == 1) { + return Common::URect::FromMinExtent(0, 0, inSize.x, inSize.y); + } + if (inPlayerNum == 2) { + return Common::URect::FromMinExtent(inSize.x / 2 * inPlayerIndex, 0, inSize.x / 2, inSize.y); + } + Assert(inPlayerNum <= 4); + return Common::URect::FromMinExtent( + inSize.x / 2 * (inPlayerIndex % 2), inSize.y / 2 * (inPlayerIndex / 2), inSize.x / 2, inSize.y / 2); + } +} diff --git a/Engine/Source/Launch/Src/GameWindow.cpp b/Engine/Source/Launch/Src/GameWindow.cpp index 666c2c304..8ac7aefea 100644 --- a/Engine/Source/Launch/Src/GameWindow.cpp +++ b/Engine/Source/Launch/Src/GameWindow.cpp @@ -1,12 +1,38 @@ -// -// Created by johnk on 2025/2/19. -// +#include +#if PLATFORM_WINDOWS +#define GLFW_EXPOSE_NATIVE_WIN32 +#elif PLATFORM_MACOS +#define GLFW_EXPOSE_NATIVE_COCOA +#endif +#include +#include + +#ifdef CreateSemaphore +#undef CreateSemaphore +#endif + +#include #include -#include -namespace Launch::Internal { - static void* GetGlfwPlatformWindow(GLFWwindow* inWindow) +namespace Launch::GameWindowing::Internal { + uint32_t windowCount = 0; + + static GLFWwindow* CreateGlfwWindow(const GameWindowDesc& inDesc) + { + if (windowCount == 0) { + const auto initialized = glfwInit(); + Assert(initialized == GLFW_TRUE); + } + glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); + glfwWindowHint(GLFW_MAXIMIZED, GLFW_FALSE); + auto* window = glfwCreateWindow(static_cast(inDesc.width), static_cast(inDesc.height), inDesc.title.c_str(), nullptr, nullptr); + Assert(window != nullptr); + ++windowCount; + return window; + } + + static void* NativeHandle(GLFWwindow* inWindow) { #if PLATFORM_WINDOWS return glfwGetWin32Window(inWindow); @@ -17,58 +43,68 @@ namespace Launch::Internal { return nullptr; #endif } + + static Common::UVec2 FramebufferSize(GLFWwindow* inWindow) + { + int width = 0; + int height = 0; + glfwGetFramebufferSize(inWindow, &width, &height); + return { static_cast(std::max(1, width)), static_cast(std::max(1, height)) }; + } } namespace Launch { - GameWindow::GameWindow(const GameWindowDesc& inDesc) - : Runtime::Window(*Runtime::EngineHolder::Get().GetRenderModule().GetDevice()) - , renderModule(Runtime::EngineHolder::Get().GetRenderModule()) - , window(nullptr) + GameWindow::GameWindow(RHI::Device& inDevice, Render::RenderThread& inRenderThread, GameClient& inClient, const GameWindowDesc& inDesc) + : window(GameWindowing::Internal::CreateGlfwWindow(inDesc)) + , renderThread(inRenderThread) + , swapChainSurface(Common::MakeUnique( + inDevice, GameWindowing::Internal::NativeHandle(window), + GameWindowing::Internal::FramebufferSize(window).x, GameWindowing::Internal::FramebufferSize(window).y)) + , viewport(new GameViewport(inClient, *swapChainSurface)) { - glfwInit(); - glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); - window = glfwCreateWindow( - static_cast(inDesc.width), - static_cast(inDesc.height), - inDesc.title.c_str(), - nullptr, - nullptr); - Assert(window != nullptr); - - InitializeSurface( - GetDevice().CreateSurface(RHI::SurfaceCreateInfo(Internal::GetGlfwPlatformWindow(window))), - inDesc.width, - inDesc.height); } GameWindow::~GameWindow() { - WaitRenderingIdle(); - DestroySurface(); + WaitIdle(); + viewport.Reset(); + swapChainSurface.Reset(); glfwDestroyWindow(window); - glfwTerminate(); + if (--GameWindowing::Internal::windowCount == 0) { + glfwTerminate(); + } } - void GameWindow::Resize(uint32_t inWidth, uint32_t inHeight) + bool GameWindow::ShouldClose() const { - glfwSetWindowSize(window, static_cast(inWidth), static_cast(inHeight)); - WaitRenderingIdle(); - Runtime::Window::Resize(inWidth, inHeight); + return glfwWindowShouldClose(window) == GLFW_TRUE; } - bool GameWindow::ShouldClose() const + void GameWindow::RequestClose() const { - return static_cast(glfwWindowShouldClose(window)); + glfwSetWindowShouldClose(window, GLFW_TRUE); } - void GameWindow::PollEvents() const + void GameWindow::Tick(float inDeltaSeconds) { glfwPollEvents(); + const auto size = GameWindowing::Internal::FramebufferSize(window); + if (size != swapChainSurface->GetSize()) { + WaitIdle(); + swapChainSurface->Resize(size.x, size.y); + } + } + + void GameWindow::Render(float inDeltaSeconds) + { + renderThread.EmplaceTask([this]() -> void { swapChainSurface->AcquireBackTexture(); }); + viewport->Render(inDeltaSeconds); + renderThread.EmplaceTask([this]() -> void { swapChainSurface->Present(); }); } - void GameWindow::WaitRenderingIdle() const + void GameWindow::WaitIdle() const { - renderModule.GetRenderThread().Flush(); - Runtime::Window::WaitRenderingIdle(); + renderThread.Flush(); + swapChainSurface->WaitRenderingIdle(); } } diff --git a/Engine/Source/Runtime/Include/Runtime/Canvas.h b/Engine/Source/Render/Include/Render/Canvas.h similarity index 75% rename from Engine/Source/Runtime/Include/Runtime/Canvas.h rename to Engine/Source/Render/Include/Render/Canvas.h index 156049a8f..0c9c41bd4 100644 --- a/Engine/Source/Runtime/Include/Runtime/Canvas.h +++ b/Engine/Source/Render/Include/Render/Canvas.h @@ -8,10 +8,10 @@ #include #include -#include +#include -namespace Runtime { - struct RUNTIME_API CanvasDesc { +namespace Render { + struct CanvasDesc { CanvasDesc(); uint32_t width; @@ -20,13 +20,14 @@ namespace Runtime { std::string debugName; }; - class RUNTIME_API Canvas : public RenderSurface { + class Canvas final : public RenderSurface { public: Canvas(RHI::Device& inDevice, const CanvasDesc& inDesc); ~Canvas() override; - RHI::Texture* GetTexture() const override; - RHI::TextureView* GetRenderTargetView() const override; + SurfaceTarget GetRenderTarget() const override; + Common::UVec2 GetSize() const override; + RHI::PixelFormat GetFormat() const override; RHI::TextureView* GetTextureView() const; void Resize(uint32_t inWidth, uint32_t inHeight) override; diff --git a/Engine/Source/Render/Include/Render/RenderSurface.h b/Engine/Source/Render/Include/Render/RenderSurface.h new file mode 100644 index 000000000..c3573ab05 --- /dev/null +++ b/Engine/Source/Render/Include/Render/RenderSurface.h @@ -0,0 +1,40 @@ +// +// Created by johnk on 2026/7/8. +// + +#pragma once + +#include + +#include +#include +#include +#include + +namespace Render { + struct SurfaceTarget { + RHI::Texture* texture; + RHI::TextureView* renderTargetView; + RHI::TextureState beforeRenderState; + RHI::TextureState afterRenderState; + RHI::Semaphore* waitSemaphore = nullptr; + RHI::Semaphore* signalSemaphore = nullptr; + }; + + class RenderSurface { + public: + virtual ~RenderSurface(); + + NonCopyable(RenderSurface) + NonMovable(RenderSurface) + + // Read on the render thread, after acquiring the backbuffer when this is a window surface. + virtual SurfaceTarget GetRenderTarget() const = 0; + virtual Common::UVec2 GetSize() const = 0; + virtual RHI::PixelFormat GetFormat() const = 0; + virtual void Resize(uint32_t inWidth, uint32_t inHeight) = 0; + + protected: + RenderSurface(); + }; +} diff --git a/Engine/Source/Render/Include/Render/SwapChainSurface.h b/Engine/Source/Render/Include/Render/SwapChainSurface.h new file mode 100644 index 000000000..8ad936c12 --- /dev/null +++ b/Engine/Source/Render/Include/Render/SwapChainSurface.h @@ -0,0 +1,48 @@ +// +// Created by johnk on 2026/7/8. +// + +#pragma once + +#include + +#include +#include +#include + +namespace Render { + class SwapChainSurface final : public RenderSurface { + public: + SwapChainSurface(RHI::Device& inDevice, void* inNativeWindow, uint32_t inWidth, uint32_t inHeight); + ~SwapChainSurface() override; + + SurfaceTarget GetRenderTarget() const override; + Common::UVec2 GetSize() const override; + RHI::PixelFormat GetFormat() const override; + void Resize(uint32_t inWidth, uint32_t inHeight) override; + void AcquireBackTexture(); + void Present(); + RHI::Device& GetDevice() const; + void WaitRenderingIdle() const; + + private: + static constexpr uint8_t swapChainTextureNum = 2; + + void ReleaseSwapChainResources(); + void RecreateSwapChain(uint32_t inWidth, uint32_t inHeight); + RHI::Semaphore* GetRenderFinishedSemaphore() const; + + RHI::Device& device; + Common::UniquePtr surface; + Common::UniquePtr swapChain; + std::vector swapChainTextures; + std::vector> swapChainTextureViews; + std::vector swapChainTextureStates; + Common::UniquePtr imageReadySemaphore; + std::vector> renderFinishedSemaphores; + RHI::PixelFormat swapChainFormat; + uint32_t currentBackTextureIndex; + uint32_t width; + uint32_t height; + }; +} diff --git a/Engine/Source/Runtime/Src/Canvas.cpp b/Engine/Source/Render/Src/Canvas.cpp similarity index 72% rename from Engine/Source/Runtime/Src/Canvas.cpp rename to Engine/Source/Render/Src/Canvas.cpp index 6c35594eb..b43c4cc1c 100644 --- a/Engine/Source/Runtime/Src/Canvas.cpp +++ b/Engine/Source/Render/Src/Canvas.cpp @@ -4,16 +4,16 @@ #include -#include +#include -namespace Runtime::Internal { +namespace Render::CanvasResources::Internal { static uint32_t ClampExtent(uint32_t inValue) { return std::max(1u, inValue); } } -namespace Runtime { +namespace Render { CanvasDesc::CanvasDesc() : width(1) , height(1) @@ -24,8 +24,8 @@ namespace Runtime { Canvas::Canvas(RHI::Device& inDevice, const CanvasDesc& inDesc) : device(inDevice) - , width(Internal::ClampExtent(inDesc.width)) - , height(Internal::ClampExtent(inDesc.height)) + , width(CanvasResources::Internal::ClampExtent(inDesc.width)) + , height(CanvasResources::Internal::ClampExtent(inDesc.height)) , format(inDesc.format) , debugName(inDesc.debugName) { @@ -34,25 +34,35 @@ namespace Runtime { Canvas::~Canvas() = default; - RHI::Texture* Canvas::GetTexture() const + SurfaceTarget Canvas::GetRenderTarget() const { - return texture.Get(); + return { + .texture = texture.Get(), + .renderTargetView = renderTargetView.Get(), + .beforeRenderState = RHI::TextureState::shaderReadOnly, + .afterRenderState = RHI::TextureState::shaderReadOnly + }; } - RHI::TextureView* Canvas::GetRenderTargetView() const + RHI::TextureView* Canvas::GetTextureView() const { - return renderTargetView.Get(); + return textureView.Get(); } - RHI::TextureView* Canvas::GetTextureView() const + Common::UVec2 Canvas::GetSize() const { - return textureView.Get(); + return { width, height }; + } + + RHI::PixelFormat Canvas::GetFormat() const + { + return format; } void Canvas::Resize(uint32_t inWidth, uint32_t inHeight) { - const uint32_t newWidth = Internal::ClampExtent(inWidth); - const uint32_t newHeight = Internal::ClampExtent(inHeight); + const uint32_t newWidth = CanvasResources::Internal::ClampExtent(inWidth); + const uint32_t newHeight = CanvasResources::Internal::ClampExtent(inHeight); if (newWidth == width && newHeight == height) { return; } diff --git a/Engine/Source/Runtime/Src/RenderSurface.cpp b/Engine/Source/Render/Src/RenderSurface.cpp similarity index 71% rename from Engine/Source/Runtime/Src/RenderSurface.cpp rename to Engine/Source/Render/Src/RenderSurface.cpp index 871d039f9..82a8287f5 100644 --- a/Engine/Source/Runtime/Src/RenderSurface.cpp +++ b/Engine/Source/Render/Src/RenderSurface.cpp @@ -2,9 +2,9 @@ // Created by johnk on 2026/7/8. // -#include +#include -namespace Runtime { +namespace Render { RenderSurface::RenderSurface() = default; RenderSurface::~RenderSurface() = default; diff --git a/Engine/Source/Render/Src/SwapChainSurface.cpp b/Engine/Source/Render/Src/SwapChainSurface.cpp new file mode 100644 index 000000000..2f54a3433 --- /dev/null +++ b/Engine/Source/Render/Src/SwapChainSurface.cpp @@ -0,0 +1,166 @@ +// +// Created by johnk on 2026/7/8. +// + +#include +#include +#include + +#include + +#ifdef CreateSemaphore +#undef CreateSemaphore +#endif + +namespace Render::WindowPresentation::Internal { + static uint32_t ClampExtent(uint32_t inValue) + { + return std::max(1u, inValue); + } +} + +namespace Render { + SwapChainSurface::SwapChainSurface(RHI::Device& inDevice, void* inNativeWindow, uint32_t inWidth, uint32_t inHeight) + : device(inDevice) + , imageReadySemaphore((device.CreateSemaphore)()) + , swapChainFormat(RHI::PixelFormat::max) + , currentBackTextureIndex(0) + , width(0) + , height(0) + { + surface = device.CreateSurface(RHI::SurfaceCreateInfo(inNativeWindow)); + RecreateSwapChain(WindowPresentation::Internal::ClampExtent(inWidth), WindowPresentation::Internal::ClampExtent(inHeight)); + } + + SwapChainSurface::~SwapChainSurface() + { + WaitRenderingIdle(); + ReleaseSwapChainResources(); + } + + SurfaceTarget SwapChainSurface::GetRenderTarget() const + { + Assert(currentBackTextureIndex < swapChainTextures.size()); + return { + .texture = swapChainTextures[currentBackTextureIndex], + .renderTargetView = swapChainTextureViews[currentBackTextureIndex].Get(), + .beforeRenderState = swapChainTextureStates[currentBackTextureIndex], + .afterRenderState = RHI::TextureState::present, + .waitSemaphore = imageReadySemaphore.Get(), + .signalSemaphore = GetRenderFinishedSemaphore() + }; + } + + void SwapChainSurface::AcquireBackTexture() + { + currentBackTextureIndex = swapChain->AcquireBackTexture(imageReadySemaphore.Get()); + Assert(currentBackTextureIndex < swapChainTextures.size()); + } + + void SwapChainSurface::Resize(uint32_t inWidth, uint32_t inHeight) + { + const auto newWidth = WindowPresentation::Internal::ClampExtent(inWidth); + const auto newHeight = WindowPresentation::Internal::ClampExtent(inHeight); + if (width == newWidth && height == newHeight) { + return; + } + WaitRenderingIdle(); + RecreateSwapChain(newWidth, newHeight); + } + + void SwapChainSurface::Present() + { + swapChain->Present(GetRenderFinishedSemaphore()); + swapChainTextureStates[currentBackTextureIndex] = RHI::TextureState::present; + } + + RHI::Device& SwapChainSurface::GetDevice() const + { + return device; + } + + Common::UVec2 SwapChainSurface::GetSize() const + { + return { width, height }; + } + + RHI::PixelFormat SwapChainSurface::GetFormat() const + { + return swapChainFormat; + } + + RHI::Semaphore* SwapChainSurface::GetRenderFinishedSemaphore() const + { + Assert(currentBackTextureIndex < renderFinishedSemaphores.size()); + return renderFinishedSemaphores[currentBackTextureIndex].Get(); + } + + void SwapChainSurface::WaitRenderingIdle() const + { + const auto fence = device.CreateFence(false); + device.GetQueue(RHI::QueueType::graphics, 0)->Flush(fence.Get()); + fence->Wait(); + } + + void SwapChainSurface::ReleaseSwapChainResources() + { + swapChainTextureViews.clear(); + swapChain.Reset(); + swapChainTextures.clear(); + swapChainTextureStates.clear(); + renderFinishedSemaphores.clear(); + currentBackTextureIndex = 0; + } + + void SwapChainSurface::RecreateSwapChain(uint32_t inWidth, uint32_t inHeight) + { + static std::vector formatQualifiers = { + RHI::PixelFormat::rgba8Unorm, + RHI::PixelFormat::bgra8Unorm + }; + + ReleaseSwapChainResources(); + + std::optional pixelFormat = {}; + for (const auto format : formatQualifiers) { + if (device.CheckSwapChainFormatSupport(surface.Get(), format, RHI::ColorSpace::srgbNonLinear)) { + pixelFormat = format; + break; + } + } + Assert(pixelFormat.has_value()); + swapChainFormat = pixelFormat.value(); + width = inWidth; + height = inHeight; + + swapChain = device.CreateSwapChain( + RHI::SwapChainCreateInfo() + .SetPresentQueue(device.GetQueue(RHI::QueueType::graphics, 0)) + .SetSurface(surface.Get()) + .SetTextureNum(swapChainTextureNum) + .SetFormat(swapChainFormat) + .SetWidth(width) + .SetHeight(height) + .SetPresentMode(RHI::PresentMode::immediately)); + + const auto actualTextureNum = swapChain->GetTextureNum(); + swapChainTextures.resize(actualTextureNum); + swapChainTextureViews.resize(actualTextureNum); + swapChainTextureStates.resize(actualTextureNum); + renderFinishedSemaphores.resize(actualTextureNum); + currentBackTextureIndex = 0; + + for (uint8_t i = 0; i < actualTextureNum; i++) { + swapChainTextures[i] = swapChain->GetTexture(i); + swapChainTextureStates[i] = swapChainTextures[i]->GetCreateInfo().initialState; + swapChainTextureViews[i] = swapChainTextures[i]->CreateTextureView( + RHI::TextureViewCreateInfo() + .SetDimension(RHI::TextureViewDimension::tv2D) + .SetMipLevels(0, 1) + .SetArrayLayers(0, 1) + .SetAspect(RHI::TextureAspect::color) + .SetType(RHI::TextureViewType::colorAttachment)); + renderFinishedSemaphores[i] = (device.CreateSemaphore)(); + } + } +} diff --git a/Engine/Source/Runtime/Include/Runtime/Client.h b/Engine/Source/Runtime/Include/Runtime/Client.h index 318f6cd4e..74d812353 100644 --- a/Engine/Source/Runtime/Include/Runtime/Client.h +++ b/Engine/Source/Runtime/Include/Runtime/Client.h @@ -5,7 +5,6 @@ #pragma once #include -#include namespace Runtime { class World; @@ -15,7 +14,6 @@ namespace Runtime { virtual ~Client(); virtual World& GetWorld() = 0; - virtual RenderSurface* GetRenderSurface() = 0; protected: Client(); diff --git a/Engine/Source/Runtime/Include/Runtime/Component/Camera.h b/Engine/Source/Runtime/Include/Runtime/Component/Camera.h index f7e9cd8d6..5895d7c83 100644 --- a/Engine/Source/Runtime/Include/Runtime/Component/Camera.h +++ b/Engine/Source/Runtime/Include/Runtime/Component/Camera.h @@ -6,10 +6,8 @@ #include -#include #include #include -#include namespace Runtime { struct RUNTIME_API EClass(comp, transient) Camera final { @@ -22,9 +20,6 @@ namespace Runtime { EProperty() std::optional farPlane; // only need when perspective EProperty() std::optional fov; - // cross-frame rendering history of the view rendered through this camera, allocated by RenderSystem on first - // use and released on the render thread with the component - RenderThreadPtr viewState; }; // TODO scene capture diff --git a/Engine/Source/Runtime/Include/Runtime/ECS.h b/Engine/Source/Runtime/Include/Runtime/ECS.h index 5fc89cec4..cec64dcae 100644 --- a/Engine/Source/Runtime/Include/Runtime/ECS.h +++ b/Engine/Source/Runtime/Include/Runtime/ECS.h @@ -30,7 +30,6 @@ namespace Runtime { using SystemClass = const Mirror::Class*; class ECRegistry; - class Client; struct SystemSetupContext; template @@ -820,7 +819,6 @@ namespace Runtime { SystemSetupContext(); PlayType playType; - Client* client; }; class SystemGraphExecutor { diff --git a/Engine/Source/Runtime/Include/Runtime/Engine.h b/Engine/Source/Runtime/Include/Runtime/Engine.h index 790a7144a..e84dbd1dc 100644 --- a/Engine/Source/Runtime/Include/Runtime/Engine.h +++ b/Engine/Source/Runtime/Include/Runtime/Engine.h @@ -13,6 +13,7 @@ namespace Runtime { class World; + class Window; struct RUNTIME_API EngineInitParams { EngineInitParams(); @@ -32,6 +33,8 @@ namespace Runtime { void MountWorld(World* inWorld); void UnmountWorld(World* inWorld); + void MountWindow(Window* inWindow); + void UnmountWindow(Window* inWindow); Render::RenderModule& GetRenderModule() const; void Tick(float inDeltaTimeSeconds); @@ -44,6 +47,7 @@ namespace Runtime { void LoadConfigs() const; std::unordered_set worlds; + std::unordered_set windows; Render::RenderModule* renderModule; std::future lastFrameRenderThreadFence; std::future last2FrameRenderThreadFence; diff --git a/Engine/Source/Runtime/Include/Runtime/RenderSurface.h b/Engine/Source/Runtime/Include/Runtime/RenderSurface.h deleted file mode 100644 index ebf4365a8..000000000 --- a/Engine/Source/Runtime/Include/Runtime/RenderSurface.h +++ /dev/null @@ -1,28 +0,0 @@ -// -// Created by johnk on 2026/7/8. -// - -#pragma once - -#include - -#include -#include -#include - -namespace Runtime { - class RUNTIME_API RenderSurface { - public: - virtual ~RenderSurface(); - - NonCopyable(RenderSurface) - NonMovable(RenderSurface) - - virtual RHI::Texture* GetTexture() const = 0; - virtual RHI::TextureView* GetRenderTargetView() const = 0; - virtual void Resize(uint32_t inWidth, uint32_t inHeight) = 0; - - protected: - RenderSurface(); - }; -} diff --git a/Engine/Source/Runtime/Include/Runtime/System/Render.h b/Engine/Source/Runtime/Include/Runtime/System/Render.h deleted file mode 100644 index 74933ed32..000000000 --- a/Engine/Source/Runtime/Include/Runtime/System/Render.h +++ /dev/null @@ -1,37 +0,0 @@ -// -// Created by johnk on 2025/3/4. -// - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace Runtime { - class RUNTIME_API EClass() RenderSystem final : public System { - EPolyDerivedClassBody(RenderSystem) - - public: - explicit RenderSystem(ECRegistry& inRegistry, const SystemSetupContext& inContext); - ~RenderSystem() override; - - NonCopyable(RenderSystem) - NonMovable(RenderSystem) - - void Tick(float inDeltaTimeSeconds) override; - - private: - static Common::URect GetPlayerViewport(uint32_t inWidth, uint32_t inHeight, uint8_t inPlayerNum, uint8_t inPlayerIndex); - Render::View BuildViewForCamera(Entity inEntity) const; - std::vector BuildViews() const; - - Render::RenderModule& renderModule; - Client* client; - RHI::Fence* lastFrameFence; - }; -} diff --git a/Engine/Source/Runtime/Include/Runtime/Viewport.h b/Engine/Source/Runtime/Include/Runtime/Viewport.h new file mode 100644 index 000000000..ca755c30d --- /dev/null +++ b/Engine/Source/Runtime/Include/Runtime/Viewport.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Runtime { + class RUNTIME_API Viewport { + public: + virtual ~Viewport(); + + NonCopyable(Viewport) + NonMovable(Viewport) + + virtual void Render(float inDeltaTimeSeconds); + void WaitIdle() const; + + protected: + Viewport(); + + virtual Client& GetClient() = 0; + virtual Render::RenderSurface& GetRenderSurface() = 0; + virtual std::vector BuildViews(ECRegistry& inRegistry, Common::UVec2 inSize) = 0; + Render::View BuildViewForCamera(ECRegistry& inRegistry, Entity inEntity, const Common::URect& inRect); + + private: + Render::RenderModule& renderModule; + Common::UniquePtr frameFence; + std::unordered_map> viewStates; + }; +} diff --git a/Engine/Source/Runtime/Include/Runtime/Window.h b/Engine/Source/Runtime/Include/Runtime/Window.h index a89b1733c..d88b2ca36 100644 --- a/Engine/Source/Runtime/Include/Runtime/Window.h +++ b/Engine/Source/Runtime/Include/Runtime/Window.h @@ -1,55 +1,23 @@ -// -// Created by johnk on 2026/7/8. -// - #pragma once -#include - -#include -#include -#include +#include +#include namespace Runtime { - class RUNTIME_API Window : public RenderSurface { + class RUNTIME_API Window { public: - ~Window() override; + virtual ~Window(); - RHI::Texture* GetTexture() const override; - RHI::TextureView* GetRenderTargetView() const override; - void Resize(uint32_t inWidth, uint32_t inHeight) override; - void AcquireBackTexture(); - void Present(); - RHI::Device& GetDevice() const; - RHI::PixelFormat GetSwapChainFormat() const; - RHI::TextureState GetCurrentBackTextureState() const; - RHI::Semaphore* GetImageReadySemaphore() const; - RHI::Semaphore* GetRenderFinishedSemaphore() const; - void WaitRenderingIdle() const; - - protected: - explicit Window(RHI::Device& inDevice); + NonCopyable(Window) + NonMovable(Window) - void InitializeSurface(Common::UniquePtr inSurface, uint32_t inWidth, uint32_t inHeight); - void DestroySurface(); + virtual bool ShouldClose() const = 0; + virtual void RequestClose() const = 0; + virtual void Tick(float inDeltaSeconds) = 0; + virtual void Render(float inDeltaSeconds) = 0; + virtual void WaitIdle() const = 0; - private: - static constexpr uint8_t swapChainTextureNum = 2; - - void ReleaseSwapChainResources(); - void RecreateSwapChain(uint32_t inWidth, uint32_t inHeight); - - RHI::Device& device; - Common::UniquePtr surface; - Common::UniquePtr swapChain; - std::vector swapChainTextures; - std::vector> swapChainTextureViews; - std::vector swapChainTextureStates; - Common::UniquePtr imageReadySemaphore; - std::vector> renderFinishedSemaphores; - RHI::PixelFormat swapChainFormat; - uint32_t currentBackTextureIndex; - uint32_t width; - uint32_t height; + protected: + Window(); }; } diff --git a/Engine/Source/Runtime/Include/Runtime/World.h b/Engine/Source/Runtime/Include/Runtime/World.h index b6c9a60ec..14f59838c 100644 --- a/Engine/Source/Runtime/Include/Runtime/World.h +++ b/Engine/Source/Runtime/Include/Runtime/World.h @@ -10,10 +10,11 @@ #include #include -#include #include namespace Runtime { + class Viewport; + enum class PlayStatus : uint8_t { stopped, playing, @@ -27,7 +28,7 @@ namespace Runtime { NonMovable(World) ~World(); - World(std::string inName, Client* inClient, PlayType inPlayType); + World(std::string inName, PlayType inPlayType); void SetSystemGraph(const SystemGraph& inSystemGraph); Runtime::PlayStatus PlayStatus() const; bool Stopped() const; @@ -46,6 +47,7 @@ namespace Runtime { private: friend class Engine; + friend class Viewport; void Tick(float inDeltaTimeSeconds); diff --git a/Engine/Source/Runtime/Src/Component/Camera.cpp b/Engine/Source/Runtime/Src/Component/Camera.cpp index 72005169d..b5165f70a 100644 --- a/Engine/Source/Runtime/Src/Component/Camera.cpp +++ b/Engine/Source/Runtime/Src/Component/Camera.cpp @@ -9,7 +9,6 @@ namespace Runtime { : perspective(true) , nearPlane(0.1f) , fov(90.0f) - , viewState(nullptr) { } } diff --git a/Engine/Source/Runtime/Src/ECS.cpp b/Engine/Source/Runtime/Src/ECS.cpp index 42d476192..dbeca9e4e 100644 --- a/Engine/Source/Runtime/Src/ECS.cpp +++ b/Engine/Source/Runtime/Src/ECS.cpp @@ -1791,7 +1791,6 @@ namespace Runtime { SystemSetupContext::SystemSetupContext() : playType(PlayType::max) - , client(nullptr) { } diff --git a/Engine/Source/Runtime/Src/Engine.cpp b/Engine/Source/Runtime/Src/Engine.cpp index ef6a51da3..299bc84b3 100644 --- a/Engine/Source/Runtime/Src/Engine.cpp +++ b/Engine/Source/Runtime/Src/Engine.cpp @@ -14,6 +14,7 @@ #include #include #include +#include namespace Runtime { EngineInitParams::EngineInitParams() @@ -60,6 +61,16 @@ namespace Runtime { worlds.erase(inWorld); } + void Engine::MountWindow(Window* inWindow) + { + windows.emplace(inWindow); + } + + void Engine::UnmountWindow(Window* inWindow) + { + windows.erase(inWindow); + } + Render::RenderModule& Engine::GetRenderModule() const { return *renderModule; @@ -81,6 +92,10 @@ namespace Runtime { renderModule->BeginFrame(); }); + for (auto* window : windows) { + window->Tick(inDeltaTimeSeconds); + } + for (auto* world : worlds) { if (!world->ShouldTick()) { continue; @@ -89,8 +104,13 @@ namespace Runtime { } GameThread::Get().Flush(); + + for (auto* window : windows) { + window->Render(inDeltaTimeSeconds); + } + last2FrameRenderThreadFence = std::move(lastFrameRenderThreadFence); - lastFrameRenderThreadFence = renderThread.EmplaceTask([]() -> void {}); + lastFrameRenderThreadFence = renderModule->GetRenderThread().EmplaceTask([]() -> void {}); } void Engine::AttachLogFile() const // NOLINT diff --git a/Engine/Source/Runtime/Src/System/Render.cpp b/Engine/Source/Runtime/Src/System/Render.cpp deleted file mode 100644 index 0ea566070..000000000 --- a/Engine/Source/Runtime/Src/System/Render.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// -// Created by johnk on 2025/3/4. -// - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Runtime { - RenderSystem::RenderSystem(ECRegistry& inRegistry, const SystemSetupContext& inContext) - : System(inRegistry, inContext) - , renderModule(EngineHolder::Get().GetRenderModule()) - , client(inContext.client) - , lastFrameFence(renderModule.GetDevice()->CreateFence(true).Release()) - { - } - - RenderSystem::~RenderSystem() // NOLINT - { - renderModule.GetRenderThread().EmplaceTask([fence = lastFrameFence]() -> void { - fence->Wait(); - delete fence; - }); - } - - void RenderSystem::Tick(float inDeltaTimeSeconds) - { - auto* target = client != nullptr ? client->GetRenderSurface() : nullptr; - if (target == nullptr) { - return; - } - auto* window = dynamic_cast(target); - - auto* texture = target->GetTexture(); - Assert(texture != nullptr); - const auto& textureDesc = texture->GetCreateInfo(); - - renderModule.GetRenderThread().EmplaceTask( - [ - fence = lastFrameFence, - views = BuildViews(), - scene = registry.GGet().scene.Get(), - surfaceExtent = Common::UVec2(textureDesc.width, textureDesc.height), - target, - window, - renderModule = &renderModule, - inDeltaTimeSeconds - ]() -> void { - fence->Reset(); - if (window != nullptr) { - window->AcquireBackTexture(); - } - - Render::StandardRenderer::Params rendererParams; - rendererParams.device = renderModule->GetDevice(); - rendererParams.scene = scene; - rendererParams.surface = target->GetTexture(); - rendererParams.surfaceExtent = surfaceExtent; - rendererParams.surfaceBeforeRenderState = window != nullptr - ? window->GetCurrentBackTextureState() - : RHI::TextureState::shaderReadOnly; - rendererParams.surfaceAfterRenderState = window != nullptr - ? RHI::TextureState::present - : RHI::TextureState::shaderReadOnly; - rendererParams.views = views; - rendererParams.waitSemaphore = window != nullptr ? window->GetImageReadySemaphore() : nullptr; - rendererParams.signalSemaphore = window != nullptr ? window->GetRenderFinishedSemaphore() : nullptr; - rendererParams.signalFence = fence; - - auto renderer = renderModule->CreateStandardRenderer(rendererParams); - renderer->Render(inDeltaTimeSeconds); - if (window != nullptr) { - window->Present(); - } - // Renderer-owned command buffers and transient resources must outlive the submitted GPU work. - fence->Wait(); - }); - } - - Common::URect RenderSystem::GetPlayerViewport(uint32_t inWidth, uint32_t inHeight, uint8_t inPlayerNum, uint8_t inPlayerIndex) - { - Assert(inPlayerNum > 0 && inPlayerIndex < inPlayerNum); - if (inPlayerNum == 1) { - return { 0, 0, inWidth, inHeight }; - } - if (inPlayerNum == 2) { - const auto widthPerPlayer = inWidth / 2; - return { widthPerPlayer * inPlayerIndex, 0, widthPerPlayer, inHeight }; - } - if (inPlayerNum <= 4) { - const auto widthPerPlayer = inWidth / 2; - const auto heightPerPlayer = inHeight / 2; - return { widthPerPlayer * (inPlayerIndex % 2), heightPerPlayer * (inPlayerIndex / 2), widthPerPlayer, heightPerPlayer }; - } - Unimplement(); - return {}; - } - - Render::View RenderSystem::BuildViewForCamera(Entity inEntity) const - { - auto& camera = registry.Get(inEntity); - const auto& worldTransform = registry.Get(inEntity); - auto* target = client->GetRenderSurface(); - Assert(target != nullptr && target->GetTexture() != nullptr); - const auto& textureDesc = target->GetTexture()->GetCreateInfo(); - const auto width = textureDesc.width; - const auto height = textureDesc.height; - - if (camera.viewState == nullptr) { - camera.viewState = renderModule.NewViewState(); - } - - // a player camera renders into its split-screen sub-viewport, any other camera (e.g. the editor camera) - // covers the whole render surface - Common::URect viewportRect = { 0, 0, width, height }; - if (registry.Has(inEntity)) { - const auto& playersInfo = registry.GGet(); - viewportRect = GetPlayerViewport(width, height, static_cast(playersInfo.players.size()), registry.Get(inEntity).localPlayerIndex); - } - - Render::View view = renderModule.CreateView(); - view.state = camera.viewState.Get(); - view.data.viewport = viewportRect; - view.data.viewMatrix = Common::FViewTransform(worldTransform.localToWorld).GetViewMatrix(); - view.data.origin = worldTransform.localToWorld.translation; - if (camera.perspective) { - const Common::FReversedZPerspectiveProjection projection(camera.fov.value(), static_cast(width), static_cast(height), camera.nearPlane, camera.farPlane); - view.data.projectionMatrix = projection.GetProjectionMatrix(); - } else { - const Common::FReversedZOrthoProjection projection(static_cast(width), static_cast(height), camera.nearPlane, camera.farPlane); - view.data.projectionMatrix = projection.GetProjectionMatrix(); - } - return view; - } - - std::vector RenderSystem::BuildViews() const - { - const auto cameras = registry.View().All(); - - std::vector result; - result.reserve(cameras.size()); - for (const auto& camera : cameras) { - result.emplace_back(BuildViewForCamera(std::get<0>(camera))); - } - return result; - } -} diff --git a/Engine/Source/Runtime/Src/SystemGraphPresets.cpp b/Engine/Source/Runtime/Src/SystemGraphPresets.cpp index 9d5c1c522..581285573 100644 --- a/Engine/Source/Runtime/Src/SystemGraphPresets.cpp +++ b/Engine/Source/Runtime/Src/SystemGraphPresets.cpp @@ -3,7 +3,6 @@ // #include -#include #include #include #include @@ -20,9 +19,8 @@ namespace Runtime { auto& transformGroup = systemGraph.AddGroup("Transform", SystemExecuteStrategy::sequential); transformGroup.EmplaceSystem(); - auto& sceneRenderingGroup = systemGraph.AddGroup("SceneRendering", SystemExecuteStrategy::sequential); - sceneRenderingGroup.EmplaceSystem(); - sceneRenderingGroup.EmplaceSystem(); + auto& sceneGroup = systemGraph.AddGroup("Scene", SystemExecuteStrategy::sequential); + sceneGroup.EmplaceSystem(); return systemGraph; }(); diff --git a/Engine/Source/Runtime/Src/Viewport.cpp b/Engine/Source/Runtime/Src/Viewport.cpp new file mode 100644 index 000000000..783a42dca --- /dev/null +++ b/Engine/Source/Runtime/Src/Viewport.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace Runtime { + Viewport::Viewport() + : renderModule(EngineHolder::Get().GetRenderModule()) + , frameFence(renderModule.GetDevice()->CreateFence(true)) + { + } + + Viewport::~Viewport() + { + WaitIdle(); + } + + void Viewport::Render(float inDeltaTimeSeconds) + { + auto& world = GetClient().GetWorld(); + auto& surface = GetRenderSurface(); + if (world.Stopped()) { + return; + } + auto& registry = world.ecRegistry; + std::erase_if(viewStates, [&](const auto& inEntry) -> bool { + return !registry.Valid(inEntry.first) || !registry.Has(inEntry.first); + }); + renderModule.GetRenderThread().EmplaceTask( + [ + fence = frameFence.Get(), + views = BuildViews(registry, surface.GetSize()), + scene = registry.GGet().scene.Get(), + surface = &surface, + renderModule = &renderModule, + inDeltaTimeSeconds + ]() -> void { + fence->Reset(); + const auto target = surface->GetRenderTarget(); + Render::StandardRenderer::Params params; + params.device = renderModule->GetDevice(); + params.scene = scene; + params.surface = target.texture; + params.surfaceExtent = surface->GetSize(); + params.surfaceBeforeRenderState = target.beforeRenderState; + params.surfaceAfterRenderState = target.afterRenderState; + params.views = views; + params.waitSemaphore = target.waitSemaphore; + params.signalSemaphore = target.signalSemaphore; + params.signalFence = fence; + + auto renderer = renderModule->CreateStandardRenderer(params); + renderer->Render(inDeltaTimeSeconds); + // Renderer-owned command buffers and transient resources must outlive the submitted GPU work. + fence->Wait(); + }); + } + + void Viewport::WaitIdle() const + { + renderModule.GetRenderThread().Flush(); + const auto fence = renderModule.GetDevice()->CreateFence(false); + renderModule.GetDevice()->GetQueue(RHI::QueueType::graphics, 0)->Flush(fence.Get()); + fence->Wait(); + } + + Render::View Viewport::BuildViewForCamera(ECRegistry& inRegistry, Entity inEntity, const Common::URect& inRect) + { + const auto& cameraComponent = inRegistry.Get(inEntity); + const auto& transform = inRegistry.Get(inEntity).localToWorld; + auto& state = viewStates[inEntity]; + if (state == nullptr) { + state = renderModule.NewViewState(); + } + + Render::View view = renderModule.CreateView(); + view.state = state.Get(); + view.data.viewport = inRect; + view.data.viewMatrix = Common::FViewTransform(transform).GetViewMatrix(); + view.data.origin = transform.translation; + if (cameraComponent.perspective) { + const Common::FReversedZPerspectiveProjection projection( + cameraComponent.fov.value(), static_cast(inRect.ExtentX()), static_cast(inRect.ExtentY()), + cameraComponent.nearPlane, cameraComponent.farPlane); + view.data.projectionMatrix = projection.GetProjectionMatrix(); + } else { + const Common::FReversedZOrthoProjection projection( + static_cast(inRect.ExtentX()), static_cast(inRect.ExtentY()), cameraComponent.nearPlane, cameraComponent.farPlane); + view.data.projectionMatrix = projection.GetProjectionMatrix(); + } + return view; + } + +} diff --git a/Engine/Source/Runtime/Src/Window.cpp b/Engine/Source/Runtime/Src/Window.cpp index 58f90b23a..266e02e69 100644 --- a/Engine/Source/Runtime/Src/Window.cpp +++ b/Engine/Source/Runtime/Src/Window.cpp @@ -1,167 +1,14 @@ -// -// Created by johnk on 2026/7/8. -// - -#include -#include -#include - #include - -namespace Runtime::Internal { - static uint32_t ClampExtent(uint32_t inValue) - { - return std::max(1u, inValue); - } -} +#include namespace Runtime { - Window::Window(RHI::Device& inDevice) - : device(inDevice) - , imageReadySemaphore((device.CreateSemaphore)()) - , swapChainFormat(RHI::PixelFormat::max) - , currentBackTextureIndex(0) - , width(1) - , height(1) - { - } - - Window::~Window() = default; - - RHI::Texture* Window::GetTexture() const - { - Assert(currentBackTextureIndex < swapChainTextures.size()); - return swapChainTextures[currentBackTextureIndex]; - } - - RHI::TextureView* Window::GetRenderTargetView() const - { - Assert(currentBackTextureIndex < swapChainTextureViews.size()); - return swapChainTextureViews[currentBackTextureIndex].Get(); - } - - void Window::AcquireBackTexture() - { - currentBackTextureIndex = swapChain->AcquireBackTexture(imageReadySemaphore.Get()); - Assert(currentBackTextureIndex < swapChainTextures.size()); - } - - void Window::Resize(uint32_t inWidth, uint32_t inHeight) - { - RecreateSwapChain(Internal::ClampExtent(inWidth), Internal::ClampExtent(inHeight)); - } - - void Window::Present() - { - swapChain->Present(GetRenderFinishedSemaphore()); - swapChainTextureStates[currentBackTextureIndex] = RHI::TextureState::present; - } - - RHI::Device& Window::GetDevice() const - { - return device; - } - - RHI::PixelFormat Window::GetSwapChainFormat() const - { - return swapChainFormat; - } - - RHI::TextureState Window::GetCurrentBackTextureState() const - { - Assert(currentBackTextureIndex < swapChainTextureStates.size()); - return swapChainTextureStates[currentBackTextureIndex]; - } - - RHI::Semaphore* Window::GetImageReadySemaphore() const + Window::Window() { - return imageReadySemaphore.Get(); + EngineHolder::Get().MountWindow(this); } - RHI::Semaphore* Window::GetRenderFinishedSemaphore() const + Window::~Window() { - Assert(currentBackTextureIndex < renderFinishedSemaphores.size()); - return renderFinishedSemaphores[currentBackTextureIndex].Get(); - } - - void Window::WaitRenderingIdle() const - { - const auto fence = device.CreateFence(false); - device.GetQueue(RHI::QueueType::graphics, 0)->Flush(fence.Get()); - fence->Wait(); - } - - void Window::InitializeSurface(Common::UniquePtr inSurface, uint32_t inWidth, uint32_t inHeight) - { - surface = std::move(inSurface); - RecreateSwapChain(Internal::ClampExtent(inWidth), Internal::ClampExtent(inHeight)); - } - - void Window::DestroySurface() - { - ReleaseSwapChainResources(); - surface.Reset(); - } - - void Window::ReleaseSwapChainResources() - { - swapChainTextureViews.clear(); - swapChain.Reset(); - swapChainTextures.clear(); - swapChainTextureStates.clear(); - renderFinishedSemaphores.clear(); - currentBackTextureIndex = 0; - } - - void Window::RecreateSwapChain(uint32_t inWidth, uint32_t inHeight) - { - static std::vector formatQualifiers = { - RHI::PixelFormat::rgba8Unorm, - RHI::PixelFormat::bgra8Unorm - }; - - ReleaseSwapChainResources(); - - std::optional pixelFormat = {}; - for (const auto format : formatQualifiers) { - if (device.CheckSwapChainFormatSupport(surface.Get(), format, RHI::ColorSpace::srgbNonLinear)) { - pixelFormat = format; - break; - } - } - Assert(pixelFormat.has_value()); - swapChainFormat = pixelFormat.value(); - width = inWidth; - height = inHeight; - - swapChain = device.CreateSwapChain( - RHI::SwapChainCreateInfo() - .SetPresentQueue(device.GetQueue(RHI::QueueType::graphics, 0)) - .SetSurface(surface.Get()) - .SetTextureNum(swapChainTextureNum) - .SetFormat(swapChainFormat) - .SetWidth(width) - .SetHeight(height) - .SetPresentMode(RHI::PresentMode::immediately)); - - const auto actualTextureNum = swapChain->GetTextureNum(); - swapChainTextures.resize(actualTextureNum); - swapChainTextureViews.resize(actualTextureNum); - swapChainTextureStates.resize(actualTextureNum); - renderFinishedSemaphores.resize(actualTextureNum); - currentBackTextureIndex = 0; - - for (uint8_t i = 0; i < actualTextureNum; i++) { - swapChainTextures[i] = swapChain->GetTexture(i); - swapChainTextureStates[i] = swapChainTextures[i]->GetCreateInfo().initialState; - swapChainTextureViews[i] = swapChainTextures[i]->CreateTextureView( - RHI::TextureViewCreateInfo() - .SetDimension(RHI::TextureViewDimension::tv2D) - .SetMipLevels(0, 1) - .SetArrayLayers(0, 1) - .SetAspect(RHI::TextureAspect::color) - .SetType(RHI::TextureViewType::colorAttachment)); - renderFinishedSemaphores[i] = (device.CreateSemaphore)(); - } + EngineHolder::Get().UnmountWindow(this); } } diff --git a/Engine/Source/Runtime/Src/World.cpp b/Engine/Source/Runtime/Src/World.cpp index 4cc807ee0..52e159bce 100644 --- a/Engine/Source/Runtime/Src/World.cpp +++ b/Engine/Source/Runtime/Src/World.cpp @@ -8,7 +8,7 @@ #include namespace Runtime { - World::World(std::string inName, Client* inClient, PlayType inPlayType) + World::World(std::string inName, PlayType inPlayType) : name(std::move(inName)) , playStatus(PlayStatus::stopped) , systemSetupContext() @@ -16,7 +16,6 @@ namespace Runtime { EngineHolder::Get().MountWorld(this); systemSetupContext.playType = inPlayType; - systemSetupContext.client = inClient; } World::~World() diff --git a/Engine/Source/Runtime/Test/WorldTest.cpp b/Engine/Source/Runtime/Test/WorldTest.cpp index 0d07a5bea..5843c0d27 100644 --- a/Engine/Source/Runtime/Test/WorldTest.cpp +++ b/Engine/Source/Runtime/Test/WorldTest.cpp @@ -105,7 +105,7 @@ TEST_F(WorldTest, BasicTest) auto& mainGroup = systemGraph.AddGroup("MainGroup", SystemExecuteStrategy::sequential); mainGroup.EmplaceSystemDyn(&BasicTest_MotionSystem::GetStaticClass()); - World world("TestWorld", nullptr, PlayType::game); + World world("TestWorld", PlayType::game); world.SetSystemGraph(systemGraph); world.Play(); for (auto i = 0; i < 5; i++) { @@ -117,7 +117,7 @@ TEST_F(WorldTest, BasicTest) #if BUILD_EDITOR TEST_F(WorldTest, EditorAccessMutatesEditorWorldImmediately) { - World world("EditorWorld", nullptr, PlayType::editor); + World world("EditorWorld", PlayType::editor); Entity editedEntity = entityNull; world.EditorAccess([&](ECRegistry& registry) -> void { @@ -189,7 +189,7 @@ TEST_F(WorldTest, ConcurrentTest) auto& verifyGroup = systemGraph.AddGroup("VerifyGroup", SystemExecuteStrategy::sequential); verifyGroup.EmplaceSystem(); - World world("TestWorld", nullptr, PlayType::game); + World world("TestWorld", PlayType::game); world.SetSystemGraph(systemGraph); world.Play(); for (auto i = 0; i < 5; i++) { diff --git a/Sample/Base/Application.cpp b/Sample/Base/Application.cpp index f80e725b7..aff29a7c6 100644 --- a/Sample/Base/Application.cpp +++ b/Sample/Base/Application.cpp @@ -256,7 +256,7 @@ float Application::GetDeltaTimeSeconds() const return deltaTimeSeconds; } -void* Application::GetPlatformWindow() const +void* Application::GetNativeWindowHandle() const { #if PLATFORM_WINDOWS return glfwGetWin32Window(window); @@ -323,7 +323,7 @@ UniquePtr Application::CreateRenderTarget(RHI::Device& devic if (headless) { return new HeadlessRenderTarget(device, windowExtent.x, windowExtent.y, outputPath); } - return new SwapChainRenderTarget(device, windowExtent.x, windowExtent.y, GetPlatformWindow()); + return new SwapChainRenderTarget(device, windowExtent.x, windowExtent.y, GetNativeWindowHandle()); } Application::ShaderCompileOutput Application::CompileShader(const std::string& fileName, const std::string& entryPoint, RHI::ShaderStageBits shaderStage, std::vector includePaths) const diff --git a/Sample/Base/Application.h b/Sample/Base/Application.h index 71334edbb..3ca6775d4 100644 --- a/Sample/Base/Application.h +++ b/Sample/Base/Application.h @@ -56,7 +56,7 @@ class Application { const std::string& GetApplicationName() const; double GetCurrentTimeSeconds() const; float GetDeltaTimeSeconds() const; - void* GetPlatformWindow() const; + void* GetNativeWindowHandle() const; uint32_t GetWindowWidth() const; uint32_t GetWindowHeight() const; bool IsHeadless() const; diff --git a/Sample/Base/RenderTarget.cpp b/Sample/Base/RenderTarget.cpp index 8ba757b54..30a5cc350 100644 --- a/Sample/Base/RenderTarget.cpp +++ b/Sample/Base/RenderTarget.cpp @@ -51,10 +51,10 @@ SampleRenderTarget::SampleRenderTarget(Device& inDevice, const uint32_t inWidth, SampleRenderTarget::~SampleRenderTarget() = default; -SwapChainRenderTarget::SwapChainRenderTarget(Device& inDevice, const uint32_t inWidth, const uint32_t inHeight, void* inPlatformWindow) +SwapChainRenderTarget::SwapChainRenderTarget(Device& inDevice, const uint32_t inWidth, const uint32_t inHeight, void* inNativeWindowHandle) : SampleRenderTarget(inDevice, inWidth, inHeight) , format(PixelFormat::max) - , surface(device.CreateSurface(SurfaceCreateInfo(inPlatformWindow))) + , surface(device.CreateSurface(SurfaceCreateInfo(inNativeWindowHandle))) , textures() , textureStates() { diff --git a/Sample/Base/RenderTarget.h b/Sample/Base/RenderTarget.h index fa489ea59..9a3e37e59 100644 --- a/Sample/Base/RenderTarget.h +++ b/Sample/Base/RenderTarget.h @@ -38,7 +38,7 @@ class SampleRenderTarget { class SwapChainRenderTarget final : public SampleRenderTarget { public: NonCopyable(SwapChainRenderTarget) - SwapChainRenderTarget(RHI::Device& inDevice, uint32_t inWidth, uint32_t inHeight, void* inPlatformWindow); + SwapChainRenderTarget(RHI::Device& inDevice, uint32_t inWidth, uint32_t inHeight, void* inNativeWindowHandle); ~SwapChainRenderTarget() override; void Initialize() override;