forked from Warzone2100/warzone2100
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction.cpp
2587 lines (2367 loc) · 81 KB
/
action.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 action.c
*
* Functions for setting the action of a droid.
*
*/
#include "lib/framework/frame.h"
#include "lib/framework/math_ext.h"
#include "lib/framework/fixedpoint.h"
#include "lib/script/script.h"
#include "lib/sound/audio.h"
#include "lib/sound/audio_id.h"
#include "lib/netplay/netplay.h"
#include "action.h"
#include "combat.h"
#include "geometry.h"
#include "mission.h"
#include "projectile.h"
#include "qtscript.h"
#include "random.h"
#include "scriptcb.h"
#include "transporter.h"
#include "mapgrid.h"
#include "hci.h"
#include "order.h"
#include "objmem.h"
#include "move.h"
#include "cmddroid.h"
/* attack run distance */
#define VTOL_ATTACK_LENGTH 1000
#define VTOL_ATTACK_TARDIST 400
// turret rotation limit
#define VTOL_TURRET_LIMIT DEG(45)
#define VTOL_TURRET_LIMIT_BOMB DEG(60)
#define VTOL_ATTACK_AUDIO_DELAY (3*GAME_TICKS_PER_SEC)
/** Droids heavier than this rotate and pitch more slowly. */
#define HEAVY_WEAPON_WEIGHT 50000
#define ACTION_TURRET_ROTATION_RATE 45
#define REPAIR_PITCH_LOWER 30
#define REPAIR_PITCH_UPPER -15
/* How many tiles to pull back. */
#define PULL_BACK_DIST 10
// data required for any action
struct DROID_ACTION_DATA
{
DROID_ACTION action;
UDWORD x, y;
//multiple action target info
BASE_OBJECT *psObj;
BASE_STATS *psStats;
};
// Check if a droid has stopped moving
#define DROID_STOPPED(psDroid) \
(psDroid->sMove.Status == MOVEINACTIVE || psDroid->sMove.Status == MOVEHOVER || \
psDroid->sMove.Status == MOVESHUFFLE)
/** Radius for search when looking for VTOL landing position */
static const int vtolLandingRadius = 23;
/**
* @typedef tileMatchFunction
*
* @brief pointer to a 'tile search function', used by spiralSearch()
*
* @param x,y are the coordinates that should be inspected.
*
* @param data a pointer to state data, allows the search function to retain
* state in between calls and can be used as a means of returning
* its result to the caller of spiralSearch().
*
* @return true when the search has finished, false when the search should
* continue.
*/
typedef bool (*tileMatchFunction)(int x, int y, void *matchState);
const char *getDroidActionName(DROID_ACTION action)
{
static const char *name[] =
{
"DACTION_NONE", // not doing anything
"DACTION_MOVE", // 1 moving to a location
"DACTION_BUILD", // building a structure
"DACTION_BUILD_FOUNDATION", // 3 building a foundation for a structure
"DACTION_DEMOLISH", // demolishing a structure
"DACTION_REPAIR", // 5 repairing a structure
"DACTION_ATTACK", // attacking something
"DACTION_OBSERVE", // 7 observing something
"DACTION_FIRESUPPORT", // attacking something visible by a sensor droid
"DACTION_SULK", // 9 refuse to do anything aggressive for a fixed time
"DACTION_DESTRUCT", // self destruct
"DACTION_TRANSPORTOUT", // 11 move transporter offworld
"DACTION_TRANSPORTWAITTOFLYIN", // wait for timer to move reinforcements in
"DACTION_TRANSPORTIN", // 13 move transporter onworld
"DACTION_DROIDREPAIR", // repairing a droid
"DACTION_RESTORE", // 15 restore resistance points of a structure
"DACTION_UNUSED",
"DACTION_MOVEFIRE", // 17
"DACTION_MOVETOBUILD", // moving to a new building location
"DACTION_MOVETODEMOLISH", // 19 moving to a new demolition location
"DACTION_MOVETOREPAIR", // moving to a new repair location
"DACTION_BUILDWANDER", // 21 moving around while building
"DACTION_FOUNDATION_WANDER", // moving around while building the foundation
"DACTION_MOVETOATTACK", // 23 moving to a target to attack
"DACTION_ROTATETOATTACK", // rotating to a target to attack
"DACTION_MOVETOOBSERVE", // 25 moving to be able to see a target
"DACTION_WAITFORREPAIR", // waiting to be repaired by a facility
"DACTION_MOVETOREPAIRPOINT", // 27 move to repair facility repair point
"DACTION_WAITDURINGREPAIR", // waiting to be repaired by a facility
"DACTION_MOVETODROIDREPAIR", // 29 moving to a new location next to droid to be repaired
"DACTION_MOVETORESTORE", // moving to a low resistance structure
"DACTION_UNUSED2",
"DACTION_MOVETOREARM", // (32)moving to a rearming pad - VTOLS
"DACTION_WAITFORREARM", // (33)waiting for rearm - VTOLS
"DACTION_MOVETOREARMPOINT", // (34)move to rearm point - VTOLS - this actually moves them onto the pad
"DACTION_WAITDURINGREARM", // (35)waiting during rearm process- VTOLS
"DACTION_VTOLATTACK", // (36) a VTOL droid doing attack runs
"DACTION_CLEARREARMPAD", // (37) a VTOL droid being told to get off a rearm pad
"DACTION_RETURNTOPOS", // (38) used by scout/patrol order when returning to route
"DACTION_FIRESUPPORT_RETREAT", // (39) used by firesupport order when sensor retreats
"ACTION UNKNOWN",
"DACTION_CIRCLE" // (41) circling while engaging
};
ASSERT_OR_RETURN(nullptr, action < sizeof(name) / sizeof(name[0]), "DROID_ACTION out of range: %u", action);
return name[action];
}
// check if a target is within weapon range
bool actionInRange(const DROID *psDroid, const BASE_OBJECT *psObj, int weapon_slot, bool useLongWithOptimum)
{
CHECK_DROID(psDroid);
if (psDroid->asWeaps[0].nStat == 0)
{
return false;
}
const unsigned compIndex = psDroid->asWeaps[weapon_slot].nStat;
ASSERT_OR_RETURN(false, compIndex < numWeaponStats, "Invalid range referenced for numWeaponStats, %d > %d", compIndex, numWeaponStats);
const WEAPON_STATS *psStats = asWeaponStats + compIndex;
const int dx = (SDWORD)psDroid->pos.x - (SDWORD)psObj->pos.x;
const int dy = (SDWORD)psDroid->pos.y - (SDWORD)psObj->pos.y;
const int radSq = dx * dx + dy * dy;
const int longRange = proj_GetLongRange(psStats, psDroid->player);
const int shortRange = proj_GetShortRange(psStats, psDroid->player);
int rangeSq = 0;
switch (psDroid->secondaryOrder & DSS_ARANGE_MASK)
{
case DSS_ARANGE_OPTIMUM:
if (!useLongWithOptimum && weaponShortHit(psStats, psDroid->player) > weaponLongHit(psStats, psDroid->player))
{
rangeSq = shortRange * shortRange;
}
else
{
rangeSq = longRange * longRange;
}
break;
case DSS_ARANGE_SHORT:
rangeSq = shortRange * shortRange;
break;
case DSS_ARANGE_LONG:
rangeSq = longRange * longRange;
break;
default:
ASSERT(!"unknown attackrange order", "unknown attack range order");
rangeSq = longRange * longRange;
break;
}
/* check max range */
if (radSq <= rangeSq)
{
/* check min range */
const int minrange = proj_GetMinRange(psStats, psDroid->player);
if (radSq >= minrange * minrange || !proj_Direct(psStats))
{
return true;
}
}
return false;
}
// check if a target is inside minimum weapon range
static bool actionInsideMinRange(DROID *psDroid, BASE_OBJECT *psObj, WEAPON_STATS *psStats)
{
CHECK_DROID(psDroid);
CHECK_OBJECT(psObj);
if (!psStats)
{
psStats = getWeaponStats(psDroid, 0);
}
/* if I am a multi-turret droid */
if (psDroid->asWeaps[0].nStat == 0)
{
return false;
}
const int dx = psDroid->pos.x - psObj->pos.x;
const int dy = psDroid->pos.y - psObj->pos.y;
const int radSq = dx * dx + dy * dy;
const int minRange = proj_GetMinRange(psStats, psDroid->player);
const int rangeSq = minRange * minRange;
// check min range
if (radSq <= rangeSq)
{
return true;
}
return false;
}
// Realign turret
void actionAlignTurret(BASE_OBJECT *psObj, int weapon_slot)
{
uint16_t nearest = 0;
uint16_t tRot;
uint16_t tPitch;
//get the maximum rotation this frame
const int rotation = gameTimeAdjustedIncrement(DEG(ACTION_TURRET_ROTATION_RATE));
switch (psObj->type)
{
case OBJ_DROID:
tRot = ((DROID *)psObj)->asWeaps[weapon_slot].rot.direction;
tPitch = ((DROID *)psObj)->asWeaps[weapon_slot].rot.pitch;
break;
case OBJ_STRUCTURE:
tRot = ((STRUCTURE *)psObj)->asWeaps[weapon_slot].rot.direction;
tPitch = ((STRUCTURE *)psObj)->asWeaps[weapon_slot].rot.pitch;
// now find the nearest 90 degree angle
nearest = (uint16_t)((tRot + DEG(45)) / DEG(90) * DEG(90)); // Cast wrapping intended.
break;
default:
ASSERT(!"invalid object type", "invalid object type");
return;
}
tRot += clip(angleDelta(nearest - tRot), -rotation, rotation); // Addition wrapping intended.
// align the turret pitch
tPitch += clip(angleDelta(0 - tPitch), -rotation / 2, rotation / 2); // Addition wrapping intended.
switch (psObj->type)
{
case OBJ_DROID:
((DROID *)psObj)->asWeaps[weapon_slot].rot.direction = tRot;
((DROID *)psObj)->asWeaps[weapon_slot].rot.pitch = tPitch;
break;
case OBJ_STRUCTURE:
((STRUCTURE *)psObj)->asWeaps[weapon_slot].rot.direction = tRot;
((STRUCTURE *)psObj)->asWeaps[weapon_slot].rot.pitch = tPitch;
break;
default:
ASSERT(!"invalid object type", "invalid object type");
return;
}
}
/* returns true if on target */
bool actionTargetTurret(BASE_OBJECT *psAttacker, BASE_OBJECT *psTarget, WEAPON *psWeapon)
{
WEAPON_STATS *psWeapStats = asWeaponStats + psWeapon->nStat;
uint16_t tRotation, tPitch;
uint16_t targetRotation;
int32_t rotationTolerance = 0;
int32_t pitchLowerLimit, pitchUpperLimit;
if (!psTarget)
{
return false;
}
bool bRepair = psAttacker->type == OBJ_DROID && ((DROID *)psAttacker)->droidType == DROID_REPAIR;
// these are constants now and can be set up at the start of the function
int rotRate = DEG(ACTION_TURRET_ROTATION_RATE) * 4;
int pitchRate = DEG(ACTION_TURRET_ROTATION_RATE) * 2;
// extra heavy weapons on some structures need to rotate and pitch more slowly
if (psWeapStats->weight > HEAVY_WEAPON_WEIGHT && !bRepair)
{
UDWORD excess = DEG(100) * (psWeapStats->weight - HEAVY_WEAPON_WEIGHT) / psWeapStats->weight;
rotRate = DEG(ACTION_TURRET_ROTATION_RATE) * 2 - excess;
pitchRate = rotRate / 2;
}
tRotation = psWeapon->rot.direction;
tPitch = psWeapon->rot.pitch;
//set the pitch limits based on the weapon stats of the attacker
pitchLowerLimit = pitchUpperLimit = 0;
Vector3i attackerMuzzlePos = psAttacker->pos; // Using for calculating the pitch, but not the direction, in case using the exact direction causes bugs somewhere.
if (psAttacker->type == OBJ_STRUCTURE)
{
STRUCTURE *psStructure = (STRUCTURE *)psAttacker;
int weapon_slot = psWeapon - psStructure->asWeaps; // Should probably be passed weapon_slot instead of psWeapon.
calcStructureMuzzleLocation(psStructure, &attackerMuzzlePos, weapon_slot);
pitchLowerLimit = DEG(psWeapStats->minElevation);
pitchUpperLimit = DEG(psWeapStats->maxElevation);
}
else if (psAttacker->type == OBJ_DROID)
{
DROID *psDroid = (DROID *)psAttacker;
int weapon_slot = psWeapon - psDroid->asWeaps; // Should probably be passed weapon_slot instead of psWeapon.
calcDroidMuzzleLocation(psDroid, &attackerMuzzlePos, weapon_slot);
if (psDroid->droidType == DROID_WEAPON || isTransporter(psDroid)
|| psDroid->droidType == DROID_COMMAND || psDroid->droidType == DROID_CYBORG
|| psDroid->droidType == DROID_CYBORG_SUPER)
{
pitchLowerLimit = DEG(psWeapStats->minElevation);
pitchUpperLimit = DEG(psWeapStats->maxElevation);
}
else if (psDroid->droidType == DROID_REPAIR)
{
pitchLowerLimit = DEG(REPAIR_PITCH_LOWER);
pitchUpperLimit = DEG(REPAIR_PITCH_UPPER);
}
}
//get the maximum rotation this frame
rotRate = gameTimeAdjustedIncrement(rotRate);
rotRate = MAX(rotRate, DEG(1));
pitchRate = gameTimeAdjustedIncrement(pitchRate);
pitchRate = MAX(pitchRate, DEG(1));
//and point the turret at target
targetRotation = calcDirection(psAttacker->pos.x, psAttacker->pos.y, psTarget->pos.x, psTarget->pos.y);
//restrict rotationerror to =/- 180 degrees
int rotationError = angleDelta(targetRotation - (tRotation + psAttacker->rot.direction));
tRotation += clip(rotationError, -rotRate, rotRate); // Addition wrapping intentional.
if (psAttacker->type == OBJ_DROID && isVtolDroid((DROID *)psAttacker))
{
// limit the rotation for vtols
int32_t limit = VTOL_TURRET_LIMIT;
if (psWeapStats->weaponSubClass == WSC_BOMB || psWeapStats->weaponSubClass == WSC_EMP)
{
limit = 0; // Don't turn bombs.
rotationTolerance = VTOL_TURRET_LIMIT_BOMB;
}
tRotation = (uint16_t)clip(angleDelta(tRotation), -limit, limit); // Cast wrapping intentional.
}
bool onTarget = abs(angleDelta(targetRotation - (tRotation + psAttacker->rot.direction))) <= rotationTolerance;
/* Set muzzle pitch if not repairing or outside minimum range */
const int minRange = proj_GetMinRange(psWeapStats, psAttacker->player);
if (!bRepair && (unsigned)objPosDiffSq(psAttacker, psTarget) > minRange * minRange)
{
/* get target distance */
Vector3i delta = psTarget->pos - attackerMuzzlePos;
int32_t dxy = iHypot(delta.x, delta.y);
uint16_t targetPitch = iAtan2(delta.z, dxy);
targetPitch = (uint16_t)clip(angleDelta(targetPitch), pitchLowerLimit, pitchUpperLimit); // Cast wrapping intended.
int pitchError = angleDelta(targetPitch - tPitch);
tPitch += clip(pitchError, -pitchRate, pitchRate); // Addition wrapping intended.
onTarget = onTarget && targetPitch == tPitch;
}
psWeapon->rot.direction = tRotation;
psWeapon->rot.pitch = tPitch;
return onTarget;
}
// return whether a droid can see a target to fire on it
bool actionVisibleTarget(DROID *psDroid, BASE_OBJECT *psTarget, int weapon_slot)
{
CHECK_DROID(psDroid);
ASSERT_OR_RETURN(false, psTarget != nullptr, "Target is NULL");
if (!psTarget->visible[psDroid->player])
{
return false;
}
if ((psDroid->numWeaps == 0 || isVtolDroid(psDroid)) && visibleObject(psDroid, psTarget, false))
{
return true;
}
return (orderState(psDroid, DORDER_FIRESUPPORT) || visibleObject(psDroid, psTarget, false))
&& lineOfFire(psDroid, psTarget, weapon_slot, true);
}
static void actionAddVtolAttackRun(DROID *psDroid)
{
BASE_OBJECT *psTarget;
CHECK_DROID(psDroid);
if (psDroid->psActionTarget[0] != nullptr)
{
psTarget = psDroid->psActionTarget[0];
}
else if (psDroid->order.psObj != nullptr)
{
psTarget = psDroid->order.psObj;
}
else
{
return;
}
/* get normal vector from droid to target */
Vector2i delta = (psTarget->pos - psDroid->pos).xy();
/* get magnitude of normal vector (Pythagorean theorem) */
int dist = std::max(iHypot(delta), 1);
/* add waypoint behind target attack length away*/
Vector2i dest = psTarget->pos.xy() + delta * VTOL_ATTACK_LENGTH / dist;
if (!worldOnMap(dest))
{
debug(LOG_NEVER, "*** actionAddVtolAttackRun: run off map! ***");
}
else
{
moveDroidToDirect(psDroid, dest.x, dest.y);
}
}
static void actionUpdateVtolAttack(DROID *psDroid)
{
CHECK_DROID(psDroid);
/* don't do attack runs whilst returning to base */
if (psDroid->order.type == DORDER_RTB)
{
return;
}
/* order back to base after fixed number of attack runs */
if (psDroid->numWeaps > 0 && psDroid->asWeaps[0].nStat > 0 && vtolEmpty(psDroid))
{
moveToRearm(psDroid);
return;
}
/* circle around target if hovering and not cyborg */
if (psDroid->sMove.Status == MOVEHOVER && !cyborgDroid(psDroid))
{
actionAddVtolAttackRun(psDroid);
}
}
static void actionUpdateTransporter(DROID *psDroid)
{
CHECK_DROID(psDroid);
//check if transporter has arrived
if (updateTransporter(psDroid))
{
// Got to destination
psDroid->action = DACTION_NONE;
}
}
// calculate a position for units to pull back to if they
// need to increase the range between them and a target
static void actionCalcPullBackPoint(BASE_OBJECT *psObj, BASE_OBJECT *psTarget, int *px, int *py)
{
// get the vector from the target to the object
int xdiff = psObj->pos.x - psTarget->pos.x;
int ydiff = psObj->pos.y - psTarget->pos.y;
const int len = iHypot(xdiff, ydiff);
if (len == 0)
{
xdiff = TILE_UNITS;
ydiff = TILE_UNITS;
}
else
{
xdiff = (xdiff * TILE_UNITS) / len;
ydiff = (ydiff * TILE_UNITS) / len;
}
// create the position
*px = psObj->pos.x + xdiff * PULL_BACK_DIST;
*py = psObj->pos.y + ydiff * PULL_BACK_DIST;
// make sure coordinates stay inside of the map
clip_world_offmap(px, py);
}
// check whether a droid is in the neighboring tile to a build position
bool actionReachedBuildPos(DROID const *psDroid, int x, int y, uint16_t dir, BASE_STATS const *psStats)
{
ASSERT_OR_RETURN(false, psStats != nullptr && psDroid != nullptr, "Bad stat or droid");
CHECK_DROID(psDroid);
StructureBounds b = getStructureBounds(psStats, Vector2i(x, y), dir);
// do all calculations in half tile units so that
// the droid moves to within half a tile of the target
// NOT ANY MORE - JOHN
Vector2i delta = map_coord(psDroid->pos.xy()) - b.map;
return delta.x >= -1 && delta.x <= b.size.x && delta.y >= -1 && delta.y <= b.size.y;
}
// check if a droid is on the foundations of a new building
static bool actionRemoveDroidsFromBuildPos(unsigned player, Vector2i pos, uint16_t dir, BASE_STATS *psStats)
{
ASSERT_OR_RETURN(false, psStats != nullptr, "Bad stat");
bool buildPosEmpty = true;
StructureBounds b = getStructureBounds(psStats, pos, dir);
Vector2i structureCentre = world_coord(b.map) + world_coord(b.size) / 2;
unsigned structureMaxRadius = iHypot(world_coord(b.size) / 2) + 1; // +1 since iHypot rounds down.
static GridList gridList; // static to avoid allocations.
gridList = gridStartIterate(structureCentre.x, structureCentre.y, structureMaxRadius);
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
DROID *droid = castDroid(*gi);
if (droid == nullptr)
{
continue; // Only looking for droids.
}
Vector2i delta = map_coord(droid->pos.xy()) - b.map;
if (delta.x < 0 || delta.x >= b.size.x || delta.y < 0 || delta.y >= b.size.y || isFlying(droid))
{
continue; // Droid not under new structure (just near it).
}
buildPosEmpty = false; // Found a droid, have to move it away.
if (!aiCheckAlliances(player, droid->player))
{
continue; // Enemy droids probably don't feel like moving.
}
// TODO If the action code was less convoluted, it would be possible for the droid should drive away instead of just getting moved away.
Vector2i bestDest(0, 0); // Dummy initialisation.
unsigned bestDist = UINT32_MAX;
for (int y = -1; y <= b.size.y; ++y)
for (int x = -1; x <= b.size.x; x += y >= 0 && y < b.size.y ? b.size.x + 1 : 1)
{
Vector2i dest = world_coord(b.map + Vector2i(x, y)) + Vector2i(TILE_UNITS, TILE_UNITS) / 2;
unsigned dist = iHypot(droid->pos.xy() - dest);
if (dist < bestDist && !fpathBlockingTile(map_coord(dest.x), map_coord(dest.y), getPropulsionStats(droid)->propulsionType))
{
bestDest = dest;
bestDist = dist;
}
}
if (bestDist != UINT32_MAX)
{
// Push the droid out of the way.
Vector2i newPos = droid->pos.xy() + iSinCosR(iAtan2(bestDest - droid->pos.xy()), gameTimeAdjustedIncrement(TILE_UNITS));
droidSetPosition(droid, newPos.x, newPos.y);
}
}
return buildPosEmpty;
}
void actionSanity(DROID *psDroid)
{
// Don't waste ammo unless given a direct attack order.
bool avoidOverkill = psDroid->order.type != DORDER_ATTACK &&
(psDroid->action == DACTION_ATTACK || psDroid->action == DACTION_MOVEFIRE || psDroid->action == DACTION_MOVETOATTACK ||
psDroid->action == DACTION_ROTATETOATTACK || psDroid->action == DACTION_VTOLATTACK);
bool bDirect = false;
// clear the target if it has died
for (int i = 0; i < MAX_WEAPONS; i++)
{
bDirect = proj_Direct(asWeaponStats + psDroid->asWeaps[i].nStat);
if (psDroid->psActionTarget[i] && (avoidOverkill ? aiObjectIsProbablyDoomed(psDroid->psActionTarget[i], bDirect) : psDroid->psActionTarget[i]->died))
{
syncDebugObject(psDroid->psActionTarget[i], '-');
setDroidActionTarget(psDroid, nullptr, i);
if (i == 0)
{
if (psDroid->action != DACTION_MOVEFIRE &&
psDroid->action != DACTION_TRANSPORTIN &&
psDroid->action != DACTION_TRANSPORTOUT)
{
psDroid->action = DACTION_NONE;
// if VTOL - return to rearm pad if not patrolling
if (isVtolDroid(psDroid))
{
if ((psDroid->order.type == DORDER_PATROL || psDroid->order.type == DORDER_CIRCLE) && (!vtolEmpty(psDroid) || (psDroid->secondaryOrder & DSS_ALEV_MASK) == DSS_ALEV_NEVER))
{
// Back to the patrol.
actionDroid(psDroid, DACTION_MOVE, psDroid->order.pos.x, psDroid->order.pos.y);
}
else
{
moveToRearm(psDroid);
}
}
}
}
}
}
}
// Update the action state for a droid
void actionUpdateDroid(DROID *psDroid)
{
bool (*actionUpdateFunc)(DROID * psDroid) = nullptr;
bool nonNullWeapon[MAX_WEAPONS] = { false };
BASE_OBJECT *psTargets[MAX_WEAPONS] = { nullptr };
bool hasVisibleTarget = false;
bool targetVisibile[MAX_WEAPONS] = { false };
bool bHasTarget = false;
bool bDirect = false;
STRUCTURE *blockingWall = nullptr;
bool wallBlocked = false;
CHECK_DROID(psDroid);
PROPULSION_STATS *psPropStats = asPropulsionStats + psDroid->asBits[COMP_PROPULSION];
ASSERT_OR_RETURN(, psPropStats != nullptr, "Invalid propulsion stats pointer");
bool secHoldActive = secondaryGetState(psDroid, DSO_HALTTYPE) == DSS_HALT_HOLD;
actionSanity(psDroid);
//if the droid has been attacked by an EMP weapon, it is temporarily disabled
if (psDroid->lastHitWeapon == WSC_EMP)
{
if (gameTime - psDroid->timeLastHit > EMP_DISABLE_TIME)
{
//the actionStarted time needs to be adjusted
psDroid->actionStarted += (gameTime - psDroid->timeLastHit);
//reset the lastHit parameters
psDroid->timeLastHit = 0;
psDroid->lastHitWeapon = WSC_NUM_WEAPON_SUBCLASSES;
}
else
{
//get out without updating
return;
}
}
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
if (psDroid->asWeaps[i].nStat > 0)
{
nonNullWeapon[i] = true;
}
}
// HACK: Apparently we can't deal with a droid that only has NULL weapons ?
// FIXME: Find out whether this is really necessary
if (psDroid->numWeaps <= 1)
{
nonNullWeapon[0] = true;
}
DROID_ORDER_DATA *order = &psDroid->order;
switch (psDroid->action)
{
case DACTION_NONE:
case DACTION_WAITFORREPAIR:
// doing nothing
// see if there's anything to shoot.
if (psDroid->numWeaps > 0 && !isVtolDroid(psDroid)
&& (order->type == DORDER_NONE || order->type == DORDER_HOLD || order->type == DORDER_RTR || order->type == DORDER_GUARD))
{
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
if (nonNullWeapon[i])
{
BASE_OBJECT *psTemp = nullptr;
WEAPON_STATS *const psWeapStats = &asWeaponStats[psDroid->asWeaps[i].nStat];
if (psDroid->asWeaps[i].nStat > 0
&& psWeapStats->rotate
&& aiBestNearestTarget(psDroid, &psTemp, i) >= 0)
{
if (secondaryGetState(psDroid, DSO_ATTACK_LEVEL) == DSS_ALEV_ALWAYS)
{
psDroid->action = DACTION_ATTACK;
setDroidActionTarget(psDroid, psTemp, 0);
}
}
}
}
}
break;
case DACTION_WAITDURINGREPAIR:
// Check that repair facility still exists
if (!order->psObj)
{
psDroid->action = DACTION_NONE;
break;
}
// move back to the repair facility if necessary
if (DROID_STOPPED(psDroid) &&
!actionReachedBuildPos(psDroid,
order->psObj->pos.x, order->psObj->pos.y, ((STRUCTURE *)order->psObj)->rot.direction,
((STRUCTURE *)order->psObj)->pStructureType))
{
moveDroidToNoFormation(psDroid, order->psObj->pos.x, order->psObj->pos.y);
}
break;
case DACTION_TRANSPORTWAITTOFLYIN:
//if we're moving droids to safety and currently waiting to fly back in, see if time is up
if (psDroid->player == selectedPlayer && getDroidsToSafetyFlag())
{
if ((SDWORD)(mission.ETA - (gameTime - missionGetReinforcementTime())) <= 0)
{
UDWORD droidX, droidY;
if (!droidRemove(psDroid, mission.apsDroidLists))
{
ASSERT_OR_RETURN(, false, "Unable to remove transporter from mission list");
}
addDroid(psDroid, apsDroidLists);
//set the x/y up since they were set to INVALID_XY when moved offWorld
missionGetTransporterExit(selectedPlayer, &droidX, &droidY);
psDroid->pos.x = droidX;
psDroid->pos.y = droidY;
//fly Transporter back to get some more droids
orderDroidLoc(psDroid, DORDER_TRANSPORTIN,
getLandingX(selectedPlayer), getLandingY(selectedPlayer), ModeImmediate);
}
}
break;
case DACTION_MOVE:
case DACTION_RETURNTOPOS:
case DACTION_FIRESUPPORT_RETREAT:
// moving to a location
if (DROID_STOPPED(psDroid))
{
bool notify = psDroid->action == DACTION_MOVE;
// Got to destination
psDroid->action = DACTION_NONE;
if (notify)
{
/* notify scripts we have reached the destination
* also triggers when patrolling and reached a waypoint
*/
psScrCBOrder = order->type;
psScrCBOrderDroid = psDroid;
eventFireCallbackTrigger((TRIGGER_TYPE)CALL_DROID_REACH_LOCATION);
psScrCBOrderDroid = nullptr;
psScrCBOrder = DORDER_NONE;
triggerEventDroidIdle(psDroid);
}
}
//added multiple weapon check
else if (psDroid->numWeaps > 0)
{
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
if (nonNullWeapon[i])
{
BASE_OBJECT *psTemp = nullptr;
//I moved psWeapStats flag update there
WEAPON_STATS *const psWeapStats = &asWeaponStats[psDroid->asWeaps[i].nStat];
if (!isVtolDroid(psDroid)
&& psDroid->asWeaps[i].nStat > 0
&& psWeapStats->rotate
&& psWeapStats->fireOnMove
&& aiBestNearestTarget(psDroid, &psTemp, i) >= 0)
{
if (secondaryGetState(psDroid, DSO_ATTACK_LEVEL) == DSS_ALEV_ALWAYS)
{
psDroid->action = DACTION_MOVEFIRE;
setDroidActionTarget(psDroid, psTemp, i);
}
}
}
}
}
break;
case DACTION_TRANSPORTIN:
case DACTION_TRANSPORTOUT:
actionUpdateTransporter(psDroid);
break;
case DACTION_MOVEFIRE:
// check if vtol is armed
if (vtolEmpty(psDroid))
{
moveToRearm(psDroid);
}
// If droid stopped, it can no longer be in DACTION_MOVEFIRE
if (DROID_STOPPED(psDroid))
{
psDroid->action = DACTION_NONE;
break;
}
// loop through weapons and look for target for each weapon
bHasTarget = false;
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
bDirect = proj_Direct(asWeaponStats + psDroid->asWeaps[i].nStat);
blockingWall = nullptr;
// Does this weapon have a target?
if (psDroid->psActionTarget[i] != nullptr)
{
// Is target worth shooting yet?
if (aiObjectIsProbablyDoomed(psDroid->psActionTarget[i], bDirect))
{
setDroidActionTarget(psDroid, nullptr, i);
}
// Is target from our team now? (Electronic Warfare)
else if (electronicDroid(psDroid) && psDroid->player == psDroid->psActionTarget[i]->player)
{
setDroidActionTarget(psDroid, nullptr, i);
}
// Is target blocked by a wall?
else if (bDirect && visGetBlockingWall(psDroid, psDroid->psActionTarget[i]))
{
setDroidActionTarget(psDroid, nullptr, i);
}
// I have a target!
else
{
bHasTarget = true;
}
}
// This weapon doesn't have a target
else
{
// Can we find a good target for the weapon?
BASE_OBJECT *psTemp;
if (aiBestNearestTarget(psDroid, &psTemp, i) >= 0) // assuming aiBestNearestTarget checks for electronic warfare
{
bHasTarget = true;
setDroidActionTarget(psDroid, psTemp, i); // this updates psDroid->psActionTarget[i] to != NULL
}
}
// If we have a target for the weapon: is it visible?
if (psDroid->psActionTarget[i] != nullptr && visibleObject(psDroid, psDroid->psActionTarget[i], false))
{
hasVisibleTarget = true; // droid have a visible target to shoot
targetVisibile[i] = true;// it is at least visible for this weapon
}
}
// if there is at least one target
if (bHasTarget)
{
// loop through weapons
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
const unsigned compIndex = psDroid->asWeaps[i].nStat;
const WEAPON_STATS *psStats = asWeaponStats + compIndex;
wallBlocked = false;
// has weapon a target? is target valid?
if (psDroid->psActionTarget[i] != nullptr && validTarget(psDroid, psDroid->psActionTarget[i], i))
{
// is target visible and weapon is not a Nullweapon?
if (targetVisibile[i] && nonNullWeapon[i]) //to fix a AA-weapon attack ground unit exploit
{
BASE_OBJECT *psActionTarget = nullptr;
blockingWall = visGetBlockingWall(psDroid, psDroid->psActionTarget[i]);
if (proj_Direct(psStats) && blockingWall)
{
WEAPON_EFFECT weapEffect = psStats->weaponEffect;
if (!aiCheckAlliances(psDroid->player, blockingWall->player)
&& asStructStrengthModifier[weapEffect][blockingWall->pStructureType->strength] >= 100)
{
psActionTarget = blockingWall;
setDroidActionTarget(psDroid, psActionTarget, i); // attack enemy wall
}
else
{
wallBlocked = true;
}
}
else
{
psActionTarget = psDroid->psActionTarget[i];
}
// is the turret aligned with the target?
if (!wallBlocked && actionTargetTurret(psDroid, psActionTarget, &psDroid->asWeaps[i]))
{
// In range - fire !!!
combFire(&psDroid->asWeaps[i], psDroid, psActionTarget, i);
}
}
}
}
// Droid don't have a visible target and it is not in pursue mode
if (!hasVisibleTarget && secondaryGetState(psDroid, DSO_ATTACK_LEVEL) != DSS_ALEV_ALWAYS)
{
// Target lost
psDroid->action = DACTION_MOVE;
}
}
// it don't have a target, change to DACTION_MOVE
else
{
psDroid->action = DACTION_MOVE;
}
//check its a VTOL unit since adding Transporter's into multiPlayer
/* check vtol attack runs */
if (isVtolDroid(psDroid))
{
actionUpdateVtolAttack(psDroid);
}
break;
case DACTION_ATTACK:
case DACTION_ROTATETOATTACK:
ASSERT_OR_RETURN(, psDroid->psActionTarget[0] != nullptr, "target is NULL while attacking");
if (psDroid->action == DACTION_ROTATETOATTACK)
{
if (psDroid->sMove.Status == MOVETURNTOTARGET)
{
moveTurnDroid(psDroid, psDroid->psActionTarget[0]->pos.x, psDroid->psActionTarget[0]->pos.y);
break; // Still turning.
}
psDroid->action = DACTION_ATTACK;
}
//check the target hasn't become one the same player ID - Electronic Warfare
if (electronicDroid(psDroid) && psDroid->player == psDroid->psActionTarget[0]->player)
{
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
setDroidActionTarget(psDroid, nullptr, i);
}
psDroid->action = DACTION_NONE;
break;
}
bHasTarget = false;
wallBlocked = false;
for (unsigned i = 0; i < psDroid->numWeaps; ++i)
{
BASE_OBJECT *psActionTarget;
if (i > 0)
{
// If we're ordered to shoot something, and we can, shoot it
if ((order->type == DORDER_ATTACK || order->type == DORDER_ATTACKTARGET) &&
psDroid->psActionTarget[i] != psDroid->psActionTarget[0] &&
validTarget(psDroid, psDroid->psActionTarget[0], i) &&
actionInRange(psDroid, psDroid->psActionTarget[0], i))
{
setDroidActionTarget(psDroid, psDroid->psActionTarget[0], i);