os_javascript.cpp 33 KB

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