os_javascript.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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/engine.h"
  32. #include "core/io/file_access_buffered_fa.h"
  33. #include "dom_keys.h"
  34. #include "drivers/gles3/rasterizer_gles3.h"
  35. #include "drivers/unix/dir_access_unix.h"
  36. #include "drivers/unix/file_access_unix.h"
  37. #include "main/main.h"
  38. #include "servers/visual/visual_server_raster.h"
  39. #include <emscripten.h>
  40. #include <stdlib.h>
  41. #define DOM_BUTTON_LEFT 0
  42. #define DOM_BUTTON_MIDDLE 1
  43. #define DOM_BUTTON_RIGHT 2
  44. template <typename T>
  45. static void dom2godot_mod(T emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  46. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  47. godot_event->set_alt(emscripten_event_ptr->altKey);
  48. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  49. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  50. }
  51. int OS_JavaScript::get_video_driver_count() const {
  52. return 1;
  53. }
  54. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  55. return "GLES3";
  56. }
  57. int OS_JavaScript::get_audio_driver_count() const {
  58. return 1;
  59. }
  60. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  61. return "JavaScript";
  62. }
  63. void OS_JavaScript::initialize_core() {
  64. OS_Unix::initialize_core();
  65. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  66. }
  67. static EM_BOOL _browser_resize_callback(int event_type, const EmscriptenUiEvent *ui_event, void *user_data) {
  68. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_RESIZE, false);
  69. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  70. // The order of the fullscreen change event and the window size change
  71. // event varies, even within just one browser, so defer handling
  72. os->request_canvas_size_adjustment();
  73. return false;
  74. }
  75. static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFullscreenChangeEvent *event, void *user_data) {
  76. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false);
  77. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  78. String id = String::utf8(event->id);
  79. // empty id is canvas
  80. if (id.empty() || id == "canvas") {
  81. OS::VideoMode vm = os->get_video_mode();
  82. // this event property is the only reliable information on
  83. // browser fullscreen state
  84. vm.fullscreen = event->isFullscreen;
  85. os->set_video_mode(vm);
  86. os->request_canvas_size_adjustment();
  87. }
  88. return false;
  89. }
  90. static InputDefault *_input;
  91. static bool is_canvas_focused() {
  92. /* clang-format off */
  93. return EM_ASM_INT_V(
  94. return document.activeElement == Module.canvas;
  95. );
  96. /* clang-format on */
  97. }
  98. static void focus_canvas() {
  99. /* clang-format off */
  100. EM_ASM(
  101. Module.canvas.focus();
  102. );
  103. /* clang-format on */
  104. }
  105. static bool _cursor_inside_canvas = true;
  106. static bool is_cursor_inside_canvas() {
  107. return _cursor_inside_canvas;
  108. }
  109. static EM_BOOL _mousebutton_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) {
  110. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEDOWN && event_type != EMSCRIPTEN_EVENT_MOUSEUP, false);
  111. Ref<InputEventMouseButton> ev;
  112. ev.instance();
  113. ev->set_pressed(event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  114. ev->set_position(Point2(mouse_event->canvasX, mouse_event->canvasY));
  115. ev->set_global_position(ev->get_position());
  116. dom2godot_mod(mouse_event, ev);
  117. switch (mouse_event->button) {
  118. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  119. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  120. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  121. default: return false;
  122. }
  123. int mask = _input->get_mouse_button_mask();
  124. int button_flag = 1 << (ev->get_button_index() - 1);
  125. if (ev->is_pressed()) {
  126. // since the event is consumed, focus manually
  127. if (!is_canvas_focused()) {
  128. focus_canvas();
  129. }
  130. mask |= button_flag;
  131. } else if (mask & button_flag) {
  132. mask &= ~button_flag;
  133. } else {
  134. // release event, but press was outside the canvas, so ignore
  135. return false;
  136. }
  137. ev->set_button_mask(mask);
  138. _input->parse_input_event(ev);
  139. // prevent selection dragging
  140. return true;
  141. }
  142. static EM_BOOL _mousemove_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) {
  143. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEMOVE, false);
  144. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  145. int input_mask = _input->get_mouse_button_mask();
  146. Point2 pos = Point2(mouse_event->canvasX, mouse_event->canvasY);
  147. // outside the canvas, only read mouse movement if dragging started inside
  148. // the canvas; imitating desktop app behaviour
  149. if (!is_cursor_inside_canvas() && !input_mask)
  150. return false;
  151. Ref<InputEventMouseMotion> ev;
  152. ev.instance();
  153. dom2godot_mod(mouse_event, ev);
  154. ev->set_button_mask(input_mask);
  155. ev->set_position(pos);
  156. ev->set_global_position(ev->get_position());
  157. ev->set_relative(ev->get_position() - _input->get_mouse_position());
  158. _input->set_mouse_position(ev->get_position());
  159. ev->set_speed(_input->get_last_mouse_speed());
  160. _input->parse_input_event(ev);
  161. // don't suppress mouseover/leave events
  162. return false;
  163. }
  164. static EM_BOOL _wheel_callback(int event_type, const EmscriptenWheelEvent *wheel_event, void *user_data) {
  165. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  166. if (!is_canvas_focused()) {
  167. if (is_cursor_inside_canvas()) {
  168. focus_canvas();
  169. } else {
  170. return false;
  171. }
  172. }
  173. Ref<InputEventMouseButton> ev;
  174. ev.instance();
  175. ev->set_button_mask(_input->get_mouse_button_mask());
  176. ev->set_position(_input->get_mouse_position());
  177. ev->set_global_position(ev->get_position());
  178. ev->set_shift(_input->is_key_pressed(KEY_SHIFT));
  179. ev->set_alt(_input->is_key_pressed(KEY_ALT));
  180. ev->set_control(_input->is_key_pressed(KEY_CONTROL));
  181. ev->set_metakey(_input->is_key_pressed(KEY_META));
  182. if (wheel_event->deltaY < 0)
  183. ev->set_button_index(BUTTON_WHEEL_UP);
  184. else if (wheel_event->deltaY > 0)
  185. ev->set_button_index(BUTTON_WHEEL_DOWN);
  186. else if (wheel_event->deltaX > 0)
  187. ev->set_button_index(BUTTON_WHEEL_LEFT);
  188. else if (wheel_event->deltaX < 0)
  189. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  190. else
  191. return false;
  192. // Different browsers give wildly different delta values, and we can't
  193. // interpret deltaMode, so use default value for wheel events' factor
  194. ev->set_pressed(true);
  195. _input->parse_input_event(ev);
  196. ev->set_pressed(false);
  197. _input->parse_input_event(ev);
  198. return true;
  199. }
  200. static Point2 _prev_touches[32];
  201. static EM_BOOL _touchpress_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  202. ERR_FAIL_COND_V(
  203. event_type != EMSCRIPTEN_EVENT_TOUCHSTART &&
  204. event_type != EMSCRIPTEN_EVENT_TOUCHEND &&
  205. event_type != EMSCRIPTEN_EVENT_TOUCHCANCEL,
  206. false);
  207. Ref<InputEventScreenTouch> ev;
  208. ev.instance();
  209. int lowest_id_index = -1;
  210. for (int i = 0; i < touch_event->numTouches; ++i) {
  211. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  212. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  213. lowest_id_index = i;
  214. if (!touch.isChanged)
  215. continue;
  216. ev->set_index(touch.identifier);
  217. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  218. _prev_touches[i] = ev->get_position();
  219. ev->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  220. _input->parse_input_event(ev);
  221. }
  222. if (touch_event->touches[lowest_id_index].isChanged) {
  223. Ref<InputEventMouseButton> ev_mouse;
  224. ev_mouse.instance();
  225. ev_mouse->set_button_mask(_input->get_mouse_button_mask());
  226. dom2godot_mod(touch_event, ev_mouse);
  227. const EmscriptenTouchPoint &first_touch = touch_event->touches[lowest_id_index];
  228. ev_mouse->set_position(Point2(first_touch.canvasX, first_touch.canvasY));
  229. ev_mouse->set_global_position(ev_mouse->get_position());
  230. ev_mouse->set_button_index(BUTTON_LEFT);
  231. ev_mouse->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  232. _input->parse_input_event(ev_mouse);
  233. }
  234. return true;
  235. }
  236. static EM_BOOL _touchmove_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  237. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_TOUCHMOVE, false);
  238. Ref<InputEventScreenDrag> ev;
  239. ev.instance();
  240. int lowest_id_index = -1;
  241. for (int i = 0; i < touch_event->numTouches; ++i) {
  242. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  243. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  244. lowest_id_index = i;
  245. if (!touch.isChanged)
  246. continue;
  247. ev->set_index(touch.identifier);
  248. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  249. Point2 &prev = _prev_touches[i];
  250. ev->set_relative(ev->get_position() - prev);
  251. prev = ev->get_position();
  252. _input->parse_input_event(ev);
  253. }
  254. if (touch_event->touches[lowest_id_index].isChanged) {
  255. Ref<InputEventMouseMotion> ev_mouse;
  256. ev_mouse.instance();
  257. dom2godot_mod(touch_event, ev_mouse);
  258. ev_mouse->set_button_mask(_input->get_mouse_button_mask());
  259. const EmscriptenTouchPoint &first_touch = touch_event->touches[lowest_id_index];
  260. ev_mouse->set_position(Point2(first_touch.canvasX, first_touch.canvasY));
  261. ev_mouse->set_global_position(ev_mouse->get_position());
  262. ev_mouse->set_relative(ev_mouse->get_position() - _input->get_mouse_position());
  263. _input->set_mouse_position(ev_mouse->get_position());
  264. ev_mouse->set_speed(_input->get_last_mouse_speed());
  265. _input->parse_input_event(ev_mouse);
  266. }
  267. return true;
  268. }
  269. static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  270. Ref<InputEventKey> ev;
  271. ev.instance();
  272. ev->set_echo(emscripten_event->repeat);
  273. dom2godot_mod(emscripten_event, ev);
  274. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  275. String unicode = String::utf8(emscripten_event->key);
  276. // check if empty or multi-character (e.g. `CapsLock`)
  277. if (unicode.length() != 1) {
  278. // might be empty as well, but better than nonsense
  279. unicode = String::utf8(emscripten_event->charValue);
  280. }
  281. if (unicode.length() == 1) {
  282. ev->set_unicode(unicode[0]);
  283. }
  284. return ev;
  285. }
  286. static Ref<InputEventKey> deferred_key_event;
  287. static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  288. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false);
  289. Ref<InputEventKey> ev = _setup_key_event(key_event);
  290. ev->set_pressed(true);
  291. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  292. // defer to keypress event for legacy unicode retrieval
  293. deferred_key_event = ev;
  294. return false; // do not suppress keypress event
  295. }
  296. _input->parse_input_event(ev);
  297. return true;
  298. }
  299. static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  300. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false);
  301. deferred_key_event->set_unicode(key_event->charCode);
  302. _input->parse_input_event(deferred_key_event);
  303. return true;
  304. }
  305. static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  306. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false);
  307. Ref<InputEventKey> ev = _setup_key_event(key_event);
  308. ev->set_pressed(false);
  309. _input->parse_input_event(ev);
  310. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  311. }
  312. static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) {
  313. OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton();
  314. if (os) {
  315. return os->joy_connection_changed(p_type, p_event);
  316. }
  317. return false;
  318. }
  319. extern "C" {
  320. void send_notification(int notif) {
  321. if (notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || notif == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  322. _cursor_inside_canvas = notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  323. }
  324. OS_JavaScript::get_singleton()->get_main_loop()->notification(notif);
  325. }
  326. }
  327. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  328. print_line("Init OS");
  329. EmscriptenWebGLContextAttributes attributes;
  330. emscripten_webgl_init_context_attributes(&attributes);
  331. attributes.alpha = false;
  332. attributes.antialias = false;
  333. attributes.majorVersion = 2;
  334. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  335. ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE);
  336. video_mode = p_desired;
  337. // can't fulfil fullscreen request due to browser security
  338. video_mode.fullscreen = false;
  339. /* clang-format off */
  340. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  341. /* clang-format on */
  342. set_window_size(Size2(video_mode.width, video_mode.height));
  343. } else {
  344. set_window_size(get_window_size());
  345. }
  346. char locale_ptr[16];
  347. /* clang-format off */
  348. EM_ASM_ARGS({
  349. stringToUTF8(Module.locale, $0, 16);
  350. }, locale_ptr);
  351. /* clang-format on */
  352. setenv("LANG", locale_ptr, true);
  353. print_line("Init Audio");
  354. AudioDriverManager::add_driver(&audio_driver_javascript);
  355. AudioDriverManager::initialize(p_audio_driver);
  356. RasterizerGLES3::register_config();
  357. RasterizerGLES3::make_current();
  358. print_line("Init VS");
  359. visual_server = memnew(VisualServerRaster());
  360. // visual_server->cursor_set_visible(false, 0);
  361. print_line("Init Physicsserver");
  362. input = memnew(InputDefault);
  363. _input = input;
  364. power_manager = memnew(PowerJavascript);
  365. #define EM_CHECK(ev) \
  366. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  367. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  368. #define SET_EM_CALLBACK(target, ev, cb) \
  369. result = emscripten_set_##ev##_callback(target, this, true, &cb); \
  370. EM_CHECK(ev)
  371. #define SET_EM_CALLBACK_NODATA(ev, cb) \
  372. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  373. EM_CHECK(ev)
  374. EMSCRIPTEN_RESULT result;
  375. SET_EM_CALLBACK("#window", mousemove, _mousemove_callback)
  376. SET_EM_CALLBACK("#canvas", mousedown, _mousebutton_callback)
  377. SET_EM_CALLBACK("#window", mouseup, _mousebutton_callback)
  378. SET_EM_CALLBACK("#window", wheel, _wheel_callback)
  379. SET_EM_CALLBACK("#window", touchstart, _touchpress_callback)
  380. SET_EM_CALLBACK("#window", touchmove, _touchmove_callback)
  381. SET_EM_CALLBACK("#window", touchend, _touchpress_callback)
  382. SET_EM_CALLBACK("#window", touchcancel, _touchpress_callback)
  383. SET_EM_CALLBACK("#canvas", keydown, _keydown_callback)
  384. SET_EM_CALLBACK("#canvas", keypress, _keypress_callback)
  385. SET_EM_CALLBACK("#canvas", keyup, _keyup_callback)
  386. SET_EM_CALLBACK(NULL, resize, _browser_resize_callback)
  387. SET_EM_CALLBACK(NULL, fullscreenchange, _fullscreen_change_callback)
  388. SET_EM_CALLBACK_NODATA(gamepadconnected, joy_callback_func)
  389. SET_EM_CALLBACK_NODATA(gamepaddisconnected, joy_callback_func)
  390. #undef SET_EM_CALLBACK_NODATA
  391. #undef SET_EM_CALLBACK
  392. #undef EM_CHECK
  393. visual_server->init();
  394. return OK;
  395. }
  396. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  397. main_loop = p_main_loop;
  398. input->set_main_loop(p_main_loop);
  399. }
  400. void OS_JavaScript::delete_main_loop() {
  401. memdelete(main_loop);
  402. }
  403. void OS_JavaScript::finalize() {
  404. memdelete(input);
  405. }
  406. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  407. /* clang-format off */
  408. EM_ASM_({
  409. window.alert(UTF8ToString($0));
  410. }, p_alert.utf8().get_data());
  411. /* clang-format on */
  412. }
  413. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  414. switch (p_shape) {
  415. case OS::CURSOR_ARROW:
  416. default:
  417. return "auto";
  418. case OS::CURSOR_IBEAM: return "text";
  419. case OS::CURSOR_POINTING_HAND: return "pointer";
  420. case OS::CURSOR_CROSS: return "crosshair";
  421. case OS::CURSOR_WAIT: return "progress";
  422. case OS::CURSOR_BUSY: return "wait";
  423. case OS::CURSOR_DRAG: return "grab";
  424. case OS::CURSOR_CAN_DROP: return "grabbing";
  425. case OS::CURSOR_FORBIDDEN: return "no-drop";
  426. case OS::CURSOR_VSIZE: return "ns-resize";
  427. case OS::CURSOR_HSIZE: return "ew-resize";
  428. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  429. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  430. case OS::CURSOR_MOVE: return "move";
  431. case OS::CURSOR_VSPLIT: return "row-resize";
  432. case OS::CURSOR_HSPLIT: return "col-resize";
  433. case OS::CURSOR_HELP: return "help";
  434. }
  435. }
  436. void OS_JavaScript::set_css_cursor(const char *p_cursor) {
  437. /* clang-format off */
  438. EM_ASM_({
  439. Module.canvas.style.cursor = UTF8ToString($0);
  440. }, p_cursor);
  441. /* clang-format on */
  442. }
  443. const char *OS_JavaScript::get_css_cursor() const {
  444. char cursor[16];
  445. /* clang-format off */
  446. EM_ASM_INT({
  447. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  448. }, cursor);
  449. /* clang-format on */
  450. return cursor;
  451. }
  452. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  453. ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1);
  454. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  455. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  456. if (p_mode == get_mouse_mode())
  457. return;
  458. if (p_mode == MOUSE_MODE_VISIBLE) {
  459. set_css_cursor(godot2dom_cursor(cursor_shape));
  460. emscripten_exit_pointerlock();
  461. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  462. set_css_cursor("none");
  463. emscripten_exit_pointerlock();
  464. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  465. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  466. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  467. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  468. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  469. set_css_cursor(godot2dom_cursor(cursor_shape));
  470. }
  471. }
  472. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  473. if (!strcmp(get_css_cursor(), "none"))
  474. return MOUSE_MODE_HIDDEN;
  475. EmscriptenPointerlockChangeEvent ev;
  476. emscripten_get_pointerlock_status(&ev);
  477. return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  478. }
  479. Point2 OS_JavaScript::get_mouse_position() const {
  480. return input->get_mouse_position();
  481. }
  482. int OS_JavaScript::get_mouse_button_state() const {
  483. return input->get_mouse_button_mask();
  484. }
  485. void OS_JavaScript::set_window_title(const String &p_title) {
  486. /* clang-format off */
  487. EM_ASM_({
  488. document.title = UTF8ToString($0);
  489. }, p_title.utf8().get_data());
  490. /* clang-format on */
  491. }
  492. //interesting byt not yet
  493. //void set_clipboard(const String& p_text);
  494. //String get_clipboard() const;
  495. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  496. video_mode = p_video_mode;
  497. }
  498. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  499. return video_mode;
  500. }
  501. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  502. EmscriptenFullscreenChangeEvent ev;
  503. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  504. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  505. return Size2(ev.screenWidth, ev.screenHeight);
  506. }
  507. void OS_JavaScript::set_window_size(const Size2 p_size) {
  508. windowed_size = p_size;
  509. if (is_window_fullscreen()) {
  510. window_maximized = false;
  511. set_window_fullscreen(false);
  512. } else if (is_window_maximized()) {
  513. set_window_maximized(false);
  514. } else {
  515. video_mode.width = p_size.x;
  516. video_mode.height = p_size.y;
  517. emscripten_set_canvas_size(p_size.x, p_size.y);
  518. }
  519. }
  520. Size2 OS_JavaScript::get_window_size() const {
  521. int canvas[3];
  522. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  523. return Size2(canvas[0], canvas[1]);
  524. }
  525. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  526. window_maximized = p_enabled;
  527. if (is_window_fullscreen()) {
  528. set_window_fullscreen(false);
  529. return;
  530. }
  531. // Calling emscripten_enter_soft_fullscreen mutltiple times hides all
  532. // page elements except the canvas permanently, so track state
  533. if (p_enabled && !soft_fs_enabled) {
  534. EmscriptenFullscreenStrategy strategy;
  535. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  536. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  537. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  538. strategy.canvasResizedCallback = NULL;
  539. emscripten_enter_soft_fullscreen(NULL, &strategy);
  540. soft_fs_enabled = true;
  541. video_mode.width = get_window_size().width;
  542. video_mode.height = get_window_size().height;
  543. } else if (!p_enabled) {
  544. emscripten_exit_soft_fullscreen();
  545. soft_fs_enabled = false;
  546. video_mode.width = windowed_size.width;
  547. video_mode.height = windowed_size.height;
  548. emscripten_set_canvas_size(video_mode.width, video_mode.height);
  549. }
  550. }
  551. void OS_JavaScript::set_window_fullscreen(bool p_enable) {
  552. if (p_enable == is_window_fullscreen()) {
  553. return;
  554. }
  555. // only requesting changes here, if successful, canvas is resized in
  556. // _browser_resize_callback or _fullscreen_change_callback
  557. EMSCRIPTEN_RESULT result;
  558. if (p_enable) {
  559. if (window_maximized) {
  560. // soft fs during real fs can cause issues
  561. set_window_maximized(false);
  562. window_maximized = true;
  563. }
  564. EmscriptenFullscreenStrategy strategy;
  565. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  566. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  567. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  568. strategy.canvasResizedCallback = NULL;
  569. emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  570. } else {
  571. result = emscripten_exit_fullscreen();
  572. if (result != EMSCRIPTEN_RESULT_SUCCESS) {
  573. ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
  574. }
  575. }
  576. }
  577. bool OS_JavaScript::is_window_fullscreen() const {
  578. return video_mode.fullscreen;
  579. }
  580. void OS_JavaScript::request_canvas_size_adjustment() {
  581. canvas_size_adjustment_requested = true;
  582. }
  583. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  584. Size2 screen = get_screen_size();
  585. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  586. }
  587. String OS_JavaScript::get_name() {
  588. return "HTML5";
  589. }
  590. MainLoop *OS_JavaScript::get_main_loop() const {
  591. return main_loop;
  592. }
  593. bool OS_JavaScript::can_draw() const {
  594. return true; //always?
  595. }
  596. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  597. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  598. cursor_shape = p_shape;
  599. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  600. set_css_cursor(godot2dom_cursor(cursor_shape));
  601. }
  602. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  603. }
  604. void OS_JavaScript::main_loop_begin() {
  605. if (main_loop)
  606. main_loop->init();
  607. /* clang-format off */
  608. EM_ASM_ARGS({
  609. const send_notification = cwrap('send_notification', null, ['number']);
  610. const notifs = arguments;
  611. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, i) {
  612. Module.canvas.addEventListener(event, send_notification.bind(null, notifs[i]));
  613. });
  614. },
  615. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  616. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  617. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  618. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  619. );
  620. /* clang-format on */
  621. }
  622. bool OS_JavaScript::main_loop_iterate() {
  623. if (!main_loop)
  624. return false;
  625. if (idbfs_available && time_to_save_sync >= 0) {
  626. int64_t newtime = get_ticks_msec();
  627. int64_t elapsed = newtime - last_sync_time;
  628. last_sync_time = newtime;
  629. time_to_save_sync -= elapsed;
  630. if (time_to_save_sync < 0) {
  631. //time to sync, for real
  632. /* clang-format off */
  633. EM_ASM(
  634. FS.syncfs(function(err) {
  635. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  636. });
  637. );
  638. /* clang-format on */
  639. }
  640. }
  641. process_joypads();
  642. if (canvas_size_adjustment_requested) {
  643. if (video_mode.fullscreen || window_maximized) {
  644. video_mode.width = get_window_size().width;
  645. video_mode.height = get_window_size().height;
  646. }
  647. if (!video_mode.fullscreen) {
  648. set_window_maximized(window_maximized);
  649. }
  650. canvas_size_adjustment_requested = false;
  651. }
  652. return Main::iteration();
  653. }
  654. void OS_JavaScript::main_loop_end() {
  655. if (main_loop)
  656. main_loop->finish();
  657. }
  658. void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
  659. input->set_accelerometer(p_accelerometer);
  660. }
  661. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  662. /* clang-format off */
  663. return EM_ASM_INT_V(
  664. return 'ontouchstart' in window;
  665. );
  666. /* clang-format on */
  667. }
  668. void OS_JavaScript::main_loop_request_quit() {
  669. if (main_loop)
  670. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  671. }
  672. Error OS_JavaScript::shell_open(String p_uri) {
  673. /* clang-format off */
  674. EM_ASM_({
  675. window.open(UTF8ToString($0), '_blank');
  676. }, p_uri.utf8().get_data());
  677. /* clang-format on */
  678. return OK;
  679. }
  680. String OS_JavaScript::get_resource_dir() const {
  681. return "/"; //javascript has it's own filesystem for resources inside the APK
  682. }
  683. String OS_JavaScript::get_user_data_dir() const {
  684. /*
  685. if (get_user_data_dir_func)
  686. return get_user_data_dir_func();
  687. */
  688. return "/userfs";
  689. };
  690. String OS_JavaScript::get_executable_path() const {
  691. return OS::get_executable_path();
  692. }
  693. void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) {
  694. OS_JavaScript *os = static_cast<OS_JavaScript *>(get_singleton());
  695. if (os->idbfs_available && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  696. os->last_sync_time = OS::get_singleton()->get_ticks_msec();
  697. os->time_to_save_sync = 5000; //five seconds since last save
  698. }
  699. }
  700. void OS_JavaScript::process_joypads() {
  701. int joy_count = emscripten_get_num_gamepads();
  702. for (int i = 0; i < joy_count; i++) {
  703. EmscriptenGamepadEvent state;
  704. emscripten_get_gamepad_status(i, &state);
  705. if (state.connected) {
  706. int num_buttons = MIN(state.numButtons, 18);
  707. int num_axes = MIN(state.numAxes, 8);
  708. for (int j = 0; j < num_buttons; j++) {
  709. float value = state.analogButton[j];
  710. if (String(state.mapping) == "standard" && (j == 6 || j == 7)) {
  711. InputDefault::JoyAxis jx;
  712. jx.min = 0;
  713. jx.value = value;
  714. input->joy_axis(i, j, jx);
  715. } else {
  716. input->joy_button(i, j, value);
  717. }
  718. }
  719. for (int j = 0; j < num_axes; j++) {
  720. InputDefault::JoyAxis jx;
  721. jx.min = -1;
  722. jx.value = state.axis[j];
  723. input->joy_axis(i, j, jx);
  724. }
  725. }
  726. }
  727. }
  728. bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) {
  729. if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  730. String guid = "";
  731. if (String(p_event->mapping) == "standard")
  732. guid = "Default HTML5 Gamepad";
  733. input->joy_connection_changed(p_event->index, true, String(p_event->id), guid);
  734. } else {
  735. input->joy_connection_changed(p_event->index, false, "");
  736. }
  737. return true;
  738. }
  739. bool OS_JavaScript::is_joy_known(int p_device) {
  740. return input->is_joy_mapped(p_device);
  741. }
  742. String OS_JavaScript::get_joy_guid(int p_device) const {
  743. return input->get_joy_guid_remapped(p_device);
  744. }
  745. OS::PowerState OS_JavaScript::get_power_state() {
  746. return power_manager->get_power_state();
  747. }
  748. int OS_JavaScript::get_power_seconds_left() {
  749. return power_manager->get_power_seconds_left();
  750. }
  751. int OS_JavaScript::get_power_percent_left() {
  752. return power_manager->get_power_percent_left();
  753. }
  754. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  755. if (p_feature == "HTML5" || p_feature == "web")
  756. return true;
  757. #ifdef JAVASCRIPT_EVAL_ENABLED
  758. if (p_feature == "JavaScript")
  759. return true;
  760. #endif
  761. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  762. // all extensions are already automatically enabled, this function allows
  763. // checking WebGL extension support without inline JavaScript
  764. if (p_feature == "s3tc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb"))
  765. return true;
  766. if (p_feature == "etc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1"))
  767. return true;
  768. if (p_feature == "etc2" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc"))
  769. return true;
  770. return false;
  771. }
  772. void OS_JavaScript::set_idbfs_available(bool p_idbfs_available) {
  773. idbfs_available = p_idbfs_available;
  774. }
  775. bool OS_JavaScript::is_userfs_persistent() const {
  776. return idbfs_available;
  777. }
  778. OS_JavaScript::OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func) {
  779. set_cmdline(p_execpath, get_cmdline_args());
  780. main_loop = NULL;
  781. window_maximized = false;
  782. soft_fs_enabled = false;
  783. canvas_size_adjustment_requested = false;
  784. get_user_data_dir_func = p_get_user_data_dir_func;
  785. FileAccessUnix::close_notification_func = _close_notification_funcs;
  786. idbfs_available = false;
  787. time_to_save_sync = -1;
  788. Vector<Logger *> loggers;
  789. loggers.push_back(memnew(StdLogger));
  790. _set_logger(memnew(CompositeLogger(loggers)));
  791. }
  792. OS_JavaScript::~OS_JavaScript() {
  793. }