Debian Codegraph @

src/platforms/rcore_web_emscripten.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rcore_web_emscripten - Functions to manage window, graphics device and inputs
4 *
5 * PLATFORM: WEB - EMSCRIPTEN
6 * - HTML5 (WebAssembly)
7 *
8 * LIMITATIONS:
9 * - TBD
10 *
11 * POSSIBLE IMPROVEMENTS:
12 * - TBD
13 *
14 * CONFIGURATION:
15 * #define RCORE_PLATFORM_CUSTOM_FLAG
16 * Custom flag for rcore on target platform -not used-
17 *
18 * DEPENDENCIES:
19 * - emscripten: Allow interaction between browser API and C
20 * - gestures: Gestures system for touch-ready devices (or simulated from mouse inputs)
21 *
22 *
23 * LICENSE: zlib/libpng
24 *
25 * Copyright (c) 2025-2026 Ramon Santamaria (@raysan5) and contributors
26 *
27 * This software is provided "as-is", without any express or implied warranty. In no event
28 * will the authors be held liable for any damages arising from the use of this software.
29 *
30 * Permission is granted to anyone to use this software for any purpose, including commercial
31 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
32 *
33 * 1. The origin of this software must not be misrepresented; you must not claim that you
34 * wrote the original software. If you use this software in a product, an acknowledgment
35 * in the product documentation would be appreciated but is not required.
36 *
37 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
38 * as being the original software.
39 *
40 * 3. This notice may not be removed or altered from any source distribution.
41 *
42 **********************************************************************************************/
43
44 #include <emscripten/emscripten.h> // Emscripten functionality for C
45 #include <emscripten/html5.h> // Emscripten HTML5 library
46
47 #include <sys/time.h> // Required for: timespec, nanosleep(), select() - POSIX
48
49 //----------------------------------------------------------------------------------
50 // Defines and Macros
51 //----------------------------------------------------------------------------------
52 #if (_POSIX_C_SOURCE < 199309L)
53 #undef _POSIX_C_SOURCE
54 #define _POSIX_C_SOURCE 199309L // Required for: CLOCK_MONOTONIC if compiled with c99 without gnu ext.
55 #endif
56
57 //----------------------------------------------------------------------------------
58 // Types and Structures Definition
59 //----------------------------------------------------------------------------------
60 typedef struct {
61 char canvasId[64]; // Current canvas id
62 EMSCRIPTEN_WEBGL_CONTEXT_HANDLE glContext; // OpenGL context
63 unsigned int *pixels; // Pointer to pixel data buffer (RGBA 32bit format)
64 } PlatformData;
65
66 //----------------------------------------------------------------------------------
67 // Global Variables Definition
68 //----------------------------------------------------------------------------------
69 extern CoreData CORE; // Global CORE state context
70
71 static PlatformData platform = { 0 }; // Platform specific data
72
73 //----------------------------------------------------------------------------------
74 // Global Variables Definition
75 //----------------------------------------------------------------------------------
76 static const char cursorLUT[11][12] = {
77 "default", // 0 MOUSE_CURSOR_DEFAULT
78 "default", // 1 MOUSE_CURSOR_ARROW
79 "text", // 2 MOUSE_CURSOR_IBEAM
80 "crosshair", // 3 MOUSE_CURSOR_CROSSHAIR
81 "pointer", // 4 MOUSE_CURSOR_POINTING_HAND
82 "ew-resize", // 5 MOUSE_CURSOR_RESIZE_EW
83 "ns-resize", // 6 MOUSE_CURSOR_RESIZE_NS
84 "nwse-resize", // 7 MOUSE_CURSOR_RESIZE_NWSE
85 "nesw-resize", // 8 MOUSE_CURSOR_RESIZE_NESW
86 "move", // 9 MOUSE_CURSOR_RESIZE_ALL
87 "not-allowed" // 10 MOUSE_CURSOR_NOT_ALLOWED
88 };
89
90 //----------------------------------------------------------------------------------
91 // Module Internal Functions Declaration
92 //----------------------------------------------------------------------------------
93 int InitPlatform(void); // Initialize platform (graphics, inputs and more)
94 void ClosePlatform(void); // Close platform
95
96 // Emscripten window callback events
97 static EM_BOOL EmscriptenResizeCallback(int eventType, const EmscriptenUiEvent *event, void *userData);
98 static EM_BOOL EmscriptenFocusCallback(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData);
99 static EM_BOOL EmscriptenVisibilityChangeCallback(int eventType, const EmscriptenVisibilityChangeEvent *visibilityChangeEvent, void *userData);
100 static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *event, void *userData);
101 // TODO: Implement GLFW3 alternative for drop callback, runs when drop files into browser/canvas
102 //static void WindowDropCallback(GLFWwindow *window, int count, const char **paths);
103
104 // Emscripten input callback events
105 static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyboardEvent, void *userData);
106 static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData);
107 static EM_BOOL EmscriptenMouseMoveCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData);
108 static EM_BOOL EmscriptenMouseWheelCallback(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData);
109 static EM_BOOL EmscriptenPointerlockCallback(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData);
110 static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData);
111 static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData);
112
113 // JS: Set the canvas id provided by the module configuration
114 EM_JS(void, SetCanvasIdJs, (char *out, int outSize), {
115 var canvasId = "#" + Module.canvas.id;
116 stringToUTF8(canvasId, out, outSize);
117 });
118
119 //----------------------------------------------------------------------------------
120 // Module Functions Declaration
121 //----------------------------------------------------------------------------------
122 // NOTE: Functions declaration is provided by raylib.h
123
124 //----------------------------------------------------------------------------------
125 // Module Functions Definition: Window and Graphics Device
126 //----------------------------------------------------------------------------------
127
128 // Check if application should close
129 // This will always return false on a web-build as web builds have no control over this functionality
130 // Sleep is handled in EndDrawing() for synchronous code
131 bool WindowShouldClose(void)
132 {
133 // Emscripten Asyncify is required to run synchronous code in asynchronous JS
134 // REF: https://emscripten.org/docs/porting/asyncify.html
135
136 // WindowShouldClose() is not called on a web-ready raylib application if using emscripten_set_main_loop()
137 // and encapsulating one frame execution on a UpdateDrawFrame() function,
138 // allowing the browser to manage execution asynchronously
139
140 // NOTE: Optionally, time can be managed, giving control back-to-browser as required,
141 // but it seems below line could generate stuttering on some browsers
142 emscripten_sleep(12);
143
144 return false;
145 }
146
147 // Toggle fullscreen mode
148 void ToggleFullscreen(void)
149 {
150 bool enterFullscreen = false;
151
152 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
153 if (wasFullscreen)
154 {
155 if (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE)) enterFullscreen = false;
156 else if (FLAG_IS_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE)) enterFullscreen = true;
157 else
158 {
159 const int canvasWidth = EM_ASM_INT( { return Module.canvas.width; }, 0);
160 const int canvasStyleWidth = EM_ASM_INT( { return parseInt(Module.canvas.style.width); }, 0);
161 if (canvasStyleWidth > canvasWidth) enterFullscreen = false;
162 else enterFullscreen = true;
163 }
164
165 EM_ASM(document.exitFullscreen(););
166
167 FLAG_CLEAR(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
168 FLAG_CLEAR(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
169 }
170 else enterFullscreen = true;
171
172 if (enterFullscreen)
173 {
174 // NOTE: The setTimeouts handle the browser mode change delay
175 EM_ASM
176 (
177 setTimeout(function()
178 {
179 Module.requestFullscreen(false, false);
180 }, 100);
181 );
182
183 FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
184 }
185
186 // NOTE: Old notes below:
187 /*
188 EM_ASM
189 (
190 // This strategy works well while using raylib minimal web shell for emscripten,
191 // it re-scales the canvas to fullscreen using monitor resolution, for tools this
192 // is a good strategy but maybe games prefer to keep current canvas resolution and
193 // display it in fullscreen, adjusting monitor resolution if possible
194 if (document.fullscreenElement) document.exitFullscreen();
195 else Module.requestFullscreen(true, true); //false, true);
196 );
197 */
198 // EM_ASM(Module.requestFullscreen(false, false););
199 /*
200 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE))
201 {
202 // Option 1: Request fullscreen for the canvas element
203 // This option does not seem to work at all:
204 // emscripten_request_pointerlock() and emscripten_request_fullscreen() are affected by web security,
205 // the user must click once on the canvas to hide the pointer or transition to full screen
206 //emscripten_request_fullscreen("#canvas", false);
207
208 // Option 2: Request fullscreen for the canvas element with strategy
209 // This option does not seem to work at all
210 // REF: https://github.com/emscripten-core/emscripten/issues/5124
211 // EmscriptenFullscreenStrategy strategy = {
212 // .scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH, //EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT,
213 // .canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF,
214 // .filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT,
215 // .canvasResizedCallback = EmscriptenWindowResizedCallback,
216 // .canvasResizedCallbackUserData = NULL
217 // };
218 //emscripten_request_fullscreen_strategy("#canvas", EM_FALSE, &strategy);
219
220 // Option 3: Request fullscreen for the canvas element with strategy
221 // It works as expected but only inside the browser (client area)
222 EmscriptenFullscreenStrategy strategy = {
223 .scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT,
224 .canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF,
225 .filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT,
226 .canvasResizedCallback = EmscriptenWindowResizedCallback,
227 .canvasResizedCallbackUserData = NULL
228 };
229 emscripten_enter_soft_fullscreen("#canvas", &strategy);
230
231 int width = 0;
232 int height = 0;
233 emscripten_get_canvas_element_size("#canvas", &width, &height);
234 TRACELOG(LOG_WARNING, "Emscripten: Enter fullscreen: Canvas size: %i x %i", width, height);
235
236 FLAG_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
237 }
238 else
239 {
240 //emscripten_exit_fullscreen();
241 //emscripten_exit_soft_fullscreen();
242
243 int width, height;
244 emscripten_get_canvas_element_size("#canvas", &width, &height);
245 TRACELOG(LOG_WARNING, "Emscripten: Exit fullscreen: Canvas size: %i x %i", width, height);
246
247 FLAG_CLEAR(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
248 }
249 */
250 }
251
252 // Toggle borderless windowed mode
253 void ToggleBorderlessWindowed(void)
254 {
255 bool enterBorderless = false;
256
257 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
258 if (wasFullscreen)
259 {
260 if (FLAG_IS_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE)) enterBorderless = false;
261 else if (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE)) enterBorderless = true;
262 else
263 {
264 const int canvasWidth = EM_ASM_INT( { return Module.canvas.width; }, 0);
265 const int screenWidth = EM_ASM_INT( { return screen.width; }, 0);
266 if (screenWidth == canvasWidth) enterBorderless = false;
267 else enterBorderless = true;
268 }
269
270 EM_ASM(document.exitFullscreen(););
271
272 FLAG_CLEAR(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
273 FLAG_CLEAR(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
274 }
275 else enterBorderless = true;
276
277 if (enterBorderless)
278 {
279 // 1. The setTimeouts handle the browser mode change delay
280 // 2. The style unset handles the possibility of a width="value%" like on the default shell.html file
281 EM_ASM
282 (
283 const canvasId = UTF8ToString($0);
284 setTimeout(function()
285 {
286 Module.requestFullscreen(false, true);
287 setTimeout(function()
288 {
289 document.querySelector(canvasId).style.width="unset";
290 }, 100);
291 }, 100);
292 , platform.canvasId);
293 FLAG_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
294 }
295 }
296
297 // Set window state: maximized, if resizable
298 void MaximizeWindow(void)
299 {
300 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE) && !FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED))
301 {
302 const int tabWidth = EM_ASM_INT( return window.innerWidth; );
303 const int tabHeight = EM_ASM_INT( return window.innerHeight; );
304
305 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
306 }
307 }
308
309 // Set window state: minimized
310 void MinimizeWindow(void)
311 {
312 TRACELOG(LOG_WARNING, "MinimizeWindow() not available on target platform");
313 }
314
315 // Restore window from being minimized/maximized
316 void RestoreWindow(void)
317 {
318 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE) && FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED))
319 {
320 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
321 }
322 }
323
324 // Set window configuration state using flags
325 void SetWindowState(unsigned int flags)
326 {
327 if (!CORE.Window.ready) TRACELOG(LOG_WARNING, "WINDOW: SetWindowState does nothing before window initialization, Use \"SetConfigFlags\" instead");
328
329 // Check previous state and requested state to apply required changes
330 // NOTE: In most cases the functions already change the flags internally
331
332 // State change: FLAG_VSYNC_HINT
333 if (FLAG_IS_SET(flags, FLAG_VSYNC_HINT))
334 {
335 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_VSYNC_HINT) not available on target platform");
336 }
337
338 // State change: FLAG_BORDERLESS_WINDOWED_MODE
339 if (FLAG_IS_SET(flags, FLAG_BORDERLESS_WINDOWED_MODE))
340 {
341 // NOTE: Window state flag updated inside ToggleBorderlessWindowed() function
342 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
343 if (wasFullscreen)
344 {
345 const int canvasWidth = EM_ASM_INT( { return Module.canvas.width; }, 0);
346 const int canvasStyleWidth = EM_ASM_INT( { return parseInt(Module.canvas.style.width); }, 0);
347 if ((FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE)) || canvasStyleWidth > canvasWidth) ToggleBorderlessWindowed();
348 }
349 else ToggleBorderlessWindowed();
350 }
351
352 // State change: FLAG_FULLSCREEN_MODE
353 if (FLAG_IS_SET(flags, FLAG_FULLSCREEN_MODE))
354 {
355 // NOTE: Window state flag updated inside ToggleFullscreen() function
356 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
357 if (wasFullscreen)
358 {
359 const int canvasWidth = EM_ASM_INT( { return Module.canvas.width; }, 0);
360 const int screenWidth = EM_ASM_INT( { return screen.width; }, 0);
361 if (FLAG_IS_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE) || (screenWidth == canvasWidth)) ToggleFullscreen();
362 }
363 else ToggleFullscreen();
364 }
365
366 // State change: FLAG_WINDOW_RESIZABLE
367 if ((FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE) != FLAG_IS_SET(flags, FLAG_WINDOW_RESIZABLE)) && FLAG_IS_SET(flags, FLAG_WINDOW_RESIZABLE))
368 {
369 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE);
370 }
371
372 // State change: FLAG_WINDOW_UNDECORATED
373 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNDECORATED))
374 {
375 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_UNDECORATED) not available on target platform");
376 }
377
378 // State change: FLAG_WINDOW_HIDDEN
379 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIDDEN))
380 {
381 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_HIDDEN) not available on target platform");
382 }
383
384 // State change: FLAG_WINDOW_MINIMIZED
385 if (FLAG_IS_SET(flags, FLAG_WINDOW_MINIMIZED))
386 {
387 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_MINIMIZED) not available on target platform");
388 }
389
390 // State change: FLAG_WINDOW_MAXIMIZED
391 if ((FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED) != FLAG_IS_SET(flags, FLAG_WINDOW_MAXIMIZED)) && FLAG_IS_SET(flags, FLAG_WINDOW_MAXIMIZED))
392 {
393 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE))
394 {
395 const int tabWidth = EM_ASM_INT( return window.innerWidth; );
396 const int tabHeight = EM_ASM_INT( return window.innerHeight; );
397
398 FLAG_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
399 }
400 }
401
402 // State change: FLAG_WINDOW_UNFOCUSED
403 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNFOCUSED))
404 {
405 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_UNFOCUSED) not available on target platform");
406 }
407
408 // State change: FLAG_WINDOW_TOPMOST
409 if (FLAG_IS_SET(flags, FLAG_WINDOW_TOPMOST))
410 {
411 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_TOPMOST) not available on target platform");
412 }
413
414 // State change: FLAG_WINDOW_ALWAYS_RUN
415 if (FLAG_IS_SET(flags, FLAG_WINDOW_ALWAYS_RUN))
416 {
417 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_ALWAYS_RUN) not available on target platform");
418 }
419
420 // The following states can not be changed after window creation
421 // NOTE: Review for PLATFORM_WEB
422
423 // State change: FLAG_WINDOW_TRANSPARENT
424 if (FLAG_IS_SET(flags, FLAG_WINDOW_TRANSPARENT))
425 {
426 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_TRANSPARENT) not available on target platform");
427 }
428
429 // State change: FLAG_WINDOW_HIGHDPI
430 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIGHDPI))
431 {
432 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_HIGHDPI) not available on target platform");
433 }
434
435 // State change: FLAG_WINDOW_MOUSE_PASSTHROUGH
436 if (FLAG_IS_SET(flags, FLAG_WINDOW_MOUSE_PASSTHROUGH))
437 {
438 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_WINDOW_MOUSE_PASSTHROUGH) not available on target platform");
439 }
440
441 // State change: FLAG_MSAA_4X_HINT
442 if (FLAG_IS_SET(flags, FLAG_MSAA_4X_HINT))
443 {
444 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_MSAA_4X_HINT) not available on target platform");
445 }
446
447 // State change: FLAG_INTERLACED_HINT
448 if (FLAG_IS_SET(flags, FLAG_INTERLACED_HINT))
449 {
450 TRACELOG(LOG_WARNING, "SetWindowState(FLAG_INTERLACED_HINT) not available on target platform");
451 }
452 }
453
454 // Clear window configuration state flags
455 void ClearWindowState(unsigned int flags)
456 {
457 // Check previous state and requested state to apply required changes
458 // NOTE: In most cases the functions already change the flags internally
459
460 // State change: FLAG_VSYNC_HINT
461 if (FLAG_IS_SET(flags, FLAG_VSYNC_HINT))
462 {
463 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_VSYNC_HINT) not available on target platform");
464 }
465
466 // State change: FLAG_BORDERLESS_WINDOWED_MODE
467 if (FLAG_IS_SET(flags, FLAG_BORDERLESS_WINDOWED_MODE))
468 {
469 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
470 if (wasFullscreen)
471 {
472 const int canvasWidth = EM_ASM_INT( { return Module.canvas.width; }, 0);
473 const int screenWidth = EM_ASM_INT( { return screen.width; }, 0);
474 if (FLAG_IS_SET(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE) || (screenWidth == canvasWidth)) EM_ASM(document.exitFullscreen(););
475 }
476
477 FLAG_CLEAR(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
478 }
479
480 // State change: FLAG_FULLSCREEN_MODE
481 if (FLAG_IS_SET(flags, FLAG_FULLSCREEN_MODE))
482 {
483 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
484 if (wasFullscreen)
485 {
486 const int canvasWidth = EM_ASM_INT( { return Module.canvas.width; }, 0);
487 const int canvasStyleWidth = EM_ASM_INT( { return parseInt(Module.canvas.style.width); }, 0);
488 if (FLAG_IS_SET(CORE.Window.flags, FLAG_FULLSCREEN_MODE) || (canvasStyleWidth > canvasWidth)) EM_ASM(document.exitFullscreen(););
489 }
490
491 FLAG_CLEAR(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
492 }
493
494 // State change: FLAG_WINDOW_RESIZABLE
495 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE) && FLAG_IS_SET(flags, FLAG_WINDOW_RESIZABLE))
496 {
497 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_RESIZABLE);
498 }
499
500 // State change: FLAG_WINDOW_HIDDEN
501 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIDDEN))
502 {
503 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_HIDDEN) not available on target platform");
504 }
505
506 // State change: FLAG_WINDOW_MINIMIZED
507 if (FLAG_IS_SET(flags, FLAG_WINDOW_MINIMIZED))
508 {
509 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_MINIMIZED) not available on target platform");
510 }
511
512 // State change: FLAG_WINDOW_MAXIMIZED
513 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED) && FLAG_IS_SET(flags, FLAG_WINDOW_MAXIMIZED))
514 {
515 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE))
516 {
517 FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
518 }
519 }
520
521 // State change: FLAG_WINDOW_UNDECORATED
522 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNDECORATED))
523 {
524 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_UNDECORATED) not available on target platform");
525 }
526
527 // State change: FLAG_WINDOW_UNFOCUSED
528 if (FLAG_IS_SET(flags, FLAG_WINDOW_UNFOCUSED))
529 {
530 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_UNFOCUSED) not available on target platform");
531 }
532
533 // State change: FLAG_WINDOW_TOPMOST
534 if (FLAG_IS_SET(flags, FLAG_WINDOW_TOPMOST))
535 {
536 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_TOPMOST) not available on target platform");
537 }
538
539 // State change: FLAG_WINDOW_ALWAYS_RUN
540 if (FLAG_IS_SET(flags, FLAG_WINDOW_ALWAYS_RUN))
541 {
542 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_ALWAYS_RUN) not available on target platform");
543 }
544
545 // The following states can not be changed after window creation
546 // NOTE: Review for PLATFORM_WEB
547
548 // State change: FLAG_WINDOW_TRANSPARENT
549 if (FLAG_IS_SET(flags, FLAG_WINDOW_TRANSPARENT))
550 {
551 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_TRANSPARENT) not available on target platform");
552 }
553
554 // State change: FLAG_WINDOW_HIGHDPI
555 if (FLAG_IS_SET(flags, FLAG_WINDOW_HIGHDPI))
556 {
557 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_HIGHDPI) not available on target platform");
558 }
559
560 // State change: FLAG_WINDOW_MOUSE_PASSTHROUGH
561 if (FLAG_IS_SET(flags, FLAG_WINDOW_MOUSE_PASSTHROUGH))
562 {
563 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_WINDOW_MOUSE_PASSTHROUGH) not available on target platform");
564 }
565
566 // State change: FLAG_MSAA_4X_HINT
567 if (FLAG_IS_SET(flags, FLAG_MSAA_4X_HINT))
568 {
569 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_MSAA_4X_HINT) not available on target platform");
570 }
571
572 // State change: FLAG_INTERLACED_HINT
573 if (FLAG_IS_SET(flags, FLAG_INTERLACED_HINT))
574 {
575 TRACELOG(LOG_WARNING, "ClearWindowState(FLAG_INTERLACED_HINT) not available on target platform");
576 }
577 }
578
579 // Set icon for window
580 void SetWindowIcon(Image image)
581 {
582 TRACELOG(LOG_WARNING, "SetWindowIcon() not available on target platform");
583 }
584
585 // Set icon for window, multiple images
586 void SetWindowIcons(Image *images, int count)
587 {
588 TRACELOG(LOG_WARNING, "SetWindowIcons() not available on target platform");
589 }
590
591 // Set title for window
592 void SetWindowTitle(const char *title)
593 {
594 CORE.Window.title = title;
595 emscripten_set_window_title(title);
596 }
597
598 // Set window position on screen (windowed mode)
599 void SetWindowPosition(int x, int y)
600 {
601 TRACELOG(LOG_WARNING, "SetWindowPosition() not available on target platform");
602 }
603
604 // Set monitor for the current window
605 void SetWindowMonitor(int monitor)
606 {
607 TRACELOG(LOG_WARNING, "SetWindowMonitor() not available on target platform");
608 }
609
610 // Set window minimum dimensions (FLAG_WINDOW_RESIZABLE)
611 void SetWindowMinSize(int width, int height)
612 {
613 CORE.Window.screenMin.width = width;
614 CORE.Window.screenMin.height = height;
615
616 // Trigger the resize event once to update the window minimum width and height
617 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE) != 0) EmscriptenResizeCallback(EMSCRIPTEN_EVENT_RESIZE, NULL, NULL);
618 }
619
620 // Set window maximum dimensions (FLAG_WINDOW_RESIZABLE)
621 void SetWindowMaxSize(int width, int height)
622 {
623 CORE.Window.screenMax.width = width;
624 CORE.Window.screenMax.height = height;
625
626 // Trigger the resize event once to update the window maximum width and height
627 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE) != 0) EmscriptenResizeCallback(EMSCRIPTEN_EVENT_RESIZE, NULL, NULL);
628 }
629
630 // Set window dimensions
631 void SetWindowSize(int width, int height)
632 {
633 // When resizing the canvas, several elements must be considered:
634 // - CSS canvas size: Web layout size, logical pixels
635 // - Canvas contained framebuffer resolution
636 // * Browser monitor, device pixel ratio (HighDPI)
637
638 double canvasCssWidth = 0.0;
639 double canvasCssHeight = 0.0;
640 emscripten_get_element_css_size(platform.canvasId, &canvasCssWidth, &canvasCssHeight);
641
642 // NOTE: emscripten_get_canvas_element_size() returns canvas framebuffer size, not CSS canvas size
643
644 // Get device pixel ratio
645 // TODO: Should DPI be considered at this point?
646 double dpr = emscripten_get_device_pixel_ratio();
647
648 // Set canvas framebuffer size
649 emscripten_set_canvas_element_size(platform.canvasId, width*dpr, height*dpr);
650
651 // Set canvas CSS size
652 // TODO: Consider canvas CSS style if already scaled 100%
653 EM_ASM({ Module.canvas.style.width = $0; }, width*dpr);
654 EM_ASM({ Module.canvas.style.height = $0; }, height*dpr);
655
656 SetupViewport(width*dpr, height*dpr); // Reset viewport and projection matrix for new size
657 }
658
659 // Set window opacity, value opacity is between 0.0 and 1.0
660 void SetWindowOpacity(float opacity)
661 {
662 if (opacity >= 1.0f) opacity = 1.0f;
663 else if (opacity <= 0.0f) opacity = 0.0f;
664
665 EM_ASM({ Module.canvas.style.opacity = $0; }, opacity);
666 }
667
668 // Set window focused
669 void SetWindowFocused(void)
670 {
671 TRACELOG(LOG_WARNING, "SetWindowFocused() not available on target platform");
672 }
673
674 // Get native window handle
675 void *GetWindowHandle(void)
676 {
677 TRACELOG(LOG_WARNING, "GetWindowHandle() not implemented on target platform");
678 return NULL;
679 }
680
681 // Get number of monitors
682 int GetMonitorCount(void)
683 {
684 TRACELOG(LOG_WARNING, "GetMonitorCount() not implemented on target platform");
685 return 1;
686 }
687
688 // Get current monitor where window is placed
689 int GetCurrentMonitor(void)
690 {
691 TRACELOG(LOG_WARNING, "GetCurrentMonitor() not implemented on target platform");
692 return 0;
693 }
694
695 // Get selected monitor position
696 Vector2 GetMonitorPosition(int monitor)
697 {
698 TRACELOG(LOG_WARNING, "GetMonitorPosition() not implemented on target platform");
699 return (Vector2){ 0, 0 };
700 }
701
702 // Get selected monitor width (currently used by monitor)
703 int GetMonitorWidth(int monitor)
704 {
705 // Get the width of the user's entire screen in CSS logical pixels,
706 // no physical pixels, it would require multiplying by device pixel ratio
707 // NOTE: Returned value is limited to the current monitor where the browser window is located
708 int width = 0;
709 width = EM_ASM_INT( { return window.screen.width; }, 0);
710 return width;
711 }
712
713 // Get selected monitor height (currently used by monitor)
714 int GetMonitorHeight(int monitor)
715 {
716 // Get the height of the user's entire screen in CSS logical pixels,
717 // no physical pixels, it would require multiplying by device pixel ratio
718 // NOTE: Returned value is limited to the current monitor where the browser window is located
719 int height = 0;
720 height = EM_ASM_INT( { return window.screen.height; }, 0);
721 return height;
722 }
723
724 // Get selected monitor physical width in millimetres
725 int GetMonitorPhysicalWidth(int monitor)
726 {
727 TRACELOG(LOG_WARNING, "GetMonitorPhysicalWidth() not implemented on target platform");
728 return 0;
729 }
730
731 // Get selected monitor physical height in millimetres
732 int GetMonitorPhysicalHeight(int monitor)
733 {
734 TRACELOG(LOG_WARNING, "GetMonitorPhysicalHeight() not implemented on target platform");
735 return 0;
736 }
737
738 // Get selected monitor refresh rate
739 int GetMonitorRefreshRate(int monitor)
740 {
741 TRACELOG(LOG_WARNING, "GetMonitorRefreshRate() not implemented on target platform");
742 return 0;
743 }
744
745 // Get the human-readable, UTF-8 encoded name of the selected monitor
746 const char *GetMonitorName(int monitor)
747 {
748 TRACELOG(LOG_WARNING, "GetMonitorName() not implemented on target platform");
749 return "";
750 }
751
752 // Get window position XY on monitor
753 Vector2 GetWindowPosition(void)
754 {
755 // Browser window position, top-left corner relative to the physical screen origin, expressed in CSS logical pixels
756 // NOTE: Returned position is relative to the current monitor where the browser window is located
757 Vector2 position = { 0, 0 };
758 position.x = (float)EM_ASM_INT( { return window.screenX; }, 0);
759 position.y = (float)EM_ASM_INT( { return window.screenY; }, 0);
760 return position;
761 }
762
763 // Get current monitor device pixel ratio
764 Vector2 GetWindowScaleDPI(void)
765 {
766 // Get device pixel ratio
767 // NOTE: Returned scale is relative to the current monitor where the browser window is located
768 Vector2 scale = { 1.0f, 1.0f };
769 scale.x = (float)EM_ASM_DOUBLE( { return window.devicePixelRatio; } );
770 scale.y = scale.x;
771 return scale;
772 }
773
774 // Set clipboard text content
775 void SetClipboardText(const char *text)
776 {
777 // Security check to (partially) avoid malicious code
778 if (strchr(text, '\'') != NULL) TRACELOG(LOG_WARNING, "SYSTEM: Provided Clipboard could be potentially malicious, avoid [\'] character");
779 else EM_ASM({ navigator.clipboard.writeText(UTF8ToString($0)); }, text);
780 }
781
782 // Async EM_JS to be able to await clickboard read asynchronous function
783 EM_ASYNC_JS(void, RequestClipboardData, (void), {
784 if (navigator.clipboard && window.isSecureContext)
785 {
786 let items = await navigator.clipboard.read();
787 for (const item of items)
788 {
789 // Check if this item contains plain text or image
790 if (item.types.includes("text/plain"))
791 {
792 const blob = await item.getType("text/plain");
793 const text = await blob.text();
794 window._lastClipboardString = text;
795 }
796 else if (item.types.find(t => t.startsWith("image/")))
797 {
798 const blob = await item.getType(item.types.find(t => t.startsWith("image/")));
799 const bitmap = await createImageBitmap(blob);
800
801 const canvas = document.createElement('canvas');
802 canvas.width = bitmap.width;
803 canvas.height = bitmap.height;
804 const ctx = canvas.getContext('2d');
805 ctx.drawImage(bitmap, 0, 0);
806
807 const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
808
809 // Store image and data for the Fetch function
810 window._lastImgWidth = canvas.width;
811 window._lastImgHeight = canvas.height;
812 window._lastImgData = imgData;
813 }
814 }
815 }
816 else console.warn("Clipboard read() requires HTTPS/Localhost");
817 });
818
819 // Returns the string created by RequestClipboardData from JS memory to Emscripten C memory
820 EM_JS(char *, GetLastPastedText, (void), {
821 var str = window._lastClipboardString || "";
822 var length = lengthBytesUTF8(str) + 1;
823 if (length > 1)
824 {
825 var ptr = _malloc(length);
826 stringToUTF8(str, ptr, length);
827 return ptr;
828 }
829 return 0;
830 });
831
832 // Returns the image created by RequestClipboardData from JS memory to Emscripten C memory
833 EM_JS(unsigned char *, GetLastPastedImage, (int *width, int *height), {
834 if (window._lastImgData)
835 {
836 const data = window._lastImgData;
837 if (data.length > 0)
838 {
839 const ptr = _malloc(data.length);
840 HEAPU8.set(data, ptr);
841
842 // Set the width and height via the pointers passed from C
843 // HEAP32 handles the 4-byte integers
844 if (width) setValue(width, window._lastImgWidth, 'i32');
845 if (height) setValue(height, window._lastImgHeight, 'i32');
846
847 // Clear the JS buffer so there is no need to fetch the same image twice
848 window._lastImgData = null;
849
850 return ptr;
851 }
852 }
853
854 return 0;
855 });
856
857 // Get clipboard text content
858 // NOTE: returned string is allocated and freed by GLFW
859 const char *GetClipboardText(void)
860 {
861 RequestClipboardData();
862 return GetLastPastedText();
863 }
864
865 // Get clipboard image
866 Image GetClipboardImage(void)
867 {
868 Image image = { 0 };
869 int w = 0, h = 0;
870 RequestClipboardData();
871 unsigned char* data = GetLastPastedImage(&w, &h);
872 if (data != NULL) {
873 image.data = data;
874 image.width = w;
875 image.height = h;
876 image.mipmaps = 1;
877 image.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
878 }
879
880 return image;
881 }
882
883 // Show mouse cursor
884 void ShowCursor(void)
885 {
886 if (CORE.Input.Mouse.cursorHidden)
887 {
888 EM_ASM( { Module.canvas.style.cursor = UTF8ToString($0); }, cursorLUT[CORE.Input.Mouse.cursor]);
889
890 CORE.Input.Mouse.cursorHidden = false;
891 }
892 }
893
894 // Hides mouse cursor
895 void HideCursor(void)
896 {
897 if (!CORE.Input.Mouse.cursorHidden)
898 {
899 EM_ASM(Module.canvas.style.cursor = 'none';);
900
901 CORE.Input.Mouse.cursorHidden = true;
902 }
903 }
904
905 // Enables cursor (unlock cursor)
906 void EnableCursor(void)
907 {
908 emscripten_exit_pointerlock();
909
910 // Set cursor position in the middle
911 SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);
912
913 // NOTE: CORE.Input.Mouse.cursorLocked handled by EmscriptenPointerlockCallback()
914 }
915
916 // Disables cursor (lock cursor)
917 void DisableCursor(void)
918 {
919 emscripten_request_pointerlock(platform.canvasId, 1);
920
921 // Set cursor position in the middle
922 SetMousePosition(CORE.Window.screen.width/2, CORE.Window.screen.height/2);
923
924 // NOTE: CORE.Input.Mouse.cursorLocked handled by EmscriptenPointerlockCallback()
925 }
926
927 // Swap back buffer with front buffer (screen drawing)
928 void SwapScreenBuffer(void)
929 {
930 #if defined(GRAPHICS_API_OPENGL_SOFTWARE)
931 // Update framebuffer
932 rlCopyFramebuffer(0, 0, CORE.Window.render.width, CORE.Window.render.height, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, platform.pixels);
933
934 // Copy framebuffer data into canvas
935 EM_ASM({
936 const width = $0;
937 const height = $1;
938 const ptr = $2;
939
940 // Get canvas and 2d context created
941 const canvas = Module.canvas;
942 //const canvas = Module['canvas'];
943 const ctx = canvas.getContext('2d');
944
945 if (!Module.__img || (Module.__img.width !== width) || (Module.__img.height !== height))
946 {
947 Module.__img = ctx.createImageData(width, height);
948 }
949
950 const src = HEAPU8.subarray(ptr, ptr + width*height*4); // RGBA (4 bytes)
951 Module.__img.data.set(src);
952 ctx.putImageData(Module.__img, 0, 0);
953
954 }, CORE.Window.screen.width, CORE.Window.screen.height, platform.pixels);
955 #endif
956 }
957
958 //----------------------------------------------------------------------------------
959 // Module Functions Definition: Misc
960 //----------------------------------------------------------------------------------
961
962 // Get elapsed time measure in seconds since InitTimer()
963 double GetTime(void)
964 {
965 double time = emscripten_get_now()*1000.0;
966
967 return time;
968 }
969
970 // Open URL with default system browser (if available)
971 // NOTE: This function is only safe to use if the provided URL is safe
972 // A user could craft a malicious string performing another action
973 // Avoid calling this function with user input non-validated strings
974 void OpenURL(const char *url)
975 {
976 // Security check to (partially) avoid malicious code on target platform
977 if (strchr(url, '\'') != NULL) TRACELOG(LOG_WARNING, "SYSTEM: Provided URL could be potentially malicious, avoid [\'] character");
978 else emscripten_run_script(TextFormat("window.open('%s', '_blank')", url));
979 }
980
981 //----------------------------------------------------------------------------------
982 // Module Functions Definition: Inputs
983 //----------------------------------------------------------------------------------
984
985 // Set internal gamepad mappings
986 int SetGamepadMappings(const char *mappings)
987 {
988 TRACELOG(LOG_INFO, "SetGamepadMappings not implemented in rcore_web.c");
989
990 return 0;
991 }
992
993 // Set gamepad vibration
994 void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration)
995 {
996 if ((gamepad < MAX_GAMEPADS) && CORE.Input.Gamepad.ready[gamepad] && (duration > 0.0f))
997 {
998 if (leftMotor < 0.0f) leftMotor = 0.0f;
999 if (leftMotor > 1.0f) leftMotor = 1.0f;
1000 if (rightMotor < 0.0f) rightMotor = 0.0f;
1001 if (rightMotor > 1.0f) rightMotor = 1.0f;
1002 if (duration > MAX_GAMEPAD_VIBRATION_TIME) duration = MAX_GAMEPAD_VIBRATION_TIME;
1003 duration *= 1000.0f; // Convert duration to ms
1004
1005 // NOTE: [2024.10.21] Current browser support:
1006 // - vibrationActuator API: Chrome, Edge, Opera, Safari, Android Chrome, Android Webview
1007 // - hapticActuators API: Firefox
1008 EM_ASM({
1009 try { navigator.getGamepads()[$0].vibrationActuator.playEffect('dual-rumble', { startDelay: 0, duration: $3, weakMagnitude: $1, strongMagnitude: $2 }); }
1010 catch (e)
1011 {
1012 try { navigator.getGamepads()[$0].hapticActuators[0].pulse($2, $3); }
1013 catch (e) { }
1014 }
1015 }, gamepad, leftMotor, rightMotor, duration);
1016 }
1017 }
1018
1019 // Set mouse position XY
1020 void SetMousePosition(int x, int y)
1021 {
1022 // WARNING: Not supported by browser for security reasons
1023 }
1024
1025 // Set mouse cursor
1026 void SetMouseCursor(int cursor)
1027 {
1028 if (CORE.Input.Mouse.cursor != cursor)
1029 {
1030 if (!CORE.Input.Mouse.cursorLocked) EM_ASM( { Module.canvas.style.cursor = UTF8ToString($0); }, cursorLUT[cursor]);
1031 CORE.Input.Mouse.cursor = cursor;
1032 }
1033 }
1034
1035 // Get physical key name
1036 const char *GetKeyName(int key)
1037 {
1038 // TODO: Browser can definitely provide a key name e->key
1039 TRACELOG(LOG_WARNING, "GetKeyName() not implemented on target platform");
1040 return "";
1041 }
1042
1043 // Register all input events
1044 void PollInputEvents(void)
1045 {
1046 #if SUPPORT_GESTURES_SYSTEM
1047 // NOTE: Gestures update must be called every frame to reset gestures correctly
1048 // because ProcessGestureEvent() is called on an event, not every frame
1049 UpdateGestures();
1050 #endif
1051
1052 // Reset keys/chars pressed registered
1053 CORE.Input.Keyboard.keyPressedQueueCount = 0;
1054 CORE.Input.Keyboard.charPressedQueueCount = 0;
1055
1056 // Reset last gamepad button/axis registered state
1057 CORE.Input.Gamepad.lastButtonPressed = 0; // GAMEPAD_BUTTON_UNKNOWN
1058 //CORE.Input.Gamepad.axisCount = 0;
1059
1060 // Keyboard/Mouse input polling (automatically managed by GLFW3 through callback)
1061
1062 // Register previous keys states
1063 for (int i = 0; i < MAX_KEYBOARD_KEYS; i++)
1064 {
1065 CORE.Input.Keyboard.previousKeyState[i] = CORE.Input.Keyboard.currentKeyState[i];
1066 CORE.Input.Keyboard.keyRepeatInFrame[i] = 0;
1067 }
1068
1069 // Register previous mouse states
1070 for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) CORE.Input.Mouse.previousButtonState[i] = CORE.Input.Mouse.currentButtonState[i];
1071
1072 // Register previous mouse wheel state
1073 CORE.Input.Mouse.previousWheelMove = CORE.Input.Mouse.currentWheelMove;
1074 CORE.Input.Mouse.currentWheelMove = (Vector2){ 0.0f, 0.0f };
1075
1076 // Register previous mouse position
1077 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.currentPosition;
1078
1079 // Register previous touch states
1080 for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.previousTouchState[i] = CORE.Input.Touch.currentTouchState[i];
1081
1082 // Reset touch positions
1083 // TODO: It resets on target platform the mouse position and not filled again until a move-event,
1084 // so, if mouse is not moved it returns a (0, 0) position... this behaviour should be reviewed!
1085 //for (int i = 0; i < MAX_TOUCH_POINTS; i++) CORE.Input.Touch.position[i] = (Vector2){ 0, 0 };
1086
1087 // Get number of gamepads connected
1088 int numGamepads = 0;
1089 if (emscripten_sample_gamepad_data() == EMSCRIPTEN_RESULT_SUCCESS) numGamepads = emscripten_get_num_gamepads();
1090
1091 for (int i = 0; (i < numGamepads) && (i < MAX_GAMEPADS); i++)
1092 {
1093 // Register previous gamepad button states
1094 for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) CORE.Input.Gamepad.previousButtonState[i][k] = CORE.Input.Gamepad.currentButtonState[i][k];
1095
1096 EmscriptenGamepadEvent gamepadState = { 0 };
1097 int result = emscripten_get_gamepad_status(i, &gamepadState);
1098
1099 if (result == EMSCRIPTEN_RESULT_SUCCESS)
1100 {
1101 // Register buttons data for every connected gamepad
1102 for (int j = 0; (j < gamepadState.numButtons) && (j < MAX_GAMEPAD_BUTTONS); j++)
1103 {
1104 GamepadButton button = -1;
1105
1106 // Gamepad Buttons reference: https://www.w3.org/TR/gamepad/#gamepad-interface
1107 switch (j)
1108 {
1109 case 0: button = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break;
1110 case 1: button = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break;
1111 case 2: button = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break;
1112 case 3: button = GAMEPAD_BUTTON_RIGHT_FACE_UP; break;
1113 case 4: button = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break;
1114 case 5: button = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break;
1115 case 6: button = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break;
1116 case 7: button = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break;
1117 case 8: button = GAMEPAD_BUTTON_MIDDLE_LEFT; break;
1118 case 9: button = GAMEPAD_BUTTON_MIDDLE_RIGHT; break;
1119 case 10: button = GAMEPAD_BUTTON_LEFT_THUMB; break;
1120 case 11: button = GAMEPAD_BUTTON_RIGHT_THUMB; break;
1121 case 12: button = GAMEPAD_BUTTON_LEFT_FACE_UP; break;
1122 case 13: button = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break;
1123 case 14: button = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break;
1124 case 15: button = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break;
1125 default: break;
1126 }
1127
1128 if (button + 1 != 0) // Check for valid button
1129 {
1130 if (gamepadState.digitalButton[j] == 1)
1131 {
1132 CORE.Input.Gamepad.currentButtonState[i][button] = 1;
1133 CORE.Input.Gamepad.lastButtonPressed = button;
1134 }
1135 else CORE.Input.Gamepad.currentButtonState[i][button] = 0;
1136 }
1137
1138 //TRACELOG(LOG_DEBUG, "INPUT: Gamepad %d, button %d: Digital: %d, Analog: %g", gamepadState.index, j, gamepadState.digitalButton[j], gamepadState.analogButton[j]);
1139 }
1140
1141 // Register axis data for every connected gamepad
1142 for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXES); j++)
1143 {
1144 CORE.Input.Gamepad.axisState[i][j] = gamepadState.axis[j];
1145 }
1146
1147 CORE.Input.Gamepad.axisCount[i] = gamepadState.numAxes;
1148 }
1149 }
1150
1151 CORE.Window.resizedLastFrame = false;
1152 }
1153
1154 //----------------------------------------------------------------------------------
1155 // Module Internal Functions Definition
1156 //----------------------------------------------------------------------------------
1157
1158 // Initialize platform: graphics, inputs and more
1159 int InitPlatform(void)
1160 {
1161 SetCanvasIdJs(platform.canvasId, 64); // Get the current canvas id
1162
1163 // Initialize graphic device: display/window and graphic context
1164 //----------------------------------------------------------------------------
1165 emscripten_set_canvas_element_size(platform.canvasId, CORE.Window.screen.width, CORE.Window.screen.height);
1166 EmscriptenWebGLContextAttributes attribs = { 0 };
1167 emscripten_webgl_init_context_attributes(&attribs);
1168 attribs.alpha = EM_TRUE;
1169 attribs.depth = EM_TRUE;
1170 attribs.stencil = EM_FALSE;
1171 attribs.antialias = EM_FALSE;
1172
1173 // Check window creation flags
1174 // Disable FLAG_WINDOW_MINIMIZED, not supported
1175 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MINIMIZED)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MINIMIZED);
1176
1177 // Disable FLAG_WINDOW_MAXIMIZED, not supported
1178 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_MAXIMIZED);
1179
1180 // Disable FLAG_WINDOW_TOPMOST, not supported
1181 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_TOPMOST)) FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_TOPMOST);
1182
1183 // NOTE: Some other flags are not supported on HTML5
1184
1185 // TODO: Scale content area based on the monitor content scale where window is placed on
1186
1187 // Request MSAA (usually x4 on WebGL 1.0)
1188 if (FLAG_IS_SET(CORE.Window.flags, FLAG_MSAA_4X_HINT)) attribs.antialias = EM_TRUE;
1189
1190 // Check selection OpenGL version
1191 if (rlGetVersion() == RL_OPENGL_SOFTWARE)
1192 {
1193 // Avoid creating a WebGL canvas, create 2d canvas for software rendering
1194 emscripten_set_canvas_element_size(platform.canvasId, CORE.Window.screen.width, CORE.Window.screen.height);
1195 EM_ASM({
1196 const canvas = document.getElementById(platform.canvasId);
1197 Module.canvas = canvas;
1198 });
1199
1200 // Load memory framebuffer with desired screen size
1201 platform.pixels = (unsigned int *)RL_CALLOC(CORE.Window.screen.width*CORE.Window.screen.height, sizeof(unsigned int));
1202 }
1203 else if (rlGetVersion() == RL_OPENGL_ES_20) // Request OpenGL ES 2.0 context --> WebGL 1.0
1204 {
1205 attribs.majorVersion = 1; // WebGL 1.0 requested
1206 attribs.minorVersion = 0;
1207
1208 // Create WebGL context
1209 platform.glContext = emscripten_webgl_create_context(platform.canvasId, &attribs);
1210 if (platform.glContext == 0) return 0;
1211
1212 emscripten_webgl_make_context_current(platform.glContext);
1213 }
1214 else if (rlGetVersion() == RL_OPENGL_ES_30) // Request OpenGL ES 3.0 context --> WebGL 2.0
1215 {
1216 attribs.majorVersion = 2; // WebGL 2.0 requested
1217 attribs.minorVersion = 0;
1218
1219 // Create WebGL context
1220 platform.glContext = emscripten_webgl_create_context(platform.canvasId, &attribs);
1221 if (platform.glContext == 0) return 0;
1222
1223 emscripten_webgl_make_context_current(platform.glContext);
1224 }
1225
1226 // NOTE: Getting video modes is not implemented in emscripten GLFW3 version
1227 CORE.Window.display.width = CORE.Window.screen.width;
1228 CORE.Window.display.height = CORE.Window.screen.height;
1229 CORE.Window.render.width = CORE.Window.screen.width;
1230 CORE.Window.render.height = CORE.Window.screen.height;
1231
1232 // Set default window title
1233 emscripten_set_window_title((CORE.Window.title != 0)? CORE.Window.title : " ");
1234
1235 // Check context activation
1236 if ((platform.glContext != 0) || (platform.pixels != NULL))
1237 {
1238 CORE.Window.ready = true;
1239
1240 int fbWidth = CORE.Window.screen.width;
1241 int fbHeight = CORE.Window.screen.height;
1242
1243 CORE.Window.render.width = fbWidth;
1244 CORE.Window.render.height = fbHeight;
1245 CORE.Window.currentFbo.width = fbWidth;
1246 CORE.Window.currentFbo.height = fbHeight;
1247
1248 TRACELOG(LOG_INFO, "DISPLAY: Device initialized successfully %s",
1249 FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI)? "(HighDPI)" : "");
1250 TRACELOG(LOG_INFO, " > Display size: %i x %i", CORE.Window.display.width, CORE.Window.display.height);
1251 TRACELOG(LOG_INFO, " > Screen size: %i x %i", CORE.Window.screen.width, CORE.Window.screen.height);
1252 TRACELOG(LOG_INFO, " > Render size: %i x %i", CORE.Window.render.width, CORE.Window.render.height);
1253 TRACELOG(LOG_INFO, " > Viewport offsets: %i, %i", CORE.Window.renderOffset.x, CORE.Window.renderOffset.y);
1254 }
1255 else
1256 {
1257 TRACELOG(LOG_FATAL, "PLATFORM: Failed to initialize graphics device");
1258 return -1;
1259 }
1260
1261 // Load OpenGL extensions
1262 // NOTE: GL procedures address loader is required to load extensions
1263 if (platform.glContext != 0) rlLoadExtensions(emscripten_webgl_get_proc_address);
1264 //----------------------------------------------------------------------------
1265
1266 // Initialize events callbacks
1267 //----------------------------------------------------------------------------
1268 // Setup window/canvas events callbacks
1269 emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 1, EmscriptenFullscreenChangeCallback);
1270 emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 1, EmscriptenResizeCallback);
1271 emscripten_set_blur_callback(platform.canvasId, NULL, 1, EmscriptenFocusCallback);
1272 emscripten_set_focus_callback(platform.canvasId, NULL, 1, EmscriptenFocusCallback);
1273 emscripten_set_visibilitychange_callback(NULL, 1, EmscriptenVisibilityChangeCallback);
1274
1275 // Setup input events
1276 emscripten_set_keypress_callback(platform.canvasId, NULL, 1, EmscriptenKeyboardCallback);
1277 emscripten_set_keydown_callback(platform.canvasId, NULL, 1, EmscriptenKeyboardCallback);
1278 emscripten_set_keyup_callback(platform.canvasId, NULL, 1, EmscriptenKeyboardCallback);
1279
1280 emscripten_set_click_callback(platform.canvasId, NULL, 1, EmscriptenMouseCallback);
1281 //emscripten_set_dblclick_callback(platform.canvasId, NULL, 1, EmscriptenMouseCallback);
1282 emscripten_set_mousedown_callback(platform.canvasId, NULL, 1, EmscriptenMouseCallback);
1283 emscripten_set_mouseup_callback(platform.canvasId, NULL, 1, EmscriptenMouseCallback);
1284 emscripten_set_mousemove_callback(platform.canvasId, NULL, 1, EmscriptenMouseCallback);
1285 emscripten_set_mousemove_callback(platform.canvasId, NULL, 1, EmscriptenMouseMoveCallback);
1286 emscripten_set_wheel_callback(platform.canvasId, NULL, 1, EmscriptenMouseWheelCallback);
1287 emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 1, EmscriptenPointerlockCallback);
1288
1289 emscripten_set_touchstart_callback(platform.canvasId, NULL, 1, EmscriptenTouchCallback);
1290 emscripten_set_touchend_callback(platform.canvasId, NULL, 1, EmscriptenTouchCallback);
1291 emscripten_set_touchmove_callback(platform.canvasId, NULL, 1, EmscriptenTouchCallback);
1292 emscripten_set_touchcancel_callback(platform.canvasId, NULL, 1, EmscriptenTouchCallback);
1293
1294 emscripten_set_gamepadconnected_callback(NULL, 1, EmscriptenGamepadCallback);
1295 emscripten_set_gamepaddisconnected_callback(NULL, 1, EmscriptenGamepadCallback);
1296
1297 // Trigger resize callback to force initial size
1298 EmscriptenResizeCallback(EMSCRIPTEN_EVENT_RESIZE, NULL, NULL);
1299 //----------------------------------------------------------------------------
1300
1301 // Initialize timing system
1302 //----------------------------------------------------------------------------
1303 InitTimer();
1304 //----------------------------------------------------------------------------
1305
1306 // Initialize storage system
1307 //----------------------------------------------------------------------------
1308 CORE.Storage.basePath = GetWorkingDirectory();
1309 //----------------------------------------------------------------------------
1310
1311 TRACELOG(LOG_INFO, "PLATFORM: WEB: Initialized successfully");
1312
1313 return 0;
1314 }
1315
1316 // Close platform
1317 // NOTE: Platform closing is managed by browser, so,
1318 // this function is actually not required, but still
1319 // implementing some logic behaviour
1320 void ClosePlatform(void)
1321 {
1322 if (platform.pixels != NULL) RL_FREE(platform.pixels);
1323 if (platform.glContext != 0) emscripten_webgl_destroy_context(platform.glContext);
1324 }
1325
1326 // Emscripten callback functions, called on specific browser events
1327 //-------------------------------------------------------------------------------------------------------
1328 // Emscripten: Called on resize event
1329 static EM_BOOL EmscriptenResizeCallback(int eventType, const EmscriptenUiEvent *event, void *userData)
1330 {
1331 // Don't resize non-resizeable windows
1332 if (!FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_RESIZABLE)) return 1;
1333 /*
1334 // Set current screen size
1335 if (FLAG_IS_SET(CORE.Window.flags, FLAG_WINDOW_HIGHDPI))
1336 {
1337 Vector2 windowScaleDPI = GetWindowScaleDPI();
1338
1339 CORE.Window.screen.width = (unsigned int)(width/windowScaleDPI.x);
1340 CORE.Window.screen.height = (unsigned int)(height/windowScaleDPI.y);
1341 }
1342 else
1343 {
1344 CORE.Window.screen.width = width;
1345 CORE.Window.screen.height = height;
1346 }
1347 */
1348 // This event is called whenever the window changes sizes,
1349 // so the size of the canvas object is explicitly retrieved below
1350 int width = EM_ASM_INT( return window.innerWidth; );
1351 int height = EM_ASM_INT( return window.innerHeight; );
1352
1353 if (width < (int)CORE.Window.screenMin.width) width = CORE.Window.screenMin.width;
1354 else if ((width > (int)CORE.Window.screenMax.width) && (CORE.Window.screenMax.width > 0)) width = CORE.Window.screenMax.width;
1355
1356 if (height < (int)CORE.Window.screenMin.height) height = CORE.Window.screenMin.height;
1357 else if ((height > (int)CORE.Window.screenMax.height) && (CORE.Window.screenMax.height > 0)) height = CORE.Window.screenMax.height;
1358
1359 emscripten_set_canvas_element_size(platform.canvasId, width, height);
1360
1361 SetupViewport(width, height); // Reset viewport and projection matrix for new size
1362
1363 CORE.Window.currentFbo.width = width;
1364 CORE.Window.currentFbo.height = height;
1365 CORE.Window.resizedLastFrame = true;
1366
1367 if (IsWindowFullscreen()) return 1;
1368
1369 // Set current screen size
1370 CORE.Window.screen.width = width;
1371 CORE.Window.screen.height = height;
1372
1373 // NOTE: Postprocessing texture is not scaled to new size
1374
1375 return 0;
1376 }
1377
1378 // Emscripten: Called on windows focus change events
1379 static EM_BOOL EmscriptenFocusCallback(int eventType, const EmscriptenFocusEvent *focusEvent, void *userData)
1380 {
1381 EM_BOOL consumed = 1;
1382
1383 switch (eventType)
1384 {
1385 case EMSCRIPTEN_EVENT_BLUR: FLAG_SET(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED); break;
1386 case EMSCRIPTEN_EVENT_FOCUS: FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_UNFOCUSED); break;
1387 default: consumed = 0; break;
1388 }
1389
1390 return consumed;
1391 }
1392
1393 // Emscripten: Called on visibility change events
1394 static EM_BOOL EmscriptenVisibilityChangeCallback(int eventType, const EmscriptenVisibilityChangeEvent *visibilityChangeEvent, void *userData)
1395 {
1396 if (visibilityChangeEvent->hidden) FLAG_SET(CORE.Window.flags, FLAG_WINDOW_HIDDEN); // The window was hidden
1397 else FLAG_CLEAR(CORE.Window.flags, FLAG_WINDOW_HIDDEN); // The window was restored
1398
1399 return 1; // The event was consumed by the callback handler
1400 }
1401
1402 // Emscripten: Called on fullscreen change events
1403 // TODO: Review fullscreen strategy
1404 static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *event, void *userData)
1405 {
1406 // NOTE: Reset the fullscreen flags if the user left fullscreen manually by pressing the Escape key
1407 const bool wasFullscreen = EM_ASM_INT( { if (document.fullscreenElement) return 1; }, 0);
1408 if (!wasFullscreen)
1409 {
1410 FLAG_CLEAR(CORE.Window.flags, FLAG_FULLSCREEN_MODE);
1411 FLAG_CLEAR(CORE.Window.flags, FLAG_BORDERLESS_WINDOWED_MODE);
1412 }
1413
1414 return 1; // The event was consumed by the callback handler
1415 }
1416
1417 /*
1418 // GLFW3: Called on file-drop over the window
1419 // TODO: Implement Emscripten (or HTML5/JS) alternative
1420 static void WindowDropCallback(GLFWwindow *window, int count, const char **paths)
1421 {
1422 if (count > 0)
1423 {
1424 // In case previous dropped filepaths have not been freed, free them
1425 if (CORE.Window.dropFileCount > 0)
1426 {
1427 for (unsigned int i = 0; i < CORE.Window.dropFileCount; i++) RL_FREE(CORE.Window.dropFilepaths[i]);
1428
1429 RL_FREE(CORE.Window.dropFilepaths);
1430
1431 CORE.Window.dropFileCount = 0;
1432 CORE.Window.dropFilepaths = NULL;
1433 }
1434
1435 // WARNING: Paths are freed by GLFW when the callback returns, an internal copy should be kept
1436 CORE.Window.dropFileCount = count;
1437 CORE.Window.dropFilepaths = (char **)RL_CALLOC(CORE.Window.dropFileCount, sizeof(char *));
1438
1439 for (unsigned int i = 0; i < CORE.Window.dropFileCount; i++)
1440 {
1441 CORE.Window.dropFilepaths[i] = (char *)RL_CALLOC(MAX_FILEPATH_LENGTH, sizeof(char));
1442 strncpy(CORE.Window.dropFilepaths[i], paths[i], MAX_FILEPATH_LENGTH - 1);
1443 }
1444 }
1445 }
1446 */
1447
1448 // Emscripten: Called on key events
1449 // TODO: keyCodes should be mapped to raylib/GLFW3 Key values
1450 static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyboardEvent, void *userData)
1451 {
1452 switch (eventType)
1453 {
1454 case EMSCRIPTEN_EVENT_KEYPRESS:
1455 {
1456 if (keyboardEvent->repeat) CORE.Input.Keyboard.keyRepeatInFrame[keyboardEvent->keyCode] = 1;
1457 } break;
1458 case EMSCRIPTEN_EVENT_KEYDOWN:
1459 {
1460 CORE.Input.Keyboard.currentKeyState[keyboardEvent->keyCode] = 1;
1461 } break;
1462 case EMSCRIPTEN_EVENT_KEYUP:
1463 {
1464 CORE.Input.Keyboard.currentKeyState[keyboardEvent->keyCode] = 0;
1465 } break;
1466 default: break;
1467 }
1468
1469 // TODO: Add char codes
1470 //unsigned int charCode
1471 // Check if there is space available in the queue for characters to be added
1472 /*
1473 if (CORE.Input.Keyboard.charPressedQueueCount < MAX_CHAR_PRESSED_QUEUE)
1474 {
1475 // Add character to the queue
1476 CORE.Input.Keyboard.charPressedQueue[CORE.Input.Keyboard.charPressedQueueCount] = keyboardEvent->charCode;
1477 CORE.Input.Keyboard.charPressedQueueCount++;
1478 }
1479 */
1480 /*
1481 // Check if there is space available in the key queue
1482 if ((CORE.Input.Keyboard.keyPressedQueueCount < MAX_KEY_PRESSED_QUEUE) && (eventType == EMSCRIPTEN_EVENT_KEYPRESS))
1483 {
1484 // Add character to the queue
1485 CORE.Input.Keyboard.keyPressedQueue[CORE.Input.Keyboard.keyPressedQueueCount] = keyboardEvent->keyCode;
1486 CORE.Input.Keyboard.keyPressedQueueCount++;
1487 }
1488
1489 // Check the exit key to set close window
1490 //if ((keyboardEvent->keyCode == CORE.Input.Keyboard.exitKey) && (eventType == EMSCRIPTEN_EVENT_KEYPRESS)) CORE.Window.shouldClose = true;
1491 */
1492
1493 return 1; // The event was consumed by the callback handler
1494 }
1495
1496 // Emscripten: Called on mouse input events
1497 static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
1498 {
1499 switch (eventType)
1500 {
1501 case EMSCRIPTEN_EVENT_MOUSEENTER: CORE.Input.Mouse.cursorOnScreen = true; break;
1502 case EMSCRIPTEN_EVENT_MOUSELEAVE: CORE.Input.Mouse.cursorOnScreen = false; break;
1503 case EMSCRIPTEN_EVENT_MOUSEDOWN:
1504 {
1505 // NOTE: Emscripten and raylib buttons indices are not aligned
1506 if (mouseEvent->button == 0) CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = 1;
1507 else if (mouseEvent->button == 1) CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_MIDDLE] = 1;
1508 else if (mouseEvent->button == 2) CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_RIGHT] = 1;
1509
1510 //CORE.Input.Touch.currentTouchState[button] = action;
1511 } break;
1512 case EMSCRIPTEN_EVENT_MOUSEUP:
1513 {
1514 if (mouseEvent->button == 0) CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] = 0;
1515 else if (mouseEvent->button == 1) CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_MIDDLE] = 0;
1516 else if (mouseEvent->button == 2) CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_RIGHT] = 0;
1517 } break;
1518 default: break;
1519 }
1520
1521 #if SUPPORT_GESTURES_SYSTEM && SUPPORT_MOUSE_GESTURES
1522 // Process mouse events as touches to be able to use mouse-gestures
1523 GestureEvent gestureEvent = { 0 };
1524
1525 // Register touch actions
1526 if ((CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] == 1) && (CORE.Input.Mouse.previousButtonState[MOUSE_BUTTON_LEFT] == 0)) gestureEvent.touchAction = TOUCH_ACTION_DOWN;
1527 else if ((CORE.Input.Mouse.currentButtonState[MOUSE_BUTTON_LEFT] == 0) && (CORE.Input.Mouse.previousButtonState[MOUSE_BUTTON_LEFT] == 1)) gestureEvent.touchAction = TOUCH_ACTION_UP;
1528
1529 // NOTE: TOUCH_ACTION_MOVE event is registered in MouseMoveCallback()
1530
1531 // Assign a pointer ID
1532 gestureEvent.pointId[0] = 0;
1533
1534 // Register touch points count
1535 gestureEvent.pointCount = 1;
1536
1537 // Register touch points position, only one point registered
1538 gestureEvent.position[0] = GetMousePosition();
1539
1540 // Normalize gestureEvent.position[0] for CORE.Window.screen.width and CORE.Window.screen.height
1541 gestureEvent.position[0].x /= (float)GetScreenWidth();
1542 gestureEvent.position[0].y /= (float)GetScreenHeight();
1543
1544 // Gesture data is sent to gestures-system for processing
1545 // Prevent calling ProcessGestureEvent() when Emscripten is present and there's a touch gesture, so EmscriptenTouchCallback() can handle it itself
1546 if (GetMouseX() != 0 || GetMouseY() != 0) ProcessGestureEvent(gestureEvent);
1547 #endif
1548
1549 return 1; // The event was consumed by the callback handler
1550 }
1551
1552 // Emscripten: Called on mouse move events
1553 static EM_BOOL EmscriptenMouseMoveCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData)
1554 {
1555 if (CORE.Input.Mouse.cursorLocked)
1556 {
1557 CORE.Input.Mouse.previousPosition.x = CORE.Input.Mouse.lockedPosition.x - mouseEvent->movementX;
1558 CORE.Input.Mouse.previousPosition.y = CORE.Input.Mouse.lockedPosition.y - mouseEvent->movementY;
1559 }
1560 else
1561 {
1562 // Get mouse position in canvas CSS pixels
1563 float mouseCssX = (float)mouseEvent->canvasX;
1564 float mouseCssY = (float)mouseEvent->canvasY;
1565
1566 // Get canvas sizes
1567 double cssWidth = 0.0;
1568 double cssHeight = 0.0;
1569 emscripten_get_element_css_size(platform.canvasId, &cssWidth, &cssHeight);
1570
1571 int fbWidth = 0;
1572 int fbHeight = 0;
1573 emscripten_get_canvas_element_size(platform.canvasId, &fbWidth, &fbHeight);
1574
1575 // Convert CSS to framebuffer coordinates
1576 float scaleX = (float)fbWidth/(float)cssWidth;
1577 float scaleY = (float)fbHeight/(float)cssHeight;
1578
1579 int mouseX = (int)(mouseCssX*scaleX);
1580 int mouseY = (int)(mouseCssY*scaleY);
1581
1582 CORE.Input.Mouse.currentPosition.x = mouseX;//(float)mouseEvent->canvasX;
1583 CORE.Input.Mouse.currentPosition.y = mouseY;//(float)mouseEvent->canvasY;
1584
1585 // Shorter alternative:
1586 //double dpr = emscripten_get_device_pixel_ratio();
1587 //int mouseX = (int)(e->canvasX*dpr);
1588 //int mouseY = (int)(e->canvasY*dpr);
1589
1590 CORE.Input.Touch.position[0] = CORE.Input.Mouse.currentPosition;
1591 }
1592
1593 #if SUPPORT_GESTURES_SYSTEM && SUPPORT_MOUSE_GESTURES
1594 // Process mouse events as touches to be able to use mouse-gestures
1595 GestureEvent gestureEvent = { 0 };
1596
1597 gestureEvent.touchAction = TOUCH_ACTION_MOVE;
1598
1599 // Assign a pointer ID
1600 gestureEvent.pointId[0] = 0;
1601
1602 // Register touch points count
1603 gestureEvent.pointCount = 1;
1604
1605 // Register touch points position, only one point registered
1606 gestureEvent.position[0] = CORE.Input.Touch.position[0];
1607
1608 // Normalize gestureEvent.position[0] for CORE.Window.screen.width and CORE.Window.screen.height
1609 gestureEvent.position[0].x /= (float)GetScreenWidth();
1610 gestureEvent.position[0].y /= (float)GetScreenHeight();
1611
1612 // Gesture data is sent to gestures-system for processing
1613 ProcessGestureEvent(gestureEvent);
1614 #endif
1615
1616 return 1; // The event was consumed by the callback handler
1617 }
1618
1619 // Emscripten: Called on mouse wheel events
1620 static EM_BOOL EmscriptenMouseWheelCallback(int eventType, const EmscriptenWheelEvent *wheelEvent, void *userData)
1621 {
1622 if (eventType == EMSCRIPTEN_EVENT_WHEEL)
1623 {
1624 CORE.Input.Mouse.currentWheelMove.x = (float)wheelEvent->deltaX;
1625 CORE.Input.Mouse.currentWheelMove.y = (float)wheelEvent->deltaY;
1626 }
1627
1628 return 1; // The event was consumed by the callback handler
1629 }
1630
1631 // Emscripten: Called on pointer lock events
1632 static EM_BOOL EmscriptenPointerlockCallback(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData)
1633 {
1634 CORE.Input.Mouse.cursorLocked = EM_ASM_INT( { if (document.pointerLockElement) return 1; }, 0);
1635
1636 if (CORE.Input.Mouse.cursorLocked)
1637 {
1638 CORE.Input.Mouse.lockedPosition = CORE.Input.Mouse.currentPosition;
1639 CORE.Input.Mouse.previousPosition = CORE.Input.Mouse.lockedPosition;
1640 }
1641
1642 return 1; // The event was consumed by the callback handler
1643 }
1644
1645 // Emscripten: Called on connect/disconnect gamepads events
1646 static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData)
1647 {
1648 /*
1649 TRACELOG(LOG_DEBUG, "%s: timeStamp: %g, connected: %d, index: %ld, numAxes: %d, numButtons: %d, id: \"%s\", mapping: \"%s\"",
1650 eventType != 0? emscripten_event_type_to_string(eventType) : "Gamepad state",
1651 gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping);
1652
1653 for (int i = 0; i < gamepadEvent->numAxes; i++) TRACELOG(LOG_DEBUG, "Axis %d: %g", i, gamepadEvent->axis[i]);
1654 for (int i = 0; i < gamepadEvent->numButtons; i++) TRACELOG(LOG_DEBUG, "Button %d: Digital: %d, Analog: %g", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]);
1655 */
1656
1657 if (gamepadEvent->connected && (gamepadEvent->index < MAX_GAMEPADS))
1658 {
1659 CORE.Input.Gamepad.ready[gamepadEvent->index] = true;
1660 snprintf(CORE.Input.Gamepad.name[gamepadEvent->index], MAX_GAMEPAD_NAME_LENGTH, "%s", gamepadEvent->id);
1661 }
1662 else CORE.Input.Gamepad.ready[gamepadEvent->index] = false;
1663
1664 return 1; // The event was consumed by the callback handler
1665 }
1666
1667 // Emscripten: Called on touch input events
1668 static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData)
1669 {
1670 // Register touch points count
1671 CORE.Input.Touch.pointCount = touchEvent->numTouches;
1672
1673 double canvasWidth = 0.0;
1674 double canvasHeight = 0.0;
1675 // NOTE: emscripten_get_canvas_element_size() returns canvas.width and canvas.height but
1676 // looking for actual CSS size: canvas.style.width and canvas.style.height
1677 // EMSCRIPTEN_RESULT res = emscripten_get_canvas_element_size("#canvas", &canvasWidth, &canvasHeight);
1678 emscripten_get_element_css_size(platform.canvasId, &canvasWidth, &canvasHeight);
1679
1680 for (int i = 0; (i < CORE.Input.Touch.pointCount) && (i < MAX_TOUCH_POINTS); i++)
1681 {
1682 // Register touch points id
1683 CORE.Input.Touch.pointId[i] = touchEvent->touches[i].identifier;
1684
1685 // Register touch points position
1686 CORE.Input.Touch.position[i] = (Vector2){touchEvent->touches[i].targetX, touchEvent->touches[i].targetY};
1687
1688 // Normalize gestureEvent.position[x] for CORE.Window.screen.width and CORE.Window.screen.height
1689 CORE.Input.Touch.position[i].x *= ((float)GetScreenWidth()/(float)canvasWidth);
1690 CORE.Input.Touch.position[i].y *= ((float)GetScreenHeight()/(float)canvasHeight);
1691
1692 if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) CORE.Input.Touch.currentTouchState[i] = 1;
1693 else if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) CORE.Input.Touch.currentTouchState[i] = 0;
1694 }
1695
1696 // Update mouse position if a single touch is detected
1697 if (CORE.Input.Touch.pointCount == 1)
1698 {
1699 CORE.Input.Mouse.currentPosition.x = CORE.Input.Touch.position[0].x;
1700 CORE.Input.Mouse.currentPosition.y = CORE.Input.Touch.position[0].y;
1701 }
1702
1703 #if SUPPORT_GESTURES_SYSTEM
1704 GestureEvent gestureEvent = { 0 };
1705 gestureEvent.pointCount = CORE.Input.Touch.pointCount;
1706
1707 // Register touch actions
1708 if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) gestureEvent.touchAction = TOUCH_ACTION_DOWN;
1709 else if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) gestureEvent.touchAction = TOUCH_ACTION_UP;
1710 else if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) gestureEvent.touchAction = TOUCH_ACTION_MOVE;
1711 else if (eventType == EMSCRIPTEN_EVENT_TOUCHCANCEL) gestureEvent.touchAction = TOUCH_ACTION_CANCEL;
1712
1713 for (int i = 0; (i < gestureEvent.pointCount) && (i < MAX_TOUCH_POINTS); i++)
1714 {
1715 gestureEvent.pointId[i] = CORE.Input.Touch.pointId[i];
1716 gestureEvent.position[i] = CORE.Input.Touch.position[i];
1717
1718 // Normalize gestureEvent.position[i]
1719 gestureEvent.position[i].x /= (float)GetScreenWidth();
1720 gestureEvent.position[i].y /= (float)GetScreenHeight();
1721 }
1722
1723 // Gesture data is sent to gestures system for processing
1724 ProcessGestureEvent(gestureEvent);
1725 #endif
1726
1727 if (eventType == EMSCRIPTEN_EVENT_TOUCHEND)
1728 {
1729 // Identify the EMSCRIPTEN_EVENT_TOUCHEND and remove it from the list
1730 for (int i = 0; i < CORE.Input.Touch.pointCount; i++)
1731 {
1732 if (touchEvent->touches[i].isChanged)
1733 {
1734 // Move all touch points one position up
1735 for (int j = i; j < CORE.Input.Touch.pointCount - 1; j++)
1736 {
1737 CORE.Input.Touch.pointId[j] = CORE.Input.Touch.pointId[j + 1];
1738 CORE.Input.Touch.position[j] = CORE.Input.Touch.position[j + 1];
1739 }
1740 // Decrease touch points count to remove the last one
1741 CORE.Input.Touch.pointCount--;
1742 break;
1743 }
1744 }
1745 // Clamp pointCount to avoid negative values
1746 if (CORE.Input.Touch.pointCount < 0) CORE.Input.Touch.pointCount = 0;
1747 }
1748
1749 return 1; // The event was consumed by the callback handler
1750 }
1751 //-------------------------------------------------------------------------------------------------------
1752
1753 // EOF