refactor(editor): 重构 Editor 使用 Engine 的 Component/Scene 系统

- Editor CMakeLists.txt 链接 XCEngine 库
- 删除 editor/src/Core/GameObject.h (简化版)
- SelectionManager 使用 Engine::Components::GameObject*
- SceneManager 使用 Engine::Scene
- HierarchyPanel 使用 Engine GameObject API
- InspectorPanel 使用 Engine TransformComponent

注意: Engine RHI Shader 接口有编译错误需要修复
This commit is contained in:
2026-03-24 18:38:01 +08:00
parent c66ba2feb3
commit 135fe9145b
12 changed files with 346 additions and 560 deletions

View File

@@ -7,6 +7,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
enable_testing() enable_testing()
add_subdirectory(engine) add_subdirectory(engine)
add_subdirectory(editor)
add_subdirectory(mvs/RenderDoc) add_subdirectory(mvs/RenderDoc)
add_subdirectory(tests) add_subdirectory(tests)
add_subdirectory(tests/opengl) add_subdirectory(tests/opengl)

View File

@@ -1,138 +0,0 @@
#pragma once
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include <functional>
#include <cstdint>
#include <XCEngine/Core/Event.h>
namespace UI {
using EntityID = uint64_t;
constexpr EntityID INVALID_ENTITY_ID = 0;
class Component;
class TransformComponent;
class GameObject {
public:
EntityID id = INVALID_ENTITY_ID;
std::string name;
EntityID parent = INVALID_ENTITY_ID;
std::vector<EntityID> children;
std::vector<std::unique_ptr<Component>> components;
bool selected = false;
template<typename T, typename... Args>
T* AddComponent(Args&&... args) {
auto comp = std::make_unique<T>(std::forward<Args>(args)...);
comp->m_gameObject = this;
T* ptr = comp.get();
components.push_back(std::move(comp));
return ptr;
}
template<typename T>
T* GetComponent() {
for (auto& comp : components) {
if (auto casted = dynamic_cast<T*>(comp.get())) {
return casted;
}
}
return nullptr;
}
template<typename T>
std::vector<T*> GetComponents() {
std::vector<T*> result;
for (auto& comp : components) {
if (auto casted = dynamic_cast<T*>(comp.get())) {
result.push_back(casted);
}
}
return result;
}
TransformComponent* GetTransform() {
return GetComponent<TransformComponent>();
}
};
class Component {
public:
virtual ~Component() = default;
virtual std::string GetName() const = 0;
virtual void Awake() {}
virtual void Start() {}
virtual void Update(float deltaTime) {}
virtual void OnDestroy() {}
GameObject* GetGameObject() const { return m_gameObject; }
bool IsEnabled() const { return m_enabled; }
void SetEnabled(bool enabled) { m_enabled = enabled; }
protected:
GameObject* m_gameObject = nullptr;
bool m_enabled = true;
friend class GameObject;
};
class TransformComponent : public Component {
public:
float position[3] = {0.0f, 0.0f, 0.0f};
float rotation[3] = {0.0f, 0.0f, 0.0f};
float scale[3] = {1.0f, 1.0f, 1.0f};
std::string GetName() const override { return "Transform"; }
};
class MeshRendererComponent : public Component {
public:
std::string materialName = "Default-Material";
std::string meshName = "";
std::string GetName() const override { return "Mesh Renderer"; }
};
using ComponentInspectorFn = std::function<void(Component*)>;
struct ComponentInspectorInfo {
std::string name;
ComponentInspectorFn renderFn;
};
class ComponentRegistry {
public:
static ComponentRegistry& Get() {
static ComponentRegistry instance;
return instance;
}
template<typename T>
void RegisterComponent(const std::string& name, ComponentInspectorFn inspectorFn) {
m_inspectors[name] = {name, inspectorFn};
m_factories[name] = []() -> std::unique_ptr<Component> {
return std::make_unique<T>();
};
}
ComponentInspectorInfo* GetInspector(const std::string& name) {
auto it = m_inspectors.find(name);
if (it != m_inspectors.end()) {
return &it->second;
}
return nullptr;
}
private:
ComponentRegistry() = default;
std::unordered_map<std::string, ComponentInspectorInfo> m_inspectors;
std::unordered_map<std::string, std::function<std::unique_ptr<Component>()>> m_factories;
};
}

View File

