From d4f9cd605b7d73e3d37f6f430d73084a7410b2aa Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 14:25:08 +0200 Subject: [PATCH 01/30] fix(compilation-warnings): fix compilation warning on ubuntu --- .../src/DocumentWindows/EditorScene/Init.cpp | 2 +- editor/src/Editor.cpp | 1 - engine/src/Application.cpp | 3 --- engine/src/ecs/ComponentArray.hpp | 11 +++++----- engine/src/renderer/primitives/Cylinder.cpp | 20 +++++++++---------- engine/src/renderer/primitives/Sphere.cpp | 2 +- engine/src/scripting/native/NativeApi.cpp | 4 ++-- tests/renderer/Buffer.test.cpp | 2 +- 8 files changed, 21 insertions(+), 24 deletions(-) diff --git a/editor/src/DocumentWindows/EditorScene/Init.cpp b/editor/src/DocumentWindows/EditorScene/Init.cpp index 341bab2b5..bfc0dc731 100644 --- a/editor/src/DocumentWindows/EditorScene/Init.cpp +++ b/editor/src/DocumentWindows/EditorScene/Init.cpp @@ -227,7 +227,7 @@ namespace nexo::editor {{-1.0f, 58.5f, 0.0f}, {3.0f, 8.0f, 4.0f}, {0, 0, 0}}, {{-5.0f, 51.0f, 0.0f}, {9.0f, 0.5f, 4.0f}, {0, 0, -25.0f}} }; - for (int i = 0; const auto& [pos, size, rotation] : tunnels) + for (const auto& [pos, size, rotation] : tunnels) { createAndAddEntity(pos, size, rotation, {0.0f, 0.28f, 0.47f, 1.0f}, system::ShapeType::Box, JPH::EMotionType::Static); } diff --git a/editor/src/Editor.cpp b/editor/src/Editor.cpp index 790531b74..515fb600c 100644 --- a/editor/src/Editor.cpp +++ b/editor/src/Editor.cpp @@ -553,7 +553,6 @@ namespace nexo::editor { void Editor::update() const { m_windowRegistry.update(); - Application& app = Application::getInstance(); getApp().endFrame(); } } diff --git a/engine/src/Application.cpp b/engine/src/Application.cpp index c130cdb7b..47b372eaa 100644 --- a/engine/src/Application.cpp +++ b/engine/src/Application.cpp @@ -311,9 +311,6 @@ namespace nexo { m_scriptingSystem->update(); - constexpr float fixedTimestep = 1.0f / 60.0f; - static float physicsAccumulator = 0.0f; - if (!m_isMinimized) { renderContext.sceneRendered = static_cast(sceneInfo.id); diff --git a/engine/src/ecs/ComponentArray.hpp b/engine/src/ecs/ComponentArray.hpp index c23c7e570..bcdc7f58f 100644 --- a/engine/src/ecs/ComponentArray.hpp +++ b/engine/src/ecs/ComponentArray.hpp @@ -230,9 +230,6 @@ namespace nexo::ecs { */ void insertRaw(Entity entity, const void *componentData) override { - if constexpr (!std::is_trivially_copyable_v) { - THROW_EXCEPTION(InternalError, "Component type must be trivially copyable for raw insertion"); - } if (entity >= MAX_ENTITIES) THROW_EXCEPTION(OutOfRange, entity); @@ -249,8 +246,12 @@ namespace nexo::ecs { // allocate new component in the array m_componentArray.emplace_back(); - // copy the raw data into the new component - std::memcpy(&m_componentArray[newIndex], componentData, sizeof(T)); + // copy the raw data into the new component, if it is trivially copyable, use memcpy, otherwise use placement new + if constexpr (std::is_trivially_copyable_v) { + std::memcpy(&m_componentArray[newIndex], componentData, sizeof(T)); + } else { + new (&m_componentArray[newIndex]) T(*reinterpret_cast(componentData)); + } ++m_size; } diff --git a/engine/src/renderer/primitives/Cylinder.cpp b/engine/src/renderer/primitives/Cylinder.cpp index ae3ee12f2..14074499a 100644 --- a/engine/src/renderer/primitives/Cylinder.cpp +++ b/engine/src/renderer/primitives/Cylinder.cpp @@ -33,7 +33,7 @@ namespace nexo::renderer std::vector vertices{}; vertices.reserve(nbSegment * 4); // Reserve memory for all vertices (2 caps + 2 sides) - int i = 0; + unsigned int i = 0; for (unsigned int k = nbSegment - 1; i < nbSegment; ++i, --k) { const float angle = static_cast(k) / static_cast(nbSegment) * 2.0f * static_cast(M_PI); @@ -81,9 +81,9 @@ namespace nexo::renderer */ static void capIndices(std::vector& indices, const int transformer, const unsigned int nbSegment) { - std::function capIndicesRec; + std::function capIndicesRec; - capIndicesRec = [&indices, &transformer, &capIndicesRec, &nbSegment](const int start, const unsigned int nbEdge) + capIndicesRec = [&indices, &transformer, &capIndicesRec, &nbSegment](const unsigned int start, const unsigned int nbEdge) { // Calculate the step size for dividing the cap into triangles // Base case: If the step size is 1, form a single triangle @@ -101,7 +101,7 @@ namespace nexo::renderer if (start + 2 * step < start + nbEdge - 1) { - int tmp = 0; + unsigned int tmp = 0; if (start + 2 * step < start + nbEdge - 1) { tmp = static_cast(start + nbEdge - 1); @@ -132,7 +132,7 @@ namespace nexo::renderer }; // Initial setup: Define the starting point and step size - constexpr int start = 0; + constexpr unsigned int start = 0; const int step = ceil(static_cast(nbSegment) / 3.0); // Add the first triangle to the indices @@ -170,7 +170,7 @@ namespace nexo::renderer indices.reserve(nbSegment * 12); // Generate indices for the side faces of the cylinder - int i = 0; + unsigned int i = 0; for (; i < nbSegment - 1; ++i) { // Create two triangles for each segment @@ -215,18 +215,18 @@ namespace nexo::renderer texCoords.reserve(nbSegment * 4); // Reserve memory for all texture coordinates (one for each vertex) // Generate texture coordinates for cylinder sides - for (int i = 0; i < nbSegment; ++i) + for (unsigned int i = 0; i < nbSegment; ++i) { const float u = static_cast(i) / static_cast(nbSegment); texCoords.emplace_back(u, 1.0f); // Top edge } - for (int i = 0; i < nbSegment; ++i) + for (unsigned int i = 0; i < nbSegment; ++i) { const float u = static_cast(i) / static_cast(nbSegment); texCoords.emplace_back(u, 0.0f); // Bottom edge } // Cap vertices use radial UV mapping - for (int i = 0; i < nbSegment * 2; ++i) + for (unsigned int i = 0; i < nbSegment * 2; ++i) { const float angle = static_cast(i % nbSegment) / static_cast(nbSegment) * 2.0f * static_cast< float>(M_PI); @@ -255,7 +255,7 @@ namespace nexo::renderer { std::vector normals{}; normals.reserve(vertices.size()); // Reserve memory for all normals (2 caps + 2 sides) - int i = 0; + unsigned int i = 0; // Generate normals for the top cap of the cylinder for (; i < nbSegment * 1; ++i) diff --git a/engine/src/renderer/primitives/Sphere.cpp b/engine/src/renderer/primitives/Sphere.cpp index 45d453009..de494a519 100644 --- a/engine/src/renderer/primitives/Sphere.cpp +++ b/engine/src/renderer/primitives/Sphere.cpp @@ -113,7 +113,7 @@ namespace nexo::renderer std::vector newIndices{}; std::map newVertices{}; - for (int j = 0; j < indices.size(); j += 3) + for (size_t j = 0; j < indices.size(); j += 3) { const unsigned int v1 = indices[j]; const unsigned int v2 = indices[j + 1]; diff --git a/engine/src/scripting/native/NativeApi.cpp b/engine/src/scripting/native/NativeApi.cpp index 852921063..0340ef69b 100644 --- a/engine/src/scripting/native/NativeApi.cpp +++ b/engine/src/scripting/native/NativeApi.cpp @@ -203,7 +203,7 @@ namespace nexo::scripting { { auto& app = Application::getInstance(); auto physicsSystem = app.getPhysicsSystem(); - + if (!physicsSystem) { LOG(NEXO_ERROR, "Physics system not available"); return; @@ -217,7 +217,7 @@ namespace nexo::scripting { system::ShapeType cppShapeType = static_cast(shapeType); JPH::EMotionType cppMotionType = static_cast(motionType); - JPH::BodyID bodyID = physicsSystem->createBodyFromShape(entity, transform, cppShapeType, cppMotionType); + physicsSystem->createBodyFromShape(entity, transform, cppShapeType, cppMotionType); LOG(NEXO_DEV, "Physics body created"); } diff --git a/tests/renderer/Buffer.test.cpp b/tests/renderer/Buffer.test.cpp index 33516cb77..9a81478de 100644 --- a/tests/renderer/Buffer.test.cpp +++ b/tests/renderer/Buffer.test.cpp @@ -206,7 +206,7 @@ namespace nexo::renderer { }; int count = 0; - for (auto& _ : layout) { + for ([[maybe_unused]] auto& _ : layout) { count++; } EXPECT_EQ(count, 2); From 5ec75728cd481bcc72760500d46c891e9956967b Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:30:30 +0200 Subject: [PATCH 02/30] fix(compilation-warnings): fix warning in example --- examples/ecs/exampleBasic.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/ecs/exampleBasic.cpp b/examples/ecs/exampleBasic.cpp index f2b0bfaf5..eab37c096 100644 --- a/examples/ecs/exampleBasic.cpp +++ b/examples/ecs/exampleBasic.cpp @@ -186,7 +186,7 @@ class GroupBenchmarkSystem : public nexo::ecs::GroupSystem< auto start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < numIterations; i++) { - m_group->each([](nexo::ecs::Entity entity, Position& position, const Velocity& velocity) { + m_group->each([]([[maybe_unused]] nexo::ecs::Entity entity, Position& position, const Velocity& velocity) { position.x += velocity.x; position.y += velocity.y; From 667db8d3669a33c68ea474b6b5e9c769af4fc7b2 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:53:43 +0200 Subject: [PATCH 03/30] fix(compilation-warnings): fix msvc warnings --- editor/src/DocumentWindows/EditorScene/Init.cpp | 12 +++++++++--- engine/src/renderer/primitives/Sphere.cpp | 6 +++--- tests/renderer/VertexArray.test.cpp | 5 ++++- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/editor/src/DocumentWindows/EditorScene/Init.cpp b/editor/src/DocumentWindows/EditorScene/Init.cpp index bfc0dc731..492acde65 100644 --- a/editor/src/DocumentWindows/EditorScene/Init.cpp +++ b/editor/src/DocumentWindows/EditorScene/Init.cpp @@ -53,9 +53,15 @@ namespace nexo::editor renderTarget); auto& cameraComponent = app.m_coordinator->getComponent(m_editorCamera); cameraComponent.render = true; - auto maskPass = std::make_shared(m_contentSize.x, m_contentSize.y); - auto outlinePass = std::make_shared(m_contentSize.x, m_contentSize.y); - auto gridPass = std::make_shared(m_contentSize.x, m_contentSize.y); + auto maskPass = std::make_shared( + static_cast(m_contentSize.x), + static_cast(m_contentSize.y)); + auto outlinePass = std::make_shared( + static_cast(m_contentSize.x), + static_cast(m_contentSize.y)); + auto gridPass = std::make_shared( + static_cast(m_contentSize.x), + static_cast(m_contentSize.y)); const renderer::PassId forwardId = cameraComponent.pipeline.getFinalOutputPass(); const renderer::PassId maskId = cameraComponent.pipeline.addRenderPass(std::move(maskPass)); diff --git a/engine/src/renderer/primitives/Sphere.cpp b/engine/src/renderer/primitives/Sphere.cpp index de494a519..91292348e 100644 --- a/engine/src/renderer/primitives/Sphere.cpp +++ b/engine/src/renderer/primitives/Sphere.cpp @@ -126,17 +126,17 @@ namespace nexo::renderer if (!newVertices.contains(m1_pos)) { vertices.emplace_back(m1_pos); - newVertices.insert({m1_pos, vertices.size() - 1}); + newVertices.insert({m1_pos, static_cast(vertices.size() - 1)}); } if (!newVertices.contains(m2_pos)) { vertices.emplace_back(m2_pos); - newVertices.insert({m2_pos, vertices.size() - 1}); + newVertices.insert({m2_pos, static_cast(vertices.size() - 1)}); } if (!newVertices.contains(m3_pos)) { vertices.emplace_back(m3_pos); - newVertices.insert({m3_pos, vertices.size() - 1}); + newVertices.insert({m3_pos, static_cast(vertices.size() - 1)}); } auto m1 = newVertices[m1_pos]; diff --git a/tests/renderer/VertexArray.test.cpp b/tests/renderer/VertexArray.test.cpp index 9a98ac2c3..86a4d3dfe 100644 --- a/tests/renderer/VertexArray.test.cpp +++ b/tests/renderer/VertexArray.test.cpp @@ -54,7 +54,10 @@ namespace nexo::renderer { 1.0f, 1.0f, 1.0f, 1.0f, // Color 3, // Texture index }; - auto vertexBuffer = std::make_shared(vertices, sizeof(vertices)); + auto vertexBuffer = std::make_shared( + vertices, + static_cast(sizeof(vertices)) + ); NxBufferLayout layout = { {NxShaderDataType::FLOAT3, "Position"}, {NxShaderDataType::FLOAT4, "Color", true}, From bea3560745dc9d2f5c9900158edd80f90a972166 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 18:04:28 +0200 Subject: [PATCH 04/30] fix(compilation-warnings): fix last ubuntu warning --- editor/src/utils/FileSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/editor/src/utils/FileSystem.cpp b/editor/src/utils/FileSystem.cpp index eecd22139..32edad84e 100644 --- a/editor/src/utils/FileSystem.cpp +++ b/editor/src/utils/FileSystem.cpp @@ -29,7 +29,7 @@ namespace nexo::editor::utils { #else std::stringstream ss; ss << "xdg-open " << std::quoted(folderPath); - std::system(ss.str().c_str()); + (void)std::system(ss.str().c_str()); #endif } } From 0451191e8b716da924f9d65201c5c6b9e62a308c Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 20:08:03 +0200 Subject: [PATCH 05/30] fix(compilation-warnings): fix last warnings --- editor/src/utils/FileSystem.cpp | 7 ++++++- tests/renderer/VertexArray.test.cpp | 9 ++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/editor/src/utils/FileSystem.cpp b/editor/src/utils/FileSystem.cpp index 32edad84e..9c021f795 100644 --- a/editor/src/utils/FileSystem.cpp +++ b/editor/src/utils/FileSystem.cpp @@ -20,6 +20,7 @@ #include #include #include "FileSystem.hpp" +#include "Logger.hpp" namespace nexo::editor::utils { void openFolder(const std::string &folderPath) @@ -29,7 +30,11 @@ namespace nexo::editor::utils { #else std::stringstream ss; ss << "xdg-open " << std::quoted(folderPath); - (void)std::system(ss.str().c_str()); + int status = std::system(ss.str().c_str()); + if (status == -1) + LOG(NEXO_ERROR, "Failed to open folder '{}'", folderPath); + else if (status != 0) + LOG(NEXO_WARN, "Opening folder '{}' returned exit code {}", folderPath, status); #endif } } diff --git a/tests/renderer/VertexArray.test.cpp b/tests/renderer/VertexArray.test.cpp index 86a4d3dfe..b5bafcc53 100644 --- a/tests/renderer/VertexArray.test.cpp +++ b/tests/renderer/VertexArray.test.cpp @@ -112,7 +112,10 @@ namespace nexo::renderer { 1.0f, 1.0f, 1.0f, 1.0f, // Color 3, // Texture index }; - auto vertexBuffer = std::make_shared(vertices, sizeof(vertices)); + auto vertexBuffer = std::make_shared( + vertices, + static_cast(sizeof(vertices)) + ); // Empty layout EXPECT_THROW( @@ -132,13 +135,13 @@ namespace nexo::renderer { auto vertexArray = std::make_shared(); float positions[] = {0.0f, 1.0f, 2.0f}; - auto positionBuffer = std::make_shared(positions, sizeof(positions)); + auto positionBuffer = std::make_shared(positions, static_cast(sizeof(positions))); positionBuffer->setLayout({ {NxShaderDataType::FLOAT3, "Position"} }); float colors[] = {1.0f, 0.0f, 0.0f}; - auto colorBuffer = std::make_shared(colors, sizeof(colors)); + auto colorBuffer = std::make_shared(colors, static_cast(sizeof(colors))); colorBuffer->setLayout({ {NxShaderDataType::FLOAT3, "Color"} }); From e5553574a8980d9cc69a633f756efeea3eb0d870 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 23:43:00 +0200 Subject: [PATCH 06/30] fix(compilation-warnings): step is now unsigned int --- engine/src/renderer/primitives/Cylinder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/src/renderer/primitives/Cylinder.cpp b/engine/src/renderer/primitives/Cylinder.cpp index 14074499a..aa7ce6c8f 100644 --- a/engine/src/renderer/primitives/Cylinder.cpp +++ b/engine/src/renderer/primitives/Cylinder.cpp @@ -133,7 +133,7 @@ namespace nexo::renderer // Initial setup: Define the starting point and step size constexpr unsigned int start = 0; - const int step = ceil(static_cast(nbSegment) / 3.0); + const unsigned int step = static_cast(ceil(static_cast(nbSegment) / 3.0)); // Add the first triangle to the indices indices.push_back(start + transformer); From 5c088d24d1a8258e2d96a8e4ecc970dc10c76810 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 23:43:25 +0200 Subject: [PATCH 07/30] tests(compilation-warnings): remove underscore for more clear intent --- tests/renderer/Buffer.test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/renderer/Buffer.test.cpp b/tests/renderer/Buffer.test.cpp index 9a81478de..532b5f5c9 100644 --- a/tests/renderer/Buffer.test.cpp +++ b/tests/renderer/Buffer.test.cpp @@ -206,7 +206,7 @@ namespace nexo::renderer { }; int count = 0; - for ([[maybe_unused]] auto& _ : layout) { + for ([[maybe_unused]] auto& element : layout) { count++; } EXPECT_EQ(count, 2); From 2e2a294f58887a2e850d6bb16d9c25fc1bc1fca7 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 23:35:40 +0200 Subject: [PATCH 08/30] fix(sonar-editor): first batch of sonar issues fix --- editor/CMakeLists.txt | 1 - editor/main.cpp | 1 - editor/src/ADocumentWindow.cpp | 2 +- editor/src/DockingRegistry.cpp | 4 +- .../AssetManager/AssetManagerWindow.hpp | 19 +- .../DocumentWindows/AssetManager/FileDrop.cpp | 46 ++--- .../AssetManager/FolderTree.cpp | 25 +-- .../src/DocumentWindows/AssetManager/Show.cpp | 163 +++++++++--------- .../AssetManager/Thumbnail.cpp | 41 ----- .../ConsoleWindow/ConsoleWindow.hpp | 3 +- .../DocumentWindows/ConsoleWindow/Show.cpp | 4 +- .../DocumentWindows/ConsoleWindow/Utils.cpp | 6 +- .../DocumentWindows/EditorScene/DragDrop.cpp | 30 ++-- .../EditorScene/EditorScene.hpp | 17 +- .../src/DocumentWindows/EditorScene/Gizmo.cpp | 78 ++++----- .../src/DocumentWindows/EditorScene/Init.cpp | 13 +- .../DocumentWindows/EditorScene/Shortcuts.cpp | 4 +- .../src/DocumentWindows/EditorScene/Show.cpp | 4 +- .../DocumentWindows/EditorScene/Toolbar.cpp | 8 +- .../DocumentWindows/EditorScene/Update.cpp | 12 +- .../EntityProperties/AmbientLightProperty.cpp | 2 +- .../EntityProperties/MaterialProperty.cpp | 19 +- .../EntityProperties/MaterialProperty.hpp | 6 +- .../EntityProperties/RenderProperty.cpp | 6 +- .../EntityProperties/TypeErasedProperty.cpp | 6 +- .../DocumentWindows/GameWindow/GameWindow.cpp | 2 +- .../DocumentWindows/GameWindow/GameWindow.hpp | 1 - .../src/DocumentWindows/GameWindow/Setup.cpp | 2 - .../src/DocumentWindows/GameWindow/Show.cpp | 12 +- .../src/DocumentWindows/GameWindow/Update.cpp | 2 +- .../InspectorWindow/InspectorWindow.hpp | 11 +- .../DocumentWindows/InspectorWindow/Show.cpp | 2 +- .../MaterialInspector/Show.cpp | 5 +- .../SceneTreeWindow/DragDrop.cpp | 24 +-- .../SceneTreeWindow/NodeHandling.cpp | 8 +- .../SceneTreeWindow/SceneCreation.cpp | 1 + .../SceneTreeWindow/SceneTreeWindow.hpp | 14 +- .../SceneTreeWindow/Selection.cpp | 2 +- .../SceneTreeWindow/Shortcuts.cpp | 20 ++- .../SceneTreeWindow/Update.cpp | 9 +- .../src/DocumentWindows/TestWindow/Parser.cpp | 6 +- .../DocumentWindows/TestWindow/Shutdown.cpp | 22 ++- editor/src/Editor.cpp | 16 +- editor/src/ImNexo/Components.cpp | 2 +- editor/src/ImNexo/Elements.cpp | 4 +- editor/src/ImNexo/Elements.hpp | 2 +- editor/src/ImNexo/EntityProperties.cpp | 4 +- editor/src/ImNexo/Guard.hpp | 2 - editor/src/ImNexo/Panels.cpp | 2 +- editor/src/ImNexo/Panels.hpp | 3 - editor/src/ImNexo/Utils.cpp | 11 +- editor/src/ImNexo/Utils.hpp | 1 - editor/src/ImNexo/Widgets.cpp | 5 +- editor/src/WindowRegistry.hpp | 10 +- editor/src/context/ActionHistory.cpp | 4 +- editor/src/context/ThumbnailCache.cpp | 35 ++-- .../actions/ComponentRestoreFactory.cpp | 3 +- editor/src/context/actions/EntityActions.cpp | 12 +- editor/src/context/actions/EntityActions.hpp | 2 +- editor/src/exceptions/Exceptions.hpp | 4 +- editor/src/inputs/Command.cpp | 4 +- editor/src/inputs/WindowState.cpp | 2 +- editor/src/utils/Config.cpp | 2 +- editor/src/utils/EditorProps.cpp | 1 - editor/src/utils/FileSystem.cpp | 2 +- editor/src/utils/FileSystem.hpp | 1 - editor/src/utils/ScenePreview.cpp | 1 - editor/src/utils/ScenePreview.hpp | 1 + editor/src/utils/String.cpp | 5 +- 69 files changed, 347 insertions(+), 457 deletions(-) delete mode 100644 editor/src/DocumentWindows/AssetManager/Thumbnail.cpp diff --git a/editor/CMakeLists.txt b/editor/CMakeLists.txt index 7d307baa3..1533c93ec 100644 --- a/editor/CMakeLists.txt +++ b/editor/CMakeLists.txt @@ -54,7 +54,6 @@ set(SRCS editor/src/DocumentWindows/AssetManager/Shutdown.cpp editor/src/DocumentWindows/AssetManager/Update.cpp editor/src/DocumentWindows/AssetManager/FolderTree.cpp - editor/src/DocumentWindows/AssetManager/Thumbnail.cpp editor/src/DocumentWindows/AssetManager/FileDrop.cpp editor/src/DocumentWindows/ConsoleWindow/Init.cpp editor/src/DocumentWindows/ConsoleWindow/Log.cpp diff --git a/editor/main.cpp b/editor/main.cpp index ee27ea0c7..3ac0ee160 100644 --- a/editor/main.cpp +++ b/editor/main.cpp @@ -26,7 +26,6 @@ #include #include -#include "Path.hpp" #include "scripting/native/ManagedTypedef.hpp" #include "scripting/native/Scripting.hpp" diff --git a/editor/src/ADocumentWindow.cpp b/editor/src/ADocumentWindow.cpp index 009f07c66..48f4ba995 100644 --- a/editor/src/ADocumentWindow.cpp +++ b/editor/src/ADocumentWindow.cpp @@ -30,7 +30,7 @@ namespace nexo::editor { { const bool isDocked = currentWindow->DockIsActive; const ImGuiID currentDockID = currentWindow->DockId; - auto dockId = m_windowRegistry.getDockId(windowName); + const auto dockId = m_windowRegistry.getDockId(windowName); // If it's the first time opening the window and we have a dock id saved in the registry, then we force set it if (m_firstOpened && (dockId && currentDockID != *dockId)) diff --git a/editor/src/DockingRegistry.cpp b/editor/src/DockingRegistry.cpp index 7cb210dd6..964563290 100644 --- a/editor/src/DockingRegistry.cpp +++ b/editor/src/DockingRegistry.cpp @@ -25,7 +25,7 @@ namespace nexo::editor { std::optional DockingRegistry::getDockId(const std::string& name) const { - auto it = dockIds.find(name); + const auto it = dockIds.find(name); if (it != dockIds.end()) { return it->second; } @@ -34,7 +34,7 @@ namespace nexo::editor { void DockingRegistry::resetDockId(const std::string &name) { - auto it = dockIds.find(name); + const auto it = dockIds.find(name); if (it == dockIds.end()) return; dockIds.erase(it); diff --git a/editor/src/DocumentWindows/AssetManager/AssetManagerWindow.hpp b/editor/src/DocumentWindows/AssetManager/AssetManagerWindow.hpp index 1c4a0d9d6..16e7ac7c0 100644 --- a/editor/src/DocumentWindows/AssetManager/AssetManagerWindow.hpp +++ b/editor/src/DocumentWindows/AssetManager/AssetManagerWindow.hpp @@ -67,15 +67,15 @@ namespace nexo::editor { } color; }; - std::set m_selectedAssets; + std::set m_selectedAssets; std::unordered_map, TransparentStringHash, std::equal_to<>> m_folderChildren; LayoutSettings m_layout; void calculateLayout(float availWidth); void drawMenuBar(); void drawAssetsGrid(); - void drawAsset(const assets::GenericAssetRef& asset, int index, const ImVec2& itemPos, const ImVec2& itemSize); - void handleSelection(int index, bool isSelected); + void drawAsset(const assets::GenericAssetRef& asset, unsigned int index, const ImVec2& itemPos, const ImVec2& itemSize); + void handleSelection(unsigned int index, bool isSelected); assets::AssetType m_selectedType = assets::AssetType::UNKNOWN; std::string m_currentFolder; // Currently selected folder @@ -87,13 +87,6 @@ namespace nexo::editor { void drawFolderTree(); void drawFolderTreeItem(const std::string& name, const std::string& path); - void drawTextureThumbnail( - ImDrawList *drawList, - ImTextureID textureId, - const ImVec2 &itemPos, - const ImVec2& thumbnailEnd - ) const ; - struct FolderCreationState { bool isCreatingFolder = false; char folderName[256] = ""; @@ -106,7 +99,7 @@ namespace nexo::editor { FolderCreationState m_folderCreationState; assets::AssetRef m_folderIcon; - ImTextureID getFolderIconTexture(); + ImTextureID getFolderIconTexture() const; void handleNewFolderCreation(); void drawFolder( @@ -120,8 +113,8 @@ namespace nexo::editor { bool m_showDropIndicator = false; void handleDroppedFiles(); - const assets::AssetLocation getAssetLocation(const std::filesystem::path &path) const; - void importDroppedFile(const std::string& filePath); + assets::AssetLocation getAssetLocation(const std::filesystem::path &path) const; + void importDroppedFile(const std::string& filePath) const; }; /** diff --git a/editor/src/DocumentWindows/AssetManager/FileDrop.cpp b/editor/src/DocumentWindows/AssetManager/FileDrop.cpp index a9df7c8ab..a170f742f 100644 --- a/editor/src/DocumentWindows/AssetManager/FileDrop.cpp +++ b/editor/src/DocumentWindows/AssetManager/FileDrop.cpp @@ -13,40 +13,21 @@ /////////////////////////////////////////////////////////////////////////////// #include "AssetManagerWindow.hpp" -#include "assets/Asset.hpp" #include "assets/AssetImporter.hpp" #include "assets/AssetLocation.hpp" -#include "assets/Assets/Model/Model.hpp" -#include "assets/Assets/Texture/Texture.hpp" #include "Logger.hpp" #include #include namespace nexo::editor { - static assets::AssetType getAssetTypeFromExtension(const std::string &extension) + assets::AssetLocation AssetManagerWindow::getAssetLocation(const std::filesystem::path &path) const { - static const std::set imageExtensions = { - ".png", ".jpg", ".jpeg", ".bmp", ".tga", ".gif", ".psd", ".hdr", ".pic", ".pnm", ".ppm", ".pgm" - }; - if (imageExtensions.contains(extension)) - return assets::AssetType::TEXTURE; - static const std::set modelExtensions = { - ".gltf", ".glb", ".fbx", ".obj", ".dae", ".3ds", ".stl", ".ply", ".blend", ".x3d", ".ifc" - }; - if (modelExtensions.contains(extension)) - return assets::AssetType::MODEL; - return assets::AssetType::UNKNOWN; - } - - const assets::AssetLocation AssetManagerWindow::getAssetLocation(const std::filesystem::path &path) const - { - std::string assetName = path.stem().string(); + const std::string assetName = path.stem().string(); std::filesystem::path folderPath; - std::string targetFolder = !m_hoveredFolder.empty() ? m_hoveredFolder : m_currentFolder; + const std::string targetFolder = !m_hoveredFolder.empty() ? m_hoveredFolder : m_currentFolder; - std::string assetPath = targetFolder; - std::string locationString = assetName + "@" + assetPath; + std::string locationString = assetName + "@" + targetFolder; LOG(NEXO_DEV, "Creating asset location: {} (current folder: '{}', hovered: '{}')", @@ -78,9 +59,9 @@ namespace nexo::editor { buildFolderStructure(); } - void AssetManagerWindow::importDroppedFile(const std::string& filePath) + void AssetManagerWindow::importDroppedFile(const std::string& filePath) const { - std::filesystem::path path(filePath); + const std::filesystem::path path(filePath); if (!std::filesystem::exists(path)) { LOG(NEXO_WARN, "Dropped file does not exist: {}", filePath); @@ -88,21 +69,14 @@ namespace nexo::editor { } std::string extension = path.extension().string(); - std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower); - - assets::AssetType assetType = getAssetTypeFromExtension(extension); - if (assetType == assets::AssetType::UNKNOWN) { - LOG(NEXO_WARN, "Unsupported file type: {}", extension); - return; - } + std::ranges::transform(extension, extension.begin(), ::tolower); - assets::AssetLocation location = getAssetLocation(path); + const assets::AssetLocation location = getAssetLocation(path); - assets::AssetImporter importer; assets::ImporterFileInput fileInput{path}; try { - auto assetRef = importer.importAssetAuto(location, fileInput); - if (!assetRef) + assets::AssetImporter importer; + if (const auto assetRef = importer.importAssetAuto(location, fileInput); !assetRef) LOG(NEXO_ERROR, "Failed to import asset: {}", location.getPath().data()); } catch (const std::exception& e) { LOG(NEXO_ERROR, "Exception while importing {}: {}", location.getPath().data(), e.what()); diff --git a/editor/src/DocumentWindows/AssetManager/FolderTree.cpp b/editor/src/DocumentWindows/AssetManager/FolderTree.cpp index 5b5d38b70..68179b6ea 100644 --- a/editor/src/DocumentWindows/AssetManager/FolderTree.cpp +++ b/editor/src/DocumentWindows/AssetManager/FolderTree.cpp @@ -59,8 +59,7 @@ namespace nexo::editor { if (opened) { // Use the precomputed children list - auto it = m_folderChildren.find(path); - if (it != m_folderChildren.end()) { + if (const auto it = m_folderChildren.find(path); it != m_folderChildren.end()) { for (const auto& childPath : it->second) { // Find the name of the child from m_folderStructure std::string childName; @@ -83,7 +82,7 @@ namespace nexo::editor { ImGui::OpenPopup("Create New Folder"); // Center the popup - ImVec2 center = ImGui::GetMainViewport()->GetCenter(); + const ImVec2 center = ImGui::GetMainViewport()->GetCenter(); ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); if (ImGui::BeginPopupModal("Create New Folder", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { @@ -102,7 +101,7 @@ namespace nexo::editor { // Check if folder already exists bool folderExists = false; - for (const auto& [path, _] : m_folderStructure) { + for (const auto &path: m_folderStructure | std::views::keys) { if (path == newFolderPath) { folderExists = true; break; @@ -164,20 +163,17 @@ namespace nexo::editor { std::unordered_set seen{""}; - const auto assets = assets::AssetCatalog::getInstance().getAssets(); - for (auto& ref : assets) { - if (auto assetData = ref.lock()) { + for (const auto assets = assets::AssetCatalog::getInstance().getAssets(); auto& ref : assets) { + if (const auto assetData = ref.lock()) { // normalized path: e.g. "Random/Sub" std::filesystem::path p{ assetData->getMetadata().location.getPath() }; std::filesystem::path curr; for (auto const& part : p) { // skip empty or “_internal” style parts - auto s = part.string(); - if (s.empty() || s.front() == '_') + if (auto s = part.string(); s.empty() || s.front() == '_') continue; curr /= part; - auto folderPath = curr.string(); - if (seen.emplace(folderPath).second) { + if (auto folderPath = curr.string(); seen.emplace(folderPath).second) { m_folderStructure.emplace_back( folderPath, curr.filename().string() @@ -208,10 +204,7 @@ namespace nexo::editor { // favorites section { - ImGuiTreeNodeFlags headerFlags = ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_OpenOnDoubleClick; - bool favoritesOpen = ImGui::TreeNodeEx(ICON_FA_STAR " Favorites", headerFlags); - - if (favoritesOpen) { + if (ImGui::TreeNodeEx(ICON_FA_STAR " Favorites", ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_OpenOnDoubleClick)) { struct FavoriteItem { std::string label; assets::AssetType type; @@ -224,7 +217,7 @@ namespace nexo::editor { }; for (const auto& fav : favorites) { - bool isSelected = (fav.type == m_selectedType); + const bool isSelected = (fav.type == m_selectedType); ImGuiTreeNodeFlags itemFlags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; if (isSelected) diff --git a/editor/src/DocumentWindows/AssetManager/Show.cpp b/editor/src/DocumentWindows/AssetManager/Show.cpp index 602c1b93e..4bd0a1570 100644 --- a/editor/src/DocumentWindows/AssetManager/Show.cpp +++ b/editor/src/DocumentWindows/AssetManager/Show.cpp @@ -16,11 +16,9 @@ #include "assets/Asset.hpp" #include "assets/AssetCatalog.hpp" #include "IconsFontAwesome.h" -#include "Path.hpp" #include "assets/Assets/Texture/Texture.hpp" #include "context/ThumbnailCache.hpp" #include -#include "Logger.hpp" #include namespace nexo::editor { @@ -39,10 +37,17 @@ namespace nexo::editor { void AssetManagerWindow::calculateLayout(const float availWidth) { // Sizes - m_layout.size.columnCount = std::max(static_cast(availWidth / (m_layout.size.iconSize + static_cast(m_layout.size.iconSpacing))), 1); - m_layout.size.itemSize = ImVec2(m_layout.size.iconSize + ImGui::GetFontSize() * 1.5f, m_layout.size.iconSize + ImGui::GetFontSize() * 1.7f); - m_layout.size.itemStep = ImVec2(m_layout.size.itemSize.x + static_cast(m_layout.size.iconSpacing), m_layout.size.itemSize.y + static_cast(m_layout.size.iconSpacing)); - + m_layout.size.columnCount = std::max( + static_cast(availWidth / m_layout.size.itemStep.x), 1 + ); + m_layout.size.itemSize = ImVec2( + m_layout.size.iconSize + ImGui::GetFontSize() * 1.5f, // width + m_layout.size.iconSize + ImGui::GetFontSize() * 1.7f // height + ); + m_layout.size.itemStep = ImVec2( + m_layout.size.itemSize.x + m_layout.size.iconSpacing, + m_layout.size.itemSize.y + m_layout.size.iconSpacing + ); // Colors m_layout.color.thumbnailBg = ImGui::GetColorU32(ImGuiCol_Button); m_layout.color.thumbnailBgHovered = ImGui::GetColorU32(ImGuiCol_ButtonHovered); @@ -59,7 +64,7 @@ namespace nexo::editor { m_layout.color.titleText = ImGui::GetColorU32(ImGuiCol_Text); } - void AssetManagerWindow::handleSelection(int index, const bool isSelected) + void AssetManagerWindow::handleSelection(const unsigned int index, const bool isSelected) { if (ImGui::GetIO().KeyCtrl) { if (isSelected) @@ -67,13 +72,13 @@ namespace nexo::editor { else m_selectedAssets.insert(index); } else if (ImGui::GetIO().KeyShift) { - const int latestSelected = m_selectedAssets.empty() ? 0 : *m_selectedAssets.rbegin(); + const unsigned int latestSelected = m_selectedAssets.empty() ? 0 : *m_selectedAssets.rbegin(); if (latestSelected <= index) { - for (int i = latestSelected ; i <= index; ++i) { + for (unsigned int i = latestSelected ; i <= index; ++i) { m_selectedAssets.insert(i); } } else { - for (int i = index; i <= latestSelected; ++i) { + for (unsigned int i = index; i <= latestSelected; ++i) { m_selectedAssets.insert(i); } } @@ -94,22 +99,22 @@ namespace nexo::editor { void AssetManagerWindow::drawAsset( const assets::GenericAssetRef& asset, - const int index, + const unsigned int index, const ImVec2& itemPos, const ImVec2& itemSize ) { - auto assetData = asset.lock(); + const auto assetData = asset.lock(); if (!assetData) return; ImDrawList* drawList = ImGui::GetWindowDrawList(); const auto itemEnd = ImVec2(itemPos.x + itemSize.x, itemPos.y + itemSize.y); - ImGui::PushID(index); + ImGui::PushID(static_cast(index)); ImGui::SetCursorScreenPos(itemPos); - bool clicked = ImGui::InvisibleButton("##item", itemSize); - bool isHovered = ImGui::IsItemHovered(); + const bool clicked = ImGui::InvisibleButton("##item", itemSize); + const bool isHovered = ImGui::IsItemHovered(); const bool isSelected = std::ranges::find(m_selectedAssets, index) != m_selectedAssets.end(); const ImU32 bgColor = isSelected ? m_layout.color.thumbnailBgSelected : m_layout.color.thumbnailBg; @@ -130,13 +135,12 @@ namespace nexo::editor { // Draw thumbnail area const auto thumbnailEnd = ImVec2(itemPos.x + itemSize.x, itemPos.y + itemSize.y * m_layout.size.thumbnailHeightRatio); - ImTextureID textureId = ThumbnailCache::getInstance().getThumbnail(asset); - if (!textureId) { + if (const ImTextureID textureId = ThumbnailCache::getInstance().getThumbnail(asset); !textureId) { drawList->AddRectFilled(itemPos, thumbnailEnd, m_layout.color.thumbnailBg); } else { - const float padding = 4.0f; - ImVec2 imageStart(itemPos.x + padding, itemPos.y + padding); - ImVec2 imageEnd(thumbnailEnd.x - padding, thumbnailEnd.y - padding); + constexpr float padding = 4.0f; + const ImVec2 imageStart(itemPos.x + padding, itemPos.y + padding); + const ImVec2 imageEnd(thumbnailEnd.x - padding, thumbnailEnd.y - padding); drawList->AddImage( textureId, @@ -159,7 +163,7 @@ namespace nexo::editor { thumbnailEnd.y + m_layout.size.titlePadding); // Background rectangle for text - ImU32 titleBgColor = isHovered ? m_layout.color.titleBgHovered : m_layout.color.titleBg; + const ImU32 titleBgColor = isHovered ? m_layout.color.titleBgHovered : m_layout.color.titleBg; drawList->AddRectFilled(ImVec2(itemPos.x, thumbnailEnd.y), ImVec2(itemEnd.x, itemEnd.y), titleBgColor); drawList->AddText(textPos, m_layout.color.titleText, assetName); @@ -185,10 +189,10 @@ namespace nexo::editor { // Show preview while dragging //TODO: Add asset preview thanks to thumbnail cache after rebasing if (assetData->getType() == assets::AssetType::TEXTURE) { - auto textureAsset = asset.as(); - auto textureData = textureAsset.lock(); - if (textureData && textureData->getData() && textureData->getData()->texture) { - ImTextureID textureId = textureData->getData()->texture->getId(); + const auto textureAsset = asset.as(); + if (const auto textureData = textureAsset.lock(); + textureData && textureData->getData() && textureData->getData()->texture) { + const ImTextureID textureId = textureData->getData()->texture->getId(); ImGui::Image(textureId, {64, 64}); } } @@ -199,10 +203,10 @@ namespace nexo::editor { ImGui::PopID(); } - ImTextureID AssetManagerWindow::getFolderIconTexture() + ImTextureID AssetManagerWindow::getFolderIconTexture() const { - if (auto texRef = m_folderIcon.lock()) { - auto &texData = texRef->getData(); + if (const auto texRef = m_folderIcon.lock()) { + const auto &texData = texRef->getData(); if (texData && texData->texture) { return texData->texture->getId(); } @@ -223,8 +227,8 @@ namespace nexo::editor { ImGui::SetCursorScreenPos(itemPos); - bool clicked = ImGui::InvisibleButton("##folder", itemSize); - bool isHovered = ImGui::IsItemHovered(); + const bool clicked = ImGui::InvisibleButton("##folder", itemSize); + const bool isHovered = ImGui::IsItemHovered(); if (isHovered) { m_hoveredFolder = folderPath; @@ -236,46 +240,45 @@ namespace nexo::editor { { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ASSET_DRAG")) { - const AssetDragDropPayload* data = (const AssetDragDropPayload*)payload->Data; + const auto* data = static_cast(payload->Data); assets::AssetCatalog::getInstance().moveAsset(data->id, folderPath); } ImGui::EndDragDropTarget(); } // Background - use hover color when hovered - ImU32 bgColor = isHovered ? m_layout.color.thumbnailBgHovered : IM_COL32(0, 0, 0, 0); + const ImU32 bgColor = isHovered ? m_layout.color.thumbnailBgHovered : IM_COL32(0, 0, 0, 0); drawList->AddRectFilled(itemPos, itemEnd, bgColor, m_layout.size.cornerRadius); const auto thumbnailEnd = ImVec2(itemPos.x + itemSize.x, itemPos.y + itemSize.y * m_layout.size.thumbnailHeightRatio); // Calculate padding for the icon - const float padding = 10.0f; + constexpr float padding = 10.0f; // Calculate available area dimensions - float availWidth = thumbnailEnd.x - itemPos.x - (padding * 2.0f); - float availHeight = thumbnailEnd.y - itemPos.y - (padding * 2.0f); + const float availWidth = thumbnailEnd.x - itemPos.x - (padding * 2.0f); + const float availHeight = thumbnailEnd.y - itemPos.y - (padding * 2.0f); // Maintain aspect ratio by using the smaller dimension - float displaySize = std::min(availWidth, availHeight); + const float displaySize = std::min(availWidth, availHeight); // Calculate centered position - float xOffset = (availWidth - displaySize) * 0.5f + padding; - float yOffset = (availHeight - displaySize) * 0.5f + padding; + const float xOffset = (availWidth - displaySize) * 0.5f + padding; + const float yOffset = (availHeight - displaySize) * 0.5f + padding; // Final image coordinates maintaining aspect ratio - ImVec2 imageStart( + const ImVec2 imageStart( itemPos.x + xOffset, itemPos.y + yOffset ); - ImVec2 imageEnd( + const ImVec2 imageEnd( imageStart.x + displaySize, imageStart.y + displaySize ); // Draw folder PNG icon - ImTextureID folderIconTexture = getFolderIconTexture(); - if (folderIconTexture) { + if (const ImTextureID folderIconTexture = getFolderIconTexture()) { drawList->AddImage( folderIconTexture, imageStart, @@ -287,11 +290,11 @@ namespace nexo::editor { } // Calculate text size to ensure it fits - ImVec2 textSize = ImGui::CalcTextSize(folderName.c_str()); + const ImVec2 textSize = ImGui::CalcTextSize(folderName.c_str()); // Draw title background - ImU32 titleBgColor = isHovered ? m_layout.color.titleBgHovered : IM_COL32(0, 0, 0, 0); - float titleAreaHeight = itemSize.y * (1.0f - m_layout.size.thumbnailHeightRatio); + const ImU32 titleBgColor = isHovered ? m_layout.color.titleBgHovered : IM_COL32(0, 0, 0, 0); + const float titleAreaHeight = itemSize.y * (1.0f - m_layout.size.thumbnailHeightRatio); drawList->AddRectFilled( ImVec2(itemPos.x, thumbnailEnd.y), @@ -300,8 +303,8 @@ namespace nexo::editor { ); // Position text with proper vertical alignment - float textY = thumbnailEnd.y + ((titleAreaHeight - textSize.y) * 0.5f); - float textX = itemPos.x + (itemSize.x - textSize.x) * 0.5f; + const float textY = thumbnailEnd.y + ((titleAreaHeight - textSize.y) * 0.5f); + const float textX = itemPos.x + (itemSize.x - textSize.x) * 0.5f; drawList->AddText( ImVec2(textX, textY), @@ -317,64 +320,58 @@ namespace nexo::editor { void AssetManagerWindow::drawAssetsGrid() { - ImVec2 startPos = ImGui::GetCursorScreenPos(); + const ImVec2 startPos = ImGui::GetCursorScreenPos(); - // 1) Collect immediate subfolders of the current folder std::vector> subfolders; for (auto& [path,name] : m_folderStructure) { if (path.empty() || path.front() == '_') continue; if (m_currentFolder.empty()) { - // root level = no slash in path if (path.find('/') == std::string::npos) subfolders.emplace_back(path, name); } else { - std::string prefix = m_currentFolder + "/"; - // immediate child: starts with "curr/" but has no further '/' - if (path.rfind(prefix, 0) == 0 && - path.find('/', prefix.size()) == std::string::npos) + if (std::string prefix = m_currentFolder + "/"; path.rfind(prefix, 0) == 0 && + path.find('/', prefix.size()) == std::string::npos) { subfolders.emplace_back(path, path.substr(prefix.size())); } } } - // 2) Collect assets exactly in the current folder std::vector filtered; for (auto& ref : assets::AssetCatalog::getInstance().getAssets()) { - if (auto d = ref.lock()) { + if (const auto d = ref.lock()) { const auto& folder = d->getMetadata().location.getPath(); - if (folder == "_internal") continue; + if (folder == "_internal") + continue; if (m_selectedType != assets::AssetType::UNKNOWN && d->getType() != m_selectedType) continue; - // **here’s the fix**: just compare the whole normalized folder if (folder == m_currentFolder) filtered.push_back(ref); } } - // 3) Layout & draw both subfolders and assets - size_t totalItems = subfolders.size() + filtered.size(); + const size_t totalItems = subfolders.size() + filtered.size(); ImGuiListClipper clipper; - int rows = int((totalItems + m_layout.size.columnCount - 1) / m_layout.size.columnCount); + const auto rows = static_cast((totalItems + m_layout.size.columnCount - 1) / m_layout.size.columnCount); clipper.Begin(rows, m_layout.size.itemStep.y); while (clipper.Step()) { for (int line = clipper.DisplayStart; line < clipper.DisplayEnd; ++line) { - int startIdx = line * m_layout.size.columnCount; - int endIdx = std::min(startIdx + m_layout.size.columnCount, (int)totalItems); + const unsigned int startIdx = line * m_layout.size.columnCount; + const unsigned int endIdx = std::min(startIdx + m_layout.size.columnCount, static_cast(totalItems)); - for (int i = startIdx; i < endIdx; ++i) { - float col = float(i % m_layout.size.columnCount); - float row = float(i / m_layout.size.columnCount); + for (unsigned int i = startIdx; i < endIdx; ++i) { + unsigned int col = i % m_layout.size.columnCount; + unsigned int row = i / m_layout.size.columnCount; ImVec2 itemPos{ startPos.x + col * m_layout.size.itemStep.x, startPos.y + row * m_layout.size.itemStep.y }; - if (i < (int)subfolders.size()) { + if (i < static_cast(subfolders.size())) { // draw folder thumbnail drawFolder( subfolders[i].first, @@ -384,7 +381,7 @@ namespace nexo::editor { ); } else { // draw asset thumbnail - int assetIdx = i - (int)subfolders.size(); + const auto assetIdx = i - static_cast(subfolders.size()); drawAsset( filtered[assetIdx], assetIdx, @@ -411,7 +408,7 @@ namespace nexo::editor { drawMenuBar(); // Calculate sizes for splitter - const float splitterWidth = 5.0f; + constexpr float splitterWidth = 5.0f; static float leftPanelWidth = 200.0f; // Default width // Left panel (folder hierarchy) @@ -437,17 +434,11 @@ namespace nexo::editor { ImGui::BeginChild("RightPanel", ImVec2(0, 0), true); // Handle file drops - if (ImGui::BeginDragDropTarget()) - { + if (ImGui::BeginDragDropTarget()) { m_showDropIndicator = true; - - // Accept external file drops (this is a placeholder - ImGui doesn't directly support OS file drops) - // The actual files come through the EventFileDrop event - + // Only to show the drop indicator ImGui::EndDragDropTarget(); - } - else - { + } else { m_showDropIndicator = false; } @@ -455,8 +446,8 @@ namespace nexo::editor { if (m_showDropIndicator || !m_pendingDroppedFiles.empty()) { ImDrawList* drawList = ImGui::GetWindowDrawList(); - ImVec2 windowPos = ImGui::GetWindowPos(); - ImVec2 windowSize = ImGui::GetWindowSize(); + const ImVec2 windowPos = ImGui::GetWindowPos(); + const ImVec2 windowSize = ImGui::GetWindowSize(); // Draw semi-transparent overlay drawList->AddRectFilled(windowPos, ImVec2(windowPos.x + windowSize.x, windowPos.y + windowSize.y), @@ -467,12 +458,12 @@ namespace nexo::editor { IM_COL32(100, 100, 255, 200), 0.0f, 0, 3.0f); // Draw text - const char* dropText = "Drop files here to import"; - ImVec2 textSize = ImGui::CalcTextSize(dropText); - ImVec2 textPos = ImVec2(windowPos.x + (windowSize.x - textSize.x) * 0.5f, + const std::string dropText = "Drop files here to import"; + const ImVec2 textSize = ImGui::CalcTextSize(dropText.c_str()); + const ImVec2 textPos = ImVec2(windowPos.x + (windowSize.x - textSize.x) * 0.5f, windowPos.y + (windowSize.y - textSize.y) * 0.5f); drawList->AddText(ImGui::GetFont(), ImGui::GetFontSize() * 1.5f, textPos, - IM_COL32(255, 255, 255, 255), dropText); + IM_COL32(255, 255, 255, 255), dropText.c_str()); } ImGui::Text(ICON_FA_FOLDER " "); @@ -487,7 +478,7 @@ namespace nexo::editor { { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ASSET_DRAG")) { - const AssetDragDropPayload* data = (const AssetDragDropPayload*)payload->Data; + const auto data = static_cast(payload->Data); assets::AssetCatalog::getInstance().moveAsset(data->id, ""); } ImGui::EndDragDropTarget(); @@ -513,7 +504,7 @@ namespace nexo::editor { { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ASSET_DRAG")) { - const AssetDragDropPayload* data = (const AssetDragDropPayload*)payload->Data; + const auto data = static_cast(payload->Data); assets::AssetCatalog::getInstance().moveAsset(data->id, fullPath); } ImGui::EndDragDropTarget(); diff --git a/editor/src/DocumentWindows/AssetManager/Thumbnail.cpp b/editor/src/DocumentWindows/AssetManager/Thumbnail.cpp deleted file mode 100644 index 453e60601..000000000 --- a/editor/src/DocumentWindows/AssetManager/Thumbnail.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//// Thumbnail.cpp /////////////////////////////////////////////////////////////// -// -// zzzzz zzz zzzzzzzzzzzzz zzzz zzzz zzzzzz zzzzz -// zzzzzzz zzz zzzz zzzz zzzz zzzz -// zzz zzz zzz zzzzzzzzzzzzz zzzz zzzz zzz -// zzz zzz zzz z zzzz zzzz zzzz zzzz -// zzz zzz zzzzzzzzzzzzz zzzz zzz zzzzzzz zzzzz -// -// Author: Mehdy MORVAN -// Date: 24/06/2025 -// Description: Source file for the thumbnail rendering of the different asset types -// -/////////////////////////////////////////////////////////////////////////////// - -#include "AssetManagerWindow.hpp" - -namespace nexo::editor { - - void AssetManagerWindow::drawTextureThumbnail( - ImDrawList *drawList, - ImTextureID textureId, - const ImVec2 &itemPos, - const ImVec2& thumbnailEnd - ) const { - if (textureId) { - const float padding = 4.0f; - ImVec2 imageStart(itemPos.x + padding, itemPos.y + padding); - ImVec2 imageEnd(thumbnailEnd.x - padding, thumbnailEnd.y - padding); - - drawList->AddImage( - textureId, - imageStart, - imageEnd, - ImVec2(0, 1), // UV0 (top-left) - ImVec2(1, 0), // UV1 (bottom-right) - IM_COL32(255, 255, 255, 255) // White tint - ); - } else - drawList->AddRectFilled(itemPos, thumbnailEnd, m_layout.color.thumbnailBg); - } -} diff --git a/editor/src/DocumentWindows/ConsoleWindow/ConsoleWindow.hpp b/editor/src/DocumentWindows/ConsoleWindow/ConsoleWindow.hpp index 3d25cb82b..172f01900 100644 --- a/editor/src/DocumentWindows/ConsoleWindow/ConsoleWindow.hpp +++ b/editor/src/DocumentWindows/ConsoleWindow/ConsoleWindow.hpp @@ -22,7 +22,7 @@ namespace nexo::editor { std::string verbosityToString(loguru::Verbosity level); loguru::Verbosity nexoLevelToLoguruLevel(LogLevel level); - const ImVec4 getVerbosityColor(loguru::Verbosity level); + ImVec4 getVerbosityColor(loguru::Verbosity level); std::string generateLogFilePath(); constexpr auto LOGURU_CALLBACK_NAME = "GEE"; @@ -57,6 +57,7 @@ namespace nexo::editor { * establishing an engine log callback that maps custom LogLevel messages to loguru verbosity levels * using nexoLevelToLoguruLevel before logging them with VLOG_F. * + * @param windowName The name of the window * @param registry The window registry used to register this console window. */ explicit ConsoleWindow(const std::string &windowName, WindowRegistry ®istry); diff --git a/editor/src/DocumentWindows/ConsoleWindow/Show.cpp b/editor/src/DocumentWindows/ConsoleWindow/Show.cpp index bec5ba2dc..3d31e6d3a 100644 --- a/editor/src/DocumentWindows/ConsoleWindow/Show.cpp +++ b/editor/src/DocumentWindows/ConsoleWindow/Show.cpp @@ -82,9 +82,9 @@ namespace nexo::editor { m_logPadding += ImGui::GetStyle().ItemSpacing.x; } - void ConsoleWindow::displayLog(loguru::Verbosity verbosity, const std::string &msg) const + void ConsoleWindow::displayLog(const loguru::Verbosity verbosity, const std::string &msg) const { - ImVec4 color = getVerbosityColor(verbosity); + const ImVec4 color = getVerbosityColor(verbosity); ImGui::PushStyleColor(ImGuiCol_Text, color); const std::string tag = verbosityToString(verbosity); diff --git a/editor/src/DocumentWindows/ConsoleWindow/Utils.cpp b/editor/src/DocumentWindows/ConsoleWindow/Utils.cpp index 5af5d9490..2b9294cfc 100644 --- a/editor/src/DocumentWindows/ConsoleWindow/Utils.cpp +++ b/editor/src/DocumentWindows/ConsoleWindow/Utils.cpp @@ -78,7 +78,7 @@ namespace nexo::editor { * @param level The verbosity level for which the corresponding color is computed. * @return ImVec4 The color associated with the specified verbosity level. */ - const ImVec4 getVerbosityColor(const loguru::Verbosity level) + ImVec4 getVerbosityColor(const loguru::Verbosity level) { ImVec4 color; @@ -107,8 +107,8 @@ namespace nexo::editor { using namespace std::chrono; // Truncate to seconds precision - auto now = floor(system_clock::now()); - zoned_time local_zoned{ current_zone(), now }; + const auto now = floor(system_clock::now()); + const zoned_time local_zoned{ current_zone(), now }; auto local_time = local_zoned.get_local_time(); std::string ts = std::format("{:%Y%m%d_%H%M%S}", local_time); diff --git a/editor/src/DocumentWindows/EditorScene/DragDrop.cpp b/editor/src/DocumentWindows/EditorScene/DragDrop.cpp index 6a0f8b956..1225c3c86 100644 --- a/editor/src/DocumentWindows/EditorScene/DragDrop.cpp +++ b/editor/src/DocumentWindows/EditorScene/DragDrop.cpp @@ -23,12 +23,12 @@ namespace nexo::editor { - void EditorScene::handleDropModel(const AssetDragDropPayload &payload) + void EditorScene::handleDropModel(const AssetDragDropPayload &payload) const { - auto modelRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + const auto modelRef = assets::AssetCatalog::getInstance().getAsset(payload.id); if (!modelRef) return; - if (auto model = modelRef.as(); model) + if (const auto model = modelRef.as(); model) { auto& sceneManager = Application::getInstance().getSceneManager(); // Create entity with the model @@ -49,12 +49,12 @@ namespace nexo::editor { } } - void EditorScene::handleDropTexture(const AssetDragDropPayload &payload) + void EditorScene::handleDropTexture(const AssetDragDropPayload &payload) const { - auto textureRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + const auto textureRef = assets::AssetCatalog::getInstance().getAsset(payload.id); if (!textureRef) return; - if (auto texture = textureRef.as(); texture) + if (const auto texture = textureRef.as(); texture) { auto [mx, my] = ImGui::GetMousePos(); mx -= m_viewportBounds[0].x; @@ -89,22 +89,22 @@ namespace nexo::editor { ActionManager::get().recordAction(std::move(action)); return; } - auto matComponent = Application::getInstance().m_coordinator->tryGetComponent(entityId); + const auto matComponent = Application::m_coordinator->tryGetComponent(entityId); if (!matComponent) return; - auto material = matComponent->get().material.lock(); + const auto material = matComponent->get().material.lock(); if (!material) return; material->getData()->albedoTexture = texture; } } - void EditorScene::handleDropMaterial(const AssetDragDropPayload &payload) + void EditorScene::handleDropMaterial(const AssetDragDropPayload &payload) const { - auto materialRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + const auto materialRef = assets::AssetCatalog::getInstance().getAsset(payload.id); if (!materialRef) return; - if (auto material = materialRef.as(); material) + if (const auto material = materialRef.as(); material) { auto [mx, my] = ImGui::GetMousePos(); mx -= m_viewportBounds[0].x; @@ -119,7 +119,7 @@ namespace nexo::editor { const int entityId = sampleEntityTexture(mx, my); if (entityId == -1) return; - auto matComponent = Application::getInstance().m_coordinator->tryGetComponent(entityId); + const auto matComponent = Application::m_coordinator->tryGetComponent(entityId); if (!matComponent) return; matComponent->get().material = material; @@ -148,11 +148,11 @@ namespace nexo::editor { if (entityId != -1 && static_cast(entityId) != m_entityHovered) { m_entityHovered = static_cast(entityId); - Application::getInstance().m_coordinator->addComponent(m_entityHovered, components::SelectedTag{}); + Application::m_coordinator->addComponent(m_entityHovered, components::SelectedTag{}); } if (entityId == -1 && m_entityHovered != ecs::INVALID_ENTITY) { - Application::getInstance().m_coordinator->removeComponent(m_entityHovered); + Application::m_coordinator->removeComponent(m_entityHovered); m_entityHovered = ecs::INVALID_ENTITY; } if (!assetPayload->IsDelivery()) @@ -160,7 +160,7 @@ namespace nexo::editor { return; } if (m_entityHovered != ecs::INVALID_ENTITY) - Application::getInstance().m_coordinator->removeComponent(m_entityHovered); + Application::m_coordinator->removeComponent(m_entityHovered); m_entityHovered = ecs::INVALID_ENTITY; const auto& payload = *static_cast(assetPayload->Data); diff --git a/editor/src/DocumentWindows/EditorScene/EditorScene.hpp b/editor/src/DocumentWindows/EditorScene/EditorScene.hpp index 779ff807f..9af23fc1e 100644 --- a/editor/src/DocumentWindows/EditorScene/EditorScene.hpp +++ b/editor/src/DocumentWindows/EditorScene/EditorScene.hpp @@ -22,7 +22,6 @@ #include "core/scene/SceneManager.hpp" #include "../PopupManager.hpp" #include "ImNexo/Widgets.hpp" -#include #include "DocumentWindows/AssetManager/AssetManagerWindow.hpp" namespace nexo::editor @@ -284,11 +283,11 @@ namespace nexo::editor void setupGizmoContext(const components::CameraComponent& camera) const; float* getSnapSettingsForOperation(ImGuizmo::OPERATION operation); static void captureInitialTransformStates(const std::vector& entities); - void applyTransformToEntities( + static void applyTransformToEntities( ecs::Entity sourceEntity, const glm::mat4& oldWorldMatrix, const glm::mat4& newWorldMatrix, - const std::vector& targetEntities) const; + const std::vector& targetEntities) ; static void createTransformUndoActions(const std::vector& entities); static bool s_wasUsingGizmo; static ImGuizmo::OPERATION s_lastOperation; @@ -307,13 +306,13 @@ namespace nexo::editor void handleSelection(); void handleDropTarget(); - void handleDropModel(const AssetDragDropPayload &payload); - void handleDropTexture(const AssetDragDropPayload &payload); - void handleDropMaterial(const AssetDragDropPayload &payload); + void handleDropModel(const AssetDragDropPayload &payload) const; + void handleDropTexture(const AssetDragDropPayload &payload) const; + void handleDropMaterial(const AssetDragDropPayload &payload) const; int sampleEntityTexture(float mx, float my) const; - ecs::Entity findRootParent(ecs::Entity entityId) const; - void selectEntityHierarchy(ecs::Entity entityId, const bool isCtrlPressed); - void selectModelChildren(const std::vector& children, const bool isCtrlPressed); + static ecs::Entity findRootParent(ecs::Entity entityId); + void selectEntityHierarchy(ecs::Entity entityId, bool isCtrlPressed); + void selectModelChildren(const std::vector& children, bool isCtrlPressed); void updateSelection(int entityId, bool isShiftPressed, bool isCtrlPressed); void updateWindowState(); diff --git a/editor/src/DocumentWindows/EditorScene/Gizmo.cpp b/editor/src/DocumentWindows/EditorScene/Gizmo.cpp index 153d3046e..10e5202a6 100644 --- a/editor/src/DocumentWindows/EditorScene/Gizmo.cpp +++ b/editor/src/DocumentWindows/EditorScene/Gizmo.cpp @@ -16,7 +16,6 @@ #include "components/Parent.hpp" #include "context/Selector.hpp" #include "context/ActionManager.hpp" -#include "math/Matrix.hpp" #include #define GLM_ENABLE_EXPERIMENTAL @@ -61,22 +60,22 @@ namespace nexo::editor { ImGuizmo::Enable(true); } - static glm::mat4 getEntityParentWorldMatrix(ecs::Entity entity) + static glm::mat4 getEntityParentWorldMatrix(const ecs::Entity entity) { const auto& coord = nexo::Application::m_coordinator; - auto parentComponent = coord->tryGetComponent(entity); + const auto parentComponent = coord->tryGetComponent(entity); if (!parentComponent) - return glm::mat4(1.0f); // No parent, return identity + return {1.0f}; // No parent, return identity - ecs::Entity parentEntity = parentComponent->get().parent; + const ecs::Entity parentEntity = parentComponent->get().parent; if (parentEntity == ecs::INVALID_ENTITY) - return glm::mat4(1.0f); // No parent, return identity + return {1.0f}; // No parent, return identity - auto parentTransform = coord->tryGetComponent(parentEntity); + const auto parentTransform = coord->tryGetComponent(parentEntity); if (!parentTransform) - return glm::mat4(1.0f); // Parent has no transform, return identity + return {1.0f}; // Parent has no transform, return identity return parentTransform->get().worldMatrix; } @@ -88,31 +87,30 @@ namespace nexo::editor { glm::scale(glm::mat4(1.0f), transform.size); } - static void updateEntityWorldMatrix(ecs::Entity entity) + static void updateEntityWorldMatrix(const ecs::Entity entity) { const auto& coord = nexo::Application::m_coordinator; - auto transform = coord->tryGetComponent(entity); + const auto transform = coord->tryGetComponent(entity); - if (!transform) { + if (!transform) return; - } // Get parent's world matrix - glm::mat4 parentWorldMatrix = getEntityParentWorldMatrix(entity); + const glm::mat4 parentWorldMatrix = getEntityParentWorldMatrix(entity); // Calculate local matrix - glm::mat4 localMatrix = calculateWorldMatrix(transform->get()); + const glm::mat4 localMatrix = calculateWorldMatrix(transform->get()); // Update world matrix transform->get().worldMatrix = parentWorldMatrix * localMatrix; } - static void updateEntityWorldMatrixRecursive(ecs::Entity entity) + static void updateEntityWorldMatrixRecursive(const ecs::Entity entity) { const auto& coord = nexo::Application::m_coordinator; - auto parentComponent = coord->tryGetComponent(entity); + const auto parentComponent = coord->tryGetComponent(entity); if (parentComponent) { - ecs::Entity parentEntity = parentComponent->get().parent; + const ecs::Entity parentEntity = parentComponent->get().parent; if (parentEntity != ecs::INVALID_ENTITY) { updateEntityWorldMatrixRecursive(parentEntity); } @@ -120,12 +118,12 @@ namespace nexo::editor { updateEntityWorldMatrix(entity); } - static void updateLocalTransformFromWorld(components::TransformComponent& transform, const glm::mat4& worldMatrix, ecs::Entity entity) + static void updateLocalTransformFromWorld(components::TransformComponent& transform, const glm::mat4& worldMatrix, const ecs::Entity entity) { - glm::mat4 parentWorldMatrix = getEntityParentWorldMatrix(entity); + const glm::mat4 parentWorldMatrix = getEntityParentWorldMatrix(entity); // Calculate local matrix by inverting parent world matrix and multiplying by entity's world matrix - glm::mat4 localMatrix = glm::inverse(parentWorldMatrix) * worldMatrix; + const glm::mat4 localMatrix = glm::inverse(parentWorldMatrix) * worldMatrix; glm::vec3 skew; glm::vec4 perspective; @@ -169,17 +167,17 @@ namespace nexo::editor { const ecs::Entity sourceEntity, const glm::mat4& oldWorldMatrix, const glm::mat4& newWorldMatrix, - const std::vector& targetEntities) const + const std::vector& targetEntities) { - const auto& coord = nexo::Application::m_coordinator; + const auto& coord = Application::m_coordinator; - glm::mat4 deltaMatrix = newWorldMatrix * glm::inverse(oldWorldMatrix); + const glm::mat4 deltaMatrix = newWorldMatrix * glm::inverse(oldWorldMatrix); // Apply to all selected entities except the source for (const auto& entity : targetEntities) { if (entity == static_cast(sourceEntity)) continue; - auto entityTransform = coord->tryGetComponent(entity); + const auto entityTransform = coord->tryGetComponent(entity); if (!entityTransform) continue; // Apply world space delta and convert back to local space @@ -198,7 +196,7 @@ namespace nexo::editor { void EditorScene::createTransformUndoActions(const std::vector& entities) { - const auto& coord = nexo::Application::m_coordinator; + const auto& coord = Application::m_coordinator; auto& actionManager = ActionManager::get(); if (entities.size() > 1) { @@ -249,7 +247,7 @@ namespace nexo::editor { void EditorScene::renderGizmo() { - const auto& coord = nexo::Application::m_coordinator; + const auto& coord = Application::m_coordinator; auto const& selector = Selector::get(); // Skip if no valid selection @@ -286,20 +284,20 @@ namespace nexo::editor { glm::mat4 projectionMatrix = camera.getProjectionMatrix(); // 1) M₀ = parentWorld * T(pos) * R(quat) * S(size) - glm::mat4 parentWorld = getEntityParentWorldMatrix(primaryEntity); - glm::mat4 Tpos = glm::translate(glm::mat4(1.0f), primaryTransform->get().pos); - glm::mat4 Rrot = glm::toMat4(primaryTransform->get().quat); - glm::mat4 Sscale = glm::scale(glm::mat4(1.0f), primaryTransform->get().size); - glm::mat4 M0 = parentWorld * Tpos * Rrot * Sscale; + const glm::mat4 parentWorld = getEntityParentWorldMatrix(primaryEntity); + const glm::mat4 Tpos = glm::translate(glm::mat4(1.0f), primaryTransform->get().pos); + const glm::mat4 Rrot = glm::toMat4(primaryTransform->get().quat); + const glm::mat4 Sscale = glm::scale(glm::mat4(1.0f), primaryTransform->get().size); + const glm::mat4 M0 = parentWorld * Tpos * Rrot * Sscale; // 2) “centroid offset” = T(centroidLocal) - glm::mat4 C_offset = glm::translate(glm::mat4(1.0f), primaryTransform->get().localCenter); + const glm::mat4 C_offset = glm::translate(glm::mat4(1.0f), primaryTransform->get().localCenter); // 3) M1 = M0 * C_offset glm::mat4 worldTransformMatrix = M0 * C_offset; // (We’ll need “M₀” again after manipulation for decomposing back.) - glm::mat4 originalWorldMatrix_ModelOrigin = M0; + const glm::mat4 originalWorldMatrix_ModelOrigin = M0; if (!ImGuizmo::IsUsing()) s_lastOperation = getActiveGuizmoOperation(); @@ -319,24 +317,24 @@ namespace nexo::editor { snap ); - bool isUsingGizmo = ImGuizmo::IsUsing(); + const bool isUsingGizmo = ImGuizmo::IsUsing(); if (isUsingGizmo) { // Disable camera movement during manipulation camera.active = false; - glm::mat4 newWorldMatrix_Centroid = worldTransformMatrix; - glm::mat4 invCentroidOffset = glm::inverse(C_offset); - glm::mat4 newWorldMatrix_ModelOrigin = newWorldMatrix_Centroid * invCentroidOffset; + const glm::mat4 newWorldMatrix_Centroid = worldTransformMatrix; + const glm::mat4 invCentroidOffset = glm::inverse(C_offset); + const glm::mat4 newWorldMatrix_ModelOrigin = newWorldMatrix_Centroid * invCentroidOffset; // Update the primary entity's local transform based on the new world transform updateLocalTransformFromWorld(primaryTransform->get(), newWorldMatrix_ModelOrigin, primaryEntity); - glm::mat4 deltaMatrix = newWorldMatrix_ModelOrigin * glm::inverse(originalWorldMatrix_ModelOrigin); + const glm::mat4 deltaMatrix = newWorldMatrix_ModelOrigin * glm::inverse(originalWorldMatrix_ModelOrigin); - for (auto entity : selectedEntities) { + for (const auto entity : selectedEntities) { if (static_cast(entity) == primaryEntity) continue; - auto tComp = coord->tryGetComponent(entity); + const auto tComp = coord->tryGetComponent(entity); if (!tComp) continue; // “OtherEntity_world₀” = tComp->worldMatrix diff --git a/editor/src/DocumentWindows/EditorScene/Init.cpp b/editor/src/DocumentWindows/EditorScene/Init.cpp index 492acde65..04b39f410 100644 --- a/editor/src/DocumentWindows/EditorScene/Init.cpp +++ b/editor/src/DocumentWindows/EditorScene/Init.cpp @@ -23,7 +23,6 @@ #include "renderPasses/OutlinePass.hpp" #include "assets/AssetImporter.hpp" #include "Path.hpp" -#include "components/SceneComponents.hpp" namespace nexo::editor { @@ -47,11 +46,11 @@ namespace nexo::editor framebufferSpecs.width = static_cast(m_contentSize.x); framebufferSpecs.height = static_cast(m_contentSize.y); const auto renderTarget = renderer::NxFramebuffer::create(framebufferSpecs); - m_editorCamera = CameraFactory::createPerspectiveCamera({0.0f, 36.0f, 25.0f}, + m_editorCamera = static_cast(CameraFactory::createPerspectiveCamera({0.0f, 36.0f, 25.0f}, static_cast(m_contentSize.x), static_cast(m_contentSize.y), - renderTarget); - auto& cameraComponent = app.m_coordinator->getComponent(m_editorCamera); + renderTarget)); + auto& cameraComponent = Application::m_coordinator->getComponent(m_editorCamera); cameraComponent.render = true; auto maskPass = std::make_shared( static_cast(m_contentSize.x), @@ -111,7 +110,7 @@ namespace nexo::editor for (int i = 0; i < numLights; ++i) { constexpr float radius = 30.0f; - const float angle = glm::radians(360.0f / numLights * i); + const float angle = glm::radians(360.0f / numLights * static_cast(i)); const glm::vec3 position = center + glm::vec3(radius * cos(angle), 0.0f, radius * sin(angle)); const auto light = LightFactory::createPointLight(position, colors[i % colors.size()], 0.01, 0.0010); scene.addEntity(light); @@ -172,7 +171,7 @@ namespace nexo::editor default: throw std::runtime_error("Unsupported shape type for entity creation."); } - JPH::BodyID bodyId = app.getPhysicsSystem()->createBodyFromShape(entity, app.m_coordinator->getComponent(entity), shapeType, motionType); + JPH::BodyID bodyId = app.getPhysicsSystem()->createBodyFromShape(entity, Application::m_coordinator->getComponent(entity), shapeType, motionType); if (bodyId.IsInvalid()) { LOG(NEXO_ERROR, "Failed to create physics body for entity {}", entity); } @@ -270,7 +269,7 @@ namespace nexo::editor constexpr float startY = 14.0f; constexpr float spacing = 3.0f; float offsetX = (row % 2 == 0) ? 0.0f : spacing / 2.0f; - glm::vec3 pos = {col * spacing + startX + offsetX, startY + row * 1.2f, 0.0f}; + glm::vec3 pos = {static_cast(col) * spacing + startX + offsetX, startY + static_cast(row) * 1.2f, 0.0f}; auto maxFactor = static_cast(totalRows * cols); float gradientFactor = static_cast((row + 1) * (col + 1)) / maxFactor; glm::vec4 color = mix(glm::vec4(0.0f, 0.77f, 0.95f, 1.0f), glm::vec4(0.83f, 0.14f, 0.67f, 1.0f), gradientFactor); diff --git a/editor/src/DocumentWindows/EditorScene/Shortcuts.cpp b/editor/src/DocumentWindows/EditorScene/Shortcuts.cpp index 836b199d3..95758e264 100644 --- a/editor/src/DocumentWindows/EditorScene/Shortcuts.cpp +++ b/editor/src/DocumentWindows/EditorScene/Shortcuts.cpp @@ -40,7 +40,7 @@ namespace nexo::editor { void EditorScene::selectAllCallback() { auto &selector = Selector::get(); - auto &app = nexo::getApp(); + auto &app = getApp(); const auto &scene = app.getSceneManager().getScene(m_sceneId); selector.clearSelection(); @@ -81,7 +81,7 @@ namespace nexo::editor { { auto &selector = Selector::get(); const auto &selectedEntities = selector.getSelectedEntities(); - auto &app = nexo::getApp(); + auto &app = getApp(); auto& actionManager = ActionManager::get(); if (selectedEntities.size() > 1) { auto actionGroup = ActionManager::createActionGroup(); diff --git a/editor/src/DocumentWindows/EditorScene/Show.cpp b/editor/src/DocumentWindows/EditorScene/Show.cpp index 50495cff4..463defe52 100644 --- a/editor/src/DocumentWindows/EditorScene/Show.cpp +++ b/editor/src/DocumentWindows/EditorScene/Show.cpp @@ -163,11 +163,11 @@ namespace nexo::editor if (m_shouldSplitDock && !m_gameWindowNameToSplit.empty()) { const std::string currentWindowName = m_windowName; - ImGuiWindow *currentImGuiWindow = ImGui::FindWindowByName((currentWindowName + NEXO_WND_USTRID_DEFAULT_SCENE + std::to_string(m_sceneId)).c_str()); + const ImGuiWindow *currentImGuiWindow = ImGui::FindWindowByName((currentWindowName + NEXO_WND_USTRID_DEFAULT_SCENE + std::to_string(m_sceneId)).c_str()); if (currentImGuiWindow && currentImGuiWindow->DockId) { - ImGuiID editorDockId = currentImGuiWindow->DockId; + const ImGuiID editorDockId = currentImGuiWindow->DockId; ImGuiID rightNode, leftNode; if (ImGui::DockBuilderSplitNode(editorDockId, ImGuiDir_Right, 0.5f, &rightNode, &leftNode)) diff --git a/editor/src/DocumentWindows/EditorScene/Toolbar.cpp b/editor/src/DocumentWindows/EditorScene/Toolbar.cpp index 468e1d7a7..498485b75 100644 --- a/editor/src/DocumentWindows/EditorScene/Toolbar.cpp +++ b/editor/src/DocumentWindows/EditorScene/Toolbar.cpp @@ -33,19 +33,19 @@ namespace nexo::editor { const std::string gameWindowName = std::format("Game View - {}{}{}", m_sceneUuid, NEXO_WND_USTRID_GAME_WINDOW, m_sceneId); // Check if game window already exists - if (auto gameWindow = editor.getWindow(gameWindowName).lock()) { + if (const auto gameWindow = editor.getWindow(gameWindowName).lock()) { // Window exists, just make it visible gameWindow->setOpened(true); } else { // Get current EditorScene window's dock ID for docking the game window const std::string currentWindowName = m_windowName; - ImGuiWindow* currentImGuiWindow = ImGui::FindWindowByName(currentWindowName.c_str()); + const ImGuiWindow* currentImGuiWindow = ImGui::FindWindowByName(currentWindowName.c_str()); if (currentImGuiWindow && currentImGuiWindow->DockId) { // Create new game window editor.registerWindow(gameWindowName); - if (auto newGameWindow = editor.getWindow(gameWindowName).lock()) { + if (const auto newGameWindow = editor.getWindow(gameWindowName).lock()) { // Configure the game window newGameWindow->setSceneId(static_cast(m_sceneId)); newGameWindow->setSceneUuid(m_sceneUuid); @@ -70,7 +70,7 @@ namespace nexo::editor { void EditorScene::initialToolbarSetup(const float buttonWidth) const { ImVec2 toolbarPos = m_windowPos; - ImVec2 contentMin = ImGui::GetWindowContentRegionMin(); + const ImVec2 contentMin = ImGui::GetWindowContentRegionMin(); toolbarPos.x += contentMin.x + 10.0f; toolbarPos.y += contentMin.y + 20.0f; diff --git a/editor/src/DocumentWindows/EditorScene/Update.cpp b/editor/src/DocumentWindows/EditorScene/Update.cpp index 3b6753ff8..cf1e1af6a 100644 --- a/editor/src/DocumentWindows/EditorScene/Update.cpp +++ b/editor/src/DocumentWindows/EditorScene/Update.cpp @@ -64,7 +64,7 @@ namespace nexo::editor { } } - ecs::Entity EditorScene::findRootParent(ecs::Entity entityId) const + ecs::Entity EditorScene::findRootParent(const ecs::Entity entityId) { const auto &coord = Application::m_coordinator; ecs::Entity currentEntity = entityId; @@ -90,7 +90,7 @@ namespace nexo::editor { auto &selector = Selector::get(); if (selectWholeHierarchy) { - ecs::Entity rootEntity = findRootParent(entityId); + const ecs::Entity rootEntity = findRootParent(entityId); if (!isShiftPressed && !isCtrlPressed) selector.clearSelection(); @@ -111,19 +111,19 @@ namespace nexo::editor { selector.setSelectedScene(m_sceneId); } - void EditorScene::selectEntityHierarchy(ecs::Entity entityId, const bool isCtrlPressed) + void EditorScene::selectEntityHierarchy(const ecs::Entity entityId, const bool isCtrlPressed) { const auto &coord = Application::m_coordinator; const auto uuid = coord->tryGetComponent(entityId); if (uuid) { - const SelectionType selType = getSelectionType(entityId); + const SelectionType selType = getSelectionType(static_cast(entityId)); auto &selector = Selector::get(); if (isCtrlPressed) - selector.toggleSelection(uuid->get().uuid, entityId, selType); + selector.toggleSelection(uuid->get().uuid, static_cast(entityId), selType); else - selector.addToSelection(uuid->get().uuid, entityId, selType); + selector.addToSelection(uuid->get().uuid, static_cast(entityId), selType); } if (coord->entityHasComponent(entityId)) { diff --git a/editor/src/DocumentWindows/EntityProperties/AmbientLightProperty.cpp b/editor/src/DocumentWindows/EntityProperties/AmbientLightProperty.cpp index b53fc5f5e..98cb1623f 100644 --- a/editor/src/DocumentWindows/EntityProperties/AmbientLightProperty.cpp +++ b/editor/src/DocumentWindows/EntityProperties/AmbientLightProperty.cpp @@ -30,7 +30,7 @@ namespace nexo::editor { if (ImNexo::Header("##AmbientNode", "Ambient light")) { - auto ambientComponentCopy = ambientComponent; + const auto ambientComponentCopy = ambientComponent; ImNexo::resetItemStates(); ImNexo::Ambient(ambientComponent); if (ImNexo::isItemActivated()) { diff --git a/editor/src/DocumentWindows/EntityProperties/MaterialProperty.cpp b/editor/src/DocumentWindows/EntityProperties/MaterialProperty.cpp index bbea4f88e..bf5a9544b 100644 --- a/editor/src/DocumentWindows/EntityProperties/MaterialProperty.cpp +++ b/editor/src/DocumentWindows/EntityProperties/MaterialProperty.cpp @@ -26,7 +26,7 @@ namespace nexo::editor { - void MaterialProperty::cleanupPopup(assets::AssetRef &materialRef, utils::ScenePreviewOut &out) const + void MaterialProperty::cleanupPopup(assets::AssetRef &materialRef, utils::ScenePreviewOut &out) { assets::AssetCatalog::getInstance().deleteAsset(materialRef); materialRef = nullptr; @@ -37,7 +37,7 @@ namespace nexo::editor { ImGui::CloseCurrentPopup(); } - void MaterialProperty::createMaterialPopup(const ecs::Entity entity) const + void MaterialProperty::createMaterialPopup(const ecs::Entity entity) { ImGui::Text("Create New Material"); ImGui::Separator(); @@ -70,7 +70,7 @@ namespace nexo::editor { ImGui::InputText("Name", materialName, IM_ARRAYSIZE(materialName)); ImGui::Spacing(); - auto material = materialRef.lock(); + const auto material = materialRef.lock(); components::Material& materialData = *material->getData(); if (ImNexo::MaterialInspector(materialData)) @@ -86,14 +86,13 @@ namespace nexo::editor { if (!out.sceneGenerated) utils::genScenePreview("Material Creation Scene", {previewWidth - 4, totalHeight}, entity, out); - Application::SceneInfo sceneInfo{out.sceneId, RenderingType::FRAMEBUFFER}; + const Application::SceneInfo sceneInfo{out.sceneId, RenderingType::FRAMEBUFFER}; auto &materialComp = Application::m_coordinator->getComponent(out.entityCopy); materialComp.material = materialRef; Application::getInstance().run(sceneInfo); const auto &cameraComp = Application::m_coordinator->getComponent(out.cameraId); const unsigned int textureId = cameraComp.m_renderTarget->getColorAttachmentId(); - const float aspectRatio = (previewWidth - 8) / totalHeight; const float displayHeight = totalHeight - 20; @@ -121,14 +120,14 @@ namespace nexo::editor { } const auto &sceneTag = Application::m_coordinator->getComponent(entity); std::string sceneName = Application::getInstance().getSceneManager().getScene(sceneTag.id).getName(); - auto hashPos = sceneName.find('#'); + const auto hashPos = sceneName.find('#'); if (hashPos != std::string::npos) { sceneName.erase(hashPos); } - assets::AssetLocation finalLocation(std::format("{}@{}/", name, sceneName)); + const assets::AssetLocation finalLocation(std::format("{}@{}/", name, sceneName)); // Create a new material asset by copying the preview material - auto newMaterialRef = assets::AssetCatalog::getInstance().createAsset( + const auto newMaterialRef = assets::AssetCatalog::getInstance().createAsset( finalLocation, std::make_unique(*materialRef.lock()->getData()) ); @@ -146,7 +145,7 @@ namespace nexo::editor { } - void MaterialProperty::show(ecs::Entity entity) + void MaterialProperty::show(const ecs::Entity entity) { if (Application::m_coordinator->entityHasComponent(entity) || Application::m_coordinator->entityHasComponent(entity) || @@ -155,7 +154,7 @@ namespace nexo::editor { const auto &materialComponent = Application::getEntityComponent(entity); if (ImNexo::Header("##MaterialNode", "Material Component")) { - ImTextureID textureID = ThumbnailCache::getInstance().getMaterialThumbnail(materialComponent.material); + const ImTextureID textureID = ThumbnailCache::getInstance().getMaterialThumbnail(materialComponent.material); ImNexo::Image(textureID, ImVec2(64, 64)); ImGui::SameLine(); diff --git a/editor/src/DocumentWindows/EntityProperties/MaterialProperty.hpp b/editor/src/DocumentWindows/EntityProperties/MaterialProperty.hpp index 6f6321e47..32a89928b 100644 --- a/editor/src/DocumentWindows/EntityProperties/MaterialProperty.hpp +++ b/editor/src/DocumentWindows/EntityProperties/MaterialProperty.hpp @@ -22,7 +22,7 @@ namespace nexo::editor { struct MaterialInspectorData { - ecs::Entity m_selectedEntity; + ecs::Entity m_selectedEntity{}; assets::AssetRef material; }; @@ -32,8 +32,8 @@ namespace nexo::editor { void show(ecs::Entity entity) override; private: - void createMaterialPopup(const ecs::Entity entity) const; - void cleanupPopup(assets::AssetRef &materialRef, utils::ScenePreviewOut &out) const; + static void createMaterialPopup(ecs::Entity entity); + static void cleanupPopup(assets::AssetRef &materialRef, utils::ScenePreviewOut &out); PopupManager m_popupManager; }; } diff --git a/editor/src/DocumentWindows/EntityProperties/RenderProperty.cpp b/editor/src/DocumentWindows/EntityProperties/RenderProperty.cpp index 49745c6dc..3294c9288 100644 --- a/editor/src/DocumentWindows/EntityProperties/RenderProperty.cpp +++ b/editor/src/DocumentWindows/EntityProperties/RenderProperty.cpp @@ -15,17 +15,13 @@ #include #include "RenderProperty.hpp" -#include "AEntityProperty.hpp" #include "Application.hpp" -#include "DocumentWindows/PopupManager.hpp" #include "Framebuffer.hpp" #include "components/Light.hpp" #include "context/actions/EntityActions.hpp" #include "utils/ScenePreview.hpp" #include "components/Camera.hpp" #include "components/Render.hpp" -#include "DocumentWindows/InspectorWindow/InspectorWindow.hpp" -#include "DocumentWindows/MaterialInspector/MaterialInspector.hpp" #include "context/ActionManager.hpp" #include "ImNexo/Elements.hpp" #include "ImNexo/Components.hpp" @@ -156,7 +152,7 @@ namespace nexo::editor { ImGui::Text("Type"); ImGui::SameLine(0, 12); - std::string primitiveTypeStr = getPrimitiveTypeName(renderComponent.type); + const std::string primitiveTypeStr = getPrimitiveTypeName(renderComponent.type); ImGui::Text("%s", primitiveTypeStr.c_str()); ImGui::TreePop(); diff --git a/editor/src/DocumentWindows/EntityProperties/TypeErasedProperty.cpp b/editor/src/DocumentWindows/EntityProperties/TypeErasedProperty.cpp index 77ad22df2..fc56c8e9f 100644 --- a/editor/src/DocumentWindows/EntityProperties/TypeErasedProperty.cpp +++ b/editor/src/DocumentWindows/EntityProperties/TypeErasedProperty.cpp @@ -82,7 +82,7 @@ namespace nexo::editor { } } - void TypeErasedProperty::show(ecs::Entity entity) + void TypeErasedProperty::show(const ecs::Entity entity) { if (!m_description) { ImGui::Text("No component description available for type %d", m_componentType); @@ -91,7 +91,7 @@ namespace nexo::editor { const auto& coordinator = Application::m_coordinator; - auto componentData = static_cast(coordinator->tryGetComponentById(m_componentType, entity)); + const auto componentData = static_cast(coordinator->tryGetComponentById(m_componentType, entity)); if (!componentData) { ImGui::Text("Entity %d does not have component type %d", entity, m_componentType); return; @@ -101,7 +101,7 @@ namespace nexo::editor { { for (const auto& field : m_description->fields) { // Move to pointer to next field data - auto currentComponentData = componentData + field.offset; + const auto currentComponentData = componentData + field.offset; // Show the field in the UI showField(field, currentComponentData); } diff --git a/editor/src/DocumentWindows/GameWindow/GameWindow.cpp b/editor/src/DocumentWindows/GameWindow/GameWindow.cpp index cb3bd4124..c94573bf5 100644 --- a/editor/src/DocumentWindows/GameWindow/GameWindow.cpp +++ b/editor/src/DocumentWindows/GameWindow/GameWindow.cpp @@ -16,7 +16,7 @@ namespace nexo::editor { - void GameWindow::setSceneId(unsigned int sceneId) + void GameWindow::setSceneId(const unsigned int sceneId) { m_sceneId = sceneId; } diff --git a/editor/src/DocumentWindows/GameWindow/GameWindow.hpp b/editor/src/DocumentWindows/GameWindow/GameWindow.hpp index 9588fe154..455eefff1 100644 --- a/editor/src/DocumentWindows/GameWindow/GameWindow.hpp +++ b/editor/src/DocumentWindows/GameWindow/GameWindow.hpp @@ -17,7 +17,6 @@ #include "ADocumentWindow.hpp" #include "../PopupManager.hpp" #include "ecs/Definitions.hpp" -#include #include namespace nexo::editor diff --git a/editor/src/DocumentWindows/GameWindow/Setup.cpp b/editor/src/DocumentWindows/GameWindow/Setup.cpp index 46a760f0b..cbfe93242 100644 --- a/editor/src/DocumentWindows/GameWindow/Setup.cpp +++ b/editor/src/DocumentWindows/GameWindow/Setup.cpp @@ -17,8 +17,6 @@ #include "ecs/Coordinator.hpp" #include "components/Camera.hpp" #include "components/Transform.hpp" -#include "components/SceneComponents.hpp" -#include "components/Name.hpp" #include "core/scene/SceneManager.hpp" #include "renderer/Framebuffer.hpp" #include "CameraFactory.hpp" diff --git a/editor/src/DocumentWindows/GameWindow/Show.cpp b/editor/src/DocumentWindows/GameWindow/Show.cpp index 358ec0f81..8f8de2355 100644 --- a/editor/src/DocumentWindows/GameWindow/Show.cpp +++ b/editor/src/DocumentWindows/GameWindow/Show.cpp @@ -14,15 +14,11 @@ #include "GameWindow.hpp" #include "IconsFontAwesome.h" -#include "ImNexo/ImNexo.hpp" #include "ImNexo/Elements.hpp" #include "ImNexo/Widgets.hpp" #include "Application.hpp" #include "ecs/Coordinator.hpp" #include "components/Camera.hpp" -#include "components/Transform.hpp" -#include "components/RenderContext.hpp" -#include "core/scene/SceneManager.hpp" #include #include #include @@ -37,7 +33,7 @@ namespace nexo::editor ImGui::SetNextWindowSize(ImVec2(1280, 720), ImGuiCond_FirstUseEver); // Begin the window - std::string windowTitle = std::format("Game View - {}###GameWindow{}", m_sceneUuid, m_sceneId); + const std::string windowTitle = std::format("Game View - {}###GameWindow{}", m_sceneUuid, m_sceneId); ImGui::Begin(windowTitle.c_str(), &m_opened, ImGuiWindowFlags_NoCollapse); // Call beginRender to handle docking and state tracking @@ -56,14 +52,14 @@ namespace nexo::editor constexpr float buttonWidth = 35.0f; constexpr float buttonHeight = 35.0f; - ImVec2 windowContentMin = ImGui::GetWindowContentRegionMin(); + const ImVec2 windowContentMin = ImGui::GetWindowContentRegionMin(); ImVec2 toolbarPos = m_windowPos; toolbarPos.x += windowContentMin.x + 10.0f; toolbarPos.y += 20.0f; ImGui::SetCursorScreenPos(toolbarPos); - const auto toolbarSize = ImVec2(200.0f, 50.0f); + constexpr auto toolbarSize = ImVec2(200.0f, 50.0f); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.1f, 0.1f, 0.1f, 0.0f)); ImGui::BeginChild("##GameToolbarOverlay", toolbarSize, 0, @@ -131,7 +127,7 @@ namespace nexo::editor } // Try to get camera component - entity might have been deleted - auto cameraCompOpt = coordinator.template tryGetComponent(m_gameCamera); + const auto cameraCompOpt = coordinator.tryGetComponent(m_gameCamera); if (!cameraCompOpt) { // Camera entity was deleted, reset to invalid diff --git a/editor/src/DocumentWindows/GameWindow/Update.cpp b/editor/src/DocumentWindows/GameWindow/Update.cpp index 3330b1ae7..82ea6a4fc 100644 --- a/editor/src/DocumentWindows/GameWindow/Update.cpp +++ b/editor/src/DocumentWindows/GameWindow/Update.cpp @@ -49,7 +49,7 @@ namespace nexo::editor if (m_gameCamera != ecs::INVALID_ENTITY) { // Try to get the camera component - auto cameraCompOpt = coordinator.tryGetComponent(m_gameCamera); + const auto cameraCompOpt = coordinator.tryGetComponent(m_gameCamera); if (cameraCompOpt) { // Disable rendering diff --git a/editor/src/DocumentWindows/InspectorWindow/InspectorWindow.hpp b/editor/src/DocumentWindows/InspectorWindow/InspectorWindow.hpp index 746de90a0..cb69279e6 100644 --- a/editor/src/DocumentWindows/InspectorWindow/InspectorWindow.hpp +++ b/editor/src/DocumentWindows/InspectorWindow/InspectorWindow.hpp @@ -102,7 +102,7 @@ namespace nexo::editor { template bool getSubInspectorVisibility() const { - auto it = m_subInspectorVisibility.find(std::type_index(typeid(T))); + const auto it = m_subInspectorVisibility.find(std::type_index(typeid(T))); return (it != m_subInspectorVisibility.end()) ? it->second : false; } @@ -135,15 +135,14 @@ namespace nexo::editor { template std::optional getSubInspectorData() const { - auto it = m_subInspectorData.find(std::type_index(typeid(WindowType))); + const auto it = m_subInspectorData.find(std::type_index(typeid(WindowType))); if (it != m_subInspectorData.end()) { if (auto ptr = std::any_cast(&it->second)) { return *ptr; - } else { - LOG(NEXO_ERROR, "Failed to cast sub-inspector data for type {}", - typeid(WindowType).name()); - return std::nullopt; } + LOG(NEXO_ERROR, "Failed to cast sub-inspector data for type {}", + typeid(WindowType).name()); + return std::nullopt; } return std::nullopt; } diff --git a/editor/src/DocumentWindows/InspectorWindow/Show.cpp b/editor/src/DocumentWindows/InspectorWindow/Show.cpp index 853d5ca99..00d15d5af 100644 --- a/editor/src/DocumentWindows/InspectorWindow/Show.cpp +++ b/editor/src/DocumentWindows/InspectorWindow/Show.cpp @@ -28,7 +28,7 @@ namespace nexo::editor { std::string uiHandle = selector.getUiHandle(scene.getUuid(), ""); // Remove the icon prefix - if (size_t spacePos = uiHandle.find(' '); spacePos != std::string::npos) + if (const size_t spacePos = uiHandle.find(' '); spacePos != std::string::npos) uiHandle = uiHandle.substr(spacePos + 1); if (ImNexo::Header("##SceneNode", uiHandle)) diff --git a/editor/src/DocumentWindows/MaterialInspector/Show.cpp b/editor/src/DocumentWindows/MaterialInspector/Show.cpp index 8e12c9656..10e34ca54 100644 --- a/editor/src/DocumentWindows/MaterialInspector/Show.cpp +++ b/editor/src/DocumentWindows/MaterialInspector/Show.cpp @@ -16,7 +16,6 @@ #include "MaterialInspector.hpp" #include "components/MaterialComponent.hpp" #include "context/ThumbnailCache.hpp" -#include "utils/ScenePreview.hpp" #include "DocumentWindows/InspectorWindow/InspectorWindow.hpp" #include "ImNexo/Elements.hpp" #include "ImNexo/Panels.hpp" @@ -27,7 +26,7 @@ namespace nexo::editor { void MaterialInspector::renderMaterialInspector() { const auto inspectorWindow = m_windowRegistry.getWindow(NEXO_WND_USTRID_INSPECTOR).lock(); - auto dataOpt = inspectorWindow->getSubInspectorData(); + const auto dataOpt = inspectorWindow->getSubInspectorData(); if (!dataOpt.has_value()) return; const auto& data = *dataOpt; @@ -49,7 +48,7 @@ namespace nexo::editor { ImNexo::Image(static_cast(static_cast(textureID)), {64, 64}); ImGui::SameLine(); - auto material = data.material.lock(); + const auto material = data.material.lock(); components::Material& materialData = *material->getData(); m_materialModified = ImNexo::MaterialInspector(materialData); diff --git a/editor/src/DocumentWindows/SceneTreeWindow/DragDrop.cpp b/editor/src/DocumentWindows/SceneTreeWindow/DragDrop.cpp index e6550eef2..d8bdca7ca 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/DragDrop.cpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/DragDrop.cpp @@ -40,7 +40,7 @@ namespace nexo::editor { if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { - SceneTreeDragDropPayload payload{ + const SceneTreeDragDropPayload payload{ object.data.entity, object.data.sceneProperties.sceneId, object.type, @@ -202,7 +202,7 @@ namespace nexo::editor { !coordinator.entityHasComponent(parentEntity)) { std::string name = dropTarget.uiName; - auto it = ObjectTypeToIcon.find(dropTarget.type); + const auto it = ObjectTypeToIcon.find(dropTarget.type); if (it != ObjectTypeToIcon.end()) { const std::string& icon = it->second; @@ -240,10 +240,10 @@ namespace nexo::editor { if (payload.type == assets::AssetType::MODEL) { - auto modelRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + const auto modelRef = assets::AssetCatalog::getInstance().getAsset(payload.id); if (!modelRef) return; - if (auto model = modelRef.as(); model) + if (const auto model = modelRef.as(); model) { ecs::Entity newEntity = EntityFactory3D::createModel( model, @@ -261,10 +261,10 @@ namespace nexo::editor { } else if (payload.type == assets::AssetType::TEXTURE) { - auto textureRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + const auto textureRef = assets::AssetCatalog::getInstance().getAsset(payload.id); if (!textureRef) return; - if (auto texture = textureRef.as(); texture) + if (const auto texture = textureRef.as(); texture) { components::Material material; material.albedoTexture = texture; @@ -286,7 +286,7 @@ namespace nexo::editor { } else if (dropTarget.type == SelectionType::ENTITY) { - auto matCompOpt = Application::m_coordinator->tryGetComponent(dropTarget.data.entity); + const auto matCompOpt = Application::m_coordinator->tryGetComponent(dropTarget.data.entity); if (!matCompOpt) { ImGui::EndDragDropTarget(); return; } @@ -294,10 +294,10 @@ namespace nexo::editor { if (payload.type == assets::AssetType::TEXTURE) { - auto texRef = assets::AssetCatalog::getInstance().getAsset(payload.id); - if (auto tex = texRef.as(); tex) + const auto texRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + if (const auto tex = texRef.as(); tex) { - auto mat = matComp.material.lock(); + const auto mat = matComp.material.lock(); if (!mat) return; mat->getData()->albedoTexture = tex; @@ -305,8 +305,8 @@ namespace nexo::editor { } else if (payload.type == assets::AssetType::MATERIAL) { - auto matRef = assets::AssetCatalog::getInstance().getAsset(payload.id); - if (auto m = matRef.as(); m) + auto const matRef = assets::AssetCatalog::getInstance().getAsset(payload.id); + if (const auto m = matRef.as(); m) { auto oldMat = matComp.material; matComp.material = m; diff --git a/editor/src/DocumentWindows/SceneTreeWindow/NodeHandling.cpp b/editor/src/DocumentWindows/SceneTreeWindow/NodeHandling.cpp index cf24f4fde..6af3d8e86 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/NodeHandling.cpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/NodeHandling.cpp @@ -109,16 +109,16 @@ namespace nexo::editor { { auto &selector = Selector::get(); SceneObject entityNode; - std::string uiName = ""; - if (nexo::Application::m_coordinator->entityHasComponent(entity)) { - const auto &nameComponent = nexo::Application::m_coordinator->getComponent(entity); + std::string uiName; + if (Application::m_coordinator->entityHasComponent(entity)) { + const auto &nameComponent = Application::m_coordinator->getComponent(entity); uiName = nameComponent.name; } else uiName = std::format("{}{}", ObjectTypeToIcon.at(SelectionType::ENTITY), entity); entityNode.type = SelectionType::ENTITY; entityNode.data.sceneProperties = SceneProperties{sceneId, uiId}; entityNode.data.entity = entity; - const auto entityUuid = nexo::Application::m_coordinator->tryGetComponent(entity); + const auto entityUuid = Application::m_coordinator->tryGetComponent(entity); if (entityUuid) { entityNode.uuid = entityUuid->get().uuid; diff --git a/editor/src/DocumentWindows/SceneTreeWindow/SceneCreation.cpp b/editor/src/DocumentWindows/SceneTreeWindow/SceneCreation.cpp index d406b0b4a..b455f5424 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/SceneCreation.cpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/SceneCreation.cpp @@ -14,6 +14,7 @@ #include "SceneTreeWindow.hpp" #include "utils/Config.hpp" +#include namespace nexo::editor { diff --git a/editor/src/DocumentWindows/SceneTreeWindow/SceneTreeWindow.hpp b/editor/src/DocumentWindows/SceneTreeWindow/SceneTreeWindow.hpp index 95a87746f..d21c21302 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/SceneTreeWindow.hpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/SceneTreeWindow.hpp @@ -80,7 +80,7 @@ namespace nexo::editor std::vector children; ///< Child objects (if any). explicit SceneObject(std::string name = "", std::vector children = {}, - SelectionType type = SelectionType::NONE, EntityProperties data = {}) + const SelectionType type = SelectionType::NONE, const EntityProperties data = {}) : uiName(std::move(name)), type(type), data(data), children(std::move(children)) { } @@ -129,7 +129,7 @@ namespace nexo::editor ecs::Entity parentEntity, SceneObject& parentNode, std::unordered_set& processedEntities); - SceneObject createEntityNode(const scene::SceneId sceneId, const WindowId uiId, const ecs::Entity entity) const; + static SceneObject createEntityNode(scene::SceneId sceneId, WindowId uiId, ecs::Entity entity) ; private: SceneObject root_; ///< Root node of the scene tree. @@ -430,27 +430,27 @@ namespace nexo::editor * @brief Handles drag source setup for scene objects. * @param object The scene object being dragged. */ - void handleDragSource(const SceneObject& object); + static void handleDragSource(const SceneObject& object); /** * @brief Handles drop target setup for scene objects. * @param object The scene object that can receive drops. */ - void handleDropTarget(const SceneObject& object); + static void handleDropTarget(const SceneObject& object); /** * @brief Processes the drop operation from the scene tree itself. * @param dropTarget The target scene object receiving the drop. * @param payload The drag-and-drop payload data. */ - void handleDropFromSceneTree(const SceneObject& dropTarget, const struct SceneTreeDragDropPayload& payload); + static void handleDropFromSceneTree(const SceneObject& dropTarget, const struct SceneTreeDragDropPayload& payload); /** * @brief Processes the drop operation from the asset manager. * @param dropTarget The target scene object receiving the drop. * @param payload The drag-and-drop payload data. */ - void handleDropFromAssetManager(const SceneObject& dropTarget, const struct AssetDragDropPayload& payload); + static void handleDropFromAssetManager(const SceneObject& dropTarget, const AssetDragDropPayload& payload); /** * @brief Validates if a drop operation is allowed. @@ -458,7 +458,7 @@ namespace nexo::editor * @param payload The drag-and-drop payload data. * @return true if the drop is valid, false otherwise. */ - static bool canAcceptDrop(const SceneObject& dropTarget, const struct SceneTreeDragDropPayload& payload); + static bool canAcceptDrop(const SceneObject& dropTarget, const SceneTreeDragDropPayload& payload); }; /** diff --git a/editor/src/DocumentWindows/SceneTreeWindow/Selection.cpp b/editor/src/DocumentWindows/SceneTreeWindow/Selection.cpp index 26bf2aa04..8cb52e78c 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/Selection.cpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/Selection.cpp @@ -26,7 +26,7 @@ namespace nexo::editor { void SceneTreeWindow::entitySelected(const SceneObject &obj) { auto &selector = Selector::get(); - auto &app = nexo::getApp(); + auto &app = getApp(); // Check if we're operating on a single item or multiple items const auto& selectedEntities = selector.getSelectedEntities(); diff --git a/editor/src/DocumentWindows/SceneTreeWindow/Shortcuts.cpp b/editor/src/DocumentWindows/SceneTreeWindow/Shortcuts.cpp index 26a12014c..8a6522e20 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/Shortcuts.cpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/Shortcuts.cpp @@ -138,10 +138,10 @@ namespace nexo::editor { void SceneTreeWindow::selectAllCallback() { auto& selector = Selector::get(); - int currentSceneId = selector.getSelectedScene(); + const int currentSceneId = selector.getSelectedScene(); if (currentSceneId != -1) { - auto& app = nexo::getApp(); + auto& app = getApp(); const auto& scene = app.getSceneManager().getScene(currentSceneId); selector.clearSelection(); @@ -160,7 +160,8 @@ namespace nexo::editor { auto& selector = Selector::get(); const auto& selectedEntities = selector.getSelectedEntities(); - if (selectedEntities.empty()) return; + if (selectedEntities.empty()) + return; auto& app = getApp(); auto& actionManager = ActionManager::get(); @@ -204,13 +205,15 @@ namespace nexo::editor { auto& selector = Selector::get(); const auto& selectedEntities = selector.getSelectedEntities(); - if (selectedEntities.empty()) return; + if (selectedEntities.empty()) + return; auto& app = nexo::getApp(); auto& actionManager = ActionManager::get(); - int currentSceneId = selector.getSelectedScene(); + const int currentSceneId = selector.getSelectedScene(); - if (currentSceneId == -1) return; + if (currentSceneId == -1) + return; std::vector newEntities; newEntities.reserve(selectedEntities.size()); @@ -244,7 +247,8 @@ namespace nexo::editor { const auto& selector = Selector::get(); const auto& selectedEntities = selector.getSelectedEntities(); - if (selectedEntities.empty()) return; + if (selectedEntities.empty()) + return; auto& actionManager = ActionManager::get(); auto actionGroup = ActionManager::createActionGroup(); @@ -268,7 +272,7 @@ namespace nexo::editor { void SceneTreeWindow::showAllCallback() { const auto& selector = Selector::get(); - int currentSceneId = selector.getSelectedScene(); + const int currentSceneId = selector.getSelectedScene(); if (currentSceneId == -1) return; diff --git a/editor/src/DocumentWindows/SceneTreeWindow/Update.cpp b/editor/src/DocumentWindows/SceneTreeWindow/Update.cpp index 7b99f024a..bd1dc83ea 100644 --- a/editor/src/DocumentWindows/SceneTreeWindow/Update.cpp +++ b/editor/src/DocumentWindows/SceneTreeWindow/Update.cpp @@ -13,7 +13,6 @@ /////////////////////////////////////////////////////////////////////////////// #include "SceneTreeWindow.hpp" -#include "components/Render3D.hpp" #include "components/StaticMesh.hpp" #include "components/Name.hpp" #include "components/Uuid.hpp" @@ -69,7 +68,7 @@ namespace nexo::editor { } void SceneTreeWindow::buildChildNodesForEntity( - ecs::Entity parentEntity, + const ecs::Entity parentEntity, SceneObject& parentNode, std::unordered_set& processedEntities) { @@ -93,10 +92,10 @@ namespace nexo::editor { } } - SceneObject SceneTreeWindow::createEntityNode(const scene::SceneId sceneId, const WindowId uiId, const ecs::Entity entity) const + SceneObject SceneTreeWindow::createEntityNode(const scene::SceneId sceneId, const WindowId uiId, const ecs::Entity entity) { - SceneProperties scene{sceneId, uiId}; - EntityProperties data{scene, entity}; + const SceneProperties scene{sceneId, uiId}; + const EntityProperties data{scene, entity}; std::string name; diff --git a/editor/src/DocumentWindows/TestWindow/Parser.cpp b/editor/src/DocumentWindows/TestWindow/Parser.cpp index 95a4142b6..2b8363a1b 100644 --- a/editor/src/DocumentWindows/TestWindow/Parser.cpp +++ b/editor/src/DocumentWindows/TestWindow/Parser.cpp @@ -25,7 +25,7 @@ namespace nexo::editor { - static std::string parseBullet(std::string line) + static std::string parseBullet(const std::string &line) { if (line.size() >= 2 && line[0] == '-' && std::isspace(line[1])) return line.substr(2); @@ -58,7 +58,7 @@ namespace nexo::editor { currentSubSection = ¤tSection->subSections.back(); currentSubSection->name = line.substr(3); // Test case - } else if (line.rfind("-", 0) == 0) { + } else if (line.rfind('-', 0) == 0) { std::string testName = parseBullet(line); if (testName.empty()) THROW_EXCEPTION(InvalidTestFileFormat, entry.path().string(), "Test case format is invalid : \"- Test case name \""); @@ -76,7 +76,7 @@ namespace nexo::editor { void TestWindow::parseTestFolder() { - std::filesystem::path testDir = Path::resolvePathRelativeToExe( + const std::filesystem::path testDir = Path::resolvePathRelativeToExe( "../tests/editor"); for (const auto &entry : std::filesystem::directory_iterator(testDir)) { diff --git a/editor/src/DocumentWindows/TestWindow/Shutdown.cpp b/editor/src/DocumentWindows/TestWindow/Shutdown.cpp index aa0ae1587..7ab548c19 100644 --- a/editor/src/DocumentWindows/TestWindow/Shutdown.cpp +++ b/editor/src/DocumentWindows/TestWindow/Shutdown.cpp @@ -20,7 +20,6 @@ #include #ifdef __linux__ - #include #include #endif @@ -54,11 +53,10 @@ namespace nexo::editor { #elif defined(__APPLE__) return "macOS"; #elif defined(__linux__) - struct utsname info; + utsname info{}; if (uname(&info) == 0) return std::string(info.sysname) + " " + info.release; - else - return "Linux"; + return "Linux"; #else return "Unknown OS"; #endif @@ -78,7 +76,7 @@ namespace nexo::editor { // trim leading spaces model.erase( model.begin(), - std::ranges::find_if(model, [](unsigned char ch) { return !std::isspace(ch); }) + std::ranges::find_if(model, [](const unsigned char ch) { return !std::isspace(ch); }) ); return model; } @@ -110,9 +108,9 @@ namespace nexo::editor { static std::string getGraphicsInfo() { #ifdef NX_GRAPHICS_API_OPENGL - auto vendor = reinterpret_cast(glGetString(GL_VENDOR)); - auto renderer = reinterpret_cast(glGetString(GL_RENDERER)); - auto version = reinterpret_cast(glGetString(GL_VERSION)); + const auto vendor = reinterpret_cast(glGetString(GL_VENDOR)); + const auto renderer = reinterpret_cast(glGetString(GL_RENDERER)); + const auto version = reinterpret_cast(glGetString(GL_VERSION)); return std::string("OpenGL: ") + vendor + " - " + renderer + " (" + version + ")"; #else return "Graphics info not available"; @@ -149,12 +147,12 @@ namespace nexo::editor { static std::filesystem::path getTestReportFilePath() { - auto now_tp = floor(std::chrono::system_clock::now()); + const auto now_tp = floor(std::chrono::system_clock::now()); std::chrono::zoned_time local_zoned{std::chrono::current_zone(), now_tp}; std::string ts = std::format("{:%Y%m%d}", local_zoned); - std::string filename = std::format("EditorTestResults_{}.report", ts); + const std::string filename = std::format("EditorTestResults_{}.report", ts); - auto testDir = std::filesystem::path(Path::resolvePathRelativeToExe("../tests/editor")); + const auto testDir = std::filesystem::path(Path::resolvePathRelativeToExe("../tests/editor")); std::filesystem::create_directories(testDir); auto filePath = testDir / filename; return filePath; @@ -170,7 +168,7 @@ namespace nexo::editor { writeEnvironmentReport(out); - for (auto §ion : m_testSections) { + for (const auto §ion : m_testSections) { out << std::format("# {}\n", section.name); for (const auto &tc : section.testCases) writeTestCaseReport(out, tc); diff --git a/editor/src/Editor.cpp b/editor/src/Editor.cpp index 515fb600c..b83e10e7a 100644 --- a/editor/src/Editor.cpp +++ b/editor/src/Editor.cpp @@ -12,6 +12,7 @@ // ////////////////////////////////////////////////////////////////////////////// +#define IMGUI_DEFINE_MATH_OPERATORS #include "ADocumentWindow.hpp" #include "utils/Config.hpp" @@ -25,9 +26,8 @@ #include "context/ActionManager.hpp" #include "DocumentWindows/TestWindow/TestWindow.hpp" -#define IMGUI_DEFINE_MATH_OPERATORS -#include "imgui.h" #include +#include "imgui.h" #include #include @@ -38,7 +38,7 @@ namespace nexo::editor { void Editor::shutdown() const { - Application& app = Application::getInstance(); + const Application& app = Application::getInstance(); app.shutdownScripting(); LOG(NEXO_INFO, "Closing editor"); @@ -187,7 +187,7 @@ namespace nexo::editor { fontSize = std::ceil(fontSize * std::max(scaleFactorX, scaleFactorY)); LOG(NEXO_WARN, "Font size adjusted to {}", fontSize); } - float iconFontSize = fontSize * 2.0f / 3.0f; + const float iconFontSize = fontSize * 2.0f / 3.0f; static const std::string sourceSansPath = Path::resolvePathRelativeToExe( "../resources/fonts/SourceSans3-Regular.ttf").string(); @@ -341,11 +341,11 @@ namespace nexo::editor { } if (ImGui::IsKeyDown(ImGuiKey_LeftCtrl) && ImGui::IsKeyDown(ImGuiKey_LeftShift) && ImGui::IsKeyPressed(ImGuiKey_T)) { - if (auto testWindow = getWindow(NEXO_WND_USTRID_TEST).lock()) { + if (const auto testWindow = getWindow(NEXO_WND_USTRID_TEST).lock()) { testWindow->setOpened(true); } else { - registerWindow(NEXO_WND_USTRID_TEST); - getWindow(NEXO_WND_USTRID_TEST).lock()->setup(); + registerWindow(NEXO_WND_USTRID_TEST); + getWindow(NEXO_WND_USTRID_TEST).lock()->setup(); } } } @@ -547,7 +547,7 @@ namespace nexo::editor { ImGui::Render(); - ImGuiBackend::end(nexo::getApp().getWindow()); + ImGuiBackend::end(getApp().getWindow()); } void Editor::update() const diff --git a/editor/src/ImNexo/Components.cpp b/editor/src/ImNexo/Components.cpp index c68c84850..45a76ca12 100644 --- a/editor/src/ImNexo/Components.cpp +++ b/editor/src/ImNexo/Components.cpp @@ -32,7 +32,7 @@ namespace ImNexo { ) { IdGuard idGuard(uniqueId); - std::string invisButtonLabel = "##" + uniqueId; + const std::string invisButtonLabel = "##" + uniqueId; if (ImGui::InvisibleButton(invisButtonLabel.c_str(), itemSize)) return true; diff --git a/editor/src/ImNexo/Elements.cpp b/editor/src/ImNexo/Elements.cpp index 92f386001..ca6000cdb 100644 --- a/editor/src/ImNexo/Elements.cpp +++ b/editor/src/ImNexo/Elements.cpp @@ -18,6 +18,8 @@ #include #include +#include +#include namespace ImNexo { @@ -98,7 +100,7 @@ namespace ImNexo { if (textSize.x > wrapWidth) { // Try to find a space to split the text - size_t splitPos = text.find(' '); + const size_t splitPos = text.find(' '); if (splitPos != std::string::npos) { // Split text into two lines diff --git a/editor/src/ImNexo/Elements.hpp b/editor/src/ImNexo/Elements.hpp index 901165182..4620700dc 100644 --- a/editor/src/ImNexo/Elements.hpp +++ b/editor/src/ImNexo/Elements.hpp @@ -14,7 +14,6 @@ #pragma once #include -#include #include #include @@ -232,6 +231,7 @@ namespace ImNexo { * @param pMax Lower right corner position of the rectangle * @param angle Angle of the gradient in degrees (0.0f = down, 90.0f = right, 180.0f = up, 270.0f = left) * @param stops Vector of gradient stops, each defined by a position (0.0f to 1.0f) and a color + * @param drawList The imgui draw list */ void RectFilledLinearGradient( const ImVec2& pMin, diff --git a/editor/src/ImNexo/EntityProperties.cpp b/editor/src/ImNexo/EntityProperties.cpp index 6d81facac..e58a1e067 100644 --- a/editor/src/ImNexo/EntityProperties.cpp +++ b/editor/src/ImNexo/EntityProperties.cpp @@ -215,8 +215,8 @@ namespace ImNexo { ImGui::TableSetupColumn("##Y", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_NoHeaderLabel); ImGui::TableSetupColumn("##Lock", ImGuiTableColumnFlags_WidthStretch); glm::vec2 viewPort = {cameraComponent.width, cameraComponent.height}; - std::vector badgeColors; - std::vector textBadgeColors; + const std::vector badgeColors; + const std::vector textBadgeColors; const bool disabled = !cameraComponent.viewportLocked; if (disabled) diff --git a/editor/src/ImNexo/Guard.hpp b/editor/src/ImNexo/Guard.hpp index 492a86b7e..cba1db059 100644 --- a/editor/src/ImNexo/Guard.hpp +++ b/editor/src/ImNexo/Guard.hpp @@ -14,7 +14,6 @@ #pragma once #include -#include #include #include @@ -314,7 +313,6 @@ namespace ImNexo { * @param scale The scaling factor to apply to the current window's font */ explicit FontScaleGuard(const float scale) - : m_active(true) { ImGui::SetWindowFontScale(scale); } diff --git a/editor/src/ImNexo/Panels.cpp b/editor/src/ImNexo/Panels.cpp index 172794e03..6ccd53684 100644 --- a/editor/src/ImNexo/Panels.cpp +++ b/editor/src/ImNexo/Panels.cpp @@ -302,7 +302,7 @@ namespace ImNexo { static double lastClickTime = 0.0f; // Button with arrow indicating state - std::string buttonText = "Add Component " + std::string(showComponentSelector ? ICON_FA_CHEVRON_UP : ICON_FA_CHEVRON_DOWN); + const std::string buttonText = "Add Component " + std::string(showComponentSelector ? ICON_FA_CHEVRON_UP : ICON_FA_CHEVRON_DOWN); if (Button(buttonText, ImVec2(buttonWidth, 0))) { diff --git a/editor/src/ImNexo/Panels.hpp b/editor/src/ImNexo/Panels.hpp index f7119d9e9..a08d9233e 100644 --- a/editor/src/ImNexo/Panels.hpp +++ b/editor/src/ImNexo/Panels.hpp @@ -13,11 +13,8 @@ /////////////////////////////////////////////////////////////////////////////// #pragma once -#include "components/Render.hpp" #include "core/scene/SceneManager.hpp" -#include - namespace ImNexo { /** * @brief Draws a material inspector widget for editing material properties. diff --git a/editor/src/ImNexo/Utils.cpp b/editor/src/ImNexo/Utils.cpp index 1ddb207cb..c80f6df35 100644 --- a/editor/src/ImNexo/Utils.cpp +++ b/editor/src/ImNexo/Utils.cpp @@ -13,13 +13,20 @@ /////////////////////////////////////////////////////////////////////////////// #include "Utils.hpp" +#include namespace ImNexo::utils { ImU32 imLerpColor(const ImU32 colA, const ImU32 colB, const float t) { - const unsigned char a0 = (colA >> 24) & 0xFF, r0 = (colA >> 16) & 0xFF, g0 = (colA >> 8) & 0xFF, b0 = colA & 0xFF; - const unsigned char a1 = (colB >> 24) & 0xFF, r1 = (colB >> 16) & 0xFF, g1 = (colB >> 8) & 0xFF, b1 = colB & 0xFF; + const unsigned char a0 = (colA >> 24) & 0xFF; + const unsigned char r0 = (colA >> 16) & 0xFF; + const unsigned char g0 = (colA >> 8) & 0xFF; + const unsigned char b0 = colA & 0xFF; + const unsigned char a1 = (colB >> 24) & 0xFF; + const unsigned char r1 = (colB >> 16) & 0xFF; + const unsigned char g1 = (colB >> 8) & 0xFF; + const unsigned char b1 = colB & 0xFF; const auto a = static_cast(static_cast(a0) + t * static_cast(a1 - a0)); const auto r = static_cast(static_cast(r0) + t * static_cast(r1 - r0)); const auto g = static_cast(static_cast(g0) + t * static_cast(g1 - g0)); diff --git a/editor/src/ImNexo/Utils.hpp b/editor/src/ImNexo/Utils.hpp index 75e3e26cd..68d469eae 100644 --- a/editor/src/ImNexo/Utils.hpp +++ b/editor/src/ImNexo/Utils.hpp @@ -14,7 +14,6 @@ #pragma once #include -#include #include #include diff --git a/editor/src/ImNexo/Widgets.cpp b/editor/src/ImNexo/Widgets.cpp index b4de26b37..28a174ceb 100644 --- a/editor/src/ImNexo/Widgets.cpp +++ b/editor/src/ImNexo/Widgets.cpp @@ -12,7 +12,6 @@ // /////////////////////////////////////////////////////////////////////////////// -#include #include #include #include @@ -91,7 +90,7 @@ namespace ImNexo } void ButtonDropDown(const ImVec2& buttonPos, const ImVec2 buttonSize, const std::vector& buttonProps, - bool& closure, DropdownOrientation orientation) + bool& closure, const DropdownOrientation orientation) { constexpr float buttonSpacing = 5.0f; constexpr float padding = 10.0f; @@ -120,7 +119,7 @@ namespace ImNexo } // Adjust layout for horizontal orientations - bool isHorizontal = (orientation == DropdownOrientation::LEFT || + const bool isHorizontal = (orientation == DropdownOrientation::LEFT || orientation == DropdownOrientation::RIGHT); // For horizontal layouts, swap width and height diff --git a/editor/src/WindowRegistry.hpp b/editor/src/WindowRegistry.hpp index 4f26235c8..70c85d0f6 100644 --- a/editor/src/WindowRegistry.hpp +++ b/editor/src/WindowRegistry.hpp @@ -113,7 +113,7 @@ namespace nexo::editor { requires std::derived_from void unregisterWindow(const std::string &windowName) { - auto it = m_windows.find(typeid(T)); + const auto it = m_windows.find(typeid(T)); if (it == m_windows.end()) { LOG(NEXO_WARN, "Window of type {} not found", typeid(T).name()); return; @@ -147,7 +147,7 @@ namespace nexo::editor { requires std::derived_from std::weak_ptr getWindow(const std::string &windowName) const { - auto it = m_windows.find(typeid(T)); + const auto it = m_windows.find(typeid(T)); if (it == m_windows.end()) { LOG(NEXO_WARN, "Window of type {} not found", typeid(T).name()); @@ -191,9 +191,9 @@ namespace nexo::editor { // Helper: non-capturing function for casting: std::shared_ptr(*caster)(const std::shared_ptr&) = &castWindow; - auto it = m_windows.find(typeid(T)); + const auto it = m_windows.find(typeid(T)); if (it == m_windows.end()) { - static const std::vector> empty; + static constexpr std::vector> empty; return std::ranges::transform_view(std::ranges::ref_view(empty), caster); } return std::ranges::transform_view(std::ranges::ref_view(it->second), caster); @@ -222,7 +222,7 @@ namespace nexo::editor { // Helper: non-capturing function for casting: std::shared_ptr(*caster)(std::shared_ptr&) = &castWindow; - auto it = m_windows.find(typeid(T)); + const auto it = m_windows.find(typeid(T)); if (it == m_windows.end()) { static std::vector> empty; return std::ranges::transform_view(std::ranges::ref_view(empty), caster); diff --git a/editor/src/context/ActionHistory.cpp b/editor/src/context/ActionHistory.cpp index 61a1b3728..0de733672 100644 --- a/editor/src/context/ActionHistory.cpp +++ b/editor/src/context/ActionHistory.cpp @@ -54,14 +54,14 @@ namespace nexo::editor { undoStack.push_back(std::move(action)); } - void ActionHistory::setMaxUndoLevels(size_t levels) + void ActionHistory::setMaxUndoLevels(const size_t levels) { maxUndoLevels = levels; while (undoStack.size() > maxUndoLevels) undoStack.pop_front(); } - void ActionHistory::clear(unsigned int count) + void ActionHistory::clear(const unsigned int count) { if (!count) { undoStack.clear(); diff --git a/editor/src/context/ThumbnailCache.cpp b/editor/src/context/ThumbnailCache.cpp index cf8af05c8..6eb88b4db 100644 --- a/editor/src/context/ThumbnailCache.cpp +++ b/editor/src/context/ThumbnailCache.cpp @@ -40,24 +40,22 @@ namespace nexo::editor { return 0; - auto asset = assetRef.lock(); + const auto asset = assetRef.lock(); if (!asset) return 0; switch (asset->getType()) { case assets::AssetType::MATERIAL: { - auto materialRef = assetRef.as(); + const auto materialRef = assetRef.as(); return getMaterialThumbnail(materialRef, size); } case assets::AssetType::TEXTURE: { - auto textureRef = assetRef.as(); + const auto textureRef = assetRef.as(); return getTextureThumbnail(textureRef, size); } case assets::AssetType::MODEL: - // Model thumbnails not currently implemented - return 0; default: - // Unsupported asset type + // Unsupported asset type | Model not supported yet return 0; } } @@ -68,14 +66,14 @@ namespace nexo::editor { if (!materialRef.isValid()) return 0; - auto material = materialRef.lock(); + const auto material = materialRef.lock(); if (!material || !material->getData()) return 0; const boost::uuids::uuid& assetId = material->getID(); // Check if thumbnail exists at requested size - auto it = m_thumbnailCache.find(assetId); + const auto it = m_thumbnailCache.find(assetId); if (it != m_thumbnailCache.end() && it->second.size == size) return it->second.framebuffer->getColorAttachmentId(0); @@ -91,7 +89,7 @@ namespace nexo::editor { if (!materialRef.isValid()) return 0; - auto material = materialRef.lock(); + const auto material = materialRef.lock(); if (!material || !material->getData()) return 0; @@ -104,13 +102,13 @@ namespace nexo::editor { if (!textureRef.isValid()) return 0; - auto texture = textureRef.lock(); + const auto texture = textureRef.lock(); if (!texture) return 0; const boost::uuids::uuid& assetId = texture->getID(); - auto it = m_thumbnailCache.find(assetId); + const auto it = m_thumbnailCache.find(assetId); if (it != m_thumbnailCache.end() && it->second.size == size) return it->second.textureId; @@ -123,14 +121,14 @@ namespace nexo::editor { unsigned int ThumbnailCache::createMaterialThumbnail(const assets::AssetRef& materialRef, const glm::vec2& size) { - auto material = materialRef.lock(); + const auto material = materialRef.lock(); if (!material || !material->getData()) return 0; utils::ScenePreviewOut previewInfo; const components::Material& materialData = *material->getData(); - ecs::Entity previewEntity = nexo::EntityFactory3D::createCube( + const ecs::Entity previewEntity = EntityFactory3D::createCube( glm::vec3(0.0f), // position glm::vec3(1.0f), // size glm::vec3(30.0f, 45.0f, 0.0f), // rotation - angled for better lighting @@ -145,13 +143,14 @@ namespace nexo::editor { app.run(sceneInfo); const auto& cameraComponent = Application::m_coordinator->getComponent(previewInfo.cameraId); - auto framebuffer = cameraComponent.m_renderTarget; + const auto framebuffer = cameraComponent.m_renderTarget; app.getSceneManager().deleteScene(previewInfo.sceneId); ThumbnailInfo info; info.framebuffer = framebuffer; info.size = size; info.previewInfo = previewInfo; info.isScenePreview = false; + info.textureId = framebuffer->getColorAttachmentId(0); m_thumbnailCache[material->getID()] = info; @@ -163,14 +162,14 @@ namespace nexo::editor { unsigned int ThumbnailCache::createTextureThumbnail(const assets::AssetRef& textureRef, const glm::vec2& size) { - auto texture = textureRef.lock(); + const auto texture = textureRef.lock(); if (!texture) return 0; // For textures, we can often just use the texture directly if (texture->isLoaded() && texture->getData()) { ThumbnailInfo info; - info.textureId = texture->getData().get()->texture->getId(); + info.textureId = texture->getData()->texture->getId(); info.size = size; info.isScenePreview = false; @@ -186,7 +185,7 @@ namespace nexo::editor { auto& app = getApp(); // Clean up all scene previews - for (auto& [assetId, info] : m_thumbnailCache) { + for (auto &info: m_thumbnailCache | std::views::values) { if (info.isScenePreview && info.previewInfo.sceneGenerated) { app.getSceneManager().deleteScene(info.previewInfo.sceneId); info.previewInfo.sceneGenerated = false; @@ -198,7 +197,7 @@ namespace nexo::editor { void ThumbnailCache::removeThumbnail(const boost::uuids::uuid& assetId) { - auto it = m_thumbnailCache.find(assetId); + const auto it = m_thumbnailCache.find(assetId); if (it == m_thumbnailCache.end()) return; diff --git a/editor/src/context/actions/ComponentRestoreFactory.cpp b/editor/src/context/actions/ComponentRestoreFactory.cpp index 62eb2f0b6..984451775 100644 --- a/editor/src/context/actions/ComponentRestoreFactory.cpp +++ b/editor/src/context/actions/ComponentRestoreFactory.cpp @@ -40,8 +40,7 @@ namespace nexo::editor { {typeid(components::PerspectiveCameraTarget), [](ecs::Entity e){ return std::make_unique>(e); }}, }; - auto it = factories.find(typeIndex); - if (it != factories.end()) { + if (const auto it = factories.find(typeIndex); it != factories.end()) { return (it->second)(entity); } return nullptr; diff --git a/editor/src/context/actions/EntityActions.cpp b/editor/src/context/actions/EntityActions.cpp index 00c263094..bda07da57 100644 --- a/editor/src/context/actions/EntityActions.cpp +++ b/editor/src/context/actions/EntityActions.cpp @@ -71,7 +71,7 @@ namespace nexo::editor { // Handle old parent if (m_oldParent != ecs::INVALID_ENTITY) { - auto oldParentTransform = coordinator.tryGetComponent(m_oldParent); + const auto oldParentTransform = coordinator.tryGetComponent(m_oldParent); if (oldParentTransform.has_value()) { oldParentTransform->get().removeChild(m_entity); } @@ -80,7 +80,7 @@ namespace nexo::editor { // Handle new parent if (m_newParent != ecs::INVALID_ENTITY) { // Add or update parent component on entity - auto parentComp = coordinator.tryGetComponent(m_entity); + const auto parentComp = coordinator.tryGetComponent(m_entity); if (!parentComp.has_value()) { coordinator.addComponent(m_entity, components::ParentComponent{m_newParent}); } else { @@ -98,7 +98,7 @@ namespace nexo::editor { } } else { // Remove parent component (make it a root entity) - auto parentComp = coordinator.tryGetComponent(m_entity); + const auto parentComp = coordinator.tryGetComponent(m_entity); if (parentComp.has_value()) { coordinator.removeComponent(m_entity); } @@ -111,7 +111,7 @@ namespace nexo::editor { // Handle new parent (undo by removing from it) if (m_newParent != ecs::INVALID_ENTITY) { - auto newParentTransform = coordinator.tryGetComponent(m_newParent); + const auto newParentTransform = coordinator.tryGetComponent(m_newParent); if (newParentTransform.has_value()) { newParentTransform->get().removeChild(m_entity); } @@ -120,7 +120,7 @@ namespace nexo::editor { // Handle old parent (restore to it) if (m_oldParent != ecs::INVALID_ENTITY) { // Add or update parent component on entity - auto parentComp = coordinator.tryGetComponent(m_entity); + const auto parentComp = coordinator.tryGetComponent(m_entity); if (!parentComp.has_value()) { coordinator.addComponent(m_entity, components::ParentComponent{m_oldParent}); } else { @@ -138,7 +138,7 @@ namespace nexo::editor { } } else { // Remove parent component (restore to root entity) - auto parentComp = coordinator.tryGetComponent(m_entity); + const auto parentComp = coordinator.tryGetComponent(m_entity); if (parentComp.has_value()) { coordinator.removeComponent(m_entity); } diff --git a/editor/src/context/actions/EntityActions.hpp b/editor/src/context/actions/EntityActions.hpp index ed858308c..b1dc2e239 100644 --- a/editor/src/context/actions/EntityActions.hpp +++ b/editor/src/context/actions/EntityActions.hpp @@ -158,7 +158,7 @@ namespace nexo::editor { */ class EntityParentChangeAction final : public Action { public: - EntityParentChangeAction(ecs::Entity entity, ecs::Entity oldParent, ecs::Entity newParent) + EntityParentChangeAction(const ecs::Entity entity, const ecs::Entity oldParent, const ecs::Entity newParent) : m_entity(entity), m_oldParent(oldParent), m_newParent(newParent) {} void redo() override; diff --git a/editor/src/exceptions/Exceptions.hpp b/editor/src/exceptions/Exceptions.hpp index fb95d9b17..bde4bd7ed 100644 --- a/editor/src/exceptions/Exceptions.hpp +++ b/editor/src/exceptions/Exceptions.hpp @@ -62,7 +62,7 @@ namespace nexo::editor { * @param windowTypeIndex The type index of the unregistered window. * @param loc The source location where the exception is thrown (defaults to the current location). */ - explicit WindowNotRegistered(std::type_index windowTypeIndex, const std::source_location loc = std::source_location::current()) + explicit WindowNotRegistered(const std::type_index windowTypeIndex, const std::source_location loc = std::source_location::current()) : Exception(std::format("Window not registered: {}. Make sure the window is registered in the WindowRegistry before accessing it.", windowTypeIndex.name()), loc) {} }; @@ -77,7 +77,7 @@ namespace nexo::editor { * @param windowName The name of the window. * @param loc The source location where the exception is thrown (defaults to the current location). */ - explicit WindowAlreadyRegistered(std::type_index windowTypeIndex, const std::string &windowName, const std::source_location loc = std::source_location::current()) + explicit WindowAlreadyRegistered(const std::type_index windowTypeIndex, const std::string &windowName, const std::source_location loc = std::source_location::current()) : Exception(std::format("Window {} already registered as: {}. Make sure the type and name is unique.", windowName, windowTypeIndex.name()), loc) {} }; diff --git a/editor/src/inputs/Command.cpp b/editor/src/inputs/Command.cpp index e2722b1cb..f0aadec56 100644 --- a/editor/src/inputs/Command.cpp +++ b/editor/src/inputs/Command.cpp @@ -139,7 +139,7 @@ namespace nexo::editor { [](const unsigned char c){ return std::tolower(c); }); // Look up in the map and set the bit in the signature - auto it = keyMap.find(segment); + const auto it = keyMap.find(segment); if (it != keyMap.end()) { m_signature.set(static_cast(it->second - ImGuiKey_NamedKey_BEGIN)); } @@ -176,7 +176,7 @@ namespace nexo::editor { std::span Command::getChildren() const { - return std::span(m_childrens); + return {m_childrens}; } const std::bitset &Command::getSignature() const diff --git a/editor/src/inputs/WindowState.cpp b/editor/src/inputs/WindowState.cpp index 69dfe21bd..52334a589 100644 --- a/editor/src/inputs/WindowState.cpp +++ b/editor/src/inputs/WindowState.cpp @@ -28,6 +28,6 @@ namespace nexo::editor { std::span WindowState::getCommands() const { - return std::span(m_commands.data(), m_commands.size()); + return {m_commands.data(), m_commands.size()}; } } diff --git a/editor/src/utils/Config.cpp b/editor/src/utils/Config.cpp index 46a191e6d..470afb3c3 100644 --- a/editor/src/utils/Config.cpp +++ b/editor/src/utils/Config.cpp @@ -150,7 +150,7 @@ namespace nexo::editor { registry.setDockId(currentWindowName, dockId); } } - } else if (inWindowSection && !isHashedWindow && !line.empty() && line[0] == '[') { + } else if (inWindowSection && !line.empty() && line[0] == '[') { // Reset state when we hit a new section inWindowSection = false; isHashedWindow = false; diff --git a/editor/src/utils/EditorProps.cpp b/editor/src/utils/EditorProps.cpp index d9e75086b..9e2c9df59 100644 --- a/editor/src/utils/EditorProps.cpp +++ b/editor/src/utils/EditorProps.cpp @@ -15,7 +15,6 @@ #include "EditorProps.hpp" #include "Renderer3D.hpp" #include "components/BillboardMesh.hpp" -#include "renderer/Texture.hpp" #include "components/Render3D.hpp" #include "Path.hpp" #include "Nexo.hpp" diff --git a/editor/src/utils/FileSystem.cpp b/editor/src/utils/FileSystem.cpp index 9c021f795..e84a281b7 100644 --- a/editor/src/utils/FileSystem.cpp +++ b/editor/src/utils/FileSystem.cpp @@ -30,7 +30,7 @@ namespace nexo::editor::utils { #else std::stringstream ss; ss << "xdg-open " << std::quoted(folderPath); - int status = std::system(ss.str().c_str()); + const int status = std::system(ss.str().c_str()); if (status == -1) LOG(NEXO_ERROR, "Failed to open folder '{}'", folderPath); else if (status != 0) diff --git a/editor/src/utils/FileSystem.hpp b/editor/src/utils/FileSystem.hpp index f0d4c2191..0c81da626 100644 --- a/editor/src/utils/FileSystem.hpp +++ b/editor/src/utils/FileSystem.hpp @@ -14,7 +14,6 @@ #pragma once #include -#include namespace nexo::editor::utils { diff --git a/editor/src/utils/ScenePreview.cpp b/editor/src/utils/ScenePreview.cpp index be4e51141..b3f621bc1 100644 --- a/editor/src/utils/ScenePreview.cpp +++ b/editor/src/utils/ScenePreview.cpp @@ -18,7 +18,6 @@ #include "LightFactory.hpp" #include "components/Camera.hpp" #include "components/MaterialComponent.hpp" -#include "components/Render3D.hpp" #include "components/StaticMesh.hpp" namespace nexo::editor::utils { diff --git a/editor/src/utils/ScenePreview.hpp b/editor/src/utils/ScenePreview.hpp index e6c09df36..2fd180615 100644 --- a/editor/src/utils/ScenePreview.hpp +++ b/editor/src/utils/ScenePreview.hpp @@ -66,6 +66,7 @@ namespace nexo::editor::utils { * @param previewSize The size (width, height) of the preview. * @param entity The entity to generate the preview from. * @param out Output structure containing preview scene details. + * @param clearColor The clear color of the camera */ void genScenePreview(const std::string &uniqueSceneName, const glm::vec2 &previewSize, ecs::Entity entity, ScenePreviewOut &out, const glm::vec4 &clearColor = {0.05f, 0.05f, 0.05f, 0.0f}); diff --git a/editor/src/utils/String.cpp b/editor/src/utils/String.cpp index 743b79992..e1d80f3e8 100644 --- a/editor/src/utils/String.cpp +++ b/editor/src/utils/String.cpp @@ -14,7 +14,6 @@ #include "String.hpp" -#include #include #include #include @@ -29,10 +28,10 @@ namespace nexo::editor::utils { void trim(std::string &s) { - auto not_space = [](char c){ return !std::isspace(static_cast(c)); }; + auto not_space = [](const char c){ return !std::isspace(static_cast(c)); }; s.erase(s.begin(), std::ranges::find_if(s, not_space)); - auto rit = std::ranges::find_if( + const auto rit = std::ranges::find_if( s | std::views::reverse, not_space ); From 129611d150e61b57cf66631cff3d5015c064f07f Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Sat, 26 Jul 2025 14:52:58 +0200 Subject: [PATCH 09/30] fix(sonar-editor): fix const expr for windows --- editor/src/WindowRegistry.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/editor/src/WindowRegistry.hpp b/editor/src/WindowRegistry.hpp index 70c85d0f6..00063d623 100644 --- a/editor/src/WindowRegistry.hpp +++ b/editor/src/WindowRegistry.hpp @@ -193,7 +193,7 @@ namespace nexo::editor { const auto it = m_windows.find(typeid(T)); if (it == m_windows.end()) { - static constexpr std::vector> empty; + static const std::vector> empty; return std::ranges::transform_view(std::ranges::ref_view(empty), caster); } return std::ranges::transform_view(std::ranges::ref_view(it->second), caster); From fcfe9b558361675b37609bd37a1b43292480968d Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Sat, 26 Jul 2025 14:57:55 +0200 Subject: [PATCH 10/30] fix(sonar-editor): fix last sonar editor issues --- editor/src/DocumentWindows/AssetManager/Show.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/editor/src/DocumentWindows/AssetManager/Show.cpp b/editor/src/DocumentWindows/AssetManager/Show.cpp index 4bd0a1570..e610e008a 100644 --- a/editor/src/DocumentWindows/AssetManager/Show.cpp +++ b/editor/src/DocumentWindows/AssetManager/Show.cpp @@ -45,8 +45,8 @@ namespace nexo::editor { m_layout.size.iconSize + ImGui::GetFontSize() * 1.7f // height ); m_layout.size.itemStep = ImVec2( - m_layout.size.itemSize.x + m_layout.size.iconSpacing, - m_layout.size.itemSize.y + m_layout.size.iconSpacing + m_layout.size.itemSize.x + static_cast(m_layout.size.iconSpacing), + m_layout.size.itemSize.y + static_cast(m_layout.size.iconSpacing) ); // Colors m_layout.color.thumbnailBg = ImGui::GetColorU32(ImGuiCol_Button); @@ -367,8 +367,8 @@ namespace nexo::editor { unsigned int col = i % m_layout.size.columnCount; unsigned int row = i / m_layout.size.columnCount; ImVec2 itemPos{ - startPos.x + col * m_layout.size.itemStep.x, - startPos.y + row * m_layout.size.itemStep.y + startPos.x + static_cast(col) * m_layout.size.itemStep.x, + startPos.y + static_cast(row) * m_layout.size.itemStep.y }; if (i < static_cast(subfolders.size())) { @@ -460,7 +460,7 @@ namespace nexo::editor { // Draw text const std::string dropText = "Drop files here to import"; const ImVec2 textSize = ImGui::CalcTextSize(dropText.c_str()); - const ImVec2 textPos = ImVec2(windowPos.x + (windowSize.x - textSize.x) * 0.5f, + const auto textPos = ImVec2(windowPos.x + (windowSize.x - textSize.x) * 0.5f, windowPos.y + (windowSize.y - textSize.y) * 0.5f); drawList->AddText(ImGui::GetFont(), ImGui::GetFontSize() * 1.5f, textPos, IM_COL32(255, 255, 255, 255), dropText.c_str()); From 5ba084a868e9c52938491cf86eac52785513287b Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Sat, 26 Jul 2025 19:04:10 +0200 Subject: [PATCH 11/30] fix(sonar-engine): fix first batch of sonar issues --- engine/src/Application.cpp | 4 +- engine/src/assets/AssetCatalog.cpp | 14 ++- engine/src/assets/AssetCatalog.hpp | 8 +- engine/src/assets/AssetImporter.cpp | 2 +- engine/src/assets/AssetLocation.hpp | 4 +- engine/src/assets/AssetRef.hpp | 4 +- engine/src/assets/Assets/Model/Model.hpp | 2 +- .../src/assets/Assets/Model/ModelImporter.cpp | 4 +- .../src/assets/Assets/Model/ModelImporter.hpp | 2 +- engine/src/assets/Assets/Texture/Texture.hpp | 2 +- .../assets/Assets/Texture/TextureImporter.cpp | 2 +- engine/src/assets/FilenameValidator.hpp | 2 +- engine/src/assets/ValidatedName.hpp | 6 +- engine/src/components/Camera.hpp | 4 +- engine/src/components/Light.hpp | 8 +- .../src/components/PhysicsBodyComponent.hpp | 2 +- engine/src/components/Transform.cpp | 6 +- engine/src/components/Transform.hpp | 1 - engine/src/core/event/Event.cpp | 3 +- engine/src/core/event/Listener.hpp | 3 +- engine/src/core/event/SignalEvent.hpp | 2 +- engine/src/core/event/Signals.hpp | 1 - engine/src/core/scene/Scene.cpp | 1 - engine/src/core/scene/Scene.hpp | 4 +- engine/src/core/scene/SceneManager.cpp | 4 +- engine/src/ecs/ComponentArray.cpp | 30 +++---- engine/src/ecs/ComponentArray.hpp | 6 +- engine/src/ecs/Coordinator.cpp | 22 ++--- engine/src/ecs/Coordinator.hpp | 18 ++-- engine/src/ecs/QuerySystem.hpp | 1 - engine/src/ecs/SingletonComponent.hpp | 6 +- engine/src/ecs/SingletonComponentMixin.hpp | 3 +- engine/src/renderer/Attributes.hpp | 3 +- engine/src/renderer/Buffer.hpp | 2 +- engine/src/renderer/DrawCommand.hpp | 2 +- engine/src/renderer/Framebuffer.hpp | 6 +- engine/src/renderer/RenderCommand.hpp | 8 +- engine/src/renderer/RenderPass.hpp | 15 ++-- engine/src/renderer/RenderPipeline.cpp | 77 +++++++--------- engine/src/renderer/RenderPipeline.hpp | 4 +- engine/src/renderer/Renderer3D.cpp | 1 - engine/src/renderer/Renderer3D.hpp | 1 - engine/src/renderer/Shader.cpp | 20 ++--- engine/src/renderer/ShaderLibrary.cpp | 2 +- engine/src/renderer/UniformCache.cpp | 18 ++-- .../src/renderer/opengl/OpenGlFramebuffer.cpp | 33 ++++--- .../src/renderer/opengl/OpenGlFramebuffer.hpp | 10 +-- .../src/renderer/opengl/OpenGlRendererApi.cpp | 6 +- engine/src/renderer/opengl/OpenGlShader.cpp | 52 ++++++----- .../opengl/OpenGlShaderReflection.cpp | 6 +- .../opengl/OpenGlShaderReflection.hpp | 1 - .../src/renderer/opengl/OpenGlTexture2D.cpp | 1 - engine/src/renderer/opengl/OpenGlWindow.cpp | 1 - engine/src/renderer/primitives/Billboard.cpp | 4 +- engine/src/renderer/primitives/Cube.cpp | 3 +- engine/src/renderer/primitives/Pyramid.cpp | 2 - engine/src/renderer/primitives/Sphere.cpp | 7 +- .../src/renderer/primitives/Tetrahedron.cpp | 16 +--- engine/src/scripting/native/HostString.cpp | 3 +- engine/src/scripting/native/HostString.hpp | 1 - engine/src/scripting/native/ManagedApi.hpp | 3 +- engine/src/scripting/native/NativeApi.cpp | 32 +++---- engine/src/scripting/native/NativeApi.hpp | 9 +- engine/src/scripting/native/Scripting.cpp | 8 +- engine/src/scripting/native/Scripting.hpp | 9 +- engine/src/scripting/native/ui/Field.hpp | 2 - engine/src/systems/CameraSystem.cpp | 14 +-- engine/src/systems/PhysicsSystem.cpp | 89 +++++++++++-------- engine/src/systems/PhysicsSystem.hpp | 61 ++++++------- engine/src/systems/RenderBillboardSystem.cpp | 26 +++--- engine/src/systems/RenderCommandSystem.cpp | 30 +++---- engine/src/systems/ScriptingSystem.cpp | 16 ++-- .../src/systems/TransformHierarchySystem.cpp | 1 - .../src/systems/TransformHierarchySystem.hpp | 2 +- engine/src/systems/TransformMatrixSystem.hpp | 1 + 75 files changed, 370 insertions(+), 419 deletions(-) diff --git a/engine/src/Application.cpp b/engine/src/Application.cpp index 47b372eaa..3a9df72e0 100644 --- a/engine/src/Application.cpp +++ b/engine/src/Application.cpp @@ -25,7 +25,6 @@ #include "components/Model.hpp" #include "components/Name.hpp" #include "components/Parent.hpp" -#include "components/Render3D.hpp" #include "components/RenderContext.hpp" #include "components/SceneComponents.hpp" #include "components/StaticMesh.hpp" @@ -75,7 +74,6 @@ namespace nexo { void Application::registerEcsComponents() const { - m_coordinator->registerComponent(); m_coordinator->registerComponent(); m_coordinator->registerComponent(); @@ -402,7 +400,7 @@ namespace nexo { return; // Create a copy of the children vector since we'll be modifying it during iteration - std::vector childrenCopy = transform->get().children; + const std::vector childrenCopy = transform->get().children; // Delete each child entity recursively for (const auto& childEntity : childrenCopy) diff --git a/engine/src/assets/AssetCatalog.cpp b/engine/src/assets/AssetCatalog.cpp index 1a8186ed9..cd1f3dfd6 100644 --- a/engine/src/assets/AssetCatalog.cpp +++ b/engine/src/assets/AssetCatalog.cpp @@ -14,13 +14,11 @@ #include "AssetCatalog.hpp" -#include - #include namespace nexo::assets { - void AssetCatalog::deleteAsset(AssetID id) + void AssetCatalog::deleteAsset(const AssetID id) { if (!m_assets.contains(id)) return; @@ -34,21 +32,21 @@ namespace nexo::assets { } } - void AssetCatalog::moveAsset(const GenericAssetRef &asset, const std::string &path) + void AssetCatalog::moveAsset(const GenericAssetRef &asset, const std::string &path) const { if (const auto assetData = asset.lock()) moveAsset(assetData->getID(), path); } - void AssetCatalog::moveAsset(AssetID id, const std::string &path) + void AssetCatalog::moveAsset(const AssetID id, const std::string &path) const { if (!m_assets.contains(id)) return; - auto asset = m_assets.at(id); + const auto asset = m_assets.at(id); asset->m_metadata.location.setPath(path); } - GenericAssetRef AssetCatalog::getAsset(AssetID id) const + GenericAssetRef AssetCatalog::getAsset(const AssetID id) const { if (!m_assets.contains(id)) return GenericAssetRef::null(); @@ -79,7 +77,7 @@ namespace nexo::assets { if (!asset) return GenericAssetRef::null(); // TODO: implement error handling if already exists (once we have the folder tree) - std::shared_ptr shared_ptr = std::move(asset); + const std::shared_ptr shared_ptr = std::move(asset); shared_ptr->m_metadata.location = location; if (shared_ptr->m_metadata.id.is_nil()) shared_ptr->m_metadata.id = boost::uuids::random_generator()(); diff --git a/engine/src/assets/AssetCatalog.hpp b/engine/src/assets/AssetCatalog.hpp index c54f35878..a8a2527c7 100644 --- a/engine/src/assets/AssetCatalog.hpp +++ b/engine/src/assets/AssetCatalog.hpp @@ -20,10 +20,6 @@ #include "Asset.hpp" #include "AssetImporter.hpp" #include "AssetLocation.hpp" - -#include "Assets/Texture/Texture.hpp" - -#include "Assets/Texture/Texture.hpp" #include "assets/AssetRef.hpp" namespace nexo::assets { @@ -86,14 +82,14 @@ namespace nexo::assets { * @param asset The asset to move. * @param path The new location for the asset. */ - void moveAsset(const GenericAssetRef &asset, const std::string &path); + void moveAsset(const GenericAssetRef &asset, const std::string &path) const; /** * @brief Moves an asset to another location. * @param id The ID of the asset to move. * @param path The new location for the asset. */ - void moveAsset(AssetID id, const std::string &path); + void moveAsset(AssetID id, const std::string &path) const; /** diff --git a/engine/src/assets/AssetImporter.cpp b/engine/src/assets/AssetImporter.cpp index f7cec5aad..5436270f7 100644 --- a/engine/src/assets/AssetImporter.cpp +++ b/engine/src/assets/AssetImporter.cpp @@ -32,7 +32,7 @@ namespace nexo::assets { AssetImporter::~AssetImporter() { - for (auto& importers: m_importers | std::views::values) { + for (const auto& importers: m_importers | std::views::values) { for (const auto& importer: importers) { delete importer; } diff --git a/engine/src/assets/AssetLocation.hpp b/engine/src/assets/AssetLocation.hpp index 618b0e6a7..710c42651 100644 --- a/engine/src/assets/AssetLocation.hpp +++ b/engine/src/assets/AssetLocation.hpp @@ -217,13 +217,13 @@ namespace nexo::assets { std::string& extractedPackName ) { - if (auto packNameEndPos = fullLocation.find("::"); packNameEndPos != std::string::npos) { + if (const auto packNameEndPos = fullLocation.find("::"); packNameEndPos != std::string::npos) { extractedPackName = fullLocation.substr(0, packNameEndPos); fullLocation.remove_prefix(packNameEndPos + 2); } else { extractedPackName.clear(); } - if (auto pathStartPos = fullLocation.find('@'); pathStartPos != std::string::npos) { + if (const auto pathStartPos = fullLocation.find('@'); pathStartPos != std::string::npos) { extractedPath = fullLocation.substr(pathStartPos + 1); fullLocation.remove_suffix(fullLocation.size() - pathStartPos); } else { diff --git a/engine/src/assets/AssetRef.hpp b/engine/src/assets/AssetRef.hpp index 3ed52b8ce..488d76660 100644 --- a/engine/src/assets/AssetRef.hpp +++ b/engine/src/assets/AssetRef.hpp @@ -108,7 +108,7 @@ namespace nexo::assets { /** * @brief Requests the AssetCatalog to load the asset */ - void load() { + void load() const { if (auto ptr = lock()) { // TODO: Implement reloadAsset in AssetCatalog // Example: AssetCatalog::getInstance().reloadAsset(ptr); @@ -119,7 +119,7 @@ namespace nexo::assets { /** * @brief Requests the AssetCatalog to unload the asset but maintain the reference */ - void unload() { + void unload() const { if (auto ptr = lock()) { // TODO: Implement unloadAsset in AssetCatalog // Example: AssetCatalog::getInstance().unloadAsset(ptr); diff --git a/engine/src/assets/Assets/Model/Model.hpp b/engine/src/assets/Assets/Model/Model.hpp index 87e02a49b..6c6367deb 100644 --- a/engine/src/assets/Assets/Model/Model.hpp +++ b/engine/src/assets/Assets/Model/Model.hpp @@ -23,7 +23,7 @@ namespace nexo::assets { struct Mesh { std::string name; std::shared_ptr vao; - assets::AssetRef material; + AssetRef material; glm::vec3 localCenter = {0.0f, 0.0f, 0.0f}; }; diff --git a/engine/src/assets/Assets/Model/ModelImporter.cpp b/engine/src/assets/Assets/Model/ModelImporter.cpp index e7eadf92f..b55364b08 100644 --- a/engine/src/assets/Assets/Model/ModelImporter.cpp +++ b/engine/src/assets/Assets/Model/ModelImporter.cpp @@ -211,7 +211,7 @@ namespace nexo::assets { modelPath = Path::getExecutablePath(); LOG(NEXO_WARN, "ModelImporter: Model {}: Model path not given (imported from memory), using executable path for texture lookup.", std::quoted(ctx.location.getFullLocation())); } - std::filesystem::path modelDirectory = modelPath.parent_path(); + const std::filesystem::path modelDirectory = modelPath.parent_path(); for (unsigned int matIdx = 0; matIdx < scene->mNumMaterials; ++matIdx) { aiMaterial const *material = scene->mMaterials[matIdx]; @@ -355,7 +355,7 @@ namespace nexo::assets { return meshNode; } - Mesh ModelImporter::processMesh(const AssetImporterContext& ctx, aiMesh* mesh, [[maybe_unused]] const aiScene* scene) + Mesh ModelImporter::processMesh(const AssetImporterContext& ctx, aiMesh* mesh, [[maybe_unused]] const aiScene* scene) const { std::shared_ptr vao = renderer::createVertexArray(); auto vertexBuffer = renderer::createVertexBuffer(mesh->mNumVertices * sizeof(renderer::NxVertex)); diff --git a/engine/src/assets/Assets/Model/ModelImporter.hpp b/engine/src/assets/Assets/Model/ModelImporter.hpp index 17adac444..b2115e2f4 100644 --- a/engine/src/assets/Assets/Model/ModelImporter.hpp +++ b/engine/src/assets/Assets/Model/ModelImporter.hpp @@ -42,7 +42,7 @@ namespace nexo::assets { void loadSceneMaterials(AssetImporterContext& ctx, const aiScene* scene); MeshNode processNode(AssetImporterContext& ctx, aiNode const *node, const aiScene* scene); - Mesh processMesh(const AssetImporterContext& ctx, aiMesh* mesh, const aiScene* scene); + Mesh processMesh(const AssetImporterContext& ctx, aiMesh* mesh, const aiScene* scene) const; static renderer::NxTextureFormat convertAssimpHintToNxTextureFormat(const char achFormatHint[9]); static glm::mat4 convertAssimpMatrixToGLM(const aiMatrix4x4& matrix); diff --git a/engine/src/assets/Assets/Texture/Texture.hpp b/engine/src/assets/Assets/Texture/Texture.hpp index fd8e67245..1ca8faf1a 100644 --- a/engine/src/assets/Assets/Texture/Texture.hpp +++ b/engine/src/assets/Assets/Texture/Texture.hpp @@ -73,7 +73,7 @@ namespace nexo::assets { * * @throws NxTextureInvalidSize If the dimensions exceed the maximum texture size. */ - Texture(unsigned int width, unsigned int height) + Texture(const unsigned int width, const unsigned int height) : Asset() { const auto texture = renderer::NxTexture2D::create(width, height); diff --git a/engine/src/assets/Assets/Texture/TextureImporter.cpp b/engine/src/assets/Assets/Texture/TextureImporter.cpp index 917f7b07f..c59894379 100644 --- a/engine/src/assets/Assets/Texture/TextureImporter.cpp +++ b/engine/src/assets/Assets/Texture/TextureImporter.cpp @@ -40,7 +40,7 @@ namespace nexo::assets { if (std::holds_alternative(ctx.input)) rendererTexture = renderer::NxTexture2D::create(std::get(ctx.input).filePath.string()); else { - auto data = std::get(ctx.input).memoryData; + const auto data = std::get(ctx.input).memoryData; rendererTexture = renderer::NxTexture2D::create(data.data(), static_cast(data.size())); } auto assetData = std::make_unique(); diff --git a/engine/src/assets/FilenameValidator.hpp b/engine/src/assets/FilenameValidator.hpp index 30c021ea4..afb74cd22 100644 --- a/engine/src/assets/FilenameValidator.hpp +++ b/engine/src/assets/FilenameValidator.hpp @@ -32,7 +32,7 @@ namespace nexo::assets { "LPT8", "LPT9" }; - [[nodiscard]] static std::optional validate(std::string_view name) + [[nodiscard]] static std::optional validate(const std::string_view name) { if (name.empty()) return "Cannot be empty."; diff --git a/engine/src/assets/ValidatedName.hpp b/engine/src/assets/ValidatedName.hpp index 3d68217d4..002f3345f 100644 --- a/engine/src/assets/ValidatedName.hpp +++ b/engine/src/assets/ValidatedName.hpp @@ -102,9 +102,9 @@ namespace nexo::assets { }; template - ValidatedName& ValidatedName::operator=(std::string_view name) + ValidatedName& ValidatedName::operator=(const std::string_view name) { - if (auto errorMessage = validate(name); errorMessage.has_value()) + if (const auto errorMessage = validate(name); errorMessage.has_value()) THROW_EXCEPTION(InvalidName, name, errorMessage.value()); _value = name; return *this; @@ -125,7 +125,7 @@ namespace nexo::assets { } template - std::optional ValidatedName::rename(std::string_view name) + std::optional ValidatedName::rename(const std::string_view name) { if (auto errorMessage = validate(name); errorMessage.has_value()) return errorMessage; diff --git a/engine/src/components/Camera.hpp b/engine/src/components/Camera.hpp index c276a073c..4448ef59d 100644 --- a/engine/src/components/Camera.hpp +++ b/engine/src/components/Camera.hpp @@ -19,8 +19,6 @@ #include "ecs/Definitions.hpp" #include "renderer/RenderPipeline.hpp" #include -#include -#include namespace nexo::components { @@ -85,7 +83,7 @@ namespace nexo::components { * @param newWidth The new width for the viewport. * @param newHeight The new height for the viewport. */ - void resize(const unsigned int newWidth, const unsigned int newHeight); + void resize(unsigned int newWidth, unsigned int newHeight); struct Memento { unsigned int width; diff --git a/engine/src/components/Light.hpp b/engine/src/components/Light.hpp index bb07f2247..a9c400178 100644 --- a/engine/src/components/Light.hpp +++ b/engine/src/components/Light.hpp @@ -36,7 +36,7 @@ namespace nexo::components { color = memento.color; } - Memento save() const + [[nodiscard]] Memento save() const { return {color}; } @@ -64,7 +64,7 @@ namespace nexo::components { color = memento.color; } - Memento save() const + [[nodiscard]] Memento save() const { return {direction, color}; } @@ -94,7 +94,7 @@ namespace nexo::components { constant = memento.constant; } - Memento save() const + [[nodiscard]] Memento save() const { return {color, linear, quadratic, maxDistance, constant}; } @@ -133,7 +133,7 @@ namespace nexo::components { constant = memento.constant; } - Memento save() const + [[nodiscard]] Memento save() const { return {direction, color, cutOff, outerCutoff, linear, quadratic, maxDistance, constant}; } diff --git a/engine/src/components/PhysicsBodyComponent.hpp b/engine/src/components/PhysicsBodyComponent.hpp index 38c9f0c88..38fc7407a 100644 --- a/engine/src/components/PhysicsBodyComponent.hpp +++ b/engine/src/components/PhysicsBodyComponent.hpp @@ -21,6 +21,6 @@ namespace nexo::components { struct PhysicsBodyComponent { enum class Type { Static, Dynamic }; JPH::BodyID bodyID; - Type type; + Type type{}; }; } diff --git a/engine/src/components/Transform.cpp b/engine/src/components/Transform.cpp index 0b28922c0..670bcc9e9 100644 --- a/engine/src/components/Transform.cpp +++ b/engine/src/components/Transform.cpp @@ -14,6 +14,8 @@ #include "Transform.hpp" +#include + namespace nexo::components { void TransformComponent::restore(const TransformComponent::Memento &memento) { @@ -30,14 +32,14 @@ namespace nexo::components { return {pos, quat, size, localMatrix, localCenter, children}; } - void TransformComponent::addChild(ecs::Entity childEntity) + void TransformComponent::addChild(const ecs::Entity childEntity) { if (std::ranges::find(children, childEntity) != children.end()) return; children.push_back(childEntity); } - void TransformComponent::removeChild(ecs::Entity childEntity) + void TransformComponent::removeChild(const ecs::Entity childEntity) { children.erase(std::ranges::remove(children, childEntity).begin(), children.end()); } diff --git a/engine/src/components/Transform.hpp b/engine/src/components/Transform.hpp index 8f6dadc66..9806626e0 100644 --- a/engine/src/components/Transform.hpp +++ b/engine/src/components/Transform.hpp @@ -18,7 +18,6 @@ #include #include #include -#include namespace nexo::components { diff --git a/engine/src/core/event/Event.cpp b/engine/src/core/event/Event.cpp index ab378d7c1..7168b43c2 100644 --- a/engine/src/core/event/Event.cpp +++ b/engine/src/core/event/Event.cpp @@ -27,7 +27,7 @@ namespace nexo::event { // Store a reference to the event to avoid evaluating *event with side effects. const IEvent &ev = *event; if (const std::type_index typeIndex(typeid(ev)); m_listeners.contains(typeIndex)) { - for (auto listener : m_listeners[typeIndex]) { + for (const auto listener : m_listeners[typeIndex]) { event->trigger(*listener); if (event->consumed) break; @@ -37,7 +37,6 @@ namespace nexo::event { } } - void EventManager::clearEvents() { m_eventQueue.clear(); diff --git a/engine/src/core/event/Listener.hpp b/engine/src/core/event/Listener.hpp index 80a3e1e32..e171ca7cb 100644 --- a/engine/src/core/event/Listener.hpp +++ b/engine/src/core/event/Listener.hpp @@ -13,7 +13,6 @@ /////////////////////////////////////////////////////////////////////////////// #pragma once -#include #include namespace nexo::event { @@ -58,7 +57,7 @@ namespace nexo::event { * * @param event The event to handle. */ - virtual void handleEvent(T &) = 0; + virtual void handleEvent(T &event) = 0; }; /** diff --git a/engine/src/core/event/SignalEvent.hpp b/engine/src/core/event/SignalEvent.hpp index 382302cb5..cc4ef58fb 100644 --- a/engine/src/core/event/SignalEvent.hpp +++ b/engine/src/core/event/SignalEvent.hpp @@ -23,7 +23,7 @@ namespace nexo::event { class EventAnySignal final : public Event { public: - explicit EventAnySignal(int signal) : signal(signal) {}; + explicit EventAnySignal(const int signal) : signal(signal) {}; int signal; friend std::ostream &operator<<(std::ostream &os, const EventAnySignal &event) diff --git a/engine/src/core/event/Signals.hpp b/engine/src/core/event/Signals.hpp index 0d5b24769..63b1790f9 100644 --- a/engine/src/core/event/Signals.hpp +++ b/engine/src/core/event/Signals.hpp @@ -17,7 +17,6 @@ #include #include - namespace nexo::utils { #ifdef _WIN32 diff --git a/engine/src/core/scene/Scene.cpp b/engine/src/core/scene/Scene.cpp index 77b3dceb1..c33a5ffa8 100644 --- a/engine/src/core/scene/Scene.cpp +++ b/engine/src/core/scene/Scene.cpp @@ -16,7 +16,6 @@ #include #include "components/Parent.hpp" -#include "components/Render.hpp" #include "components/SceneComponents.hpp" #include "components/Transform.hpp" #include "components/Uuid.hpp" diff --git a/engine/src/core/scene/Scene.hpp b/engine/src/core/scene/Scene.hpp index bc6331f5a..eeae5df50 100644 --- a/engine/src/core/scene/Scene.hpp +++ b/engine/src/core/scene/Scene.hpp @@ -56,7 +56,7 @@ namespace nexo::scene { * @param entity The entity identifier to add. */ void addEntity(ecs::Entity entity); - void addChildEntityToScene(const ecs::Entity entity); + void addChildEntityToScene(ecs::Entity entity); /** * @brief Removes an entity from the scene. @@ -90,7 +90,7 @@ namespace nexo::scene { [[nodiscard]] bool isRendered() const { return m_rendered; } [[nodiscard]] const std::string& getName() const {return m_sceneName;}; - void setName(std::string_view newName) { m_sceneName = newName; } + void setName(const std::string_view newName) { m_sceneName = newName; } [[nodiscard]] unsigned int getId() const {return m_id;}; [[nodiscard]] const std::string &getUuid() const {return m_uuid;} [[nodiscard]] const std::set &getEntities() const {return m_entities;}; diff --git a/engine/src/core/scene/SceneManager.cpp b/engine/src/core/scene/SceneManager.cpp index df473a5ad..18c3ace63 100644 --- a/engine/src/core/scene/SceneManager.cpp +++ b/engine/src/core/scene/SceneManager.cpp @@ -45,12 +45,12 @@ namespace nexo::scene { return newScene.getId(); } - void SceneManager::deleteScene(unsigned int id) + void SceneManager::deleteScene(const unsigned int id) { m_scenes.erase(id); } - Scene &SceneManager::getScene(unsigned int id) + Scene &SceneManager::getScene(const unsigned int id) { return m_scenes.at(id); } diff --git a/engine/src/ecs/ComponentArray.cpp b/engine/src/ecs/ComponentArray.cpp index 491325f3e..ad8c2a3f1 100644 --- a/engine/src/ecs/ComponentArray.cpp +++ b/engine/src/ecs/ComponentArray.cpp @@ -27,7 +27,7 @@ namespace nexo::ecs { m_componentData.reserve(m_capacity * m_componentSize); } - void TypeErasedComponentArray::insert(Entity entity, const void* componentData) + void TypeErasedComponentArray::insert(const Entity entity, const void* componentData) { insertRaw(entity, componentData); } @@ -49,7 +49,7 @@ namespace nexo::ecs { m_dense.push_back(entity); // Resize component data vector if needed - size_t requiredSize = (m_size + 1) * m_componentSize; + const size_t requiredSize = (m_size + 1) * m_componentSize; if (m_componentData.size() < requiredSize) { m_componentData.resize(requiredSize); } @@ -61,7 +61,7 @@ namespace nexo::ecs { ++m_size; } - void TypeErasedComponentArray::remove(Entity entity) + void TypeErasedComponentArray::remove(const Entity entity) { if (!hasComponent(entity)) THROW_EXCEPTION(ComponentNotFound, entity); @@ -96,18 +96,18 @@ namespace nexo::ecs { shrinkIfNeeded(); } - bool TypeErasedComponentArray::hasComponent(Entity entity) const + bool TypeErasedComponentArray::hasComponent(const Entity entity) const { return (entity < m_sparse.size() && m_sparse[entity] != INVALID_ENTITY); } - void TypeErasedComponentArray::entityDestroyed(Entity entity) + void TypeErasedComponentArray::entityDestroyed(const Entity entity) { if (hasComponent(entity)) remove(entity); } - void TypeErasedComponentArray::duplicateComponent(Entity sourceEntity, Entity destEntity) + void TypeErasedComponentArray::duplicateComponent(const Entity sourceEntity, const Entity destEntity) { if (!hasComponent(sourceEntity)) THROW_EXCEPTION(ComponentNotFound, sourceEntity); @@ -126,14 +126,14 @@ namespace nexo::ecs { return m_size; } - void* TypeErasedComponentArray::getRawComponent(Entity entity) + void* TypeErasedComponentArray::getRawComponent(const Entity entity) { if (!hasComponent(entity)) return nullptr; return m_componentData.data() + m_sparse[entity] * m_componentSize; } - const void* TypeErasedComponentArray::getRawComponent(Entity entity) const + const void* TypeErasedComponentArray::getRawComponent(const Entity entity) const { if (!hasComponent(entity)) return nullptr; @@ -155,19 +155,19 @@ namespace nexo::ecs { return {m_dense.data(), m_size}; } - Entity TypeErasedComponentArray::getEntityAtIndex(size_t index) const + Entity TypeErasedComponentArray::getEntityAtIndex(const size_t index) const { if (index >= m_size) THROW_EXCEPTION(OutOfRange, index); return m_dense[index]; } - void TypeErasedComponentArray::addToGroup(Entity entity) + void TypeErasedComponentArray::addToGroup(const Entity entity) { if (!hasComponent(entity)) THROW_EXCEPTION(ComponentNotFound, entity); - size_t index = m_sparse[entity]; + const size_t index = m_sparse[entity]; if (index < m_groupSize) return; @@ -180,12 +180,12 @@ namespace nexo::ecs { ++m_groupSize; } - void TypeErasedComponentArray::removeFromGroup(Entity entity) + void TypeErasedComponentArray::removeFromGroup(const Entity entity) { if (!hasComponent(entity)) THROW_EXCEPTION(ComponentNotFound, entity); - size_t index = m_sparse[entity]; + const size_t index = m_sparse[entity]; if (index >= m_groupSize) return; @@ -210,7 +210,7 @@ namespace nexo::ecs { + sizeof(Entity) * m_dense.capacity(); } - void TypeErasedComponentArray::ensureSparseCapacity(Entity entity) + void TypeErasedComponentArray::ensureSparseCapacity(const Entity entity) { if (entity >= m_sparse.size()) { size_t newSize = m_sparse.size(); @@ -239,7 +239,7 @@ namespace nexo::ecs { void TypeErasedComponentArray::shrinkIfNeeded() { if (m_size < m_componentData.capacity() / 4 && m_componentData.capacity() > m_capacity * m_componentSize * 2) { - size_t newCapacity = std::max(m_size * 2, static_cast(m_capacity)) * m_componentSize; + size_t newCapacity = std::max(m_size * 2, m_capacity) * m_componentSize; if (newCapacity < m_capacity * m_componentSize) newCapacity = m_capacity * m_componentSize; diff --git a/engine/src/ecs/ComponentArray.hpp b/engine/src/ecs/ComponentArray.hpp index bcdc7f58f..76c8effc5 100644 --- a/engine/src/ecs/ComponentArray.hpp +++ b/engine/src/ecs/ComponentArray.hpp @@ -171,7 +171,7 @@ namespace nexo::ecs { return &m_componentArray[m_sparse[entity]]; } - [[nodiscard]] const void* getRawComponent(Entity entity) const override + [[nodiscard]] const void* getRawComponent(const Entity entity) const override { if (!hasComponent(entity)) return nullptr; @@ -335,7 +335,7 @@ namespace nexo::ecs { return m_componentArray[m_sparse[entity]]; } - void duplicateComponent(Entity sourceEntity, Entity destEntity) override + void duplicateComponent(const Entity sourceEntity, const Entity destEntity) override { if (!hasComponent(sourceEntity)) THROW_EXCEPTION(ComponentNotFound, sourceEntity); @@ -608,7 +608,7 @@ namespace nexo::ecs { { if (m_size < m_componentArray.capacity() / 4 && m_componentArray.capacity() > capacity * 2) { // Only shrink if vectors are significantly oversized to avoid frequent reallocations - size_t newCapacity = std::max(m_size * 2, static_cast(capacity)); + size_t newCapacity = std::max(m_size * 2, capacity); if (newCapacity < capacity) newCapacity = capacity; diff --git a/engine/src/ecs/Coordinator.cpp b/engine/src/ecs/Coordinator.cpp index a061195e6..4204d3f95 100644 --- a/engine/src/ecs/Coordinator.cpp +++ b/engine/src/ecs/Coordinator.cpp @@ -59,7 +59,7 @@ namespace nexo::ecs { return types; } - std::vector Coordinator::getAllComponentTypeIndices(Entity entity) const + std::vector Coordinator::getAllComponentTypeIndices(const Entity entity) const { const std::vector& types = getAllComponentTypes(entity); std::vector typeIndices; @@ -110,32 +110,32 @@ namespace nexo::ecs { bool Coordinator::supportsMementoPattern(const std::any& component) const { - auto typeId = std::type_index(component.type()); - auto it = m_supportsMementoPattern.find(typeId); + const auto typeId = std::type_index(component.type()); + const auto it = m_supportsMementoPattern.find(typeId); return (it != m_supportsMementoPattern.end()) && it->second; } std::any Coordinator::saveComponent(const std::any& component) const { - auto typeId = std::type_index(component.type()); - auto it = m_saveComponentFunctions.find(typeId); + const auto typeId = std::type_index(component.type()); + const auto it = m_saveComponentFunctions.find(typeId); if (it != m_saveComponentFunctions.end()) return it->second(component); - return std::any(); + return {}; } std::any Coordinator::restoreComponent(const std::any& memento, const std::type_index& componentType) const { - auto it = m_restoreComponentFunctions.find(componentType); + const auto it = m_restoreComponentFunctions.find(componentType); if (it != m_restoreComponentFunctions.end()) return it->second(memento); - return std::any(); + return {}; } - void Coordinator::addComponentAny(Entity entity, const std::type_index& typeIndex, const std::any& component) + void Coordinator::addComponentAny(const Entity entity, const std::type_index& typeIndex, const std::any& component) { - auto it = m_addComponentFunctions.find(typeIndex); + const auto it = m_addComponentFunctions.find(typeIndex); if (it != m_addComponentFunctions.end()) it->second(entity, component); } -} \ No newline at end of file +} diff --git a/engine/src/ecs/Coordinator.hpp b/engine/src/ecs/Coordinator.hpp index 300d466a1..946431d7c 100644 --- a/engine/src/ecs/Coordinator.hpp +++ b/engine/src/ecs/Coordinator.hpp @@ -142,20 +142,20 @@ namespace nexo::ecs { { m_componentManager->registerComponent(); - m_getComponentFunctions[typeid(T)] = [this](Entity entity) -> std::any { + m_getComponentFunctions[typeid(T)] = [this](const Entity entity) -> std::any { return this->getComponent(entity); }; - m_getComponentPointers[typeid(T)] = [this](Entity entity) -> std::any { + m_getComponentPointers[typeid(T)] = [this](const Entity entity) -> std::any { auto opt = this->tryGetComponent(entity); if (!opt.has_value()) - return std::any(); + return {}; T* ptr = &opt.value().get(); return std::any(static_cast(ptr)); }; m_typeIDtoTypeIndex.emplace(getComponentType(), typeid(T)); - m_addComponentFunctions[typeid(T)] = [this](Entity entity, const std::any& componentAny) { + m_addComponentFunctions[typeid(T)] = [this](const Entity entity, const std::any& componentAny) { T component = std::any_cast(componentAny); this->addComponent(entity, component); }; @@ -184,7 +184,7 @@ namespace nexo::ecs { ComponentType registerComponent(const size_t componentSize, const size_t initialCapacity = 1024) { - auto typeID = m_componentManager->registerComponent(componentSize, initialCapacity); + const auto typeID = m_componentManager->registerComponent(componentSize, initialCapacity); return typeID; } @@ -368,7 +368,7 @@ namespace nexo::ecs { return m_addComponentFunctions; } - Signature getSignature(Entity entity) const { + Signature getSignature(const Entity entity) const { return m_entityManager->getSignature(entity); } @@ -440,10 +440,10 @@ namespace nexo::ecs { const Signature entitySignature = m_entityManager->getSignature(entity); // Entity must have all required components - bool hasAllRequired = (entitySignature & requiredSignature) == requiredSignature; + const bool hasAllRequired = (entitySignature & requiredSignature) == requiredSignature; // Entity must not have any excluded components - bool hasAnyExcluded = (entitySignature & excludeSignature).any(); + const bool hasAnyExcluded = (entitySignature & excludeSignature).any(); if (hasAllRequired && !hasAnyExcluded) result.push_back(entity); @@ -606,7 +606,7 @@ namespace nexo::ecs { result.reserve(livingEntities.size()); for (Entity entity : livingEntities) { - bool hasAll = (entityHasComponent(entity) && ...); + const bool hasAll = (entityHasComponent(entity) && ...); if (hasAll) { result.push_back(entity); diff --git a/engine/src/ecs/QuerySystem.hpp b/engine/src/ecs/QuerySystem.hpp index d7bbd3738..7328c6243 100644 --- a/engine/src/ecs/QuerySystem.hpp +++ b/engine/src/ecs/QuerySystem.hpp @@ -20,7 +20,6 @@ #include "ComponentArray.hpp" #include "Coordinator.hpp" #include "SingletonComponentMixin.hpp" -#include #include #include diff --git a/engine/src/ecs/SingletonComponent.hpp b/engine/src/ecs/SingletonComponent.hpp index c37affc9b..14c4818ec 100644 --- a/engine/src/ecs/SingletonComponent.hpp +++ b/engine/src/ecs/SingletonComponent.hpp @@ -125,7 +125,7 @@ namespace nexo::ecs { template T &getSingletonComponent() { - ComponentType typeName = getUniqueComponentTypeID(); + const ComponentType typeName = getUniqueComponentTypeID(); if (!m_singletonComponents.contains(typeName)) THROW_EXCEPTION(SingletonComponentNotRegistered); @@ -144,7 +144,7 @@ namespace nexo::ecs { template std::shared_ptr getRawSingletonComponent() { - ComponentType typeName = getUniqueComponentTypeID(); + const ComponentType typeName = getUniqueComponentTypeID(); if (!m_singletonComponents.contains(typeName)) THROW_EXCEPTION(SingletonComponentNotRegistered); @@ -162,7 +162,7 @@ namespace nexo::ecs { template void unregisterSingletonComponent() { - ComponentType typeName = getUniqueComponentTypeID(); + const ComponentType typeName = getUniqueComponentTypeID(); if (!m_singletonComponents.contains(typeName)) THROW_EXCEPTION(SingletonComponentNotRegistered); diff --git a/engine/src/ecs/SingletonComponentMixin.hpp b/engine/src/ecs/SingletonComponentMixin.hpp index b9cf1d628..a85f68b5a 100644 --- a/engine/src/ecs/SingletonComponentMixin.hpp +++ b/engine/src/ecs/SingletonComponentMixin.hpp @@ -15,7 +15,6 @@ #include "Access.hpp" #include "SingletonComponent.hpp" -#include #include namespace nexo::ecs { @@ -93,7 +92,7 @@ namespace nexo::ecs { void cacheSingletonComponent() { auto* derived = static_cast(this); - std::shared_ptr instance = derived->coord->template getRawSingletonComponent(); + const std::shared_ptr instance = derived->coord->template getRawSingletonComponent(); // Store in the type-specific cache auto typedInstance = std::static_pointer_cast>(instance); diff --git a/engine/src/renderer/Attributes.hpp b/engine/src/renderer/Attributes.hpp index 536703b62..09de8cdf0 100644 --- a/engine/src/renderer/Attributes.hpp +++ b/engine/src/renderer/Attributes.hpp @@ -15,7 +15,6 @@ #include - namespace nexo::renderer { struct RequiredAttributes { @@ -36,7 +35,7 @@ namespace nexo::renderer { return bitsUnion.bits == o.bitsUnion.bits; } - bool compatibleWith(RequiredAttributes const& o) const { + [[nodiscard]] bool compatibleWith(RequiredAttributes const& o) const { return (bitsUnion.bits & o.bitsUnion.bits) == bitsUnion.bits; } }; diff --git a/engine/src/renderer/Buffer.hpp b/engine/src/renderer/Buffer.hpp index 05bfd85a2..57b17a22c 100644 --- a/engine/src/renderer/Buffer.hpp +++ b/engine/src/renderer/Buffer.hpp @@ -64,7 +64,7 @@ namespace nexo::renderer { * - FLOAT3 will return 12 (3 floats, 4 bytes each). * - MAT4 will return 64 (4x4 matrix of floats). */ - static unsigned int shaderDataTypeSize(NxShaderDataType type) + static unsigned int shaderDataTypeSize(const NxShaderDataType type) { switch (type) { diff --git a/engine/src/renderer/DrawCommand.hpp b/engine/src/renderer/DrawCommand.hpp index 1c7de47df..3bf4045c8 100644 --- a/engine/src/renderer/DrawCommand.hpp +++ b/engine/src/renderer/DrawCommand.hpp @@ -35,7 +35,7 @@ namespace nexo::renderer { 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; - auto vb = createVertexBuffer(sizeof(quadVertices)); + const auto vb = createVertexBuffer(sizeof(quadVertices)); vb->setData(quadVertices, sizeof(quadVertices)); vb->setLayout({ {NxShaderDataType::FLOAT2, "aPosition"}, diff --git a/engine/src/renderer/Framebuffer.hpp b/engine/src/renderer/Framebuffer.hpp index 09237e60c..d9047d45c 100644 --- a/engine/src/renderer/Framebuffer.hpp +++ b/engine/src/renderer/Framebuffer.hpp @@ -85,7 +85,7 @@ namespace nexo::renderer { */ struct NxFrameBufferAttachmentsSpecifications { NxFrameBufferAttachmentsSpecifications() = default; - NxFrameBufferAttachmentsSpecifications(std::initializer_list attachments) : attachments(attachments) {}; + NxFrameBufferAttachmentsSpecifications(const std::initializer_list attachments) : attachments(attachments) {}; std::vector attachments; }; @@ -177,7 +177,7 @@ namespace nexo::renderer { virtual void setClearColor(const glm::vec4 &color) = 0; - virtual void copy(const std::shared_ptr source) = 0; + virtual void copy(std::shared_ptr source) = 0; /** * @brief Retrieves the unique OpenGL ID of the framebuffer. @@ -216,7 +216,7 @@ namespace nexo::renderer { * @return T The pixel data. */ template - T getPixel(unsigned int attachmentIndex, int x, int y) const + T getPixel(const unsigned int attachmentIndex, const int x, const int y) const { T result; getPixelWrapper(attachmentIndex, x, y, &result, typeid(T)); diff --git a/engine/src/renderer/RenderCommand.hpp b/engine/src/renderer/RenderCommand.hpp index 036613948..8eeb095b9 100644 --- a/engine/src/renderer/RenderCommand.hpp +++ b/engine/src/renderer/RenderCommand.hpp @@ -91,7 +91,7 @@ namespace nexo::renderer { */ static void setClearColor(const glm::vec4 &color) { _rendererApi->setClearColor(color); }; - static void setClearDepth(float depth) { _rendererApi->setClearDepth(depth); }; + static void setClearDepth(const float depth) { _rendererApi->setClearDepth(depth); }; /** * @brief Clears the screen using the current clear color. @@ -212,17 +212,17 @@ namespace nexo::renderer { _rendererApi->setStencilOp(sfail, dpfail, dppass); } - static void setCulling(bool enable) + static void setCulling(const bool enable) { _rendererApi->setCulling(enable); } - static void setCulledFace(CulledFace face) + static void setCulledFace(const CulledFace face) { _rendererApi->setCulledFace(face); } - static void setWindingOrder(WindingOrder order) + static void setWindingOrder(const WindingOrder order) { _rendererApi->setWindingOrder(order); } diff --git a/engine/src/renderer/RenderPass.hpp b/engine/src/renderer/RenderPass.hpp index 94ced7670..f93726e12 100644 --- a/engine/src/renderer/RenderPass.hpp +++ b/engine/src/renderer/RenderPass.hpp @@ -13,6 +13,7 @@ /////////////////////////////////////////////////////////////////////////////// #pragma once #include +#include #include #include @@ -24,21 +25,21 @@ namespace nexo::renderer { class RenderPass { public: - RenderPass(PassId id, const std::string& debugName = "") : id(id), name(debugName) {} + explicit RenderPass(const PassId id, std::string debugName = "") : id(id), name(std::move(debugName)) {} virtual ~RenderPass() = default; // The actual rendering work virtual void execute(RenderPipeline& pipeline) = 0; virtual void resize(unsigned int width, unsigned int height) = 0; - void setFinal(bool isFinal) {m_isFinal = isFinal;}; - bool isFinal() const {return m_isFinal;} + void setFinal(const bool isFinal) {m_isFinal = isFinal;}; + [[nodiscard]] bool isFinal() const {return m_isFinal;} - PassId getId() const { return id; } - const std::string& getName() const { return name; } + [[nodiscard]] PassId getId() const { return id; } + [[nodiscard]] const std::string& getName() const { return name; } std::vector &getPrerequisites() { return prerequisites; } - const std::vector &getPrerequisites() const { return prerequisites; } + [[nodiscard]] const std::vector &getPrerequisites() const { return prerequisites; } std::vector &getEffects() { return effects; } - const std::vector &getEffects() const { return effects; } + [[nodiscard]] const std::vector &getEffects() const { return effects; } protected: bool m_isFinal = false; PassId id; diff --git a/engine/src/renderer/RenderPipeline.cpp b/engine/src/renderer/RenderPipeline.cpp index e85b2a3f4..33b0402f0 100644 --- a/engine/src/renderer/RenderPipeline.cpp +++ b/engine/src/renderer/RenderPipeline.cpp @@ -15,12 +15,13 @@ #include "Framebuffer.hpp" #include #include +#include namespace nexo::renderer { PassId RenderPipeline::addRenderPass(std::shared_ptr pass) { // If this is the first pass, set it as the final output - PassId id = pass->getId(); + const PassId id = pass->getId(); passes[id] = std::move(pass); if (passes.size() == 1) setFinalOutputPass(id); @@ -28,44 +29,38 @@ namespace nexo::renderer { return id; } - void RenderPipeline::removeRenderPass(PassId id) + void RenderPipeline::removeRenderPass(const PassId id) { if (!passes.contains(id)) return; - auto& pass = passes[id]; + const auto &pass = passes[id]; // Save prerequisites and effects before removal std::vector prerequisites = pass->getPrerequisites(); std::vector effects = pass->getEffects(); // For each prerequisite -> effect pair, create a new relationship - for (PassId prereqId : prerequisites) { - for (PassId effectId : effects) { + for (const PassId prereqId : prerequisites) { + for (const PassId effectId : effects) { addPrerequisite(effectId, prereqId); addEffect(prereqId, effectId); } } // Remove this pass from all prerequisites lists - for (auto& [passId, p] : passes) { + for (const auto &[passId, p] : passes) { auto& prereqs = p->getPrerequisites(); - prereqs.erase( - std::remove(prereqs.begin(), prereqs.end(), id), - prereqs.end() - ); + std::erase(prereqs, id); } // Remove this pass from all effects lists - for (auto& [passId, p] : passes) { + for (const auto& [passId, p] : passes) { auto& effs = p->getEffects(); - effs.erase( - std::remove(effs.begin(), effs.end(), id), - effs.end() - ); + std::erase(effs, id); } // First remove the pass, then find a new final output if needed - bool needNewFinalOutput = (finalOutputPass == static_cast(id)); + const bool needNewFinalOutput = (finalOutputPass == static_cast(id)); // Remove the pass from the maps passes.erase(id); @@ -79,7 +74,7 @@ namespace nexo::renderer { finalOutputPass = -1; } else { // Prefer terminal passes (those with no effects) - auto terminalPasses = findTerminalPasses(); + const auto terminalPasses = findTerminalPasses(); if (!terminalPasses.empty()) { setFinalOutputPass(terminalPasses[0]); } else { @@ -91,7 +86,7 @@ namespace nexo::renderer { m_isDirty = true; } - void RenderPipeline::addPrerequisite(PassId pass, PassId prerequisite) + void RenderPipeline::addPrerequisite(const PassId pass, const PassId prerequisite) { if (!passes.contains(pass) || !passes.contains(prerequisite)) return; @@ -102,20 +97,17 @@ namespace nexo::renderer { m_isDirty = true; } - void RenderPipeline::removePrerequisite(PassId pass, PassId prerequisite) + void RenderPipeline::removePrerequisite(const PassId pass, const PassId prerequisite) { if (!passes.contains(pass)) return; auto& prereqs = passes[pass]->getPrerequisites(); - prereqs.erase( - std::remove(prereqs.begin(), prereqs.end(), prerequisite), - prereqs.end() - ); + std::erase(prereqs, prerequisite); m_isDirty = true; } - void RenderPipeline::addEffect(PassId pass, PassId effect) + void RenderPipeline::addEffect(const PassId pass, const PassId effect) { if (!passes.contains(pass) || !passes.contains(effect)) return; @@ -126,28 +118,25 @@ namespace nexo::renderer { m_isDirty = true; } - void RenderPipeline::removeEffect(PassId pass, PassId effect) + void RenderPipeline::removeEffect(const PassId pass, const PassId effect) { if (!passes.contains(pass)) return; auto& effects = passes[pass]->getEffects(); - effects.erase( - std::remove(effects.begin(), effects.end(), effect), - effects.end() - ); + std::erase(effects, effect); m_isDirty = true; } - std::shared_ptr RenderPipeline::getRenderPass(PassId id) + std::shared_ptr RenderPipeline::getRenderPass(const PassId id) { - auto it = passes.find(id); + const auto it = passes.find(id); if (it != passes.end()) return it->second; return nullptr; } - std::shared_ptr RenderPipeline::getOutput(PassId id) + std::shared_ptr RenderPipeline::getOutput(const PassId id) { auto it = passOutputs.find(id); if (it != passOutputs.end()) @@ -155,23 +144,23 @@ namespace nexo::renderer { return nullptr; } - void RenderPipeline::setOutput(PassId id, std::shared_ptr output) + void RenderPipeline::setOutput(const PassId id, const std::shared_ptr& output) { passOutputs[id] = output; } - void RenderPipeline::setFinalOutputPass(PassId id) + void RenderPipeline::setFinalOutputPass(const PassId id) { if (passes.contains(id)) { if (finalOutputPass != -1 && passes.contains(finalOutputPass)) passes[finalOutputPass]->setFinal(false); passes[id]->setFinal(true); - finalOutputPass = id; + finalOutputPass = static_cast(id); } } - void RenderPipeline::setFinalRenderTarget(std::shared_ptr finalRenderTarget) + void RenderPipeline::setFinalRenderTarget(const std::shared_ptr &finalRenderTarget) { m_finalRenderTarget = finalRenderTarget; } @@ -192,15 +181,15 @@ namespace nexo::renderer { return terminals; } - bool RenderPipeline::hasPrerequisites(PassId id) const + bool RenderPipeline::hasPrerequisites(const PassId id) const { - auto it = passes.find(id); + const auto it = passes.find(id); return it != passes.end() && !it->second->getPrerequisites().empty(); } - bool RenderPipeline::hasEffects(PassId id) const + bool RenderPipeline::hasEffects(const PassId id) const { - auto it = passes.find(id); + const auto it = passes.find(id); return it != passes.end() && !it->second->getEffects().empty(); } @@ -216,12 +205,12 @@ namespace nexo::renderer { std::set visited; // DFS helper to build execution plan - std::function buildPlan = [&](PassId current) { + std::function buildPlan = [&](const PassId current) { if (visited.contains(current)) return; // First process all prerequisites - for (PassId prereq : passes[current]->getPrerequisites()) { + for (const PassId prereq : passes[current]->getPrerequisites()) { if (passes.contains(prereq)) buildPlan(prereq); } @@ -244,7 +233,7 @@ namespace nexo::renderer { } // Process each terminal pass - for (PassId term : terminals) + for (const PassId term : terminals) buildPlan(term); } m_isDirty = false; @@ -289,7 +278,7 @@ namespace nexo::renderer { return m_cameraClearColor; } - void RenderPipeline::resize(unsigned int width, unsigned int height) const + void RenderPipeline::resize(const unsigned int width, const unsigned int height) const { if (!m_finalRenderTarget) return; diff --git a/engine/src/renderer/RenderPipeline.hpp b/engine/src/renderer/RenderPipeline.hpp index 55482451d..5abfa43f8 100644 --- a/engine/src/renderer/RenderPipeline.hpp +++ b/engine/src/renderer/RenderPipeline.hpp @@ -48,9 +48,9 @@ namespace nexo::renderer { std::shared_ptr getOutput(PassId id); // Set output for a pass - void setOutput(PassId id, std::shared_ptr output); + void setOutput(PassId id, const std::shared_ptr& output); - void setFinalRenderTarget(std::shared_ptr finalRenderTarget); + void setFinalRenderTarget(const std::shared_ptr& finalRenderTarget); std::shared_ptr getFinalRenderTarget() const; // Set the final output pass diff --git a/engine/src/renderer/Renderer3D.cpp b/engine/src/renderer/Renderer3D.cpp index db4768a48..e21f334f0 100644 --- a/engine/src/renderer/Renderer3D.cpp +++ b/engine/src/renderer/Renderer3D.cpp @@ -14,7 +14,6 @@ #include "ShaderLibrary.hpp" #define GLM_ENABLE_EXPERIMENTAL -#include #include #include diff --git a/engine/src/renderer/Renderer3D.hpp b/engine/src/renderer/Renderer3D.hpp index 62cf182ef..75ec3e5ff 100644 --- a/engine/src/renderer/Renderer3D.hpp +++ b/engine/src/renderer/Renderer3D.hpp @@ -16,7 +16,6 @@ #include "Shader.hpp" #include "VertexArray.hpp" #include "Texture.hpp" -#include "ShaderLibrary.hpp" #include #include diff --git a/engine/src/renderer/Shader.cpp b/engine/src/renderer/Shader.cpp index 91f6aea07..a15384597 100644 --- a/engine/src/renderer/Shader.cpp +++ b/engine/src/renderer/Shader.cpp @@ -60,18 +60,18 @@ namespace nexo::renderer { m_storageBuffers.push_back(buffer); } - void NxShader::setStorageBufferData(unsigned int index, void *data, unsigned int size) + void NxShader::setStorageBufferData(const unsigned int index, void *data, const unsigned int size) { if (index >= m_storageBuffers.size()) THROW_EXCEPTION(NxOutOfRangeException, index, m_storageBuffers.size()); m_storageBuffers[index]->setData(data, size); } - bool NxShader::setUniformFloat(const std::string& name, float value) const + bool NxShader::setUniformFloat(const std::string& name, const float value) const { // Use uniform cache to avoid redundant state changes if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == value) { @@ -86,7 +86,7 @@ namespace nexo::renderer { bool NxShader::setUniformFloat2(const std::string& name, const glm::vec2& values) const { if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == values) { @@ -101,7 +101,7 @@ namespace nexo::renderer { bool NxShader::setUniformFloat3(const std::string& name, const glm::vec3& values) const { if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == values) { @@ -116,7 +116,7 @@ namespace nexo::renderer { bool NxShader::setUniformFloat4(const std::string& name, const glm::vec4& values) const { if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == values) { @@ -131,7 +131,7 @@ namespace nexo::renderer { bool NxShader::setUniformMatrix(const std::string& name, const glm::mat4& matrix) const { if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == matrix) { @@ -146,7 +146,7 @@ namespace nexo::renderer { bool NxShader::setUniformBool(const std::string& name, bool value) const { if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == value) { @@ -161,7 +161,7 @@ namespace nexo::renderer { bool NxShader::setUniformInt(const std::string& name, int value) const { if (!m_uniformCache.isDirty(name)) { - auto optionalValue = m_uniformCache.getValue(name); + const auto optionalValue = m_uniformCache.getValue(name); if (optionalValue.has_value() && std::holds_alternative(*optionalValue) && std::get(*optionalValue) == value) { @@ -211,7 +211,7 @@ namespace nexo::renderer { return m_uniformInfos.contains(name); } - bool NxShader::hasAttribute(int location) const + bool NxShader::hasAttribute(const int location) const { return m_attributeInfos.contains(location); } diff --git a/engine/src/renderer/ShaderLibrary.cpp b/engine/src/renderer/ShaderLibrary.cpp index b26ef9461..5da0014ef 100644 --- a/engine/src/renderer/ShaderLibrary.cpp +++ b/engine/src/renderer/ShaderLibrary.cpp @@ -24,7 +24,7 @@ namespace nexo::renderer { auto safeLoadShader = [this](const std::string& name, const std::string& relativePath) { try { // Resolve the absolute path - std::filesystem::path absPath = Path::resolvePathRelativeToExe(relativePath); + const std::filesystem::path absPath = Path::resolvePathRelativeToExe(relativePath); // Check if the shader file exists if (!std::filesystem::exists(absPath)) { diff --git a/engine/src/renderer/UniformCache.cpp b/engine/src/renderer/UniformCache.cpp index 771ffca4f..c472fcd63 100644 --- a/engine/src/renderer/UniformCache.cpp +++ b/engine/src/renderer/UniformCache.cpp @@ -18,7 +18,7 @@ namespace nexo::renderer { void UniformCache::setFloat(const std::string& name, float value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -27,7 +27,7 @@ namespace nexo::renderer { void UniformCache::setFloat2(const std::string& name, const glm::vec2& value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -36,7 +36,7 @@ namespace nexo::renderer { void UniformCache::setFloat3(const std::string& name, const glm::vec3& value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -45,7 +45,7 @@ namespace nexo::renderer { void UniformCache::setFloat4(const std::string& name, const glm::vec4& value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -54,7 +54,7 @@ namespace nexo::renderer { void UniformCache::setInt(const std::string& name, int value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -63,7 +63,7 @@ namespace nexo::renderer { void UniformCache::setBool(const std::string& name, bool value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -72,7 +72,7 @@ namespace nexo::renderer { void UniformCache::setMatrix(const std::string& name, const glm::mat4& value) { - auto it = m_values.find(name); + const auto it = m_values.find(name); if (it == m_values.end() || !std::holds_alternative(it->second) || std::get(it->second) != value) { m_values[name] = value; m_dirtyFlags[name] = true; @@ -81,7 +81,7 @@ namespace nexo::renderer { bool UniformCache::isDirty(const std::string& name) const { - auto it = m_dirtyFlags.find(name); + const auto it = m_dirtyFlags.find(name); return it != m_dirtyFlags.end() && it->second; } @@ -92,7 +92,7 @@ namespace nexo::renderer { std::optional UniformCache::getValue(const std::string& name) const { - auto it = m_values.find(name); + const auto it = m_values.find(name); return (it != m_values.end()) ? std::optional(it->second) : std::nullopt; } diff --git a/engine/src/renderer/opengl/OpenGlFramebuffer.cpp b/engine/src/renderer/opengl/OpenGlFramebuffer.cpp index 72689d1b9..faec1c0e2 100644 --- a/engine/src/renderer/opengl/OpenGlFramebuffer.cpp +++ b/engine/src/renderer/opengl/OpenGlFramebuffer.cpp @@ -15,7 +15,6 @@ #include "OpenGlFramebuffer.hpp" #include "Logger.hpp" -#include #include #include @@ -287,7 +286,7 @@ namespace nexo::renderer { glViewport(0, 0, static_cast(m_specs.width), static_cast(m_specs.height)); } - void NxOpenGlFramebuffer::bindAsTexture(unsigned int slot, unsigned int attachment) + void NxOpenGlFramebuffer::bindAsTexture(const unsigned int slot, unsigned int attachment) { if (attachment >= m_colorAttachments.size()) { LOG(NEXO_ERROR, "Attachment index {} out of bounds (max: {})", attachment, m_colorAttachments.size() - 1); @@ -297,7 +296,7 @@ namespace nexo::renderer { glBindTexture(GL_TEXTURE_2D, getColorAttachmentId(attachment)); } - void NxOpenGlFramebuffer::bindDepthAsTexture(unsigned int slot) + void NxOpenGlFramebuffer::bindDepthAsTexture(const unsigned int slot) { glActiveTexture(GL_TEXTURE0 + slot); glBindTexture(GL_TEXTURE_2D, m_depthAttachment); @@ -321,9 +320,9 @@ namespace nexo::renderer { glBindFramebuffer(GL_READ_FRAMEBUFFER, source->getFramebufferId()); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_id); - unsigned int numAttachments = source->getNbColorAttachments(); + const unsigned int numAttachments = source->getNbColorAttachments(); for (unsigned int i = 0; i < numAttachments; i++) { - GLenum attachment = GL_COLOR_ATTACHMENT0 + i; + const GLenum attachment = GL_COLOR_ATTACHMENT0 + i; // Set read and draw buffers glReadBuffer(attachment); @@ -331,8 +330,8 @@ namespace nexo::renderer { // Blit this attachment glBlitFramebuffer( - 0, 0, source->getSpecs().width, source->getSpecs().height, - 0, 0, m_specs.width, m_specs.height, + 0, 0, static_cast(source->getSpecs().width), static_cast(source->getSpecs().height), + 0, 0, static_cast(m_specs.width), static_cast(m_specs.height), GL_COLOR_BUFFER_BIT, GL_NEAREST ); @@ -347,13 +346,13 @@ namespace nexo::renderer { for (unsigned int i = 0; i < numAttachments; i++) { drawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; } - glDrawBuffers(numAttachments, drawBuffers.data()); + glDrawBuffers(static_cast(numAttachments), drawBuffers.data()); // If depth and stencil are combined, copy them together if (source->hasDepthStencilAttachment() && this->hasDepthStencilAttachment()) { glBlitFramebuffer( - 0, 0, source->getSpecs().width, source->getSpecs().height, - 0, 0, m_specs.width, m_specs.height, + 0, 0, static_cast(source->getSpecs().width), static_cast(source->getSpecs().height), + 0, 0, static_cast(m_specs.width), static_cast(m_specs.height), GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST ); @@ -364,8 +363,8 @@ namespace nexo::renderer { // Copy depth buffer if both source and destination have it if (source->hasDepthAttachment() && this->hasDepthAttachment()) { glBlitFramebuffer( - 0, 0, source->getSpecs().width, source->getSpecs().height, - 0, 0, m_specs.width, m_specs.height, + 0, 0, static_cast(source->getSpecs().width), static_cast(source->getSpecs().height), + 0, 0, static_cast(m_specs.width), static_cast(m_specs.height), GL_DEPTH_BUFFER_BIT, GL_NEAREST ); @@ -374,8 +373,8 @@ namespace nexo::renderer { // Copy stencil buffer if both source and destination have it if (source->hasStencilAttachment() && this->hasStencilAttachment()) { glBlitFramebuffer( - 0, 0, source->getSpecs().width, source->getSpecs().height, - 0, 0, m_specs.width, m_specs.height, + 0, 0, static_cast(source->getSpecs().width), static_cast(source->getSpecs().height), + 0, 0, static_cast(m_specs.width), static_cast(m_specs.height), GL_STENCIL_BUFFER_BIT, GL_NEAREST ); @@ -403,10 +402,10 @@ namespace nexo::renderer { glm::vec2 NxOpenGlFramebuffer::getSize() const { - return glm::vec2(m_specs.width, m_specs.height); + return {m_specs.width, m_specs.height}; } - void NxOpenGlFramebuffer::getPixelWrapper(unsigned int attachementIndex, int x, int y, void *result, const std::type_info &ti) const + void NxOpenGlFramebuffer::getPixelWrapper(const unsigned int attachementIndex, const int x, const int y, void *result, const std::type_info &ti) const { // Add more types here when necessary if (ti == typeid(int)) @@ -415,7 +414,7 @@ namespace nexo::renderer { THROW_EXCEPTION(NxFramebufferUnsupportedColorFormat, "OPENGL"); } - void NxOpenGlFramebuffer::clearAttachmentWrapper(unsigned int attachmentIndex, const void *value, const std::type_info &ti) const + void NxOpenGlFramebuffer::clearAttachmentWrapper(const unsigned int attachmentIndex, const void *value, const std::type_info &ti) const { // Add more types here when necessary if (ti == typeid(int)) diff --git a/engine/src/renderer/opengl/OpenGlFramebuffer.hpp b/engine/src/renderer/opengl/OpenGlFramebuffer.hpp index bd2e5e365..2681e9a1d 100644 --- a/engine/src/renderer/opengl/OpenGlFramebuffer.hpp +++ b/engine/src/renderer/opengl/OpenGlFramebuffer.hpp @@ -126,7 +126,7 @@ namespace nexo::renderer { void setClearColor(const glm::vec4 &color) override {m_clearColor = color;} - void copy(const std::shared_ptr source) override; + void copy(std::shared_ptr source) override; [[nodiscard]] unsigned int getFramebufferId() const override; @@ -159,7 +159,7 @@ namespace nexo::renderer { * @return T The pixel data. */ template - T getPixelImpl(unsigned int attachmentIndex, int x, int y) const + T getPixelImpl(const unsigned int attachmentIndex, const int x, const int y) const { if (attachmentIndex >= m_colorAttachments.size()) THROW_EXCEPTION(NxFramebufferInvalidIndex, "OPENGL", attachmentIndex); @@ -167,8 +167,8 @@ namespace nexo::renderer { glReadBuffer(GL_COLOR_ATTACHMENT0 + attachmentIndex); auto &textureFormat = m_colorAttachmentsSpecs[attachmentIndex].textureFormat; - GLenum format = framebufferTextureFormatToOpenGlFormat(textureFormat); - GLenum type = getGLTypeFromTemplate(); + const GLenum format = framebufferTextureFormatToOpenGlFormat(textureFormat); + const GLenum type = getGLTypeFromTemplate(); T pixelData; glReadPixels(x, y, 1, 1, format, type, &pixelData); @@ -188,7 +188,7 @@ namespace nexo::renderer { * @param value The value to clear the attachment to. */ template - void clearAttachmentImpl(unsigned int attachmentIndex, const void *value) const + void clearAttachmentImpl(const unsigned int attachmentIndex, const void *value) const { if (attachmentIndex >= m_colorAttachments.size()) THROW_EXCEPTION(NxFramebufferInvalidIndex, "OPENGL", attachmentIndex); diff --git a/engine/src/renderer/opengl/OpenGlRendererApi.cpp b/engine/src/renderer/opengl/OpenGlRendererApi.cpp index 8193246ef..402b23a08 100644 --- a/engine/src/renderer/opengl/OpenGlRendererApi.cpp +++ b/engine/src/renderer/opengl/OpenGlRendererApi.cpp @@ -157,7 +157,7 @@ namespace nexo::renderer { glStencilOp(sfail, dpfail, dppass); } - void NxOpenGlRendererApi::setCulling(bool enable) + void NxOpenGlRendererApi::setCulling(const bool enable) { if (!m_initialized) THROW_EXCEPTION(NxGraphicsApiNotInitialized, "OPENGL"); @@ -167,7 +167,7 @@ namespace nexo::renderer { glDisable(GL_CULL_FACE); } - void NxOpenGlRendererApi::setCulledFace(CulledFace face) + void NxOpenGlRendererApi::setCulledFace(const CulledFace face) { if (!m_initialized) THROW_EXCEPTION(NxGraphicsApiNotInitialized, "OPENGL"); @@ -179,7 +179,7 @@ namespace nexo::renderer { glCullFace(GL_FRONT_AND_BACK); } - void NxOpenGlRendererApi::setWindingOrder(WindingOrder order) + void NxOpenGlRendererApi::setWindingOrder(const WindingOrder order) { if (!m_initialized) THROW_EXCEPTION(NxGraphicsApiNotInitialized, "OPENGL"); diff --git a/engine/src/renderer/opengl/OpenGlShader.cpp b/engine/src/renderer/opengl/OpenGlShader.cpp index 1189c841b..92d6767d5 100644 --- a/engine/src/renderer/opengl/OpenGlShader.cpp +++ b/engine/src/renderer/opengl/OpenGlShader.cpp @@ -19,7 +19,6 @@ #include "renderer/RendererExceptions.hpp" #include "OpenGlShaderReflection.hpp" -#include #include #include #include @@ -39,7 +38,7 @@ namespace nexo::renderer { NxOpenGlShader::NxOpenGlShader(const std::string &path) { const std::string src = readFile(path); - auto shaderSources = preProcess(src, path); + const auto shaderSources = preProcess(src, path); compile(shaderSources); auto lastSlash = path.find_last_of("/\\"); @@ -72,7 +71,7 @@ namespace nexo::renderer { const char *typeToken = "#type"; size_t pos = src.find(typeToken, 0); - int currentLine = 1; + unsigned int currentLine = 1; while (pos != std::string::npos) { constexpr size_t typeTokenLength = 5; @@ -169,7 +168,7 @@ namespace nexo::renderer { // We don't need the program anymore. glDeleteProgram(m_id); // Don't leak shaders either. - for (auto id: glShaderIds) + for (const auto id: glShaderIds) glDeleteShader(id); THROW_EXCEPTION(NxShaderCreationFailed, "OPENGL", @@ -195,7 +194,7 @@ namespace nexo::renderer { }; for (const auto& [location, info] : m_attributeInfos) { - auto it = attributeMappers.find(info.name); + const auto it = attributeMappers.find(info.name); if (it != attributeMappers.end()) { it->second(m_requiredAttributes); } @@ -213,21 +212,21 @@ namespace nexo::renderer { } int NxOpenGlShader::getUniformLocation(const std::string& name) const { - auto it = m_uniformInfos.find(name); + const auto it = m_uniformInfos.find(name); if (it != m_uniformInfos.end()) { return it->second.location; } return glGetUniformLocation(m_id, name.c_str()); } - bool NxOpenGlShader::setUniformFloat(const std::string& name, float value) const + bool NxOpenGlShader::setUniformFloat(const std::string& name, const float value) const { if (!NxShader::hasUniform(name)) return false; if (NxShader::setUniformFloat(name, value)) return true; // Value was cached, no need to update - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -245,7 +244,7 @@ namespace nexo::renderer { if (NxShader::setUniformFloat(name, value)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -262,7 +261,7 @@ namespace nexo::renderer { if (NxShader::setUniformFloat2(name, values)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -279,8 +278,7 @@ namespace nexo::renderer { if (NxShader::setUniformFloat3(name, values)) return true; - - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -298,7 +296,7 @@ namespace nexo::renderer { if (NxShader::setUniformFloat3(name, values)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -315,7 +313,7 @@ namespace nexo::renderer { if (NxShader::setUniformFloat4(name, values)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -333,7 +331,7 @@ namespace nexo::renderer { if (NxShader::setUniformFloat4(name, values)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -350,7 +348,7 @@ namespace nexo::renderer { if (NxShader::setUniformMatrix(name, matrix)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -368,8 +366,7 @@ namespace nexo::renderer { if (NxShader::setUniformMatrix(name, matrix)) return true; - - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -386,7 +383,7 @@ namespace nexo::renderer { if (NxShader::setUniformInt(name, value)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -403,7 +400,7 @@ namespace nexo::renderer { if (NxShader::setUniformBool(name, value)) return true; - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -421,8 +418,7 @@ namespace nexo::renderer { if (NxShader::setUniformInt(name, value)) return true; - - int location = getUniformLocation(name); + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -436,7 +432,8 @@ namespace nexo::renderer { { if (!NxShader::hasUniform(name)) return false; - int location = getUniformLocation(name); + + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -451,7 +448,8 @@ namespace nexo::renderer { const std::string &name = ShaderUniformsName.at(uniform); if (!NxShader::hasUniform(name)) return false; - int location = getUniformLocation(name); + + const int location = getUniformLocation(name); if (location == -1) { LOG(NEXO_WARN, "For shader {}, uniform {} not found", m_name, name); return false; @@ -461,21 +459,21 @@ namespace nexo::renderer { return true; } - void NxOpenGlShader::bindStorageBuffer(unsigned int index) const + void NxOpenGlShader::bindStorageBuffer(const unsigned int index) const { if (index > m_storageBuffers.size()) THROW_EXCEPTION(NxOutOfRangeException, index, m_storageBuffers.size()); m_storageBuffers[index]->bind(); } - void NxOpenGlShader::unbindStorageBuffer(unsigned int index) const + void NxOpenGlShader::unbindStorageBuffer(const unsigned int index) const { if (index > m_storageBuffers.size()) THROW_EXCEPTION(NxOutOfRangeException, index, m_storageBuffers.size()); m_storageBuffers[index]->unbind(); } - void NxOpenGlShader::bindStorageBufferBase(unsigned int index, unsigned int bindingLocation) const + void NxOpenGlShader::bindStorageBufferBase(const unsigned int index, const unsigned int bindingLocation) const { if (index > m_storageBuffers.size()) THROW_EXCEPTION(NxOutOfRangeException, index, m_storageBuffers.size()); diff --git a/engine/src/renderer/opengl/OpenGlShaderReflection.cpp b/engine/src/renderer/opengl/OpenGlShaderReflection.cpp index fc0619d55..d4f4d6b06 100644 --- a/engine/src/renderer/opengl/OpenGlShaderReflection.cpp +++ b/engine/src/renderer/opengl/OpenGlShaderReflection.cpp @@ -50,7 +50,7 @@ namespace nexo::renderer { // For array uniforms, also store the base name (without [0]) std::string baseName = info.name; - size_t bracketPos = baseName.find('['); + const size_t bracketPos = baseName.find('['); if (bracketPos != std::string::npos) { baseName = baseName.substr(0, bracketPos); @@ -67,7 +67,7 @@ namespace nexo::renderer { return uniforms; } - std::unordered_map ShaderReflection::reflectAttributes(unsigned int programId) + std::unordered_map ShaderReflection::reflectAttributes(const unsigned int programId) { std::unordered_map attributes; @@ -93,7 +93,7 @@ namespace nexo::renderer { return attributes; } - std::vector ShaderReflection::getRequiredAttributes(unsigned int programId) + std::vector ShaderReflection::getRequiredAttributes(const unsigned int programId) { auto attributes = reflectAttributes(programId); std::vector required; diff --git a/engine/src/renderer/opengl/OpenGlShaderReflection.hpp b/engine/src/renderer/opengl/OpenGlShaderReflection.hpp index 6861e8e17..3dbd1b626 100644 --- a/engine/src/renderer/opengl/OpenGlShaderReflection.hpp +++ b/engine/src/renderer/opengl/OpenGlShaderReflection.hpp @@ -16,7 +16,6 @@ #include #include #include -#include #include "Shader.hpp" namespace nexo::renderer { diff --git a/engine/src/renderer/opengl/OpenGlTexture2D.cpp b/engine/src/renderer/opengl/OpenGlTexture2D.cpp index 400f326e2..d11eaf5f7 100644 --- a/engine/src/renderer/opengl/OpenGlTexture2D.cpp +++ b/engine/src/renderer/opengl/OpenGlTexture2D.cpp @@ -17,7 +17,6 @@ #include #include -#include "Logger.hpp" #include namespace nexo::renderer { diff --git a/engine/src/renderer/opengl/OpenGlWindow.cpp b/engine/src/renderer/opengl/OpenGlWindow.cpp index 3484ef9ae..111782c4d 100644 --- a/engine/src/renderer/opengl/OpenGlWindow.cpp +++ b/engine/src/renderer/opengl/OpenGlWindow.cpp @@ -20,7 +20,6 @@ #include "renderer/RendererExceptions.hpp" #include "Logger.hpp" - namespace nexo::renderer { static void glfwErrorCallback(const int errorCode, const char *errorStr) { diff --git a/engine/src/renderer/primitives/Billboard.cpp b/engine/src/renderer/primitives/Billboard.cpp index cb0c29a80..828c2b763 100644 --- a/engine/src/renderer/primitives/Billboard.cpp +++ b/engine/src/renderer/primitives/Billboard.cpp @@ -80,7 +80,7 @@ namespace nexo::renderer return billboardVao; billboardVao = createVertexArray(); - auto vertexBuffer = createVertexBuffer(nbVerticesBillboard * sizeof(NxVertex)); + const auto vertexBuffer = createVertexBuffer(nbVerticesBillboard * sizeof(NxVertex)); const NxBufferLayout cubeVertexBufferLayout = { {NxShaderDataType::FLOAT3, "aPos"}, {NxShaderDataType::FLOAT2, "aTexCoord"}, @@ -114,7 +114,7 @@ namespace nexo::renderer for (uint32_t i = 0; i < nbVerticesBillboard; ++i) indices[i] = i; - auto indexBuffer = createIndexBuffer(); + const auto indexBuffer = createIndexBuffer(); indexBuffer->setData(indices.data(), static_cast(indices.size())); billboardVao->setIndexBuffer(indexBuffer); diff --git a/engine/src/renderer/primitives/Cube.cpp b/engine/src/renderer/primitives/Cube.cpp index ccc15b1de..469742d5d 100644 --- a/engine/src/renderer/primitives/Cube.cpp +++ b/engine/src/renderer/primitives/Cube.cpp @@ -21,7 +21,6 @@ #define GLM_ENABLE_EXPERIMENTAL #include #include -#include namespace nexo::renderer { @@ -136,7 +135,7 @@ namespace nexo::renderer for (uint32_t i = 0; i < nbVerticesCube; ++i) indices[i] = i; - auto indexBuffer = createIndexBuffer(); + const auto indexBuffer = createIndexBuffer(); indexBuffer->setData(indices.data(), static_cast(indices.size())); cubeVao->setIndexBuffer(indexBuffer); diff --git a/engine/src/renderer/primitives/Pyramid.cpp b/engine/src/renderer/primitives/Pyramid.cpp index b5780ca4b..bb2883fef 100644 --- a/engine/src/renderer/primitives/Pyramid.cpp +++ b/engine/src/renderer/primitives/Pyramid.cpp @@ -13,7 +13,6 @@ /////////////////////////////////////////////////////////////////////////////// #include "renderer/Renderer3D.hpp" -#include "renderer/RendererExceptions.hpp" #include #include @@ -22,7 +21,6 @@ #include #include #include -#include namespace nexo::renderer { diff --git a/engine/src/renderer/primitives/Sphere.cpp b/engine/src/renderer/primitives/Sphere.cpp index 91292348e..31cd1296a 100644 --- a/engine/src/renderer/primitives/Sphere.cpp +++ b/engine/src/renderer/primitives/Sphere.cpp @@ -25,7 +25,6 @@ #define GLM_ENABLE_EXPERIMENTAL #include #include -#include #include #include @@ -44,7 +43,7 @@ namespace nexo::renderer std::vector vertices{}; vertices.reserve(12); // Reserve space for the 12 vertices of the icosahedron - const float phi = (1.0f + sqrt(5.0f)) * 0.5f; // golden ratio + const float phi = (1.0f + sqrtf(5.0f)) * 0.5f; // golden ratio float a = 1.0f; float b = 1.0f / phi; @@ -241,11 +240,11 @@ namespace nexo::renderer vertexData[i].entityID = 0; // Default entity ID } - vertexBuffer->setData(vertexData.data(), vertexData.size() * sizeof(NxVertex)); + vertexBuffer->setData(vertexData.data(), static_cast(vertexData.size() * sizeof(NxVertex))); sphereVaoMap[nbSubdivision]->addVertexBuffer(vertexBuffer); const auto indexBuffer = createIndexBuffer(); - indexBuffer->setData(indices.data(), indices.size()); + indexBuffer->setData(indices.data(), static_cast(indices.size())); sphereVaoMap[nbSubdivision]->setIndexBuffer(indexBuffer); return sphereVaoMap[nbSubdivision]; diff --git a/engine/src/renderer/primitives/Tetrahedron.cpp b/engine/src/renderer/primitives/Tetrahedron.cpp index 36b585650..c5f2fc8e6 100644 --- a/engine/src/renderer/primitives/Tetrahedron.cpp +++ b/engine/src/renderer/primitives/Tetrahedron.cpp @@ -14,17 +14,13 @@ #include "renderer/Renderer3D.hpp" -#include "renderer/RendererExceptions.hpp" -#include #include #include #define GLM_ENABLE_EXPERIMENTAL #include #include #include -#include - namespace nexo::renderer { @@ -60,7 +56,7 @@ namespace nexo::renderer vertices = verts; // Basic UV mapping for each face - std::array textureCoords = {{ + const std::array textureCoords = {{ {0.5f, 1.0f}, {0.0f, 0.0f}, {1.0f, 0.0f}, // Front face {1.0f, 0.5f}, {1.0f, 1.0f}, {0.0f, 0.0f}, // Right face {0.0f, 0.5f}, {1.0f, 0.0f}, {1.0f, 1.0f}, // Left face @@ -69,9 +65,6 @@ namespace nexo::renderer texCoords = textureCoords; - // Compute normals for each face - //std::array norm; - for (int i = 0; i < 12; i += 3) { const glm::vec3 normal = glm::normalize( @@ -83,9 +76,6 @@ namespace nexo::renderer normals[i + 1] = normal; normals[i + 2] = normal; } - - //normals = norm; - //std::ranges::copy(norm, normals.begin()); } @@ -128,7 +118,7 @@ namespace nexo::renderer vertexData[i].entityID = 0; // Default entity ID } - vertexBuffer->setData(vertexData.data(), vertexData.size() * sizeof(NxVertex)); + vertexBuffer->setData(vertexData.data(), static_cast(vertexData.size() * sizeof(NxVertex))); tetrahedronVao->addVertexBuffer(vertexBuffer); std::vector indices(nbVerticesTetrahedron); @@ -136,7 +126,7 @@ namespace nexo::renderer indices[i] = i; const auto indexBuffer = createIndexBuffer(); - indexBuffer->setData(indices.data(), indices.size()); + indexBuffer->setData(indices.data(), static_cast(indices.size())); tetrahedronVao->setIndexBuffer(indexBuffer); return tetrahedronVao; diff --git a/engine/src/scripting/native/HostString.cpp b/engine/src/scripting/native/HostString.cpp index 931bf0712..d21006b08 100644 --- a/engine/src/scripting/native/HostString.cpp +++ b/engine/src/scripting/native/HostString.cpp @@ -14,6 +14,7 @@ #include #include +#include #include "HostString.hpp" @@ -56,7 +57,7 @@ namespace nexo::scripting { utf8::utf16to8(m_buffer.data(), m_buffer.data() + size(), std::back_inserter(utf8)); return utf8; #else - return std::string(m_buffer.data(), size()); + return {m_buffer.data(), size()}; #endif } diff --git a/engine/src/scripting/native/HostString.hpp b/engine/src/scripting/native/HostString.hpp index f49e4e11a..6a4d233ab 100644 --- a/engine/src/scripting/native/HostString.hpp +++ b/engine/src/scripting/native/HostString.hpp @@ -19,7 +19,6 @@ #include #include -#include namespace nexo::scripting { diff --git a/engine/src/scripting/native/ManagedApi.hpp b/engine/src/scripting/native/ManagedApi.hpp index 6ae8d14fb..9afa52848 100644 --- a/engine/src/scripting/native/ManagedApi.hpp +++ b/engine/src/scripting/native/ManagedApi.hpp @@ -16,7 +16,6 @@ #include -#include "Entity.hpp" #include "Exception.hpp" #include "ManagedTypedef.hpp" #include "components/Transform.hpp" @@ -40,7 +39,7 @@ namespace nexo::scripting { using Type = Ret (CORECLR_DELEGATE_CALLTYPE *)(Args...); // Constructor explicitly accepting function pointers - explicit(false) ManagedApiFn(Type f) : func(f) + explicit(false) ManagedApiFn(const Type f) : func(f) { if (!func) { THROW_EXCEPTION(InvalidManagedApi, std::format("Function pointer is null: {}", typeid(Type).name())); diff --git a/engine/src/scripting/native/NativeApi.cpp b/engine/src/scripting/native/NativeApi.cpp index 0340ef69b..9ac6bbab8 100644 --- a/engine/src/scripting/native/NativeApi.cpp +++ b/engine/src/scripting/native/NativeApi.cpp @@ -49,7 +49,7 @@ namespace nexo::scripting { LOG(static_cast(level), "[Scripting] {}", message); } - ecs::Entity NxCreateCube(Vector3 position, Vector3 size, Vector3 rotation, Vector4 color) + ecs::Entity NxCreateCube(const Vector3 position, const Vector3 size, const Vector3 rotation, const Vector4 color) { auto& app = Application::getInstance(); const ecs::Entity basicCube = EntityFactory3D::createCube(position, size, rotation, color); @@ -57,7 +57,7 @@ namespace nexo::scripting { return basicCube; } - ecs::Entity NxCreateTetrahedron(Vector3 position, Vector3 size, Vector3 rotation, Vector4 color) + ecs::Entity NxCreateTetrahedron(const Vector3 position, const Vector3 size, const Vector3 rotation, const Vector4 color) { auto& app = Application::getInstance(); const ecs::Entity entity = EntityFactory3D::createTetrahedron(position, size, rotation, color); @@ -65,7 +65,7 @@ namespace nexo::scripting { return entity; } - ecs::Entity NxCreatePyramid(Vector3 position, Vector3 size, Vector3 rotation, Vector4 color) + ecs::Entity NxCreatePyramid(const Vector3 position, const Vector3 size, const Vector3 rotation, const Vector4 color) { auto& app = Application::getInstance(); const ecs::Entity entity = EntityFactory3D::createPyramid(position, size, rotation, color); @@ -73,7 +73,7 @@ namespace nexo::scripting { return entity; } - ecs::Entity NxCreateCylinder(Vector3 position, Vector3 size, Vector3 rotation, Vector4 color, UInt32 nbSegment) + ecs::Entity NxCreateCylinder(const Vector3 position, const Vector3 size, const Vector3 rotation, const Vector4 color, const UInt32 nbSegment) { auto& app = Application::getInstance(); const ecs::Entity entity = EntityFactory3D::createCylinder(position, size, rotation, color, nbSegment); @@ -81,7 +81,7 @@ namespace nexo::scripting { return entity; } - ecs::Entity NxCreateSphere(Vector3 position, Vector3 size, Vector3 rotation, Vector4 color, UInt32 nbSubdivision) + ecs::Entity NxCreateSphere(const Vector3 position, const Vector3 size, const Vector3 rotation, const Vector4 color, const UInt32 nbSubdivision) { auto& app = Application::getInstance(); const ecs::Entity entity = EntityFactory3D::createSphere(position, size, rotation, color, nbSubdivision); @@ -101,7 +101,7 @@ namespace nexo::scripting { void* NxGetComponent(const ecs::Entity entity, const UInt32 componentTypeId) { - auto& coordinator = *Application::m_coordinator; + const auto& coordinator = *Application::m_coordinator; const auto opt = coordinator.tryGetComponentById(componentTypeId, entity); return opt; } @@ -181,7 +181,7 @@ namespace nexo::scripting { ComponentTypeIds NxGetComponentTypeIds() { - auto& coordinator = *Application::m_coordinator; + const auto& coordinator = *Application::m_coordinator; return ComponentTypeIds { .Transform = coordinator.getComponentType(), @@ -201,7 +201,7 @@ namespace nexo::scripting { void NxCreateBodyFromShape(ecs::Entity entity, Vector3 position, Vector3 size, Vector3 rotation, UInt32 shapeType, UInt32 motionType) { - auto& app = Application::getInstance(); + const auto& app = Application::getInstance(); auto physicsSystem = app.getPhysicsSystem(); if (!physicsSystem) { @@ -214,18 +214,18 @@ namespace nexo::scripting { transform.size = {size.x, size.y, size.z}; transform.quat = glm::quat(glm::radians(glm::vec3(rotation.x, rotation.y, rotation.z))); - system::ShapeType cppShapeType = static_cast(shapeType); - JPH::EMotionType cppMotionType = static_cast(motionType); + auto cppShapeType = static_cast(shapeType); + auto cppMotionType = static_cast(motionType); physicsSystem->createBodyFromShape(entity, transform, cppShapeType, cppMotionType); LOG(NEXO_DEV, "Physics body created"); } - void NxApplyForce(ecs::Entity entity, Vector3 force) + void NxApplyForce(ecs::Entity entity, const Vector3 force) { - auto& app = Application::getInstance(); - auto physicsSystem = app.getPhysicsSystem(); + const auto& app = Application::getInstance(); + const auto physicsSystem = app.getPhysicsSystem(); if (!physicsSystem) { LOG(NEXO_ERROR, "Physics system not available"); return; @@ -235,9 +235,9 @@ namespace nexo::scripting { LOG(NEXO_ERROR, "Entity {} has no PhysicsBodyComponent", entity); return; } - auto& bodyComp = coordinator.getComponent(entity); - JPH::BodyID joltBodyID = bodyComp.bodyID; - JPH::Vec3 joltForce(force.x, force.y, force.z); + const auto& bodyComp = coordinator.getComponent(entity); + const JPH::BodyID joltBodyID = bodyComp.bodyID; + const JPH::Vec3 joltForce(force.x, force.y, force.z); physicsSystem->applyForce(joltBodyID, joltForce); } } diff --git a/engine/src/scripting/native/NativeApi.hpp b/engine/src/scripting/native/NativeApi.hpp index 15f113fb4..9b509a032 100644 --- a/engine/src/scripting/native/NativeApi.hpp +++ b/engine/src/scripting/native/NativeApi.hpp @@ -40,7 +40,6 @@ #define NEXO_RET(type) NEXO_API type NEXO_CALL -#include "Entity.hpp" #include "ManagedTypedef.hpp" #include "components/Transform.hpp" @@ -91,8 +90,8 @@ namespace nexo::scripting { NEXO_RET(components::TransformComponent *) NxGetTransformComponent(ecs::Entity entity); NEXO_RET(void *) NxGetComponent(ecs::Entity entity, UInt32 componentTypeId); NEXO_RET(void) NxAddComponent(ecs::Entity entity, UInt32 typeId, const void *componentData); - NEXO_RET(void) NxRemoveComponent(const ecs::Entity entity, const UInt32 componentTypeId); - NEXO_RET(void) NxDestroyEntity(const ecs::Entity entity); + NEXO_RET(void) NxRemoveComponent(ecs::Entity entity, UInt32 componentTypeId); + NEXO_RET(void) NxDestroyEntity(ecs::Entity entity); NEXO_RET(bool) NxHasComponent(ecs::Entity entity, UInt32 typeId); NEXO_RET(Int64) NxRegisterComponent(const char *name, UInt64 componentSize, const Field *fields, UInt64 fieldCount); NEXO_RET(ComponentTypeIds) NxGetComponentTypeIds(); @@ -127,8 +126,8 @@ namespace nexo::scripting { ApiCallback NxGetTransformComponent{&scripting::NxGetTransformComponent}; ApiCallback NxGetComponent{&scripting::NxGetComponent}; ApiCallback NxAddComponent{&scripting::NxAddComponent}; - ApiCallback NxRemoveComponent{&scripting::NxRemoveComponent}; - ApiCallback NxDestroyEntity{&scripting::NxDestroyEntity}; + ApiCallback NxRemoveComponent{&scripting::NxRemoveComponent}; + ApiCallback NxDestroyEntity{&scripting::NxDestroyEntity}; ApiCallback NxHasComponent{&scripting::NxHasComponent}; ApiCallback NxRegisterComponent{&scripting::NxRegisterComponent}; ApiCallback NxGetComponentTypeIds{&scripting::NxGetComponentTypeIds}; diff --git a/engine/src/scripting/native/Scripting.cpp b/engine/src/scripting/native/Scripting.cpp index abc75c470..3dbc76f5f 100644 --- a/engine/src/scripting/native/Scripting.cpp +++ b/engine/src/scripting/native/Scripting.cpp @@ -109,7 +109,7 @@ namespace nexo::scripting { const auto assemblyPath = HostString(m_params.assemblyPath.c_str()); const auto dotnetRoot = HostString(m_params.dotnetRoot.c_str()); - get_hostfxr_parameters params { + const get_hostfxr_parameters params { sizeof(get_hostfxr_parameters), assemblyPath.empty() ? nullptr : assemblyPath.c_str(), dotnetRoot.empty() ? nullptr : dotnetRoot.c_str() @@ -158,7 +158,7 @@ namespace nexo::scripting { const HostString configPath = runtimeConfigPath.c_str(); // Load .NET Core - unsigned int rc = m_hostfxr_fn.init_for_config(configPath.c_str(), nullptr, &m_host_ctx); + const unsigned int rc = m_hostfxr_fn.init_for_config(configPath.c_str(), nullptr, &m_host_ctx); if (rc != 0 || m_host_ctx == nullptr) { m_params.errorCallback(std::format("Init failed: 0x{:X}", rc)); m_hostfxr_fn.close(m_host_ctx); @@ -327,7 +327,7 @@ namespace nexo::scripting { return m_status = SUCCESS; } - int HostHandler::runScriptExample() + int HostHandler::runScriptExample() const { // Run managed code // Call the Hello method multiple times @@ -342,7 +342,7 @@ namespace nexo::scripting { // Call UnmanagedCallersOnly method - lib_args args_unmanaged { + const lib_args args_unmanaged { STR("from host!"), -1 }; diff --git a/engine/src/scripting/native/Scripting.hpp b/engine/src/scripting/native/Scripting.hpp index 61e936b1a..1a39d6397 100644 --- a/engine/src/scripting/native/Scripting.hpp +++ b/engine/src/scripting/native/Scripting.hpp @@ -32,7 +32,6 @@ #define DIR_SEPARATOR L'\\' #else #include - #include #define STR(s) s #define CH(c) c @@ -130,7 +129,7 @@ namespace nexo::scripting { Status initialize(Parameters parameters); - const ManagedApi& getManagedApi() const + [[nodiscard]] const ManagedApi& getManagedApi() const { return m_managedApi; } @@ -157,7 +156,7 @@ namespace nexo::scripting { } - int runScriptExample(); + int runScriptExample() const; protected: @@ -173,8 +172,8 @@ namespace nexo::scripting { protected: Status m_status = UNINITIALIZED; - Parameters m_params; - HostString m_assembly_path; + Parameters m_params{}; + HostString m_assembly_path{}; HostfxrFn m_hostfxr_fn = {}; CoreclrDelegate m_delegates = {}; diff --git a/engine/src/scripting/native/ui/Field.hpp b/engine/src/scripting/native/ui/Field.hpp index ff31603e2..9bc28e32a 100644 --- a/engine/src/scripting/native/ui/Field.hpp +++ b/engine/src/scripting/native/ui/Field.hpp @@ -16,8 +16,6 @@ #pragma once -#include - #include "FieldType.hpp" #include "scripting/native/ManagedTypedef.hpp" diff --git a/engine/src/systems/CameraSystem.cpp b/engine/src/systems/CameraSystem.cpp index e627b63b5..402e905dd 100644 --- a/engine/src/systems/CameraSystem.cpp +++ b/engine/src/systems/CameraSystem.cpp @@ -154,12 +154,12 @@ namespace nexo::system { auto &controller = getComponent(entity); const auto &sceneTag = getComponent(entity); const auto &cameraComponent = getComponent(entity); - bool isActiveScene = sceneTag.isActive && sceneTag.id == sceneRendered; - bool isActiveCamera = isActiveScene && cameraComponent.active; - bool mouseDown = event::isMouseDown(NEXO_MOUSE_LEFT); + const bool isActiveScene = sceneTag.isActive && sceneTag.id == sceneRendered; + const bool isActiveCamera = isActiveScene && cameraComponent.active; + const bool mouseDown = event::isMouseDown(NEXO_MOUSE_LEFT); // Check for scene transition - if the camera wasn't active before but is now - bool sceneTransition = isActiveCamera && !controller.wasActiveLastFrame; + const bool sceneTransition = isActiveCamera && !controller.wasActiveLastFrame; controller.wasActiveLastFrame = isActiveCamera; // Reset position on scene transition to prevent abrupt rotation @@ -196,10 +196,10 @@ namespace nexo::system { glm::quat pitchRotation = glm::angleAxis(glm::radians(-mouseDelta.y), right); glm::quat yawRotation = glm::angleAxis(glm::radians(-mouseDelta.x), glm::vec3(0.0f, 1.0f, 0.0f)); // World up for yaw glm::quat newQuat = glm::normalize(yawRotation * pitchRotation * transform.quat); - glm::vec3 newFront = newQuat * glm::vec3(0.0f, 0.0f, -1.0f); + const glm::vec3 newFront = newQuat * glm::vec3(0.0f, 0.0f, -1.0f); // Check if the resulting orientation would flip the camera (pitch constraint) - float pitchAngle = glm::degrees(std::asin(newFront.y)); + const float pitchAngle = glm::degrees(std::asin(newFront.y)); if (pitchAngle < -85.0f || pitchAngle > 85.0f) transform.quat = glm::normalize(yawRotation * transform.quat); else @@ -288,7 +288,7 @@ namespace nexo::system { // Prevent excessive pitch rotation when the camera is nearly vertical. glm::vec3 front = glm::normalize(transformTargetComponent.pos - transformCameraComponent.pos); - auto sgn = [](float x) { return (x >= 0.0f ? 1.0f : -1.0f); }; + auto sgn = [](const float x) { return (x >= 0.0f ? 1.0f : -1.0f); }; if (glm::dot(front, glm::vec3(0, 1, 0)) * sgn(yAngle) > 0.99f) yAngle = 0.0f; diff --git a/engine/src/systems/PhysicsSystem.cpp b/engine/src/systems/PhysicsSystem.cpp index b8bfe8e5e..f249da4d5 100644 --- a/engine/src/systems/PhysicsSystem.cpp +++ b/engine/src/systems/PhysicsSystem.cpp @@ -14,11 +14,17 @@ #include "PhysicsSystem.hpp" #include +#include +#include +#include +#include -namespace nexo::system { - PhysicsSystem::PhysicsSystem() { - } + +#include + +namespace nexo::system { + PhysicsSystem::PhysicsSystem() = default; PhysicsSystem::~PhysicsSystem() { delete physicsSystem; @@ -35,7 +41,7 @@ namespace nexo::system { tempAllocator = new JPH::TempAllocatorImpl(10 * 1024 * 1024); jobSystem = new JPH::JobSystemThreadPool( - JPH::cMaxPhysicsJobs, JPH::cMaxPhysicsBarriers, std::thread::hardware_concurrency() - 1 + JPH::cMaxPhysicsJobs, JPH::cMaxPhysicsBarriers, static_cast(std::thread::hardware_concurrency()) - 1 ); physicsSystem = new JPH::PhysicsSystem(); @@ -48,8 +54,8 @@ namespace nexo::system { void PhysicsSystem::update() { - const double currentTime = static_cast(std::chrono::duration_cast>( - std::chrono::high_resolution_clock::now().time_since_epoch()).count()); + const double currentTime = std::chrono::duration_cast>( + std::chrono::high_resolution_clock::now().time_since_epoch()).count(); const double delta = currentTime - m_lastPhysicsTime; @@ -58,12 +64,12 @@ namespace nexo::system { m_lastPhysicsTime = currentTime; - const int collisionSteps = 5; + constexpr int collisionSteps = 5; physicsSystem->Update(fixedTimestep, collisionSteps, tempAllocator, jobSystem); - for (ecs::Entity entity : entities) { + for (const ecs::Entity entity : entities) { auto& transform = getComponent(entity); - auto& physicsBody = getComponent(entity); + const auto& physicsBody = getComponent(entity); const JPH::Vec3 pos = bodyInterface->GetPosition(physicsBody.bodyID); transform.pos = glm::vec3(pos.GetX(), pos.GetY(), pos.GetZ()); @@ -75,12 +81,13 @@ namespace nexo::system { JPH::BodyID PhysicsSystem::createBodyFromShape( - ecs::Entity entity, + const ecs::Entity entity, const components::TransformComponent& transform, - ShapeType shapeType, - JPH::EMotionType motionType - ) { - JPH::ShapeSettings* shapeSettings = nullptr; + const ShapeType shapeType, + const JPH::EMotionType motionType + ) const + { + const JPH::ShapeSettings* shapeSettings = nullptr; switch (shapeType) { case ShapeType::Box: @@ -102,9 +109,9 @@ namespace nexo::system { } case ShapeType::Tetrahedron: { - auto size = transform.size.x; + const auto size = transform.size.x; // Define the vertices of the tetrahedron relative to its center - JPH::Vec3 vertices[] = { + const JPH::Vec3 vertices[] = { JPH::Vec3(-size, -size, -size), JPH::Vec3(size, -size, size), JPH::Vec3(-size, size, size), @@ -118,7 +125,7 @@ namespace nexo::system { case ShapeType::Pyramid: { // Define the vertices of the pyramid relative to its center - JPH::Vec3 vertices[] = { + const JPH::Vec3 vertices[] = { JPH::Vec3(0.0f, 1.0f, 0.0f) * transform.size.y, // Apex JPH::Vec3(-1.0f, -1.0f, -1.0f) * transform.size.x, // Base vertex 1 JPH::Vec3(1.0f, -1.0f, -1.0f) * transform.size.x, // Base vertex 2 @@ -133,7 +140,7 @@ namespace nexo::system { default: LOG(NEXO_ERROR, "Unsupported shape type"); - return JPH::BodyID(); + return {}; } JPH::ShapeRefC shape = nullptr; @@ -142,28 +149,28 @@ namespace nexo::system { } catch (const std::exception& e) { LOG(NEXO_ERROR, "Exception during shape creation: {}", e.what()); delete shapeSettings; - return JPH::BodyID(); + return {}; } delete shapeSettings; if (!shape) { LOG(NEXO_ERROR, "Shape was null after creation."); - return JPH::BodyID(); + return {}; } const JPH::Vec3 position(transform.pos.x, transform.pos.y, transform.pos.z); const JPH::Quat rotation(transform.quat.x, transform.quat.y, transform.quat.z, transform.quat.w); - JPH::BodyCreationSettings bodySettings( + const JPH::BodyCreationSettings bodySettings( shape, position, rotation, motionType, motionType == JPH::EMotionType::Dynamic ? Layers::MOVING : Layers::NON_MOVING ); - JPH::Body* body = bodyInterface->CreateBody(bodySettings); + const JPH::Body* body = bodyInterface->CreateBody(bodySettings); if (!body) { LOG(NEXO_ERROR, "Body creation failed."); - return JPH::BodyID(); + return {}; } bodyInterface->AddBody(body->GetID(), @@ -179,13 +186,13 @@ namespace nexo::system { return body->GetID(); } + JPH::BodyID PhysicsSystem::createDynamicBody(const ecs::Entity entity, const components::TransformComponent& transform) const + { + const JPH::Vec3 halfExtent(transform.size.x * 0.5f, transform.size.y * 0.5f, transform.size.z * 0.5f); + const JPH::BoxShapeSettings shapeSettings(halfExtent); + const JPH::ShapeRefC shape = shapeSettings.Create().Get(); - JPH::BodyID PhysicsSystem::createDynamicBody(ecs::Entity entity, const components::TransformComponent& transform) { - JPH::Vec3 halfExtent(transform.size.x * 0.5f, transform.size.y * 0.5f, transform.size.z * 0.5f); - JPH::BoxShapeSettings shapeSettings(halfExtent); - JPH::ShapeRefC shape = shapeSettings.Create().Get(); - - JPH::BodyCreationSettings bodySettings( + const JPH::BodyCreationSettings bodySettings( shape, JPH::Vec3(transform.pos.x, transform.pos.y, transform.pos.z), JPH::Quat(transform.quat.x, transform.quat.y, transform.quat.z, transform.quat.w), @@ -193,7 +200,7 @@ namespace nexo::system { Layers::MOVING ); - JPH::Body* body = bodyInterface->CreateBody(bodySettings); + const JPH::Body* body = bodyInterface->CreateBody(bodySettings); // Inertia => Non tested // if (body->IsDynamic()) { @@ -206,7 +213,8 @@ namespace nexo::system { return body->GetID(); } - JPH::BodyID PhysicsSystem::createStaticBody(ecs::Entity entity, const components::TransformComponent& transform) { + JPH::BodyID PhysicsSystem::createStaticBody(ecs::Entity entity, const components::TransformComponent& transform) const + { JPH::BoxShapeSettings baseShapeSettings( JPH::Vec3(transform.size.x * 0.5f, transform.size.y * 0.5f, transform.size.z * 0.5f) ); @@ -234,7 +242,7 @@ namespace nexo::system { return body->GetID(); } - JPH::BodyID PhysicsSystem::createBody(const components::TransformComponent& transform, JPH::EMotionType motionType) + JPH::BodyID PhysicsSystem::createBody(const components::TransformComponent& transform, JPH::EMotionType motionType) const { JPH::Vec3 halfExtent(transform.size.x * 0.5f, transform.size.y * 0.5f, transform.size.z * 0.5f); JPH::BoxShapeSettings shapeSettings(halfExtent); @@ -253,7 +261,8 @@ namespace nexo::system { } - void PhysicsSystem::syncTransformsToBodies(const std::vector& entities, ecs::Coordinator& coordinator) const { + void PhysicsSystem::syncTransformsToBodies(const std::vector& entities, ecs::Coordinator& coordinator) const + { for (const auto& entity : entities) { if (!coordinator.entityHasComponent(entity) || !coordinator.entityHasComponent(entity)) @@ -271,21 +280,23 @@ namespace nexo::system { } } - - - void PhysicsSystem::applyForce(JPH::BodyID bodyID, const JPH::Vec3& force) { + void PhysicsSystem::applyForce(const JPH::BodyID bodyID, const JPH::Vec3& force) const + { bodyInterface->AddForce(bodyID, force); } - void PhysicsSystem::setGravity(const JPH::Vec3& gravity) { + void PhysicsSystem::setGravity(const JPH::Vec3& gravity) const + { physicsSystem->SetGravity(gravity); } - void PhysicsSystem::activateBody(JPH::BodyID bodyID) { + void PhysicsSystem::activateBody(const JPH::BodyID bodyID) const + { bodyInterface->ActivateBody(bodyID); } - void PhysicsSystem::deactivateBody(JPH::BodyID bodyID) { + void PhysicsSystem::deactivateBody(const JPH::BodyID bodyID) const + { bodyInterface->DeactivateBody(bodyID); } diff --git a/engine/src/systems/PhysicsSystem.hpp b/engine/src/systems/PhysicsSystem.hpp index 5033160b7..a2466ddf9 100644 --- a/engine/src/systems/PhysicsSystem.hpp +++ b/engine/src/systems/PhysicsSystem.hpp @@ -18,18 +18,11 @@ #include #include #include -#include -#include #include #include #include #include -#include -#include -#include #include -#include -#include #include #include #include @@ -54,11 +47,11 @@ namespace nexo::system constexpr JPH::uint NUM_LAYERS = 2; } - class MyContactListener : public JPH::ContactListener + class MyContactListener final : public JPH::ContactListener { public: // See: ContactListener - virtual JPH::ValidateResult OnContactValidate( + JPH::ValidateResult OnContactValidate( [[maybe_unused]] const JPH::Body& inBody1, [[maybe_unused]] const JPH::Body& inBody2, [[maybe_unused]] JPH::RVec3Arg inBaseOffset, @@ -70,7 +63,7 @@ namespace nexo::system return JPH::ValidateResult::AcceptAllContactsForThisBodyPair; } - virtual void OnContactAdded( + void OnContactAdded( [[maybe_unused]] const JPH::Body& inBody1, [[maybe_unused]] const JPH::Body& inBody2, [[maybe_unused]] const JPH::ContactManifold& inManifold, @@ -79,7 +72,7 @@ namespace nexo::system //cout << "A contact was added" << endl; } - virtual void OnContactPersisted( + void OnContactPersisted( [[maybe_unused]] const JPH::Body& inBody1, [[maybe_unused]] const JPH::Body& inBody2, [[maybe_unused]] const JPH::ContactManifold& inManifold, @@ -88,7 +81,7 @@ namespace nexo::system //cout << "A contact was persisted" << endl; } - virtual void OnContactRemoved([[maybe_unused]] const JPH::SubShapeIDPair& inSubShapePair) override + void OnContactRemoved([[maybe_unused]] const JPH::SubShapeIDPair& inSubShapePair) override { //cout << "A contact was removed" << endl; } @@ -105,12 +98,12 @@ namespace nexo::system mObjectToBroadPhase[Layers::MOVING] = BroadPhaseLayers::MOVING; } - virtual JPH::uint GetNumBroadPhaseLayers() const override + [[nodiscard]] JPH::uint GetNumBroadPhaseLayers() const override { return BroadPhaseLayers::NUM_LAYERS; } - virtual JPH::BroadPhaseLayer GetBroadPhaseLayer(JPH::ObjectLayer inLayer) const override + [[nodiscard]] JPH::BroadPhaseLayer GetBroadPhaseLayer(JPH::ObjectLayer inLayer) const override { JPH_ASSERT(inLayer < Layers::NUM_LAYERS); return mObjectToBroadPhase[inLayer]; @@ -129,13 +122,13 @@ namespace nexo::system #endif // JPH_EXTERNAL_PROFILE || JPH_PROFILE_ENABLED private: - JPH::BroadPhaseLayer mObjectToBroadPhase[Layers::NUM_LAYERS]; + JPH::BroadPhaseLayer mObjectToBroadPhase[Layers::NUM_LAYERS]{}; }; - class ObjectVsBroadPhaseLayerFilterImpl : public JPH::ObjectVsBroadPhaseLayerFilter + class ObjectVsBroadPhaseLayerFilterImpl final : public JPH::ObjectVsBroadPhaseLayerFilter { public: - virtual bool ShouldCollide(JPH::ObjectLayer inLayer1, JPH::BroadPhaseLayer inLayer2) const override + [[nodiscard]] bool ShouldCollide(JPH::ObjectLayer inLayer1, JPH::BroadPhaseLayer inLayer2) const override { switch (inLayer1) { @@ -150,10 +143,10 @@ namespace nexo::system } }; - class ObjectLayerPairFilterImpl : public JPH::ObjectLayerPairFilter + class ObjectLayerPairFilterImpl final : public JPH::ObjectLayerPairFilter { public: - virtual bool ShouldCollide(JPH::ObjectLayer inObject1, JPH::ObjectLayer inObject2) const override + [[nodiscard]] bool ShouldCollide(JPH::ObjectLayer inObject1, JPH::ObjectLayer inObject2) const override { switch (inObject1) { @@ -170,14 +163,14 @@ namespace nexo::system enum class ShapeType { Box, Sphere, Cylinder, Tetrahedron, Pyramid }; - class PhysicsSystem : public ecs::QuerySystem< + class PhysicsSystem final : public ecs::QuerySystem< ecs::Write, ecs::Write > { public: PhysicsSystem(); - ~PhysicsSystem(); + ~PhysicsSystem() override; PhysicsSystem(const PhysicsSystem&) = delete; PhysicsSystem& operator=(const PhysicsSystem&) = delete; @@ -185,12 +178,12 @@ namespace nexo::system void init(); void update(); - JPH::BodyID createDynamicBody(ecs::Entity entity, const components::TransformComponent& transform); - JPH::BodyID createStaticBody(ecs::Entity entity, const components::TransformComponent& transform); + JPH::BodyID createDynamicBody(ecs::Entity entity, const components::TransformComponent& transform) const; + JPH::BodyID createStaticBody(ecs::Entity entity, const components::TransformComponent& transform) const; - JPH::BodyID createBody(const components::TransformComponent& transform, JPH::EMotionType motionType); + JPH::BodyID createBody(const components::TransformComponent& transform, JPH::EMotionType motionType) const; JPH::BodyID createBodyFromShape(ecs::Entity entity, const components::TransformComponent& transform, - ShapeType shapeType, JPH::EMotionType motionType); + ShapeType shapeType, JPH::EMotionType motionType) const; void syncTransformsToBodies( @@ -198,20 +191,20 @@ namespace nexo::system ecs::Coordinator& coordinator ) const; - void applyForce(JPH::BodyID bodyID, const JPH::Vec3& force); - void setGravity(const JPH::Vec3& gravity); - void activateBody(JPH::BodyID bodyID); - void deactivateBody(JPH::BodyID bodyID); + void applyForce(JPH::BodyID bodyID, const JPH::Vec3& force) const; + void setGravity(const JPH::Vec3& gravity) const; + void activateBody(JPH::BodyID bodyID) const; + void deactivateBody(JPH::BodyID bodyID) const; JPH::BodyInterface* getBodyInterface() const { return bodyInterface; } const JPH::BodyLockInterface* getBodyLockInterface() const { return bodyLockInterface; } private: - JPH::TempAllocatorImpl* tempAllocator; - JPH::JobSystemThreadPool* jobSystem; - JPH::PhysicsSystem* physicsSystem; - JPH::BodyInterface* bodyInterface; - const JPH::BodyLockInterface* bodyLockInterface; + JPH::TempAllocatorImpl* tempAllocator{}; + JPH::JobSystemThreadPool* jobSystem{}; + JPH::PhysicsSystem* physicsSystem{}; + JPH::BodyInterface* bodyInterface{}; + const JPH::BodyLockInterface* bodyLockInterface{}; BPLayerInterfaceImpl broadPhaseLayerInterface; ObjectVsBroadPhaseLayerFilterImpl objectVsBroadPhaseLayerFilter; diff --git a/engine/src/systems/RenderBillboardSystem.cpp b/engine/src/systems/RenderBillboardSystem.cpp index 990e4ad67..ff2292a0d 100644 --- a/engine/src/systems/RenderBillboardSystem.cpp +++ b/engine/src/systems/RenderBillboardSystem.cpp @@ -115,14 +115,14 @@ namespace nexo::system { { renderer::DrawCommand cmd; cmd.vao = mesh.vao; - bool isOpaque = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->isOpaque : true; + const bool isOpaque = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->isOpaque : true; if (isOpaque) cmd.shader = renderer::ShaderLibrary::getInstance().get("Flat color"); else { cmd.shader = renderer::ShaderLibrary::getInstance().get("Albedo unshaded transparent"); cmd.uniforms["uMaterial.albedoColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoColor : glm::vec4(0.0f); - auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; - auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; + const auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; + const auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.albedoTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(albedoTexture); } const glm::mat4 &billboardRotation = createBillboardTransformMatrix(cameraPosition, transform); @@ -135,7 +135,7 @@ namespace nexo::system { } static renderer::DrawCommand createDrawCommand( - ecs::Entity entity, + const ecs::Entity entity, const glm::vec3 &cameraPosition, const std::shared_ptr &shader, const components::BillboardComponent &billboard, @@ -152,23 +152,23 @@ namespace nexo::system { cmd.uniforms["uEntityId"] = static_cast(entity); cmd.uniforms["uMaterial.albedoColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoColor : glm::vec4(0.0f); - auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; - auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; + const auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; + const auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.albedoTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(albedoTexture); cmd.uniforms["uMaterial.specularColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->specularColor : glm::vec4(0.0f); - auto specularTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->metallicMap.lock() : nullptr; - auto specularTexture = specularTextureAsset && specularTextureAsset->isLoaded() ? specularTextureAsset->getData()->texture : nullptr; + const auto specularTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->metallicMap.lock() : nullptr; + const auto specularTexture = specularTextureAsset && specularTextureAsset->isLoaded() ? specularTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.specularTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(specularTexture); cmd.uniforms["uMaterial.emissiveColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->emissiveColor : glm::vec3(0.0f); - auto emissiveTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->emissiveMap.lock() : nullptr; - auto emissiveTexture = emissiveTextureAsset && emissiveTextureAsset->isLoaded() ? emissiveTextureAsset->getData()->texture : nullptr; + const auto emissiveTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->emissiveMap.lock() : nullptr; + const auto emissiveTexture = emissiveTextureAsset && emissiveTextureAsset->isLoaded() ? emissiveTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.emissiveTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(emissiveTexture); cmd.uniforms["uMaterial.roughness"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->roughness : 1.0f; - auto roughnessTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->roughnessMap.lock() : nullptr; - auto roughnessTexture = roughnessTextureAsset && roughnessTextureAsset->isLoaded() ? roughnessTextureAsset->getData()->texture : nullptr; + const auto roughnessTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->roughnessMap.lock() : nullptr; + const auto roughnessTexture = roughnessTextureAsset && roughnessTextureAsset->isLoaded() ? roughnessTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.roughnessTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(roughnessTexture); cmd.filterMask = 0; @@ -211,7 +211,7 @@ namespace nexo::system { const auto &transform = transformComponentArray->get(entitySpan[i]); const auto &materialAsset = materialComponentArray->get(entitySpan[i]).material.lock(); const auto &billboard = billboardSpan[i]; - auto shaderStr = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->shader : nullptr; + auto shaderStr = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->shader : ""; auto shader = renderer::ShaderLibrary::getInstance().get(shaderStr); auto cmd = createDrawCommand( entity, diff --git a/engine/src/systems/RenderCommandSystem.cpp b/engine/src/systems/RenderCommandSystem.cpp index 91b0c2f33..a6812a62b 100644 --- a/engine/src/systems/RenderCommandSystem.cpp +++ b/engine/src/systems/RenderCommandSystem.cpp @@ -127,8 +127,8 @@ namespace nexo::system { cmd.uniforms["uGridSize"] = gridParams.gridSize; cmd.uniforms["uGridCellSize"] = gridParams.cellSize; cmd.uniforms["uGridMinPixelsBetweenCells"] = gridParams.minPixelsBetweenCells; - const glm::vec4 gridColorThin = {0.5f, 0.55f, 0.7f, 0.6f}; - const glm::vec4 gridColorThick = {0.7f, 0.75f, 0.9f, 0.8f}; + constexpr glm::vec4 gridColorThin = {0.5f, 0.55f, 0.7f, 0.6f}; + constexpr glm::vec4 gridColorThick = {0.7f, 0.75f, 0.9f, 0.8f}; cmd.uniforms["uGridColorThin"] = gridColorThin; cmd.uniforms["uGridColorThick"] = gridColorThick; @@ -206,14 +206,14 @@ namespace nexo::system { { renderer::DrawCommand cmd; cmd.vao = mesh.vao; - bool isOpaque = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->isOpaque : true; + const bool isOpaque = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->isOpaque : true; if (isOpaque) cmd.shader = renderer::ShaderLibrary::getInstance().get("Flat color"); else { cmd.shader = renderer::ShaderLibrary::getInstance().get("Albedo unshaded transparent"); cmd.uniforms["uMaterial.albedoColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoColor : glm::vec4(0.0f); - auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; - auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; + const auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; + const auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.albedoTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(albedoTexture); } cmd.uniforms["uMatModel"] = transform.worldMatrix; @@ -223,7 +223,7 @@ namespace nexo::system { } static renderer::DrawCommand createDrawCommand( - ecs::Entity entity, + const ecs::Entity entity, const std::shared_ptr &shader, const components::StaticMeshComponent &mesh, const std::shared_ptr &materialAsset, @@ -236,23 +236,23 @@ namespace nexo::system { cmd.uniforms["uEntityId"] = static_cast(entity); cmd.uniforms["uMaterial.albedoColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoColor : glm::vec4(0.0f); - auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; - auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; + const auto albedoTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->albedoTexture.lock() : nullptr; + const auto albedoTexture = albedoTextureAsset && albedoTextureAsset->isLoaded() ? albedoTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.albedoTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(albedoTexture); cmd.uniforms["uMaterial.specularColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->specularColor : glm::vec4(0.0f); - auto specularTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->metallicMap.lock() : nullptr; - auto specularTexture = specularTextureAsset && specularTextureAsset->isLoaded() ? specularTextureAsset->getData()->texture : nullptr; + const auto specularTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->metallicMap.lock() : nullptr; + const auto specularTexture = specularTextureAsset && specularTextureAsset->isLoaded() ? specularTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.specularTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(specularTexture); cmd.uniforms["uMaterial.emissiveColor"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->emissiveColor : glm::vec3(0.0f); - auto emissiveTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->emissiveMap.lock() : nullptr; - auto emissiveTexture = emissiveTextureAsset && emissiveTextureAsset->isLoaded() ? emissiveTextureAsset->getData()->texture : nullptr; + const auto emissiveTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->emissiveMap.lock() : nullptr; + const auto emissiveTexture = emissiveTextureAsset && emissiveTextureAsset->isLoaded() ? emissiveTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.emissiveTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(emissiveTexture); cmd.uniforms["uMaterial.roughness"] = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->roughness : 1.0f; - auto roughnessTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->roughnessMap.lock() : nullptr; - auto roughnessTexture = roughnessTextureAsset && roughnessTextureAsset->isLoaded() ? roughnessTextureAsset->getData()->texture : nullptr; + const auto roughnessTextureAsset = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->roughnessMap.lock() : nullptr; + const auto roughnessTexture = roughnessTextureAsset && roughnessTextureAsset->isLoaded() ? roughnessTextureAsset->getData()->texture : nullptr; cmd.uniforms["uMaterial.roughnessTexIndex"] = renderer::NxRenderer3D::get().getTextureIndex(roughnessTexture); cmd.filterMask = 0; @@ -293,7 +293,7 @@ namespace nexo::system { continue; const auto &transform = transformSpan[i]; const auto &materialAsset = materialSpan[i].material.lock(); - auto shaderStr = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->shader : nullptr; + auto shaderStr = materialAsset && materialAsset->isLoaded() ? materialAsset->getData()->shader : ""; const auto &mesh = meshSpan[i]; auto shader = renderer::ShaderLibrary::getInstance().get(shaderStr); if (!shader) diff --git a/engine/src/systems/ScriptingSystem.cpp b/engine/src/systems/ScriptingSystem.cpp index 9bceb104e..da42d7aaa 100644 --- a/engine/src/systems/ScriptingSystem.cpp +++ b/engine/src/systems/ScriptingSystem.cpp @@ -20,16 +20,16 @@ namespace nexo::system { ScriptingSystem::ScriptingSystem() { - nexo::scripting::HostHandler::Parameters params; - params.errorCallback = [this](const nexo::scripting::HostString& message) { + scripting::HostHandler::Parameters params; + params.errorCallback = [this](const scripting::HostString& message) { LOG(NEXO_ERROR, "Scripting host error: {}", message.to_utf8()); m_latestScriptingError = message.to_utf8(); }; - nexo::scripting::HostHandler& host = nexo::scripting::HostHandler::getInstance(); + scripting::HostHandler& host = scripting::HostHandler::getInstance(); // Initialize the host - if (host.initialize(params) != nexo::scripting::HostHandler::SUCCESS) { + if (host.initialize(params) != scripting::HostHandler::SUCCESS) { LOG(NEXO_ERROR, "Failed to initialize host"); THROW_EXCEPTION(scripting::ScriptingBackendInitFailed, m_latestScriptingError); } @@ -38,7 +38,7 @@ namespace nexo::system { int ScriptingSystem::init() { - auto &scriptHost = scripting::HostHandler::getInstance(); + const auto &scriptHost = scripting::HostHandler::getInstance(); updateWorldState(); if (auto ret = scriptHost.getManagedApi().SystemBase.InitializeComponents(); ret != 0) { @@ -64,10 +64,10 @@ namespace nexo::system { int ScriptingSystem::update() { const auto &scriptHost = scripting::HostHandler::getInstance(); - auto &api = scriptHost.getManagedApi(); + const auto &api = scriptHost.getManagedApi(); updateWorldState(); - if (auto ret = api.SystemBase.UpdateSystems(&m_worldState, sizeof(m_worldState)); ret != 0) { + if (const auto ret = api.SystemBase.UpdateSystems(&m_worldState, sizeof(m_worldState)); ret != 0) { LOG_ONCE(NEXO_ERROR, "Failed to update scripting systems"); return ret; } @@ -78,7 +78,7 @@ namespace nexo::system { int ScriptingSystem::shutdown() { const auto &scriptHost = scripting::HostHandler::getInstance(); - auto &api = scriptHost.getManagedApi(); + const auto &api = scriptHost.getManagedApi(); updateWorldState(); if (auto ret = api.SystemBase.ShutdownSystems(&m_worldState, sizeof(m_worldState)); ret != 0) { diff --git a/engine/src/systems/TransformHierarchySystem.cpp b/engine/src/systems/TransformHierarchySystem.cpp index 462cd5afb..08a9b883c 100644 --- a/engine/src/systems/TransformHierarchySystem.cpp +++ b/engine/src/systems/TransformHierarchySystem.cpp @@ -13,7 +13,6 @@ /////////////////////////////////////////////////////////////////////////////// #include "TransformHierarchySystem.hpp" -#include "components/Model.hpp" #include "components/Parent.hpp" #include "components/Transform.hpp" #include "components/SceneComponents.hpp" diff --git a/engine/src/systems/TransformHierarchySystem.hpp b/engine/src/systems/TransformHierarchySystem.hpp index 9c4f883fd..1d5b9621c 100644 --- a/engine/src/systems/TransformHierarchySystem.hpp +++ b/engine/src/systems/TransformHierarchySystem.hpp @@ -48,6 +48,6 @@ namespace nexo::system { const std::shared_ptr> &transformComponentArray, const std::vector& children, const glm::mat4& parentWorldMatrix); - glm::mat4 calculateLocalMatrix(const components::TransformComponent& transform) const; + [[nodiscard]] glm::mat4 calculateLocalMatrix(const components::TransformComponent& transform) const; }; } diff --git a/engine/src/systems/TransformMatrixSystem.hpp b/engine/src/systems/TransformMatrixSystem.hpp index 60182acf6..41f6443b0 100644 --- a/engine/src/systems/TransformMatrixSystem.hpp +++ b/engine/src/systems/TransformMatrixSystem.hpp @@ -17,6 +17,7 @@ #include "components/Transform.hpp" #include "components/SceneComponents.hpp" #include "components/RenderContext.hpp" + namespace nexo::system { class TransformMatrixSystem final : public ecs::QuerySystem< ecs::Write, From fa9068e7d943bf2724f02d720ae903f694ab572e Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Sat, 26 Jul 2025 19:14:42 +0200 Subject: [PATCH 12/30] fix(sonar-engine): missing include for windows --- engine/src/core/event/Listener.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/engine/src/core/event/Listener.hpp b/engine/src/core/event/Listener.hpp index e171ca7cb..778b4c5cb 100644 --- a/engine/src/core/event/Listener.hpp +++ b/engine/src/core/event/Listener.hpp @@ -13,6 +13,7 @@ /////////////////////////////////////////////////////////////////////////////// #pragma once +#include #include namespace nexo::event { From 5d3896fa895f21607b5931ed163fa9f1cf2afb2a Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Sat, 26 Jul 2025 22:41:43 +0200 Subject: [PATCH 13/30] fix(sonar-engine): add exception for non trivially copyable component in insertRaw method --- engine/src/ecs/ComponentArray.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/src/ecs/ComponentArray.hpp b/engine/src/ecs/ComponentArray.hpp index 76c8effc5..4fd9d8d31 100644 --- a/engine/src/ecs/ComponentArray.hpp +++ b/engine/src/ecs/ComponentArray.hpp @@ -250,7 +250,7 @@ namespace nexo::ecs { if constexpr (std::is_trivially_copyable_v) { std::memcpy(&m_componentArray[newIndex], componentData, sizeof(T)); } else { - new (&m_componentArray[newIndex]) T(*reinterpret_cast(componentData)); + THROW_EXCEPTION(InternalError, "Component type is not trivially copyable for raw insertion"); } ++m_size; From 76903358a298df534cb1f2ac172ccac9215d0669 Mon Sep 17 00:00:00 2001 From: Thyodas Date: Sat, 26 Jul 2025 17:26:47 +0200 Subject: [PATCH 14/30] feat(windows-titlebar): add dark mode and title bar name customization --- engine/src/Application.cpp | 1 + engine/src/renderer/Window.hpp | 15 ++++-- engine/src/renderer/opengl/OpenGlWindow.cpp | 58 +++++++++++++++++++-- engine/src/renderer/opengl/OpenGlWindow.hpp | 6 +++ 4 files changed, 72 insertions(+), 8 deletions(-) diff --git a/engine/src/Application.cpp b/engine/src/Application.cpp index 3a9df72e0..37af72f6d 100644 --- a/engine/src/Application.cpp +++ b/engine/src/Application.cpp @@ -274,6 +274,7 @@ namespace nexo { m_window->init(); registerWindowCallbacks(); m_window->setVsync(false); + m_window->setDarkMode(true); #ifdef NX_GRAPHICS_API_OPENGL if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) diff --git a/engine/src/renderer/Window.hpp b/engine/src/renderer/Window.hpp index 115bc1b8e..7ff88b5cb 100644 --- a/engine/src/renderer/Window.hpp +++ b/engine/src/renderer/Window.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #define GLFW_INCLUDE_NONE #include #include @@ -35,8 +36,9 @@ namespace nexo::renderer { { unsigned int width; unsigned int height; - const char *title; - bool vsync{}; + std::string title; + bool vsync = true; + bool isDarkMode = false; ResizeCallback resizeCallback; CloseCallback closeCallback; @@ -46,7 +48,7 @@ namespace nexo::renderer { MouseMoveCallback mouseMoveCallback; FileDropCallback fileDropCallback; - NxWindowProperty(const unsigned int w, const unsigned h, const char * t) : width(w), height(h), title(t) {} + NxWindowProperty(const unsigned int w, const unsigned h, std::string t) : width(w), height(h), title(std::move(t)) {} }; /** @@ -81,6 +83,13 @@ namespace nexo::renderer { virtual void getDpiScale(float *x, float *y) const = 0; virtual void setWindowIcon(const std::filesystem::path& iconPath) = 0; + + virtual void setTitle(const std::string& title) = 0; + [[nodiscard]] virtual const std::string& getTitle() const = 0; + + virtual void setDarkMode(bool enabled) = 0; + [[nodiscard]] virtual bool isDarkMode() const = 0; + virtual void setVsync(bool enabled) = 0; [[nodiscard]] virtual bool isVsync() const = 0; diff --git a/engine/src/renderer/opengl/OpenGlWindow.cpp b/engine/src/renderer/opengl/OpenGlWindow.cpp index 111782c4d..08396b964 100644 --- a/engine/src/renderer/opengl/OpenGlWindow.cpp +++ b/engine/src/renderer/opengl/OpenGlWindow.cpp @@ -20,6 +20,15 @@ #include "renderer/RendererExceptions.hpp" #include "Logger.hpp" +#if defined(_WIN32) || defined(_WIN64) + #include + #define GLFW_EXPOSE_NATIVE_WIN32 + #define GLFW_EXPOSE_NATIVE_WGL + #define GLFW_NATIVE_INCLUDE_NONE + #include + #pragma comment (lib, "Dwmapi") +#endif + namespace nexo::renderer { static void glfwErrorCallback(const int errorCode, const char *errorStr) { @@ -113,12 +122,13 @@ namespace nexo::renderer { glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); - _openGlWindow = glfwCreateWindow(static_cast(_props.width), static_cast(_props.height), _props.title, nullptr, nullptr); + _openGlWindow = glfwCreateWindow(static_cast(_props.width), static_cast(_props.height), _props.title.c_str(), nullptr, nullptr); if (!_openGlWindow) THROW_EXCEPTION(NxGraphicsApiWindowInitFailure, "OPENGL"); glfwMakeContextCurrent(_openGlWindow); glfwSetWindowUserPointer(_openGlWindow, &_props); setVsync(true); + setDarkMode(false); setupCallback(); LOG(NEXO_DEV, "Opengl window ({}, {}) initialized", _props.width, _props.height); } @@ -154,15 +164,14 @@ namespace nexo::renderer { glfwGetWindowContentScale(_openGlWindow, x, y); } - void NxOpenGlWindow::setWindowIcon(const std::filesystem::path& iconPath) + void NxOpenGlWindow::setWindowIcon(const std::filesystem::path &iconPath) { GLFWimage icon; const auto iconStringPath = iconPath.string(); - icon.pixels = stbi_load(iconStringPath.c_str(), &icon.width, &icon.height, nullptr, 4); + icon.pixels = stbi_load(iconStringPath.c_str(), &icon.width, &icon.height, nullptr, 4); if (!icon.pixels) { THROW_EXCEPTION(NxStbiLoadException, - std::format("Failed to load icon '{}': {}", - iconStringPath, stbi_failure_reason())); + std::format("Failed to load icon '{}': {}", iconStringPath, stbi_failure_reason())); } if (icon.width == 0 || icon.height == 0) { LOG(NEXO_WARN, "Icon '{}' has a size of 0x0", iconStringPath); @@ -172,6 +181,45 @@ namespace nexo::renderer { stbi_image_free(icon.pixels); } + void NxOpenGlWindow::setTitle(const std::string &title) + { + _props.title = title; + glfwSetWindowTitle(_openGlWindow, _props.title.c_str()); + LOG(NEXO_DEV, "Window title set to '{}'", _props.title); + } + + const std::string &NxOpenGlWindow::getTitle() const + { + return _props.title; + } + + void NxOpenGlWindow::setDarkMode(const bool enabled) + { +#if defined(_WIN32) || defined(_WIN64) + HWND hWnd = glfwGetWin32Window(_openGlWindow); + if (hWnd == nullptr) { + LOG(NEXO_ERROR, "[GLFW ERROR] Failed to get Win32 window handle for dark mode setting"); + return; + } + + const BOOL useDarkMode = enabled ? TRUE : FALSE; + const BOOL setImmersiveDarkModeSuccess = SUCCEEDED(DwmSetWindowAttribute( + hWnd, DWMWINDOWATTRIBUTE::DWMWA_USE_IMMERSIVE_DARK_MODE, &_props.isDarkMode, sizeof(useDarkMode))); + if (!setImmersiveDarkModeSuccess) { + LOG(NEXO_ERROR, "[GLFW ERROR] Failed to set enable/disable immersive dark mode for window: {}", + GetLastError()); + return; + } +#endif + LOG(NEXO_DEV, "Setting dark mode to {}", enabled ? "enabled" : "disabled"); + _props.isDarkMode = enabled; + } + + bool NxOpenGlWindow::isDarkMode() const + { + return _props.isDarkMode; + } + void NxOpenGlWindow::setErrorCallback(void *fctPtr) { glfwSetErrorCallback(reinterpret_cast(fctPtr)); diff --git a/engine/src/renderer/opengl/OpenGlWindow.hpp b/engine/src/renderer/opengl/OpenGlWindow.hpp index dbeb11eb6..ff7b06b3d 100644 --- a/engine/src/renderer/opengl/OpenGlWindow.hpp +++ b/engine/src/renderer/opengl/OpenGlWindow.hpp @@ -81,6 +81,12 @@ namespace nexo::renderer { void setWindowIcon(const std::filesystem::path& iconPath) override; + void setTitle(const std::string& title) override; + [[nodiscard]] const std::string& getTitle() const override; + + void setDarkMode(bool enabled) override; + [[nodiscard]] bool isDarkMode() const override; + /** * @brief Enables or disables vertical synchronization (VSync). * From eef1079081582969e0fc2909f8bf0b763d08750b Mon Sep 17 00:00:00 2001 From: Thyodas Date: Sun, 27 Jul 2025 20:28:06 +0200 Subject: [PATCH 15/30] fix(windows-titlebar): invalid variable in argument --- engine/src/renderer/opengl/OpenGlWindow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/src/renderer/opengl/OpenGlWindow.cpp b/engine/src/renderer/opengl/OpenGlWindow.cpp index 08396b964..0c19d9db2 100644 --- a/engine/src/renderer/opengl/OpenGlWindow.cpp +++ b/engine/src/renderer/opengl/OpenGlWindow.cpp @@ -204,7 +204,7 @@ namespace nexo::renderer { const BOOL useDarkMode = enabled ? TRUE : FALSE; const BOOL setImmersiveDarkModeSuccess = SUCCEEDED(DwmSetWindowAttribute( - hWnd, DWMWINDOWATTRIBUTE::DWMWA_USE_IMMERSIVE_DARK_MODE, &_props.isDarkMode, sizeof(useDarkMode))); + hWnd, DWMWINDOWATTRIBUTE::DWMWA_USE_IMMERSIVE_DARK_MODE, &useDarkMode, sizeof(useDarkMode))); if (!setImmersiveDarkModeSuccess) { LOG(NEXO_ERROR, "[GLFW ERROR] Failed to set enable/disable immersive dark mode for window: {}", GetLastError()); From d577c76f649762914402bf5085382a34a24514a2 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:01:35 +0200 Subject: [PATCH 16/30] feat(render-passes): add pipeline render target not set exception --- engine/src/renderer/RendererExceptions.hpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/engine/src/renderer/RendererExceptions.hpp b/engine/src/renderer/RendererExceptions.hpp index e425bab18..2bc14245b 100644 --- a/engine/src/renderer/RendererExceptions.hpp +++ b/engine/src/renderer/RendererExceptions.hpp @@ -209,4 +209,11 @@ namespace nexo::renderer { const std::source_location loc = std::source_location::current()) : Exception(std::format("STBI load failed: {}", msg), loc) {} }; + + class NxPipelineRenderTargetNotSetException final : public Exception { + public: + explicit NxPipelineRenderTargetNotSetException(const std::source_location loc = + std::source_location::current()) + : Exception(std::format("Pipeline render target not set"), loc) {} + }; } From 0e235939aa5afaff7e1f277dbaba72444be03cde Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:02:22 +0200 Subject: [PATCH 17/30] feat(render-passes): make resize abstract + add getOutput virtual method --- engine/src/renderer/RenderPass.hpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/engine/src/renderer/RenderPass.hpp b/engine/src/renderer/RenderPass.hpp index f93726e12..63bc25d47 100644 --- a/engine/src/renderer/RenderPass.hpp +++ b/engine/src/renderer/RenderPass.hpp @@ -16,6 +16,7 @@ #include #include #include +#include "Framebuffer.hpp" namespace nexo::renderer { @@ -30,7 +31,7 @@ namespace nexo::renderer { // The actual rendering work virtual void execute(RenderPipeline& pipeline) = 0; - virtual void resize(unsigned int width, unsigned int height) = 0; + virtual void resize([[maybe_unused]] unsigned int width, [[maybe_unused]] unsigned int height) {}; void setFinal(const bool isFinal) {m_isFinal = isFinal;}; [[nodiscard]] bool isFinal() const {return m_isFinal;} @@ -40,6 +41,8 @@ namespace nexo::renderer { [[nodiscard]] const std::vector &getPrerequisites() const { return prerequisites; } std::vector &getEffects() { return effects; } [[nodiscard]] const std::vector &getEffects() const { return effects; } + + virtual std::shared_ptr getOutput() const { return nullptr; }; protected: bool m_isFinal = false; PassId id; From 9c2fb04b383e51d2957d9b2231796b5f9fbc83c9 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:03:06 +0200 Subject: [PATCH 18/30] refactor(render-passes): pipeline now only have one render target, each render passes draws onto it or use their own --- engine/src/renderer/RenderPipeline.cpp | 69 ++++++++++---------------- engine/src/renderer/RenderPipeline.hpp | 17 ++----- 2 files changed, 29 insertions(+), 57 deletions(-) diff --git a/engine/src/renderer/RenderPipeline.cpp b/engine/src/renderer/RenderPipeline.cpp index 33b0402f0..668ea607b 100644 --- a/engine/src/renderer/RenderPipeline.cpp +++ b/engine/src/renderer/RenderPipeline.cpp @@ -12,7 +12,11 @@ // /////////////////////////////////////////////////////////////////////////////// #include "RenderPipeline.hpp" +#include "Exception.hpp" #include "Framebuffer.hpp" +#include "RenderCommand.hpp" +#include "RendererExceptions.hpp" +#include "Renderer3D.hpp" #include #include #include @@ -35,7 +39,7 @@ namespace nexo::renderer { return; const auto &pass = passes[id]; - // Save prerequisites and effects before removal + // Save dependencies before removal std::vector prerequisites = pass->getPrerequisites(); std::vector effects = pass->getEffects(); @@ -62,14 +66,11 @@ namespace nexo::renderer { // First remove the pass, then find a new final output if needed const bool needNewFinalOutput = (finalOutputPass == static_cast(id)); - // Remove the pass from the maps + // Erase the pass passes.erase(id); - if (passOutputs.contains(id)) - passOutputs.erase(id); - // Now, after removing the pass, find a new final output if needed - if (needNewFinalOutput) { - // If there are no passes left, set finalOutputPass to -1 directly + // Choose new final output if necessary + if (needNewFinal) { if (passes.empty()) { finalOutputPass = -1; } else { @@ -78,11 +79,11 @@ namespace nexo::renderer { if (!terminalPasses.empty()) { setFinalOutputPass(terminalPasses[0]); } else { - // Fallback to any pass setFinalOutputPass(passes.begin()->first); } } } + m_isDirty = true; } @@ -90,7 +91,6 @@ namespace nexo::renderer { { if (!passes.contains(pass) || !passes.contains(prerequisite)) return; - auto& prereqs = passes[pass]->getPrerequisites(); if (std::find(prereqs.begin(), prereqs.end(), prerequisite) == prereqs.end()) prereqs.push_back(prerequisite); @@ -101,7 +101,6 @@ namespace nexo::renderer { { if (!passes.contains(pass)) return; - auto& prereqs = passes[pass]->getPrerequisites(); std::erase(prereqs, prerequisite); m_isDirty = true; @@ -111,7 +110,6 @@ namespace nexo::renderer { { if (!passes.contains(pass) || !passes.contains(effect)) return; - auto& effects = passes[pass]->getEffects(); if (std::find(effects.begin(), effects.end(), effect) == effects.end()) effects.push_back(effect); @@ -122,7 +120,6 @@ namespace nexo::renderer { { if (!passes.contains(pass)) return; - auto& effects = passes[pass]->getEffects(); std::erase(effects, effect); m_isDirty = true; @@ -136,17 +133,14 @@ namespace nexo::renderer { return nullptr; } - std::shared_ptr RenderPipeline::getOutput(const PassId id) + void RenderPipeline::setRenderTarget(std::shared_ptr renderTarget) { - auto it = passOutputs.find(id); - if (it != passOutputs.end()) - return it->second; - return nullptr; + m_renderTarget = std::move(renderTarget); } - void RenderPipeline::setOutput(const PassId id, const std::shared_ptr& output) + std::shared_ptr RenderPipeline::getRenderTarget() const { - passOutputs[id] = output; + return m_renderTarget; } void RenderPipeline::setFinalOutputPass(const PassId id) @@ -160,16 +154,6 @@ namespace nexo::renderer { } } - void RenderPipeline::setFinalRenderTarget(const std::shared_ptr &finalRenderTarget) - { - m_finalRenderTarget = finalRenderTarget; - } - - std::shared_ptr RenderPipeline::getFinalRenderTarget() const - { - return m_finalRenderTarget; - } - std::vector RenderPipeline::findTerminalPasses() const { std::vector terminals; @@ -196,8 +180,6 @@ namespace nexo::renderer { std::vector RenderPipeline::createExecutionPlan() { std::vector result; - - // Early return if there are no passes if (passes.empty()) { m_isDirty = false; return result; @@ -214,20 +196,15 @@ namespace nexo::renderer { if (passes.contains(prereq)) buildPlan(prereq); } - - // Then add this pass visited.insert(current); result.push_back(current); }; - // Start with the final output pass if it exists if (finalOutputPass != -1 && passes.contains(finalOutputPass)) { buildPlan(finalOutputPass); } else { - // Fallback to processing all terminal passes auto terminals = findTerminalPasses(); if (terminals.empty()) { - // If no terminal passes, include all passes for (const auto& [id, _] : passes) terminals.push_back(id); } @@ -236,6 +213,7 @@ namespace nexo::renderer { for (const PassId term : terminals) buildPlan(term); } + m_isDirty = false; return result; } @@ -245,6 +223,9 @@ namespace nexo::renderer { if (m_isDirty) m_plan = createExecutionPlan(); + if (!m_renderTarget) + THROW_EXCEPTION(NxPipelineRenderTargetNotSetException); + for (PassId id : m_plan) { if (passes.contains(id)) passes[id]->execute(*this); @@ -252,38 +233,38 @@ namespace nexo::renderer { m_drawCommands.clear(); } - void RenderPipeline::addDrawCommands(const std::vector &drawCommands) + void RenderPipeline::addDrawCommands(const std::vector& drawCommands) { m_drawCommands.reserve(m_drawCommands.size() + drawCommands.size()); m_drawCommands.insert(m_drawCommands.end(), drawCommands.begin(), drawCommands.end()); } - void RenderPipeline::addDrawCommand(const DrawCommand &drawCommand) + void RenderPipeline::addDrawCommand(const DrawCommand& drawCommand) { m_drawCommands.push_back(drawCommand); } - const std::vector &RenderPipeline::getDrawCommands() const + const std::vector& RenderPipeline::getDrawCommands() const { return m_drawCommands; } - void RenderPipeline::setCameraClearColor(const glm::vec4 &clearColor) + void RenderPipeline::setCameraClearColor(const glm::vec4& clearColor) { m_cameraClearColor = clearColor; } - const glm::vec4 &RenderPipeline::getCameraClearColor() const + const glm::vec4& RenderPipeline::getCameraClearColor() const { return m_cameraClearColor; } void RenderPipeline::resize(const unsigned int width, const unsigned int height) const { - if (!m_finalRenderTarget) + if (!m_renderTarget) return; - m_finalRenderTarget->resize(width, height); - for (const auto &[_, pass] : passes) + m_renderTarget->resize(width, height); + for (const auto& [_, pass] : passes) pass->resize(width, height); } } diff --git a/engine/src/renderer/RenderPipeline.hpp b/engine/src/renderer/RenderPipeline.hpp index 5abfa43f8..7aa184c32 100644 --- a/engine/src/renderer/RenderPipeline.hpp +++ b/engine/src/renderer/RenderPipeline.hpp @@ -44,14 +44,8 @@ namespace nexo::renderer { // Get a render pass by ID std::shared_ptr getRenderPass(PassId id); - // Get output from a pass - std::shared_ptr getOutput(PassId id); - - // Set output for a pass - void setOutput(PassId id, const std::shared_ptr& output); - - void setFinalRenderTarget(const std::shared_ptr& finalRenderTarget); - std::shared_ptr getFinalRenderTarget() const; + void setRenderTarget(std::shared_ptr finalRenderTarget); + std::shared_ptr getRenderTarget() const; // Set the final output pass void setFinalOutputPass(PassId id); @@ -59,7 +53,7 @@ namespace nexo::renderer { // Get the final output pass PassId getFinalOutputPass() const { return finalOutputPass; } - // Calculate execution plan using GOAP + // Calculate execution plan using DFS std::vector createExecutionPlan(); // Execute the pipeline @@ -95,10 +89,7 @@ namespace nexo::renderer { // For generating unique IDs PassId nextPassId = 0; - // Stores outputs of passes - std::unordered_map> passOutputs; - - std::shared_ptr m_finalRenderTarget = nullptr; + std::shared_ptr m_renderTarget = nullptr; // The final output pass (what gets rendered to screen) int finalOutputPass = -1; From 7502d36bce90d07cc7213b3f30a4c7339d612569 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:04:01 +0200 Subject: [PATCH 19/30] refactor(render-passes): forward and grid pass draw onto the same render target and grid does not copy the content anymore --- engine/src/renderPasses/ForwardPass.cpp | 38 +++++++------------------ engine/src/renderPasses/ForwardPass.hpp | 5 +--- engine/src/renderPasses/GridPass.cpp | 36 ++++------------------- engine/src/renderPasses/GridPass.hpp | 5 +--- 4 files changed, 18 insertions(+), 66 deletions(-) diff --git a/engine/src/renderPasses/ForwardPass.cpp b/engine/src/renderPasses/ForwardPass.cpp index b3f2760f9..5497033d4 100644 --- a/engine/src/renderPasses/ForwardPass.cpp +++ b/engine/src/renderPasses/ForwardPass.cpp @@ -14,6 +14,7 @@ #include "ForwardPass.hpp" #include "DrawCommand.hpp" +#include "Framebuffer.hpp" #include "RenderCommand.hpp" #include "renderPasses/Masks.hpp" #include "renderer/RenderPipeline.hpp" @@ -23,43 +24,24 @@ #include namespace nexo::renderer { - ForwardPass::ForwardPass(unsigned int width, unsigned int height) : RenderPass(Passes::FORWARD, "Forward Pass") + ForwardPass::ForwardPass() : RenderPass(Passes::FORWARD, "Forward Pass") { - renderer::NxFramebufferSpecs framebufferSpecs; - framebufferSpecs.attachments = { - renderer::NxFrameBufferTextureFormats::RGBA8, - renderer::NxFrameBufferTextureFormats::RED_INTEGER, - renderer::NxFrameBufferTextureFormats::Depth - }; - framebufferSpecs.width = width; - framebufferSpecs.height = height; - m_output = renderer::NxFramebuffer::create(framebufferSpecs); + } void ForwardPass::execute(RenderPipeline& pipeline) { - auto output = (m_isFinal) ? pipeline.getFinalRenderTarget() : m_output; - output->bind(); - renderer::NxRenderCommand::setClearColor(pipeline.getCameraClearColor()); - renderer::NxRenderCommand::clear(); - output->clearAttachment(1, -1); - - //IMPORTANT: Bind textures after binding the framebuffer, since binding can trigger a resize and invalidate the - // current texture slots - renderer::NxRenderer3D::get().bindTextures(); + const std::shared_ptr renderTarget = pipeline.getRenderTarget(); + renderTarget->bind(); + NxRenderCommand::setClearColor(pipeline.getCameraClearColor()); + NxRenderCommand::clear(); + renderTarget->clearAttachment(1, -1); + NxRenderer3D::get().bindTextures(); const std::vector &drawCommands = pipeline.getDrawCommands(); for (const auto &cmd : drawCommands) { if (cmd.filterMask & F_FORWARD_PASS) cmd.execute(); } - output->unbind(); - pipeline.setOutput(id, output); - } - - void ForwardPass::resize(unsigned int width, unsigned int height) - { - if (!m_output) - return; - m_output->resize(width, height); + renderTarget->unbind(); } } diff --git a/engine/src/renderPasses/ForwardPass.hpp b/engine/src/renderPasses/ForwardPass.hpp index 0eb67e52b..4e18fc6c0 100644 --- a/engine/src/renderPasses/ForwardPass.hpp +++ b/engine/src/renderPasses/ForwardPass.hpp @@ -20,12 +20,9 @@ namespace nexo::renderer { class ForwardPass : public RenderPass { public: - ForwardPass(unsigned int width, unsigned int height); + ForwardPass(); ~ForwardPass() override = default; void execute(RenderPipeline& pipeline) override; - void resize(unsigned int width, unsigned int height) override; - private: - std::shared_ptr m_output; }; } diff --git a/engine/src/renderPasses/GridPass.cpp b/engine/src/renderPasses/GridPass.cpp index 0df603051..b86b89cb3 100644 --- a/engine/src/renderPasses/GridPass.cpp +++ b/engine/src/renderPasses/GridPass.cpp @@ -21,34 +21,18 @@ #include "Passes.hpp" namespace nexo::renderer { - GridPass::GridPass(unsigned int width, unsigned int height) : RenderPass(Passes::GRID, "Grid pass") + GridPass::GridPass() : RenderPass(Passes::GRID, "Grid pass") { - renderer::NxFramebufferSpecs framebufferSpecs; - framebufferSpecs.attachments = { - renderer::NxFrameBufferTextureFormats::RGBA8, - renderer::NxFrameBufferTextureFormats::RED_INTEGER, - renderer::NxFrameBufferTextureFormats::Depth - }; - framebufferSpecs.width = width; - framebufferSpecs.height = height; - m_output = renderer::NxFramebuffer::create(framebufferSpecs); + } void GridPass::execute(RenderPipeline& pipeline) { - auto output = (m_isFinal) ? pipeline.getFinalRenderTarget() : m_output; - std::shared_ptr prevPass = nullptr; - for (const auto &prereq : prerequisites) { - const auto &prereqPass = pipeline.getRenderPass(prereq); - prevPass = pipeline.getOutput(prereqPass->getId()); - break; - } - if (!prevPass) + std::shared_ptr renderTarget = pipeline.getRenderTarget(); + if (!renderTarget) return; - output->copy(prevPass); - output->bind(); - + renderTarget->bind(); renderer::NxRenderCommand::setDepthMask(false); renderer::NxRenderCommand::setCulling(false); const auto &drawCommands = pipeline.getDrawCommands(); @@ -61,14 +45,6 @@ namespace nexo::renderer { renderer::NxRenderCommand::setCulling(true); renderer::NxRenderCommand::setCulledFace(CulledFace::BACK); - output->unbind(); - pipeline.setOutput(id, output); - } - - void GridPass::resize(unsigned int width, unsigned int height) - { - if (!m_output) - return; - m_output->resize(width, height); + renderTarget->unbind(); } } diff --git a/engine/src/renderPasses/GridPass.hpp b/engine/src/renderPasses/GridPass.hpp index 18fb7ec9e..ced5fd413 100644 --- a/engine/src/renderPasses/GridPass.hpp +++ b/engine/src/renderPasses/GridPass.hpp @@ -20,12 +20,9 @@ namespace nexo::renderer { class GridPass : public RenderPass { public: - GridPass(unsigned int width, unsigned int height); + GridPass(); ~GridPass() override = default; void execute(RenderPipeline& pipeline) override; - void resize(unsigned int width, unsigned int height) override; - private: - std::shared_ptr m_output; }; } From a8b300171fa373de825b4939ee755881a84cccb1 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:04:28 +0200 Subject: [PATCH 20/30] refactor(render-passes): mask pass only has one framebuffer --- engine/src/renderPasses/MaskPass.cpp | 18 +++++++++++------- engine/src/renderPasses/MaskPass.hpp | 3 ++- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/engine/src/renderPasses/MaskPass.cpp b/engine/src/renderPasses/MaskPass.cpp index eebe3e6e9..d1cc1a4a8 100644 --- a/engine/src/renderPasses/MaskPass.cpp +++ b/engine/src/renderPasses/MaskPass.cpp @@ -13,6 +13,7 @@ /////////////////////////////////////////////////////////////////////////////// #include "MaskPass.hpp" +#include #include "DrawCommand.hpp" #include "Framebuffer.hpp" #include "renderer/RenderPipeline.hpp" @@ -28,13 +29,12 @@ namespace nexo::renderer { maskFramebufferSpecs.attachments = { renderer::NxFrameBufferTextureFormats::RGBA8, renderer::NxFrameBufferTextureFormats::DEPTH24STENCIL8 }; maskFramebufferSpecs.width = width; // Default size, will be resized as needed maskFramebufferSpecs.height = height; - m_output = renderer::NxFramebuffer::create(maskFramebufferSpecs); + m_mask = renderer::NxFramebuffer::create(maskFramebufferSpecs); } void MaskPass::execute(RenderPipeline& pipeline) { - auto output = (m_isFinal) ? pipeline.getFinalRenderTarget() : m_output; - output->bind(); + m_mask->bind(); renderer::NxRenderCommand::setClearColor({0.0f, 0.0f, 0.0f, 0.0f}); renderer::NxRenderCommand::clear(); @@ -46,14 +46,18 @@ namespace nexo::renderer { if (cmd.filterMask & F_OUTLINE_MASK) cmd.execute(); } - output->unbind(); - pipeline.setOutput(id, output); + m_mask->unbind(); } void MaskPass::resize(unsigned int width, unsigned int height) { - if (!m_output) + if (!m_mask) return; - m_output->resize(width, height); + m_mask->resize(width, height); + } + + std::shared_ptr MaskPass::getOutput() const + { + return m_mask; } } diff --git a/engine/src/renderPasses/MaskPass.hpp b/engine/src/renderPasses/MaskPass.hpp index 633937b04..99f3d027f 100644 --- a/engine/src/renderPasses/MaskPass.hpp +++ b/engine/src/renderPasses/MaskPass.hpp @@ -25,7 +25,8 @@ namespace nexo::renderer { void execute(RenderPipeline& pipeline) override; void resize(unsigned int width, unsigned int height) override; + std::shared_ptr getOutput() const override; private: - std::shared_ptr m_output; + std::shared_ptr m_mask; }; } From 5bb29faaa4b6b8ee7a5b8d5bb8c61873aed7c518 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:05:04 +0200 Subject: [PATCH 21/30] refactor(render-passes): outline pass now retrieve the framebuffer from mask pass and draws onto the same render target as forward and grid without copying --- engine/src/renderPasses/OutlinePass.cpp | 36 ++++++------------------- engine/src/renderPasses/OutlinePass.hpp | 5 +--- 2 files changed, 9 insertions(+), 32 deletions(-) diff --git a/engine/src/renderPasses/OutlinePass.cpp b/engine/src/renderPasses/OutlinePass.cpp index d94d9e6fd..cf577564a 100644 --- a/engine/src/renderPasses/OutlinePass.cpp +++ b/engine/src/renderPasses/OutlinePass.cpp @@ -25,41 +25,29 @@ #include namespace nexo::renderer { - OutlinePass::OutlinePass(unsigned int width, unsigned int height) : RenderPass(Passes::OUTLINE, "Outline pass") + OutlinePass::OutlinePass() : RenderPass(Passes::OUTLINE, "Outline pass") { - renderer::NxFramebufferSpecs framebufferSpecs; - framebufferSpecs.attachments = { - renderer::NxFrameBufferTextureFormats::RGBA8, - renderer::NxFrameBufferTextureFormats::RED_INTEGER, - renderer::NxFrameBufferTextureFormats::Depth - }; - framebufferSpecs.width = width; - framebufferSpecs.height = height; - m_output = renderer::NxFramebuffer::create(framebufferSpecs); + } void OutlinePass::execute(RenderPipeline& pipeline) { - auto output = (m_isFinal) ? pipeline.getFinalRenderTarget() : m_output; + const std::shared_ptr renderTarget = pipeline.getRenderTarget(); std::shared_ptr maskPass = nullptr; - std::shared_ptr prevPass = nullptr; for (const auto &prereq : prerequisites) { const auto &prereqPass = pipeline.getRenderPass(prereq); if (prereqPass->getId() == Passes::MASK) { - maskPass = pipeline.getOutput(prereqPass->getId()); - } else { - prevPass = pipeline.getOutput(prereqPass->getId()); + maskPass = prereqPass->getOutput(); } } - if (!prevPass || !maskPass) + if (!renderTarget || !maskPass) return; - output->copy(prevPass); - output->bind(); + renderTarget->bind(); renderer::NxRenderCommand::setDepthTest(false); renderer::NxRenderCommand::setDepthMask(false); maskPass->bindAsTexture(); - output->bindDepthAsTexture(1); + renderTarget->bindDepthAsTexture(1); maskPass->bindDepthAsTexture(2); const auto &drawCommands = pipeline.getDrawCommands(); for (const auto &cmd : drawCommands) { @@ -67,16 +55,8 @@ namespace nexo::renderer { cmd.execute(); } } - output->unbind(); + renderTarget->unbind(); renderer::NxRenderCommand::setDepthMask(true); renderer::NxRenderCommand::setDepthTest(true); - pipeline.setOutput(id, output); - } - - void OutlinePass::resize(unsigned int width, unsigned int height) - { - if (!m_output) - return; - m_output->resize(width, height); } } diff --git a/engine/src/renderPasses/OutlinePass.hpp b/engine/src/renderPasses/OutlinePass.hpp index abe41ab31..1a8d71b0f 100644 --- a/engine/src/renderPasses/OutlinePass.hpp +++ b/engine/src/renderPasses/OutlinePass.hpp @@ -20,12 +20,9 @@ namespace nexo::renderer { class OutlinePass : public RenderPass { public: - OutlinePass(unsigned int width, unsigned int height); + OutlinePass(); ~OutlinePass() override = default; void execute(RenderPipeline& pipeline) override; - void resize(unsigned int width, unsigned int height) override; - private: - std::shared_ptr m_output; }; } From 9e47ffc56e0d526c8e5ff65d33de146f5cfb62eb Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:06:22 +0200 Subject: [PATCH 22/30] refactor(render-passes): call the correct method --- engine/src/CameraFactory.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/engine/src/CameraFactory.cpp b/engine/src/CameraFactory.cpp index fbe06a96a..da52e6ef6 100644 --- a/engine/src/CameraFactory.cpp +++ b/engine/src/CameraFactory.cpp @@ -37,13 +37,13 @@ namespace nexo { camera.farPlane = farPlane; camera.type = components::CameraType::PERSPECTIVE; - auto forwardPass = std::make_shared(width, height); + auto forwardPass = std::make_shared(); renderer::PassId forwardPassId = camera.pipeline.addRenderPass(forwardPass); camera.pipeline.setFinalOutputPass(forwardPassId); camera.pipeline.setCameraClearColor(clearColor); if (renderTarget) { camera.m_renderTarget = std::move(renderTarget); - camera.pipeline.setFinalRenderTarget(camera.m_renderTarget); + camera.pipeline.setRenderTarget(camera.m_renderTarget); } camera.clearColor = clearColor; From 092b4527834d97a2e935c15a0fb8907ee9f2776e Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:06:37 +0200 Subject: [PATCH 23/30] tests(render-passes): fix tests to comply with the new api --- tests/renderer/Pipeline.test.cpp | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/tests/renderer/Pipeline.test.cpp b/tests/renderer/Pipeline.test.cpp index 25896565c..24d1fed03 100644 --- a/tests/renderer/Pipeline.test.cpp +++ b/tests/renderer/Pipeline.test.cpp @@ -227,6 +227,7 @@ TEST_F(RenderPipelineTest, RemovePassPreservesConnections) { TEST_F(RenderPipelineTest, ExecutePipeline) { auto pass1 = createMockPass("Pass1"); auto pass2 = createMockPass("Pass2"); + auto renderTarget = createMockFramebuffer(); // Set up expectations for the execute method EXPECT_CALL(*pass1, execute(::testing::_)).Times(1); @@ -235,29 +236,39 @@ TEST_F(RenderPipelineTest, ExecutePipeline) { PassId id1 = pipeline.addRenderPass(pass1); PassId id2 = pipeline.addRenderPass(pass2); + std::cout << "la" << std::endl; // Setup pass1 -> pass2 pipeline.addPrerequisite(id2, id1); pipeline.addEffect(id1, id2); + std::cout << "la2" << std::endl; + // Make sure pass2 is the final output to ensure it gets executed pipeline.setFinalOutputPass(id2); + pipeline.setRenderTarget(renderTarget); + std::cout << "la3" << std::endl; + // Verify the setup is correct EXPECT_EQ(pipeline.getFinalOutputPass(), static_cast(id2)); + std::cout << "la7" << std::endl; + // Execute the pipeline pipeline.execute(); + std::cout << "la5" << std::endl; + } -TEST_F(RenderPipelineTest, SetAndGetOutputFramebuffer) { +TEST_F(RenderPipelineTest, SetandGetRenderTarget) { auto pass = createMockPass("Pass1"); auto framebuffer = createMockFramebuffer(); - PassId id = pipeline.addRenderPass(pass); + pipeline.addRenderPass(pass); // Set and verify output framebuffer for a pass - pipeline.setOutput(id, framebuffer); - auto retrievedFramebuffer = pipeline.getOutput(id); + pipeline.setRenderTarget(framebuffer); + auto retrievedFramebuffer = pipeline.getRenderTarget(); EXPECT_EQ(retrievedFramebuffer, framebuffer); } @@ -267,6 +278,8 @@ TEST_F(RenderPipelineTest, DrawCommandsManagement) { DrawCommand cmd2; + auto mockRenderTarget = createMockFramebuffer(); + // Add single command pipeline.addDrawCommand(cmd1); @@ -278,6 +291,8 @@ TEST_F(RenderPipelineTest, DrawCommandsManagement) { auto& retrievedCommands = pipeline.getDrawCommands(); EXPECT_EQ(retrievedCommands.size(), 3); + pipeline.setRenderTarget(mockRenderTarget); + // Check they're cleared after execution pipeline.execute(); EXPECT_TRUE(pipeline.getDrawCommands().empty()); @@ -322,7 +337,7 @@ TEST_F(RenderPipelineTest, ResizePipeline) { // Don't need the ID, but need to add pass to pipeline pipeline.addRenderPass(pass); - pipeline.setFinalRenderTarget(framebuffer); + pipeline.setRenderTarget(framebuffer); // Test resize pipeline.resize(800, 600); @@ -412,8 +427,8 @@ TEST_F(RenderPipelineTest, FinalOutputPassManagement) { // Set final render target auto framebuffer = createMockFramebuffer(); - pipeline.setFinalRenderTarget(framebuffer); - EXPECT_EQ(pipeline.getFinalRenderTarget(), framebuffer); + pipeline.setRenderTarget(framebuffer); + EXPECT_EQ(pipeline.getRenderTarget(), framebuffer); } TEST_F(RenderPipelineTest, HasPrerequisitesAndEffects) { From 891828e58d3a61539db35dcde8e13516b3e1b493 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:57:28 +0200 Subject: [PATCH 24/30] style(compilation-warnings): fix test name + remove debug prints --- tests/renderer/Pipeline.test.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/tests/renderer/Pipeline.test.cpp b/tests/renderer/Pipeline.test.cpp index 24d1fed03..dc72c8a87 100644 --- a/tests/renderer/Pipeline.test.cpp +++ b/tests/renderer/Pipeline.test.cpp @@ -236,31 +236,26 @@ TEST_F(RenderPipelineTest, ExecutePipeline) { PassId id1 = pipeline.addRenderPass(pass1); PassId id2 = pipeline.addRenderPass(pass2); - std::cout << "la" << std::endl; // Setup pass1 -> pass2 pipeline.addPrerequisite(id2, id1); pipeline.addEffect(id1, id2); - std::cout << "la2" << std::endl; // Make sure pass2 is the final output to ensure it gets executed pipeline.setFinalOutputPass(id2); pipeline.setRenderTarget(renderTarget); - std::cout << "la3" << std::endl; // Verify the setup is correct EXPECT_EQ(pipeline.getFinalOutputPass(), static_cast(id2)); - std::cout << "la7" << std::endl; // Execute the pipeline pipeline.execute(); - std::cout << "la5" << std::endl; } -TEST_F(RenderPipelineTest, SetandGetRenderTarget) { +TEST_F(RenderPipelineTest, SetAndGetRenderTarget) { auto pass = createMockPass("Pass1"); auto framebuffer = createMockFramebuffer(); From ae0de61c05d892acd4ad2b1328aba7b8e18455b9 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 19:05:02 +0200 Subject: [PATCH 25/30] hotfix(render-passes): temp fix for render passes on windows --- engine/src/renderPasses/GridPass.cpp | 6 ++++++ engine/src/renderPasses/OutlinePass.cpp | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/engine/src/renderPasses/GridPass.cpp b/engine/src/renderPasses/GridPass.cpp index b86b89cb3..0a69b5db2 100644 --- a/engine/src/renderPasses/GridPass.cpp +++ b/engine/src/renderPasses/GridPass.cpp @@ -20,6 +20,8 @@ #include "Masks.hpp" #include "Passes.hpp" +#include + namespace nexo::renderer { GridPass::GridPass() : RenderPass(Passes::GRID, "Grid pass") { @@ -33,6 +35,8 @@ namespace nexo::renderer { return; renderTarget->bind(); + constexpr GLenum singleDrawBuffer[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, singleDrawBuffer); renderer::NxRenderCommand::setDepthMask(false); renderer::NxRenderCommand::setCulling(false); const auto &drawCommands = pipeline.getDrawCommands(); @@ -45,6 +49,8 @@ namespace nexo::renderer { renderer::NxRenderCommand::setCulling(true); renderer::NxRenderCommand::setCulledFace(CulledFace::BACK); + constexpr GLenum allBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; + glDrawBuffers(2, allBuffers); renderTarget->unbind(); } } diff --git a/engine/src/renderPasses/OutlinePass.cpp b/engine/src/renderPasses/OutlinePass.cpp index cf577564a..42e2824fd 100644 --- a/engine/src/renderPasses/OutlinePass.cpp +++ b/engine/src/renderPasses/OutlinePass.cpp @@ -43,6 +43,8 @@ namespace nexo::renderer { if (!renderTarget || !maskPass) return; renderTarget->bind(); + constexpr GLenum singleDrawBuffer[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, singleDrawBuffer); renderer::NxRenderCommand::setDepthTest(false); renderer::NxRenderCommand::setDepthMask(false); @@ -55,6 +57,8 @@ namespace nexo::renderer { cmd.execute(); } } + constexpr GLenum allBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; + glDrawBuffers(2, allBuffers); renderTarget->unbind(); renderer::NxRenderCommand::setDepthMask(true); renderer::NxRenderCommand::setDepthTest(true); From 89fa97da595fac4cadd1656578900fd42e8106b4 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:06:37 +0200 Subject: [PATCH 26/30] tests(render-passes): fix tests to comply with the new api --- tests/renderer/Pipeline.test.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/renderer/Pipeline.test.cpp b/tests/renderer/Pipeline.test.cpp index dc72c8a87..204eba07c 100644 --- a/tests/renderer/Pipeline.test.cpp +++ b/tests/renderer/Pipeline.test.cpp @@ -236,9 +236,12 @@ TEST_F(RenderPipelineTest, ExecutePipeline) { PassId id1 = pipeline.addRenderPass(pass1); PassId id2 = pipeline.addRenderPass(pass2); + std::cout << "la" << std::endl; // Setup pass1 -> pass2 pipeline.addPrerequisite(id2, id1); pipeline.addEffect(id1, id2); + std::cout << "la2" << std::endl; + // Make sure pass2 is the final output to ensure it gets executed @@ -248,6 +251,8 @@ TEST_F(RenderPipelineTest, ExecutePipeline) { // Verify the setup is correct EXPECT_EQ(pipeline.getFinalOutputPass(), static_cast(id2)); + std::cout << "la7" << std::endl; + // Execute the pipeline From 911f0d6294e72a357648caebee1b6172a30630cd Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Fri, 25 Jul 2025 16:57:28 +0200 Subject: [PATCH 27/30] style(compilation-warnings): fix test name + remove debug prints --- tests/renderer/Pipeline.test.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/renderer/Pipeline.test.cpp b/tests/renderer/Pipeline.test.cpp index 204eba07c..4341dc311 100644 --- a/tests/renderer/Pipeline.test.cpp +++ b/tests/renderer/Pipeline.test.cpp @@ -236,11 +236,9 @@ TEST_F(RenderPipelineTest, ExecutePipeline) { PassId id1 = pipeline.addRenderPass(pass1); PassId id2 = pipeline.addRenderPass(pass2); - std::cout << "la" << std::endl; // Setup pass1 -> pass2 pipeline.addPrerequisite(id2, id1); pipeline.addEffect(id1, id2); - std::cout << "la2" << std::endl; @@ -251,7 +249,6 @@ TEST_F(RenderPipelineTest, ExecutePipeline) { // Verify the setup is correct EXPECT_EQ(pipeline.getFinalOutputPass(), static_cast(id2)); - std::cout << "la7" << std::endl; From 8517c8b1d0edba7c007f9ef0b3e0b86dfe5e8437 Mon Sep 17 00:00:00 2001 From: iMeaNz Date: Sat, 26 Jul 2025 22:56:04 +0200 Subject: [PATCH 28/30] fix(render-passes): remove constructor argument --- editor/src/DocumentWindows/EditorScene/Init.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/editor/src/DocumentWindows/EditorScene/Init.cpp b/editor/src/DocumentWindows/EditorScene/Init.cpp index 04b39f410..22ffaecda 100644 --- a/editor/src/DocumentWindows/EditorScene/Init.cpp +++ b/editor/src/DocumentWindows/EditorScene/Init.cpp @@ -55,12 +55,8 @@ namespace nexo::editor auto maskPass = std::make_shared( static_cast(m_contentSize.x), static_cast(m_contentSize.y)); - auto outlinePass = std::make_shared( - static_cast(m_contentSize.x), - static_cast(m_contentSize.y)); - auto gridPass = std::make_shared( - static_cast(m_contentSize.x), - static_cast(m_contentSize.y)); + auto outlinePass = std::make_shared(); + auto gridPass = std::make_shared(); const renderer::PassId forwardId = cameraComponent.pipeline.getFinalOutputPass(); const renderer::PassId maskId = cameraComponent.pipeline.addRenderPass(std::move(maskPass)); From e53991913dffaab486733742dcb220ac40af5cee Mon Sep 17 00:00:00 2001 From: Thomas Parenteau Date: Wed, 30 Jul 2025 15:26:17 +0200 Subject: [PATCH 29/30] fix(render-passes): rebase confclits and change window title type --- engine/src/renderer/RenderPipeline.cpp | 2 +- engine/src/renderer/Window.cpp | 2 +- engine/src/renderer/Window.hpp | 4 ++-- engine/src/renderer/opengl/OpenGlWindow.hpp | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/engine/src/renderer/RenderPipeline.cpp b/engine/src/renderer/RenderPipeline.cpp index 668ea607b..56d17264a 100644 --- a/engine/src/renderer/RenderPipeline.cpp +++ b/engine/src/renderer/RenderPipeline.cpp @@ -70,7 +70,7 @@ namespace nexo::renderer { passes.erase(id); // Choose new final output if necessary - if (needNewFinal) { + if (needNewFinalOutput) { if (passes.empty()) { finalOutputPass = -1; } else { diff --git a/engine/src/renderer/Window.cpp b/engine/src/renderer/Window.cpp index aefad4add..2822547c5 100644 --- a/engine/src/renderer/Window.cpp +++ b/engine/src/renderer/Window.cpp @@ -19,7 +19,7 @@ #endif namespace nexo::renderer { - std::shared_ptr NxWindow::create(int width, int height, const char *title) + std::shared_ptr NxWindow::create(int width, int height, const std::string &title) { #ifdef NX_GRAPHICS_API_OPENGL return std::make_shared(width, height, title); diff --git a/engine/src/renderer/Window.hpp b/engine/src/renderer/Window.hpp index 7ff88b5cb..1f1de5f8e 100644 --- a/engine/src/renderer/Window.hpp +++ b/engine/src/renderer/Window.hpp @@ -48,7 +48,7 @@ namespace nexo::renderer { MouseMoveCallback mouseMoveCallback; FileDropCallback fileDropCallback; - NxWindowProperty(const unsigned int w, const unsigned h, std::string t) : width(w), height(h), title(std::move(t)) {} + NxWindowProperty(const unsigned int w, const unsigned h, const std::string &t) : width(w), height(h), title(t) {} }; /** @@ -110,7 +110,7 @@ namespace nexo::renderer { * @param title Title of the window. * @return A shared pointer to the created `NxWindow` instance. */ - static std::shared_ptr create(int width = 1920, int height = 1080, const char *title = "Nexo window"); + static std::shared_ptr create(int width = 1920, int height = 1080, const std::string &title = "Nexo window"); virtual void setErrorCallback(void *fctPtr) = 0; virtual void setResizeCallback(ResizeCallback callback) = 0; diff --git a/engine/src/renderer/opengl/OpenGlWindow.hpp b/engine/src/renderer/opengl/OpenGlWindow.hpp index ff7b06b3d..1c5848d4d 100644 --- a/engine/src/renderer/opengl/OpenGlWindow.hpp +++ b/engine/src/renderer/opengl/OpenGlWindow.hpp @@ -45,7 +45,7 @@ namespace nexo::renderer { */ explicit NxOpenGlWindow(const int width = 1920, const int height = 1080, - const char *title = "Nexo window") : + const std::string &title = "Nexo window") : _props(width, height, title) {} /** From c37199eb663509284a9fa528ce21cb0d163af76c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 8 Sep 2025 16:26:17 +0000 Subject: [PATCH 30/30] chore(deps): bump actions/setup-dotnet from 4 to 5 Bumps [actions/setup-dotnet](https://github.com/actions/setup-dotnet) from 4 to 5. - [Release notes](https://github.com/actions/setup-dotnet/releases) - [Commits](https://github.com/actions/setup-dotnet/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/setup-dotnet dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/build.yml | 6 +++--- .github/workflows/codeql.yml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ec8b448e9..764be221f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -118,7 +118,7 @@ jobs: execute_install_scripts: true - name: Install .NET SDK 9.0 - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: '9.x' @@ -278,7 +278,7 @@ jobs: pattern: 'nexo-engine-installer-msvc14-windows-latest' - name: Install .NET SDK 9.0 - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: '9.x' @@ -350,7 +350,7 @@ jobs: pattern: 'nexo-engine-installer-gcc13-ubuntu-latest' - name: Install .NET SDK 9.0 - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: '9.x' diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 2b3729810..0c5335f33 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -71,7 +71,7 @@ jobs: execute_install_scripts: true - name: Install .NET SDK 9.0 - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: '9.x'