os_javascript.cpp 30 KB

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