Uranus  1.0.1.0
Uranus is a GameEngine written in C++
Loading...
Searching...
No Matches
View.hpp
1/*
2** EPITECH PROJECT, 2023
3** View.hpp
4** File description:
5** View.hpp
6*/
7#ifndef URANUS_VIEW_HPP
8#define URANUS_VIEW_HPP
9
10#include "Registry.hpp"
11
12namespace uranus::ecs {
13 template<typename... Components>
14 class View {
15 public:
16 using Tuple = std::tuple<size_t, Components &...>;
17
18 explicit View(ecs::Registry &registry) : _registry(registry) {}
19
20 class Iterator {
21 public:
22 explicit Iterator(ecs::Registry &registry) : _registry(registry)
23 {
24 idx = 0;
25 skipInvalidEntities<Components...>();
26 }
27
28 Iterator &operator++()
29 {
30 idx++;
31 skipInvalidEntities<Components...>();
32 return *this;
33 }
34
35 Tuple operator->() { return Tuple(idx, (_registry.getComponent<Components>(idx).get()->value())...); }
36
37 Tuple operator*() { return Tuple(idx, (_registry.getComponent<Components>(idx).get()->value())...); }
38
39 bool operator==(const Iterator &other) const { return idx == other.idx; }
40
41 bool operator!=(const Iterator &other) const { return !(other == *this); }
42
43 std::size_t idx;
44
45 private:
46 ecs::Registry _registry;
47
48 template<typename Component, typename... Others>
49 void skipInvalidEntities()
50 {
51 while (idx < _registry.getEntityCounter()) {
52 bool hasAllComponents = true;
53 auto &component = _registry.getComponent<Component>(idx);
54 if (component == nullptr || !component->has_value()) {
55 hasAllComponents = false;
56 }
57 if (hasAllComponents) {
58 if constexpr (sizeof...(Others) > 0) {
59 skipInvalidEntities<Others...>();
60 }
61 }
62 if (hasAllComponents) {
63 return;
64 }
65 if (idx == _registry.getEntityCounter()) break;
66 idx++;
67 }
68 }
69 };
70
71 Iterator begin() { return Iterator(_registry); }
72
73 Iterator end()
74 {
75 Iterator it(_registry);
76 it.idx = _registry.getEntityCounter();
77 return it;
78 }
79
80 private:
81 Registry _registry;
82 };
83} // namespace uranus::ecs
84
85#endif // URANUS_VIEW_HPP
Registry class, used to store and manage entities and their components.
Definition: Registry.hpp:24
size_t getEntityCounter() const
Get the counter used to generate new entity ids.
Definition: Registry.hpp:329
SparseArray< Component >::ReferenceType getComponent(const Entity &e)
Get a component from an entity.
Definition: Registry.hpp:210
Definition: View.hpp:20
Definition: View.hpp:14