Vivid
Loading...
Searching...
No Matches
ECS.cpp
1#include "ECS.h"
2#include "ComponentFactory.h"
3
4Map<int, Ref<Vivid::Component>> g_Components;
5Map<int, Ref<Vivid::Entity>> g_Entities;
6
7int Vivid::ECS::s_EntityID = 0;
8int Vivid::ECS::s_ComponentID = 0;
9
10bool Vivid::ECS::AddComponent(int componentID, int entityID)
11{
12 // Check if the component already exists
13 // If So then just update the component
14 Ref<Component> component = g_Components[componentID];
15 const ComponentType ct = component->GetComponentType();
16
17 const int index = g_Entities[entityID]->HasComponent(ct);
18 Ref<Entity> entity = g_Entities[entityID];
19 if (index != -1)
20 {
21 const String& componentName = g_AllComponentStrings.at(ct);
22 std::cerr << componentName << " already exists\n"
23 << std::endl;
24 std::cout << "Updating component: " << componentName << std::endl;
25
26 entity->RemoveComponent(componentID);
27 }
28
29 component->SetEntity(entity->GetEntityID());
30
31 g_Components[componentID] = component;
32 entity->AddComponent(componentID);
33 return true;
34}
35
36bool Vivid::ECS::RemoveComponent(int componentID, int entityID)
37{
38 Ref<Component> component = g_Components[componentID];
39 const ComponentType ct = component->GetComponentType();
40
41 const int index = g_Entities[entityID]->HasComponent(ct);
42 Ref<Entity> entity = g_Entities[index];
43 component->SetEntity(entity->GetEntityID());
44
45 for (auto&& comp : g_Components)
46 {
47 if (comp.second->GetComponentType() == component->GetComponentType())
48 {
49 entity->RemoveComponent(componentID);
50 auto it = g_Components.find(comp.first);
51 g_Components.erase(it);
52 return true;
53 }
54 }
55
56 const String& componentName = g_AllComponentStrings.at(ct);
57 std::cerr << "Failed to remove component: " << componentName << std::endl;
58 return false;
59}
60
61void Vivid::ECS::Draw(Camera* camera)
62{
63 for (auto& entity : g_Entities)
64 {
65 entity.second->Draw(camera);
66 }
67}
68
69void Vivid::ECS::ImGuiRender()
70{
71 for (auto& entity : g_Entities)
72 {
73 entity.second->ImguiRender();
74 }
75}
76
77Ref<Vivid::Entity> Vivid::ECS::CreateEntity(const String& name)
78{
79 Ref<Entity> entity = MakeRef<Entity>(s_EntityID, name);
80 g_Entities[entity->GetEntityID()] = entity;
81
82 // std::cout << g_Entities[entity->GetID()] << "\n";
83 // std::cout << entity << "\n";
84
85 auto tc = ECS::CreateComponent<TransformComponent>();
86 AddComponent(tc->GetComponentID(), entity->GetEntityID());
87 return entity;
88}
89
90Ref<Vivid::Component> Vivid::ECS::GetComponent(ComponentType ct, int entityID)
91{
92 int componentID = g_Entities[entityID]->HasComponent(ct);
93
94 if (componentID == -1)
95 {
96 return nullptr;
97 }
98 return g_Components[componentID];
99}
A class that represents the camera.
Definition: Camera.h:25