forked from Warzone2100/warzone2100
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.cpp
1311 lines (1147 loc) · 39.6 KB
/
ai.cpp
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
/*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2019 Warzone 2100 Project
Warzone 2100 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 2 of the License, or
(at your option) any later version.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file ai.c
*
* AI update functions for the different object types.
*
*/
#include "lib/framework/frame.h"
#include "action.h"
#include "cmddroid.h"
#include "combat.h"
#include "droid.h"
#include "group.h"
#include "mapgrid.h"
#include "map.h"
#include "projectile.h"
#include "objmem.h"
#include "order.h"
/* Weights used for target selection code,
* target distance is used as 'common currency'
*/
#define WEIGHT_DIST_TILE 13 //In points used in weaponmodifier.txt and structuremodifier.txt
#define WEIGHT_DIST_TILE_DROID WEIGHT_DIST_TILE //How much weight a distance of 1 tile (128 world units) has when looking for the best nearest target
#define WEIGHT_DIST_TILE_STRUCT WEIGHT_DIST_TILE
#define WEIGHT_HEALTH_DROID (WEIGHT_DIST_TILE * 10) //How much weight unit damage has (100% of damage is equally weighted as 10 tiles distance)
//~100% damage should be ~8 tiles (max sensor range)
#define WEIGHT_HEALTH_STRUCT (WEIGHT_DIST_TILE * 7)
#define WEIGHT_NOT_VISIBLE_F 10 //We really don't like objects we can't see
#define WEIGHT_SERVICE_DROIDS (WEIGHT_DIST_TILE_DROID * 5) //We don't want them to be repairing droids or structures while we are after them
#define WEIGHT_WEAPON_DROIDS (WEIGHT_DIST_TILE_DROID * 4) //We prefer to go after anything that has a gun and can hurt us
#define WEIGHT_COMMAND_DROIDS (WEIGHT_DIST_TILE_DROID * 6) //Commanders get a higher priority
#define WEIGHT_MILITARY_STRUCT WEIGHT_DIST_TILE_STRUCT //Droid/cyborg factories, repair facility; shouldn't have too much weight
#define WEIGHT_WEAPON_STRUCT WEIGHT_WEAPON_DROIDS //Same as weapon droids (?)
#define WEIGHT_DERRICK_STRUCT (WEIGHT_MILITARY_STRUCT + WEIGHT_DIST_TILE_STRUCT * 4) //Even if it's 4 tiles further away than defenses we still choose it
#define WEIGHT_STRUCT_NOTBUILT_F 8 //Humans won't fool us anymore!
#define OLD_TARGET_THRESHOLD (WEIGHT_DIST_TILE * 4) //it only makes sense to switch target if new one is 4+ tiles closer
#define EMP_DISABLED_PENALTY_F 10 //EMP shouldn't attack emped targets again
#define EMP_STRUCT_PENALTY_F (EMP_DISABLED_PENALTY_F * 2) //EMP don't attack structures, should be bigger than EMP_DISABLED_PENALTY_F
#define TOO_CLOSE_PENALTY_F 20
#define TARGET_DOOMED_PENALTY_F 10 // Targets that have a lot of damage incoming are less attractive
#define TARGET_DOOMED_SLOW_RELOAD_T 21 // Weapon ROF threshold for above penalty. per minute.
//Some weights for the units attached to a commander
#define WEIGHT_CMD_RANK (WEIGHT_DIST_TILE * 4) //A single rank is as important as 4 tiles distance
#define WEIGHT_CMD_SAME_TARGET WEIGHT_DIST_TILE //Don't want this to be too high, since a commander can have many units assigned
uint8_t alliances[MAX_PLAYER_SLOTS][MAX_PLAYER_SLOTS];
/// A bitfield of vision sharing in alliances, for quick manipulation of vision information
PlayerMask alliancebits[MAX_PLAYER_SLOTS];
/// A bitfield for the satellite uplink
PlayerMask satuplinkbits;
static int aiDroidRange(DROID *psDroid, int weapon_slot)
{
int32_t longRange;
if (psDroid->droidType == DROID_SENSOR)
{
longRange = objSensorRange(psDroid);
}
else if (psDroid->numWeaps == 0 || psDroid->asWeaps[0].nStat == 0)
{
// Can't attack without a weapon
return 0;
}
else
{
WEAPON_STATS *psWStats = psDroid->asWeaps[weapon_slot].nStat + asWeaponStats;
longRange = proj_GetLongRange(psWStats, psDroid->player);
}
return longRange;
}
// see if a structure has the range to fire on a target
static bool aiStructHasRange(STRUCTURE *psStruct, BASE_OBJECT *psTarget, int weapon_slot)
{
if (psStruct->numWeaps == 0 || psStruct->asWeaps[0].nStat == 0)
{
// Can't attack without a weapon
return false;
}
WEAPON_STATS *psWStats = psStruct->asWeaps[weapon_slot].nStat + asWeaponStats;
int longRange = proj_GetLongRange(psWStats, psStruct->player);
return objPosDiffSq(psStruct, psTarget) < longRange * longRange && lineOfFire(psStruct, psTarget, weapon_slot, true);
}
static bool aiDroidHasRange(DROID *psDroid, BASE_OBJECT *psTarget, int weapon_slot)
{
int32_t longRange = aiDroidRange(psDroid, weapon_slot);
return objPosDiffSq(psDroid, psTarget) < longRange * longRange;
}
static bool aiObjHasRange(BASE_OBJECT *psObj, BASE_OBJECT *psTarget, int weapon_slot)
{
if (psObj->type == OBJ_DROID)
{
return aiDroidHasRange((DROID *)psObj, psTarget, weapon_slot);
}
else if (psObj->type == OBJ_STRUCTURE)
{
return aiStructHasRange((STRUCTURE *)psObj, psTarget, weapon_slot);
}
return false;
}
/* Initialise the AI system */
bool aiInitialise()
{
SDWORD i, j;
for (i = 0; i < MAX_PLAYER_SLOTS; i++)
{
alliancebits[i] = 0;
for (j = 0; j < MAX_PLAYER_SLOTS; j++)
{
bool valid = (i == j && i < MAX_PLAYERS);
alliances[i][j] = valid ? ALLIANCE_FORMED : ALLIANCE_BROKEN;
alliancebits[i] |= valid << j;
}
}
satuplinkbits = 0;
return true;
}
/* Shutdown the AI system */
bool aiShutdown()
{
return true;
}
/** Search the global list of sensors for a possible target for psObj. */
static BASE_OBJECT *aiSearchSensorTargets(BASE_OBJECT *psObj, int weapon_slot, WEAPON_STATS *psWStats, TARGET_ORIGIN *targetOrigin)
{
int longRange = proj_GetLongRange(psWStats, psObj->player);
int tarDist = longRange * longRange;
bool foundCB = false;
int minDist = proj_GetMinRange(psWStats, psObj->player) * proj_GetMinRange(psWStats, psObj->player);
BASE_OBJECT *psTarget = nullptr;
if (targetOrigin)
{
*targetOrigin = ORIGIN_UNKNOWN;
}
for (BASE_OBJECT *psSensor = apsSensorList[0]; psSensor; psSensor = psSensor->psNextFunc)
{
BASE_OBJECT *psTemp = nullptr;
bool isCB = false;
bool isRD = false;
if (!aiCheckAlliances(psSensor->player, psObj->player))
{
continue;
}
else if (psSensor->type == OBJ_DROID)
{
DROID *psDroid = (DROID *)psSensor;
ASSERT_OR_RETURN(nullptr, psDroid->droidType == DROID_SENSOR, "A non-sensor droid in a sensor list is non-sense");
// Skip non-observing droids.
if (psDroid->action != DACTION_OBSERVE)
{
continue;
}
psTemp = psDroid->psActionTarget[0];
isCB = cbSensorDroid(psDroid);
isRD = objRadarDetector((BASE_OBJECT *)psDroid);
}
else if (psSensor->type == OBJ_STRUCTURE)
{
STRUCTURE *psCStruct = (STRUCTURE *)psSensor;
// skip incomplete structures
if (psCStruct->status != SS_BUILT)
{
continue;
}
psTemp = psCStruct->psTarget[0];
isCB = structCBSensor(psCStruct);
isRD = objRadarDetector((BASE_OBJECT *)psCStruct);
}
if (!psTemp || psTemp->died || aiObjectIsProbablyDoomed(psTemp, false) || !validTarget(psObj, psTemp, 0) || aiCheckAlliances(psTemp->player, psObj->player))
{
continue;
}
int distSq = objPosDiffSq(psTemp->pos, psObj->pos);
// Need to be in range, prefer closer targets or CB targets
if ((isCB > foundCB || (isCB == foundCB && distSq < tarDist)) && distSq > minDist)
{
if (aiObjHasRange(psObj, psTemp, weapon_slot) && visibleObject(psSensor, psTemp, false))
{
tarDist = distSq;
psTarget = psTemp;
if (targetOrigin)
{
*targetOrigin = ORIGIN_SENSOR;
}
if (isCB)
{
if (targetOrigin)
{
*targetOrigin = ORIGIN_CB_SENSOR;
}
foundCB = true; // got CB target, drop everything and shoot!
}
else if (isRD)
{
if (targetOrigin)
{
*targetOrigin = ORIGIN_RADAR_DETECTOR;
}
}
}
}
}
return psTarget;
}
/* Calculates attack priority for a certain target */
static SDWORD targetAttackWeight(BASE_OBJECT *psTarget, BASE_OBJECT *psAttacker, SDWORD weapon_slot)
{
SDWORD targetTypeBonus = 0, damageRatio = 0, attackWeight = 0, noTarget = -1;
UDWORD weaponSlot;
DROID *targetDroid = nullptr, *psAttackerDroid = nullptr, *psGroupDroid, *psDroid;
STRUCTURE *targetStructure = nullptr;
WEAPON_EFFECT weaponEffect;
WEAPON_STATS *attackerWeapon;
bool bEmpWeap = false, bCmdAttached = false, bTargetingCmd = false, bDirect = false;
if (psTarget == nullptr || psAttacker == nullptr || psTarget->died)
{
return noTarget;
}
ASSERT(psTarget != psAttacker, "targetAttackWeight: Wanted to evaluate the worth of attacking ourselves...");
targetTypeBonus = 0; //Sensors/ecm droids, non-military structures get lower priority
/* Get attacker weapon effect */
if (psAttacker->type == OBJ_DROID)
{
psAttackerDroid = (DROID *)psAttacker;
attackerWeapon = (WEAPON_STATS *)(asWeaponStats + psAttackerDroid->asWeaps[weapon_slot].nStat);
//check if this droid is assigned to a commander
bCmdAttached = hasCommander(psAttackerDroid);
//find out if current target is targeting our commander
if (bCmdAttached)
{
if (psTarget->type == OBJ_DROID)
{
psDroid = (DROID *)psTarget;
//go through all enemy weapon slots
for (weaponSlot = 0; !bTargetingCmd &&
weaponSlot < ((DROID *)psTarget)->numWeaps; weaponSlot++)
{
//see if this weapon is targeting our commander
if (psDroid->psActionTarget[weaponSlot] == (BASE_OBJECT *)psAttackerDroid->psGroup->psCommander)
{
bTargetingCmd = true;
}
}
}
else
{
if (psTarget->type == OBJ_STRUCTURE)
{
//go through all enemy weapons
for (weaponSlot = 0; !bTargetingCmd && weaponSlot < ((STRUCTURE *)psTarget)->numWeaps; weaponSlot++)
{
if (((STRUCTURE *)psTarget)->psTarget[weaponSlot] ==
(BASE_OBJECT *)psAttackerDroid->psGroup->psCommander)
{
bTargetingCmd = true;
}
}
}
}
}
}
else if (psAttacker->type == OBJ_STRUCTURE)
{
attackerWeapon = ((WEAPON_STATS *)(asWeaponStats + ((STRUCTURE *)psAttacker)->asWeaps[weapon_slot].nStat));
}
else /* feature */
{
ASSERT(!"invalid attacker object type", "targetAttackWeight: Invalid attacker object type");
return noTarget;
}
bDirect = proj_Direct(attackerWeapon);
if (psAttacker->type == OBJ_DROID && psAttackerDroid->droidType == DROID_SENSOR)
{
// Sensors are considered a direct weapon,
// but for computing expected damage it makes more sense to use indirect damage
bDirect = false;
}
//Get weapon effect
weaponEffect = attackerWeapon->weaponEffect;
//See if attacker is using an EMP weapon
bEmpWeap = (attackerWeapon->weaponSubClass == WSC_EMP);
int dist = iHypot((psAttacker->pos - psTarget->pos).xy());
bool tooClose = (unsigned)dist <= proj_GetMinRange(attackerWeapon, psAttacker->player);
if (tooClose)
{
dist = objSensorRange(psAttacker); // If object is too close to fire at, consider it to be at maximum range.
}
/* Calculate attack weight */
if (psTarget->type == OBJ_DROID)
{
targetDroid = (DROID *)psTarget;
if (targetDroid->died)
{
debug(LOG_NEVER, "Target droid is dead, skipping invalid droid.\n");
return noTarget;
}
/* Calculate damage this target suffered */
if (targetDroid->originalBody == 0) // FIXME Somewhere we get 0HP droids from
{
damageRatio = 0;
debug(LOG_ERROR, "targetAttackWeight: 0HP droid detected!");
debug(LOG_ERROR, " Type: %i Name: \"%s\" Owner: %i \"%s\")",
targetDroid->droidType, targetDroid->aName, targetDroid->player, getPlayerName(targetDroid->player));
}
else
{
damageRatio = 100 - 100 * targetDroid->body / targetDroid->originalBody;
}
assert(targetDroid->originalBody != 0); // Assert later so we get the info from above
/* See if this type of a droid should be prioritized */
switch (targetDroid->droidType)
{
case DROID_SENSOR:
case DROID_ECM:
case DROID_PERSON:
case DROID_TRANSPORTER:
case DROID_SUPERTRANSPORTER:
case DROID_DEFAULT:
case DROID_ANY:
break;
case DROID_CYBORG:
case DROID_WEAPON:
case DROID_CYBORG_SUPER:
targetTypeBonus = WEIGHT_WEAPON_DROIDS;
break;
case DROID_COMMAND:
targetTypeBonus = WEIGHT_COMMAND_DROIDS;
break;
case DROID_CONSTRUCT:
case DROID_REPAIR:
case DROID_CYBORG_CONSTRUCT:
case DROID_CYBORG_REPAIR:
targetTypeBonus = WEIGHT_SERVICE_DROIDS;
break;
}
/* Now calculate the overall weight */
attackWeight = asWeaponModifier[weaponEffect][(asPropulsionStats + targetDroid->asBits[COMP_PROPULSION])->propulsionType] // Our weapon's effect against target
+ asWeaponModifierBody[weaponEffect][(asBodyStats + targetDroid->asBits[COMP_BODY])->size]
+ WEIGHT_DIST_TILE_DROID * objSensorRange(psAttacker) / TILE_UNITS
- WEIGHT_DIST_TILE_DROID * dist / TILE_UNITS // farther droids are less attractive
+ WEIGHT_HEALTH_DROID * damageRatio / 100 // we prefer damaged droids
+ targetTypeBonus; // some droid types have higher priority
/* If attacking with EMP try to avoid targets that were already "EMPed" */
if (bEmpWeap &&
(targetDroid->lastHitWeapon == WSC_EMP) &&
((gameTime - targetDroid->timeLastHit) < EMP_DISABLE_TIME)) //target still disabled
{
attackWeight /= EMP_DISABLED_PENALTY_F;
}
}
else if (psTarget->type == OBJ_STRUCTURE)
{
targetStructure = (STRUCTURE *)psTarget;
/* Calculate damage this target suffered */
damageRatio = 100 - 100 * targetStructure->body / structureBody(targetStructure);
/* See if this type of a structure should be prioritized */
switch (targetStructure->pStructureType->type)
{
case REF_DEFENSE:
targetTypeBonus = WEIGHT_WEAPON_STRUCT;
break;
case REF_RESOURCE_EXTRACTOR:
targetTypeBonus = WEIGHT_DERRICK_STRUCT;
break;
case REF_FACTORY:
case REF_CYBORG_FACTORY:
case REF_REPAIR_FACILITY:
targetTypeBonus = WEIGHT_MILITARY_STRUCT;
break;
default:
break;
}
/* Now calculate the overall weight */
attackWeight = asStructStrengthModifier[weaponEffect][targetStructure->pStructureType->strength] // Our weapon's effect against target
+ WEIGHT_DIST_TILE_STRUCT * objSensorRange(psAttacker) / TILE_UNITS
- WEIGHT_DIST_TILE_STRUCT * dist / TILE_UNITS // farther structs are less attractive
+ WEIGHT_HEALTH_STRUCT * damageRatio / 100 // we prefer damaged structures
+ targetTypeBonus; // some structure types have higher priority
/* Go for unfinished structures only if nothing else found (same for non-visible structures) */
if (targetStructure->status != SS_BUILT) //a decoy?
{
attackWeight /= WEIGHT_STRUCT_NOTBUILT_F;
}
/* EMP should only attack structures if no enemy droids are around */
if (bEmpWeap)
{
attackWeight /= EMP_STRUCT_PENALTY_F;
}
}
else //a feature
{
return 1;
}
/* We prefer objects we can see and can attack immediately */
if (!visibleObject((BASE_OBJECT *)psAttacker, psTarget, true))
{
attackWeight /= WEIGHT_NOT_VISIBLE_F;
}
if (tooClose)
{
attackWeight /= TOO_CLOSE_PENALTY_F;
}
/* Penalty for units that are already considered doomed (but the missile might miss!) */
if (aiObjectIsProbablyDoomed(psTarget, bDirect))
{
/* indirect firing units have slow reload times, so give the target a chance to die,
* and give a different unit a chance to get in range, too. */
if (weaponROF(attackerWeapon, psAttacker->player) < TARGET_DOOMED_SLOW_RELOAD_T)
{
debug(LOG_NEVER, "Not killing unit - doomed. My ROF: %i (%s)", weaponROF(attackerWeapon, psAttacker->player), getName(attackerWeapon));
return noTarget;
}
attackWeight /= TARGET_DOOMED_PENALTY_F;
}
/* Commander-related criterias */
if (bCmdAttached) //attached to a commander and don't have a target assigned by some order
{
ASSERT(psAttackerDroid->psGroup->psCommander != nullptr, "Commander is NULL");
//if commander is being targeted by our target, try to defend the commander
if (bTargetingCmd)
{
attackWeight += WEIGHT_CMD_RANK * (1 + getDroidLevel(psAttackerDroid->psGroup->psCommander));
}
//fire support - go through all droids assigned to the commander
for (psGroupDroid = psAttackerDroid->psGroup->psList; psGroupDroid; psGroupDroid = psGroupDroid->psGrpNext)
{
for (weaponSlot = 0; weaponSlot < psGroupDroid->numWeaps; weaponSlot++)
{
//see if this droid is currently targeting current target
if (psGroupDroid->order.psObj == psTarget ||
psGroupDroid->psActionTarget[weaponSlot] == psTarget)
{
//we prefer targets that are already targeted and hence will be destroyed faster
attackWeight += WEIGHT_CMD_SAME_TARGET;
}
}
}
}
return std::max<int>(1, attackWeight);
}
// Find the best nearest target for a droid.
// If extraRange is higher than zero, then this is the range it accepts for movement to target.
// Returns integer representing target priority, -1 if failed
int aiBestNearestTarget(DROID *psDroid, BASE_OBJECT **ppsObj, int weapon_slot, int extraRange)
{
int failure = -1;
int bestMod = 0;
BASE_OBJECT *psTarget = nullptr, *bestTarget = nullptr, *tempTarget;
bool electronic = false;
STRUCTURE *targetStructure;
WEAPON_EFFECT weaponEffect;
TARGET_ORIGIN tmpOrigin = ORIGIN_UNKNOWN;
//don't bother looking if empty vtol droid
if (vtolEmpty(psDroid))
{
return failure;
}
/* Return if have no weapons */
// The ai orders a non-combat droid to patrol = crash without it...
if ((psDroid->asWeaps[0].nStat == 0 || psDroid->numWeaps == 0) && psDroid->droidType != DROID_SENSOR)
{
return failure;
}
// Check if we have a CB target to begin with
if (!proj_Direct(asWeaponStats + psDroid->asWeaps[weapon_slot].nStat))
{
WEAPON_STATS *psWStats = psDroid->asWeaps[weapon_slot].nStat + asWeaponStats;
bestTarget = aiSearchSensorTargets((BASE_OBJECT *)psDroid, weapon_slot, psWStats, &tmpOrigin);
bestMod = targetAttackWeight(bestTarget, (BASE_OBJECT *)psDroid, weapon_slot);
}
weaponEffect = (asWeaponStats + psDroid->asWeaps[weapon_slot].nStat)->weaponEffect;
electronic = electronicDroid(psDroid);
// Range was previously 9*TILE_UNITS. Increasing this doesn't seem to help much, though. Not sure why.
int droidRange = std::min(aiDroidRange(psDroid, weapon_slot) + extraRange, objSensorRange(psDroid) + 6 * TILE_UNITS);
static GridList gridList; // static to avoid allocations.
gridList = gridStartIterate(psDroid->pos.x, psDroid->pos.y, droidRange);
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
BASE_OBJECT *friendlyObj = nullptr;
BASE_OBJECT *targetInQuestion = *gi;
/* This is a friendly unit, check if we can reuse its target */
if (aiCheckAlliances(targetInQuestion->player, psDroid->player))
{
friendlyObj = targetInQuestion;
targetInQuestion = nullptr;
/* Can we see what it is doing? */
if (friendlyObj->visible[psDroid->player] == UBYTE_MAX)
{
if (friendlyObj->type == OBJ_DROID)
{
DROID *friendlyDroid = (DROID *)friendlyObj;
/* See if friendly droid has a target */
tempTarget = friendlyDroid->psActionTarget[0];
if (tempTarget && !tempTarget->died)
{
//make sure a weapon droid is targeting it
if (friendlyDroid->numWeaps > 0)
{
// make sure this target wasn't assigned explicitly to this droid
if (friendlyDroid->order.type != DORDER_ATTACK)
{
targetInQuestion = tempTarget; //consider this target
}
}
}
}
else if (friendlyObj->type == OBJ_STRUCTURE)
{
tempTarget = ((STRUCTURE *)friendlyObj)->psTarget[0];
if (tempTarget && !tempTarget->died)
{
targetInQuestion = tempTarget;
}
}
}
}
if (targetInQuestion != nullptr
&& targetInQuestion != psDroid // in case friendly unit had me as target
&& (targetInQuestion->type == OBJ_DROID || targetInQuestion->type == OBJ_STRUCTURE || targetInQuestion->type == OBJ_FEATURE)
&& targetInQuestion->visible[psDroid->player] == UBYTE_MAX
&& !aiCheckAlliances(targetInQuestion->player, psDroid->player)
&& validTarget(psDroid, targetInQuestion, weapon_slot)
&& objPosDiffSq(psDroid, targetInQuestion) < droidRange * droidRange)
{
if (targetInQuestion->type == OBJ_DROID)
{
// in multiPlayer - don't attack Transporters with EW
if (bMultiPlayer)
{
// if not electronic then valid target
if (!electronic
|| (electronic
&& !isTransporter((DROID *)targetInQuestion)))
{
//only a valid target if NOT a transporter
psTarget = targetInQuestion;
}
}
else
{
psTarget = targetInQuestion;
}
}
else if (targetInQuestion->type == OBJ_STRUCTURE)
{
STRUCTURE *psStruct = (STRUCTURE *)targetInQuestion;
if (electronic)
{
/* don't want to target structures with resistance of zero if using electronic warfare */
if (validStructResistance((STRUCTURE *)targetInQuestion))
{
psTarget = targetInQuestion;
}
}
else if (psStruct->asWeaps[0].nStat > 0)
{
// structure with weapons - go for this
psTarget = targetInQuestion;
}
else if ((isHumanPlayer(psDroid->player) && (psStruct->pStructureType->type != REF_WALL && psStruct->pStructureType->type != REF_WALLCORNER))
|| !isHumanPlayer(psDroid->player))
{
psTarget = targetInQuestion;
}
}
else if (targetInQuestion->type == OBJ_FEATURE
&& psDroid->lastFrustratedTime > 0
&& gameTime - psDroid->lastFrustratedTime < FRUSTRATED_TIME
&& ((FEATURE *)targetInQuestion)->psStats->damageable
&& psDroid->player != scavengerPlayer()) // hack to avoid scavs blowing up their nice feature walls
{
psTarget = targetInQuestion;
objTrace(psDroid->id, "considering shooting at %s in frustration", objInfo(targetInQuestion));
}
/* Check if our weapon is most effective against this object */
if (psTarget != nullptr && psTarget == targetInQuestion) //was assigned?
{
int newMod = targetAttackWeight(psTarget, (BASE_OBJECT *)psDroid, weapon_slot);
/* Remember this one if it's our best target so far */
if (newMod >= 0 && (newMod > bestMod || bestTarget == nullptr))
{
bestMod = newMod;
tmpOrigin = ORIGIN_ALLY;
bestTarget = psTarget;
}
}
}
}
if (bestTarget)
{
ASSERT(!bestTarget->died, "AI gave us a target that is already dead.");
targetStructure = visGetBlockingWall(psDroid, bestTarget);
// See if target is blocked by a wall; only affects direct weapons
// Ignore friendly walls here
if (proj_Direct(asWeaponStats + psDroid->asWeaps[weapon_slot].nStat)
&& targetStructure
&& !aiCheckAlliances(psDroid->player, targetStructure->player))
{
//are we any good against walls?
if (asStructStrengthModifier[weaponEffect][targetStructure->pStructureType->strength] >= 100) //can attack atleast with default strength
{
bestTarget = (BASE_OBJECT *)targetStructure; //attack wall
}
}
*ppsObj = bestTarget;
return bestMod;
}
return failure;
}
// Are there a lot of bullets heading towards the droid?
static bool aiDroidIsProbablyDoomed(DROID *psDroid, bool isDirect)
{
if (isDirect)
{
return psDroid->expectedDamageDirect > psDroid->body
&& psDroid->expectedDamageDirect - psDroid->body > psDroid->body / 5; // Doomed if projectiles will damage 120% of remaining body points.
}
else
{
return psDroid->expectedDamageIndirect > psDroid->body
&& psDroid->expectedDamageIndirect - psDroid->body > psDroid->body / 5; // Doomed if projectiles will damage 120% of remaining body points.
}
}
// Are there a lot of bullets heading towards the structure?
static bool aiStructureIsProbablyDoomed(STRUCTURE *psStructure)
{
return psStructure->expectedDamage > psStructure->body
&& psStructure->expectedDamage - psStructure->body > psStructure->body / 15; // Doomed if projectiles will damage 106.6666666667% of remaining body points.
}
// Are there a lot of bullets heading towards the object?
bool aiObjectIsProbablyDoomed(BASE_OBJECT *psObject, bool isDirect)
{
if (psObject->died)
{
return true; // Was definitely doomed.
}
switch (psObject->type)
{
case OBJ_DROID:
return aiDroidIsProbablyDoomed((DROID *)psObject, isDirect);
case OBJ_STRUCTURE:
return aiStructureIsProbablyDoomed((STRUCTURE *)psObject);
default:
return false;
}
}
// Update the expected damage of the object.
void aiObjectAddExpectedDamage(BASE_OBJECT *psObject, SDWORD damage, bool isDirect)
{
if (psObject == nullptr)
{
return; // Hard to destroy the ground.
}
switch (psObject->type)
{
case OBJ_DROID:
if (isDirect)
{
((DROID *)psObject)->expectedDamageDirect += damage;
ASSERT((SDWORD)((DROID *)psObject)->expectedDamageDirect >= 0, "aiObjectAddExpectedDamage: Negative amount of projectiles heading towards droid.");
}
else
{
((DROID *)psObject)->expectedDamageIndirect += damage;
ASSERT((SDWORD)((DROID *)psObject)->expectedDamageIndirect >= 0, "aiObjectAddExpectedDamage: Negative amount of projectiles heading towards droid.");
}
break;
case OBJ_STRUCTURE:
((STRUCTURE *)psObject)->expectedDamage += damage;
ASSERT((SDWORD)((STRUCTURE *)psObject)->expectedDamage >= 0, "aiObjectAddExpectedDamage: Negative amount of projectiles heading towards droid.");
break;
default:
break;
}
}
// see if an object is a wall
static bool aiObjIsWall(BASE_OBJECT *psObj)
{
if (psObj->type != OBJ_STRUCTURE)
{
return false;
}
if (((STRUCTURE *)psObj)->pStructureType->type != REF_WALL &&
((STRUCTURE *)psObj)->pStructureType->type != REF_WALLCORNER)
{
return false;
}
return true;
}
/* See if there is a target in range */
bool aiChooseTarget(BASE_OBJECT *psObj, BASE_OBJECT **ppsTarget, int weapon_slot, bool bUpdateTarget, TARGET_ORIGIN *targetOrigin)
{
BASE_OBJECT *psTarget = nullptr;
DROID *psCommander;
SDWORD curTargetWeight = -1;
TARGET_ORIGIN tmpOrigin = ORIGIN_UNKNOWN;
if (targetOrigin)
{
*targetOrigin = ORIGIN_UNKNOWN;
}
if (psObj->type == OBJ_DROID && secondaryGetState((DROID *)psObj, DSO_HALTTYPE) == DSS_HALT_HOLD)
{
return false; // Not sure why we check this here...
}
ASSERT_OR_RETURN(false, (unsigned)weapon_slot < psObj->numWeaps, "Invalid weapon selected");
/* See if there is a something in range */
if (psObj->type == OBJ_DROID)
{
BASE_OBJECT *psCurrTarget = ((DROID *)psObj)->psActionTarget[0];
/* find a new target */
int newTargetWeight = aiBestNearestTarget((DROID *)psObj, &psTarget, weapon_slot);
/* Calculate weight of the current target if updating; but take care not to target
* ourselves... */
if (bUpdateTarget && psCurrTarget != psObj)
{
curTargetWeight = targetAttackWeight(psCurrTarget, psObj, weapon_slot);
}
if (newTargetWeight >= 0 // found a new target
&& (!bUpdateTarget // choosing a new target, don't care if current one is better
|| curTargetWeight <= 0 // attacker had no valid target, use new one
|| newTargetWeight > curTargetWeight + OLD_TARGET_THRESHOLD) // updating and new target is better
&& validTarget(psObj, psTarget, weapon_slot)
&& aiDroidHasRange((DROID *)psObj, psTarget, weapon_slot))
{
ASSERT(!isDead(psTarget), "Droid found a dead target!");
*ppsTarget = psTarget;
return true;
}
}
else if (psObj->type == OBJ_STRUCTURE)
{
bool bCommanderBlock = false;
ASSERT_OR_RETURN(false, psObj->asWeaps[weapon_slot].nStat > 0, "Invalid weapon turret");
WEAPON_STATS *psWStats = psObj->asWeaps[weapon_slot].nStat + asWeaponStats;
int longRange = proj_GetLongRange(psWStats, psObj->player);
// see if there is a target from the command droids
psTarget = nullptr;
psCommander = cmdDroidGetDesignator(psObj->player);
if (!proj_Direct(psWStats) && (psCommander != nullptr) &&
aiStructHasRange((STRUCTURE *)psObj, (BASE_OBJECT *)psCommander, weapon_slot))
{
// there is a commander that can fire designate for this structure
// set bCommanderBlock so that the structure does not fire until the commander
// has a target - (slow firing weapons will not be ready to fire otherwise).
bCommanderBlock = true;
// I do believe this will never happen, check for yourself :-)
debug(LOG_NEVER, "Commander %d is good enough for fire designation", psCommander->id);
if (psCommander->action == DACTION_ATTACK
&& psCommander->psActionTarget[0] != nullptr
&& !psCommander->psActionTarget[0]->died)
{
// the commander has a target to fire on
if (aiStructHasRange((STRUCTURE *)psObj, psCommander->psActionTarget[0], weapon_slot))
{
// target in range - fire on it
tmpOrigin = ORIGIN_COMMANDER;
psTarget = psCommander->psActionTarget[0];
}
else
{
// target out of range - release the commander block
bCommanderBlock = false;
}
}
}
// indirect fire structures use sensor towers first
if (psTarget == nullptr && !bCommanderBlock && !proj_Direct(psWStats))
{
psTarget = aiSearchSensorTargets(psObj, weapon_slot, psWStats, &tmpOrigin);
}
if (psTarget == nullptr && !bCommanderBlock)
{
int targetValue = -1;
int tarDist = INT32_MAX;
int srange = longRange;
if (!proj_Direct(psWStats) && srange > objSensorRange(psObj))
{
// search radius of indirect weapons limited by their sight, unless they use
// external sensors to provide fire designation
srange = objSensorRange(psObj);
}
static GridList gridList; // static to avoid allocations.
gridList = gridStartIterate(psObj->pos.x, psObj->pos.y, srange);
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
BASE_OBJECT *psCurr = *gi;
/* Check that it is a valid target */
if (psCurr->type != OBJ_FEATURE && !psCurr->died
&& !aiCheckAlliances(psCurr->player, psObj->player)
&& validTarget(psObj, psCurr, weapon_slot) && psCurr->visible[psObj->player] == UBYTE_MAX
&& aiStructHasRange((STRUCTURE *)psObj, psCurr, weapon_slot))
{
int newTargetValue = targetAttackWeight(psCurr, psObj, weapon_slot);
// See if in sensor range and visible
int distSq = objPosDiffSq(psCurr->pos, psObj->pos);
if (newTargetValue < targetValue || (newTargetValue == targetValue && distSq >= tarDist))
{
continue;
}
tmpOrigin = ORIGIN_VISUAL;
psTarget = psCurr;
tarDist = distSq;
targetValue = newTargetValue;
}
}
}
if (psTarget)
{
ASSERT(!psTarget->died, "Structure found a dead target!");
if (targetOrigin)
{
*targetOrigin = tmpOrigin;
}
*ppsTarget = psTarget;
return true;
}
}
return false;
}
/* See if there is a target in range for Sensor objects*/
bool aiChooseSensorTarget(BASE_OBJECT *psObj, BASE_OBJECT **ppsTarget)
{
int sensorRange = objSensorRange(psObj);
unsigned int radSquared = sensorRange * sensorRange;
bool radarDetector = objRadarDetector(psObj);
if (!objActiveRadar(psObj) && !radarDetector)
{
ASSERT(false, "Only to be used for sensor turrets!");
return false;
}
/* See if there is something in range */
if (psObj->type == OBJ_DROID)
{
BASE_OBJECT *psTarget = nullptr;
if (aiBestNearestTarget((DROID *)psObj, &psTarget, 0) >= 0)
{
/* See if in sensor range */
const int xdiff = psTarget->pos.x - psObj->pos.x;
const int ydiff = psTarget->pos.y - psObj->pos.y;
const unsigned int distSq = xdiff * xdiff + ydiff * ydiff;
// I do believe this will never happen, check for yourself :-)
debug(LOG_NEVER, "Sensor droid(%d) found possible target(%d)!!!", psObj->id, psTarget->id);
if (distSq < radSquared)
{
*ppsTarget = psTarget;
return true;
}
}
}
else // structure
{
BASE_OBJECT *psTemp = nullptr;
unsigned tarDist = UINT32_MAX;
static GridList gridList; // static to avoid allocations.
gridList = gridStartIterate(psObj->pos.x, psObj->pos.y, objSensorRange(psObj));
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
BASE_OBJECT *psCurr = *gi;