forked from FAForever/fa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
defaultunits.lua
2809 lines (2389 loc) · 96.4 KB
/
defaultunits.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/defaultunits.lua
-- Author(s): John Comes, Gordon Duclos
-- Summary : Default definitions of units
-- Copyright © 2005 Gas Powered Games, Inc. All rights reserved.
-----------------------------------------------------------------
local Entity = import("/lua/sim/entity.lua").Entity
local Unit = import("/lua/sim/unit.lua").Unit
local explosion = import("/lua/defaultexplosions.lua")
local EffectUtil = import("/lua/effectutilities.lua")
local EffectTemplate = import("/lua/effecttemplates.lua")
local ScenarioUtils = import("/lua/sim/scenarioutilities.lua")
local Buff = import("/lua/sim/buff.lua")
local AdjacencyBuffs = import("/lua/sim/adjacencybuffs.lua")
local FireState = import("/lua/game.lua").FireState
local ScenarioFramework = import("/lua/scenarioframework.lua")
local RolloffUnitTable = { nil }
local RolloffPositionTable = { 0, 0, 0 }
-- allows us to skip ai-specific functionality
local GameHasAIs = ScenarioInfo.GameHasAIs
-- compute once and store as upvalue for performance
local StructureUnitRotateTowardsEnemiesLand = categories.STRUCTURE + categories.LAND + categories.NAVAL
local StructureUnitRotateTowardsEnemiesArtillery = categories.ARTILLERY * (categories.TECH2 + categories.TECH3 + categories.EXPERIMENTAL)
local StructureUnitOnStartBeingBuiltRotateBuildings = categories.STRUCTURE * (categories.DIRECTFIRE + categories.INDIRECTFIRE) * (categories.DEFENSE + categories.ARTILLERY)
-- STRUCTURE UNITS
---@class StructureUnit : Unit
---@field AdjacentUnits? Unit[]
StructureUnit = Class(Unit) {
LandBuiltHiddenBones = {'Floatation'},
MinConsumptionPerSecondEnergy = 1,
MinWeaponRequiresEnergy = 0,
-- Stucture unit specific damage effects and smoke
FxDamage1 = {EffectTemplate.DamageStructureSmoke01, EffectTemplate.DamageStructureSparks01},
FxDamage2 = {EffectTemplate.DamageStructureFireSmoke01, EffectTemplate.DamageStructureSparks01},
FxDamage3 = {EffectTemplate.DamageStructureFire01, EffectTemplate.DamageStructureSparks01},
ConsumptionActive = true,
---@param self StructureUnit
OnCreate = function(self)
Unit.OnCreate(self)
self:HideLandBones()
self.FxBlinkingLightsBag = {}
if self.Layer == 'Land' and self.Blueprint.Physics.FlattenSkirt then
self:FlattenSkirt()
end
end,
--- Hides parts of a mesh that should be visible when the structure is made on water
---@param self StructureUnit
HideLandBones = function(self)
if self.LandBuiltHiddenBones and self.Layer == 'Land' then
for _, v in self.LandBuiltHiddenBones do
if self:IsValidBone(v) then
self:HideBone(v, true)
end
end
end
end,
--- Rotates the structure towards the enemy, primarily used for point defenses
---@param self StructureUnit
RotateTowardsEnemy = function(self)
-- retrieve information we may need
local bp = self.Blueprint
local brain = self:GetAIBrain()
local pos = self:GetPosition()
-- determine default threat that aims at center of the map
local x, z = GetMapSize()
local target = {
location = {0.5 * x, 0, 0.5 * z},
distance = -1,
threat = -1,
}
-- determine radius
local radius = 40
local weapons = self.Blueprint.Weapon
if weapons then
for k, weapon in weapons do
if weapon.MaxRadius and weapon.MaxRadius > radius then
radius = 1.1 * weapon.MaxRadius
end
end
end
local cats = EntityCategoryContains(categories.ANTIAIR, self) and categories.AIR or (StructureUnitRotateTowardsEnemiesLand)
local units = brain:GetUnitsAroundPoint(cats, pos, radius, 'Enemy')
if units then
for _, u in units do
local blip = u:GetBlip(self.Army)
if blip then
-- check if we've got it on radar and whether it is identified by army in question
local radar = blip:IsOnRadar(self.Army)
local identified = blip:IsSeenEver(self.Army)
if radar or identified then
local threat = (identified and u.Blueprint.Defense.SurfaceThreatLevel) or 1
if threat >= target.threat then
target.location = u:GetPosition()
target.threat = threat
end
end
end
end
end
-- get direction vector, atanify it for angle
local rad = math.atan2(target.location[1] - pos[1], target.location[3] - pos[3])
local degrees = rad * (180 / math.pi)
-- some buildings can only take 90 degree angles
if EntityCategoryContains(StructureUnitRotateTowardsEnemiesArtillery, self) then
degrees = math.floor((degrees + 45) / 90) * 90
end
self:SetRotation(degrees)
end,
---@param self StructureUnit
---@param builder Builder
---@param layer Layer
OnStartBeingBuilt = function(self, builder, layer)
Unit.OnStartBeingBuilt(self, builder, layer)
if EntityCategoryContains(StructureUnitOnStartBeingBuiltRotateBuildings, self) then
self:RotateTowardsEnemy()
end
local bp = self.Blueprint
if bp.Physics.FlattenSkirt and not self:HasTarmac() and bp.General.FactionName ~= "Seraphim" then
if self.TarmacBag then
self:CreateTarmac(true, true, true, self.TarmacBag.Orientation, self.TarmacBag.CurrentBP)
else
self:CreateTarmac(true, true, true, false, false)
end
end
end,
---@param self StructureUnit
---@param builder Builder
---@param layer Layer
OnStopBeingBuilt = function(self, builder, layer)
Unit.OnStopBeingBuilt(self, builder, layer)
-- tarmac is made once seraphim animation is complete
if self.Blueprint.General.FactionName == "Seraphim" then
self:CreateTarmac(true, true, true, false, false)
end
self:PlayActiveAnimation()
-- remove land bones if the structure has them
self:HideLandBones()
end,
---@param self StructureUnit
OnFailedToBeBuilt = function(self)
Unit.OnFailedToBeBuilt(self)
self:DestroyTarmac()
end,
---@param self StructureUnit
FlattenSkirt = function(self)
local x, y, z = self:GetPositionXYZ()
local x0, z0, x1, z1 = self:GetSkirtRect()
x0, z0, x1, z1 = math.floor(x0), math.floor(z0), math.ceil(x1), math.ceil(z1)
FlattenMapRect(x0, z0, x1 - x0, z1 - z0, y)
end,
---@param self StructureUnit
---@param albedo string
---@param normal string
---@param glow string
---@param orientation number
---@param specTarmac string
---@param lifeTime number
---@return boolean
CreateTarmac = function(self, albedo, normal, glow, orientation, specTarmac, lifeTime)
if self.Layer ~= 'Land' then return end
local tarmac
local bp = self.Blueprint.Display.Tarmacs
if not specTarmac then
if bp and not table.empty(bp) then
local num = Random(1, table.getn(bp))
tarmac = bp[num]
else
return false
end
else
tarmac = specTarmac
end
local w = tarmac.Width
local l = tarmac.Length
local fadeout = tarmac.FadeOut
local x, y, z = self:GetPositionXYZ()
-- I'm disabling this for now since there are so many things wrong with it
local orient = orientation
if not orientation then
if tarmac.Orientations and not table.empty(tarmac.Orientations) then
orient = tarmac.Orientations[Random(1, table.getn(tarmac.Orientations))]
orient = (0.01745 * orient)
else
orient = 0
end
end
if not self.TarmacBag then
self.TarmacBag = {
Decals = {},
Orientation = orient,
CurrentBP = tarmac,
}
end
local GetTarmac = import("/lua/tarmacs.lua").GetTarmacType
local terrain = GetTerrainType(x, z)
local terrainName
if terrain then
terrainName = terrain.Name
end
-- Players and AI can build buildings outside of their faction. Get the *building's* faction to determine the correct tarrain-specific tarmac
local factionTable = {e = 1, a = 2, r = 3, s = 4}
local faction = factionTable[string.sub(self.UnitId, 2, 2)]
if albedo and tarmac.Albedo then
local albedo2 = tarmac.Albedo2
if albedo2 then
albedo2 = albedo2 .. GetTarmac(faction, terrain)
end
local tarmacHndl = CreateDecal(self:GetPosition(), orient, tarmac.Albedo .. GetTarmac(faction, terrainName) , albedo2 or '', 'Albedo', w, l, fadeout, lifeTime or 0, self.Army, 0)
table.insert(self.TarmacBag.Decals, tarmacHndl)
if tarmac.RemoveWhenDead then
self.Trash:Add(tarmacHndl)
end
end
if normal and tarmac.Normal then
local tarmacHndl = CreateDecal(self:GetPosition(), orient, tarmac.Normal .. GetTarmac(faction, terrainName), '', 'Alpha Normals', w, l, fadeout, lifeTime or 0, self.Army, 0)
table.insert(self.TarmacBag.Decals, tarmacHndl)
if tarmac.RemoveWhenDead then
self.Trash:Add(tarmacHndl)
end
end
if glow and tarmac.Glow then
local tarmacHndl = CreateDecal(self:GetPosition(), orient, tarmac.Glow .. GetTarmac(faction, terrainName), '', 'Glow', w, l, fadeout, lifeTime or 0, self.Army, 0)
table.insert(self.TarmacBag.Decals, tarmacHndl)
if tarmac.RemoveWhenDead then
self.Trash:Add(tarmacHndl)
end
end
end,
---@param self StructureUnit
DestroyTarmac = function(self)
if not self.TarmacBag then return end
for k, v in self.TarmacBag.Decals do
v:Destroy()
end
self.TarmacBag.Orientation = nil
self.TarmacBag.CurrentBP = nil
end,
---@param self StructureUnit
HasTarmac = function(self)
if not self.TarmacBag then return false end
return not table.empty(self.TarmacBag.Decals)
end,
---@param self StructureUnit
DestroyBlinkingLights = function(self)
for _, v in self.FxBlinkingLightsBag do
v:Destroy()
end
self.FxBlinkingLightsBag = {}
end,
---@param self StructureUnit
---@param overkillRatio number
CreateDestructionEffects = function(self, overkillRatio)
if explosion.GetAverageBoundingXZRadius(self) < 1.0 then
explosion.CreateScalableUnitExplosion(self)
else
explosion.CreateTimedStuctureUnitExplosion(self, self.DeathAnimManip)
WaitSeconds(0.3)
explosion.CreateScalableUnitExplosion(self)
end
end,
-- Modified to use same upgrade logic as the ui. This adds more upgrade options via General.UpgradesFromBase blueprint option
---@param self StructureUnit
---@param unitBeingBuilt Unit
---@param order boolean
OnStartBuild = function(self, unitBeingBuilt, order)
-- Check for death loop
if not Unit.OnStartBuild(self, unitBeingBuilt, order) then
return
end
self.UnitBeingBuilt = unitBeingBuilt
local builderBp = self.Blueprint
local targetBp = unitBeingBuilt.Blueprint
local performUpgrade = false
if targetBp.General.UpgradesFrom == builderBp.BlueprintId then
performUpgrade = true
elseif targetBp.General.UpgradesFrom == builderBp.General.UpgradesTo then
performUpgrade = true
elseif targetBp.General.UpgradesFromBase ~= "none" then
-- Try testing against the base
if targetBp.General.UpgradesFromBase == builderBp.BlueprintId then
performUpgrade = true
elseif targetBp.General.UpgradesFromBase == builderBp.General.UpgradesFromBase then
performUpgrade = true
end
end
if performUpgrade and order == 'Upgrade' then
ChangeState(self, self.UpgradingState)
-- Fix an oddly specific bug to structures with damaged shields:
-- 1) let an engineer to assist the structure, repairing the damaged shield
-- 2) upgrade the structure while the shield is being healed
-- 3) engineer changes consumption target, but is in limbo - it consumes resources, but it doesn't repair the shield or help upgrade the structure
-- Luckily, engineers do not heal damaged shields on their own. It usually only happens when an engineer was specifically told to assist the shield,
-- therefore we add a check when we upgrade a structure that has a shield. For each guarding unit, check if this is the only command. If so,
-- re-issue the guard command
if self.MyShield then
local guards = self:GetGuards()
for k, guard in guards do
if table.getn(guard:GetCommandQueue()) == 1 then
IssueClearCommands({guard})
IssueGuard({guard}, self)
end
end
end
end
end,
IdleState = State {
Main = function(self)
end,
},
UpgradingState = State {
Main = function(self)
self:DestroyTarmac()
self:PlayUnitSound('UpgradeStart')
self:DisableDefaultToggleCaps()
local animation = self:GetUpgradeAnimation(self.UnitBeingBuilt)
if animation then
local unitBuilding = self.UnitBeingBuilt
self.AnimatorUpgradeManip = CreateAnimator(self)
self.Trash:Add(self.AnimatorUpgradeManip)
local fractionOfComplete = 0
self:StartUpgradeEffects(unitBuilding)
self.AnimatorUpgradeManip:PlayAnim(animation, false):SetRate(0)
while fractionOfComplete < 1 and not self.Dead do
fractionOfComplete = unitBuilding:GetFractionComplete()
self.AnimatorUpgradeManip:SetAnimationFraction(fractionOfComplete)
WaitTicks(1)
end
if not self.Dead then
self.AnimatorUpgradeManip:SetRate(1)
end
end
end,
OnStopBuild = function(self, unitBuilding)
Unit.OnStopBuild(self, unitBuilding)
self:EnableDefaultToggleCaps()
if unitBuilding:GetFractionComplete() == 1 then
NotifyUpgrade(self, unitBuilding)
self:StopUpgradeEffects(unitBuilding)
self:PlayUnitSound('UpgradeEnd')
self:Destroy()
end
end,
OnFailedToBuild = function(self)
Unit.OnFailedToBuild(self)
self:EnableDefaultToggleCaps()
if self.AnimatorUpgradeManip then
self.AnimatorUpgradeManip:Destroy()
end
self:PlayUnitSound('UpgradeFailed')
self:PlayActiveAnimation()
self:CreateTarmac(true, true, true, self.TarmacBag.Orientation, self.TarmacBag.CurrentBP)
ChangeState(self, self.IdleState)
end,
},
---@param self StructureUnit
---@param builder Unit
---@param layer Layer
StartBeingBuiltEffects = function(self, builder, layer)
Unit.StartBeingBuiltEffects(self, builder, layer)
local bp = self.Blueprint
local FactionName = bp.General.FactionName
if FactionName == 'UEF' then
self:HideBone(0, true)
self.BeingBuiltShowBoneTriggered = false
if bp.General.UpgradesFrom ~= builder.UnitId then
self:ForkThread(EffectUtil.CreateBuildCubeThread, builder, self.OnBeingBuiltEffectsBag)
end
elseif FactionName == 'Aeon' then
if bp.General.UpgradesFrom ~= builder.UnitId then
self:ForkThread(EffectUtil.CreateAeonBuildBaseThread, builder, self.OnBeingBuiltEffectsBag)
end
elseif FactionName == 'Seraphim' then
if bp.General.UpgradesFrom ~= builder.UnitId then
self:ForkThread(EffectUtil.CreateSeraphimBuildBaseThread, builder, self.OnBeingBuiltEffectsBag)
end
end
end,
---@param self StructureUnit
---@param builder Unit
---@param layer Layer
StopBeingBuiltEffects = function(self, builder, layer)
local FactionName = self.Blueprint.General.FactionName
if FactionName == 'UEF' and not self.BeingBuiltShowBoneTriggered then
self:ShowBone(0, true)
self:HideLandBones()
end
Unit.StopBeingBuiltEffects(self, builder, layer)
end,
---comment
---@param self StructureUnit
---@param unitBeingBuilt Unit
---@param order table
StartBuildingEffects = function(self, unitBeingBuilt, order)
Unit.StartBuildingEffects(self, unitBeingBuilt, order)
end,
---@param self StructureUnit
---@param unitBeingBuilt Unit
StopBuildingEffects = function(self, unitBeingBuilt)
Unit.StopBuildingEffects(self, unitBeingBuilt)
end,
---@param self StructureUnit
---@param unitBeingBuilt Unit
StartUpgradeEffects = function(self, unitBeingBuilt)
unitBeingBuilt:HideBone(0, true)
end,
---@param self StructureUnit
---@param unitBeingBuilt Unit
StopUpgradeEffects = function(self, unitBeingBuilt)
unitBeingBuilt:ShowBone(0, true)
end,
---@param self StructureUnit
PlayActiveAnimation = function(self)
end,
---@param self StructureUnit
---@param instigator Unit
---@param type string
---@param overkillRatio number
OnKilled = function(self, instigator, type, overkillRatio)
local scus = EntityCategoryFilterDown(categories.SUBCOMMANDER, self:GetGuards())
if scus[1] then
for _, u in scus do
u:SetFocusEntity(self)
self.Repairers[u.EntityId] = u
end
end
Unit.OnKilled(self, instigator, type, overkillRatio)
-- Adding into OnKilled the ability to destroy the tarmac but put a new one down that looks exactly like it but
-- will time out over the time spec'd or 300 seconds.
local orient = self.TarmacBag.Orientation
local currentBP = self.TarmacBag.CurrentBP
self:DestroyTarmac()
self:CreateTarmac(true, true, true, orient, currentBP, currentBP.DeathLifetime or 300)
end,
---@param self StructureUnit
---@param wreckage Wreckage
CheckRepairersForRebuild = function(self, wreckage)
local units = {}
for id, u in self.Repairers do
if u:BeenDestroyed() then
self.Repairers[id] = nil
else
local focus = u:GetFocusUnit()
if focus == self and ((u:IsUnitState('Repairing') and not u:GetGuardedUnit()) or
EntityCategoryContains(categories.SUBCOMMANDER, u)) then
table.insert(units, u)
end
end
end
if not units[1] then return end
wreckage:Rebuild(units)
end,
---@param self StructureUnit
---@param overkillRatio number
---@return Wreckage|nil
CreateWreckage = function(self, overkillRatio)
local wreckage = Unit.CreateWreckage(self, overkillRatio)
if wreckage then
self:CheckRepairersForRebuild(wreckage)
end
return wreckage
end,
-- Called by the engine when a structure is finished building for each adjacent unit
---@param self StructureUnit
---@param adjacentUnit StructureUnit
---@param triggerUnit StructureUnit
OnAdjacentTo = function(self, adjacentUnit, triggerUnit)
-- make sure we're both finished building
if self:IsBeingBuilt() or adjacentUnit:IsBeingBuilt() then
return
end
-- make sure we have adjacency buffs to apply
local adjBuffs = self.Blueprint.Adjacency
if not adjBuffs then
return
end
-- keep track of who is adjacent to who
self.AdjacentUnits = self.AdjacentUnits or { }
adjacentUnit.AdjacentUnits = adjacentUnit.AdjacentUnits or { }
self.AdjacentUnits[adjacentUnit.EntityId] = adjacentUnit
adjacentUnit.AdjacentUnits[self.EntityId] = self
-- apply the buffs
if self.ConsumptionActive then
for k, v in AdjacencyBuffs[adjBuffs] do
Buff.ApplyBuff(adjacentUnit, v, self)
end
end
-- refresh the UI
self:RequestRefreshUI()
adjacentUnit:RequestRefreshUI()
end,
-- Called by the engine when a structure is destroyed for each adjacent unit
---@param self StructureUnit
---@param adjacentUnit StructureUnit
OnNotAdjacentTo = function(self, adjacentUnit)
-- make sure we're both finished building
if self:IsBeingBuilt() or adjacentUnit:IsBeingBuilt() then
return
end
-- make sure we have buffs to remove
local adjBuffs = self.Blueprint.Adjacency
if not adjBuffs then
return
end
-- remove the buffs
if adjBuffs and AdjacencyBuffs[adjBuffs] then
for k, v in AdjacencyBuffs[adjBuffs] do
if Buff.HasBuff(adjacentUnit, v) then
Buff.RemoveBuff(adjacentUnit, v)
end
end
end
-- clean up effects
self:DestroyAdjacentEffects(adjacentUnit)
-- keep track of who is adjacent to who
self.AdjacentUnits[adjacentUnit.EntityId] = nil
adjacentUnit.AdjacentUnits[self.EntityId] = nil
-- refresh the UI
adjacentUnit:RequestRefreshUI()
self:RequestRefreshUI()
end,
-- Add/Remove Adjacency Functionality
-- Applies all appropriate buffs to all adjacent units
---@param self StructureUnit
ApplyAdjacencyBuffs = function(self)
local adjBuffs = self.Blueprint.Adjacency
if not adjBuffs then return end
-- There won't be any adjacentUnit if this is a producer just built...
if self.AdjacentUnits then
for k, adjacentUnit in self.AdjacentUnits do
for k, v in AdjacencyBuffs[adjBuffs] do
Buff.ApplyBuff(adjacentUnit, v, self)
adjacentUnit:RequestRefreshUI()
end
end
self:RequestRefreshUI()
end
end,
-- Removes all appropriate buffs from all adjacent units
---@param self StructureUnit
RemoveAdjacencyBuffs = function(self)
local adjBuffs = self.Blueprint.Adjacency
if not adjBuffs then return end
if self.AdjacentUnits then
for k, adjacentUnit in self.AdjacentUnits do
for key, v in AdjacencyBuffs[adjBuffs] do
if Buff.HasBuff(adjacentUnit, v) then
Buff.RemoveBuff(adjacentUnit, v, false, self)
adjacentUnit:RequestRefreshUI()
end
end
end
self:RequestRefreshUI()
end
end,
-- Add/Remove Adjacency Effects
---@param self StructureUnit
---@param adjacentUnit StructureUnit
CreateAdjacentEffect = function(self, adjacentUnit)
-- Create trashbag to hold all these entities and beams
if not self.AdjacencyBeamsBag then
self.AdjacencyBeamsBag = {}
end
for k, v in self.AdjacencyBeamsBag do
if v.Unit.EntityId == adjacentUnit.EntityId then
return
end
end
EffectUtil.CreateAdjacencyBeams(self, adjacentUnit, self.AdjacencyBeamsBag)
end,
---@param self StructureUnit
---@param adjacentUnit StructureUnit
DestroyAdjacentEffects = function(self, adjacentUnit)
if not self.AdjacencyBeamsBag then return end
for k, v in self.AdjacencyBeamsBag do
if v.Unit:BeenDestroyed() or v.Unit.Dead then
v.Trash:Destroy()
self.AdjacencyBeamsBag[k] = nil
end
end
end,
---@param self StructureUnit
---@param instigator Unit
---@param amount number
---@param vector Vector
---@param damageType DamageType
DoTakeDamage = function(self, instigator, amount, vector, damageType)
-- Handle incoming OC damage
if damageType == 'Overcharge' then
local wep = instigator:GetWeaponByLabel('OverCharge')
amount = wep.Blueprint.Overcharge.structureDamage
end
Unit.DoTakeDamage(self, instigator, amount, vector, damageType)
end,
---@deprecated
---@param self StructureUnit
ChangeBlinkingLights = function(self)
end,
---@deprecated
---@param self StructureUnit
CreateBlinkingLights = function(self)
end,
---@deprecated
---@param self StructureUnit
OnMassStorageStateChange = function(self, state)
end,
---@deprecated
---@param self StructureUnit
OnEnergyStorageStateChange = function(self, state)
end,
}
-- FACTORY UNITS
---@class FactoryUnit : StructureUnit
---@field BuildingUnit boolean
---@field BuildBoneRotator moho.RotateManipulator
---@field BuildEffectBones string[]
FactoryUnit = Class(StructureUnit) {
---@param self FactoryUnit
OnCreate = function(self)
StructureUnit.OnCreate(self)
-- if we're a support factory, make sure our build restrictions are correct
if self.Blueprint.CategoriesHash["SUPPORTFACTORY"] then
self:UpdateBuildRestrictions()
end
-- Save build effect bones for faster access when creating build effects
self.BuildBoneRotator = CreateRotator(self, self.Blueprint.Display.BuildAttachBone or 0, 'y', 0, 10000)
self.Trash:Add(self.BuildBoneRotator)
self.BuildEffectBones = self.Blueprint.General.BuildBones.BuildEffectBones
self.BuildingUnit = false
self:SetFireState(FireState.GROUND_FIRE)
end,
---@param self FactoryUnit
---@return string?
ToSupportFactoryIdentifier = function(self)
local hashedCategories = self.Blueprint.CategoriesHash
local identifier = self.Blueprint.BlueprintId --[[@as string]]
local faction = identifier:sub(2, 2)
local layer = identifier:sub(7, 7)
-- HQs can not upgrade to support factories
if hashedCategories["RESEARCH"] then
return nil
end
-- tech 1 factories can go tech 2 support factories if we have a tech 2 hq
if hashedCategories["TECH1"] and
self.Brain:CountHQs(self.Blueprint.FactionCategory, self.Blueprint.LayerCategory, 'TECH2') > 0
then
return 'z' .. faction .. 'b950' .. layer
end
-- tech 2 support factories can go tech 3 support factories if we have a tech 3 hq
if hashedCategories["TECH2"] and
hashedCategories["SUPPORTFACTORY"] and
self.Brain:CountHQs(self.Blueprint.FactionCategory, self.Blueprint.LayerCategory, 'TECH3') > 0
then
return 'z' .. faction .. 'b960' .. layer
end
-- anything else can not upgrade
return nil
end,
---@param self FactoryUnit
ToHQFactoryIdentifier = function(self)
local hashedCategories = self.Blueprint.CategoriesHash
local identifier = self.Blueprint.BlueprintId --[[@as string]]
local faction = identifier:sub(1, 3)
local layer = identifier:sub(7, 7)
-- support factories can not upgrade to HQs
if hashedCategories["SUPPORTFACTORY"] then
return nil
end
-- tech 1 factories can always upgrade
if hashedCategories["TECH1"] then
return faction .. '020' .. layer
end
-- tech 2 factories can always upgrade
if hashedCategories["TECH2"] and hashedCategories["RESEARCH"] then
return faction .. '030' .. layer
end
-- anything else can not upgrade
return nil
end,
---@param self FactoryUnit
DestroyUnitBeingBuilt = function(self)
if self.UnitBeingBuilt and not self.UnitBeingBuilt.Dead and self.UnitBeingBuilt:GetFractionComplete() < 1 then
if self.UnitBeingBuilt:GetFractionComplete() > 0.5 then
self.UnitBeingBuilt:Kill()
else
self.UnitBeingBuilt:Destroy()
end
end
end,
---@param self FactoryUnit
OnDestroy = function(self)
StructureUnit.OnDestroy(self)
if self.Blueprint.CategoriesHash["RESEARCH"] and self:GetFractionComplete() == 1.0 then
-- update internal state
self.Brain:RemoveHQ(self.factionCategory, self.layerCategory, self.techCategory)
self.Brain:SetHQSupportFactoryRestrictions(self.factionCategory, self.layerCategory)
-- update all units affected by this
local affected = self.Brain:GetListOfUnits(categories.SUPPORTFACTORY - categories.EXPERIMENTAL, false)
for id, unit in affected do
unit:UpdateBuildRestrictions()
end
end
self:DestroyUnitBeingBuilt()
end,
---@param self FactoryUnit
OnPaused = function(self)
StructureUnit.OnPaused(self)
-- When factory is paused take some action
if self:IsUnitState('Building') then
self:StopUnitAmbientSound('ConstructLoop')
StructureUnit.StopBuildingEffects(self, self.UnitBeingBuilt)
end
end,
---@param self FactoryUnit
OnUnpaused = function(self)
StructureUnit.OnUnpaused(self)
if self:IsUnitState('Building') then
self:PlayUnitAmbientSound('ConstructLoop')
StructureUnit.StartBuildingEffects(self, self.UnitBeingBuilt, self.UnitBuildOrder)
end
end,
---@param self FactoryUnit
---@param unitBeingBuilt Unit
---@param order boolean
OnStartBuild = function(self, unitBeingBuilt, order)
StructureUnit.OnStartBuild(self, unitBeingBuilt, order)
self.BuildingUnit = true
if order ~= 'Upgrade' then
ChangeState(self, self.BuildingState)
self.BuildingUnit = false
elseif unitBeingBuilt.Blueprint.CategoriesHash["RESEARCH"] then
-- Removes assist command to prevent accidental cancellation when right-clicking on other factory
self:RemoveCommandCap('RULEUCC_Guard')
self.DisabledAssist = true
end
self.FactoryBuildFailed = false
end,
--- Introduce a rolloff delay, where defined.
---@param self FactoryUnit
---@param unitBeingBuilt Unit
---@param order boolean
OnStopBuild = function(self, unitBeingBuilt, order)
if self.DisabledAssist then
self:AddCommandCap('RULEUCC_Guard')
self.DisabledAssist = nil
end
local bp = self.Blueprint
if bp.General.RolloffDelay and bp.General.RolloffDelay > 0 and not self.FactoryBuildFailed then
self:ForkThread(self.PauseThread, bp.General.RolloffDelay, unitBeingBuilt, order)
else
self:DoStopBuild(unitBeingBuilt, order)
end
end,
---@param self FactoryUnit
---@param builder Unit
---@param layer Layer
OnStopBeingBuilt = function(self, builder, layer)
StructureUnit.OnStopBeingBuilt(self, builder, layer)
if self.Blueprint.CategoriesHash["RESEARCH"] then
-- update internal state
self.Brain:AddHQ(self.factionCategory, self.layerCategory, self.techCategory)
self.Brain:SetHQSupportFactoryRestrictions(self.factionCategory, self.layerCategory)
-- update all units affected by this
local affected = self.Brain:GetListOfUnits(categories.SUPPORTFACTORY - categories.EXPERIMENTAL, false)
for _, unit in affected do
unit:UpdateBuildRestrictions()
end
end
end,
--- Adds a pause between unit productions
---@param self FactoryUnit
---@param productionpause number
---@param unitBeingBuilt Unit
---@param order boolean
PauseThread = function(self, productionpause, unitBeingBuilt, order)
self:StopBuildFx()
self:SetBusy(true)
self:SetBlockCommandQueue(true)
WaitSeconds(productionpause)
self:SetBusy(false)
self:SetBlockCommandQueue(false)
self:DoStopBuild(unitBeingBuilt, order)
end,
---@param self FactoryUnit
---@param unitBeingBuilt Unit
---@param order boolean
DoStopBuild = function(self, unitBeingBuilt, order)
StructureUnit.OnStopBuild(self, unitBeingBuilt, order)
if not self.FactoryBuildFailed and not self.Dead then
if not EntityCategoryContains(categories.AIR, unitBeingBuilt) then
self:RollOffUnit()
end
self:StopBuildFx()
self:ForkThread(self.FinishBuildThread, unitBeingBuilt, order)
end
self.BuildingUnit = false
end,
---@param self FactoryUnit
---@param unitBeingBuilt Unit
---@param order boolean
FinishBuildThread = function(self, unitBeingBuilt, order)
self:SetBusy(true)
self:SetBlockCommandQueue(true)
local bp = self.Blueprint
local bpAnim = bp.Display.AnimationFinishBuildLand
if bpAnim and EntityCategoryContains(categories.LAND, unitBeingBuilt) then
self.RollOffAnim = CreateAnimator(self):PlayAnim(bpAnim)
self.Trash:Add(self.RollOffAnim)
WaitTicks(1)
WaitFor(self.RollOffAnim)
end
if unitBeingBuilt and not unitBeingBuilt.Dead then
unitBeingBuilt:DetachFrom(true)
end
self:DetachAll(bp.Display.BuildAttachBone or 0)
self:DestroyBuildRotator()
if order ~= 'Upgrade' then
ChangeState(self, self.RollingOffState)
else
self:SetBusy(false)
self:SetBlockCommandQueue(false)
end
end,
---@param self FactoryUnit
---@param target_bp any
---@return boolean
CheckBuildRestriction = function(self, target_bp)
-- Check basic build restrictions first (Unit.CheckBuildRestriction but we only go up one inheritance level)
if not StructureUnit.CheckBuildRestriction(self, target_bp) then
return false
end
-- Factories never build factories (this does not break Upgrades since CheckBuildRestriction is never called for Upgrades)
-- Note: We check for the primary category, since e.g. AircraftCarriers have the FACTORY category.
-- TODO: This is a hotfix for --1043, remove when engymod design is properly fixed
return target_bp.General.Category ~= 'Factory'
end,
---@param self FactoryUnit
OnFailedToBuild = function(self)
StructureUnit.OnFailedToBuild(self)
self.FactoryBuildFailed = true
self:StopBuildFx()
ChangeState(self, self.IdleState)
end,
---@param self FactoryUnit
RollOffUnit = function(self)
local spin, x, y, z = self:CalculateRollOffPoint()
self.UnitBeingBuilt:SetRotation(spin)
RolloffUnitTable[1] = self.UnitBeingBuilt
RolloffPositionTable[1], RolloffPositionTable[2], RolloffPositionTable[3] = x, y, z
IssueMove(RolloffUnitTable, RolloffPositionTable)
end,
---@param self FactoryUnit
CalculateRollOffPoint = function(self)
local px, py, pz = self:GetPositionXYZ()