forked from FAForever/fa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScenarioFramework.lua
2354 lines (2111 loc) · 74.2 KB
/
ScenarioFramework.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/scenarioFramework.lua
-- Authors : John Comes, Drew Staltman
-- Summary : Functions for use in the scenario scripts.
-- Copyright © 2005 Gas Powered Games, Inc. All rights reserved.
-----------------------------------------------------------------
---@class Dialogue : SoundBlueprint
---@field duration number
---@field text string
---@field vid string
---@field delay number
---@field faction string
---@class DialogueTable : table<Dialogue>
---@field Callback? fun()
---@field Critical? boolean
---@field Flushed boolean
---@class MovieTable
---@field [1] string path/name
---@field [2] string bank
---@field [3] string cue
---@field [4] string faction
local SyncVoice = import("/lua/simsyncutils.lua").SyncVoice
local CategoryToString = import("/lua/sim/categoryutils.lua").ToString
local Cinematics = import("/lua/cinematics.lua")
local Game = import("/lua/game.lua")
local ScenarioUtils = import("/lua/sim/scenarioutilities.lua")
local SimCamera = import("/lua/simcamera.lua").SimCamera
local SimUIVars = import("/lua/sim/simuistate.lua")
local TriggerFile = import("/lua/scenariotriggers.lua")
local VizMarker = import("/lua/sim/vizmarker.lua").VizMarker
Objectives = import("/lua/simobjectives.lua")
PingGroups = import("/lua/simpinggroup.lua")
---@class Team
---@field ArmyCount number
---@field Armies string[] names of armies in team
---@field LastRecallVoteTime number game tick of last recall vote
local PauseUnitDeathActive = false
--- Causes the game to exit immediately
function ExitGame()
Sync.RequestingExit = true
end
--- Ends an operation
---@param success boolean instructs UI which dialog to show
---@param allPrimary boolean
---@param allSecondary boolean
---@param allBonus boolean
function EndOperation(success, allPrimary, allSecondary, allBonus)
local opFile = string.gsub(ScenarioInfo.Options.ScenarioFile, 'scenario', 'operation')
local opData
if DiskGetFileInfo(opFile) then
opData = import(opFile)
end
import("/lua/sim/matchstate.lua").CallEndGame() -- We need this here to populate the score screen
ForkThread(function()
WaitSeconds(3) -- Wait for the stats to be synced
UnlockInput()
EndOperationT {
success = success,
difficulty = ScenarioInfo.Options.Difficulty,
allPrimary = allPrimary,
allSecondary = allSecondary,
allBonus = allBonus,
faction = ScenarioInfo.LocalFaction,
opData = opData.operationData
}
end)
end
---@alias FactionSelectData {Faction: "aeon" | "cybran" | "uef"}
local factionCallbacks = {}
--- Pops up a dialog to ask the user what faction they want to play
---@param callback fun(data: FactionSelectData)
function RequestPlayerFaction(callback)
Sync.RequestPlayerFaction = true
if callback then
table.insert(factionCallbacks, callback)
end
end
--- Hook for player requested faction
---@param data FactionSelectData
function OnFactionSelect(data)
if ScenarioInfo.campaignInfo then
ScenarioInfo.campaignInfo.campaignID = data.Faction
end
if not table.empty(factionCallbacks) then
for _, callback in factionCallbacks do
if callback then
callback(data)
end
end
else
WARN('I chose ', data.Faction, ' but I dont have a callback set!')
end
end
--- Ends an operation where the data is already provided in table form (just a wrapper for sync)
---@param opData table
function EndOperationT(opData)
Sync.OperationComplete = opData
end
CreateAreaTrigger = TriggerFile.CreateAreaTrigger
CreateMultipleAreaTrigger = TriggerFile.CreateMultipleAreaTrigger
local timerThread = nil
--- Creates a timer that runs `callback` after `seconds` have passed, calling `onTickSecond` with
--- the current number of seconds left on the timer if `doOnTickSecond` is set. This includes the
--- starting duration, but also 0--note that this adds an extra second.
--- If `name` is supplied, the callback is called with TriggerManager and the name as arguments.
---@param callback function
---@param seconds number
---@param name? string
---@param doOnTickSecond? boolean
---@param onTickSecond? fun(seconds: number)
---@return thread
function CreateTimerTrigger(callback, seconds, name, doOnTickSecond, onTickSecond)
timerThread = TriggerFile.CreateTimerTrigger(callback, seconds, name, doOnTickSecond, onTickSecond)
return timerThread
end
--- Stops the last timer set by `CreateTimerTrigger` and resets the objective timer
function ResetUITimer()
if timerThread then
Sync.ObjectiveTimer = 0
KillThread(timerThread)
end
end
CreateUnitDamagedTrigger = TriggerFile.CreateUnitDamagedTrigger
---
---@param callback any
---@param aiBrain AIBrain
---@param category EntityCategory
---@param percent number
function CreateUnitPercentageBuiltTrigger(callback, aiBrain, category, percent)
aiBrain:AddUnitBuiltPercentageCallback(callback, category, percent)
end
CreateUnitDeathTrigger = TriggerFile.CreateUnitDeathTrigger
--- Sets a unit's death to be paused. It is unpaused globally, since this usually only
--- happens to one unit at a time (e.g. the camera zooms in an ACU before it explodes)
---@param unit Unit
function PauseUnitDeath(unit)
if unit and not unit.Dead then
unit.OnKilled = OverrideKilled
unit.CanBeKilled = false
unit.DoTakeDamage = OverrideDoDamage
end
end
--- An override for `Unit.DoTakeDamage` to hold on to the final blow and then release it
--- on the unit once its death is unpaused
---@param self Unit
---@param instigator Unit
---@param amount number
---@param vector any
---@param damageType DamageType
function OverrideDoDamage(self, instigator, amount, vector, damageType)
local preAdjHealth = self:GetHealth()
self:AdjustHealth(instigator, -amount)
local health = self:GetHealth()
if (health <= 0 or amount > preAdjHealth) and not self.KilledFlag then
self.KilledFlag = true
if damageType == 'Reclaimed' then
self:Destroy()
else
local excessDamageRatio = 0.0
-- Calculate the excess damage amount
local excess = preAdjHealth - amount
local maxHealth = self:GetMaxHealth()
if excess < 0 and maxHealth > 0 then
excessDamageRatio = -excess / maxHealth
end
IssueClearCommands({self})
ForkThread(UnlockAndKillUnitThread, self, instigator, damageType, excessDamageRatio)
end
end
end
function UnlockAndKillUnitThread(self, instigator, damageType, excessDamageRatio)
self:DoUnitCallbacks('OnKilled')
while PauseUnitDeathActive do
WaitSeconds(1)
end
self.CanBeKilled = true
self:Kill(instigator, damageType, excessDamageRatio)
end
--- An override for `Unit.OnKilled` to make unit death pausing work
---@param self Unit
---@param instigator Unit
---@param type any
---@param overkillRatio number
function OverrideKilled(self, instigator, type, overkillRatio)
if not self.CanBeKilled then
self:DoTakeDamage(instigator, 1000000, nil, 'Normal')
return
end
self.Dead = true
local bp = self:GetBlueprint()
if self.Layer == 'Water' and bp.Physics.MotionType == 'RULEUMT_Hover' then
self:PlayUnitSound('HoverKilledOnWater')
end
if self.Layer == 'Land' and bp.Physics.MotionType == 'RULEUMT_AmphibiousFloating' then
self:PlayUnitSound('AmphibiousFloatingKilledOnLand')
else
self:PlayUnitSound('Killed')
end
-- If factory, destroy what I'm building if I die
if EntityCategoryContains(categories.FACTORY, self) then
if self.UnitBeingBuilt and not self.UnitBeingBuilt.Dead and self.UnitBeingBuilt:GetFractionComplete() ~= 1 then
self.UnitBeingBuilt:Kill()
end
end
if self.PlayDeathAnimation and not self:IsBeingBuilt() then
self:ForkThread(self.PlayAnimationThread, 'AnimationDeath')
self:SetCollisionShape('None')
end
self:DestroyTopSpeedEffects()
if self.UnitBeingTeleported and not self.UnitBeingTeleported.Dead then
self.UnitBeingTeleported:Destroy()
self.UnitBeingTeleported = nil
end
-- Notify instigator that you killed me.
if instigator and IsUnit(instigator) then
instigator:OnKilledUnit(self)
end
if self.DeathWeaponEnabled ~= false then
self:DoDeathWeapon()
end
self:DisableShield()
self:DisableUnitIntel('Killed')
self:ForkThread(self.DeathThread, overkillRatio, instigator)
end
---
---@param unit Unit
---@param army number
---@param triggerOnGiven boolean
---@return Unit
function GiveUnitToArmy(unit, army, triggerOnGiven)
-- Shared army mod will result in different players having the same army number
if unit.Army == army then
return unit
end
-- We need the brain to ignore army cap when transferring the unit
-- do all necessary steps to set brain to ignore, then un-ignore if necessary the unit cap
unit.IsBeingTransferred = true
SetIgnoreArmyUnitCap(army, true)
IgnoreRestrictions(true)
local newUnit = ChangeUnitArmy(unit, army)
local newBrain = ArmyBrains[army]
if not newBrain.IgnoreArmyCaps then
SetIgnoreArmyUnitCap(army, false)
end
IgnoreRestrictions(false)
if triggerOnGiven then
unit:OnGiven(newUnit)
end
return newUnit
end
-- When `unit` is killed, reclaimed, or captured it will call the `callback` function provided
---@param callback fun(self: Unit, source: Unit)
---@param unit Unit
function CreateUnitDestroyedTrigger(callback, unit)
CreateUnitReclaimedTrigger(callback, unit)
CreateUnitCapturedTrigger(callback, nil, unit)
CreateUnitDeathTrigger(callback, unit)
end
CreateUnitGivenTrigger = TriggerFile.CreateUnitGivenTrigger
CreateUnitBuiltTrigger = TriggerFile.CreateUnitBuiltTrigger
CreateUnitCapturedTrigger = TriggerFile.CreateUnitCapturedTrigger
CreateUnitStartBeingCapturedTrigger = TriggerFile.CreateUnitStartBeingCapturedTrigger
CreateUnitStopBeingCapturedTrigger = TriggerFile.CreateUnitStopBeingCapturedTrigger
CreateUnitFailedBeingCapturedTrigger = TriggerFile.CreateUnitFailedBeingCapturedTrigger
CreateUnitStartCaptureTrigger = TriggerFile.CreateUnitStartCaptureTrigger
CreateUnitStopCaptureTrigger = TriggerFile.CreateUnitStopCaptureTrigger
CreateUnitFailedCaptureTrigger = TriggerFile.CreateUnitFailedCaptureTrigger
CreateUnitReclaimedTrigger = TriggerFile.CreateUnitReclaimedTrigger
CreateUnitStartReclaimTrigger = TriggerFile.CreateUnitStartReclaimTrigger
CreateUnitStopReclaimTrigger = TriggerFile.CreateUnitStopReclaimTrigger
CreateUnitVeterancyTrigger = TriggerFile.CreateUnitVeterancyTrigger
CreateGroupDeathTrigger = TriggerFile.CreateGroupDeathTrigger
-- When all units in `platoon` are destroyed, `callback` will be called
---@param callback fun(brain: AIBrain, platoon: Platoon)
---@param platoon Platoon
function CreatePlatoonDeathTrigger(callback, platoon)
platoon:AddDestroyCallback(callback)
end
CreateSubGroupDeathTrigger = TriggerFile.CreateSubGroupDeathTrigger
-- Checks if units of `cat` are within the provided rectangle
---@param cat EntityCategory
---@param area Area | Rectangle
---@return boolean
function UnitsInAreaCheck(cat, area)
if type(area) == 'string' then
area = ScenarioUtils.AreaToRect(area)
end
local entities = GetUnitsInRect(area)
if not entities then
return false
end
for _, entity in entities do
if EntityCategoryContains(cat, entity) then
return true
end
end
return false
end
-- Returns the number of `cat` units in `area` belonging to `brain`
---@param cat EntityCategory
---@param area Area | Rectangle
---@param brain AIBrain
---@return number
function NumCatUnitsInArea(cat, area, brain)
if type(area) == 'string' then
area = ScenarioUtils.AreaToRect(area)
end
local entities = GetUnitsInRect(area)
local result = 0
if entities then
local filteredList = EntityCategoryFilterDown(cat, entities)
for _, entity in filteredList do
if entity:GetAIBrain() == brain then
result = result + 1
end
end
end
return result
end
-- Returns the units in `area` of `cat` belonging to `brain`
---@param cat EntityCategory
---@param area Area | Rectangle
---@param brain AIBrain
---@return Unit[]
function GetCatUnitsInArea(cat, area, brain)
if type(area) == 'string' then
area = ScenarioUtils.AreaToRect(area)
end
local entities = GetUnitsInRect(area)
local result = {}
if entities then
local filteredList = EntityCategoryFilterDown(cat, entities)
for _, entity in filteredList do
if entity:GetAIBrain() == brain then
table.insert(result, entity)
end
end
end
return result
end
--- Goes through every unit in `group` and destroys them without explosions
---@param units Unit[]
function DestroyGroup(units)
for _, unit in units do
unit:Destroy()
end
end
CreateUnitDistanceTrigger = TriggerFile.CreateUnitDistanceTrigger
CreateArmyStatTrigger = TriggerFile.CreateArmyStatTrigger
CreateThreatTriggerAroundPosition = TriggerFile.CreateThreatTriggerAroundPosition
CreateThreatTriggerAroundUnit = TriggerFile.CreateThreatTriggerAroundUnit
CreateArmyIntelTrigger = TriggerFile.CreateArmyIntelTrigger
CreateArmyUnitCategoryVeterancyTrigger = TriggerFile.CreateArmyUnitCategoryVeterancyTrigger
CreateUnitToPositionDistanceTrigger = TriggerFile.CreateUnitToPositionDistanceTrigger
CreateUnitToMarkerDistanceTrigger = CreateUnitToPositionDistanceTrigger -- got renamed for some reason
CreateUnitNearTypeTrigger = TriggerFile.CreateUnitNearTypeTrigger
-- platoon functions REQUIRE `squad` to be non-nil when present
-- Orders a platoon to move along a route
---@param platoon Platoon
---@param route (Marker | Vector)[]
---@param squad? string
function PlatoonMoveRoute(platoon, route, squad)
for _, node in route do
if type(node) == 'string' then
node = ScenarioUtils.MarkerToPosition(node)
end
if squad then
platoon:MoveToLocation(node, false, squad)
else
platoon:MoveToLocation(node, false)
end
end
end
--- Orders platoon to patrol a route
---@param platoon Platoon
---@param route (Marker | Vector)[]
---@param squad? string
function PlatoonPatrolRoute(platoon, route, squad)
for _, node in route do
if type(node) == 'string' then
node = ScenarioUtils.MarkerToPosition(node)
end
if squad then
platoon:Patrol(node, squad)
else
platoon:Patrol(node)
end
end
end
--- Orders a platoon to attack-move along a route
---@param platoon Platoon
---@param route (Marker | Vector)[]
---@param squad? string
function PlatoonAttackRoute(platoon, route, squad)
for _, node in route do
if type(node) == 'string' then
node = ScenarioUtils.MarkerToPosition(node)
end
if squad then
platoon:AggressiveMoveToLocation(node, squad)
else
platoon:AggressiveMoveToLocation(node)
end
end
end
--- Orders a platoon to move along a chain
---@param platoon Platoon
---@param chain MarkerChain
---@param squad? string
function PlatoonMoveChain(platoon, chain, squad)
for _, pos in ScenarioUtils.ChainToPositions(chain) do
if squad then
platoon:MoveToLocation(pos, false, squad)
else
platoon:MoveToLocation(pos, false)
end
end
end
--- Orders a platoon to patrol along a chain
---@param platoon Platoon
---@param chain MarkerChain
---@param squad? string
function PlatoonPatrolChain(platoon, chain, squad)
for _, pos in ScenarioUtils.ChainToPositions(chain) do
if squad then
platoon:Patrol(pos, squad)
else
platoon:Patrol(pos)
end
end
end
--- Orders a platoon to attack-move through a chain
---@param platoon Platoon
---@param chain MarkerChain
---@param squad? string
---@return SimCommand # the last attack-move command
function PlatoonAttackChain(platoon, chain, squad)
local cmd = false
for _, pos in ScenarioUtils.ChainToPositions(chain) do
if squad then
cmd = platoon:AggressiveMoveToLocation(pos, squad)
else
cmd = platoon:AggressiveMoveToLocation(pos)
end
end
return cmd
end
--- Orders a group to patrol along a chain
---@param units Unit[]
---@param chain MarkerChain
function GroupPatrolChain(units, chain)
for _, pos in ScenarioUtils.ChainToPositions(chain) do
IssuePatrol(units, pos)
end
end
--- Orders a group to patrol a route
---@param units Unit[]
---@param route (Marker | Vector)[]
function GroupPatrolRoute(units, route)
for _, node in route do
if type(node) == 'string' then
node = ScenarioUtils.MarkerToPosition(node)
end
IssuePatrol(units, node)
end
end
--- Orders a group to patrol a route in formation
---@param units Unit[]
---@param chain MarkerChain
---@param formation string
function GroupFormPatrolChain(units, chain, formation)
for _, pos in ScenarioUtils.ChainToPositions(chain) do
IssueFormPatrol(units, pos, formation, 0)
end
end
--- Orders a group to attack-move a along a chain
---@param units Unit[]
---@param chain MarkerChain
function GroupAttackChain(units, chain)
for _, pos in ScenarioUtils.ChainToPositions(chain) do
IssueAggressiveMove(units, pos)
end
end
--- Orders a group to move along a chain
---@param units Unit[]
---@param chain MarkerChain
function GroupMoveChain(units, chain)
for _, pos in ScenarioUtils.ChainToPositions(chain) do
IssueMove(units, pos)
end
end
--- Makes `units` to have their work progress start at `0.0` and scale to `1.0` over `time`
---@param units Unit[]
---@param time number
function GroupProgressTimer(units, time)
ForkThread(GroupProgressTimerThread, units, time)
end
---
---@param units Unit[]
---@param time number
function GroupProgressTimerThread(units, time)
local currTime = 0
while currTime < time do
local prog = currTime / time
for _, unit in units do
if not unit.Dead then
unit:SetWorkProgress(prog)
end
end
WaitSeconds(1)
currTime = currTime + 1
end
end
---
---@param dialogueTable DialogueTable
---@param callback? fun()
---@param critical? boolean
---@param speaker? Unit
function Dialogue(dialogueTable, callback, critical, speaker)
if not (speaker and speaker.Dead) then
local dTable = table.deepcopy(dialogueTable)
if callback then
dTable.Callback = callback
end
if critical then
dTable.Critical = critical
end
if ScenarioInfo.DialogueLock == nil then
ScenarioInfo.DialogueLock = false
ScenarioInfo.DialogueLockPosition = 0
ScenarioInfo.DialogueQueue = {}
ScenarioInfo.DialogueFinished = {}
end
table.insert(ScenarioInfo.DialogueQueue, dTable)
if not ScenarioInfo.DialogueLock then
ScenarioInfo.DialogueLock = true
ForkThread(PlayDialogue)
end
end
end
---
function FlushDialogueQueue()
if ScenarioInfo.DialogueQueue then
for _, dialogue in ScenarioInfo.DialogueQueue do
dialogue.Flushed = true
end
end
end
--- This function sends movie data to the sync table and saves it off for reloading in save games
---@param movieTable MovieTable
---@param text string
function SetupMFDSync(movieTable, text)
DisplayVideoText(text)
Sync.PlayMFDMovie = {movieTable[1], movieTable[2], movieTable[3], movieTable[4]}
ScenarioInfo.DialogueFinished[movieTable[1]] = false
local tempText = LOC(text)
local tempData = {}
local nameStart = tempText:find(']')
if nameStart ~= nil then
tempData.name = LOC("<LOC " .. tempText:sub(2, nameStart - 1) .. ">")
tempData.text = tempText:sub(nameStart + 2)
else
tempData.name = "INVALID NAME"
tempData.text = tempText
LOG("ERROR: Unable to find name in string: " .. text .. " (" .. tempText .. ")")
end
-- `GetGameTime()` would be the perfect thing to use here--unfortunately, that's sim-side only
local seconds = GetGameTimeSeconds()
local MathFloor = math.floor
local hours = MathFloor(seconds / 3600)
seconds = seconds - hours * 3600
local minutes = MathFloor(seconds / 60)
seconds = seconds - minutes * 60
tempData.time = ("%02d:%02d:%02d"):format(hours, minutes, seconds)
if movieTable[4] == 'UEF' then
tempData.color = 'ff00c1ff'
elseif movieTable[4] == 'Cybran' then
tempData.color = 'ffff0000'
elseif movieTable[4] == 'Aeon' then
tempData.color = 'ff89d300'
else
tempData.color = 'ffffffff'
end
AddTransmissionData(tempData)
WaitForDialogue(movieTable[1])
end
---
---@param entryData Transmission
function AddTransmissionData(entryData)
SimUIVars.SaveEntry(entryData)
end
--- The actual thread used by `Dialogue`
function PlayDialogue()
while not table.empty(ScenarioInfo.DialogueQueue) do
local dialogueTable = table.remove(ScenarioInfo.DialogueQueue, 1)
if not dialogueTable then
WARN('dialogueTable is nil, ScenarioInfo.DialogueQueue len is ' .. table.getn(ScenarioInfo.DialogueQueue))
end
if not dialogueTable.Flushed and (not ScenarioInfo.OpEnded or dialogueTable.Critical) then
for _, dialogue in dialogueTable do
if dialogue ~= nil and not dialogueTable.Flushed and (not ScenarioInfo.OpEnded or dialogueTable.Critical) then
local bank = dialogue.bank
local cue = dialogue.cue
local delay = dialogue.delay
local duration = dialogue.duration
local text = dialogue.text
local vid = dialogue.vid
if not vid and bank and cue then
SyncVoice({Cue = cue, Bank = bank})
if not delay then
WaitSeconds(5)
end
end
if text and not vid then
DisplayMissionText(text)
end
if vid then
text = text or ""
local movieData = {}
if GetMovieDuration('/movies/' .. vid) == 0 then
movieData = {'/movies/AllyCom.sfd', bank, cue, dialogue.faction}
else
movieData = {'/movies/' .. vid, bank, cue, dialogue.faction}
end
SetupMFDSync(movieData, text)
end
if delay and delay > 0 then
WaitSeconds(delay)
end
if duration and duration > 0 then
WaitSeconds(duration)
end
end
end
end
if dialogueTable.Callback then
ForkThread(dialogueTable.Callback)
end
WaitTicks(1)
end
ScenarioInfo.DialogueLock = false
end
---
---@param name string
function WaitForDialogue(name)
while not ScenarioInfo.DialogueFinished[name] do
WaitTicks(1)
end
end
---
function PlayUnlockDialogue()
if Random(1, 2) == 1 then
SyncVoice({Bank = 'XGG', Cue = 'Computer_Computer_UnitRevalation_01370'})
else
SyncVoice({Bank = 'XGG', Cue = 'Computer_Computer_UnitRevalation_01372'})
end
end
--- Given a head and taunt number, tells the UI to play the related taunt
---@param head number
---@param taunt number
function PlayTaunt(head, taunt)
Sync.MPTaunt = {head, taunt}
end
---
---@param text string
function DisplayMissionText(text)
if not Sync.MissionText then
Sync.MissionText = {}
end
table.insert(Sync.MissionText, text)
end
---
---@param text string
function DisplayVideoText(text)
if not Sync.VideoText then
Sync.VideoText = {}
end
table.insert(Sync.VideoText, text)
end
--- Plays an NIS
---@param pathToMovie string
function PlayNIS(pathToMovie)
if not Sync.NISVideo then
Sync.NISVideo = pathToMovie
end
end
---
---@param faction string
---@param callback fun()
function PlayEndGameMovie(faction, callback)
if not Sync.EndGameMovie then
Sync.EndGameMovie = faction
end
if callback then
if not ScenarioInfo.DialogueFinished then
ScenarioInfo.DialogueFinished = {}
end
ScenarioInfo.DialogueFinished['EndGameMovie'] = false
ForkThread(EndGameWaitThread, callback)
end
end
---
---@param callback fun()
function EndGameWaitThread(callback)
while not ScenarioInfo.DialogueFinished['EndGameMovie'] do
WaitTicks(1)
end
callback()
ScenarioInfo.DialogueFinished['EndGameMovie'] = false
end
--- Plays an XACT sound if needed--currently all VOs are videos
---@param voSound SoundBlueprint
function PlayVoiceOver(voSound)
SyncVoice(voSound)
end
--- Sets enhancement restrictions from the names of the enhancements you do not want the player to build
---@param enhancements string[]
function RestrictEnhancements(enhancements)
local restrict = {}
for _, enh in enhancements do
restrict[enh] = true
end
SimUIVars.SaveEnhancementRestriction(restrict)
import("/lua/enhancementcommon.lua").RestrictList(restrict)
Sync.EnhanceRestrict = restrict
end
--- Returns if all units in the group are dead
---@param units Unit[]
---@return boolean
function GroupDeathCheck(units)
for _, unit in units do
if not unit.Dead then
return false
end
end
return true
end
--- Returns if the list is entirely truthy
---@param list unknown
---@return boolean
function CheckObjectives(list)
for _, val in list do
if not val then
return false
end
end
return true
end
---
---@param brain string
---@param unit string
---@param effect string
---@param name? string | true # if `true`, uses the brain's nickname
---@param pauseAtDeath? boolean
---@param deathTrigger? fun(self: Unit)
---@param enhancements? string[]
---@return CommandUnit
function SpawnCommander(brain, unit, effect, name, pauseAtDeath, deathTrigger, enhancements)
local ACU = ScenarioUtils.CreateArmyUnit(brain, unit)
local bp = ACU:GetBlueprint()
local bonesToHide = bp.WarpInEffect.HideBones
local delay = 0
local function CreateEnhancements(unit, enhancements, delay)
if delay then
WaitSeconds(delay)
end
for _, enhancement in enhancements do
unit:CreateEnhancement(enhancement)
end
end
local function GateInEffect(unit, effect, bonesToHide)
if effect == 'Gate' then
delay = 0.75
ForkThread(FakeGateInUnit, unit, nil, bonesToHide)
elseif effect == 'Warp' then
delay = 2.1
unit:PlayCommanderWarpInEffect(bonesToHide)
else
WARN('*WARNING: Invalid effect type: ' .. effect .. '. Available types: Gate, Warp.')
end
end
if enhancements and effect then
-- Don't hide upgrade bones that we want add on the command unit
for _, enh in enhancements do
if bp.Enhancements[enh].ShowBones then
for _, bone in bp.Enhancements[enh].ShowBones do
table.removeByValue(bonesToHide, bone)
end
end
end
GateInEffect(ACU, effect, bonesToHide)
-- Creating upgrades needs to be delayed until the effect plays, else the upgrade bone would show up before the rest of the unit
ForkThread(CreateEnhancements, ACU, enhancements, delay)
elseif enhancements then
CreateEnhancements(ACU, enhancements)
elseif effect then
GateInEffect(ACU, effect)
end
-- If true is passed as argument then use default name
if name == true then
ACU:SetCustomName(GetArmyBrain(brain).Nickname)
elseif type(name) == 'string' then
ACU:SetCustomName(name)
end
if pauseAtDeath then
PauseUnitDeath(ACU)
end
if deathTrigger then
CreateUnitDeathTrigger(deathTrigger, ACU)
end
return ACU
end
--- Run teleport effect then delete unit if told to do so
---@param unit Unit
---@param killUnit boolean
function FakeTeleportUnit(unit, killUnit)
IssueStop({unit})
IssueClearCommands({unit})
unit.CanBeKilled = false
unit:PlayTeleportChargeEffects(unit:GetPosition(), unit:GetOrientation())
unit:PlayUnitSound('GateCharge')
WaitSeconds(2)
unit:CleanupTeleportChargeEffects()
unit:PlayTeleportOutEffects()
unit:PlayUnitSound('GateOut')
WaitSeconds(1)
if killUnit then
unit:Destroy()
end
end
--- Run teleport effect then delete unit if told to do so
---@param units Unit
---@param killUnits boolean
function FakeTeleportUnits(units, killUnits)
IssueStop(units)
IssueClearCommands(units)
for _, unit in units do
if not IsDestroyed(unit) then
unit.CanBeKilled = false
unit:PlayTeleportChargeEffects(unit:GetPosition(), unit:GetOrientation())
unit:PlayUnitSound('GateCharge')
end
end
WaitSeconds(2)
for _, unit in units do
if not IsDestroyed(unit) then
unit:CleanupTeleportChargeEffects()
unit:PlayTeleportOutEffects()
unit:PlayUnitSound('GateOut')
end
end
WaitSeconds(1)
if killUnits then
for _, unit in units do
if not IsDestroyed(unit) then
unit:Destroy()
end
end
end
end
---
---@param unit Unit
---@param callback fun()
---@param bonesToHide Bone[]
function FakeGateInUnit(unit, callback, bonesToHide)
local bp = unit:GetBlueprint()
if EntityCategoryContains(categories.COMMAND + categories.SUBCOMMANDER, unit) then
unit:HideBone(0, true)
unit:SetUnSelectable(true)
unit:SetBusy(true)
unit:PlayUnitSound('CommanderArrival')
unit:CreateProjectile('/effects/entities/UnitTeleport03/UnitTeleport03_proj.bp', 0, 1.35, 0, nil, nil, nil):SetCollision(false)
WaitSeconds(0.75)
local shieldMesh = bp.Display.WarpInEffect.PhaseShieldMesh
if shieldMesh then
unit:SetMesh(shieldMesh, true)
end
unit:ShowBone(0, true)
for _, bone in bonesToHide or bp.Display.WarpInEffect.HideBones do
unit:HideBone(bone, true)
end
unit:SetUnSelectable(false)
unit:SetBusy(false)
local totalBones = unit:GetBoneCount() - 1