-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTDCSRedFlag.lua
More file actions
2080 lines (1692 loc) · 69 KB
/
TDCSRedFlag.lua
File metadata and controls
2080 lines (1692 loc) · 69 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 version = "{{version}}"
--=========================================
-- BIG NOTE!!!
-- This script only works properly in DCS when it's being run on a Dedicated Server.
-- This is due to a player slot or a client slot that has the same userID (when run from the game itself) the unit commands on the host don't work.
--=========================================
--============================================
-- Config
--============================================
local Config = {
-- Delimiter of callsign. Messages to GCI will show as: "Hacker 1-1" as opposed to "Hacker 1-1 | Dutchie"
CallSignDelimiter = "|",
-- If AI are hit they will be set to:
-- NonEvasive
-- NonAggressive
-- RTB (If last waypoint in route is "Land" it will land there)
-- Done on a unit basis
PlayersOnly = false,
-- Mad Dog behaviour of AA missiles
-- CURRENTLY NOT IMPLEMENTED
MadDog = {
Behaviour = 0 --DEFAULT: 0
},
DeadUnitWeapons = { -- Behaviour of weapons when launched by a dead unit
AAWeaponsBehaviour = 0, --DEFAULT: 0
AGWeaponsBehaviour = 0 --DEFAULT: 0
},
-- Delays are in seconds
Delays = {
MissDelay = 5, -- Message TO the shooter, to the target any hits are always instant
MissileKillDelay = 3, -- Message TO the shooter, to the target any hits are always instant
GunKillDelay = 0, -- Message TO the shooter, to the target any hits are always instant
MissMessageOnScreen = 5, -- Message TO the shooter
DeathMessageOnScreenSeconds = 120
},
Messages = {
--- replaceable variables:
--- {{ callsign }} => replaces with the callsign (delimited first part)
--- If you want to disable a message, simply replace the string with nil
--- example:
--- UnitKilled = nil
PlayerMessages = {
UnitKilled = "{{ callsign }}, You are dead, flow away from the action",
MissileMissed = "{{ callsign }}, PK Miss",
ConfirmKill = "{{ callsign }}, PK Hit",
ConfirmKillGunKill = "{{ callsign }}, good guns, splash one",
CopyShotMessage = "{{ callsign }}, Copy Shot",
ReviveMessage = "{{ callsign }}, you have been reset and are cleared to enter the action"
},
--- Messages that are sent to the server for LotATC, Olympus and other tool users.
ControllerMessages = {
UnitKilled = "{{ callsign }}, dead", -- callsign of the unit that died
MissileMissed = "{{ callsign }} , PK MISS", -- callsign of the unit that missed
ConfirmKill = "{{ callsign }}, PK HIT", -- callsign of the unit whos missile hit
ConfirmKillGunKill = "{{ callsign }}, GUN KILL" -- callsign of the shooter
}
},
-- Amount of registered hits before "death"
KillParameters = {
Bullets = 8,
Missiles = 1,
---If you want the Gun solution checker to ONLY work when the shooter is behind the target
GunKillOnlyRearAspect = true
},
-- REVIVE NOT IMPLEMENTED YET
Revive = {
-- Revive player after taking first fuel from a tanker
TankerConnect = true,
--After landing, if an aircraft is still on the ground 30 seconds after landing. (No Touch and goes)
Landing = true,
-- Respawn zones need to start with "REVIVE_" so "REVIVE_<zoneName>"
InRespawnZone = true,
},
AutoInvulnerableSettings = {
-- Automatically manages invulnerablity.
Enabled = true,
-- Players only
PlayersOnly = false,
-- Invulnerable when outside trigger zones starting with name "vulnerablezone_"
OutsideVulnerableZone = true,
-- NOT IMPLEMENTED YET!!
-- Invulnerable when inside trigger zones starting with name "invulnerablezone_"
-- (Doesn't really do anything if OutsideVulnerableZone is set to true as well)
InsideInvulnerablezone = true,
-- Detects whether or not a unit has hit the ground or scenery object when invulnerable.
-- If a unit indeed hit the ground in an "excessive way" it will explode
GroundCollisionDetection = true,
ObjectCollisionDetection = true
},
DebugLog = false,
DebugOutText = false,
}
--============================================
-- Devs TODO list
--============================================
--[[
MissileTracker:
TODO: MadDogged missiles.
TODO: Destroyed missiles
CrashManager:
TODO: Over G ?
BombTracker:
TODO: Practice Bombs
(This might better help with "unlimited weapons" options)
]]--
--============================================
-- Script starts here
--============================================
local isSinglePlayer = false
if net.get_my_player_id() == 0 then
isSinglePlayer = true
end
local Util = {}
do
function Util.split_string(input, separator)
if separator == nil then
separator = " "
end
local result = {}
if input == nil then
return result
end
for str in string.gmatch(input, "[^" .. separator .. "]+") do
table.insert(result, str)
end
return result
end
function Util.distance(a, b)
return math.sqrt((b.x - a.x) ^ 2 + (b.z - a.z) ^ 2)
end
---comment
---@param a Vec3
---@param b Vec3
---@return number
function Util.getDistance3D(a, b)
return Util.vectorMagnitude({ x = a.x - b.x, y = a.y - b.y, z = a.z - b.z })
end
function Util.vectorMagnitude(vec)
return (vec.x ^ 2 + vec.y ^ 2 + vec.z ^ 2) ^ 0.5
end
---@param str string
---@param findable string
---@param ignoreCase boolean?
---@return boolean
function Util.startsWith(str, findable, ignoreCase)
if ignoreCase == true then
return string.lower(str):find('^' .. string.lower(findable)) ~= nil
end
return str:find('^' .. findable) ~= nil
end
---@param number number
---@return string
function Util.roundNumber(number)
return string.format("%.2f", number)
end
end
local Log = {}
do
Log.info = function(string)
env.info("[TDCS Red Flag] " .. (string or "nil"))
end
Log.warn = function(string)
env.warn("[TDCS Red Flag] " .. (string or "nil"))
end
Log.error = function(string)
env.error("[TDCS Red Flag] " .. (string or "nil"))
end
Log.debug = function(string)
if Config.DebugLog == false then
return
end
env.info("[DEBUG][TDCS Red Flag] " .. (string or "nil"))
end
Log.debugOutText = function(string, time)
if Config.DebugOutText == true then
trigger.action.outText("[DEBUG] " .. string, time)
end
end
Log.debugOutTextForUnit = function(unitId, string, time)
if Config.DebugOutText == true then
trigger.action.outTextForUnit(unitId, string, time)
end
end
end
local Helpers = {}
do
local function table_print(tt, indent, done)
done = done or {}
indent = indent or 0
if type(tt) == "table" then
local sb = {}
for key, value in pairs(tt) do
table.insert(sb, string.rep(" ", indent)) -- indent it
if type(value) == "table" and not done[value] then
done[value] = true
table.insert(sb, key .. " = {\n");
table.insert(sb, table_print(value, indent + 2, done))
table.insert(sb, string.rep(" ", indent)) -- indent it
table.insert(sb, "}\n");
elseif "number" == type(key) then
table.insert(sb, string.format("\"%s\"\n", tostring(value)))
else
table.insert(sb, string.format(
"%s = \"%s\"\n", tostring(key), tostring(value)))
end
end
return table.concat(sb)
else
return tt .. "\n"
end
end
Helpers.toString = function(something)
if something == nil then
return "nil"
elseif "table" == type(something) then
return table_print(something)
elseif "string" == type(something) then
return something
else
return tostring(something)
end
end
Helpers.vecSub = function(vec1, vec2)
return { x = vec1.x - vec2.x, y = vec1.y - vec2.y, z = vec1.z - vec2.z }
end
---comment
---@param a Vec3
---@param b Vec3
Helpers.vecAdd = function (a, b)
return {x=a.x+b.x, y=a.y+b.y, z=a.z+b.z}
end
Helpers.normVec = function(vec)
local magnitude = Util.vectorMagnitude(vec)
return {
x = vec.x / magnitude,
y = vec.y / magnitude,
z = vec.z / magnitude
}
end
---@param posA Vec3 Bullet
---@param speedA Vec3 Bullet
---@param posB Vec3 Jet
---@param speedB Vec3 Jet
---@param acc Vec3 JetAcceleration
---@return boolean
Helpers.vecCollision = function(posA, speedA, posB, speedB, acc)
---@param bulletX number bullet position
---@param jetX number jet position
---@param bulletV number
---@param jetV number
---@param jetA number
---@return number, number
local dimensionCollision = function(bulletX, jetX, bulletV, jetV, jetA)
local closestToZero = function(a, b)
if a == b then
if a > 0 then return a end
return b
end
if math.abs(a) < math.abs(b) then return a end
if math.abs(b) < math.abs(a) then return b end
return 0
end
local SolveAccelerated = function(a, b, c, d, e)
-- local a = bulletX
-- local b = bulletV
-- local c = jetX
-- local d = jetV
-- local e = jetA
local underRoot = math.pow((2 * d -2 * b),2) - 4 * e * (2 * c - 2 * a)
local first = (-2 * d + 2 * b + math.sqrt(underRoot)) / (2 * e)
local second = (-2 * d + 2 * b - math.sqrt(underRoot)) / (2 * e)
-- The most logical solution is the one that lies closest to 0 (as it's all short ranges and t should be very low)
return closestToZero(first, second)
end
local minx1 = bulletX - 0.5
local maxx1 = bulletX + 0.5
local minx2 = jetX - 20
local maxx2 = jetX + 20
if jetA == 0 then
Log.debugOutText("Solving linear",1)
local xA = (maxx2 - minx1) / (bulletV - jetV)
local xB = (minx2 - maxx1) / (bulletV - jetV)
local minTime = math.min(xA, xB)
local maxTime = math.max(xA, xB)
return minTime, maxTime
end
local xA = SolveAccelerated(minx1, bulletV, maxx2, jetV, jetA)
local xB = SolveAccelerated(maxx1, bulletV, minx2, jetV, jetA)
local minTime = math.min(xA, xB)
local maxTime = math.max(xA, xB)
return minTime, maxTime
end
local xTimeMin, xTimeMax = dimensionCollision(posA.x, posB.x, speedA.x, speedB.x, acc.x)
local yTimeMin, yTimeMax = dimensionCollision(posA.y, posB.y, speedA.y, speedB.y, acc.y)
local zTimeMin, zTimeMax = dimensionCollision(posA.z, posB.z, speedA.z, speedB.z, acc.z)
Log.debugOutText("[" .. Util.roundNumber(xTimeMin) .. ",".. Util.roundNumber(xTimeMax) .. "]" ..
"[" .. Util.roundNumber(yTimeMin) .. ",".. Util.roundNumber(yTimeMax) .. "]" ..
"[" .. Util.roundNumber(zTimeMin) .. ",".. Util.roundNumber(zTimeMax) .. "]", 1)
return
(xTimeMin <= yTimeMax and yTimeMin <= xTimeMax)
and (yTimeMin <= zTimeMax and zTimeMin <= yTimeMax)
and (xTimeMin <= zTimeMax and zTimeMin <= yTimeMax)
end
---@param vec Vec3
---@param magnitude number
---@return Vec3
Helpers.vecSetMagnitude = function(vec, magnitude)
local oldMag = Helpers.vectorMagnitude(vec)
return {
x = vec.x / oldMag * magnitude,
y = vec.y / oldMag * magnitude,
z = vec.z / oldMag * magnitude,
}
end
Helpers.vectorMagnitude = function(vec)
return (vec.x ^ 2 + vec.y ^ 2 + vec.z ^ 2) ^ 0.5
end
---returns a number in range [-1,1]. > 0 same direction. < 0 opposite direction
---@param vec1 any
---@param vec2 any
---@return number
Helpers.vecAlignment = function(vec1, vec2)
local vec1Norm = Helpers.normVec(vec1)
local vec2Norm = Helpers.normVec(vec2)
return ((vec1Norm.x * vec2Norm.x) + (vec1Norm.y * vec2Norm.y) + (vec1Norm.z * vec2Norm.z))
end
Helpers.isPlayer = function(unitId, coalitionId)
if coalitionId == nil then
local players = coalition.getPlayers(coalitionId)
for i, player in ipairs(players) do
if player:getID() == unitId then
return true
end
end
else
-- Check all coalitions
for i = 0, 2 do
local players = coalition.getPlayers(i)
for key, player in pairs(players) do
if player:getID() == unitId then
return true
end
end
end
end
return false
end
end
local AIHelpers = {}
do
AIHelpers.setDocile = function(unit)
Log.info("Setting unit docile: " .. unit:getName())
local con = unit:getController()
if isSinglePlayer == true then
con = unit:getGroup():getController()
end
con:setOption(0, 4) --hold fire
con:setOption(1, 0) --No reaction to threat
con:setOption(3, 1) --No radar using
end
local finalAirbases = {}
do -- load final airbases
for coalition_name, coalition_data in pairs(env.mission.coalition) do
if coalition_data.country then
for country_index, country_data in pairs(coalition_data.country) do
if country_data.plane and country_data.plane.group then
for _, group in ipairs(country_data.plane.group) do
if group.route and group.route.points then
local count = 0
for _, point in ipairs(group.route.points) do
count = count + 1
end
if #group.route.points > 0 then
local lastpoint = group.route.points[count]
if lastpoint.action and lastpoint.action == "Landing" then
local landingPoint = {
airdromeId = lastpoint.airdromeId,
x = lastpoint.x,
y = lastpoint.y,
alt = lastpoint.alt,
speed = lastpoint.speed,
}
finalAirbases[group.name] = landingPoint
end
end
end
end
end
end
end
end
end
AIHelpers.sendRTB = function(unit)
local groupName = unit:getGroup():getName()
local airbaseData = finalAirbases[groupName]
if airbaseData == nil then
return --TODO: If no RTB base was added
end
local currentPosition = unit:getPoint()
local task = {
id = "Mission",
params = {
airborne = true, -- RTB mission generally are given to airborne units
route = {
points = {
[1] = {
["alt"] = 2000,
["action"] = "Turning Point",
["alt_type"] = "BARO",
["speed"] = 220.97222222222,
["task"] =
{
["id"] = "ComboTask",
["params"] =
{
["tasks"] =
{
[1] =
{
["enabled"] = true,
["auto"] = false,
["id"] = "WrappedAction",
["number"] = 1,
["params"] =
{
["action"] =
{
["id"] = "Option",
["params"] =
{
["value"] = 4,
["name"] = 0,
}, -- end of ["params"]
}, -- end of ["action"]
}, -- end of ["params"]
}, -- end of [1]
[2] =
{
["enabled"] = true,
["auto"] = false,
["id"] = "WrappedAction",
["number"] = 2,
["params"] =
{
["action"] =
{
["id"] = "Option",
["params"] =
{
["value"] = 0,
["name"] = 3,
}, -- end of ["params"]
}, -- end of ["action"]
}, -- end of ["params"]
}, -- end of [2]
[3] =
{
["enabled"] = true,
["auto"] = false,
["id"] = "WrappedAction",
["number"] = 3,
["params"] =
{
["action"] =
{
["id"] = "Option",
["params"] =
{
["value"] = 0,
["name"] = 1,
}, -- end of ["params"]
}, -- end of ["action"]
}, -- end of ["params"]
}, -- end of [3]
}, -- end of ["tasks"]
}, -- end of ["params"]
}, -- end of ["task"]
["type"] = "Turning Point",
["ETA"] = 419.83667467719,
["ETA_locked"] = false,
["y"] = airbaseData.y,
["x"] = airbaseData.x,
["speed_locked"] = true,
["formation_template"] = "",
},
[2] = {
alt = airbaseData.alt,
action = "Landing",
alt_type = "BARO",
speed = airbaseData.speed,
ETA = 0,
ETA_locked = false,
x = airbaseData.x,
y = airbaseData.y,
speed_locked = true,
formation_template = "",
airdromeId = airbaseData.airdromeId,
type = "Land",
task = {
id = "ComboTask",
params = {
tasks = {}
}
}
}
}
}
}
}
local con = unit:getController()
con:setTask(task)
Log.info("Sending Unit RTB: " .. unit:getName())
end
end
---@class Notifier
---@field private config NotificationConfig
local Notifier = {}
do
---@class NotificationConfig
---@field CallsignDelimiter string
---comment
---@param config NotificationConfig
---@return Notifier
function Notifier.New(config)
Notifier.__index = Notifier
local self = setmetatable({}, Notifier)
self.config = config
return self
end
---@private
function Notifier:NameToCallSign(name)
local split = Util.split_string(name or "", Config.CallSignDelimiter)
local controllerFriendlyName = split[1]
return controllerFriendlyName
end
---@private
---@param template string
---@param key string
---@param value string
---@returns string
function Notifier:Format(template, key, value)
if not template or not key or not value then return template end
return template:gsub("{{ " .. key .. " }}", value):gsub("{{" .. key .. "}}", value)
end
---@param shooter table
function Notifier:NotifyMissed(shooter)
local name = shooter:getPlayerName() or shooter:getCallsign()
local friendlyName = self:NameToCallSign(name)
if Config.Messages.ControllerMessages.MissileMissed ~= nil then
local message = self:Format(Config.Messages.ControllerMessages.MissileMissed, "callsign", friendlyName)
net.send_chat(message, true)
end
if Config.Messages.PlayerMessages.MissileMissed ~= nil then
local message = self:Format(Config.Messages.PlayerMessages.MissileMissed, "callsign", friendlyName)
trigger.action.outTextForUnit(shooter:getID(), message, Config.Delays.MissMessageOnScreen)
end
end
---@param shooter table
---@param delaySeconds number
function Notifier:NotifyMissedDelayed(shooter, delaySeconds)
local notify = function(input, time)
input.notifier:NotifyMissed(input.shooter)
return nil
end
timer.scheduleFunction(notify, { notifier = self, shooter = shooter }, timer.getTime() + delaySeconds)
end
---@param target table
function Notifier:NotifyKilled(target)
local name = target:getName()
if target.getPlayerName then
name = target:getPlayerName() or target:getName()
end
local friendlyName = self:NameToCallSign(name)
if Config.Messages.ControllerMessages.UnitKilled ~= nil then
local controllerMessage = self:Format(Config.Messages.ControllerMessages.UnitKilled, "callsign", friendlyName)
net.send_chat(controllerMessage, true)
end
if target.getID and Config.Messages.PlayerMessages.UnitKilled ~= nil then
local message = self:Format(Config.Messages.PlayerMessages.UnitKilled, "callsign", friendlyName)
trigger.action.outTextForUnit(target:getID(), message, Config.Delays.DeathMessageOnScreenSeconds, true)
end
end
---@param shooter table
function Notifier:NotifyKill(shooter)
local name = shooter:getPlayerName() or shooter:getCallsign()
local friendlyName = self:NameToCallSign(name)
if Config.Messages.ControllerMessages.ConfirmKill ~= nil then
local message = self:Format(Config.Messages.ControllerMessages.ConfirmKill, "callsign", friendlyName)
net.send_chat(message, true)
end
if Config.Messages.PlayerMessages.ConfirmKill ~= nil then
local message = self:Format(Config.Messages.PlayerMessages.ConfirmKill, "callsign", friendlyName)
trigger.action.outTextForUnit(shooter:getID(), message, 5)
end
end
---@param shooter table
---@param delaySeconds number
function Notifier:NotifyKillDelayed(shooter, delaySeconds)
if delaySeconds <= 1 then
self:NotifyKill(shooter)
else
local notify = function(input, time)
input.notifier:NotifyKill(input.shooter)
return nil
end
timer.scheduleFunction(notify, { notifier = self, shooter = shooter } , timer.getTime() + delaySeconds)
end
end
---@param shooter table
function Notifier:NotifyGunKill(shooter)
local name = shooter:getPlayerName() or shooter:getCallsign()
local friendlyName = self:NameToCallSign(name)
if Config.Messages.ControllerMessages.ConfirmKill ~= nil then
local message = self:Format(Config.Messages.ControllerMessages.ConfirmKillGunKill, "callsign", friendlyName)
net.send_chat(message, true)
end
if Config.Messages.PlayerMessages.ConfirmKill ~= nil then
local message = self:Format(Config.Messages.PlayerMessages.ConfirmKillGunKill, "callsign", friendlyName)
trigger.action.outTextForUnit(shooter:getID(), message, 8)
end
end
---@param shooter table
---@param delaySeconds number
function Notifier:NotifyGunKillDelayed(shooter, delaySeconds)
if delaySeconds <= 1 then
self:NotifyGunKill(shooter)
else
local notify = function(input, time)
input.notifier:NotifyGunKill(input.shooter)
return nil
end
timer.scheduleFunction(notify, { notifier = self, shooter = shooter }, timer.getTime() + delaySeconds)
end
end
---@param shooter table
function Notifier:CopyShot(shooter)
if Config.Messages.PlayerMessages.CopyShotMessage ~= nil then
local name = shooter:getPlayerName() or shooter:getCallsign()
local friendlyName = self:NameToCallSign(name)
local message = self:Format(Config.Messages.PlayerMessages.CopyShotMessage, "callsign", friendlyName)
trigger.action.outTextForUnit(shooter:getID(), message, 5)
end
end
---@param shooter table
---@param delaySeconds number
function Notifier:CopyShotDelayed(shooter, delaySeconds)
local notify = function(input, time)
input.notifier:CopyShot(input.shooter)
return nil
end
timer.scheduleFunction(notify, { notifier = self, shooter = shooter }, timer.getTime() + delaySeconds)
end
---@param shooter table
function Notifier:DenyShot(shooter)
local name = shooter:getPlayerName() or shooter:getCallsign()
local friendlyName = self:NameToCallSign(name)
trigger.action.outTextForUnit(shooter:getID(), friendlyName .. " " .. "Shot scrapped", 5)
end
function Notifier:NotifyRevived(unit)
if Config.Messages.PlayerMessages.ReviveMessage == nil then
return
end
local name = unit:getPlayerName() or unit:getCallsign()
local friendlyName = self:NameToCallSign(name)
local message = self:Format(Config.Messages.PlayerMessages.ReviveMessage, "callsign", friendlyName)
trigger.action.outTextForUnit(unit:getID(), message, 10)
end
---@param unit table
function Notifier:NotifyInvinsible(unit)
Log.info("Set unit immortal: " .. unit:getName())
trigger.action.outTextForUnit(unit:getID(), "Invinsibility activated", 3)
end
---@param unit table
function Notifier:NotifyNotInvinsible(unit)
Log.info("Set unit not immortal: " .. unit:getName())
trigger.action.outTextForUnit(unit:getID(), "Invinsibility de-activated", 3)
end
end
Log.info("Initiating ...")
---@class UnitManager
---@field private dead_players table<string, boolean>
---@field private dead_units table<string, boolean>
---@field private crashed_units table<string, boolean>
---@field private bullet_hits table<string, integer>
---@field private missile_hits table<string, integer>
---@field private _notifier Notifier
---@field private invincibilityManager InvincibilityManager
local UnitManager = {}
do --- UnitManager
---comment
---@param invincibilityManager InvincibilityManager
---@param notifier Notifier
---@return UnitManager
function UnitManager.New(invincibilityManager, notifier)
UnitManager.__index = UnitManager
local self = setmetatable({}, UnitManager)
self.dead_players = {}
self.dead_units = {}
self.crashed_units = {}
self.bullet_hits = {}
self.missile_hits = {}
self.invincibilityManager = invincibilityManager
self._notifier = notifier
return self
end
---Checks if unit is alive according to the simulation
---@param unitName string
---@return boolean
function UnitManager:isUnitAlive(unitName)
if self.dead_units[unitName] == true then
return false
end
return true
end
---comment
---@return Array<string>
function UnitManager:getDeadPlayers()
local result = {}
for unitName, isDead in pairs(self.dead_players) do
if isDead == true then
table.insert(result, unitName)
end
end
return result
end
---comment
---@param shooter Unit
---@param target Unit
function UnitManager:registerGunKill(shooter, target)
if self:isUnitAlive(shooter:getName()) == false then
return --if hit by a bullet from a dead unit the hit does not count
end
if not self.bullet_hits[target:getName()] then
self.bullet_hits[target:getName()] = 0
end
if self:isUnitAlive(target:getName()) == false then
return --if a unit is already dead there's no need to do anything
end
self.bullet_hits[target:getName()] = Config.KillParameters.Bullets
if self.bullet_hits[target:getName()] >= Config.KillParameters.Bullets then
self:markUnitDead(target)
self._notifier:NotifyGunKillDelayed(shooter, Config.Delays.GunKillDelay)
end
end
---Registers a hit
---@param target Unit
---@param shooter Unit
---@param weapon Weapon
function UnitManager:registerHit(target, shooter, weapon)
if Object.getCategory(weapon) == Object.Category.WEAPON then
if weapon:getDesc().category == Weapon.Category.SHELL then
if self:isUnitAlive(shooter:getName()) == false then
return --if hit by a bullet from a dead unit the hit does not count
end
if not self.bullet_hits[target:getName()] then
self.bullet_hits[target:getName()] = 0
end
self.bullet_hits[target:getName()] = self.bullet_hits[target:getName()] + 1
if self.bullet_hits[target:getName()] >= Config.KillParameters.Bullets then
self:markUnitDead(target)
self._notifier:NotifyGunKillDelayed(shooter, Config.Delays.GunKillDelay)
end
elseif weapon:getDesc().category == Weapon.Category.MISSILE then
if not self.missile_hits[target:getName()] then
self.missile_hits[target:getName()] = 0
end
self.missile_hits[target:getName()] = self.missile_hits[target:getName()] + 1
if self.missile_hits[target:getName()] >= Config.KillParameters.Missiles then
self._notifier:NotifyKillDelayed(shooter, Config.Delays.MissileKillDelay)
self:markUnitDead(target)
end
end
elseif Object.getCategory(weapon) == Object.Category.UNIT then
local targetName = "nil"
if target.getName then
targetName = target:getName()
end
local unitName = weapon:getName()
if self.crashed_units[unitName] == true then -- only crash and explode unit once
return
end
self.crashed_units[unitName] = true
self.invincibilityManager:setMortal(weapon)
trigger.action.explosion(weapon:getPoint(), 5)
end
end
---@param unit table
---@param notify boolean
function UnitManager:markUnitAlive(unit, notify)
Log.info("Marking " .. unit:getName() .. " as alive")
self.dead_units[unit:getName()] = false
self.bullet_hits[unit:getName()] = 0
self.missile_hits[unit:getName()] = 0
self.crashed_units[unit:getName()] = false
if Helpers.isPlayer(unit:getID(), unit:getCoalition()) == true then
self.dead_players[unit:getName()] = false
end
self:setInvisible(unit, false)
if notify == true then
self._notifier:NotifyRevived(unit)
end
end
---comment
---@param unit table
function UnitManager:markUnitDead(unit)
Log.info("Marking " .. unit:getName() .. " as dead")
self._notifier:NotifyKilled(unit)
self:setInvisible(unit, true)
local function SendAIRtb(unit)
AIHelpers.setDocile(unit)
AIHelpers.sendRTB(unit)
AIHelpers.setDocile(unit)
end
self.dead_units[unit:getName()] = true
self.bullet_hits[unit:getName()] = 0
self.missile_hits[unit:getName()] = 0
if Helpers.isPlayer(unit:getID(), unit:getCoalition()) == true then
self.dead_players[unit:getName()] = true
else
SendAIRtb(unit)
end
end
---comment
---@param unit Unit
function UnitManager:OnUnitBirth(unit)
self:markUnitAlive(unit, false)
self.invincibilityManager:resetUnit(unit)
trigger.action.outTextForUnit(unit:getID(), "Reset unit...", 1, true)
end
---@private