forked from electronicarts/CnC_Generals_Zero_Hour
-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathAIPathfind.cpp
More file actions
11378 lines (10113 loc) · 329 KB
/
Copy pathAIPathfind.cpp
File metadata and controls
11378 lines (10113 loc) · 329 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
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// AIPathfind.cpp
// AI pathfinding system
// Author: Michael S. Booth, October 2001
#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine
#include "GameLogic/AIPathfind.h"
#include "Common/PerfTimer.h"
#include "Common/Player.h"
#include "Common/CRCDebug.h"
#include "Common/GlobalData.h"
#include "Common/LatchRestore.h"
#include "Common/ThingTemplate.h"
#include "Common/ThingFactory.h"
#include "GameClient/Line2D.h"
#include "GameLogic/AI.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/PhysicsUpdate.h"
#include "GameLogic/Object.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/TerrainLogic.h"
#include "GameLogic/Weapon.h"
#if RETAIL_COMPATIBLE_PATHFINDING
#include "GameClient/InGameUI.h"
#include "GameClient/GameText.h"
#include "Common/GameAudio.h"
#include "Common/MiscAudio.h"
#endif
#include "Common/UnitTimings.h" //Contains the DO_UNIT_TIMINGS define jba.
#define no_INTENSE_DEBUG
#define DEBUG_QPF
#ifdef INTENSE_DEBUG
#include "GameLogic/ScriptEngine.h"
#endif
#include "Common/Xfer.h"
#include "Common/XferCRC.h"
//------------------------------------------------------------------------------ Performance Timers
#include "Common/PerfMetrics.h"
//-------------------------------------------------------------------------------------------------
static inline Bool IS_IMPASSABLE(PathfindCell::CellType type) {
// Return true if cell is impassable to ground units. jba. [8/18/2003]
if (type==PathfindCell::CELL_IMPASSABLE) {
return true;
}
if (type==PathfindCell::CELL_OBSTACLE) {
return true;
}
if (type==PathfindCell::CELL_BRIDGE_IMPASSABLE) {
return true;
}
return false;
}
struct TCheckMovementInfo
{
// Input
ICoord2D cell;
PathfindLayerEnum layer;
Int radius;
Bool centerInCell;
Bool considerTransient;
LocomotorSurfaceTypeMask acceptableSurfaces;
// Output
Int allyFixedCount;
Bool enemyFixed;
Bool allyMoving;
Bool allyGoal;
};
inline Int IABS(Int x) { if (x>=0) return x; return -x;};
//-----------------------------------------------------------------------------------
static Int frameToShowObstacles;
constexpr const UnsignedInt ZONE_UPDATE_FREQUENCY = 300;
constexpr const UnsignedInt MAX_CELL_COUNT = 500;
constexpr const UnsignedInt MAX_ADJUSTMENT_CELL_COUNT = 400;
constexpr const UnsignedInt MAX_SAFE_PATH_CELL_COUNT = 2000;
constexpr const UnsignedInt PATHFIND_CELLS_PER_FRAME = 5000; // Number of cells we will search pathfinding per frame.
constexpr const UnsignedInt CELL_INFOS_TO_ALLOCATE = 30000;
//-----------------------------------------------------------------------------------
PathNode::PathNode() :
m_nextOpti(nullptr),
m_next(nullptr),
m_prev(nullptr),
m_nextOptiDist2D(0),
m_canOptimize(false),
m_id(-1)
{
m_nextOptiDirNorm2D.x = 0;
m_nextOptiDirNorm2D.y = 0;
m_pos.zero();
m_layer = LAYER_INVALID;
}
//-----------------------------------------------------------------------------------
PathNode::~PathNode()
{
}
//-----------------------------------------------------------------------------------
void PathNode::setNextOptimized(PathNode *node)
{
m_nextOpti = node;
if (node)
{
m_nextOptiDirNorm2D.x = node->getPosition()->x - getPosition()->x;
m_nextOptiDirNorm2D.y = node->getPosition()->y - getPosition()->y;
m_nextOptiDist2D = m_nextOptiDirNorm2D.length();
if (m_nextOptiDist2D == 0.0f)
{
//DEBUG_LOG(("Warning - Path Seg length == 0, adjusting. john a."));
m_nextOptiDist2D = 0.01f;
}
m_nextOptiDirNorm2D.x /= m_nextOptiDist2D;
m_nextOptiDirNorm2D.y /= m_nextOptiDist2D;
}
else
{
m_nextOptiDist2D = 0;
}
}
//-----------------------------------------------------------------------------------
/// given a list, prepend this node, return new list
PathNode *PathNode::prependToList( PathNode *list )
{
m_next = list;
if (list)
list->m_prev = this;
m_prev = nullptr;
return this;
}
//-----------------------------------------------------------------------------------
/// given a list, append this node, return new list. slow implementation.
/// @todo optimize this
PathNode *PathNode::appendToList( PathNode *list )
{
if (list == nullptr)
{
m_next = nullptr;
m_prev = nullptr;
return this;
}
PathNode *tail;
for( tail = list; tail->m_next; tail = tail->m_next )
;
tail->m_next = this;
m_prev = tail;
m_next = nullptr;
return list;
}
//-----------------------------------------------------------------------------------
/// given a node, append new node to this.
void PathNode::append( PathNode *newNode )
{
newNode->m_next = this->m_next;
newNode->m_prev = this;
if (newNode->m_next) {
newNode->m_next->m_prev = newNode;
}
this->m_next = newNode;
}
//-----------------------------------------------------------------------------------
/**
* Compute direction vector to next node
*/
const Coord3D *PathNode::computeDirectionVector()
{
static Coord3D dir;
if (m_next == nullptr)
{
if (m_prev == nullptr)
{
// only one node on whole path - no direction
dir.x = 0.0f;
dir.y = 0.0f;
dir.z = 0.0f;
}
else
{
// tail node - continue prior direction
return m_prev->computeDirectionVector();
}
}
else
{
dir.x = m_next->m_pos.x - m_pos.x;
dir.y = m_next->m_pos.y - m_pos.y;
dir.z = m_next->m_pos.z - m_pos.z;
}
return &dir;
}
//-----------------------------------------------------------------------------------
Path::Path():
m_path(nullptr),
m_pathTail(nullptr),
m_isOptimized(FALSE),
m_blockedByAlly(FALSE),
m_cpopRecentStart(nullptr),
m_cpopCountdown(MAX_CPOP),
m_cpopValid(FALSE)
{
m_cpopIn.zero();
m_cpopOut.distAlongPath=0;
m_cpopOut.layer = LAYER_GROUND;
m_cpopOut.posOnPath.zero();
}
Path::~Path()
{
PathNode *node, *nextNode;
// delete all of the path nodes
for( node = m_path; node; node = nextNode )
{
nextNode = node->getNext();
deleteInstance(node);
}
}
// ------------------------------------------------------------------------------------------------
/** CRC */
// ------------------------------------------------------------------------------------------------
void Path::crc( Xfer *xfer )
{
}
// ------------------------------------------------------------------------------------------------
/** Xfer Method */
// ------------------------------------------------------------------------------------------------
void Path::xfer( Xfer *xfer )
{
// version
XferVersion currentVersion = 1;
XferVersion version = currentVersion;
xfer->xferVersion( &version, currentVersion );
PathNode *node = m_path;
Int count = 0;
while (node) {
count++;
node = node->getNext();
}
xfer->xferInt(&count);
if (xfer->getXferMode() == XFER_SAVE) {
node = m_pathTail; // Write them out backwards.
while (node) {
node->m_id = count;
xfer->xferInt(&count);
Coord3D pos = *node->getPosition();
xfer->xferCoord3D(&pos);
PathfindLayerEnum layer = node->getLayer();
xfer->xferUser(&layer, sizeof(layer));
Bool canOpt = node->getCanOptimize();
xfer->xferBool(&canOpt);
Int id = -1;
if (node->getNextOptimized()) {
id = node->getNextOptimized()->m_id;
}
xfer->xferInt(&id);
count--;
node = node->getPrevious();
}
DEBUG_ASSERTCRASH(count==0, ("Wrong data count"));
} else {
m_cpopValid = FALSE;
while (count) {
Int nodeId;
xfer->xferInt(&nodeId);
DEBUG_ASSERTCRASH(nodeId==count, ("Bad data"));
Coord3D pos;
xfer->xferCoord3D(&pos);
PathfindLayerEnum layer;
xfer->xferUser(&layer, sizeof(layer));
Bool canOpt;
xfer->xferBool(&canOpt);
Int optID = -1;
xfer->xferInt(&optID);
PathNode *node = newInstance(PathNode);
node->m_id = nodeId;
node->setPosition(&pos);
node->setLayer(layer);
node->setCanOptimize(canOpt);
PathNode *optNode = nullptr;
if (optID > 0) {
optNode = m_path;
while (optNode && optNode->m_id != optID) {
optNode = optNode->getNext();
}
DEBUG_ASSERTCRASH (optNode && optNode->m_id == optID, ("Could not find optimized link."));
}
m_path = node->prependToList(m_path);
if (m_pathTail == nullptr)
m_pathTail = node;
if (optNode) {
node->setNextOptimized(optNode);
}
count--;
}
}
xfer->xferBool(&m_isOptimized);
Int obsolete1 = 0;
xfer->xferInt(&obsolete1);
UnsignedInt obsolete2;
xfer->xferUnsignedInt(&obsolete2);
xfer->xferBool(&m_blockedByAlly);
#if defined(RTS_DEBUG)
if (TheGlobalData->m_debugAI == AI_DEBUG_PATHS)
{
extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color);
RGBColor color;
color.blue = 0;
color.red = color.green = 1;
Coord3D pos;
addIcon(nullptr, 0, 0, color); // erase feedback.
for( PathNode *node = getFirstNode(); node; node = node->getNext() )
{
// create objects to show path - they decay
pos = *node->getPosition();
addIcon(&pos, PATHFIND_CELL_SIZE_F*.25f, 200, color);
}
// show optimized path
for( node = getFirstNode(); node; node = node->getNextOptimized() )
{
pos = *node->getPosition();
addIcon(&pos, PATHFIND_CELL_SIZE_F*.8f, 200, color);
}
TheAI->pathfinder()->setDebugPath(this);
}
#endif
}
// ------------------------------------------------------------------------------------------------
/** Load post process */
// ------------------------------------------------------------------------------------------------
void Path::loadPostProcess()
{
}
/**
* Create a new node at the head of the path
*/
void Path::prependNode( const Coord3D *pos, PathfindLayerEnum layer )
{
PathNode *node = newInstance(PathNode);
node->setPosition( pos );
node->setLayer(layer);
m_path = node->prependToList( m_path );
if (m_pathTail == nullptr)
m_pathTail = node;
m_isOptimized = false;
#ifdef CPOP_STARTS_FROM_PREV_SEG
m_cpopRecentStart = nullptr;
#endif
}
/**
* Create a new node at the tail of the path
*/
void Path::appendNode( const Coord3D *pos, PathfindLayerEnum layer )
{
if (m_isOptimized && m_pathTail)
{
/* Check for duplicates. */
if (pos->x == m_pathTail->getPosition()->x && pos->y == m_pathTail->getPosition()->y) {
DEBUG_LOG(("Warning - Path Seg length == 0, ignoring. john a."));
return;
}
}
PathNode *node = newInstance(PathNode);
node->setPosition( pos );
node->setLayer(layer);
m_path = node->appendToList( m_path );
if (m_isOptimized && m_pathTail)
{
m_pathTail->setNextOptimized(node);
}
m_pathTail = node;
#ifdef CPOP_STARTS_FROM_PREV_SEG
m_cpopRecentStart = nullptr;
#endif
}
/**
* Create a new node at the tail of the path
*/
void Path::updateLastNode( const Coord3D *pos )
{
PathfindLayerEnum layer = TheTerrainLogic->getLayerForDestination(pos);
if (m_pathTail) {
m_pathTail->setPosition(pos);
m_pathTail->setLayer(layer);
}
if (m_isOptimized && m_pathTail)
{
PathNode *node = m_path;
while(node && node->getNextOptimized() != m_pathTail) {
node = node->getNextOptimized();
}
if (node && node->getNextOptimized() == m_pathTail) {
node->setNextOptimized(m_pathTail);
}
}
}
/**
* Optimize the path by checking line of sight
*/
void Path::optimize( const Object *obj, LocomotorSurfaceTypeMask acceptableSurfaces, Bool blocked )
{
PathNode *node, *anchor;
// start with first node in the path
anchor = getFirstNode();
Bool firstNode = true;
PathfindLayerEnum firstLayer = anchor->getLayer();
// backwards.
//
// For each node in the path, check LOS from last node in path, working forward.
// When a clear LOS is found, keep the resulting straight line segment.
//
while( anchor != getLastNode() )
{
// find the farthest node in the path that has a clear line-of-sight to this anchor
Bool optimizedSegment = false;
PathfindLayerEnum layer = anchor->getLayer();
PathfindLayerEnum curLayer = anchor->getLayer();
Int count = 0;
const Int ALLOWED_STEPS = 3; // we can optimize 3 steps to or from a bridge. Otherwise, we need to insert a point. jba.
for (node = anchor->getNext(); node->getNext(); node=node->getNext()) {
count++;
if (curLayer==LAYER_GROUND) {
if (node->getLayer() != curLayer) {
layer = node->getLayer();
curLayer = layer;
if (count > ALLOWED_STEPS) break;
}
} else {
if (node->getNext()->getLayer() != curLayer) {
if (count > ALLOWED_STEPS) break;
}
}
curLayer = node->getLayer();
if (node->getCanOptimize()==false) {
break;
}
}
if (firstNode) {
layer = firstLayer;
firstNode = false;
}
//PathfindLayerEnum curLayer = LAYER_GROUND;
for( ; node != anchor; node = node->getPrevious() )
{
Bool isPassable = false;
//CRCDEBUG_LOG(("Path::optimize() calling isLinePassable()"));
if (TheAI->pathfinder()->isLinePassable( obj, acceptableSurfaces, layer, *anchor->getPosition(),
*node->getPosition(), blocked, false))
{
isPassable = true;
}
PathfindCell* cell = TheAI->pathfinder()->getCell( layer, node->getPosition());
if (cell && cell->getType()==PathfindCell::CELL_CLIFF && !cell->getPinched()) {
isPassable = true;
}
// Horizontal, diagonal, and vertical steps are passable.
if (!isPassable) {
Int dx = node->getPosition()->x - anchor->getPosition()->x;
Int dy = node->getPosition()->y - anchor->getPosition()->y;
Bool mightBePassable = false;
if (IABS(dx)==PATHFIND_CELL_SIZE && IABS(dy)==PATHFIND_CELL_SIZE) {
isPassable = true;
}
PathNode *tmpNode;
if (dx==0) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dx = tmpNode->getNext()->getPosition()->x - tmpNode->getPosition()->x;
if (dx!=0) mightBePassable = false;
}
}
if (dy==0) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dy = tmpNode->getNext()->getPosition()->y - tmpNode->getPosition()->y;
if (dy!=0) mightBePassable = false;
}
}
if (dx == dy) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dx = tmpNode->getNext()->getPosition()->x - tmpNode->getPosition()->x;
dy = tmpNode->getNext()->getPosition()->y - tmpNode->getPosition()->y;
if (dy!=dx) mightBePassable = false;
}
}
if (dx == -dy) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dx = tmpNode->getNext()->getPosition()->x - tmpNode->getPosition()->x;
dy = tmpNode->getNext()->getPosition()->y - tmpNode->getPosition()->y;
if (dy!=-dx) mightBePassable = false;
}
}
if (mightBePassable) {
isPassable = true;
}
}
if (isPassable)
{
// anchor can directly see this node, make it next in the optimized path
anchor->setNextOptimized( node );
anchor = node;
optimizedSegment = true;
break;
}
}
if (optimizedSegment == false)
{
// for some reason, there is no clear LOS between the anchor node and the very next node
anchor->setNextOptimized( anchor->getNext() );
anchor = anchor->getNext();
}
}
// the path has been optimized
m_isOptimized = true;
}
/**
* Optimize the path by checking line of sight
*/
void Path::optimizeGroundPath( Bool crusher, Int pathDiameter )
{
PathNode *node, *anchor;
// start with first node in the path
anchor = getFirstNode();
//
// For each node in the path, check LOS from last node in path, working forward.
// When a clear LOS is found, keep the resulting straight line segment.
//
while( anchor != getLastNode() )
{
// find the farthest node in the path that has a clear line-of-sight to this anchor
Bool optimizedSegment = false;
PathfindLayerEnum layer = anchor->getLayer();
PathfindLayerEnum curLayer = anchor->getLayer();
Int count = 0;
const Int ALLOWED_STEPS = 3; // we can optimize 3 steps to or from a bridge. Otherwise, we need to insert a point. jba.
for (node = anchor->getNext(); node->getNext(); node=node->getNext()) {
count++;
if (curLayer==LAYER_GROUND) {
if (node->getLayer() != curLayer) {
layer = node->getLayer();
curLayer = layer;
if (count > ALLOWED_STEPS) break;
}
} else {
if (node->getNext()->getLayer() != curLayer) {
if (count > ALLOWED_STEPS) break;
}
}
curLayer = node->getLayer();
}
// find the farthest node in the path that has a clear line-of-sight to this anchor
for( ; node != anchor; node = node->getPrevious() )
{
Bool isPassable = false;
//CRCDEBUG_LOG(("Path::optimize() calling isLinePassable()"));
if (TheAI->pathfinder()->isGroundPathPassable( crusher, *anchor->getPosition(), layer,
*node->getPosition(), pathDiameter))
{
isPassable = true;
}
// Horizontal, diagonal, and vertical steps are passable.
if (!isPassable) {
Int dx = node->getPosition()->x - anchor->getPosition()->x;
Int dy = node->getPosition()->y - anchor->getPosition()->y;
Bool mightBePassable = false;
PathNode *tmpNode;
if (dx==0) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dx = tmpNode->getNext()->getPosition()->x - tmpNode->getPosition()->x;
if (dx!=0) mightBePassable = false;
}
}
if (dy==0) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dy = tmpNode->getNext()->getPosition()->y - tmpNode->getPosition()->y;
if (dy!=0) mightBePassable = false;
}
}
if (dx == dy) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dx = tmpNode->getNext()->getPosition()->x - tmpNode->getPosition()->x;
dy = tmpNode->getNext()->getPosition()->y - tmpNode->getPosition()->y;
if (dy!=dx) mightBePassable = false;
}
}
if (dx == -dy) {
mightBePassable = true;
for (tmpNode = node->getPrevious(); tmpNode && tmpNode != anchor; tmpNode = tmpNode->getPrevious()) {
dx = tmpNode->getNext()->getPosition()->x - tmpNode->getPosition()->x;
dy = tmpNode->getNext()->getPosition()->y - tmpNode->getPosition()->y;
if (dy!=-dx) mightBePassable = false;
}
}
if (mightBePassable) {
isPassable = true;
}
}
if (isPassable)
{
// anchor can directly see this node, make it next in the optimized path
anchor->setNextOptimized( node );
anchor = node;
optimizedSegment = true;
break;
}
}
if (optimizedSegment == false)
{
// for some reason, there is no clear LOS between the anchor node and the very next node
anchor->setNextOptimized( anchor->getNext() );
anchor = anchor->getNext();
}
}
// Remove jig/jogs :) jba.
for (anchor=getFirstNode(); anchor!=nullptr; anchor=anchor->getNextOptimized()) {
node = anchor->getNextOptimized();
if (node && node->getNextOptimized()) {
Real dx = node->getPosition()->x - anchor->getPosition()->x;
Real dy = node->getPosition()->y - anchor->getPosition()->y;
// If the x & y offsets are less than 2 pathfind cells, kill it.
if (dx*dx+dy*dy < sqr(PATHFIND_CELL_SIZE_F)*3.9f) {
anchor->setNextOptimized(node->getNextOptimized());
}
}
}
// the path has been optimized
m_isOptimized = true;
}
inline Bool isReallyClose(const Coord3D& a, const Coord3D& b)
{
const Real CLOSE_ENOUGH = 0.1f;
return
WWMath::FAbs_Origin(a.x-b.x) <= CLOSE_ENOUGH &&
WWMath::FAbs_Origin(a.y-b.y) <= CLOSE_ENOUGH &&
WWMath::FAbs_Origin(a.z-b.z) <= CLOSE_ENOUGH;
}
/**
* Given a location, return the closest position on the path.
* If 'allowBacktrack' is true, the entire path is considered.
* If it is false, the point computed cannot be prior to previously returned non-backtracking points on this path.
* Because the path "knows" the direction of travel, it will "lead" the given position a bit
* to ensure the path is followed in the intended direction.
*
* Note: The path cleanup does not take into account rolling terrain, so we can end up with
* these situations:
*
* B
* ######
* ##########
* A-##----------##---C
* #######################
*
*
* When an agent gets to B, he seems far off of the path, but it really not.
* There are similar problems with valleys.
*
* Since agents track the closest path, if a high hill gets close to the underside of
* a bridge, an agent may 'jump' to the higher path. This must be avoided in maps.
*
* return along-path distance to the end will be returned as function result
*/
void Path::computePointOnPath(
const Object* obj,
const LocomotorSet& locomotorSet,
const Coord3D& pos,
ClosestPointOnPathInfo& out
)
{
CRCDEBUG_LOG(("Path::computePointOnPath() for %s", DebugDescribeObject(obj).str()));
out.layer = LAYER_GROUND;
out.posOnPath.zero();
out.distAlongPath = 0;
if (m_path == nullptr)
{
m_cpopValid = false;
return;
}
out.layer = m_path->getLayer();
if (m_cpopValid && m_cpopCountdown>0 && isReallyClose(pos, m_cpopIn))
{
out = m_cpopOut;
m_cpopCountdown--;
CRCDEBUG_LOG(("Path::computePointOnPath() end because we're really close"));
return;
}
m_cpopCountdown = MAX_CPOP;
// default pathPos to end of the path
out.posOnPath = *getLastNode()->getPosition();
const PathNode* closeNode = nullptr;
Coord2D toPos;
Real closeDistSqr = 99999999.9f;
Real totalPathLength = 0.0f;
Real lengthAlongPathToPos = 0.0f;
//
// Find the closest segment of the path
//
#ifdef CPOP_STARTS_FROM_PREV_SEG
const PathNode* prevNode = m_cpopRecentStart;
if (prevNode == nullptr)
prevNode = m_path;
#else
const PathNode* prevNode = m_path;
#endif
Coord2D segmentDirNorm;
Real segmentLength;
// note that the seg dir and len returned by this is the dist & vec from 'prevNode' to 'node'
for ( const PathNode* node = prevNode->getNextOptimized(&segmentDirNorm, &segmentLength);
node != nullptr;
node = node->getNextOptimized(&segmentDirNorm, &segmentLength) )
{
const Coord3D* prevNodePos = prevNode->getPosition();
const Coord3D* nodePos = node->getPosition();
// compute vector from start of segment to pos
toPos.x = pos.x - prevNodePos->x;
toPos.y = pos.y - prevNodePos->y;
// compute distance projection of 'toPos' onto segment
Real alongPathDist = segmentDirNorm.x * toPos.x + segmentDirNorm.y * toPos.y;
Coord3D pointOnPath;
if (alongPathDist < 0.0f)
{
// projected point is before start of segment, use starting point
alongPathDist = 0.0f;
pointOnPath = *prevNodePos;
}
else if (alongPathDist > segmentLength)
{
// projected point is beyond end of segment, use end point
if (node->getNextOptimized() == nullptr)
{
alongPathDist = segmentLength;
pointOnPath = *nodePos;
}
else
{
// beyond the end of this segment, skip this segment
// if bend is sharp, start of next segment will grab this point
// if bend is gradual, the point will project into the next segment
totalPathLength += segmentLength;
prevNode = node;
continue;
}
}
else
{
// projected point is on this segment, compute it
pointOnPath.x = prevNodePos->x + alongPathDist * segmentDirNorm.x;
pointOnPath.y = prevNodePos->y + alongPathDist * segmentDirNorm.y;
pointOnPath.z = 0;
}
// compute distance to point on path, and track the closest we've found so far
Coord2D offset;
offset.x = pos.x - pointOnPath.x;
offset.y = pos.y - pointOnPath.y;
Real offsetDistSqr = offset.x*offset.x + offset.y*offset.y;
if (offsetDistSqr < closeDistSqr)
{
closeDistSqr = offsetDistSqr;
closeNode = prevNode;
out.posOnPath = pointOnPath;
lengthAlongPathToPos = totalPathLength + alongPathDist;
}
// add this segment's length to find total path length
/// @todo Precompute this and store in path
totalPathLength += segmentLength;
prevNode = node;
DUMPCOORD3D(&pointOnPath);
}
#ifdef CPOP_STARTS_FROM_PREV_SEG
m_cpopRecentStart = closeNode;
#endif
//
// Compute the goal movement position for this agent
//
if (closeNode && closeNode->getNextOptimized())
{
// note that the seg dir and len returned by this is the dist & vec from 'closeNode' to 'closeNext'
const PathNode* closeNext = closeNode->getNextOptimized(&segmentDirNorm, &segmentLength);
const Coord3D* nextNodePos = closeNext->getPosition();
const Coord3D* closeNodePos = closeNode->getPosition();
const PathNode* closePrev = closeNode->getPrevious();
if (closePrev && closePrev->getLayer() > LAYER_GROUND)
{
out.layer = closeNode->getLayer();
}
if (closeNode->getLayer() > LAYER_GROUND)
{
out.layer = closeNode->getLayer();
}
if (closeNext->getLayer() > LAYER_GROUND)
{
out.layer = closeNext->getLayer();
}
// compute vector from start of segment to pos
toPos.x = pos.x - closeNodePos->x;
toPos.y = pos.y - closeNodePos->y;
// compute distance projection of 'toPos' onto segment
Real alongPathDist = segmentDirNorm.x * toPos.x + segmentDirNorm.y * toPos.y;
// we know this is the closest segment, so don't allow farther back than the start node
if (alongPathDist < 0.0f)
alongPathDist = 0.0f;
// compute distance of point from this path segment
Real toDistSqr = sqr(toPos.x) + sqr(toPos.y);
Real offsetDistSq = toDistSqr - sqr(alongPathDist);
Real offsetDist = (offsetDistSq <= 0.0) ? 0.0 : WWMath::Sqrt_Origin(offsetDistSq);
// If we are basically on the path, return the next path node as the movement goal.
// However, the farther off the path we get, the movement goal becomes closer to our
// projected position on the path. If we are very far off the path, we will move
// directly towards the nearest point on the path, and not the next path node.
const Real maxPathError = 3.0f * PATHFIND_CELL_SIZE_F;
const Real maxPathErrorInv = 1.0 / maxPathError;
Real k = offsetDist * maxPathErrorInv;
if (k > 1.0f)
k = 1.0f;
Bool gotPos = false;
CRCDEBUG_LOG(("Path::computePointOnPath() calling isLinePassable() 1"));
if (TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos, *nextNodePos,
false, true ))
{
out.posOnPath = *nextNodePos;
gotPos = true;
Bool tryAhead = alongPathDist > segmentLength * 0.5;
if (closeNext->getCanOptimize() == false)
{
tryAhead = false; // don't go past no-opt nodes.
}
if (closeNode->getLayer() != closeNext->getLayer())
{
tryAhead = false; // don't go past layers.
}
if (obj->getLayer()!=LAYER_GROUND) {
tryAhead = false;
}
Bool veryClose = false;
if (segmentLength-alongPathDist<1.0f) {
tryAhead = true;
veryClose = true;
}
if (tryAhead)
{
// try next segment middle.
const PathNode *next = closeNext->getNextOptimized();
if (next)
{
Coord3D tryPos;
tryPos.x = (nextNodePos->x + next->getPosition()->x) * 0.5;
tryPos.y = (nextNodePos->y + next->getPosition()->y) * 0.5;
tryPos.z = nextNodePos->z;
CRCDEBUG_LOG(("Path::computePointOnPath() calling isLinePassable() 2"));
if (veryClose || TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), closeNext->getLayer(), pos, tryPos, false, true ))
{
gotPos = true;
out.posOnPath = tryPos;
}
}
}
}
else if (k > 0.5f)
{
Real tryDist = alongPathDist + (0.5) * (segmentLength - alongPathDist);
// projected point is on this segment, compute it
out.posOnPath.x = closeNodePos->x + tryDist * segmentDirNorm.x;
out.posOnPath.y = closeNodePos->y + tryDist * segmentDirNorm.y;
out.posOnPath.z = closeNodePos->z;
CRCDEBUG_LOG(("Path::computePointOnPath() calling isLinePassable() 3"));
if (TheAI->pathfinder()->isLinePassable( obj, locomotorSet.getValidSurfaces(), out.layer, pos, out.posOnPath, false, true ))
{
k = 0.5f;
gotPos = true;
}
}
// if we are on the path (k == 0), then alongPathDist == segmentLength
// if we are way off the path (k == 1), then alongPathDist is unchanged, and it projection of actual pos
alongPathDist += (1.0f - k) * (segmentLength - alongPathDist);