]> git.tdb.fi Git - libs/game.git/blobdiff - source/game/component.h
Implement base support for buffered components
[libs/game.git] / source / game / component.h
index 6b49dd19e8c6e3f64da05ceb550616d1e2c31624..44927ffd2e73c640f9d8a609f4e4b66984633572 100644 (file)
@@ -20,6 +20,39 @@ public:
        Handle<Entity> get_entity() const { return entity; }
 };
 
+template<typename T>
+class BufferedComponent: public Component
+{
+public:
+       using Data = T;
+       
+protected:
+       T data[2];
+       uint8_t read_index = 0;
+       uint8_t write_index = 0;
+       bool written = false;
+
+       BufferedComponent(Handle<Entity> e): Component(e) { }
+
+       const T &read() const { return data[read_index]; }
+       T &write();
+
+public:
+       virtual void prepare_tick() { write_index = 1-read_index; written = false; }
+       virtual void commit_tick() { if(written) read_index = write_index; }
+};
+
+template<typename T>
+T &BufferedComponent<T>::write()
+{
+       if(!written && write_index!=read_index)
+       {
+               data[write_index] = data[read_index];
+               written = true;
+       }
+       return data[write_index];
+}
+
 } // namespace Msp::Game
 
 #endif