os_javascript.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os_javascript.h"
  31. #include "gles2/rasterizer_gles2.h"
  32. #include "gles3/rasterizer_gles3.h"
  33. #include "io/file_access_buffered_fa.h"
  34. #include "main/main.h"
  35. #include "servers/visual/visual_server_raster.h"
  36. #include "unix/dir_access_unix.h"
  37. #include "unix/file_access_unix.h"
  38. #include <emscripten.h>
  39. #include <stdlib.h>
  40. #include "dom_keys.inc"
  41. #define DOM_BUTTON_LEFT 0
  42. #define DOM_BUTTON_MIDDLE 1
  43. #define DOM_BUTTON_RIGHT 2
  44. #define DOM_BUTTON_XBUTTON1 3
  45. #define DOM_BUTTON_XBUTTON2 4
  46. // Window (canvas)
  47. static void focus_canvas() {
  48. /* clang-format off */
  49. EM_ASM(
  50. Module.canvas.focus();
  51. );
  52. /* clang-format on */
  53. }
  54. static bool is_canvas_focused() {
  55. /* clang-format off */
  56. return EM_ASM_INT_V(
  57. return document.activeElement == Module.canvas;
  58. );
  59. /* clang-format on */
  60. }
  61. static bool cursor_inside_canvas = true;
  62. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  63. OS_JavaScript *os = get_singleton();
  64. // Empty ID is canvas.
  65. String target_id = String::utf8(p_event->id);
  66. if (target_id.empty() || target_id == "canvas") {
  67. // This event property is the only reliable data on
  68. // browser fullscreen state.
  69. os->video_mode.fullscreen = p_event->isFullscreen;
  70. if (os->video_mode.fullscreen) {
  71. os->entering_fullscreen = false;
  72. } else {
  73. // Restoring maximized window now will cause issues,
  74. // so delay until main_loop_iterate.
  75. os->just_exited_fullscreen = true;
  76. }
  77. }
  78. return false;
  79. }
  80. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  81. video_mode = p_video_mode;
  82. }
  83. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  84. return video_mode;
  85. }
  86. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  87. EmscriptenFullscreenChangeEvent ev;
  88. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  89. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  90. return Size2(ev.screenWidth, ev.screenHeight);
  91. }
  92. void OS_JavaScript::set_window_size(const Size2 p_size) {
  93. windowed_size = p_size;
  94. if (video_mode.fullscreen) {
  95. window_maximized = false;
  96. set_window_fullscreen(false);
  97. } else {
  98. if (window_maximized) {
  99. emscripten_exit_soft_fullscreen();
  100. window_maximized = false;
  101. }
  102. emscripten_set_canvas_size(p_size.x, p_size.y);
  103. }
  104. }
  105. Size2 OS_JavaScript::get_window_size() const {
  106. int canvas[3];
  107. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  108. return Size2(canvas[0], canvas[1]);
  109. }
  110. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  111. if (video_mode.fullscreen) {
  112. window_maximized = p_enabled;
  113. set_window_fullscreen(false);
  114. } else if (!p_enabled) {
  115. emscripten_exit_soft_fullscreen();
  116. window_maximized = false;
  117. } else if (!window_maximized) {
  118. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  119. // this would hide page elements permanently.
  120. EmscriptenFullscreenStrategy strategy;
  121. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  122. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  123. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  124. strategy.canvasResizedCallback = NULL;
  125. emscripten_enter_soft_fullscreen(NULL, &strategy);
  126. window_maximized = p_enabled;
  127. }
  128. }
  129. bool OS_JavaScript::is_window_maximized() const {
  130. return window_maximized;
  131. }
  132. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  133. if (p_enabled == video_mode.fullscreen) {
  134. return;
  135. }
  136. // Just request changes here, if successful, logic continues in
  137. // fullscreen_change_callback.
  138. if (p_enabled) {
  139. if (window_maximized) {
  140. // Soft fullsreen during real fullscreen can cause issues, so exit.
  141. // This must be called before requesting full screen.
  142. emscripten_exit_soft_fullscreen();
  143. }
  144. EmscriptenFullscreenStrategy strategy;
  145. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  146. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  147. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  148. strategy.canvasResizedCallback = NULL;
  149. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  150. ERR_EXPLAIN("Enabling fullscreen is only possible from an input callback for the HTML5 platform");
  151. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  152. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  153. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  154. // being overwritten.
  155. entering_fullscreen = true;
  156. } else {
  157. // No logic allowed here, since exiting w/ ESC key won't use this function.
  158. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  159. }
  160. }
  161. bool OS_JavaScript::is_window_fullscreen() const {
  162. return video_mode.fullscreen;
  163. }
  164. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  165. Size2 screen = get_screen_size();
  166. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  167. }
  168. // Keys
  169. template <typename T>
  170. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  171. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  172. godot_event->set_alt(emscripten_event_ptr->altKey);
  173. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  174. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  175. }
  176. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  177. Ref<InputEventKey> ev;
  178. ev.instance();
  179. ev->set_echo(emscripten_event->repeat);
  180. dom2godot_mod(emscripten_event, ev);
  181. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  182. String unicode = String::utf8(emscripten_event->key);
  183. // Check if empty or multi-character (e.g. `CapsLock`).
  184. if (unicode.length() != 1) {
  185. // Might be empty as well, but better than nonsense.
  186. unicode = String::utf8(emscripten_event->charValue);
  187. }
  188. if (unicode.length() == 1) {
  189. ev->set_unicode(unicode[0]);
  190. }
  191. return ev;
  192. }
  193. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  194. OS_JavaScript *os = get_singleton();
  195. Ref<InputEventKey> ev = setup_key_event(p_event);
  196. ev->set_pressed(true);
  197. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  198. // Defer to keypress event for legacy unicode retrieval.
  199. os->deferred_key_event = ev;
  200. // Do not suppress keypress event.
  201. return false;
  202. }
  203. os->input->parse_input_event(ev);
  204. return true;
  205. }
  206. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  207. OS_JavaScript *os = get_singleton();
  208. os->deferred_key_event->set_unicode(p_event->charCode);
  209. os->input->parse_input_event(os->deferred_key_event);
  210. return true;
  211. }
  212. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  213. Ref<InputEventKey> ev = setup_key_event(p_event);
  214. ev->set_pressed(false);
  215. get_singleton()->input->parse_input_event(ev);
  216. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  217. }
  218. // Mouse
  219. Point2 OS_JavaScript::get_mouse_position() const {
  220. return input->get_mouse_position();
  221. }
  222. int OS_JavaScript::get_mouse_button_state() const {
  223. return input->get_mouse_button_mask();
  224. }
  225. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  226. OS_JavaScript *os = get_singleton();
  227. Ref<InputEventMouseButton> ev;
  228. ev.instance();
  229. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  230. ev->set_position(Point2(p_event->canvasX, p_event->canvasY));
  231. ev->set_global_position(ev->get_position());
  232. dom2godot_mod(p_event, ev);
  233. switch (p_event->button) {
  234. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  235. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  236. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  237. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  238. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  239. default: return false;
  240. }
  241. int mask = os->input->get_mouse_button_mask();
  242. int button_flag = 1 << (ev->get_button_index() - 1);
  243. if (ev->is_pressed()) {
  244. // Since the event is consumed, focus manually. The containing iframe,
  245. // if exists, may not have focus yet, so focus even if already focused.
  246. focus_canvas();
  247. mask |= button_flag;
  248. } else if (mask & button_flag) {
  249. mask &= ~button_flag;
  250. } else {
  251. // Received release event, but press was outside the canvas, so ignore.
  252. return false;
  253. }
  254. ev->set_button_mask(mask);
  255. os->input->parse_input_event(ev);
  256. // Prevent multi-click text selection and wheel-click scrolling anchor.
  257. // Context menu is prevented through contextmenu event.
  258. return true;
  259. }
  260. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  261. OS_JavaScript *os = get_singleton();
  262. int input_mask = os->input->get_mouse_button_mask();
  263. Point2 pos = Point2(p_event->canvasX, p_event->canvasY);
  264. // For motion outside the canvas, only read mouse movement if dragging
  265. // started inside the canvas; imitating desktop app behaviour.
  266. if (!cursor_inside_canvas && !input_mask)
  267. return false;
  268. Ref<InputEventMouseMotion> ev;
  269. ev.instance();
  270. dom2godot_mod(p_event, ev);
  271. ev->set_button_mask(input_mask);
  272. ev->set_position(pos);
  273. ev->set_global_position(ev->get_position());
  274. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  275. os->input->set_mouse_position(ev->get_position());
  276. ev->set_speed(os->input->get_last_mouse_speed());
  277. os->input->parse_input_event(ev);
  278. // Don't suppress mouseover/-leave events.
  279. return false;
  280. }
  281. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  282. switch (p_shape) {
  283. case OS::CURSOR_ARROW:
  284. default:
  285. return "auto";
  286. case OS::CURSOR_IBEAM: return "text";
  287. case OS::CURSOR_POINTING_HAND: return "pointer";
  288. case OS::CURSOR_CROSS: return "crosshair";
  289. case OS::CURSOR_WAIT: return "progress";
  290. case OS::CURSOR_BUSY: return "wait";
  291. case OS::CURSOR_DRAG: return "grab";
  292. case OS::CURSOR_CAN_DROP: return "grabbing";
  293. case OS::CURSOR_FORBIDDEN: return "no-drop";
  294. case OS::CURSOR_VSIZE: return "ns-resize";
  295. case OS::CURSOR_HSIZE: return "ew-resize";
  296. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  297. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  298. case OS::CURSOR_MOVE: return "move";
  299. case OS::CURSOR_VSPLIT: return "row-resize";
  300. case OS::CURSOR_HSPLIT: return "col-resize";
  301. case OS::CURSOR_HELP: return "help";
  302. }
  303. }
  304. static void set_css_cursor(const char *p_cursor) {
  305. /* clang-format off */
  306. EM_ASM_({
  307. Module.canvas.style.cursor = UTF8ToString($0);
  308. }, p_cursor);
  309. /* clang-format on */
  310. }
  311. static const char *get_css_cursor() {
  312. char cursor[16];
  313. /* clang-format off */
  314. EM_ASM_INT({
  315. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  316. }, cursor);
  317. /* clang-format on */
  318. return cursor;
  319. }
  320. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  321. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  322. cursor_shape = p_shape;
  323. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  324. set_css_cursor(godot2dom_cursor(cursor_shape));
  325. }
  326. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  327. }
  328. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  329. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  330. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  331. if (p_mode == get_mouse_mode())
  332. return;
  333. if (p_mode == MOUSE_MODE_VISIBLE) {
  334. set_css_cursor(godot2dom_cursor(cursor_shape));
  335. emscripten_exit_pointerlock();
  336. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  337. set_css_cursor("none");
  338. emscripten_exit_pointerlock();
  339. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  340. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  341. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  342. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  343. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  344. set_css_cursor(godot2dom_cursor(cursor_shape));
  345. }
  346. }
  347. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  348. if (String::utf8(get_css_cursor()) == "none")
  349. return MOUSE_MODE_HIDDEN;
  350. EmscriptenPointerlockChangeEvent ev;
  351. emscripten_get_pointerlock_status(&ev);
  352. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  353. }
  354. // Wheel
  355. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  356. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  357. if (!is_canvas_focused()) {
  358. if (cursor_inside_canvas) {
  359. focus_canvas();
  360. } else {
  361. return false;
  362. }
  363. }
  364. InputDefault *input = get_singleton()->input;
  365. Ref<InputEventMouseButton> ev;
  366. ev.instance();
  367. ev->set_button_mask(input->get_mouse_button_mask());
  368. ev->set_position(input->get_mouse_position());
  369. ev->set_global_position(ev->get_position());
  370. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  371. ev->set_alt(input->is_key_pressed(KEY_ALT));
  372. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  373. ev->set_metakey(input->is_key_pressed(KEY_META));
  374. if (p_event->deltaY < 0)
  375. ev->set_button_index(BUTTON_WHEEL_UP);
  376. else if (p_event->deltaY > 0)
  377. ev->set_button_index(BUTTON_WHEEL_DOWN);
  378. else if (p_event->deltaX > 0)
  379. ev->set_button_index(BUTTON_WHEEL_LEFT);
  380. else if (p_event->deltaX < 0)
  381. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  382. else
  383. return false;
  384. // Different browsers give wildly different delta values, and we can't
  385. // interpret deltaMode, so use default value for wheel events' factor.
  386. ev->set_pressed(true);
  387. input->parse_input_event(ev);
  388. ev->set_pressed(false);
  389. input->parse_input_event(ev);
  390. return true;
  391. }
  392. // Touch
  393. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  394. /* clang-format off */
  395. return EM_ASM_INT_V(
  396. return 'ontouchstart' in window;
  397. );
  398. /* clang-format on */
  399. }
  400. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  401. OS_JavaScript *os = get_singleton();
  402. Ref<InputEventScreenTouch> ev;
  403. ev.instance();
  404. int lowest_id_index = -1;
  405. for (int i = 0; i < p_event->numTouches; ++i) {
  406. const EmscriptenTouchPoint &touch = p_event->touches[i];
  407. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  408. lowest_id_index = i;
  409. if (!touch.isChanged)
  410. continue;
  411. ev->set_index(touch.identifier);
  412. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  413. os->touches[i] = ev->get_position();
  414. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  415. os->input->parse_input_event(ev);
  416. }
  417. return true;
  418. }
  419. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  420. OS_JavaScript *os = get_singleton();
  421. Ref<InputEventScreenDrag> ev;
  422. ev.instance();
  423. int lowest_id_index = -1;
  424. for (int i = 0; i < p_event->numTouches; ++i) {
  425. const EmscriptenTouchPoint &touch = p_event->touches[i];
  426. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  427. lowest_id_index = i;
  428. if (!touch.isChanged)
  429. continue;
  430. ev->set_index(touch.identifier);
  431. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  432. Point2 &prev = os->touches[i];
  433. ev->set_relative(ev->get_position() - prev);
  434. prev = ev->get_position();
  435. os->input->parse_input_event(ev);
  436. }
  437. return true;
  438. }
  439. // Gamepad
  440. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  441. InputDefault *input = get_singleton()->input;
  442. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  443. String guid = "";
  444. if (String::utf8(p_event->mapping) == "standard")
  445. guid = "Default HTML5 Gamepad";
  446. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  447. } else {
  448. input->joy_connection_changed(p_event->index, false, "");
  449. }
  450. return true;
  451. }
  452. void OS_JavaScript::process_joypads() {
  453. int joypad_count = emscripten_get_num_gamepads();
  454. for (int joypad = 0; joypad < joypad_count; joypad++) {
  455. EmscriptenGamepadEvent state;
  456. emscripten_get_gamepad_status(joypad, &state);
  457. if (state.connected) {
  458. int button_count = MIN(state.numButtons, 18);
  459. int axis_count = MIN(state.numAxes, 8);
  460. for (int button = 0; button < button_count; button++) {
  461. float value = state.analogButton[button];
  462. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  463. InputDefault::JoyAxis joy_axis;
  464. joy_axis.min = 0;
  465. joy_axis.value = value;
  466. input->joy_axis(joypad, button, joy_axis);
  467. } else {
  468. input->joy_button(joypad, button, value);
  469. }
  470. }
  471. for (int axis = 0; axis < axis_count; axis++) {
  472. InputDefault::JoyAxis joy_axis;
  473. joy_axis.min = -1;
  474. joy_axis.value = state.axis[axis];
  475. input->joy_axis(joypad, axis, joy_axis);
  476. }
  477. }
  478. }
  479. }
  480. bool OS_JavaScript::is_joy_known(int p_device) {
  481. return input->is_joy_mapped(p_device);
  482. }
  483. String OS_JavaScript::get_joy_guid(int p_device) const {
  484. return input->get_joy_guid_remapped(p_device);
  485. }
  486. // Video
  487. int OS_JavaScript::get_video_driver_count() const {
  488. return VIDEO_DRIVER_MAX;
  489. }
  490. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  491. switch (p_driver) {
  492. case VIDEO_DRIVER_GLES3:
  493. return "GLES3";
  494. case VIDEO_DRIVER_GLES2:
  495. return "GLES2";
  496. }
  497. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  498. ERR_FAIL_V(NULL);
  499. }
  500. // Audio
  501. int OS_JavaScript::get_audio_driver_count() const {
  502. return 1;
  503. }
  504. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  505. return "JavaScript";
  506. }
  507. // Lifecycle
  508. int OS_JavaScript::get_current_video_driver() const {
  509. return video_driver_index;
  510. }
  511. void OS_JavaScript::initialize_core() {
  512. OS_Unix::initialize_core();
  513. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  514. }
  515. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  516. EmscriptenWebGLContextAttributes attributes;
  517. emscripten_webgl_init_context_attributes(&attributes);
  518. attributes.alpha = false;
  519. attributes.antialias = false;
  520. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  521. bool gles3 = true;
  522. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  523. gles3 = false;
  524. }
  525. bool gl_initialization_error = false;
  526. while (true) {
  527. if (gles3) {
  528. if (RasterizerGLES3::is_viable() == OK) {
  529. attributes.majorVersion = 2;
  530. RasterizerGLES3::register_config();
  531. RasterizerGLES3::make_current();
  532. break;
  533. } else {
  534. if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") {
  535. p_video_driver = VIDEO_DRIVER_GLES2;
  536. gles3 = false;
  537. continue;
  538. } else {
  539. gl_initialization_error = true;
  540. break;
  541. }
  542. }
  543. } else {
  544. if (RasterizerGLES2::is_viable() == OK) {
  545. attributes.majorVersion = 1;
  546. RasterizerGLES2::register_config();
  547. RasterizerGLES2::make_current();
  548. break;
  549. } else {
  550. gl_initialization_error = true;
  551. break;
  552. }
  553. }
  554. }
  555. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  556. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  557. gl_initialization_error = true;
  558. }
  559. if (gl_initialization_error) {
  560. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  561. "Please update your browser version.",
  562. "Unable to initialize Video driver");
  563. return ERR_UNAVAILABLE;
  564. }
  565. video_driver_index = p_video_driver;
  566. video_mode = p_desired;
  567. // Can't fulfil fullscreen request during start-up due to browser security.
  568. video_mode.fullscreen = false;
  569. /* clang-format off */
  570. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  571. /* clang-format on */
  572. set_window_size(Size2(video_mode.width, video_mode.height));
  573. } else {
  574. set_window_size(get_window_size());
  575. }
  576. char locale_ptr[16];
  577. /* clang-format off */
  578. EM_ASM_ARGS({
  579. stringToUTF8(Module.locale, $0, 16);
  580. }, locale_ptr);
  581. /* clang-format on */
  582. setenv("LANG", locale_ptr, true);
  583. AudioDriverManager::initialize(p_audio_driver);
  584. VisualServer *visual_server = memnew(VisualServerRaster());
  585. input = memnew(InputDefault);
  586. EMSCRIPTEN_RESULT result;
  587. #define EM_CHECK(ev) \
  588. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  589. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  590. #define SET_EM_CALLBACK(target, ev, cb) \
  591. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  592. EM_CHECK(ev)
  593. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  594. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  595. EM_CHECK(ev)
  596. // These callbacks from Emscripten's html5.h suffice to access most
  597. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  598. // is used below.
  599. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  600. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  601. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  602. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  603. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  604. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  605. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  606. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  607. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  608. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  609. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  610. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  611. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  612. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  613. #undef SET_EM_CALLBACK_NODATA
  614. #undef SET_EM_CALLBACK
  615. #undef EM_CHECK
  616. /* clang-format off */
  617. EM_ASM_ARGS({
  618. const send_notification = cwrap('send_notification', null, ['number']);
  619. const notifications = arguments;
  620. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  621. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  622. });
  623. },
  624. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  625. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  626. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  627. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  628. );
  629. /* clang-format on */
  630. visual_server->init();
  631. return OK;
  632. }
  633. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  634. main_loop = p_main_loop;
  635. input->set_main_loop(p_main_loop);
  636. }
  637. MainLoop *OS_JavaScript::get_main_loop() const {
  638. return main_loop;
  639. }
  640. void OS_JavaScript::run_async() {
  641. main_loop->init();
  642. emscripten_set_main_loop(main_loop_callback, -1, false);
  643. }
  644. void OS_JavaScript::main_loop_callback() {
  645. get_singleton()->main_loop_iterate();
  646. }
  647. bool OS_JavaScript::main_loop_iterate() {
  648. if (is_userfs_persistent() && sync_wait_time >= 0) {
  649. int64_t current_time = get_ticks_msec();
  650. int64_t elapsed_time = current_time - last_sync_check_time;
  651. last_sync_check_time = current_time;
  652. sync_wait_time -= elapsed_time;
  653. if (sync_wait_time < 0) {
  654. /* clang-format off */
  655. EM_ASM(
  656. FS.syncfs(function(err) {
  657. if (err) { console.warn('Failed to save IDB file system: ' + err.message); }
  658. });
  659. );
  660. /* clang-format on */
  661. }
  662. }
  663. process_joypads();
  664. if (just_exited_fullscreen) {
  665. if (window_maximized) {
  666. EmscriptenFullscreenStrategy strategy;
  667. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  668. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  669. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  670. strategy.canvasResizedCallback = NULL;
  671. emscripten_enter_soft_fullscreen(NULL, &strategy);
  672. } else {
  673. emscripten_set_canvas_size(windowed_size.width, windowed_size.height);
  674. }
  675. just_exited_fullscreen = false;
  676. }
  677. int canvas[3];
  678. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  679. video_mode.width = canvas[0];
  680. video_mode.height = canvas[1];
  681. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  682. windowed_size.width = canvas[0];
  683. windowed_size.height = canvas[1];
  684. }
  685. return Main::iteration();
  686. }
  687. void OS_JavaScript::delete_main_loop() {
  688. memdelete(main_loop);
  689. }
  690. void OS_JavaScript::finalize() {
  691. memdelete(input);
  692. }
  693. // Miscellaneous
  694. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  695. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  696. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  697. }
  698. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  699. }
  700. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  701. if (p_feature == "HTML5" || p_feature == "web")
  702. return true;
  703. #ifdef JAVASCRIPT_EVAL_ENABLED
  704. if (p_feature == "JavaScript")
  705. return true;
  706. #endif
  707. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  708. // All extensions are already automatically enabled, this function allows
  709. // checking WebGL extension support without inline JavaScript
  710. if (p_feature == "s3tc")
  711. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb");
  712. if (p_feature == "etc")
  713. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1");
  714. if (p_feature == "etc2")
  715. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc");
  716. return false;
  717. }
  718. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  719. /* clang-format off */
  720. EM_ASM_({
  721. window.alert(UTF8ToString($0));
  722. }, p_alert.utf8().get_data());
  723. /* clang-format on */
  724. }
  725. void OS_JavaScript::set_window_title(const String &p_title) {
  726. /* clang-format off */
  727. EM_ASM_({
  728. document.title = UTF8ToString($0);
  729. }, p_title.utf8().get_data());
  730. /* clang-format on */
  731. }
  732. String OS_JavaScript::get_executable_path() const {
  733. return OS::get_executable_path();
  734. }
  735. Error OS_JavaScript::shell_open(String p_uri) {
  736. // Open URI in a new tab, browser will deal with it by protocol.
  737. /* clang-format off */
  738. EM_ASM_({
  739. window.open(UTF8ToString($0), '_blank');
  740. }, p_uri.utf8().get_data());
  741. /* clang-format on */
  742. return OK;
  743. }
  744. String OS_JavaScript::get_name() {
  745. return "HTML5";
  746. }
  747. bool OS_JavaScript::can_draw() const {
  748. return true; // Always?
  749. }
  750. String OS_JavaScript::get_user_data_dir() const {
  751. return "/userfs";
  752. };
  753. String OS_JavaScript::get_resource_dir() const {
  754. return "/";
  755. }
  756. OS::PowerState OS_JavaScript::get_power_state() {
  757. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  758. return OS::POWERSTATE_UNKNOWN;
  759. }
  760. int OS_JavaScript::get_power_seconds_left() {
  761. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  762. return -1;
  763. }
  764. int OS_JavaScript::get_power_percent_left() {
  765. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  766. return -1;
  767. }
  768. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  769. OS_JavaScript *os = get_singleton();
  770. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  771. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  772. // Wait five seconds in case more files are about to be closed.
  773. os->sync_wait_time = 5000;
  774. }
  775. }
  776. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  777. idb_available = p_idb_available;
  778. }
  779. bool OS_JavaScript::is_userfs_persistent() const {
  780. return idb_available;
  781. }
  782. OS_JavaScript *OS_JavaScript::get_singleton() {
  783. return static_cast<OS_JavaScript *>(OS::get_singleton());
  784. }
  785. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  786. List<String> arguments;
  787. for (int i = 1; i < p_argc; i++) {
  788. arguments.push_back(String::utf8(p_argv[i]));
  789. }
  790. set_cmdline(p_argv[0], arguments);
  791. window_maximized = false;
  792. entering_fullscreen = false;
  793. just_exited_fullscreen = false;
  794. main_loop = NULL;
  795. idb_available = false;
  796. sync_wait_time = -1;
  797. AudioDriverManager::add_driver(&audio_driver_javascript);
  798. Vector<Logger *> loggers;
  799. loggers.push_back(memnew(StdLogger));
  800. _set_logger(memnew(CompositeLogger(loggers)));
  801. FileAccessUnix::close_notification_func = file_access_close_callback;
  802. }