-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathDefaultProjectileWeapon.lua
More file actions
1358 lines (1163 loc) · 52.4 KB
/
DefaultProjectileWeapon.lua
File metadata and controls
1358 lines (1163 loc) · 52.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local Weapon = import("/lua/sim/weapon.lua").Weapon
-- upvalue globals for performance
local GetSurfaceHeight = GetSurfaceHeight
local VDist2 = VDist2
local EntityMethods = moho.entity_methods
local EntityGetPosition = EntityMethods.GetPosition
local EntityGetPositionXYZ = EntityMethods.GetPositionXYZ
local UnitMethods = moho.unit_methods
local UnitGetVelocity = UnitMethods.GetVelocity
local UnitGetTargetEntity = UnitMethods.GetTargetEntity
local MathClamp = math.clamp
local MathSqrt = math.sqrt
---@class WeaponSalvoData
---@field target? Unit | Prop if absent, will use `targetPos` instead
---@field targetPos Vector stores the last location upon which we dropped bombs for a target, or the ground fire location
-- Most weapons derive from this class, including beam weapons later in this file
---@class DefaultProjectileWeapon : Weapon
---@field RecoilManipulators? TrashBag
---@field CurrentSalvoNumber number
---@field CurrentRackSalvoNumber number
---@field CurrentSalvoData? WeaponSalvoData
---@field AdjustedSalvoDelay? number if the weapon blueprint requests a trajectory fix, this is set to the effective duration of the salvo in ticks used to calculate projectile spread
---@field DropBombShortRatio? number if the weapon blueprint requests a trajectory fix, this is set to the ratio of the distance to the target that the projectile is launched short to
---@field SalvoSpreadStart? number if the weapon blueprint requests a trajectory fix, this is set to the value that centers the projectile spread for `CurrentSalvoNumber` shot on the optimal target position
---@field WeaponPackState 'Packed' | 'Unpacked' | 'Unpacking' | 'Packing'
---@field EconDrain? moho.EconomyEvent
---@field AdjEnergyMod number? # Energy drain multiplier from buffs
---@field AdjRoFMod number? # Firerate multiplier from buffs
DefaultProjectileWeapon = ClassWeapon(Weapon) {
FxRackChargeMuzzleFlash = {},
FxRackChargeMuzzleFlashScale = 1,
FxChargeMuzzleFlash = {},
FxChargeMuzzleFlashScale = 1,
FxMuzzleFlash = {
'/effects/emitters/default_muzzle_flash_01_emit.bp',
'/effects/emitters/default_muzzle_flash_02_emit.bp',
},
FxMuzzleFlashScale = 1,
WeaponPackState = 'Packed',
-- Called when the weapon is created, almost always when the owning unit is created
---@param self DefaultProjectileWeapon
---@return boolean
OnCreate = function(self)
Weapon.OnCreate(self)
local bp = self.Blueprint
local rackBones = bp.RackBones
local rackRecoilDist = bp.RackRecoilDistance
local muzzleSalvoDelay = bp.MuzzleSalvoDelay
local muzzleSalvoSize = bp.MuzzleSalvoSize
self.WeaponCanFire = true
-- Make certain the weapon has essential aspects defined
if not rackBones then
local strg = '*ERROR: No RackBones table specified, aborting weapon setup. Weapon: ' ..
(bp.Label or bp.DisplayName or 'Unlabelled') .. ' on Unit: ' .. self.unit:GetUnitId()
error(strg, 2)
return
end
if not muzzleSalvoSize then
local strg = '*ERROR: No MuzzleSalvoSize specified, aborting weapon setup. Weapon: ' ..
(bp.Label or bp.DisplayName or 'Unlabelled') .. ' on Unit: ' .. self.unit:GetUnitId()
error(strg, 2)
return
end
if not muzzleSalvoDelay then
local strg = '*ERROR: No MuzzleSalvoDelay specified, aborting weapon setup. Weapon: ' ..
(bp.Label or bp.DisplayName or 'Unlabelled') .. ' on Unit: ' .. self.unit:GetUnitId()
error(strg, 2)
return
end
self.CurrentRackSalvoNumber = 1
local rof = self:GetWeaponRoF()
-- Calculate recoil speed so that it finishes returning just as the next shot is ready
if rackRecoilDist ~= 0 then
self.RecoilManipulators = TrashBag()
self.Trash:Add(self.RecoilManipulators)
local dist = rackRecoilDist
local telescopeRecoilDist = rackBones[1].TelescopeRecoilDistance
if telescopeRecoilDist and math.abs(telescopeRecoilDist) > math.abs(dist) then
dist = telescopeRecoilDist
end
self.RackRecoilReturnSpeed = bp.RackRecoilReturnSpeed or
math.abs(dist / ((1 / rof) - (bp.MuzzleChargeDelay or 0))) * 1.25
end
if rackRecoilDist ~= 0 and muzzleSalvoDelay ~= 0 then
local strg = '*ERROR: You can not have a RackRecoilDistance with a MuzzleSalvoDelay not equal to 0, aborting weapon setup. Weapon: '
.. bp.DisplayName .. ' on Unit: ' .. self.unit:GetUnitId()
error(strg, 2)
return false
end
-- Ensure firing cycle is compatible internally
local numRackBones = table.getn(rackBones)
local numMuzzles = 0
for _, rack in rackBones do
local muzzleBones = rack.MuzzleBones
numMuzzles = numMuzzles + table.getn(muzzleBones)
end
self.NumMuzzles = numMuzzles / numRackBones
self.NumRackBones = numRackBones
local totalMuzzleFiringTime = (self.NumMuzzles - 1) * muzzleSalvoDelay
if totalMuzzleFiringTime > (1 / rof) then
local strg = '*ERROR: The total time to fire muzzles is longer than the RateOfFire allows, aborting weapon setup. Weapon: '
.. bp.DisplayName .. ' on Unit: ' .. self.unit:GetUnitId()
error(strg, 2)
return false
end
if bp.EnergyChargeForFirstShot == false then
self.FirstShot = true
end
-- Set the firing cycle progress bar to full if required
if bp.RenderFireClock then
self.unit:SetWorkProgress(1)
end
if bp.FixBombTrajectory then
local dropShort = bp.DropBombShort
if dropShort then
self.DropBombShortRatio = MathClamp(1 - dropShort, 0, 1)
end
if muzzleSalvoSize > 1 then
-- center the spread on the target
self.SalvoSpreadStart = -0.5 - 0.5 * muzzleSalvoSize
-- adjusted time between bombs, this is multiplied by 0.5 to get the bombs overlapping a bit
-- (also pre-convert velocity from per-ticks to per-seconds by multiplying by 10)
self.AdjustedSalvoDelay = 5 * bp.MuzzleSalvoDelay
end
end
ChangeState(self, self.IdleState)
end,
-- This function creates the projectile, and happens when the unit is trying to fire
-- Called from inside RackSalvoFiringState
---@param self DefaultProjectileWeapon
---@param muzzle Bone
---@return Projectile
CreateProjectileAtMuzzle = function(self, muzzle)
local proj = self:CreateProjectileForWeapon(muzzle)
if not proj or proj:BeenDestroyed() then
return proj
end
local bp = self.Blueprint
if bp.DetonatesAtTargetHeight == true then
local pos = self:GetCurrentTargetPos()
if pos then
local theight = GetSurfaceHeight(pos[1], pos[3])
local hght = pos[2] - theight
proj:ChangeDetonateAboveHeight(hght)
end
end
if bp.Flare then
proj:AddFlare(bp.Flare)
end
if self.unit.Layer == 'Water' and bp.Audio.FireUnderWater then
self:PlaySound(bp.Audio.FireUnderWater)
elseif bp.Audio.Fire then
self:PlaySound(bp.Audio.Fire)
end
if bp.FixBombTrajectory then
self:CheckBallisticAcceleration(proj)
end
return proj
end;
-- Used mainly for Bomb drop physics calculations
---@param self DefaultProjectileWeapon
---@param proj Projectile
CheckBallisticAcceleration = function(self, proj)
-- Change projectile trajectory so it hits the target
proj:SetBallisticAcceleration(-self:CalculateBallisticAcceleration(proj))
end,
--- Returns the positive downwards acceleration needed for a projectile to hit its target when travelling at the same speed as the unit launching it (for bombs)
---@param self DefaultProjectileWeapon
---@param projectile Projectile
---@return number
CalculateBallisticAcceleration = function(self, projectile)
local launcher = projectile:GetLauncher()
if not launcher then -- fail-fast
return 4.9 -- Return the default gravity value if some calculations fail
end
local UnitGetVelocity = UnitGetVelocity
local VDist2 = VDist2
-- Get projectile position and velocity
-- velocity will need to be multiplied by 10 due to being returned /tick instead of /s
local projPosX, projPosY, projPosZ = EntityGetPositionXYZ(projectile)
local projVelX, projVelY, projVelZ = UnitGetVelocity(launcher)
-- The projectile will have velocity in the horizontal plane equal to the unit's 3 dimensional speed
-- Multiply the XZ components by the ratio of the XYZ to XZ speeds to get the correct XZ components
local projVelXZSquareSum = projVelX * projVelX + projVelZ * projVelZ
local multiplier = MathSqrt((projVelXZSquareSum + projVelY * projVelY) / (projVelXZSquareSum))
projVelX = projVelX * multiplier
projVelZ = projVelZ * multiplier
local targetPos
local targetVelX, targetVelY, targetVelZ = 0, 0, 0
local data = self.CurrentSalvoData
-- if it's the first time...
if not data then
-- setup target (which won't change mid-bombing run)
local target = UnitGetTargetEntity(launcher)
if target then -- target is a unit / prop
targetPos = EntityGetPosition(target)
if not target.IsProp then
targetVelX, targetVelY, targetVelZ = UnitGetVelocity(target)
end
else -- target is a position i.e. attack ground
targetPos = self:GetCurrentTargetPos()
end
-- and there's not going to be a second time
if self.Blueprint.MuzzleSalvoSize <= 1 then
-- do the calculation but skip any cache or salvo logic
if not targetPos then
return 4.9
end
if target and not target.IsProp then
targetVelX, targetVelY, targetVelZ = UnitGetVelocity(target)
end
local targetPosX, targetPosZ = targetPos[1], targetPos[3]
local distVel = VDist2(projVelX, projVelZ, targetVelX, targetVelZ)
if distVel == 0 then
return 4.9
end
local distPos = VDist2(projPosX, projPosZ, targetPosX, targetPosZ)
do
local dropShort = self.DropBombShortRatio
if dropShort then
distPos = distPos * dropShort
end
end
if distPos == 0 then
return 4.9
end
local time = distPos / distVel
projPosY = projPosY - GetSurfaceHeight(targetPosX + time * targetVelX, targetPosZ + time * targetVelZ)
return 200 * projPosY / (time * time)
else -- otherwise, calculate & cache a couple things the first time only
data = {
targetPos = targetPos,
}
if target then
if target.Dead then
data.target = nil
else
data.target = target
end
end
self.CurrentSalvoData = data
end
else -- if it's a successive bomb drop, update the targeting data
local target = data.target
if target then
if target.Dead then -- if the unit is destroyed, use the last known position
data.target = nil
targetPos = data.targetPos
else
if not target.IsProp then
targetVelX, targetVelY, targetVelZ = UnitGetVelocity(target)
end
targetPos = EntityGetPosition(target)
end
else
targetPos = data.targetPos
end
end
if not targetPos then
-- put the bomb cluster in free-fall
local GetSurfaceHeight = GetSurfaceHeight
local spread = self.AdjustedSalvoDelay * (self.SalvoSpreadStart + self.CurrentSalvoNumber)
-- default gravitational acceleration is 4.9; however, bomb clusters adjust the time it takes to land
-- so we convert the acceleration to time to add the spread and convert back:
-- h = unitY - surfaceY => h2 = 0.5 * (unitY - surfaceHeight(unitX, unitZ))
-- t = sqrt(2 h / a) + spread => t = sqrt(4 / 4.9 * h2) + spread
-- a = 0.5 h / t^2 => a = h2 / t^2
local halfHeight = 0.5 * (projPosY - GetSurfaceHeight(projPosX, projPosZ))
if halfHeight < 0.01 then return 4.9 end
local time = MathSqrt(0.816326530612 * halfHeight) + spread
-- now that we know roughly when we'll land, we can find a better guess for where
-- we'll land, and thus guess the true falling height better as well
halfHeight = 0.5 * (projPosY - GetSurfaceHeight(projPosX + time * projVelX, projPosX + time * projVelX))
if halfHeight < 0.01 then return 4.9 end
time = MathSqrt(0.816326530612 * halfHeight) + spread
return halfHeight / (time * time)
end
-- calculate flat (exclude y-axis) distance and velocity between projectile and target
-- velocity will eventually need to multiplied by 10 due to being per tick instead of per second
local distVel = VDist2(projVelX, projVelZ, targetVelX, targetVelZ)
if distVel == 0 then
return 4.9
end
local targetPosX, targetPosZ = targetPos[1], targetPos[3]
-- calculate the distance for this particular bomb
local distPos = VDist2(projPosX, projPosZ, targetPosX, targetPosZ)
do
local dropShort = self.DropBombShortRatio
if dropShort then
distPos = distPos * dropShort
end
end
-- how many ticks until the bomb hits the target in xz-space
local time = distPos / distVel
local adjustedTime = time + self.AdjustedSalvoDelay * (self.SalvoSpreadStart + self.CurrentSalvoNumber)
if adjustedTime == 0 then
return 4.9
end
-- If we have a target, targetPos may have updated now.
-- save the new predicted target position in case we lose the target
-- so that we can drop the bomb salvo centered onto there.
if data.target then
targetPos[1] = targetPos[1] + time * targetVelX
targetPos[3] = targetPos[3] + time * targetVelZ
data.targetPos = targetPos
end
-- find out where the target will be at that point in time (it could be moving)
-- (time and velocity being in ticks cancel out)
-- what is the height difference at that future position
projPosY = projPosY -
GetSurfaceHeight(targetPosX + adjustedTime * targetVelX, targetPosZ + adjustedTime * targetVelZ)
-- The basic formula for displacement over time is h = 0.5 * a * t^2
-- h: displacement, a: acceleration, t: time
-- now we can calculate what acceleration we need to make it hit the target in the y-axis
-- a = 2 * h / t^2
-- also convert time from ticks to seconds (multiply by 10, twice)
return 200 * projPosY / (adjustedTime * adjustedTime)
end,
-- Triggers when the weapon is moved horizontally, usually by owner's motion
---@param self DefaultProjectileWeapon
---@param new HorizontalMovementState
---@param old HorizontalMovementState
OnMotionHorzEventChange = function(self, new, old)
Weapon.OnMotionHorzEventChange(self, new, old)
local blueprint = self.Blueprint
-- Handle weapons which must pack before moving
if blueprint.WeaponUnpackLocksMotion == true and old == 'Stopped' and self.WeaponPackState ~= 'Packed' then
self:PackAndMove()
end
-- Handle motion-triggered FiringRandomness changes
if blueprint.FiringRandomnessWhileMoving then
if old == 'Stopped' then
self:SetFiringRandomness(blueprint.FiringRandomnessWhileMoving)
elseif new == 'Stopped' then
self:SetFiringRandomness(blueprint.FiringRandomness)
end
end
end,
-- Called on horizontal motion event
---@param self DefaultProjectileWeapon
PackAndMove = function(self)
ChangeState(self, self.WeaponPackingState)
end,
-- Create an economy event for those weapons which require Energy to fire
---@param self DefaultProjectileWeapon
StartEconomyDrain = function(self)
if self.FirstShot then return end
if self.unit:GetFractionComplete() ~= 1 then return end
if not self.EconDrain and self.EnergyRequired and self.EnergyDrainPerSecond then
local nrgReq = self:GetWeaponEnergyRequired()
local nrgDrain = self:GetWeaponEnergyDrain()
if nrgReq > 0 and nrgDrain > 0 then
local time = nrgReq / nrgDrain
if time < 0.1 then
time = 0.1
end
self.EconDrain = CreateEconomyEvent(self.unit, nrgReq, 0, time)
self.FirstShot = true
ForkThread(self.EconomyDrainThread, self)
end
end
end,
---@param self DefaultProjectileWeapon
EconomyDrainThread = function(self)
WaitFor(self.EconDrain)
RemoveEconomyEvent(self.unit, self.EconDrain)
self.EconDrain = nil
end,
-- Determine how much Energy is required to fire
---@param self DefaultProjectileWeapon
---@return number
GetWeaponEnergyRequired = function(self)
local weapNRG = (self.EnergyRequired or 0) * (self.AdjEnergyMod or 1)
if weapNRG < 0 then
weapNRG = 0
end
return weapNRG
end,
-- Determine how much Energy should be drained per second
---@param self DefaultProjectileWeapon
---@return number
GetWeaponEnergyDrain = function(self)
local weapNRG = (self.EnergyDrainPerSecond or 0) / (self.AdjRoFMod or 1) * (self.AdjEnergyMod or 1)
return weapNRG
end,
---@param self DefaultProjectileWeapon
---@return number
GetWeaponRoF = function(self)
return self.Blueprint.RateOfFire / (self.AdjRoFMod or 1)
end,
-- Effect Functions Section
-- Play visual effects, animations, recoil etc
-- Played when a muzzle is fired. Mostly used for muzzle flashes
---@param self DefaultProjectileWeapon
---@param muzzle Bone
PlayFxMuzzleSequence = function(self, muzzle)
local unit = self.unit
local army = self.Army
local scale = self.FxMuzzleFlashScale
for _, effect in self.FxMuzzleFlash do
CreateAttachedEmitter(unit, muzzle, army, effect):ScaleEmitter(scale)
end
end,
-- Played during the beginning of the MuzzleChargeDelay time when a muzzle in a rack is fired.
---@param self DefaultProjectileWeapon
---@param muzzle string
PlayFxMuzzleChargeSequence = function(self, muzzle)
local unit = self.unit
local army = self.Army
local scale = self.FxChargeMuzzleFlashScale
for _, effect in self.FxChargeMuzzleFlash do
CreateAttachedEmitter(unit, muzzle, army, effect):ScaleEmitter(scale)
end
end,
-- Played when a rack salvo charges
-- Do not wait in here or the sequence in the blueprint will be messed up. Fork a thread instead
---@param self DefaultProjectileWeapon
PlayFxRackSalvoChargeSequence = function(self)
local bp = self.Blueprint
local muzzleBones = bp.RackBones[self.CurrentRackSalvoNumber].MuzzleBones
local unit = self.unit
local army = self.Army
local scale = self.FxRackChargeMuzzleFlashScale
for _, effect in self.FxRackChargeMuzzleFlash do
for _, muzzle in muzzleBones do
CreateAttachedEmitter(unit, muzzle, army, effect):ScaleEmitter(scale)
end
end
local chargeStart = bp.Audio.ChargeStart
if chargeStart then
self:PlaySound(chargeStart)
end
local animationCharge = bp.AnimationCharge
if animationCharge and self.Animator then
local animator = CreateAnimator(unit)
self.Animator = animator
animator:PlayAnim(animationCharge):SetRate(bp.AnimationChargeRate or 1)
end
end,
-- Played when a rack salvo reloads
-- Do not wait in here or the sequence in the blueprint will be messed up. Fork a thread instead
---@param self DefaultProjectileWeapon
PlayFxRackSalvoReloadSequence = function(self)
local bp = self.Blueprint
local animationReload = bp.AnimationReload
if animationReload and not self.Animator then
local animator = CreateAnimator(self.unit)
self.Animator = animator
animator:PlayAnim(animationReload):SetRate(bp.AnimationReloadRate or 1)
end
end,
-- Played when a rack reloads. Mostly used for Recoil
---@param self DefaultProjectileWeapon
PlayFxRackReloadSequence = function(self)
local bp = self.Blueprint
local cameraShakeRadius = bp.CameraShakeRadius
local cameraShakeMax = bp.CameraShakeMax
local cameraShakeMin = bp.CameraShakeMin
local cameraShakeDuration = bp.CameraShakeDuration
if cameraShakeRadius and cameraShakeRadius > 0 and
cameraShakeMax and cameraShakeMax > 0 and
cameraShakeMin and cameraShakeMin >= 0 and
cameraShakeDuration and cameraShakeDuration > 0
then
self.unit:ShakeCamera(cameraShakeRadius, cameraShakeMax, cameraShakeMin, cameraShakeDuration)
end
if bp.RackRecoilDistance ~= 0 then
self:PlayRackRecoil({ bp.RackBones[self.CurrentRackSalvoNumber] })
end
end,
-- Played when a weapon unpacks
---@param self DefaultProjectileWeapon
PlayFxWeaponUnpackSequence = function(self)
-- Deal with owner's audio cues
local unitBP = self.unit:GetBlueprint()
local unitBPAudio = unitBP.Audio
local activate = unitBPAudio.Activate
if activate then
self:PlaySound(activate)
end
local open = unitBPAudio.Open
if open then
self:PlaySound(open)
end
-- Deal with the Weapon's audio and animations
local bp = self.Blueprint
local unpack = bp.Audio.Unpack
if unpack then
self:PlaySound(unpack)
end
local unpackAnimation = bp.WeaponUnpackAnimation
local unpackAnimator = self.UnpackAnimator
if unpackAnimation and not unpackAnimator then
unpackAnimator = CreateAnimator(self.unit)
self.UnpackAnimator = unpackAnimator
unpackAnimator:PlayAnim(unpackAnimation):SetRate(0)
unpackAnimator:SetPrecedence(bp.WeaponUnpackAnimatorPrecedence or 0)
self.Trash:Add(unpackAnimator)
end
if unpackAnimator then
unpackAnimator:SetRate(bp.WeaponUnpackAnimationRate)
self.WeaponPackState = 'Unpacking'
WaitFor(unpackAnimator)
end
self.WeaponPackState = 'Unpacked'
end,
-- Played when a weapon packs up
-- There is no target, and all rack salvos are complete
---@param self DefaultProjectileWeapon
PlayFxWeaponPackSequence = function(self)
local bp = self.Blueprint
local close = self.unit.Blueprint.Audio.Close
if close then
self:PlaySound(close)
end
local unpackAnimator = self.UnpackAnimator
if unpackAnimator then
if bp.WeaponUnpackAnimation then
unpackAnimator:SetRate(-bp.WeaponUnpackAnimationRate)
end
self.WeaponPackState = 'Packing'
WaitFor(unpackAnimator)
end
self.WeaponPackState = 'Packed'
end,
-- Create the visual side of rack recoil
---@param self DefaultProjectileWeapon
---@param rackList RackBoneBlueprint[]
PlayRackRecoil = function(self, rackList)
local bp = self.Blueprint
local rackRecoilDist = bp.RackRecoilDistance
---@type TrashBag
local recoilManipulatorBag = self.RecoilManipulators
for _, rack in rackList do
local telescopeBone = rack.TelescopeBone
local tmpSldr = CreateSlider(self.unit, rack.RackBone)
tmpSldr:SetPrecedence(11)
tmpSldr:SetGoal(0, 0, rackRecoilDist)
tmpSldr:SetSpeed(-1)
recoilManipulatorBag:Add(tmpSldr)
if telescopeBone then
tmpSldr = CreateSlider(self.unit, telescopeBone)
tmpSldr:SetPrecedence(11)
tmpSldr:SetGoal(0, 0, rack.TelescopeRecoilDistance or rackRecoilDist)
tmpSldr:SetSpeed(-1)
recoilManipulatorBag:Add(tmpSldr)
end
end
self:ForkThread(self.PlayRackRecoilReturn, rackList)
end,
-- The opposite function to PlayRackRecoil, returns the rack to default position
---@param self DefaultProjectileWeapon
---@param rackList RackBoneBlueprint[]
PlayRackRecoilReturn = function(self, rackList)
WaitTicks(1)
local speed = self.RackRecoilReturnSpeed
for _, recManip in self.RecoilManipulators do
recManip:SetGoal(0, 0, 0)
recManip:SetSpeed(speed)
end
end,
-- Wait for all recoil and animations
---@param self DefaultProjectileWeapon
WaitForAndDestroyManips = function(self)
local manips = self.RecoilManipulators
if manips then
for _, manip in manips do
WaitFor(manip)
end
self:DestroyRecoilManips()
end
local animator = self.Animator
if animator then
WaitFor(animator)
animator:Destroy()
self.Animator = nil
end
end,
-- Destroy the sliders which cause weapon visual recoil
---@param self DefaultProjectileWeapon
DestroyRecoilManips = function(self)
if self.RecoilManipulators then
self.RecoilManipulators:Destroy()
end
end,
-- Should be called whenever a target is lost
-- Includes the manual selection of a new target, and the issuing of a move order
---@param self DefaultProjectileWeapon
OnLostTarget = function(self)
-- Issue 43
-- Tell the owner this weapon has lost the target
local unit = self.unit
if unit then
unit:OnLostTarget(self)
end
Weapon.OnLostTarget(self)
if self.Blueprint.WeaponUnpacks then
ChangeState(self, self.WeaponPackingState)
else
ChangeState(self, self.IdleState)
end
end,
-- Sends the weapon to DeadState, probably called by the Owner
---@param self DefaultProjectileWeapon
OnDestroy = function(self)
Weapon.OnDestroy(self)
ChangeState(self, self.DeadState)
end,
-- Checks to see if the weapon is allowed to fire
---@param self DefaultProjectileWeapon
---@return boolean
CanWeaponFire = function(self)
return self.WeaponCanFire
end,
-- Present for Overcharge to hook into
---@param self DefaultProjectileWeapon
OnWeaponFired = function(self)
end,
-- I think this is triggered whenever the state changes to anything but DeadState
---@param self DefaultProjectileWeapon
OnEnterState = function(self)
local weaponWantEnabled = self.WeaponWantEnabled
local weaponIsEnabled = self.WeaponIsEnabled
if weaponWantEnabled and not weaponIsEnabled then
self.WeaponIsEnabled = true
self:SetWeaponEnabled(true)
elseif not weaponWantEnabled and weaponIsEnabled then
local bp = self.Blueprint
if bp.CountedProjectile ~= true then
self.WeaponIsEnabled = false
self:SetWeaponEnabled(false)
end
end
local weaponAimWantEnabled = self.WeaponAimWantEnabled
local weaponAimIsEnabled = self.WeaponAimIsEnabled
if weaponAimWantEnabled and not weaponAimIsEnabled then
self.WeaponAimIsEnabled = true
self:AimManipulatorSetEnabled(true)
elseif not weaponAimWantEnabled and weaponAimIsEnabled then
self.WeaponAimIsEnabled = false
self:AimManipulatorSetEnabled(false)
end
end,
-- Weapon States
-- Idle state is when the weapon has no target and is done with any animations or unpacking
IdleState = State {
StateName = 'IdleState',
WeaponWantEnabled = true,
WeaponAimWantEnabled = true,
Main = function(self)
local unit = self.unit
if unit.Dead then return end
unit:SetBusy(false)
-- at this point salvo is always done so reset the data in case firing was interrupted
self.CurrentSalvoData = nil
self:WaitForAndDestroyManips()
local bp = self.Blueprint
for _, rack in bp.RackBones do
if rack.HideMuzzle then
for _, muzzle in rack.MuzzleBones do
unit:ShowBone(muzzle, true)
end
end
end
self:StartEconomyDrain()
if self.NumRackBones > 1 and self.CurrentRackSalvoNumber > 1 then
WaitSeconds(bp.RackReloadTimeout)
self:PlayFxRackSalvoReloadSequence()
self.CurrentRackSalvoNumber = 1
end
end,
OnGotTarget = function(self)
Weapon.OnGotTarget(self)
local unit = self.unit
if unit then
unit:OnGotTarget(self)
end
local bp = self.Blueprint
if not bp.WeaponUnpackLockMotion or (bp.WeaponUnpackLocksMotion and not self.unit:IsUnitState('Moving')) then
if bp.CountedProjectile and not self:CanFire() then
return
end
if bp.WeaponUnpacks then
ChangeState(self, self.WeaponUnpackingState)
else
if bp.RackSalvoChargeTime and bp.RackSalvoChargeTime > 0 then
-- don't charge and then possibly fire while unaimed
if not bp.RackSalvoFiresAfterCharge then
ChangeState(self, self.RackSalvoChargeState)
end
else
ChangeState(self, self.RackSalvoFireReadyState)
end
end
end
end,
OnFire = function(self)
local bp = self.Blueprint
if bp.WeaponUnpacks and self.WeaponPackState ~= 'Unpacked' then
ChangeState(self, self.WeaponUnpackingState)
else
if bp.RackSalvoChargeTime and bp.RackSalvoChargeTime > 0 then
ChangeState(self, self.RackSalvoChargeState)
-- SkipReadyState used for Janus and Corsair
elseif bp.SkipReadyState then
ChangeState(self, self.RackSalvoFiringState)
else
ChangeState(self, self.RackSalvoFireReadyState)
end
end
end,
},
-- This state is for when the weapon is charging before firing
RackSalvoChargeState = State {
StateName = 'RackSalvoChargeState',
WeaponWantEnabled = true,
WeaponAimWantEnabled = true,
Main = function(self)
local unit = self.unit
local bp = self.Blueprint
local notExclusive = bp.NotExclusive
unit:SetBusy(true)
self:PlayFxRackSalvoChargeSequence()
if notExclusive then
unit:SetBusy(false)
end
WaitSeconds(bp.RackSalvoChargeTime)
if notExclusive then
unit:SetBusy(true)
end
if bp.RackSalvoFiresAfterCharge then
ChangeState(self, self.RackSalvoFiringState)
else
ChangeState(self, self.RackSalvoFireReadyState)
end
end,
OnFire = function(self)
end,
},
-- This state is for when the weapon is ready to fire
RackSalvoFireReadyState = State {
StateName = 'RackSalvoFireReadyState',
WeaponWantEnabled = true,
WeaponAimWantEnabled = true,
Main = function(self)
-- We change the state on counted projectiles because we won't get another OnFire call.
-- The second part is a hack for units with reload animations. They have the same problem
-- they need a RackSalvoReloadTime that's 1/RateOfFire set to avoid firing twice on the first shot
local unit = self.unit
local bp = self.Blueprint
if bp.ManualFire and not bp.OverChargeWeapon then
unit:SetBusy(true)
else
unit:SetBusy(false)
end
self.WeaponCanFire = true
local econDrain = self.EconDrain
if econDrain then
self.WeaponCanFire = false
WaitFor(econDrain)
self.WeaponCanFire = true
end
-- Usually weapons with counted projectiles (TMLs, SMLs, SMDs) have a weapon unpacking / packing animation. As a result,
-- once they reach this state they won't receive another 'OnFire' event from the engine. To help them fire anyway we
-- manually force them proceed at this point
if (bp.CountedProjectile) then
-- But, as we're doing something unnatural we need to take into account the fire state. As an interesting side effect,
-- this bit of logic allows for the 'Sync strike' feature to function
-- prevent firing the weapon through `OnFire`
self.WeaponCanFire = false
while unit:GetFireState() == 1 do
WaitTicks(1)
end
-- now we're good and ready to fire as we see fit
self.WeaponCanFire = true
ChangeState(self, self.RackSalvoFiringState)
end
-- Bombers should not have their targets reset since they take a large path much longer than their reload time.
if not (IsDestroyed(unit) or IsDestroyed(self)) and not bp.NeedToComputeBombDrop then
if bp.TargetResetWhenReady then
-- attempts to fix weapons that intercept projectiles to being stuck on a projectile while reloading, preventing
-- other weapons from targeting that projectile. Is a side effect of the blueprint field `DesiredShooterCap`. For a more
-- aggressive version see the blueprint field `DisableWhileReloading` which completely disables the weapon
WaitTicks(5)
self:ResetTarget()
else
-- attempts to fix weapons being stuck on targets that are outside their current attack radius, but inside
-- the tracking radius. This happens when the weapon acquires a target, but never actually fires and
-- therefore the thread of this state is not destroyed
-- wait reload time + 3 seconds, then force the weapon to recheck its target
WaitSeconds((1 / self.Blueprint.RateOfFire) + 3)
self:ResetTarget()
end
end
end,
OnFire = function(self)
if self.WeaponCanFire then
ChangeState(self, self.RackSalvoFiringState)
end
end,
},
-- This state is for when the weapon is actually in the process of firing
RackSalvoFiringState = State {
StateName = 'RackSalvoFiringState',
WeaponWantEnabled = true,
WeaponAimWantEnabled = true,
-- Render the fire recharge bar
---@param self DefaultProjectileWeapon
---@param rateOfFire number
RenderClockThread = function(self, rateOfFire)
local unit = self.unit
local clockTime = math.round(10 * rateOfFire)
local totalTime = clockTime
while clockTime >= 0
and not self:BeenDestroyed()
and not unit.Dead
do
-- do not override work progress that is used for replenishing silo ammo upon unit transfer
if not unit:IsUnitState("SiloBuildingAmmo") then
unit:SetWorkProgress(1 - clockTime / totalTime)
end
clockTime = clockTime - 1
WaitSeconds(0.1)
end
end,
---@param self DefaultProjectileWeapon
---@param rateOfFire number
DisabledWhileReloadingThread = function(self, rateOfFire)
-- attempts to fix weapons that intercept projectiles to being stuck on a projectile while reloading, preventing
-- other weapons from targeting that projectile. Is a side effect of the blueprint field `DesiredShooterCap`. This
-- is the more aggressive variant of `TargetResetWhenReady` as it completely disables the weapon. Should only be used
-- for weapons that do not visually track, such as torpedo defenses
local reloadTime = math.floor(10 * rateOfFire) - 1
if reloadTime > 4 then
if IsDestroyed(self) then
return
end
self:SetEnabled(false)
WaitTicks(reloadTime)
if IsDestroyed(self) then
return
end
self:SetEnabled(true)
end
end,
Main = function(self)
local unit = self.unit
unit:SetBusy(true)
self:DestroyRecoilManips()
local bp = self.Blueprint
local rof = self:GetWeaponRoF()
local rackBoneCount = self.NumRackBones
local muzzleCharge = bp.Audio.MuzzleChargeStart
local countedProjectile = bp.CountedProjectile
local salvoDelay = bp.MuzzleSalvoDelay or 0
local chargeDelay = bp.MuzzleChargeDelay or 0
local salvoSize = bp.MuzzleSalvoSize
local notExclusive = bp.NotExclusive
local rackBones = bp.RackBones
local numRackFiring = self.CurrentRackSalvoNumber
--This is done to make sure that when racks should fire together, they do
if bp.RackFireTogether then
numRackFiring = rackBoneCount
end
-- Fork timer counter thread carefully
if not self:BeenDestroyed() and
not unit.Dead then