Line data Source code
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 : #include "precompiled.h"
19 :
20 : #include "HierarchicalPathfinder.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/Overlay.h"
24 : #include "lib/code_generation.h"
25 : #include "maths/Fixed.h"
26 : #include "maths/FixedVector2D.h"
27 : #include "ps/Profile.h"
28 : #include "ps/Profiler2.h"
29 : #include "renderer/Scene.h"
30 : #include "simulation2/helpers/Grid.h"
31 : #include "simulation2/helpers/PathGoal.h"
32 : #include "simulation2/helpers/Pathfinding.h"
33 : #include "simulation2/helpers/Position.h"
34 : #include "simulation2/helpers/Render.h"
35 :
36 : #include <algorithm>
37 : #include <cstring>
38 :
39 : class CSimContext;
40 :
41 : namespace
42 : {
43 : // Find the root ID of a region, used by InitRegions
44 20 : std::uint16_t RootID(std::uint16_t x, const std::vector<std::uint16_t>& v)
45 : {
46 86 : while (v[x] < x)
47 : x = v[x];
48 :
49 60 : return x;
50 : }
51 :
52 0 : void BuildTextureRGBA(HierarchicalPathfinder& pathfinderHier, std::uint8_t* data, std::size_t w,
53 : std::size_t h)
54 : {
55 0 : ENSURE(h <= std::numeric_limits<std::uint16_t>::max() &&
56 : w <= std::numeric_limits<std::uint16_t>::max());
57 0 : pass_class_t passClass = pathfinderHier.GetPassabilityClass("default");
58 :
59 0 : TerrainTextureOverlay::OverwriteEachTile(data, w, h, [&](const int i, const int j)
60 : {
61 0 : HierarchicalPathfinder::RegionID rid = pathfinderHier.Get(static_cast<std::uint16_t>(j),
62 0 : static_cast<std::uint16_t>(i), passClass);
63 0 : if (rid.r == 0)
64 0 : return SColor4ub{0, 0, 0, 0};
65 0 : if (rid.r == 0xFFFF)
66 0 : return SColor4ub{255, 0, 255, 255};
67 0 : return TerrainTextureOverlay::GetColor(rid.r + rid.ci*5 + rid.cj*7, 127);
68 : });
69 0 : }
70 : }
71 :
72 5301 : void HierarchicalPathfinder::Chunk::InitRegions(int ci, int cj, Grid<NavcellData>* grid, pass_class_t passClass)
73 : {
74 5301 : ENSURE(ci < 256 && cj < 256); // avoid overflows
75 5301 : m_ChunkI = ci;
76 5301 : m_ChunkJ = cj;
77 :
78 5301 : memset(m_Regions, 0, sizeof(m_Regions));
79 :
80 5301 : int i0 = ci * CHUNK_SIZE;
81 5301 : int j0 = cj * CHUNK_SIZE;
82 5301 : int i1 = std::min(i0 + CHUNK_SIZE, (int)grid->m_W);
83 5301 : int j1 = std::min(j0 + CHUNK_SIZE, (int)grid->m_H);
84 :
85 : // Efficiently flood-fill the m_Regions grid
86 :
87 5301 : int regionID = 0;
88 10602 : std::vector<std::uint16_t> connect;
89 :
90 5301 : std::uint16_t* pCurrentID = NULL;
91 5301 : std::uint16_t LeftID = 0;
92 5301 : std::uint16_t DownID = 0;
93 5301 : bool Checked = false; // prevent some unneccessary RootID calls
94 :
95 5301 : connect.reserve(32); // TODO: What's a sensible number?
96 5301 : connect.push_back(0); // connect[0] = 0
97 :
98 : // Start by filling the grid with 0 for blocked,
99 : // and regionID for unblocked
100 512100 : for (int j = j0; j < j1; ++j)
101 : {
102 49019898 : for (int i = i0; i < i1; ++i)
103 : {
104 48513099 : pCurrentID = &m_Regions[j-j0][i-i0];
105 48513099 : if (!IS_PASSABLE(grid->get(i, j), passClass))
106 : {
107 23223878 : *pCurrentID = 0;
108 23223878 : continue;
109 : }
110 :
111 25289221 : if (j > j0)
112 25049727 : DownID = m_Regions[j-1-j0][i-i0];
113 :
114 25289221 : if (i == i0)
115 : LeftID = 0;
116 : else
117 25050727 : LeftID = m_Regions[j-j0][i-1-i0];
118 :
119 25050727 : if (LeftID > 0)
120 : {
121 25015787 : *pCurrentID = LeftID;
122 25015787 : if (*pCurrentID != DownID && DownID > 0 && !Checked)
123 : {
124 20 : std::uint16_t id0 = RootID(DownID, connect);
125 20 : std::uint16_t id1 = RootID(LeftID, connect);
126 20 : Checked = true; // this avoids repeatedly connecting the same IDs
127 :
128 20 : if (id0 < id1)
129 16 : connect[id1] = id0;
130 4 : else if (id0 > id1)
131 4 : connect[id0] = id1;
132 : }
133 25015767 : else if (DownID == 0)
134 270402 : Checked = false;
135 : }
136 273434 : else if (DownID > 0)
137 : {
138 270458 : *pCurrentID = DownID;
139 270458 : Checked = false;
140 : }
141 : else
142 : {
143 : // New ID
144 2976 : *pCurrentID = ++regionID;
145 2976 : connect.push_back(regionID);
146 2976 : Checked = false;
147 : }
148 : }
149 : }
150 :
151 : // Mark connected regions as being the same ID (i.e. the lowest)
152 5301 : m_RegionsID.clear();
153 8277 : for (std::uint16_t i = 1; i < regionID+1; ++i)
154 : {
155 2976 : if (connect[i] != i)
156 20 : connect[i] = RootID(i, connect);
157 : else
158 2956 : m_RegionsID.push_back(connect[i]);
159 : }
160 :
161 : // Replace IDs by the root ID
162 514197 : for (int j = 0; j < CHUNK_SIZE; ++j)
163 49362912 : for (int i = 0; i < CHUNK_SIZE; ++i)
164 48854016 : m_Regions[j][i] = connect[m_Regions[j][i]];
165 5301 : }
166 :
167 : /**
168 : * Returns a RegionID for the given global navcell coords
169 : * (which must be inside this chunk);
170 : */
171 2194835 : HierarchicalPathfinder::RegionID HierarchicalPathfinder::Chunk::Get(int i, int j) const
172 : {
173 2194835 : ENSURE(i < CHUNK_SIZE && j < CHUNK_SIZE);
174 2194835 : return RegionID(m_ChunkI, m_ChunkJ, m_Regions[j][i]);
175 : }
176 :
177 : /**
178 : * Return the global navcell coords that correspond roughly to the
179 : * center of the given region in this chunk.
180 : * (This is not guaranteed to be actually inside the region.)
181 : */
182 0 : void HierarchicalPathfinder::Chunk::RegionCenter(std::uint16_t r, int& i_out, int& j_out) const
183 : {
184 : // Find the mean of i,j coords of navcells in this region:
185 :
186 0 : std::uint32_t si = 0, sj = 0; // sum of i,j coords
187 0 : std::uint32_t n = 0; // number of navcells in region
188 :
189 0 : cassert(CHUNK_SIZE < 256); // conservative limit to ensure si and sj don't overflow
190 :
191 0 : for (int j = 0; j < CHUNK_SIZE; ++j)
192 : {
193 0 : for (int i = 0; i < CHUNK_SIZE; ++i)
194 : {
195 0 : if (m_Regions[j][i] == r)
196 : {
197 0 : si += i;
198 0 : sj += j;
199 0 : n += 1;
200 : }
201 : }
202 : }
203 :
204 : // Avoid divide-by-zero
205 0 : if (n == 0)
206 : n = 1;
207 :
208 0 : i_out = m_ChunkI * CHUNK_SIZE + si / n;
209 0 : j_out = m_ChunkJ * CHUNK_SIZE + sj / n;
210 0 : }
211 :
212 : /**
213 : * Returns the global navcell coords, and the squared distance to the goal
214 : * navcell, of whichever navcell inside the given region is closest to
215 : * that goal.
216 : */
217 1052 : void HierarchicalPathfinder::Chunk::RegionNavcellNearest(std::uint16_t r, int iGoal, int jGoal, int& iBest,
218 : int& jBest, std::uint32_t& dist2Best) const
219 : {
220 1052 : iBest = 0;
221 1052 : jBest = 0;
222 1052 : dist2Best = std::numeric_limits<std::uint32_t>::max();
223 :
224 50300 : for (int j = 0; j < CHUNK_SIZE; ++j)
225 : {
226 4781916 : for (int i = 0; i < CHUNK_SIZE; ++i)
227 : {
228 4732668 : if (m_Regions[j][i] != r)
229 748572 : continue;
230 :
231 3984096 : std::uint32_t dist2 = (i + m_ChunkI*CHUNK_SIZE - iGoal)*(i + m_ChunkI*CHUNK_SIZE - iGoal)
232 3984096 : + (j + m_ChunkJ*CHUNK_SIZE - jGoal)*(j + m_ChunkJ*CHUNK_SIZE - jGoal);
233 :
234 3984096 : if (dist2 < dist2Best)
235 : {
236 275983 : iBest = i + m_ChunkI*CHUNK_SIZE;
237 275983 : jBest = j + m_ChunkJ*CHUNK_SIZE;
238 275983 : dist2Best = dist2;
239 : }
240 : }
241 : }
242 1052 : }
243 :
244 : /**
245 : * Gives the global navcell coords, and the squared distance to the (i0,j0)
246 : * navcell, of whichever navcell inside the given region and inside the given goal
247 : * is closest to (i0,j0)
248 : * Returns true if the goal is inside the region, false otherwise.
249 : */
250 1353 : bool HierarchicalPathfinder::Chunk::RegionNearestNavcellInGoal(std::uint16_t r, std::uint16_t i0,
251 : std::uint16_t j0, const PathGoal& goal, std::uint16_t& iOut, std::uint16_t& jOut,
252 : std::uint32_t& dist2Best) const
253 : {
254 : // TODO: this should be optimized further.
255 : // Most used cases empirically seem to be SQUARE, INVERTED_CIRCLE and then POINT and CIRCLE somehwat equally
256 1353 : iOut = 0;
257 1353 : jOut = 0;
258 1353 : dist2Best = std::numeric_limits<std::uint32_t>::max();
259 :
260 : // Calculate the navcell that contains the center of the goal.
261 1353 : int gi = (goal.x >> Pathfinding::NAVCELL_SIZE_LOG2).ToInt_RoundToNegInfinity();
262 1353 : int gj = (goal.z >> Pathfinding::NAVCELL_SIZE_LOG2).ToInt_RoundToNegInfinity();
263 :
264 1353 : switch(goal.type)
265 : {
266 0 : case PathGoal::POINT:
267 0 : {
268 : // i and j can be equal to CHUNK_SIZE on the top and right borders of the map,
269 : // specially when mapSize is a multiple of CHUNK_SIZE
270 0 : int i = std::min((int)CHUNK_SIZE - 1, gi - m_ChunkI * CHUNK_SIZE);
271 0 : int j = std::min((int)CHUNK_SIZE - 1, gj - m_ChunkJ * CHUNK_SIZE);
272 0 : if (m_Regions[j][i] == r)
273 : {
274 0 : iOut = gi;
275 0 : jOut = gj;
276 0 : dist2Best = (gi - i0)*(gi - i0)
277 0 : + (gj - j0)*(gj - j0);
278 0 : return true;
279 : }
280 : return false;
281 : }
282 1233 : case PathGoal::CIRCLE:
283 1233 : case PathGoal::SQUARE:
284 1233 : {
285 : // restrict ourselves to a square surrounding the goal.
286 1233 : int radius = (std::max(goal.hw*3/2,goal.hh*3/2) >> Pathfinding::NAVCELL_SIZE_LOG2).ToInt_RoundToInfinity();
287 1233 : int imin = std::max(0, gi-m_ChunkI*CHUNK_SIZE-radius);
288 1233 : int imax = std::min((int)CHUNK_SIZE, gi-m_ChunkI*CHUNK_SIZE+radius+1);
289 1233 : int jmin = std::max(0, gj-m_ChunkJ*CHUNK_SIZE-radius);
290 1233 : int jmax = std::min((int)CHUNK_SIZE, gj-m_ChunkJ*CHUNK_SIZE+radius+1);
291 1233 : bool found = false;
292 1233 : std::uint32_t dist2 = std::numeric_limits<std::uint32_t>::max();
293 39342 : for (std::uint16_t j = jmin; j < jmax; ++j)
294 : {
295 1250790 : for (std::uint16_t i = imin; i < imax; ++i)
296 : {
297 1212681 : if (m_Regions[j][i] != r)
298 1447 : continue;
299 :
300 1211234 : if (found)
301 : {
302 874906 : dist2 = (i + m_ChunkI*CHUNK_SIZE - i0)*(i + m_ChunkI*CHUNK_SIZE - i0)
303 874906 : + (j + m_ChunkJ*CHUNK_SIZE - j0)*(j + m_ChunkJ*CHUNK_SIZE - j0);
304 874906 : if (dist2 >= dist2Best)
305 876924 : continue;
306 : }
307 :
308 334310 : if (goal.NavcellContainsGoal(m_ChunkI * CHUNK_SIZE + i, m_ChunkJ * CHUNK_SIZE + j))
309 : {
310 6253 : if (!found)
311 : {
312 1009 : found = true;
313 1009 : dist2 = (i + m_ChunkI*CHUNK_SIZE - i0)*(i + m_ChunkI*CHUNK_SIZE - i0)
314 1009 : + (j + m_ChunkJ*CHUNK_SIZE - j0)*(j + m_ChunkJ*CHUNK_SIZE - j0);
315 : }
316 6253 : iOut = i + m_ChunkI*CHUNK_SIZE;
317 6253 : jOut = j + m_ChunkJ*CHUNK_SIZE;
318 6253 : dist2Best = dist2;
319 : }
320 : }
321 : }
322 : return found;
323 : }
324 : case PathGoal::INVERTED_CIRCLE:
325 : case PathGoal::INVERTED_SQUARE:
326 : {
327 : bool found = false;
328 : std::uint32_t dist2 = std::numeric_limits<std::uint32_t>::max();
329 : // loop over all navcells.
330 11452 : for (std::uint16_t j = 0; j < CHUNK_SIZE; ++j)
331 : {
332 754829 : for (std::uint16_t i = 0; i < CHUNK_SIZE; ++i)
333 : {
334 743497 : if (m_Regions[j][i] != r)
335 74599 : continue;
336 :
337 668898 : if (found)
338 : {
339 668526 : dist2 = (i + m_ChunkI*CHUNK_SIZE - i0)*(i + m_ChunkI*CHUNK_SIZE - i0)
340 668526 : + (j + m_ChunkJ*CHUNK_SIZE - j0)*(j + m_ChunkJ*CHUNK_SIZE - j0);
341 668526 : if (dist2 >= dist2Best)
342 629103 : continue;
343 : }
344 :
345 39795 : if (goal.NavcellContainsGoal(m_ChunkI * CHUNK_SIZE + i, m_ChunkJ * CHUNK_SIZE + j))
346 : {
347 31402 : if (!found)
348 : {
349 120 : found = true;
350 120 : dist2 = (i + m_ChunkI*CHUNK_SIZE - i0)*(i + m_ChunkI*CHUNK_SIZE - i0)
351 120 : + (j + m_ChunkJ*CHUNK_SIZE - j0)*(j + m_ChunkJ*CHUNK_SIZE - j0);
352 : }
353 31402 : iOut = i + m_ChunkI*CHUNK_SIZE;
354 31402 : jOut = j + m_ChunkJ*CHUNK_SIZE;
355 31402 : dist2Best = dist2;
356 : }
357 : }
358 : }
359 : return found;
360 : }
361 : }
362 : return false;
363 : }
364 :
365 14 : HierarchicalPathfinder::HierarchicalPathfinder() : m_DebugOverlay(NULL)
366 : {
367 14 : }
368 :
369 14 : HierarchicalPathfinder::~HierarchicalPathfinder()
370 : {
371 14 : SAFE_DELETE(m_DebugOverlay);
372 14 : }
373 :
374 0 : void HierarchicalPathfinder::SetDebugOverlay(bool enabled, const CSimContext* simContext)
375 : {
376 0 : if (enabled && !m_DebugOverlay)
377 : {
378 0 : m_DebugOverlay = new TerrainTextureOverlay{Pathfinding::NAVCELLS_PER_TERRAIN_TILE,
379 0 : std::bind_front(BuildTextureRGBA, std::ref(*this))};
380 0 : m_DebugOverlayLines.clear();
381 0 : m_SimContext = simContext;
382 0 : AddDebugEdges(GetPassabilityClass("default"));
383 : }
384 0 : else if (!enabled && m_DebugOverlay)
385 : {
386 0 : SAFE_DELETE(m_DebugOverlay);
387 0 : m_DebugOverlayLines.clear();
388 0 : m_SimContext = NULL;
389 : }
390 0 : }
391 :
392 0 : void HierarchicalPathfinder::RenderSubmit(SceneCollector& collector)
393 : {
394 0 : if (!m_DebugOverlay)
395 : return;
396 :
397 0 : for (size_t i = 0; i < m_DebugOverlayLines.size(); ++i)
398 0 : collector.Submit(&m_DebugOverlayLines[i]);
399 : }
400 :
401 12 : void HierarchicalPathfinder::Recompute(Grid<NavcellData>* grid,
402 : const std::map<std::string, pass_class_t>& nonPathfindingPassClassMasks,
403 : const std::map<std::string, pass_class_t>& pathfindingPassClassMasks)
404 : {
405 12 : PROFILE2("Hierarchical Recompute");
406 :
407 12 : m_PassClassMasks = pathfindingPassClassMasks;
408 :
409 12 : std::map<std::string, pass_class_t> allPassClasses = m_PassClassMasks;
410 12 : allPassClasses.insert(nonPathfindingPassClassMasks.begin(), nonPathfindingPassClassMasks.end());
411 :
412 12 : m_W = grid->m_W;
413 12 : m_H = grid->m_H;
414 :
415 : // else the std::uint8_t Chunk::m_ChunkI will overflow
416 12 : ENSURE((grid->m_W + CHUNK_SIZE - 1) / CHUNK_SIZE < 256 &&
417 : (grid->m_H + CHUNK_SIZE - 1) / CHUNK_SIZE < 256);
418 :
419 : // Divide grid into chunks with round-to-positive-infinity
420 12 : m_ChunksW = (grid->m_W + CHUNK_SIZE - 1) / CHUNK_SIZE;
421 12 : m_ChunksH = (grid->m_H + CHUNK_SIZE - 1) / CHUNK_SIZE;
422 :
423 12 : m_Chunks.clear();
424 12 : m_Edges.clear();
425 :
426 : // Reset global regions.
427 12 : m_NextGlobalRegionID = 1;
428 :
429 102 : for (auto& passClassMask : allPassClasses)
430 : {
431 90 : pass_class_t passClass = passClassMask.second;
432 :
433 : // Compute the regions within each chunk
434 90 : m_Chunks[passClass].resize(m_ChunksW*m_ChunksH);
435 759 : for (int cj = 0; cj < m_ChunksH; ++cj)
436 : {
437 5910 : for (int ci = 0; ci < m_ChunksW; ++ci)
438 : {
439 5241 : m_Chunks[passClass].at(cj*m_ChunksW + ci).InitRegions(ci, cj, grid, passClass);
440 : }
441 : }
442 :
443 : // Construct the search graph over the regions.
444 90 : EdgesMap& edges = m_Edges[passClass];
445 90 : RecomputeAllEdges(passClass, edges);
446 :
447 : // Spread global regions.
448 90 : std::map<RegionID, GlobalRegionID>& globalRegion = m_GlobalRegions[passClass];
449 90 : globalRegion.clear();
450 759 : for (std::uint8_t cj = 0; cj < m_ChunksH; ++cj)
451 5910 : for (std::uint8_t ci = 0; ci < m_ChunksW; ++ci)
452 8163 : for (std::uint16_t rid : GetChunk(ci, cj, passClass).m_RegionsID)
453 : {
454 2922 : RegionID reg{ci,cj,rid};
455 2922 : if (globalRegion.find(reg) == globalRegion.end())
456 : {
457 53 : GlobalRegionID ID = m_NextGlobalRegionID++;
458 :
459 53 : globalRegion.insert({ reg, ID });
460 : // Avoid creating an empty link if possible, FindReachableRegions uses [] which calls the default constructor.
461 53 : if (edges.find(reg) != edges.end())
462 : {
463 49 : std::set<RegionID> reachable;
464 49 : FindReachableRegions(reg, reachable, passClass);
465 2967 : for (const RegionID& region : reachable)
466 2918 : globalRegion.insert({ region, ID });
467 49 : }
468 : }
469 : }
470 : }
471 :
472 12 : if (m_DebugOverlay)
473 : {
474 0 : m_DebugOverlayLines.clear();
475 0 : AddDebugEdges(GetPassabilityClass("default"));
476 : }
477 12 : }
478 :
479 7 : void HierarchicalPathfinder::Update(Grid<NavcellData>* grid, const Grid<std::uint8_t>& dirtinessGrid)
480 : {
481 7 : PROFILE3("Hierarchical Update");
482 :
483 7 : ASSERT(m_NextGlobalRegionID < std::numeric_limits<GlobalRegionID>::max());
484 :
485 7 : std::map<pass_class_t, std::vector<RegionID> > needNewGlobalRegionMap;
486 :
487 : // Algorithm for the partial update:
488 : // 1. Loop over chunks.
489 : // 2. For any dirty chunk:
490 : // - remove all regions from the global region map
491 : // - remove all edges, by removing the neighbor connection with them and then deleting us
492 : // - recreate regions inside the chunk
493 : // - reconnect the regions. We may do too much work if we reconnect with a dirty chunk, but that's fine.
494 : // 3. Recreate global regions.
495 : // This means that if any chunk changes, we may need to flood (at most once) the whole map.
496 : // That's quite annoying, but I can't think of an easy way around it.
497 : // If we could be sure that a region's topology hasn't changed, we could skip removing its global region
498 : // but that's non trivial as we have no easy way to determine said topology (regions could "switch" IDs on update for now).
499 28 : for (std::uint8_t cj = 0; cj < m_ChunksH; ++cj)
500 : {
501 21 : int j0 = cj * CHUNK_SIZE;
502 21 : int j1 = std::min(j0 + CHUNK_SIZE, (int)dirtinessGrid.m_H);
503 84 : for (std::uint8_t ci = 0; ci < m_ChunksW; ++ci)
504 : {
505 : // Skip chunks where no navcells are dirty.
506 63 : int i0 = ci * CHUNK_SIZE;
507 63 : int i1 = std::min(i0 + CHUNK_SIZE, (int)dirtinessGrid.m_W);
508 126 : if (!dirtinessGrid.any_set_in_square(i0, j0, i1, j1))
509 33 : continue;
510 :
511 90 : for (const std::pair<const std::string, pass_class_t>& passClassMask : m_PassClassMasks)
512 : {
513 60 : pass_class_t passClass = passClassMask.second;
514 60 : Chunk& a = m_Chunks[passClass].at(ci + cj*m_ChunksW);
515 :
516 : // Clean up edges and global region ID
517 60 : EdgesMap& edgeMap = m_Edges[passClass];
518 94 : for (std::uint16_t i : a.m_RegionsID)
519 : {
520 34 : RegionID reg{ci, cj, i};
521 34 : m_GlobalRegions[passClass].erase(reg);
522 124 : for (const RegionID& neighbor : edgeMap[reg])
523 : {
524 90 : edgeMap[neighbor].erase(reg);
525 90 : if (edgeMap[neighbor].empty())
526 90 : edgeMap.erase(neighbor);
527 : }
528 34 : edgeMap.erase(reg);
529 : }
530 :
531 : // Recompute regions inside this chunk.
532 60 : a.InitRegions(ci, cj, grid, passClass);
533 :
534 94 : for (std::uint16_t i : a.m_RegionsID)
535 34 : needNewGlobalRegionMap[passClass].push_back(RegionID{ci, cj, i});
536 :
537 60 : UpdateEdges(ci, cj, passClass, edgeMap);
538 : }
539 : }
540 : }
541 :
542 7 : UpdateGlobalRegions(needNewGlobalRegionMap);
543 :
544 7 : if (m_DebugOverlay)
545 : {
546 0 : m_DebugOverlayLines.clear();
547 0 : AddDebugEdges(GetPassabilityClass("default"));
548 : }
549 7 : }
550 :
551 9326 : void HierarchicalPathfinder::ComputeNeighbors(EdgesMap& edges, Chunk& a, Chunk& b, bool transpose, bool opposite) const
552 : {
553 : // For each edge between chunks, we loop over every adjacent pair of
554 : // navcells in the two chunks. If they are both in valid regions
555 : // (i.e. are passable navcells) then add a graph edge between those regions.
556 : // (We don't need to test for duplicates since EdgesMap already uses a
557 : // std::set which will drop duplicate entries.)
558 : // But as set.insert can be quite slow on large collection, and that we usually
559 : // try to insert the same values, we cache the previous one for a fast test.
560 9326 : RegionID raPrev(0,0,0);
561 9326 : RegionID rbPrev(0,0,0);
562 904622 : for (int k = 0; k < CHUNK_SIZE; ++k)
563 : {
564 895296 : std::uint8_t aSide = opposite ? CHUNK_SIZE - 1 : 0;
565 895296 : std::uint8_t bSide = CHUNK_SIZE - 1 - aSide;
566 895296 : RegionID ra = transpose ? a.Get(k, aSide) : a.Get(aSide, k);
567 895296 : RegionID rb = transpose ? b.Get(k, bSide) : b.Get(bSide, k);
568 895296 : if (ra.r && rb.r)
569 : {
570 951288 : if (ra == raPrev && rb == rbPrev)
571 473053 : continue;
572 5179 : edges[ra].insert(rb);
573 5179 : edges[rb].insert(ra);
574 5179 : raPrev = ra;
575 5179 : rbPrev = rb;
576 : }
577 : }
578 9326 : }
579 :
580 : /**
581 : * Connect a chunk's regions to their neighbors. Not optimised for global recomputing.
582 : */
583 60 : void HierarchicalPathfinder::UpdateEdges(std::uint8_t ci, std::uint8_t cj, pass_class_t passClass,
584 : EdgesMap& edges)
585 : {
586 60 : std::vector<Chunk>& chunks = m_Chunks[passClass];
587 :
588 60 : Chunk& a = chunks.at(cj*m_ChunksW + ci);
589 :
590 60 : if (ci > 0)
591 60 : ComputeNeighbors(edges, a, chunks.at(cj*m_ChunksW + (ci-1)), false, false);
592 :
593 60 : if (ci < m_ChunksW-1)
594 42 : ComputeNeighbors(edges, a, chunks.at(cj*m_ChunksW + (ci+1)), false, true);
595 :
596 60 : if (cj > 0)
597 40 : ComputeNeighbors(edges, a, chunks.at((cj-1)*m_ChunksW + ci), true, false);
598 :
599 60 : if (cj < m_ChunksH - 1)
600 40 : ComputeNeighbors(edges, a, chunks.at((cj+1)*m_ChunksW + ci), true, true);
601 60 : }
602 :
603 : /**
604 : * Find edges between regions in all chunks, in an optimised manner (only look at top/left)
605 : */
606 90 : void HierarchicalPathfinder::RecomputeAllEdges(pass_class_t passClass, EdgesMap& edges)
607 : {
608 90 : std::vector<Chunk>& chunks = m_Chunks[passClass];
609 :
610 90 : edges.clear();
611 :
612 759 : for (int cj = 0; cj < m_ChunksH; ++cj)
613 : {
614 5910 : for (int ci = 0; ci < m_ChunksW; ++ci)
615 : {
616 5241 : Chunk& a = chunks.at(cj*m_ChunksW + ci);
617 :
618 5241 : if (ci > 0)
619 4572 : ComputeNeighbors(edges, a, chunks.at(cj*m_ChunksW + (ci-1)), false, false);
620 :
621 5241 : if (cj > 0)
622 4572 : ComputeNeighbors(edges, a, chunks.at((cj-1)*m_ChunksW + ci), true, false);
623 : }
624 : }
625 90 : }
626 :
627 : /**
628 : * Debug visualisation of graph edges between regions.
629 : */
630 0 : void HierarchicalPathfinder::AddDebugEdges(pass_class_t passClass)
631 : {
632 0 : const EdgesMap& edges = m_Edges[passClass];
633 0 : const std::vector<Chunk>& chunks = m_Chunks[passClass];
634 :
635 0 : for (auto& edge : edges)
636 : {
637 0 : for (const RegionID& region: edge.second)
638 : {
639 : // Draw a line between the two regions' centers
640 :
641 0 : int i0, j0, i1, j1;
642 0 : chunks[edge.first.cj * m_ChunksW + edge.first.ci].RegionCenter(edge.first.r, i0, j0);
643 0 : chunks[region.cj * m_ChunksW + region.ci].RegionCenter(region.r, i1, j1);
644 :
645 0 : CFixedVector2D a, b;
646 0 : Pathfinding::NavcellCenter(i0, j0, a.X, a.Y);
647 0 : Pathfinding::NavcellCenter(i1, j1, b.X, b.Y);
648 :
649 : // Push the endpoints inwards a little to avoid overlaps
650 0 : CFixedVector2D d = b - a;
651 0 : d.Normalize(entity_pos_t::FromInt(1));
652 0 : a += d;
653 0 : b -= d;
654 :
655 0 : std::vector<float> xz;
656 0 : xz.push_back(a.X.ToFloat());
657 0 : xz.push_back(a.Y.ToFloat());
658 0 : xz.push_back(b.X.ToFloat());
659 0 : xz.push_back(b.Y.ToFloat());
660 :
661 0 : m_DebugOverlayLines.emplace_back();
662 0 : m_DebugOverlayLines.back().m_Color = CColor(1.0, 1.0, 1.0, 1.0);
663 0 : SimRender::ConstructLineOnGround(*m_SimContext, xz, m_DebugOverlayLines.back(), true);
664 0 : }
665 : }
666 0 : }
667 :
668 7 : void HierarchicalPathfinder::UpdateGlobalRegions(const std::map<pass_class_t, std::vector<RegionID> >& needNewGlobalRegionMap)
669 : {
670 : // Use FindReachableRegions because we cannot be sure, even if we find a non-dirty chunk nearby,
671 : // that we weren't the only bridge connecting that chunk to the rest of the global region.
672 14 : for (const std::pair<const pass_class_t, std::vector<RegionID>>& regionsInNeed : needNewGlobalRegionMap)
673 : {
674 41 : for (const RegionID& reg : regionsInNeed.second)
675 : {
676 34 : std::map<RegionID, GlobalRegionID>& globalRegions = m_GlobalRegions[regionsInNeed.first];
677 : // If we have already been given a region, skip us.
678 34 : if (globalRegions.find(reg) != globalRegions.end())
679 25 : continue;
680 :
681 9 : std::set<RegionID> reachable;
682 9 : FindReachableRegions(reg, reachable, regionsInNeed.first);
683 :
684 9 : GlobalRegionID ID = m_NextGlobalRegionID++;
685 :
686 76 : for (const RegionID& regionId : reachable)
687 67 : globalRegions[regionId] = ID;
688 9 : }
689 : }
690 7 : }
691 :
692 404242 : HierarchicalPathfinder::RegionID HierarchicalPathfinder::Get(std::uint16_t i, std::uint16_t j, pass_class_t passClass) const
693 : {
694 404242 : int ci = i / CHUNK_SIZE;
695 404242 : int cj = j / CHUNK_SIZE;
696 404242 : ENSURE(ci < m_ChunksW && cj < m_ChunksH);
697 404242 : return m_Chunks.at(passClass)[cj*m_ChunksW + ci].Get(i % CHUNK_SIZE, j % CHUNK_SIZE);
698 : }
699 :
700 403415 : HierarchicalPathfinder::GlobalRegionID HierarchicalPathfinder::GetGlobalRegion(std::uint16_t i,
701 : std::uint16_t j, pass_class_t passClass) const
702 : {
703 403415 : return GetGlobalRegion(Get(i, j, passClass), passClass);
704 : }
705 :
706 404105 : HierarchicalPathfinder::GlobalRegionID HierarchicalPathfinder::GetGlobalRegion(RegionID region, pass_class_t passClass) const
707 : {
708 404105 : return region.r == 0 ? GlobalRegionID(0) : m_GlobalRegions.at(passClass).at(region);
709 : }
710 :
711 959 : void CreatePointGoalAt(std::uint16_t i, std::uint16_t j, PathGoal& goal)
712 : {
713 959 : PathGoal newGoal;
714 959 : newGoal.type = PathGoal::POINT;
715 959 : Pathfinding::NavcellCenter(i, j, newGoal.x, newGoal.z);
716 959 : goal = newGoal;
717 684 : }
718 :
719 964 : bool HierarchicalPathfinder::MakeGoalReachable(std::uint16_t i0, std::uint16_t j0, PathGoal& goal,
720 : pass_class_t passClass) const
721 : {
722 964 : PROFILE2("MakeGoalReachable");
723 :
724 965 : std::uint16_t iGoal, jGoal;
725 965 : Pathfinding::NearestNavcell(goal.x, goal.z, iGoal, jGoal, m_W, m_H);
726 :
727 965 : std::set<InterestingRegion, SortByBestToPoint> goalRegions(SortByBestToPoint(i0, j0));
728 : // This returns goal regions ordered by distance from the best navcell in each region.
729 965 : FindGoalRegionsAndBestNavcells(i0, j0, iGoal, jGoal, goal, goalRegions, passClass);
730 :
731 : // Because of the sorting above, we can stop as soon as the first reachable goal region is found.
732 964 : for (const InterestingRegion& region : goalRegions)
733 690 : if (GetGlobalRegion(region.region, passClass) == GetGlobalRegion(i0, j0, passClass))
734 : {
735 689 : iGoal = region.bestI;
736 689 : jGoal = region.bestJ;
737 :
738 : // No need to move reachable point goals.
739 689 : if (goal.type != PathGoal::POINT)
740 684 : CreatePointGoalAt(iGoal, jGoal, goal);
741 689 : return true;
742 : }
743 :
744 : // Goal wasn't reachable - get the closest navcell in the nearest reachable region.
745 274 : std::set<RegionID, SortByCenterToPoint> reachableRegions(SortByCenterToPoint(iGoal, jGoal));
746 274 : FindReachableRegions(Get(i0, j0, passClass), reachableRegions, passClass);
747 :
748 274 : FindNearestNavcellInRegions(reachableRegions, iGoal, jGoal, passClass);
749 275 : CreatePointGoalAt(iGoal, jGoal, goal);
750 275 : return false;
751 964 : }
752 :
753 :
754 0 : bool HierarchicalPathfinder::IsGoalReachable(std::uint16_t i0, std::uint16_t j0, const PathGoal& goal,
755 : pass_class_t passClass) const
756 : {
757 0 : PROFILE2("IsGoalReachable");
758 :
759 0 : std::uint16_t iGoal, jGoal;
760 0 : Pathfinding::NearestNavcell(goal.x, goal.z, iGoal, jGoal, m_W, m_H);
761 :
762 0 : std::set<InterestingRegion, SortByBestToPoint> goalRegions(SortByBestToPoint(i0, j0));
763 : // This returns goal regions ordered by distance from the best navcell in each region.
764 0 : FindGoalRegionsAndBestNavcells(i0, j0, iGoal, jGoal, goal, goalRegions, passClass);
765 :
766 : // Because of the sorting above, we can stop as soon as the first reachable goal region is found.
767 0 : for (const InterestingRegion& region : goalRegions)
768 0 : if (GetGlobalRegion(region.region, passClass) == GetGlobalRegion(i0, j0, passClass))
769 0 : return true;
770 : return false;
771 0 : }
772 :
773 17 : void HierarchicalPathfinder::FindNearestPassableNavcell(std::uint16_t& i, std::uint16_t& j,
774 : pass_class_t passClass) const
775 : {
776 17 : std::set<RegionID, SortByCenterToPoint> regions(SortByCenterToPoint(i, j));
777 :
778 : // Construct a set of all regions of all chunks for this pass class
779 170 : for (const Chunk& chunk : m_Chunks.at(passClass))
780 336 : for (int r : chunk.m_RegionsID)
781 183 : regions.insert(RegionID(chunk.m_ChunkI, chunk.m_ChunkJ, r));
782 :
783 17 : FindNearestNavcellInRegions(regions, i, j, passClass);
784 17 : }
785 :
786 292 : void HierarchicalPathfinder::FindNearestNavcellInRegions(
787 : const std::set<RegionID, SortByCenterToPoint>& regions, std::uint16_t& iGoal, std::uint16_t& jGoal,
788 : pass_class_t passClass) const
789 : {
790 292 : std::uint16_t bestI = iGoal, bestJ = jGoal; // Somewhat sensible default-values should regions() be passed empty.
791 292 : std::uint32_t bestDist = std::numeric_limits<std::uint32_t>::max();
792 :
793 : // Because regions are sorted by increasing distance, we can ignore regions that are obviously farther than the current best point.
794 : // Since regions are squares, that happens when the center of a region is at least sqrt(2) * CHUNK_SIZE farther than the current best point.
795 : // Add one to avoid cases where the center navcell is actually slightly off-center (= CHUNK_SIZE is even)
796 292 : std::uint32_t maxDistFromBest = (fixed::FromInt(3) / 2 * CHUNK_SIZE).ToInt_RoundToInfinity() + 1;
797 : // TODO: update to static_assert with constexpr
798 292 : ENSURE(maxDistFromBest < std::numeric_limits<std::uint16_t>::max());
799 292 : maxDistFromBest *= maxDistFromBest;
800 :
801 1344 : for (const RegionID& region : regions)
802 : {
803 1344 : std::uint32_t chunkDist = region.DistanceTo(iGoal, jGoal);
804 : // This might overflow, but only if we are already close to the maximal possible distance, so the condition would probably be false anyways.
805 : // It's also a bit pessimistic, so we'll still consider a few too many regions.
806 1344 : if (bestDist < std::numeric_limits<std::uint32_t>::max() &&
807 1052 : chunkDist > maxDistFromBest + bestDist)
808 : {
809 : break; // Break, the set is ordered by increased distance so a closer region will not be found.
810 : }
811 :
812 1052 : int ri, rj;
813 1052 : std::uint32_t dist;
814 1052 : GetChunk(region.ci, region.cj, passClass).RegionNavcellNearest(region.r, iGoal, jGoal, ri, rj, dist);
815 1052 : if (dist < bestDist)
816 : {
817 292 : bestI = ri;
818 292 : bestJ = rj;
819 292 : bestDist = dist;
820 : }
821 : }
822 292 : iGoal = bestI;
823 292 : jGoal = bestJ;
824 292 : }
825 :
826 965 : void HierarchicalPathfinder::FindGoalRegionsAndBestNavcells(std::uint16_t i0, std::uint16_t j0,
827 : std::uint16_t gi, std::uint16_t gj, const PathGoal& goal,
828 : std::set<InterestingRegion, SortByBestToPoint>& regions, pass_class_t passClass) const
829 : {
830 965 : if (goal.type == PathGoal::POINT)
831 : {
832 278 : RegionID region = Get(gi, gj, passClass);
833 277 : if (region.r > 0)
834 5 : regions.insert({region, gi, gj});
835 277 : return;
836 : }
837 :
838 : // For non-point cases, we'll test each region inside the bounds of the goal.
839 : // we might occasionally test a few too many for circles but it's not too bad.
840 : // Note that this also works in the Inverse-circle / Inverse-square case
841 : // Since our ranges are inclusive, we will necessarily test at least the perimeter/outer bound of the goal.
842 : // If we find a navcell, great, if not, well then we'll be surrounded by an impassable barrier.
843 : // Since in the Inverse-XX case we're supposed to start inside, then we can't ever reach the goal so it's good enough.
844 : // It's not worth it to skip the "inner" regions since we'd need ranges above CHUNK_SIZE for that to start mattering
845 : // (and even then not always) and that just doesn't happen for Inverse-XX goals
846 1313 : int size = (std::max(goal.hh, goal.hw) * 3 / 2).ToInt_RoundToInfinity();
847 :
848 687 : std::uint16_t bestI, bestJ;
849 687 : std::uint32_t c; // Unused.
850 :
851 2196 : for (std::uint8_t sz = std::max(0,(gj - size) / CHUNK_SIZE);
852 3204 : sz <= std::min(m_ChunksH-1, (gj + size + 1) / CHUNK_SIZE); ++sz)
853 : {
854 3182 : for (std::uint8_t sx = std::max(0,(gi - size) / CHUNK_SIZE);
855 4534 : sx <= std::min(m_ChunksW-1, (gi + size + 1) / CHUNK_SIZE); ++sx)
856 : {
857 1354 : const Chunk& chunk = GetChunk(sx, sz, passClass);
858 2706 : for (std::uint16_t i : chunk.m_RegionsID)
859 1352 : if (chunk.RegionNearestNavcellInGoal(i, i0, j0, goal, bestI, bestJ, c))
860 1129 : regions.insert({RegionID{sx, sz, i}, bestI, bestJ});
861 : }
862 : }
863 : }
864 :
865 0 : void HierarchicalPathfinder::FillRegionOnGrid(const RegionID& region, pass_class_t passClass,
866 : std::uint16_t value, Grid<std::uint16_t>& grid) const
867 : {
868 0 : ENSURE(grid.m_W == m_W && grid.m_H == m_H);
869 :
870 0 : int i0 = region.ci * CHUNK_SIZE;
871 0 : int j0 = region.cj * CHUNK_SIZE;
872 :
873 0 : const Chunk& c = m_Chunks.at(passClass)[region.cj * m_ChunksW + region.ci];
874 :
875 0 : for (int j = 0; j < CHUNK_SIZE; ++j)
876 0 : for (int i = 0; i < CHUNK_SIZE; ++i)
877 0 : if (c.m_Regions[j][i] == region.r)
878 0 : grid.set(i0 + i, j0 + j, value);
879 0 : }
880 :
881 0 : Grid<std::uint16_t> HierarchicalPathfinder::GetConnectivityGrid(pass_class_t passClass) const
882 : {
883 0 : Grid<std::uint16_t> connectivityGrid(m_W, m_H);
884 0 : connectivityGrid.reset();
885 :
886 0 : std::uint16_t idx = 1;
887 :
888 0 : for (std::uint16_t i = 0; i < m_W; ++i)
889 : {
890 0 : for (std::uint16_t j = 0; j < m_H; ++j)
891 : {
892 0 : if (connectivityGrid.get(i, j) != 0)
893 0 : continue;
894 :
895 0 : RegionID from = Get(i, j, passClass);
896 0 : if (from.r == 0)
897 0 : continue;
898 :
899 0 : std::set<RegionID> reachable;
900 0 : FindReachableRegions(from, reachable, passClass);
901 :
902 0 : for (const RegionID& region : reachable)
903 0 : FillRegionOnGrid(region, passClass, idx, connectivityGrid);
904 :
905 0 : ++idx;
906 0 : }
907 : }
908 :
909 0 : return connectivityGrid;
910 0 : }
|