-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGamesEngineeringBase.h
1216 lines (1081 loc) · 34.3 KB
/
GamesEngineeringBase.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
/*
MIT License
Copyright (c) 2024 MSc Games Engineering Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
// Include necessary Windows and DirectX headers
#include <Windows.h>
#include <string>
#include <D3D11.h>
#include <D3Dcompiler.h>
#include <xaudio2.h>
#include <map>
#include <wincodec.h>
#include <wincodecsdk.h>
#include <atlbase.h>
#include <Xinput.h>
#include <math.h>
// Link necessary libraries
#pragma comment(lib, "D3D11.lib")
#pragma comment(lib, "D3DCompiler.lib")
#pragma comment(lib, "WindowsCodecs.lib")
#pragma comment(lib, "xinput.lib")
// Define the namespace to encapsulate the library's classes
namespace GamesEngineeringBase
{
// Macros to extract mouse coordinates from LPARAM
#define CANVAS_GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define CANVAS_GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
// The Window class manages the creation and rendering of a window
class Window
{
private:
// Private member variables
HWND hwnd; // Handle to the window
HINSTANCE hinstance; // Handle to the application instance
float invZoom; // Inverse of the zoom factor
std::string name; // Window name/title
ID3D11Device* dev; // Direct3D device
ID3D11DeviceContext* devcontext; // Direct3D device context
IDXGISwapChain* sc; // Swap chain for double buffering
ID3D11RenderTargetView* rtv; // Render target view
D3D11_VIEWPORT vp; // Viewport configuration
ID3D11Texture2D* tex; // Texture for pixel data
ID3D11ShaderResourceView* srv; // Shader resource view
ID3D11PixelShader* ps; // Pixel shader
ID3D11VertexShader* vs; // Vertex shader
unsigned char* image; // Back buffer image data
bool keys[256]; // Keyboard state array
int mousex; // Mouse X-coordinate
int mousey; // Mouse Y-coordinate
bool mouseButtons[3]; // Mouse button states (left, middle, right)
int mouseWheel; // Mouse wheel value
unsigned int width; // Window width
unsigned int height; // Window height
// Static window procedure to handle window messages
static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
Window* canvas = NULL;
if (msg == WM_CREATE)
{
// On window creation, associate the Window instance with the HWND
canvas = reinterpret_cast<Window*>(((LPCREATESTRUCT)lParam)->lpCreateParams);
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)canvas);
}
else
{
// Retrieve the Window instance associated with the HWND
canvas = reinterpret_cast<Window*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
}
if (canvas)
return canvas->realWndProc(hwnd, msg, wParam, lParam);
return DefWindowProc(hwnd, msg, wParam, lParam);
}
// Updates the internal mouse coordinates
void updateMouse(int x, int y)
{
mousex = x;
mousey = y;
}
// Instance-specific window procedure to handle messages
LRESULT CALLBACK realWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
case WM_CLOSE:
{
// Handle window close/destroy messages
PostQuitMessage(0);
exit(0);
return 0;
}
case WM_KEYDOWN:
{
// Update key state to pressed
keys[static_cast<unsigned int>(wParam)] = true;
return 0;
}
case WM_KEYUP:
{
// Update key state to released
keys[static_cast<unsigned int>(wParam)] = false;
return 0;
}
case WM_LBUTTONDOWN:
{
// Handle left mouse button down
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseButtons[0] = true;
return 0;
}
case WM_LBUTTONUP:
{
// Handle left mouse button up
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseButtons[0] = false;
return 0;
}
case WM_RBUTTONDOWN:
{
// Handle right mouse button down
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseButtons[2] = true;
return 0;
}
case WM_RBUTTONUP:
{
// Handle right mouse button up
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseButtons[2] = false;
return 0;
}
case WM_MBUTTONDOWN:
{
// Handle middle mouse button down
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseButtons[1] = true;
return 0;
}
case WM_MBUTTONUP:
{
// Handle middle mouse button up
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseButtons[1] = false;
return 0;
}
case WM_MOUSEWHEEL:
{
// Handle mouse wheel movement
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
mouseWheel += GET_WHEEL_DELTA_WPARAM(wParam);
return 0;
}
case WM_MOUSEMOVE:
{
// Handle mouse movement
updateMouse(CANVAS_GET_X_LPARAM(lParam), CANVAS_GET_Y_LPARAM(lParam));
return 0;
}
default:
{
// Default message handling
return DefWindowProc(hwnd, msg, wParam, lParam);
}
}
}
// Processes window messages
void pumpLoop()
{
MSG msg;
ZeroMemory(&msg, sizeof(MSG));
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
public:
// Creates and initializes the window
void create(unsigned int window_width, unsigned int window_height, const std::string window_name, float zoom = 1.0f, bool window_fullscreen = false, int window_x = 0, int window_y = 0)
{
// Window class structure
WNDCLASSEX wc;
hinstance = GetModuleHandle(NULL);
name = window_name;
// Fill in the window class attributes
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hinstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hIconSm = wc.hIcon;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
std::wstring wname = std::wstring(name.begin(), name.end());
wc.lpszClassName = wname.c_str();
wc.cbSize = sizeof(WNDCLASSEX);
// Register the window class
RegisterClassEx(&wc);
DWORD style;
if (window_fullscreen)
{
// Configure fullscreen settings
width = GetSystemMetrics(SM_CXSCREEN);
height = GetSystemMetrics(SM_CYSCREEN);
DEVMODE fs;
memset(&fs, 0, sizeof(DEVMODE));
fs.dmSize = sizeof(DEVMODE);
fs.dmPelsWidth = (unsigned long)width;
fs.dmPelsHeight = (unsigned long)height;
fs.dmBitsPerPel = 32;
fs.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
ChangeDisplaySettings(&fs, CDS_FULLSCREEN);
style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP;
}
else
{
// Configure windowed mode settings
width = window_width;
height = window_height;
style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
}
// Set the process DPI awareness for proper scaling
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_SYSTEM_AWARE);
// Adjust window rectangle to accommodate for window borders
RECT wr = { 0, 0, static_cast<LONG>(width * zoom), static_cast<LONG>(height * zoom) };
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
// Create the window
hwnd = CreateWindowEx(
WS_EX_APPWINDOW,
wname.c_str(),
wname.c_str(),
style,
window_x,
window_y,
wr.right - wr.left,
wr.bottom - wr.top,
NULL,
NULL,
hinstance,
this);
// Calculate inverse zoom factor
invZoom = 1.0f / static_cast<float>(zoom);
// Display and focus the window
ShowWindow(hwnd, SW_SHOW);
SetForegroundWindow(hwnd);
SetFocus(hwnd);
// Initialize the swap chain description
DXGI_SWAP_CHAIN_DESC sd;
memset(&sd, 0, sizeof(DXGI_SWAP_CHAIN_DESC));
sd.BufferCount = 1;
sd.BufferDesc.Width = width;
sd.BufferDesc.Height = height;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hwnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = window_fullscreen ? false : true;
// Specify the DirectX feature level
D3D_FEATURE_LEVEL fl;
fl = D3D_FEATURE_LEVEL_11_0;
// Create the Direct3D device and swap chain
D3D11CreateDeviceAndSwapChain(
NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
0,
&fl,
1,
D3D11_SDK_VERSION,
&sd,
&sc,
&dev,
NULL,
&devcontext);
// Get the back buffer from the swap chain
ID3D11Texture2D* backbuffer;
sc->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backbuffer);
// Create the render target view
dev->CreateRenderTargetView(backbuffer, NULL, &rtv);
backbuffer->Release();
// Configure the viewport
vp.Width = (float)width;
vp.Height = (float)height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
// Set the viewport and render target
devcontext->RSSetViewports(1, &vp);
devcontext->OMSetRenderTargets(1, &rtv, NULL);
// Create the texture description for the back buffer image
D3D11_TEXTURE2D_DESC texdesc;
memset(&texdesc, 0, sizeof(D3D11_TEXTURE2D_DESC));
texdesc.Width = width * 3; // Width times 3 for RGB channels
texdesc.Height = height;
texdesc.MipLevels = 1;
texdesc.ArraySize = 1;
texdesc.Format = DXGI_FORMAT_R8_UNORM;
texdesc.SampleDesc.Count = 1;
texdesc.Usage = D3D11_USAGE_DYNAMIC;
texdesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
texdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
texdesc.MiscFlags = 0;
// Create the texture and shader resource view
dev->CreateTexture2D(&texdesc, NULL, &tex);
D3D11_SHADER_RESOURCE_VIEW_DESC srvdesc;
srvdesc.Format = DXGI_FORMAT_R8_UNORM;
srvdesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvdesc.Texture2D.MostDetailedMip = 0;
srvdesc.Texture2D.MipLevels = 1;
dev->CreateShaderResourceView(tex, &srvdesc, &srv);
// Set the default states
devcontext->OMSetBlendState(NULL, NULL, 0xffffffff);
devcontext->OMSetDepthStencilState(NULL, 0);
devcontext->RSSetState(NULL);
devcontext->IASetInputLayout(NULL);
devcontext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Vertex and pixel shader source code
std::string vertexShader = "struct VSOut\
{\
float4 pos : SV_Position;\
};\
VSOut VS(uint vertexID : SV_VertexId)\
{\
VSOut output;\
float2 texcoords = float2((vertexID << 1) & 2, vertexID & 2);\
output.pos = float4((texcoords.x * 2.0f) - 1.0f, (-texcoords.y * 2.0f) + 1.0f, 0, 1.0f);\
return output;\
}";
std::string pixelShader = "Texture2D tex : register(t0);\
struct VSOut\
{\
float4 pos : SV_Position;\
};\
float4 PS(VSOut psInput) : SV_Target0\
{\
int3 texcoordsr = int3(psInput.pos.x * 3, psInput.pos.y, 0);\
int3 texcoordsg = texcoordsr + int3(1, 0, 0);\
int3 texcoordsb = texcoordsr + int3(2, 0, 0);\
return float4(tex.Load(texcoordsb).r, tex.Load(texcoordsr).r, tex.Load(texcoordsg).r, 1.0f);\
}";
// Compile the shaders
ID3DBlob* vshader;
ID3DBlob* pshader;
D3DCompile(
vertexShader.c_str(),
strlen(vertexShader.c_str()),
NULL,
NULL,
NULL,
"VS",
"vs_5_0",
0,
0,
&vshader,
NULL);
dev->CreateVertexShader(vshader->GetBufferPointer(), vshader->GetBufferSize(), NULL, &vs);
D3DCompile(
pixelShader.c_str(),
strlen(pixelShader.c_str()),
NULL,
NULL,
NULL,
"PS",
"ps_5_0",
0,
0,
&pshader,
NULL);
dev->CreatePixelShader(pshader->GetBufferPointer(), pshader->GetBufferSize(), NULL, &ps);
// Cleanup the shader build data
vshader->Release();
pshader->Release();
// Set the shaders and shader resources
devcontext->VSSetShader(vs, NULL, 0);
devcontext->PSSetShader(ps, NULL, 0);
devcontext->PSSetShaderResources(0, 1, &srv);
// Allocate memory for the back buffer image data
image = new unsigned char[width * height * 3];
clear(); // Clear the image data
// Initialize input states
memset(keys, 0, 256 * sizeof(bool));
memset(mouseButtons, 0, 3 * sizeof(bool));
// Initialize COM library for image loading
HRESULT comResult;
comResult = CoInitializeEx(NULL, COINIT_MULTITHREADED);
}
// Processes input messages
void checkInput()
{
pumpLoop();
}
// Returns a pointer to the back buffer image data
unsigned char* backBuffer()
{
return image;
}
// Draws a pixel at (x, y) with the specified RGB color
void draw(int x, int y, unsigned char r, unsigned char g, unsigned char b)
{
int index = ((y * width) + x) * 3;
image[index] = r;
image[index + 1] = g;
image[index + 2] = b;
}
// Draws a pixel at the specified pixel index with the given RGB color
void draw(int pixelIndex, unsigned char r, unsigned char g, unsigned char b)
{
int index = pixelIndex * 3;
image[index] = r;
image[index + 1] = g;
image[index + 2] = b;
}
// Draws a pixel at (x, y) using the color from the provided pixel array
void draw(int x, int y, unsigned char* pixel)
{
int index = ((y * width) + x) * 3;
image[index] = pixel[0];
image[index + 1] = pixel[1];
image[index + 2] = pixel[2];
}
// Clears the back buffer by setting all pixels to black
void clear()
{
memset(image, 0, width * height * 3 * sizeof(unsigned char));
}
// Presents the back buffer to the screen
void present()
{
// Map the texture to update its data
D3D11_MAPPED_SUBRESOURCE res;
devcontext->Map(tex, 0, D3D11_MAP_WRITE_DISCARD, 0, &res);
// Copy the image data to the texture
memcpy(res.pData, image, width * height * 3 * sizeof(unsigned char));
// Unmap the texture
devcontext->Unmap(tex, 0);
// Clear the render target view
float ClearColor[4] = { 0.0f, 0.0f, 1.0f, 1.0f }; // RGBA
devcontext->ClearRenderTargetView(rtv, ClearColor);
// Draw the vertices
devcontext->Draw(3, 0);
// Present the swap chain
sc->Present(0, 0);
// Process any pending messages
pumpLoop();
}
// Returns the window's width
unsigned int getWidth()
{
return width;
}
// Returns the window's height
unsigned int getHeight()
{
return height;
}
// Checks if a specific key is currently pressed
bool keyPressed(int key)
{
return keys[key];
}
// Gets the mouse X-coordinate relative to the window, accounting for zoom
int getMouseInWindowX()
{
POINT p;
GetCursorPos(&p);
ScreenToClient(hwnd, &p);
RECT rect;
GetClientRect(hwnd, &rect);
p.x = p.x - rect.left;
p.x = static_cast<LONG>(p.x * invZoom);
return p.x;
}
// Gets the mouse Y-coordinate relative to the window, accounting for zoom
int getMouseInWindowY()
{
POINT p;
GetCursorPos(&p);
ScreenToClient(hwnd, &p);
RECT rect;
GetClientRect(hwnd, &rect);
p.y = p.y - rect.top;
p.y = static_cast<LONG>(p.y * invZoom);
return p.y;
}
// Restricts the mouse cursor to the window's client area
void clipMouseToWindow()
{
RECT rect;
GetClientRect(hwnd, &rect);
POINT ul;
ul.x = rect.left;
ul.y = rect.top;
POINT lr;
lr.x = rect.right;
lr.y = rect.bottom;
MapWindowPoints(hwnd, nullptr, &ul, 1);
MapWindowPoints(hwnd, nullptr, &lr, 1);
rect.left = ul.x;
rect.top = ul.y;
rect.right = lr.x;
rect.bottom = lr.y;
ClipCursor(&rect);
}
// Destructor to release resources
~Window()
{
vs->Release();
ps->Release();
srv->Release();
tex->Release();
rtv->Release();
sc->Release();
devcontext->Release();
dev->Release();
CoUninitialize();
}
};
// FourCC codes for WAV file parsing (big-Endian)
#ifdef _XBOX
#define fourccRIFF 'RIFF'
#define fourccDATA 'data'
#define fourccFMT 'fmt '
#define fourccWAVE 'WAVE'
#define fourccXWMA 'XWMA'
#define fourccDPDS 'dpds'
#endif
// FourCC codes for WAV file parsing (little-endian)
#ifndef _XBOX
#define fourccRIFF 'FFIR'
#define fourccDATA 'atad'
#define fourccFMT ' tmf'
#define fourccWAVE 'EVAW'
#define fourccXWMA 'AMWX'
#define fourccDPDS 'sdpd'
#endif
// The Sound class handles loading and playing WAV audio files
class Sound
{
private:
XAUDIO2_BUFFER buffer; // Audio buffer
IXAudio2SourceVoice* sourceVoice[128]; // Array of source voices for playback
int index; // Current index for source voices
// Helper function to find a chunk in the WAV file (from documentation)
HRESULT FindChunk(HANDLE hFile, DWORD fourcc, DWORD& dwChunkSize, DWORD& dwChunkDataPosition)
{
HRESULT hr = S_OK;
if (INVALID_SET_FILE_POINTER == SetFilePointer(hFile, 0, NULL, FILE_BEGIN))
return HRESULT_FROM_WIN32(GetLastError());
DWORD dwChunkType;
DWORD dwChunkDataSize;
DWORD dwRIFFDataSize = 0;
DWORD dwFileType;
DWORD bytesRead = 0;
DWORD dwOffset = 0;
while (hr == S_OK)
{
DWORD dwRead;
if (0 == ReadFile(hFile, &dwChunkType, sizeof(DWORD), &dwRead, NULL))
hr = HRESULT_FROM_WIN32(GetLastError());
if (0 == ReadFile(hFile, &dwChunkDataSize, sizeof(DWORD), &dwRead, NULL))
hr = HRESULT_FROM_WIN32(GetLastError());
switch (dwChunkType)
{
case fourccRIFF:
dwRIFFDataSize = dwChunkDataSize;
dwChunkDataSize = 4;
if (0 == ReadFile(hFile, &dwFileType, sizeof(DWORD), &dwRead, NULL))
hr = HRESULT_FROM_WIN32(GetLastError());
break;
default:
if (INVALID_SET_FILE_POINTER == SetFilePointer(hFile, dwChunkDataSize, NULL, FILE_CURRENT))
return HRESULT_FROM_WIN32(GetLastError());
}
dwOffset += sizeof(DWORD) * 2;
if (dwChunkType == fourcc)
{
dwChunkSize = dwChunkDataSize;
dwChunkDataPosition = dwOffset;
return S_OK;
}
dwOffset += dwChunkDataSize;
if (bytesRead >= dwRIFFDataSize)
return S_FALSE;
}
return S_OK;
}
// Helper function to read chunk data from the WAV file
HRESULT ReadChunkData(HANDLE hFile, void* buffer, DWORD buffersize, DWORD bufferoffset)
{
HRESULT hr = S_OK;
if (INVALID_SET_FILE_POINTER == SetFilePointer(hFile, bufferoffset, NULL, FILE_BEGIN))
return HRESULT_FROM_WIN32(GetLastError());
DWORD dwRead;
if (0 == ReadFile(hFile, buffer, buffersize, &dwRead, NULL))
hr = HRESULT_FROM_WIN32(GetLastError());
return hr;
}
public:
// Loads a WAV file into the audio buffer
bool loadWAV(IXAudio2* xaudio, std::string filename)
{
WAVEFORMATEXTENSIBLE wfx = { 0 };
// Open the file
HANDLE hFile = CreateFileA(
filename.c_str(),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL);
SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
DWORD dwChunkSize;
DWORD dwChunkPosition;
// Check the file type; it should be 'WAVE'
FindChunk(hFile, fourccRIFF, dwChunkSize, dwChunkPosition);
DWORD filetype;
ReadChunkData(hFile, &filetype, sizeof(DWORD), dwChunkPosition);
if (filetype != fourccWAVE)
return S_FALSE;
// Read the 'fmt ' chunk to get the format
FindChunk(hFile, fourccFMT, dwChunkSize, dwChunkPosition);
ReadChunkData(hFile, &wfx, dwChunkSize, dwChunkPosition);
// Read the 'data' chunk to get the audio data
FindChunk(hFile, fourccDATA, dwChunkSize, dwChunkPosition);
BYTE* pDataBuffer = new BYTE[dwChunkSize];
ReadChunkData(hFile, pDataBuffer, dwChunkSize, dwChunkPosition);
// Fill the XAUDIO2_BUFFER structure
buffer.AudioBytes = dwChunkSize;
buffer.pAudioData = pDataBuffer;
buffer.Flags = XAUDIO2_END_OF_STREAM;
HRESULT hr;
// Create multiple source voices for concurrent playback
for (int i = 0; i < 128; i++)
{
if (FAILED(hr = xaudio->CreateSourceVoice(&sourceVoice[i], (WAVEFORMATEX*)&wfx)))
{
return false;
}
}
// Submit the audio buffer to the first source voice
if (FAILED(hr = sourceVoice[0]->SubmitSourceBuffer(&buffer)))
{
return false;
}
index = 0; // Reset the index
return true;
}
// Plays the sound once
void play()
{
sourceVoice[index]->SubmitSourceBuffer(&buffer);
sourceVoice[index]->Start(0);
index++;
if (index == 128)
{
index = 0;
}
}
// Plays the sound in an infinite loop (for music)
void playMusic()
{
buffer.LoopCount = XAUDIO2_LOOP_INFINITE;
sourceVoice[index]->SubmitSourceBuffer(&buffer);
sourceVoice[index]->Start(0);
}
};
// The SoundManager class manages multiple Sound instances
class SoundManager
{
private:
IXAudio2* xaudio; // XAudio2 interface
IXAudio2MasteringVoice* xaudioMasterVoice; // Mastering voice
std::map<std::string, Sound*> sounds; // Map of sounds
Sound* music; // Music sound
// Helper function to find a sound by filename
Sound* find(std::string filename)
{
auto it = sounds.find(filename);
if (it != sounds.end())
{
return it->second;
}
return NULL;
}
public:
// Constructor that initializes XAudio2
SoundManager()
{
HRESULT comResult;
comResult = XAudio2Create(&xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR);
comResult = xaudio->CreateMasteringVoice(&xaudioMasterVoice);
}
// Loads a sound effect
void load(std::string filename)
{
if (find(filename) == NULL)
{
Sound* sound = new Sound();
if (sound->loadWAV(xaudio, filename))
{
sounds[filename] = sound;
}
}
}
// Plays a loaded sound effect
void play(std::string filename)
{
Sound* sound = find(filename);
if (sound != NULL)
{
sound->play();
}
}
// Loads a music track
void loadMusic(std::string filename)
{
music = new Sound();
music->loadWAV(xaudio, filename);
}
// Plays the loaded music track
void playMusic()
{
music->playMusic();
}
// Destructor to release resources
~SoundManager()
{
xaudio->Release();
}
};
// The Timer class provides high-resolution timing functionality
class Timer
{
private:
LARGE_INTEGER freq; // Frequency of the performance counter
LARGE_INTEGER start; // Starting time
public:
// Constructor that initializes the frequency
Timer()
{
QueryPerformanceFrequency(&freq);
reset();
}
// Resets the timer
void reset()
{
QueryPerformanceCounter(&start);
}
// Returns the elapsed time since the last reset in seconds. Note this should only be called once per frame as it resets the timer.
float dt()
{
LARGE_INTEGER cur;
QueryPerformanceCounter(&cur);
float value = static_cast<float>(cur.QuadPart - start.QuadPart) / freq.QuadPart;
reset();
return value;
}
};
// The Image class handles loading and manipulating images
// This class is a bit of an exception in that the members are public. The reason for this is users may want to create procedural images.
class Image
{
public:
unsigned int width; // Image width
unsigned int height; // Image height
unsigned int channels; // Number of color channels
unsigned char* data; // Pointer to image data
// Loads an image from a file using WIC
bool load(std::string filename)
{
CComPtr<IWICImagingFactory> factory;
factory.CoCreateInstance(CLSID_WICImagingFactory);
CComPtr<IWICBitmapDecoder> decoder;
IWICStream* stream = NULL;
factory->CreateStream(&stream);
std::wstring wFilename = std::wstring(filename.begin(), filename.end());
stream->InitializeFromFilename(wFilename.c_str(), GENERIC_READ);
factory->CreateDecoderFromStream(stream, 0, WICDecodeMetadataCacheOnDemand, &decoder);
CComPtr<IWICBitmapFrameDecode> frame;
decoder->GetFrame(0, &frame);
frame->GetSize(&width, &height);
WICPixelFormatGUID pixelFormat = { 0 };
frame->GetPixelFormat(&pixelFormat);
channels = 0;
int isRGB = 0;
// Determine the number of channels based on the pixel format
if (pixelFormat == GUID_WICPixelFormat24bppBGR)
{
channels = 3;
}
if (pixelFormat == GUID_WICPixelFormat32bppBGRA)
{
channels = 4;
}
if (pixelFormat == GUID_WICPixelFormat24bppRGB)
{
channels = 3;
isRGB = 1;
}
if (pixelFormat == GUID_WICPixelFormat32bppRGBA)
{
channels = 4;
isRGB = 1;
}
if (channels == 0)
{
return false;
}
data = new unsigned char[width * height * channels];
unsigned int stride = (width * channels + 3) & ~3; // Align stride to 4 bytes
if (stride == (width * channels))
{
// Copy pixels directly if stride matches
frame->CopyPixels(0, stride, width * height * channels, data);
}
else
{
// Handle images with padded stride
unsigned char* strideData = new unsigned char[stride * height];
frame->CopyPixels(0, stride, width * height * channels, strideData);
for (unsigned int i = 0; i < height; i++)
{
memcpy(&data[i * width * channels], &strideData[i * stride], width * channels * sizeof(unsigned char));
}
delete[] strideData;
}
if (isRGB == 0)
{
// Swap red and blue channels for BGR formats
for (unsigned int i = 0; i < width * height; i++)
{
unsigned char p = data[i * channels];
data[i * channels] = data[(i * channels) + 2];
data[(i * channels) + 2] = p;
}
}
return true;
}
// Returns a pointer to the pixel data at (x, y)
// Note, the bounds are handled via clamping
unsigned char* at(unsigned int x, unsigned int y)
{
return &data[((min(y, height - 1) * width) + min(x, width - 1)) * channels];
}
// Returns the alpha value of the pixel at (x, y)
// Note, the bounds are handled via clamping
unsigned char alphaAt(unsigned int x, unsigned int y)
{
if (channels == 4)
{
return data[((min(y, height - 1) * width) + min(x, width - 1)) * channels + 3];
}
return 255;
}
// Returns a the colour specified by index at (x, y)
// Note, the image bounds are handled via clamping, but the index is not checked
unsigned char at(unsigned int x, unsigned int y, unsigned int index)
{
return data[(((min(y, height - 1) * width) + min(x, width - 1)) * channels) + index];
}
// Returns a pointer to the pixel data at (x, y)
// Note, no checks performed on x and y coordinates
unsigned char* atUnchecked(unsigned int x, unsigned int y)
{