Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
Grid.h
Go to the documentation of this file.
1/* Copyright (C) 2026 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#ifndef INCLUDED_GRID
19#define INCLUDED_GRID
20
21#include "lib/code_annotation.h"
22#include "lib/code_generation.h"
23#include "lib/debug.h"
26
27#include <algorithm>
28#include <cstring>
29#include <new>
30#include <type_traits>
31#include <utility>
32
33#ifdef NDEBUG
34#define GRID_BOUNDS_DEBUG 0
35#else
36#define GRID_BOUNDS_DEBUG 1
37#endif
38
39/**
40 * Basic 2D array, intended for storing tile data, plus support for lazy updates
41 * by ICmpObstructionManager.
42 * @c T must be a POD type that can be initialised with 0s.
43 */
44template<typename T>
45class Grid
46{
47 friend struct SerializeHelper<Grid<T>>;
48public:
49 Grid() : m_W(0), m_H(0), m_Data(NULL)
50 {
51 }
52
53 Grid(std::uint16_t w, std::uint16_t h) : m_W(w), m_H(h), m_Data(NULL)
54 {
55 resize(w, h);
56 }
57
58 Grid(const Grid& g) : m_W(0), m_H(0), m_Data(NULL)
59 {
60 *this = g;
61 }
62
63 using value_type = T;
64public:
65
66 // Ensure that o and this are the same size before calling.
67 Grid& operator=(const Grid& g)
68 {
69 if (this == &g)
70 return *this;
71
72 if (m_W == g.m_W && m_H == g.m_H)
73 {
74 if constexpr (std::is_trivially_copyable_v<T>)
75 memcpy(m_Data, g.m_Data, m_W*m_H*sizeof(T));
76 else
77 std::copy(g.m_Data, g.m_Data + m_H*m_W, &m_Data[0]);
78 return *this;
79 }
80
81 m_W = g.m_W;
82 m_H = g.m_H;
84 if (g.m_Data)
85 {
86 m_Data = new T[m_W * m_H];
87 if constexpr (std::is_trivially_copyable_v<T>)
88 memcpy(m_Data, g.m_Data, m_W*m_H*sizeof(T));
89 else
90 std::copy(g.m_Data, g.m_Data + m_H*m_W, &m_Data[0]);
91 }
92 return *this;
93 }
94
95 void swap(Grid& g)
96 {
98 std::swap(m_H, g.m_H);
99 std::swap(m_W, g.m_W);
100 }
101
103 {
105 }
106
107 // Ensure that o and this are the same size before calling.
108
109 bool operator==(const Grid& g) const
110 {
111 if (!compare_sizes(&g))
112 return false;
113
114 if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>)
115 return memcmp(m_Data, g.m_Data, m_W*m_H*sizeof(T)) == 0;
116 else
117 return std::equal(&m_Data[0], &m_Data[m_W*m_H], g.m_Data);
118 }
119 bool operator!=(const Grid& g) const { return !(*this==g); }
120
121 bool blank() const
122 {
123 return m_W == 0 && m_H == 0;
124 }
125
126 std::uint16_t width() const { return m_W; };
127 std::uint16_t height() const { return m_H; };
128
129 bool any_set_in_square(int i0, int j0, int i1, int j1) const
130 {
131 if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>)
132 {
133#if GRID_BOUNDS_DEBUG
134 ENSURE(i0 >= 0 && j0 >= 0 && i1 <= m_W && j1 <= m_H);
135#endif
136 for (int j = j0; j < j1; ++j)
137 {
138 int sum = 0;
139 for (int i = i0; i < i1; ++i)
140 sum += m_Data[j*m_W + i];
141 if (sum > 0)
142 return true;
143 }
144 return false;
145 }
146 else
147 {
148 static_assert(!std::is_same<T, T>::value, "Not implemented.");
149 return false; // Fix warnings.
150 }
151 }
152
153 // Reset the data to its default-constructed value (usually 0), not changing size.
154 void reset()
155 {
156 if (m_Data) {
157 if constexpr (std::is_standard_layout_v<T> && std::is_trivial_v<T>)
158 memset(m_Data, 0, m_W*m_H*sizeof(T));
159 else
160 std::fill(&m_Data[0], &m_Data[m_H*m_W], T{});
161 }
162 }
163
164 // Clear the grid setting the size to 0 and freeing any data.
165 void clear()
166 {
167 resize(0, 0);
168 }
169
170 void resize(std::uint16_t w, std::uint16_t h)
171 {
173 m_W = w;
174 m_H = h;
175
176 if (!m_W && !m_H)
177 return;
178
179 m_Data = new T[m_W * m_H];
180 ENSURE(m_Data);
181 reset();
182 }
183
184 // Add two grids of the same size
185 void add(const Grid& g)
186 {
187#if GRID_BOUNDS_DEBUG
188 ENSURE(g.m_W == m_W && g.m_H == m_H);
189#endif
190 for (int i=0; i < m_H*m_W; ++i)
191 m_Data[i] += g.m_Data[i];
192 }
193
194 void bitwise_or(const Grid& g)
195 {
196 if (this == &g)
197 return;
198
199#if GRID_BOUNDS_DEBUG
200 ENSURE(g.m_W == m_W && g.m_H == m_H);
201#endif
202 for (int i = 0; i < m_H*m_W; ++i)
203 m_Data[i] |= g.m_Data[i];
204 }
205
206 void set(int i, int j, const T& value)
207 {
208#if GRID_BOUNDS_DEBUG
209 ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
210#endif
211 m_Data[j*m_W + i] = value;
212 }
213
214 T& operator[](std::pair<std::uint16_t, std::uint16_t> coords) { return get(coords.first, coords.second); }
215 T& get(std::pair<std::uint16_t, std::uint16_t> coords) { return get(coords.first, coords.second); }
216
217 T& operator[](std::pair<std::uint16_t, std::uint16_t> coords) const { return get(coords.first, coords.second); }
218 T& get(std::pair<std::uint16_t, std::uint16_t> coords) const { return get(coords.first, coords.second); }
219
220 T& get(int i, int j)
221 {
222#if GRID_BOUNDS_DEBUG
223 ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
224#endif
225 return m_Data[j*m_W + i];
226 }
227
228 T& get(int i, int j) const
229 {
230#if GRID_BOUNDS_DEBUG
231 ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
232#endif
233 return m_Data[j*m_W + i];
234 }
235
236 template<typename U>
237 bool compare_sizes(const Grid<U>* g) const
238 {
239 return g && m_W == g->m_W && m_H == g->m_H;
240 }
241
242 std::uint16_t m_W, m_H;
244};
245
246
247/**
248 * Serialize a grid, applying a simple RLE compression that is assumed efficient.
249 */
250template<typename T>
252{
253 void operator()(ISerializer& serialize, const char* name, Grid<T>& value)
254 {
255 size_t len = value.m_H * value.m_W;
256 serialize.NumberU16_Unbounded("width", value.m_W);
257 serialize.NumberU16_Unbounded("height", value.m_H);
258 if (len == 0)
259 return;
260 std::uint32_t count = 1;
261 T prevVal = value.m_Data[0];
262 for (size_t i = 1; i < len; ++i)
263 {
264 if (prevVal == value.m_Data[i])
265 {
266 count++;
267 continue;
268 }
269 serialize.NumberU32_Unbounded("#", count);
270 Serializer(serialize, name, prevVal);
271 count = 1;
272 prevVal = value.m_Data[i];
273 }
274 serialize.NumberU32_Unbounded("#", count);
275 Serializer(serialize, name, prevVal);
276 }
277
278 void operator()(IDeserializer& deserialize, const char* name, Grid<T>& value)
279 {
280 std::uint16_t w, h;
281 deserialize.NumberU16_Unbounded("width", w);
282 deserialize.NumberU16_Unbounded("height", h);
283 std::uint32_t len = h * w;
284 value.resize(w, h);
285 for (size_t i = 0; i < len;)
286 {
287 std::uint32_t count;
288 deserialize.NumberU32_Unbounded("#", count);
289 T el;
290 Serializer(deserialize, name, el);
291 std::fill(&value.m_Data[i], &value.m_Data[i+count], el);
292 i += count;
293 }
294 }
295};
296
297
298/**
299 * Similar to Grid, except optimised for sparse usage (the grid is subdivided into
300 * buckets whose contents are only initialised on demand, to save on memset cost).
301 */
302template<typename T>
304{
306
307 enum { BucketBits = 4, BucketSize = 1 << BucketBits };
308
309 T* GetBucket(int i, int j)
310 {
311 size_t b = (j >> BucketBits) * m_BW + (i >> BucketBits);
312 if (!m_Data[b])
313 {
314 m_Data[b] = new T[BucketSize*BucketSize]();
315 }
316 return m_Data[b];
317 }
318
319public:
320 SparseGrid(std::uint16_t w, std::uint16_t h) : m_W(w), m_H(h), m_DirtyID(0)
321 {
322 ENSURE(m_W && m_H);
323
324 m_BW = static_cast<std::uint16_t>((m_W + BucketSize-1) >> BucketBits);
325 m_BH = static_cast<std::uint16_t>((m_H + BucketSize-1) >> BucketBits);
326
327 m_Data = new T*[m_BW*m_BH]();
328 }
329
331 {
332 reset();
334 }
335
336 void reset()
337 {
338 for (size_t i = 0; i < (size_t)(m_BW*m_BH); ++i)
340
341 // Reset m_Data by value-constructing in place with placement new.
342 m_Data = new (m_Data) T*[m_BW*m_BH]();
343 }
344
345 void set(int i, int j, const T& value)
346 {
347#if GRID_BOUNDS_DEBUG
348 ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
349#endif
350 GetBucket(i, j)[(j % BucketSize)*BucketSize + (i % BucketSize)] = value;
351 }
352
353 T& get(int i, int j)
354 {
355#if GRID_BOUNDS_DEBUG
356 ENSURE(0 <= i && i < m_W && 0 <= j && j < m_H);
357#endif
358 return GetBucket(i, j)[(j % BucketSize)*BucketSize + (i % BucketSize)];
359 }
360
361 std::uint16_t m_W, m_H;
362 std::uint16_t m_BW, m_BH;
364
365 size_t m_DirtyID; // if this is < the id maintained by ICmpObstructionManager then it needs to be updated
366};
367
368/**
369 * Structure holding grid dirtiness informations, for clever updates.
370 */
372{
373 bool dirty;
376
377 /**
378 * Update the information with additionnal needed updates, then erase the source of additions.
379 * This can usually be optimized through a careful memory management.
380 */
382 {
384
385 bool wasDirty = dirty;
386
387 dirty |= b.dirty;
389
390 // If the current grid is useless, swap it
391 if (!wasDirty)
393 // If the new grid isn't used, don't bother updating it
394 else if (dirty && !globallyDirty)
396
397 b.Clean();
398 }
399
400 /**
401 * Mark everything as clean
402 */
403 void Clean()
404 {
405 dirty = false;
406 globallyDirty = false;
408 }
409};
410
411#endif // INCLUDED_GRID
#define swap(a, i, j)
Helper templates definitions for serializing/deserializing common objects.
void Serializer(S &serialize, const char *name, Args &&... args)
Definition: SerializeTemplates.h:51
Basic 2D array, intended for storing tile data, plus support for lazy updates by ICmpObstructionManag...
Definition: Grid.h:46
std::uint16_t m_W
Definition: Grid.h:242
Grid(std::uint16_t w, std::uint16_t h)
Definition: Grid.h:53
~Grid()
Definition: Grid.h:102
Grid & operator=(const Grid &g)
Definition: Grid.h:67
void bitwise_or(const Grid &g)
Definition: Grid.h:194
T * m_Data
Definition: Grid.h:243
void resize(std::uint16_t w, std::uint16_t h)
Definition: Grid.h:170
T & get(std::pair< std::uint16_t, std::uint16_t > coords) const
Definition: Grid.h:218
void add(const Grid &g)
Definition: Grid.h:185
void clear()
Definition: Grid.h:165
T & get(int i, int j)
Definition: Grid.h:220
T & get(int i, int j) const
Definition: Grid.h:228
Grid()
Definition: Grid.h:49
bool any_set_in_square(int i0, int j0, int i1, int j1) const
Definition: Grid.h:129
T & operator[](std::pair< std::uint16_t, std::uint16_t > coords)
Definition: Grid.h:214
std::uint16_t width() const
Definition: Grid.h:126
T & get(std::pair< std::uint16_t, std::uint16_t > coords)
Definition: Grid.h:215
void set(int i, int j, const T &value)
Definition: Grid.h:206
std::uint16_t height() const
Definition: Grid.h:127
T & operator[](std::pair< std::uint16_t, std::uint16_t > coords) const
Definition: Grid.h:217
void swap(Grid &g)
Definition: Grid.h:95
void reset()
Definition: Grid.h:154
Grid(const Grid &g)
Definition: Grid.h:58
bool operator==(const Grid &g) const
Definition: Grid.h:109
T value_type
Definition: Grid.h:63
bool compare_sizes(const Grid< U > *g) const
Definition: Grid.h:237
bool operator!=(const Grid &g) const
Definition: Grid.h:119
std::uint16_t m_H
Definition: Grid.h:242
bool blank() const
Definition: Grid.h:121
Deserialization interface; see serialization overview.
Definition: IDeserializer.h:40
virtual void NumberU16_Unbounded(const char *name, uint16_t &out)
Definition: IDeserializer.cpp:112
virtual void NumberU32_Unbounded(const char *name, uint32_t &out)
Definition: IDeserializer.cpp:126
Serialization interface; see serialization overview.
Definition: ISerializer.h:126
void NumberU32_Unbounded(const char *name, uint32_t value)
Serialize a number.
Definition: ISerializer.h:176
void NumberU16_Unbounded(const char *name, uint16_t value)
Serialize a number.
Definition: ISerializer.h:166
Similar to Grid, except optimised for sparse usage (the grid is subdivided into buckets whose content...
Definition: Grid.h:304
T * GetBucket(int i, int j)
Definition: Grid.h:309
std::uint16_t m_BW
Definition: Grid.h:362
T ** m_Data
Definition: Grid.h:363
size_t m_DirtyID
Definition: Grid.h:365
std::uint16_t m_W
Definition: Grid.h:361
~SparseGrid()
Definition: Grid.h:330
void set(int i, int j, const T &value)
Definition: Grid.h:345
void reset()
Definition: Grid.h:336
SparseGrid(std::uint16_t w, std::uint16_t h)
Definition: Grid.h:320
std::uint16_t m_H
Definition: Grid.h:361
std::uint16_t m_BH
Definition: Grid.h:362
T & get(int i, int j)
Definition: Grid.h:353
@ BucketSize
Definition: Grid.h:307
@ BucketBits
Definition: Grid.h:307
NONCOPYABLE(SparseGrid)
#define SAFE_ARRAY_DELETE(p)
delete memory ensuing from new[] and set the pointer to zero (thus making double-frees safe / a no-op...
Definition: code_generation.h:121
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
Definition: debug.h:222
#define T(string_literal)
Definition: secure_crt.cpp:81
Structure holding grid dirtiness informations, for clever updates.
Definition: Grid.h:372
bool dirty
Definition: Grid.h:373
void Clean()
Mark everything as clean.
Definition: Grid.h:403
bool globallyDirty
Definition: Grid.h:374
void MergeAndClear(GridUpdateInformation &b)
Update the information with additionnal needed updates, then erase the source of additions.
Definition: Grid.h:381
Grid< std::uint8_t > dirtinessGrid
Definition: Grid.h:375
void operator()(IDeserializer &deserialize, const char *name, Grid< T > &value)
Definition: Grid.h:278
void operator()(ISerializer &serialize, const char *name, Grid< T > &value)
Definition: Grid.h:253
Definition: SerializeTemplates.h:42