Gaia-ECS v1.0.0
A simple and powerful entity component system
Loading...
Searching...
No Matches
query_match_stamps.h
1#pragma once
2#include "gaia/config/config.h"
3
4#include <cstdint>
5#include <cstring>
6
7#include "gaia/cnt/darray.h"
8#include "gaia/core/utility.h"
9#include "gaia/mem/mem_alloc.h"
10
12namespace gaia {
13 namespace ecs {
14 struct ArchetypeMatchStamps {
17 static constexpr uint32_t PageBits = 10;
18 static constexpr uint32_t PageSize = 1U << PageBits;
19 static constexpr uint32_t PageMask = PageSize - 1;
20
22 cnt::darray<uint32_t*> pages;
23
24 ArchetypeMatchStamps() = default;
25 ArchetypeMatchStamps(const ArchetypeMatchStamps&) = delete;
26 ArchetypeMatchStamps& operator=(const ArchetypeMatchStamps&) = delete;
27
28 ArchetypeMatchStamps(ArchetypeMatchStamps&& other) noexcept: pages(GAIA_MOV(other.pages)) {
29 other.pages = {};
30 }
31
32 ArchetypeMatchStamps& operator=(ArchetypeMatchStamps&& other) noexcept {
33 if (this == &other)
34 return *this;
35
36 free_pages();
37 pages = GAIA_MOV(other.pages);
38 other.pages = {};
39 return *this;
40 }
41
42 ~ArchetypeMatchStamps() {
43 free_pages();
44 }
45
46 GAIA_NODISCARD bool has(uint32_t sid) const {
47 const auto pid = sid >> PageBits;
48 return pid < pages.size() && pages[pid] != nullptr;
49 }
50
51 GAIA_NODISCARD uint32_t get(uint32_t sid) const {
52 GAIA_ASSERT(has(sid));
53 const auto pid = sid >> PageBits;
54 const auto did = sid & PageMask;
55 return pages[pid][did];
56 }
57
58 void set(uint32_t sid, uint32_t version) {
59 const auto pid = sid >> PageBits;
60 const auto did = sid & PageMask;
61 auto* page = ensure_page(pid);
62 page[did] = version;
63 }
64
65 void clear() {
66 for (auto* page: pages) {
67 if (page == nullptr)
68 continue;
72 std::memset(page, 0, sizeof(uint32_t) * PageSize);
73 }
74 }
75
76 private:
77 GAIA_NODISCARD uint32_t* ensure_page(uint32_t pid) {
78 if (pid >= pages.size())
79 pages.resize(pid + 1, nullptr);
80
81 auto*& page = pages[pid];
82 if (page == nullptr) {
83 page = mem::AllocHelper::alloc<uint32_t>("ArchetypeMatchStampPage", PageSize);
84 std::memset(page, 0, sizeof(uint32_t) * PageSize);
85 }
86
87 return page;
88 }
89
90 void free_pages() {
91 for (auto* page: pages) {
92 if (page == nullptr)
93 continue;
94 mem::AllocHelper::free("ArchetypeMatchStampPage", page);
95 }
96 pages = {};
97 }
98 };
99 } // namespace ecs
100} // namespace gaia