forked from FAForever/fa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimCallbacks.lua
1360 lines (1095 loc) · 40.4 KB
/
SimCallbacks.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
----
----
---- This module contains the Sim-side lua functions that can be invoked
---- from the user side. These need to validate all arguments against
---- cheats and exploits.
----
--
---- We store the callbacks in a sub-table (instead of directly in the
---- module) so that we don't include any
---@class SimCallback
---@field Func string
---@field Args table
local SimUtils = import("/lua/simutils.lua")
local SimPing = import("/lua/simping.lua")
local SimTriggers = import("/lua/scenariotriggers.lua")
local SUtils = import("/lua/ai/sorianutilities.lua")
local ScenarioFramework = import("/lua/scenarioframework.lua")
-- upvalue table operations for performance
local TableInsert = table.insert
local TableEmpty = table.empty
local TableRemove = table.remove
local TableMerged = table.merged
-- upvalue scope for performance
local type = type
local Vector = Vector
local IsEntity = IsEntity
local GetEntityById = GetEntityById
local GetSurfaceHeight = GetSurfaceHeight
local OkayToMessWithArmy = OkayToMessWithArmy
local EntityCategoryFilterDown = EntityCategoryFilterDown
local GetCurrentCommandSource = GetCurrentCommandSource
local GetSystemTimeSecondsOnlyForProfileUse = GetSystemTimeSecondsOnlyForProfileUse
local IssueClearCommands = IssueClearCommands
local IssueBuildMobile = IssueBuildMobile
local IssueAggressiveMove = IssueAggressiveMove
local IssueGuard = IssueGuard
local IssueFerry = IssueFerry
-- upvalue categories for performance
local CategoriesTransportation = categories.TRANSPORTATION
--- List of callbacks that is being populated throughout this file
---@type table<string, fun(data: table, units?: Unit[])>
local Callbacks = {}
---@param name string
---@param data table
---@param units? Unit[]
function DoCallback(name, data, units)
local start = GetSystemTimeSecondsOnlyForProfileUse()
local fn = Callbacks[name];
if fn then
fn(data, units)
else
SPEW('No callback named: ' .. tostring(name))
end
local timeTaken = GetSystemTimeSecondsOnlyForProfileUse() - start
if (timeTaken > 0.005) then
SPEW(string.format("Time to process %s from %d: %f", name, timeTaken, GetCurrentCommandSource() or -2))
end
end
--- Common utility function to retrieve the actual units.
---@param units Unit[]
---@return Unit[]
function SecureUnits(units)
local secure = {}
if units and type(units) ~= 'table' then
units = { units }
end
for _, u in units or {} do
if not IsEntity(u) then
u = GetEntityById(u)
end
if IsEntity(u) and OkayToMessWithArmy(u.Army) then
TableInsert(secure, u)
end
end
return secure
end
--- Empty callback for ui mods to communicate
Callbacks.EmptyCallback = function(data, units)
end
--- Callback takes a boolean and toggles a stat on given units between 0 and 1
---@param data table<string, boolean>
Callbacks.SetStatByCallback = function(data, units)
for stat, value in data do
if not type(value) == 'boolean' then
WARN('SetStatByCallback: received non boolean value ' ..
tostring(value) .. ' for stat ' .. tostring(stat) .. '!')
continue
end
value = (value and 1) or 0 -- numerize our bool
for _, u in units or {} do
if IsEntity(u) and OkayToMessWithArmy(u.Army) then
if not u.Blueprint.General.StatToggles or not u.Blueprint.General.StatToggles[stat] then
WARN('SetStatByCallback: ' .. tostring(stat) .. ' is not a valid stat for this unit!')
continue
end
u:UpdateStat(stat, value)
end
end
end
end
Callbacks.AutoOvercharge = function(data, units)
for _, u in units or {} do
if IsEntity(u) and OkayToMessWithArmy(u.Army) and u.SetAutoOvercharge then
u:SetAutoOvercharge(data.auto == true)
end
end
end
Callbacks.PersistFerry = function(data, units)
local transports = EntityCategoryFilterDown(CategoriesTransportation, SecureUnits(units))
if TableEmpty(transports) then return end
local start = data.route[1]
-- function CreateUnit(blueprint, army, tx, ty, tz, qx, qy, qz, qw, [layer])
local helper = CreateUnit('hel0001', units[1].Army, start[1], start[2], start[3], 1, 1, 1, 1, 'Air')
TableInsert(units, helper)
IssueClearCommands(units)
for _, r in data.route do
IssueFerry(units, r)
end
end
Callbacks.ClearCommands = function(data, units)
local safe = SecureUnits(data.ids or units)
IssueClearCommands(safe)
end
Callbacks.BreakAlliance = SimUtils.BreakAlliance
Callbacks.GiveUnitsToPlayer = SimUtils.GiveUnitsToPlayer
Callbacks.GiveResourcesToPlayer = SimUtils.GiveResourcesToPlayer
Callbacks.SetResourceSharing = SimUtils.SetResourceSharing
Callbacks.RequestAlliedVictory = SimUtils.RequestAlliedVictory
Callbacks.SetOfferDraw = SimUtils.SetOfferDraw
Callbacks.SetRecallVote = import("/lua/sim/recall.lua").SetRecallVote
Callbacks.SpawnPing = SimPing.SpawnPing
--Nuke Ping
Callbacks.SpawnSpecialPing = SimPing.SpawnSpecialPing
Callbacks.UpdateMarker = SimPing.UpdateMarker
Callbacks.FactionSelection = ScenarioFramework.OnFactionSelect
Callbacks.ToggleSelfDestruct = import("/lua/selfdestruct.lua").ToggleSelfDestruct
Callbacks.MarkerOnScreen = import("/lua/simcameramarkers.lua").MarkerOnScreen
Callbacks.SimDialogueButtonPress = import("/lua/simdialogue.lua").OnButtonPress
Callbacks.AIChat = SUtils.FinishAIChat
Callbacks.DiplomacyHandler = import("/lua/simdiplomacy.lua").DiplomacyHandler
Callbacks.Rebuild = function(data, units)
local wreck = GetEntityById(data.entity)
if not wreck.AssociatedBP then return end
local units = SecureUnits(units)
if not units[1] then return end
if data.Clear then
IssueClearCommands(units)
end
wreck:Rebuild(units)
end
--Callbacks.GetUnitHandle = import("/lua/debugai.lua").GetHandle
function Callbacks.OnMovieFinished(name)
ScenarioInfo.DialogueFinished[name] = true
end
Callbacks.OnControlGroupAssign = function(units)
if ScenarioInfo.tutorial then
local function OnUnitKilled(unit)
if ScenarioInfo.ControlGroupUnits then
for i, v in ScenarioInfo.ControlGroupUnits do
if unit == v then
TableRemove(ScenarioInfo.ControlGroupUnits, i)
end
end
end
end
if not ScenarioInfo.ControlGroupUnits then
ScenarioInfo.ControlGroupUnits = {}
end
-- add units to list
local entities = {}
for k, v in units do
TableInsert(entities, GetEntityById(v))
end
ScenarioInfo.ControlGroupUnits = TableMerged(ScenarioInfo.ControlGroupUnits, entities)
-- remove units on death
for k, v in entities do
SimTriggers.CreateUnitDeathTrigger(OnUnitKilled, v)
SimTriggers.CreateUnitReclaimedTrigger(OnUnitKilled, v) --same as killing for our purposes
end
end
end
local SimCamera = import("/lua/simcamera.lua")
Callbacks.OnCameraFinish = SimCamera.OnCameraFinish
local SimPlayerQuery = import("/lua/simplayerquery.lua")
Callbacks.OnPlayerQuery = SimPlayerQuery.OnPlayerQuery
Callbacks.OnPlayerQueryResult = SimPlayerQuery.OnPlayerQueryResult
Callbacks.PingGroupClick = import("/lua/simpinggroup.lua").OnClickCallback
---@param unit Unit
---@param target? Unit
---@return boolean
function IsInvalidAssist(unit, target)
if target and target.EntityId == unit.EntityId then
return true
elseif not target or not target:GetGuardedUnit() then
return false
else
return IsInvalidAssist(unit, target:GetGuardedUnit())
end
end
--- Detect and fix a simulation freeze by clearing the command queue of all factories that take part in a cycle
---@param data { target: EntityId}
---@param units any
Callbacks.ValidateAssist = function(data, units)
units = SecureUnits(units)
local target = GetEntityById(data.target)
if units and target then
for k, u in units do
if IsEntity(u) and u.Army == target.Army and IsInvalidAssist(u, target) then
IssueToUnitClearCommands(target)
return
end
end
end
end
Callbacks.AttackMove = function(data, units)
-- exclude structures as it makes no sense to apply a move command to them
local allNonStructures = EntityCategoryFilterDown(categories.ALLUNITS - categories.STRUCTURE, units)
if data.Clear then
IssueClearCommands(allNonStructures)
end
IssueAggressiveMove(allNonStructures, data.Target)
end
--tells a unit to toggle its pointer
Callbacks.FlagShield = function(data, units)
units = SecureUnits(units)
local target = GetEntityById(data.target)
if units and target then
for k, u in units do
if IsEntity(u) and u.PointerEnabled == true then
u.PointerEnabled = false --turn the pointer flag off
u:DisablePointer() --turn the pointer off
end
end
end
end
-------------------------------------------------------------------------------
--#region General orders
---@param data { }
---@param selection Unit[]
Callbacks.SelfDestruct = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- suppress self destruct in tutorial missions as they screw up the mission
if ScenarioInfo.tutorial then
return
end
import("/lua/sim/commands/self-destruct.lua").RingExtractor(selection, true)
end
--#endregion
-------------------------------------------------------------------------------
--#region Advanced orders
Callbacks.WeaponPriorities = import("/lua/weaponpriorities.lua").SetWeaponPriorities
---@param data { target: EntityId }
---@param selection Unit[]
Callbacks.RingWithStorages = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify we have engineers
local engineers = EntityCategoryFilterDown(categories.ENGINEER, selection)
if TableEmpty(engineers) then
return
end
-- verify the extractor
local extractor = GetUnitById(data.target) --[[@as Unit]]
if (not extractor) or
(not extractor.Army) or
(not OkayToMessWithArmy(extractor.Army)) or
(not EntityCategoryContains(categories.MASSEXTRACTION, extractor))
then
return
end
import("/lua/sim/commands/ringing/ring-with-storages.lua").RingExtractor(extractor, engineers)
end
---@param data { target: EntityId, allFabricators: boolean }
---@param selection Unit[]
Callbacks.RingWithFabricators = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify we have engineers
local engineers = EntityCategoryFilterDown(categories.ENGINEER, selection)
if TableEmpty(engineers) then
return
end
-- verify the extractor
local extractor = GetUnitById(data.target) --[[@as Unit]]
if (not extractor) or
(not extractor.Army) or
(not OkayToMessWithArmy(extractor.Army)) or
(not EntityCategoryContains(categories.MASSEXTRACTION, extractor))
then
return
end
import("/lua/sim/commands/ringing/ring-with-fabricators.lua").RingExtractor(extractor, engineers, data.allFabricators)
end
---@param data { target: EntityId }
---@param selection Unit[]
Callbacks.RingRadar = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify we have engineers
local engineers = EntityCategoryFilterDown(categories.ENGINEER, selection)
if TableEmpty(engineers) then
return
end
-- verify the extractor
local target = GetUnitById(data.target) --[[@as Unit]]
if (not target) or
(not target.Army) or
(not OkayToMessWithArmy(target.Army)) or
(not EntityCategoryContains((categories.RADAR + categories.OMNI) * categories.STRUCTURE, target))
then
return
end
import("/lua/sim/commands/ringing/ring-with-power-tech1.lua").RingWithPower(target, engineers)
end
---@param data { target: EntityId }
---@param selection Unit[]
Callbacks.RingArtilleryTech2 = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify we have engineers
local engineers = EntityCategoryFilterDown(categories.ENGINEER, selection)
if TableEmpty(engineers) then
return
end
-- verify the extractor
local target = GetUnitById(data.target) --[[@as Unit]]
if (not target) or
(not target.Army) or
(not OkayToMessWithArmy(target.Army)) or
(not EntityCategoryContains(categories.ARTILLERY * categories.TECH2 * categories.STRUCTURE, target))
then
return
end
import("/lua/sim/commands/ringing/ring-with-power-tech1.lua").RingWithPower(target, engineers)
end
---@param data { target: EntityId }
---@param selection Unit[]
Callbacks.RingArtilleryTech3Exp = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify we have engineers
local engineers = EntityCategoryFilterDown(categories.ENGINEER, selection)
if TableEmpty(engineers) then
return
end
-- verify the extractor
local target = GetUnitById(data.target) --[[@as Unit]]
if (not target) or
(not target.Army) or
(not OkayToMessWithArmy(target.Army)) or
(
not
EntityCategoryContains(categories.ARTILLERY * (categories.TECH3 + categories.EXPERIMENTAL) *
categories.STRUCTURE, target))
then
return
end
import("/lua/sim/commands/ringing/ring-with-power-tech3.lua").RingWithPower(target, engineers)
end
---@param data any
---@param selection Unit[]
Callbacks.SelectHighestEngineerAndAssist = function(data, selection)
if selection then
-- check for cheats
local target = GetUnitById(data.TargetId) --[[@as Unit]]
if not target or not target.Army then return end
if not OkayToMessWithArmy(target.Army) then return end
local noACU = EntityCategoryFilterDown(categories.ALLUNITS - categories.COMMAND, selection)
IssueClearCommands(noACU)
IssueGuard(noACU, target)
end
end
do
-- upvalue for performance
local EntityCategoryFilterDown = EntityCategoryFilterDown
local IssueClearCommands = IssueClearCommands
local IssueUpgrade = IssueUpgrade
local cxrb0104 = categories.xrb0104
local cxrb0204 = categories.xrb0204
--- Forces hives in the selection to upgrade immediately
---@param data {UpgradeTo: string} what we want to upgrade to, should be 'xrb0204' or 'xrb0304'
---@param units Unit[] selected units
Callbacks.ImmediateHiveUpgrade = function(data, units)
-- make sure we have valid units
units = SecureUnits(units)
-- find t1 / t2 hives
local xrb0104 = EntityCategoryFilterDown(cxrb0104, units)
local xrb0204 = EntityCategoryFilterDown(cxrb0204, units)
-- upgrade tech 1 hives
if xrb0104[1] then
-- oof for performance, but this doesn't get run that often
local notUpgradingh = 1
local notUpgrading = {}
local upgradingh = 1
local upgrading = {}
-- split between upgrading / and not upgrading hives for different behavior
for k, unit in xrb0104 do
if not unit:IsUnitState('Upgrading') then
notUpgrading[notUpgradingh] = unit
notUpgradingh = notUpgradingh + 1
else
upgrading[upgradingh] = unit
upgradingh = upgradingh + 1
end
end
-- always clear things out
IssueClearCommands(notUpgrading)
-- upgrading to t2 from t1
if data.UpgradeTo == "xrb0204" then
IssueUpgrade(notUpgrading, "xrb0204")
-- upgrading to t3 from t1
elseif data.UpgradeTo == "xrb0304" then
IssueUpgrade(notUpgrading, "xrb0204")
IssueUpgrade(xrb0104, "xrb0304")
end
end
-- upgrade tech 2 hives
if xrb0204[1] then
-- always clear things out
if data.ClearCommands then
IssueClearCommands(xrb0204)
end
-- upgrading to t3 form t1
if data.UpgradeTo == "xrb0304" then
IssueUpgrade(xrb0204, "xrb0304")
end
end
end
end
do
--- Processes the orders and re-distributes them over the units
---@param data { Target: EntityId, ClearCommands: boolean }
---@param selection Unit[]
Callbacks.DistributeOrders = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify the target
local target = (data.Target and GetUnitById(data.Target)) --[[@as Unit]]
if (not target) or
(not target.Army) or
(not OkayToMessWithArmy(target.Army))
then
return
end
import("/lua/sim/commands/distribute-queue.lua").DistributeOrders(selection, target, data.ClearCommands or false
, true)
end
end
do
--- Processes the orders and re-distributes them over the units
---@param data { Target: EntityId, ClearCommands: boolean }
---@param selection Unit[]
Callbacks.CopyOrders = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify the target
local target = GetUnitById(data.Target) --[[@as Unit]]
if (not target) or
(not target.Army) or
(not OkayToMessWithArmy(target.Army))
then
return
end
import("/lua/sim/commands/copy-queue.lua").CopyOrders(selection, target, data.ClearCommands or false, true)
end
end
do
---@param data { ClearCommands: boolean }
---@param selection Unit[]
Callbacks.LoadIntoTransports = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
local transports = EntityCategoryFilterDown(categories.TRANSPORTATION, selection)
local transportees = EntityCategoryFilterDown(categories.ALLUNITS - (categories.AIR + categories.TRANSPORTATION)
, selection)
local transportedUnits, transportsUsed, remUnits, remTransports = import("/lua/sim/commands/load-in-transport.lua")
.LoadIntoTransports(transportees, transports, data.ClearCommands or false, true)
end
end
do
local CommandSourceGuards = {}
---@param data { }
---@param selection Unit[]
Callbacks.AbortNavigation = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
if (GetFocusArmy() == GetCurrentCommandSource()) then
print("Unable to interrupt path finding")
end
return
end
-- only apply this to engineers
local engineers = EntityCategoryFilterDown(categories.ENGINEER + categories.COMMAND, selection)
if table.empty(engineers) then
if (GetFocusArmy() == GetCurrentCommandSource()) then
print("Unable to interrupt path finding")
end
return
end
-- prevent automation
local gameTick = GetGameTick()
local commandSource = GetCurrentCommandSource()
local commandSourceGuard = CommandSourceGuards[commandSource]
if commandSourceGuard and commandSourceGuard + 5 >= gameTick then
if (GetFocusArmy() == GetCurrentCommandSource()) then
print("Unable to interrupt path finding")
end
return
end
CommandSourceGuards[commandSource] = gameTick
-- perform the command
import("/lua/sim/commands/abort-navigation.lua").AbortNavigation(engineers, true)
end
end
do
local CommandSourceGuards = {}
---@param data { }
---@param selection Unit[]
Callbacks.DischargeShields = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
if (GetFocusArmy() == GetCurrentCommandSource()) then
print("Unable to discharge")
end
return
end
-- only apply this to units with shields
local shead = 1
local unitsWithShields = {}
for k = 1, table.getn(selection) do
local unit = selection[k]
if unit.MyShield then
unitsWithShields[shead] = unit
shead = shead + 1
end
end
if table.empty(unitsWithShields) then
if (GetFocusArmy() == GetCurrentCommandSource()) then
print("Unable to discharge")
end
return
end
-- prevent automation
local gameTick = GetGameTick()
local commandSource = GetCurrentCommandSource()
local commandSourceGuard = CommandSourceGuards[commandSource]
if commandSourceGuard and commandSourceGuard + 5 >= gameTick then
if (GetFocusArmy() == GetCurrentCommandSource()) then
print("Unable to discharge")
end
return
end
CommandSourceGuards[commandSource] = gameTick
-- perform the command
import("/lua/sim/commands/discharge-shields.lua").DischargeShields(unitsWithShields, true)
end
end
do
local Width = import("/lua/shared/commands/area-reclaim-order.lua").MaximumWidth
local MaximumDistance = import("/lua/shared/commands/area-reclaim-order.lua").MaximumDistance
---@param data { Origin: number, Destination: Vector}
---@param selection Unit[]
Callbacks.ExtendReclaimOrder = function(data, selection)
do -- feature: area commands
return
end
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify the command queue
local unit = selection[1]
local queue = unit:GetCommandQueue()
local lastCommand = queue[table.getn(queue)]
if not (lastCommand and lastCommand.commandType == 19 and lastCommand.target) then
return
end
local ps = lastCommand.target:GetPosition()
local pe = data.Destination
local dx = pe[1] - ps[1]
local dz = pe[3] - ps[3]
local distance = math.sqrt(dx * dx + dz * dz)
-- limit the maximum distance
if distance > MaximumDistance then
pe[1] = (1 / distance) * MaximumDistance * dx + ps[1]
pe[3] = (1 / distance) * MaximumDistance * dz + ps[3]
end
-- radius = math.min(distance, maximumDistance)
-- local width = 5
-- local ox = nz
-- local oz = -nx
-- DrawCircle(ps, 1, 'ffffff')
-- DrawCircle(pe, 1, 'ffffff')
-- local ps1 = { ps[1] + width * ox, ps[2], ps[3] + width * oz }
-- local ps2 = { ps[1] - width * ox, ps[2], ps[3] - width * oz }
-- DrawCircle(ps1, 1, 'ffffff')
-- DrawCircle(ps2, 1, 'ffffff')
-- local pe1 = { pe[1] + width * ox, pe[2], pe[3] + width * oz }
-- local pe2 = { pe[1] - width * ox, pe[2], pe[3] - width * oz }
-- DrawCircle(pe1, 1, 'ffffff')
-- DrawCircle(pe2, 1, 'ffffff')
local start = GetSystemTimeSecondsOnlyForProfileUse()
import("/lua/sim/commands/area-reclaim-order.lua").AreaReclaimProps(selection, ps, pe, Width, true)
SPEW("Time taken for area reclaim order: ", 1000 * (GetSystemTimeSecondsOnlyForProfileUse() - start),
"miliseconds")
end
---@param data table
---@param selection Unit[]
Callbacks.ExtendAttackOrder = function(data, selection)
-- verify selection
selection = SecureUnits(selection)
if (not selection) or TableEmpty(selection) then
return
end
-- verify the command queue
local unit = selection[1]
local queue = unit:GetCommandQueue()
local lastCommand = queue[table.getn(queue)]
if not (lastCommand and lastCommand.commandType == 10) or lastCommand.target then
return
end
local target = lastCommand.target --[[@as Unit | Prop]]
local start = GetSystemTimeSecondsOnlyForProfileUse()
import("/lua/sim/commands/area-attack-ground-order.lua").AreaAttackOrder(selection,
{ lastCommand.x, lastCommand.y, lastCommand.z }, data.Radius)
SPEW("Time taken for area attack order: ", 1000 * (GetSystemTimeSecondsOnlyForProfileUse() - start), "miliseconds")
end
end
--#endregion
-------------------------------------------------------------------------------
--#region Development / debug related functionality
--- An anti cheat check that passes when there is only 1 player or cheats are enabled
---@return boolean
local PassesAntiCheatCheck = function()
-- allow when cheats are enabled
return CheatsEnabled()
end
--- A simplified check that also passes when the game has AIs
---@return boolean
local PassesAIAntiCheatCheck = function()
-- allow when there are AIs
if ScenarioInfo.GameHasAIs then
return true
end
-- allow when cheats are enabled
return PassesAntiCheatCheck()
end
local SpawnedMeshes = {}
local function SpawnUnitMesh(id, x, y, z, pitch, yaw, roll)
local bp = __blueprints[id]
local bpD = bp.Display
if __blueprints[bpD.MeshBlueprint] then
SPEW("Spawning mesh of " .. id)
local entity = import('/lua/sim/Entity.lua').Entity()
if bp.CollisionOffsetY and bp.CollisionOffsetY < 0 then
y = y - bp.CollisionOffsetY
end
entity:SetPosition(Vector(x, y, z), true)
entity:SetMesh(bpD.MeshBlueprint)
entity:SetDrawScale(bpD.UniformScale)
entity:SetVizToAllies 'Intel'
entity:SetVizToNeutrals 'Intel'
entity:SetVizToEnemies 'Intel'
table.insert(SpawnedMeshes, entity)
return entity
else
SPEW("Can\' spawn mesh of " .. id .. " no mesh found")
end
end
local function SetWorldCameraToUnitIconAngle(location, zoom)
local sx = 1 / 6
local th = 1 + (location[2] - GetSurfaceHeight(location[1], location[3]))
-- Note: The maths for setting zoom is kinda all over the place, and is just 'good enough' for what I used it for.
--_ALERT(location[2], GetSurfaceHeight(location[1], location[3]), th)
--_ALERT(zoom, th)
Sync.CameraRequests = Sync.CameraRequests or {}
table.insert(Sync.CameraRequests, {
Name = 'WorldCamera',
Type = 'CAMERA_UNIT_SPIN',
Marker = {
orientation = VECTOR3(math.pi * (1 + sx), math.pi * sx, 0),
position = location,
zoom = FLOAT(zoom * th),
},
HeadingRate = 0,
Callback = {
Func = 'OnCameraFinish',
Args = 'WorldCamera',
}
})
end
local function ShowRaisedPlatforms(self)
local plats = self:GetBlueprint().Physics.RaisedPlatforms
if not plats then return end
local pos = self:GetPosition()
local entities = {}
for i = 1, (table.getn(plats) / 12) do
entities[i] = {}
for b = 1, 4 do
entities[i][b] = import('/lua/sim/Entity.lua').Entity { Owner = self }
self.Trash:Add(entities[i][b])
entities[i][b]:SetPosition(Vector(
pos[1] + plats[((i - 1) * 12) + (b * 3) - 2],
pos[2] + plats[((i - 1) * 12) + (b * 3)],
pos[3] + plats[((i - 1) * 12) + (b * 3) - 1]
), true)
end
self.Trash:Add(AttachBeamEntityToEntity(entities[i][1], -2, entities[i][2], -2, self:GetArmy(),
'/effects/emitters/build_beam_01_emit.bp'))
self.Trash:Add(AttachBeamEntityToEntity(entities[i][1], -2, entities[i][3], -2, self:GetArmy(),
'/effects/emitters/build_beam_01_emit.bp'))
self.Trash:Add(AttachBeamEntityToEntity(entities[i][4], -2, entities[i][2], -2, self:GetArmy(),
'/effects/emitters/build_beam_01_emit.bp'))
self.Trash:Add(AttachBeamEntityToEntity(entities[i][4], -2, entities[i][3], -2, self:GetArmy(),
'/effects/emitters/build_beam_01_emit.bp'))
end
end
Callbacks.ClearSpawnedMeshes = function()
if not PassesAntiCheatCheck() then
return
end
for i, v in SpawnedMeshes do
v:Destroy()
end
SpawnedMeshes = {}
end
Callbacks.CheatBoxSpawnProp = function(data)
if not PassesAntiCheatCheck() then
return
end
local offsetX = data.bpId.SizeX or 1
local offsetZ = data.bpId.SizeZ or 1
local squareX = math.ceil(math.sqrt(data.count or 1))
local squareZ = math.ceil((data.count or 1) / squareX)
local startOffsetX = (squareX - 1) * 0.5 * offsetX
local startOffsetZ = (squareZ - 1) * 0.5 * offsetZ
for i = 1, (data.count or 1) do
local x = data.pos[1] - startOffsetX + math.mod(i, squareX) * offsetX
local z = data.pos[3] - startOffsetZ + math.mod(math.floor(i / squareX), squareZ) * offsetZ
if data.rand and data.rand ~= 0 then
x = (x - data.rand * 0.5) + data.rand * Random()
z = (z - data.rand * 0.5) + data.rand * Random()
if math.mod(data.yaw or 0, 360) == 0 then
data.yaw = 360 * Random()
end
end
CreatePropHPR(data.bpId, x, GetTerrainHeight(x, z), z, data.yaw or 0, 0, 0) --blueprint, x, y, z, heading, pitch, roll
end
end
Callbacks.CheatSpawnUnit = function(data)
if not PassesAntiCheatCheck() then
return
end
local pos = data.pos
if data.MeshOnly then
SpawnUnitMesh(data.bpId, pos[1], pos[2], pos[3], 0, data.yaw, 0)
else
-- allow creating multiple units to make it easier to test specific scenarios
for i = 1, (data.count or 1) do
local unit = CreateUnitHPR(data.bpId, data.army, pos[1], pos[2], pos[3], 0, data.yaw, 0)
local unitbp = __blueprints[data.bpId]
if data.CreateTarmac and unit.CreateTarmac and unitbp.Display and unitbp.Display.Tarmacs then
unit:CreateTarmac(true, true, true, false, false)
end
if data.UnitIconCameraMode then
local size = math.max(
(unitbp.SizeX or 1),
(unitbp.SizeY or 1) * 3,
(unitbp.SizeZ or 1),
(unitbp.Physics.SkirtSizeX or 1),
(unitbp.Physics.SkirtSizeZ or 1)
) + math.abs(unitbp.CollisionOffsetY or 0)
local dist = size / math.tan(60 --[[* (9/16)]] * 0.5 * ((math.pi * 2) / 360))
SetWorldCameraToUnitIconAngle(pos, dist)
end
if data.veterancy and data.veterancy ~= 0 and unit.SetVeterancy then
unit:SetVeterancy(data.veterancy)
end
if data.ShowRaisedPlatforms then
ShowRaisedPlatforms(unit)
end
end
end
end
--- Toggles the profiler on / off
Callbacks.ToggleProfiler = function(data)
if not PassesAIAntiCheatCheck() then
return
end
import("/lua/sim/profiler.lua").ToggleProfiler(data.Army, data.ForceEnable or false)
end
-- Allows searching for benchmarks
Callbacks.FindBenchmarks = function(data)
if not PassesAIAntiCheatCheck() then
return
end