os_javascript.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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/engine.h"
  32. #include "core/io/file_access_buffered_fa.h"
  33. #include "dom_keys.h"
  34. #include "drivers/gles2/rasterizer_gles2.h"
  35. #include "drivers/gles3/rasterizer_gles3.h"
  36. #include "drivers/unix/dir_access_unix.h"
  37. #include "drivers/unix/file_access_unix.h"
  38. #include "main/main.h"
  39. #include "servers/visual/visual_server_raster.h"
  40. #include <emscripten.h>
  41. #include <stdlib.h>
  42. #define DOM_BUTTON_LEFT 0
  43. #define DOM_BUTTON_MIDDLE 1
  44. #define DOM_BUTTON_RIGHT 2
  45. template <typename T>
  46. static void dom2godot_mod(T emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  47. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  48. godot_event->set_alt(emscripten_event_ptr->altKey);
  49. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  50. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  51. }
  52. int OS_JavaScript::get_video_driver_count() const {
  53. return VIDEO_DRIVER_MAX;
  54. }
  55. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  56. switch (p_driver) {
  57. case VIDEO_DRIVER_GLES3:
  58. return "GLES3";
  59. case VIDEO_DRIVER_GLES2:
  60. return "GLES2";
  61. }
  62. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  63. ERR_FAIL_V(NULL);
  64. }
  65. int OS_JavaScript::get_audio_driver_count() const {
  66. return 1;
  67. }
  68. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  69. return "JavaScript";
  70. }
  71. void OS_JavaScript::initialize_core() {
  72. OS_Unix::initialize_core();
  73. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  74. }
  75. static EM_BOOL _browser_resize_callback(int event_type, const EmscriptenUiEvent *ui_event, void *user_data) {
  76. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_RESIZE, false);
  77. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  78. // The order of the fullscreen change event and the window size change
  79. // event varies, even within just one browser, so defer handling
  80. os->request_canvas_size_adjustment();
  81. return false;
  82. }
  83. static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFullscreenChangeEvent *event, void *user_data) {
  84. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false);
  85. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  86. String id = String::utf8(event->id);
  87. // empty id is canvas
  88. if (id.empty() || id == "canvas") {
  89. OS::VideoMode vm = os->get_video_mode();
  90. // this event property is the only reliable information on
  91. // browser fullscreen state
  92. vm.fullscreen = event->isFullscreen;
  93. os->set_video_mode(vm);
  94. os->request_canvas_size_adjustment();
  95. }
  96. return false;
  97. }
  98. static InputDefault *_input;
  99. static bool is_canvas_focused() {
  100. /* clang-format off */
  101. return EM_ASM_INT_V(
  102. return document.activeElement == Module.canvas;
  103. );
  104. /* clang-format on */
  105. }
  106. static void focus_canvas() {
  107. /* clang-format off */
  108. EM_ASM(
  109. Module.canvas.focus();
  110. );
  111. /* clang-format on */
  112. }
  113. static bool _cursor_inside_canvas = true;
  114. static bool is_cursor_inside_canvas() {
  115. return _cursor_inside_canvas;
  116. }
  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. Ref<InputEventMouseButton> ev;
  120. ev.instance();
  121. ev->set_pressed(event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  122. ev->set_position(Point2(mouse_event->canvasX, mouse_event->canvasY));
  123. ev->set_global_position(ev->get_position());
  124. dom2godot_mod(mouse_event, ev);
  125. switch (mouse_event->button) {
  126. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  127. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  128. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  129. default: return false;
  130. }
  131. int mask = _input->get_mouse_button_mask();
  132. int button_flag = 1 << (ev->get_button_index() - 1);
  133. if (ev->is_pressed()) {
  134. // since the event is consumed, focus manually
  135. if (!is_canvas_focused()) {
  136. focus_canvas();
  137. }
  138. mask |= button_flag;
  139. } else if (mask & button_flag) {
  140. mask &= ~button_flag;
  141. } else {
  142. // release event, but press was outside the canvas, so ignore
  143. return false;
  144. }
  145. ev->set_button_mask(mask);
  146. _input->parse_input_event(ev);
  147. // prevent selection dragging
  148. return true;
  149. }
  150. static EM_BOOL _mousemove_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) {
  151. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEMOVE, false);
  152. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  153. int input_mask = _input->get_mouse_button_mask();
  154. Point2 pos = Point2(mouse_event->canvasX, mouse_event->canvasY);
  155. // outside the canvas, only read mouse movement if dragging started inside
  156. // the canvas; imitating desktop app behaviour
  157. if (!is_cursor_inside_canvas() && !input_mask)
  158. return false;
  159. Ref<InputEventMouseMotion> ev;
  160. ev.instance();
  161. dom2godot_mod(mouse_event, ev);
  162. ev->set_button_mask(input_mask);
  163. ev->set_position(pos);
  164. ev->set_global_position(ev->get_position());
  165. ev->set_relative(ev->get_position() - _input->get_mouse_position());
  166. _input->set_mouse_position(ev->get_position());
  167. ev->set_speed(_input->get_last_mouse_speed());
  168. _input->parse_input_event(ev);
  169. // don't suppress mouseover/leave events
  170. return false;
  171. }
  172. static EM_BOOL _wheel_callback(int event_type, const EmscriptenWheelEvent *wheel_event, void *user_data) {
  173. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  174. if (!is_canvas_focused()) {
  175. if (is_cursor_inside_canvas()) {
  176. focus_canvas();
  177. } else {
  178. return false;
  179. }
  180. }
  181. Ref<InputEventMouseButton> ev;
  182. ev.instance();
  183. ev->set_button_mask(_input->get_mouse_button_mask());
  184. ev->set_position(_input->get_mouse_position());
  185. ev->set_global_position(ev->get_position());
  186. ev->set_shift(_input->is_key_pressed(KEY_SHIFT));
  187. ev->set_alt(_input->is_key_pressed(KEY_ALT));
  188. ev->set_control(_input->is_key_pressed(KEY_CONTROL));
  189. ev->set_metakey(_input->is_key_pressed(KEY_META));
  190. if (wheel_event->deltaY < 0)
  191. ev->set_button_index(BUTTON_WHEEL_UP);
  192. else if (wheel_event->deltaY > 0)
  193. ev->set_button_index(BUTTON_WHEEL_DOWN);
  194. else if (wheel_event->deltaX > 0)
  195. ev->set_button_index(BUTTON_WHEEL_LEFT);
  196. else if (wheel_event->deltaX < 0)
  197. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  198. else
  199. return false;
  200. // Different browsers give wildly different delta values, and we can't
  201. // interpret deltaMode, so use default value for wheel events' factor
  202. ev->set_pressed(true);
  203. _input->parse_input_event(ev);
  204. ev->set_pressed(false);
  205. _input->parse_input_event(ev);
  206. return true;
  207. }
  208. static Point2 _prev_touches[32];
  209. static EM_BOOL _touchpress_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  210. ERR_FAIL_COND_V(
  211. event_type != EMSCRIPTEN_EVENT_TOUCHSTART &&
  212. event_type != EMSCRIPTEN_EVENT_TOUCHEND &&
  213. event_type != EMSCRIPTEN_EVENT_TOUCHCANCEL,
  214. false);
  215. Ref<InputEventScreenTouch> ev;
  216. ev.instance();
  217. int lowest_id_index = -1;
  218. for (int i = 0; i < touch_event->numTouches; ++i) {
  219. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  220. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  221. lowest_id_index = i;
  222. if (!touch.isChanged)
  223. continue;
  224. ev->set_index(touch.identifier);
  225. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  226. _prev_touches[i] = ev->get_position();
  227. ev->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  228. _input->parse_input_event(ev);
  229. }
  230. if (touch_event->touches[lowest_id_index].isChanged) {
  231. Ref<InputEventMouseButton> ev_mouse;
  232. ev_mouse.instance();
  233. ev_mouse->set_button_mask(_input->get_mouse_button_mask());
  234. dom2godot_mod(touch_event, ev_mouse);
  235. const EmscriptenTouchPoint &first_touch = touch_event->touches[lowest_id_index];
  236. ev_mouse->set_position(Point2(first_touch.canvasX, first_touch.canvasY));
  237. ev_mouse->set_global_position(ev_mouse->get_position());
  238. ev_mouse->set_button_index(BUTTON_LEFT);
  239. ev_mouse->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  240. _input->parse_input_event(ev_mouse);
  241. }
  242. return true;
  243. }
  244. static EM_BOOL _touchmove_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  245. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_TOUCHMOVE, false);
  246. Ref<InputEventScreenDrag> ev;
  247. ev.instance();
  248. int lowest_id_index = -1;
  249. for (int i = 0; i < touch_event->numTouches; ++i) {
  250. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  251. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  252. lowest_id_index = i;
  253. if (!touch.isChanged)
  254. continue;
  255. ev->set_index(touch.identifier);
  256. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  257. Point2 &prev = _prev_touches[i];
  258. ev->set_relative(ev->get_position() - prev);
  259. prev = ev->get_position();
  260. _input->parse_input_event(ev);
  261. }
  262. if (touch_event->touches[lowest_id_index].isChanged) {
  263. Ref<InputEventMouseMotion> ev_mouse;
  264. ev_mouse.instance();
  265. dom2godot_mod(touch_event, ev_mouse);
  266. ev_mouse->set_button_mask(_input->get_mouse_button_mask());
  267. const EmscriptenTouchPoint &first_touch = touch_event->touches[lowest_id_index];
  268. ev_mouse->set_position(Point2(first_touch.canvasX, first_touch.canvasY));
  269. ev_mouse->set_global_position(ev_mouse->get_position());
  270. ev_mouse->set_relative(ev_mouse->get_position() - _input->get_mouse_position());
  271. _input->set_mouse_position(ev_mouse->get_position());
  272. ev_mouse->set_speed(_input->get_last_mouse_speed());
  273. _input->parse_input_event(ev_mouse);
  274. }
  275. return true;
  276. }
  277. static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  278. Ref<InputEventKey> ev;
  279. ev.instance();
  280. ev->set_echo(emscripten_event->repeat);
  281. dom2godot_mod(emscripten_event, ev);
  282. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  283. String unicode = String::utf8(emscripten_event->key);
  284. // check if empty or multi-character (e.g. `CapsLock`)
  285. if (unicode.length() != 1) {
  286. // might be empty as well, but better than nonsense
  287. unicode = String::utf8(emscripten_event->charValue);
  288. }
  289. if (unicode.length() == 1) {
  290. ev->set_unicode(unicode[0]);
  291. }
  292. return ev;
  293. }
  294. static Ref<InputEventKey> deferred_key_event;
  295. static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  296. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false);
  297. Ref<InputEventKey> ev = _setup_key_event(key_event);
  298. ev->set_pressed(true);
  299. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  300. // defer to keypress event for legacy unicode retrieval
  301. deferred_key_event = ev;
  302. return false; // do not suppress keypress event
  303. }
  304. _input->parse_input_event(ev);
  305. return true;
  306. }
  307. static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  308. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false);
  309. deferred_key_event->set_unicode(key_event->charCode);
  310. _input->parse_input_event(deferred_key_event);
  311. return true;
  312. }
  313. static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  314. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false);
  315. Ref<InputEventKey> ev = _setup_key_event(key_event);
  316. ev->set_pressed(false);
  317. _input->parse_input_event(ev);
  318. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  319. }
  320. static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) {
  321. OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton();
  322. if (os) {
  323. return os->joy_connection_changed(p_type, p_event);
  324. }
  325. return false;
  326. }
  327. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int notif) {
  328. if (notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || notif == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  329. _cursor_inside_canvas = notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  330. }
  331. OS_JavaScript::get_singleton()->get_main_loop()->notification(notif);
  332. }
  333. Error 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. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  340. switch (p_video_driver) {
  341. case VIDEO_DRIVER_GLES3:
  342. attributes.majorVersion = 2;
  343. RasterizerGLES3::register_config();
  344. RasterizerGLES3::make_current();
  345. break;
  346. case VIDEO_DRIVER_GLES2:
  347. attributes.majorVersion = 1;
  348. RasterizerGLES2::register_config();
  349. RasterizerGLES2::make_current();
  350. break;
  351. }
  352. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  353. ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available");
  354. ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE);
  355. video_mode = p_desired;
  356. // can't fulfil fullscreen request due to browser security
  357. video_mode.fullscreen = false;
  358. /* clang-format off */
  359. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  360. /* clang-format on */
  361. set_window_size(Size2(video_mode.width, video_mode.height));
  362. } else {
  363. set_window_size(get_window_size());
  364. }
  365. char locale_ptr[16];
  366. /* clang-format off */
  367. EM_ASM_ARGS({
  368. stringToUTF8(Module.locale, $0, 16);
  369. }, locale_ptr);
  370. /* clang-format on */
  371. setenv("LANG", locale_ptr, true);
  372. print_line("Init Audio");
  373. AudioDriverManager::initialize(p_audio_driver);
  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. #define EM_CHECK(ev) \
  381. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  382. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  383. #define SET_EM_CALLBACK(target, ev, cb) \
  384. result = emscripten_set_##ev##_callback(target, this, true, &cb); \
  385. EM_CHECK(ev)
  386. #define SET_EM_CALLBACK_NODATA(ev, cb) \
  387. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  388. EM_CHECK(ev)
  389. EMSCRIPTEN_RESULT result;
  390. SET_EM_CALLBACK("#window", mousemove, _mousemove_callback)
  391. SET_EM_CALLBACK("#canvas", mousedown, _mousebutton_callback)
  392. SET_EM_CALLBACK("#window", mouseup, _mousebutton_callback)
  393. SET_EM_CALLBACK("#window", wheel, _wheel_callback)
  394. SET_EM_CALLBACK("#window", touchstart, _touchpress_callback)
  395. SET_EM_CALLBACK("#window", touchmove, _touchmove_callback)
  396. SET_EM_CALLBACK("#window", touchend, _touchpress_callback)
  397. SET_EM_CALLBACK("#window", touchcancel, _touchpress_callback)
  398. SET_EM_CALLBACK("#canvas", keydown, _keydown_callback)
  399. SET_EM_CALLBACK("#canvas", keypress, _keypress_callback)
  400. SET_EM_CALLBACK("#canvas", keyup, _keyup_callback)
  401. SET_EM_CALLBACK(NULL, resize, _browser_resize_callback)
  402. SET_EM_CALLBACK(NULL, fullscreenchange, _fullscreen_change_callback)
  403. SET_EM_CALLBACK_NODATA(gamepadconnected, joy_callback_func)
  404. SET_EM_CALLBACK_NODATA(gamepaddisconnected, joy_callback_func)
  405. #undef SET_EM_CALLBACK_NODATA
  406. #undef SET_EM_CALLBACK
  407. #undef EM_CHECK
  408. visual_server->init();
  409. return OK;
  410. }
  411. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  412. main_loop = p_main_loop;
  413. input->set_main_loop(p_main_loop);
  414. }
  415. void OS_JavaScript::delete_main_loop() {
  416. memdelete(main_loop);
  417. }
  418. void OS_JavaScript::finalize() {
  419. memdelete(input);
  420. }
  421. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  422. /* clang-format off */
  423. EM_ASM_({
  424. window.alert(UTF8ToString($0));
  425. }, p_alert.utf8().get_data());
  426. /* clang-format on */
  427. }
  428. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  429. switch (p_shape) {
  430. case OS::CURSOR_ARROW:
  431. default:
  432. return "auto";
  433. case OS::CURSOR_IBEAM: return "text";
  434. case OS::CURSOR_POINTING_HAND: return "pointer";
  435. case OS::CURSOR_CROSS: return "crosshair";
  436. case OS::CURSOR_WAIT: return "progress";
  437. case OS::CURSOR_BUSY: return "wait";
  438. case OS::CURSOR_DRAG: return "grab";
  439. case OS::CURSOR_CAN_DROP: return "grabbing";
  440. case OS::CURSOR_FORBIDDEN: return "no-drop";
  441. case OS::CURSOR_VSIZE: return "ns-resize";
  442. case OS::CURSOR_HSIZE: return "ew-resize";
  443. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  444. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  445. case OS::CURSOR_MOVE: return "move";
  446. case OS::CURSOR_VSPLIT: return "row-resize";
  447. case OS::CURSOR_HSPLIT: return "col-resize";
  448. case OS::CURSOR_HELP: return "help";
  449. }
  450. }
  451. void OS_JavaScript::set_css_cursor(const char *p_cursor) {
  452. /* clang-format off */
  453. EM_ASM_({
  454. Module.canvas.style.cursor = UTF8ToString($0);
  455. }, p_cursor);
  456. /* clang-format on */
  457. }
  458. const char *OS_JavaScript::get_css_cursor() const {
  459. char cursor[16];
  460. /* clang-format off */
  461. EM_ASM_INT({
  462. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  463. }, cursor);
  464. /* clang-format on */
  465. return cursor;
  466. }
  467. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  468. ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1);
  469. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  470. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  471. if (p_mode == get_mouse_mode())
  472. return;
  473. if (p_mode == MOUSE_MODE_VISIBLE) {
  474. set_css_cursor(godot2dom_cursor(cursor_shape));
  475. emscripten_exit_pointerlock();
  476. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  477. set_css_cursor("none");
  478. emscripten_exit_pointerlock();
  479. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  480. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  481. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  482. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  483. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  484. set_css_cursor(godot2dom_cursor(cursor_shape));
  485. }
  486. }
  487. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  488. if (!strcmp(get_css_cursor(), "none"))
  489. return MOUSE_MODE_HIDDEN;
  490. EmscriptenPointerlockChangeEvent ev;
  491. emscripten_get_pointerlock_status(&ev);
  492. return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  493. }
  494. Point2 OS_JavaScript::get_mouse_position() const {
  495. return input->get_mouse_position();
  496. }
  497. int OS_JavaScript::get_mouse_button_state() const {
  498. return input->get_mouse_button_mask();
  499. }
  500. void OS_JavaScript::set_window_title(const String &p_title) {
  501. /* clang-format off */
  502. EM_ASM_({
  503. document.title = UTF8ToString($0);
  504. }, p_title.utf8().get_data());
  505. /* clang-format on */
  506. }
  507. //interesting byt not yet
  508. //void set_clipboard(const String& p_text);
  509. //String get_clipboard() const;
  510. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  511. video_mode = p_video_mode;
  512. }
  513. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  514. return video_mode;
  515. }
  516. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  517. EmscriptenFullscreenChangeEvent ev;
  518. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  519. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  520. return Size2(ev.screenWidth, ev.screenHeight);
  521. }
  522. void OS_JavaScript::set_window_size(const Size2 p_size) {
  523. windowed_size = p_size;
  524. if (is_window_fullscreen()) {
  525. window_maximized = false;
  526. set_window_fullscreen(false);
  527. } else if (is_window_maximized()) {
  528. set_window_maximized(false);
  529. } else {
  530. video_mode.width = p_size.x;
  531. video_mode.height = p_size.y;
  532. emscripten_set_canvas_size(p_size.x, p_size.y);
  533. }
  534. }
  535. Size2 OS_JavaScript::get_window_size() const {
  536. int canvas[3];
  537. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  538. return Size2(canvas[0], canvas[1]);
  539. }
  540. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  541. window_maximized = p_enabled;
  542. if (is_window_fullscreen()) {
  543. set_window_fullscreen(false);
  544. return;
  545. }
  546. // Calling emscripten_enter_soft_fullscreen mutltiple times hides all
  547. // page elements except the canvas permanently, so track state
  548. if (p_enabled && !soft_fs_enabled) {
  549. EmscriptenFullscreenStrategy strategy;
  550. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  551. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  552. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  553. strategy.canvasResizedCallback = NULL;
  554. emscripten_enter_soft_fullscreen(NULL, &strategy);
  555. soft_fs_enabled = true;
  556. video_mode.width = get_window_size().width;
  557. video_mode.height = get_window_size().height;
  558. } else if (!p_enabled) {
  559. emscripten_exit_soft_fullscreen();
  560. soft_fs_enabled = false;
  561. video_mode.width = windowed_size.width;
  562. video_mode.height = windowed_size.height;
  563. emscripten_set_canvas_size(video_mode.width, video_mode.height);
  564. }
  565. }
  566. void OS_JavaScript::set_window_fullscreen(bool p_enable) {
  567. if (p_enable == is_window_fullscreen()) {
  568. return;
  569. }
  570. // only requesting changes here, if successful, canvas is resized in
  571. // _browser_resize_callback or _fullscreen_change_callback
  572. EMSCRIPTEN_RESULT result;
  573. if (p_enable) {
  574. if (window_maximized) {
  575. // soft fs during real fs can cause issues
  576. set_window_maximized(false);
  577. window_maximized = true;
  578. }
  579. EmscriptenFullscreenStrategy strategy;
  580. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  581. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  582. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  583. strategy.canvasResizedCallback = NULL;
  584. emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  585. } else {
  586. result = emscripten_exit_fullscreen();
  587. if (result != EMSCRIPTEN_RESULT_SUCCESS) {
  588. ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
  589. }
  590. }
  591. }
  592. bool OS_JavaScript::is_window_fullscreen() const {
  593. return video_mode.fullscreen;
  594. }
  595. void OS_JavaScript::request_canvas_size_adjustment() {
  596. canvas_size_adjustment_requested = true;
  597. }
  598. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  599. Size2 screen = get_screen_size();
  600. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  601. }
  602. String OS_JavaScript::get_name() {
  603. return "HTML5";
  604. }
  605. MainLoop *OS_JavaScript::get_main_loop() const {
  606. return main_loop;
  607. }
  608. bool OS_JavaScript::can_draw() const {
  609. return true; //always?
  610. }
  611. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  612. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  613. cursor_shape = p_shape;
  614. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  615. set_css_cursor(godot2dom_cursor(cursor_shape));
  616. }
  617. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  618. }
  619. void OS_JavaScript::main_loop_begin() {
  620. if (main_loop)
  621. main_loop->init();
  622. /* clang-format off */
  623. EM_ASM_ARGS({
  624. const send_notification = cwrap('send_notification', null, ['number']);
  625. const notifs = arguments;
  626. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, i) {
  627. Module.canvas.addEventListener(event, send_notification.bind(null, notifs[i]));
  628. });
  629. },
  630. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  631. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  632. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  633. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  634. );
  635. /* clang-format on */
  636. }
  637. bool OS_JavaScript::main_loop_iterate() {
  638. if (!main_loop)
  639. return false;
  640. if (idbfs_available && time_to_save_sync >= 0) {
  641. int64_t newtime = get_ticks_msec();
  642. int64_t elapsed = newtime - last_sync_time;
  643. last_sync_time = newtime;
  644. time_to_save_sync -= elapsed;
  645. if (time_to_save_sync < 0) {
  646. //time to sync, for real
  647. /* clang-format off */
  648. EM_ASM(
  649. FS.syncfs(function(err) {
  650. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  651. });
  652. );
  653. /* clang-format on */
  654. }
  655. }
  656. process_joypads();
  657. if (canvas_size_adjustment_requested) {
  658. if (video_mode.fullscreen || window_maximized) {
  659. video_mode.width = get_window_size().width;
  660. video_mode.height = get_window_size().height;
  661. }
  662. if (!video_mode.fullscreen) {
  663. set_window_maximized(window_maximized);
  664. }
  665. canvas_size_adjustment_requested = false;
  666. }
  667. return Main::iteration();
  668. }
  669. void OS_JavaScript::main_loop_end() {
  670. if (main_loop)
  671. main_loop->finish();
  672. }
  673. void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
  674. input->set_accelerometer(p_accelerometer);
  675. }
  676. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  677. /* clang-format off */
  678. return EM_ASM_INT_V(
  679. return 'ontouchstart' in window;
  680. );
  681. /* clang-format on */
  682. }
  683. void OS_JavaScript::main_loop_request_quit() {
  684. if (main_loop)
  685. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  686. }
  687. Error OS_JavaScript::shell_open(String p_uri) {
  688. /* clang-format off */
  689. EM_ASM_({
  690. window.open(UTF8ToString($0), '_blank');
  691. }, p_uri.utf8().get_data());
  692. /* clang-format on */
  693. return OK;
  694. }
  695. String OS_JavaScript::get_resource_dir() const {
  696. return "/"; //javascript has it's own filesystem for resources inside the APK
  697. }
  698. String OS_JavaScript::get_user_data_dir() const {
  699. /*
  700. if (get_user_data_dir_func)
  701. return get_user_data_dir_func();
  702. */
  703. return "/userfs";
  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. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  762. return OS::POWERSTATE_UNKNOWN;
  763. }
  764. int OS_JavaScript::get_power_seconds_left() {
  765. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  766. return -1;
  767. }
  768. int OS_JavaScript::get_power_percent_left() {
  769. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  770. return -1;
  771. }
  772. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  773. if (p_feature == "HTML5" || p_feature == "web")
  774. return true;
  775. #ifdef JAVASCRIPT_EVAL_ENABLED
  776. if (p_feature == "JavaScript")
  777. return true;
  778. #endif
  779. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  780. // all extensions are already automatically enabled, this function allows
  781. // checking WebGL extension support without inline JavaScript
  782. if (p_feature == "s3tc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb"))
  783. return true;
  784. if (p_feature == "etc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1"))
  785. return true;
  786. if (p_feature == "etc2" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc"))
  787. return true;
  788. return false;
  789. }
  790. void OS_JavaScript::set_idbfs_available(bool p_idbfs_available) {
  791. idbfs_available = p_idbfs_available;
  792. }
  793. bool OS_JavaScript::is_userfs_persistent() const {
  794. return idbfs_available;
  795. }
  796. OS_JavaScript::OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func) {
  797. set_cmdline(p_execpath, get_cmdline_args());
  798. main_loop = NULL;
  799. window_maximized = false;
  800. soft_fs_enabled = false;
  801. canvas_size_adjustment_requested = false;
  802. get_user_data_dir_func = p_get_user_data_dir_func;
  803. FileAccessUnix::close_notification_func = _close_notification_funcs;
  804. idbfs_available = false;
  805. time_to_save_sync = -1;
  806. Vector<Logger *> loggers;
  807. loggers.push_back(memnew(StdLogger));
  808. _set_logger(memnew(CompositeLogger(loggers)));
  809. AudioDriverManager::add_driver(&audio_driver_javascript);
  810. }
  811. OS_JavaScript::~OS_JavaScript() {
  812. }