forked from Warzone2100/warzone2100
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprojectile.cpp
1741 lines (1490 loc) · 56.1 KB
/
projectile.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
*/
/***************************************************************************/
/*
* Projectile functions
*
*/
/***************************************************************************/
#include <string.h>
#include "lib/framework/frame.h"
#include "lib/framework/trig.h"
#include "lib/framework/fixedpoint.h"
#include "lib/framework/math_ext.h"
#include "lib/gamelib/gtime.h"
#include "lib/sound/audio_id.h"
#include "lib/sound/audio.h"
#include "lib/ivis_opengl/ivisdef.h"
#include "lib/ivis_opengl/piestate.h"
#include "lib/ivis_opengl/piematrix.h"
#include "objects.h"
#include "move.h"
#include "action.h"
#include "combat.h"
#include "effects.h"
#include "map.h"
#include "order.h"
#include "projectile.h"
#include "visibility.h"
#include "group.h"
#include "cmddroid.h"
#include "feature.h"
#include "loop.h"
#include "scores.h"
#include "display3ddef.h"
#include "display.h"
#include "multiplay.h"
#include "multistat.h"
#include "mapgrid.h"
#include "random.h"
#include <algorithm>
#include <functional>
#ifndef GLM_ENABLE_EXPERIMENTAL
#define GLM_ENABLE_EXPERIMENTAL
#endif
#include <glm/gtx/transform.hpp>
#define VTOL_HITBOX_MODIFICATOR 100
#define HOMINGINDIRECT_HEIGHT_MIN 200
#define HOMINGINDIRECT_HEIGHT_MAX 450
static int experienceGain[MAX_PLAYERS];
struct INTERVAL
{
int begin, end; // Time 1 = 0, time 2 = 1024. Or begin >= end if empty.
};
// Watermelon:they are from droid.c
/* The range for neighbouring objects */
#define PROJ_NEIGHBOUR_RANGE (TILE_UNITS*4)
// used to create a specific ID for projectile objects to facilitate tracking them.
static const UDWORD ProjectileTrackerID = 0xdead0000;
/* The list of projectiles in play */
static std::vector<PROJECTILE *> psProjectileList;
/* The next projectile to give out in the proj_First / proj_Next methods */
static ProjectileIterator psProjectileNext;
/***************************************************************************/
// the last unit that did damage - used by script functions
BASE_OBJECT *g_pProjLastAttacker;
/***************************************************************************/
static void proj_ImpactFunc(PROJECTILE *psObj);
static void proj_PostImpactFunc(PROJECTILE *psObj);
static void proj_checkPeriodicalDamage(PROJECTILE *psProj);
static int32_t objectDamage(BASE_OBJECT *psObj, unsigned damage, WEAPON_CLASS weaponClass, WEAPON_SUBCLASS weaponSubClass, unsigned impactTime, bool isDamagePerSecond, int minDamage);
static inline void setProjectileDestination(PROJECTILE *psProj, BASE_OBJECT *psObj)
{
bool bDirect = proj_Direct(psProj->psWStats);
#if defined( _MSC_VER )
#pragma warning( push )
#pragma warning( disable : 4146 ) // warning C4146: unary minus operator applied to unsigned type, result still unsigned
#endif
aiObjectAddExpectedDamage(psProj->psDest, -psProj->expectedDamageCaused, bDirect); // The old target shouldn't be expecting any more damage from this projectile.
#if defined( _MSC_VER )
#pragma warning( pop )
#endif
psProj->psDest = psObj;
aiObjectAddExpectedDamage(psProj->psDest, psProj->expectedDamageCaused, bDirect); // Let the new target know to say its prayers.
}
/***************************************************************************/
bool gfxVisible(PROJECTILE *psObj)
{
// Already know it is visible
if (psObj->bVisible)
{
return true;
}
// You fired it
if (psObj->player == selectedPlayer)
{
return true;
}
// Someone elses structure firing at something you can't see
if (psObj->psSource != nullptr
&& !psObj->psSource->died
&& psObj->psSource->type == OBJ_STRUCTURE
&& psObj->psSource->player != selectedPlayer
&& (psObj->psDest == nullptr
|| psObj->psDest->died
|| !psObj->psDest->visible[selectedPlayer]))
{
return false;
}
// Something you cannot see firing at a structure that isn't yours
if (psObj->psDest != nullptr
&& !psObj->psDest->died
&& psObj->psDest->type == OBJ_STRUCTURE
&& psObj->psDest->player != selectedPlayer
&& (psObj->psSource == nullptr
|| !psObj->psSource->visible[selectedPlayer]))
{
return false;
}
// You can see the source
if (psObj->psSource != nullptr
&& !psObj->psSource->died
&& psObj->psSource->visible[selectedPlayer])
{
return true;
}
// You can see the destination
if (psObj->psDest != nullptr
&& !psObj->psDest->died
&& psObj->psDest->visible[selectedPlayer])
{
return true;
}
return false;
}
/***************************************************************************/
bool
proj_InitSystem()
{
psProjectileList.clear();
psProjectileNext = psProjectileList.end();
for (int x = 0; x < MAX_PLAYERS; ++x)
{
experienceGain[x] = 100;
}
return true;
}
/***************************************************************************/
// Clean out all projectiles from the system, and properly decrement
// all reference counts.
void
proj_FreeAllProjectiles()
{
psProjectileList.clear();
psProjectileNext = psProjectileList.end();
}
/***************************************************************************/
bool
proj_Shutdown()
{
proj_FreeAllProjectiles();
return true;
}
/***************************************************************************/
// Reset the first/next methods, and give out the first projectile in the list.
PROJECTILE *
proj_GetFirst()
{
psProjectileNext = psProjectileList.begin();
return psProjectileNext != psProjectileList.end() ? *psProjectileNext : nullptr;
}
/***************************************************************************/
// Get the next projectile
PROJECTILE *
proj_GetNext()
{
++psProjectileNext;
return psProjectileNext != psProjectileList.end() ? *psProjectileNext : nullptr;
}
/***************************************************************************/
/*
* Relates the quality of the attacker to the quality of the victim.
* The value returned satisfies the following inequality: 0.5 <= ret/65536 <= 2.0
*/
static uint32_t qualityFactor(DROID *psAttacker, DROID *psVictim)
{
uint32_t powerRatio = (uint64_t)65536 * calcDroidPower(psVictim) / calcDroidPower(psAttacker);
uint32_t pointsRatio = (uint64_t)65536 * calcDroidPoints(psVictim) / calcDroidPoints(psAttacker);
CLIP(powerRatio, 65536 / 2, 65536 * 2);
CLIP(pointsRatio, 65536 / 2, 65536 * 2);
return (powerRatio + pointsRatio) / 2;
}
void setExpGain(int player, int gain)
{
experienceGain[player] = gain;
}
int getExpGain(int player)
{
return experienceGain[player];
}
// update the kills after a target is damaged/destroyed
static void proj_UpdateKills(PROJECTILE *psObj, int32_t experienceInc)
{
DROID *psDroid;
BASE_OBJECT *psSensor;
CHECK_PROJECTILE(psObj);
if (psObj->psSource == nullptr || (psObj->psDest && psObj->psDest->type == OBJ_FEATURE)
|| (psObj->psDest && psObj->psSource->player == psObj->psDest->player)) // no exp for friendly fire
{
return;
}
// If experienceInc is negative then the target was killed
if (bMultiPlayer && experienceInc < 0)
{
updateMultiStatsKills(psObj->psDest, psObj->psSource->player);
}
// Since we are no longer interested if it was killed or not, abs it
experienceInc = abs(experienceInc) * getExpGain(psObj->psSource->player) / 100;
if (psObj->psSource->type == OBJ_DROID) /* update droid kills */
{
psDroid = (DROID *) psObj->psSource;
// If it is 'droid-on-droid' then modify the experience by the Quality factor
// Only do this in MP so to not un-balance the campaign
if (psObj->psDest != nullptr
&& psObj->psDest->type == OBJ_DROID
&& bMultiPlayer)
{
// Modify the experience gained by the 'quality factor' of the units
experienceInc = (uint64_t)experienceInc * qualityFactor(psDroid, (DROID *)psObj->psDest) / 65536;
}
ASSERT_OR_RETURN(, 0 <= experienceInc && experienceInc < (int)(2.1 * 65536), "Experience increase out of range");
psDroid->experience += experienceInc;
cmdDroidUpdateKills(psDroid, experienceInc);
psSensor = orderStateObj(psDroid, DORDER_FIRESUPPORT);
if (psSensor
&& psSensor->type == OBJ_DROID)
{
((DROID *)psSensor)->experience += experienceInc;
}
}
else if (psObj->psSource->type == OBJ_STRUCTURE)
{
ASSERT_OR_RETURN(, 0 <= experienceInc && experienceInc < (int)(2.1 * 65536), "Experience increase out of range");
// See if there was a command droid designating this target
psDroid = cmdDroidGetDesignator(psObj->psSource->player);
if (psDroid != nullptr
&& psDroid->action == DACTION_ATTACK
&& psDroid->psActionTarget[0] == psObj->psDest)
{
psDroid->experience += experienceInc;
}
}
}
/***************************************************************************/
void _syncDebugProjectile(const char *function, PROJECTILE const *psProj, char ch)
{
if (psProj->type != OBJ_PROJECTILE) {
ASSERT(false, "%c Broken psProj->type %u!", ch, psProj->type);
syncDebug("Broken psProj->type %u!", psProj->type);
}
int list[] =
{
ch,
psProj->player,
psProj->pos.x, psProj->pos.y, psProj->pos.z,
psProj->rot.direction, psProj->rot.pitch, psProj->rot.roll,
psProj->state,
(int)psProj->expectedDamageCaused,
(int)psProj->psDamaged.size(),
};
_syncDebugIntList(function, "%c projectile = p%d;pos(%d,%d,%d),rot(%d,%d,%d),state%d,expectedDamageCaused%d,numberDamaged%u", list, ARRAY_SIZE(list));
}
static int32_t randomVariation(int32_t val)
{
// Up to ±5% random variation.
return (int64_t)val * (95000 + gameRand(10001)) / 100000;
}
int32_t projCalcIndirectVelocities(const int32_t dx, const int32_t dz, int32_t v, int32_t *vx, int32_t *vz, int min_angle)
{
// Find values of vx and vz, which solve the equations:
// dz = -1/2 g t² + vz t
// dx = vx t
// v² = vx² + vz²
// Increases v, if needed for there to be a solution. Decreases v, if needed for vz > 0.
// Randomly changes v by up to 2.5%, so the shots don't all follow the same path.
const int32_t g = ACC_GRAVITY; // In units/s².
int32_t a = randomVariation(v * v) - dz * g; // In units²/s².
uint64_t b = g * g * ((uint64_t)dx * dx + (uint64_t)dz * dz); // In units⁴/s⁴. Casting to uint64_t does sign extend the int32_t.
int64_t c = (uint64_t)a * a - b; // In units⁴/s⁴.
if (c < 0)
{
// Must increase velocity, target too high. Find the smallest possible a (which corresponds to the smallest possible velocity).
a = i64Sqrt(b) + 1; // Still in units²/s². Adding +1, since i64Sqrt rounds down.
c = (uint64_t)a * a - b; // Still in units⁴/s⁴. Should be 0, plus possible rounding errors.
}
int32_t t = MAX(1, iSqrt(2 * (a - i64Sqrt(c))) * (GAME_TICKS_PER_SEC / g)); // In ticks. Note that a - √c ≥ 0, since c ≤ a². Try changing the - to +, and watch the mini-rockets.
*vx = dx * GAME_TICKS_PER_SEC / t; // In units/sec.
*vz = dz * GAME_TICKS_PER_SEC / t + g * t / (2 * GAME_TICKS_PER_SEC); // In units/sec.
STATIC_ASSERT(GAME_TICKS_PER_SEC / ACC_GRAVITY * ACC_GRAVITY == GAME_TICKS_PER_SEC); // On line that calculates t, must cast iSqrt to uint64_t, and remove brackets around TICKS_PER_SEC/g, if changing ACC_GRAVITY.
if (*vz < 0)
{
// Don't want to shoot downwards, reduce velocity and let gravity take over.
t = MAX(1, i64Sqrt(-2 * dz * (uint64_t)GAME_TICKS_PER_SEC * GAME_TICKS_PER_SEC / g)); // Still in ticks.
*vx = dx * GAME_TICKS_PER_SEC / t; // Still in units/sec.
*vz = 0; // Still in units/sec. (Wouldn't really matter if it was pigeons/inch, since it's 0 anyway.)
}
/* CorvusCorax: Check against min_angle */
if (iAtan2(*vz, *vx) < min_angle)
{
/* set pitch to pass terrain */
// tan(min_angle)=mytan/65536
int64_t mytan = ((int64_t)iSin(min_angle) * 65536) / iCos(min_angle);
t = MAX(1, i64Sqrt(2 * ((int64_t)dx * mytan - dz * 65536) * (int64_t)GAME_TICKS_PER_SEC * GAME_TICKS_PER_SEC / (int64_t)(g * 65536))); // Still in ticks.
*vx = dx * GAME_TICKS_PER_SEC / t;
// mytan=65536*vz/vx
*vz = (mytan * (*vx)) / 65536;
}
return t;
}
bool proj_SendProjectile(WEAPON *psWeap, SIMPLE_OBJECT *psAttacker, int player, Vector3i target, BASE_OBJECT *psTarget, bool bVisible, int weapon_slot)
{
return proj_SendProjectileAngled(psWeap, psAttacker, player, target, psTarget, bVisible, weapon_slot, 0, gameTime - 1);
}
bool proj_SendProjectileAngled(WEAPON *psWeap, SIMPLE_OBJECT *psAttacker, int player, Vector3i target, BASE_OBJECT *psTarget, bool bVisible, int weapon_slot, int min_angle, unsigned fireTime)
{
WEAPON_STATS *psStats = &asWeaponStats[psWeap->nStat];
ASSERT_OR_RETURN(false, psWeap->nStat < numWeaponStats, "Invalid range referenced for numWeaponStats, %d > %d", psWeap->nStat, numWeaponStats);
ASSERT_OR_RETURN(false, psStats != nullptr, "Invalid weapon stats");
ASSERT_OR_RETURN(false, psTarget == nullptr || !psTarget->died, "Aiming at dead target!");
PROJECTILE *psProj = new PROJECTILE(ProjectileTrackerID | (realTime >> 4), player);
/* get muzzle offset */
if (psAttacker == nullptr)
{
// if there isn't an attacker just start at the target position
// NB this is for the script function to fire the las sats
psProj->src = target;
}
else if (psAttacker->type == OBJ_DROID && weapon_slot >= 0)
{
calcDroidMuzzleLocation((DROID *)psAttacker, &psProj->src, weapon_slot);
/*update attack runs for VTOL droid's each time a shot is fired*/
updateVtolAttackRun((DROID *)psAttacker, weapon_slot);
}
else if (psAttacker->type == OBJ_STRUCTURE && weapon_slot >= 0)
{
calcStructureMuzzleLocation((STRUCTURE *)psAttacker, &psProj->src, weapon_slot);
}
else // incase anything wants a projectile
{
psProj->src = psAttacker->pos;
}
/* Initialise the structure */
psProj->psWStats = psStats;
psProj->pos = psProj->src;
psProj->dst = target;
psProj->bVisible = false;
// Must set ->psDest and ->expectedDamageCaused before first call to setProjectileDestination().
psProj->psDest = nullptr;
psProj->expectedDamageCaused = objGuessFutureDamage(psStats, player, psTarget);
setProjectileDestination(psProj, psTarget); // Updates expected damage of psProj->psDest, using psProj->expectedDamageCaused.
/*
When we have been created by penetration (spawned from another projectile),
we shall live no longer than the original projectile may have lived
*/
if (psAttacker && psAttacker->type == OBJ_PROJECTILE)
{
PROJECTILE *psOldProjectile = (PROJECTILE *)psAttacker;
psProj->born = psOldProjectile->born;
psProj->src = psOldProjectile->src;
psProj->prevSpacetime.time = psOldProjectile->time; // Have partially ticked already.
psProj->time = gameTime;
psProj->prevSpacetime.time -= psProj->prevSpacetime.time == psProj->time; // Times should not be equal, for interpolation.
setProjectileSource(psProj, psOldProjectile->psSource);
psProj->psDamaged = psOldProjectile->psDamaged;
// TODO Should finish the tick, when penetrating.
}
else
{
psProj->born = fireTime; // Born at the start of the tick.
psProj->prevSpacetime.time = fireTime;
psProj->time = psProj->prevSpacetime.time;
setProjectileSource(psProj, psAttacker);
}
if (psTarget)
{
int maxHeight = establishTargetHeight(psTarget);
int minHeight = std::min(std::max(maxHeight + 2 * LINE_OF_FIRE_MINIMUM - areaOfFire(psAttacker, psTarget, weapon_slot, true), 0), maxHeight);
scoreUpdateVar(WD_SHOTS_ON_TARGET);
psProj->dst.z = psTarget->pos.z + minHeight + gameRand(std::max(maxHeight - minHeight, 1));
/* store visible part (LOCK ON this part for homing :) */
psProj->partVisible = maxHeight - minHeight;
}
else
{
psProj->dst.z = target.z + LINE_OF_FIRE_MINIMUM;
scoreUpdateVar(WD_SHOTS_OFF_TARGET);
}
Vector3i deltaPos = psProj->dst - psProj->src;
/* roll never set */
psProj->rot.roll = 0;
psProj->rot.direction = iAtan2(deltaPos.xy());
// Get target distance, horizontal distance only.
uint32_t dist = iHypot(deltaPos.xy());
if (proj_Direct(psStats))
{
psProj->rot.pitch = iAtan2(deltaPos.z, dist);
}
else
{
/* indirect */
projCalcIndirectVelocities(dist, deltaPos.z, psStats->flightSpeed, &psProj->vXY, &psProj->vZ, min_angle);
psProj->rot.pitch = iAtan2(psProj->vZ, psProj->vXY);
}
psProj->state = PROJ_INFLIGHT;
// If droid or structure, set muzzle pitch.
if (psAttacker != nullptr && weapon_slot >= 0)
{
if (psAttacker->type == OBJ_DROID)
{
((DROID *)psAttacker)->asWeaps[weapon_slot].rot.pitch = psProj->rot.pitch;
}
else if (psAttacker->type == OBJ_STRUCTURE)
{
((STRUCTURE *)psAttacker)->asWeaps[weapon_slot].rot.pitch = psProj->rot.pitch;
}
}
/* put the projectile object in the global list */
psProjectileList.push_back(psProj);
/* play firing audio */
// only play if either object is visible, i know it's a bit of a hack, but it avoids the problem
// of having to calculate real visibility values for each projectile.
if (bVisible || gfxVisible(psProj))
{
// note that the projectile is visible
psProj->bVisible = true;
if (psStats->iAudioFireID != NO_SOUND)
{
if (psProj->psSource)
{
/* firing sound emitted from source */
audio_PlayObjDynamicTrack(psProj->psSource, psStats->iAudioFireID, nullptr);
/* GJ HACK: move howitzer sound with shell */
if (psStats->weaponSubClass == WSC_HOWITZERS)
{
audio_PlayObjDynamicTrack(psProj, ID_SOUND_HOWITZ_FLIGHT, nullptr);
}
}
//don't play the sound for a LasSat in multiPlayer
else if (!(bMultiPlayer && psStats->weaponSubClass == WSC_LAS_SAT))
{
audio_PlayObjStaticTrack(psProj, psStats->iAudioFireID);
}
}
}
if (psAttacker != nullptr && !proj_Direct(psStats))
{
//check for Counter Battery Sensor in range of target
counterBatteryFire(castBaseObject(psAttacker), psTarget);
}
syncDebugProjectile(psProj, '*');
CHECK_PROJECTILE(psProj);
return true;
}
/***************************************************************************/
static INTERVAL intervalIntersection(INTERVAL i1, INTERVAL i2)
{
INTERVAL ret = {MAX(i1.begin, i2.begin), MIN(i1.end, i2.end)};
return ret;
}
static bool intervalEmpty(INTERVAL i)
{
return i.begin >= i.end;
}
static INTERVAL collisionZ(int32_t z1, int32_t z2, int32_t height)
{
INTERVAL ret = { -1, -1};
if (z1 > z2)
{
z1 *= -1;
z2 *= -1;
}
if (z1 > height || z2 < -height)
{
return ret; // No collision between time 1 and time 2.
}
if (z1 == z2)
{
if (z1 >= -height && z1 <= height)
{
ret.begin = 0;
ret.end = 1024;
}
return ret;
}
ret.begin = 1024 * (-height - z1) / (z2 - z1);
ret.end = 1024 * (height - z1) / (z2 - z1);
return ret;
}
static INTERVAL collisionXY(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t radius)
{
// Solve (1 - t)v1 + t v2 = r.
int32_t dx = x2 - x1, dy = y2 - y1;
int64_t a = (int64_t)dx * dx + (int64_t)dy * dy; // a = (v2 - v1)²
int64_t b = (int64_t)x1 * dx + (int64_t)y1 * dy; // b = v1(v2 - v1)
int64_t c = (int64_t)x1 * x1 + (int64_t)y1 * y1 - (int64_t)radius * radius; // c = v1² - r²
// Equation to solve is now a t^2 + 2 b t + c = 0.
int64_t d = b * b - a * c; // d = b² - a c
// Solution is (-b ± √d)/a.
INTERVAL empty = { -1, -1};
INTERVAL full = {0, 1024};
INTERVAL ret;
if (d < 0)
{
return empty; // Missed.
}
if (a == 0)
{
return c < 0 ? full : empty; // Not moving. See if inside the target.
}
int32_t sd = i64Sqrt(d);
ret.begin = MAX(0, 1024 * (-b - sd) / a);
ret.end = MIN(1024, 1024 * (-b + sd) / a);
return ret;
}
static int32_t collisionXYZ(Vector3i v1, Vector3i v2, ObjectShape shape, int32_t height)
{
INTERVAL i = collisionZ(v1.z, v2.z, height);
if (!intervalEmpty(i)) // Don't bother checking x and y unless z passes.
{
if (shape.isRectangular)
{
i = intervalIntersection(i, collisionZ(v1.x, v2.x, shape.size.x));
if (!intervalEmpty(i)) // Don't bother checking y unless x and z pass.
{
i = intervalIntersection(i, collisionZ(v1.y, v2.y, shape.size.y));
}
}
else // Else is circular.
{
i = intervalIntersection(i, collisionXY(v1.x, v1.y, v2.x, v2.y, shape.radius()));
}
if (!intervalEmpty(i))
{
return MAX(0, i.begin);
}
}
return -1;
}
static void proj_InFlightFunc(PROJECTILE *psProj)
{
/* we want a delay between Las-Sats firing and actually hitting in multiPlayer
magic number but that's how long the audio countdown message lasts! */
const unsigned int LAS_SAT_DELAY = 4;
BASE_OBJECT *closestCollisionObject = nullptr;
Spacetime closestCollisionSpacetime;
CHECK_PROJECTILE(psProj);
int timeSoFar = gameTime - psProj->born;
psProj->time = gameTime;
int deltaProjectileTime = psProj->time - psProj->prevSpacetime.time;
WEAPON_STATS *psStats = psProj->psWStats;
ASSERT_OR_RETURN(, psStats != nullptr, "Invalid weapon stats pointer");
/* we want a delay between Las-Sats firing and actually hitting in multiPlayer
magic number but that's how long the audio countdown message lasts! */
if (bMultiPlayer && psStats->weaponSubClass == WSC_LAS_SAT &&
(unsigned)timeSoFar < LAS_SAT_DELAY * GAME_TICKS_PER_SEC)
{
return;
}
/* Calculate movement vector: */
int32_t currentDistance = 0;
switch (psStats->movementModel)
{
case MM_DIRECT: // Go in a straight line.
{
Vector3i delta = psProj->dst - psProj->src;
if (psStats->weaponSubClass == WSC_LAS_SAT)
{
// LASSAT doesn't have a z
delta.z = 0;
}
int targetDistance = std::max(iHypot(delta.xy()), 1);
currentDistance = timeSoFar * psStats->flightSpeed / GAME_TICKS_PER_SEC;
psProj->pos = psProj->src + delta * currentDistance / targetDistance;
break;
}
case MM_INDIRECT: // Ballistic trajectory.
{
Vector3i delta = psProj->dst - psProj->src;
delta.z = (psProj->vZ - (timeSoFar * ACC_GRAVITY / (GAME_TICKS_PER_SEC * 2))) * timeSoFar / GAME_TICKS_PER_SEC; // '2' because we reach our highest point in the mid of flight, when "vZ is 0".
int targetDistance = std::max(iHypot(delta.xy()), 1);
currentDistance = timeSoFar * psProj->vXY / GAME_TICKS_PER_SEC;
psProj->pos = psProj->src + delta * currentDistance / targetDistance;
psProj->pos.z = psProj->src.z + delta.z; // Use raw z value.
psProj->rot.pitch = iAtan2(psProj->vZ - (timeSoFar * ACC_GRAVITY / GAME_TICKS_PER_SEC), psProj->vXY);
break;
}
case MM_HOMINGDIRECT: // Fly towards target, even if target moves.
case MM_HOMINGINDIRECT: // Fly towards target, even if target moves. Avoid terrain.
{
if (psProj->psDest != nullptr)
{
if (psStats->movementModel == MM_HOMINGDIRECT)
{
// If it's homing and has a target (not a miss)...
// Home at the centre of the part that was visible when firing.
psProj->dst = psProj->psDest->pos + Vector3i(0, 0, establishTargetHeight(psProj->psDest) - psProj->partVisible / 2);
}
else
{
psProj->dst = psProj->psDest->pos + Vector3i(0, 0, establishTargetHeight(psProj->psDest) / 2);
}
DROID *targetDroid = castDroid(psProj->psDest);
if (targetDroid != nullptr)
{
// Do target prediction.
Vector3i delta = psProj->dst - psProj->pos;
int flightTime = iHypot(delta.xy()) * GAME_TICKS_PER_SEC / psStats->flightSpeed;
psProj->dst += Vector3i(iSinCosR(targetDroid->sMove.moveDir, std::min<int>(targetDroid->sMove.speed, psStats->flightSpeed * 3 / 4) * flightTime / GAME_TICKS_PER_SEC), 0);
}
psProj->dst.x = clip(psProj->dst.x, 0, world_coord(mapWidth) - 1);
psProj->dst.y = clip(psProj->dst.y, 0, world_coord(mapHeight) - 1);
}
if (psStats->movementModel == MM_HOMINGINDIRECT)
{
if (psProj->psDest == nullptr)
{
psProj->dst.z = map_Height(psProj->pos.xy()) - 1; // Target missing, so just home in on the ground under where the target was.
}
int horizontalTargetDistance = iHypot((psProj->dst - psProj->pos).xy());
int terrainHeight = std::max(map_Height(psProj->pos.xy()), map_Height(psProj->pos.xy() + iSinCosR(iAtan2((psProj->dst - psProj->pos).xy()), psStats->flightSpeed * 2 * deltaProjectileTime / GAME_TICKS_PER_SEC)));
int desiredMinHeight = terrainHeight + std::min(horizontalTargetDistance / 4, HOMINGINDIRECT_HEIGHT_MIN);
int desiredMaxHeight = std::max(psProj->dst.z, terrainHeight + HOMINGINDIRECT_HEIGHT_MAX);
int heightError = psProj->pos.z - clip(psProj->pos.z, desiredMinHeight, desiredMaxHeight);
psProj->dst.z -= horizontalTargetDistance * heightError * 2 / HOMINGINDIRECT_HEIGHT_MIN;
}
Vector3i delta = psProj->dst - psProj->pos;
int targetDistance = std::max(iHypot(delta), 1);
if (psProj->psDest == nullptr && targetDistance < 10000 && psStats->movementModel == MM_HOMINGDIRECT)
{
psProj->dst = psProj->pos + delta * 10; // Target missing, so just keep going in a straight line.
}
currentDistance = timeSoFar * psStats->flightSpeed / GAME_TICKS_PER_SEC;
Vector3i step = quantiseFraction(delta * int32_t(psStats->flightSpeed), GAME_TICKS_PER_SEC * targetDistance, psProj->time, psProj->prevSpacetime.time);
if (psStats->movementModel == MM_HOMINGINDIRECT && psProj->psDest != nullptr)
{
for (int tries = 0; tries < 10 && map_LineIntersect(psProj->prevSpacetime.pos, psProj->pos + step, iHypot(step)) < targetDistance - 1u; ++tries)
{
psProj->dst.z += iHypot((psProj->dst - psProj->pos).xy()); // Would collide with terrain this tick, change trajectory.
// Recalculate delta, targetDistance and step.
delta = psProj->dst - psProj->pos;
targetDistance = std::max(iHypot(delta), 1);
step = quantiseFraction(delta * int32_t(psStats->flightSpeed), GAME_TICKS_PER_SEC * targetDistance, psProj->time, psProj->prevSpacetime.time);
}
}
psProj->pos += step;
psProj->rot.direction = iAtan2(delta.xy());
psProj->rot.pitch = iAtan2(delta.z, targetDistance);
break;
}
}
closestCollisionSpacetime.time = 0xFFFFFFFF;
/* Check nearby objects for possible collisions */
static GridList gridList; // static to avoid allocations.
gridList = gridStartIterate(psProj->pos.x, psProj->pos.y, PROJ_NEIGHBOUR_RANGE);
for (GridIterator gi = gridList.begin(); gi != gridList.end(); ++gi)
{
BASE_OBJECT *psTempObj = *gi;
CHECK_OBJECT(psTempObj);
if (std::find(psProj->psDamaged.begin(), psProj->psDamaged.end(), psTempObj) != psProj->psDamaged.end())
{
// Dont damage one target twice
continue;
}
else if (psTempObj->died)
{
// Do not damage dead objects further
ASSERT(psTempObj->type < OBJ_NUM_TYPES, "Bad pointer! type=%u", psTempObj->type);
continue;
}
else if (psTempObj->type == OBJ_FEATURE && !((FEATURE *)psTempObj)->psStats->damageable)
{
// Ignore oil resources, artifacts and other pickups
continue;
}
else if (aiCheckAlliances(psTempObj->player, psProj->player) && psTempObj != psProj->psDest)
{
// No friendly fire unless intentional
continue;
}
else if (!(psStats->surfaceToAir & SHOOT_ON_GROUND) &&
(psTempObj->type == OBJ_STRUCTURE ||
psTempObj->type == OBJ_FEATURE ||
(psTempObj->type == OBJ_DROID && !isFlying((DROID *)psTempObj))
))
{
// AA weapons should not hit buildings and non-vtol droids
continue;
}
Vector3i psTempObjPrevPos = isDroid(psTempObj) ? castDroid(psTempObj)->prevSpacetime.pos : psTempObj->pos;
const Vector3i diff = psProj->pos - psTempObj->pos;
const Vector3i prevDiff = psProj->prevSpacetime.pos - psTempObjPrevPos;
const unsigned int targetHeight = establishTargetHeight(psTempObj);
const ObjectShape targetShape = establishTargetShape(psTempObj);
const int32_t collision = collisionXYZ(prevDiff, diff, targetShape, targetHeight);
const uint32_t collisionTime = psProj->prevSpacetime.time + (psProj->time - psProj->prevSpacetime.time) * collision / 1024;
if (collision >= 0 && collisionTime < closestCollisionSpacetime.time)
{
// We hit!
closestCollisionSpacetime = interpolateObjectSpacetime(psProj, collisionTime);
closestCollisionObject = psTempObj;
// Keep testing for more collisions, in case there was a closer target.
}
}
unsigned terrainIntersectTime = map_LineIntersect(psProj->prevSpacetime.pos, psProj->pos, psProj->time - psProj->prevSpacetime.time);
if (terrainIntersectTime != UINT32_MAX)
{
const uint32_t collisionTime = psProj->prevSpacetime.time + terrainIntersectTime;
if (collisionTime < closestCollisionSpacetime.time)
{
// We hit the terrain!
closestCollisionSpacetime = interpolateObjectSpacetime(psProj, collisionTime);
closestCollisionObject = nullptr;
}
}
if (closestCollisionSpacetime.time != 0xFFFFFFFF)
{
// We hit!
setSpacetime(psProj, closestCollisionSpacetime);
psProj->time = std::max(psProj->time, gameTime - deltaGameTime + 1); // Make sure .died gets set in the interval [gameTime - deltaGameTime + 1; gameTime].
if (psProj->time == psProj->prevSpacetime.time)
{
--psProj->prevSpacetime.time;
}
setProjectileDestination(psProj, closestCollisionObject); // We hit something.
// Buildings and terrain cannot be penetrated and we need a penetrating weapon.
if (closestCollisionObject != nullptr && closestCollisionObject->type == OBJ_DROID && psStats->penetrate)
{
WEAPON asWeap;
asWeap.nStat = psStats - asWeaponStats;
// Assume we damaged the chosen target
psProj->psDamaged.push_back(closestCollisionObject);
proj_SendProjectile(&asWeap, psProj, psProj->player, psProj->dst, nullptr, true, -1);
}
psProj->state = PROJ_IMPACT;
return;
}
if (currentDistance * 100u >= proj_GetLongRange(psStats, psProj->player) * psStats->distanceExtensionFactor)
{
// We've travelled our maximum range.
psProj->state = PROJ_IMPACT;
setProjectileDestination(psProj, nullptr); /* miss registered if NULL target */
return;
}
/* Paint effects if visible */
if (gfxVisible(psProj))
{
uint32_t effectTime;
for (effectTime = ((psProj->prevSpacetime.time + 31) & ~31); effectTime < psProj->time; effectTime += 32)
{
Spacetime st = interpolateObjectSpacetime(psProj, effectTime);
Vector3i posFlip = st.pos.xzy();
switch (psStats->weaponSubClass)
{
case WSC_FLAME:
posFlip.z -= 8; // Why?
effectGiveAuxVar(PERCENT(currentDistance, proj_GetLongRange(psStats, psProj->player)));
addEffect(&posFlip, EFFECT_EXPLOSION, EXPLOSION_TYPE_FLAMETHROWER, false, nullptr, 0, effectTime);
break;
case WSC_COMMAND:
case WSC_ELECTRONIC:
case WSC_EMP:
posFlip.z -= 8; // Why?
effectGiveAuxVar(PERCENT(currentDistance, proj_GetLongRange(psStats, psProj->player)) / 2);
addEffect(&posFlip, EFFECT_EXPLOSION, EXPLOSION_TYPE_LASER, false, nullptr, 0, effectTime);
break;
case WSC_ROCKET:
case WSC_MISSILE:
case WSC_SLOWROCKET:
case WSC_SLOWMISSILE:
posFlip.z += 8; // Why?
addEffect(&posFlip, EFFECT_SMOKE, SMOKE_TYPE_TRAIL, false, nullptr, 0, effectTime);
break;
default:
// Add smoke trail to indirect weapons, even if firing directly.
if (!proj_Direct(psStats))
{
posFlip.z += 4; // Why?
addEffect(&posFlip, EFFECT_SMOKE, SMOKE_TYPE_TRAIL, false, nullptr, 0, effectTime);
}
// Otherwise no effect.
break;
}
}
}
}
/***************************************************************************/
static void proj_ImpactFunc(PROJECTILE *psObj)
{
WEAPON_STATS *psStats;
SDWORD iAudioImpactID;
int32_t relativeDamage;
Vector3i position, scatter;
iIMDShape *imd;
BASE_OBJECT *temp;
ASSERT_OR_RETURN(, psObj != nullptr, "Invalid pointer");
CHECK_PROJECTILE(psObj);
psStats = psObj->psWStats;
ASSERT_OR_RETURN(, psStats != nullptr, "Invalid weapon stats pointer");
// note the attacker if any
g_pProjLastAttacker = psObj->psSource;
/* play impact audio */
if (gfxVisible(psObj))
{
if (psStats->iAudioImpactID == NO_SOUND)
{
/* play richochet if MG */
if (psObj->psDest != nullptr && psStats->weaponSubClass == WSC_MGUN
&& ONEINTHREE)
{
iAudioImpactID = ID_SOUND_RICOCHET_1 + (rand() % 3);
audio_PlayStaticTrack(psObj->psDest->pos.x, psObj->psDest->pos.y, iAudioImpactID);
}
}
else
{
audio_PlayStaticTrack(psObj->pos.x, psObj->pos.y, psStats->iAudioImpactID);
}
/* Shouldn't need to do this check but the stats aren't all at a value yet... */ // FIXME
if (psStats->upgrade[psObj->player].periodicalDamageRadius != 0 && psStats->upgrade[psObj->player].periodicalDamageTime != 0)
{
position.x = psObj->pos.x;
position.z = psObj->pos.y; // z = y [sic] intentional
position.y = map_Height(position.x, position.z);
effectGiveAuxVar(psStats->upgrade[psObj->player].periodicalDamageRadius);
effectGiveAuxVarSec(psStats->upgrade[psObj->player].periodicalDamageTime);
addEffect(&position, EFFECT_FIRE, FIRE_TYPE_LOCALISED, false, nullptr, 0, psObj->time);
}
// may want to add both a fire effect and the las sat effect
if (psStats->weaponSubClass == WSC_LAS_SAT)
{
position.x = psObj->pos.x;
position.z = psObj->pos.y; // z = y [sic] intentional
position.y = map_Height(position.x, position.z);
addEffect(&position, EFFECT_SAT_LASER, SAT_LASER_STANDARD, false, nullptr, 0, psObj->time);