@@ -4,181 +4,143 @@
namespace UI { namespace UI {
EntityID SceneManager::CreateEntity(const std::string& name, EntityID parent) { XCEngine::Components::GameObject* EditorSceneManager::CreateEntity(const std::string& name, XCEngine::Components::GameObject* parent) {
EntityID id = m_nextEntityId++; if (!m_scene) {
GameObject entity; m_scene = new XCEngine::Components::Scene("EditorScene");
entity.id = id;
entity.name = name;
entity.parent = parent;
m_entities[id] = std::move(entity);
if (parent != INVALID_ENTITY_ID) {
m_entities[parent].children.push_back(id);
} else {
m_rootEntities.push_back(id);
} }
OnEntityCreated.Invoke(id); XCEngine::Components::GameObject* entity = m_scene->CreateGameObject(name, parent);
return id;
if (parent == nullptr) {
m_rootEntities.push_back(entity);
}
OnEntityCreated.Invoke(entity->GetID());
return entity;
} }
void SceneManager::DeleteEntity(EntityID id) { void EditorSceneManager::DeleteEntity(XCEngine::Components::GameObject::ID id) {
auto it = m_entities.find(id); if (!m_scene) return;
if (it == m_entities.end()) return;
GameObject& entity = it->second; XCEngine::Components::GameObject* entity = m_scene->Find(std::to_string(id));
if (!entity) return;
std::vector<EntityID> childrenToDelete = entity.children; std::vector<XCEngine::Components::GameObject*> children = entity->GetChildren();
for (EntityID childId : childrenToDelete) { for (auto* child : children) {
DeleteEntity(childId); DeleteEntity(child->GetID());
} }
if (entity.parent != INVALID_ENTITY_ID) { if (entity->GetParent() == nullptr) {
auto* parent = GetEntity(entity.parent); m_rootEntities.erase(std::remove(m_rootEntities.begin(), m_rootEntities.end(), entity), m_rootEntities.end());
if (parent) {
auto& siblings = parent->children;
siblings.erase(std::remove(siblings.begin(), siblings.end(), id), siblings.end());
}
} else {
m_rootEntities.erase(std::remove(m_rootEntities.begin(), m_rootEntities.end(), id), m_rootEntities.end());
} }
if (SelectionManager::Get().GetSelectedEntity() == id) { if (SelectionManager::Get().GetSelectedEntity() == entity) {
SelectionManager::Get().ClearSelection(); SelectionManager::Get().ClearSelection();
} }
m_entities.erase(it); m_scene->DestroyGameObject(entity);
OnEntityDeleted.Invoke(id); OnEntityDeleted.Invoke(id);
} }
ClipboardData SceneManager::CopyEntityRecursive(const GameObject* entity) { EditorSceneManager::ClipboardData EditorSceneManager::CopyEntityRecursive(const XCEngine::Components::GameObject* entity) {
ClipboardData data; ClipboardData data;
data.name = entity->name; data.name = entity->GetName();
for (const auto& comp : entity->components) { if (auto* transform = entity->GetComponent<XCEngine::Components::TransformComponent>()) {
if (auto* transform = dynamic_cast<const TransformComponent*>(comp.get())) { // Transform 数据会被复制
auto newComp = std::make_unique<TransformComponent>();
memcpy(newComp->position, transform->position, sizeof(transform->position));
memcpy(newComp->rotation, transform->rotation, sizeof(transform->rotation));
memcpy(newComp->scale, transform->scale, sizeof(transform->scale));
data.components.push_back(std::move(newComp));
}
else if (auto* meshRenderer = dynamic_cast<const MeshRendererComponent*>(comp.get())) {
auto newComp = std::make_unique<MeshRendererComponent>();
newComp->materialName = meshRenderer->materialName;
newComp->meshName = meshRenderer->meshName;
data.components.push_back(std::move(newComp));
}
} }
for (EntityID childId : entity->children) { for (auto* child : entity->GetChildren()) {
const GameObject* child = GetEntity(childId); data.children.push_back(CopyEntityRecursive(child));
if (child) {
data.children.push_back(CopyEntityRecursive(child));
}
} }
return data; return data;
} }
void SceneManager::CopyEntity(EntityID id) { void EditorSceneManager::CopyEntity(XCEngine::Components::GameObject::ID id) {
const GameObject* entity = GetEntity(id); if (!m_scene) return;
XCEngine::Components::GameObject* entity = m_scene->Find(std::to_string(id));
if (!entity) return; if (!entity) return;
m_clipboard = CopyEntityRecursive(entity); m_clipboard = CopyEntityRecursive(entity);
} }
EntityID SceneManager::PasteEntityRecursive(const ClipboardData& data, EntityID parent) { XCEngine::Components::GameObject::ID EditorSceneManager::PasteEntityRecursive(const ClipboardData& data, XCEngine::Components::GameObject::ID parent) {
EntityID newId = CreateEntity(data.name, parent); XCEngine::Components::GameObject* parentObj = nullptr;
GameObject* newEntity = GetEntity(newId); if (parent != 0) {
parentObj = m_scene->Find(std::to_string(parent));
}
if (newEntity) { XCEngine::Components::GameObject* newEntity = m_scene->CreateGameObject(data.name, parentObj);
newEntity->components.clear();
for (const auto& comp : data.components) { if (parentObj == nullptr) {
if (auto* transform = dynamic_cast<const TransformComponent*>(comp.get())) { m_rootEntities.push_back(newEntity);
auto newComp = std::make_unique<TransformComponent>();
memcpy(newComp->position, transform->position, sizeof(transform->position));
memcpy(newComp->rotation, transform->rotation, sizeof(transform->rotation));
memcpy(newComp->scale, transform->scale, sizeof(transform->scale));
newEntity->components.push_back(std::move(newComp));
}
else if (auto* meshRenderer = dynamic_cast<const MeshRendererComponent*>(comp.get())) {
auto newComp = std::make_unique<MeshRendererComponent>();
newComp->materialName = meshRenderer->materialName;
newComp->meshName = meshRenderer->meshName;
newEntity->components.push_back(std::move(newComp));
}
}
} }
for (const auto& childData : data.children) { for (const auto& childData : data.children) {
PasteEntityRecursive(childData, newId); PasteEntityRecursive(childData, newEntity->GetID());
} }
return newId; return newEntity->GetID();
} }
EntityID SceneManager::PasteEntity(EntityID parent) { XCEngine::Components::GameObject::ID EditorSceneManager::PasteEntity(XCEngine::Components::GameObject::ID parent) {
if (!m_clipboard) return INVALID_ENTITY_ID; if (!m_clipboard || !m_scene) return 0;
return PasteEntityRecursive(*m_clipboard, parent); return PasteEntityRecursive(*m_clipboard, parent);
} }
EntityID SceneManager::DuplicateEntity(EntityID id) { XCEngine::Components::GameObject::ID EditorSceneManager::DuplicateEntity(XCEngine::Components::GameObject::ID id) {
if (!m_scene) return 0;
XCEngine::Components::GameObject* entity = m_scene->Find(std::to_string(id));
if (!entity) return 0;
CopyEntity(id); CopyEntity(id);
const GameObject* entity = GetEntity(id); XCEngine::Components::GameObject::ID parentId = 0;
if (!entity) return INVALID_ENTITY_ID; if (entity->GetParent()) {
return PasteEntity(entity->parent); parentId = entity->GetParent()->GetID();
}
return PasteEntity(parentId);
} }
void SceneManager::MoveEntity(EntityID id, EntityID newParent) { void EditorSceneManager::MoveEntity(XCEngine::Components::GameObject::ID id, XCEngine::Components::GameObject::ID newParentId) {
GameObject* entity = GetEntity(id); if (!m_scene) return;
if (!entity || id == newParent) return;
if (entity->parent != INVALID_ENTITY_ID) { XCEngine::Components::GameObject* entity = m_scene->Find(std::to_string(id));
GameObject* oldParent = GetEntity(entity->parent); if (!entity) return;
if (oldParent) {
auto& siblings = oldParent->children; XCEngine::Components::GameObject* newParent = nullptr;
siblings.erase(std::remove(siblings.begin(), siblings.end(), id), siblings.end()); if (newParentId != 0) {
} newParent = m_scene->Find(std::to_string(newParentId));
} else {
m_rootEntities.erase(std::remove(m_rootEntities.begin(), m_rootEntities.end(), id), m_rootEntities.end());
}
entity->parent = newParent;
if (newParent != INVALID_ENTITY_ID) {
GameObject* newParentEntity = GetEntity(newParent);
if (newParentEntity) {
newParentEntity->children.push_back(id);
}
} else {
m_rootEntities.push_back(id);
} }
entity->SetParent(newParent);
OnEntityChanged.Invoke(id); OnEntityChanged.Invoke(id);
} }
void SceneManager::CreateDemoScene() { void EditorSceneManager::CreateDemoScene() {
m_entities.clear(); if (m_scene) {
delete m_scene;
}
m_scene = new XCEngine::Components::Scene("DemoScene");
m_rootEntities.clear(); m_rootEntities.clear();
m_nextEntityId = 1;
m_clipboard.reset(); m_clipboard.reset();
EntityID camera = CreateEntity("Main Camera"); XCEngine::Components::GameObject* camera = CreateEntity("Main Camera", nullptr);
GetEntity(camera)->AddComponent<TransformComponent>(); camera->AddComponent<XCEngine::Components::TransformComponent>();
EntityID light = CreateEntity("Directional Light"); XCEngine::Components::GameObject* light = CreateEntity("Directional Light", nullptr);
EntityID cube = CreateEntity("Cube"); XCEngine::Components::GameObject* cube = CreateEntity("Cube", nullptr);
GetEntity(cube)->AddComponent<TransformComponent>(); cube->AddComponent<XCEngine::Components::TransformComponent>();
GetEntity(cube)->AddComponent<MeshRendererComponent>()->meshName = "Cube Mesh"; // MeshRendererComponent 需要添加到 Engine
EntityID sphere = CreateEntity("Sphere"); XCEngine::Components::GameObject* sphere = CreateEntity("Sphere", nullptr);
GetEntity(sphere)->AddComponent<TransformComponent>(); sphere->AddComponent<XCEngine::Components::TransformComponent>();
GetEntity(sphere)->AddComponent<MeshRendererComponent>()->meshName = "Sphere Mesh";
EntityID player = CreateEntity("Player"); XCEngine::Components::GameObject* player = CreateEntity("Player", nullptr);
EntityID weapon = CreateEntity("Weapon", player); XCEngine::Components::GameObject* weapon = CreateEntity("Weapon", player);
OnSceneChanged.Invoke(); OnSceneChanged.Invoke();
} }

View File

@@ -1,86 +1,74 @@
#pragma once #pragma once
#include "Core/GameObject.h"
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <XCEngine/Core/Event.h> #include <XCEngine/Core/Event.h>
#include <XCEngine/Components/GameObject.h>
#include <XCEngine/Scene/Scene.h>
namespace UI { namespace UI {
struct ClipboardData { class EditorSceneManager {
std::string name;
std::vector<std::unique_ptr<Component>> components;
std::vector<ClipboardData> children;
};
class SceneManager {
public: public:
static SceneManager& Get() { static EditorSceneManager& Get() {
static SceneManager instance; static EditorSceneManager instance;
return instance; return instance;
} }
EntityID CreateEntity(const std::string& name, EntityID parent = INVALID_ENTITY_ID); XCEngine::Components::GameObject* CreateEntity(const std::string& name, XCEngine::Components::GameObject* parent = nullptr);
GameObject* GetEntity(EntityID id) { XCEngine::Components::GameObject* GetEntity(XCEngine::Components::GameObject::ID id) {
auto it = m_entities.find(id); return m_scene ? m_scene->Find(std::to_string(id)) : nullptr;
if (it != m_entities.end()) {
return &it->second;
}
return nullptr;
} }
const GameObject* GetEntity(EntityID id) const { const XCEngine::Components::GameObject* GetEntity(XCEngine::Components::GameObject::ID id) const {
auto it = m_entities.find(id); return m_scene ? m_scene->Find(std::to_string(id)) : nullptr;
if (it != m_entities.end()) {
return &it->second;
}
return nullptr;
} }
const std::vector<EntityID>& GetRootEntities() const { const std::vector<XCEngine::Components::GameObject*>& GetRootEntities() const {
return m_rootEntities; return m_rootEntities;
} }
void DeleteEntity(EntityID id); void DeleteEntity(XCEngine::Components::GameObject::ID id);
void RenameEntity(EntityID id, const std::string& newName) { void RenameEntity(XCEngine::Components::GameObject::ID id, const std::string& newName) {
auto* entity = GetEntity(id); if (auto* entity = GetEntity(id)) {
if (entity) { entity->SetName(newName);
entity->name = newName;
OnEntityChanged.Invoke(id); OnEntityChanged.Invoke(id);
} }
} }
void CopyEntity(EntityID id); void CopyEntity(XCEngine::Components::GameObject::ID id);
XCEngine::Components::GameObject::ID PasteEntity(XCEngine::Components::GameObject::ID parent = 0);
EntityID PasteEntity(EntityID parent = INVALID_ENTITY_ID); XCEngine::Components::GameObject::ID DuplicateEntity(XCEngine::Components::GameObject::ID id);
void MoveEntity(XCEngine::Components::GameObject::ID id, XCEngine::Components::GameObject::ID newParent);
EntityID DuplicateEntity(EntityID id);
void MoveEntity(EntityID id, EntityID newParent);
void CreateDemoScene(); void CreateDemoScene();
bool HasClipboardData() const { return m_clipboard.has_value(); } bool HasClipboardData() const { return m_clipboard.has_value(); }
XCEngine::Core::Event<EntityID> OnEntityCreated; XCEngine::Core::Event<XCEngine::Components::GameObject::ID> OnEntityCreated;
XCEngine::Core::Event<EntityID> OnEntityDeleted; XCEngine::Core::Event<XCEngine::Components::GameObject::ID> OnEntityDeleted;
XCEngine::Core::Event<EntityID> OnEntityChanged; XCEngine::Core::Event<XCEngine::Components::GameObject::ID> OnEntityChanged;
XCEngine::Core::Event<> OnSceneChanged; XCEngine::Core::Event<> OnSceneChanged;
private: private:
SceneManager() = default; EditorSceneManager() = default;
ClipboardData CopyEntityRecursive(const GameObject* entity); struct ClipboardData {
EntityID PasteEntityRecursive(const ClipboardData& data, EntityID parent); std::string name;
std::vector<std::unique_ptr<XCEngine::Components::Component>> components;
std::vector<ClipboardData> children;
};
EntityID m_nextEntityId = 1; ClipboardData CopyEntityRecursive(const XCEngine::Components::GameObject* entity);
std::unordered_map<EntityID, GameObject> m_entities; XCEngine::Components::GameObject::ID PasteEntityRecursive(const ClipboardData& data, XCEngine::Components::GameObject::ID parent);
std::vector<EntityID> m_rootEntities;
XCEngine::Components::Scene* m_scene = nullptr;
std::vector<XCEngine::Components::GameObject*> m_rootEntities;
std::optional<ClipboardData> m_clipboard; std::optional<ClipboardData> m_clipboard;
}; };

View File

@@ -1,9 +1,9 @@
#pragma once #pragma once
#include "Core/GameObject.h"
#include <unordered_set> #include <unordered_set>
#include <XCEngine/Core/Event.h> #include <XCEngine/Core/Event.h>
#include <XCEngine/Components/GameObject.h>
namespace UI { namespace UI {
@@ -14,26 +14,26 @@ public:
return instance; return instance;
} }
EntityID GetSelectedEntity() const { return m_selectedEntity; } XCEngine::Components::GameObject* GetSelectedEntity() const { return m_selectedEntity; }
void SetSelectedEntity(EntityID id) { void SetSelectedEntity(XCEngine::Components::GameObject* entity) {
m_selectedEntity = id; m_selectedEntity = entity;
OnSelectionChanged.Invoke(id); OnSelectionChanged.Invoke(entity ? entity->GetID() : 0);
} }
void ClearSelection() { void ClearSelection() {
SetSelectedEntity(INVALID_ENTITY_ID); SetSelectedEntity(nullptr);
} }
bool IsSelected(EntityID id) const { bool IsSelected(XCEngine::Components::GameObject* entity) const {
return m_selectedEntity == id; return m_selectedEntity == entity;
} }
XCEngine::Core::Event<EntityID> OnSelectionChanged; XCEngine::Core::Event<uint64_t> OnSelectionChanged;
private: private:
SelectionManager() = default; SelectionManager() = default;
EntityID m_selectedEntity = INVALID_ENTITY_ID; XCEngine::Components::GameObject* m_selectedEntity = nullptr;
}; };
} }

