-
Notifications
You must be signed in to change notification settings - Fork 532
Expand file tree
/
Copy pathPathFinder.cpp
More file actions
2026 lines (1720 loc) · 67.3 KB
/
PathFinder.cpp
File metadata and controls
2026 lines (1720 loc) · 67.3 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Meta Platforms, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "PathFinder.h"
#include <cstddef>
#include <numeric>
#include <stack>
#include <unordered_map>
#include <Magnum/Magnum.h>
#include <Magnum/Math/Vector3.h>
#include <Magnum/EigenIntegration/GeometryIntegration.h>
#include <Magnum/EigenIntegration/Integration.h>
#include <Corrade/Containers/Optional.h>
#include <Corrade/Utility/Path.h>
#include <cstdio>
// NOLINTNEXTLINE
#define _USE_MATH_DEFINES
#include <cmath>
#include <limits>
#include <utility>
#include "esp/assets/MeshData.h"
#include "esp/core/Esp.h"
#include "DetourCommon.h"
#include "DetourNavMesh.h"
#include "DetourNavMeshBuilder.h"
#include "DetourNavMeshQuery.h"
#include "DetourNode.h"
#include "Recast.h"
#include <rapidjson/document.h>
#include "esp/core/Check.h"
#include "esp/io/Json.h"
#include "esp/io/JsonAllTypes.h"
namespace Mn = Magnum;
namespace Cr = Corrade;
namespace esp {
namespace nav {
bool operator==(const NavMeshSettings& a, const NavMeshSettings& b) {
#define CLOSE(name) (std::abs(a.name - b.name) < 1e-5)
#define EQ(name) (a.name == b.name)
return CLOSE(cellSize) && CLOSE(cellHeight) && CLOSE(agentHeight) &&
CLOSE(agentRadius) && CLOSE(agentMaxClimb) && CLOSE(agentMaxSlope) &&
CLOSE(regionMinSize) && CLOSE(regionMinSize) && CLOSE(edgeMaxLen) &&
CLOSE(edgeMaxError) && CLOSE(vertsPerPoly) &&
CLOSE(detailSampleDist) && CLOSE(detailSampleMaxError) &&
EQ(filterLowHangingObstacles) && EQ(filterLedgeSpans) &&
EQ(filterWalkableLowHeightSpans) && EQ(includeStaticObjects);
#undef CLOSE
#undef EQ
}
bool operator!=(const NavMeshSettings& a, const NavMeshSettings& b) {
return !(a == b);
}
void NavMeshSettings::readFromJSON(const std::string& jsonFile) {
if (!Corrade::Utility::Path::exists(jsonFile.data())) {
ESP_ERROR() << "File" << jsonFile << "not found.";
return;
}
try {
auto newDoc = esp::io::parseJsonFile(jsonFile);
esp::io::fromJsonValue(newDoc, *this);
} catch (...) {
ESP_ERROR() << "Failed to parse keyframes from" << jsonFile << ".";
}
}
void NavMeshSettings::writeToJSON(const std::string& jsonFile) const {
rapidjson::Document d(rapidjson::kObjectType);
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
auto jsonObj = esp::io::toJsonValue(*this, allocator);
d.Swap(jsonObj);
ESP_CHECK(!d.ObjectEmpty(), "Error writing JSON. Shouldn't happen.");
const float maxDecimalPlaces = 7;
auto ok = esp::io::writeJsonToFile(d, jsonFile, true, maxDecimalPlaces);
ESP_CHECK(ok, "writeSavedKeyframesToFile: unable to write to " << jsonFile);
}
struct MultiGoalShortestPath::Impl {
std::vector<vec3f> requestedEnds;
std::vector<dtPolyRef> endRefs;
//! Tracks whether an endpoint is valid or not as determined by setup to avoid
//! extra work or issues later.
std::vector<bool> endIsValid;
std::vector<vec3f> pathEnds;
std::vector<float> minTheoreticalDist;
vec3f prevRequestedStart = vec3f::Zero();
};
MultiGoalShortestPath::MultiGoalShortestPath()
: pimpl_{spimpl::make_unique_impl<Impl>()} {};
void MultiGoalShortestPath::setRequestedEnds(
const std::vector<vec3f>& newEnds) {
pimpl_->endRefs.clear();
pimpl_->pathEnds.clear();
pimpl_->requestedEnds = newEnds;
pimpl_->minTheoreticalDist.assign(newEnds.size(), 0);
}
const std::vector<vec3f>& MultiGoalShortestPath::getRequestedEnds() const {
return pimpl_->requestedEnds;
}
namespace {
template <typename T>
std::tuple<dtStatus, dtPolyRef, vec3f> projectToPoly(
const T& pt,
const dtNavMeshQuery* navQuery,
const dtQueryFilter* filter) {
// Defines size of the bounding box to search in for the nearest polygon. If
// there is no polygon inside the bounding box, the status is set to failure
// and polyRef == 0
constexpr float polyPickExt[3] = {2, 4, 2}; // [2 * dx, 2 * dy, 2 * dz]
dtPolyRef polyRef = 0;
// Initialize with all NANs at dtStatusSucceed(status) == true does NOT mean
// that it found a point to project to..........
vec3f polyXYZ = vec3f::Constant(Mn::Constants::nan());
dtStatus status = navQuery->findNearestPoly(pt.data(), polyPickExt, filter,
&polyRef, polyXYZ.data());
// So let's call it a failure if it didn't actually find a point....
if (std::isnan(polyXYZ[0]))
status = DT_FAILURE;
return std::make_tuple(status, polyRef, polyXYZ);
}
} // namespace
namespace impl {
// some systems lack this typedef (e.g. emscripten build)
typedef unsigned short int ushort; // NOLINT
//! (flag & flag) operator wrapper for function pointers
inline ushort andFlag(ushort curFlags, ushort flag) {
return curFlags & flag;
}
//! (flag | flag) operator wrapper for function pointers
inline ushort orFlag(ushort curFlags, ushort flag) {
return curFlags | flag;
}
// Runs connected component analysis on the navmesh to figure out which polygons
// are connected This gives O(1) lookup for if a path between two polygons
// exists or not
// Takes O(npolys) to construct
class IslandSystem {
public:
IslandSystem(const dtNavMesh* navMesh, const dtQueryFilter* filter) {
std::vector<vec3f> islandVerts;
// Iterate over all tiles
for (int iTile = 0; iTile < navMesh->getMaxTiles(); ++iTile) {
const dtMeshTile* tile = navMesh->getTile(iTile);
if (!tile)
continue;
// Iterate over all polygons in a tile
for (int jPoly = 0; jPoly < tile->header->polyCount; ++jPoly) {
// Get the polygon reference from the tile and polygon id
dtPolyRef startRef = navMesh->encodePolyId(tile->salt, iTile, jPoly);
// If the polygon ref is valid, and we haven't seen it yet,
// start connected component analysis from this polygon
if (navMesh->isValidPolyRef(startRef) &&
(polyToIsland_.find(startRef) == polyToIsland_.end())) {
uint32_t newIslandId = islandRadius_.size();
expandFrom(navMesh, filter, newIslandId, startRef, islandVerts);
// The radius is calculated as the max deviation from the mean for all
// points in the island
vec3f centroid = vec3f::Zero();
for (auto& v : islandVerts) {
centroid += v;
}
centroid /= islandVerts.size();
float maxRadius = 0.0;
for (auto& v : islandVerts) {
maxRadius = std::max(maxRadius, (v - centroid).norm());
}
islandRadius_.emplace_back(maxRadius);
}
}
}
}
inline bool hasConnection(dtPolyRef startRef, dtPolyRef endRef) const {
// If both polygons are on the same island, there must be a path between
// them
auto itStart = polyToIsland_.find(startRef);
if (itStart == polyToIsland_.end())
return false;
auto itEnd = polyToIsland_.find(endRef);
if (itEnd == polyToIsland_.end())
return false;
return itStart->second == itEnd->second;
}
//! check that island index is valid. indexOptional allows ID_UNDEFINED as
//! valid.
inline void assertValidIsland(int islandIndex, bool indexOptional = true) {
if (indexOptional && islandIndex == ID_UNDEFINED) {
return;
}
CORRADE_ASSERT(
(islandIndex >= 0 && islandIndex < islandRadius_.size()),
islandIndex << " not a valid index for this island system.", );
}
inline float islandRadius(int islandIndex) {
assertValidIsland(islandIndex, /*indexOptional*/ false);
return islandRadius_[islandIndex];
}
inline float polyIslandRadius(dtPolyRef ref) const {
auto itRef = polyToIsland_.find(ref);
if (itRef == polyToIsland_.end())
return 0.0;
return islandRadius_[itRef->second];
}
//! Get the area of an island.
//! islandIndex=ID_UNDEFINED specifies the full NavMesh area.
inline float getNavigableArea(int islandIndex) {
assertValidIsland(islandIndex);
return islandsToArea_[islandIndex];
}
inline int numIslands() const {
// TODO: better way to track number of islands
return islandRadius_.size();
}
/**
* @brief Sets a specified poly flag for all polys specified by the
* islandIndex.
*
* @param[in] navMesh The navmesh to operate on.
* @param[in] flag The flag to set or clear.
* @param[in] islandIndex Specify the island. islandIndex == ID_UNDEFINED
* specifies all islands.
* @param[in] setFlag If true, set the flag(currentFlags OR newFlag),
* otherwise clear the flag(currentFlags AND ~newFlag).
* @param[in] invert If true, set or clear the flag for all islands except the
* specified one. Has no effect if islandIndex == ID_UNDEFINED.
*/
inline void setPolyFlagForIsland(dtNavMesh* navMesh,
ushort flag,
int islandIndex = ID_UNDEFINED,
bool setFlag = true,
bool invert = false) {
assertValidIsland(islandIndex);
CORRADE_ASSERT(navMesh != nullptr, "invalid navMesh pointer", );
std::vector<int> islands;
if (islandIndex == ID_UNDEFINED) {
// all islands
islands.reserve(islandsToPolys_.size());
for (auto& itr : islandsToPolys_) {
islands.push_back(itr.first);
}
} else if (invert) {
// all but a single island
islands.reserve(islandsToPolys_.size());
for (auto& itr : islandsToPolys_) {
if (itr.first != islandIndex) {
islands.push_back(itr.first);
}
}
} else {
// a single island
islands.push_back(islandIndex);
}
// Pull this check and adjustment logic outside of the main loop
ushort (*op)(ushort, ushort) = nullptr;
op = setFlag ? orFlag : andFlag;
ushort modFlag = setFlag ? flag : ~flag;
// for each island
for (int island : islands) {
// for each poly
for (auto& polyRef : islandsToPolys_[island]) {
// get current flags
ushort f = 0;
navMesh->getPolyFlags(polyRef, &f);
// set the modified flags
navMesh->setPolyFlags(polyRef, op(f, modFlag));
}
}
}
/**
* @brief Sets a specified poly flag for all polys specified by the
* islandIndex within range of a given circle.
*
* @param[in] navMesh The navmesh to operate on.
* @param[in] flag The flag to set or clear.
* @param[in] circleCenter The center of the circle.
* @param[in] radius The radius of the circle.
* @param[in] islandIndex Specify the island. islandIndex == ID_UNDEFINED
* specifies all islands.
*/
inline void setPolyFlagForIslandCircle(dtNavMesh* navMesh,
ushort flag,
const vec3f& circleCenter,
const float radius,
int islandIndex = ID_UNDEFINED) {
assertValidIsland(islandIndex);
CORRADE_ASSERT(navMesh != nullptr, "invalid navMesh pointer", );
std::vector<int> islands;
float radSqr = radius * radius;
// all islands
islands.reserve(islandsToPolys_.size());
for (auto& itr : islandsToPolys_) {
islands.push_back(itr.first);
}
// for each island
for (int island : islands) {
// for each poly
for (auto& polyRef : islandsToPolys_[island]) {
// remove all off-island polys immediately
if (islandIndex != ID_UNDEFINED && islandIndex != island) {
// get current flags
ushort f = 0;
navMesh->getPolyFlags(polyRef, &f);
// set the modified flags
navMesh->setPolyFlags(polyRef, orFlag(f, flag));
continue;
}
// poly is on island, check if it is outside of range
const dtMeshTile* tile = nullptr;
const dtPoly* poly = nullptr;
navMesh->getTileAndPolyByRefUnsafe(polyRef, &tile, &poly);
// check if this poly is within range of the circle
bool inRange = false;
for (int iVert = 0; iVert < poly->vertCount; ++iVert) {
int nVert = (iVert + 1) % 3;
float tseg = 0;
float distSqr = dtDistancePtSegSqr2D(
circleCenter.data(),
&tile->verts[static_cast<size_t>(poly->verts[iVert]) * 3],
&tile->verts[static_cast<size_t>(poly->verts[nVert]) * 3], tseg);
if (distSqr < radSqr) {
// skip this poly if any edge is within radius
inRange = true;
break;
}
}
if (!inRange) {
// get current flags
ushort f = 0;
navMesh->getPolyFlags(polyRef, &f);
// set the modified flags
navMesh->setPolyFlags(polyRef, orFlag(f, flag));
}
}
}
}
// Some polygons have zero area for some reason. When we navigate into a zero
// area polygon, things crash. So we find all zero area polygons and mark
// them as disabled/not navigable.
// Also compute the NavMesh areas for later query.
void removeZeroAreaPolys(dtNavMesh* navMesh);
//! return the island for a navmesh polygon
inline int getPolyIsland(dtPolyRef polyRef) { return polyToIsland_[polyRef]; }
private:
//! map islands to area for quick query
std::unordered_map<uint32_t, float> islandsToArea_;
//! map islands to lists of polys for quick query and enumeration
std::unordered_map<uint32_t, std::vector<dtPolyRef>> islandsToPolys_;
//! map polygons to their island for quick look-up
std::unordered_map<dtPolyRef, uint32_t> polyToIsland_;
std::vector<float> islandRadius_;
void expandFrom(const dtNavMesh* navMesh,
const dtQueryFilter* filter,
const uint32_t newIslandId,
const dtPolyRef& startRef,
std::vector<vec3f>& islandVerts) {
islandsToPolys_[newIslandId].push_back(startRef);
polyToIsland_.emplace(startRef, newIslandId);
islandVerts.clear();
// Force std::stack to be implemented via an std::vector as linked
// lists are gross
std::stack<dtPolyRef, std::vector<dtPolyRef>> stack;
// Add the start ref to the stack
stack.push(startRef);
while (!stack.empty()) {
dtPolyRef ref = stack.top();
stack.pop();
const dtMeshTile* tile = nullptr;
const dtPoly* poly = nullptr;
navMesh->getTileAndPolyByRefUnsafe(ref, &tile, &poly);
for (int iVert = 0; iVert < poly->vertCount; ++iVert) {
islandVerts.emplace_back(Eigen::Map<vec3f>(
&tile->verts[static_cast<size_t>(poly->verts[iVert]) * 3]));
}
// Iterate over all neighbours
for (unsigned int iLink = poly->firstLink; iLink != DT_NULL_LINK;
iLink = tile->links[iLink].next) {
dtPolyRef neighbourRef = tile->links[iLink].ref;
// If we've already visited this poly, skip it!
if (polyToIsland_.find(neighbourRef) != polyToIsland_.end())
continue;
const dtMeshTile* neighbourTile = nullptr;
const dtPoly* neighbourPoly = nullptr;
navMesh->getTileAndPolyByRefUnsafe(neighbourRef, &neighbourTile,
&neighbourPoly);
// If a neighbour isn't walkable, don't add it
if (!filter->passFilter(neighbourRef, neighbourTile, neighbourPoly))
continue;
polyToIsland_.emplace(neighbourRef, newIslandId);
islandsToPolys_[newIslandId].push_back(neighbourRef);
stack.push(neighbourRef);
}
}
}
};
} // namespace impl
struct PathFinder::Impl {
Impl();
~Impl() = default;
bool build(const NavMeshSettings& bs,
const float* verts,
int nverts,
const int* tris,
int ntris,
const float* bmin,
const float* bmax);
bool build(const NavMeshSettings& bs, const esp::assets::MeshData& mesh);
vec3f getRandomNavigablePoint(int maxTries,
int islandIndex /*= ID_UNDEFINED*/);
vec3f getRandomNavigablePointAroundSphere(const vec3f& circleCenter,
float radius,
int maxTries,
int islandIndex /*= ID_UNDEFINED*/);
vec3f getRandomNavigablePointInCircle(const vec3f& circleCenter,
const float radius,
const int maxTries,
int islandIndex /*= ID_UNDEFINED*/);
bool findPath(ShortestPath& path);
bool findPath(MultiGoalShortestPath& path);
template <typename T>
T tryStep(const T& start, const T& end, bool allowSliding);
template <typename T>
T snapPoint(const T& pt, int islandIndex = ID_UNDEFINED);
template <typename T>
int getIsland(const T& pt) const;
bool loadNavMesh(const std::string& path);
bool saveNavMesh(const std::string& path);
bool isLoaded() const { return navMesh_ != nullptr; };
float getNavigableArea(int islandIndex /*= ID_UNDEFINED*/) const {
return islandSystem_->getNavigableArea(islandIndex);
};
int numIslands();
void seed(uint32_t newSeed);
float islandRadius(const vec3f& pt) const;
float islandRadius(int islandIndex) const;
float distanceToClosestObstacle(const vec3f& pt,
float maxSearchRadius = 2.0) const;
HitRecord closestObstacleSurfacePoint(const vec3f& pt,
float maxSearchRadius = 2.0) const;
bool isNavigable(const vec3f& pt, float maxYDelta = 0.5) const;
std::pair<vec3f, vec3f> bounds() const { return bounds_; };
Eigen::Matrix<bool, Eigen::Dynamic, Eigen::Dynamic>
getTopDownView(float metersPerPixel, float height, float eps) const;
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic>
getTopDownIslandView(float metersPerPixel, float height, float eps) const;
assets::MeshData::ptr getNavMeshData(int islandIndex /*= ID_UNDEFINED*/);
Cr::Containers::Optional<NavMeshSettings> getNavMeshSettings() const {
return navMeshSettings_;
}
private:
struct NavMeshDeleter {
void operator()(dtNavMesh* mesh) { dtFreeNavMesh(mesh); }
};
struct NavQueryDeleter {
void operator()(dtNavMeshQuery* query) { dtFreeNavMeshQuery(query); }
};
std::unique_ptr<dtNavMesh, NavMeshDeleter> navMesh_ = nullptr;
std::unique_ptr<dtNavMeshQuery, NavQueryDeleter> navQuery_ = nullptr;
std::unique_ptr<dtQueryFilter> filter_ = nullptr;
std::unique_ptr<impl::IslandSystem> islandSystem_ = nullptr;
//! Holds triangulated geom/topo. Generated when queried. Reset with
//! navQuery_.
std::unordered_map<int, assets::MeshData::ptr> islandMeshData_;
Cr::Containers::Optional<NavMeshSettings> navMeshSettings_;
std::pair<vec3f, vec3f> bounds_;
bool initNavQuery();
Cr::Containers::Optional<std::tuple<float, std::vector<vec3f>>>
findPathInternal(const vec3f& start,
dtPolyRef startRef,
const vec3f& pathStart,
const vec3f& end,
dtPolyRef endRef,
const vec3f& pathEnd);
bool findPathSetup(MultiGoalShortestPath& path,
dtPolyRef& startRef,
vec3f& pathStart);
};
namespace {
struct Workspace {
rcHeightfield* solid = nullptr;
unsigned char* triareas = nullptr;
rcCompactHeightfield* chf = nullptr;
rcContourSet* cset = nullptr;
rcPolyMesh* pmesh = nullptr;
rcPolyMeshDetail* dmesh = nullptr;
~Workspace() {
rcFreeHeightField(solid);
delete[] triareas;
rcFreeCompactHeightfield(chf);
rcFreeContourSet(cset);
rcFreePolyMesh(pmesh);
rcFreePolyMeshDetail(dmesh);
}
};
enum PolyAreas { POLYAREA_GROUND, POLYAREA_DOOR };
enum PolyFlags {
POLYFLAGS_WALK = 0x01, // walkable
POLYFLAGS_DOOR = 0x02, // ability to move through doors
POLYFLAGS_DISABLED = 0x04, // disabled polygon
POLYFLAGS_OFF_ISLAND =
0x08, // dynamically set to filter all but a specific island
POLYFLAGS_ALL = 0xffff // all abilities
};
} // namespace
PathFinder::Impl::Impl() {
filter_ = std::make_unique<dtQueryFilter>();
filter_->setIncludeFlags(POLYFLAGS_WALK);
filter_->setExcludeFlags(0);
}
bool PathFinder::Impl::build(const NavMeshSettings& bs,
const float* verts,
const int nverts,
const int* tris,
const int ntris,
const float* bmin,
const float* bmax) {
Workspace ws;
rcContext ctx;
//
// Step 1. Initialize build config.
//
// Init build configuration from GUI
rcConfig cfg{};
memset(&cfg, 0, sizeof(cfg));
cfg.cs = bs.cellSize;
cfg.ch = bs.cellHeight;
cfg.walkableSlopeAngle = bs.agentMaxSlope;
cfg.walkableHeight = static_cast<int>(ceilf(bs.agentHeight / cfg.ch));
cfg.walkableClimb = static_cast<int>(floorf(bs.agentMaxClimb / cfg.ch));
cfg.walkableRadius = static_cast<int>(ceilf(bs.agentRadius / cfg.cs));
cfg.maxEdgeLen = static_cast<int>(bs.edgeMaxLen / bs.cellSize);
cfg.maxSimplificationError = bs.edgeMaxError;
cfg.minRegionArea =
static_cast<int>(rcSqr(bs.regionMinSize)); // Note: area = size*size
cfg.mergeRegionArea =
static_cast<int>(rcSqr(bs.regionMergeSize)); // Note: area = size*size
cfg.maxVertsPerPoly = static_cast<int>(bs.vertsPerPoly);
cfg.detailSampleDist =
bs.detailSampleDist < 0.9f ? 0 : bs.cellSize * bs.detailSampleDist;
cfg.detailSampleMaxError = bs.cellHeight * bs.detailSampleMaxError;
// Set the area where the navigation will be build.
// Here the bounds of the input mesh are used, but the
// area could be specified by an user defined box, etc.
rcVcopy(cfg.bmin, bmin);
rcVcopy(cfg.bmax, bmax);
rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
ESP_DEBUG() << "Building navmesh with" << cfg.width << "x" << cfg.height
<< "cells";
//
// Step 2. Rasterize input polygon soup.
//
// Allocate voxel heightfield where we rasterize our input data to.
ws.solid = rcAllocHeightfield();
if (!ws.solid) {
ESP_ERROR() << "Out of memory for heightfield allocation";
return false;
}
if (!rcCreateHeightfield(&ctx, *ws.solid, cfg.width, cfg.height, cfg.bmin,
cfg.bmax, cfg.cs, cfg.ch)) {
ESP_ERROR() << "Could not create solid heightfield";
return false;
}
// Allocate array that can hold triangle area types.
// If you have multiple meshes you need to process, allocate
// and array which can hold the max number of triangles you need to process.
ws.triareas = new unsigned char[ntris];
if (!ws.triareas) {
ESP_ERROR() << "Out of memory for triareas" << ntris;
return false;
}
// Find triangles which are walkable based on their slope and rasterize them.
// If your input data is multiple meshes, you can transform them here,
// calculate the are type for each of the meshes and rasterize them.
memset(ws.triareas, 0, ntris * sizeof(unsigned char));
rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris,
ntris, ws.triareas);
if (!rcRasterizeTriangles(&ctx, verts, nverts, tris, ws.triareas, ntris,
*ws.solid, cfg.walkableClimb)) {
ESP_ERROR() << "Could not rasterize triangles.";
return false;
}
//
// Step 3. Filter walkables surfaces.
//
// Once all geoemtry is rasterized, we do initial pass of filtering to
// remove unwanted overhangs caused by the conservative rasterization
// as well as filter spans where the character cannot possibly stand.
if (bs.filterLowHangingObstacles)
rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *ws.solid);
if (bs.filterLedgeSpans)
rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *ws.solid);
if (bs.filterWalkableLowHeightSpans)
rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *ws.solid);
//
// Step 4. Partition walkable surface to simple regions.
//
// Compact the heightfield so that it is faster to handle from now on.
// This will result more cache coherent data as well as the neighbours
// between walkable cells will be calculated.
ws.chf = rcAllocCompactHeightfield();
if (!ws.chf) {
ESP_ERROR() << "Out of memory for compact heightfield";
return false;
}
if (!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb,
*ws.solid, *ws.chf)) {
ESP_ERROR() << "Could not build compact heightfield";
return false;
}
// Erode the walkable area by agent radius.
if (!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *ws.chf)) {
ESP_ERROR() << "Could not erode walkable area";
return false;
}
// // (Optional) Mark areas.
// const ConvexVolume* vols = geom->getConvexVolumes();
// for (int i = 0; i < geom->getConvexVolumeCount(); ++i)
// rcMarkConvexPolyArea(ctx, vols[i].verts, vols[i].nverts, vols[i].hmin,
// vols[i].hmax, (unsigned char)vols[i].area, *ws.chf);
// Partition the heightfield so that we can use simple algorithm later to
// triangulate the walkable areas. There are 3 martitioning methods, each with
// some pros and cons: 1) Watershed partitioning
// - the classic Recast partitioning
// - creates the nicest tessellation
// - usually slowest
// - partitions the heightfield into nice regions without holes or overlaps
// - the are some corner cases where this method creates produces holes and
// overlaps
// - holes may appear when a small obstacles is close to large open area
// (triangulation can handle this)
// - overlaps may occur if you have narrow spiral corridors (i.e stairs),
// this make triangulation to fail
// * generally the best choice if you precompute the nacmesh, use this if
// you have large open areas
// 2) Monotone partioning
// - fastest
// - partitions the heightfield into regions without holes and overlaps
// (guaranteed)
// - creates long thin polygons, which sometimes causes paths with detours
// * use this if you want fast navmesh generation
// 3) Layer partitoining
// - quite fast
// - partitions the heighfield into non-overlapping regions
// - relies on the triangulation code to cope with holes (thus slower than
// monotone partitioning)
// - produces better triangles than monotone partitioning
// - does not have the corner cases of watershed partitioning
// - can be slow and create a bit ugly tessellation (still better than
// monotone)
// if you have large open areas with small obstacles (not a problem if you
// use tiles)
// * good choice to use for tiled navmesh with medium and small sized tiles
// Prepare for region partitioning, by calculating distance field along the
// walkable surface.
if (!rcBuildDistanceField(&ctx, *ws.chf)) {
ESP_ERROR() << "Could not build distance field";
return false;
}
// Partition the walkable surface into simple regions without holes.
if (!rcBuildRegions(&ctx, *ws.chf, 0, cfg.minRegionArea,
cfg.mergeRegionArea)) {
ESP_ERROR() << "Could not build watershed regions";
return false;
}
// // Partition the walkable surface into simple regions without holes.
// // Monotone partitioning does not need distancefield.
// if (!rcBuildRegionsMonotone(ctx, *ws.chf, 0, cfg.minRegionArea,
// cfg.mergeRegionArea))
// // Partition the walkable surface into simple regions without holes.
// if (!rcBuildLayerRegions(ctx, *ws.chf, 0, cfg.minRegionArea))
//
// Step 5. Trace and simplify region contours.
//
// Create contours.
ws.cset = rcAllocContourSet();
if (!ws.cset) {
ESP_ERROR() << "Out of memory for contour set";
return false;
}
if (!rcBuildContours(&ctx, *ws.chf, cfg.maxSimplificationError,
cfg.maxEdgeLen, *ws.cset)) {
ESP_ERROR() << "Could not create contours";
return false;
}
//
// Step 6. Build polygons mesh from contours.
//
// Build polygon navmesh from the contours.
ws.pmesh = rcAllocPolyMesh();
if (!ws.pmesh) {
ESP_ERROR() << "Out of memory for polymesh";
return false;
}
if (!rcBuildPolyMesh(&ctx, *ws.cset, cfg.maxVertsPerPoly, *ws.pmesh)) {
ESP_ERROR() << "Could not triangulate contours";
return false;
}
//
// Step 7. Create detail mesh which allows to access approximate height on
// each polygon.
//
ws.dmesh = rcAllocPolyMeshDetail();
if (!ws.dmesh) {
ESP_ERROR() << "Out of memory for polymesh detail";
return false;
}
if (!rcBuildPolyMeshDetail(&ctx, *ws.pmesh, *ws.chf, cfg.detailSampleDist,
cfg.detailSampleMaxError, *ws.dmesh)) {
ESP_ERROR() << "Could not build detail mesh";
return false;
}
// At this point the navigation mesh data is ready, you can access it from
// ws.pmesh. See duDebugDrawPolyMesh or dtCreateNavMeshData as examples how to
// access the data.
//
// (Optional) Step 8. Create Detour data from Recast poly mesh.
//
// The GUI may allow more max points per polygon than Detour can handle.
// Only build the detour navmesh if we do not exceed the limit.
if (cfg.maxVertsPerPoly <= DT_VERTS_PER_POLYGON) {
unsigned char* navData = nullptr;
int navDataSize = 0;
// Update poly flags from areas.
for (int i = 0; i < ws.pmesh->npolys; ++i) {
if (ws.pmesh->areas[i] == RC_WALKABLE_AREA) {
ws.pmesh->areas[i] = POLYAREA_GROUND;
}
if (ws.pmesh->areas[i] == POLYAREA_GROUND) {
ws.pmesh->flags[i] = POLYFLAGS_WALK;
} else if (ws.pmesh->areas[i] == POLYAREA_DOOR) {
ws.pmesh->flags[i] = POLYFLAGS_WALK | POLYFLAGS_DOOR;
}
}
dtNavMeshCreateParams params{};
memset(¶ms, 0, sizeof(params));
params.verts = ws.pmesh->verts;
params.vertCount = ws.pmesh->nverts;
params.polys = ws.pmesh->polys;
params.polyAreas = ws.pmesh->areas;
params.polyFlags = ws.pmesh->flags;
params.polyCount = ws.pmesh->npolys;
params.nvp = ws.pmesh->nvp;
params.detailMeshes = ws.dmesh->meshes;
params.detailVerts = ws.dmesh->verts;
params.detailVertsCount = ws.dmesh->nverts;
params.detailTris = ws.dmesh->tris;
params.detailTriCount = ws.dmesh->ntris;
// params.offMeshConVerts = geom->getOffMeshConnectionVerts();
// params.offMeshConRad = geom->getOffMeshConnectionRads();
// params.offMeshConDir = geom->getOffMeshConnectionDirs();
// params.offMeshConAreas = geom->getOffMeshConnectionAreas();
// params.offMeshConFlags = geom->getOffMeshConnectionFlags();
// params.offMeshConUserID = geom->getOffMeshConnectionId();
// params.offMeshConCount = geom->getOffMeshConnectionCount();
params.walkableHeight = bs.agentHeight;
params.walkableRadius = bs.agentRadius;
params.walkableClimb = bs.agentMaxClimb;
rcVcopy(params.bmin, ws.pmesh->bmin);
rcVcopy(params.bmax, ws.pmesh->bmax);
params.cs = cfg.cs;
params.ch = cfg.ch;
params.buildBvTree = true;
if (!dtCreateNavMeshData(¶ms, &navData, &navDataSize)) {
ESP_ERROR() << "Could not build Detour navmesh";
return false;
}
navMesh_.reset(dtAllocNavMesh());
if (!navMesh_) {
dtFree(navData);
ESP_ERROR() << "Could not allocate Detour navmesh";
return false;
}
dtStatus status = 0;
status = navMesh_->init(navData, navDataSize, DT_TILE_FREE_DATA);
if (dtStatusFailed(status)) {
dtFree(navData);
ESP_ERROR() << "Could not init Detour navmesh";
return false;
}
if (!initNavQuery()) {
return false;
}
navMeshSettings_ = {bs};
} else {
ESP_ERROR() << "cfg.maxVertsPerPoly(" << cfg.maxVertsPerPoly
<< ") > DT_VERTS_PER_POLYGON(" << DT_VERTS_PER_POLYGON
<< "), so cannot build the Detour NavMesh. Aborting NavMesh "
"construction.";
return false;
}
bounds_ = std::make_pair(vec3f(bmin), vec3f(bmax));
ESP_DEBUG() << "Created navmesh with" << ws.pmesh->nverts << "vertices"
<< ws.pmesh->npolys << "polygons";
return true;
}
bool PathFinder::Impl::initNavQuery() {
// if we are reinitializing the NavQuery, then also reset the MeshData
islandMeshData_.clear();
navQuery_.reset(dtAllocNavMeshQuery());
dtStatus status = navQuery_->init(navMesh_.get(), 2048);
if (dtStatusFailed(status)) {
ESP_ERROR() << "Could not init Detour navmesh query";
return false;
}
islandSystem_ =
std::make_unique<impl::IslandSystem>(navMesh_.get(), filter_.get());
// Added as we also need to remove these on navmesh recomputation
islandSystem_->removeZeroAreaPolys(navMesh_.get());
return true;
}
bool PathFinder::Impl::build(const NavMeshSettings& bs,
const esp::assets::MeshData& mesh) {
const int numVerts = mesh.vbo.size();
const int numIndices = mesh.ibo.size();
const float mf = std::numeric_limits<float>::max();
vec3f bmin(mf, mf, mf);
vec3f bmax(-mf, -mf, -mf);
for (int i = 0; i < numVerts; ++i) {
const vec3f& p = mesh.vbo[i];
bmin = bmin.cwiseMin(p);
bmax = bmax.cwiseMax(p);
}
int* indices = new int[numIndices];
for (int i = 0; i < numIndices; ++i) {
indices[i] = static_cast<int>(mesh.ibo[i]);
}
const bool success = build(bs, mesh.vbo[0].data(), numVerts, indices,
numIndices / 3, bmin.data(), bmax.data());
delete[] indices;
return success;
}
namespace {
const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; //'MSET';
const int NAVMESHSET_VERSION = 2;
struct NavMeshSetHeader {
int magic;
int version;
int numTiles;
dtNavMeshParams params;
};
struct NavMeshTileHeader {
dtTileRef tileRef;
int dataSize;
};
struct Triangle {
std::vector<vec3f> v;
Triangle() { v.resize(3); }
};
std::vector<Triangle> getPolygonTriangles(const dtPoly* poly,
const dtMeshTile* tile) {
// Code to iterate over triangles from here:
// https://github.com/recastnavigation/recastnavigation/blob/57610fa6ef31b39020231906f8c5d40eaa8294ae/Detour/Source/DetourNavMesh.cpp#L684
const std::ptrdiff_t ip = poly - tile->polys;
const dtPolyDetail* pd = &tile->detailMeshes[ip];