os_javascript.cpp 28 KB

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