/
ContinuousBuffer.h
348 lines (273 loc) · 10.1 KB
/
ContinuousBuffer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#pragma once
#include <cstdint>
#include <stack>
#include <limits>
#include <vector>
#include "igeometrystore.h"
namespace render
{
namespace detail
{
struct BufferTransaction
{
enum class Type
{
Allocate,
Deallocate,
Update,
};
IGeometryStore::Slot slot;
Type type;
};
}
/**
* Buffer object managing allocations within a continuous block of memory.
*
* While the memory location itself might change when the buffer is growing,
* the whole data is always stored in a single continuous memory block.
*
* Use the allocate/deallocate methods to acquire or release a chunk of
* a certain size. The chunk size is fixed and cannot be changed.
*/
template<typename ElementType>
class ContinuousBuffer
{
public:
static constexpr std::size_t DefaultInitialSize = 65536;
using Handle = std::uint32_t;
private:
static constexpr std::size_t GrowthRate = 1; // 100% growth each time
std::vector<ElementType> _buffer;
struct SlotInfo
{
bool Occupied; // whether this slot is free
std::size_t Offset; // The index to the first element within the buffer
std::size_t Size; // Number of allocated elements
std::size_t Used; // Number of used elements
SlotInfo() :
Occupied(false),
Offset(0),
Size(0),
Used(0)
{}
SlotInfo(std::size_t offset, std::size_t size, bool occupied) :
Occupied(occupied),
Offset(offset),
Size(size),
Used(0)
{}
};
std::vector<SlotInfo> _slots;
// A stack of slots that can be re-used instead
std::stack<Handle> _emptySlots;
public:
ContinuousBuffer(std::size_t initialSize = DefaultInitialSize)
{
// Pre-allocate some memory, but don't go all the way down to zero
_buffer.resize(initialSize == 0 ? 16 : initialSize);
// The initial slot info which is going to be cut into pieces
createSlotInfo(0, _buffer.size());
}
ContinuousBuffer(const ContinuousBuffer& other)
{
*this = other;
}
// Custom assignment operator
ContinuousBuffer<ElementType>& operator=(const ContinuousBuffer<ElementType>& other)
{
_buffer.resize(other._buffer.size());
memcpy(_buffer.data(), other._buffer.data(), other._buffer.size() * sizeof(ElementType));
_slots.resize(other._slots.size());
memcpy(_slots.data(), other._slots.data(), other._slots.size() * sizeof(SlotInfo));
_emptySlots = other._emptySlots;
return *this;
}
Handle allocate(std::size_t requiredSize)
{
return getNextFreeSlotForSize(requiredSize);
}
ElementType* getBufferStart()
{
return _buffer.data();
}
std::size_t getSize(Handle handle) const
{
return _slots[handle].Size;
}
std::size_t getNumUsedElements(Handle handle) const
{
return _slots[handle].Used;
}
std::size_t getOffset(Handle handle) const
{
return _slots[handle].Offset;
}
void setData(Handle handle, const std::vector<ElementType>& elements)
{
auto& slot = _slots[handle];
auto numElements = elements.size();
if (numElements > slot.Size)
{
throw std::logic_error("Cannot store more data than allocated in GeometryStore::Buffer::setData");
}
std::copy(elements.begin(), elements.end(), _buffer.begin() + slot.Offset);
slot.Used = numElements;
}
void setSubData(Handle handle, std::size_t elementOffset, const std::vector<ElementType>& elements)
{
auto& slot = _slots[handle];
auto numElements = elements.size();
if (elementOffset + numElements > slot.Size)
{
throw std::logic_error("Cannot store more data than allocated in GeometryStore::Buffer::setSubData");
}
std::copy(elements.begin(), elements.end(), _buffer.begin() + slot.Offset + elementOffset);
slot.Used = std::max(slot.Used, elementOffset + numElements);
}
void deallocate(Handle handle)
{
auto& releasedSlot = _slots[handle];
releasedSlot.Occupied = false;
releasedSlot.Used = 0;
// Check if the slot can merge with an adjacent one
Handle slotIndexToMerge = std::numeric_limits<Handle>::max();
if (findLeftFreeSlot(releasedSlot, slotIndexToMerge))
{
auto& slotToMerge = _slots[slotIndexToMerge];
releasedSlot.Offset = slotToMerge.Offset;
releasedSlot.Size += slotToMerge.Size;
// The merged handle goes to recycling, block it against future use
slotToMerge.Size = 0;
slotToMerge.Used = 0;
slotToMerge.Occupied = true;
_emptySlots.push(slotIndexToMerge);
}
// Try to find an adjacent free slot to the right
if (findRightFreeSlot(releasedSlot, slotIndexToMerge))
{
auto& slotToMerge = _slots[slotIndexToMerge];
releasedSlot.Size += slotToMerge.Size;
// The merged handle goes to recycling, block it against future use
slotToMerge.Size = 0;
slotToMerge.Used = 0;
slotToMerge.Occupied = true;
_emptySlots.push(slotIndexToMerge);
}
}
void applyTransactions(const std::vector<detail::BufferTransaction>& transactions, const ContinuousBuffer<ElementType>& other,
const std::function<std::uint32_t(IGeometryStore::Slot)>& getHandle)
{
// Ensure the buffer is the same size
_buffer.resize(other._buffer.size());
for (const auto& transaction : transactions)
{
if (transaction.type == detail::BufferTransaction::Type::Allocate ||
transaction.type == detail::BufferTransaction::Type::Update)
{
auto handle = getHandle(transaction.slot);
auto& otherSlot = other._slots[handle];
memcpy(_buffer.data() + otherSlot.Offset, other._buffer.data() + otherSlot.Offset, otherSlot.Size * sizeof(ElementType));
}
}
_slots.resize(other._slots.size());
memcpy(_slots.data(), other._slots.data(), other._slots.size() * sizeof(SlotInfo));
_emptySlots = other._emptySlots;
}
private:
bool findLeftFreeSlot(const SlotInfo& slotToTouch, Handle& found)
{
auto numSlots = _slots.size();
for (Handle slotIndex = 0; slotIndex < numSlots; ++slotIndex)
{
const auto& candidate = _slots[slotIndex];
if (candidate.Offset + candidate.Size == slotToTouch.Offset)
{
// The slot coordinates match, return true if this block is free
found = slotIndex;
return !candidate.Occupied;
}
}
return false;
}
bool findRightFreeSlot(const SlotInfo& slotToTouch, Handle& found)
{
auto numSlots = _slots.size();
auto offsetToMatch = slotToTouch.Offset + slotToTouch.Size;
for (Handle slotIndex = 0; slotIndex < numSlots; ++slotIndex)
{
const auto& candidate = _slots[slotIndex];
if (candidate.Offset == offsetToMatch)
{
// The slot coordinates match, return true if this block is free
found = slotIndex;
return !candidate.Occupied;
}
}
return false;
}
Handle getNextFreeSlotForSize(std::size_t requiredSize)
{
auto numSlots = _slots.size();
Handle rightmostFreeSlotIndex = static_cast<Handle>(numSlots);
std::size_t rightmostFreeOffset = 0;
Handle slotIndex = 0;
for (slotIndex = 0; slotIndex < numSlots; ++slotIndex)
{
auto& slot = _slots[slotIndex];
if (slot.Occupied) continue;
// Keep track of the highest slot, we need that when re-allocating
if (slot.Offset > rightmostFreeOffset)
{
rightmostFreeOffset = slot.Offset;
rightmostFreeSlotIndex = slotIndex;
}
if (slot.Size < requiredSize) continue; // this slot is no use for us
// Calculate the remaining size before assignment
auto remainingSize = slot.Size - requiredSize;
slot.Size = requiredSize;
slot.Occupied = true;
if (remainingSize > 0)
{
// Allocate a new free slot with the remaining space
createSlotInfo(slot.Offset + requiredSize, remainingSize);
}
return slotIndex;
}
// No space wherever, we need to expand the buffer
// Check if we have any free slots, otherwise allocate a new one
if (rightmostFreeSlotIndex == numSlots)
{
// Create a free slot with 0 size,
// rightMostFreeSlotIndex is now within the valid range
_slots.emplace_back(_buffer.size(), 0, false);
}
// Allocate more memory
auto additionalSize = std::max(_buffer.size() * GrowthRate, requiredSize);
auto newSize = _buffer.size() + additionalSize;
_buffer.resize(newSize);
// Use the right most slot for our requirement, then cut up the rest of the space
auto& rightmostFreeSlot = _slots[rightmostFreeSlotIndex];
assert(rightmostFreeSlot.Size < requiredSize); // otherwise we've run wrong above
auto remainingSize = rightmostFreeSlot.Size + additionalSize - requiredSize;
rightmostFreeSlot.Occupied = true;
rightmostFreeSlot.Size = requiredSize;
createSlotInfo(rightmostFreeSlot.Offset + rightmostFreeSlot.Size, remainingSize);
return rightmostFreeSlotIndex;
}
SlotInfo& createSlotInfo(std::size_t offset, std::size_t size, bool occupied = false)
{
if (_emptySlots.empty())
{
return _slots.emplace_back(offset, size, occupied);
}
// Re-use an old slot
auto& slot = _slots.at(_emptySlots.top());
_emptySlots.pop();
slot.Occupied = occupied;
slot.Offset = offset;
slot.Size = size;
slot.Used = 0;
return slot;
}
};
}