-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtils.h
1756 lines (1471 loc) · 46.6 KB
/
Utils.h
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
#pragma once
#include <dbghelp.h>
#include <d3dcompiler.h>
#include <wincodec.h>
#include <Shlobj.h>
#include "Globals.h"
#include "Matrix4x4.h"
#include "Log.h"
#define STACK_TIMER(Name) StackTimer Name(__FUNCTION__)
#define CS_LOCK(pCriticalSection) StackReadWriteLock _CRT_CONCATENATE(__FUNCTION__, Lock)(pCriticalSection)
#define CS_LOCK_SPINCOUNT(pCriticalSection, Spincount) StackReadWriteLock _CRT_CONCATENATE(__FUNCTION__, Lock)(pCriticalSection, (DWORD)(Spincount))
typedef struct StackTimer
{
StackTimer(const char* szName)
: m_szName(szName), m_start(clock()), m_end(0), m_duration(0.0)
{
}
~StackTimer()
{
m_end = clock();
m_duration = (double)(m_end - m_start) / CLOCKS_PER_SEC;
printf("%s took %fs\n", m_szName, m_duration);
}
private:
clock_t m_start, m_end;
double m_duration;
const char* m_szName;
} DebugStackTimer;
struct StackReadWriteLock
{
StackReadWriteLock(LPCRITICAL_SECTION pCriticalSection)
{
m_pCriticalSection = pCriticalSection;
InitializeCriticalSection(m_pCriticalSection);
m_bCriticalSectionInitialized = TRUE;
EnterCriticalSection(m_pCriticalSection);
}
StackReadWriteLock(LPCRITICAL_SECTION pCriticalSection, DWORD dwSpinCount)
: m_bCriticalSectionInitialized(FALSE)
{
m_pCriticalSection = pCriticalSection;
/*
* Windows Server 2003 and Windows XP: If the function succeeds, the return value is nonzero.
* If the function fails, the return value is zero (0). To get extended error information, call GetLastError.
* Starting with Windows Vista, the InitializeCriticalSectionAndSpinCount function always succeeds, even in low memory situations.
*/
if (!InitializeCriticalSectionAndSpinCount(m_pCriticalSection, dwSpinCount))
return;
m_bCriticalSectionInitialized = TRUE;
EnterCriticalSection(m_pCriticalSection);
}
~StackReadWriteLock()
{
if (m_bCriticalSectionInitialized)
{
LeaveCriticalSection(m_pCriticalSection);
DeleteCriticalSection(m_pCriticalSection);
m_bCriticalSectionInitialized = FALSE;
}
}
// Delete Copy Constructor
StackReadWriteLock(const StackReadWriteLock&) = delete;
StackReadWriteLock& operator=(const StackReadWriteLock&) = delete;
private:
LPCRITICAL_SECTION m_pCriticalSection;
BOOL m_bCriticalSectionInitialized;
};
enum NierVersion
{
NIERVER_UNKNOWN,
NIERVER_100,
NIERVER_101,
NIERVER_102,
NIERVER_102_UNPACKED,
NIERVER_102_WOLF_EXTENDED_HEAPS,
NIERVER_WINSTORE,
NIERVER_DEBUG,
NIERVER_MAX
};
static std::ostream& operator<<(std::ostream& os, const NierVersion& v)
{
switch (v)
{
case NIERVER_100:
os << "NieR:Automata (v1.00)";
break;
case NIERVER_101:
os << "NieR:Automata (v1.01)";
break;
case NIERVER_102:
os << "NieR:Automata (v1.02)";
break;
case NIERVER_102_UNPACKED:
os << "NieR:Automata (v1.02 Unpacked)";
break;
case NIERVER_102_WOLF_EXTENDED_HEAPS:
os << "NieR:Automata (v1.02 Extended Heaps)";
break;
case NIERVER_WINSTORE:
os << "NieR:Automata (Winstore)";
break;
case NIERVER_DEBUG:
os << "NieR:Automata (Debug)";
break;
case NIERVER_UNKNOWN:
default:
os << "NieR:Automata (Unknown Version)";
break;
}
return os;
}
struct NierVersionInfo
{
NierVersionInfo(NierVersion Version)
: m_pHash(NULL), m_uHashSize(0), m_Version(Version)
{
Init();
}
NierVersionInfo(NierVersion Version, const char* Hash)
: m_pHash((BYTE*)Hash), m_uHashSize(strlen(Hash)), m_Version(Version)
{
Init();
}
void Init(void)
{
switch (m_Version)
{
case NIERVER_100:
m_szVersion = TEXT("NieR:Automata (v1.00)");
break;
case NIERVER_101:
m_szVersion = TEXT("NieR:Automata (v1.01)");
break;
case NIERVER_102:
m_szVersion = TEXT("NieR:Automata (v1.02)");
break;
case NIERVER_102_UNPACKED:
m_szVersion = TEXT("NieR:Automata (v1.02 Unpacked)");
break;
case NIERVER_102_WOLF_EXTENDED_HEAPS:
m_szVersion = TEXT("NieR:Automata (v1.02 Extended Heaps)");
break;
case NIERVER_WINSTORE:
m_szVersion = TEXT("NieR:Automata (Winstore)");
break;
case NIERVER_DEBUG:
m_szVersion = TEXT("NieR:Automata (Debug)");
break;
case NIERVER_UNKNOWN:
default:
m_szVersion = TEXT("NieR:Automata (Unknown Version)");
break;
}
}
bool operator==(NierVersionInfo& other) const
{
return !memcmp(this->m_pHash, other.m_pHash, m_uHashSize);
}
bool operator==(const BYTE* pHash) const
{
return !memcmp(this->m_pHash, pHash, m_uHashSize);
}
BYTE* m_pHash;
ULONG_PTR m_uHashSize;
NierVersion m_Version;
TCHAR* m_szVersion;
};
static NTSTATUS QueryNierBinaryHash(NierVersionInfo& Version)
{
// TCHAR szFileName[MAX_PATH];
// Set the inital status to success
NTSTATUS Status = STATUS_SUCCESS;
// Retrieve the size of the nier bin ary file path
uint32_t uFileNameSize = MAX_PATH;//GetModuleFileName(NULL, NULL, 0);
// Allocate the correct amount of memory
TCHAR* szFileName = new TCHAR[(uFileNameSize + 1) * sizeof(TCHAR)];
// Query the nier binary file path
GetModuleFileName(NULL, szFileName, uFileNameSize + 1);
// Query a file handle to the nier binary
HANDLE hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
// Free the nier binary file path
delete[] szFileName;
// If the handle is invalid, bail
if (hFile == INVALID_HANDLE_VALUE)
return STATUS_INVALID_HANDLE;
// Query the file size of the nier binary
DWORD dwFileSize = GetFileSize(hFile, NULL);
DWORD dwBytesRead;
// Allocate the memory for the nier binary
BYTE* pBinary = new BYTE[dwFileSize];
// Read the binary file
ReadFile(hFile, pBinary, dwFileSize, &dwBytesRead, NULL);
// Close the file handle to the nier binary
CloseHandle(hFile);
// Bail out if there was a partial read
if (dwFileSize != dwBytesRead)
{
delete[] pBinary;
return ERROR_CLUSTER_PARTIAL_READ;
}
ULONG uHashLengthSize;
// Query the hash length
Status = BCryptGetProperty(BCRYPT_SHA256_ALG_HANDLE, BCRYPT_HASH_LENGTH, (PUCHAR)&Version.m_uHashSize, sizeof(ULONG), &uHashLengthSize, 0);
if (SUCCEEDED(Status))
{
// Allocate the memory for hash
Version.m_pHash = new BYTE[Version.m_uHashSize];
// Create the hash
ULONG uBlockSize = (Version.m_uHashSize > UINT32_MAX) ? 0x100000 : Version.m_uHashSize;
// Files bigger than 0xFFFFFFFF are unsupported and invoke UB
Status = BCryptHash(BCRYPT_SHA256_ALG_HANDLE, NULL, 0, pBinary, dwFileSize, Version.m_pHash, (ULONG)Version.m_uHashSize);
}
// Free the binary from memory
delete[] pBinary;
return Status;
}
static NTSTATUS QueryNierBinaryHash(BYTE*& pHash, ULONG& uHashSize)
{
// TCHAR szFileName[MAX_PATH];
// Set the inital status to success
NTSTATUS Status = STATUS_SUCCESS;
// Retrive the size of the nier binary file path
uint32_t uFileNameSize = MAX_PATH;//GetModuleFileName(NULL, NULL, 0);
// Allocate the correct amount of memory
TCHAR* szFileName = new TCHAR[(uFileNameSize + 1) * sizeof(TCHAR)];
// Query the nier binary file path
GetModuleFileName(NULL, szFileName, uFileNameSize + 1);
// Query a file handle to the nier binary
HANDLE hFile = CreateFile(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
// Free the nier binary file path
delete[] szFileName;
// If the handle is invalid, bail
if (hFile == INVALID_HANDLE_VALUE)
return STATUS_INVALID_HANDLE;
// Query the file size of the nier binary
DWORD dwFileSize = GetFileSize(hFile, NULL);
DWORD dwBytesRead;
// Allocate the memory for the nier binary
BYTE* pBinary = new BYTE[dwFileSize];
// Read the binary file
ReadFile(hFile, pBinary, dwFileSize, &dwBytesRead, NULL);
// Close the file handle to the nier binary
CloseHandle(hFile);
// Bail out if there was a partial read
if (dwFileSize != dwBytesRead)
{
delete[] pBinary;
return ERROR_CLUSTER_PARTIAL_READ;
}
ULONG uHashLengthSize;
// Query the hash length
Status = BCryptGetProperty(BCRYPT_SHA256_ALG_HANDLE, BCRYPT_HASH_LENGTH, (PUCHAR)&uHashSize, sizeof(ULONG), &uHashLengthSize, 0);
if (SUCCEEDED(Status))
{
// Allocate the memory for hash
pHash = new BYTE[uHashSize];
// Create the hash
Status = BCryptHash(BCRYPT_SHA256_ALG_HANDLE, NULL, 0, pBinary, dwFileSize, pHash, uHashSize);
}
// Free the binary from memory
delete[] pBinary;
return Status;
}
static NierVersionInfo* QueryNierBinaryVersion(void)
{
static NierVersionInfo Versions[] =
{
{ NIERVER_101, "\xA0\x1A\xC5\x13\x2E\x10\x92\x52\xD6\xD9\xA4\xCB\xF9\x74\x61\x4D\xEC\xFB\xE3\x23\x71\x3C\x1F\xBF\x5B\xC2\x48\xF0\x12\x61\x77\x3F" },
{ NIERVER_102, "\x51\x71\xBE\xD0\x9E\x6F\xEC\x7B\x21\xBF\x0E\xA4\x79\xDB\xD2\xE1\xB2\x28\x69\x5C\x67\xD1\xF0\xB4\x78\x54\x9A\x9B\xE2\xF5\x72\x6A" },
{ NIERVER_102_UNPACKED, "\x5F\x97\x20\xD8\xC7\x7C\xD5\x97\x8E\xFE\x49\x88\x89\x3A\xF8\xFD\x99\x9F\x90\xA4\x76\xA8\xDE\xEB\xB3\x91\x26\x94\xF6\x18\xDC\x43" },
{ NIERVER_102_WOLF_EXTENDED_HEAPS, "\xC9\x90\x4A\x39\xE4\x48\xD6\xCB\x3C\x98\xC2\x8A\x90\x15\x9C\xF9\x31\x47\x53\xB0\xCF\xEA\x5C\xEB\x4E\x76\xA1\x2D\x33\x08\xA3\x55" },
{ NIERVER_WINSTORE, "\x3D\xDE\x56\x6C\xEA\x3E\x3B\xC1\x5E\x45\x92\x66\x02\xFB\x4F\x24\xD4\x8F\x77\xDF\x8A\x7B\xC5\x50\xA5\xB2\xDC\xAE\xCC\xCF\x09\x48" },
{ NIERVER_DEBUG, "\xE9\xEF\x66\x01\xEB\x40\xEB\x0A\x6D\x3F\x30\xA6\x63\x95\x43\xEC\x2F\x81\x71\xC2\x6A\x3D\xE8\xB2\xB1\x30\x39\xEE\xBE\x3B\xC8\x1C" },
{ NIERVER_UNKNOWN }
};
BYTE* pHash;
ULONG uHashSize;
// Set the version the first entry
NierVersionInfo* pVersion = Versions;
// Query the nier binary hash, if it fails return NIERVER_UNKNOWN
if (FAILED(QueryNierBinaryHash(pHash, uHashSize)))
return &Versions[ARRAYSIZE(Versions) - 1];
// Traverse the array comparing the loaded binary hash to the known hashes
for (; pVersion->m_Version != NIERVER_UNKNOWN; ++pVersion)
if (*pVersion == pHash)
break;
// Free the hash memory
delete[] pHash;
return pVersion;
}
struct CCommon : public IUnknown
{
//IUnknownVtbl* m_pVtbl; //0x0000
CCommon* m_pSelf; //0x0008
IID* pGuid; //0x0010
};
// Size of struct 0x1A0 from _Common_NewRiid_
struct CDirectInputDevice8A : public IDirectInputDevice8A
{
//IDirectInputDeviceAVtbl* m_pVtbl; // 0x0000
CDirectInputDevice8A* m_pDerived; // 0x0008
IID* pGuid; // 0x0010
char pad0018[0x12C]; // 0x0018
volatile INT m_iReferenceCount; // 0x0148
DWORD m_dwThreadId; // 0x014C
CRITICAL_SECTION m_CriticalSection; // 0x0150
char pad0178[40]; // 0x0178
};
VALIDATE_OFFSET(CDirectInputDevice8A, m_pDerived, 0x0008);
VALIDATE_OFFSET(CDirectInputDevice8A, m_CriticalSection, 0x0150);
VALIDATE_SIZE(CDirectInputDevice8A, 0x01A0);
// TODO: finish dinput8.dll & gamerendereroverlay64.dll stuff
// Thanks valve and your gamerendereroverlay64.dll!HookedDirectInput8Create
#pragma region gamerendereroverlay64
// Size of struct 0x18 (24) bytes
struct CWrapDirectInput8
{
void* m_pVtbl; //0x0000
union {
IDirectInput8A* m_pDirectInputA; //0x0008
IDirectInput8W* m_pDirectInputW; //0x0008
};
bool m_bWideVersion; //0x0010
};
VALIDATE_SIZE(CWrapDirectInput8, 0x18);
// imaginary base class
struct CWrapDirectInputDevice8
{
void* m_pVtbl; //0x0000
union {
IDirectInputDevice8A* m_pDeviceA; //0x0008
IDirectInputDevice8W* m_pDeviceW; //0x0008
};
};
// Size of struct 0x138 (312) bytes
struct CWrapKeyboardDevice8 //: public IWrapMouseDevice8
{
void* m_pVtbl; //0x0000
union {
IDirectInputDevice8A* m_pDeviceA; //0x0008
IDirectInputDevice8W* m_pDeviceW; //0x0008
};
char pad0010[0x128]; //0x0010
};
VALIDATE_SIZE(CWrapKeyboardDevice8, 0x138);
// Size of struct 0x48 (72) bytes
struct CWrapMouseDevice8 //: public IWrapMouseDevice8
{
void* m_pVtbl; //0x0000
union {
IDirectInputDevice8A* m_pDeviceA; //0x0008
IDirectInputDevice8W* m_pDeviceW; //0x0008
};
char pad0010[56]; //0x0010
};
VALIDATE_SIZE(CWrapMouseDevice8, 0x48);
#pragma endregion gamerendereroverlay64
static void IDirectInputDevice_Lock(IDirectInputDevice8A* pDevice)
{
static HMODULE s_hDirectInput8 = GetModuleHandle(TEXT("dinput8.dll"));
HMODULE hOwnerModule = NULL;
if (s_hDirectInput8 != RtlPcToFileHeader(*(void**)pDevice, (PVOID*)&hOwnerModule))
{
//pDevice = CONTAINING_RECORD(pDevice, CWrapDirectInputDevice8, m_pDeviceA);
pDevice = ((CWrapDirectInputDevice8*)pDevice)->m_pDeviceA;
}
CDirectInputDevice8A* pImpl = CONTAINING_RECORD(pDevice, CDirectInputDevice8A, m_pDerived);
EnterCriticalSection(&pImpl->m_CriticalSection);
}
static void IDirectInputDevice_Unlock(IDirectInputDevice8A* pDevice)
{
static HMODULE s_hDirectInput8 = GetModuleHandle(TEXT("dinput8.dll"));
HMODULE hOwnerModule = NULL;
if (s_hDirectInput8 != RtlPcToFileHeader(*(void**)pDevice, (PVOID*)&hOwnerModule))
{
//pDevice = CONTAINING_RECORD(pDevice, CWrapDirectInputDevice8, m_pDeviceA);
pDevice = ((CWrapDirectInputDevice8*)pDevice)->m_pDeviceA;
}
CDirectInputDevice8A* pImpl = CONTAINING_RECORD(pDevice, CDirectInputDevice8A, m_pDerived);
LeaveCriticalSection(&pImpl->m_CriticalSection);
}
// https://stackoverflow.com/questions/46182845/field-of-view-aspect-ratio-view-matrix-from-projection-matrix-hmd-ost-calib
static float GetFovFromProjectionMatrix(void)
{
return 2.0f * atan(1.0f / g_pCamera->m_pInstance->m_ViewProjection[1][1]);
}
/*
Doesn't seem to be 100% accurate.
I tired adding the fov math into it but no success
all the examples use a different method than me.
Either that or CGameCamera::m_flFov isn't the fov value and I fucked up
https://guidedhacking.com/threads/world2screen-direct3d-and-opengl-worldtoscreen-functions.8044/
https://www.cs.toronto.edu/~jepson/csc420/notes/imageProjection.pdf
https://www.scratchapixel.com/lessons/3d-basic-rendering/computing-pixel-coordinates-of-3d-point/mathematics-computing-2d-coordinates-of-3d-points
https://www.cse.unr.edu/~bebis/CS791E/Notes/CameraParameters.pdf
https://github.com/VSES/SourceEngine2007/blob/master/se2007/engine/gl_rmain.cpp
Source Eng:
pScreen->x = 0.5f * ( pScreen->x + 1.0f ) * CurrentView().width + CurrentView().x;
pScreen->y = 0.5f * ( pScreen->y + 1.0f ) * CurrentView().height + CurrentView().y;
aka
pScreen->x = 0.5f * pScreen->x * CurrentView().width + 0.5f * CurrenView().width + CurrentView.x;
pScreen->y = 0.5f * pScreen->y * CurrentView().height + 0.5f * CurrenView().height + CurrentView.y;
*/
static bool WorldToScreen(const Vector3& vIn, Vector2& vOut)
{
Vector3 vTransform;
VMatrix& vMatrix = g_pCamera->m_pInstance->m_ViewProjection;
float w = vMatrix[0][3] * vIn[0] + vMatrix[1][3] * vIn[1] + vMatrix[2][3] * vIn[2] + vMatrix[3][3];
if (w < 0.001f)
return false;
// transform by viewmatrix
vMatrix.Transform(vIn, vTransform);
// multiply by inverse w (vTransform /= w)
vTransform *= 1.0f / w;
int width = g_pGraphicDevice->m_iScreenWidth;
int height = g_pGraphicDevice->m_iScreenHeight;
float x = width / 2.0f;
float y = height / 2.0f;
//float flFocalLengthY = 1.0f / tanf(g_pCamera->m_flFov * 0.5f);
//float flFocalLengthX = flFocalLengthX / (width / height);
//vOut.x = x * (1.f + (vTransform.x / tanf(g_pCamera->m_flFov * 0.5f) / vTransform.z));
//vOut.y = y * (1.f - (vTransform.y / tanf(g_pCamera->m_flFov * 0.5f) / vTransform.z));
//vOut.x = x + vTransform.x * flFocalLengthX * width / vTransform.z;
//vOut.y = y - vTransform.y * flFocalLengthY * height / vTransform.z;
vOut.x = x + 0.5f * vTransform.x * (float)width + 0.5f;
vOut.y = y - 0.5f * vTransform.y * (float)height + 0.5f;
return true;
}
static inline unsigned short EntityHandleToListIndex(const EntityHandle hEntity)
{
return (unsigned short)((hEntity & 0x00FFFF00) >> 8); // (unsigned short)(handle >> 8)
}
static inline EntityHandle GenerateEntityHandle(const CEntityList* pList, const unsigned short index)
{
return (index | (pList->m_uShift << 16)) << 8;
}
// NOTE: You should use these functions two get entity's by their handle from now on.
// It is the proper way to do it, since it doesn't do any filtering.
static CBehaviorAppBase* GetEntityByHandle(const CEntityList* pList, const EntityHandle hEntity)
{
int idx = EntityHandleToListIndex(hEntity);
// Check if the index is valid and the top 24-bits of the handles match
if (idx > pList->m_uItems || idx < 0 || (hEntity ^ pList->m_pItems[idx].first) & 0xFFFFFF00)
return NULL;
CEntityInfo* pEntityInfo = pList->m_pItems[idx].second;
if (!pEntityInfo || pEntityInfo->m_Flags & 3)
return NULL;
return pEntityInfo->m_pEntity;
}
// global func to get all the entity's from handle
// actual standalone function doesn't exist in the binary no more
// NOTE: You should use these functions two get entity's by their handle from now on.
// It is the proper way to do it, since it doesn't do any filtering.
static CBehaviorAppBase* GetEntityFromHandleGlobal(EntityHandle* phEntity)
{
CEntityInfo* pEntityInfo = GetEntityInfoFromHandle(phEntity);
return pEntityInfo ? pEntityInfo->m_pParent : NULL;
}
// Rebuilt from binary with added functionality
static BOOL ObjectIdToObjectName(char* szObjectName, size_t size, int objectId, ObjectIdConvert** ppConvert)
{
static char HexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static ObjectIdConvert Converts[] = { { 0x10000, "pl" }, { 0x20000, "em" }, { 0x30000, "wp" }, { 0x40000, "et" }, { 0x50000, "ef" }, { 0x60000, "es" },
{ 0x70000, "it" }, { 0x90000, "sc" }, { 0xA0000, "um" }, { 0xC0000, "bg" }, { 0xE0000, "bh" }, { 0xF0000, "ba" } };
unsigned int i = 0;
do
{
if (Converts[i].m_ObjectIdBase == (objectId & 0xFFFF0000)) // high word of the int
{
szObjectName[0] = Converts[i].m_szPrefix[0];
szObjectName[1] = Converts[i].m_szPrefix[1];
szObjectName[2] = HexChars[(objectId >> 12) & 0xF];
szObjectName[3] = HexChars[(objectId >> 8) & 0xF];
szObjectName[4] = HexChars[(objectId >> 4) & 0xF];
szObjectName[5] = HexChars[objectId & 0xF];
szObjectName[6] = 0; //null terminator
if (*ppConvert)
*ppConvert = &Converts[i];
return TRUE;
}
++i;
} while (i < ARRAYSIZE(Converts));
memset(szObjectName, 0, size);
if (objectId == -1)
strcpy_s(szObjectName, size, "eObjInvalid");
else
strcpy_s(szObjectName, size, (objectId != 0x700000) ? "Unknow" : "Null");
if (*ppConvert)
*ppConvert = NULL;
return FALSE;
}
static BOOL ObjectNameToObjectId(int* pObjectId, const char* szObjectName)
{
static ObjectIdConvert Converts[] = { { 0x10000, "pl" }, { 0x20000, "em" }, { 0x30000, "wp" }, { 0x40000, "et" }, { 0x50000, "ef" }, { 0x60000, "es" },
{ 0x70000, "it" }, { 0x90000, "sc" }, { 0xA0000, "um" }, { 0xC0000, "bg" }, { 0xE0000, "bh" }, { 0xF0000, "ba" } };
size_t i = 0;
BOOLEAN bFound = FALSE;
if (!szObjectName)
return FALSE;
for (; i < ARRAYSIZE(Converts); ++i)
{
if (Converts[i].m_szPrefix[0] == szObjectName[0] && Converts[i].m_szPrefix[1] == szObjectName[1])
{
bFound = TRUE;
break;
}
}
*pObjectId = (bFound) ? Converts[i].m_ObjectIdBase | ((szObjectName[2] - 0x30) << 12) | ((szObjectName[3] - 0x30) << 8) | ((szObjectName[4] - 0x30) << 4) | (szObjectName[5] - 0x30) : -1;
return TRUE;
}
// FIXME: This is disgusting
static DWORD DataFile_QueryFileIndex(DATHeader** ppBuffer, const char* szFileName)
{
const char* szName; // r12
LPBYTE* pHeaders; // r15
unsigned int v4; // esi
DATHeader* pHdr; // r8
DWORD dwOffset; // r9
DWORD dwFileCount; // ebp
DWORD dwNextNameOffset; // r14
const char* szCurrentFileName; // rdi
unsigned int i; // ebx
DWORD result; // eax
szName = szFileName;
pHeaders = (LPBYTE*)ppBuffer;
v4 = 0;
while (v4 < 2)
{
pHdr = (DATHeader*)*pHeaders;
if (*pHeaders)
{
dwOffset = pHdr->dwNameTableOffset;
if (dwOffset)
{
dwFileCount = pHdr->dwFileCount;
dwNextNameOffset = *(DWORD*)((LPBYTE)pHdr + dwOffset);
szCurrentFileName = (const char*)(pHdr + dwOffset + 4);
i = 0;
if (dwFileCount)
{
while (_stricmp(szName, szCurrentFileName))
{
++i;
szCurrentFileName += dwNextNameOffset;
if (i >= dwFileCount)
goto next_file;
}
result = i + (v4 << 28);
if (result != -1)
return result;
}
}
}
next_file:
++v4;
++pHeaders;
}
return 0xFFFFFFFF; //-1
}
static void DataFile_EnumContents(void* pBuffer, const char*** pppszFiles, DWORD* pdwFileCount)
{
if (!pBuffer)
return;
if (!pppszFiles)
return;
if (!pdwFileCount)
return;
DATHeader* pHdr = (DATHeader*)pBuffer;
*pdwFileCount = pHdr->dwFileCount;
DWORD dwNextNameOffset = *(DWORD*)((LPBYTE)pBuffer + pHdr->dwNameTableOffset);
*pppszFiles = (const char**)malloc(sizeof(const char*) * pHdr->dwFileCount);
if (*pppszFiles)
{
for (DWORD i = 0; i < pHdr->dwFileCount; ++i)
(*pppszFiles)[i] = (const char*)((LPBYTE)pBuffer + pHdr->dwNameTableOffset + 4 + i * dwNextNameOffset);
}
}
static void DataFile_FindFile(void* pBuffer, const char* szName, void** ppFile)
{
if (!ppFile)
return;
DWORD flags = DataFile_QueryFileIndex((DATHeader**)&pBuffer, szName);
if (flags == -1)
{
*ppFile = NULL;
}
else
{
DWORD dwFileIndex = flags & 0xFFFFFFF; // pretty sure this and flags >> 28 and equivalent
DATHeader* pHdr = (DATHeader*)((&pBuffer)[flags >> 28]); // get the highest 4 bytes (32 - 28) and use as the index
if (pHdr->dwFileCount > dwFileIndex)
{
PDWORD pFileTable = (PDWORD)((LPBYTE)pHdr + pHdr->dwFileTableOffset);
DWORD rva = pFileTable[dwFileIndex];
*ppFile = rva ? MakePtr(void*, pHdr, rva) : NULL;
}
else
{
*ppFile = NULL;
}
}
}
/// <summary>
/// Rebuilt from IDA Database
/// </summary>
/// <typeparam name="N">Size of szPath</typeparam>
/// <param name="szPath">File path of the game</param>
/// <returns></returns>
template<size_t N>
static bool GetSaveFolderPath(char (&szPath)[N])
{
if (SHGetSpecialFolderPathA(NULL, szPath, CSIDL_PERSONAL, FALSE))
{
sprintf_s(szPath, "%s\\%s\\%s\\", szPath, "My Games", "NieR_Automata");
return true;
}
return false;
}
/// <summary>
/// Rebuilt from IDA Database
/// </summary>
/// <typeparam name="N"></typeparam>
/// <param name="pSavedata"></param>
/// <param name="szPath"></param>
/// <returns></returns>
template<size_t N = MAX_PATH>
static bool GetGameDataPath(CSaveDataDevice* pSavedata, char(&szPath)[N])
{
if (GetSaveFolderPath(szPath))
{
switch (pSavedata->m_nSlot)
{
case CSaveDataDevice::SLOT_SAVE_SYSTEMDATA:
//strcat_s(szPath, "SystemData.dat");
sprintf_s(szPath, "%sSystemData.dat", szPath);
break;
case CSaveDataDevice::SLOT_SAVE_GAMEDATA:
//strcat_s(szPath, "SystemData.dat");
sprintf_s(szPath, "%sGameData.dat", szPath);
break;
default:
sprintf_s(szPath, "%sSlotData_%d.dat", szPath, pSavedata->m_nSlot);
break;
}
return true;
}
return false;
}
// Rebuilt from the binary for the reason that it was inlined which
// will complicate things in the hook otherwise
static void CSaveDataDevice_DeleteSaveData(CSaveDataDevice* pSavedata)
{
char szFilename[MAX_PATH];
switch (pSavedata->m_Status)
{
case 0:
// sub_140282BD0
if (GetGameDataPath(pSavedata, szFilename))
{
if (DeleteFileA(szFilename))
{
pSavedata->m_pSaveSlots[pSavedata->m_nSlot].m_uAccountId = 0;
pSavedata->m_pSaveSlots[pSavedata->m_nSlot].m_bInUse = FALSE;
if (pSavedata->m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(pSavedata->m_hFile);
pSavedata->m_hFile = INVALID_HANDLE_VALUE;
}
*(&pSavedata->m_nMaxSlot + 1) = 0;
pSavedata->m_uFlags64 = 0i64;
}
else
{
pSavedata->m_Status = CSaveDataDevice::STATUS_SAVE_DATA_READ_SLOTS;
}
}
break;
case 1:
if (pSavedata->m_hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(pSavedata->m_hFile);
pSavedata->m_hFile = INVALID_HANDLE_VALUE;
}
*(&pSavedata->m_nMaxSlot + 1) = 3;
pSavedata->m_uFlags64 = 0i64;
break;
case 2:
if (pSavedata->qwUnk0xC8)
{
if (!*(DWORD*)(pSavedata->qwUnk0xC8 + 8))
break;
*(DWORD*)(pSavedata->qwUnk0xC8 + 12) = 1;
}
pSavedata->qwUnk0xC8 = 0i64;
break;
default:
pSavedata->m_Status = CSaveDataDevice::STATUS_SAVE_DATA_READ_SLOTS;
break;
}
}
static CMeshPart* GetModelMesh(CModelWork* pWork, const char* szMesh)
{
for (int32_t i = 0; i < pWork->m_nMeshes; ++i)
if (!strcmp(pWork->m_pMeshes[i].m_szMeshName, szMesh))
return &pWork->m_pMeshes[i];
return NULL;
}
static int32_t GetModelMeshIndex(const CModelWork* pWork, const char* szMesh)
{
for (int32_t i = 0; i < pWork->m_nMeshes; ++i)
if (!strcmp(pWork->m_pMeshes[i].m_szMeshName, szMesh))
return i;
return -1;
}
// Rebuilt from binary
static int16_t GetBoneIndex(const CModelData* pModelData, int16_t Id)
{
int16_t* pTable;
int16_t iBoneIndex, t1, t2;
pTable = pModelData->m_pBoneIndexTranslationTable2;
if (pTable)
{
t1 = pTable[(Id >> 8) & 0xF]; // id / 256 clamped to 0-15
if (t1 != -1)
{
t2 = pTable[t1 + ((Id >> 4) & 0xF)]; // id
if (t2 != -1)
{
iBoneIndex = pTable[t2 + (Id & 0xF)];
if (iBoneIndex != 0xFFF) // 4095
return iBoneIndex;
}
}
}
return -1;
}
static int16_t GetBoneId(int16_t index)
{
}
static void SwapTexture(uint32_t srcid, CTexture* pReplace)
{
CTextureResource* pRes = TextureResourceManager_FindResource(srcid);
if (pRes)
pRes->m_pTexture = pReplace;
}
static HRESULT CreateTextureEx(const wchar_t* szFile, CTextureDescription& Desc)
{
IWICImagingFactory* pFactory;
IWICFormatConverter* pConverter;
IWICBitmapDecoder* pDecoder;
IWICBitmapFrameDecode* pFrame;
WICPixelFormatGUID Format;
uint32_t w, h, uFrames, uStride, uSize, * rgba;
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (void**)&pFactory);
if (FAILED(hr))
return hr;
hr = pFactory->CreateDecoderFromFilename(szFile, NULL, GENERIC_READ, WICDecodeMetadataCacheOnDemand, &pDecoder);
if (FAILED(hr))
return hr;
hr = pDecoder->GetFrameCount(&uFrames);
if (FAILED(hr))
return hr;
hr = pDecoder->GetFrame(0, &pFrame);
if (FAILED(hr))
return hr;
hr = pFrame->GetPixelFormat(&Format);
if (FAILED(hr))
return hr;
hr = pFrame->GetSize(&w, &h);
uStride = w * sizeof(uint32_t);
uSize = uStride * h;
if (!IsEqualGUID(Format, GUID_WICPixelFormat32bppBGRA))
{
hr = pFactory->CreateFormatConverter(&pConverter);
hr = pConverter->Initialize(pFrame, GUID_WICPixelFormat32bppBGRA,
WICBitmapDitherTypeNone, // Specified dither pattern
NULL, // Specify a particular palette
0.f, // Alpha threshold
WICBitmapPaletteTypeCustom); // Palette translation type
hr = pConverter->CopyPixels(NULL, uStride, uSize, (uint8_t*)rgba);
pConverter->Release();
}
else
hr = pFrame->CopyPixels(NULL, uStride, uSize, (uint8_t*)rgba);
return hr;
}
// FIXME: This is for sure broken on new version. Adapt to use the game's allocation routines to avoid crashes on freeing resources
static CTargetTexture* CreateTextureR(const char* szFile, CTextureDescription& Desc)
{
CTargetTexture* pTexture = NULL;
ZeroMemory(&Desc, sizeof(CTextureDescription));
HANDLE hFile = CreateFileA(szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD dwFileSize = GetFileSize(hFile, NULL);
HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, dwFileSize, NULL);
if (hMapping)
{
TextureFile* pFile = (TextureFile*)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, dwFileSize);
Desc.m_pDDS = pFile;
Desc.m_uTextureSize = dwFileSize;
Desc.dword18 = 2;
pTexture = (CTargetTexture*)malloc(sizeof(CTargetTexture)); //AllocHeapMemoryFn or ReserveMemory
if (pTexture)
{
ZeroMemory(pTexture, sizeof(CTargetTexture));
// old sig: 33 D2 48 8D 05 ? ? ? ? 48 89 51 58
// old: 0x140E9FA38 | base + 0xE9FA38
// new sig: 48 89 58 50 48 8D 05 ? ? ? ?
// new: 0x140DB1DE8 | base + 0xDB1DE8
pTexture->m_vtbl = (void*)FindPatternPtr(NULL, "48 89 58 50 48 8D 05 ? ? ? ?", 7);
// old: 0x140934FE0
// old sig: 48 89 5C 24 ? 48 89 6C 24 ? 48 89 74 24 ? 57 48 83 EC ? 48 8B 02 48 8B CA 49 8B F0 48 8B FA FF 50 08 48 83 3D 95 ? ? ? ?
// new sig: 48 89 5C 24 ? 48 89 74 24 ? 57 48 83 EC ? 48 8B 44 24 ? 33 F6