Debian Codegraph @

src/platforms/rcore_desktop_win32.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rcore_desktop_win32 - Functions to manage window, graphics device and inputs
4 *
5 * PLATFORM: DESKTOP: WIN32
6 * - Windows (Win32, Win64)
7 *
8 * LIMITATIONS:
9 * - Initial development stage, lot of functionality missing
10 * - No support for MOUSE_BUTTON_FORWARD/MOUSE_BUTTON_BACK
11 *
12 * POSSIBLE IMPROVEMENTS:
13 * - Improvement 01
14 * - Improvement 02
15 *
16 * CONFIGURATION:
17 * #define RCORE_PLATFORM_CUSTOM_FLAG
18 * Custom flag for rcore on target platform -not used-
19 *
20 * DEPENDENCIES:
21 * - Win32 API (windows.h)
22 *
23 *
24 * LICENSE: zlib/libpng
25 *
26 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5) and contributors
27 *
28 * This software is provided "as-is", without any express or implied warranty. In no event
29 * will the authors be held liable for any damages arising from the use of this software.
30 *
31 * Permission is granted to anyone to use this software for any purpose, including commercial
32 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
33 *
34 * 1. The origin of this software must not be misrepresented; you must not claim that you
35 * wrote the original software. If you use this software in a product, an acknowledgment
36 * in the product documentation would be appreciated but is not required.
37 *
38 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
39 * as being the original software.
40 *
41 * 3. This notice may not be removed or altered from any source distribution.
42 *
43 **********************************************************************************************/
44
45 // Move windows.h symbols to new names to avoid redefining the same names as raylib
46 #define CloseWindow CloseWindowWin32
47 #define Rectangle RectangleWin32
48 #define ShowCursor ShowCursorWin32
49 #define DrawTextA DrawTextAWin32
50 #define DrawTextW DrawTextWin32
51 #define DrawTextExA DrawTextExAWin32
52 #define DrawTextExW DrawTextExWin32
53
54 #define WIN32_LEAN_AND_MEAN
55 #include <windows.h>
56
57 #undef CloseWindow // raylib symbol collision
58 #undef Rectangle // raylib symbol collision
59 #undef ShowCursor // raylib symbol collision
60 #undef LoadImage // raylib symbol collision
61 #undef DrawText // raylib symbol collision
62 #undef DrawTextA
63 #undef DrawTextW
64 #undef DrawTextEx // raylib symbol collision
65 #undef DrawTextExA
66 #undef DrawTextExW
67
68 #include <windowsx.h>
69 #include <shellscalingapi.h>
70 #include <versionhelpers.h>
71
72 #include <malloc.h> // Required for alloca()
73
74 #if !defined(GRAPHICS_API_OPENGL_SOFTWARE)
75 #include <GL/gl.h>
76 #endif
77
78 //----------------------------------------------------------------------------------
79 // Types and Structures Definition
80 //----------------------------------------------------------------------------------
81
82 // NOTE: appScreenSize is the last screen size requested by the app,
83 // the backend must keep the client area this size (after DPI scaling is applied)
84 // when the window isn't fullscreen/maximized/minimized
85 typedef struct {
86 HWND hwnd; // Window handler
87 HDC hdc; // Graphic context handler
88 HGLRC glContext; // OpenGL context handler
89
90 // Software renderer variables
91 HDC hdcmem; // Memory graphic context handler
92 HBITMAP hbitmap; // GDI bitmap handler
93 unsigned int *pixels; // Pointer to pixel data buffer (BGRA format)
94
95 unsigned int appScreenWidth;
96 unsigned int appScreenHeight;
97 unsigned int desiredFlags;
98
99 LARGE_INTEGER timerFrequency;
100 } PlatformData;
101
102 // Define WGL function pointer types (no wglext.h needed)
103 typedef HGLRC (WINAPI *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int *);
104 typedef BOOL (WINAPI *PFNWGLCHOOSEPIXELFORMATARBPROC)(HDC, const int *, const FLOAT *, UINT, int *, UINT *);
105 typedef BOOL (WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int);
106 typedef const char *(WINAPI *PFNWGLGETEXTENSIONSSTRINGARBPROC)(HDC hdc);
107
108 //----------------------------------------------------------------------------------
109 // Global Variables Definition
110 //----------------------------------------------------------------------------------
111 extern CoreData CORE; // Global CORE state context
112
113 static PlatformData platform = { 0 }; // Platform specific data
114
115 // Required WGL functions
116 static PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
117 static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = NULL;
118 static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
119 static PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = NULL;
120
121 // --------------------------------------------------------------------------------
122 // This part of the file contains pure functions that never access global state
123 // This distinction helps keep the backend maintainable as the inputs and outputs
124 // of every function called in this section can be fully derived from the call-site alone
125 // --------------------------------------------------------------------------------
126
127 // Prevent any code in this part of the file from accessing the global CORE state
128 #define CORE DONT_USE_CORE_HERE
129
130 //----------------------------------------------------------------------------------
131 // Defines and Macros
132 //----------------------------------------------------------------------------------
133 #define A_TO_W_ALLOCA(outWstr, inAnsi) do { \
134 size_t outLen = AToWLen(inAnsi); \
135 outWstr = (WCHAR *)alloca(sizeof(WCHAR)*(outLen + 1)); \
136 AToWCopy(inAnsi, outWstr, outLen); \
137 outWstr[outLen] = 0; \
138 } while (0)
139
140 #define STYLE_MASK_ALL 0xffffffff
141 #define STYLE_MASK_READONLY (WS_MINIMIZE | WS_MAXIMIZE)
142 #define STYLE_MASK_WRITABLE (~STYLE_MASK_READONLY)
143
144 #define STYLE_FLAGS_RESIZABLE (WS_THICKFRAME | WS_MAXIMIZEBOX)
145
146 #define STYLE_FLAGS_UNDECORATED_OFF (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX)
147 #define STYLE_FLAGS_UNDECORATED_ON WS_POPUP
148
149 #define WINDOW_STYLE_EX 0
150
151 #define CLASS_NAME L"raylibWindow"
152
153 #define FLAG_MASK_OPTIONAL (FLAG_VSYNC_HINT)
154 #define FLAG_MASK_REQUIRED ~(FLAG_MASK_OPTIONAL)
155
156 // Flags that have no operations to perform during an update
157 #define FLAG_MASK_NO_UPDATE (FLAG_WINDOW_HIGHDPI | FLAG_MSAA_4X_HINT)
158
159 #define WGL_DRAW_TO_WINDOW_ARB 0x2001
160 #define WGL_ACCELERATION_ARB 0x2003
161 #define WGL_SUPPORT_OPENGL_ARB 0x2010
162 #define WGL_DOUBLE_BUFFER_ARB 0x2011
163 #define WGL_PIXEL_TYPE_ARB 0x2013
164 #define WGL_COLOR_BITS_ARB 0x2014
165 #define WGL_RED_BITS_ARB 0x2015
166 #define WGL_RED_SHIFT_ARB 0x2016
167 #define WGL_GREEN_BITS_ARB 0x2017
168 #define WGL_GREEN_SHIFT_ARB 0x2018
169 #define WGL_BLUE_BITS_ARB 0x2019
170 #define WGL_BLUE_SHIFT_ARB 0x201a
171 #define WGL_ALPHA_BITS_ARB 0x201b
172 #define WGL_ALPHA_SHIFT_ARB 0x201c
173 #define WGL_DEPTH_BITS_ARB 0x2022
174 #define WGL_STENCIL_BITS_ARB 0x2023
175 #define WGL_TYPE_RGBA_ARB 0x202b
176
177 // Context acceleration types
178 #define WGL_NO_ACCELERATION_ARB 0x2025 // OpenGL 1.1 GDI software rasterizer
179 #define WGL_GENERIC_ACCELERATION_ARB 0x2026
180 #define WGL_FULL_ACCELERATION_ARB 0x2027 // OpenGL hardware-accelerated, using GPU-drivers provided by vendor
181
182 // WGL_ARB_multisample extension supported
183 #define WGL_SAMPLE_BUFFERS_ARB 0x2041 // Multisampling: 1 if multisample buffers are supported
184 #define WGL_SAMPLES_ARB 0x2042 // Multisampling: Number of samples per pixel (4, 8, 16)
185
186 // WGL_ARB_framebuffer_sRGB extension supported
187 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20a9 // GL_TRUE if the framebuffer can do sRGB conversion
188
189 #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
190 #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
191 #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
192 #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
193 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
194 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
195 #define WGL_CONTEXT_ES_PROFILE_BIT_EXT 0x00000004
196 #define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004
197
198 //----------------------------------------------------------------------------------
199 // Types and Structures Definition
200 //----------------------------------------------------------------------------------
201 // Maximize-minimize request types
202 typedef enum {
203 MIZED_NONE,
204 MIZED_MIN,
205 MIZED_MAX
206 } Mized;
207
208 // Flag operations
209 // NOTE: Some ops need to be deferred
210 typedef struct {
211 DWORD set;
212 DWORD clear;
213 } FlagsOp;
214
215 // Monitor info type
216 typedef struct {
217 HMONITOR needle;
218 int index;
219 int matchIndex;
220 RECT rect;
221 } MonitorInfo;
222
223 //----------------------------------------------------------------------------------
224 // Module Internal Functions Declaration
225 //----------------------------------------------------------------------------------
226 // Get ASCII to WCHAR length
227 static size_t AToWLen(const char *ascii)
228 {
229 int sizeNeeded = MultiByteToWideChar(CP_UTF8, 0, ascii, -1, NULL, 0);
230
231 if (sizeNeeded < 0) TRACELOG(LOG_ERROR, "WIN32: Failed to calculate wide length [ERROR: %u]", GetLastError());
232
233 return sizeNeeded;
234 }
235
236 // Copy ASCII to WCHAR string
237 static void AToWCopy(const char *ascii, wchar_t *outPtr, size_t outLen)
238 {
239 int size = MultiByteToWideChar(CP_UTF8, 0, ascii, -1, outPtr, (int)outLen);
240 if (size != outLen) TRACELOG(LOG_WARNING, "WIN32: Failed to convert %i UTF-8 chars to WCHAR, converted %i chars", outLen, size);
241 }
242
243 static bool DecoratedFromStyle(DWORD style)
244 {
245 if (style & STYLE_FLAGS_UNDECORATED_ON)
246 {
247 if (style & STYLE_FLAGS_UNDECORATED_OFF) TRACELOG(LOG_ERROR, "WIN32: FLAGS: Style 0x%x has both undecorated on/off flags", style);
248 return false; // Not decorated
249 }
250
251 DWORD masked = (style & STYLE_FLAGS_UNDECORATED_OFF);
252 if (STYLE_FLAGS_UNDECORATED_OFF != masked) TRACELOG(LOG_ERROR, "WIN32: FLAGS: Style 0x%x is missing flags 0x%x", masked, masked ^ STYLE_FLAGS_UNDECORATED_OFF);
253
254 return true; // Decorated
255 }
256
257 // Get window style from required flags
258 static DWORD MakeWindowStyle(unsigned flags)
259 {
260 // Flag is not needed because there are no child windows,
261 // but supposedly it improves efficiency, plus, windows adds this
262 // flag automatically anyway so it keeps flags in sync with the OS
263 DWORD style = WS_CLIPSIBLINGS;
264
265 style |= (flags & FLAG_WINDOW_HIDDEN)? 0 : WS_VISIBLE;
266 style |= (flags & FLAG_WINDOW_RESIZABLE)? STYLE_FLAGS_RESIZABLE : 0;
267 style |= (flags & FLAG_WINDOW_UNDECORATED)? STYLE_FLAGS_UNDECORATED_ON : STYLE_FLAGS_UNDECORATED_OFF;
268
269 // Minimized takes precedence over maximized
270 int mized = MIZED_NONE;
271 if (flags & FLAG_WINDOW_MINIMIZED) mized = MIZED_MIN;
272 else if (flags & FLAG_WINDOW_MAXIMIZED) mized = MIZED_MAX;
273
274 switch (mized)
275 {
276 case MIZED_NONE: break;
277 case MIZED_MIN: style |= WS_MINIMIZE; break;
278 case MIZED_MAX: style |= WS_MAXIMIZE; break;
279 default: break;
280 }
281
282 return style;
283 }
284
285 // Check flags state, enforces that the actual window/platform state is in sync with raylib's flags
286 static void CheckFlags(const char *context, HWND hwnd, DWORD flags, DWORD expectedStyle, DWORD styleCheckMask)
287 {
288 DWORD styleFromFlags = MakeWindowStyle(flags);
289 if ((styleFromFlags & styleCheckMask) != (expectedStyle & styleCheckMask))
290 {
291 TRACELOG(LOG_ERROR, "WIN32: FLAGS: %s: window flags (0x%x) produced style 0x%x which != expected 0x%x (diff=0x%x, mask=0x%x)",
292 context, flags, styleFromFlags & styleCheckMask, expectedStyle & styleCheckMask,
293 (styleFromFlags & styleCheckMask) ^ (expectedStyle & styleCheckMask), styleCheckMask);
294 }
295
296 SetLastError(0);
297 LONG actualStyle = (LONG)GetWindowLongPtrW(hwnd, GWL_STYLE);
298 if ((actualStyle & styleCheckMask) != (expectedStyle & styleCheckMask))
299 {
300 TRACELOG(LOG_ERROR, "WIN32: FLAGS: %s: expected style 0x%x but got 0x%x (diff=0x%x, mask=0x%x, lasterror=%lu)",
301 context, expectedStyle & styleCheckMask, actualStyle & styleCheckMask,
302 (expectedStyle & styleCheckMask) ^ (actualStyle & styleCheckMask),
303 styleCheckMask, GetLastError());
304 }
305
306 if (styleCheckMask & WS_MINIMIZE)
307 {
308 bool isIconic = IsIconic(hwnd);
309 bool styleMinimized = !!(WS_MINIMIZE & actualStyle);
310 if (isIconic != styleMinimized) TRACELOG(LOG_ERROR, "WIN32: FLAGS: IsIconic(%d) != WS_MINIMIZED(%d)", isIconic, styleMinimized);
311 }
312
313 if (styleCheckMask & WS_MAXIMIZE)
314 {
315 WINDOWPLACEMENT placement;
316 placement.length = sizeof(placement);
317 if (!GetWindowPlacement(hwnd, &placement))
318 {
319 TRACELOG(LOG_ERROR, "WIN32: FLAGS: %s failed, error=%lu", "GetWindowPlacement", GetLastError());
320 }
321 bool placementMaximized = (placement.showCmd == SW_SHOWMAXIMIZED);
322 bool styleMaximized = WS_MAXIMIZE & actualStyle;
323 if (placementMaximized != styleMaximized)
324 {
325 TRACELOG(LOG_ERROR, "WIN32: FLAGS: Maximized state desync, placement maximized=%d (showCmd=%lu) style maximized=%d",
326 placementMaximized, placement.showCmd, styleMaximized);
327 }
328 }
329 }
330
331 // Calculate window size (with borders, title-bar...) from desired client size (framebuffer size)
332 static SIZE CalcWindowSize(UINT dpi, SIZE clientSize, DWORD style)
333 {
334 RECT rect = { 0, 0, clientSize.cx, clientSize.cy };
335
336 int result = AdjustWindowRectExForDpi(&rect, style, 0, WINDOW_STYLE_EX, dpi);
337 if (result == 0) TRACELOG(LOG_ERROR, "WIN32: Failed to adjust window rect [ERROR: %lu]", GetLastError());
338
339 return (SIZE){ rect.right - rect.left, rect.bottom - rect.top };
340 }
341
342 // Update window size if required
343 // NOTE: Returns true if the window size was updated, false otherwise
344 static bool UpdateWindowSize(int mode, HWND hwnd, int width, int height, unsigned flags)
345 {
346 if (flags & FLAG_WINDOW_MINIMIZED) return false;
347
348 if (flags & FLAG_WINDOW_MAXIMIZED)
349 {
350 CheckFlags("UpdateWindowSize(maximized)", hwnd, flags, MakeWindowStyle(flags), STYLE_MASK_ALL);
351 return false;
352 }
353
354 if (flags & FLAG_BORDERLESS_WINDOWED_MODE)
355 {
356 MONITORINFO info = { 0 };
357 HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY);
358 info.cbSize = sizeof(info);
359 if (!GetMonitorInfoW(monitor, &info)) TRACELOG(LOG_ERROR, "WIN32: Failed to get monitor info [ERROR: %lu]", GetLastError());
360
361 RECT windowRect = { 0 };
362 if (!GetWindowRect(hwnd, &windowRect)) TRACELOG(LOG_ERROR, "WIN32: Failed to get window rect [ERROR: %lu]", GetLastError());
363
364 if ((windowRect.left == info.rcMonitor.left) &&
365 (windowRect.top == info.rcMonitor.top) &&
366 ((windowRect.right - windowRect.left) == (info.rcMonitor.right - info.rcMonitor.left)) &&
367 ((windowRect.bottom - windowRect.top) == (info.rcMonitor.bottom - info.rcMonitor.top))) return false;
368
369 if (!SetWindowPos(hwnd, HWND_TOP,
370 info.rcMonitor.left, info.rcMonitor.top,
371 info.rcMonitor.right - info.rcMonitor.left,
372 info.rcMonitor.bottom - info.rcMonitor.top,
373 SWP_NOOWNERZORDER))
374 {
375 TRACELOG(LOG_ERROR, "WIN32: Failed to set window position [ERROR: %lu]", GetLastError());
376 }
377
378 return true;
379 }
380
381 // Get size in pixels from points, considering high-dpi
382 UINT dpi = GetDpiForWindow(hwnd);
383 float dpiScale = ((float)dpi)/96.0f;
384 bool dpiScaling = flags & FLAG_WINDOW_HIGHDPI;
385 SIZE desiredSize = {
386 .cx = dpiScaling? (int)((float)width*dpiScale) : width,
387 .cy = dpiScaling? (int)((float)height*dpiScale) : height
388 };
389
390 // Get client size (framebuffer inside the window)
391 RECT rect = { 0 };
392 GetClientRect(hwnd, &rect);
393 SIZE clientSize = { rect.right, rect.bottom };
394
395 // If client size is alread desired size, no need to update
396 if ((clientSize.cx == desiredSize.cx) || (clientSize.cy == desiredSize.cy)) return false;
397
398 TRACELOG(LOG_INFO, "WIN32: Restoring client size from [%dx%d] to [%dx%d] (dpi:%lu dpiScaling:%d app:%ix%i)",
399 clientSize.cx, clientSize.cy, desiredSize.cx, desiredSize.cy, dpi, dpiScaling, width, height);
400
401 // Calculate window size from desired framebuffer size and window flags
402 SIZE windowSize = CalcWindowSize(dpi, desiredSize, MakeWindowStyle(flags));
403 POINT windowPos = { 0 };
404 UINT swpFlags = SWP_NOZORDER | SWP_FRAMECHANGED;
405
406 if (mode == 0) // UPDATE_WINDOW_FIRST
407 {
408 HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY);
409 if (!monitor) TRACELOG(LOG_ERROR, "WIN32: Failed to get monitor from window [ERROR: %lu]", GetLastError());
410
411 MONITORINFO info = { 0 };
412 info.cbSize = sizeof(info);
413 if (!GetMonitorInfoW(monitor, &info)) TRACELOG(LOG_ERROR, "WIN32: Failed to get monitor info [ERROR: %lu]", GetLastError());
414
415 #define MAX(a,b) (((a)>(b))? (a):(b))
416
417 LONG monitorWidth = info.rcMonitor.right - info.rcMonitor.left;
418 LONG monitorHeight = info.rcMonitor.bottom - info.rcMonitor.top;
419 windowPos = (POINT){
420 MAX(0, (monitorWidth - windowSize.cx)/2),
421 MAX(0, (monitorHeight - windowSize.cy)/2),
422 };
423 }
424 else swpFlags |= SWP_NOMOVE;
425
426 // WARNING: This code must be called after swInit() has been called, after InitPlatform() in [rcore]
427 SetWindowPos(hwnd, NULL, windowPos.x, windowPos.y, windowSize.cx, windowSize.cy, SWP_NOMOVE | SWP_NOZORDER);
428
429 return true;
430 }
431
432 // Check if running in Windows 10 version 1703 (Creators Update)
433 static BOOL IsWindows10Version1703OrGreaterWin32(void)
434 {
435 HMODULE ntdll = LoadLibraryW(L"ntdll.dll");
436
437 DWORD (*Verify)(RTL_OSVERSIONINFOEXW*, ULONG, ULONGLONG) =
438 (DWORD (*)(RTL_OSVERSIONINFOEXW*, ULONG, ULONGLONG))GetProcAddress(ntdll, "RtlVerifyVersionInfo");
439 if (!Verify)
440 {
441 TRACELOG(LOG_ERROR, "WIN32: Failed to verify Windows version [ERROR: %lu]", GetLastError());
442 return 0;
443 }
444
445 RTL_OSVERSIONINFOEXW osvi = { 0 };
446 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
447 osvi.dwMajorVersion = 10;
448 osvi.dwMinorVersion = 0;
449 osvi.dwBuildNumber = 15063; // Build 15063 corresponds to Windows 10 version 1703 (Creators Update)
450
451 DWORDLONG cond = 0;
452 VER_SET_CONDITION(cond, VER_MAJORVERSION, VER_GREATER_EQUAL);
453 VER_SET_CONDITION(cond, VER_MINORVERSION, VER_GREATER_EQUAL);
454 VER_SET_CONDITION(cond, VER_BUILDNUMBER, VER_GREATER_EQUAL);
455
456 return 0 == (*Verify)(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, cond);
457 }
458
459 // Get OpenGL function pointers
460 static void *WglGetProcAddress(const char *procname)
461 {
462 void *proc = (void *)wglGetProcAddress(procname);
463
464 if ((proc == NULL) ||
465 // NOTE: Some GPU drivers could return following
466 // invalid sentinel values instead of NULL
467 (proc == (void *)0x1) ||
468 (proc == (void *)0x2) ||
469 (proc == (void *)0x3) ||
470 (proc == (void *)-1))
471 {
472 // TODO: Keep gl module pointer as global platform data?
473 HMODULE glModule = LoadLibraryW(L"opengl32.dll");
474 proc = (void *)GetProcAddress(glModule, procname);
475
476 //if (proc == NULL) TRACELOG(LOG_ERROR, "GL: GetProcAddress() failed to get %s [%p], error=%u", procname, proc, GetLastError());
477 //else TRACELOG(LOG_INFO, "GL: Found entry point for %s [%p]", procname, proc);
478 }
479
480 return proc;
481 }
482
483 // Get key from wparam (mapping)
484 static KeyboardKey GetKeyFromWparam(WPARAM wparam)
485 {
486 switch (wparam)
487 {
488 /* case VK_LBUTTON: return KEY_; */
489 /* case VK_RBUTTON: return KEY_; */
490 /* case VK_CANCEL: return KEY_; */
491 /* case VK_MBUTTON: return KEY_; */
492 /* case VK_XBUTTON1: return KEY_; */
493 /* case VK_XBUTTON2: return KEY_; */
494 /* case VK_BACK: return KEY_; */
495 /* case VK_TAB: return KEY_; */
496 /* case VK_CLEAR: return KEY_; */
497 case VK_RETURN: return KEY_ENTER;
498 /* case VK_SHIFT: return KEY_; */
499 /* case VK_CONTROL: return KEY_; */
500 /* case VK_MENU: return KEY_; */
501 /* case VK_PAUSE: return KEY_; */
502 /* case VK_CAPITAL: return KEY_; */
503 /* case VK_KANA: return KEY_; */
504 /* case VK_HANGUL: return KEY_; */
505 /* case VK_IME_ON: return KEY_; */
506 /* case VK_JUNJA: return KEY_; */
507 /* case VK_FINAL: return KEY_; */
508 /* case VK_HANJA: return KEY_; */
509 /* case VK_KANJI: return KEY_; */
510 /* case VK_IME_OFF: return KEY_; */
511 case VK_ESCAPE: return KEY_ESCAPE;
512 /* case VK_CONVERT: return KEY_; */
513 /* case VK_NONCONVERT: return KEY_; */
514 /* case VK_ACCEPT: return KEY_; */
515 /* case VK_MODECHANGE: return KEY_; */
516 case VK_SPACE: return KEY_SPACE;
517 /* case VK_PRIOR: return KEY_; */
518 /* case VK_NEXT: return KEY_; */
519 /* case VK_END: return KEY_; */
520 /* case VK_HOME: return KEY_; */
521 case VK_LEFT: return KEY_LEFT;
522 case VK_UP: return KEY_UP;
523 case VK_RIGHT: return KEY_RIGHT;
524 case VK_DOWN: return KEY_DOWN;
525 /* case VK_SELECT: return KEY_; */
526 /* case VK_PRINT: return KEY_; */
527 /* case VK_EXECUTE: return KEY_; */
528 /* case VK_SNAPSHOT: return KEY_; */
529 /* case VK_INSERT: return KEY_; */
530 /* case VK_DELETE: return KEY_; */
531 /* case VK_HELP: return KEY_; */
532 case '0': return KEY_ZERO;
533 case '1': return KEY_ONE;
534 case '2': return KEY_TWO;
535 case '3': return KEY_THREE;
536 case '4': return KEY_FOUR;
537 case '5': return KEY_FIVE;
538 case '6': return KEY_SIX;
539 case '7': return KEY_SEVEN;
540 case '8': return KEY_EIGHT;
541 case '9': return KEY_NINE;
542 /* case 0x3A-40: return KEY_; */
543 case 'A': return KEY_A;
544 case 'B': return KEY_B;
545 case 'C': return KEY_C;
546 case 'D': return KEY_D;
547 case 'E': return KEY_E;
548 case 'F': return KEY_F;
549 case 'G': return KEY_G;
550 case 'H': return KEY_H;
551 case 'I': return KEY_I;
552 case 'J': return KEY_J;
553 case 'K': return KEY_K;
554 case 'L': return KEY_L;
555 case 'M': return KEY_M;
556 case 'N': return KEY_N;
557 case 'O': return KEY_O;
558 case 'P': return KEY_P;
559 case 'Q': return KEY_Q;
560 case 'R': return KEY_R;
561 case 'S': return KEY_S;
562 case 'T': return KEY_T;
563 case 'U': return KEY_U;
564 case 'V': return KEY_V;
565 case 'W': return KEY_W;
566 case 'X': return KEY_X;
567 case 'Y': return KEY_Y;
568 case 'Z': return KEY_Z;
569 /* case VK_LWIN: return KEY_; */
570 /* case VK_RWIN: return KEY_; */
571 /* case VK_APPS: return KEY_; */
572 /* case VK_SLEEP: return KEY_; */
573 /* case VK_NUMPAD0: return KEY_; */
574 /* case VK_NUMPAD1: return KEY_; */
575 /* case VK_NUMPAD2: return KEY_; */
576 /* case VK_NUMPAD3: return KEY_; */
577 /* case VK_NUMPAD4: return KEY_; */
578 /* case VK_NUMPAD5: return KEY_; */
579 /* case VK_NUMPAD6: return KEY_; */
580 /* case VK_NUMPAD7: return KEY_; */
581 /* case VK_NUMPAD8: return KEY_; */
582 /* case VK_NUMPAD9: return KEY_; */
583 /* case VK_MULTIPLY: return KEY_; */
584 /* case VK_ADD: return KEY_; */
585 /* case VK_SEPARATOR: return KEY_; */
586 /* case VK_SUBTRACT: return KEY_; */
587 /* case VK_DECIMAL: return KEY_; */
588 /* case VK_DIVIDE: return KEY_; */
589 /* case VK_F1: return KEY_; */
590 /* case VK_F2: return KEY_; */
591 /* case VK_F3: return KEY_; */
592 /* case VK_F4: return KEY_; */
593 /* case VK_F5: return KEY_; */
594 /* case VK_F6: return KEY_; */
595 /* case VK_F7: return KEY_; */
596 /* case VK_F8: return KEY_; */
597 /* case VK_F9: return KEY_; */
598 /* case VK_F10: return KEY_; */
599 /* case VK_F11: return KEY_; */
600 /* case VK_F12: return KEY_; */
601 /* case VK_F13: return KEY_; */
602 /* case VK_F14: return KEY_; */
603 /* case VK_F15: return KEY_; */
604 /* case VK_F16: return KEY_; */
605 /* case VK_F17: return KEY_; */
606 /* case VK_F18: return KEY_; */
607 /* case VK_F19: return KEY_; */
608 /* case VK_F20: return KEY_; */
609 /* case VK_F21: return KEY_; */
610 /* case VK_F22: return KEY_; */
611 /* case VK_F23: return KEY_; */
612 /* case VK_F24: return KEY_; */
613 /* case VK_NUMLOCK: return KEY_; */
614 /* case VK_SCROLL: return KEY_; */
615 /* case VK_LSHIFT: return KEY_; */
616 /* case VK_RSHIFT: return KEY_; */
617 /* case VK_LCONTROL: return KEY_; */
618 /* case VK_RCONTROL: return KEY_; */
619 /* case VK_LMENU: return KEY_; */
620 /* case VK_RMENU: return KEY_; */
621 /* case VK_BROWSER_BACK: return KEY_; */
622 /* case VK_BROWSER_FORWARD: return KEY_; */
623 /* case VK_BROWSER_REFRESH: return KEY_; */
624 /* case VK_BROWSER_STOP: return KEY_; */
625 /* case VK_BROWSER_SEARCH: return KEY_; */
626 /* case VK_BROWSER_FAVORITES: return KEY_; */
627 /* case VK_BROWSER_HOME: return KEY_; */
628 /* case VK_VOLUME_MUTE: return KEY_; */
629 /* case VK_VOLUME_DOWN: return KEY_; */
630 /* case VK_VOLUME_UP: return KEY_; */
631 /* case VK_MEDIA_NEXT_TRACK: return KEY_; */
632 /* case VK_MEDIA_PREV_TRACK: return KEY_; */
633 /* case VK_MEDIA_STOP: return KEY_; */
634 /* case VK_MEDIA_PLAY_PAUSE: return KEY_; */
635 /* case VK_LAUNCH_MAIL: return KEY_; */
636 /* case VK_LAUNCH_MEDIA_SELECT: return KEY_; */
637 /* case VK_LAUNCH_APP1: return KEY_; */
638 /* case VK_LAUNCH_APP2: return KEY_; */
639 /* case VK_OEM_1: return KEY_; */
640 /* case VK_OEM_PLUS: return KEY_; */
641 /* case VK_OEM_COMMA: return KEY_; */
642 /* case VK_OEM_MINUS: return KEY_; */
643 /* case VK_OEM_PERIOD: return KEY_; */
644 /* case VK_OEM_2: return KEY_; */
645 /* case VK_OEM_3: return KEY_; */
646 /* case VK_OEM_4: return KEY_; */
647 /* case VK_OEM_5: return KEY_; */
648 /* case VK_OEM_6: return KEY_; */
649 /* case VK_OEM_7: return KEY_; */
650 /* case VK_OEM_8: return KEY_; */
651 /* case VK_OEM_102: return KEY_; */
652 /* case VK_PROCESSKEY: return KEY_; */
653 /* case VK_PACKET: return KEY_; */
654 /* case VK_ATTN: return KEY_; */
655 /* case VK_CRSEL: return KEY_; */
656 /* case VK_EXSEL: return KEY_; */
657 /* case VK_EREOF: return KEY_; */
658 /* case VK_PLAY: return KEY_; */
659 /* case VK_ZOOM: return KEY_; */
660 /* case VK_NONAME: return KEY_; */
661 /* case VK_PA1: return KEY_; */
662 /* case VK_OEM_CLEAR: return KEY_; */
663 default: return KEY_NULL;
664 }
665 }
666
667 // Get cursor name
668 static LPCWSTR GetCursorName(int cursor)
669 {
670 LPCWSTR name = (LPCWSTR)IDC_ARROW;
671
672 switch (cursor)
673 {
674 case MOUSE_CURSOR_DEFAULT: name = (LPCWSTR)IDC_ARROW; break;
675 case MOUSE_CURSOR_ARROW: name = (LPCWSTR)IDC_ARROW; break;
676 case MOUSE_CURSOR_IBEAM: name = (LPCWSTR)IDC_IBEAM; break;
677 case MOUSE_CURSOR_CROSSHAIR: name = (LPCWSTR)IDC_CROSS; break;
678 case MOUSE_CURSOR_POINTING_HAND: name = (LPCWSTR)IDC_HAND; break;
679 case MOUSE_CURSOR_RESIZE_EW: name = (LPCWSTR)IDC_SIZEWE; break;
680 case MOUSE_CURSOR_RESIZE_NS: name = (LPCWSTR)IDC_SIZENS; break;
681 case MOUSE_CURSOR_RESIZE_NWSE: name = (LPCWSTR)IDC_SIZENWSE; break;
682 case MOUSE_CURSOR_RESIZE_NESW: name = (LPCWSTR)IDC_SIZENESW; break;
683 case MOUSE_CURSOR_RESIZE_ALL: name = (LPCWSTR)IDC_SIZEALL; break;
684 case MOUSE_CURSOR_NOT_ALLOWED: name = (LPCWSTR)IDC_NO; break;
685 default: break;
686 }
687
688 return name;
689 }
690
691 // Count monitors process
692 // NOTE: Required by GetMonitorCount()
693 static BOOL CALLBACK CountMonitorsProc(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM lparam)
694 {
695 int *count = (int *)lparam;
696 *count += 1;
697
698 // Always return TRUE to continue the loop, otherwise, the caller
699 // can't distinguish between stopping the loop and an error
700 return TRUE;
701 }
702
703 // Find monitor process
704 // NOTE: Required by GetCurrentMonitor()
705 static BOOL CALLBACK FindMonitorProc(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM lparam)
706 {
707 MonitorInfo *monitor = (MonitorInfo *)lparam;
708
709 if (handle == monitor->needle)
710 {
711 monitor->matchIndex = monitor->index;
712 monitor->rect = *rect;
713 }
714
715 monitor->index += 1;
716
717 // Always return TRUE to continue the loop, otherwise, the caller
718 // can't distinguish between stopping the loop and an error
719 return TRUE;
720 }
721
722 // Get style changed required operations flags
723 // NOTE: Required for deferred operations
724 static void GetStyleChangeFlagOps(DWORD coreWindowFlags, STYLESTRUCT *style, FlagsOp *deferredFlags)
725 {
726 // Check window resizable flag change
727 bool resizable = (coreWindowFlags & FLAG_WINDOW_RESIZABLE);
728 bool resizableOld = ((style->styleOld & STYLE_FLAGS_RESIZABLE) != 0);
729 bool resizableNew = ((style->styleNew & STYLE_FLAGS_RESIZABLE) != 0);
730 if (resizable != resizableOld) TRACELOG(LOG_ERROR, "WIN32: Expected resizable %u but got %u", resizable, resizableOld);
731 if (resizableOld != resizableNew)
732 {
733 if (resizableNew) deferredFlags->set |= FLAG_WINDOW_RESIZABLE;
734 else deferredFlags->clear |= FLAG_WINDOW_RESIZABLE;
735 }
736
737 // Check window decorated flag change
738 bool decorated = (0 == (coreWindowFlags & FLAG_WINDOW_UNDECORATED));
739 bool decoratedOld = DecoratedFromStyle(style->styleOld);
740 bool decoratedNew = DecoratedFromStyle(style->styleNew);
741 if (decorated != decoratedOld) TRACELOG(LOG_ERROR, "WIN32: Expected decorated %u but got %u", decorated, decoratedOld);
742 if (decoratedOld != decoratedNew)
743 {
744 if (decoratedNew) deferredFlags->clear |= FLAG_WINDOW_UNDECORATED;
745 else deferredFlags->set |= FLAG_WINDOW_UNDECORATED;
746 }
747
748 // Check window hidden flag change
749 bool hidden = (coreWindowFlags & FLAG_WINDOW_HIDDEN);
750 bool hiddenOld = ((style->styleOld & WS_VISIBLE) == 0);
751 bool hiddenNew = ((style->styleNew & WS_VISIBLE) == 0);
752 if (hidden != hiddenOld) TRACELOG(LOG_ERROR, "WIN32: Expected hidden %u but got %u", hidden, hiddenOld);
753 if (hiddenOld != hiddenNew)
754 {
755 if (hiddenNew) deferredFlags->set |= FLAG_WINDOW_HIDDEN;
756 else deferredFlags->clear |= FLAG_WINDOW_HIDDEN;
757 }
758 }
759
760 // Adopt window resize
761 // NOTE: Call when the window is rezised, returns true
762 // if the new window size should update the desired app size
763 static bool AdoptWindowResize(unsigned flags)
764 {
765 if (flags & FLAG_WINDOW_MINIMIZED) return false;
766 if (flags & FLAG_WINDOW_MAXIMIZED) return false;
767 if (flags & FLAG_FULLSCREEN_MODE) return false;
768 if (flags & FLAG_BORDERLESS_WINDOWED_MODE) return false;
769 if (!(flags & FLAG_WINDOW_RESIZABLE)) return false;
770
771 return true;
772 }
773
774 // ---------------------------------------------------------------------------------------------
775 // Here's the end of the "pure function section", the rest of the file can access global state
776 // ---------------------------------------------------------------------------------------------
777
778 // Unlock the ability to use CORE in the rest of the file
779 #undef CORE
780
781 //----------------------------------------------------------------------------------
782 // Module Internal Functions Declaration
783 //----------------------------------------------------------------------------------
784 int InitPlatform(void); // Initialize platform (graphics, inputs and more)
785 void ClosePlatform(void); // Close platform
786
787 // Win32 process messages management function
788 static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
789
790 // Win32: Handle inputs functions
791 static void HandleKey(WPARAM wparam, LPARAM lparam, char state);
792 static void HandleMouseButton(int button, char state);
793 static void HandleRawInput(LPARAM lparam);
794 static void HandleWindowResize(HWND hwnd, int *width, int *height);
795
796 static void UpdateWindowStyle(HWND hwnd, unsigned desiredFlags);
797 static unsigned SanitizeFlags(int mode, unsigned flags);
798 static void UpdateFlags(HWND hwnd, unsigned desiredFlags, int width, int height); // Update window flags
799
800 // Check if OpenGL extension is available
801 static bool IsWglExtensionAvailable(HDC hdc, const char *extension);
802
803 //----------------------------------------------------------------------------------
804 // Module Functions Declaration
805 //----------------------------------------------------------------------------------
806 // NOTE: Functions declaration is provided by raylib.h
807
808 //----------------------------------------------------------------------------------
809 // Module Functions Definition: Window and Graphics Device
810 //----------------------------------------------------------------------------------
811
812 // Check if application should close
813 bool WindowShouldClose(void)
814 {
815 return CORE.Window.shouldClose;
816 }
817
818 // Toggle fullscreen mode
819 void ToggleFullscreen(void)
820 {
821 TRACELOG(LOG_WARNING, "WIN32: Toggle full screen functionality not implemented");
822 }
823
824 // Toggle borderless windowed mode
825 void ToggleBorderlessWindowed(void)
826 {
827 if (CORE.Window.flags & FLAG_BORDERLESS_WINDOWED_MODE) ClearWindowState(FLAG_BORDERLESS_WINDOWED_MODE);
828 else SetWindowState(FLAG_BORDERLESS_WINDOWED_MODE);
829 }
830
831 // Set window state: maximized, if resizable
832 void MaximizeWindow(void)
833 {
834 SetWindowState(FLAG_WINDOW_MAXIMIZED);
835 }
836
837 // Set window state: minimized
838 void MinimizeWindow(void)
839 {
840 SetWindowState(FLAG_WINDOW_MINIMIZED);
841 }
842
843 // Restore window from being minimized/maximized
844 void RestoreWindow(void)
845 {
846 if ((CORE.Window.flags & FLAG_WINDOW_MAXIMIZED) &&
847 (CORE.Window.flags & FLAG_WINDOW_MINIMIZED)) ClearWindowState(FLAG_WINDOW_MINIMIZED);
848 else ClearWindowState(FLAG_WINDOW_MINIMIZED | FLAG_WINDOW_MAXIMIZED);
849 }
850
851 // Set window configuration state using flags
852 void SetWindowState(unsigned int flags)
853 {
854 platform.desiredFlags = SanitizeFlags(1 /*SANITIZE_FLAGS_NORMAL*/, CORE.Window.flags | flags);
855 UpdateFlags(platform.hwnd, platform.desiredFlags, platform.appScreenWidth, platform.appScreenHeight);
856 }
857
858 // Clear window configuration state flags
859 void ClearWindowState(unsigned int flags)
860 {
861 platform.desiredFlags = SanitizeFlags(1 /*SANITIZE_FLAGS_NORMAL*/, CORE.Window.flags & ~flags);
862 UpdateFlags(platform.hwnd, platform.desiredFlags, platform.appScreenWidth, platform.appScreenHeight);
863 }
864
865 // Set icon for window
866 void SetWindowIcon(Image image)
867 {
868 if (!platform.hwnd || (image.data == NULL) || (image.width <= 0) || (image.height <= 0)) return;
869
870 HDC hdc = GetDC(platform.hwnd);
871
872 // Create 32-bit BGRA DIB for color
873 BITMAPV5HEADER bi = { 0 };
874 ZeroMemory(&bi, sizeof(bi));
875 bi.bV5Size = sizeof(bi);
876 bi.bV5Width = image.width;
877 bi.bV5Height = -image.height; // Negative = top-down bitmap
878 bi.bV5Planes = 1;
879 bi.bV5BitCount = 32;
880 bi.bV5Compression = BI_BITFIELDS;
881 bi.bV5RedMask = 0x00FF0000;
882 bi.bV5GreenMask = 0x0000FF00;
883 bi.bV5BlueMask = 0x000000FF;
884 bi.bV5AlphaMask = 0xFF000000;
885
886 unsigned char *targetBits = NULL;
887 HBITMAP hColorBitmap = CreateDIBSection(hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS, (void **)&targetBits, NULL, 0);
888 if (!hColorBitmap)
889 {
890 ReleaseDC(platform.hwnd, hdc);
891 return;
892 }
893
894 // Copy RGBA > BGRA (Win32 expects BGRA)
895 for (int y = 0; y < image.height; y++)
896 {
897 for (int x = 0; x < image.width; x++)
898 {
899 int i = (y*image.width + x)*4;
900 targetBits[i + 0] = ((unsigned char *)image.data)[i + 2]; // B
901 targetBits[i + 1] = ((unsigned char *)image.data)[i + 1]; // G
902 targetBits[i + 2] = ((unsigned char *)image.data)[i + 0]; // R
903 targetBits[i + 3] = ((unsigned char *)image.data)[i + 3]; // A
904 }
905 }
906
907 // Create mask bitmap (1-bit, all opaque)
908 HBITMAP hMaskBitmap = CreateBitmap(image.width, image.height, 1, 1, NULL);
909
910 // Build icon info
911 ICONINFO ii = { 0 };
912 ZeroMemory(&ii, sizeof(ii));
913 ii.fIcon = TRUE;
914 ii.hbmMask = hMaskBitmap;
915 ii.hbmColor = hColorBitmap;
916
917 HICON hIcon = CreateIconIndirect(&ii);
918
919 // Clean up GDI bitmaps (icon keeps copies internally)
920 DeleteObject(hColorBitmap);
921 DeleteObject(hMaskBitmap);
922 ReleaseDC(platform.hwnd, hdc);
923
924 if (hIcon)
925 {
926 // Set both large and small icons
927 SendMessage(platform.hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
928 SendMessage(platform.hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
929 }
930 }
931
932 // Set icon for window
933 void SetWindowIcons(Image *images, int count)
934 {
935 // TODO: Implement SetWindowIcons()
936 }
937
938 void SetWindowTitle(const char *title)
939 {
940 CORE.Window.title = title;
941
942 WCHAR *titleWide = NULL;
943 A_TO_W_ALLOCA(titleWide, CORE.Window.title);
944
945 int result = SetWindowTextW(platform.hwnd, titleWide);
946 if (result == 0) TRACELOG(LOG_WARNING, "WIN32: Failed to set window title [ERROR: %lu]", GetLastError());
947 }
948
949 // Set window position on screen (windowed mode)
950 void SetWindowPosition(int x, int y)
951 {
952 if (platform.hwnd != NULL)
953 {
954 RECT rect = { 0 };
955 if (GetWindowRect(platform.hwnd, &rect))
956 {
957 int width = rect.right - rect.left;
958 int height = rect.bottom - rect.top;
959
960 // Move the window to the new position (keeping size and z-order)
961 SetWindowPos(platform.hwnd, NULL, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE);
962 }
963 }
964 }
965
966 // Set monitor for the current window
967 void SetWindowMonitor(int monitor)
968 {
969 TRACELOG(LOG_WARNING, "SetWindowMonitor not implemented");
970 }
971
972 // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
973 void SetWindowMinSize(int width, int height)
974 {
975 if ((width > CORE.Window.screenMax.width) || (height > CORE.Window.screenMax.height))
976 {
977 TRACELOG(LOG_WARNING, "WIN32: WINDOW: Cannot set minimum screen size higher than the maximum");
978 return;
979 }
980
981 CORE.Window.screenMin.width = width;
982 CORE.Window.screenMin.height = height;
983
984 SetWindowSize(platform.appScreenWidth, platform.appScreenHeight);
985 }
986
987 // Set window maximum dimensions (FLAG_WINDOW_RESIZABLE)
988 void SetWindowMaxSize(int width, int height)
989 {
990 if ((width < CORE.Window.screenMin.width) || (height < CORE.Window.screenMin.height))
991 {
992 TRACELOG(LOG_WARNING, "WIN32: WINDOW: Cannot set maximum screen size lower than the minimum");
993 return;
994 }
995
996 CORE.Window.screenMax.width = width;
997 CORE.Window.screenMax.height = height;
998
999 SetWindowSize(platform.appScreenWidth, platform.appScreenHeight);
1000 }
1001
1002 // Set window dimensions
1003 void SetWindowSize(int width, int height)
1004 {
1005 int screenWidth = fmaxf(CORE.Window.screenMin.width, fminf(CORE.Window.screenMax.width, width));
1006 int screenHeight = fmaxf(CORE.Window.screenMin.height, fminf(CORE.Window.screenMax.height, height));
1007
1008 UpdateWindowSize(1, platform.hwnd, screenWidth, screenHeight, platform.desiredFlags);
1009 }
1010
1011 // Set window opacity, value opacity is between 0.0 and 1.0
1012 void SetWindowOpacity(float opacity)
1013 {
1014 TRACELOG(LOG_WARNING, "SetWindowOpacity not implemented");
1015 }
1016
1017 // Set window focused
1018 void SetWindowFocused(void)
1019 {
1020 TRACELOG(LOG_WARNING, "SetWindowFocused not implemented");
1021 }
1022
1023 // Get native window handle
1024 void *GetWindowHandle(void)
1025 {
1026 return platform.hwnd;
1027 }
1028
1029 int GetMonitorCount(void)
1030 {
1031 int count = 0;
1032
1033 int result = EnumDisplayMonitors(NULL, NULL, CountMonitorsProc, (LPARAM)&count);
1034 if (result == 0) TRACELOG(LOG_ERROR, "%s failed, error=%lu", "EnumDisplayMonitors", GetLastError());
1035
1036 return count;
1037 }
1038
1039 // Get current monitor where window is placed
1040 int GetCurrentMonitor(void)
1041 {
1042 HMONITOR monitor = MonitorFromWindow(platform.hwnd, MONITOR_DEFAULTTOPRIMARY);
1043 if (!monitor) TRACELOG(LOG_ERROR, "%s failed, error=%lu", "MonitorFromWindow", GetLastError());
1044
1045 MonitorInfo info = { 0 };
1046 info.needle = monitor;
1047 info.index = 0;
1048 info.matchIndex = -1;
1049
1050 int result = EnumDisplayMonitors(NULL, NULL, FindMonitorProc, (LPARAM)&info);
1051 if (result == 0) TRACELOG(LOG_ERROR, "%s failed, error=%lu", "EnumDisplayMonitors", GetLastError());
1052
1053 return info.matchIndex;
1054 }
1055
1056 // Get selected monitor position
1057 Vector2 GetMonitorPosition(int monitor)
1058 {
1059 TRACELOG(LOG_WARNING, "GetMonitorPosition not implemented");
1060 return (Vector2){ 0, 0 };
1061 }
1062
1063 // Get selected monitor width (currently used by monitor)
1064 int GetMonitorWidth(int monitor)
1065 {
1066 //TRACELOG(LOG_WARNING, "GetMonitorWidth not implemented");
1067 return 0;
1068 }
1069
1070 // Get selected monitor height (currently used by monitor)
1071 int GetMonitorHeight(int monitor)
1072 {
1073 //TRACELOG(LOG_WARNING, "GetMonitorHeight not implemented");
1074 return 0;
1075 }
1076
1077 // Get selected monitor physical width in millimetres
1078 int GetMonitorPhysicalWidth(int monitor)
1079 {
1080 TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth not implemented");
1081 return 0;
1082 }
1083
1084 // Get selected monitor physical height in millimetres
1085 int GetMonitorPhysicalHeight(int monitor)
1086 {
1087 TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight not implemented");
1088 return 0;
1089 }
1090
1091 // Get selected monitor refresh rate
1092 int GetMonitorRefreshRate(int monitor)
1093 {
1094 TRACELOG(LOG_WARNING, "GetMonitorRefreshRate not implemented");
1095 return 0;
1096 }
1097
1098 // Get the human-readable, UTF-8 encoded name of the selected monitor
1099 const char *GetMonitorName(int monitor)
1100 {
1101 TRACELOG(LOG_WARNING, "GetMonitorName not implemented");
1102 return 0;
1103 }
1104
1105 // Get window position XY on monitor
1106 Vector2 GetWindowPosition(void)
1107 {
1108 //TRACELOG(LOG_WARNING, "GetWindowPosition not implemented");
1109 return (Vector2){ 0, 0 };
1110 }
1111
1112 // Get window scale DPI factor for current monitor
1113 Vector2 GetWindowScaleDPI(void)
1114 {
1115 float scale = ((float)GetDpiForWindow(platform.hwnd))/96.0f;
1116 return (Vector2){ scale, scale };
1117 }
1118
1119 // Set clipboard text content
1120 void SetClipboardText(const char *text)
1121 {
1122 TRACELOG(LOG_WARNING, "SetClipboardText not implemented");
1123 }
1124
1125 // Get clipboard text content
1126 const char *GetClipboardText(void)
1127 {
1128 TRACELOG(LOG_WARNING, "GetClipboardText not implemented");
1129 return NULL;
1130 }
1131
1132 // Get clipboard image
1133 Image GetClipboardImage(void)
1134 {
1135 Image image = { 0 };
1136
1137 TRACELOG(LOG_WARNING, "GetClipboardText not implemented");
1138
1139 return image;
1140 }
1141
1142 // Show mouse cursor
1143 void ShowCursor(void)
1144 {
1145 SetCursor(LoadCursorW(NULL, (LPCWSTR)IDC_ARROW));
1146 CORE.Input.Mouse.cursorHidden = false;
1147 }
1148
1149 // Hides mouse cursor
1150 void HideCursor(void)
1151 {
1152 // NOTE: Using SetCursor() instead of ShowCursor() because
1153 // it makes it easy to only hide the cursor while it's inside the client area
1154 SetCursor(NULL);
1155 CORE.Input.Mouse.cursorHidden = true;
1156 }
1157
1158 // Enables cursor (unlock cursor)
1159 void EnableCursor(void)
1160 {
1161 if (CORE.Input.Mouse.cursorLocked)
1162 {
1163 if (!ClipCursor(NULL)) TRACELOG(LOG_WARNING, "WIN32: Failed to clip cursor [ERROR: %lu]", GetLastError());
1164
1165 RAWINPUTDEVICE rid = { 0 };
1166 rid.usUsagePage = 0x01; // HID_USAGE_PAGE_GENERIC
1167 rid.usUsage = 0x02; // HID_USAGE_GENERIC_MOUSE
1168 rid.dwFlags = RIDEV_REMOVE; // Add to this window even in background
1169 rid.hwndTarget = NULL;
1170 int result = RegisterRawInputDevices(&rid, 1, sizeof(rid));
1171 if (result == 0) TRACELOG(LOG_WARNING, "WIN32: Failed to register raw input devices [ERROR: %lu]", GetLastError());
1172
1173 ShowCursor();
1174 CORE.Input.Mouse.cursorLocked = false;
1175 }
1176 }
1177
1178 // Disables cursor (lock cursor)
1179 void DisableCursor(void)
1180 {
1181 if (!CORE.Input.Mouse.cursorLocked)
1182 {
1183 RAWINPUTDEVICE rid = { 0 };
1184 rid.usUsagePage = 0x01; // HID_USAGE_PAGE_GENERIC
1185 rid.usUsage = 0x02; // HID_USAGE_GENERIC_MOUSE
1186 rid.dwFlags = RIDEV_INPUTSINK; // Add to this window even in background
1187 rid.hwndTarget = platform.hwnd;
1188 int result = RegisterRawInputDevices(&rid, 1, sizeof(rid));
1189 if (result == 0) TRACELOG(LOG_WARNING, "WIN32: Failed to register raw input devices [ERROR: %lu]", GetLastError());
1190
1191 RECT clientRect = { 0 };
1192 if (!GetClientRect(platform.hwnd, &clientRect)) TRACELOG(LOG_WARNING, "WIN32: Failed to get client rectangle [ERROR: %lu]", GetLastError());
1193
1194 POINT topleft = { clientRect.left, clientRect.top };
1195 if (!ClientToScreen(platform.hwnd, &topleft)) TRACELOG(LOG_WARNING, "WIN32: Failed to get client to screen size [ERROR: %lu]", GetLastError());
1196
1197 LONG width = clientRect.right - clientRect.left;
1198 LONG height = clientRect.bottom - clientRect.top;
1199
1200 TRACELOG(LOG_INFO, "WIN32: Clip cursor client rect: [%d,%d %d,%d], top-left: (%d,%d)",
1201 clientRect.left, clientRect.top, clientRect.right, clientRect.bottom, topleft.x, topleft.y);
1202
1203 LONG centerX = topleft.x + width/2;
1204 LONG centerY = topleft.y + height/2;
1205 RECT clipRect = { centerX, centerY, centerX + 1, centerY + 1 };
1206 if (!ClipCursor(&clipRect)) TRACELOG(LOG_WARNING, "WIN32: Failed to clip cursor [ERROR: %lu]", GetLastError());
1207
1208 CORE.Input.Mouse.previousPosition = (Vector2){ 0, 0 };
1209 CORE.Input.Mouse.currentPosition = (Vector2){ 0, 0 };
1210 HideCursor();
1211
1212 CORE.Input.Mouse.cursorLocked = true;
1213 }
1214 }
1215
1216 // Swap back buffer with front buffer (screen drawing)
1217 void SwapScreenBuffer(void)
1218 {
1219 if (!platform.hdc) abort();
1220
1221 #if defined(GRAPHICS_API_OPENGL_SOFTWARE)
1222 // Update framebuffer
1223 rlCopyFramebuffer(0, 0, CORE.Window.render.width, CORE.Window.render.height, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, platform.pixels);
1224
1225 // Force redraw
1226 InvalidateRect(platform.hwnd, NULL, FALSE);
1227 UpdateWindow(platform.hwnd);
1228 #else
1229 if (!SwapBuffers(platform.hdc)) TRACELOG(LOG_ERROR, "WIN32: Failed to swap buffers [ERROR: %lu]", GetLastError());
1230 if (!ValidateRect(platform.hwnd, NULL)) TRACELOG(LOG_ERROR, "WIN32: Failed to validate screen rect [ERROR: %lu]", GetLastError());
1231 #endif
1232 }
1233
1234 //----------------------------------------------------------------------------------
1235 // Module Functions Definition: Misc
1236 //----------------------------------------------------------------------------------
1237
1238 // Get elapsed time measure in seconds
1239 double GetTime(void)
1240 {
1241 double time = 0.0;
1242 LARGE_INTEGER now = { 0 };
1243 QueryPerformanceCounter(&now);
1244 time = (double)(now.QuadPart - CORE.Time.base)/(double)platform.timerFrequency.QuadPart;
1245
1246 return time;
1247 }
1248
1249 // Open URL with default system browser (if available)
1250 // NOTE: This function is only safe to use if the provided URL is safe
1251 // A user could craft a malicious string performing another action
1252 // Avoid calling this function with user input non-validated strings
1253 // REF: https://github.com/raysan5/raylib/issues/686
1254 void OpenURL(const char *url)
1255 {
1256 // Security check to (partially) avoid malicious code on target platform
1257 if (strchr(url, '\'') != NULL) TRACELOG(LOG_WARNING, "SYSTEM: Provided URL could be potentially malicious, avoid [\'] character");
1258 else
1259 {
1260 char *cmd = (char *)RL_CALLOC(strlen(url) + 32, sizeof(char));
1261 sprintf(cmd, "explorer \"%s\"", url);
1262 int result = system(cmd);
1263 if (result == -1) TRACELOG(LOG_WARNING, "OpenURL() child process could not be created");
1264 RL_FREE(cmd);
1265 }
1266 }
1267
1268 //----------------------------------------------------------------------------------
1269 // Module Functions Definition: Inputs
1270 //----------------------------------------------------------------------------------
1271
1272 // Set internal gamepad mappings
1273 int SetGamepadMappings(const char *mappings)
1274 {
1275 TRACELOG(LOG_WARNING, "SetGamepadMappings not implemented");
1276
1277 return -1;
1278 }
1279
1280 // Set gamepad vibration
1281 void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
1282 {
1283 TRACELOG(LOG_WARNING, "SetGamepadVibration not implemented");
1284 }
1285
1286 // Set mouse position XY
1287 void SetMousePosition(int x, int y)
1288 {
1289 if (!CORE.Input.Mouse.cursorLocked)
1290 {
1291 CORE.Input.Mouse.currentPosition = (Vector2){ (float)x, (float)y };
1292 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1293 TRACELOG(LOG_WARNING, "SetMousePosition not implemented");
1294 }
1295 else TRACELOG(LOG_WARNING, "INPUT: MOUSE: Cursor not enabled");
1296 }
1297
1298 // Set mouse cursor
1299 void SetMouseCursor(int cursor)
1300 {
1301 LPCWSTR cursorName = GetCursorName(cursor);
1302 HCURSOR hcursor = LoadCursorW(NULL, cursorName);
1303 if (!hcursor) TRACELOG(LOG_ERROR, "WIN32: Failed to load requested cursor [ERROR: %lu]", GetLastError());
1304
1305 SetCursor(hcursor);
1306 CORE.Input.Mouse.cursorHidden = false;
1307 }
1308
1309 // Get physical key name
1310 const char *GetKeyName(int key)
1311 {
1312 TRACELOG(LOG_WARNING, "GetKeyName not implemented");
1313 return NULL;
1314 }
1315
1316 // Register all input events
1317 void PollInputEvents(void)
1318 {
1319 // Reset keys/chars pressed registered
1320 CORE.Input.Keyboard.keyPressedQueueCount = 0;
1321 CORE.Input.Keyboard.charPressedQueueCount = 0;
1322
1323 // Reset key repeats
1324 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++) CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
1325
1326 // Reset last gamepad button/axis registered state
1327 CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN
1328 //CORE.Input.Gamepad.axisCount = 0;
1329
1330 // Register previous touch states
1331 for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
1332
1333 // Reset touch positions
1334 // TODO: It resets on target platform the mouse position and not filled again until a move-event,
1335 // so, if mouse is not moved it returns a (0, 0) position... this behaviour should be reviewed!
1336 //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 };
1337
1338 memcpy(CORE.Input.Keyboard.previousKeyState, CORE.Input.Keyboard.currentKeyState, sizeof(CORE.Input.Keyboard.previousKeyState));
1339 memset(CORE.Input.Keyboard.keyRepeatInFrame, 0, sizeof(CORE.Input.Keyboard.keyRepeatInFrame));
1340
1341 // Register previous mouse wheel state
1342 CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
1343 CORE.Input.Mouse.currentWheelMove = (Vector2){ 0.0f, 0.0f };
1344
1345 // Register previous mouse position
1346 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1347
1348 // Process windows messages
1349 MSG msg = { 0 };
1350 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
1351 {
1352 TranslateMessage(&msg);
1353 DispatchMessageW(&msg);
1354 }
1355 }
1356
1357 //----------------------------------------------------------------------------------
1358 // Module Internal Functions Definition
1359 //----------------------------------------------------------------------------------
1360
1361 // Initialize modern OpenGL context
1362 // NOTE: Creating a dummy context first to query required extensions
1363 HGLRC InitOpenGL(HWND hwnd, HDC hdc)
1364 {
1365 // First, create a dummy context to get WGL extensions
1366 PIXELFORMATDESCRIPTOR pixelFormatDesc = {
1367 .nSize = sizeof(PIXELFORMATDESCRIPTOR),
1368 .nVersion = 1,
1369 .dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
1370 .iPixelType = PFD_TYPE_RGBA,
1371 .cColorBits = 32,
1372 .cAlphaBits = 8,
1373 .cDepthBits = 24,
1374 .iLayerType = PFD_MAIN_PLANE
1375 };
1376
1377 int pixelFormat = ChoosePixelFormat(hdc, &pixelFormatDesc);
1378 SetPixelFormat(hdc, pixelFormat, &pixelFormatDesc);
1379 //int pixelFormat = ChoosePixelFormat(platform.hdc, &pixelFormatDesc);
1380 //if (!pixelFormat) { TRACELOG(LOG_ERROR, "%s failed, error=%lu", "ChoosePixelFormat", GetLastError()); return -1; }
1381 //if (!SetPixelFormat(platform.hdc, pixelFormat, &pixelFormatDesc)) { TRACELOG(LOG_ERROR, "%s failed, error=%lu", "SetPixelFormat", GetLastError()); return -1; }
1382
1383 HGLRC tempContext = wglCreateContext(hdc);
1384 //if (!tempContext) { TRACELOG(LOG_ERROR, "%s failed, error=%lu", "wglCreateContext", GetLastError()); return -1; }
1385 BOOL result = wglMakeCurrent(hdc, tempContext);
1386 //if (!result) { TRACELOG(LOG_ERROR, "%s failed, error=%lu", "wglMakeCurrent", GetLastError()); return -1; }
1387
1388 // Load WGL extension entry points
1389 wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
1390 wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
1391 wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
1392 wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
1393
1394 // Setup modern pixel format if extension is available
1395 if (wglChoosePixelFormatARB)
1396 {
1397 int pixelFormatAttribs[] = {
1398 WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
1399 WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
1400 WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
1401 WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
1402 WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
1403 WGL_COLOR_BITS_ARB, 32,
1404 //WGL_RED_BITS_ARB, 8,
1405 //WGL_GREEN_BITS_ARB, 8,
1406 //WGL_BLUE_BITS_ARB, 8,
1407 //WGL_ALPHA_BITS_ARB, 8,
1408 WGL_DEPTH_BITS_ARB, 24,
1409 WGL_STENCIL_BITS_ARB, 8,
1410 0 // Terminator
1411 };
1412
1413 int format = 0;
1414 UINT numFormats = 0;
1415 if (wglChoosePixelFormatARB(hdc, pixelFormatAttribs, NULL, 1, &format, &numFormats) && (numFormats > 0))
1416 {
1417 PIXELFORMATDESCRIPTOR newPixelFormatDescriptor = { 0 };
1418 DescribePixelFormat(hdc, format, sizeof(newPixelFormatDescriptor), &newPixelFormatDescriptor);
1419 SetPixelFormat(hdc, format, &newPixelFormatDescriptor);
1420 }
1421 }
1422
1423 // Create real modern OpenGL context (3.3 core)
1424 HGLRC realContext = NULL;
1425 if (wglCreateContextAttribsARB)
1426 {
1427 int glContextVersionMajor = 1;
1428 int glContextVersionMinor = 1;
1429 int glContextProfile = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
1430
1431 if (rlGetVersion() == RL_OPENGL_21) // Request OpenGL 2.1 context
1432 {
1433 glContextVersionMajor = 2;
1434 glContextVersionMinor = 1;
1435 }
1436 else if (rlGetVersion() == RL_OPENGL_33) // Request OpenGL 3.3 context
1437 {
1438 glContextVersionMajor = 3;
1439 glContextVersionMinor = 3;
1440 }
1441 else if (rlGetVersion() == RL_OPENGL_43) // Request OpenGL 4.3 context
1442 {
1443 glContextVersionMajor = 4;
1444 glContextVersionMinor = 3;
1445 }
1446 else if (rlGetVersion() == RL_OPENGL_ES_20) // Request OpenGL ES 2.0 context
1447 {
1448 if (IsWglExtensionAvailable(platform.hdc, "WGL_EXT_create_context_es_profile") ||
1449 IsWglExtensionAvailable(platform.hdc, "WGL_EXT_create_context_es2_profile"))
1450 {
1451 glContextVersionMajor = 2;
1452 glContextVersionMinor = 0;
1453 glContextProfile = WGL_CONTEXT_ES_PROFILE_BIT_EXT;
1454 }
1455 else TRACELOG(LOG_WARNING, "GL: OpenGL ES context not supported by GPU");
1456 }
1457 else if (rlGetVersion() == RL_OPENGL_ES_30) // Request OpenGL ES 3.0 context
1458 {
1459 if (IsWglExtensionAvailable(platform.hdc, "WGL_EXT_create_context_es_profile") ||
1460 IsWglExtensionAvailable(platform.hdc, "WGL_EXT_create_context_es2_profile"))
1461 {
1462 glContextVersionMajor = 3;
1463 glContextVersionMinor = 0;
1464 glContextProfile = WGL_CONTEXT_ES_PROFILE_BIT_EXT;
1465 }
1466 else TRACELOG(LOG_WARNING, "GL: OpenGL ES context not supported by GPU");
1467 }
1468
1469 int contextAttribs[] = {
1470 WGL_CONTEXT_MAJOR_VERSION_ARB, glContextVersionMajor,
1471 WGL_CONTEXT_MINOR_VERSION_ARB, glContextVersionMinor,
1472 WGL_CONTEXT_PROFILE_MASK_ARB, glContextProfile, // WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, WGL_CONTEXT_ES_PROFILE_BIT_EXT (if supported)
1473 //WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB [glDebugMessageCallback()]
1474 0 // Terminator
1475 };
1476
1477 // NOTE: Not sharing context resources so, second parameters is NULL
1478 realContext = wglCreateContextAttribsARB(hdc, NULL, contextAttribs);
1479
1480 // Check for error context creation errors
1481 // ERROR_INVALID_VERSION_ARB (0x2095)
1482 // ERROR_INVALID_PROFILE_ARB (0x2096)
1483 if (realContext == NULL) TRACELOG(LOG_ERROR, "GL: Error creating requested context: %lu", GetLastError());
1484 }
1485
1486 // Cleanup dummy temp context
1487 wglMakeCurrent(NULL, NULL);
1488 wglDeleteContext(tempContext);
1489
1490 // Activate real context
1491 if (realContext) wglMakeCurrent(hdc, realContext);
1492
1493 // Once a real modern OpenGL context is created,
1494 // required extensions can be loaded (function pointers)
1495 rlLoadExtensions(WglGetProcAddress);
1496
1497 return realContext;
1498 }
1499
1500 // Initialize platform: graphics, inputs and more
1501 int InitPlatform(void)
1502 {
1503 int result = 0;
1504
1505 platform.appScreenWidth = CORE.Window.screen.width;
1506 platform.appScreenHeight = CORE.Window.screen.height;
1507 platform.desiredFlags = SanitizeFlags(0 /*SANITIZE_FLAGS_FIRST*/, CORE.Window.flags);
1508
1509 // NOTE: From this point CORE.Window.flags should always reflect the actual state of the window
1510 CORE.Window.flags = FLAG_WINDOW_HIDDEN | (platform.desiredFlags & FLAG_MASK_NO_UPDATE);
1511 CORE.Window.screenMax.width = 9999;
1512 CORE.Window.screenMax.height = 9999;
1513 /*
1514 // TODO: Review SetProcessDpiAwarenessContext()
1515 // NOTE: SetProcessDpiAwarenessContext() requires Windows 10, version 1703 and shcore.lib linkage
1516 if (IsWindows10Version1703OrGreaterWin32())
1517 {
1518 TRACELOG(LOG_INFO, "DpiAware: >=Win10Creators");
1519 if (!SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2))
1520 TRACELOG(LOG_ERROR, "%s failed, error %u", "SetProcessDpiAwarenessContext", GetLastError());
1521 }
1522 else
1523 {
1524 TRACELOG(LOG_INFO, "DpiAware: <Win10Creators");
1525 HRESULT hr = SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
1526 if (hr < 0) TRACELOG(LOG_ERROR, "%s failed, hresult=0x%lx", "SetProcessDpiAwareness", (DWORD)hr);
1527 }
1528 */
1529
1530 HINSTANCE hInstance = GetModuleHandleW(0);
1531
1532 // Define window class
1533 WNDCLASSEXW windowClass = {
1534 .cbSize = sizeof(WNDCLASSEXW),
1535 .style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC,
1536 .lpfnWndProc = WndProc, // Custom procedure assigned
1537 .cbWndExtra = sizeof(LONG_PTR), // extra space for the Tuple object ptr
1538 .hInstance = hInstance,
1539 .hCursor = LoadCursorW(NULL, (LPCWSTR)IDC_ARROW), // TODO: Check if this is really required, since WM_SETCURSOR event is processed
1540 .lpszClassName = CLASS_NAME // Class name: L"raylibWindow"
1541 };
1542
1543 // Load user-provided icon if available
1544 // NOTE: raylib resource file defaults to GLFW_ICON id, so looking for same identifier
1545 windowClass.hIcon = LoadImageW(hInstance, L"GLFW_ICON", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
1546 if (!windowClass.hIcon) windowClass.hIcon = LoadImageW(NULL, (LPCWSTR)IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
1547
1548 // Register window class
1549 result = (int)RegisterClassExW(&windowClass);
1550 if (result == 0) TRACELOG(LOG_ERROR, "WIN32: Failed to register window class [ERROR: %lu]", GetLastError());
1551
1552 // Get primary monitor info
1553 POINT primaryTopLeft = { 0 };
1554 HMONITOR monitor = MonitorFromPoint(primaryTopLeft, MONITOR_DEFAULTTOPRIMARY);
1555 if (monitor != NULL)
1556 {
1557 MONITORINFO info = { 0 };
1558 info.cbSize = sizeof(info);
1559 result = (int)GetMonitorInfoW(monitor, &info);
1560
1561 if (result == 0) TRACELOG(LOG_WARNING, "WIN32: DISPLAY: Failed to get monitor info [ERROR: %u]", GetLastError());
1562 else
1563 {
1564 CORE.Window.display.width = info.rcMonitor.right - info.rcMonitor.left;
1565 CORE.Window.display.height = info.rcMonitor.bottom - info.rcMonitor.top;
1566 }
1567 }
1568 else TRACELOG(LOG_WARNING, "WIN32: DISPLAY: Failed to get primary monitor from point [ERROR: %u]", GetLastError());
1569
1570 // Adjust the window rectangle so the *client area* matches desired size
1571 // NOTE: Window width/height includes borders and title-bar
1572 DWORD style = WS_OVERLAPPEDWINDOW;
1573 RECT rect = { 0, 0, platform.appScreenWidth, platform.appScreenHeight };
1574 AdjustWindowRect(&rect, style, FALSE);
1575 //AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, FALSE, WINDOW_STYLE_EX);
1576 //AdjustWindowRectExForDpi(&rect, style, FALSE, WINDOW_STYLE_EX, dpi);
1577 int windowWidth = rect.right - rect.left;
1578 int windowHeight = rect.bottom - rect.top;
1579
1580 // Create window
1581 // NOTE: Title string needs to be converted to WCHAR
1582 WCHAR *titleWide = NULL;
1583 A_TO_W_ALLOCA(titleWide, CORE.Window.title);
1584
1585 // Create window and get handle
1586 platform.hwnd = CreateWindowExW(
1587 WINDOW_STYLE_EX,
1588 CLASS_NAME,
1589 titleWide,
1590 MakeWindowStyle(CORE.Window.flags), // WS_OVERLAPPEDWINDOW | WS_VISIBLE
1591 CW_USEDEFAULT, CW_USEDEFAULT,
1592 windowWidth, windowHeight, // TODO: Window size [width, height], needs to be updated?
1593 NULL, NULL,
1594 GetModuleHandleW(NULL), NULL);
1595
1596 if (!platform.hwnd)
1597 {
1598 TRACELOG(LOG_ERROR, "WIN32: WINDOW: Failed to create window [ERROR: %lu]", GetLastError());
1599 return -1;
1600 }
1601
1602 // Get handle to device drawing context
1603 // NOTE: Windows GDI object that represents a drawing surface
1604 platform.hdc = GetDC(platform.hwnd);
1605
1606 if (rlGetVersion() == RL_OPENGL_SOFTWARE) // Using software renderer
1607 {
1608 // Initialize software framebuffer
1609 BITMAPINFO bmi = { 0 };
1610 ZeroMemory(&bmi, sizeof(bmi));
1611 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1612 bmi.bmiHeader.biWidth = platform.appScreenWidth;
1613 bmi.bmiHeader.biHeight = -(int)(platform.appScreenHeight); // Top-down bitmap
1614 bmi.bmiHeader.biPlanes = 1;
1615 bmi.bmiHeader.biBitCount = 32; // 32-bit BGRA
1616 bmi.bmiHeader.biCompression = BI_RGB;
1617
1618 platform.hdcmem = CreateCompatibleDC(platform.hdc);
1619
1620 platform.hbitmap = CreateDIBSection(
1621 platform.hdcmem, &bmi, DIB_RGB_COLORS,
1622 (void **)&platform.pixels, NULL, 0);
1623
1624 SelectObject(platform.hdcmem, platform.hbitmap);
1625
1626 //ReleaseDC(platform.hwnd, platform.hdc); // Required?
1627 }
1628 else
1629 {
1630 // Init hardware-accelerated OpenGL modern context
1631 platform.glContext = InitOpenGL(platform.hwnd, platform.hdc);
1632 }
1633
1634 CORE.Window.ready = true;
1635
1636 // Activate window to set focus and show taskbar icon
1637 ShowWindow(platform.hwnd, SW_SHOWDEFAULT);
1638
1639 // Update flags (in case of deferred state change required)
1640 UpdateFlags(platform.hwnd, platform.desiredFlags, platform.appScreenWidth, platform.appScreenHeight);
1641
1642 CORE.Window.render.width = CORE.Window.screen.width;
1643 CORE.Window.render.height = CORE.Window.screen.height;
1644 CORE.Window.currentFbo.width = CORE.Window.render.width;
1645 CORE.Window.currentFbo.height = CORE.Window.render.height;
1646 TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully %s",
1647 FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)? "(HighDPI)" : "");
1648 TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
1649 TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
1650 TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
1651 TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
1652
1653 if (rlGetVersion() == RL_OPENGL_SOFTWARE) // Using software renderer
1654 {
1655 TRACELOG(LOG_INFO, "GL: OpenGL device information:");
1656 TRACELOG(LOG_INFO, " > Vendor: %s", glGetString(GL_VENDOR));
1657 TRACELOG(LOG_INFO, " > Renderer: %s", glGetString(GL_RENDERER));
1658 TRACELOG(LOG_INFO, " > Version: %s", glGetString(GL_VERSION));
1659 TRACELOG(LOG_INFO, " > GLSL: %s", "NOT SUPPORTED");
1660 }
1661
1662 // Initialize timing system
1663 //----------------------------------------------------------------------------
1664 LARGE_INTEGER time = { 0 };
1665 QueryPerformanceCounter(&time);
1666 QueryPerformanceFrequency(&platform.timerFrequency);
1667 CORE.Time.base = time.QuadPart;
1668
1669 InitTimer();
1670 //----------------------------------------------------------------------------
1671
1672 // Initialize storage system
1673 //----------------------------------------------------------------------------
1674 CORE.Storage.basePath = GetWorkingDirectory();
1675 //----------------------------------------------------------------------------
1676
1677 TRACELOG(LOG_INFO, "PLATFORM: DESKTOP: WIN32: Initialized successfully");
1678
1679 return 0;
1680 }
1681
1682 // Close platform
1683 void ClosePlatform(void)
1684 {
1685 if (platform.hwnd)
1686 {
1687 int result = DestroyWindow(platform.hwnd);
1688 if (result == 0) TRACELOG(LOG_WARNING, "WIN32: WINDOW: Failed on window destroy [ERROR: %u]", GetLastError());
1689 platform.hwnd = NULL;
1690 }
1691 }
1692
1693 // Window procedure, message processing callback
1694 // NOTE: All window event messages are processed here
1695 static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
1696 {
1697 LRESULT result = 0;
1698
1699 // Sanity check
1700 DWORD mask = STYLE_MASK_ALL;
1701 if (platform.hwnd == hwnd)
1702 {
1703 if (msg == WM_WINDOWPOSCHANGING) mask &= ~(WS_MINIMIZE | WS_MAXIMIZE);
1704 CheckFlags("WndProc", hwnd, CORE.Window.flags, MakeWindowStyle(CORE.Window.flags), mask);
1705 }
1706
1707 FlagsOp flagsOp = { 0 };
1708 FlagsOp *deferredFlags = &flagsOp;
1709
1710 // Message processing
1711 //------------------------------------------------------------------------------------
1712 switch (msg)
1713 {
1714 case WM_CREATE:
1715 {
1716 // WARNING: Not recommended to do OpenGL intialization at this point
1717
1718 } break;
1719 //case WM_ACTIVATE
1720 case WM_DESTROY:
1721 {
1722 // Clean up for window destruction
1723 if (rlGetVersion() == RL_OPENGL_SOFTWARE) // Using software renderer
1724 {
1725 if (platform.hdcmem)
1726 {
1727 DeleteDC(platform.hdcmem);
1728 platform.hdcmem = NULL;
1729 }
1730
1731 if (platform.hbitmap)
1732 {
1733 DeleteObject(platform.hbitmap); // Clears platform.pixels data
1734 platform.hbitmap = NULL;
1735 platform.pixels = NULL; // NOTE: Pointer invalid after DeleteObject()
1736 }
1737 }
1738 else // OpenGL hardware renderer
1739 {
1740 wglMakeCurrent(platform.hdc, NULL);
1741 if (platform.glContext)
1742 {
1743 if (!wglDeleteContext(platform.glContext)) abort();
1744 platform.glContext = NULL;
1745 }
1746 }
1747
1748 if (platform.hdc)
1749 {
1750 if (!ReleaseDC(hwnd, platform.hdc)) abort();
1751 platform.hdc = NULL;
1752 }
1753
1754 PostQuitMessage(0);
1755
1756 } break;
1757 case WM_CLOSE: CORE.Window.shouldClose = true; break; // Window close button [x], ALT+F4
1758 //case WM_QUIT: // Application closing, not related to window
1759 case WM_KILLFOCUS:
1760 {
1761 memset(CORE.Input.Keyboard.previousKeyState, 0, sizeof(CORE.Input.Keyboard.previousKeyState));
1762 memset(CORE.Input.Keyboard.currentKeyState, 0, sizeof(CORE.Input.Keyboard.currentKeyState));
1763 } break;
1764 case WM_SIZING: // Sent to a window that the user is resizing
1765 {
1766 if (CORE.Window.flags & FLAG_WINDOW_RESIZABLE)
1767 {
1768 //HandleWindowResize(hwnd, &platform.appScreenWidth, &platform.appScreenHeight);
1769 }
1770
1771 result = TRUE;
1772 } break;
1773 case WM_SIZE:
1774 {
1775 // WARNING: Don't trust the docs, they say this message can not be obtained if not calling DefWindowProc()
1776 // in response to WM_WINDOWPOSCHANGED but looks like when a window is created,
1777 // this message can be obtained without getting WM_WINDOWPOSCHANGED
1778
1779 #if defined(GRAPHICS_API_OPENGL_SOFTWARE)
1780 // WARNING: Waiting two frames before resizing because software-renderer backend is initilized with swInit() later
1781 // than InitPlatform(), that triggers WM_SIZE, so avoid crashing
1782 if (CORE.Time.frameCounter > 2) HandleWindowResize(hwnd, &platform.appScreenWidth, &platform.appScreenHeight);
1783 #else
1784 // NOTE: This message is only triggered on window creation
1785 HandleWindowResize(hwnd, &platform.appScreenWidth, &platform.appScreenHeight);
1786 #endif
1787 result = 0; // If an application processes WM_SIZE message, it should return zero
1788 } break;
1789 case WM_GETMINMAXINFO:
1790 {
1791 DWORD style = MakeWindowStyle(platform.desiredFlags);
1792 SIZE maxClientSize = { CORE.Window.screenMax.width, CORE.Window.screenMax.height };
1793 SIZE maxWindowSize = CalcWindowSize(96, maxClientSize, style);
1794 SIZE minClientSize = { CORE.Window.screenMin.width, CORE.Window.screenMin.height };
1795 SIZE minWindowSize = CalcWindowSize(96, minClientSize, style);
1796
1797 LPMINMAXINFO lpmmi = (LPMINMAXINFO) lparam;
1798 lpmmi->ptMaxSize.x = maxWindowSize.cx;
1799 lpmmi->ptMaxSize.y = maxWindowSize.cy;
1800 lpmmi->ptMaxTrackSize.x = maxWindowSize.cx;
1801 lpmmi->ptMaxTrackSize.y = maxWindowSize.cy;
1802 lpmmi->ptMinTrackSize.x = minWindowSize.cx;
1803 lpmmi->ptMinTrackSize.y = minWindowSize.cy;
1804 } break;
1805 case WM_STYLECHANGING:
1806 {
1807 if (wparam == GWL_STYLE)
1808 {
1809 STYLESTRUCT *ss = (STYLESTRUCT *)lparam;
1810 GetStyleChangeFlagOps(CORE.Window.flags, ss, deferredFlags);
1811
1812 UINT dpi = GetDpiForWindow(hwnd);
1813 // Get client size (framebuffer inside the window)
1814 RECT rect = { 0 };
1815 GetClientRect(hwnd, &rect);
1816 SIZE clientSize = { rect.right, rect.bottom };
1817 SIZE oldSize = CalcWindowSize(dpi, clientSize, ss->styleOld);
1818 SIZE newSize = CalcWindowSize(dpi, clientSize, ss->styleNew);
1819
1820 if (oldSize.cx != newSize.cx || oldSize.cy != newSize.cy)
1821 {
1822 TRACELOG(LOG_INFO, "WIN32: WINDOW: Resize from style change [%dx%d] to [%dx%d]", oldSize.cx, oldSize.cy, newSize.cx, newSize.cy);
1823
1824 if (CORE.Window.flags & FLAG_WINDOW_MAXIMIZED)
1825 {
1826 // looks like windows will automatically "unminimize" a window
1827 // if a style changes modifies it's size
1828 TRACELOG(LOG_INFO, "WIN32: WINDOW: Style change modified window size, removing maximized flag");
1829 deferredFlags->clear |= FLAG_WINDOW_MAXIMIZED;
1830 }
1831 }
1832 }
1833 } break;
1834 case WM_WINDOWPOSCHANGING:
1835 {
1836 WINDOWPOS *pos = (WINDOWPOS *)lparam;
1837 if (pos->flags & SWP_SHOWWINDOW) deferredFlags->clear |= FLAG_WINDOW_HIDDEN;
1838 else if (pos->flags & SWP_HIDEWINDOW) deferredFlags->set |= FLAG_WINDOW_HIDDEN;
1839
1840 Mized mized = MIZED_NONE;
1841 bool isIconic = IsIconic(hwnd);
1842 bool styleMinimized = !!(WS_MINIMIZE & GetWindowLongPtrW(hwnd, GWL_STYLE));
1843 if (isIconic != styleMinimized) TRACELOG(LOG_WARNING, "WIN32: IsIconic state different from WS_MINIMIZED state");
1844
1845 if (isIconic) mized = MIZED_MIN;
1846 else
1847 {
1848 WINDOWPLACEMENT placement;
1849 placement.length = sizeof(placement);
1850 if (!GetWindowPlacement(hwnd, &placement)) TRACELOG(LOG_ERROR, "WIN32: WINDOW: FAiled to get monitor placement [ERROR: %lu]", GetLastError());
1851
1852 if (placement.showCmd == SW_SHOWMAXIMIZED) mized = MIZED_MAX;
1853 }
1854
1855 switch (mized)
1856 {
1857 case MIZED_NONE:
1858 {
1859 deferredFlags->clear |= (FLAG_WINDOW_MINIMIZED | FLAG_WINDOW_MAXIMIZED);
1860 HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY);
1861 MONITORINFO info;
1862 info.cbSize = sizeof(info);
1863 if (!GetMonitorInfoW(monitor, &info)) TRACELOG(LOG_ERROR, "WIN32: MONITOR: Failed to get monitor info [ERROR: %lu]", GetLastError());
1864
1865 if ((pos->x == info.rcMonitor.left) &&
1866 (pos->y == info.rcMonitor.top) &&
1867 (pos->cx == (info.rcMonitor.right - info.rcMonitor.left)) &&
1868 (pos->cy == (info.rcMonitor.bottom - info.rcMonitor.top))) deferredFlags->set |= FLAG_BORDERLESS_WINDOWED_MODE;
1869 else deferredFlags->clear |= FLAG_BORDERLESS_WINDOWED_MODE;
1870
1871 } break;
1872 case MIZED_MIN:
1873 {
1874 // !!! NOTE !!! Do not update the maximized/borderless
1875 // flags because when hwnd is minimized it temporarily overrides
1876 // the maximized state/flag which gets restored on SW_RESTORE
1877 deferredFlags->set |= FLAG_WINDOW_MINIMIZED;
1878 } break;
1879 case MIZED_MAX:
1880 {
1881 deferredFlags->clear |= FLAG_WINDOW_MINIMIZED;
1882 deferredFlags->set |= FLAG_WINDOW_MAXIMIZED;
1883 } break;
1884 default: break;
1885 }
1886 } break;
1887 //case WM_MOVE: break;
1888 case WM_WINDOWPOSCHANGED:
1889 {
1890 WINDOWPOS *pos = (WINDOWPOS*)lparam;
1891 if (!(pos->flags & SWP_NOSIZE)) HandleWindowResize(hwnd, &platform.appScreenWidth, &platform.appScreenHeight);
1892
1893 DefWindowProc(hwnd, msg, wparam, lparam);
1894 } break;
1895 case WM_GETDPISCALEDSIZE:
1896 {
1897 SIZE *inoutSize = (SIZE *)lparam;
1898 UINT newDpi = (UINT)wparam; // TODO: WARNING: Converting from WPARAM = UINT_PTR
1899
1900 // For the following flag changes, a window resize event should be posted,
1901 // TODO: Should it be done after dpi changes?
1902 if (CORE.Window.flags & FLAG_WINDOW_MINIMIZED) return TRUE;
1903 if (CORE.Window.flags & FLAG_WINDOW_MAXIMIZED) return TRUE;
1904 if (CORE.Window.flags & FLAG_BORDERLESS_WINDOWED_MODE) return TRUE;
1905
1906 float dpiScale = ((float)newDpi)/96.0f;
1907 bool dpiScaling = CORE.Window.flags & FLAG_WINDOW_HIGHDPI;
1908 // Get size in pixels from points
1909 SIZE desired = {
1910 .cx = dpiScaling? (int)((float)platform.appScreenWidth*dpiScale) : platform.appScreenWidth,
1911 .cy = dpiScaling? (int)((float)platform.appScreenHeight*dpiScale) : platform.appScreenHeight
1912 };
1913 inoutSize->cx = desired.cx;
1914 inoutSize->cy = desired.cy;
1915
1916 result = TRUE;
1917 } break;
1918 case WM_DPICHANGED:
1919 {
1920 // Get current dpi scale factor
1921 float scalex = HIWORD(wparam)/96.0f;
1922 float scaley = LOWORD(wparam)/96.0f;
1923
1924 RECT *suggestedRect = (RECT *)lparam;
1925
1926 // Never set the window size to anything other than the suggested rect here
1927 // Doing so can cause a window to stutter between monitors when transitioning between them
1928 int result = (int)SetWindowPos(hwnd, NULL,
1929 suggestedRect->left, suggestedRect->top,
1930 suggestedRect->right - suggestedRect->left,
1931 suggestedRect->bottom - suggestedRect->top,
1932 SWP_NOZORDER | SWP_NOACTIVATE);
1933
1934 if (result == 0) TRACELOG(LOG_ERROR, "Failed to set window position [ERROR: %lu]", GetLastError());
1935
1936 // TODO: Update screen data, render size, screen scaling, viewport...
1937
1938 } break;
1939 case WM_SETCURSOR:
1940 {
1941 // Called when mouse moves, enters/leaves window...
1942 if (LOWORD(lparam) == HTCLIENT)
1943 {
1944 SetCursor(CORE.Input.Mouse.cursorHidden? NULL : LoadCursorW(NULL, (LPCWSTR)IDC_ARROW));
1945 return 0;
1946 }
1947
1948 result = DefWindowProc(hwnd, msg, wparam, lparam);
1949 } break;
1950 case WM_PAINT:
1951 {
1952 if (rlGetVersion() == RL_OPENGL_SOFTWARE) // Using software renderer
1953 {
1954 PAINTSTRUCT ps = { 0 };
1955 HDC hdc = BeginPaint(hwnd, &ps);
1956
1957 // Blit from memory DC to window DC
1958 BitBlt(hdc, 0, 0, platform.appScreenWidth, platform.appScreenHeight, platform.hdcmem, 0, 0, SRCCOPY);
1959
1960 EndPaint(hwnd, &ps);
1961 }
1962 else DefWindowProc(hwnd, msg, wparam, lparam);
1963 }
1964 case WM_INPUT:
1965 {
1966 //HandleRawInput(lparam);
1967 } break;
1968 case WM_MOUSEMOVE:
1969 {
1970 if (!CORE.Input.Mouse.cursorLocked)
1971 {
1972 CORE.Input.Mouse.currentPosition.x = (float)GET_X_LPARAM(lparam);
1973 CORE.Input.Mouse.currentPosition.y = (float)GET_Y_LPARAM(lparam);
1974 CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition;
1975 }
1976 } break;
1977 case WM_KEYDOWN: HandleKey(wparam, lparam, 1); break;
1978 case WM_KEYUP: HandleKey(wparam, lparam, 0); break;
1979 case WM_LBUTTONDOWN: HandleMouseButton(MOUSE_BUTTON_LEFT, 1); break;
1980 case WM_LBUTTONUP : HandleMouseButton(MOUSE_BUTTON_LEFT, 0); break;
1981 case WM_RBUTTONDOWN: HandleMouseButton(MOUSE_BUTTON_RIGHT, 1); break;
1982 case WM_RBUTTONUP : HandleMouseButton(MOUSE_BUTTON_RIGHT, 0); break;
1983 case WM_MBUTTONDOWN: HandleMouseButton(MOUSE_BUTTON_MIDDLE, 1); break;
1984 case WM_MBUTTONUP : HandleMouseButton(MOUSE_BUTTON_MIDDLE, 0); break;
1985 case WM_XBUTTONDOWN:
1986 {
1987 switch (HIWORD(wparam))
1988 {
1989 case XBUTTON1: HandleMouseButton(MOUSE_BUTTON_SIDE, 1); break;
1990 case XBUTTON2: HandleMouseButton(MOUSE_BUTTON_EXTRA, 1); break;
1991 default: TRACELOG(LOG_WARNING, "TODO: handle ex mouse button DOWN wparam=%u", HIWORD(wparam)); break;
1992 }
1993 } break;
1994 case WM_XBUTTONUP:
1995 {
1996 switch (HIWORD(wparam))
1997 {
1998 case XBUTTON1: HandleMouseButton(MOUSE_BUTTON_SIDE, 0); break;
1999 case XBUTTON2: HandleMouseButton(MOUSE_BUTTON_EXTRA, 0); break;
2000 default: TRACELOG(LOG_WARNING, "TODO: handle ex mouse button UP wparam=%u", HIWORD(wparam)); break;
2001 }
2002 } break;
2003 case WM_MOUSEWHEEL: CORE.Input.Mouse.currentWheelMove.y = ((float)GET_WHEEL_DELTA_WPARAM(wparam))/WHEEL_DELTA; break;
2004 case WM_MOUSEHWHEEL: CORE.Input.Mouse.currentWheelMove.x = ((float)GET_WHEEL_DELTA_WPARAM(wparam))/WHEEL_DELTA; break;
2005
2006 default: result = DefWindowProcW(hwnd, msg, wparam, lparam); // Message passed directly for execution (default behaviour)
2007 }
2008 //------------------------------------------------------------------------------------
2009
2010 // Sanity check for flags
2011 if (platform.hwnd == hwnd) CheckFlags("After WndProc", hwnd, CORE.Window.flags, MakeWindowStyle(CORE.Window.flags), mask);
2012
2013 // Operations to execute after the above check
2014 if (flagsOp.set & flagsOp.clear) TRACELOG(LOG_WARNING, "WIN32: FLAGS: Flags 0x%x were both set and cleared", flagsOp.set & flagsOp.clear);
2015
2016 DWORD save = CORE.Window.flags;
2017 CORE.Window.flags |= flagsOp.set;
2018 CORE.Window.flags &= ~flagsOp.clear;
2019 if (save != CORE.Window.flags) TRACELOG(LOG_DEBUG, "WIN32: FLAGS: Current deferred flags: 0x%x > 0x%x (diff 0x%x)", save, CORE.Window.flags, save ^ CORE.Window.flags);
2020
2021 return result;
2022 }
2023
2024 // Handle keyboard input event
2025 static void HandleKey(WPARAM wparam, LPARAM lparam, char state)
2026 {
2027 KeyboardKey key = GetKeyFromWparam(wparam);
2028
2029 // TODO: Use scancode?
2030 //BYTE scancode = lparam >> 16;
2031 //TRACELOG(LOG_INFO, "KEY key=%d vk=%lu scan=%u = %u", key, wparam, scancode, state);
2032
2033 if (key != KEY_NULL)
2034 {
2035 CORE.Input.Keyboard.currentKeyState[key] = state;
2036
2037 if ((key == KEY_ESCAPE) && (state == 1)) CORE.Window.shouldClose = true;
2038 }
2039 else TRACELOG(LOG_WARNING, "INPUT: Unknown (or currently unhandled) virtual keycode %d (0x%x)", wparam, wparam);
2040
2041 // TODO: Add key to the queue as well?
2042 }
2043
2044 // Handle mouse button input event
2045 static void HandleMouseButton(int button, char state)
2046 {
2047 // Register current mouse button state
2048 CORE.Input.Mouse.currentButtonState[button] = state;
2049 CORE.Input.Touch.currentTouchState[button] = state;
2050 }
2051
2052 // Handle raw input event
2053 static void HandleRawInput(LPARAM lparam)
2054 {
2055 RAWINPUT input = { 0 };
2056
2057 UINT inputSize = sizeof(input);
2058 UINT size = GetRawInputData((HRAWINPUT)lparam, RID_INPUT, &input, &inputSize, sizeof(RAWINPUTHEADER));
2059
2060 if (size == (UINT)-1) TRACELOG(LOG_ERROR, "WIN32: Failed to get raw input data [ERROR: %lu]", GetLastError());
2061
2062 if (input.header.dwType != RIM_TYPEMOUSE) TRACELOG(LOG_ERROR, "WIN32: Unexpected WM_INPUT type %lu", input.header.dwType);
2063
2064 if (input.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE) TRACELOG(LOG_ERROR, "TODO: handle absolute mouse inputs!");
2065
2066 if (input.data.mouse.usFlags & MOUSE_VIRTUAL_DESKTOP) TRACELOG(LOG_ERROR, "TODO: handle virtual desktop mouse inputs!");
2067
2068 // Trick to keep the mouse position at (0,0) and instead move
2069 // the previous position so a proper mouse delta can still be retrieved
2070 //CORE.Input.Mouse.previousPosition.x -= input.data.mouse.lLastX;
2071 //CORE.Input.Mouse.previousPosition.y -= input.data.mouse.lLastY;
2072 //if (CORE.Input.Mouse.currentPosition.x != 0) abort();
2073 //if (CORE.Input.Mouse.currentPosition.y != 0) abort();
2074 }
2075
2076 // Handle window resizing event
2077 static void HandleWindowResize(HWND hwnd, int *width, int *height)
2078 {
2079 if (CORE.Window.flags & FLAG_WINDOW_MINIMIZED) return;
2080
2081 // Get client size (framebuffer inside the window)
2082 RECT rect = { 0 };
2083 GetClientRect(hwnd, &rect);
2084 SIZE clientSize = { rect.right, rect.bottom };
2085
2086 CORE.Window.currentFbo.width = (int)clientSize.cx;
2087 CORE.Window.currentFbo.height = (int)clientSize.cy;
2088 SetupViewport(clientSize.cx, clientSize.cy);
2089
2090 CORE.Window.resizedLastFrame = true;
2091 float dpiScale = ((float)GetDpiForWindow(hwnd))/96.0f;
2092 bool highdpi = !!(CORE.Window.flags & FLAG_WINDOW_HIGHDPI);
2093 unsigned int screenWidth = highdpi? (unsigned int)(((float)clientSize.cx)/dpiScale) : clientSize.cx;
2094 unsigned int screenHeight = highdpi? (unsigned int)(((float)clientSize.cy)/dpiScale) : clientSize.cy;
2095 CORE.Window.screen.width = screenWidth;
2096 CORE.Window.screen.height = screenHeight;
2097
2098 if (AdoptWindowResize(CORE.Window.flags))
2099 {
2100 TRACELOG(LOG_DEBUG, "WIN32: WINDOW: Updating app size to [%ix%i] from window resize", screenWidth, screenHeight);
2101 *width = screenWidth;
2102 *height = screenHeight;
2103 }
2104
2105 CORE.Window.screenScale = MatrixScale( (float)CORE.Window.render.width/CORE.Window.screen.width,
2106 (float)CORE.Window.render.height/CORE.Window.screen.height, 1.0f);
2107
2108 #if defined(GRAPHICS_API_OPENGL_SOFTWARE)
2109 swResize(clientSize.cx, clientSize.cy);
2110 #endif
2111 }
2112
2113 // Update window style
2114 static void UpdateWindowStyle(HWND hwnd, unsigned desiredFlags)
2115 {
2116 DWORD current = STYLE_MASK_WRITABLE & MakeWindowStyle(CORE.Window.flags);
2117 DWORD desired = STYLE_MASK_WRITABLE & MakeWindowStyle(desiredFlags);
2118
2119 if (current != desired)
2120 {
2121 SetLastError(0);
2122 DWORD previous = STYLE_MASK_WRITABLE & SetWindowLongPtrW(hwnd, GWL_STYLE, desired);
2123 if (previous != current)
2124 {
2125 TRACELOG(LOG_ERROR, "WIN32: WINDOW: SetWindowLongPtr() returned writable flags 0x%x but expected 0x%x (diff=0x%x, error=%lu)",
2126 previous, current, previous ^ current, GetLastError());
2127 }
2128
2129 CheckFlags("UpdateWindowStyle", hwnd, desiredFlags, desired, STYLE_MASK_WRITABLE);
2130 }
2131
2132 // Minimized takes precedence over maximized
2133 Mized currentMized = MIZED_NONE;
2134 Mized desiredMized = MIZED_NONE;
2135 if (CORE.Window.flags & FLAG_WINDOW_MINIMIZED) currentMized = MIZED_MIN;
2136 else if (CORE.Window.flags & FLAG_WINDOW_MAXIMIZED) currentMized = MIZED_MAX;
2137 if (desiredFlags & FLAG_WINDOW_MINIMIZED) desiredMized = MIZED_MIN;
2138 else if (desiredFlags & FLAG_WINDOW_MAXIMIZED) desiredMized = MIZED_MAX;
2139
2140 if (currentMized != desiredMized)
2141 {
2142 switch (desiredMized)
2143 {
2144 case MIZED_NONE: ShowWindow(hwnd, SW_RESTORE); break;
2145 case MIZED_MIN: ShowWindow(hwnd, SW_MINIMIZE); break;
2146 case MIZED_MAX: ShowWindow(hwnd, SW_MAXIMIZE); break;
2147 }
2148 }
2149 }
2150
2151 // Sanitize flags
2152 static unsigned SanitizeFlags(int mode, unsigned flags)
2153 {
2154 if (flags & FLAG_WINDOW_MAXIMIZED)
2155 {
2156 if (flags & FLAG_BORDERLESS_WINDOWED_MODE)
2157 {
2158 TRACELOG(LOG_WARNING, "WIN32: WINDOW: Borderless windows mode overriding maximized window flag");
2159 flags &= ~FLAG_WINDOW_MAXIMIZED;
2160 }
2161
2162 if (~flags & FLAG_WINDOW_RESIZABLE)
2163 {
2164 if (!(CORE.Window.flags & FLAG_WINDOW_MAXIMIZED))
2165 {
2166 TRACELOG(LOG_WARNING, "WIN32: WINDOW: Cannot maximize a non-resizable window");
2167 flags &= ~FLAG_WINDOW_MAXIMIZED;
2168 }
2169 else if (CORE.Window.flags & FLAG_WINDOW_RESIZABLE)
2170 {
2171 TRACELOG(LOG_WARNING, "WIN32: WINDOW: Cannot set window as non-resizable when maximized");
2172 flags |= FLAG_WINDOW_RESIZABLE;
2173 }
2174 }
2175 else if (!(CORE.Window.flags & FLAG_WINDOW_MAXIMIZED))
2176 {
2177 if (CORE.Window.flags & FLAG_WINDOW_MINIMIZED)
2178 {
2179 // Window needs to be unminimized before it can be maximized since minimizing takes precedence
2180 flags &= ~FLAG_WINDOW_MINIMIZED;
2181 }
2182 else if ((flags & FLAG_WINDOW_MINIMIZED) && !(CORE.Window.flags & FLAG_WINDOW_MINIMIZED))
2183 {
2184 TRACELOG(LOG_WARNING, "WIN32: WINDOW: Cannot minimize and maximize a window in the same frame");
2185 flags &= ~FLAG_WINDOW_MINIMIZED;
2186 flags &= ~FLAG_WINDOW_MAXIMIZED;
2187 }
2188 }
2189 }
2190
2191 if (mode == 1)
2192 {
2193 if ((flags & FLAG_MSAA_4X_HINT) && (!(CORE.Window.flags & FLAG_MSAA_4X_HINT)))
2194 {
2195 TRACELOG(LOG_WARNING, "WIN32: WINDOW: MSAA can only be configured before window initialization");
2196 flags &= ~FLAG_MSAA_4X_HINT;
2197 }
2198 }
2199
2200 return flags;
2201 }
2202
2203 // All window state changes from raylib flags go through this function. It performs
2204 // whatever operations are needed to update the window state to match the desired flags
2205 // In most cases this function should not update CORE.Window.flags directly, instead,
2206 // the window itself should update CORE.Window.flags in response to actual state changes
2207 // This means that CORE.Window.flags should always represent the actual state of the
2208 // window. This function will continue to perform these update operations so long as
2209 // the state continues to change
2210 //
2211 // This design takes care of many odd corner cases. For example, in case of restoring
2212 // a window that was previously maximized AND minimized and those two flags need to be removed,
2213 // ShowWindow with SW_RESTORE twice need to bee actually calleed. Another example is
2214 // wheen having a maximized window, if the undecorated flag is modified then the window style
2215 // needs to be updated, but updating the style would mean the window size would change
2216 // causing the window to lose its Maximized state which would mean the window size
2217 // needs to be updated, followed by the update of window style, a second time, to restore that maximized
2218 // state. This implementation is able to handle any/all of these special situations with a
2219 // retry loop that continues until either the desired state is reached or the state stops changing
2220 static void UpdateFlags(HWND hwnd, unsigned desiredFlags, int width, int height)
2221 {
2222 // Flags that apply immediately without needing any operations
2223 CORE.Window.flags |= (desiredFlags & FLAG_MASK_NO_UPDATE);
2224
2225 int vsync = (desiredFlags & FLAG_VSYNC_HINT)? 1 : 0;
2226 if (wglSwapIntervalEXT)
2227 {
2228 wglSwapIntervalEXT(vsync);
2229 if (vsync) CORE.Window.flags |= FLAG_VSYNC_HINT;
2230 else CORE.Window.flags &= ~FLAG_VSYNC_HINT;
2231 }
2232
2233 // TODO: Review all this code...
2234 DWORD previousStyle = 0;
2235 for (unsigned attempt = 1; ; attempt++)
2236 {
2237 CheckFlags("UpdateFlags", hwnd, CORE.Window.flags, MakeWindowStyle(CORE.Window.flags), STYLE_MASK_ALL);
2238
2239 bool windowSizeUpdated = false;
2240 if (MakeWindowStyle(CORE.Window.flags) == MakeWindowStyle(desiredFlags))
2241 {
2242 windowSizeUpdated = UpdateWindowSize(1, hwnd, width, height, desiredFlags);
2243 if ((FLAG_MASK_REQUIRED & desiredFlags) == (FLAG_MASK_REQUIRED & CORE.Window.flags)) break;
2244 }
2245
2246
2247 if ((attempt > 1) && (previousStyle == MakeWindowStyle(CORE.Window.flags)) && !windowSizeUpdated)
2248 {
2249 TRACELOG(LOG_ERROR, "WIN32: WINDOW: UpdateFlags() failed after %u attempt(s) wanted 0x%x but is 0x%x (diff=0x%x)",
2250 attempt, desiredFlags, CORE.Window.flags, desiredFlags ^ CORE.Window.flags);
2251 }
2252
2253 previousStyle = MakeWindowStyle(CORE.Window.flags);
2254 UpdateWindowStyle(hwnd, desiredFlags);
2255 }
2256 }
2257
2258 // Check if OpenGL extension is available
2259 static bool IsWglExtensionAvailable(HDC hdc, const char *extension)
2260 {
2261 bool result = false;
2262
2263 if (wglGetExtensionsStringARB != NULL)
2264 {
2265 const char *extList = wglGetExtensionsStringARB(hdc);
2266 if (extList != NULL)
2267 {
2268 // Simple substring search (could use strtok or strstr)
2269 if (strstr(extList, extension) != NULL) result = true;
2270 }
2271 }
2272
2273 return result;
2274 }