All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
DynamicBuffer.h
1 // Copyright eeGeo Ltd (2012-2014), All Rights Reserved
2 
3 #pragma once
4 
5 #include "Types.h"
6 #include "GLState.h"
7 #include <vector>
8 #include "GLHelpers.h"
9 
10 namespace Eegeo
11 {
12  namespace Rendering
13  {
15  template<class T>
17  {
18  public:
19  DynamicBuffer(GLenum bufferType, int initialCapacity)
20  : m_glBuffer(0)
21  , m_bufferType(bufferType)
22  {
23  // avoid issues on some older Android devices where glBufferData fails if called with zero bytes or null source
24  Eegeo_ASSERT(initialCapacity > 0, "initial capacity must be greater than zero");
25  m_bufferData.reserve(initialCapacity);
26  GenerateBuffers();
27  }
28 
29  ~DynamicBuffer()
30  {
31  DestroyBuffers();
32  }
33 
34  void GenerateBuffers()
35  {
37  Eegeo_ASSERT(m_glBuffer == 0);
38  Eegeo_GL(glGenBuffers(1, &m_glBuffer));
39  Eegeo_GL(glBindBuffer(m_bufferType, m_glBuffer));
40  Eegeo_GL(glBufferData(m_bufferType, BufferCapacityBytes(), m_bufferData.data(), GL_DYNAMIC_DRAW));
41  Eegeo_BUFFER_MEMORY_ADD(m_glBuffer, BufferCapacityBytes());
42 
43  Eegeo_GL(glBindBuffer (m_bufferType, 0));
44  }
45 
46  void DestroyBuffers()
47  {
48  Eegeo_BUFFER_MEMORY_REMOVE(m_glBuffer);
49  Eegeo_GL(glDeleteBuffers(1, &m_glBuffer));
50 
51  m_glBuffer = 0;
52  }
53 
54  void Reset()
55  {
56  m_bufferData.clear();
57  }
58 
59  void AddElement(const T& element)
60  {
61  size_t prevCapacity = m_bufferData.capacity();
62 
63  m_bufferData.push_back(element);
64 
65  if (prevCapacity != m_bufferData.capacity())
66  {
67  DestroyBuffers();
68  GenerateBuffers();
69  }
70  }
71 
72  int CurrentElementCount() const { return static_cast<int>(m_bufferData.size()); }
73  int BufferCapacity() const { return m_bufferData.capacity(); }
74  size_t BufferCapacityBytes() const { return m_bufferData.capacity() * sizeof(T); }
75  size_t BufferDataBytes() const { return m_bufferData.size() * sizeof(T); }
76 
77  const std::vector<T>& GetBufferData() const { return m_bufferData; }
78 
79  u32 GetGLBuffer() { return m_glBuffer; }
80 
81  private:
82  u32 m_glBuffer;
83  GLenum m_bufferType;
84  std::vector<T> m_bufferData;
85  };
86  }
87 }