-
Notifications
You must be signed in to change notification settings - Fork 1
/
pathfinder.h
3433 lines (3290 loc) · 221 KB
/
pathfinder.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
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
#ifndef PATHFINDER_PATHFINDER_H_
#define PATHFINDER_PATHFINDER_H_
// #include "binary_min_heap.h"
#include "debuglogger.h"
#include "interval.h"
#include "math_helpers.h"
#include "path.h"
#include "vector.h"
#include <absl/log/globals.h>
#include <absl/log/initialize.h>
#include <absl/log/log.h>
#include <absl/strings/str_format.h>
#include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <queue>
#include <set>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <variant>
#include <vector>
namespace pathfinder {
double calculatePathLength(const std::vector<std::unique_ptr<PathSegment>> &path);
namespace internal {
enum class RelativePositionToInterval {
kIsLeftOf,
kIsRightOf,
kIsWithin
};
std::string toString(RelativePositionToInterval pos);
bool lineActuallyIntersectedWithCircle(const pathfinder::Vector &lineSegmentStartPoint,
const pathfinder::Vector &lineSegmentEndPoint,
const pathfinder::Vector ¢erOfCircle,
const double circleRadius,
int intersectionCount,
const pathfinder::Vector &intersectionPoint1,
const pathfinder::Vector &intersectionPoint2);
struct RAIIPrinter {
RAIIPrinter(const std::string &msg);
~RAIIPrinter();
private:
std::string msg_;
};
} // namespace internal
/* TODO: Outline NavmeshType requirements
*
*
*/
enum class PathfinderAlgorithm {
kPolyanya,
kTriangleAStar
};
class PathfinderConfig {
public:
PathfinderConfig() = default;
PathfinderConfig(PathfinderAlgorithm primaryAlgorithm) : primaryAlgorithm_(primaryAlgorithm) {}
void setAgentRadius(double radius) {
agentRadius_ = radius;
}
void setTimeout(std::chrono::milliseconds timeout, std::optional<PathfinderAlgorithm> secondaryAlgorithm = std::nullopt) {
timeoutMilliseconds_ = timeout;
algorithmAfterTimeout_ = secondaryAlgorithm;
}
double agentRadius() const {
return agentRadius_;
}
PathfinderAlgorithm primaryAlgorithm() const {
return primaryAlgorithm_;
}
std::optional<std::chrono::milliseconds> timeoutMilliseconds() const {
return timeoutMilliseconds_;
}
std::optional<PathfinderAlgorithm> algorithmAfterTimeout() const {
return algorithmAfterTimeout_;
}
private:
double agentRadius_{0.0};
PathfinderAlgorithm primaryAlgorithm_{PathfinderAlgorithm::kPolyanya};
std::optional<std::chrono::milliseconds> timeoutMilliseconds_;
std::optional<PathfinderAlgorithm> algorithmAfterTimeout_;
};
template<typename NavmeshType>
class Pathfinder {
public:
static constexpr bool kProduceDebugAnimationData_{false};
using State = typename NavmeshType::State;
using IndexType = typename NavmeshType::IndexType;
using IntervalType = Interval<State, IndexType>;
struct IntervalAndCost {
IntervalAndCost(const IntervalType &i, double c) : interval(i), cost(c) {}
IntervalType interval;
double cost;
};
struct IntervalAndCostComp {
bool operator()(const IntervalAndCost &lhs, const IntervalAndCost &rhs) const {
return lhs.cost > rhs.cost;
}
};
using IntervalHeapType = std::priority_queue<IntervalAndCost, std::vector<IntervalAndCost>, IntervalAndCostComp>;
using IntervalCompareType = pathfinder::IntervalCompare<IntervalType>;
using PreviousIntervalMapType = std::unordered_map<IntervalType, IntervalType>;
using IntervalSetType = std::unordered_set<IntervalType>;
struct PathfindingAStarInfo {
enum class PushOrPop {
kPush, kPop
};
std::vector<std::pair<Pathfinder::IntervalType, PushOrPop>> intervals;
PreviousIntervalMapType previous;
};
struct PathfindingResult {
std::vector<std::unique_ptr<PathSegment>> shortestPath;
struct EmptyType {};
using DebugAStarInfoType = std::conditional_t<kProduceDebugAnimationData_, PathfindingAStarInfo, EmptyType>;
DebugAStarInfoType debugAStarInfo;
};
Pathfinder(const NavmeshType &navmesh, const PathfinderConfig &config);
static constexpr bool hasDebugAnimationData() {
return kProduceDebugAnimationData_;
}
// template<typename PointType>
// std::pair<Vector, IndexType> getPointAwayFromConstraint(const PointType &point) const;
template<typename PointType>
PathfindingResult findShortestPath(const PointType &startPoint, const PointType &goalPoint) const;
private:
const NavmeshType &navmesh_;
const PathfinderConfig config_;
mutable std::unordered_map<State, std::unordered_map<IndexType, bool>> constraintForStateCache_;
// Does a cheaper check (compared to actual pathfinding) to see if it is possible at all to get from the start state to the goal state.
bool canGetToState(const State &startState, const State &goalState, std::optional<std::chrono::high_resolution_clock::time_point> pathfindingStartTime) const;
PathfindingResult polyanya(const Vector &startPoint, const State &startState, const Vector &goalPoint, const State &goalState, std::optional<std::chrono::high_resolution_clock::time_point> pathfindingStartTime) const;
// Helpers
std::tuple<Vector, IndexType, Vector, IndexType> getLeftAndRight(const State &successorState) const;
bool isAConstraintVertexForState(const State ¤tState, const IndexType vertexIndex) const;
using BendResult = std::tuple<std::optional<Vector>, std::optional<IndexType>, std::optional<std::pair<Vector, IndexType>>>;
// Returns the splitting point as projectedPoint, projectedIndex
// Returns the rightConstraint
BendResult bendThatMfRoundTheRight(const Vector &successorEdgeRightPoint,
const IndexType successorEdgeRightIndex,
const IntervalType ¤tInterval,
const Vector &successorEdgeLeftPoint,
const IndexType successorEdgeLeftIndex,
const double kEndpointIntersectionPrecision,
const State ¤tState) const;
// Returns the splitting point as projectedPoint, projectedIndex
// Returns the leftConstraint
BendResult bendThatMfRoundTheLeft(const Vector &successorEdgeRightPoint,
const IndexType successorEdgeRightIndex,
const IntervalType ¤tInterval,
const Vector &successorEdgeLeftPoint,
const IndexType successorEdgeLeftIndex,
const double kEndpointIntersectionPrecision,
const State ¤tState) const;
std::pair<Vector,Vector> createTempRightIntervalForCrossProduct(const IntervalType ¤tInterval, const Vector &point) const;
std::pair<Vector,Vector> createTempLeftIntervalForCrossProduct(const IntervalType ¤tInterval, const Vector &point) const;
// Given an `IntervalType` and line segment (toDestinationStart->toDestinationEnd), determine the line's relation to the left and right of the interval.
std::pair<bool,bool> booberGobblin(const std::optional<IndexType> successorEdgeLeftIndex,
const std::optional<IndexType> successorEdgeRightIndex,
const IntervalType ¤tInterval,
const Vector &toDestinationStart,
const Vector &toDestinationEnd) const;
double costFromIntervalToGoal(const IntervalType &interval, const Vector &goalPoint) const;
void pushSuccessor(const IntervalType *currentInterval,
IntervalType successorInterval,
IntervalHeapType &intervalHeap,
IntervalSetType &visited,
IntervalSetType &pushed,
PreviousIntervalMapType &previous,
const Vector &goalPoint,
typename PathfindingResult::DebugAStarInfoType &debugAStarInfo) const;
void handleStartStateSuccessor(const State &successorState,
const Vector &startPoint,
const State &startState,
const Vector &goalPoint,
IntervalHeapType &intervalHeap,
IntervalSetType &visited,
IntervalSetType &pushed,
PreviousIntervalMapType &previous,
typename PathfindingResult::DebugAStarInfoType &debugAStarInfo) const;
void expandInterval(IntervalType ¤tInterval,
const Vector &startPoint,
const Vector &goalPoint,
const State &goalState,
IntervalHeapType &intervalHeap,
IntervalSetType &visited,
IntervalSetType &pushed,
PreviousIntervalMapType &previous,
typename PathfindingResult::DebugAStarInfoType &debugAStarInfo) const;
void checkLeftAndRightConstraints(IntervalType ¤tInterval) const;
bool successorIsInsideIntervalConstraint(const IntervalType ¤tInterval, const State &successorState) const;
void buildResultFromGoalInterval(const IntervalType &goalInterval,
const Vector &startPoint,
const Vector &goalPoint,
PreviousIntervalMapType &previous,
PathfindingResult &result) const;
void handleNormalSuccessor(const State ¤tState,
const State &successorState,
const IntervalType ¤tInterval,
const Vector &goalPoint,
IntervalHeapType &intervalHeap,
IntervalSetType &visited,
IntervalSetType &pushed,
PreviousIntervalMapType &previous,
typename PathfindingResult::DebugAStarInfoType &debugAStarInfo
) const;
void buildLeftIntervals(IntervalType ¤tInterval) const;
void buildRightIntervals(IntervalType ¤tInterval) const;
void handleGoalSuccessor(const IntervalType ¤tInterval,
const State &successorState,
IntervalHeapType &intervalHeap,
IntervalSetType &visited,
IntervalSetType &pushed,
PreviousIntervalMapType &previous,
const Vector &goalPoint,
typename PathfindingResult::DebugAStarInfoType &debugAStarInfo) const;
bool doesRightIntervalIntersectWithLeftOfSuccessorEdge(const IntervalType ¤tInterval,
bool successorLeftIsConstraintVertex,
IndexType successorEdgeLeftIndex,
const Vector &successorEdgeLeftPoint,
const Vector &successorEdgeRightPoint) const;
bool doesLeftIntervalIntersectWithRightOfSuccessorEdge(const IntervalType ¤tInterval,
bool successorRightIsConstraintVertex,
IndexType successorEdgeRightIndex,
const Vector &successorEdgeLeftPoint,
const Vector &successorEdgeRightPoint) const;
internal::RelativePositionToInterval calculateSuccessorLeftRelativeToInterval(const IntervalType ¤tInterval,
IndexType currentEdgeLeftIndex,
const Vector &successorEdgeLeftPoint,
IndexType successorEdgeLeftIndex,
const Vector &successorEdgeRightPoint,
IndexType successorEdgeRightIndex,
bool successorLeftIsConstraintVertex) const;
internal::RelativePositionToInterval calculateSuccessorRightRelativeToInterval(const IntervalType ¤tInterval,
IndexType currentEdgeRightIndex,
const Vector &successorEdgeLeftPoint,
IndexType successorEdgeLeftIndex,
const Vector &successorEdgeRightPoint,
IndexType successorEdgeRightIndex,
bool successorRightIsConstraintVertex) const;
bool intervalIsClosed(const IntervalType ¤tInterval,
const Vector &successorEdgeLeftPoint,
const Vector &successorEdgeRightPoint,
bool checkIfIntersectWithLeftConstraint,
bool checkIfIntersectWithRightConstraint) const;
bool canFitThroughEdge(const State ¤tState, IndexType edgeIndex) const;
// Checks if the given point collides with any of the constraint vertices of the triangle
// If the distance to a constraint vertex is exactly the agent radius, then it will not collide
// TODO: Does not check if the given point collides with edges of the triangle
// std::optional<Vector> getCollidingConstraint(const Vector &point, const IndexType triangleIndex) const;
// void buildShortestPathWithinSingleTriangle(const IndexType triangleIndex, const Vector &startPoint, const Vector &goalPoint, std::vector<std::unique_ptr<PathSegment>> &shortestPath) const;
// double distanceBetweenEdgeAndPoint(IndexType edgeIndex, const Vector &point, Vector *pointUsedForDistanceCalculation=nullptr) const;
// double calculateArcLength(const IndexType edge1Index, const IndexType edge2Index) const;
// double calculateHValue(const State &state, const Vector &goalPoint) const;
// double calculateEstimateGValue(const State &state, const State &parentState, const Vector &startPoint, const Vector &goalPoint, const std::unordered_map<State, double> &gScores) const;
// std::tuple<double, Vector, std::optional<LengthFunnel>> calculateGValue(const State &state, const State &parentState, const Vector &startPoint, const Vector &goalPoint, const std::unordered_map<State, State> &previous) const;
// PathfindingAStarInfo triangleAStar(const Vector &startPoint, const State &startState, const Vector &goalPoint, const State &goalState) const;
// bool pathCanExist(const State &startState, const State &goalState) const;
// std::vector<std::pair<Vector,Vector>> buildCorridor(const std::vector<IndexType> &trianglesInCorridor) const;
// static std::vector<IndexType> rebuildPath(State state, const std::unordered_map<State, State> &previous);
};
template<typename NavmeshType>
Pathfinder<NavmeshType>::Pathfinder(const NavmeshType &navmesh, const PathfinderConfig &config) : navmesh_(navmesh), config_(config) {
// Initialize debug logger
DebugLogger::instance().setPointToIndexFunction(std::bind(&NavmeshType::getVertexIndex, std::cref(navmesh_), std::placeholders::_1));
}
// template<typename NavmeshType>
// template<typename PointType>
// std::pair<Vector, typename Pathfinder<NavmeshType>::IndexType> Pathfinder<NavmeshType>::getPointAwayFromConstraint(const PointType &point) const {
// Vector point2d = NavmeshType::to2dPoint(point);
// std::optional<IndexType> triangleForPoint = navmesh_.findTriangleForPoint(point2d);
// if (!triangleForPoint) {
// throw std::runtime_error("Unable to find valid triangle for point");
// }
// constexpr const int kMaxIterations{5};
// int iterationCount{0};
// std::optional<Vector> collidingConstraint = getCollidingConstraint(point2d, *triangleForPoint);
// while (collidingConstraint.has_value()) {
// if (iterationCount == kMaxIterations) {
// throw std::runtime_error("Cannot point away from constraint");
// }
// // Push point out to radius of circle.
// point2d = math::extendLineSegmentToLength(*collidingConstraint, point2d, config_.agentRadius()*1.01);
// triangleForPoint = navmesh_.findTriangleForPoint(point2d);
// if (!triangleForPoint) {
// throw std::runtime_error("Unable to find valid triangle for point");
// }
// // Check if the new point overlaps with any constraint.
// collidingConstraint = getCollidingConstraint(point2d, *triangleForPoint);
// // Keep track that we dont get stuck here for too long.
// ++iterationCount;
// }
// return {point2d, *triangleForPoint};
// }
template<typename NavmeshType>
bool Pathfinder<NavmeshType>::isAConstraintVertexForState(const State ¤tState, const typename NavmeshType::IndexType vertexIndex) const {
// TODO: Instead of a cache, this could be computed as a pre-computation step.
auto &subMap = constraintForStateCache_[currentState];
if (const auto it = subMap.find(vertexIndex); it != subMap.end()) {
return it->second;
}
// Check if we can do a 360 around this vertex without running into any constraints.
std::queue<State> nextStates;
std::set<State> visited;
nextStates.push(currentState);
while (!nextStates.empty()) {
auto currentState = nextStates.front();
nextStates.pop();
visited.emplace(currentState);
const auto successorStates = navmesh_.getSuccessors(currentState, std::nullopt, 0.0);
// Do any of these successors go through an edge which has the vertex in question as an endpoint?
for (const auto &successorState : successorStates) {
if (!successorState.hasEntryEdgeIndex()) {
// Has no entry edge. What does that mean?
continue;
}
const auto [v1, v2] = navmesh_.getEdgeVertexIndices(successorState.getEntryEdgeIndex());
if (v1 != vertexIndex && v2 != vertexIndex) {
// This successor is across an edge that does not touch our vertex; we don't care about this successor.
continue;
}
if (visited.find(successorState) != visited.end()) {
// We've already visited this state! That means we made a full loop!
subMap.emplace(vertexIndex, false);
return false;
}
// We have not yet visited this state.
nextStates.push(successorState);
}
}
subMap.emplace(vertexIndex, true);
return true;
}
template<typename NavmeshType>
template<typename PointType>
typename Pathfinder<NavmeshType>::PathfindingResult Pathfinder<NavmeshType>::findShortestPath(const PointType &startPoint, const PointType &goalPoint) const {
const auto pathfindingStartTime = std::chrono::high_resolution_clock::now();
const auto pathfindingDeadline = [&]() -> std::optional<std::chrono::high_resolution_clock::time_point> {
if (config_.timeoutMilliseconds().has_value()) {
return pathfindingStartTime + *config_.timeoutMilliseconds();
} else {
return std::nullopt;
}
}();
// { // TODO: <Remove>
// // // Print specific vertices.
// // const std::vector<IndexType> indicesToPrint = {
// // 486,487,488,603,601,520,521,522,613,583,577,477,483,482,480,479,478,476,481,489,485,600,599,598,602,604
// // };
// // for (const auto index : indicesToPrint) {
// // if (index >= navmesh_.getVertexCount()) {
// // VLOG(1) << "Asking for a vertex which is out of bounds!";
// // continue;
// // }
// // const auto &vertex = navmesh_.getVertex(index);
// // VLOG(1) << absl::StreamFormat("Index %d is (%.15f,%.15f)", index, vertex.x(), vertex.y());
// // }
// // ------------------------------------------------------------------------
// // Print vertices within a bounding box.
// constexpr double kMinX = 1015.0;
// constexpr double kMaxX = 1070.0;
// constexpr double kMinY = 1430.0;
// constexpr double kMaxY = 1480.0;
// std::vector<Vector> vertices;
// for (size_t i=0; i<navmesh_.getVertexCount(); ++i) {
// const auto &vertex = navmesh_.getVertex(i);
// if (vertex.x() >= kMinX && vertex.x() <= kMaxX &&
// vertex.y() >= kMinY && vertex.y() <= kMaxY) {
// vertices.push_back(vertex);
// }
// }
// VLOG(1) << vertices.size() << " 2 0 0";
// for (size_t i=0; i<vertices.size(); ++i) {
// VLOG(1) << absl::StreamFormat("%d %.20f %.20f", i, vertices[i].x(), vertices[i].y());
// }
// } // </Remove>
// Find the triangle for the start point.
Vector startPoint2d = NavmeshType::to2dPoint(startPoint);
std::optional<IndexType> startTriangle = navmesh_.findTriangleForPoint(startPoint2d);
if (!startTriangle) {
throw std::runtime_error("Unable to find start triangle");
}
const auto startState = navmesh_.createStartState(startPoint, *startTriangle);
// Find the triangle for the goal point.
Vector goalPoint2d = NavmeshType::to2dPoint(goalPoint);
std::optional<IndexType> goalTriangle = navmesh_.findTriangleForPoint(goalPoint2d);
if (!goalTriangle) {
throw std::runtime_error("Unable to find goal triangle");
}
const auto goalState = navmesh_.createGoalState(goalPoint, *goalTriangle);
// Do a quick check to see if it's even possible to get from the start triangle to the goal triangle.
bool isMaybePossible = canGetToState(startState, goalState, pathfindingDeadline);
if (!isMaybePossible) {
// For sure no way to get there.
return {};
}
PathfindingResult result;
if (config_.primaryAlgorithm() == PathfinderAlgorithm::kPolyanya) {
// TODO: get timeout status and then go to fallback algorithm
result = polyanya(startPoint2d, startState, goalPoint2d, goalState, pathfindingDeadline);
}
return result;
}
template<typename NavmeshType>
bool Pathfinder<NavmeshType>::canGetToState(const State &startState, const State &goalState, std::optional<std::chrono::high_resolution_clock::time_point> pathfindingDeadline) const {
struct StateAndCost {
StateAndCost(const State &i, double d) : state(i), distanceToGoal(d) {}
State state;
double distanceToGoal;
};
struct StateAndCostComp {
bool operator()(const StateAndCost &lhs, const StateAndCost &rhs) const {
return lhs.distanceToGoal > rhs.distanceToGoal;
}
};
auto centerOfTriangleOfState = [this](const State &state) -> Vector {
const auto& [v1,v2,v3] = navmesh_.getTriangleVertices(state.getTriangleIndex());
return (v1 + v2 + v3) / 3.0;
};
std::priority_queue<StateAndCost, std::vector<StateAndCost>, StateAndCostComp> stateHeap;
std::set<State> visited;
// Calculate the center of the goal triangle for rough distance calculations.
const auto centerOfGoal = centerOfTriangleOfState(goalState);
auto pushState = [¢erOfTriangleOfState, ¢erOfGoal](auto &stateHeap, const State &state) {
const auto centerOfState = centerOfTriangleOfState(state);
stateHeap.emplace(state, math::distance(centerOfState, centerOfGoal));
};
pushState(stateHeap, startState);
while (!stateHeap.empty()) {
if (pathfindingDeadline) {
if (std::chrono::high_resolution_clock::now() >= *pathfindingDeadline) {
VLOG(1) << "Pathfinding timed out";
return {};
}
}
const auto stateAndCost = stateHeap.top();
const State ¤tState = stateAndCost.state;;
stateHeap.pop();
// Check if this is the goal.
if (currentState.isGoal()) {
return true;
}
visited.emplace(currentState);
auto successorStates = navmesh_.getSuccessors(currentState, goalState, 0.0); // TODO: Change 0.0 to config_.agentRadius()
for (const auto &state : successorStates) {
if (visited.find(state) == visited.end()) {
pushState(stateHeap, state);
}
}
}
// Couldn't get to goal.
return false;
}
template<typename NavmeshType>
typename Pathfinder<NavmeshType>::PathfindingResult Pathfinder<NavmeshType>::polyanya(const Vector &startPoint, const State &startState, const Vector &goalPoint, const State &goalState, std::optional<std::chrono::high_resolution_clock::time_point> pathfindingDeadline) const {
PathfindingResult result;
typename PathfindingResult::DebugAStarInfoType &debugAStarInfo = result.debugAStarInfo;
if (startState.isSameTriangleAs(goalState)) {
// Start and goal is in same triangle. Path is a straight line to the goal.
// TODO: This is not always safe.
result.shortestPath.emplace_back(std::unique_ptr<PathSegment>(new StraightPathSegment(startPoint, goalPoint)));
return result;
}
IntervalHeapType intervalHeap;
PreviousIntervalMapType previous;
IntervalSetType visited;
IntervalSetType pushed;
VLOG(1) << "Starting with state " << startPoint << " in triangle " << startState.getTriangleIndex() << " with " << (startState.hasEntryEdgeIndex() ? "entry edge "+std::to_string(startState.getEntryEdgeIndex()) : "no entry edge");
// Initialize the list of intervals.
const auto startStateSuccessors = navmesh_.getSuccessors(startState, goalState, config_.agentRadius());
for (const auto &successorState : startStateSuccessors) {
handleStartStateSuccessor(successorState, startPoint, startState, goalPoint, intervalHeap, visited, pushed, previous, debugAStarInfo);
}
// Run the A* algorithm as defined by the Polyanya paper.
while (!intervalHeap.empty()) {
if (pathfindingDeadline) {
if (std::chrono::high_resolution_clock::now() >= *pathfindingDeadline) {
VLOG(1) << "Pathfinder timed out";
return {};
}
}
VLOG(1) << "\n===== Next iteration of A* =====";
if (VLOG_IS_ON(1)) {
// Print all intervals.
// There's no way to iterate my heap in order, so we copy it and continually pop and print the top element.
IntervalHeapType copyOfHeap = intervalHeap;
while (!copyOfHeap.empty()) {
const IntervalAndCost top = copyOfHeap.top();
copyOfHeap.pop();
VLOG(1) << " Interval " << top.interval.toString() << " has cost " << top.cost;
}
}
// Pop the next interval off the minheap and expand it.
IntervalAndCost intervalWithCost = intervalHeap.top();
intervalHeap.pop();
IntervalType ¤tInterval = intervalWithCost.interval;
VLOG(1) << "The minimum element is " << currentInterval.toString() << " with cost " << intervalWithCost.cost;
visited.emplace(currentInterval);
if constexpr (kProduceDebugAnimationData_) {
debugAStarInfo.intervals.emplace_back(currentInterval, PathfindingAStarInfo::PushOrPop::kPop);
}
if (currentInterval.isGoal) {
buildResultFromGoalInterval(currentInterval, startPoint, goalPoint, previous, result);
break;
}
expandInterval(currentInterval, startPoint, goalPoint, goalState, intervalHeap, visited, pushed, previous, debugAStarInfo);
}
if constexpr (kProduceDebugAnimationData_) {
debugAStarInfo.previous = previous;
}
return result;
}
template<typename NavmeshType>
typename Pathfinder<NavmeshType>::BendResult Pathfinder<NavmeshType>::bendThatMfRoundTheRight(
const Vector &successorEdgeRightPoint,
const IndexType successorEdgeRightIndex,
const IntervalType ¤tInterval,
const Vector &successorEdgeLeftPoint,
const IndexType successorEdgeLeftIndex,
const double kEndpointIntersectionPrecision,
const State ¤tState) const {
if (VLOG_IS_ON(1)) {
std::cout << std::endl;
}
VLOG(1) << "Enter bendThatMfRoundTheRight";
internal::RAIIPrinter raiiPrinter("Exiting bendThatMfRoundTheRight\n");
Vector projectedRightPoint;
std::optional<IndexType> projectedRightIndex;
bool successorEdgeIntersectsWithRightOfInterval=false;
if (currentInterval.rightIsRoot()) {
// We can definitely get to the right vertex of the successor edge.
projectedRightPoint = successorEdgeRightPoint;
projectedRightIndex = successorEdgeRightIndex;
} else {
if (!currentInterval.rightInterval()) {
throw std::runtime_error("Right is not root and do not have a right interval");
}
const LineSegment &rightInterval = *currentInterval.rightInterval();
bool createdProjectedPoint{false};
if (currentInterval.intervalRightIsConstraintVertex() && *currentInterval.rightIndex != successorEdgeRightIndex) {
VLOG(1) << "Right of interval is constraint and the right of the edge is a different point";
// Check if the successor edge intersects with the right of the interval.
Vector intersectionPoint1, intersectionPoint2;
int intersectionCount = math::lineSegmentIntersectsWithCircle(successorEdgeLeftPoint, successorEdgeRightPoint, currentInterval.rightPoint, config_.agentRadius(), &intersectionPoint1, &intersectionPoint2);
VLOG(1) << "Checking if segment Segment(" << '(' << successorEdgeLeftPoint.x() << ',' << successorEdgeLeftPoint.y() << ')' << ',' << '(' << successorEdgeRightPoint.x() << ',' << successorEdgeRightPoint.y() << ')' << ") intersects with point at " << currentInterval.rightPoint.x() << ',' << currentInterval.rightPoint.y();
if (intersectionCount > 0) {
// Only use this intersection if it is not inside the right point of the successor edge (if that point is a constraint).
VLOG(1) << "[bendThatMfRoundTheRight] Itersection count is " << intersectionCount;
if (!isAConstraintVertexForState(currentState, successorEdgeRightIndex) || math::distanceSquared(intersectionPoint1, successorEdgeRightPoint) > config_.agentRadius()*config_.agentRadius()) {
successorEdgeIntersectsWithRightOfInterval = true;
// One interval will be
// root: same as current
// left: successorEdgeLeftPoint, successorEdgeLeftIndex
// right: currentInterval.right
projectedRightPoint = currentInterval.rightPoint;
projectedRightIndex = currentInterval.rightIndex;
createdProjectedPoint = true;
if (intersectionCount == 2) {
VLOG(1) << "Oh. hmm";
// TODO:
// If there are two intersection points, there will be another interval which is
// root: currentInterval.right
// left: successorEdgeRightPoint, successorEdgeRightIndex
// right: currentInterval.right
// throw std::runtime_error("Still need to handle");
}
}
}
} else {
VLOG(1) << "Right is not a constraint";
}
{
double t1, t2;
auto ir = math::intersectForIntervals(rightInterval.first, rightInterval.second, successorEdgeLeftPoint, successorEdgeRightPoint, &t1, &t2);
if (ir != math::IntersectionResult::kInfinite) {
const Vector point = successorEdgeLeftPoint + (successorEdgeRightPoint-successorEdgeLeftPoint)*t2;
VLOG(1) << "Intersected at " << absl::StreamFormat("%.20f,%.20f", point.x(), point.y());
} else {
VLOG(1) << "Inf intersection";
}
}
if (!createdProjectedPoint) {
VLOG(1) << "Havent yet created a projected point";
math::IntersectionResult intersectionResult;
double t1, t2;
if (math::equal(rightInterval.first, rightInterval.second)) {
VLOG(1) << absl::StreamFormat("Right interval has length %.20f", math::distance(rightInterval.first, rightInterval.second));
// Right interval has 0-length, create a fake temporary vector for an intersection test.
Vector tangentStart, tangentEnd;
if (!currentInterval.intervalRightIsConstraintVertex()) {
// How do we create a temporary right interval if the right isnt a constraint?
// Is there a root point and is this right interval on it?
if (currentInterval.rootIndex && math::equal(math::distanceSquared(currentInterval.rootPoint, rightInterval.first), config_.agentRadius()*config_.agentRadius())) {
std::tie(tangentStart, tangentEnd) = math::createVectorTangentToPointOnCircle(currentInterval.rootPoint, config_.agentRadius(), rightInterval.first);
} else {
VLOG(1) << "currentInterval.rootIndex: " << (bool)currentInterval.rootIndex;
VLOG(1) << absl::StreamFormat("Distance squared from %.5f,%.5f to %.5f,%.5f is %.10f", currentInterval.rootPoint.x(), currentInterval.rootPoint.y(), rightInterval.first.x(), rightInterval.first.y(), math::distanceSquared(currentInterval.rootPoint, rightInterval.first));
throw std::runtime_error("Unseen case 1");
}
} else {
std::tie(tangentStart, tangentEnd) = math::createVectorTangentToPointOnCircle(currentInterval.rightPoint, config_.agentRadius(), rightInterval.first);
VLOG(1) << "Created tmp interval as Segment(" << '(' << tangentStart.x() << ',' << tangentStart.y() << ')' << ',' << '(' << tangentEnd.x() << ',' << tangentEnd.y() << ')' << ")";
}
intersectionResult = math::intersectForIntervals(tangentStart, tangentEnd, successorEdgeLeftPoint, successorEdgeRightPoint, &t1, &t2);
} else {
intersectionResult = math::intersectForIntervals(rightInterval.first, rightInterval.second, successorEdgeLeftPoint, successorEdgeRightPoint, &t1, &t2);
}
if (math::equal(t2, 0.0, kEndpointIntersectionPrecision)) {
// Right point is actually the left of the edge.
projectedRightPoint = successorEdgeLeftPoint;
projectedRightIndex = successorEdgeLeftIndex;
VLOG(1) << "Projection is on left endpoint";
} else if (math::equal(t2, 1.0, kEndpointIntersectionPrecision)) {
// Right point is actually the right of the edge.
projectedRightPoint = successorEdgeRightPoint;
projectedRightIndex = successorEdgeRightIndex;
VLOG(1) << "Projection is on right endpoint";
} else {
projectedRightPoint = successorEdgeLeftPoint + t2 * (successorEdgeRightPoint - successorEdgeLeftPoint);
VLOG(1) << "Projection is at " << projectedRightPoint.x() << ',' << projectedRightPoint.y();
}
}
if (!currentInterval.intervalRightIsConstraintVertex()) {
// Right of interval is not a constraint, but the interval could intersect with a constraint on the way to the successor edge.
// Extend right interval out to successor.
VLOG(1) << "Checking if right interval intersects with a constraint on the way to the successor edge";
double i1, i2;
auto intersectionResult = math::intersectForIntervals(rightInterval.first, rightInterval.second, successorEdgeLeftPoint, successorEdgeRightPoint, &i1, &i2);
if (!math::lessThan(i2, 0.0) && !math::lessThan(1.0, i2)) {
VLOG(1) << "This does intersect with the successor edge";
const Vector rightIntervalIntersectionWithSuccessorEdge = successorEdgeLeftPoint + (successorEdgeRightPoint - successorEdgeLeftPoint) * i2;
// For now, we only check if this intersects with the currrent entry edge's right.
// TODO: Check if this line intersects with any other constraint vertices within range.
const auto [currentEdgeLeftPoint, currentEdgeLeftIndex, currentEdgeRightPoint, currentEdgeRightIndex] = getLeftAndRight(currentState);
if (isAConstraintVertexForState(currentState, currentEdgeRightIndex)) {
VLOG(1) << "Right of current edge is a constraint";
Vector intersectionPoint1, intersectionPoint2;
auto intersectionResult2 = math::lineSegmentIntersectsWithCircle(rightInterval.first, rightIntervalIntersectionWithSuccessorEdge, currentEdgeRightPoint, config_.agentRadius(), &intersectionPoint1, &intersectionPoint2);
// Weed out the tangential intersections.
const bool actuallyIntersected = internal::lineActuallyIntersectedWithCircle(rightInterval.first, rightIntervalIntersectionWithSuccessorEdge, currentEdgeRightPoint, config_.agentRadius(), intersectionResult2, intersectionPoint1, intersectionPoint2);
if (actuallyIntersected) {
VLOG(1) << "Augmented right interval Segment(" << '(' << rightInterval.first.x() << ',' << rightInterval.first.y() << "),(" << rightIntervalIntersectionWithSuccessorEdge.x() << ',' << rightIntervalIntersectionWithSuccessorEdge.y() << ')' << ") intersects with right of current edge point " << currentEdgeRightIndex;
return {currentEdgeRightPoint, currentEdgeRightIndex, std::nullopt};
}
}
}
}
}
// The left of the interval might not be a vertex, but the left interval extended out to the next edge might pass through the left vertex of the successor edge.
std::optional<Vector> optionalProjectedRightPoint = projectedRightPoint;
std::optional<std::pair<Vector, IndexType>> rightConstraint;
if (!successorEdgeIntersectsWithRightOfInterval) {
VLOG(1) << "Successor edge does not intersect with right of interval";
if (!currentInterval.rightIsRoot() && isAConstraintVertexForState(currentState, successorEdgeRightIndex) && math::lineSegmentIntersectsWithCircle(currentInterval.rightInterval()->first, projectedRightPoint, successorEdgeRightPoint, config_.agentRadius()) == 2) {
VLOG(1) << "Right interval to projected point intersects with successor right edge twice";
// We will need to create two intervals. First create a tangent line to the right point of the successor edge. One interval will go straight to the projected point of that tangent. The other interval will bend around the right of that successor edge.
const auto [lineStart, lineEnd] = math::createCircleConsciousLine(currentInterval.rightInterval()->first, AngleDirection::kNoDirection, successorEdgeRightPoint, AngleDirection::kClockwise, config_.agentRadius());
double t1_2, t2_2;
const Vector pushedSuccessorRight = math::extendLineSegmentToLength(successorEdgeRightPoint, successorEdgeLeftPoint, config_.agentRadius());
const Vector pushedSuccessorLeft = isAConstraintVertexForState(currentState, successorEdgeLeftIndex) ? math::extendLineSegmentToLength(successorEdgeLeftPoint, successorEdgeRightPoint, config_.agentRadius()) : successorEdgeLeftPoint;
auto intersectionResult2 = math::intersectForIntervals(lineStart, lineEnd, pushedSuccessorLeft, pushedSuccessorRight, &t1_2, &t2_2);
// TODO: This line might not actually make it to the successor edge before hitting a constraint.
VLOG(1) << "Intersection interval 1: " << t1_2 << ", 2: " << t2_2;
(void)intersectionResult2;
if (math::betweenOrEqual(t2_2, 0.0, 1.0)) {
// Update projected right point
optionalProjectedRightPoint = lineStart + t1_2 * (lineEnd - lineStart);
VLOG(1) << "Created projected point is at " << optionalProjectedRightPoint->x() << ',' << optionalProjectedRightPoint->y();
} else {
VLOG(1) << "Didnt actually hit successor edge. Not going to return a projected point.";
optionalProjectedRightPoint.reset();
}
rightConstraint.emplace(successorEdgeRightPoint, successorEdgeRightIndex);
} else if (currentInterval.rightIndex && isAConstraintVertexForState(currentState, *currentInterval.rightIndex)) {
rightConstraint.emplace(currentInterval.rightPoint, *currentInterval.rightIndex);
}
}
return {optionalProjectedRightPoint, projectedRightIndex, rightConstraint};
}
template<typename NavmeshType>
typename Pathfinder<NavmeshType>::BendResult Pathfinder<NavmeshType>::bendThatMfRoundTheLeft(
const Vector &successorEdgeRightPoint,
const IndexType successorEdgeRightIndex,
const IntervalType ¤tInterval,
const Vector &successorEdgeLeftPoint,
const IndexType successorEdgeLeftIndex,
const double kEndpointIntersectionPrecision,
const State ¤tState) const {
if (VLOG_IS_ON(1)) {
std::cout << std::endl;
}
VLOG(1) << "Enter bendThatMfRoundTheLeft";
internal::RAIIPrinter raiiPrinter("Exiting bendThatMfRoundTheLeft\n");
Vector projectedLeftPoint;
std::optional<IndexType> projectedLeftIndex;
bool successorEdgeIntersectsWithLeftOfInterval=false;
if (currentInterval.leftIsRoot()) {
// We can definitely get to the left vertex of the successor edge.
projectedLeftPoint = successorEdgeLeftPoint;
projectedLeftIndex = successorEdgeLeftIndex;
} else {
if (!currentInterval.leftInterval()) {
throw std::runtime_error("Should not get here without left interval");
}
const LineSegment &leftInterval = *currentInterval.leftInterval();
bool createdProjectedPoint{false};
if (currentInterval.intervalLeftIsConstraintVertex() && *currentInterval.leftIndex != successorEdgeLeftIndex) {
VLOG(1) << "Left of interval is constraint and the left of the edge is a different point";
// Check if the successor edge intersects with the left of the interval.
Vector intersectionPoint1, intersectionPoint2;
int intersectionCount = math::lineSegmentIntersectsWithCircle(successorEdgeLeftPoint, successorEdgeRightPoint, currentInterval.leftPoint, config_.agentRadius(), &intersectionPoint1, &intersectionPoint2);
VLOG(1) << "Checking if segment Segment(" << '(' << successorEdgeLeftPoint.x() << ',' << successorEdgeLeftPoint.y() << ')' << ',' << '(' << successorEdgeRightPoint.x() << ',' << successorEdgeRightPoint.y() << ')' << ") intersects with point at " << currentInterval.leftPoint.x() << ',' << currentInterval.leftPoint.y();
if (intersectionCount > 0) {
// Only use this intersection if it is not inside the right point of the successor edge (if that point is a constraint).
VLOG(1) << "[bendThatMfRoundTheLeft] Itersection count is " << intersectionCount;
if (!isAConstraintVertexForState(currentState, successorEdgeLeftIndex) || math::distanceSquared(intersectionPoint1, successorEdgeLeftPoint) > config_.agentRadius()*config_.agentRadius()) {
successorEdgeIntersectsWithLeftOfInterval = true;
// One interval will be
// root: same as current
// left: currentInterval.left
// right: successorEdgeRightPoint, successorEdgeRightIndex
projectedLeftPoint = currentInterval.leftPoint;
projectedLeftIndex = currentInterval.leftIndex;
createdProjectedPoint = true;
if (intersectionCount == 2) {
VLOG(1) << "Oh. hmm";
// TODO:
// If there are two intersection points, there will be another interval which is
// root: currentInterval.left
// left: currentInterval.left
// right: successorEdgeLeftPoint, successorEdgeLeftIndex
// throw std::runtime_error("Still need to handle");
}
}
}
} else {
VLOG(1) << "Left is not a constraint";
}
if (!createdProjectedPoint) {
VLOG(1) << "Havent yet created a projected point";
math::IntersectionResult intersectionResult;
double t1, t2;
if (math::equal(leftInterval.first, leftInterval.second)) {
VLOG(1) << absl::StreamFormat("Left interval has length %.20f", math::distance(leftInterval.first, leftInterval.second));
// Left interval has 0-length, create a fake temporary vector for an intersection test.
Vector tangentStart, tangentEnd;
if (!currentInterval.intervalLeftIsConstraintVertex()) {
// How do we create a temporary left interval if the left isnt a constraint?
// Is there a root point and is this left interval on it?
if (currentInterval.rootIndex && math::equal(math::distanceSquared(currentInterval.rootPoint, leftInterval.first), config_.agentRadius()*config_.agentRadius())) {
std::tie(tangentStart, tangentEnd) = math::createVectorTangentToPointOnCircle(currentInterval.rootPoint, config_.agentRadius(), leftInterval.first);
} else {
VLOG(1) << "currentInterval.rootIndex: " << (bool)currentInterval.rootIndex;
VLOG(1) << absl::StreamFormat("Distance squared from %.5f,%.5f to %.5f,%.5f is %.10f which==?:%v, diff=%.20f", currentInterval.rootPoint.x(), currentInterval.rootPoint.y(), leftInterval.first.x(), leftInterval.first.y(), math::distanceSquared(currentInterval.rootPoint, leftInterval.first), math::distanceSquared(currentInterval.rootPoint, leftInterval.first) == config_.agentRadius()*config_.agentRadius(), math::distanceSquared(currentInterval.rootPoint, leftInterval.first) - config_.agentRadius()*config_.agentRadius());
throw std::runtime_error("Unseen case 0");
}
} else {
std::tie(tangentStart, tangentEnd) = math::createVectorTangentToPointOnCircle(currentInterval.leftPoint, config_.agentRadius(), leftInterval.first);
VLOG(1) << "Created tmp interval as Segment(" << '(' << tangentStart.x() << ',' << tangentStart.y() << ')' << ',' << '(' << tangentEnd.x() << ',' << tangentEnd.y() << ')' << ")";
}
intersectionResult = math::intersectForIntervals(tangentStart, tangentEnd, successorEdgeLeftPoint, successorEdgeRightPoint, &t1, &t2);
} else {
intersectionResult = math::intersectForIntervals(leftInterval.first, leftInterval.second, successorEdgeLeftPoint, successorEdgeRightPoint, &t1, &t2);
}
if (math::equal(t2, 0.0, kEndpointIntersectionPrecision)) {
// Left point is actually the left of the edge.
projectedLeftPoint = successorEdgeLeftPoint;
projectedLeftIndex = successorEdgeLeftIndex;
} else if (math::equal(t2, 1.0, kEndpointIntersectionPrecision)) {
// Left point is actually the right of the edge.
projectedLeftPoint = successorEdgeRightPoint;
projectedLeftIndex = successorEdgeRightIndex;
} else {
projectedLeftPoint = successorEdgeLeftPoint + t2 * (successorEdgeRightPoint - successorEdgeLeftPoint);
VLOG(1) << "Created projected point " << projectedLeftPoint.x() << ',' << projectedLeftPoint.y();
}
}
if (!currentInterval.intervalLeftIsConstraintVertex()) {
// Left of interval is not a constraint, but the interval could intersect with a constraint on the way to the successor edge.
// Extend left interval out to successor.
VLOG(1) << "Checking if left interval intersects with a constraint on the way to the successor edge";
double i1, i2;
auto intersectionResult = math::intersectForIntervals(leftInterval.first, leftInterval.second, successorEdgeLeftPoint, successorEdgeRightPoint, &i1, &i2);
if (!math::lessThan(i2, 0.0) && !math::lessThan(1.0, i2)) {
VLOG(1) << "This does intersect with the successor edge";
const Vector leftIntervalIntersectionWithSuccessorEdge = successorEdgeLeftPoint + (successorEdgeRightPoint - successorEdgeLeftPoint) * i2;
// For now, we only check if this intersects with the currrent entry edge's left.
// TODO: Check if this line intersects with any other constraint vertices within range.
const auto [currentEdgeLeftPoint, currentEdgeLeftIndex, currentEdgeRightPoint, currentEdgeRightIndex] = getLeftAndRight(currentState);
if (isAConstraintVertexForState(currentState, currentEdgeLeftIndex)) {
VLOG(1) << "Left of current edge is a constraint";
Vector intersectionPoint1, intersectionPoint2;
auto intersectionResult2 = math::lineSegmentIntersectsWithCircle(leftInterval.first, leftIntervalIntersectionWithSuccessorEdge, currentEdgeLeftPoint, config_.agentRadius(), &intersectionPoint1, &intersectionPoint2);
// Weed out the tangential intersections.
const bool actuallyIntersected = internal::lineActuallyIntersectedWithCircle(leftInterval.first, leftIntervalIntersectionWithSuccessorEdge, currentEdgeLeftPoint, config_.agentRadius(), intersectionResult2, intersectionPoint1, intersectionPoint2);
if (actuallyIntersected) {
VLOG(1) << "Augmented left interval Segment(" << '(' << leftInterval.first.x() << ',' << leftInterval.first.y() << "),(" << leftIntervalIntersectionWithSuccessorEdge.x() << ',' << leftIntervalIntersectionWithSuccessorEdge.y() << ')' << ") intersects with left of current edge point " << currentEdgeLeftIndex;
return {currentEdgeLeftPoint, currentEdgeLeftIndex, std::nullopt};
}
}
}
}
}
// The right of the interval might not be a vertex, but the right interval extended out to the next edge might pass through the right vertex of the successor edge.
std::optional<std::pair<Vector, IndexType>> leftConstraint;
if (!successorEdgeIntersectsWithLeftOfInterval) {
if (!currentInterval.leftIsRoot() && isAConstraintVertexForState(currentState, successorEdgeLeftIndex) && math::lineSegmentIntersectsWithCircle(currentInterval.leftInterval()->first, projectedLeftPoint, successorEdgeLeftPoint, config_.agentRadius()) == 2) {
const auto [lineStart, lineEnd] = math::createCircleConsciousLine(currentInterval.leftInterval()->first, AngleDirection::kNoDirection, successorEdgeLeftPoint, AngleDirection::kCounterclockwise, config_.agentRadius());
double t1_2, t2_2;
auto intersectionResult2 = math::intersectForIntervals(lineStart, lineEnd, successorEdgeLeftPoint, successorEdgeRightPoint, &t1_2, &t2_2);
(void)intersectionResult2;
projectedLeftPoint = lineStart + t1_2 * (lineEnd - lineStart);
leftConstraint.emplace(successorEdgeLeftPoint, successorEdgeLeftIndex);
} else if (currentInterval.intervalLeftIsConstraintVertex()) {
leftConstraint.emplace(currentInterval.leftPoint, *currentInterval.leftIndex);
}
}
// If the root of the interval is a constraint, the left of the interval is not a constraint, and the left of the interval is inside the root, return the root as a left constraint.
if (!leftConstraint && currentInterval.rootIndex && currentInterval.rootDirection != AngleDirection::kNoDirection && !currentInterval.intervalLeftIsConstraintVertex()) {
if (math::distanceSquared(currentInterval.rootPoint, currentInterval.leftPoint) < config_.agentRadius()*config_.agentRadius()) {
VLOG(1) << "Left is inside the root";
leftConstraint.emplace(currentInterval.rootPoint, *currentInterval.rootIndex);
}
}
return {projectedLeftPoint, projectedLeftIndex, leftConstraint};
}
template<typename NavmeshType>
std::pair<Vector,Vector> Pathfinder<NavmeshType>::createTempRightIntervalForCrossProduct(const IntervalType ¤tInterval, const Vector &point) const {
if (currentInterval.rootDirection == AngleDirection::kNoDirection) {
// Order doesnt matter?
return math::createPerpendicularBisector(currentInterval.rightPoint, currentInterval.rootPoint, /*bisectorLength=*/1);
} else if (currentInterval.rootDirection == AngleDirection::kClockwise) {
return math::createPerpendicularBisector(point, currentInterval.rootPoint, /*bisectorLength=*/1);
} else {
return math::createPerpendicularBisector(currentInterval.rootPoint, point, /*bisectorLength=*/1);
}
}
template<typename NavmeshType>
std::pair<Vector,Vector> Pathfinder<NavmeshType>::createTempLeftIntervalForCrossProduct(const IntervalType ¤tInterval, const Vector &point) const {
if (currentInterval.rootDirection == AngleDirection::kNoDirection) {
// Order doesnt matter?
return math::createPerpendicularBisector(currentInterval.leftPoint, currentInterval.rootPoint, /*bisectorLength=*/1);
} else if (currentInterval.rootDirection == AngleDirection::kClockwise) {
return math::createPerpendicularBisector(point, currentInterval.rootPoint, /*bisectorLength=*/1);
} else {
return math::createPerpendicularBisector(currentInterval.rootPoint, point, /*bisectorLength=*/1);
}
}
template<typename NavmeshType>
std::pair<bool,bool> Pathfinder<NavmeshType>::booberGobblin(
const std::optional<IndexType> successorEdgeLeftIndex,
const std::optional<IndexType> successorEdgeRightIndex,
const IntervalType ¤tInterval,
const Vector &toDestinationStart,
const Vector &toDestinationEnd) const {
VLOG(1) << absl::StreamFormat("Blop is looking at Segment((%.20f,%.20f),(%.20f,%.20f))", toDestinationStart.x(), toDestinationStart.y(), toDestinationEnd.x(), toDestinationEnd.y());
if (!currentInterval.leftIsRoot() && !currentInterval.leftInterval()) {
throw std::runtime_error("left is not root and dont have an interval");
}
if (!currentInterval.rightIsRoot() && !currentInterval.rightInterval()) {
throw std::runtime_error("right is not root and dont have an interval");
}
if (!currentInterval.state.hasEntryEdgeIndex()) {
throw std::runtime_error("This function expects the current interval to have a state with a entry edge. i.e., not the Start state");
}
bool finalIsLeftOfLeftInterval;
bool finalIsRightOfRightInterval;
// Handle the left of the interval
if (currentInterval.leftIsRoot()) {
finalIsLeftOfLeftInterval = false;
} else {
if (!currentInterval.leftInterval()) {
// We must have a left interval.
throw std::runtime_error("Left is not root and dont have a left interval");
}
const LineSegment &leftInterval = *currentInterval.leftInterval();
if (math::equal(leftInterval.first, leftInterval.second)) {
// Left interval is 0-length.
// I think this only occurs when right is root and the left of the currentInterval is another constraint touching the constraint of the right.
// Create a new temporary interval that would have the same direction/angle as if this interval had an actual length.
const auto [tmpStart, tmpEnd] = createTempLeftIntervalForCrossProduct(currentInterval, leftInterval.first);
// Use the temporary interval for angle comparison
finalIsLeftOfLeftInterval = math::lessThan(0.0, math::crossProductForSign(tmpStart, tmpEnd, toDestinationStart, toDestinationEnd));
} else {
// Left interval is not 0-length.
if (currentInterval.leftIntervalToCurrentEntryEdge()) {
const LineSegment &leftIntervalToCurrentEntryEdge = *currentInterval.leftIntervalToCurrentEntryEdge();
if (currentInterval.leftIndex) {
// leftIntervalToCurrentEntryEdge is useful.
// Which end is closer?
const auto lengthOfLeftInterval = math::distanceSquared(leftInterval.first, leftInterval.second);
const auto lengthOfLeftIntervalToCurrentEntryEdge = math::distanceSquared(leftIntervalToCurrentEntryEdge.first, leftIntervalToCurrentEntryEdge.second);
const auto lengthOfToDestination = math::distanceSquared(toDestinationStart, toDestinationEnd);
// If the length of the given segment is longer than the left interval, then use the left interval for the cross product
if (lengthOfToDestination >= lengthOfLeftInterval) {
finalIsLeftOfLeftInterval = math::lessThan(0.0, math::crossProductForSign(leftInterval.first, leftInterval.second, toDestinationStart, toDestinationEnd));
} else {
// The given segment is shorter than the left interval
if (lengthOfLeftIntervalToCurrentEntryEdge < lengthOfLeftInterval) {
// Interval to entry edge is closer, use that as the interval for our cross product.
finalIsLeftOfLeftInterval = math::lessThan(0.0, math::crossProductForSign(leftIntervalToCurrentEntryEdge.first, leftIntervalToCurrentEntryEdge.second, toDestinationStart, toDestinationEnd));
} else {
// Regular interval is closer.
finalIsLeftOfLeftInterval = math::lessThan(0.0, math::crossProductForSign(leftInterval.first, leftInterval.second, toDestinationStart, toDestinationEnd));
}
}
} else {
// Dont need leftIntervalToCurrentEntryEdge.