os_javascript.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  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/io/file_access_buffered_fa.h"
  32. #include "gles2/rasterizer_gles2.h"
  33. #include "gles3/rasterizer_gles3.h"
  34. #include "main/main.h"
  35. #include "servers/visual/visual_server_raster.h"
  36. #include "unix/dir_access_unix.h"
  37. #include "unix/file_access_unix.h"
  38. #include <emscripten.h>
  39. #include <png.h>
  40. #include <stdlib.h>
  41. #include "dom_keys.inc"
  42. #define DOM_BUTTON_LEFT 0
  43. #define DOM_BUTTON_MIDDLE 1
  44. #define DOM_BUTTON_RIGHT 2
  45. #define DOM_BUTTON_XBUTTON1 3
  46. #define DOM_BUTTON_XBUTTON2 4
  47. // Window (canvas)
  48. static void focus_canvas() {
  49. /* clang-format off */
  50. EM_ASM(
  51. Module.canvas.focus();
  52. );
  53. /* clang-format on */
  54. }
  55. static bool is_canvas_focused() {
  56. /* clang-format off */
  57. return EM_ASM_INT_V(
  58. return document.activeElement == Module.canvas;
  59. );
  60. /* clang-format on */
  61. }
  62. static bool cursor_inside_canvas = true;
  63. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  64. OS_JavaScript *os = get_singleton();
  65. // Empty ID is canvas.
  66. String target_id = String::utf8(p_event->id);
  67. if (target_id.empty() || target_id == "canvas") {
  68. // This event property is the only reliable data on
  69. // browser fullscreen state.
  70. os->video_mode.fullscreen = p_event->isFullscreen;
  71. if (os->video_mode.fullscreen) {
  72. os->entering_fullscreen = false;
  73. } else {
  74. // Restoring maximized window now will cause issues,
  75. // so delay until main_loop_iterate.
  76. os->just_exited_fullscreen = true;
  77. }
  78. }
  79. return false;
  80. }
  81. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  82. video_mode = p_video_mode;
  83. }
  84. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  85. return video_mode;
  86. }
  87. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  88. EmscriptenFullscreenChangeEvent ev;
  89. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  90. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  91. return Size2(ev.screenWidth, ev.screenHeight);
  92. }
  93. void OS_JavaScript::set_window_size(const Size2 p_size) {
  94. windowed_size = p_size;
  95. if (video_mode.fullscreen) {
  96. window_maximized = false;
  97. set_window_fullscreen(false);
  98. } else {
  99. if (window_maximized) {
  100. emscripten_exit_soft_fullscreen();
  101. window_maximized = false;
  102. }
  103. emscripten_set_canvas_size(p_size.x, p_size.y);
  104. }
  105. }
  106. Size2 OS_JavaScript::get_window_size() const {
  107. int canvas[3];
  108. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  109. return Size2(canvas[0], canvas[1]);
  110. }
  111. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  112. if (video_mode.fullscreen) {
  113. window_maximized = p_enabled;
  114. set_window_fullscreen(false);
  115. } else if (!p_enabled) {
  116. emscripten_exit_soft_fullscreen();
  117. window_maximized = false;
  118. } else if (!window_maximized) {
  119. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  120. // this would hide page elements permanently.
  121. EmscriptenFullscreenStrategy strategy;
  122. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  123. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  124. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  125. strategy.canvasResizedCallback = NULL;
  126. emscripten_enter_soft_fullscreen(NULL, &strategy);
  127. window_maximized = p_enabled;
  128. }
  129. }
  130. bool OS_JavaScript::is_window_maximized() const {
  131. return window_maximized;
  132. }
  133. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  134. if (p_enabled == video_mode.fullscreen) {
  135. return;
  136. }
  137. // Just request changes here, if successful, logic continues in
  138. // fullscreen_change_callback.
  139. if (p_enabled) {
  140. if (window_maximized) {
  141. // Soft fullsreen during real fullscreen can cause issues, so exit.
  142. // This must be called before requesting full screen.
  143. emscripten_exit_soft_fullscreen();
  144. }
  145. EmscriptenFullscreenStrategy strategy;
  146. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  147. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  148. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  149. strategy.canvasResizedCallback = NULL;
  150. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  151. ERR_EXPLAIN("Enabling fullscreen is only possible from an input callback for the HTML5 platform");
  152. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  153. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  154. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  155. // being overwritten.
  156. entering_fullscreen = true;
  157. } else {
  158. // No logic allowed here, since exiting w/ ESC key won't use this function.
  159. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  160. }
  161. }
  162. bool OS_JavaScript::is_window_fullscreen() const {
  163. return video_mode.fullscreen;
  164. }
  165. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  166. Size2 screen = get_screen_size();
  167. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  168. }
  169. // Keys
  170. template <typename T>
  171. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  172. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  173. godot_event->set_alt(emscripten_event_ptr->altKey);
  174. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  175. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  176. }
  177. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  178. Ref<InputEventKey> ev;
  179. ev.instance();
  180. ev->set_echo(emscripten_event->repeat);
  181. dom2godot_mod(emscripten_event, ev);
  182. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  183. String unicode = String::utf8(emscripten_event->key);
  184. // Check if empty or multi-character (e.g. `CapsLock`).
  185. if (unicode.length() != 1) {
  186. // Might be empty as well, but better than nonsense.
  187. unicode = String::utf8(emscripten_event->charValue);
  188. }
  189. if (unicode.length() == 1) {
  190. ev->set_unicode(unicode[0]);
  191. }
  192. return ev;
  193. }
  194. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  195. OS_JavaScript *os = get_singleton();
  196. Ref<InputEventKey> ev = setup_key_event(p_event);
  197. ev->set_pressed(true);
  198. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  199. // Defer to keypress event for legacy unicode retrieval.
  200. os->deferred_key_event = ev;
  201. // Do not suppress keypress event.
  202. return false;
  203. }
  204. os->input->parse_input_event(ev);
  205. return true;
  206. }
  207. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  208. OS_JavaScript *os = get_singleton();
  209. os->deferred_key_event->set_unicode(p_event->charCode);
  210. os->input->parse_input_event(os->deferred_key_event);
  211. return true;
  212. }
  213. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  214. Ref<InputEventKey> ev = setup_key_event(p_event);
  215. ev->set_pressed(false);
  216. get_singleton()->input->parse_input_event(ev);
  217. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  218. }
  219. // Mouse
  220. Point2 OS_JavaScript::get_mouse_position() const {
  221. return input->get_mouse_position();
  222. }
  223. int OS_JavaScript::get_mouse_button_state() const {
  224. return input->get_mouse_button_mask();
  225. }
  226. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  227. OS_JavaScript *os = get_singleton();
  228. Ref<InputEventMouseButton> ev;
  229. ev.instance();
  230. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  231. ev->set_position(Point2(p_event->canvasX, p_event->canvasY));
  232. ev->set_global_position(ev->get_position());
  233. dom2godot_mod(p_event, ev);
  234. switch (p_event->button) {
  235. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  236. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  237. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  238. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  239. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  240. default: return false;
  241. }
  242. int mask = os->input->get_mouse_button_mask();
  243. int button_flag = 1 << (ev->get_button_index() - 1);
  244. if (ev->is_pressed()) {
  245. // Since the event is consumed, focus manually. The containing iframe,
  246. // if exists, may not have focus yet, so focus even if already focused.
  247. focus_canvas();
  248. mask |= button_flag;
  249. } else if (mask & button_flag) {
  250. mask &= ~button_flag;
  251. } else {
  252. // Received release event, but press was outside the canvas, so ignore.
  253. return false;
  254. }
  255. ev->set_button_mask(mask);
  256. os->input->parse_input_event(ev);
  257. // Prevent multi-click text selection and wheel-click scrolling anchor.
  258. // Context menu is prevented through contextmenu event.
  259. return true;
  260. }
  261. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  262. OS_JavaScript *os = get_singleton();
  263. int input_mask = os->input->get_mouse_button_mask();
  264. Point2 pos = Point2(p_event->canvasX, p_event->canvasY);
  265. // For motion outside the canvas, only read mouse movement if dragging
  266. // started inside the canvas; imitating desktop app behaviour.
  267. if (!cursor_inside_canvas && !input_mask)
  268. return false;
  269. Ref<InputEventMouseMotion> ev;
  270. ev.instance();
  271. dom2godot_mod(p_event, ev);
  272. ev->set_button_mask(input_mask);
  273. ev->set_position(pos);
  274. ev->set_global_position(ev->get_position());
  275. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  276. os->input->set_mouse_position(ev->get_position());
  277. ev->set_speed(os->input->get_last_mouse_speed());
  278. os->input->parse_input_event(ev);
  279. // Don't suppress mouseover/-leave events.
  280. return false;
  281. }
  282. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  283. switch (p_shape) {
  284. case OS::CURSOR_ARROW:
  285. default:
  286. return "auto";
  287. case OS::CURSOR_IBEAM: return "text";
  288. case OS::CURSOR_POINTING_HAND: return "pointer";
  289. case OS::CURSOR_CROSS: return "crosshair";
  290. case OS::CURSOR_WAIT: return "progress";
  291. case OS::CURSOR_BUSY: return "wait";
  292. case OS::CURSOR_DRAG: return "grab";
  293. case OS::CURSOR_CAN_DROP: return "grabbing";
  294. case OS::CURSOR_FORBIDDEN: return "no-drop";
  295. case OS::CURSOR_VSIZE: return "ns-resize";
  296. case OS::CURSOR_HSIZE: return "ew-resize";
  297. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  298. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  299. case OS::CURSOR_MOVE: return "move";
  300. case OS::CURSOR_VSPLIT: return "row-resize";
  301. case OS::CURSOR_HSPLIT: return "col-resize";
  302. case OS::CURSOR_HELP: return "help";
  303. }
  304. }
  305. static void set_css_cursor(const char *p_cursor) {
  306. /* clang-format off */
  307. EM_ASM_({
  308. Module.canvas.style.cursor = UTF8ToString($0);
  309. }, p_cursor);
  310. /* clang-format on */
  311. }
  312. static const char *get_css_cursor() {
  313. char cursor[16];
  314. /* clang-format off */
  315. EM_ASM_INT({
  316. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  317. }, cursor);
  318. /* clang-format on */
  319. return cursor;
  320. }
  321. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  322. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  323. cursor_shape = p_shape;
  324. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  325. set_css_cursor(godot2dom_cursor(cursor_shape));
  326. }
  327. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  328. }
  329. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  330. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  331. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  332. if (p_mode == get_mouse_mode())
  333. return;
  334. if (p_mode == MOUSE_MODE_VISIBLE) {
  335. set_css_cursor(godot2dom_cursor(cursor_shape));
  336. emscripten_exit_pointerlock();
  337. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  338. set_css_cursor("none");
  339. emscripten_exit_pointerlock();
  340. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  341. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  342. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  343. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  344. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  345. set_css_cursor(godot2dom_cursor(cursor_shape));
  346. }
  347. }
  348. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  349. if (String::utf8(get_css_cursor()) == "none")
  350. return MOUSE_MODE_HIDDEN;
  351. EmscriptenPointerlockChangeEvent ev;
  352. emscripten_get_pointerlock_status(&ev);
  353. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  354. }
  355. // Wheel
  356. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  357. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  358. if (!is_canvas_focused()) {
  359. if (cursor_inside_canvas) {
  360. focus_canvas();
  361. } else {
  362. return false;
  363. }
  364. }
  365. InputDefault *input = get_singleton()->input;
  366. Ref<InputEventMouseButton> ev;
  367. ev.instance();
  368. ev->set_button_mask(input->get_mouse_button_mask());
  369. ev->set_position(input->get_mouse_position());
  370. ev->set_global_position(ev->get_position());
  371. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  372. ev->set_alt(input->is_key_pressed(KEY_ALT));
  373. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  374. ev->set_metakey(input->is_key_pressed(KEY_META));
  375. if (p_event->deltaY < 0)
  376. ev->set_button_index(BUTTON_WHEEL_UP);
  377. else if (p_event->deltaY > 0)
  378. ev->set_button_index(BUTTON_WHEEL_DOWN);
  379. else if (p_event->deltaX > 0)
  380. ev->set_button_index(BUTTON_WHEEL_LEFT);
  381. else if (p_event->deltaX < 0)
  382. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  383. else
  384. return false;
  385. // Different browsers give wildly different delta values, and we can't
  386. // interpret deltaMode, so use default value for wheel events' factor.
  387. ev->set_pressed(true);
  388. input->parse_input_event(ev);
  389. ev->set_pressed(false);
  390. input->parse_input_event(ev);
  391. return true;
  392. }
  393. // Touch
  394. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  395. /* clang-format off */
  396. return EM_ASM_INT_V(
  397. return 'ontouchstart' in window;
  398. );
  399. /* clang-format on */
  400. }
  401. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  402. OS_JavaScript *os = get_singleton();
  403. Ref<InputEventScreenTouch> ev;
  404. ev.instance();
  405. int lowest_id_index = -1;
  406. for (int i = 0; i < p_event->numTouches; ++i) {
  407. const EmscriptenTouchPoint &touch = p_event->touches[i];
  408. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  409. lowest_id_index = i;
  410. if (!touch.isChanged)
  411. continue;
  412. ev->set_index(touch.identifier);
  413. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  414. os->touches[i] = ev->get_position();
  415. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  416. os->input->parse_input_event(ev);
  417. }
  418. return true;
  419. }
  420. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  421. OS_JavaScript *os = get_singleton();
  422. Ref<InputEventScreenDrag> ev;
  423. ev.instance();
  424. int lowest_id_index = -1;
  425. for (int i = 0; i < p_event->numTouches; ++i) {
  426. const EmscriptenTouchPoint &touch = p_event->touches[i];
  427. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  428. lowest_id_index = i;
  429. if (!touch.isChanged)
  430. continue;
  431. ev->set_index(touch.identifier);
  432. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  433. Point2 &prev = os->touches[i];
  434. ev->set_relative(ev->get_position() - prev);
  435. prev = ev->get_position();
  436. os->input->parse_input_event(ev);
  437. }
  438. return true;
  439. }
  440. // Gamepad
  441. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  442. InputDefault *input = get_singleton()->input;
  443. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  444. String guid = "";
  445. if (String::utf8(p_event->mapping) == "standard")
  446. guid = "Default HTML5 Gamepad";
  447. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  448. } else {
  449. input->joy_connection_changed(p_event->index, false, "");
  450. }
  451. return true;
  452. }
  453. void OS_JavaScript::process_joypads() {
  454. int joypad_count = emscripten_get_num_gamepads();
  455. for (int joypad = 0; joypad < joypad_count; joypad++) {
  456. EmscriptenGamepadEvent state;
  457. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  458. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  459. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  460. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  461. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  462. int button_count = MIN(state.numButtons, 18);
  463. int axis_count = MIN(state.numAxes, 8);
  464. for (int button = 0; button < button_count; button++) {
  465. float value = state.analogButton[button];
  466. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  467. InputDefault::JoyAxis joy_axis;
  468. joy_axis.min = 0;
  469. joy_axis.value = value;
  470. input->joy_axis(joypad, button, joy_axis);
  471. } else {
  472. input->joy_button(joypad, button, value);
  473. }
  474. }
  475. for (int axis = 0; axis < axis_count; axis++) {
  476. InputDefault::JoyAxis joy_axis;
  477. joy_axis.min = -1;
  478. joy_axis.value = state.axis[axis];
  479. input->joy_axis(joypad, axis, joy_axis);
  480. }
  481. }
  482. }
  483. }
  484. bool OS_JavaScript::is_joy_known(int p_device) {
  485. return input->is_joy_mapped(p_device);
  486. }
  487. String OS_JavaScript::get_joy_guid(int p_device) const {
  488. return input->get_joy_guid_remapped(p_device);
  489. }
  490. // Video
  491. int OS_JavaScript::get_video_driver_count() const {
  492. return VIDEO_DRIVER_MAX;
  493. }
  494. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  495. switch (p_driver) {
  496. case VIDEO_DRIVER_GLES3:
  497. return "GLES3";
  498. case VIDEO_DRIVER_GLES2:
  499. return "GLES2";
  500. }
  501. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  502. ERR_FAIL_V(NULL);
  503. }
  504. // Audio
  505. int OS_JavaScript::get_audio_driver_count() const {
  506. return 1;
  507. }
  508. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  509. return "JavaScript";
  510. }
  511. // Lifecycle
  512. int OS_JavaScript::get_current_video_driver() const {
  513. return video_driver_index;
  514. }
  515. void OS_JavaScript::initialize_core() {
  516. OS_Unix::initialize_core();
  517. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  518. }
  519. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  520. EmscriptenWebGLContextAttributes attributes;
  521. emscripten_webgl_init_context_attributes(&attributes);
  522. attributes.alpha = false;
  523. attributes.antialias = false;
  524. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  525. bool gles3 = true;
  526. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  527. gles3 = false;
  528. }
  529. bool gl_initialization_error = false;
  530. while (true) {
  531. if (gles3) {
  532. if (RasterizerGLES3::is_viable() == OK) {
  533. attributes.majorVersion = 2;
  534. RasterizerGLES3::register_config();
  535. RasterizerGLES3::make_current();
  536. break;
  537. } else {
  538. if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") {
  539. p_video_driver = VIDEO_DRIVER_GLES2;
  540. gles3 = false;
  541. continue;
  542. } else {
  543. gl_initialization_error = true;
  544. break;
  545. }
  546. }
  547. } else {
  548. if (RasterizerGLES2::is_viable() == OK) {
  549. attributes.majorVersion = 1;
  550. RasterizerGLES2::register_config();
  551. RasterizerGLES2::make_current();
  552. break;
  553. } else {
  554. gl_initialization_error = true;
  555. break;
  556. }
  557. }
  558. }
  559. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  560. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  561. gl_initialization_error = true;
  562. }
  563. if (gl_initialization_error) {
  564. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  565. "Please update your browser version.",
  566. "Unable to initialize Video driver");
  567. return ERR_UNAVAILABLE;
  568. }
  569. video_driver_index = p_video_driver;
  570. video_mode = p_desired;
  571. // Can't fulfill fullscreen request during start-up due to browser security.
  572. video_mode.fullscreen = false;
  573. /* clang-format off */
  574. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  575. /* clang-format on */
  576. set_window_size(Size2(video_mode.width, video_mode.height));
  577. } else {
  578. set_window_size(get_window_size());
  579. }
  580. char locale_ptr[16];
  581. /* clang-format off */
  582. EM_ASM_ARGS({
  583. stringToUTF8(Module.locale, $0, 16);
  584. }, locale_ptr);
  585. /* clang-format on */
  586. setenv("LANG", locale_ptr, true);
  587. AudioDriverManager::initialize(p_audio_driver);
  588. VisualServer *visual_server = memnew(VisualServerRaster());
  589. input = memnew(InputDefault);
  590. EMSCRIPTEN_RESULT result;
  591. #define EM_CHECK(ev) \
  592. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  593. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  594. #define SET_EM_CALLBACK(target, ev, cb) \
  595. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  596. EM_CHECK(ev)
  597. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  598. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  599. EM_CHECK(ev)
  600. // These callbacks from Emscripten's html5.h suffice to access most
  601. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  602. // is used below.
  603. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  604. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  605. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  606. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  607. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  608. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  609. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  610. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  611. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  612. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  613. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  614. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  615. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  616. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  617. #undef SET_EM_CALLBACK_NODATA
  618. #undef SET_EM_CALLBACK
  619. #undef EM_CHECK
  620. /* clang-format off */
  621. EM_ASM_ARGS({
  622. const send_notification = cwrap('send_notification', null, ['number']);
  623. const notifications = arguments;
  624. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  625. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  626. });
  627. },
  628. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  629. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  630. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  631. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  632. );
  633. /* clang-format on */
  634. visual_server->init();
  635. return OK;
  636. }
  637. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  638. main_loop = p_main_loop;
  639. input->set_main_loop(p_main_loop);
  640. }
  641. MainLoop *OS_JavaScript::get_main_loop() const {
  642. return main_loop;
  643. }
  644. void OS_JavaScript::run_async() {
  645. main_loop->init();
  646. emscripten_set_main_loop(main_loop_callback, -1, false);
  647. }
  648. void OS_JavaScript::main_loop_callback() {
  649. get_singleton()->main_loop_iterate();
  650. }
  651. bool OS_JavaScript::main_loop_iterate() {
  652. if (is_userfs_persistent() && sync_wait_time >= 0) {
  653. int64_t current_time = get_ticks_msec();
  654. int64_t elapsed_time = current_time - last_sync_check_time;
  655. last_sync_check_time = current_time;
  656. sync_wait_time -= elapsed_time;
  657. if (sync_wait_time < 0) {
  658. /* clang-format off */
  659. EM_ASM(
  660. FS.syncfs(function(err) {
  661. if (err) { console.warn('Failed to save IDB file system: ' + err.message); }
  662. });
  663. );
  664. /* clang-format on */
  665. }
  666. }
  667. process_joypads();
  668. if (just_exited_fullscreen) {
  669. if (window_maximized) {
  670. EmscriptenFullscreenStrategy strategy;
  671. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  672. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  673. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  674. strategy.canvasResizedCallback = NULL;
  675. emscripten_enter_soft_fullscreen(NULL, &strategy);
  676. } else {
  677. emscripten_set_canvas_size(windowed_size.width, windowed_size.height);
  678. }
  679. just_exited_fullscreen = false;
  680. }
  681. int canvas[3];
  682. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  683. video_mode.width = canvas[0];
  684. video_mode.height = canvas[1];
  685. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  686. windowed_size.width = canvas[0];
  687. windowed_size.height = canvas[1];
  688. }
  689. return Main::iteration();
  690. }
  691. void OS_JavaScript::delete_main_loop() {
  692. memdelete(main_loop);
  693. }
  694. void OS_JavaScript::finalize() {
  695. memdelete(input);
  696. }
  697. // Miscellaneous
  698. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  699. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  700. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  701. }
  702. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  703. }
  704. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  705. if (p_feature == "HTML5" || p_feature == "web")
  706. return true;
  707. #ifdef JAVASCRIPT_EVAL_ENABLED
  708. if (p_feature == "JavaScript")
  709. return true;
  710. #endif
  711. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  712. // All extensions are already automatically enabled, this function allows
  713. // checking WebGL extension support without inline JavaScript
  714. if (p_feature == "s3tc")
  715. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb");
  716. if (p_feature == "etc")
  717. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1");
  718. if (p_feature == "etc2")
  719. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc");
  720. return false;
  721. }
  722. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  723. /* clang-format off */
  724. EM_ASM_({
  725. window.alert(UTF8ToString($0));
  726. }, p_alert.utf8().get_data());
  727. /* clang-format on */
  728. }
  729. void OS_JavaScript::set_window_title(const String &p_title) {
  730. /* clang-format off */
  731. EM_ASM_({
  732. document.title = UTF8ToString($0);
  733. }, p_title.utf8().get_data());
  734. /* clang-format on */
  735. }
  736. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  737. ERR_FAIL_COND(p_icon.is_null());
  738. Ref<Image> icon = p_icon;
  739. if (icon->is_compressed()) {
  740. icon = icon->duplicate();
  741. ERR_FAIL_COND(icon->decompress() != OK)
  742. }
  743. if (icon->get_format() != Image::FORMAT_RGBA8) {
  744. if (icon == p_icon)
  745. icon = icon->duplicate();
  746. icon->convert(Image::FORMAT_RGBA8);
  747. }
  748. png_image png_meta;
  749. memset(&png_meta, 0, sizeof png_meta);
  750. png_meta.version = PNG_IMAGE_VERSION;
  751. png_meta.width = icon->get_width();
  752. png_meta.height = icon->get_height();
  753. png_meta.format = PNG_FORMAT_RGBA;
  754. PoolByteArray png;
  755. size_t len;
  756. PoolByteArray::Read r = icon->get_data().read();
  757. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  758. png.resize(len);
  759. PoolByteArray::Write w = png.write();
  760. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  761. w = PoolByteArray::Write();
  762. r = png.read();
  763. /* clang-format off */
  764. EM_ASM_ARGS({
  765. var PNG_PTR = $0;
  766. var PNG_LEN = $1;
  767. var png = new Blob([HEAPU8.slice(PNG_PTR, PNG_PTR + PNG_LEN)], { type: "image/png" });
  768. var url = URL.createObjectURL(png);
  769. var link = document.getElementById('-gd-engine-icon');
  770. if (link === null) {
  771. link = document.createElement('link');
  772. link.rel = 'icon';
  773. link.id = '-gd-engine-icon';
  774. document.head.appendChild(link);
  775. }
  776. link.href = url;
  777. }, r.ptr(), len);
  778. /* clang-format on */
  779. }
  780. String OS_JavaScript::get_executable_path() const {
  781. return OS::get_executable_path();
  782. }
  783. Error OS_JavaScript::shell_open(String p_uri) {
  784. // Open URI in a new tab, browser will deal with it by protocol.
  785. /* clang-format off */
  786. EM_ASM_({
  787. window.open(UTF8ToString($0), '_blank');
  788. }, p_uri.utf8().get_data());
  789. /* clang-format on */
  790. return OK;
  791. }
  792. String OS_JavaScript::get_name() {
  793. return "HTML5";
  794. }
  795. bool OS_JavaScript::can_draw() const {
  796. return true; // Always?
  797. }
  798. String OS_JavaScript::get_user_data_dir() const {
  799. return "/userfs";
  800. };
  801. String OS_JavaScript::get_resource_dir() const {
  802. return "/";
  803. }
  804. OS::PowerState OS_JavaScript::get_power_state() {
  805. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  806. return OS::POWERSTATE_UNKNOWN;
  807. }
  808. int OS_JavaScript::get_power_seconds_left() {
  809. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  810. return -1;
  811. }
  812. int OS_JavaScript::get_power_percent_left() {
  813. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  814. return -1;
  815. }
  816. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  817. OS_JavaScript *os = get_singleton();
  818. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  819. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  820. // Wait five seconds in case more files are about to be closed.
  821. os->sync_wait_time = 5000;
  822. }
  823. }
  824. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  825. idb_available = p_idb_available;
  826. }
  827. bool OS_JavaScript::is_userfs_persistent() const {
  828. return idb_available;
  829. }
  830. OS_JavaScript *OS_JavaScript::get_singleton() {
  831. return static_cast<OS_JavaScript *>(OS::get_singleton());
  832. }
  833. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  834. List<String> arguments;
  835. for (int i = 1; i < p_argc; i++) {
  836. arguments.push_back(String::utf8(p_argv[i]));
  837. }
  838. set_cmdline(p_argv[0], arguments);
  839. window_maximized = false;
  840. entering_fullscreen = false;
  841. just_exited_fullscreen = false;
  842. main_loop = NULL;
  843. idb_available = false;
  844. sync_wait_time = -1;
  845. AudioDriverManager::add_driver(&audio_driver_javascript);
  846. Vector<Logger *> loggers;
  847. loggers.push_back(memnew(StdLogger));
  848. _set_logger(memnew(CompositeLogger(loggers)));
  849. FileAccessUnix::close_notification_func = file_access_close_callback;
  850. }