-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserInterface.cpp
1430 lines (1208 loc) · 60 KB
/
UserInterface.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
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <timeapi.h>
#include <wincodec.h>
#include "Patcher.h"
#include "Util.h"
#include "Resources.h"
#include "Stream.h"
#include "Tethys/Common/Library.h"
#include "Tethys/API/Mission.h"
#include "Tethys/API/TethysGame.h"
#include "Tethys/API/GameMap.h"
#include "Tethys/API/Enumerators.h"
#include "Tethys/Game/TApp.h"
#include "Tethys/Game/MapObject.h"
#include "Tethys/UI/GameFrame.h"
#include "Tethys/UI/Odasl.h"
#include "Tethys/Resource/CConfig.h"
#include "Tethys/Resource/StreamIO.h"
#include "Tethys/Resource/ResManager.h"
#include "Tethys/Resource/MemoryMappedFile.h"
#include "Tethys/Resource/Font.h"
#include "Tethys/Resource/SoundManager.h"
#include "Tethys/Resource/LocalizedStrings.h"
#include "Tethys/Resource/GFXBitmap.h"
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <random>
#include <string>
#include <filesystem>
#include <map>
#include <set>
#include <deque>
#include <charconv>
using namespace Tethys;
using namespace TethysAPI;
using namespace Tethys::TethysUtil;
using namespace Patcher::Util;
using namespace Patcher::Registers;
static constexpr char NewIconName[] = "FENRISUL_OP2_ICON";
static constexpr uint32 MaxNumMessagesLogged = 64; // ** TODO Try to increase this?
static constexpr uint32 MaxLogMessageLen = sizeof(ListItem::text) - 10; // ** TODO Try to increase this?
static constexpr uint32 MaxChatMessageLen = (std::min)(sizeof(ChatCommand::message), MaxLogMessageLen);
static MessageLogEntry<MaxLogMessageLen> g_messageLogRb[MaxNumMessagesLogged] = { };
static char g_chatBarMessage[MaxLogMessageLen] = { };
static char g_statusBarMessage[MaxLogMessageLen] = { };
enum class PreserveAspect : int {
Disabled = 0,
Enabled,
CropWidth,
CropHeight
};
// =====================================================================================================================
static HBITMAP LoadGdiImageFromFile(
const std::filesystem::path& path,
int scaleWidth = 0,
int scaleHeight = 0,
PreserveAspect preserveAspect = PreserveAspect::Disabled,
HDC hDc = NULL)
{
HBITMAP hBitmapOut = NULL;
HRESULT hInitResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
HRESULT hResult = hInitResult;
IWICImagingFactory* pWic = nullptr;
IWICBitmapDecoder* pDecoder = nullptr;
IWICBitmapFrameDecode* pFrame = nullptr;
IWICBitmapScaler* pScaler = nullptr;
IWICFormatConverter* pConverter = nullptr;
if (SUCCEEDED(hResult)) {
hResult = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pWic));
}
// Open the image.
if (SUCCEEDED(hResult)) {
const auto filename = std::filesystem::absolute(path);
hResult = pWic->CreateDecoderFromFilename(
filename.wstring().data(), nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &pDecoder);
}
// Get frame 0 of the image.
if (SUCCEEDED(hResult)) {
hResult = pDecoder->GetFrame(0, &pFrame);
}
uint32 srcWidth = 0;
uint32 srcHeight = 0;
if (SUCCEEDED(hResult)) {
hResult = pFrame->GetSize(&srcWidth, &srcHeight);
}
// Convert the image to a GDI compatible bitmap.
if (SUCCEEDED(hResult)) {
hResult = pWic->CreateFormatConverter(&pConverter);
}
if (SUCCEEDED(hResult)) {
hResult = pConverter->Initialize(
pFrame, GUID_WICPixelFormat32bppBGR, WICBitmapDitherTypeNone, nullptr, 0.f, WICBitmapPaletteTypeCustom);
}
// Scale the image, if requested.
const bool scaled = (srcWidth > 0) && (srcHeight > 0) && (scaleWidth > 0) && (scaleHeight > 0);
if (SUCCEEDED(hResult) && scaled) {
auto ScaleWidth = [preserveAspect, srcWidth, srcHeight, &scaleWidth, &scaleHeight]() {
if ((preserveAspect == PreserveAspect::Enabled) || (preserveAspect == PreserveAspect::CropWidth)) {
scaleWidth = scaleHeight * srcWidth / srcHeight;
}
};
auto ScaleHeight = [preserveAspect, srcWidth, srcHeight, &scaleWidth, &scaleHeight]() {
if ((preserveAspect == PreserveAspect::Enabled) || (preserveAspect == PreserveAspect::CropHeight)) {
scaleHeight = scaleWidth * srcHeight / srcWidth;
}
};
if (scaleWidth >= scaleHeight) {
ScaleWidth();
ScaleHeight();
}
else {
ScaleHeight();
ScaleWidth();
}
if (hResult = pWic->CreateBitmapScaler(&pScaler); SUCCEEDED(hResult)) {
hResult = pScaler->Initialize(pConverter, scaleWidth, scaleHeight, WICBitmapInterpolationModeHighQualityCubic);
}
}
else {
scaleWidth = srcWidth;
scaleHeight = srcHeight;
}
if (SUCCEEDED(hResult) && (scaleWidth > 0) && (scaleHeight > 0)) {
if (HDC hDcScreen = GetDC(NULL); hDcScreen != NULL) {
BITMAPINFO createInfo = { };
createInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
createInfo.bmiHeader.biWidth = scaleWidth;
createInfo.bmiHeader.biHeight = -scaleHeight;
createInfo.bmiHeader.biPlanes = 1;
createInfo.bmiHeader.biBitCount = 32;
createInfo.bmiHeader.biCompression = BI_RGB;
// Create DIB section and copy the image source to it.
void* pImageBuffer = nullptr;
HBITMAP hDibBitmap = CreateDIBSection(hDcScreen, &createInfo, DIB_RGB_COLORS, &pImageBuffer, NULL, 0);
if (hDibBitmap != NULL) {
const size_t scanlineSize = (((scaleWidth * 32) + 31) / 32) * 4;
const size_t bufferSize = scanlineSize * scaleHeight;
// This actually performs the format conversion (and scaling, if requested).
hResult = scaled ? pScaler->CopyPixels(nullptr, scanlineSize, bufferSize, (BYTE*)(pImageBuffer))
: pConverter->CopyPixels(nullptr, scanlineSize, bufferSize, (BYTE*)(pImageBuffer));
if (SUCCEEDED(hResult)) {
// Create the output compatible bitmap.
hBitmapOut = CreateDIBitmap(
hDc ? hDc : hDcScreen, &createInfo.bmiHeader, CBM_INIT, pImageBuffer, &createInfo, DIB_RGB_COLORS);
}
DeleteObject(hDibBitmap);
}
else {
hResult = E_FAIL;
}
ReleaseDC(NULL, hDcScreen);
}
else {
hResult = E_FAIL;
}
}
if (SUCCEEDED(hInitResult)) {
CoUninitialize();
}
return hBitmapOut;
}
// =====================================================================================================================
// Replacement resource template names in .rc files must be defined using the RESOURCE_REPLACE macro defined in Util.h.
static std::string FindResourceReplacement(
const char* pResType,
const char* pTemplate,
HMODULE* phModule)
{
const auto hModule = *phModule;
std::string moduleName;
if ((hModule == NULL) || (hModule == g_tApp.hOut2ResLib_)) {
moduleName = "OUT2RES.DLL";
}
else if (hModule == g_tApp.hInstance_) {
moduleName = "OUTPOST2.EXE";
}
else if (hModule == GetModuleHandleA("op2shres.dll")) {
moduleName = "OP2SHRES.DLL";
}
else {
char buf[MAX_PATH] = "";
GetModuleFileNameA(hModule, &buf[0], sizeof(buf));
moduleName = std::filesystem::path(buf).filename().string();
std::transform(moduleName.begin(), moduleName.end(), moduleName.begin(), ::toupper);
}
char buf[256] = "";
if (IS_INTRESOURCE(pTemplate)) {
snprintf(
&buf[0], sizeof(buf), RESOURCE_REPLACE_NAME(%s, %i), moduleName.data(), reinterpret_cast<int>(pTemplate));
}
else {
snprintf(&buf[0], sizeof(buf), RESOURCE_REPLACE_NAME(%s, %s), moduleName.data(), pTemplate);
}
std::string result = "";
if (FindResourceA(g_hInst, &buf[0], pResType) != NULL) {
// ** TODO This should search in all loaded modules
result = buf;
*phModule = g_hInst;
}
return result;
}
// =====================================================================================================================
// Replaces main menu assets.
static bool SetMainMenuPatch(
bool enable)
{
static Patcher::PatchContext patcher("OP2Shell.dll", true);
bool success = true;
if (enable) {
// Inject main menu background replacement, and draw the OP2 logo and game version number on the main menu screen.
static HDC hDcLogo = NULL;
static HANDLE hBitmapLogo = NULL;
static BITMAP hPvLogo = { };
static HFONT hVersionFont = NULL;
// In OP2Shell::Init()
patcher.LowLevelHook(0x13007EB9, [](Eax<HBITMAP>& hBitmapBg, Esp<void*> pEsp) {
// If files of the form "MainMenuBackground{00-99}.png" (continuous) exist, pick one at random.
std::filesystem::path bgPath;
std::vector<std::filesystem::path> bgFilePaths;
char curFilename[] = "MainMenuBackground00.png";
if (auto dir = GetFilePath(curFilename); dir.has_parent_path()) {
dir = dir.parent_path();
for (int i = 0; i < 100; ++i) {
curFilename[sizeof("MainMenuBackground") - 1] = '0' + (i / 10);
curFilename[sizeof("MainMenuBackground")] = '0' + (i % 10);
if (auto curPath = dir/curFilename; std::filesystem::exists(curPath)) {
bgFilePaths.emplace_back(std::move(curPath));
}
else {
break;
}
}
}
if (bgFilePaths.empty() == false) {
std::shuffle(bgFilePaths.begin(), bgFilePaths.end(), std::mt19937());
bgPath = bgFilePaths[0];
}
if (hDcLogo = hDcLogo ? hDcLogo : CreateCompatibleDC(NULL); (hDcLogo != NULL) && (hBitmapLogo == NULL)) {
// Load the Outpost 2 logo image from op2shres.dll so we can draw it to the main menu.
HMODULE hOp2ShRes = GetModuleHandleA("op2shres.dll");
hBitmapLogo = (hOp2ShRes != NULL) ? LoadImageA(hOp2ShRes, MAKEINTRESOURCEA(145), IMAGE_BITMAP, 0, 0, 0) : NULL;
if (hBitmapLogo != NULL) {
hPvLogo = { };
GetObjectA(hBitmapLogo, sizeof(hPvLogo), &hPvLogo);
}
}
if (hVersionFont == NULL) {
// Initialize the font to use to draw the version text on the main menu.
LOGFONTA createInfo = { };
strncpy_s(&createInfo.lfFaceName[0], sizeof(createInfo.lfFaceName), "Arial", _TRUNCATE);
createInfo.lfHeight = -11;
createInfo.lfWeight = 400;
createInfo.lfCharSet = 1;
createInfo.lfOutPrecision = 7;
createInfo.lfPitchAndFamily = 82;
hVersionFont = CreateFontIndirectA(&createInfo);
}
auto*const pRect = static_cast<RECT*>(PtrInc(pEsp, 0xC));
hBitmapBg =
bgPath.empty() ? NULL : LoadGdiImageFromFile(bgPath, pRect->right, pRect->bottom, PreserveAspect::CropWidth);
return (hBitmapBg != NULL) ? 0x13007ED3 : 0; // Use original background image as a fallback.
});
// In OP2Shell::WndProc()
// ** TODO Should do all blits to a backbuffer, modern Windows DWM presents after every window DC blit
patcher.LowLevelHook(0x13008012, [](Ebx<void*> pThis, Esi<HDC> hDcWnd, Ebp<int> x, Edi<int> y) {
const auto [cx, cy] = std::tie(*PtrInc<int*>(pThis, 0x1C), *PtrInc<int*>(pThis, 0x20));
// Draw Outpost 2 logo.
if ((hDcLogo != NULL) && (hBitmapLogo != NULL) && (hPvLogo.bmWidth != 0) && (hPvLogo.bmHeight != 0)) {
SelectObject(hDcLogo, hBitmapLogo);
BitBlt(
hDcWnd, x + ((cx - hPvLogo.bmWidth) / 2), y + 40, hPvLogo.bmWidth, hPvLogo.bmHeight, hDcLogo, 0, 0, SRCCOPY);
}
// Draw OPU mod version number.
if (hVersionFont != NULL) {
static constexpr char Version[] = "OPU Mod v" OP2_VERSION_TRIPLE_STR;
RECT textRect = { 10, 10, 0, 0 };
SetTextColor(hDcWnd, 0x606060);
SetBkMode(hDcWnd, TRANSPARENT);
SelectObject(hDcWnd, hVersionFont);
if (DrawTextA(hDcWnd, &Version[0], -1, &textRect, DT_CALCRECT) != 0) {
DrawTextA(hDcWnd, &Version[0], -1, &textRect, DT_TOP | DT_LEFT);
}
}
});
// In OP2Shell::ShutDown()
patcher.LowLevelHook(0x13009383, [] {
if (hDcLogo != NULL) {
DeleteDC(hDcLogo);
hDcLogo = NULL;
}
if (hBitmapLogo != NULL) {
DeleteObject(hBitmapLogo);
hBitmapLogo = NULL;
}
if (hVersionFont != NULL) {
DeleteObject(hVersionFont);
hVersionFont = NULL;
}
});
// In OP2Shell::RegisterClass()
patcher.HookCall(0x130092ED, StdcallLambdaPtr([](HMODULE, const char*)
{ return LoadIconA(g_hInst, &NewIconName[0]); }));
// In AviWnd::RegisterClass()
patcher.LowLevelHook(0x1300129E, [](Esp<void*> pEsp)
{ PtrInc<WNDCLASSA*>(pEsp, 20)->hIcon = LoadIconA(g_hInst, &NewIconName[0]); });
// Enable D keyboard shortcut for the hidden debug menu button on the main menu dialog.
// Hook MainMenuDialog::DlgProc() (replace vtbl entry)
patcher.Write(0x130110A0, ThiscallLambdaPtr([](IDlgWnd* pThis, UINT uMsg, WPARAM wParam, LPARAM lParam) {
static auto*const pfnDialogProc =
static_cast<INT_PTR(__thiscall*)(IDlgWnd*, UINT, WPARAM, LPARAM)>(patcher.FixPtr(0x13002900));
const INT_PTR result = pfnDialogProc(pThis, uMsg, wParam, lParam);
if (uMsg == WM_INITDIALOG) {
if (const HWND hDebugButton = GetDlgItem(pThis->hWnd_, 1033); hDebugButton != NULL) {
SendMessageA(hDebugButton, WM_SETTEXT, 0, LPARAM("&DEBUG TEST..."));
}
}
return result;
}));
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Replaces several UI dialogs, as well as the icon used by game windows.
bool SetUiResourceReplacePatch(
bool enable)
{
static Patcher::PatchContext op2Patcher;
static Patcher::PatchContext odaslPatcher("odasl.dll", true);
static Patcher::PatchContext sysPatcher(&LoadStringA);
static std::set<std::string> loadedFonts;
bool success = true;
if (enable) {
// ** TODO Consider hooking the Win32 API imports instead?
op2Patcher.Hook(IDlgWnd::Vtbl()->pfnDoModal, SetCapturedTrampoline, ThiscallFunctor(
[F = decltype(IDlgWnd::VtblType::pfnDoModal){}](IDlgWnd* pThis, const char* pTmpl, HMODULE hMod) {
const std::string newName = FindResourceReplacement(RT_DIALOG, pTmpl, &hMod);
return F(pThis, (newName.empty() ? pTmpl : newName.data()), hMod);
}));
op2Patcher.Hook(IDlgWnd::Vtbl()->pfnDoModeless, SetCapturedTrampoline, ThiscallFunctor(
[F = decltype(IDlgWnd::VtblType::pfnDoModeless){}](IDlgWnd* pThis, const char* pTmpl, HMODULE hMod, HWND hWnd) {
const std::string newName = FindResourceReplacement(RT_DIALOG, pTmpl, &hMod);
return F(pThis, (newName.empty() ? pTmpl : newName.data()), hMod, hWnd);
}));
// In GameFrame::RegisterClass()
op2Patcher.HookCall(0x49B1C4, StdcallLambdaPtr([](HMODULE, const char*)
{ return LoadIconA(g_hInst, &NewIconName[0]); }));
// In IWnd::RegisterClass()
op2Patcher.LowLevelHook(0x43151D, [](Esp<void*> pEsp)
{ PtrInc<WNDCLASSA*>(pEsp, 8)->hIcon = LoadIconA(g_hInst, &NewIconName[0]); });
// In wplLoadResourceBitmap()
static std::set<std::string> resourceNames;
odaslPatcher.LowLevelHook(0x2000B129, [](Eax<const char*>& pName, Esp<void*> pEsp) {
auto it = resourceNames.insert(FindResourceReplacement(RT_BITMAP, pName, PtrInc<HMODULE*>(pEsp, 0x10))).first;
pName = ((it == resourceNames.end()) || it->empty()) ? pName : it->data();
});
// Hook LoadStringA() to replace string table resources (which are used by odasl for fonts and element colors).
sysPatcher.Hook(&LoadStringA, SetCapturedTrampoline, StdcallFunctor(
[F = decltype(&LoadStringA){}](HMODULE hMod, UINT id, char* pBuffer, int size) -> int {
if (auto name = FindResourceReplacement(RT_STRING, MAKEINTRESOURCE(id), &hMod); name.empty() == false) {
if (HRSRC hRsrc = FindResourceA(hMod, name.data(), RT_STRING); hRsrc != NULL) {
if (size == 0) {
return SizeofResource(hMod, hRsrc);
}
else if (HANDLE hRes = LoadResource(hMod, hRsrc); hRes != NULL) {
if (void* pStr = LockResource(hRes); pStr != nullptr) {
return (strncpy_s(pBuffer, size, static_cast<char*>(pStr), _TRUNCATE) == 0) ? strlen(pBuffer) : 0;
}
}
}
}
return F(hMod, id, pBuffer, size);
}));
// Load Open Sans and Roboto fonts found in search paths.
// ** TODO Load any *.ttf/*.ttc/*.otf font files found
static constexpr const char* FontFilenames[] = {
"OpenSans-Bold.ttf", "OpenSans-BoldItalic.ttf", "OpenSans-Italic.ttf", "OpenSans-Regular.ttf", "Roboto-Bold.ttf",
"Roboto-BoldItalic.ttf", "Roboto-Italic.ttf", "Roboto-Regular.ttf"
};
for (const char* pFilename : FontFilenames) {
if (auto path = GetFilePath(pFilename).string(); (path.empty() == false) && (loadedFonts.count(path) == 0)) {
if (int count = AddFontResourceExA(path.data(), FR_PRIVATE, nullptr); count > 0) {
loadedFonts.insert(path);
}
}
}
success = (op2Patcher.GetStatus() == PatcherStatus::Ok) &&
(odaslPatcher.GetStatus() == PatcherStatus::Ok) &&
(sysPatcher.GetStatus() == PatcherStatus::Ok) &&
SetMainMenuPatch(true);
if (success) {
static const auto cleanup = atexit([] { SetUiResourceReplacePatch(false); });
}
}
if ((enable == false) || (success == false)) {
for (const std::string& font : loadedFonts) {
RemoveFontResourceExA(font.data(), FR_PRIVATE, nullptr);
}
loadedFonts.clear();
success &= (op2Patcher.RevertAll() == PatcherStatus::Ok);
success &= (odaslPatcher.RevertAll() == PatcherStatus::Ok);
success &= (sysPatcher.RevertAll() == PatcherStatus::Ok);
success &= (SetMainMenuPatch(false));
}
// Re-init Odasl to refresh loaded resources.
if (HMODULE hShell = GetModuleHandleA("OP2Shell.dll"); hShell && g_configFile.GetInt("Game", "SpiffyDraw", 1)) {
Odasl::wplExit();
auto*const pfnShellInitOdasl = reinterpret_cast<ibool(FASTCALL*)(void* pShell)>(
reinterpret_cast<uint8*>(hShell) - OP2ShellBase + 0x13007D30);
pfnShellInitOdasl(reinterpret_cast<uint8*>(hShell) - OP2ShellBase + 0x130158F0);
}
return success;
}
// =====================================================================================================================
static int __fastcall MessageLog_AddMessage(
MessageLog* pThis, int,
uint32 pixelX,
uint32 pixelY,
char* pText,
SoundID soundID)
{
if (soundID == SoundID{0}) {
soundID = SoundID::Beep8;
}
int result = 1;
if ((soundID < SoundID::SavantBegin) || (soundID > SoundID::SavantEnd)) {
g_soundManager.AddGameSound(soundID, -1);
}
else if (pThis->ShouldAddMessage(soundID, pixelX, pixelY)) {
g_soundManager.AddSavantSound(soundID, pixelX, pixelY, -1);
}
else {
result = 0;
}
if (result != 0) {
pThis->timestamps_[0] = timeGetTime();
int index = ((pThis->rbBegin_ + pThis->numRbElements_) % MaxNumMessagesLogged);
if (pThis->numRbElements_ == MaxNumMessagesLogged) {
pThis->rbBegin_ = ((pThis->rbBegin_ + 1) % MaxNumMessagesLogged);
}
else {
++(pThis->numRbElements_);
}
auto& entry = g_messageLogRb[index];
entry.pixelX = pixelX;
entry.pixelY = pixelY;
g_gameFrame.SetChatBarText(pText, 0xFFFFFF);
result = snprintf(&entry.message[0], MaxChatMessageLen, "<N>%i: %s", TethysGame::Mark(), pText);
}
return result;
}
// =====================================================================================================================
static int __fastcall CommunicationListData_GetString(
void* pThis, int,
int index,
char* pBuffer,
size_t bufferSize)
{
auto& entry = g_messageLogRb[g_messageLog.GetEntrySlotFromIndex<MaxNumMessagesLogged>(index)];
return snprintf(
pBuffer, bufferSize, (((entry.pixelX != -2) || (entry.pixelY != -1)) ? "<C2>%s" : "%s"), &entry.message[0]);
}
// =====================================================================================================================
static void __fastcall MessageLogJumpTo_OnClick(
void* pThis)
{
int index = g_messageLog.GetEntrySlotFromIndex<MaxNumMessagesLogged>(OP2Mem<0x567D30, int&>());
if (index != -1) {
auto& entry = g_messageLogRb[index];
if (entry.pixelY != -1) {
g_gameFrame.detailPane_.CenterViewOn(entry.pixelX, entry.pixelY);
}
}
}
// =====================================================================================================================
static void __fastcall CommunicationsReport_CenterViewOn(
void* pThis, int,
int index)
{
if (index != -1) {
auto& entry = g_messageLogRb[g_messageLog.GetEntrySlotFromIndex<MaxNumMessagesLogged>(index)];
if (entry.pixelY != -1) {
g_gameFrame.detailPane_.CenterViewOn(entry.pixelX, entry.pixelY);
}
}
}
// =====================================================================================================================
static void __fastcall CommunicationsReport_SetJumpButtonEnabled(
void* pThis, int,
int index)
{
auto*const pButton = static_cast<UIButton*>(PtrInc(pThis, 2876)); // ** TODO come up with a def for CommsReport
if (index == -1) {
pButton->SetEnabledState(false);
}
else {
auto& slot = *static_cast<int*>(PtrInc(pThis, 3040));
slot = g_messageLog.GetEntrySlotFromIndex<MaxNumMessagesLogged>(index);
auto& entry = g_messageLogRb[slot];
pButton->SetEnabledState(entry.pixelY != -1);
}
}
// =====================================================================================================================
// Increases the max length of chat messages, and bypasses forced uppercasing of chat bar display.
bool SetChatLengthPatch(
bool enable)
{
static Patcher::PatchContext patcher;
bool success = true;
if (enable) {
constexpr uint32 MaxPrefixLen = sizeof("<N>12345: MaxLenName12: ") - 1;
constexpr uint32 ReservePrefixLen = max(MaxPrefixLen - (MaxLogMessageLen - MaxChatMessageLen), 0);
constexpr uint32 MaxInputLen = (MaxChatMessageLen - ReservePrefixLen) - 1;
// Status bar (chat input) patches
// In StatusBar::OnUIEvent()
patcher.LowLevelHook(0x4118C0, [](Eax<uint32> len) { return (len <= MaxInputLen) ? 0x4118C9 : 0x41196C; });
patcher.LowLevelHook(0x4118EA, [](Eax<uint32> len, Ebx<char> val)
{ g_statusBarMessage[len] = val; return 0x4118EE; });
patcher.LowLevelHook(0x4119DB, [](Edi<CommandPacket*> pPacket, Eax<uint32> len)
{ strncpy_s(&pPacket->data.chat.message[0], MaxChatMessageLen, &g_statusBarMessage[0], len); return 0x4119F1; });
// In StatusBar::SetTopText()
patcher.LowLevelHook(0x411D30, [](Ebx<char*>& pDst) { pDst = &g_statusBarMessage[0]; });
patcher.LowLevelHook(0x411D80, [](Edi<int>& i)
{ const auto index = i++; g_statusBarMessage[index] = toupper(g_statusBarMessage[index]); return 0x411D93; });
patcher.LowLevelHook(0x411DB4, [](Eax<int> i) { return (g_statusBarMessage[i] == '&') ? 0x411DC5 : 0x411DBA; });
patcher.LowLevelHook(0x411DE0, [](Eax<int> len, Edx<char>& chr) { chr = g_statusBarMessage[len]; });
// In StatusBar::Paint()
// ** TODO Probably worth it to just reimplement this function entirely, but this works
patcher.LowLevelHook(0x411ABA, [](Eax<char*>& pStr) { pStr = &g_statusBarMessage[0]; });
patcher.LowLevelHook(0x411ADB, [](Eax<char*>& pStr) { pStr = &g_statusBarMessage[0]; });
patcher.LowLevelHook(0x411B90, [](Edx<char*>& pStr) { pStr = &g_statusBarMessage[0]; });
patcher.LowLevelHook(0x411BC3, [](Eax<char*>& pStr) { pStr = &g_statusBarMessage[0]; });
patcher.LowLevelHook(0x411B02, [](Eax<char*>& pAmpersand, Eax<int> offset)
{ pAmpersand = &g_statusBarMessage[1 + offset]; return 0x411B07; });
patcher.LowLevelHook(0x411C2F, [](Eax<char*>& pAmpersand, Eax<int> offset)
{ pAmpersand = &g_statusBarMessage[1 + offset]; return 0x411C34; });
patcher.LowLevelHook(0x411B17, [](Ecx<int>& len, Eax<char*>& pAfterAmp, Eax<int> offset)
{ len -= 2; pAfterAmp = &g_statusBarMessage[2 + offset]; return 0x411B1F; });
patcher.LowLevelHook(0x411BE9, [](Ecx<int>& len, Eax<char*>& pAfterAmp, Eax<int> offset)
{ len -= 2; pAfterAmp = &g_statusBarMessage[2 + offset]; return 0x411BF1; });
// DansRule (chat display) patches
// Reimplement GameFrame::SetChatBarText()
patcher.Hook(0x49BFE0, ThiscallLambdaPtr([](GameFrame* pThis, char* pText, COLORREF color) {
pThis->chatColor_ = color;
pThis->chatLength_ = strlen(pText);
strncpy_s(&g_chatBarMessage[0], MaxChatMessageLen, pText, _TRUNCATE);
InvalidateRect(pThis->hWnd_, &pThis->chatRect_, FALSE);
}));
// In DansRule::OnPaint()
patcher.LowLevelHook(0x499F22, [](Edx<char*>& pChatMessage) { pChatMessage = &g_chatBarMessage[0]; });
// In DansRule::WndProc()
patcher.LowLevelHook(0x49BE87, [] { g_chatBarMessage[0] = '\0'; });
// Communications log patches
patcher.Hook(0x439070, &MessageLog_AddMessage);
patcher.Hook(0x466760, &CommunicationListData_GetString);
patcher.Hook(0x466800, &MessageLogJumpTo_OnClick);
patcher.Hook(0x466B30, &CommunicationsReport_CenterViewOn);
patcher.Hook(0x466AA0, &CommunicationsReport_SetJumpButtonEnabled);
// In MessageLog::Save()
patcher.LowLevelHook(0x439350, [](Eax<int> index, Edi<StreamIO*> pStream)
{ return (pStream->Write(sizeof(g_messageLogRb[0]), &g_messageLogRb[index]) != 0) ? 0x439367 : 0x43937E; });
// In MessageLog::Load()
// ** TODO See if this can be made backwards compatible with older saves
patcher.LowLevelHook(0x43941D, [](Eax<int> index, Esi<StreamIO*> pStream)
{ return (pStream->Read(sizeof(g_messageLogRb[0]), &g_messageLogRb[index]) != 0) ? 0x439434 : 0x43944B; });
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Allows players to ping locations by sending chat messages of the form "@tileX,tileY".
// ** TODO Look into how to make it respond to spacebar like disaster warnings etc. do
// ** TODO Add a mouse command to ping by clicking on the detail pane or mini map
bool SetChatPingLocationPatch(
bool enable)
{
static Patcher::PatchContext patcher;
bool success = true;
if (enable) {
// In Player::ProcessCommandPacket()
patcher.LowLevelHook(0x40FE07, [](Eax<char*> pText, Esi<ChatCommand*> pData) {
bool isPing = false;
const std::string_view msg(pData->message);
if (size_t sep = msg.find(','); (sep != std::string_view::npos) && (msg[0] == '@')) {
int x = 0;
int y = 0;
const auto [p, ec] = std::from_chars(msg.data() + 1, msg.data() + sep, x);
const auto [p2, ec2] = std::from_chars(msg.data() + sep + 1, msg.data() + msg.size(), y);
isPing = (ec == std::errc()) && (ec2 == std::errc());
if (isPing) {
const Location loc = GameMap::At(x, y);
g_messageLog.AddMessage(loc.GetPixelX(), loc.GetPixelY(), pText, SoundID::Beep9);
}
}
return isPing ? 0x4101D3 : 0;
});
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Converts escaped characters to real characters (in ini strings).
static std::string UnEscapeString(
const std::string_view& in)
{
static constexpr std::pair<const char*, const char*> pReplacements[] = {
{ "\\a", "\a" }, { "\\b", "\b" }, { "\\f", "\f" }, { "\\n", "\n" }, { "\\r", "\r" }, { "\\t", "\t" },
{ "\\v", "\v" }, { "\\\\", "\\" }, { "\\'", "\'" }, { "\\\"", "\"" }, { "\\?", "\?" }
};
std::string out(in);
for (const auto [pEscaped, pUnescaped] : pReplacements) {
for (size_t p = out.length(); ((p = out.rfind(pEscaped, p)) != std::string::npos); out.replace(p, 2, pUnescaped));
}
return out;
}
// =====================================================================================================================
// Sets localized string table entries in Outpost2.exe and OP2Shell.dll based on settings in language.ini.
// ** TODO replaced UI dialogs lose localization, mission DLLs aren't localized
bool SetLocalizationPatch(
bool enable)
{
static Patcher::PatchContext op2Patcher;
static Patcher::PatchContext shellPatcher("OP2Shell.dll", true);
static std::deque<char*> pAllocations;
bool success = true;
if (enable && ((op2Patcher.NumPatches() + shellPatcher.NumPatches()) == 0)) {
if (char confPath[MAX_PATH] = ""; g_resManager.GetFilePath("language.ini", &confPath[0])) {
auto PatchStrings = [confPath](const char* pSectionName, auto& stringTable, Patcher::PatchContext* pPatcher) {
bool success = true;
char setting[1024] = "";
for (size_t i = 0; (success && (i < TethysUtil::ArrayLen(stringTable))); ++i) {
const size_t len = GetPrivateProfileStringA(
pSectionName, std::to_string(i).data(), "", &setting[0], sizeof(setting), &confPath[0]);
if ((len != 0) && (setting[0] != '\0')) {
std::string str = UnEscapeString(setting);
if (char*const pBuf = static_cast<char*>(OP2Alloc(str.length() + 1)); success = (pBuf != nullptr)) {
pAllocations.push_back(pBuf);
strncpy_s(pBuf, str.length() + 1, str.data(), _TRUNCATE);
success &= (pPatcher->Write(&stringTable[i], &pBuf[0]) == PatcherStatus::Ok);
}
}
}
return success;
};
success = PatchStrings("Game", GetLocalizedStringTable(), &op2Patcher) &&
PatchStrings("Shell", GetShellLocalizedStringTable(), &shellPatcher);
if (success) {
static const auto cleanup = atexit([] { SetLocalizationPatch(false); });
}
}
}
if ((enable == false) || (success == false)) {
for (char* pAllocation : pAllocations) {
OP2Free(pAllocation);
}
pAllocations.clear();
success &= (op2Patcher.RevertAll() == PatcherStatus::Ok);
success &= (shellPatcher.RevertAll() == PatcherStatus::Ok);
}
if (success) {
OP2Thunk<0x45C710>(); // Call ReportButtonHelpText::Init() to refresh report button mouseover text
}
return success;
}
// =====================================================================================================================
// Replaces usage of Arial in the game's UI with the given font.
// ** TODO Figure out how to make antialiasing look better
bool SetFontPatch(
const char* pNewFont)
{
static Patcher::PatchContext patcher;
static std::string fontStr;
bool success = true;
bool isDefault = ((pNewFont == nullptr) || (_stricmp(pNewFont, "Arial") == 0));
if (isDefault) {
pNewFont = "Arial";
}
fontStr = pNewFont;
LOGFONTA createInfo = {};
createInfo.lfCharSet = 1;
createInfo.lfOutPrecision = 7;
createInfo.lfPitchAndFamily = 82;
strncpy_s(createInfo.lfFaceName, sizeof(createInfo.lfFaceName), pNewFont, _TRUNCATE);
createInfo.lfHeight = -11;
createInfo.lfWeight = 400;
// ** TODO Define these font fields
for (Font* pFont:
{ PtrInc<Font*>(&g_gameFrame, 0x0BC8), PtrInc<Font*>(&g_gameFrame, 0x2828), PtrInc<Font*>(&g_gameFrame, 0x4488) })
{
pFont->Init(createInfo);
}
if (isDefault == false) {
createInfo.lfHeight = 13;
createInfo.lfWeight = 700;
patcher.Write(&g_gameFrame.hChatFont_, CreateFontIndirectA(&createInfo));
patcher.Write(&g_gameFrame.statusBar_.hFont_, CreateFontIndirectA(&createInfo));
createInfo.lfHeight = 48;
patcher.Write(&g_gameFrame.detailPane_.hLargeMessageFont_, CreateFontIndirectA(&createInfo));
patcher.ReplaceReferencesToGlobal(0x4DEB40, 1, fontStr.data()); // Replace "Arial"
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if (isDefault || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Swap the behavior of holding shift vs. not when using control group hotkeys, such that using shift centers your view.
// ** TODO Would like to make it so if you double-select a group (e.g. press "1" twice) that also centers your view
// ** TODO Double clicking a unit should select all units of the same type on screen
bool SetControlGroupHotkeyPatch(
bool enable)
{
static Patcher::PatchContext patcher;
bool success = true;
if (enable) {
// In TApp::HandleCommand()
patcher.WriteBytes(0x486901, { 0x40, 0x04, }); // 0x2C, 0x02
patcher.WriteBytes(0x486917, { 0x0A, 0x04, }); // 0xF9, 0x01
patcher.WriteBytes(0x486989, { 0x87, 0x01, }); // 0x98, 0x03
patcher.WriteBytes(0x4869A4, { 0x89, 0x01, }); // 0x9D, 0x03
patcher.WriteBytes(0x486B16, { 0x21, 0x9D, }); // 0xDE, 0x9C
patcher.WriteBytes(0x486D27, { 0xDE, 0x9C, }); // 0x21, 0x9D
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Patch for setting default focus of UI elements.
// ** TODO Reimplement this with C++ hooks
bool SetUiHighlightFix(
bool enable)
{
static Patcher::PatchContext patcher("odasl.dll", true);
bool success = true;
if (enable) {
patcher.WriteBytes(0x20004E92, {
0xF6, 0xC1, 0x04, // test cl, 0x4
0x75, 0x19, // jne 0x1E (0x20004EB0)
0xF6, 0xC1, 0x10, // test cl, 0x10
0x75, 0x09, // jne 0x13 (0x20004EA5)
0xF6, 0xC1, 0x01, // test cl, 0x1
0x75, 0x01, // jne 0x10 (0x20004EA2)
0xC3, // retn
0xB0, 0x03, // mov al, 0x3
0xC3, // retn
0xF6, 0xC1, 0x01, // test cl, 0x1
0x75, 0x03, // jne 0x1B (0x20004EAD)
0xB0, 0x02, // mov al, 0x2
0xC3, // retn
0xB0, 0x04, // mov al, 0x4
0xC3, // retn
0xF6, 0xC1, 0x01, // test cl, 0x1
0x75, 0x03, // jne 0xB (0x20004EB8)
0xB0, 0x01, // mov al, 0x1
0xC3, // retn
0xF6, 0x05, 0xB9, 0x21, 0x01, 0x20, 0x10, // test BYTE PTR ds:0x200121B9, 0x10
0x74, 0xE0, // je -0xC (0x20004EA1)
0xB0, 0x05, // mov al, 0x5
0xC3, // retn
0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,
0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90,
0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, // nop
});
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Set default focus of the checkboxes in the broadcast/IP address window.
bool SetIpWindowFocusPatch(
bool enable)
{
static Patcher::PatchContext patcher;
bool success = true;
if (enable) {
// In IPDialog::DlgProc()
patcher.Write<uint32>(0x419779, 1008); // GetDlgItem.nIDDlgItem 1005 => 1008
patcher.Write<uint32>(0x41979B, 1007); // GetDlgItem.nIDDlgItem 1005 => 1007
patcher.Write<uint8>(0x4197AE, 1); // EnableWindow.bEnable false => true
success = (patcher.GetStatus() == PatcherStatus::Ok);
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Check bottom coordinate instead of top coordinate of window clip rect in minimap logic.
bool SetMiniMapFix(
bool enable)
{
static Patcher::PatchContext patcher;
bool success = true;
if (enable) {
// In MiniMapPane::WndProc()
success = (patcher.Write<uint8>(0x45865F, 0x1C) == PatcherStatus::Ok); // 0x14
}
if ((enable == false) || (success == false)) {
success &= (patcher.RevertAll() == PatcherStatus::Ok);
}
return success;
}
// =====================================================================================================================
// Makes vehicles display their cargo in mouseover tooltips and in destroyed notifications in the message log.
bool SetVehicleCargoDisplayPatch(
bool enable)
{
static Patcher::PatchContext patcher;
bool success = true;
if (enable && (patcher.NumPatches() == 0)) {
static constexpr int UnitStrSize = sizeof(MapObjectType::unitName_);
static auto GetCargoStr = [](Vehicle* pVec) -> std::string {
static const char*const pTruckCargoStrings[] = {
"empty",
GetLocalizedString(LocalizedString::Food),
GetLocalizedString(LocalizedString::CommonOre),
GetLocalizedString(LocalizedString::RareOre),
GetLocalizedString(LocalizedString::CommonMetals),
GetLocalizedString(LocalizedString::RareMetals),