-
Notifications
You must be signed in to change notification settings - Fork 0
/
win32.cpp
1179 lines (975 loc) · 34 KB
/
win32.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
#ifndef COMPILER_MSVC
#define COMPILER_MSVC 0
#endif // ! COMPILER_MSVC
#ifndef COMPILER_LLVM
#define COMPILER_LLVM 0
#endif // ! COMPILER_MSVC
#if !COMPILER_MSVC && !COMPILER_MSVC
#if _MSC_VER
#undef COMPILER_MSVC
#define COMPILER_MSVC 1
#else
#undef COMPILER_LLVM
#define COMPILER_LLVM 1
#endif //
#endif
#if COMPILER_MSVC
#include <intrin.h>
#else
#define BEGIN_TIMED_BLOCK(ID)
#define END_TIMED_BLOCK(ID)
#endif
#define Assert(Expression) if(!(Expression)) {printf("Assert in Function %s, File %s line %i.\n", __FUNCTION__, __FILE__, __LINE__); fflush(stdout); __debugbreak();}
#define InvalidDefaultCase \
default: \
{\
Die;\
}break;
template <typename F>
struct saucy_defer {
F f;
saucy_defer(F f) : f(f) {}
~saucy_defer() { f(); }
};
template <typename F>
saucy_defer<F> defer_func(F f) {
return saucy_defer<F>(f);
}
#define DEFER_1(x, y) x##y
#define DEFER_2(x, y) DEFER_1(x, y)
#define DEFER_3(x) DEFER_2(x, __LINE__)
#define defer(code) auto DEFER_3(_defer_) = defer_func([&](){code;})
#define WGLPROC(a) a = (a##_ *)wglGetProcAddress(#a);
#define ArrayCount(a) (sizeof(a)/sizeof(*a))
#define GigaBytes(a) (1024 * MegaBytes(a))
#define MegaBytes(a) (1024 * KiloBytes(a))
#define KiloBytes(a) (1024 * (a))
#define OffsetOf(type, Member) (umm)&(((type *)0)->Member)
#define Die Assert(false)
#include <cstdio>
#include "Game.h"
#include <Windows.h>
#include <gl/gl.h>
#include <dsound.h>
#undef CreateFile
#undef PlaySound
// note this is so when we compile shaders we can just stop.
static bool running;
#include "OpenGL.h"
//sound
#define DIRECT_SOUND_CREATE(name) HRESULT WINAPI name(LPCGUID pcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter)
typedef DIRECT_SOUND_CREATE(direct_sound_create);
// todo: remove all globals?
static bool globalGamePaused;
static LPDIRECTSOUNDBUFFER globalSoundBuffer;
static MouseInput globalMouseInput;
static WorkHandler workHandler;
static i64 globalPerformanceCountFrequency;
static HANDLE semaphoreHandle;
static HWND globalWindow;
static void FreeFile(BuddyAllocator *alloc, File file) // todo make this take a pointer and clear it, just in case.
{
void *memory = file.memory;
if (memory)
{
DynamicFree(alloc, memory);
}
}
//todo clean it up, such that there are not 3 LoadFile...
static File LoadFile(char *fileName, BuddyAllocator *alloc)
{
void *memory = 0;
unsigned int size = 0;
HANDLE fileHandle = CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (fileHandle == INVALID_HANDLE_VALUE)
{
return { 0, NULL };
}
LARGE_INTEGER fileSize;
if (GetFileSizeEx(fileHandle, &fileSize))
{
u32 fileSize32 = (u32)fileSize.QuadPart;
memory = DynamicAlloc(alloc, u8, fileSize32);
if (memory)
{
DWORD bytesRead;
if (ReadFile(fileHandle, memory, fileSize32, &bytesRead, 0) && fileSize32 == bytesRead)
{
size = fileSize32;
}
else
{
Die;
memory = 0;
}
}
}
CloseHandle(fileHandle);
File result;
result.fileSize = size;
result.memory = (u8 *)memory;
return result;
}
static File LoadFile(char *fileName, void *dest, u32 destSize)
{
void *memory = NULL;
u32 size = 0;
HANDLE fileHandle = CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (fileHandle == INVALID_HANDLE_VALUE)
{
return { 0, NULL };
}
LARGE_INTEGER fileSize;
if (GetFileSizeEx(fileHandle, &fileSize))
{
u32 fileSize32 = (u32)fileSize.QuadPart;
if (fileSize32 <= destSize)
{
memory = dest;
DWORD bytesRead;
if (ReadFile(fileHandle, memory, fileSize32, &bytesRead, 0) && fileSize32 == bytesRead)
{
size = fileSize32;
}
else
{
Die;
memory = 0;
}
}
}
CloseHandle(fileHandle);
File result;
result.fileSize = size;
result.memory = (u8 *)memory;
return result;
}
static File LoadFile(char *fileName, Arena *arena)
{
void *memory = 0;
unsigned int size = 0;
HANDLE fileHandle = CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (fileHandle != INVALID_HANDLE_VALUE)
{
LARGE_INTEGER fileSize;
if (GetFileSizeEx(fileHandle, &fileSize))
{
u32 fileSize32 = (u32)fileSize.QuadPart;
memory = PushData(arena, u8, fileSize32);
if (memory)
{
DWORD bytesRead;
if (ReadFile(fileHandle, memory, fileSize32, &bytesRead, 0) && fileSize32 == bytesRead)
{
size = fileSize32;
}
else
{
Die;
memory = 0;
}
}
}
CloseHandle(fileHandle);
}
File result;
result.fileSize = size;
result.memory = (u8 *)memory;
return result;
}
static bool WriteEntireFile(char * fileName, File file) //zero terminated
{
void * memory = file.memory;
unsigned int size = file.fileSize;
bool result = false;
HANDLE fileHandle = CreateFileA(fileName, GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, NULL, NULL);
if (fileHandle != INVALID_HANDLE_VALUE)
{
DWORD bytesWritten;
if (WriteFile(fileHandle, memory, size, &bytesWritten, 0) && (bytesWritten == size))
{
result = true;
}
else
{
//todo: logging
Die;
OutputDebugStringA("Error writing file.");
}
CloseHandle(fileHandle);
}
return result;
}
// note path ending in '/' filetype includes '.'. Strings get loaded into arenaForStrings
static StringArray FindAllFiles(char *path, char *fileType, Arena *arenaForStrings)
{
char* searchString = FormatCString("%c**%c*", path, fileType);
Arena *arena = PushArena(frameArena, 8000);
BeginArray(arena, String, ret);
WIN32_FIND_DATAA data = {};
HANDLE handle = FindFirstFile(searchString, &data);
if (handle != INVALID_HANDLE_VALUE)
{
*PushStruct(arena, String) = S(data.cFileName, arenaForStrings);
while (FindNextFile(handle, &data))
{
*PushStruct(arena, String) = S(data.cFileName, arenaForStrings);
}
}
EndArray(arena, String, ret);
return ret;
}
static void displayImageBuffer(HDC deviceContext)
{
TimedBlock;
SwapBuffers(deviceContext);
}
static void initializeSoundBuffer(HWND window, SoundBuffer *soundOutput)
{
//soundOutput.hz = 256;
soundOutput->toneVolume = 2000;
soundOutput->samplesPerSecond = 48000;
soundOutput->runningSampleIndex = 0;
//soundOutput.squareWavePeriod = soundOutput.samplesPerSecond / soundOutput.hz;
//soundOutput.halfSquareWavePeriod = (soundOutput.squareWavePeriod / 2);
soundOutput->bytesPerSample = sizeof(i16) * 2;
soundOutput->secondaryBufferSize = soundOutput->samplesPerSecond *soundOutput->bytesPerSample;
soundOutput->soundIsPlaying = false;
soundOutput->soundIsValid = false;
soundOutput->latencySampleCount = soundOutput->samplesPerSecond / 10; //1/4 seconds of latency
//load library
HMODULE dSoundLibrary = LoadLibrary("dsound.dll");
if (dSoundLibrary)
{
//NOTE: Get a DirectSoundobject
LPDIRECTSOUND directSound;
direct_sound_create *directSoundCreate = (direct_sound_create *)GetProcAddress(dSoundLibrary, "DirectSoundCreate");
if (directSoundCreate && SUCCEEDED(directSoundCreate(0, &directSound, 0)))
{
WAVEFORMATEX waveFormat = {};
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = 2;
waveFormat.nSamplesPerSec = soundOutput->samplesPerSecond;
waveFormat.wBitsPerSample = 16;
waveFormat.nBlockAlign = (waveFormat.nChannels * waveFormat.wBitsPerSample) / 8;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
//NOTE: "create" a primary buffer
if (SUCCEEDED(directSound->SetCooperativeLevel(window, DSSCL_PRIORITY)))
{
//TODO :DSBVAPS _GLOBALFOCUS
DSBUFFERDESC bufferDescription = {};
bufferDescription.dwSize = sizeof(bufferDescription);
bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
LPDIRECTSOUNDBUFFER primaryBuffer;
if (SUCCEEDED(directSound->CreateSoundBuffer(&bufferDescription, &primaryBuffer, 0)))
{
if (SUCCEEDED(primaryBuffer->SetFormat(&waveFormat)))
{
OutputDebugStringA("primary buffer created");
}
else
{
//TODO: diag
}
}
}
else
{
// TODO diag
}
//NOTE: "create" a secondary buffer
DSBUFFERDESC bufferDescription = {};
bufferDescription.dwSize = sizeof(bufferDescription);
bufferDescription.dwBufferBytes = soundOutput->secondaryBufferSize;
bufferDescription.dwFlags = 0;
bufferDescription.lpwfxFormat = &waveFormat;
if (SUCCEEDED(directSound->CreateSoundBuffer(&bufferDescription, &globalSoundBuffer, 0)))
{
OutputDebugStringA("secondary buffer created");
}
else
{
}
//NOTE: Start it playing
}
else
{
//TODO diagnostic
}
}
}
static void win32FillSoundBuffer(SoundBuffer* soundOutput, DWORD byteToLock, DWORD bytesToWrite,
i16 *samples)
{
void* region1;
DWORD region1Size;
void* region2;
DWORD region2Size;
//s16 s16 s16...
//[Left Right] Left Right
// one Sample
if (SUCCEEDED(globalSoundBuffer->Lock(byteToLock, bytesToWrite, ®ion1, ®ion1Size, ®ion2, ®ion2Size, 0)))
{
//TODO assert taht stuff is valid
i16 *sampleOut = (i16*)region1;
i16 *sourceSample = samples;
DWORD Region1SampleCount = region1Size / soundOutput->bytesPerSample;
for (DWORD sampleIndex = 0; sampleIndex < Region1SampleCount; ++sampleIndex)
{
*sampleOut++ = *sourceSample++;
*sampleOut++ = *sourceSample++;
soundOutput->runningSampleIndex++;
}
DWORD Region2SampleCount = region2Size / soundOutput->bytesPerSample;
sampleOut = (i16*)region2;
for (DWORD sampleIndex = 0; sampleIndex < Region2SampleCount; ++sampleIndex)
{
*sampleOut++ = *sourceSample++;
*sampleOut++ = *sourceSample++;
soundOutput->runningSampleIndex++;
}
globalSoundBuffer->Unlock(region1, region1Size, region2, region2Size);
}
}
inline f32 win32GetSecondsElapsed(LARGE_INTEGER start, LARGE_INTEGER end)
{
return (((f32)end.QuadPart - (f32)start.QuadPart) / (f32)globalPerformanceCountFrequency);
}
LRESULT CALLBACK win32MainWindowCallback(
HWND window,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
LRESULT result = 0;
switch (message)
{
case WM_DESTROY:
{
running = false;
}break;
case WM_PAINT:
{
//OutputDebugStringA("WM_PAINT\n");
PAINTSTRUCT paint;
HDC deviceContext = BeginPaint(window, &paint);
EndPaint(window, &paint);
}break;
default:
{
result = DefWindowProc(window, message, wParam, lParam);
break;
}
}
return result;
}
#define WRITEBARRIER _WriteBarrier(); _mm_sfence();
#define READBARRIER _ReadBarrier()
struct WorkQueueEntry
{
char *stringToPrint;
};
static u32 volatile entryCount;
static u32 volatile todo; // todo hui ui ui, what is this jank exactly?
WorkQueueEntry entries[256];
struct ThreadInfo
{
u32 threadIndex;
HANDLE semaphoreHandle;
};
static i64 AtomicIncrement(volatile i64 *toIncrement)
{
return InterlockedIncrement((volatile long *)toIncrement);
}
static i64 AtomicCompareExchange(volatile i64 *dest, i64 expectedValueOfDest, i64 newValue)
{
return InterlockedCompareExchange((volatile long *)dest, (long)expectedValueOfDest, (long)newValue);
}
static bool work(int threadIndex)
{
bool worked = false;
if (todo < entryCount)
{
int entryIndex = InterlockedIncrement(&todo) - 1;
WorkQueueEntry *entry = entries + entryIndex++;
char buffer[256];
wsprintf(buffer, "Thread %u: %s \n", threadIndex, entry->stringToPrint);
OutputDebugStringA(buffer);
worked = true;
}
return worked;
}
static void WakeThreads()
{
ReleaseSemaphore(semaphoreHandle, 1, 0);
}
DWORD WINAPI ThreadProc(LPVOID param)
{
ThreadInfo *threadInfo = (ThreadInfo *)param;
for (;;)
{
if (WorkDone(&workHandler))
{
WaitForSingleObjectEx(threadInfo->semaphoreHandle, INFINITE, FALSE);
}
else
{
DoWork(&workHandler);
}
}
return 0;
}
typedef BOOL WINAPI wgl_swap_inverval_ext(int interval);
typedef HGLRC WINAPI wgl_create_context_attribs_ARB(HDC hdC, HGLRC sharedContext, const int *attribList);
#define WGL_DRAW_TO_WINDOW_ARB 0x2001
#define WGL_ACCELERATION_ARB 0x2003
#define WGL_SUPPORT_OPENGL_ARB 0x2010
#define WGL_DOUBLE_BUFFER_ARB 0x2011
#define WGL_PIXEL_TYPE_ARB 0x2013
#define WGL_TYPE_RGBA_ARB 0x202B
#define WGL_FULL_ACCELERATION_ARB 0x2027
#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
#define WGL_RED_BITS_ARB 0x2015
#define WGL_GREEN_BITS_ARB 0x2017
#define WGL_BLUE_BITS_ARB 0x2019
#define WGL_ALPHA_BITS_ARB 0x201B
#define WGL_DEPTH_BITS_ARB 0x2022
#define WGL_STENCIL_BITS_ARB 0x2024
#define WGL_SAMPLE_BUFFERS_ARB 0x2041
#define WGL_SAMPLES_ARB 0x2042
typedef BOOL WINAPI wglGetPixelFormatAttribivARB_(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
typedef BOOL WINAPI wglGetPixelFormatAttribfvARB_(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
typedef BOOL WINAPI wglChoosePixelFormatARB_(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
static wglChoosePixelFormatARB_ *wglChoosePixelFormatARB;
static wgl_create_context_attribs_ARB *wglCreateContextAttribsARB;
int win32OpenGLAttribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 2,
WGL_CONTEXT_FLAGS_ARB, 0
| WGL_CONTEXT_DEBUG_BIT_ARB
,
//WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0,
};
static void win32SetPixelFormat(HDC windowDC)
{
int suggestedPixelFormatIndex = 0;
u32 extendedPick = 0;
if (wglChoosePixelFormatARB)
{
int ARBAttribs[] =
{
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, GL_TRUE,
WGL_RED_BITS_ARB, 8,
WGL_GREEN_BITS_ARB, 8,
WGL_BLUE_BITS_ARB, 8,
WGL_ALPHA_BITS_ARB, 8,
WGL_DEPTH_BITS_ARB, 24,
WGL_SAMPLE_BUFFERS_ARB, 1,
WGL_SAMPLES_ARB, 4,
//WGL_STENCIL_BITS_ARB, 8, aperantly this does not work with multisampling
0, 0
};
wglChoosePixelFormatARB(windowDC, ARBAttribs, { 0 }, 1, &suggestedPixelFormatIndex, &extendedPick);
}
if(!extendedPick)
{
//wglGetPixelFormatAttribfvARB_ *wglGetPixelFormatAttribfvARB = (wglGetPixelFormatAttribfvARB_ *)wglGetProcAddress("wglGetPixelFormatAttribfvARB");
//wglGetPixelFormatAttribivARB_ *wglGetPixelFormatAttribivARB = (wglGetPixelFormatAttribivARB_ *)wglGetProcAddress("wglGetPixelFormatAttribivARB");
PIXELFORMATDESCRIPTOR desiredPixelFormat = {};
desiredPixelFormat.nSize = sizeof(desiredPixelFormat);
desiredPixelFormat.nVersion = 1;
desiredPixelFormat.iPixelType = PFD_TYPE_RGBA;
desiredPixelFormat.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
desiredPixelFormat.cColorBits = 32;
desiredPixelFormat.cAlphaBits = 8;
desiredPixelFormat.cDepthBits = 24;
desiredPixelFormat.cStencilBits = 8;
desiredPixelFormat.iLayerType = PFD_MAIN_PLANE;
suggestedPixelFormatIndex = ChoosePixelFormat(windowDC, &desiredPixelFormat);
}
PIXELFORMATDESCRIPTOR suggestedPixelFormat;
DescribePixelFormat(windowDC, suggestedPixelFormatIndex, sizeof(suggestedPixelFormat), &suggestedPixelFormat);
SetPixelFormat(windowDC, suggestedPixelFormatIndex, &suggestedPixelFormat);
}
static void win32LoadWglExtensions()
{
WNDCLASSA windowClass = {};
windowClass.lpfnWndProc = DefWindowProcA;
windowClass.hInstance = GetModuleHandle(0);
windowClass.lpszClassName = "WGLLoader";
if (RegisterClassA(&windowClass))
{
HWND helperWindow = CreateWindowExA(0, windowClass.lpszClassName, "WGLLOADER", WS_BORDER, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, 0, 0, windowClass.hInstance, 0);
HDC windowDC = GetDC(helperWindow);
win32SetPixelFormat(windowDC);
HGLRC contextRC = wglCreateContext(windowDC);
if (wglMakeCurrent(windowDC, contextRC))
{
//wglChoosePixelFormatARB = (wglChoosePixelFormatARB_ *)wglGetProcAddress("wglChoosePixelFormatARB");
WGLPROC(wglChoosePixelFormatARB);
wglCreateContextAttribsARB = (wgl_create_context_attribs_ARB *)wglGetProcAddress("wglCreateContextAttribsARB");
}
wglMakeCurrent(0, 0);
wglDeleteContext(contextRC);
ReleaseDC(helperWindow, windowDC);
DestroyWindow(helperWindow);
}
}
static OpenGLContext win32InitOpenGL(HWND window)
{
OpenGLContext ret = {};
win32LoadWglExtensions();
HDC windowDC = GetDC(window);
win32SetPixelFormat(windowDC);
bool modernContext = true;
HGLRC context = 0;
if (wglCreateContextAttribsARB)
{
//NOTE: modern Version of openGL
HGLRC sharedContext = 0;
context = wglCreateContextAttribsARB(windowDC, sharedContext, win32OpenGLAttribs);
}
if (!context)
{
modernContext = false;
context = wglCreateContext(windowDC);
}
if (wglMakeCurrent(windowDC, context))
{
// vsync
wgl_swap_inverval_ext *wglSwapIntervalEXT= (wgl_swap_inverval_ext *)wglGetProcAddress("wglSwapIntervalEXT");
if (wglSwapIntervalEXT)
{
wglSwapIntervalEXT(1);
}
WGLPROC(glBlendEquation);
WGLPROC(glTexImage3D);
WGLPROC(glTexSubImage3D);
WGLPROC(glGetStringi);
WGLPROC(glTexImage2DMultisample);
WGLPROC(glBufferData);
WGLPROC(glBindBuffer);
WGLPROC(glGenBuffers);
WGLPROC(glBindVertexArray);
WGLPROC(glGenVertexArrays);
WGLPROC(glCreateShader);
WGLPROC(glShaderSource);
WGLPROC(glCompileShader);
WGLPROC(glLinkProgram);
WGLPROC(glCreateProgram);
WGLPROC(glAttachShader);
WGLPROC(glValidateProgram);
WGLPROC(glGetProgramInfoLog);
WGLPROC(glGetProgramiv);
WGLPROC(glGetShaderInfoLog);
WGLPROC(glUniformMatrix4fv);
WGLPROC(glUniform4fv);
WGLPROC(glUniform1iv);
WGLPROC(glGetUniformLocation);
WGLPROC(glUseProgram);
WGLPROC(glVertexAttribIPointer);
WGLPROC(glVertexAttribPointer);
WGLPROC(glEnableVertexAttribArray);
WGLPROC(glDisableVertexAttribArray);
WGLPROC(glGetAttribLocation);
WGLPROC(glGenFramebuffers);
WGLPROC(glBindFramebuffer);
WGLPROC(glVertexAttrib3f);
WGLPROC(glCheckFramebufferStatus);
WGLPROC(glFramebufferTexture);
WGLPROC(glFramebufferTexture2D);
WGLPROC(glBlitFramebuffer);
WGLPROC(glDebugMessageCallback);
WGLPROC(glActiveTexture);
WGLPROC(glUniform1i);
WGLPROC(glUniform1f);
WGLPROC(glUniform2f);
WGLPROC(glUniform3f);
WGLPROC(glUniform4f);
WGLPROC(glBindAttribLocation);
ret = OpenGLInit(modernContext);
}
ReleaseDC(window, windowDC);
return ret;
}
static String OSGetClipBoard()
{
if(OpenClipboard(NULL))
{
String ret;
HANDLE handle = GetClipboardData(CF_TEXT);
char *inp = (char *)GlobalLock(handle);
String inpS = CreateString(inp);
ret = CopyString(inpS);
GlobalUnlock(handle);
CloseClipboard();
return ret;
}
return {};
}
static void OSSetClipBoard(String string)
{
if (OpenClipboard(globalWindow))
{
EmptyClipboard();
HGLOBAL clipbuffer = GlobalAlloc(GMEM_SHARE, string.length + 1);
char* buffer = (char *)GlobalLock(clipbuffer);
memcpy(buffer, ToNullTerminated(frameArena, string), sizeof(char) * (string.length + 1));
GlobalUnlock(clipbuffer);
HANDLE ret = SetClipboardData(CF_TEXT, buffer);
// todo do I need to do something with this handle?
CloseClipboard();
}
}
static void DispatchKeyMessage(KeyStateMessage keyMessage)
{
*PushStruct(frameArena, KeyStateMessage) = keyMessage;
}
static KeyStateMessageArray HandleWindowsMessages() //todo make this buffer allocate on the frame arena? could just be the first thing that happens ont that
{
// todo should these be values in the buffer?
static b32 shiftDown = false;
static b32 controlDown = false;
BeginArray(frameArena, KeyStateMessage, ret);
MSG message;
while (PeekMessageA(&message, 0, 0, 0, PM_REMOVE))
{
u32 shiftCtrlFlag = ((shiftDown > 0) * KeyState_ShiftDown) | ((controlDown > 0) * KeyState_ControlDown);
switch (message.message)
{
case WM_LBUTTONDOWN:
{
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_Down | KeyState_PressedThisFrame | shiftCtrlFlag;
keyMessage.key = Key_leftMouse;
DispatchKeyMessage(keyMessage);
}break;
case WM_LBUTTONUP:
{
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_Up | KeyState_ReleasedThisFrame | shiftCtrlFlag;
keyMessage.key = Key_leftMouse;
DispatchKeyMessage(keyMessage);
}break;
case WM_RBUTTONDOWN:
{
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_Down | KeyState_PressedThisFrame | shiftCtrlFlag;
keyMessage.key = Key_rightMouse;
DispatchKeyMessage(keyMessage);
}break;
case WM_RBUTTONUP:
{
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_Up | KeyState_ReleasedThisFrame | shiftCtrlFlag;
keyMessage.key = Key_rightMouse;
DispatchKeyMessage(keyMessage);
}break;
case WM_MBUTTONDOWN:
{
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_Down | KeyState_PressedThisFrame | shiftCtrlFlag;
keyMessage.key = Key_middleMouse;
DispatchKeyMessage(keyMessage);
}break;
case WM_MBUTTONUP:
{
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_Up | KeyState_ReleasedThisFrame | shiftCtrlFlag;
keyMessage.key = Key_middleMouse;
DispatchKeyMessage(keyMessage);
}break;
case WM_MOUSEWHEEL:
{
u32 fwKeys = GET_KEYSTATE_WPARAM(message.wParam);
int zDelta = GET_WHEEL_DELTA_WPARAM(message.wParam);
KeyStateMessage keyMessage;
keyMessage.flag = KeyState_PressedThisFrame | KeyState_Down | shiftCtrlFlag;
keyMessage.key = (zDelta > 0) ? Key_mouseWheelForward : Key_mouseWheelBack;
DispatchKeyMessage(keyMessage);
}break;
case WM_MOUSEMOVE:
{
POINT mousePos;
GetCursorPos(&mousePos);
if (GetCursorPos(&mousePos))
{
ScreenToClient(message.hwnd, &mousePos);
globalMouseInput.x = mousePos.x;
globalMouseInput.y = mousePos.y;
}
else
{
OutputDebugStringA("could not get mousePosition.\n");
}
}break;
case WM_KEYUP:
case WM_SYSKEYUP:
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
u64 vkCode = message.wParam;
u32 repeaded = message.lParam & 0xFF;
b32 wasDown = ((message.lParam & (1UL << 30)) != 0);
b32 isDown = ((message.lParam & (1UL << 31)) == 0);
KeyStateMessage keyMessage;
keyMessage.key = (KeyEnum)vkCode;
if (vkCode == Key_shift)
{
shiftDown = isDown;
}
if (vkCode == Key_control)
{
controlDown = isDown;
}
keyMessage.flag = shiftCtrlFlag;
if (isDown) //todo could make this better, just oring em together
{
keyMessage.flag |= KeyState_Down;
if (isDown != wasDown)
{
keyMessage.flag |= KeyState_PressedThisFrame;
}
if (repeaded)
{
keyMessage.flag |= KeyState_Repeaded;
}
}
else
{
keyMessage.flag |= KeyState_Up;
if (isDown != wasDown)
{
keyMessage.flag |= KeyState_ReleasedThisFrame;
}
}
DispatchKeyMessage(keyMessage);
if (isDown && vkCode == VK_F4)
{
running = false;
}
if (isDown && vkCode == VK_F2)
{
globalDebugState.paused = !globalDebugState.paused;
}
if (isDown && vkCode == VK_F3)
{
globalGamePaused = !globalGamePaused;
}
}
default:
{
TranslateMessage(&message);
DispatchMessage(&message);
}
}
}
EndArray(frameArena, KeyStateMessage, ret);
return ret;
}
#if 0
//int __stdcall WiaaanMainCRTStartup(void)
#endif
int CALLBACK WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR commandLine, int showCode)
{
printf("do we work?\n");
#if 0
unsigned short __stdcall RtlCaptureStackBackTrace(
unsigned long FramesToSkip,
unsigned long FramesToCapture,
void ** BackTrace,
unsigned long *BackTraceHash
);
AllocConsole();
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
Assert(hStdout != INVALID_HANDLE_VALUE);
Assert(GetConsoleScreenBufferInfo(hStdout, &csbiInfo));
DWORD err0r = GetLastError();
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csbiInfo.dwSize);
Assert(SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_INTENSITY));
LPSTR lpszPrompt1 = "Type a line and press Enter, or q to quit: ";
DWORD cWritten;
Assert(WriteFile(hStdout, lpszPrompt1, lstrlenA(lpszPrompt1), &cWritten, NULL));
#endif
u32 constantMemorySize = GigaBytes(1);
u32 frameMemorySize = MegaBytes(100);
void *constantMemory = VirtualAlloc(0, constantMemorySize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
Arena *constantArena = InitArena(constantMemory, constantMemorySize);
void *frameMem = VirtualAlloc(0, frameMemorySize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
frameArena = InitArena(frameMem, frameMemorySize);
Assert(frameMem);
Assert(constantMemory);
globalAlloc = PushStruct(constantArena, BuddyAllocator);
*globalAlloc = CreateBuddyAllocator(constantArena, MegaBytes(128), KiloBytes(64));
//TestAllocator(&buddyAlloc);
void *debugMemory = VirtualAlloc(0, MegaBytes(300), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
globalDebugState.arena = InitArena(debugMemory, MegaBytes(300));
Assert(debugMemory);
InitDebug();
ResetDebugState();
// setting up windows timing stuff
UINT desiredSchedulerMS = 1;
bool sleepIsGranular = (timeBeginPeriod(desiredSchedulerMS) == TIMERR_NOERROR);
LARGE_INTEGER perfCountFrequencyResult;
QueryPerformanceFrequency(&perfCountFrequencyResult);
globalPerformanceCountFrequency = perfCountFrequencyResult.QuadPart;
#if 0
const u32 threadCount = 3 - 1;
ThreadInfo threadInfo[1]; //threadCount
semaphoreHandle = CreateSemaphoreEx(0, 0, threadCount, 0, 0, SEMAPHORE_ALL_ACCESS);
for (int threadIndex = 0; threadIndex < threadCount; ++threadIndex)
{
threadInfo[threadIndex].threadIndex = threadIndex;
threadInfo->semaphoreHandle = semaphoreHandle;
DWORD threadID;
HANDLE threadHandle = CreateThread(0, 0, ThreadProc, &(threadInfo[threadIndex]), 0, &threadID);
}