This repository has been archived by the owner on Jul 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
hooks.cpp
2399 lines (2016 loc) · 98.7 KB
/
hooks.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the modding toolset for Disciples 2.
* (https://github.com/VladimirMakeev/D2ModdingToolset)
* Copyright (C) 2020 Vladimir Makeev.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hooks.h"
#include "aigiveitemsaction.h"
#include "aigiveitemsactionhooks.h"
#include "attackimpl.h"
#include "attackreachcat.h"
#include "attackutils.h"
#include "autodialog.h"
#include "batattackbestowwards.h"
#include "batattackdoppelganger.h"
#include "batattackdrain.h"
#include "batattackdrainlevel.h"
#include "batattackdrainoverflow.h"
#include "batattackgiveattack.h"
#include "batattackgroupupgrade.h"
#include "batattackshatter.h"
#include "batattacksummon.h"
#include "batattacktransformother.h"
#include "batattacktransformself.h"
#include "batattackuntransformeffect.h"
#include "batbigface.h"
#include "battleattackinfo.h"
#include "battlemsgdatahooks.h"
#include "battleviewerinterf.h"
#include "battleviewerinterfhooks.h"
#include "bestowwardshooks.h"
#include "buildingbranch.h"
#include "buildingtype.h"
#include "button.h"
#include "citystackinterf.h"
#include "citystackinterfhooks.h"
#include "cmdbattlechooseactionmsg.h"
#include "cmdbattleendmsg.h"
#include "cmdbattleresultmsg.h"
#include "cmdbattlestartmsg.h"
#include "commandmsghooks.h"
#include "condinterf.h"
#include "condinterfhooks.h"
#include "customattackhooks.h"
#include "customattacks.h"
#include "customattackutils.h"
#include "custombuildingcategories.h"
#include "d2string.h"
#include "dbfaccess.h"
#include "dbtable.h"
#include "dialoginterf.h"
#include "difficultylevel.h"
#include "displayhandlershooks.h"
#include "doppelgangerhooks.h"
#include "drainattackhooks.h"
#include "drainlevelhooks.h"
#include "dynamiccast.h"
#include "dynupgrade.h"
#include "editboxinterf.h"
#include "editor.h"
#include "effectinterfhooks.h"
#include "effectresulthooks.h"
#include "enclayoutcityhooks.h"
#include "enclayoutruinhooks.h"
#include "enclayoutstack.h"
#include "enclayoutstackhooks.h"
#include "enclayoutunithooks.h"
#include "encparambase.h"
#include "encparambasehooks.h"
#include "eventconditioncathooks.h"
#include "eventeffectcathooks.h"
#include "exchangeinterf.h"
#include "exchangeinterfhooks.h"
#include "fonts.h"
#include "fontshooks.h"
#include "fortcategory.h"
#include "fortification.h"
#include "gameutils.h"
#include "globaldata.h"
#include "groupupgradehooks.h"
#include "idlist.h"
#include "interfmanager.h"
#include "interftexthooks.h"
#include "intvector.h"
#include "isoenginegroundhooks.h"
#include "itembase.h"
#include "itemcategory.h"
#include "itemexpotionboost.h"
#include "itemtransferhooks.h"
#include "itemutils.h"
#include "leaderabilitycat.h"
#include "listbox.h"
#include "log.h"
#include "lordtype.h"
#include "mainview2.h"
#include "mainview2hooks.h"
#include "managestkinterf.h"
#include "managestkinterfhooks.h"
#include "mempool.h"
#include "menuloadskirmishmultihooks.h"
#include "menunewskirmishhooks.h"
#include "menunewskirmishhotseathooks.h"
#include "menunewskirmishmultihooks.h"
#include "menunewskirmishsingle.h"
#include "menunewskirmishsinglehooks.h"
#include "menuphasehooks.h"
#include "menuprotocolhooks.h"
#include "middatacache.h"
#include "midevconditionhooks.h"
#include "mideveffecthooks.h"
#include "mideventhooks.h"
#include "midgardid.h"
#include "midgardmsgbox.h"
#include "midgardscenariomap.h"
#include "midgardstreamenv.h"
#include "midmsgboxbuttonhandlerstd.h"
#include "midmusic.h"
#include "midplayer.h"
#include "midscenvariables.h"
#include "midserverlogic.h"
#include "midserverlogichooks.h"
#include "midstack.h"
#include "midunitdescriptor.h"
#include "midunitdescriptorhooks.h"
#include "midunithooks.h"
#include "midvillage.h"
#include "modifgroup.h"
#include "modifgrouphooks.h"
#include "modifierutils.h"
#include "movepathhooks.h"
#include "musichooks.h"
#include "netmsghooks.h"
#include "netplayerinfo.h"
#include "netsingleplayer.h"
#include "netsingleplayerhooks.h"
#include "originalfunctions.h"
#include "phasegame.h"
#include "playerbuildings.h"
#include "playerincomehooks.h"
#include "racecategory.h"
#include "racetype.h"
#include "restrictions.h"
#include "scenariodata.h"
#include "scenariodataarray.h"
#include "scenarioinfo.h"
#include "settings.h"
#include "sitemerchantinterf.h"
#include "sitemerchantinterfhooks.h"
#include "smartptr.h"
#include "stackbattleactionmsg.h"
#include "summonhooks.h"
#include "testconditionhooks.h"
#include "transformotherhooks.h"
#include "transformselfhooks.h"
#include "umattack.h"
#include "umattackhooks.h"
#include "umunit.h"
#include "umunithooks.h"
#include "unitbranchcat.h"
#include "unitgenerator.h"
#include "unitmodifier.h"
#include "unitmodifierhooks.h"
#include "unitsforhire.h"
#include "unitstovalidate.h"
#include "unitutils.h"
#include "untransformeffecthooks.h"
#include "usracialsoldier.h"
#include "ussoldier.h"
#include "usstackleader.h"
#include "usunitimpl.h"
#include "utils.h"
#include "version.h"
#include "visitors.h"
#include <algorithm>
#include <cstring>
#include <fmt/format.h>
#include <fstream>
#include <iterator>
#include <string>
namespace hooks {
/** Hooks that used only in game. */
static Hooks getGameHooks()
{
using namespace game;
auto& fn = gameFunctions();
auto& battle = BattleMsgDataApi::get();
auto& orig = getOriginalFunctions();
// clang-format off
Hooks hooks{
// Fix game crash in battles with summoners
{CMidUnitApi::get().removeModifier, removeModifierHooked},
// Fix unit transformation to include hp mods into current hp recalculation
{CMidUnitApi::get().transform, transformHooked},
// Show buildings with custom branch category on the 'other buildings' tab
{CBuildingBranchApi::get().constructor, buildingBranchCtorHooked},
// Allow alchemists to buff retreating units
{CBatAttackGiveAttackApi::vftable()->canPerform, giveAttackCanPerformHooked},
// Random scenario generator
{CMenuNewSkirmishSingleApi::get().constructor, menuNewSkirmishSingleCtorHooked, (void**)&orig.menuNewSkirmishSingleCtor},
{CMenuNewSkirmishHotseatApi::get().constructor, menuNewSkirmishHotseatCtorHooked, (void**)&orig.menuNewSkirmishHotseatCtor},
{CMenuNewSkirmishMultiApi::get().constructor, menuNewSkirmishMultiCtorHooked, (void**)&orig.menuNewSkirmishMultiCtor},
// Random scenario generator templates
{CMenuPhaseApi::get().constructor, menuPhaseCtorHooked, (void**)&orig.menuPhaseCtor},
{CMenuPhaseApi::vftable()->destructor, menuPhaseDtorHooked, (void**)&orig.menuPhaseDtor},
// Support custom battle attack objects
{fn.createBatAttack, createBatAttackHooked, (void**)&orig.createBatAttack},
// Support immunity bitmask in BattleMsgData
{fn.getAttackClassWardFlagPosition, getAttackClassWardFlagPositionHooked, (void**)&orig.getAttackClassWardFlagPosition},
// Support custom attack animations?
{fn.attackClassToString, attackClassToStringHooked, (void**)&orig.attackClassToString},
// Add items transfer buttons to city interface
{CCityStackInterfApi::get().constructor, cityStackInterfCtorHooked, (void**)&orig.cityStackInterfCtor},
// Add items transfer buttons to stack exchange interface
{CExchangeInterfApi::get().constructor, exchangeInterfCtorHooked, (void**)&orig.exchangeInterfCtor},
// Add items transfer buttons to pickup drop interface
{CPickUpDropInterfApi::get().constructor, pickupDropInterfCtorHooked, (void**)&orig.pickupDropInterfCtor},
// Add sell all valuables button to merchant interface
{CSiteMerchantInterfApi::get().constructor, siteMerchantInterfCtorHooked, (void**)&orig.siteMerchantInterfCtor},
// Cities can generate daily income depending on scenario variable settings
{fn.computePlayerDailyIncome, computePlayerDailyIncomeHooked, (void**)&orig.computePlayerDailyIncome},
// Vampiric attacks can deal critical damage
{CBatAttackDrainApi::vftable()->onHit, drainAttackOnHitHooked},
{CBatAttackDrainOverflowApi::vftable()->onHit, drainOverflowAttackOnHitHooked},
// Support additional music tracks for battle and capital cities
{CMidMusicApi::get().playBattleTrack, playBattleTrackHooked},
{CMidMusicApi::get().playCapitalTrack, playCapitalTrackHooked},
// Fix game crash with pathfinding on 144x144 maps
{fn.markMapPosition, markMapPositionHooked, (void**)&orig.markMapPosition},
// Allow user to tweak power computations
{fn.getAttackPower, getAttackPowerHooked},
// Fix game crash when AI controlled unit with transform self attack
// uses alternative attack with 'adjacent' attack range
// Fix incorrect calculation of effective HP used by AI for target prioritization
{fn.computeUnitEffectiveHpForAi, computeUnitEffectiveHpForAiHooked},
// Allow transform-self attack to not consume a unit turn for transformation
// Fixes modifiers becoming permanent after modified unit is transformed
// Support custom attack damage ratios
{battle.beforeBattleTurn, beforeBattleTurnHooked},
// Fix free transform-self to properly reset if the same unit has consequent turns in consequent battles
{battle.beforeBattleRound, beforeBattleRoundHooked, (void**)&orig.beforeBattleRound},
/**
* Allows bestow wards to:
* 1) Grant modifiers even if there are no source wards among them
* 2) Heal its targets to the ammount specified in QTY_HEAL
* 3) Heal retreating units
* 4) Use Revive as a secondary attack
* 5) Target a unit with a secondary attack even if there are no modifiers that can be
* applied to this unit
* 6) Treat modifiers with complete immunity correctly
*/
{CBatAttackBestowWardsApi::vftable()->canPerform, bestowWardsAttackCanPerformHooked},
/**
* Fix bestow wards:
* 1) Becoming permanent when more than 8 modifiers are applied at once
* 2) Not resetting attack class wards (when reapplied)
* 3) Incorrectly resetting attack source ward if its modifier also contains hp, regen or armor element
*/
// Fixes modifiers getting lost after modified unit is untransformed
{CBatAttackBestowWardsApi::vftable()->onHit, bestowWardsAttackOnHitHooked},
// Fix bestow wards with double attack where modifiers granted by first attack are removed
{battle.afterBattleTurn, afterBattleTurnHooked},
// Allow any attack with QTY_HEAL > 0 to heal units when battle ends (just like ordinary heal does)
{fn.getUnitHealAttackNumber, getUnitHealAttackNumberHooked},
// Fix AI not being able to find target for lower damage/ini attack
// Fix incorrect AI prioritization of shatter attack targets
{battle.findAttackTarget, findAttackTargetHooked, (void**)&orig.findAttackTarget},
// Support custom attack sources
{fn.getUnitAttackSourceImmunities, getUnitAttackSourceImmunitiesHooked},
{battle.isUnitAttackSourceWardRemoved, isUnitAttackSourceWardRemovedHooked},
{battle.removeUnitAttackSourceWard, removeUnitAttackSourceWardHooked},
{battle.addUnitToBattleMsgData, addUnitToBattleMsgDataHooked, (void**)&orig.addUnitToBattleMsgData},
// Support custom attack reaches
{battle.fillTargetsList, fillTargetsListHooked},
{battle.fillEmptyTargetsList, fillEmptyTargetsListHooked},
{battle.getTargetsToAttack, getTargetsToAttackHooked},
{battle.findDoppelgangerAttackTarget, findDoppelgangerAttackTargetHooked},
{battle.findDamageAttackTargetWithNonAllReach, findDamageAttackTargetWithNonAllReachHooked},
{BattleViewerInterfApi::get().markAttackTargets, markAttackTargetsHooked},
{fn.isGroupSuitableForAiNobleMisfit, isGroupSuitableForAiNobleMisfitHooked},
{fn.isUnitSuitableForAiNobleDuel, isUnitSuitableForAiNobleDuelHooked},
{fn.isAttackBetterThanItemUsage, isAttackBetterThanItemUsageHooked},
{fn.getSummonUnitImplIdByAttack, getSummonUnitImplIdByAttackHooked},
{fn.isSmallMeleeFighter, isSmallMeleeFighterHooked},
{fn.cAiHireUnitEval, cAiHireUnitEvalHooked},
{fn.getMeleeUnitToHireAiRating, getMeleeUnitToHireAiRatingHooked},
{fn.computeTargetUnitAiPriority, computeTargetUnitAiPriorityHooked},
// Allow users to specify critical hit chance
// Support custom attack damage ratios
{fn.computeDamage, computeDamageHooked},
// Fix occasional crash with incorrect removal of summoned unit info
// Fix persistent crash with summons when unrestrictedBestowWards is enabled
{battle.removeUnitInfo, removeUnitInfoHooked},
// Fix bug where transform-self attack is unable to target self if alt attack is targeting allies
{CBatAttackTransformSelfApi::vftable()->fillTargetsList, transformSelfAttackFillTargetsListHooked},
// Allow transform self into leveled units using script logic
// Allow transform-self attack to not consume a unit turn for transformation
// Fix bug where transform-self attack is unable to target self if alt attack is targeting allies
// Fix possible attack count mismatch (once vs twice) on unit transformation
{CBatAttackTransformSelfApi::vftable()->onHit, transformSelfAttackOnHitHooked},
// Allow transform other into leveled units using script logic
// Fix bug where transform-other attack selects melee vs ranged transform based on attacker position rather than target position
// Fix possible attack count mismatch (once vs twice) on unit transformation
{CBatAttackTransformOtherApi::vftable()->onHit, transformOtherAttackOnHitHooked},
// Allow to drain different number of levels using script logic
// Fix possible attack count mismatch (once vs twice) on unit transformation
{CBatAttackDrainLevelApi::vftable()->onHit, drainLevelAttackOnHitHooked},
// Fix possible attack count mismatch (once vs twice) on unit transformation
{CBatAttackUntransformEffectApi::vftable()->onHit, untransformEffectAttackOnHitHooked},
// Fix inability to target self for transformation in case of transform-self + summon attack
// Remove persistent marking of all target units in case of transform-self attack
{BattleViewerInterfApi::vftable()->update, battleViewerInterfUpdateHooked},
// Fix missing modifiers of alternative attacks
{fn.getUnitAttacks, getUnitAttacksHooked},
// Support custom event conditions
{ITestConditionApi::get().create, createTestConditionHooked, (void**)&orig.createTestCondition},
// Support custom event effects
//{IEffectResultApi::get().create, createEffectResultHooked, (void**)&orig.createEffectResult},
// Support additional as well as high tier units in hire list
{fn.addPlayerUnitsToHireList, addPlayerUnitsToHireListHooked},
{fn.shouldAddUnitToHire, shouldAddUnitToHireHooked},
{fn.enableUnitInHireListUi, enableUnitInHireListUiHooked},
// Allow scenarios with prebuilt buildings in capitals
// Start with prebuilt temple in capital for warrior lord depending on user setting
{fn.buildLordSpecificBuildings, buildLordSpecificBuildingsHooked},
// Allows transformed leaders (doppelganger, drain-level, transform-self/other attacks) to use battle items (potions, orbs and talismans)
{BattleViewerInterfApi::get().updateBattleItems, battleViewerInterfUpdateBattleItemsHooked},
{BatBigFaceApi::get().update, batBigFaceUpdateHooked},
{battle.updateBattleActions, updateBattleActionsHooked},
// Support race-specific village graphics
{GameImagesApi::get().getCityPreviewLargeImageNames, getCityPreviewLargeImageNamesHooked, (void**)&orig.getCityPreviewLargeImageNames},
{GameImagesApi::get().getCityIconImageNames, getCityIconImageNamesHooked, (void**)&orig.getCityIconImageNames},
// Support grid toggle button
{CMainView2Api::get().showIsoDialog, mainView2ShowIsoDialogHooked},
// Reference ground rendering implementation
// TODO: fix occasional magenta 'triangles' showing up after closing capital window
//{CGroundTextureApi::vftable()->draw, groundTextureDrawHooked},
//{CGroundTextureApi::isoEngineVftable()->render, isoEngineGroundRenderHooked},
// Support native modifiers
{CMidUnitApi::get().upgrade, upgradeHooked},
// Fix doppelganger attack using alternative attack when attacker is transformed (by doppelganger, drain-level, transform-self/other attacks)
{battle.cannotUseDoppelgangerAttack, cannotUseDoppelgangerAttackHooked},
// Support new menu windows
{CMenuPhaseApi::get().setTransition, menuPhaseSetTransitionHooked, (void**)&orig.menuPhaseSetTransition},
// Support custom modifiers
{fn.loadScenarioMap, loadScenarioMapHooked, (void**)&orig.loadScenarioMap},
// Show broken (removed) wards in unit encyclopedia
{CEncParamBaseApi::get().addUnitBattleInfo, encParamBaseAddUnitBattleInfoHooked},
// Fix crash on drag&drop when INotify::OnObjectChanged is processed between mouse down and up
{CManageStkInterfApi::vftable().notify->onObjectChanged, manageStkInterfOnObjectChangedHooked, (void**)&orig.manageStkInterfOnObjectChanged},
{CExchangeInterfApi::vftable().notify->onObjectChanged, exchangeInterfOnObjectChangedHooked, (void**)&orig.exchangeInterfOnObjectChanged},
{CCityStackInterfApi::vftable().notify->onObjectChanged, cityStackInterfOnObjectChangedHooked, (void**)&orig.cityStackInterfOnObjectChanged},
{CSiteMerchantInterfApi::vftable().notify->onObjectChanged, siteMerchantInterfOnObjectChangedHooked, (void**)&orig.siteMerchantInterfOnObjectChanged},
// Fix inability to use heal potion on transformed unit if its current hp is greater than maximum hp of unit it is transformed to
// (most common case is a unit transformed to Imp by a Witch while retaining his original hp)
{fn.canApplyPotionToUnit, canApplyPotionToUnitHooked},
// Fix crash on AI turn when it tries to exchange items and a source stack is destroyed in battle/event while moving to destination
{CAiGiveItemsActionApi::vftable().action->execute, aiGiveItemsActionExecuteHooked},
// Allow foreign race units to upgrade even if its race capital is present in scenario (functions as if the unit type is locked)
// Allow foreign race units (including neutral) to be upgraded using capital buildings
// Fix errornous logic that allowed retreated units to upgrade under certain conditions (introduce setting battle.allowRetreatedUnitsToUpgrade)
{CBatAttackGroupUpgradeApi::get().upgradeGroup, upgradeGroupHooked},
{fn.getUpgradeUnitImplCheckXp, getUpgradeUnitImplCheckXpHooked},
{fn.changeUnitXpCheckUpgrade, changeUnitXpCheckUpgradeHooked},
// Allow player to customize movement cost
{fn.computeMovementCost, computeMovementCostHooked},
};
// clang-format on
if (userSettings().engine.sendRefreshInfoObjectCountLimit) {
// Fix incomplete scenario loading when its object size exceed network message buffer size
// of 512 KB
hooks.emplace_back(HookInfo{CMidServerLogicApi::get().sendRefreshInfo,
midServerLogicSendRefreshInfoHooked});
}
if (userSettings().shatteredArmorMax != baseSettings().shatteredArmorMax) {
// Allow users to customize total armor shatter damage
hooks.emplace_back(
HookInfo{CBatAttackShatterApi::vftable()->canPerform, shatterCanPerformHooked});
hooks.emplace_back(HookInfo{battle.setUnitShatteredArmor, setUnitShatteredArmorHooked});
}
if (userSettings().shatterDamageMax != baseSettings().shatterDamageMax) {
// Allow users to customize maximum armor shatter damage per attack
hooks.emplace_back(HookInfo{CBatAttackShatterApi::vftable()->onHit, shatterOnHitHooked});
}
if (userSettings().showBanners != baseSettings().showBanners) {
// Allow users to show banners by default
hooks.emplace_back(HookInfo{fn.toggleShowBannersInit, toggleShowBannersInitHooked});
}
if (userSettings().showResources != baseSettings().showResources
|| userSettings().showLandConverted != baseSettings().showLandConverted) {
// Allow users to show resources panel by default
hooks.emplace_back(HookInfo{fn.respopupInit, respopupInitHooked});
}
if (userSettings().carryOverItemsMax != baseSettings().carryOverItemsMax) {
// Change maximum number of items that player can carry between campaign scenarios
hooks.emplace_back(HookInfo{CDDCarryOverItemsApi::get().constructor,
carryOverItemsCtorHooked, (void**)&orig.carryOverItemsCtor});
}
if (userSettings().doppelgangerRespectsEnemyImmunity
!= baseSettings().doppelgangerRespectsEnemyImmunity
|| userSettings().doppelgangerRespectsAllyImmunity
!= baseSettings().doppelgangerRespectsAllyImmunity) {
// Make Doppelganger attack respect target source/class wards and immunities
hooks.emplace_back(HookInfo{CBatAttackDoppelgangerApi::vftable()->canPerform,
doppelgangerAttackCanPerformHooked});
hooks.emplace_back(HookInfo{CBatAttackDoppelgangerApi::vftable()->isImmune,
doppelgangerAttackIsImmuneHooked});
}
if (userSettings().leveledDoppelgangerAttack != baseSettings().leveledDoppelgangerAttack) {
// Allow doppelganger to transform into leveled units using script logic
hooks.emplace_back(
HookInfo{CBatAttackDoppelgangerApi::vftable()->onHit, doppelgangerAttackOnHitHooked});
}
if (userSettings().leveledSummonAttack != baseSettings().leveledSummonAttack) {
// Allow summon leveled units using script logic
hooks.emplace_back(
HookInfo{CBatAttackSummonApi::vftable()->onHit, summonAttackOnHitHooked});
}
if (userSettings().missChanceSingleRoll != baseSettings().missChanceSingleRoll) {
// Compute attack miss chance using single random value, instead of two
hooks.emplace_back(HookInfo{fn.attackShouldMiss, attackShouldMissHooked});
}
if (userSettings().unrestrictedBestowWards != baseSettings().unrestrictedBestowWards) {
// Increases total ward limit for bestow-wards attack from 8 to 48
// clang-format off
hooks.emplace_back(HookInfo{battle.constructor, battleMsgDataCtorHooked, (void**)&orig.battleMsgDataCtor});
hooks.emplace_back(HookInfo{battle.copyConstructor, battleMsgDataCopyCtorHooked});
hooks.emplace_back(HookInfo{battle.copyConstructor2, battleMsgDataCopyCtorHooked});
hooks.emplace_back(HookInfo{battle.copyAssignment, battleMsgDataCopyAssignHooked});
hooks.emplace_back(HookInfo{battle.copy, battleMsgDataCopyHooked});
hooks.emplace_back(HookInfo{battle.destructor, battleMsgDataDtorHooked});
hooks.emplace_back(HookInfo{CStackBattleActionMsgApi::vftable()->serialize, stackBattleActionMsgSerializeHooked, (void**)&orig.stackBattleActionMsgSerialize});
hooks.emplace_back(HookInfo{CCmdBattleStartMsgApi::vftable()->serialize, cmdBattleStartMsgSerializeHooked, (void**)&orig.cmdBattleStartMsgSerialize});
hooks.emplace_back(HookInfo{CCmdBattleChooseActionMsgApi::vftable()->serialize, cmdBattleChooseActionMsgSerializeHooked, (void**)&orig.cmdBattleChooseActionMsgSerialize});
hooks.emplace_back(HookInfo{CCmdBattleResultMsgApi::vftable()->serialize, cmdBattleResultMsgSerializeHooked, (void**)&orig.cmdBattleResultMsgSerialize});
hooks.emplace_back(HookInfo{CCmdBattleEndMsgApi::vftable()->serialize, cmdBattleEndMsgSerializeHooked, (void**)&orig.cmdBattleEndMsgSerialize});
hooks.emplace_back(HookInfo{CCommandMsgApi::get().destructor, commandMsgDtorHooked, (void**)&orig.commandMsgDtor});
hooks.emplace_back(HookInfo{CNetMsgApi::get().destructor, netMsgDtorHooked, (void**)&orig.netMsgDtor});
// clang-format on
}
if (userSettings().movementCost.show) {
// Show movement cost
hooks.emplace_back(HookInfo{fn.showMovementPath, showMovementPathHooked});
}
if (isLobbySupported()) {
// clang-format off
// Support custom lobby server
hooks.emplace_back(HookInfo{CMenuProtocolApi::get().createMenu, menuProtocolCreateMenuHooked});
hooks.emplace_back(HookInfo{CMenuProtocolApi::get().continueHandler, menuProtocolContinueHandlerHooked, (void**)&orig.menuProtocolContinueHandler});
hooks.emplace_back(HookInfo{CMenuProtocolApi::get().displayCallback, menuProtocolDisplayCallbackHooked, (void**)&orig.menuProtocolDisplayCallback});
hooks.emplace_back(HookInfo{CMenuNewSkirmishApi::get().loadScenarioCallback, menuNewSkirmishLoadScenarioCallbackHooked, (void**)&orig.menuNewSkirmishLoadScenario});
hooks.emplace_back(HookInfo{CMenuNewSkirmishMultiApi::get().createServer, menuNewSkirmishMultiCreateServerHooked, (void**)&orig.menuNewSkirmishMultiCreateServer});
hooks.emplace_back(HookInfo{CMenuLoadApi::get().buttonLoadCallback, menuLoadSkirmishMultiLoadScenarioHooked, (void**)&orig.menuLoadSkirmishMultiLoadScenario});
hooks.emplace_back(HookInfo{CMenuLoadApi::get().createHostPlayer, menuLoadSkirmishMultiCreateHostPlayerHooked, (void**)&orig.menuLoadSkirmishMultiCreateHostPlayer});
// clang-format on
}
bool hookSendObjectsChanges = false;
if (userSettings().debugMode) {
// clang-format off
// Log all net messages being sent by single player (both client and server) to netMessages<PID>.log
if (userSettings().debug.logSinglePlayerMessages) {
hooks.emplace_back(HookInfo{CNetSinglePlayerApi::vftable()->sendMessage, netSinglePlayerSendMessageHooked, (void**)&orig.netSinglePlayerSendMessage});
}
// Log added/changed/erased objects ids being sent by server to netMessages<PID>.log
if (userSettings().debug.sendObjectsChangesTreshold) {
hookSendObjectsChanges = true;
}
// clang-format on
}
if (userSettings().modifiers.validateUnitsOnGroupChanged) {
// Validate current HP / XP of units when their group changes (units added, removed,
// rearranged, etc.) to resolve issues with custom HP / XP modifiers, that depend on other
// units (like auras in MNS mod).
hooks.emplace_back(
HookInfo{fn.getStackFortRuinGroupForChange, getStackFortRuinGroupForChangeHooked});
hookSendObjectsChanges = true;
}
if (hookSendObjectsChanges) {
hooks.emplace_back(HookInfo{CMidServerLogicApi::vftable().midMsgSender->sendObjectsChanges,
midServerLogicSendObjectsChangesHooked,
(void**)&orig.midServerLogicSendObjectsChanges});
}
return hooks;
}
/** Hooks that used only in Scenario Editor. */
static Hooks getScenarioEditorHooks()
{
using namespace game;
auto& orig = getOriginalFunctions();
// clang-format off
Hooks hooks{
// Check sites placement the same way as ruins, allowing them to be placed on water
{editorFunctions.canPlaceSite, editorFunctions.canPlaceRuin},
// Allow editor to set elves race as caster in 'cast spell on location' event effect
{editorFunctions.radioButtonIndexToPlayerId, radioButtonIndexToPlayerIdHooked},
// Fix DLG_R_C_SPELL so it shows actual spell info
{CEncLayoutSpellApi::get().constructor, encLayoutSpellCtorHooked, (void**)&orig.encLayoutSpellCtor},
// Allow editor to place more than 200 stacks on a map
{editorFunctions.countStacksOnMap, countStacksOnMapHooked},
// Support custom event conditions
{CMidEvConditionApi::get().getInfoString, eventConditionGetInfoStringHooked, (void**)&orig.eventConditionGetInfoString},
{CMidEvConditionApi::get().getDescription, eventConditionGetDescriptionHooked, (void**)&orig.eventConditionGetDescription},
{CMidEvConditionApi::get().getBrief, eventConditionGetBriefHooked, (void**)&orig.eventConditionGetBrief},
{editor::CCondInterfApi::get().createFromCategory, createCondInterfFromCategoryHooked, (void**)&orig.createCondInterfFromCategory},
{CMidEventApi::get().checkValid, checkEventValidHooked, (void**)&orig.checkEventValid},
// Support custom event effects
//{CMidEvEffectApi::get().getInfoString, eventEffectGetInfoStringHooked, (void**)&orig.eventEffectGetInfoString},
//{CMidEvEffectApi::get().getDescription, eventEffectGetDescriptionHooked, (void**)&orig.eventEffectGetDescription},
//{CMidEvEffectApi::get().getBrief, eventEffectGetBriefHooked, (void**)&orig.eventEffectGetBrief},
//{editor::CEffectInterfApi::get().createFromCategory, createEffectInterfFromCategoryHooked, (void**)&orig.createEffectInterfFromCategory},
{CMidgardScenarioMapApi::get().checkObjects, checkMapObjectsHooked},
// Support custom modifiers
{CMidgardScenarioMapApi::get().stream, scenarioMapStreamHooked, (void**)&orig.scenarioMapStream},
};
// clang-format on
return hooks;
}
Hooks getHooks()
{
using namespace game;
Hooks hooks{executableIsGame() ? getGameHooks() : getScenarioEditorHooks()};
auto& fn = gameFunctions();
auto& orig = getOriginalFunctions();
// Register buildings with custom branch category as unit buildings
hooks.emplace_back(HookInfo{fn.createBuildingType, createBuildingTypeHooked});
// Support custom building branch category
hooks.emplace_back(
HookInfo{LBuildingCategoryTableApi::get().constructor, buildingCategoryTableCtorHooked});
// Increase maximum allowed game turn
hooks.emplace_back(HookInfo{fn.isTurnValid, isTurnValidHooked});
// Support custom attack class category
hooks.emplace_back(
HookInfo{LAttackClassTableApi::get().constructor, attackClassTableCtorHooked});
// Support custom attack class in CAttackImpl constructor
// Support custom attack damage ratios
// Support per-attack crit settings
hooks.emplace_back(HookInfo{CAttackImplApi::get().constructor, attackImplCtorHooked});
hooks.emplace_back(HookInfo{CAttackImplApi::get().constructor2, attackImplCtor2Hooked,
(void**)&orig.attackImplCtor2});
hooks.emplace_back(HookInfo{CAttackImplApi::vftable()->getData, attackImplGetDataHooked,
(void**)&orig.attackImplGetData});
/**
* Display heal/damage value for any attack with qtyHeal/qtyDamage > 0 regardless of its class.
* This hook is required for detailedAttackDescription.
*/
hooks.emplace_back(HookInfo{fn.getAttackQtyDamageOrHeal, getAttackQtyDamageOrHealHooked});
// Support custom attack sources
hooks.emplace_back(
HookInfo{LAttackSourceTableApi::get().constructor, attackSourceTableCtorHooked});
hooks.emplace_back(
HookInfo{fn.getSoldierAttackSourceImmunities, getSoldierAttackSourceImmunitiesHooked});
hooks.emplace_back(HookInfo{fn.getSoldierImmunityAiRating, getSoldierImmunityAiRatingHooked,
(void**)&orig.getSoldierImmunityAiRating});
hooks.emplace_back(HookInfo{fn.getAttackSourceText, getAttackSourceTextHooked});
hooks.emplace_back(HookInfo{fn.appendAttackSourceText, appendAttackSourceTextHooked});
hooks.emplace_back(HookInfo{fn.getAttackSourceWardFlagPosition,
getAttackSourceWardFlagPositionHooked,
(void**)&orig.getAttackSourceWardFlagPosition});
// Support custom attack reaches
hooks.emplace_back(
HookInfo{LAttackReachTableApi::get().constructor, attackReachTableCtorHooked});
hooks.emplace_back(HookInfo{fn.getAttackClassAiRating, getAttackClassAiRatingHooked});
hooks.emplace_back(HookInfo{fn.getAttackReachAiRating, getAttackReachAiRatingHooked});
hooks.emplace_back(HookInfo{CMidStackApi::vftable()->initialize, midStackInitializeHooked});
// Always place melee units at the front lane in groups controlled by non-neutrals AI
// Support custom attack reaches
hooks.emplace_back(HookInfo{fn.chooseUnitLane, chooseUnitLaneHooked});
// Fix missing modifiers of alternative attacks
hooks.emplace_back(HookInfo{CUmAttackApi::get().constructor, umAttackCtorHooked});
hooks.emplace_back(HookInfo{CUmAttackApi::get().copyConstructor, umAttackCopyCtorHooked});
// Fix incorrect representation of alternative attack modifiers in unit encyclopedia
hooks.emplace_back(
HookInfo{CMidUnitDescriptorApi::get().getAttack, midUnitDescriptorGetAttackHooked});
hooks.emplace_back(HookInfo{CMidUnitDescriptorApi::vftable()->getAttackInitiative,
midUnitDescriptorGetAttackInitiativeHooked});
// Fix crash in encyclopedia showing info
// about dyn leveled (stopped) doppleganger that transformed to stack leader
hooks.emplace_back(HookInfo{CMidUnitDescriptorApi ::vftable()->isUnitLeader,
midUnitDescriptorIsUnitLeaderHooked});
if (userSettings().debugMode) {
// Show and log game exceptions information
hooks.emplace_back(HookInfo{os_exceptionApi::get().throwException, throwExceptionHooked,
(void**)&orig.throwException});
}
if (userSettings().shatterDamageUpgradeRatio != baseSettings().shatterDamageUpgradeRatio) {
// Allow users to customize shatter damage upgrade ratio
hooks.emplace_back(
HookInfo{fn.applyDynUpgradeToAttackData, applyDynUpgradeToAttackDataHooked});
}
if (userSettings().unitEncyclopedia.detailedAttackDescription
!= baseSettings().unitEncyclopedia.detailedAttackDescription) {
// Additional display of some stats bonuses, drain, critical hit, custom attack ratios, etc.
hooks.emplace_back(HookInfo{fn.generateAttackDescription, generateAttackDescriptionHooked});
}
// Support custom event conditions
hooks.emplace_back(
HookInfo{LEventCondCategoryTableApi::get().constructor, eventCondCategoryTableCtorHooked});
hooks.emplace_back(HookInfo{CMidEvConditionApi::get().createFromCategory,
createEventConditionFromCategoryHooked,
(void**)&orig.createEventConditionFromCategory});
// Support custom event effects
// hooks.emplace_back(HookInfo{LEventEffectCategoryTableApi::get().constructor,
// eventEffectCategoryTableCtorHooked});
// hooks.emplace_back(HookInfo{CMidEvEffectApi::get().createFromCategory,
// createEventEffectFromCategoryHooked,
// (void**)&orig.createEventEffectFromCategory});
// Allow every leader use additional animations on strategic map
hooks.emplace_back(
HookInfo{fn.isUnitUseAdditionalAnimation, isUnitUseAdditionalAnimationHooked});
// Support race-specific village graphics
hooks.emplace_back(
HookInfo{DisplayHandlersApi::get().villageHandler, displayHandlerVillageHooked});
if (userSettings().modifiers.cumulativeUnitRegeneration) {
// Allow unit regeneration modifiers to stack
hooks.emplace_back(HookInfo{CUmUnitApi::get().constructor, umUnitCtorHooked});
hooks.emplace_back(HookInfo{CUmUnitApi::get().copyConstructor, umUnitCopyCtorHooked});
hooks.emplace_back(
HookInfo{CUmUnitApi::vftable().usSoldier->getRegen, umUnitGetRegenHooked});
}
// Support custom modifiers
hooks.emplace_back(HookInfo{LModifGroupTableApi::get().constructor, modifGroupTableCtorHooked});
hooks.emplace_back(HookInfo{TUnitModifierApi::get().constructor, unitModifierCtorHooked});
hooks.emplace_back(HookInfo{TUnitModifierApi::vftable()->destructor, unitModifierDtorHooked});
hooks.emplace_back(HookInfo{CMidUnitApi::get().addModifier, addModifierHooked});
hooks.emplace_back(HookInfo{CMidUnitApi::vftable()->stream, midUnitStreamHooked});
// Support custom modifiers display for unit encyclopedia
hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().constructor, encLayoutUnitCtorHooked});
hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().constructor2, encLayoutUnitCtor2Hooked});
hooks.emplace_back(
HookInfo{CEncLayoutUnitApi::get().dataConstructor, encLayoutUnitDataCtorHooked});
hooks.emplace_back(
HookInfo{CEncLayoutUnitApi::get().dataDestructor, encLayoutUnitDataDtorHooked});
hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().initialize, encLayoutUnitInitializeHooked,
(void**)&orig.encLayoutUnitInitialize});
// Show effective HP in unit encyclopedia
hooks.emplace_back(HookInfo{CEncLayoutUnitApi::get().update, encLayoutUnitUpdateHooked,
(void**)&orig.encLayoutUnitUpdate});
// Show total xp-killed in stack/city/ruin encyclopedia
hooks.emplace_back(HookInfo{CEncLayoutStackApi::get().update, encLayoutStackUpdateHooked,
(void**)&orig.encLayoutStackUpdate});
hooks.emplace_back(HookInfo{CEncLayoutCityApi::get().update, encLayoutCityUpdateHooked,
(void**)&orig.encLayoutCityUpdate});
hooks.emplace_back(HookInfo{CEncLayoutRuinApi::get().update, encLayoutRuinUpdateHooked,
(void**)&orig.encLayoutRuinUpdate});
// Support native modifiers
hooks.emplace_back(HookInfo{CMidUnitApi::get().getModifiers, getModifiersHooked});
hooks.emplace_back(HookInfo{CMidUnitApi::get().addModifiers, addModifiersHooked});
hooks.emplace_back(HookInfo{CMidUnitApi::get().removeModifiers, removeModifiersHooked});
hooks.emplace_back(HookInfo{CMidUnitApi::vftable()->initWithSoldierImpl,
initWithSoldierImplHooked, (void**)&orig.initWithSoldierImpl});
// Update city encyclopedia on visiting stack changes
hooks.emplace_back(HookInfo{CEncLayoutCityApi::vftable()->onObjectChanged,
encLayoutCityOnObjectChangedHooked});
// Fix infamous crash in multiplayer with city encyclopedia when observing other player's cities
hooks.emplace_back(
HookInfo{CEncLayoutCityApi::get().updateGroupUi, encLayoutCityUpdateGroupUiHooked});
// Fix display of required buildings when multiple units have the same upgrade building
hooks.emplace_back(HookInfo{fn.getUnitRequiredBuildings, getUnitRequiredBuildingsHooked});
// Allow foreign race units to upgrade even if its race capital is present in scenario
// (functions as if the unit type is locked) Allow foreign race units (including neutral) to be
// upgraded using capital buildings
hooks.emplace_back(HookInfo{fn.isUnitTierMax, isUnitTierMaxHooked});
hooks.emplace_back(HookInfo{fn.isUnitLevelNotMax, isUnitLevelNotMaxHooked});
hooks.emplace_back(HookInfo{fn.isUnitUpgradePending, isUnitUpgradePendingHooked});
// Fixes crash on scenario loading when level of any unit is below its template from
// `GUnits.dbf`, or above maximum level for generated units (restricted by total count of unit
// templates)
hooks.emplace_back(
HookInfo{CMidUnitApi::get().streamImplIdAndLevel, midUnitStreamImplIdAndLevelHooked});
// Support custom fonts
hooks.emplace_back(HookInfo{FontCacheApi::get().loadFontFiles, loadFontFilesHooked});
hooks.emplace_back(HookInfo{FontCacheApi::get().dataDestructor, fontCacheDataDtorHooked});
// Fixes incorrect order of building status checks along with missing lordHasBuilding condition
hooks.emplace_back(HookInfo{fn.getBuildingStatus, getBuildingStatusHooked});
// Fix input of 'io' (U+0451) and 'IO' (U+0401)
hooks.emplace_back(HookInfo{CEditBoxInterfApi::get().isCharValid, editBoxIsCharValidHooked});
return hooks;
}
Hooks getVftableHooks()
{
using namespace game;
Hooks hooks;
if (CBatAttackBestowWardsApi::vftable())
// Allow bestow wards to target dead units, so it can be coupled with Revive as a secondary
// attack
hooks.emplace_back(
HookInfo{&CBatAttackBestowWardsApi::vftable()->method15, bestowWardsMethod15Hooked});
if (userSettings().allowShatterAttackToMiss != baseSettings().allowShatterAttackToMiss) {
if (CBatAttackShatterApi::vftable())
// Fix an issue where shatter attack always hits regardless of its power value
hooks.emplace_back(
HookInfo{&CBatAttackShatterApi::vftable()->canMiss, shatterCanMissHooked});
}
return hooks;
}
void respopupInitHooked(void)
{
logDebug("mss32Proxy.log", "Resource popup hook start");
auto& variables = game::gameVariables();
*variables.minimapMode = userSettings().showLandConverted;
*variables.respopup = userSettings().showResources;
logDebug("mss32Proxy.log", "Resource popup hook finished");
}
void* __fastcall toggleShowBannersInitHooked(void* thisptr, int /*%edx*/)
{
logDebug("mss32Proxy.log", "Show banners hook start");
char* ptr = (char*)thisptr;
*ptr = userSettings().showBanners;
// meaning unknown
ptr[1] = 0;
logDebug("mss32Proxy.log", "Show banners hook finished");
return thisptr;
}
bool __stdcall addPlayerUnitsToHireListHooked(game::CMidDataCache2* dataCache,
const game::CMidgardID* playerId,
const game::CMidgardID* a3,
game::IdList* hireList)
{
using namespace game;
const auto& list = IdListApi::get();
list.clear(hireList);
const auto& id = CMidgardIDApi::get();
if (id.getType(a3) != IdType::Fortification) {
return false;
}
auto findScenarioObjectById = dataCache->vftable->findScenarioObjectById;
auto playerObject = findScenarioObjectById(dataCache, playerId);
if (!playerObject) {
logError("mssProxyError.log",
fmt::format("Could not find player object with id {:x}", playerId->value));
return false;
}
const auto dynamicCast = RttiApi::get().dynamicCast;
const auto& rtti = RttiApi::rtti();
CMidPlayer* player = (CMidPlayer*)dynamicCast(playerObject, 0, rtti.IMidScenarioObjectType,
rtti.CMidPlayerType, 0);
if (!player) {
logError("mssProxyError.log",
fmt::format("Object with id {:x} is not player", playerId->value));
return false;
}
auto buildingsObject = findScenarioObjectById(dataCache, &player->buildingsId);
if (!buildingsObject) {
logError("mssProxyError.log", fmt::format("Could not find player buildings with id {:x}",
player->buildingsId.value));
return false;
}
auto playerBuildings = (CPlayerBuildings*)dynamicCast(buildingsObject, 0,
rtti.IMidScenarioObjectType,
rtti.CPlayerBuildingsType, 0);
if (!playerBuildings) {
logError("mssProxyError.log", fmt::format("Object with id {:x} is not player buildings",
player->buildingsId.value));
return false;
}
const auto& global = GlobalDataApi::get();
const auto globalData = *global.getGlobalData();
auto races = globalData->races;
TRaceType* race = (TRaceType*)global.findById(races, &player->raceId);
const auto& fn = gameFunctions();
const auto& addUnitToHireList = fn.addUnitToHireList;
const auto& unitBranch = UnitBranchCategories::get();
addUnitToHireList(race, playerBuildings, unitBranch.fighter, hireList);
addUnitToHireList(race, playerBuildings, unitBranch.archer, hireList);
addUnitToHireList(race, playerBuildings, unitBranch.mage, hireList);
addUnitToHireList(race, playerBuildings, unitBranch.special, hireList);
fn.addSideshowUnitToHireList(race, playerBuildings, hireList);
if (!unitsForHire().empty()) {
const int raceIndex = id.getTypeIndex(&player->raceId);
const auto& units = unitsForHire()[raceIndex];
for (const auto& unit : units) {
list.pushBack(hireList, &unit);
}
}
const auto& buildList = playerBuildings->buildings;
if (buildList.length == 0) {
// Player has no buildings in capital, skip
return true;
}
auto variables{getScenarioVariables(dataCache)};
if (!variables || !variables->variables.length) {
return true;
}
int hireTierMax{0};
for (const auto& variable : variables->variables) {
static const char varName[]{"UNIT_HIRE_TIER_MAX"};
if (!strncmp(variable.second.name, varName, sizeof(varName))) {
hireTierMax = variable.second.value;
break;
}
}
if (hireTierMax <= 1) {
// No variable defined or high tier hire is disabled, skip.
return true;
}
const auto units = globalData->units;
for (auto current = units->map->data.bgn, end = units->map->data.end; current != end;
++current) {
const auto unitImpl = current->second;
auto soldier = fn.castUnitImplToSoldier(unitImpl);
if (!soldier) {
continue;
}
if (race->id != *soldier->vftable->getRaceId(soldier)) {
continue;
}
auto racialSoldier = fn.castUnitImplToRacialSoldier(unitImpl);
if (!racialSoldier) {
continue;
}
auto upgradeBuildingId = racialSoldier->vftable->getUpgradeBuildingId(racialSoldier);
if (*upgradeBuildingId == emptyId) {
continue;
}
bool hasBulding{false};
for (auto node = buildList.head->next; node != buildList.head; node = node->next) {
if (node->data == *upgradeBuildingId) {
hasBulding = true;
break;
}
}
if (!hasBulding) {
// No building for this unit was built in capital, skip
continue;
}
if (getBuildingLevel(upgradeBuildingId) <= hireTierMax) {
list.pushBack(hireList, ¤t->first);
}
}
return true;
}
void __stdcall createBuildingTypeHooked(const game::CDBTable* dbTable,
void* a2,
const game::GlobalData** globalData)
{
using namespace game;
auto* buildings = (*globalData)->buildingCategories;
LBuildingCategory category;
category.vftable = BuildingCategories::vftable();
auto& db = CDBTableApi::get();
db.findBuildingCategory(&category, dbTable, "CATEGORY", buildings);
auto memAlloc = Memory::get().allocate;
auto constructor = TBuildingTypeApi::get().constructor;
TBuildingType* buildingType = nullptr;
auto& buildingCategories = BuildingCategories::get();
if (category.id == buildingCategories.unit->id || isCustomBuildingCategory(&category)) {
// This is TBuildingUnitUpgType constructor
// without TBuildingTypeData::category validity check
TBuildingUnitUpgType* unitBuilding = (TBuildingUnitUpgType*)memAlloc(
sizeof(TBuildingUnitUpgType));
constructor(unitBuilding, dbTable, globalData);
unitBuilding->branch.vftable = UnitBranchCategories::vftable();
unitBuilding->vftable = (IMidObjectVftable*)TBuildingUnitUpgTypeApi::vftable();
auto* branches = (*globalData)->unitBranches;
db.findUnitBranchCategory(&unitBuilding->branch, dbTable, "BRANCH", branches);
db.readUnitLevel(&unitBuilding->level, dbTable, "LEVEL");
buildingType = unitBuilding;
} else {
buildingType = constructor((TBuildingType*)memAlloc(sizeof(TBuildingType)), dbTable,
globalData);
}
if (!gameFunctions().addObjectAndCheckDuplicates(a2, buildingType)) {
db.duplicateRecordException(dbTable, &buildingType->id);
}
}
game::LBuildingCategoryTable* __fastcall buildingCategoryTableCtorHooked(
game::LBuildingCategoryTable* thisptr,
int /*%edx*/,
const char* globalsFolderPath,
void* codeBaseEnvProxy)
{
using namespace game;
static const char dbfFileName[] = "LBuild.dbf";
logDebug("newBuildingType.log", "Hook started");
const auto dbfFilePath{std::filesystem::path(globalsFolderPath) / dbfFileName};
addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Fighter, "L_FIGHTER");
addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Mage, "L_MAGE");
addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Archer, "L_ARCHER");
addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Other, "L_CUSTOM");
addCustomBuildingCategory(dbfFilePath, BuildingBranchNumber::Special, "L_SPECIAL");
auto& table = LBuildingCategoryTableApi::get();
auto& categories = BuildingCategories::get();
thisptr->bgn = nullptr;