-
Notifications
You must be signed in to change notification settings - Fork 256
/
EmuD3D8.cpp
10430 lines (8001 loc) · 294 KB
/
EmuD3D8.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 is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// ******************************************************************
// *
// * .,-::::: .,:: .::::::::. .,:: .:
// * ,;;;'````' `;;;, .,;; ;;;'';;' `;;;, .,;;
// * [[[ '[[,,[[' [[[__[[\. '[[,,[['
// * $$$ Y$$$P $$""""Y$$ Y$$$P
// * `88bo,__,o, oP"``"Yo, _88o,,od8P oP"``"Yo,
// * "YUMMMMMP",m" "Mm,""YUMMMP" ,m" "Mm,
// *
// * Cxbx->Win32->CxbxKrnl->EmuD3D8.cpp
// *
// * This file is part of the Cxbx project.
// *
// * Cxbx and Cxbe are free software; you can redistribute them
// * and/or modify them under the terms of the GNU General Public
// * License as published by the Free Software Foundation; either
// * version 2 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 recieved a copy of the GNU General Public License
// * along with this program; see the file COPYING.
// * If not, write to the Free Software Foundation, Inc.,
// * 59 Temple Place - Suite 330, Bostom, MA 02111-1307, USA.
// *
// * (c) 2002-2003 Aaron Robinson <caustik@caustik.com>
// *
// * All rights reserved
// *
// ******************************************************************
#define _CXBXKRNL_INTERNAL
#define _XBOXKRNL_DEFEXTRN_
// prevent name collisions
namespace xboxkrnl
{
#include <xboxkrnl/xboxkrnl.h>
};
#include "CxbxUtil.h"
#include "CxbxVersion.h"
#include "CxbxKrnl.h"
#include "Emu.h"
#include "EmuFS.h"
#include "EmuShared.h"
#include "DbgConsole.h"
#include "ResourceTracker.h"
#include "EmuAlloc.h"
#include "MemoryManager.h"
#include "EmuXTL.h"
#include "libyuv_extract.h" // for YUY2ToARGB
#include <assert.h>
#include <process.h>
#include <clocale>
// Global(s)
HWND g_hEmuWindow = NULL; // rendering window
XTL::LPDIRECT3DDEVICE8 g_pD3DDevice8 = NULL; // Direct3D8 Device
XTL::LPDIRECTDRAWSURFACE7 g_pDDSPrimary = NULL; // DirectDraw7 Primary Surface
XTL::LPDIRECTDRAWSURFACE7 g_pDDSOverlay7 = NULL; // DirectDraw7 Overlay Surface
XTL::LPDIRECTDRAWCLIPPER g_pDDClipper = NULL; // DirectDraw7 Clipper
DWORD g_CurrentVertexShader = 0;
DWORD g_dwCurrentPixelShader = 0;
XTL::PIXEL_SHADER *g_CurrentPixelShader = NULL;
BOOL g_bFakePixelShaderLoaded = FALSE;
BOOL g_bIsFauxFullscreen = FALSE;
BOOL g_bHackUpdateSoftwareOverlay = FALSE;
// Static Function(s)
static BOOL WINAPI EmuEnumDisplayDevices(GUID FAR *lpGUID, LPSTR lpDriverDescription, LPSTR lpDriverName, LPVOID lpContext, HMONITOR hm);
static DWORD WINAPI EmuRenderWindow(LPVOID);
static DWORD WINAPI EmuCreateDeviceProxy(LPVOID);
static LRESULT WINAPI EmuMsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
static DWORD WINAPI EmuUpdateTickCount(LPVOID);
static inline void EmuVerifyResourceIsRegistered(XTL::X_D3DResource *pResource);
static void EmuAdjustPower2(UINT *dwWidth, UINT *dwHeight);
// Static Variable(s)
static HMONITOR g_hMonitor = NULL; // Handle to DirectDraw monitor
static BOOL g_bSupportsYUY2 = FALSE;// Does device support YUY2 overlays?
static XTL::LPDIRECTDRAW7 g_pDD7 = NULL; // DirectDraw7
static DWORD g_dwOverlayW = 640; // Cached Overlay Width
static DWORD g_dwOverlayH = 480; // Cached Overlay Height
static DWORD g_dwOverlayP = 640; // Cached Overlay Pitch
static Xbe::Header *g_XbeHeader = NULL; // XbeHeader
static uint32 g_XbeHeaderSize = 0; // XbeHeaderSize
static HBRUSH g_hBgBrush = NULL; // Background Brush
static volatile bool g_bRenderWindowActive = false;
static XBVideo g_XBVideo;
static XTL::D3DVBLANKCALLBACK g_pVBCallback = NULL; // Vertical-Blank callback routine
static XTL::D3DSWAPCALLBACK g_pSwapCallback = NULL; // Swap/Present callback routine
static XTL::D3DCALLBACK g_pCallback = NULL; // D3DDevice::InsertCallback routine
static XTL::X_D3DCALLBACKTYPE g_CallbackType; // Callback type
static DWORD g_CallbackParam; // Callback param
static BOOL g_bHasDepthStencil = FALSE; // Does device have a Depth/Stencil Buffer?
//static DWORD g_dwPrimPerFrame = 0; // Number of primitives within one frame
// D3D based variables
static GUID g_ddguid; // DirectDraw driver GUID
static XTL::LPDIRECT3D8 g_pD3D8 = NULL; // Direct3D8
static XTL::D3DCAPS8 g_D3DCaps; // Direct3D8 Caps
// wireframe toggle
static int g_iWireframe = 0;
// build version
extern uint32 g_BuildVersion;
// resource caching for _Register
static XTL::X_D3DResource pCache[16] = {0};
// current active index buffer
static XTL::X_D3DIndexBuffer *g_pIndexBuffer = NULL; // current active index buffer
static DWORD g_dwBaseVertexIndex = 0;// current active index buffer base index
// current active vertex stream
static XTL::X_D3DVertexBuffer *g_pVertexBuffer = NULL; // current active vertex buffer
static XTL::IDirect3DVertexBuffer8 *g_pDummyBuffer = NULL; // Dummy buffer, used to set unused stream sources with
static DWORD g_dwLastSetStream = 0; // The last stream set by D3DDevice::SetStreamSource
// current vertical blank information
static XTL::D3DVBLANKDATA g_VBData = {0};
static DWORD g_VBLastSwap = 0;
// current swap information
static XTL::D3DSWAPDATA g_SwapData = {0};
static DWORD g_SwapLast = 0;
// cached Direct3D state variable(s)
static XTL::X_D3DSurface *g_pCachedRenderTarget = NULL;
static XTL::X_D3DSurface *g_pCachedDepthStencil = NULL;
static XTL::X_D3DSurface *g_pCachedYuvSurface = NULL;
static BOOL g_fYuvEnabled = FALSE;
static DWORD g_dwVertexShaderUsage = 0;
static DWORD g_VertexShaderSlots[136];
// cached palette pointer
static PVOID pCurrentPalette = nullptr;
// cached palette size
static DWORD dwCurrentPaletteSize = -1;
static XTL::X_VERTEXSHADERCONSTANTMODE g_VertexShaderConstantMode = X_VSCM_192;
// cached Direct3D tiles
XTL::X_D3DTILE XTL::EmuD3DTileCache[0x08] = {0};
// cached active texture
XTL::X_D3DResource *XTL::EmuD3DActiveTexture[4] = {0,0,0,0};
// information passed to the create device proxy thread
struct EmuD3D8CreateDeviceProxyData
{
XTL::UINT Adapter;
XTL::D3DDEVTYPE DeviceType;
HWND hFocusWindow;
XTL::DWORD BehaviorFlags;
XTL::X_D3DPRESENT_PARAMETERS *pPresentationParameters;
XTL::IDirect3DDevice8 **ppReturnedDeviceInterface;
volatile bool bReady;
union
{
volatile HRESULT hRet;
volatile bool bCreate; // false : release
};
}
g_EmuCDPD = {0};
VOID XTL::CxbxInitWindow(Xbe::Header *XbeHeader, uint32 XbeHeaderSize)
{
g_EmuShared->GetXBVideo(&g_XBVideo);
if(g_XBVideo.GetFullscreen())
CxbxKrnl_hEmuParent = NULL;
// cache XbeHeader and size of XbeHeader
g_XbeHeader = XbeHeader;
g_XbeHeaderSize = XbeHeaderSize;
// create timing thread
{
DWORD dwThreadId;
HANDLE hThread = CreateThread(NULL, NULL, EmuUpdateTickCount, NULL, NULL, &dwThreadId);
// Ported from Dxbx :
// If possible, assign this thread to another core than the one that runs Xbox1 code :
SetThreadAffinityMask(hThread, g_CPUOthers);
// We set the priority of this thread a bit higher, to assure reliable timing :
SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);
// we must duplicate this handle in order to retain Suspend/Resume thread rights from a remote thread
{
HANDLE hDupHandle = NULL;
DuplicateHandle(g_CurrentProcessHandle, hThread, g_CurrentProcessHandle, &hDupHandle, 0, FALSE, DUPLICATE_SAME_ACCESS);
CxbxKrnlRegisterThread(hDupHandle);
}
}
/* TODO : Port this Dxbx code :
// create vblank handling thread
{
dwThreadId = 0;
{hThread :=} CreateThread(NULL, 0, EmuThreadHandleVBlank, NULL, 0, &dwThreadId);
// Make sure VBlank callbacks run on the same core as the one that runs Xbox1 code :
SetThreadAffinityMask(dwThreadId, g_CPUXbox);
}
*/
// create window message processing thread
{
DWORD dwThreadId;
g_bRenderWindowActive = false;
HANDLE hRenderWindowThread = CreateThread(NULL, NULL, EmuRenderWindow, NULL, NULL, &dwThreadId);
if (hRenderWindowThread == NULL) {
char szBuffer[1024] = { 0 };
sprintf(szBuffer, "Creating EmuRenderWindowThread Failed: %08X", GetLastError());
MessageBoxA(NULL, szBuffer, "CreateThread Failed", 0);
EmuShared::Cleanup();
ExitProcess(0);
}
// Ported from Dxbx :
// If possible, assign this thread to another core than the one that runs Xbox1 code :
SetThreadAffinityMask(hRenderWindowThread, g_CPUOthers);
while(!g_bRenderWindowActive)
Sleep(10); // Dxbx: Should we use SwitchToThread() or YieldProcessor() ?
Sleep(50);
}
SetFocus(g_hEmuWindow);
}
XTL::IDirect3DResource8 *GetHostResource(XTL::X_D3DResource *pThis)
{
if ((pThis->Data & X_D3DRESOURCE_DATA_FLAG_SPECIAL) == X_D3DRESOURCE_DATA_FLAG_SPECIAL) // Was X_D3DRESOURCE_DATA_YUV_SURFACE
return nullptr;
if (pThis->Lock == X_D3DRESOURCE_LOCK_PALETTE)
return nullptr;
if (pThis->EmuResource8 == nullptr)
{
__asm int 3;
//EmuWarning("EmuResource is not a valid pointer!");
}
return pThis->EmuResource8;
}
int GetD3DResourceRefCount(XTL::IDirect3DResource8 *EmuResource)
{
if (EmuResource != nullptr)
{
// Get actual reference count by increasing it using AddRef,
// and relying on the return value of Release (which is
// probably more reliable than AddRef)
EmuResource->AddRef();
return EmuResource->Release();
}
return 0;
}
XTL::X_D3DSurface *EmuNewD3DSurface()
{
XTL::X_D3DSurface *result = (XTL::X_D3DSurface *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DSurface));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_SURFACE | 1; // Set refcount to 1
return result;
}
XTL::X_D3DTexture *EmuNewD3DTexture()
{
XTL::X_D3DTexture *result = (XTL::X_D3DTexture *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DTexture));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_TEXTURE | 1; // Set refcount to 1
return result;
}
XTL::X_D3DVolumeTexture *EmuNewD3DVolumeTexture()
{
XTL::X_D3DVolumeTexture *result = (XTL::X_D3DVolumeTexture *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DVolumeTexture));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_TEXTURE | 1; // Set refcount to 1
return result;
}
XTL::X_D3DCubeTexture *EmuNewD3DCubeTexture()
{
XTL::X_D3DCubeTexture *result = (XTL::X_D3DCubeTexture *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DCubeTexture));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_TEXTURE | 1; // Set refcount to 1
return result;
}
XTL::X_D3DIndexBuffer *EmuNewD3DIndexBuffer()
{
XTL::X_D3DIndexBuffer *result = (XTL::X_D3DIndexBuffer *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DIndexBuffer));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_INDEXBUFFER | 1; // Set refcount to 1
return result;
}
XTL::X_D3DVertexBuffer *EmuNewD3DVertexBuffer()
{
XTL::X_D3DVertexBuffer *result = (XTL::X_D3DVertexBuffer *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DVertexBuffer));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_VERTEXBUFFER | 1; // Set refcount to 1
return result;
}
XTL::X_D3DPalette *EmuNewD3DPalette()
{
XTL::X_D3DPalette *result = (XTL::X_D3DPalette *)g_MemoryManager.AllocateZeroed(1, sizeof(XTL::X_D3DPalette));
result->Common = X_D3DCOMMON_D3DCREATED | X_D3DCOMMON_TYPE_PALETTE | 1; // Set refcount to 1
return result;
}
VOID CxbxSetPixelContainerHeader
(
XTL::X_D3DPixelContainer* pPixelContainer,
DWORD Common,
UINT Width,
UINT Height,
UINT Levels,
XTL::X_D3DFORMAT Format,
UINT Dimensions,
UINT Pitch
)
{
// Set X_D3DResource field(s) :
pPixelContainer->Common = Common;
// DON'T SET pPixelContainer->Data
// DON'T SET pPixelContainer->Lock
// Are Width and Height both a power of two?
DWORD l2w; _BitScanReverse(&l2w, Width); // MSVC intrinsic; GCC has __builtin_clz
DWORD l2h; _BitScanReverse(&l2h, Height);
if (((1 << l2w) == Width) && ((1 << l2h) == Height)) {
Width = Height = Pitch = 1; // When setting Format, clear Size field
}
else {
l2w = l2h = 0; // When setting Size, clear D3DFORMAT_USIZE and VSIZE
}
// TODO : Must this be set using Usage / Pool / something else?
const int Depth = 1;
// Set X_D3DPixelContainer field(s) :
pPixelContainer->Format = 0
| ((Dimensions << X_D3DFORMAT_DIMENSION_SHIFT) & X_D3DFORMAT_DIMENSION_MASK)
| (((DWORD)Format << X_D3DFORMAT_FORMAT_SHIFT) & X_D3DFORMAT_FORMAT_MASK)
| ((Levels << X_D3DFORMAT_MIPMAP_SHIFT) & X_D3DFORMAT_MIPMAP_MASK)
| ((l2w << X_D3DFORMAT_USIZE_SHIFT) & X_D3DFORMAT_USIZE_MASK)
| ((l2h << X_D3DFORMAT_VSIZE_SHIFT) & X_D3DFORMAT_VSIZE_MASK)
| ((Depth << X_D3DFORMAT_PSIZE_SHIFT) & X_D3DFORMAT_PSIZE_MASK)
;
pPixelContainer->Size = 0
| (((Width - 1) /*X_D3DSIZE_WIDTH_SHIFT*/) & X_D3DSIZE_WIDTH_MASK)
| (((Height - 1) << X_D3DSIZE_HEIGHT_SHIFT) & X_D3DSIZE_HEIGHT_MASK)
| (((Pitch - 1) << X_D3DSIZE_PITCH_SHIFT) & X_D3DSIZE_PITCH_MASK)
;
}
VOID CxbxReleaseBackBufferLock()
{
XTL::IDirect3DSurface8 *pBackBuffer = nullptr;
if (D3D_OK == g_pD3DDevice8->GetBackBuffer(0, XTL::D3DBACKBUFFER_TYPE_MONO, &pBackBuffer))
{
assert(pBackBuffer != nullptr);
pBackBuffer->UnlockRect();
pBackBuffer->Release();
}
}
// Direct3D initialization (called before emulation begins)
VOID XTL::EmuD3DInit()
{
// create the create device proxy thread
{
DWORD dwThreadId;
CreateThread(NULL, NULL, EmuCreateDeviceProxy, NULL, NULL, &dwThreadId);
// Ported from Dxbx :
// If possible, assign this thread to another core than the one that runs Xbox1 code :
SetThreadAffinityMask(&dwThreadId, g_CPUOthers);
}
// create Direct3D8 and retrieve caps
{
using namespace XTL;
// xbox Direct3DCreate8 returns "1" always, so we need our own ptr
g_pD3D8 = Direct3DCreate8(D3D_SDK_VERSION);
if(g_pD3D8 == NULL)
CxbxKrnlCleanup("Could not initialize Direct3D8!");
D3DDEVTYPE DevType = (g_XBVideo.GetDirect3DDevice() == 0) ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF;
g_pD3D8->GetDeviceCaps(g_XBVideo.GetDisplayAdapter(), DevType, &g_D3DCaps);
}
// create default device
{
XTL::X_D3DPRESENT_PARAMETERS PresParam;
ZeroMemory(&PresParam, sizeof(PresParam));
PresParam.BackBufferWidth = 640;
PresParam.BackBufferHeight = 480;
PresParam.BackBufferFormat = X_D3DFMT_A8R8G8B8;
PresParam.BackBufferCount = 1;
PresParam.EnableAutoDepthStencil = TRUE;
PresParam.AutoDepthStencilFormat = X_D3DFMT_D24S8;
PresParam.SwapEffect = XTL::D3DSWAPEFFECT_DISCARD;
XTL::EMUPATCH(Direct3D_CreateDevice)(0, XTL::D3DDEVTYPE_HAL, 0, D3DCREATE_HARDWARE_VERTEXPROCESSING, &PresParam, &g_pD3DDevice8);
}
}
// cleanup Direct3D
VOID XTL::EmuD3DCleanup()
{
XTL::EmuDInputCleanup();
return;
}
// enumeration procedure for locating display device GUIDs
static BOOL WINAPI EmuEnumDisplayDevices(GUID FAR *lpGUID, LPSTR lpDriverDescription, LPSTR lpDriverName, LPVOID lpContext, HMONITOR hm)
{
static DWORD dwEnumCount = 0;
if(dwEnumCount++ == g_XBVideo.GetDisplayAdapter()+1)
{
g_hMonitor = hm;
dwEnumCount = 0;
if(lpGUID != 0)
{
memcpy(&g_ddguid, lpGUID, sizeof(GUID));
}
else
{
memset(&g_ddguid, 0, sizeof(GUID));
}
return FALSE;
}
return TRUE;
}
// window message processing thread
static DWORD WINAPI EmuRenderWindow(LPVOID lpVoid)
{
char AsciiTitle[MAX_PATH];
// register window class
{
LOGBRUSH logBrush = {BS_SOLID, RGB(0,0,0)};
g_hBgBrush = CreateBrushIndirect(&logBrush);
WNDCLASSEX wc =
{
sizeof(WNDCLASSEX),
CS_CLASSDC,
EmuMsgProc,
0, 0, GetModuleHandle(NULL),
0, // TODO : LoadIcon(hmodule, ?)
LoadCursor(NULL, IDC_ARROW),
(HBRUSH)(g_hBgBrush), NULL,
"CxbxRender",
NULL
};
RegisterClassEx(&wc);
}
// retrieve Xbe title (if possible)
{
char tAsciiTitle[40] = "Unknown";
uint32 CertAddr = g_XbeHeader->dwCertificateAddr - g_XbeHeader->dwBaseAddr;
#define CertTitleNameLength 40
// Does the title fall entirely inside the read XbeHeader?
if(CertAddr + offsetof(Xbe::Certificate, wszTitleName) + CertTitleNameLength < g_XbeHeaderSize)
{
Xbe::Certificate *XbeCert = (Xbe::Certificate*)((uint32)g_XbeHeader + CertAddr);
setlocale( LC_ALL, "English" );
wcstombs(tAsciiTitle, XbeCert->wszTitleName, CertTitleNameLength);
}
sprintf(AsciiTitle, "Cxbx-Reloaded %s : Emulating %s", _CXBX_VERSION, tAsciiTitle);
}
// create the window
{
DWORD dwStyle = (g_XBVideo.GetFullscreen() || (CxbxKrnl_hEmuParent == 0))? WS_OVERLAPPEDWINDOW : WS_CHILD;
int nTitleHeight = GetSystemMetrics(SM_CYCAPTION);
int nBorderWidth = GetSystemMetrics(SM_CXSIZEFRAME);
int nBorderHeight = GetSystemMetrics(SM_CYSIZEFRAME);
int x = 100, y = 100, nWidth = 640, nHeight = 480;
nWidth += nBorderWidth*2;
nHeight += nBorderHeight*2 + nTitleHeight;
sscanf(g_XBVideo.GetVideoResolution(), "%d x %d", &nWidth, &nHeight);
if(g_XBVideo.GetFullscreen())
{
x = y = nWidth = nHeight = 0;
dwStyle = WS_POPUP;
}
HWND hwndParent = GetDesktopWindow();
if(!g_XBVideo.GetFullscreen())
{
hwndParent = CxbxKrnl_hEmuParent;
}
g_hEmuWindow = CreateWindow
(
"CxbxRender", AsciiTitle,
dwStyle, x, y, nWidth, nHeight,
hwndParent, NULL, GetModuleHandle(NULL), NULL
);
}
ShowWindow(g_hEmuWindow, ((CxbxKrnl_hEmuParent == 0) || g_XBVideo.GetFullscreen()) ? SW_SHOWDEFAULT : SW_SHOWMAXIMIZED);
UpdateWindow(g_hEmuWindow);
if(!g_XBVideo.GetFullscreen() && (CxbxKrnl_hEmuParent != NULL))
{
SetFocus(CxbxKrnl_hEmuParent);
}
// initialize direct input
if(!XTL::EmuDInputInit())
CxbxKrnlCleanup("Could not initialize DirectInput!");
DbgPrintf("EmuD3D8: Message-Pump thread is running.\n");
SetFocus(g_hEmuWindow);
DbgConsole *dbgConsole = new DbgConsole();
// message processing loop
{
MSG msg;
ZeroMemory(&msg, sizeof(msg));
bool lPrintfOn = g_bPrintfOn;
g_bRenderWindowActive = true;
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Sleep(10);
// if we've just switched back to display off, clear buffer & display prompt
if(!g_bPrintfOn && lPrintfOn)
{
dbgConsole->Reset();
}
lPrintfOn = g_bPrintfOn;
dbgConsole->Process();
}
}
g_bRenderWindowActive = false;
delete dbgConsole;
CxbxKrnlCleanup(NULL);
}
return 0;
}
// simple helper function
void ToggleFauxFullscreen(HWND hWnd)
{
if(g_XBVideo.GetFullscreen())
return;
static LONG lRestore = 0, lRestoreEx = 0;
static RECT lRect = {0};
if(!g_bIsFauxFullscreen)
{
if(CxbxKrnl_hEmuParent != NULL)
{
SetParent(hWnd, NULL);
}
else
{
lRestore = GetWindowLong(hWnd, GWL_STYLE);
lRestoreEx = GetWindowLong(hWnd, GWL_EXSTYLE);
GetWindowRect(hWnd, &lRect);
}
SetWindowLong(hWnd, GWL_STYLE, WS_POPUP);
ShowWindow(hWnd, SW_MAXIMIZE);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
else
{
if(CxbxKrnl_hEmuParent != NULL)
{
SetParent(hWnd, CxbxKrnl_hEmuParent);
SetWindowLong(hWnd, GWL_STYLE, WS_CHILD);
ShowWindow(hWnd, SW_MAXIMIZE);
SetFocus(CxbxKrnl_hEmuParent);
}
else
{
SetWindowLong(hWnd, GWL_STYLE, lRestore);
SetWindowLong(hWnd, GWL_EXSTYLE, lRestoreEx);
ShowWindow(hWnd, SW_RESTORE);
SetWindowPos(hWnd, HWND_NOTOPMOST, lRect.left, lRect.top, lRect.right - lRect.left, lRect.bottom - lRect.top, 0);
SetFocus(hWnd);
}
}
g_bIsFauxFullscreen = !g_bIsFauxFullscreen;
}
// rendering window message procedure
static LRESULT WINAPI EmuMsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static bool bAutoPaused = false;
switch(msg)
{
case WM_DESTROY:
{
DeleteObject(g_hBgBrush);
PostQuitMessage(0);
return D3D_OK; // = 0
}
break;
case WM_SYSKEYDOWN:
{
if(wParam == VK_RETURN)
{
ToggleFauxFullscreen(hWnd);
}
else if(wParam == VK_F4)
{
PostMessage(hWnd, WM_CLOSE, 0, 0);
}
}
break;
case WM_KEYDOWN:
{
/*! disable fullscreen if we are set to faux mode, and faux fullscreen is active */
if(wParam == VK_ESCAPE)
{
if(g_XBVideo.GetFullscreen())
{
SendMessage(hWnd, WM_CLOSE, 0, 0);
}
else if(g_bIsFauxFullscreen)
{
ToggleFauxFullscreen(hWnd);
}
}
else if(wParam == VK_F8)
{
g_bPrintfOn = !g_bPrintfOn;
}
else if(wParam == VK_F9)
{
XTL::g_bBrkPush = TRUE;
}
else if(wParam == VK_F10)
{
ToggleFauxFullscreen(hWnd);
}
else if(wParam == VK_F11)
{
if(g_iWireframe++ == 2)
g_iWireframe = 0;
}
else if(wParam == VK_F12)
{
XTL::g_bStepPush = !XTL::g_bStepPush;
}
}
break;
case WM_SIZE:
{
switch(wParam)
{
case SIZE_RESTORED:
case SIZE_MAXIMIZED:
{
if(bAutoPaused)
{
bAutoPaused = false;
CxbxKrnlResume();
}
}
break;
case SIZE_MINIMIZED:
{
if(g_XBVideo.GetFullscreen())
CxbxKrnlCleanup(NULL);
if(!g_bEmuSuspended)
{
bAutoPaused = true;
CxbxKrnlSuspend();
}
}
break;
}
}
break;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_SETFOCUS:
{
if(CxbxKrnl_hEmuParent != NULL)
{
SetFocus(CxbxKrnl_hEmuParent);
}
}
break;
case WM_SETCURSOR:
{
if(g_XBVideo.GetFullscreen() || g_bIsFauxFullscreen)
{
SetCursor(NULL);
return D3D_OK; // = 0
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return D3D_OK; // = 0
}
// timing thread procedure
static DWORD WINAPI EmuUpdateTickCount(LPVOID)
{
// since callbacks come from here
EmuGenerateFS(CxbxKrnl_TLS, CxbxKrnl_TLSData);
DbgPrintf("EmuD3D8: Timing thread is running.\n");
timeBeginPeriod(0);
// current vertical blank count
int curvb = 0;
while(true)
{
xboxkrnl::KeTickCount = timeGetTime();
Sleep(1);
//
// Poll input
//
{
int v;
for(v=0;v<XINPUT_SETSTATE_SLOTS;v++)
{
HANDLE hDevice = g_pXInputSetStateStatus[v].hDevice;
if(hDevice == 0)
continue;
DWORD dwLatency = g_pXInputSetStateStatus[v].dwLatency++;
if(dwLatency < XINPUT_SETSTATE_LATENCY)
continue;
g_pXInputSetStateStatus[v].dwLatency = 0;
XTL::PXINPUT_FEEDBACK pFeedback = (XTL::PXINPUT_FEEDBACK)g_pXInputSetStateStatus[v].pFeedback;
if(pFeedback == 0)
continue;
//
// Only update slot if it has not already been updated
//
if(pFeedback->Header.dwStatus != ERROR_SUCCESS)
{
if(pFeedback->Header.hEvent != 0)
{
SetEvent(pFeedback->Header.hEvent);
}
pFeedback->Header.dwStatus = ERROR_SUCCESS;
}
}
}
// trigger vblank callback
{
g_VBData.VBlank++;
// TODO: Fixme. This may not be right...
g_SwapData.SwapVBlank = 1;
if(g_pVBCallback != NULL)
{
g_pVBCallback(&g_VBData);
}
g_VBData.Swap = 0;
// TODO: This can't be accurate...
g_SwapData.TimeUntilSwapVBlank = 0;
// TODO: Recalculate this for PAL version if necessary.
// Also, we should check the D3DPRESENT_INTERVAL value for accurracy.
// g_SwapData.TimeBetweenSwapVBlanks = 1/60;
g_SwapData.TimeBetweenSwapVBlanks = 0;
}
}
timeEndPeriod(0);
}
// thread dedicated to create devices
static DWORD WINAPI EmuCreateDeviceProxy(LPVOID)
{
DbgPrintf("EmuD3D8: CreateDevice proxy thread is running.\n");
while(true)
{
// if we have been signalled, create the device with cached parameters
if(g_EmuCDPD.bReady)
{
DbgPrintf("EmuD3D8: CreateDevice proxy thread recieved request.\n");
if(g_EmuCDPD.bCreate)
{
// only one device should be created at once
// TODO: ensure all surfaces are somehow cleaned up?
if(g_pD3DDevice8 != nullptr)
{
DbgPrintf("EmuD3D8: CreateDevice proxy thread releasing old Device.\n");
g_pD3DDevice8->EndScene();
// Address DirectX Debug Runtime reported error in _DEBUG builds
// Direct3D8: (ERROR) :Not all objects were freed: the following indicate the types of unfreed objects.
#ifndef _DEBUG
while(g_pD3DDevice8->Release() != 0);
#endif
g_pD3DDevice8 = nullptr;
}
if(g_EmuCDPD.pPresentationParameters->BufferSurfaces[0] != NULL)
EmuWarning("BufferSurfaces[0] : 0x%.08X", g_EmuCDPD.pPresentationParameters->BufferSurfaces[0]);
if(g_EmuCDPD.pPresentationParameters->DepthStencilSurface != NULL)
EmuWarning("DepthStencilSurface : 0x%.08X", g_EmuCDPD.pPresentationParameters->DepthStencilSurface);
// make adjustments to parameters to make sense with windows Direct3D
{
g_EmuCDPD.DeviceType = (g_XBVideo.GetDirect3DDevice() == 0) ? XTL::D3DDEVTYPE_HAL : XTL::D3DDEVTYPE_REF;
g_EmuCDPD.Adapter = g_XBVideo.GetDisplayAdapter();
g_EmuCDPD.pPresentationParameters->Windowed = !g_XBVideo.GetFullscreen();
if(g_XBVideo.GetVSync())
g_EmuCDPD.pPresentationParameters->SwapEffect = XTL::D3DSWAPEFFECT_COPY_VSYNC;
g_EmuCDPD.hFocusWindow = g_hEmuWindow;
g_EmuCDPD.pPresentationParameters->BackBufferFormat = (XTL::X_D3DFORMAT)XTL::EmuXB2PC_D3DFormat(g_EmuCDPD.pPresentationParameters->BackBufferFormat);
g_EmuCDPD.pPresentationParameters->AutoDepthStencilFormat = (XTL::X_D3DFORMAT)XTL::EmuXB2PC_D3DFormat(g_EmuCDPD.pPresentationParameters->AutoDepthStencilFormat);
if(!g_XBVideo.GetVSync() && (g_D3DCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE) && g_XBVideo.GetFullscreen())
g_EmuCDPD.pPresentationParameters->FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
else
{
if(g_D3DCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE && g_XBVideo.GetFullscreen())
g_EmuCDPD.pPresentationParameters->FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_ONE;
else
g_EmuCDPD.pPresentationParameters->FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
}
// HACK: Disable Tripple Buffering for now...
// TODO: Enumerate maximum BackBufferCount if possible.
if(g_EmuCDPD.pPresentationParameters->BackBufferCount > 1)
{
EmuWarning("Limiting BackBufferCount to 1...");
g_EmuCDPD.pPresentationParameters->BackBufferCount = 1;
}
// TODO: Support Xbox extensions if possible
if(g_EmuCDPD.pPresentationParameters->MultiSampleType != 0)
{
EmuWarning("MultiSampleType 0x%.08X is not supported!", g_EmuCDPD.pPresentationParameters->MultiSampleType);
g_EmuCDPD.pPresentationParameters->MultiSampleType = XTL::D3DMULTISAMPLE_NONE;
// TODO: Check card for multisampling abilities
// if(pPresentationParameters->MultiSampleType == X_D3DMULTISAMPLE_2_SAMPLES_MULTISAMPLE_QUINCUNX) // = 0x00001121
// pPresentationParameters->MultiSampleType = D3DMULTISAMPLE_2_SAMPLES;
// else
// CxbxKrnlCleanup("Unknown MultiSampleType (0x%.08X)", pPresentationParameters->MultiSampleType);
}
g_EmuCDPD.pPresentationParameters->Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
// retrieve resolution from configuration
if(g_EmuCDPD.pPresentationParameters->Windowed)
{
sscanf(g_XBVideo.GetVideoResolution(), "%d x %d", &g_EmuCDPD.pPresentationParameters->BackBufferWidth, &g_EmuCDPD.pPresentationParameters->BackBufferHeight);
XTL::D3DDISPLAYMODE D3DDisplayMode;
g_pD3D8->GetAdapterDisplayMode(g_XBVideo.GetDisplayAdapter(), &D3DDisplayMode);
g_EmuCDPD.pPresentationParameters->BackBufferFormat = (XTL::X_D3DFORMAT)D3DDisplayMode.Format;
g_EmuCDPD.pPresentationParameters->FullScreen_RefreshRateInHz = 0;
}
else
{
char szBackBufferFormat[16];
sscanf(g_XBVideo.GetVideoResolution(), "%d x %d %*dbit %s (%d hz)",
&g_EmuCDPD.pPresentationParameters->BackBufferWidth,
&g_EmuCDPD.pPresentationParameters->BackBufferHeight,
szBackBufferFormat,
&g_EmuCDPD.pPresentationParameters->FullScreen_RefreshRateInHz);
if(strcmp(szBackBufferFormat, "x1r5g5b5") == 0)
g_EmuCDPD.pPresentationParameters->BackBufferFormat = (XTL::X_D3DFORMAT)XTL::D3DFMT_X1R5G5B5;
else if(strcmp(szBackBufferFormat, "r5g6r5") == 0)
g_EmuCDPD.pPresentationParameters->BackBufferFormat = (XTL::X_D3DFORMAT)XTL::D3DFMT_R5G6B5;
else if(strcmp(szBackBufferFormat, "x8r8g8b8") == 0)
g_EmuCDPD.pPresentationParameters->BackBufferFormat = (XTL::X_D3DFORMAT)XTL::D3DFMT_X8R8G8B8;
else if(strcmp(szBackBufferFormat, "a8r8g8b8") == 0)
g_EmuCDPD.pPresentationParameters->BackBufferFormat = (XTL::X_D3DFORMAT)XTL::D3DFMT_A8R8G8B8;
}
}
// detect vertex processing capabilities
if((g_D3DCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) && g_EmuCDPD.DeviceType == XTL::D3DDEVTYPE_HAL)
{
DbgPrintf("EmuD3D8: Using hardware vertex processing\n");