]> git.tdb.fi Git - libs/game.git/blob - source/game/component.h
Implement base support for buffered components
[libs/game.git] / source / game / component.h
1 #ifndef MSP_GAME_COMPONENT_H_
2 #define MSP_GAME_COMPONENT_H_
3
4 #include <msp/time/timedelta.h>
5 #include "handle.h"
6
7 namespace Msp::Game {
8
9 class Entity;
10
11 class Component
12 {
13 protected:
14         Handle<Entity> entity;
15
16         Component(Handle<Entity>);
17 public:
18         virtual ~Component() = default;
19
20         Handle<Entity> get_entity() const { return entity; }
21 };
22
23 template<typename T>
24 class BufferedComponent: public Component
25 {
26 public:
27         using Data = T;
28         
29 protected:
30         T data[2];
31         uint8_t read_index = 0;
32         uint8_t write_index = 0;
33         bool written = false;
34
35         BufferedComponent(Handle<Entity> e): Component(e) { }
36
37         const T &read() const { return data[read_index]; }
38         T &write();
39
40 public:
41         virtual void prepare_tick() { write_index = 1-read_index; written = false; }
42         virtual void commit_tick() { if(written) read_index = write_index; }
43 };
44
45 template<typename T>
46 T &BufferedComponent<T>::write()
47 {
48         if(!written && write_index!=read_index)
49         {
50                 data[write_index] = data[read_index];
51                 written = true;
52         }
53         return data[write_index];
54 }
55
56 } // namespace Msp::Game
57
58 #endif