os_javascript.cpp 27 KB

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