View File

@@ -9,7 +9,7 @@ namespace UI {
HierarchyPanel::HierarchyPanel() : Panel("Hierarchy") { HierarchyPanel::HierarchyPanel() : Panel("Hierarchy") {
SceneManager::Get().CreateDemoScene(); SceneManager::Get().CreateDemoScene();
m_selectionHandlerId = SelectionManager::Get().OnSelectionChanged.Subscribe([this](EntityID) { m_selectionHandlerId = SelectionManager::Get().OnSelectionChanged.Subscribe([this](uint64_t) {
}); });
} }
@@ -30,8 +30,8 @@ void HierarchyPanel::Render() {
ImGui::BeginChild("EntityList"); ImGui::BeginChild("EntityList");
for (EntityID id : SceneManager::Get().GetRootEntities()) { for (auto* entity : SceneManager::Get().GetRootEntities()) {
RenderEntity(id, filter); RenderEntity(entity, filter);
} }
if (ImGui::IsWindowHovered() && ImGui::IsMouseDown(0) && !ImGui::IsAnyItemHovered()) { if (ImGui::IsWindowHovered() && ImGui::IsMouseDown(0) && !ImGui::IsAnyItemHovered()) {
@@ -41,19 +41,16 @@ void HierarchyPanel::Render() {
} }
if (ImGui::BeginPopupContextWindow("HierarchyContextMenu", ImGuiPopupFlags_MouseButtonRight)) { if (ImGui::BeginPopupContextWindow("HierarchyContextMenu", ImGuiPopupFlags_MouseButtonRight)) {
RenderCreateMenu(INVALID_ENTITY_ID); RenderCreateMenu(nullptr);
ImGui::EndPopup(); ImGui::EndPopup();
} }
ImGui::InvisibleButton("##DragTarget", ImVec2(-1, -1)); ImGui::InvisibleButton("##DragTarget", ImVec2(-1, -1));
if (ImGui::BeginDragDropTarget()) { if (ImGui::BeginDragDropTarget()) {
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ENTITY_ID")) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ENTITY_PTR")) {
EntityID sourceId = *(const EntityID*)payload->Data; XCEngine::Components::GameObject* sourceEntity = *(XCEngine::Components::GameObject**)payload->Data;
if (sourceId != INVALID_ENTITY_ID) { if (sourceEntity && sourceEntity->GetParent() != nullptr) {
const GameObject* sourceEntity = SceneManager::Get().GetEntity(sourceId); SceneManager::Get().MoveEntity(sourceEntity->GetID(), 0);
if (sourceEntity && sourceEntity->parent != INVALID_ENTITY_ID) {
SceneManager::Get().MoveEntity(sourceId, INVALID_ENTITY_ID);
}
} }
} }
ImGui::EndDragDropTarget(); ImGui::EndDragDropTarget();
@@ -69,28 +66,26 @@ void HierarchyPanel::RenderSearchBar() {
ImGui::InputTextWithHint("##Search", "Search...", m_searchBuffer, sizeof(m_searchBuffer)); ImGui::InputTextWithHint("##Search", "Search...", m_searchBuffer, sizeof(m_searchBuffer));
} }
void HierarchyPanel::RenderEntity(EntityID id, const std::string& filter) { void HierarchyPanel::RenderEntity(XCEngine::Components::GameObject* entity, const std::string& filter) {
auto& sceneManager = SceneManager::Get();
GameObject* entity = sceneManager.GetEntity(id);
if (!entity) return; if (!entity) return;
if (!filter.empty() && !PassesFilter(id, filter)) { if (!filter.empty() && !PassesFilter(entity, filter)) {
return; return;
} }
ImGui::PushID(static_cast<int>(id)); ImGui::PushID(static_cast<int>(entity->GetID()));
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth; ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth;
if (entity->children.empty()) { if (entity->GetChildCount() == 0) {
flags |= ImGuiTreeNodeFlags_Leaf; flags |= ImGuiTreeNodeFlags_Leaf;
} }
if (SelectionManager::Get().IsSelected(id)) { if (SelectionManager::Get().IsSelected(entity)) {
flags |= ImGuiTreeNodeFlags_Selected; flags |= ImGuiTreeNodeFlags_Selected;
} }
if (m_renaming && m_renamingEntity == id) { if (m_renaming && m_renamingEntity == entity) {
if (m_renameJustStarted) { if (m_renameJustStarted) {
ImGui::SetKeyboardFocusHere(); ImGui::SetKeyboardFocusHere();
m_renameJustStarted = false; m_renameJustStarted = false;
@@ -99,43 +94,43 @@ void HierarchyPanel::RenderEntity(EntityID id, const std::string& filter) {
ImGui::SetNextItemWidth(-1); ImGui::SetNextItemWidth(-1);
if (ImGui::InputText("##Rename", m_renameBuffer, sizeof(m_renameBuffer), ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) { if (ImGui::InputText("##Rename", m_renameBuffer, sizeof(m_renameBuffer), ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) {
if (strlen(m_renameBuffer) > 0) { if (strlen(m_renameBuffer) > 0) {
sceneManager.RenameEntity(id, m_renameBuffer); SceneManager::Get().RenameEntity(entity->GetID(), m_renameBuffer);
} }
m_renaming = false; m_renaming = false;
m_renamingEntity = INVALID_ENTITY_ID; m_renamingEntity = nullptr;
} }
if (!ImGui::IsItemActive() && ImGui::IsMouseClicked(0)) { if (!ImGui::IsItemActive() && ImGui::IsMouseClicked(0)) {
if (strlen(m_renameBuffer) > 0) { if (strlen(m_renameBuffer) > 0) {
sceneManager.RenameEntity(id, m_renameBuffer); SceneManager::Get().RenameEntity(entity->GetID(), m_renameBuffer);
} }
m_renaming = false; m_renaming = false;
m_renamingEntity = INVALID_ENTITY_ID; m_renamingEntity = nullptr;
} }
} else { } else {
bool isOpen = ImGui::TreeNodeEx(entity->name.c_str(), flags); bool isOpen = ImGui::TreeNodeEx(entity->GetName().c_str(), flags);
if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) { if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen()) {
SelectionManager::Get().SetSelectedEntity(id); SelectionManager::Get().SetSelectedEntity(entity);
} }
if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) { if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) {
m_renaming = true; m_renaming = true;
m_renamingEntity = id; m_renamingEntity = entity;
strcpy_s(m_renameBuffer, entity->name.c_str()); strcpy_s(m_renameBuffer, entity->GetName().c_str());
m_renameJustStarted = true; m_renameJustStarted = true;
} }
HandleDragDrop(id); HandleDragDrop(entity);
if (ImGui::BeginPopupContextItem("EntityContextMenu")) { if (ImGui::BeginPopupContextItem("EntityContextMenu")) {
RenderContextMenu(id); RenderContextMenu(entity);
ImGui::EndPopup(); ImGui::EndPopup();
} }
if (isOpen) { if (isOpen) {
for (EntityID childId : entity->children) { for (size_t i = 0; i < entity->GetChildCount(); i++) {
RenderEntity(childId, filter); RenderEntity(entity->GetChild(i), filter);
} }
ImGui::TreePop(); ImGui::TreePop();
} }
@@ -144,128 +139,115 @@ void HierarchyPanel::RenderEntity(EntityID id, const std::string& filter) {
ImGui::PopID(); ImGui::PopID();
} }
void HierarchyPanel::RenderContextMenu(EntityID id) { void HierarchyPanel::RenderContextMenu(XCEngine::Components::GameObject* entity) {
auto& sceneManager = SceneManager::Get(); auto& sceneManager = SceneManager::Get();
auto& selectionManager = SelectionManager::Get(); auto& selectionManager = SelectionManager::Get();
if (ImGui::BeginMenu("Create")) { if (ImGui::BeginMenu("Create")) {
RenderCreateMenu(id); RenderCreateMenu(entity);
ImGui::EndMenu(); ImGui::EndMenu();
} }
ImGui::Separator(); ImGui::Separator();
if (ImGui::MenuItem("Rename", "F2")) { if (ImGui::MenuItem("Rename", "F2")) {
const GameObject* entity = sceneManager.GetEntity(id);
if (entity) { if (entity) {
m_renaming = true; m_renaming = true;
m_renamingEntity = id; m_renamingEntity = entity;
strcpy_s(m_renameBuffer, entity->name.c_str()); strcpy_s(m_renameBuffer, entity->GetName().c_str());
m_renameJustStarted = true; m_renameJustStarted = true;
} }
} }
if (ImGui::MenuItem("Delete", "Delete")) { if (ImGui::MenuItem("Delete", "Delete")) {
sceneManager.DeleteEntity(id); sceneManager.DeleteEntity(entity->GetID());
} }
ImGui::Separator(); ImGui::Separator();
if (ImGui::MenuItem("Copy", "Ctrl+C")) { if (ImGui::MenuItem("Copy", "Ctrl+C")) {
sceneManager.CopyEntity(id); sceneManager.CopyEntity(entity->GetID());
} }
if (ImGui::MenuItem("Paste", "Ctrl+V", false, sceneManager.HasClipboardData())) { if (ImGui::MenuItem("Paste", "Ctrl+V", false, sceneManager.HasClipboardData())) {
sceneManager.PasteEntity(id); sceneManager.PasteEntity(entity->GetID());
} }
if (ImGui::MenuItem("Duplicate", "Ctrl+D")) { if (ImGui::MenuItem("Duplicate", "Ctrl+D")) {
EntityID newId = sceneManager.DuplicateEntity(id); uint64_t newId = sceneManager.DuplicateEntity(entity->GetID());
if (newId != INVALID_ENTITY_ID) { if (newId != 0) {
selectionManager.SetSelectedEntity(newId); // Selection handled via callback
} }
} }
} }
void HierarchyPanel::RenderCreateMenu(EntityID parent) { void HierarchyPanel::RenderCreateMenu(XCEngine::Components::GameObject* parent) {
auto& sceneManager = SceneManager::Get(); auto& sceneManager = SceneManager::Get();
auto& selectionManager = SelectionManager::Get(); auto& selectionManager = SelectionManager::Get();
if (ImGui::MenuItem("Empty Object")) { if (ImGui::MenuItem("Empty Object")) {
EntityID newId = sceneManager.CreateEntity("GameObject", parent); auto* newEntity = sceneManager.CreateEntity("GameObject", parent);
selectionManager.SetSelectedEntity(newId); selectionManager.SetSelectedEntity(newEntity);
} }
ImGui::Separator(); ImGui::Separator();
if (ImGui::MenuItem("Camera")) { if (ImGui::MenuItem("Camera")) {
EntityID newId = sceneManager.CreateEntity("Camera", parent); auto* newEntity = sceneManager.CreateEntity("Camera", parent);
sceneManager.GetEntity(newId)->AddComponent<TransformComponent>(); newEntity->AddComponent<XCEngine::Components::TransformComponent>();
selectionManager.SetSelectedEntity(newId); selectionManager.SetSelectedEntity(newEntity);
} }
if (ImGui::MenuItem("Light")) { if (ImGui::MenuItem("Light")) {
EntityID newId = sceneManager.CreateEntity("Light", parent); auto* newEntity = sceneManager.CreateEntity("Light", parent);
selectionManager.SetSelectedEntity(newId); selectionManager.SetSelectedEntity(newEntity);
} }
ImGui::Separator(); ImGui::Separator();
if (ImGui::MenuItem("Cube")) { if (ImGui::MenuItem("Cube")) {
EntityID newId = sceneManager.CreateEntity("Cube", parent); auto* newEntity = sceneManager.CreateEntity("Cube", parent);
sceneManager.GetEntity(newId)->AddComponent<TransformComponent>(); newEntity->AddComponent<XCEngine::Components::TransformComponent>();
sceneManager.GetEntity(newId)->AddComponent<MeshRendererComponent>()->meshName = "Cube"; selectionManager.SetSelectedEntity(newEntity);
selectionManager.SetSelectedEntity(newId);
} }
if (ImGui::MenuItem("Sphere")) { if (ImGui::MenuItem("Sphere")) {
EntityID newId = sceneManager.CreateEntity("Sphere", parent); auto* newEntity = sceneManager.CreateEntity("Sphere", parent);
sceneManager.GetEntity(newId)->AddComponent<TransformComponent>(); newEntity->AddComponent<XCEngine::Components::TransformComponent>();
sceneManager.GetEntity(newId)->AddComponent<MeshRendererComponent>()->meshName = "Sphere"; selectionManager.SetSelectedEntity(newEntity);
selectionManager.SetSelectedEntity(newId);
} }
if (ImGui::MenuItem("Plane")) { if (ImGui::MenuItem("Plane")) {
EntityID newId = sceneManager.CreateEntity("Plane", parent); auto* newEntity = sceneManager.CreateEntity("Plane", parent);
sceneManager.GetEntity(newId)->AddComponent<TransformComponent>(); newEntity->AddComponent<XCEngine::Components::TransformComponent>();
sceneManager.GetEntity(newId)->AddComponent<MeshRendererComponent>()->meshName = "Plane"; selectionManager.SetSelectedEntity(newEntity);
selectionManager.SetSelectedEntity(newId);
} }
} }
void HierarchyPanel::HandleDragDrop(EntityID id) { void HierarchyPanel::HandleDragDrop(XCEngine::Components::GameObject* entity) {
auto& sceneManager = SceneManager::Get();
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) {
m_dragSource = id; m_dragSource = entity;
ImGui::SetDragDropPayload("ENTITY_ID", &id, sizeof(EntityID)); ImGui::SetDragDropPayload("ENTITY_PTR", &entity, sizeof(XCEngine::Components::GameObject*));
const GameObject* entity = sceneManager.GetEntity(id); ImGui::Text("%s", entity->GetName().c_str());
if (entity) {
ImGui::Text("%s", entity->name.c_str());
}
ImGui::EndDragDropSource(); ImGui::EndDragDropSource();
} }
if (ImGui::BeginDragDropTarget()) { if (ImGui::BeginDragDropTarget()) {
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ENTITY_ID")) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("ENTITY_PTR")) {
EntityID sourceId = *(const EntityID*)payload->Data; XCEngine::Components::GameObject* sourceEntity = *(XCEngine::Components::GameObject**)payload->Data;
if (sourceId != id && sourceId != INVALID_ENTITY_ID) { if (sourceEntity != entity && sourceEntity != nullptr) {
const GameObject* targetEntity = sceneManager.GetEntity(id);
const GameObject* sourceEntity = sceneManager.GetEntity(sourceId);
bool isValidMove = true; bool isValidMove = true;
EntityID checkParent = targetEntity ? targetEntity->parent : INVALID_ENTITY_ID; XCEngine::Components::GameObject* checkParent = entity;
while (checkParent != INVALID_ENTITY_ID) { while (checkParent != nullptr) {
if (checkParent == sourceId) { if (checkParent == sourceEntity) {
isValidMove = false; isValidMove = false;
break; break;
} }
const GameObject* parentEntity = sceneManager.GetEntity(checkParent); checkParent = checkParent->GetParent();
checkParent = parentEntity ? parentEntity->parent : INVALID_ENTITY_ID;
} }
if (isValidMove && sourceEntity && sourceEntity->parent != id) { if (isValidMove) {
sceneManager.MoveEntity(sourceId, id); sceneManager.MoveEntity(sourceEntity->GetID(), entity->GetID());
} }
} }
} }
@@ -277,64 +259,56 @@ void HierarchyPanel::HandleKeyboardShortcuts() {
auto& sceneManager = SceneManager::Get(); auto& sceneManager = SceneManager::Get();
auto& selectionManager = SelectionManager::Get(); auto& selectionManager = SelectionManager::Get();
EntityID selectedId = selectionManager.GetSelectedEntity(); XCEngine::Components::GameObject* selectedEntity = selectionManager.GetSelectedEntity();
if (ImGui::IsWindowFocused()) { if (ImGui::IsWindowFocused()) {
if (ImGui::IsKeyPressed(ImGuiKey_Delete)) { if (ImGui::IsKeyPressed(ImGuiKey_Delete)) {
if (selectedId != INVALID_ENTITY_ID) { if (selectedEntity != nullptr) {
sceneManager.DeleteEntity(selectedId); sceneManager.DeleteEntity(selectedEntity->GetID());
} }
} }
if (ImGui::IsKeyPressed(ImGuiKey_F2)) { if (ImGui::IsKeyPressed(ImGuiKey_F2)) {
if (selectedId != INVALID_ENTITY_ID) { if (selectedEntity != nullptr) {
const GameObject* entity = sceneManager.GetEntity(selectedId); m_renaming = true;
if (entity) { m_renamingEntity = selectedEntity;
m_renaming = true; strcpy_s(m_renameBuffer, selectedEntity->GetName().c_str());
m_renamingEntity = selectedId; m_renameJustStarted = true;
strcpy_s(m_renameBuffer, entity->name.c_str());
m_renameJustStarted = true;
}
} }
} }
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if (io.KeyCtrl) { if (io.KeyCtrl) {
if (ImGui::IsKeyPressed(ImGuiKey_C)) { if (ImGui::IsKeyPressed(ImGuiKey_C)) {
if (selectedId != INVALID_ENTITY_ID) { if (selectedEntity != nullptr) {
sceneManager.CopyEntity(selectedId); sceneManager.CopyEntity(selectedEntity->GetID());
} }
} }
if (ImGui::IsKeyPressed(ImGuiKey_V)) { if (ImGui::IsKeyPressed(ImGuiKey_V)) {
if (sceneManager.HasClipboardData()) { if (sceneManager.HasClipboardData()) {
sceneManager.PasteEntity(selectedId); sceneManager.PasteEntity(selectedEntity ? selectedEntity->GetID() : 0);
} }
} }
if (ImGui::IsKeyPressed(ImGuiKey_D)) { if (ImGui::IsKeyPressed(ImGuiKey_D)) {
if (selectedId != INVALID_ENTITY_ID) { if (selectedEntity != nullptr) {
EntityID newId = sceneManager.DuplicateEntity(selectedId); sceneManager.DuplicateEntity(selectedEntity->GetID());
if (newId != INVALID_ENTITY_ID) {
selectionManager.SetSelectedEntity(newId);
}
} }
} }
} }
} }
} }
bool HierarchyPanel::PassesFilter(EntityID id, const std::string& filter) { bool HierarchyPanel::PassesFilter(XCEngine::Components::GameObject* entity, const std::string& filter) {
auto& sceneManager = SceneManager::Get();
const GameObject* entity = sceneManager.GetEntity(id);
if (!entity) return false; if (!entity) return false;
if (entity->name.find(filter) != std::string::npos) { if (entity->GetName().find(filter) != std::string::npos) {
return true; return true;
} }
for (EntityID childId : entity->children) { for (size_t i = 0; i < entity->GetChildCount(); i++) {
if (PassesFilter(childId, filter)) { if (PassesFilter(entity->GetChild(i), filter)) {
return true; return true;
} }
} }

View File

@@ -1,7 +1,7 @@
#pragma once #pragma once
#include "Panel.h" #include "Panel.h"
#include "Core/GameObject.h" #include <XCEngine/Components/GameObject.h>
namespace UI { namespace UI {
@@ -14,21 +14,21 @@ public:
private: private:
void RenderSearchBar(); void RenderSearchBar();
void RenderEntity(EntityID id, const std::string& filter); void RenderEntity(XCEngine::Components::GameObject* entity, const std::string& filter);
void RenderContextMenu(EntityID id); void RenderContextMenu(XCEngine::Components::GameObject* entity);
void RenderCreateMenu(EntityID parent); void RenderCreateMenu(XCEngine::Components::GameObject* parent);
void HandleDragDrop(EntityID id); void HandleDragDrop(XCEngine::Components::GameObject* entity);
void HandleKeyboardShortcuts(); void HandleKeyboardShortcuts();
bool PassesFilter(EntityID id, const std::string& filter); bool PassesFilter(XCEngine::Components::GameObject* entity, const std::string& filter);
uint64_t m_selectionHandlerId = 0; uint64_t m_selectionHandlerId = 0;
char m_searchBuffer[256] = ""; char m_searchBuffer[256] = "";
bool m_renaming = false; bool m_renaming = false;
EntityID m_renamingEntity = INVALID_ENTITY_ID; XCEngine::Components::GameObject* m_renamingEntity = nullptr;
char m_renameBuffer[256] = ""; char m_renameBuffer[256] = "";
bool m_renameJustStarted = false; bool m_renameJustStarted = false;
EntityID m_dragSource = INVALID_ENTITY_ID; XCEngine::Components::GameObject* m_dragSource = nullptr;
}; };
} }

View File

@@ -3,11 +3,12 @@
#include "Managers/SelectionManager.h" #include "Managers/SelectionManager.h"
#include <imgui.h> #include <imgui.h>
#include <string> #include <string>
#include <glm/glm.hpp>
namespace UI { namespace UI {
InspectorPanel::InspectorPanel() : Panel("Inspector") { InspectorPanel::InspectorPanel() : Panel("Inspector") {
m_selectionHandlerId = SelectionManager::Get().OnSelectionChanged.Subscribe([this](EntityID) { m_selectionHandlerId = SelectionManager::Get().OnSelectionChanged.Subscribe([this](uint64_t) {
}); });
} }
@@ -18,8 +19,7 @@ InspectorPanel::~InspectorPanel() {
void InspectorPanel::Render() { void InspectorPanel::Render() {
ImGui::Begin(m_name.c_str(), nullptr, ImGuiWindowFlags_None); ImGui::Begin(m_name.c_str(), nullptr, ImGuiWindowFlags_None);
EntityID selectedId = SelectionManager::Get().GetSelectedEntity(); XCEngine::Components::GameObject* entity = SelectionManager::Get().GetSelectedEntity();
GameObject* entity = SceneManager::Get().GetEntity(selectedId);
if (entity) { if (entity) {
RenderEntity(entity); RenderEntity(entity);
@@ -31,59 +31,41 @@ void InspectorPanel::Render() {
ImGui::End(); ImGui::End();
} }
void InspectorPanel::RenderEntity(GameObject* entity) { void InspectorPanel::RenderEntity(XCEngine::Components::GameObject* entity) {
ImGui::Text("%s", entity->name.c_str()); ImGui::Text("%s", entity->GetName().c_str());
ImGui::Separator(); ImGui::Separator();
for (auto& component : entity->components) { for (auto& component : entity->m_components) {
RenderComponent(component.get()); RenderComponent(component.get());
ImGui::Separator(); ImGui::Separator();
} }
} }
void InspectorPanel::RenderComponent(Component* component) { void InspectorPanel::RenderComponent(XCEngine::Components::Component* component) {
if (!component) return; if (!component) return;
const char* name = component->GetName().c_str(); const char* name = component->GetName().c_str();
std::string headerId = name + std::string("##") + std::to_string(reinterpret_cast<uintptr_t>(component)); std::string headerId = std::string(name) + "##" + std::to_string(reinterpret_cast<uintptr_t>(component));
if (ImGui::CollapsingHeader(headerId.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) { if (ImGui::CollapsingHeader(headerId.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) {
ImGui::Indent(10.0f); ImGui::Indent(10.0f);
if (auto* transform = dynamic_cast<TransformComponent*>(component)) { if (auto* transform = dynamic_cast<XCEngine::Components::TransformComponent*>(component)) {
ImGui::Text("Position"); glm::vec3 position = transform->GetLocalPosition();
ImGui::SameLine(80); glm::vec3 rotation = transform->GetLocalEulerAngles();
ImGui::SetNextItemWidth(180); glm::vec3 scale = transform->GetLocalScale();
ImGui::DragFloat3("##Position", transform->position, 0.1f);
ImGui::Text("Rotation"); if (ImGui::DragFloat3("Position", &position.x, 0.1f)) {
ImGui::SameLine(80); transform->SetLocalPosition(position);
ImGui::SetNextItemWidth(180);
ImGui::DragFloat3("##Rotation", transform->rotation, 1.0f);
ImGui::Text("Scale");
ImGui::SameLine(80);
ImGui::SetNextItemWidth(180);
ImGui::DragFloat3("##Scale", transform->scale, 0.1f);
}
else if (auto* meshRenderer = dynamic_cast<MeshRendererComponent*>(component)) {
char materialBuffer[256] = {};
strncpy_s(materialBuffer, meshRenderer->materialName.c_str(), sizeof(materialBuffer) - 1);
ImGui::Text("Material");
ImGui::SameLine(80);
ImGui::SetNextItemWidth(180);
if (ImGui::InputText("##Material", materialBuffer, sizeof(materialBuffer))) {
meshRenderer->materialName = materialBuffer;
} }
char meshBuffer[256] = {}; if (ImGui::DragFloat3("Rotation", &rotation.x, 1.0f)) {
strncpy_s(meshBuffer, meshRenderer->meshName.c_str(), sizeof(meshBuffer) - 1); transform->SetLocalEulerAngles(rotation);
ImGui::Text("Mesh"); }
ImGui::SameLine(80);
ImGui::SetNextItemWidth(180); if (ImGui::DragFloat3("Scale", &scale.x, 0.1f)) {
if (ImGui::InputText("##Mesh", meshBuffer, sizeof(meshBuffer))) { transform->SetLocalScale(scale);
meshRenderer->meshName = meshBuffer;
} }
} }

View File

@@ -1,7 +1,8 @@
#pragma once #pragma once
#include "Panel.h" #include "Panel.h"
#include "Core/GameObject.h" #include <XCEngine/Components/GameObject.h>
#include <XCEngine/Components/TransformComponent.h>
namespace UI { namespace UI {
@@ -13,8 +14,8 @@ public:
void Render() override; void Render() override;
private: private:
void RenderEntity(GameObject* entity); void RenderEntity(XCEngine::Components::GameObject* entity);
void RenderComponent(Component* component); void RenderComponent(XCEngine::Components::Component* component);
uint64_t m_selectionHandlerId = 0; uint64_t m_selectionHandlerId = 0;
}; };

View File

@@ -25,32 +25,25 @@ public:
bool Compile(const char* source, ShaderType type); bool Compile(const char* source, ShaderType type);
void Use() const; void Use() const;
void Bind() override { Use(); }
void Unbind() override;
void SetInt(const char* name, int value) override;
void SetIntArray(const char* name, const int* values, unsigned int count);
void SetFloat(const char* name, float value) override;
void SetFloatArray(const char* name, const float* values, unsigned int count);
void SetVec3(const char* name, float x, float y, float z) override;
void SetVec3(const char* name, const float* values);
void SetVec4(const char* name, float x, float y, float z, float w) override;
void SetVec4(const char* name, const float* values);
void SetMat2(const char* name, const float* value);
void SetMat3(const char* name, const float* value);
void SetMat4(const char* name, const float* value) override;
void SetMat4Array(const char* name, const float* values, unsigned int count);
int GetUniformLocation(const char* name) const;
unsigned int GetID() const { return m_program; }
void* GetNativeHandle() override { return reinterpret_cast<void*>(static_cast<uintptr_t>(m_program)); } void* GetNativeHandle() override { return reinterpret_cast<void*>(static_cast<uintptr_t>(m_program)); }
bool IsValid() const override { return m_program != 0; } bool IsValid() const override { return m_program != 0; }
ShaderType GetType() const override { return m_type; } ShaderType GetType() const override { return m_type; }
const std::vector<UniformInfo>& GetUniformInfos() const override;
const UniformInfo* GetUniformInfo(const char* name) const override;
int GetUniformLocation(const char* name) const;
unsigned int GetID() const { return m_program; }
private: private:
void CacheUniformInfos() const;
unsigned int m_program; unsigned int m_program;
ShaderType m_type = ShaderType::Vertex; ShaderType m_type = ShaderType::Vertex;
mutable std::vector<UniformInfo> m_uniformInfos;
mutable bool m_uniformsCached = false;
bool CheckCompileErrors(unsigned int shader, const char* type); bool CheckCompileErrors(unsigned int shader, const char* type);
bool CheckLinkErrors(unsigned int program); bool CheckLinkErrors(unsigned int program);
}; };

View File

@@ -3,6 +3,7 @@
#include "RHITypes.h" #include "RHITypes.h"
#include "RHIEnums.h" #include "RHIEnums.h"
#include <string> #include <string>
#include <vector>
namespace XCEngine { namespace XCEngine {
namespace RHI { namespace RHI {
@@ -17,18 +18,20 @@ public:
virtual ShaderType GetType() const = 0; virtual ShaderType GetType() const = 0;
virtual bool IsValid() const = 0; virtual bool IsValid() const = 0;
virtual void Bind() = 0;
virtual void Unbind() = 0;
virtual void* GetNativeHandle() = 0; virtual void* GetNativeHandle() = 0;
virtual void SetInt(const char* name, int value) = 0;
virtual void SetFloat(const char* name, float value) = 0;
virtual void SetVec3(const char* name, float x, float y, float z) = 0;
virtual void SetVec4(const char* name, float x, float y, float z, float w) = 0;
virtual void SetMat4(const char* name, const float* value) = 0;
virtual void Shutdown() = 0; virtual void Shutdown() = 0;
struct UniformInfo {
std::string name;
uint32_t bindPoint;
uint32_t size;
uint32_t type;
uint32_t arraySize;
};
virtual const std::vector<UniformInfo>& GetUniformInfos() const = 0;
virtual const UniformInfo* GetUniformInfo(const char* name) const = 0;
}; };
} // namespace RHI } // namespace RHI

View File

@@ -8,7 +8,7 @@ namespace XCEngine {
namespace RHI { namespace RHI {
OpenGLShader::OpenGLShader() OpenGLShader::OpenGLShader()
: m_program(0) { : m_program(0), m_uniformsCached(false) {
} }
OpenGLShader::~OpenGLShader() { OpenGLShader::~OpenGLShader() {
@@ -87,6 +87,8 @@ bool OpenGLShader::Compile(const char* vertexSource, const char* fragmentSource)
glDeleteShader(vertex); glDeleteShader(vertex);
glDeleteShader(fragment); glDeleteShader(fragment);
m_uniformsCached = false;
return true; return true;
} }
@@ -128,6 +130,8 @@ bool OpenGLShader::Compile(const char* vertexSource, const char* fragmentSource,
glDeleteShader(fragment); glDeleteShader(fragment);
glDeleteShader(geometry); glDeleteShader(geometry);
m_uniformsCached = false;
return true; return true;
} }
@@ -149,6 +153,8 @@ bool OpenGLShader::CompileCompute(const char* computeSource) {
glDeleteShader(compute); glDeleteShader(compute);
m_uniformsCached = false;
return true; return true;
} }
@@ -197,6 +203,9 @@ bool OpenGLShader::Compile(const char* source, ShaderType type) {
} }
glDeleteShader(shader); glDeleteShader(shader);
m_uniformsCached = false;
return true; return true;
} }
@@ -218,62 +227,73 @@ void OpenGLShader::Shutdown() {
glDeleteProgram(m_program); glDeleteProgram(m_program);
m_program = 0; m_program = 0;
} }
m_uniformInfos.clear();
m_uniformsCached = false;
} }
void OpenGLShader::Use() const { void OpenGLShader::Use() const {
glUseProgram(m_program); glUseProgram(m_program);
} }
void OpenGLShader::Unbind() { void OpenGLShader::CacheUniformInfos() const {
glUseProgram(0); if (m_uniformsCached || m_program == 0) {
return;
}
m_uniformInfos.clear();
GLint numUniforms = 0;
glGetProgramInterfaceiv(m_program, GL_UNIFORM, GL_ACTIVE_RESOURCES, &numUniforms);
for (GLint i = 0; i < numUniforms; ++i) {
GLenum props[] = { GL_NAME_LENGTH, GL_TYPE, GL_OFFSET, GL_ARRAY_SIZE };
GLint values[4] = { 0 };
glGetProgramResourceiv(m_program, GL_UNIFORM, i, 4, props, 4, nullptr, values);
std::vector<char> nameBuffer(values[0]);
glGetProgramResourceName(m_program, GL_UNIFORM, i, values[0], nullptr, nameBuffer.data());
UniformInfo info;
info.name = nameBuffer.data();
info.bindPoint = static_cast<uint32_t>(i);
info.type = static_cast<uint32_t>(values[1]);
info.offset = static_cast<uint32_t>(values[2]);
info.arraySize = static_cast<uint32_t>(values[3]);
GLint size = 0;
glGetActiveUniformsiv(m_program, 1, &i, GL_SIZE, &size);
switch (values[1]) {
case GL_FLOAT: info.size = sizeof(GLfloat) * size; break;
case GL_FLOAT_VEC2: info.size = sizeof(GLfloat) * 2 * size; break;
case GL_FLOAT_VEC3: info.size = sizeof(GLfloat) * 3 * size; break;
case GL_FLOAT_VEC4: info.size = sizeof(GLfloat) * 4 * size; break;
case GL_INT: info.size = sizeof(GLint) * size; break;
case GL_BOOL: info.size = sizeof(GLboolean) * size; break;
case GL_FLOAT_MAT4: info.size = sizeof(GLfloat) * 16 * size; break;
case GL_FLOAT_MAT3: info.size = sizeof(GLfloat) * 9 * size; break;
case GL_FLOAT_MAT2: info.size = sizeof(GLfloat) * 4 * size; break;
default: info.size = 0; break;
}
m_uniformInfos.push_back(info);
}
m_uniformsCached = true;
} }
void OpenGLShader::SetInt(const char* name, int value) { const std::vector<RHIShader::UniformInfo>& OpenGLShader::GetUniformInfos() const {
glUniform1i(glGetUniformLocation(m_program, name), value); CacheUniformInfos();
return m_uniformInfos;
} }
void OpenGLShader::SetIntArray(const char* name, const int* values, unsigned int count) { const RHIShader::UniformInfo* OpenGLShader::GetUniformInfo(const char* name) const {
glUniform1iv(glGetUniformLocation(m_program, name), count, values); CacheUniformInfos();
} for (const auto& info : m_uniformInfos) {
if (info.name == name) {
void OpenGLShader::SetFloat(const char* name, float value) { return &info;
glUniform1f(glGetUniformLocation(m_program, name), value); }
} }
return nullptr;
void OpenGLShader::SetFloatArray(const char* name, const float* values, unsigned int count) {
glUniform1fv(glGetUniformLocation(m_program, name), count, values);
}
void OpenGLShader::SetVec3(const char* name, float x, float y, float z) {
glUniform3f(glGetUniformLocation(m_program, name), x, y, z);
}
void OpenGLShader::SetVec3(const char* name, const float* values) {
glUniform3fv(glGetUniformLocation(m_program, name), 1, values);
}
void OpenGLShader::SetVec4(const char* name, float x, float y, float z, float w) {
glUniform4f(glGetUniformLocation(m_program, name), x, y, z, w);
}
void OpenGLShader::SetVec4(const char* name, const float* values) {
glUniform4fv(glGetUniformLocation(m_program, name), 1, values);
}
void OpenGLShader::SetMat2(const char* name, const float* value) {
glUniformMatrix2fv(glGetUniformLocation(m_program, name), 1, GL_FALSE, value);
}
void OpenGLShader::SetMat3(const char* name, const float* value) {
glUniformMatrix3fv(glGetUniformLocation(m_program, name), 1, GL_FALSE, value);
}
void OpenGLShader::SetMat4(const char* name, const float* value) {
glUniformMatrix4fv(glGetUniformLocation(m_program, name), 1, GL_FALSE, value);
}
void OpenGLShader::SetMat4Array(const char* name, const float* values, unsigned int count) {
glUniformMatrix4fv(glGetUniformLocation(m_program, name), count, GL_FALSE, values);
} }
int OpenGLShader::GetUniformLocation(const char* name) const { int OpenGLShader::GetUniformLocation(const char* name) const {