os_javascript.cpp 30 KB

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