os_javascript.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. int mask = os->input->get_mouse_button_mask();
  243. int button_flag = 1 << (ev->get_button_index() - 1);
  244. if (ev->is_pressed()) {
  245. // Since the event is consumed, focus manually. The containing iframe,
  246. // if exists, may not have focus yet, so focus even if already focused.
  247. focus_canvas();
  248. mask |= button_flag;
  249. } else if (mask & button_flag) {
  250. mask &= ~button_flag;
  251. } else {
  252. // Received release event, but press was outside the canvas, so ignore.
  253. return false;
  254. }
  255. ev->set_button_mask(mask);
  256. os->input->parse_input_event(ev);
  257. // Prevent multi-click text selection and wheel-click scrolling anchor.
  258. // Context menu is prevented through contextmenu event.
  259. return true;
  260. }
  261. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  262. OS_JavaScript *os = get_singleton();
  263. int input_mask = os->input->get_mouse_button_mask();
  264. Point2 pos = Point2(p_event->canvasX, p_event->canvasY);
  265. // For motion outside the canvas, only read mouse movement if dragging
  266. // started inside the canvas; imitating desktop app behaviour.
  267. if (!cursor_inside_canvas && !input_mask)
  268. return false;
  269. Ref<InputEventMouseMotion> ev;
  270. ev.instance();
  271. dom2godot_mod(p_event, ev);
  272. ev->set_button_mask(input_mask);
  273. ev->set_position(pos);
  274. ev->set_global_position(ev->get_position());
  275. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  276. os->input->set_mouse_position(ev->get_position());
  277. ev->set_speed(os->input->get_last_mouse_speed());
  278. os->input->parse_input_event(ev);
  279. // Don't suppress mouseover/-leave events.
  280. return false;
  281. }
  282. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  283. switch (p_shape) {
  284. case OS::CURSOR_ARROW:
  285. default:
  286. return "auto";
  287. case OS::CURSOR_IBEAM: return "text";
  288. case OS::CURSOR_POINTING_HAND: return "pointer";
  289. case OS::CURSOR_CROSS: return "crosshair";
  290. case OS::CURSOR_WAIT: return "progress";
  291. case OS::CURSOR_BUSY: return "wait";
  292. case OS::CURSOR_DRAG: return "grab";
  293. case OS::CURSOR_CAN_DROP: return "grabbing";
  294. case OS::CURSOR_FORBIDDEN: return "no-drop";
  295. case OS::CURSOR_VSIZE: return "ns-resize";
  296. case OS::CURSOR_HSIZE: return "ew-resize";
  297. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  298. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  299. case OS::CURSOR_MOVE: return "move";
  300. case OS::CURSOR_VSPLIT: return "row-resize";
  301. case OS::CURSOR_HSPLIT: return "col-resize";
  302. case OS::CURSOR_HELP: return "help";
  303. }
  304. }
  305. static void set_css_cursor(const char *p_cursor) {
  306. /* clang-format off */
  307. EM_ASM_({
  308. Module.canvas.style.cursor = UTF8ToString($0);
  309. }, p_cursor);
  310. /* clang-format on */
  311. }
  312. static bool is_css_cursor_hidden() {
  313. /* clang-format off */
  314. return EM_ASM_INT({
  315. return Module.canvas.style.cursor === 'none';
  316. });
  317. /* clang-format on */
  318. }
  319. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  320. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  321. cursor_shape = p_shape;
  322. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  323. set_css_cursor(godot2dom_cursor(cursor_shape));
  324. }
  325. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  326. }
  327. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  328. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  329. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  330. if (p_mode == get_mouse_mode())
  331. return;
  332. if (p_mode == MOUSE_MODE_VISIBLE) {
  333. set_css_cursor(godot2dom_cursor(cursor_shape));
  334. emscripten_exit_pointerlock();
  335. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  336. set_css_cursor("none");
  337. emscripten_exit_pointerlock();
  338. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  339. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  340. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  341. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  342. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  343. set_css_cursor(godot2dom_cursor(cursor_shape));
  344. }
  345. }
  346. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  347. if (is_css_cursor_hidden())
  348. return MOUSE_MODE_HIDDEN;
  349. EmscriptenPointerlockChangeEvent ev;
  350. emscripten_get_pointerlock_status(&ev);
  351. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  352. }
  353. // Wheel
  354. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  355. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  356. if (!is_canvas_focused()) {
  357. if (cursor_inside_canvas) {
  358. focus_canvas();
  359. } else {
  360. return false;
  361. }
  362. }
  363. InputDefault *input = get_singleton()->input;
  364. Ref<InputEventMouseButton> ev;
  365. ev.instance();
  366. ev->set_position(input->get_mouse_position());
  367. ev->set_global_position(ev->get_position());
  368. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  369. ev->set_alt(input->is_key_pressed(KEY_ALT));
  370. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  371. ev->set_metakey(input->is_key_pressed(KEY_META));
  372. if (p_event->deltaY < 0)
  373. ev->set_button_index(BUTTON_WHEEL_UP);
  374. else if (p_event->deltaY > 0)
  375. ev->set_button_index(BUTTON_WHEEL_DOWN);
  376. else if (p_event->deltaX > 0)
  377. ev->set_button_index(BUTTON_WHEEL_LEFT);
  378. else if (p_event->deltaX < 0)
  379. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  380. else
  381. return false;
  382. // Different browsers give wildly different delta values, and we can't
  383. // interpret deltaMode, so use default value for wheel events' factor.
  384. int button_flag = 1 << (ev->get_button_index() - 1);
  385. ev->set_pressed(true);
  386. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  387. input->parse_input_event(ev);
  388. ev->set_pressed(false);
  389. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  390. input->parse_input_event(ev);
  391. return true;
  392. }
  393. // Touch
  394. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  395. /* clang-format off */
  396. return EM_ASM_INT_V(
  397. return 'ontouchstart' in window;
  398. );
  399. /* clang-format on */
  400. }
  401. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  402. OS_JavaScript *os = get_singleton();
  403. Ref<InputEventScreenTouch> ev;
  404. ev.instance();
  405. int lowest_id_index = -1;
  406. for (int i = 0; i < p_event->numTouches; ++i) {
  407. const EmscriptenTouchPoint &touch = p_event->touches[i];
  408. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  409. lowest_id_index = i;
  410. if (!touch.isChanged)
  411. continue;
  412. ev->set_index(touch.identifier);
  413. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  414. os->touches[i] = ev->get_position();
  415. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  416. os->input->parse_input_event(ev);
  417. }
  418. return true;
  419. }
  420. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  421. OS_JavaScript *os = get_singleton();
  422. Ref<InputEventScreenDrag> ev;
  423. ev.instance();
  424. int lowest_id_index = -1;
  425. for (int i = 0; i < p_event->numTouches; ++i) {
  426. const EmscriptenTouchPoint &touch = p_event->touches[i];
  427. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  428. lowest_id_index = i;
  429. if (!touch.isChanged)
  430. continue;
  431. ev->set_index(touch.identifier);
  432. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  433. Point2 &prev = os->touches[i];
  434. ev->set_relative(ev->get_position() - prev);
  435. prev = ev->get_position();
  436. os->input->parse_input_event(ev);
  437. }
  438. return true;
  439. }
  440. // Gamepad
  441. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  442. InputDefault *input = get_singleton()->input;
  443. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  444. String guid = "";
  445. if (String::utf8(p_event->mapping) == "standard")
  446. guid = "Default HTML5 Gamepad";
  447. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  448. } else {
  449. input->joy_connection_changed(p_event->index, false, "");
  450. }
  451. return true;
  452. }
  453. void OS_JavaScript::process_joypads() {
  454. int joypad_count = emscripten_get_num_gamepads();
  455. for (int joypad = 0; joypad < joypad_count; joypad++) {
  456. EmscriptenGamepadEvent state;
  457. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  458. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  459. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  460. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  461. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  462. int button_count = MIN(state.numButtons, 18);
  463. int axis_count = MIN(state.numAxes, 8);
  464. for (int button = 0; button < button_count; button++) {
  465. float value = state.analogButton[button];
  466. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  467. InputDefault::JoyAxis joy_axis;
  468. joy_axis.min = 0;
  469. joy_axis.value = value;
  470. input->joy_axis(joypad, button, joy_axis);
  471. } else {
  472. input->joy_button(joypad, button, value);
  473. }
  474. }
  475. for (int axis = 0; axis < axis_count; axis++) {
  476. InputDefault::JoyAxis joy_axis;
  477. joy_axis.min = -1;
  478. joy_axis.value = state.axis[axis];
  479. input->joy_axis(joypad, axis, joy_axis);
  480. }
  481. }
  482. }
  483. }
  484. bool OS_JavaScript::is_joy_known(int p_device) {
  485. return input->is_joy_mapped(p_device);
  486. }
  487. String OS_JavaScript::get_joy_guid(int p_device) const {
  488. return input->get_joy_guid_remapped(p_device);
  489. }
  490. // Video
  491. int OS_JavaScript::get_video_driver_count() const {
  492. return VIDEO_DRIVER_MAX;
  493. }
  494. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  495. switch (p_driver) {
  496. case VIDEO_DRIVER_GLES3:
  497. return "GLES3";
  498. case VIDEO_DRIVER_GLES2:
  499. return "GLES2";
  500. }
  501. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  502. ERR_FAIL_V(NULL);
  503. }
  504. // Audio
  505. int OS_JavaScript::get_audio_driver_count() const {
  506. return 1;
  507. }
  508. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  509. return "JavaScript";
  510. }
  511. // Lifecycle
  512. int OS_JavaScript::get_current_video_driver() const {
  513. return video_driver_index;
  514. }
  515. void OS_JavaScript::initialize_core() {
  516. OS_Unix::initialize_core();
  517. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  518. }
  519. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  520. EmscriptenWebGLContextAttributes attributes;
  521. emscripten_webgl_init_context_attributes(&attributes);
  522. attributes.alpha = false;
  523. attributes.antialias = false;
  524. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  525. bool gles3 = true;
  526. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  527. gles3 = false;
  528. }
  529. bool gl_initialization_error = false;
  530. while (true) {
  531. if (gles3) {
  532. if (RasterizerGLES3::is_viable() == OK) {
  533. attributes.majorVersion = 2;
  534. RasterizerGLES3::register_config();
  535. RasterizerGLES3::make_current();
  536. break;
  537. } else {
  538. if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") {
  539. p_video_driver = VIDEO_DRIVER_GLES2;
  540. gles3 = false;
  541. continue;
  542. } else {
  543. gl_initialization_error = true;
  544. break;
  545. }
  546. }
  547. } else {
  548. if (RasterizerGLES2::is_viable() == OK) {
  549. attributes.majorVersion = 1;
  550. RasterizerGLES2::register_config();
  551. RasterizerGLES2::make_current();
  552. break;
  553. } else {
  554. gl_initialization_error = true;
  555. break;
  556. }
  557. }
  558. }
  559. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  560. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  561. gl_initialization_error = true;
  562. }
  563. if (gl_initialization_error) {
  564. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  565. "Please update your browser version.",
  566. "Unable to initialize Video driver");
  567. return ERR_UNAVAILABLE;
  568. }
  569. video_driver_index = p_video_driver;
  570. video_mode = p_desired;
  571. // Can't fulfill fullscreen request during start-up due to browser security.
  572. video_mode.fullscreen = false;
  573. /* clang-format off */
  574. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  575. /* clang-format on */
  576. set_window_size(Size2(video_mode.width, video_mode.height));
  577. } else {
  578. set_window_size(get_window_size());
  579. }
  580. char locale_ptr[16];
  581. /* clang-format off */
  582. EM_ASM_ARGS({
  583. stringToUTF8(Module.locale, $0, 16);
  584. }, locale_ptr);
  585. /* clang-format on */
  586. setenv("LANG", locale_ptr, true);
  587. AudioDriverManager::initialize(p_audio_driver);
  588. VisualServer *visual_server = memnew(VisualServerRaster());
  589. input = memnew(InputDefault);
  590. EMSCRIPTEN_RESULT result;
  591. #define EM_CHECK(ev) \
  592. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  593. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  594. #define SET_EM_CALLBACK(target, ev, cb) \
  595. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  596. EM_CHECK(ev)
  597. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  598. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  599. EM_CHECK(ev)
  600. // These callbacks from Emscripten's html5.h suffice to access most
  601. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  602. // is used below.
  603. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  604. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  605. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  606. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  607. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  608. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  609. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  610. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  611. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  612. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  613. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  614. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  615. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  616. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  617. #undef SET_EM_CALLBACK_NODATA
  618. #undef SET_EM_CALLBACK
  619. #undef EM_CHECK
  620. /* clang-format off */
  621. EM_ASM_ARGS({
  622. const send_notification = cwrap('send_notification', null, ['number']);
  623. const notifications = arguments;
  624. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  625. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  626. });
  627. },
  628. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  629. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  630. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  631. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  632. );
  633. /* clang-format on */
  634. visual_server->init();
  635. return OK;
  636. }
  637. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  638. main_loop = p_main_loop;
  639. input->set_main_loop(p_main_loop);
  640. }
  641. MainLoop *OS_JavaScript::get_main_loop() const {
  642. return main_loop;
  643. }
  644. void OS_JavaScript::run_async() {
  645. main_loop->init();
  646. emscripten_set_main_loop(main_loop_callback, -1, false);
  647. }
  648. void OS_JavaScript::main_loop_callback() {
  649. get_singleton()->main_loop_iterate();
  650. }
  651. bool OS_JavaScript::main_loop_iterate() {
  652. if (is_userfs_persistent() && sync_wait_time >= 0) {
  653. int64_t current_time = get_ticks_msec();
  654. int64_t elapsed_time = current_time - last_sync_check_time;
  655. last_sync_check_time = current_time;
  656. sync_wait_time -= elapsed_time;
  657. if (sync_wait_time < 0) {
  658. /* clang-format off */
  659. EM_ASM(
  660. FS.syncfs(function(err) {
  661. if (err) { console.warn('Failed to save IDB file system: ' + err.message); }
  662. });
  663. );
  664. /* clang-format on */
  665. }
  666. }
  667. process_joypads();
  668. if (just_exited_fullscreen) {
  669. if (window_maximized) {
  670. EmscriptenFullscreenStrategy strategy;
  671. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  672. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  673. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  674. strategy.canvasResizedCallback = NULL;
  675. emscripten_enter_soft_fullscreen(NULL, &strategy);
  676. } else {
  677. emscripten_set_canvas_element_size(NULL, windowed_size.width, windowed_size.height);
  678. }
  679. just_exited_fullscreen = false;
  680. }
  681. int canvas[2];
  682. emscripten_get_canvas_element_size(NULL, canvas, canvas + 1);
  683. video_mode.width = canvas[0];
  684. video_mode.height = canvas[1];
  685. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  686. windowed_size.width = canvas[0];
  687. windowed_size.height = canvas[1];
  688. }
  689. return Main::iteration();
  690. }
  691. void OS_JavaScript::delete_main_loop() {
  692. memdelete(main_loop);
  693. }
  694. void OS_JavaScript::finalize() {
  695. memdelete(input);
  696. }
  697. // Miscellaneous
  698. 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) {
  699. ERR_EXPLAIN("OS::execute() is not available on the HTML5 platform");
  700. ERR_FAIL_V(ERR_UNAVAILABLE);
  701. }
  702. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  703. ERR_EXPLAIN("OS::kill() is not available on the HTML5 platform");
  704. ERR_FAIL_V(ERR_UNAVAILABLE);
  705. }
  706. int OS_JavaScript::get_process_id() const {
  707. ERR_EXPLAIN("OS::get_process_id() is not available on the HTML5 platform");
  708. ERR_FAIL_V(0);
  709. }
  710. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  711. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  712. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  713. }
  714. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  715. }
  716. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  717. if (p_feature == "HTML5" || p_feature == "web")
  718. return true;
  719. #ifdef JAVASCRIPT_EVAL_ENABLED
  720. if (p_feature == "JavaScript")
  721. return true;
  722. #endif
  723. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  724. // All extensions are already automatically enabled, this function allows
  725. // checking WebGL extension support without inline JavaScript
  726. if (p_feature == "s3tc")
  727. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb");
  728. if (p_feature == "etc")
  729. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1");
  730. if (p_feature == "etc2")
  731. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc");
  732. return false;
  733. }
  734. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  735. /* clang-format off */
  736. EM_ASM_({
  737. window.alert(UTF8ToString($0));
  738. }, p_alert.utf8().get_data());
  739. /* clang-format on */
  740. }
  741. void OS_JavaScript::set_window_title(const String &p_title) {
  742. /* clang-format off */
  743. EM_ASM_({
  744. document.title = UTF8ToString($0);
  745. }, p_title.utf8().get_data());
  746. /* clang-format on */
  747. }
  748. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  749. ERR_FAIL_COND(p_icon.is_null());
  750. Ref<Image> icon = p_icon;
  751. if (icon->is_compressed()) {
  752. icon = icon->duplicate();
  753. ERR_FAIL_COND(icon->decompress() != OK)
  754. }
  755. if (icon->get_format() != Image::FORMAT_RGBA8) {
  756. if (icon == p_icon)
  757. icon = icon->duplicate();
  758. icon->convert(Image::FORMAT_RGBA8);
  759. }
  760. png_image png_meta;
  761. memset(&png_meta, 0, sizeof png_meta);
  762. png_meta.version = PNG_IMAGE_VERSION;
  763. png_meta.width = icon->get_width();
  764. png_meta.height = icon->get_height();
  765. png_meta.format = PNG_FORMAT_RGBA;
  766. PoolByteArray png;
  767. size_t len;
  768. PoolByteArray::Read r = icon->get_data().read();
  769. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  770. png.resize(len);
  771. PoolByteArray::Write w = png.write();
  772. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  773. w = PoolByteArray::Write();
  774. r = png.read();
  775. /* clang-format off */
  776. EM_ASM_ARGS({
  777. var PNG_PTR = $0;
  778. var PNG_LEN = $1;
  779. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: "image/png" });
  780. var url = URL.createObjectURL(png);
  781. var link = document.getElementById('-gd-engine-icon');
  782. if (link === null) {
  783. link = document.createElement('link');
  784. link.rel = 'icon';
  785. link.id = '-gd-engine-icon';
  786. document.head.appendChild(link);
  787. }
  788. link.href = url;
  789. }, r.ptr(), len);
  790. /* clang-format on */
  791. }
  792. String OS_JavaScript::get_executable_path() const {
  793. return OS::get_executable_path();
  794. }
  795. Error OS_JavaScript::shell_open(String p_uri) {
  796. // Open URI in a new tab, browser will deal with it by protocol.
  797. /* clang-format off */
  798. EM_ASM_({
  799. window.open(UTF8ToString($0), '_blank');
  800. }, p_uri.utf8().get_data());
  801. /* clang-format on */
  802. return OK;
  803. }
  804. String OS_JavaScript::get_name() {
  805. return "HTML5";
  806. }
  807. bool OS_JavaScript::can_draw() const {
  808. return true; // Always?
  809. }
  810. String OS_JavaScript::get_user_data_dir() const {
  811. return "/userfs";
  812. };
  813. String OS_JavaScript::get_resource_dir() const {
  814. return "/";
  815. }
  816. OS::PowerState OS_JavaScript::get_power_state() {
  817. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  818. return OS::POWERSTATE_UNKNOWN;
  819. }
  820. int OS_JavaScript::get_power_seconds_left() {
  821. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  822. return -1;
  823. }
  824. int OS_JavaScript::get_power_percent_left() {
  825. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  826. return -1;
  827. }
  828. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  829. OS_JavaScript *os = get_singleton();
  830. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  831. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  832. // Wait five seconds in case more files are about to be closed.
  833. os->sync_wait_time = 5000;
  834. }
  835. }
  836. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  837. idb_available = p_idb_available;
  838. }
  839. bool OS_JavaScript::is_userfs_persistent() const {
  840. return idb_available;
  841. }
  842. OS_JavaScript *OS_JavaScript::get_singleton() {
  843. return static_cast<OS_JavaScript *>(OS::get_singleton());
  844. }
  845. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  846. List<String> arguments;
  847. for (int i = 1; i < p_argc; i++) {
  848. arguments.push_back(String::utf8(p_argv[i]));
  849. }
  850. set_cmdline(p_argv[0], arguments);
  851. window_maximized = false;
  852. entering_fullscreen = false;
  853. just_exited_fullscreen = false;
  854. main_loop = NULL;
  855. idb_available = false;
  856. sync_wait_time = -1;
  857. AudioDriverManager::add_driver(&audio_driver_javascript);
  858. Vector<Logger *> loggers;
  859. loggers.push_back(memnew(StdLogger));
  860. _set_logger(memnew(CompositeLogger(loggers)));
  861. FileAccessUnix::close_notification_func = file_access_close_callback;
  862. }