forked from FAForever/fa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplatoon.lua
4925 lines (4455 loc) · 214 KB
/
platoon.lua
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
--****************************************************************************
--**
--** File : /lua/platoon.lua
--** Author(s): Drew Staltman, Robert Oates, Gautam Vasudevan, Daniel Teh?, ...?
--**
--** Summary :
--**
--** Copyright © 2007 Gas Powered Games, Inc. All rights reserved.
--****************************************************************************
----------------------------------------------------------------------------------
-- Platoon Lua Module --
----------------------------------------------------------------------------------
local AIUtils = import("/lua/ai/aiutilities.lua")
local TransportUtils = import("/lua/ai/transportutilities.lua")
local Utilities = import("/lua/utilities.lua")
local AIBuildStructures = import("/lua/ai/aibuildstructures.lua")
local UpgradeTemplates = import("/lua/upgradetemplates.lua")
local Behaviors = import("/lua/ai/aibehaviors.lua")
local AIAttackUtils = import("/lua/ai/aiattackutilities.lua")
local ScenarioUtils = import("/lua/sim/scenarioutilities.lua")
local SPAI = import("/lua/scenarioplatoonai.lua")
--for sorian AI
local SUtils = import("/lua/ai/sorianutilities.lua")
---@alias PlatoonSquads 'Attack' | 'Artillery' | 'Guard' | 'None' | 'Scout' | 'Support' | 'Unassigned'
---@class Platoon : moho.platoon_methods
---@field PlatoonData table
Platoon = Class(moho.platoon_methods) {
NeedCoolDown = false,
LastAttackDestination = {},
---@param self Platoon
---@param plan table
OnCreate = function(self, plan)
self.Trash = TrashBag()
if self[plan] then
self.AIThread = self:ForkThread(self[plan])
end
self.PlatoonData = {}
self.EventCallbacks = {
OnDestroyed = {},
}
self.PartOfAttackForce = false
self.CreationTime = GetGameTimeSeconds()
end,
---@param self Platoon
---@param dataTable table
SetPlatoonData = function(self, dataTable)
self.PlatoonData = table.deepcopy(dataTable)
end,
---@param self Platoon
SetPartOfAttackForce = function(self)
if not self.PlatoonData then
self.PlatoonData = {}
end
if self.PlatoonData.NotPartOfAttackForce then return end
local platoonsGiven = false
local aiBrain = self:GetBrain()
self.PartOfAttackForce = true
-- Because of how the PlatoonData in the editor exports table.getn will not work here
if self.PlatoonData.AMPlatoons then
for k,v in self.PlatoonData.AMPlatoons do
platoonsGiven = true
if not aiBrain.AttackData.PlatoonCount[v] then
aiBrain.AttackData.PlatoonCount[v] = 1
else
aiBrain.AttackData.PlatoonCount[v] = aiBrain.AttackData.PlatoonCount[v] + 1
end
end
end
if not platoonsGiven then
local testUnit = self:GetPlatoonUnits()[1]
if testUnit then
self.PlatoonData.AMPlatoons = {}
if EntityCategoryContains(categories.MOBILE * categories.AIR, testUnit) then
aiBrain.AttackData.PlatoonCount['DefaultGroupAir'] = aiBrain.AttackData.PlatoonCount['DefaultGroupAir'] + 1
table.insert(self.PlatoonData.AMPlatoons, 'DefaultGroupAir')
elseif EntityCategoryContains(categories.MOBILE * categories.LAND, testUnit) then
aiBrain.AttackData.PlatoonCount['DefaultGroupLand'] = aiBrain.AttackData.PlatoonCount['DefaultGroupLand'] + 1
table.insert(self.PlatoonData.AMPlatoons, 'DefaultGroupLand')
elseif EntityCategoryContains(categories.MOBILE * categories.NAVAL, testUnit) then
aiBrain.AttackData.PlatoonCount['DefaultGroupSea'] = aiBrain.AttackData.PlatoonCount['DefaultGroupSea'] + 1
table.insert(self.PlatoonData.AMPlatoons, 'DefaultGroupSea')
end
end
end
self:AddDestroyCallback(aiBrain.AttackManager.DecrementCount)
end,
---@param self Platoon
---@return boolean
IsPartOfAttackForce = function(self)
return self.PartOfAttackForce
end,
---@param self Platoon
---@param fn function
---@param ... any
---@return thread
ForkAIThread = function(self, fn, ...)
if fn then
self.AIThread = ForkThread(fn, self, unpack(arg))
self.Trash:Add(self.AIThread)
return self.AIThread
else
return nil
end
end,
---@param self Platoon
StopAI = function(self)
if self.AIThread != nil then
self.AIThread:Destroy()
end
end,
---@param self Platoon
---@param callbackFunction function
AddDestroyCallback = function(self, callbackFunction)
if not callbackFunction then
error('*ERROR: Tried to add an OnDestroy on a platoon callback with a nil function')
return
end
table.insert(self.EventCallbacks.OnDestroyed, callbackFunction)
end,
---@param self Platoon
DoDestroyCallbacks = function(self)
if self.EventCallbacks.OnDestroyed then
for k, cb in self.EventCallbacks.OnDestroyed do
if cb then
cb(self:GetBrain(), self)
end
end
end
end,
---@param self Platoon
---@param fn function
RemoveDestroyCallback = function(self, fn)
for k,v in self.EventCallbacks.OnDestroyed do
if v == fn then
self.EventCallbacks.OnDestroyed[k] = nil
end
end
end,
---@param self Platoon
OnDestroy = function(self)
--DUNCAN - Added
self:StopAI()
self:DoDestroyCallbacks()
if self.Trash then
self.Trash:Destroy()
end
end,
---@param self Platoon
---@param fn function
---@param ... any
---@return thread
ForkThread = function(self, fn, ...)
if fn then
local thread = ForkThread(fn, self, unpack(arg))
self.Trash:Add(thread)
return thread
else
return nil
end
end,
---@param self Platoon
---@param plan table
SetAIPlan = function(self, plan)
if not self[plan] then return end
if self.AIThread then
self.AIThread:Destroy()
end
self.PlanName = plan
self:ForkAIThread(self[plan])
end,
---@param self Platoon
---@return string|nil
GetPlan = function(self)
if self.PlanName then
return self.PlanName
end
end,
---@param self Platoon
---@param rings number
---@return number
GetThreatLevel = function(self, rings)
local brain = self:GetBrain()
return brain:GetThreatAtPosition(self:GetPlatoonPosition(), rings, true)
end,
---@param self Platoon
---@param commands PlatoonCommand[]
---@return boolean
CheckCommandsCompleted = function(self, commands)
for k, v in commands do
if self:IsCommandsActive(v) then
return false
end
end
return true
end,
---@param self Platoon
TurnOffPoolAI = function(self)
if self.PoolAIOn then
self.AIThread:Destroy()
self.PoolAIOn = false
self.AIThread = nil
end
end,
---@param self Platoon
TurnOnPoolAI = function(self)
if not self.PoolAIOn and not self.AIThread then
self.AIThread = self:ForkAIThread(self.PoolAI)
end
end,
---@param self Platoon
PoolAI = function(self)
end,
---@param self Platoon
OnUnitsAddedToPlatoon = function(self)
for k,v in self:GetPlatoonUnits() do
if not v.Dead then
v.PlatoonHandle = self
end
end
end,
---@param self Platoon
PlatoonDisband = function(self)
if self.ArmyPool then
--WARN('AI WARNING: Platoon trying to disband ArmyPool')
--LOG(reprsl(debug.traceback()))
return
end
local aiBrain = self:GetBrain()
if self.BuilderHandle then
self.BuilderHandle:RemoveHandle(self)
end
for k,v in self:GetPlatoonUnits() do
v.PlatoonHandle = nil
v.AssistSet = nil
v.AssistPlatoon = nil
v.UnitBeingAssist = nil
v.ReclaimInProgress = nil
v.CaptureInProgress = nil
if v:IsPaused() then
v:SetPaused( false )
end
if not v.Dead and v.BuilderManagerData then
if self.CreationTime == GetGameTimeSeconds() and v.BuilderManagerData.EngineerManager then
if self.BuilderName then
--LOG('*PlatoonDisband: ERROR - Platoon disbanded same tick as created - ' .. self.BuilderName .. ' - Army: ' .. aiBrain:GetArmyIndex() .. ' - Location: ' .. repr(v.BuilderManagerData.LocationType))
v.BuilderManagerData.EngineerManager:AssignTimeout(v, self.BuilderName)
else
--LOG('*PlatoonDisband: ERROR - Platoon disbanded same tick as created - Army: ' .. aiBrain:GetArmyIndex() .. ' - Location: ' .. repr(v.BuilderManagerData.LocationType))
end
v.BuilderManagerData.EngineerManager:DelayAssign(v)
elseif v.BuilderManagerData.EngineerManager then
v.BuilderManagerData.EngineerManager:TaskFinished(v)
end
end
if not v.Dead then
IssueStop({v})
IssueClearCommands({v})
end
end
if self.AIThread then
self.AIThread:Destroy()
end
aiBrain:DisbandPlatoon(self)
end,
---@param self Platoon
---@param threatType BrainThreatType
---@param unitCategory EntityCategory
---@param position Vector
---@param radius number
---@return number|nil
GetPlatoonThreat = function(self, threatType, unitCategory, position, radius)
local threat = 0
if position then
threat = self:CalculatePlatoonThreatAroundPosition(threatType, unitCategory, position, radius)
else
threat = self:CalculatePlatoonThreat(threatType, unitCategory)
end
return threat
end,
---@param self Platoon
---@param category EntityCategory
---@param point Vector
---@param radius number
---@return Unit[]
GetPlatoonUnitsAroundPoint = function(self, category, point, radius)
local units = {}
for k,v in self:GetPlatoonUnits() do
-- Wrong unit type
if not EntityCategoryContains(category, v) then
continue
end
-- Too far away
if Utilities.XZDistanceTwoVectors(v:GetPosition(), point) > radius then
continue
end
table.insert(units, v)
end
return units
end,
---@param self Platoon
---@param category EntityCategory
---@param position Vector
---@param radius number
---@return nil
GetNumCategoryUnits = function(self, category, position, radius)
local numUnits = 0
if position then
numUnits = self:PlatoonCategoryCountAroundPosition(category, position, radius)
else
numUnits = self:PlatoonCategoryCount(category)
end
return numUnits
end,
-- ===== AI THREADS ===== --
---@param self Platoon
BuildOnceAI = function(self)
local aiBrain = self:GetBrain()
for k,v in self:GetPlatoonUnits() do
if not v.Dead then
v.PreviousPriority = aiBrain:PBMGetPriority(self)
v.Platoon = self
end
end
aiBrain:PBMSetPriority(self, 0)
end,
---@param self Platoon
EnhanceAI = function(self)
local aiBrain = self:GetBrain()
local unit
local data = self.PlatoonData
local lastEnhancement
local numLoop = 0
for k,v in self:GetPlatoonUnits() do
unit = v
break
end
if unit then
IssueStop({unit})
IssueClearCommands({unit})
for k,v in data.Enhancement do
if not unit:HasEnhancement(v) then
local order = {
TaskName = "EnhanceTask",
Enhancement = v
}
--LOG('*AI DEBUG: '..aiBrain.Nickname..' EnhanceAI Added Enhancement: '..v)
IssueScript({unit}, order)
lastEnhancement = v
end
end
WaitSeconds(data.TimeBetweenEnhancements or 1)
repeat
WaitSeconds(5)
--LOG('*AI DEBUG: '..aiBrain.Nickname..' Com still upgrading ')
until unit.Dead or unit:HasEnhancement(lastEnhancement)
--LOG('*AI DEBUG: '..aiBrain.Nickname..' Com finished upgrading ')
end
self:PlatoonDisband()
end,
---@param self Platoon
HuntAI = function(self)
self:Stop()
local aiBrain = self:GetBrain()
local armyIndex = aiBrain:GetArmyIndex()
local target
local blip
while aiBrain:PlatoonExists(self) do
target = self:FindClosestUnit('Attack', 'Enemy', true, categories.ALLUNITS - categories.WALL)
if target then
blip = target:GetBlip(armyIndex)
self:Stop()
self:AggressiveMoveToLocation(table.copy(target:GetPosition()))
--DUNCAN - added to try and stop AI getting stuck.
local position = AIUtils.RandomLocation(target:GetPosition()[1],target:GetPosition()[3])
self:MoveToLocation(position, false)
end
WaitSeconds(17)
end
end,
---@param self Platoon
TacticalAI = function(self)
self:Stop()
local aiBrain = self:GetBrain()
local armyIndex = aiBrain:GetArmyIndex()
local platoonUnits = self:GetPlatoonUnits()
local unit
if not aiBrain:PlatoonExists(self) then return end
--GET THE Launcher OUT OF THIS PLATOON
for k, v in platoonUnits do
if EntityCategoryContains(categories.STRUCTURE * categories.TACTICALMISSILEPLATFORM, v) then
unit = v
break
end
end
if not unit then return end
local bp = unit:GetBlueprint()
local weapon = bp.Weapon[1]
local maxRadius = weapon.MaxRadius
local minRadius = weapon.MinRadius
unit:SetAutoMode(true)
--DUNCAN - commented out
--local atkPri = { 'COMMAND', 'STRUCTURE STRATEGIC', 'STRUCTURE DEFENSE', 'CONSTRUCTION', 'EXPERIMENTAL MOBILE LAND', 'TECH3 MOBILE LAND',
-- 'TECH2 MOBILE LAND', 'TECH1 MOBILE LAND', 'ALLUNITS' }
--DUNCAN - added energy production, removed construction, repriotised.
self:SetPrioritizedTargetList('Attack', {
categories.COMMAND,
categories.EXPERIMENTAL,
categories.ENERGYPRODUCTION,
categories.STRUCTURE,
categories.TECH3 * categories.MOBILE})
while aiBrain:PlatoonExists(self) do
local target = false
local blip = false
while unit:GetTacticalSiloAmmoCount() < 1 or not target do
WaitSeconds(7)
target = false
while not target do
if not target then
target = self:FindPrioritizedUnit('Attack', 'Enemy', true, unit:GetPosition(), maxRadius)
end
if target then
break
end
WaitSeconds(3)
if not aiBrain:PlatoonExists(self) then
return
end
end
end
if not target.Dead then
--LOG('*AI DEBUG: Firing Tactical Missile at enemy swine!')
IssueTactical({unit}, target)
end
WaitSeconds(3)
end
end,
---@param self Platoon
NukeAI = function(self)
--self:Stop()
local aiBrain = self:GetBrain()
local platoonUnits = self:GetPlatoonUnits()
local unit
--GET THE Launcher OUT OF THIS PLATOON
for k, v in platoonUnits do
if EntityCategoryContains(categories.SILO * categories.NUKE, v) then
unit = v
break
end
end
if unit then
local nukePos
unit:SetAutoMode(true)
while aiBrain:PlatoonExists(self) do
while unit:GetNukeSiloAmmoCount() < 1 do
WaitSeconds(11)
if not aiBrain:PlatoonExists(self) then
return
end
end
nukePos = import("/lua/ai/aibehaviors.lua").GetHighestThreatClusterLocation(aiBrain, unit)
if nukePos then
IssueNuke({unit}, nukePos)
WaitSeconds(12)
IssueClearCommands({unit})
end
WaitSeconds(1)
end
end
self:PlatoonDisband()
end,
---@param self Platoon
AntiNukeAI = function(self)
self:Stop()
local platoonUnits = self:GetPlatoonUnits()
local aiBrain = self:GetBrain()
local antiNuke
--GET THE AntiNuke OUT OF THIS PLATOON
for k, v in platoonUnits do
if EntityCategoryContains(categories.STRUCTURE * categories.ANTIMISSILE * categories.TECH3, v) then
antiNuke = v
break
end
end
-- Toggle on auto build
antiNuke:SetAutoMode(true)
end,
---@param self Platoon
PauseAI = function(self)
local platoonUnits = self:GetPlatoonUnits()
local aiBrain = self:GetBrain()
for k, v in platoonUnits do
v:SetScriptBit('RULEUTC_ProductionToggle', true)
end
local econ = AIUtils.AIGetEconomyNumbers(aiBrain)
while econ.EnergyStorageRatio < 0.4 do
WaitSeconds(2)
econ = AIUtils.AIGetEconomyNumbers(aiBrain)
end
for k, v in platoonUnits do
v:SetScriptBit('RULEUTC_ProductionToggle', false)
end
self:PlatoonDisband()
end,
---## Function: ExperimentalAIHub
--- If set as a platoon's AI function, will select an appropriate behavior based on the unit type.
---@param self Platoon
---@return nil
ExperimentalAIHub = function(self)
local behaviors = import("/lua/ai/aibehaviors.lua")
local experimental = self:GetPlatoonUnits()[1]
if not experimental then
return
end
local ID = experimental.UnitId
--LOG('Starting experimental behaviour...' .. ID)
if ID == 'uel0401' then
return behaviors.FatBoyBehavior(self)
elseif ID == 'uaa0310' then
return behaviors.CzarBehavior(self)
elseif ID == 'xsa0402' then
return behaviors.AhwassaBehavior(self)
elseif ID == 'ura0401' then
return behaviors.TickBehavior(self)
end
return behaviors.BehemothBehavior(self)
end,
---## Function: GuardEngineer
--- Provides logic for platoons to guard expansion areas and engineers.
---@param self Platoon
---@param nextAIFunc? function
---@param forceGuardBase? boolean
---@return nil
GuardEngineer = function(self, nextAIFunc, forceGuardBase)
local aiBrain = self:GetBrain()
if not aiBrain:PlatoonExists(self) or not self:GetPlatoonPosition() then
return
end
local NavUtils = import("/lua/sim/navutils.lua")
local renderThread = false
self.PlatoonSurfaceThreat = self:GetPlatoonThreat('Surface', categories.ALLUNITS)
AIAttackUtils.GetMostRestrictiveLayer(self)
if forceGuardBase or not self.PlatoonData.NeverGuardBases then
--Guard the closest least-defended base
local bestBase = false
local bestBaseName = ""
local bestDistSq = 999999999
local bestDefense = 999999999
local MAIN = aiBrain.BuilderManagers.MAIN
local threatType = 'AntiSurface'
for baseName, base in aiBrain.BuilderManagers do
if baseName != 'MAIN' and (base.BaseSettings and not base.BaseSettings.NoGuards) then
if AIAttackUtils.GetSurfaceThreatOfUnits(self) <= 0 then
threatType = 'StructuresNotMex'
end
local baseDefense = aiBrain:GetThreatAtPosition(base.Position, 1, true, threatType, aiBrain:GetArmyIndex())
local distSq = VDist2Sq(MAIN.Position[1], MAIN.Position[3], base.Position[1], base.Position[3])
if baseDefense < bestDefense then
bestBase = base
bestBaseName = baseName
bestDistSq = distSq
bestDefense = baseDefense
elseif baseDefense == bestDefense then
if distSq < bestDistSq then
bestBase = base
bestBaseName = baseName
bestDistSq = distSq
end
end
end
end
local threshold = 10
if bestBase.BaseSettings then
threshold = bestBase.BaseSettings.DesiredGuardThreat or 10
end
if bestBase and bestDefense < threshold then
local path, reason = NavUtils.PathToWithThreatThreshold(self.MovementLayer, self:GetPlatoonPosition(), bestBase.Position, aiBrain, NavUtils.ThreatFunctions.AntiSurface, self.PlatoonSurfaceThreat * 10, aiBrain.IMAPConfig.Rings)
IssueClearCommands(self:GetPlatoonUnits())
if path then
local pathLength = table.getn(path)
for i=1, pathLength-1 do
self:MoveToLocation(path[i], false)
end
end
IssueGuard(self:GetPlatoonUnits(), bestBase.Position)
--self:MoveToLocation(bestBase.Position, false)
--Handle base guarding logic in this loop
local guardTime = 0
while aiBrain:PlatoonExists(self) do
--Is the threat of this base good enough?
if not forceGuardBase then
local rnd = Random(13,17)
WaitSeconds(rnd)
guardTime = guardTime + rnd
if (aiBrain:GetThreatAtPosition(bestBase.Position, 1, true, threatType, aiBrain:GetArmyIndex()) >= threshold + self:GetPlatoonThreatEx().SurfaceThreatLevel
or (self.PlatoonData.BaseGuardTimeLimit and guardTime > self.PlatoonData.BaseGuardTimeLimit)) then
--Stop guarding and guard something else.
break
end
else
--Set to permanently guard a base, and we already received our move orders.
return
end
end
end
end
if not self.PlatoonData.NeverGuardEngineers then
--Otherwise guard an engineer until it dies or our guard timer expires
local unitToGuard = false
local units = aiBrain:GetListOfUnits(categories.ENGINEER - categories.COMMAND, false)
for k,v in units do
if v.NeedGuard and not v.BeingGuarded then
unitToGuard = v
v.BeingGuarded = true
end
end
local guardTime = 0
if unitToGuard and not unitToGuard.Dead then
IssueGuard(self:GetPlatoonUnits(), unitToGuard)
while aiBrain:PlatoonExists(self) and not unitToGuard.Dead do
guardTime = guardTime + 5
WaitSeconds(5)
if self.PlatoonData.EngineerGuardTimeLimit and guardTime >= self.PlatoonData.EngineerGuardTimeLimit
or (not unitToGuard.Dead and unitToGuard.Layer == 'Seabed' and self.MovementLayer == 'Land') then
break
end
end
end
end
----Tail call into the next ai function
WaitSeconds(1)
if type(nextAIFunc) == 'function' then
return nextAIFunc(self)
end
return self:GuardEngineer(nextAIFunc, forceGuardBase)
end,
---@param self Platoon
---@return AIBrain|nil
GuardUnit = function(self)
--LOG('GuardUnit AI started...')
local aiBrain = self:GetBrain()
if not aiBrain:PlatoonExists(self) or not self:GetPlatoonPosition() then
return
end
AIAttackUtils.GetMostRestrictiveLayer(self)
local unitToGuard = false
local guardRadiusCheck = self.PlatoonData.GuardRadius or 60
local units = aiBrain:GetListOfUnits(self.PlatoonData.GuardCategory , false)
for k,v in units do
if VDist3(v:GetPosition(), self:GetPlatoonPosition()) < guardRadiusCheck then
if not v.BeingAirGuarded and self.MovementLayer == 'Air' then
unitToGuard = v
v.BeingAirGuarded = true
end
if not v.BeingLandGuarded and (self.MovementLayer == 'Land' or self.MovementLayer == 'Amphibious') then
unitToGuard = v
v.BeingLandGuarded = true
end
end
end
if not unitToGuard then
--Dont know if this works...
--unitToGuard = self:FindClosestUnit('Attack', 'Ally', true, self.PlatoonData.GuardCategory)
local units = aiBrain:GetListOfUnits(self.PlatoonData.GuardCategory , false)
for k,v in units do
if VDist3(v:GetPosition(), self:GetPlatoonPosition()) < guardRadiusCheck then
unitToGuard = v
end
end
end
local guardTime = 0
if unitToGuard and not unitToGuard.Dead then
IssueGuard(self:GetPlatoonUnits(), unitToGuard)
while aiBrain:PlatoonExists(self) and not unitToGuard.Dead do
guardTime = guardTime + 5
WaitSeconds(5)
if self.PlatoonData.GuardTimeLimit and guardTime >= self.PlatoonData.GuardTimeLimit
or (not unitToGuard.Dead and unitToGuard.Layer == 'Seabed' and self.MovementLayer == 'Land') then
break
end
end
if not unitToGuard.Dead and self.MovementLayer == 'Air' then
unitToGuard.BeingAirGuarded = false
end
if not unitToGuard.Dead and (self.MovementLayer == 'Land' or self.MovementLayer == 'Amphibious') then
unitToGuard.BeingLandGuarded = false
end
else
--LOG('GuardUnit AI .. No unit found.')
self:PlatoonDisband()
return
end
WaitSeconds(1)
return self:HuntAI()
end,
---## Function: GuardMarker
--- Will guard the location of a marker
---@param self Platoon
---@return nil
GuardMarker = function(self)
local aiBrain = self:GetBrain()
local platLoc = self:GetPlatoonPosition()
if not aiBrain:PlatoonExists(self) or not platLoc then
return
end
-----------------------------------------------------------------------
-- Platoon Data
-----------------------------------------------------------------------
-- type of marker to guard
-- Start location = 'Start Location'... see MarkerTemplates.lua for other types
local markerType = self.PlatoonData.MarkerType or 'Expansion Area'
-- what should we look for for the first marker? This can be 'Random',
-- 'Threat' or 'Closest'
local moveFirst = self.PlatoonData.MoveFirst or 'Threat'
-- should our next move be no move be (same options as before) as well as 'None'
-- which will cause the platoon to guard the first location they get to
local moveNext = self.PlatoonData.MoveNext or 'None'
-- Minimum distance when looking for closest
local avoidClosestRadius = self.PlatoonData.AvoidClosestRadius or 0
-- set time to wait when guarding a location with moveNext = 'None'
local guardTimer = self.PlatoonData.GuardTimer or 0
-- threat type to look at
local threatType = self.PlatoonData.ThreatType or 'AntiSurface'
-- should we look at our own threat or the enemy's
local bSelfThreat = self.PlatoonData.SelfThreat or false
-- if true, look to guard highest threat, otherwise,
-- guard the lowest threat specified
local bFindHighestThreat = self.PlatoonData.FindHighestThreat or false
-- minimum threat to look for
local minThreatThreshold = self.PlatoonData.MinThreatThreshold or -1
-- maximum threat to look for
local maxThreatThreshold = self.PlatoonData.MaxThreatThreshold or 99999999
-- Avoid bases (true or false)
local bAvoidBases = self.PlatoonData.AvoidBases or false
-- Radius around which to avoid the main base
local avoidBasesRadius = self.PlatoonData.AvoidBasesRadius or 0
-- Use Aggresive Moves Only
local bAggroMove = self.PlatoonData.AggressiveMove or false
local PlatoonFormation = self.PlatoonData.UseFormation or 'NoFormation'
-----------------------------------------------------------------------
local markerLocations = import("/lua/sim/markerutilities.lua").GetMarkersByType(markerType)
local NavUtils = import("/lua/sim/navutils.lua")
AIAttackUtils.GetMostRestrictiveLayer(self)
self:SetPlatoonFormationOverride(PlatoonFormation)
self.PlatoonSurfaceThreat = self:GetPlatoonThreat('Surface', categories.ALLUNITS)
local bestMarker = false
if not self.LastMarker then
self.LastMarker = {nil,nil}
end
-- look for a random marker
if moveFirst == 'Random' then
if table.getn(markerLocations) <= 2 then
self.LastMarker[1] = nil
self.LastMarker[2] = nil
end
for _,marker in RandomIter(markerLocations) do
if (self.MovementLayer == 'Land' and marker.NavLayer ~= 'Amphibious') or (self.MovementLayer == 'Water' and marker.NavLayer == 'Amphibious') then
if table.getn(markerLocations) <= 2 then
self.LastMarker[1] = nil
self.LastMarker[2] = nil
end
if self:AvoidsBases(marker.position, bAvoidBases, avoidBasesRadius) then
if self.LastMarker[1] and marker.position[1] == self.LastMarker[1][1] and marker.position[3] == self.LastMarker[1][3] then
continue
end
if self.LastMarker[2] and marker.position[1] == self.LastMarker[2][1] and marker.position[3] == self.LastMarker[2][3] then
continue
end
bestMarker = marker
break
end
end
end
elseif moveFirst == 'Threat' then
--Guard the closest least-defended marker
local bestMarkerThreat = 0
if not bFindHighestThreat then
bestMarkerThreat = 99999999
end
local bestDistSq = 99999999
-- find best threat at the closest distance
for _,marker in markerLocations do
if (self.MovementLayer == 'Land' and marker.NavLayer ~= 'Amphibious') or (self.MovementLayer == 'Water' and marker.NavLayer == 'Amphibious') then
local markerThreat
if bSelfThreat then
markerThreat = aiBrain:GetThreatAtPosition(marker.position, 0, true, threatType, aiBrain:GetArmyIndex())
else
markerThreat = aiBrain:GetThreatAtPosition(marker.position, 0, true, threatType)
end
local distSq = VDist2Sq(marker.position[1], marker.position[3], platLoc[1], platLoc[3])
if markerThreat >= minThreatThreshold and markerThreat <= maxThreatThreshold then
if self:AvoidsBases(marker.position, bAvoidBases, avoidBasesRadius) then
if self.IsBetterThreat(bFindHighestThreat, markerThreat, bestMarkerThreat) then
bestDistSq = distSq
bestMarker = marker
bestMarkerThreat = markerThreat
elseif markerThreat == bestMarkerThreat then
if distSq < bestDistSq then
bestDistSq = distSq
bestMarker = marker
bestMarkerThreat = markerThreat
end
end
end
end
end
end
else
-- if we didn't want random or threat, assume closest (but avoid ping-ponging)
local bestDistSq = 99999999
if table.getn(markerLocations) <= 2 then
self.LastMarker[1] = nil
self.LastMarker[2] = nil
end
for _,marker in markerLocations do
if (self.MovementLayer == 'Land' and marker.NavLayer ~= 'Amphibious') or (self.MovementLayer == 'Water' and marker.NavLayer == 'Amphibious') then
local distSq = VDist2Sq(marker.position[1], marker.position[3], platLoc[1], platLoc[3])
if self:AvoidsBases(marker.position, bAvoidBases, avoidBasesRadius) and distSq > (avoidClosestRadius * avoidClosestRadius) then
if distSq < bestDistSq then
if self.LastMarker[1] and marker.position[1] == self.LastMarker[1][1] and marker.position[3] == self.LastMarker[1][3] then
continue
end
if self.LastMarker[2] and marker.position[1] == self.LastMarker[2][1] and marker.position[3] == self.LastMarker[2][3] then
continue
end
bestDistSq = distSq
bestMarker = marker
end
end
end
end
end
-- did we find a threat?
local usedTransports = false
if bestMarker then
self.LastMarker[2] = self.LastMarker[1]
self.LastMarker[1] = bestMarker.position
--LOG("GuardMarker: Attacking " .. bestMarker.Name)
local path, reason = NavUtils.PathToWithThreatThreshold(self.MovementLayer, self:GetPlatoonPosition(), bestMarker.position, aiBrain, NavUtils.ThreatFunctions.AntiSurface, self.PlatoonSurfaceThreat * 10, aiBrain.IMAPConfig.Rings)
local success, bestGoalPos = AIAttackUtils.CheckPlatoonPathingEx(self, bestMarker.position)
IssueClearCommands(self:GetPlatoonUnits())
if path then
local position = self:GetPlatoonPosition()
if not success or VDist2(position[1], position[3], bestMarker.position[1], bestMarker.position[3]) > 512 then
usedTransports = TransportUtils.SendPlatoonWithTransports(aiBrain, self, bestMarker.position, 2, true)
elseif VDist2(position[1], position[3], bestMarker.position[1], bestMarker.position[3]) > 256 then
usedTransports = TransportUtils.SendPlatoonWithTransports(aiBrain, self, bestMarker.position, 1, false)
end
if not usedTransports then
local pathLength = table.getn(path)
for i=1, pathLength-1 do
if bAggroMove then
self:AggressiveMoveToLocation(path[i])
else
self:MoveToLocation(path[i], false)
end
end
end
elseif (not path and reason == 'NoPath') and self.MovementLayer ~= 'Water' then
--LOG('Guardmarker requesting transports')
local foundTransport = TransportUtils.SendPlatoonWithTransports(aiBrain, self, bestMarker.position, 3, true)
--DUNCAN - if we need a transport and we cant get one the disband
if not foundTransport then
--LOG('Guardmarker no transports')
self:PlatoonDisband()
return
end
--LOG('Guardmarker found transports')
else
self:PlatoonDisband()
return
end
if (not path or not success) and not usedTransports then
self:PlatoonDisband()
return
end
if moveNext == 'None' then
-- guard
IssueGuard(self:GetPlatoonUnits(), bestMarker.position)
-- guard forever
if guardTimer <= 0 then return end
else
-- otherwise, we're moving to the location
self:AggressiveMoveToLocation(bestMarker.position)
end