A 3D game engine from scratch.
1// (c) 2020 Vlad-Stefan Harbuz <vlad@vladh.net>
2
3#pragma once
4
5#include "memory.hpp"
6
7template <typename T, u32 capacity>
8class StackArray {
9public:
10 T items[capacity] = {{}};
11 u32 length = 0;
12 bool is_sparse = false;
13 u32 starting_idx = 0;
14
15 T* push() {
16 assert(this->length < capacity);
17 u32 new_idx = this->length;
18 this->length++;
19 T* new_slot = &this->items[new_idx];
20 return new_slot;
21 }
22
23 T* push(T new_item) {
24 T* new_slot = push();
25 *new_slot = new_item;
26 return new_slot;
27 }
28
29 T* get(u32 idx) {
30 assert(idx >= this->starting_idx && idx < capacity);
31 if (idx >= this->length) {
32 assert(this->is_sparse);
33 this->length = idx + 1;
34 }
35 return &this->items[idx];
36 }
37
38 T* operator[](u32 idx) {
39 return get(idx);
40 }
41
42 template <typename F>
43 T* find(F match) {
44 for (auto item = begin(); item < end(); item++) {
45 if (match(item)) {
46 return item;
47 }
48 }
49 return nullptr;
50 }
51
52 T* begin() {
53 return &this->items[this->starting_idx];
54 }
55
56 T* end() {
57 return &this->items[this->length];
58 }
59
60 void clear() {
61 memset(this->items, 0, sizeof(this->items));
62 this->length = 0;
63 }
64
65 void delete_elements_after_index(u32 idx) {
66 memset(&this->items[idx], 0, sizeof(T) * (this->length - idx));
67 this->length = idx;
68 }
69};