os_javascript.cpp 29 KB

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