-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUnitPanel.lua.eui.modcompat
1472 lines (1330 loc) · 55.2 KB
/
UnitPanel.lua.eui.modcompat
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
--==========================================================
-- Unit Panel
-- Re-written by bc1 using Notepad++
-- code is common using gk_mode and bnw_mode switches
--==========================================================
Events.SequenceGameInitComplete.Add(function()
include "UserInterfaceSettings"
local UserInterfaceSettings = UserInterfaceSettings
include "GameInfoCache" -- warning! booleans are true, not 1, and use iterator ONLY with table field conditions, NOT string SQL query
local GameInfo = GameInfoCache
include "IconHookup"
local IconHookup = IconHookup
local Color = Color
local PrimaryColors = PrimaryColors
local BackgroundColors = BackgroundColors
include "GetUnitBuildProgressData"
local GetUnitBuildProgressData = GetUnitBuildProgressData
--==========================================================
-- Minor lua optimizations
--==========================================================
local gk_mode = Game.GetReligionName ~= nil
local bnw_mode = Game.GetActiveLeague ~= nil
--local debug_print = print
local ceil = math.ceil
local floor = math.floor
local min = math.min
local max = math.max
local pairs = pairs
--local print = print
local format = string.format
local insert = table.insert
local remove = table.remove
local tostring = tostring
local ActionSubTypes = ActionSubTypes
local ActivityTypes = ActivityTypes
local ContextPtr = ContextPtr
local Controls = Controls
local DomainTypes = DomainTypes
local Events = Events
local Game = Game
local GameDefines = GameDefines
local GameInfoActions = GameInfoActions
local GameInfo_Automates = GameInfo.Automates
local GameInfo_Builds = GameInfo.Builds
local GameInfo_Missions = GameInfo.Missions
local GameInfo_Units = GameInfo.Units
local L = Locale.ConvertTextKey
local ToUpper = Locale.ToUpper
--local PlotDistance = Map.PlotDistance
local Mouse = Mouse
local OrderTypes = OrderTypes
local Players = Players
local Teams = Teams
local ToHexFromGrid = ToHexFromGrid
local DoSelectCityAtPlot = UI.DoSelectCityAtPlot
local GetHeadSelectedCity = UI.GetHeadSelectedCity
local GetHeadSelectedUnit = UI.GetHeadSelectedUnit
--local GetSelectedUnitID = UI.GetSelectedUnitID
local GetUnitFlagIcon = UI.GetUnitFlagIcon
local GetUnitPortraitIcon = UI.GetUnitPortraitIcon
local LookAt = UI.LookAt
local SelectUnit = UI.SelectUnit
include "InstanceManager"
local actionIM = InstanceManager:new("UnitAction", "UnitActionButton", Controls.ActionStack)
--==========================================================
-- Globals
--==========================================================
local g_activePlayerID, g_activePlayer, g_activeTeamID, g_activeTeam, g_activeTechs
local g_AllPlayerOptions = { UnitTypes = {}, UnitsInRibbon = {} }
local g_ActivePlayerUnitTypes
local g_ActivePlayerUnitsInRibbon = {}
local g_isHideCityList, g_isHideUnitList, g_isHideUnitTypes
--[[
_ _ _ _ ___ ____ _ _ _ ____ _ _ _
| | | |_ __ (_) |_ ___ ( _ ) / ___(_) |_(_) ___ ___ | _ \(_) |__ | |__ ___ _ __
| | | | '_ \| | __/ __| / _ \/\ | | | | __| |/ _ \/ __| | |_) | | '_ \| '_ \ / _ \| '_ \
| |_| | | | | | |_\__ \ | (_> < | |___| | |_| | __/\__ \ | _ <| | |_) | |_) | (_) | | | |
\___/|_| |_|_|\__|___/ \___/\/ \____|_|\__|_|\___||___/ |_| \_\_|_.__/|_.__/ \___/|_| |_|
]]
-- NO_ACTIVITY, ACTIVITY_AWAKE, ACTIVITY_HOLD, ACTIVITY_SLEEP, ACTIVITY_HEAL, ACTIVITY_SENTRY, ACTIVITY_INTERCEPT, ACTIVITY_MISSION
local g_activityMissions = {
--[ActivityTypes.ACTIVITY_AWAKE or -1] = nil,
[ActivityTypes.ACTIVITY_HOLD or -1] = false, --GameInfo_Missions.MISSION_SKIP, -- only when moves left > 0
--[ActivityTypes.ACTIVITY_SLEEP or -1] = GameInfo_Missions.MISSION_SLEEP, -- can be sleep or fortify
[ActivityTypes.ACTIVITY_HEAL or -1] = GameInfo_Missions.MISSION_HEAL,
[ActivityTypes.ACTIVITY_SENTRY or -1] = GameInfo_Missions.MISSION_ALERT,
[ActivityTypes.ACTIVITY_INTERCEPT or -1] = GameInfo_Missions.MISSION_AIRPATROL,
--[ActivityTypes.ACTIVITY_MISSION or -1] = GameInfo_Missions.MISSION_MOVE_TO,
[-1] = nil }
local MAX_HIT_POINTS = GameDefines.MAX_HIT_POINTS or 100
local AIR_UNIT_REBASE_RANGE_MULTIPLIER = GameDefines.AIR_UNIT_REBASE_RANGE_MULTIPLIER
local RELIGION_MISSIONARY_PRESSURE_MULTIPLIER = GameDefines.RELIGION_MISSIONARY_PRESSURE_MULTIPLIER or 1
local MOVE_DENOMINATOR = GameDefines.MOVE_DENOMINATOR
local g_unitsIM, g_citiesIM, g_unitTypesIM, g_units, g_cities, g_unitTypes
local g_cityFocusIcons = {
--[CityAIFocusTypes.NO_CITY_AI_FOCUS_TYPE or -1] = "",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_FOOD or -1] = "[ICON_FOOD]",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_PRODUCTION or -1] = "[ICON_PRODUCTION]",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_GOLD or -1] = "[ICON_GOLD]",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_SCIENCE or -1] = "[ICON_RESEARCH]",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_CULTURE or -1] = "[ICON_CULTURE]",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_GREAT_PEOPLE or -1] = "[ICON_GREAT_PEOPLE]",
[CityAIFocusTypes.CITY_AI_FOCUS_TYPE_FAITH or -1] = "[ICON_PEACE]",
[-1] = nil }
local g_UnitTypeOrder = {}
do
local i = 0
for unit in GameInfo.Units() do
i = i + 65536
g_UnitTypeOrder[ unit.ID ] = i
end
end
local function SortByVoid2( a, b )
return a and b and a:GetVoid2() > b:GetVoid2()
end
--==========================================================
-- Mod Panels
--==========================================================
local addinActions = {}
local addinBuilds = {}
function OnUnitPanelActionAddin(action)
print(string.format("Adding UnitPanel action %s (%s)", Locale.ConvertTextKey(action.Title), action.Name))
table.insert(addinActions, action)
end
LuaEvents.UnitPanelActionAddin.Add(OnUnitPanelActionAddin)
-- function OnUnitPanelBuildAddin(build)
-- print(string.format("Adding UnitPanel build %s (%s)", Locale.ConvertTextKey(build.Title), build.Name))
-- table.insert(addinBuilds, build)
-- end
-- LuaEvents.UnitPanelBuildAddin.Add(OnUnitPanelBuildAddin)
do
g_uiAddins = {}
local Modding = Modding
local insert = table.insert
local uiAddins = g_uiAddins
for addin in Modding.GetActivatedModEntryPoints("UnitPanelAddin") do
local addinFile = Modding.GetEvaluatedFilePath(addin.ModID, addin.Version, addin.File)
if addinFile then
print("Loading MOD UnitPanelUIAddin\n", Modding.GetModProperty(addin.ModID, addin.Version, "Name"), addin.File )
insert(uiAddins, ContextPtr:LoadNewContext( addinFile.EvaluatedPath:match("(.*)%..*")))
end
end
end
--Insert ContextPtr for modded unit panel buttons here
--==========================================================
-- Tooltip Utilities
--==========================================================
local function lookAtPlot( plot )
local hex = ToHexFromGrid{ x=plot:GetX(), y=plot:GetY() }
Events.GameplayFX( hex.x, hex.y, -1 )
return LookAt( plot )
end
local function lookAtUnit( unit )
if unit then
return lookAtPlot( unit:GetPlot() )
end
end
--==========================================================
-- Ribbon Manager
--==========================================================
local function g_RibbonManager( name, stack, scrap, createAllItems, initItem, callbacks, tooltips, closure, toolTipCallback )
local index = {}
local spares = {}
local function Create( item, itemID, itemOrder )
if item then
local instance = remove( spares )
local button
if instance then
--debug_print("Recycle from scrap", name, instance, "item", itemID, item and item:GetName() )
button = instance.Button
button:ChangeParent( stack )
else
instance = { m_PromotionIcons={} }
--debug_print("Create new ", name, instance, "item", itemID, item and item:GetName() )
ContextPtr:BuildInstanceForControl( name, instance, stack )
-- Setup Tootip Callbacks
for controlID, toolTipType in pairs( tooltips ) do
instance[ controlID ]:SetToolTipCallback( function( control )
control:SetToolTipCallback( function( control ) return toolTipCallback( control, closure( button ) ) end )
control:SetToolTipType( toolTipType )
end)
end
-- Setup action Callbacks
button = instance.Button
for event, callback in pairs( callbacks ) do
button:RegisterCallback( event, callback )
end
end
index[ itemID ] = instance
button:SetVoids( itemID, itemOrder )
return initItem( item, instance )
--else print( "Failed attempt to add an item to the list", itemID )
end
end
return{
Create = Create,
Destroy = function( itemID )
local instance = index[ itemID ]
--debug_print( "Remove item from list", name, "item", itemID, instance )
if instance then
index[ itemID ] = nil
insert( spares, instance )
instance.Button:ChangeParent( scrap )
end
end,
Initialize = function( isHidden )
--debug_print("Initializing ", name, " stack", "hidden ?", isHidden )
for itemID, instance in pairs( index ) do
insert( spares, instance )
instance.Button:ChangeParent( scrap )
index[ itemID ] = nil
end
if not isHidden then
--debug_print("Initializing ", name, " stack contents" )
createAllItems( Create )
end
end,
}, index
end
--==========================================================
-- Item Functions
--==========================================================
local function UpdateCity( city, instance )
if city and instance then
local isNotPuppet = not city:IsPuppet()
local isRazing = city:IsRazing()
local isResistance = city:IsResistance()
local isCapital = city:IsCapital()
local itemInfo, portraitOffset, portraitAtlas, buildPercent
local turnsRemaining = city:GetProductionTurnsLeft()
local productionNeeded = city:GetProductionNeeded()
local storedProduction = city:GetProduction() + city:GetOverflowProduction() + city:GetFeatureProduction()
local orderID, itemID = city:GetOrderFromQueue()
if orderID == OrderTypes.ORDER_TRAIN then
itemInfo = GameInfo.Units
portraitOffset, portraitAtlas = GetUnitPortraitIcon( itemID, g_activePlayerID )
elseif orderID == OrderTypes.ORDER_CONSTRUCT then
itemInfo = GameInfo.Buildings
elseif orderID == OrderTypes.ORDER_CREATE then
itemInfo = GameInfo.Projects
elseif orderID == OrderTypes.ORDER_MAINTAIN then
itemInfo = GameInfo.Processes
turnsRemaining = nil
productionNeeded = 0
end
if itemInfo then
itemInfo = itemInfo[ itemID ]or{}
itemInfo = IconHookup( portraitOffset or itemInfo.PortraitIndex, 64, portraitAtlas or itemInfo.IconAtlas, instance.CityProduction )
if productionNeeded > 0 then
buildPercent = 1 - max( 0, storedProduction/productionNeeded )
end
instance.BuildMeter:SetPercents( 0, buildPercent or 0 )
end
instance.CityProduction:SetHide( not itemInfo )
instance.BuildGrowth:SetString( itemInfo and not isResistance and not isRazing and turnsRemaining )
instance.CityPopulation:SetString( city:GetPopulation() )
local foodPerTurnTimes100 = city:FoodDifferenceTimes100()
if isRazing or foodPerTurnTimes100 < 0 then
instance.CityGrowth:SetString( "[COLOR_RED]" .. (isRazing and 1 or min( floor( ( city:GetFoodTimes100() ) / -foodPerTurnTimes100 ) + 1, 99 ) ) .. "[ENDCOLOR]" )
elseif city:IsForcedAvoidGrowth() then
instance.CityGrowth:SetString( "[ICON_LOCKED]" )
elseif city:IsFoodProduction() or foodPerTurnTimes100 == 0 then
instance.CityGrowth:SetString()
else
instance.CityGrowth:SetString( min( city:GetFoodTurnsLeft(), 99 ) )
end
instance.CityIsCapital:SetHide( not isCapital )
instance.CityIsPuppet:SetHide( isNotPuppet )
instance.CityFocus:SetText( not isRazing and isNotPuppet and g_cityFocusIcons[city:GetFocusType()] )
instance.CityQuests:SetText( city:GetWeLoveTheKingDayCounter() > 0 and "[ICON_HAPPINESS_1]" or (GameInfo.Resources[city:GetResourceDemanded()] or {}).IconString )
instance.CityIsRazing:SetHide( not isRazing )
instance.CityIsResistance:SetHide( not isResistance )
instance.CityResistanceTurns:SetText( isRazing and city:GetRazingTurns() or isResistance and city:GetResistanceTurns() )
instance.CityIsConnected:SetHide( isCapital or not g_activePlayer:IsCapitalConnectedToCity( city ) )
instance.CityIsBlockaded:SetHide( not city:IsBlockaded() )
instance.CityIsOccupied:SetHide( not city:IsOccupied() or city:IsNoOccupiedUnhappiness() )
instance.CityName:SetString( city:GetName() )
local religion = city.GetReligiousMajority and GameInfo.Religions[city:GetReligiousMajority()]
instance.CityReligion:SetString( religion and religion.IconString )
local culturePerTurn = city:GetJONSCulturePerTurn()
instance.BorderGrowth:SetString( culturePerTurn > 0 and ceil( (city:GetJONSCultureThreshold() - city:GetJONSCultureStored()) / culturePerTurn ) )
local percent = 1 - city:GetDamage() / ( city.GetMaxHitPoints and city:GetMaxHitPoints() or GameDefines.MAX_CITY_HIT_POINTS )
instance.Button:SetColor( Color( 1, percent, percent, 1 ) )
end
end
local function UpdateUnit( unit, instance, nextInstance )
if unit and instance then
local unitMovesLeft = unit:MovesLeft()
local pip
if unitMovesLeft >= unit:MaxMoves() then
pip = 0 -- cyan (green)
elseif unitMovesLeft > 0 then
if unit:IsCombatUnit() and unit:IsOutOfAttacks() then
pip = 96 -- orange (gray)
else
pip = 32 -- green (yellow)
end
else
pip = 64 -- red
end
local damage = unit:GetDamage()
local percent
if damage <= 0 then
percent = 1
elseif instance == Controls then
percent = 1 - damage / MAX_HIT_POINTS / 3
else
percent = 1 - damage / MAX_HIT_POINTS
end
local info
local text
local buildID = unit:GetBuildType()
if buildID ~= -1 then -- unit is actively building something
info = GameInfo_Builds[buildID]
text = GetUnitBuildProgressData( unit:GetPlot(), buildID, unit )
if text > 99 then text = nil end
elseif unit:IsEmbarked() then
info = GameInfo_Missions.MISSION_EMBARK
elseif unit:IsReadyToMove() then
elseif unit:IsAutomated() then
if unit:IsWork() then
info = GameInfo_Automates.AUTOMATE_BUILD
elseif bnw_mode and unit:IsTrade() then
info = GameInfo_Missions.MISSION_ESTABLISH_TRADE_ROUTE
else
info = GameInfo_Automates.AUTOMATE_EXPLORE
end
elseif unit:LastMissionPlot() ~= unit:GetPlot() then
info = GameInfo_Missions.MISSION_MOVE_TO
elseif unit:IsWaiting() then
local activityType = unit:GetActivityType()
info = g_activityMissions[ activityType ]
if not info and unitMovesLeft > 0 then
--print( "ACTIVITY_MISSION", unit:GetName(), unit:GetX(), unit:GetY(), unit:GetPlot() ~= unit:LastMissionPlot() )
if info == false then
info = GameInfo_Missions.MISSION_SKIP
elseif unit:IsGarrisoned() then
info = GameInfo_Missions.MISSION_GARRISON
elseif unit:IsEverFortifyable() then
info = GameInfo_Missions.MISSION_FORTIFY
else
info = GameInfo_Missions.MISSION_SLEEP
end
end
elseif unitMovesLeft > 0 then
info = GameInfo_Missions.MISSION_MOVE_TO
end
repeat
instance.Button:SetColor( Color( 1, percent, percent, 1 ) )
instance.MovementPip:SetTextureOffsetVal( 0, pip )
instance.Mission:SetHide( not( info and IconHookup( info.IconIndex, 45, info.IconAtlas, instance.Mission ) ) )
instance.MissionText:SetText( text )
if nextInstance then
instance, nextInstance = nextInstance
instance.MovementPip:Play()
else
break
end
until false
end
end
local function FilterUnit( unit )
return unit and g_ActivePlayerUnitsInRibbon[ unit:GetUnitType() ]
end
--==========================================================
-- Unit Ribbon "Object"
--==========================================================
local CallFlagManagerUpdateUnitPromotions = LuaEvents.CallFlagManagerUpdateUnitPromotions.Call
g_unitsIM, g_units = g_RibbonManager( "UnitInstance", Controls.UnitStack, Controls.Scrap,
function( Create ) -- createAllItems( Create )
local unitID
for unit in g_activePlayer:Units() do
if FilterUnit( unit ) then
unitID = unit:GetID()
Create( unit, unitID, g_UnitTypeOrder[unit:GetUnitType()] + unitID % 65536 )
end
end
Controls.UnitStack:SortChildren( SortByVoid2 )
end,
function( unit, instance ) -- initItem( item, instance )
local portraitOffset, portraitAtlas = GetUnitPortraitIcon( unit )
IconHookup( portraitOffset, 64, portraitAtlas, instance.Portrait )
if unit == GetHeadSelectedUnit() then
instance.MovementPip:Play()
else
instance.MovementPip:SetToBeginning()
end
UpdateUnit( unit, instance )
return CallFlagManagerUpdateUnitPromotions( unit )
end,
{-- the callback function table names need to match associated instance control ID defined in xml
[Mouse.eLClick] = function( unitID )
local unit = g_activePlayer:GetUnitByID( unitID )
SelectUnit( unit )
lookAtUnit( unit )
end,
[Mouse.eRClick] = function( unitID )
lookAtUnit( g_activePlayer:GetUnitByID( unitID ) )
end,
},--/unit callbacks
{
Button = "EUI_UnitTooltip",
MovementPip = "EUI_ItemTooltip",
Mission = "EUI_ItemTooltip",
},
function( button )
return g_activePlayer:GetUnitByID( button:GetVoid1() )
end,
LuaEvents.UnitToolTips.Call
)--/unit ribbon object
--==========================================================
LuaEvents.EUI_UnitRibbonTable( g_units )
--==========================================================
-- City Ribbon "Object"
--==========================================================
g_citiesIM, g_cities = g_RibbonManager( "CityInstance", Controls.CityStack, Controls.Scrap,
function( Create ) -- createAllItems( Create )
for city in g_activePlayer:Cities() do
Create( city, city:GetID() )
end
end,
UpdateCity, -- initItem( item, instance )
{-- the callback function table names need to match associated instance control ID defined in xml
[Mouse.eLClick] = function( cityID )
local city = g_activePlayer:GetCityByID( cityID )
if city then
DoSelectCityAtPlot( city:Plot() )
end
end,
[Mouse.eRClick] = function( cityID )
local city = g_activePlayer:GetCityByID( cityID )
if city then
lookAtPlot( city:Plot() )
end
end,
},--/city callbacks
{
Button = "EUI_CityProductionTooltip",
CityPopulation = "EUI_CityGrowthTooltip",
-- CityProduction = "EUI_CityProductionTooltip",
-- BuildMeter = "EUI_ItemTooltip",
-- GrowthMeter = "EUI_ItemTooltip",
CityIsCapital = "EUI_ItemTooltip",
CityIsPuppet = "EUI_ItemTooltip",
CityIsOccupied = "EUI_ItemTooltip",
CityIsResistance = "EUI_ItemTooltip",
CityIsRazing = "EUI_ItemTooltip",
CityIsConnected = "EUI_ItemTooltip",
CityIsBlockaded = "EUI_ItemTooltip",
CityReligion = "EUI_ItemTooltip",
CityFocus = "EUI_ItemTooltip",
CityGrowth = "EUI_ItemTooltip",
CityQuests = "EUI_ItemTooltip",
BuildGrowth = "EUI_ItemTooltip",
BorderGrowth = "EUI_ItemTooltip",
},
function( button )
return g_activePlayer:GetCityByID( button:GetVoid1() )
end,
LuaEvents.CityToolTips.Call
)--/city ribbon object
--==========================================================
--[[
_ _ _ _ ____ _
| | | |_ __ (_) |_ | _ \ __ _ _ __ ___| |
| | | | '_ \| | __| | |_) / _` | '_ \ / _ \ |
| |_| | | | | | |_ | __/ (_| | | | | __/ |
\___/|_| |_|_|\__| |_| \__,_|_| |_|\___|_|
]]
local g_screenWidth , g_screenHeight = UIManager:GetScreenSizeVal()
local g_topOffset0 = Controls.CityPanel:GetOffsetY()
local g_topOffset = g_topOffset0
local g_bottomOffset0 = Controls.UnitPanel:GetOffsetY()
local g_bottomOffset = g_bottomOffset0
local g_Actions = {}
local g_Promotions = {}
local g_UnusedControls = Controls.Scrap
local g_lastUnit -- Used to determine if a different unit has been selected.
local g_isWorkerActionPanelOpen = false
local g_unitPortraitSize = Controls.UnitPortrait:GetSizeX()
local g_actionButtonSpacing = OptionsManager.GetSmallUIAssets() and 42 or 58
--[[
local g_actionIconSize = OptionsManager.GetSmallUIAssets() and 36 or 50
local g_recommendedActionButton = {}
ContextPtr:BuildInstanceForControlAtIndex( "UnitAction", g_recommendedActionButton, Controls.WorkerActionStack, 1 )
--Controls.RecommendedActionLabel:ChangeParent( g_recommendedActionButton.UnitActionButton )
local g_existingBuild = {}
ContextPtr:BuildInstanceForControl( "UnitAction", g_existingBuild, Controls.WorkerActionStack )
g_existingBuild.WorkerProgressBar:SetPercent( 1 )
g_existingBuild.UnitActionButton:SetDisabled( true )
g_existingBuild.UnitActionButton:SetAlpha( 0.8 )
--]]
--==========================================================
-- Event Handlers
--==========================================================
local function OnUnitActionClicked( actionID )
local action = GameInfoActions[actionID]
if action and g_activePlayer:IsTurnActive() then
Game.HandleAction( actionID )
if action.SubType == ActionSubTypes.ACTIONSUBTYPE_PROMOTION then
Events.AudioPlay2DSound("AS2D_INTERFACE_UNIT_PROMOTION")
end
end
end
Controls.CycleLeft:RegisterCallback( Mouse.eLClick,
function()
-- Cycle to next selection.
Game.CycleUnits(true, true, false)
end)
Controls.CycleRight:RegisterCallback( Mouse.eLClick,
function()
-- Cycle to previous selection.
Game.CycleUnits(true, false, false)
end)
local function OnUnitNameClicked()
-- go to this unit
lookAtUnit( GetHeadSelectedUnit() )
end
Controls.UnitNameButton:RegisterCallback( Mouse.eLClick, OnUnitNameClicked )
do
local UnitToolTipCall = LuaEvents.UnitToolTip.Call
Controls.UnitPortraitButton:SetToolTipCallback( function( control )
control:SetToolTipCallback( function() return UnitToolTipCall( GetHeadSelectedUnit(), L"TXT_KEY_CURRENTLY_SELECTED_UNIT", "----------------" ) end )
control:SetToolTipType( "EUI_UnitTooltip" )
end)
end
Controls.UnitPortraitButton:RegisterCallback( Mouse.eLClick, OnUnitNameClicked )
Controls.UnitPortraitButton:RegisterCallback( Mouse.eRClick,
function()
local unit = GetHeadSelectedUnit()
Events.SearchForPediaEntry( unit and unit:GetNameKey() )
end)
local function OnEditNameClick()
if GetHeadSelectedUnit() then
Events.SerialEventGameMessagePopup{
Type = ButtonPopupTypes.BUTTONPOPUP_RENAME_UNIT,
Data1 = GetHeadSelectedUnit():GetID(),
Data2 = -1,
Data3 = -1,
Option1 = false,
Option2 = false
}
end
end
Controls.EditButton:RegisterCallback( Mouse.eLClick, OnEditNameClick )
Controls.UnitNameButton:RegisterCallback( Mouse.eRClick, OnEditNameClick )
--==========================================================
-- Utilities
--==========================================================
local function ResizeCityUnitRibbons()
--debug_print("ResizeCityUnitRibbons" )
local maxTotalStackHeight = g_screenHeight - g_topOffset - g_bottomOffset
local halfTotalStackHeight = floor(maxTotalStackHeight / 2)
Controls.CityStack:CalculateSize()
local cityStackHeight = Controls.CityStack:GetSizeY()
Controls.UnitStack:CalculateSize()
local unitStackHeight = Controls.UnitStack:GetSizeY()
if unitStackHeight + cityStackHeight <= maxTotalStackHeight then
unitStackHeight = false
halfTotalStackHeight = false
elseif cityStackHeight <= halfTotalStackHeight then
unitStackHeight = maxTotalStackHeight - cityStackHeight
halfTotalStackHeight = false
elseif unitStackHeight <= halfTotalStackHeight then
cityStackHeight = maxTotalStackHeight - unitStackHeight
unitStackHeight = false
else
cityStackHeight = halfTotalStackHeight
unitStackHeight = halfTotalStackHeight
end
Controls.CityScrollPanel:SetHide( not halfTotalStackHeight )
if halfTotalStackHeight then
Controls.CityStack:ChangeParent( Controls.CityScrollPanel )
Controls.CityScrollPanel:SetSizeY( cityStackHeight )
Controls.CityScrollPanel:CalculateInternalSize()
else
Controls.CityStack:ChangeParent( Controls.CityPanel )
end
Controls.CityPanel:ReprocessAnchoring()
Controls.DarkBorders:SetSizeY( cityStackHeight+g_topOffset )
-- Controls.CityPanel:SetSizeY( cityStackHeight )
Controls.UnitScrollPanel:SetHide( not unitStackHeight )
if unitStackHeight then
Controls.UnitStack:ChangeParent( Controls.UnitScrollPanel )
Controls.UnitScrollPanel:SetSizeY( unitStackHeight )
Controls.UnitScrollPanel:CalculateInternalSize()
else
Controls.UnitStack:ChangeParent( Controls.UnitPanel )
end
Controls.UnitPanel:ReprocessAnchoring()
end
local function UpdateUnits()
local activePlayer = g_activePlayer
for unitID, instance in pairs( g_units ) do
UpdateUnit( activePlayer:GetUnitByID( unitID ), instance )
end
end
local function UpdateCities()
local activePlayer = g_activePlayer
for cityID, instance in pairs( g_cities ) do
UpdateCity( activePlayer:GetCityByID( cityID ), instance )
end
end
local function UpdateSpecificCity( playerID, cityID )
if playerID == g_activePlayerID then
UpdateCity( g_activePlayer:GetCityByID( cityID ), g_cities[cityID] )
end
end
local function SelectUnitType( isChecked, unitTypeID ) -- Void2, control )
g_ActivePlayerUnitsInRibbon[ unitTypeID ] = isChecked
g_unitsIM.Initialize( g_isHideUnitList )
ResizeCityUnitRibbons()
-- only save player 0 preferences, not other hotseat player's
if g_activePlayerID == 0 then
UserInterfaceSettings[ "RIBBON_"..GameInfo_Units[ unitTypeID ].Type] = isChecked and 1 or 0
end
end
local function ResizeUnitTypesPanel()
-- if not g_isHideUnitTypes then
local n = Controls.UnitTypesStack:GetNumChildren()
Controls.UnitTypesStack:SetWrapWidth( ceil( n / ceil( n / 5 ) ) * 64 )
Controls.UnitTypesStack:CalculateSize()
local x, y = Controls.UnitTypesStack:GetSizeVal()
if y<64 then y=64 elseif y>320 then y=320 end
Controls.UnitTypesPanel:SetSizeVal( x+40, y+85 )
Controls.UnitTypesScrollPanel:SetSizeVal( x, y )
Controls.UnitTypesScrollPanel:CalculateInternalSize()
Controls.UnitTypesScrollPanel:ReprocessAnchoring()
end
local function AddUnitType( unit, unitID )
local unitTypeID = unit:GetUnitType()
g_ActivePlayerUnitTypes[ unitID or unit:GetID() ] = unitTypeID
local instance = g_unitTypes[ unitTypeID ]
if instance then
--debug_print( "Add unit:", unit:GetID(), unit:GetName(), "type:", instance, unitTypeID, "count:", n )
return instance.Count:SetText( instance.Count:GetText()+1 )
else
--debug_print( "Add unit:", unit:GetID(), unit:GetName(), "new type:", unitTypeID )
g_unitTypesIM.Create( unit, unitTypeID, -g_UnitTypeOrder[unitTypeID] )
if unitID then
Controls.UnitTypesStack:SortChildren( SortByVoid2 )
return ResizeUnitTypesPanel()
end
end
end
--==========================================================
-- Unit Options "Object"
--==========================================================
g_unitTypesIM, g_unitTypes = g_RibbonManager( "UnitTypeInstance", Controls.UnitTypesStack, Controls.Scrap,
function() -- createAllItems
g_ActivePlayerUnitTypes = {}
for unit in g_activePlayer:Units() do
AddUnitType( unit )
end
Controls.UnitTypesStack:SortChildren( SortByVoid2 )
return ResizeUnitTypesPanel()
end,
function( unit, instance ) -- initItem( item, instance )
local portrait = instance.Portrait
local portraitOffset, portraitAtlas = GetUnitPortraitIcon( unit )
portrait:SetHide(not ( portraitOffset and portraitAtlas and IconHookup( portraitOffset, portrait:GetSizeX(), portraitAtlas, portrait ) ) )
instance.CheckBox:RegisterCheckHandler( SelectUnitType )
local unitTypeID = unit:GetUnitType()
instance.CheckBox:SetCheck( g_ActivePlayerUnitsInRibbon[ unitTypeID ] )
instance.CheckBox:SetVoid1( unitTypeID )
instance.Count:SetText("1")
end,
{-- the callback function table names need to match associated instance control ID defined in xml
[Mouse.eRClick] = function( unitTypeID )
local unit = GameInfo.Units[ unitTypeID ]
if unit then
Events.SearchForPediaEntry( unit.Description )
end
end,
},--/unit options callbacks
{-- the tooltip function names need to match associated instance control ID defined in xml
Button = "EUI_ItemTooltip",
},--/units options tooltips
function( button )
return button:GetVoid1()
end,
LuaEvents.UnitPanelItemTooltip.Call
)--/unit options object
local function CreateUnit( playerID, unitID ) --hexVec, unitType, cultureType, civID, primaryColor, secondaryColor, unitFlagIndex, fogState, selected, military, notInvisible )
if playerID == g_activePlayerID then
local unit = g_activePlayer:GetUnitByID( unitID )
--debug_print("Create unit", unitID, unit and unit:GetName() )
if unit then
AddUnitType( unit, unitID )
if FilterUnit( unit ) then
g_unitsIM.Create( unit, unitID, g_UnitTypeOrder[unit:GetUnitType()] + unitID % 65536 )
Controls.UnitStack:SortChildren( SortByVoid2 )
return ResizeCityUnitRibbons()
end
end
end
end
local function CreateCity( hexPos, playerID, cityID ) --, cultureType, eraType, continent, populationSize, size, fowState )
if playerID == g_activePlayerID then
g_citiesIM.Create( g_activePlayer:GetCityByID( cityID ), cityID )
return ResizeCityUnitRibbons()
end
end
local function DestroyUnit( playerID, unitID )
if playerID == g_activePlayerID then
g_unitsIM.Destroy( unitID )
local unitTypeID = g_ActivePlayerUnitTypes[ unitID ]
local instance = g_unitTypes[ unitTypeID ]
--debug_print( "Destroy unit", unitID, "type:", g_ActivePlayerUnitTypes[ unitID ], instance, "previous count:", instance.Count )
g_ActivePlayerUnitTypes[ unitID ] = nil
if instance then
local n = instance.Count:GetText() - 1
if n <= 0 then
g_unitTypesIM.Destroy( unitTypeID )
ResizeUnitTypesPanel()
else
instance.Count:SetText( n )
end
end
return ResizeCityUnitRibbons()
end
end
local function DestroyCity( hexPos, playerID, cityID )
if playerID == g_activePlayerID then
g_citiesIM.Destroy( cityID )
return ResizeCityUnitRibbons()
end
end
local function SetHide( ... )
for _, control in pairs{...} do
control:SetHide( true )
end
end
local function SetShow( ... )
for _, control in pairs{...} do
control:SetHide( false )
end
end
local function SetTextAndFontSize( control, text, x )
control:SetText( text )
for i = 24, 14, -2 do
control:SetFontByName( "TwCenMT"..i )
if control:GetSizeVal() <= x then
break
end
end
end
local function DeselectLastUnit( unit )
if g_lastUnit then
local lastUnitID = g_lastUnit:GetID()
Events.UnitSelectionChanged( g_lastUnit:GetOwner(), lastUnitID, 0, 0, 0, false, false )
local instance = g_units[ lastUnitID ]
if instance then
instance.MovementPip:SetToBeginning()
UpdateUnit( g_lastUnit, instance )
end
end
g_lastUnit = unit
end
local g_infoSource = {
[ ActionSubTypes.ACTIONSUBTYPE_PROMOTION or -1 ] = GameInfo.UnitPromotions,
[ ActionSubTypes.ACTIONSUBTYPE_INTERFACEMODE or -1 ] = GameInfo.InterfaceModes,
[ ActionSubTypes.ACTIONSUBTYPE_MISSION or -1 ] = GameInfo.Missions,
[ ActionSubTypes.ACTIONSUBTYPE_COMMAND or -1 ] = GameInfo.Commands,
[ ActionSubTypes.ACTIONSUBTYPE_AUTOMATE or -1 ] = GameInfo.Automates,
[ ActionSubTypes.ACTIONSUBTYPE_BUILD or -1 ] = GameInfo.Builds,
[ ActionSubTypes.ACTIONSUBTYPE_CONTROL or -1 ] = GameInfo.Controls,
[-1] = nil
}
local UnitActionToolTipCall = LuaEvents.UnitActionToolTip.Call
local function UnitActionToolTip( button )
button:SetToolTipCallback( UnitActionToolTipCall )
button:SetToolTipType( "EUI_UnitAction" )
end
local function UpdateUnitPanel()
actionIM:ResetInstances()
-- Retrieve the currently selected unit.
local unit = GetHeadSelectedUnit()
-- Events.GameplayAlertMessage( "SerialEventUnitInfoDirty, GetHeadSelectedUnit=".. tostring(unit and unit:GetName())..", last unit="..tostring(g_lastUnit and g_lastUnit:GetName()) )
--debug_print( "UpdateUnitPanel", "GetHeadSelectedCity", GetHeadSelectedCity() and GetHeadSelectedCity():GetName(), "GetHeadSelectedUnit", GetHeadSelectedUnit()and GetHeadSelectedUnit():GetName(), "Last unit", g_lastUnit and g_lastUnit:GetName() )
if unit then
local unitID = unit:GetID()
-- Selected Unit
if unit ~= g_lastUnit then
DeselectLastUnit( unit )
local hexPosition = ToHexFromGrid{ x = unit:GetX(), y = unit:GetY() }
Events.UnitSelectionChanged( unit:GetOwner(), unitID, hexPosition.x, hexPosition.y, 0, true, false )
end
local unitMovesLeft = unit:MovesLeft() / MOVE_DENOMINATOR
local unitPlot = unit:GetPlot()
-- Unit Name
SetTextAndFontSize( Controls.UnitName, ToUpper( L( unit:IsGreatPerson() and unit:HasName() and unit:GetNameNoDesc() or unit:GetName() ) ), Controls.UnitNameButton:GetSizeVal()-50 )
-- Unit Actions
local canPromote = unit:IsPromotionReady()
local GameCanHandleAction = Game.CanHandleAction
local numBuildActions = 0
local action, instance, button, buildTurnsLeft, buildProgress, buildTime, canBuild, isBuildRecommended
--==========================================================
--Mod Actions
--==========================================================
local function SetToolTip(sTitle, sToolTip)
print(string.format("Setting Tooltip: Title: %s - Tooltip: %s", sTitle, sToolTip))
local ttTable = {}
TTManager:GetTypeControlTable( "EUI_UnitAction", ttTable )
ttTable.UnitActionHelp:SetText(string.format("[NEWLINE]%s", sToolTip))
ttTable.UnitActionText:SetText(string.format("[COLOR_POSITIVE_TEXT]%s[ENDCOLOR]", Locale.ConvertTextKey(sTitle)))
ttTable.UnitActionHotKey:SetText("")
ttTable.UnitActionMouseover:DoAutoSize()
local mouseoverSize = ttTable.UnitActionMouseover:GetSize();
if (mouseoverSize.x < 350) then
ttTable.UnitActionMouseover:SetSizeX(350)
end
end
for _, action in pairs(addinActions) do
print(string.format("Processing UnitPanel action %s (%s)", Locale.ConvertTextKey(action.Title), action.Name))
if (action.Condition == nil or
(type(action.Condition) == "function" and action.Condition(action, unit)) or
(type(action.Condition) ~= "function" and action.Condition)) then
local instance = actionIM:GetInstance()
if ((type(action.Disabled) == "function" and action.Disabled(action, unit)) or
(type(action.Disabled) ~= "function" and action.Disabled)) then
instance.UnitActionButton:SetAlpha(0.4)
instance.UnitActionButton:SetDisabled(true)
else
instance.UnitActionButton:SetAlpha(1.0)
instance.UnitActionButton:SetDisabled(false)
end
IconHookup(action.PortraitIndex, actionIconSize, action.IconAtlas, instance.UnitActionIcon)
local sTitle
if (type(action.Title) == "function") then
sTitle = action.Title(action, unit)
else
sTitle = action.Title
end
local sToolTip
if (type(action.ToolTip) == "function") then
sToolTip = action.ToolTip(action, unit)
else
sToolTip = action.ToolTip
end
instance.UnitActionButton:SetToolTipCallback(function() SetToolTip(sTitle, sToolTip) end)
if (type(action.Action) == "function") then
instance.UnitActionButton:RegisterCallback(Mouse.eLClick, function() action.Action(action, unit, Mouse.eLClick) end)
instance.UnitActionButton:RegisterCallback(Mouse.eRClick, function() action.Action(action, unit, Mouse.eRClick) end)
else
instance.UnitActionButton:RegisterCallback(Mouse.eLClick, function() end)
instance.UnitActionButton:RegisterCallback(Mouse.eRClick, function() end)
end
end
end
-- for _, build in pairs(addinBuilds) do
-- if (build.Condition == nil or
-- (type(build.Condition) == "function" and build.Condition(build, unit)) or
-- (type(build.Condition) ~= "function" and build.Condition)) then
-- local instance = g_BuildIM:GetInstance()
-- instance.UnitActionButton:SetAnchor( "L,B" )
-- instance.UnitActionButton:SetOffsetVal((numBuildActions % numberOfButtonsPerRow) * buttonSize + buttonPadding + buttonOffsetX, math.floor(numBuildActions / numberOfButtonsPerRow) * buttonSize + buttonPadding + buttonOffsetY)
-- numBuildActions = numBuildActions + 1
-- if ((type(build.Disabled) == "function" and build.Disabled(build, unit)) or
-- (type(build.Disabled) ~= "function" and build.Disabled)) then
-- instance.UnitActionButton:SetAlpha(0.4)
-- instance.UnitActionButton:SetDisabled(true)
-- else
-- instance.UnitActionButton:SetAlpha(1.0)
-- instance.UnitActionButton:SetDisabled(false)
-- end
-- IconHookup(build.PortraitIndex, actionIconSize, build.IconAtlas, instance.UnitActionIcon)
-- local sToolTip
-- if (type(build.ToolTip) == "function") then
-- sToolTip = build.ToolTip(build, unit)
-- else
-- sToolTip = build.ToolTip
-- end
-- instance.UnitActionButton:SetToolTipCallback(function() SetToolTip(build.Title, sToolTip) end)
-- if (type(build.Build) == "function") then
-- instance.UnitActionButton:RegisterCallback(Mouse.eLClick, function() build.Build(build, unit, Mouse.eLClick) end)
-- instance.UnitActionButton:RegisterCallback(Mouse.eRClick, function() build.Build(build, unit, Mouse.eRClick) end)
-- else
-- instance.UnitActionButton:RegisterCallback(Mouse.eLClick, function() end)
-- instance.UnitActionButton:RegisterCallback(Mouse.eRClick, function() end)
-- end
-- if (recommendedBuild == nil and
-- ((type(build.Recommended) == "function" and build.Recommended(build, unit)) or
-- (type(build.Recommended) ~= "function" and build.Recommended))) then
-- recommendedBuild = build;
-- IconHookup(build.PortraitIndex, actionIconSize, build.IconAtlas, Controls.RecommendedActionImage)
-- if (type(build.Build) == "function") then
-- Controls.RecommendedActionButton:RegisterCallback(Mouse.eLClick, function() build.Build(build, unit, Mouse.eLClick) end)
-- Controls.RecommendedActionButton:RegisterCallback(Mouse.eRClick, function() build.Build(build, unit, Mouse.eRClick) end)
-- else
-- Controls.RecommendedActionButton:RegisterCallback(Mouse.eLClick, function() end)
-- Controls.RecommendedActionButton:RegisterCallback(Mouse.eRClick, function() end)