forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAIUpdate.cpp
More file actions
5014 lines (4428 loc) · 160 KB
/
AIUpdate.cpp
File metadata and controls
5014 lines (4428 loc) · 160 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(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. //
// //
////////////////////////////////////////////////////////////////////////////////
// AIUpdate.cpp //
// Implementation of generic AI mechanisms
// Author: Michael S. Booth, 2001-2002
// Subsequently : John Ahlquist 2002 and a cast of thousands.
#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
#define DEFINE_LOCOMOTORSET_NAMES // for TheLocomotorSetNames[]
#define DEFINE_AUTOACQUIRE_NAMES
#include "Common/ActionManager.h"
#include "Common/GameState.h"
#include "Common/CRCDebug.h"
#include "Common/GlobalData.h"
#include "Common/Player.h"
#include "Common/PlayerList.h"
#include "Common/RandomValue.h"
#include "Common/Team.h"
#include "Common/ThingFactory.h"
#include "Common/ThingTemplate.h"
#include "Common/Upgrade.h"
#include "Common/PerfTimer.h"
#include "Common/UnitTimings.h"
#include "Common/Xfer.h"
#include "Common/XferCRC.h"
#include "GameClient/ControlBar.h"
#include "GameClient/Drawable.h"
#include "GameClient/InGameUI.h" // useful for printing quick debug strings when we need to
#include "GameLogic/AI.h"
#include "GameLogic/AIPathfind.h"
#include "GameLogic/Locomotor.h"
#include "GameLogic/Module/AIUpdate.h"
#include "GameLogic/Module/BodyModule.h"
#include "GameLogic/Module/ContainModule.h"
#include "GameLogic/Module/PhysicsUpdate.h"
#include "GameLogic/Module/ProneUpdate.h"
#include "GameLogic/Module/DeliverPayloadAIUpdate.h"
#include "GameLogic/Module/HackInternetAIUpdate.h"
#include "GameLogic/Module/HordeUpdate.h"
#include "GameLogic/Object.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/PolygonTrigger.h"
#include "GameLogic/ScriptEngine.h"
#include "GameLogic/TurretAI.h"
#include "GameLogic/Weapon.h"
#include "Common/Radar.h" // For TheRadar
#define SLEEPY_AI
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
#endif
//-------------------------------------------------------------------------------------------------
AIUpdateModuleData::AIUpdateModuleData()
{
//m_locomotorTemplates -- nothing to do
for (int i = 0; i < MAX_TURRETS; i++)
m_turretData[i] = NULL;
m_autoAcquireEnemiesWhenIdle = 0;
m_moodAttackCheckRate = LOGICFRAMES_PER_SECOND * 2;
#ifdef ALLOW_SURRENDER
m_surrenderDuration = LOGICFRAMES_PER_SECOND * 120;
#endif
}
//-------------------------------------------------------------------------------------------------
AIUpdateModuleData::~AIUpdateModuleData()
{
for (int i = 0; i < MAX_TURRETS; i++)
{
if (m_turretData[i])
{
TurretAIData* td = const_cast<TurretAIData*>(m_turretData[i]);
if (td)
td->deleteInstance();
}
}
}
//-------------------------------------------------------------------------------------------------
const LocomotorTemplateVector* AIUpdateModuleData::findLocomotorTemplateVector(LocomotorSetType t) const
{
if (m_locomotorTemplates.empty())
return NULL;
LocomotorTemplateMap::const_iterator it = m_locomotorTemplates.find(t);
if (it == m_locomotorTemplates.end())
{
return NULL;
}
else
{
return &(*it).second;
}
}
//-------------------------------------------------------------------------------------------------
/*static*/ void AIUpdateModuleData::buildFieldParse(MultiIniFieldParse& p)
{
ModuleData::buildFieldParse(p);
static const FieldParse dataFieldParse[] =
{
{ "Turret", AIUpdateModuleData::parseTurret, NULL, offsetof(AIUpdateModuleData, m_turretData[0]) },
{ "AltTurret", AIUpdateModuleData::parseTurret, NULL, offsetof(AIUpdateModuleData, m_turretData[1]) },
{ "AutoAcquireEnemiesWhenIdle", INI::parseBitString32, TheAutoAcquireEnemiesNames, offsetof(AIUpdateModuleData, m_autoAcquireEnemiesWhenIdle) },
{ "MoodAttackCheckRate", INI::parseDurationUnsignedInt, NULL, offsetof(AIUpdateModuleData, m_moodAttackCheckRate) },
#ifdef ALLOW_SURRENDER
{ "SurrenderDuration", INI::parseDurationUnsignedInt, NULL, offsetof(AIUpdateModuleData, m_surrenderDuration) },
#endif
{ 0, 0, 0, 0 }
};
p.add(dataFieldParse);
}
//-------------------------------------------------------------------------------------------------
/*static*/ void AIUpdateModuleData::parseTurret(INI* ini, void *instance, void * store, const void* /*userData*/)
{
if (*(TurretAIData**)store)
{
DEBUG_CRASH(("Only one turret to a customer, for now"));
throw INI_INVALID_DATA;
}
TurretAIData* td = newInstance(TurretAIData);
ini->initFromINIMultiProc(td, td->buildFieldParse);
*(TurretAIData**)store = td;
}
//-------------------------------------------------------------------------------------------------
/*static*/ void AIUpdateModuleData::parseLocomotorSet(INI* ini, void *instance, void * /*store*/, const void* /*userData*/)
{
ThingTemplate *tt = (ThingTemplate *)instance;
AIUpdateModuleData *self = tt->friend_getAIModuleInfo();
if (!self)
{
DEBUG_CRASH(("Attempted to specify a locomotor for an object without an AIUpdate block."));
throw INI_INVALID_DATA;
}
LocomotorSetType set = (LocomotorSetType)INI::scanIndexList(ini->getNextToken(), TheLocomotorSetNames);
if (!self->m_locomotorTemplates[set].empty())
{
if (ini->getLoadType() != INI_LOAD_CREATE_OVERRIDES)
{
DEBUG_CRASH(("re-specifying a LocomotorSet is no longer allowed\n"));
throw INI_INVALID_DATA;
}
}
self->m_locomotorTemplates[set].clear();
for (const char* locoName = ini->getNextToken(); locoName; locoName = ini->getNextTokenOrNull())
{
if (!*locoName || !stricmp(locoName, "None"))
continue;
NameKeyType locoKey = NAMEKEY(locoName);
const LocomotorTemplate* lt = TheLocomotorStore->findLocomotorTemplate(locoKey);
if (!lt)
{
DEBUG_CRASH(("Locomotor %s not found!\n",locoName));
throw INI_INVALID_DATA;
}
self->m_locomotorTemplates[set].push_back(lt);
}
}
//-------------------------------------------------------------------------------------------------
// subclasses may want to override this, to use a subclass of AIStateMachine.
AIStateMachine* AIUpdateInterface::makeStateMachine()
{
return newInstance(AIStateMachine)( getObject(), "AIUpdateInterfaceMachine");
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
AIUpdateInterface::AIUpdateInterface( Thing *thing, const ModuleData* moduleData ) :
UpdateModule( thing, moduleData )
{
int i;
m_priorWaypointID = 0xfacade;
m_currentWaypointID = 0xfacade;
m_stateMachine = NULL;
m_nextEnemyScanTime = 0;
m_currentVictimID = INVALID_ID;
m_desiredSpeed = FAST_AS_POSSIBLE;
m_lastCommandSource = CMD_FROM_AI;
m_guardMode = GUARDMODE_NORMAL;
m_guardTargetType[0] = m_guardTargetType[1] = GUARDTARGET_NONE;
m_locationToGuard.zero();
m_objectToGuard = INVALID_ID;
m_areaToGuard = NULL;
m_attackInfo = NULL;
m_waypointCount = 0;
m_waypointIndex = 0;
m_completedWaypoint = NULL;
m_path = NULL;
m_requestedVictimID = INVALID_ID;
m_requestedDestination.zero();
m_requestedDestination2.zero();
m_pathTimestamp = 0;
m_ignoreObstacleID = INVALID_ID;
m_pathExtraDistance = 0;
m_pathfindGoalCell.x = m_pathfindGoalCell.y = -1;
m_pathfindCurCell.x = m_pathfindCurCell.y = -1;
m_blockedFrames = 0;
m_curMaxBlockedSpeed = 0;
m_bumpSpeedLimit = FAST_AS_POSSIBLE;
m_ignoreCollisionsUntil = 0;
m_queueForPathFrame = 0;
m_finalPosition.zero();
m_repulsor1 = INVALID_ID;
m_repulsor2 = INVALID_ID;
m_nextGoalPathIndex = -1;
m_moveOutOfWay1 = INVALID_ID;
m_moveOutOfWay2 = INVALID_ID;
m_locomotorSet.clear();
m_curLocomotor = NULL;
m_curLocomotorSet = LOCOMOTORSET_INVALID;
m_locomotorGoalType = NONE;
m_locomotorGoalData.zero();
for (i = 0; i < MAX_TURRETS; i++)
m_turretAI[i] = NULL;
m_turretSyncFlag = TURRET_INVALID;
m_attitude = ATTITUDE_NORMAL;
m_nextMoodCheckTime = 0;
#ifdef ALLOW_DEMORALIZE
m_demoralizedFramesLeft = 0;
#endif
#ifdef ALLOW_SURRENDER
m_surrenderedFramesLeft = 0;
m_surrenderedPlayerIndex = -1;
#endif
m_crateCreated = INVALID_ID;
m_tmpInt = 0;
m_doFinalPosition = FALSE;
m_waitingForPath = FALSE;
m_isAttackPath = FALSE;
m_isFinalGoal = FALSE;
m_isApproachPath = FALSE;
m_isSafePath = FALSE;
m_movementComplete = FALSE;
m_isMoving = FALSE;
m_isBlocked = FALSE;
m_isBlockedAndStuck = FALSE;
m_upgradedLocomotors = FALSE;
m_canPathThroughUnits = FALSE;
m_randomlyOffsetMoodCheck = FALSE;
m_isAiDead = FALSE;
m_isRecruitable = TRUE; // Things default to being recruitable.
m_executingWaypointQueue = FALSE;
m_retryPath = FALSE;
m_isInUpdate = FALSE;
m_fixLocoInPostProcess = FALSE;
// ---------------------------------------------
for (i = 0; i < MAX_TURRETS; i++)
{
if (getAIUpdateModuleData()->m_turretData[i])
{
m_turretAI[i] = newInstance(TurretAI)(getObject(), getAIUpdateModuleData()->m_turretData[i], (WhichTurretType)i);
}
}
chooseLocomotorSet(LOCOMOTORSET_NORMAL);
#ifdef SLEEPY_AI
setWakeFrame(getObject(), UPDATE_SLEEP_NONE);
#endif
}
#ifdef ALLOW_SURRENDER
//=============================================================================
// Object::setSurrendered, and related methods ================================
//=============================================================================
void AIUpdateInterface::setSurrendered( const Object *objWeSurrenderedTo, Bool surrendered )
{
if (surrendered)
{
Bool wasSurrendered = isSurrendered();
const AIUpdateModuleData* d = getAIUpdateModuleData();
if (m_surrenderedFramesLeft < d->m_surrenderDuration)
m_surrenderedFramesLeft = d->m_surrenderDuration;
const Player* playerWeSurrenderedTo = objWeSurrenderedTo ? objWeSurrenderedTo->getControllingPlayer() : NULL;
m_surrenderedPlayerIndex = playerWeSurrenderedTo ? playerWeSurrenderedTo->getPlayerIndex() : -1;
if (!wasSurrendered)
{
//aiIdle(CMD_FROM_AI);
// srj sez: calling aiIdle() won't work, since we are probably "effectivelyDead"...
// meaning we won't respong to aiDoCommand! so go straight to the metal here:
getStateMachine()->clear();
getStateMachine()->setState( AI_IDLE );
setLastCommandSource(CMD_FROM_AI);
// Play our sound surrendered
AudioEventRTS surrenderSound = *getObject()->getTemplate()->getVoiceSurrender();
surrenderSound.setObjectID(getObject()->getID());
TheAudio->addAudioEvent(&surrenderSound);
}
}
else
{
// GS During the act of surrendering, we dipped to 0 and then were manually set to have hit points.
// That made us alive but marked as Dead. Gotta undo that.
getObject()->setEffectivelyDead( FALSE );
m_surrenderedFramesLeft = 0;
m_surrenderedPlayerIndex = -1;
}
}
#endif
//=============================================================================
void AIUpdateInterface::setGoalPositionClipped(const Coord3D* in, CommandSourceType cmdSource)
{
if (in)
{
Coord3D tmp = *in;
if (cmdSource == CMD_FROM_PLAYER)
{
Real fudge = TheGlobalData->m_partitionCellSize * 0.5f;
if (getObject()->isKindOf(KINDOF_AIRCRAFT) && getObject()->isSignificantlyAboveTerrain() && m_curLocomotor != NULL)
{
// aircraft must stay further away from the map edges, to prevent getting "lost"
fudge = max(fudge, m_curLocomotor->getPreferredHeight());
}
Region3D mapRegion;
TheTerrainLogic->getExtent( &mapRegion );
if (tmp.x < mapRegion.lo.x + fudge)
{
tmp.x = mapRegion.lo.x + fudge;
}
if (tmp.x > mapRegion.hi.x - fudge)
{
tmp.x = mapRegion.hi.x - fudge;
}
if (tmp.y < mapRegion.lo.y + fudge)
{
tmp.y = mapRegion.lo.y + fudge;
}
if (tmp.y > mapRegion.hi.y - fudge)
{
tmp.y = mapRegion.hi.y - fudge;
}
}
getStateMachine()->setGoalPosition(&tmp);
}
else
{
getStateMachine()->setGoalPosition(NULL);
}
}
/* Called by the pathfinder when it processes the pathfind queue. Basically, it's our turn
to call use the PathfindServicesInterface to do a pathfind operation. This shouldn't be called
(and in fact is very hard to do because PathfindServicesInterace is private to the pathfinder)
except by the pathfinder during pathfind queue processing. jba */
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::doPathfind( PathfindServicesInterface *pathfinder )
{
if (!m_waitingForPath) {
return;
}
//CRCDEBUG_LOG(("AIUpdateInterface::doPathfind() for object %d\n", getObject()->getID()));
m_waitingForPath = FALSE;
if (m_isSafePath) {
destroyPath();
Coord3D pos1, pos2;
pos1.set(-1000,-1000,0);
Object *repulsor = TheGameLogic->findObjectByID(m_repulsor1);
if (repulsor) {
pos1 = *repulsor->getPosition();
}
pos2 = pos1;
repulsor = TheGameLogic->findObjectByID(m_repulsor2);
if (repulsor) {
pos2 = *repulsor->getPosition();
}
m_path = pathfinder->findSafePath(getObject(), m_locomotorSet,
getObject()->getPosition(),
&pos1, &pos2,
getObject()->getVisionRange() + TheAI->getAiData()->m_repulsedDistance);
return;
}
if (m_isApproachPath & !isDoingGroundMovement()) {
m_isApproachPath = false;
}
if (m_isApproachPath) {
destroyPath();
m_path = pathfinder->findClosestPath(getObject(), m_locomotorSet, getObject()->getPosition(),
&m_requestedDestination, m_isBlockedAndStuck, 0.2f, FALSE );
if (isDoingGroundMovement() && getPath()) {
TheAI->pathfinder()->updateGoal(getObject(), getPath()->getLastNode()->getPosition(),
getPath()->getLastNode()->getLayer());
}
return;
}
if (m_isAttackPath) {
Object *victim = NULL;
if (m_requestedVictimID != INVALID_ID) {
victim = TheGameLogic->findObjectByID(m_requestedVictimID);
}
if (computeAttackPath(pathfinder, victim, &m_requestedDestination)) {
if (getPath()) {
TheAI->pathfinder()->updateGoal(getObject(), getPath()->getLastNode()->getPosition(),
getPath()->getLastNode()->getLayer());
}
//CRCDEBUG_LOG(("AIUpdateInterface::doPathfind() - m_isAttackPath = TRUE after computeAttackPath\n"));
m_isAttackPath = TRUE;
return;
}
//CRCDEBUG_LOG(("AIUpdateInterface::doPathfind() - m_isAttackPath = FALSE after computeAttackPath()\n"));
m_isAttackPath = FALSE;
if (victim) {
m_requestedDestination = *victim->getPosition();
/* find a pathable destination near the victim.*/
TheAI->pathfinder()->adjustToPossibleDestination(getObject(), getLocomotorSet(), &m_requestedDestination);
ignoreObstacle(victim);
}
}
computePath(pathfinder, &m_requestedDestination);
if (m_isFinalGoal && isDoingGroundMovement() && getPath()) {
TheAI->pathfinder()->updateGoal(getObject(), getPath()->getLastNode()->getPosition(),
getPath()->getLastNode()->getLayer());
}
if (m_queueForPathFrame > TheGameLogic->getFrame()) {
m_waitingForPath = TRUE;
}
#ifdef SLEEPY_AI
// if we're no longer waiting for a path, make sure we wake up right away!
if (!m_waitingForPath)
{
wakeUpNow();
}
#endif
}
/* Requests a path to be found. Note that if it is possible to do it without having to use the
pathfinder (air units just move point to point) it generates the path immediately. Otherwise the path
will be processed when we get to the front of the pathfind queue. jba */
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::requestPath( Coord3D *destination, Bool isFinalGoal )
{
if (m_locomotorSet.getValidSurfaces() == 0) {
DEBUG_CRASH(("Attempting to path immobile unit."));
}
//DEBUG_LOG(("Request Frame %d, obj %s %x\n", TheGameLogic->getFrame(), getObject()->getTemplate()->getName().str(), getObject()));
m_requestedDestination = *destination;
m_isFinalGoal = isFinalGoal;
CRCDEBUG_LOG(("AIUpdateInterface::requestPath() - m_isAttackPath = FALSE for object %d\n", getObject()->getID()));
m_isAttackPath = FALSE;
m_requestedVictimID = INVALID_ID;
m_isApproachPath = FALSE;
m_isSafePath = FALSE;
if (canComputeQuickPath()) {
computeQuickPath(destination);
return;
}
m_waitingForPath = TRUE;
if (m_pathTimestamp > TheGameLogic->getFrame()-3) {
/* Requesting path very quickly. Can cause a spin. */
//DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 1 second\n",
//TheGameLogic->getFrame()));
setQueueForPathTime(LOGICFRAMES_PER_SECOND);
// See if it has been too soon.
// jba intense debug
//DEBUG_LOG(("Info - RePathing very quickly %d, %d.\n", m_pathTimestamp, TheGameLogic->getFrame()));
if (m_path && m_isBlockedAndStuck) {
setIgnoreCollisionTime(2*LOGICFRAMES_PER_SECOND);
m_blockedFrames = 0;
m_isBlocked = FALSE;
m_isBlockedAndStuck = FALSE;
}
return;
}
TheAI->pathfinder()->queueForPath(getObject()->getID());
}
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::requestAttackPath( ObjectID victimID, const Coord3D* victimPos )
{
if (m_locomotorSet.getValidSurfaces() == 0) {
DEBUG_CRASH(("Attempting to path immobile unit."));
}
CRCDEBUG_LOG(("AIUpdateInterface::requestAttackPath() - m_isAttackPath = TRUE for object %d\n", getObject()->getID()));
m_requestedDestination = *victimPos;
m_requestedVictimID = victimID;
m_isAttackPath = TRUE;
m_isApproachPath = FALSE;
m_isSafePath = FALSE;
m_waitingForPath = TRUE;
if (m_pathTimestamp > TheGameLogic->getFrame()-3) {
/* Requesting path very quickly. Can cause a spin. */
//DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 2 second\n",TheGameLogic->getFrame()));
setQueueForPathTime(2*LOGICFRAMES_PER_SECOND);
return;
}
TheAI->pathfinder()->queueForPath(getObject()->getID());
}
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::requestApproachPath( Coord3D *destination )
{
if (m_locomotorSet.getValidSurfaces() == 0) {
DEBUG_CRASH(("Attempting to path immobile unit."));
}
m_requestedDestination = *destination;
m_isFinalGoal = TRUE;
CRCDEBUG_LOG(("AIUpdateInterface::requestApproachPath() - m_isAttackPath = FALSE for object %d\n", getObject()->getID()));
m_isAttackPath = FALSE;
m_requestedVictimID = INVALID_ID;
m_isApproachPath = TRUE;
m_isSafePath = FALSE;
m_waitingForPath = TRUE;
if (m_pathTimestamp > TheGameLogic->getFrame()-3) {
/* Requesting path very quickly. Can cause a spin. */
//DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 2 second\n",TheGameLogic->getFrame()));
setQueueForPathTime(2*LOGICFRAMES_PER_SECOND);
return;
}
TheAI->pathfinder()->queueForPath(getObject()->getID());
}
//-------------------------------------------------------------------------------------------------
// Requests a safe path away from the repulsor.
void AIUpdateInterface::requestSafePath( ObjectID repulsor )
{
if (repulsor != m_repulsor1) {
m_repulsor2 = m_repulsor1; // save the prior repulsor.
}
m_repulsor1 = repulsor;
m_isFinalGoal = FALSE;
CRCDEBUG_LOG(("AIUpdateInterface::requestSafePath() - m_isAttackPath = FALSE for object %d\n", getObject()->getID()));
m_isAttackPath = FALSE;
m_requestedVictimID = INVALID_ID;
m_isApproachPath = FALSE;
m_isSafePath = TRUE;
m_waitingForPath = TRUE;
if (m_pathTimestamp > TheGameLogic->getFrame()-3) {
/* Requesting path very quickly. Can cause a spin. */
//DEBUG_LOG(("%d Pathfind - repathing in less than 3 frames. Waiting 2 second\n",TheGameLogic->getFrame()));
setQueueForPathTime(2*LOGICFRAMES_PER_SECOND);
return;
}
TheAI->pathfinder()->queueForPath(getObject()->getID());
}
enum {WAYPOINT_PATH_LIMIT=1024};
//-------------------------------------------------------------------------------------------------
//
void AIUpdateInterface::setPathFromWaypoint(const Waypoint *way, const Coord2D *offset)
{
destroyPath();
m_path = newInstance(Path);
Coord3D pos = *getObject()->getPosition();
m_path->prependNode( &pos, LAYER_GROUND );
m_path->markOptimized();
int count = 0;
while (way) {
Coord3D wayPos = *way->getLocation();
wayPos.x += offset->x;
wayPos.y += offset->y;
if (way->getLink(0) == NULL) {
TheAI->pathfinder()->snapPosition(getObject(), &wayPos);
}
m_path->appendNode( &wayPos, LAYER_GROUND );
way = way->getLink(0);
count++;
if (count>WAYPOINT_PATH_LIMIT) break;
}
m_waitingForPath = FALSE;
TheAI->pathfinder()->setDebugPath(m_path);
#ifdef SLEEPY_AI
// if we're no longer waiting for a path, make sure we wake up right away!
wakeUpNow();
#endif
}
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::onObjectCreated()
{
// create the behavior state machine.
// can't do this in the ctor because makeStateMachine is a protected virtual func,
// and overrides to virtual funcs don't exist in our ctor. (look it up.)
if (m_stateMachine == NULL)
{
m_stateMachine = makeStateMachine();
m_stateMachine->initDefaultState();
}
}
//-------------------------------------------------------------------------------------------------
AIUpdateInterface::~AIUpdateInterface( void )
{
m_locomotorSet.clear();
m_curLocomotor = NULL;
if( m_stateMachine ) {
m_stateMachine->halt();
m_stateMachine->deleteInstance();
}
for (int i = 0; i < MAX_TURRETS; i++)
{
if (m_turretAI[i])
m_turretAI[i]->deleteInstance();
m_turretAI[i] = NULL;
}
m_stateMachine = NULL;
// destroy the current path. (destroyPath is NULL savvy)
destroyPath();
}
//=============================================================================
void AIUpdateInterface::setTurretTargetObject(WhichTurretType tur, Object* o, Bool forceAttacking)
{
if (m_turretAI[tur])
{
m_turretAI[tur]->setTurretTargetObject(o, forceAttacking);
}
}
//=============================================================================
Object* AIUpdateInterface::getTurretTargetObject( WhichTurretType tur )
{
if( m_turretAI[ tur ] )
{
Object *obj;
Coord3D pos;
if( m_turretAI[ tur ]->friend_getTurretTarget( obj, pos ) == TARGET_OBJECT )
{
return obj;
}
}
return NULL;
}
//=============================================================================
void AIUpdateInterface::setTurretTargetPosition(WhichTurretType tur, const Coord3D* pos)
{
if (m_turretAI[tur])
{
m_turretAI[tur]->setTurretTargetPosition(pos);
}
}
//=============================================================================
void AIUpdateInterface::setTurretEnabled(WhichTurretType tur, Bool enabled)
{
if (m_turretAI[tur])
{
m_turretAI[tur]->setTurretEnabled( enabled );
}
}
//=============================================================================
void AIUpdateInterface::recenterTurret(WhichTurretType tur)
{
if (m_turretAI[tur])
{
m_turretAI[tur]->recenterTurret();
}
}
//=============================================================================
Bool AIUpdateInterface::isTurretEnabled( WhichTurretType tur ) const
{
if( m_turretAI[ tur ] )
{
return m_turretAI[ tur ]->isTurretEnabled();
}
return FALSE;
}
//=============================================================================
Bool AIUpdateInterface::isTurretInNaturalPosition(WhichTurretType tur) const
{
if (m_turretAI[tur])
{
return m_turretAI[tur]->isTurretInNaturalPosition();
}
return FALSE;
}
//=============================================================================
Bool AIUpdateInterface::isWeaponSlotOnTurretAndAimingAtTarget(WeaponSlotType wslot, const Object* victim) const
{
for (int i = 0; i < MAX_TURRETS; i++)
{
if (m_turretAI[i] && m_turretAI[i]->isWeaponSlotOnTurret(wslot))
{
return m_turretAI[i]->isTryingToAimAtTarget(victim);
}
}
return FALSE;
}
//=============================================================================
Bool AIUpdateInterface::getTurretRotAndPitch(WhichTurretType tur, Real* turretAngle, Real* turretPitch) const
{
if (m_turretAI[tur])
{
if (turretAngle)
*turretAngle = m_turretAI[tur]->getTurretAngle();
if (turretPitch)
*turretPitch = m_turretAI[tur]->getTurretPitch();
return TRUE;
}
return FALSE;
}
//=============================================================================
Real AIUpdateInterface::getTurretTurnRate(WhichTurretType tur) const
{
return (tur != TURRET_INVALID && m_turretAI[tur] != NULL) ?
m_turretAI[tur]->getTurnRate() :
0.0f;
}
//=============================================================================
WhichTurretType AIUpdateInterface::getWhichTurretForCurWeapon() const
{
for (int i = 0; i < MAX_TURRETS; ++i)
if (m_turretAI[i] && m_turretAI[i]->isOwnersCurWeaponOnTurret())
return (WhichTurretType)i;
return TURRET_INVALID;
}
//=============================================================================
WhichTurretType AIUpdateInterface::getWhichTurretForWeaponSlot(WeaponSlotType wslot, Real* turretAngle, Real* turretPitch) const
{
for (int i = 0; i < MAX_TURRETS; ++i)
{
if (m_turretAI[i] && m_turretAI[i]->isWeaponSlotOnTurret(wslot))
{
if (turretAngle)
*turretAngle = m_turretAI[i]->getTurretAngle();
if (turretPitch)
*turretPitch = m_turretAI[i]->getTurretPitch();
return (WhichTurretType)i;
}
}
return TURRET_INVALID;
}
//=============================================================================
Real AIUpdateInterface::getCurLocomotorSpeed() const
{
if (m_curLocomotor != NULL)
return m_curLocomotor->getMaxSpeedForCondition(getObject()->getBodyModule()->getDamageState());
DEBUG_LOG(("no current locomotor!"));
return 0.0f;
}
//=============================================================================
void AIUpdateInterface::setLocomotorUpgrade(Bool set)
{
m_upgradedLocomotors = set;
if (m_curLocomotorSet == LOCOMOTORSET_NORMAL || m_curLocomotorSet == LOCOMOTORSET_NORMAL_UPGRADED)
chooseLocomotorSet(LOCOMOTORSET_NORMAL);
}
//=============================================================================
Bool AIUpdateInterface::chooseLocomotorSet(LocomotorSetType wst)
{
DEBUG_ASSERTCRASH(wst != LOCOMOTORSET_NORMAL_UPGRADED, ("never pass LOCOMOTORSET_NORMAL_UPGRADED here"));
if (wst == LOCOMOTORSET_NORMAL && m_upgradedLocomotors)
wst = LOCOMOTORSET_NORMAL_UPGRADED;
if (wst == m_curLocomotorSet)
return TRUE;
if (chooseLocomotorSetExplicit(wst))
{
chooseGoodLocomotorFromCurrentSet();
return TRUE;
}
return FALSE;
}
//=============================================================================
// this should only be called by load/save, or by chooseLocomotorSet.
// it does no sanity checking; it just jams it in.
Bool AIUpdateInterface::chooseLocomotorSetExplicit(LocomotorSetType wst)
{
const LocomotorTemplateVector* set = getAIUpdateModuleData()->findLocomotorTemplateVector(wst);
if (set)
{
m_locomotorSet.clear();
m_curLocomotor = NULL;
for (Int i = 0; i < set->size(); ++i)
{
const LocomotorTemplate* lt = set->at(i);
if (lt)
m_locomotorSet.addLocomotor(lt);
}
m_curLocomotorSet = wst;
return TRUE;
}
return FALSE;
}
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::chooseGoodLocomotorFromCurrentSet( void )
{
Locomotor* prevLoco = m_curLocomotor;
Locomotor* newLoco = TheAI->pathfinder()->chooseBestLocomotorForPosition(getObject()->getLayer(), &m_locomotorSet, getObject()->getPosition());
if (newLoco == NULL)
{
if (prevLoco != NULL)
{
/* due to physics, we might slight into a cell for which we have no loco
(eg, cliff) and get stuck. this is bad. as a solution, we do this.
this may look a little funny, but as a practical matter, it works well,
since the pathfinder will prevent us from doing any significant "wrong" terrain. */
newLoco = prevLoco;
}
else
{
/* this can happen for a newly-created object, which might come into being in
the middle of an obstacle. for now, we just fake it and choose a ground locomotor. */
newLoco = m_locomotorSet.findLocomotor(LOCOMOTORSURFACE_GROUND);
}
}
m_curLocomotor = newLoco;
if (prevLoco != m_curLocomotor)
{
// make sure the group's speed will be recalculated
if (getGroup())
getGroup()->recomputeGroupSpeed();
// turn off precision-z-pos anytime the loco changes, just in case,
// since it should only be enabled in very special cases
m_curLocomotor->setUsePreciseZPos(FALSE);
// ditto for no-slow-down.
m_curLocomotor->setNoSlowDownAsApproachingDest(FALSE);
// ditto for ultra-accuracy.
m_curLocomotor->setUltraAccurate(FALSE);
}
}
//----------------------------------------------------------------------------------------------------------
Object* AIUpdateInterface::checkForCrateToPickup()
{
if (m_crateCreated != INVALID_ID)
{
m_crateCreated = INVALID_ID; // we have processed it, so clear it.
Object* crate = TheGameLogic->findObjectByID(m_crateCreated);
if (crate)
{
for (BehaviorModule** m = crate->getBehaviorModules(); *m; ++m)
{
CollideModuleInterface* collide = (*m)->getCollide();
if (!collide)
continue;
if( collide->wouldLikeToCollideWith(getObject()))
{
return crate;
}
}
}
}
return NULL;
}
#ifdef ALLOW_SURRENDER
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::doSurrenderUpdateStuff()
{
RELEASE_CRASH(("Read the comment in doSurrenderUpdateStuff"));
/*
If you ever re-enable this code, you must convert it to be
properly sleepy. It is crucial that we avoid requiring a call
to AIUpdate every frame just to support this. (srj)
*/
UnsignedInt prevSurrenderedFrames = m_surrenderedFramesLeft;
if (m_surrenderedFramesLeft > 0)
--m_surrenderedFramesLeft;
if (m_surrenderedFramesLeft > 0)
getObject()->setModelConditionState( MODELCONDITION_SURRENDER );
else
getObject()->clearModelConditionState( MODELCONDITION_SURRENDER );
//
// when we leave a surrendered state we give ourselves an idle command ... why you ask? Well
// during the surrender sequence we might have started moving towards a POW truck come
// to pick us up, but now we should stop and be all normal again
//
if( prevSurrenderedFrames > 0 && m_surrenderedFramesLeft == 0 )
{
m_surrenderedPlayerIndex = -1;
aiIdle( CMD_FROM_AI );
}
}
#endif
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::setQueueForPathTime(Int frames)
{
#ifdef SLEEPY_AI
if (frames >= UPDATE_SLEEP_NONE && getWakeFrame() > UPDATE_SLEEP(frames))
{
if (m_isInUpdate)
{
// we're changing this while in our own update (probably via a move state).
// just do nothing, since update will calculate the correct sleep behavior at the end.
}
else
{
setWakeFrame(getObject(), UPDATE_SLEEP(frames));
}
}
#endif
m_queueForPathFrame = frames ? (TheGameLogic->getFrame() + frames) : 0;
}
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::wakeUpNow()
{
#ifdef SLEEPY_AI
if (getWakeFrame() > UPDATE_SLEEP_NONE)
{
if (m_isInUpdate)
{
// we're changing this while in our own update (probably via a move state).
// just do nothing, since update will calculate the correct sleep behavior at the end.
}
else
{
setWakeFrame(getObject(), UPDATE_SLEEP_NONE);
}
}
#endif
}
//-------------------------------------------------------------------------------------------------
void AIUpdateInterface::friend_notifyStateMachineChanged()
{
wakeUpNow();
}
//-------------------------------------------------------------------------------------------------
/**
* The "main loop" of the AI subsystem