os_javascript.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. void OS_JavaScript::set_css_cursor(const char *p_cursor) {
  403. /* clang-format off */
  404. EM_ASM_({
  405. Module.canvas.style.cursor = Module.UTF8ToString($0);
  406. }, p_cursor);
  407. /* clang-format on */
  408. }
  409. const char *OS_JavaScript::get_css_cursor() const {
  410. char cursor[16];
  411. /* clang-format off */
  412. EM_ASM_INT({
  413. Module.stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  414. }, cursor);
  415. /* clang-format on */
  416. return cursor;
  417. }
  418. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  419. ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1);
  420. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  421. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  422. if (p_mode == get_mouse_mode())
  423. return;
  424. if (p_mode == MOUSE_MODE_VISIBLE) {
  425. set_css_cursor("auto");
  426. emscripten_exit_pointerlock();
  427. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  428. set_css_cursor("none");
  429. emscripten_exit_pointerlock();
  430. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  431. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  432. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  433. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  434. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  435. set_css_cursor("auto");
  436. }
  437. }
  438. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  439. if (!strcmp(get_css_cursor(), "none"))
  440. return MOUSE_MODE_HIDDEN;
  441. EmscriptenPointerlockChangeEvent ev;
  442. emscripten_get_pointerlock_status(&ev);
  443. return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  444. }
  445. Point2 OS_JavaScript::get_mouse_position() const {
  446. return input->get_mouse_position();
  447. }
  448. int OS_JavaScript::get_mouse_button_state() const {
  449. return input->get_mouse_button_mask();
  450. }
  451. void OS_JavaScript::set_window_title(const String &p_title) {
  452. /* clang-format off */
  453. EM_ASM_({
  454. document.title = UTF8ToString($0);
  455. }, p_title.utf8().get_data());
  456. /* clang-format on */
  457. }
  458. //interesting byt not yet
  459. //void set_clipboard(const String& p_text);
  460. //String get_clipboard() const;
  461. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  462. video_mode = p_video_mode;
  463. }
  464. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  465. return video_mode;
  466. }
  467. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  468. ERR_FAIL_COND_V(p_screen != 0, Size2());
  469. EmscriptenFullscreenChangeEvent ev;
  470. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  471. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  472. return Size2(ev.screenWidth, ev.screenHeight);
  473. }
  474. void OS_JavaScript::set_window_size(const Size2 p_size) {
  475. window_maximized = false;
  476. if (is_window_fullscreen()) {
  477. set_window_fullscreen(false);
  478. }
  479. _windowed_size = p_size;
  480. video_mode.width = p_size.x;
  481. video_mode.height = p_size.y;
  482. emscripten_set_canvas_size(p_size.x, p_size.y);
  483. }
  484. Size2 OS_JavaScript::get_window_size() const {
  485. int canvas[3];
  486. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  487. return Size2(canvas[0], canvas[1]);
  488. }
  489. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  490. window_maximized = p_enabled;
  491. if (p_enabled) {
  492. if (is_window_fullscreen()) {
  493. // _browser_resize callback will set canvas size
  494. set_window_fullscreen(false);
  495. } else {
  496. /* clang-format off */
  497. video_mode.width = EM_ASM_INT_V(return window.innerWidth);
  498. video_mode.height = EM_ASM_INT_V(return window.innerHeight);
  499. /* clang-format on */
  500. emscripten_set_canvas_size(video_mode.width, video_mode.height);
  501. }
  502. } else {
  503. set_window_size(_windowed_size);
  504. }
  505. }
  506. void OS_JavaScript::set_window_fullscreen(bool p_enable) {
  507. if (p_enable == is_window_fullscreen()) {
  508. return;
  509. }
  510. // only requesting changes here, if successful, canvas is resized in
  511. // _browser_resize_callback or _fullscreen_change_callback
  512. EMSCRIPTEN_RESULT result;
  513. if (p_enable) {
  514. /* clang-format off */
  515. EM_ASM(Module.requestFullscreen(false, false););
  516. /* clang-format on */
  517. } else {
  518. result = emscripten_exit_fullscreen();
  519. if (result != EMSCRIPTEN_RESULT_SUCCESS) {
  520. ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
  521. }
  522. }
  523. }
  524. bool OS_JavaScript::is_window_fullscreen() const {
  525. return video_mode.fullscreen;
  526. }
  527. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  528. Size2 screen = get_screen_size();
  529. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  530. }
  531. String OS_JavaScript::get_name() {
  532. return "HTML5";
  533. }
  534. MainLoop *OS_JavaScript::get_main_loop() const {
  535. return main_loop;
  536. }
  537. bool OS_JavaScript::can_draw() const {
  538. return true; //always?
  539. }
  540. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  541. //javascript really really really has no mouse.. how amazing..
  542. }
  543. void OS_JavaScript::main_loop_begin() {
  544. if (main_loop)
  545. main_loop->init();
  546. }
  547. bool OS_JavaScript::main_loop_iterate() {
  548. if (!main_loop)
  549. return false;
  550. if (time_to_save_sync >= 0) {
  551. int64_t newtime = get_ticks_msec();
  552. int64_t elapsed = newtime - last_sync_time;
  553. last_sync_time = newtime;
  554. time_to_save_sync -= elapsed;
  555. if (time_to_save_sync < 0) {
  556. //time to sync, for real
  557. /* clang-format off */
  558. EM_ASM(
  559. FS.syncfs(function(err) {
  560. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  561. });
  562. );
  563. /* clang-format on */
  564. }
  565. }
  566. process_joypads();
  567. return Main::iteration();
  568. }
  569. void OS_JavaScript::main_loop_end() {
  570. if (main_loop)
  571. main_loop->finish();
  572. }
  573. void OS_JavaScript::main_loop_focusout() {
  574. if (main_loop)
  575. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  576. //audio_driver_javascript.set_pause(true);
  577. }
  578. void OS_JavaScript::main_loop_focusin() {
  579. if (main_loop)
  580. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  581. //audio_driver_javascript.set_pause(false);
  582. }
  583. void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
  584. input->set_accelerometer(p_accelerometer);
  585. }
  586. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  587. return false; //???
  588. }
  589. void OS_JavaScript::main_loop_request_quit() {
  590. if (main_loop)
  591. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  592. }
  593. Error OS_JavaScript::shell_open(String p_uri) {
  594. /* clang-format off */
  595. EM_ASM_({
  596. window.open(UTF8ToString($0), '_blank');
  597. }, p_uri.utf8().get_data());
  598. /* clang-format on */
  599. return OK;
  600. }
  601. String OS_JavaScript::get_resource_dir() const {
  602. return "/"; //javascript has it's own filesystem for resources inside the APK
  603. }
  604. String OS_JavaScript::get_data_dir() const {
  605. /*
  606. if (get_data_dir_func)
  607. return get_data_dir_func();
  608. */
  609. return "/userfs";
  610. //return GlobalConfig::get_singleton()->get_singleton_object("GodotOS")->call("get_data_dir");
  611. };
  612. String OS_JavaScript::get_executable_path() const {
  613. return OS::get_executable_path();
  614. }
  615. void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) {
  616. print_line("close " + p_file + " flags " + itos(p_flags));
  617. if (p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  618. static_cast<OS_JavaScript *>(get_singleton())->last_sync_time = OS::get_singleton()->get_ticks_msec();
  619. static_cast<OS_JavaScript *>(get_singleton())->time_to_save_sync = 5000; //five seconds since last save
  620. }
  621. }
  622. void OS_JavaScript::process_joypads() {
  623. int joy_count = emscripten_get_num_gamepads();
  624. for (int i = 0; i < joy_count; i++) {
  625. EmscriptenGamepadEvent state;
  626. emscripten_get_gamepad_status(i, &state);
  627. if (state.connected) {
  628. int num_buttons = MIN(state.numButtons, 18);
  629. int num_axes = MIN(state.numAxes, 8);
  630. for (int j = 0; j < num_buttons; j++) {
  631. float value = state.analogButton[j];
  632. if (String(state.mapping) == "standard" && (j == 6 || j == 7)) {
  633. InputDefault::JoyAxis jx;
  634. jx.min = 0;
  635. jx.value = value;
  636. input->joy_axis(i, j, jx);
  637. } else {
  638. input->joy_button(i, j, value);
  639. }
  640. }
  641. for (int j = 0; j < num_axes; j++) {
  642. InputDefault::JoyAxis jx;
  643. jx.min = -1;
  644. jx.value = state.axis[j];
  645. input->joy_axis(i, j, jx);
  646. }
  647. }
  648. }
  649. }
  650. bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) {
  651. if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  652. String guid = "";
  653. if (String(p_event->mapping) == "standard")
  654. guid = "Default HTML5 Gamepad";
  655. input->joy_connection_changed(p_event->index, true, String(p_event->id), guid);
  656. } else {
  657. input->joy_connection_changed(p_event->index, false, "");
  658. }
  659. return true;
  660. }
  661. bool OS_JavaScript::is_joy_known(int p_device) {
  662. return input->is_joy_mapped(p_device);
  663. }
  664. String OS_JavaScript::get_joy_guid(int p_device) const {
  665. return input->get_joy_guid_remapped(p_device);
  666. }
  667. PowerState OS_JavaScript::get_power_state() {
  668. return power_manager->get_power_state();
  669. }
  670. int OS_JavaScript::get_power_seconds_left() {
  671. return power_manager->get_power_seconds_left();
  672. }
  673. int OS_JavaScript::get_power_percent_left() {
  674. return power_manager->get_power_percent_left();
  675. }
  676. OS_JavaScript::OS_JavaScript(const char *p_execpath, GFXInitFunc p_gfx_init_func, void *p_gfx_init_ud, GetDataDirFunc p_get_data_dir_func) {
  677. set_cmdline(p_execpath, get_cmdline_args());
  678. gfx_init_func = p_gfx_init_func;
  679. gfx_init_ud = p_gfx_init_ud;
  680. main_loop = NULL;
  681. gl_extensions = NULL;
  682. window_maximized = false;
  683. get_data_dir_func = p_get_data_dir_func;
  684. FileAccessUnix::close_notification_func = _close_notification_funcs;
  685. time_to_save_sync = -1;
  686. }
  687. OS_JavaScript::~OS_JavaScript() {
  688. }