os_javascript.cpp 30 KB

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