os_javascript.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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/json.h"
  32. #include "drivers/gles2/rasterizer_gles2.h"
  33. #include "drivers/gles3/rasterizer_gles3.h"
  34. #include "drivers/unix/dir_access_unix.h"
  35. #include "drivers/unix/file_access_unix.h"
  36. #include "main/main.h"
  37. #include "servers/visual/visual_server_raster.h"
  38. #ifndef NO_THREADS
  39. #include "servers/visual/visual_server_wrap_mt.h"
  40. #endif
  41. #include <dlfcn.h>
  42. #include <emscripten.h>
  43. #include <png.h>
  44. #include <stdlib.h>
  45. #include "dom_keys.inc"
  46. #include "godot_js.h"
  47. #define DOM_BUTTON_LEFT 0
  48. #define DOM_BUTTON_MIDDLE 1
  49. #define DOM_BUTTON_RIGHT 2
  50. #define DOM_BUTTON_XBUTTON1 3
  51. #define DOM_BUTTON_XBUTTON2 4
  52. // Quit
  53. void OS_JavaScript::request_quit_callback() {
  54. OS_JavaScript *os = get_singleton();
  55. if (os && os->get_main_loop()) {
  56. os->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  57. }
  58. }
  59. // Files drop (implemented in JS for now).
  60. void OS_JavaScript::drop_files_callback(char **p_filev, int p_filec) {
  61. OS_JavaScript *os = get_singleton();
  62. if (!os || !os->get_main_loop()) {
  63. return;
  64. }
  65. Vector<String> files;
  66. for (int i = 0; i < p_filec; i++) {
  67. files.push_back(String::utf8(p_filev[i]));
  68. }
  69. os->get_main_loop()->drop_files(files);
  70. }
  71. void OS_JavaScript::send_notification_callback(int p_notification) {
  72. OS_JavaScript *os = get_singleton();
  73. if (!os) {
  74. return;
  75. }
  76. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  77. os->cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  78. }
  79. MainLoop *loop = os->get_main_loop();
  80. if (loop) {
  81. loop->notification(p_notification);
  82. }
  83. }
  84. // Window (canvas)
  85. bool OS_JavaScript::check_size_force_redraw() {
  86. return godot_js_display_size_update() != 0;
  87. }
  88. void OS_JavaScript::fullscreen_change_callback(int p_fullscreen) {
  89. OS_JavaScript *os = get_singleton();
  90. os->video_mode.fullscreen = p_fullscreen;
  91. }
  92. void OS_JavaScript::window_blur_callback() {
  93. get_singleton()->input->release_pressed_events();
  94. }
  95. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  96. video_mode = p_video_mode;
  97. }
  98. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  99. return video_mode;
  100. }
  101. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  102. int size[2];
  103. godot_js_display_screen_size_get(size, size + 1);
  104. return Size2(size[0], size[1]);
  105. }
  106. void OS_JavaScript::set_window_size(const Size2 p_size) {
  107. if (video_mode.fullscreen) {
  108. set_window_fullscreen(false);
  109. }
  110. godot_js_display_desired_size_set(p_size.x, p_size.y);
  111. }
  112. Size2 OS_JavaScript::get_window_size() const {
  113. int size[2];
  114. godot_js_display_window_size_get(size, size + 1);
  115. return Size2(size[0], size[1]);
  116. }
  117. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  118. WARN_PRINT_ONCE("Maximizing windows is not supported for the HTML5 platform.");
  119. }
  120. bool OS_JavaScript::is_window_maximized() const {
  121. return false;
  122. }
  123. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  124. if (p_enabled == video_mode.fullscreen) {
  125. return;
  126. }
  127. // Just request changes here, if successful, logic continues in
  128. // fullscreen_change_callback.
  129. if (p_enabled) {
  130. int result = godot_js_display_fullscreen_request();
  131. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the HTML5 platform.");
  132. } else {
  133. // No logic allowed here, since exiting w/ ESC key won't use this function.
  134. ERR_FAIL_COND(godot_js_display_fullscreen_exit());
  135. }
  136. }
  137. bool OS_JavaScript::is_window_fullscreen() const {
  138. return video_mode.fullscreen;
  139. }
  140. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  141. Size2 screen = get_screen_size();
  142. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  143. }
  144. bool OS_JavaScript::get_window_per_pixel_transparency_enabled() const {
  145. if (!is_layered_allowed()) {
  146. return false;
  147. }
  148. return transparency_enabled;
  149. }
  150. void OS_JavaScript::set_window_per_pixel_transparency_enabled(bool p_enabled) {
  151. if (!is_layered_allowed()) {
  152. return;
  153. }
  154. transparency_enabled = p_enabled;
  155. }
  156. // Keys
  157. static void dom2godot_mod(Ref<InputEventWithModifiers> ev, int p_mod) {
  158. ev->set_shift(p_mod & 1);
  159. ev->set_alt(p_mod & 2);
  160. ev->set_control(p_mod & 4);
  161. ev->set_metakey(p_mod & 8);
  162. }
  163. void OS_JavaScript::key_callback(int p_pressed, int p_repeat, int p_modifiers) {
  164. OS_JavaScript *os = get_singleton();
  165. JSKeyEvent &key_event = os->key_event;
  166. // Resume audio context after input in case autoplay was denied.
  167. os->resume_audio();
  168. Ref<InputEventKey> ev;
  169. ev.instance();
  170. ev->set_echo(p_repeat);
  171. ev->set_scancode(dom_code2godot_scancode(key_event.code, key_event.key, false));
  172. ev->set_physical_scancode(dom_code2godot_scancode(key_event.code, key_event.key, true));
  173. ev->set_pressed(p_pressed);
  174. dom2godot_mod(ev, p_modifiers);
  175. String unicode = String::utf8(key_event.key);
  176. if (unicode.length() == 1) {
  177. ev->set_unicode(unicode[0]);
  178. }
  179. os->input->parse_input_event(ev);
  180. // Make sure to flush all events so we can call restricted APIs inside the event.
  181. os->input->flush_buffered_events();
  182. }
  183. // Mouse
  184. Point2 OS_JavaScript::get_mouse_position() const {
  185. return input->get_mouse_position();
  186. }
  187. int OS_JavaScript::get_mouse_button_state() const {
  188. return input->get_mouse_button_mask();
  189. }
  190. int OS_JavaScript::mouse_button_callback(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers) {
  191. OS_JavaScript *os = get_singleton();
  192. Ref<InputEventMouseButton> ev;
  193. ev.instance();
  194. ev->set_pressed(p_pressed);
  195. ev->set_position(Point2(p_x, p_y));
  196. ev->set_global_position(ev->get_position());
  197. ev->set_pressed(p_pressed);
  198. dom2godot_mod(ev, p_modifiers);
  199. switch (p_button) {
  200. case DOM_BUTTON_LEFT:
  201. ev->set_button_index(BUTTON_LEFT);
  202. break;
  203. case DOM_BUTTON_MIDDLE:
  204. ev->set_button_index(BUTTON_MIDDLE);
  205. break;
  206. case DOM_BUTTON_RIGHT:
  207. ev->set_button_index(BUTTON_RIGHT);
  208. break;
  209. case DOM_BUTTON_XBUTTON1:
  210. ev->set_button_index(BUTTON_XBUTTON1);
  211. break;
  212. case DOM_BUTTON_XBUTTON2:
  213. ev->set_button_index(BUTTON_XBUTTON2);
  214. break;
  215. default:
  216. return false;
  217. }
  218. if (p_pressed) {
  219. uint64_t diff = (OS::get_singleton()->get_ticks_usec() / 1000) - os->last_click_ms;
  220. if (ev->get_button_index() == os->last_click_button_index) {
  221. if (diff < 400 && Point2(os->last_click_pos).distance_to(ev->get_position()) < 5) {
  222. os->last_click_ms = 0;
  223. os->last_click_pos = Point2(-100, -100);
  224. os->last_click_button_index = -1;
  225. ev->set_doubleclick(true);
  226. }
  227. } else {
  228. os->last_click_button_index = ev->get_button_index();
  229. }
  230. if (!ev->is_doubleclick()) {
  231. os->last_click_ms += diff;
  232. os->last_click_pos = ev->get_position();
  233. }
  234. }
  235. int mask = os->input->get_mouse_button_mask();
  236. int button_flag = 1 << (ev->get_button_index() - 1);
  237. if (ev->is_pressed()) {
  238. mask |= button_flag;
  239. } else if (mask & button_flag) {
  240. mask &= ~button_flag;
  241. } else {
  242. // Received release event, but press was outside the canvas, so ignore.
  243. return false;
  244. }
  245. ev->set_button_mask(mask);
  246. os->input->parse_input_event(ev);
  247. // Resume audio context after input in case autoplay was denied.
  248. os->resume_audio();
  249. // Make sure to flush all events so we can call restricted APIs inside the event.
  250. os->input->flush_buffered_events();
  251. // Prevent multi-click text selection and wheel-click scrolling anchor.
  252. // Context menu is prevented through contextmenu event.
  253. return true;
  254. }
  255. void OS_JavaScript::mouse_move_callback(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers) {
  256. OS_JavaScript *os = get_singleton();
  257. int input_mask = os->input->get_mouse_button_mask();
  258. // For motion outside the canvas, only read mouse movement if dragging
  259. // started inside the canvas; imitating desktop app behaviour.
  260. if (!os->cursor_inside_canvas && !input_mask)
  261. return;
  262. Ref<InputEventMouseMotion> ev;
  263. ev.instance();
  264. dom2godot_mod(ev, p_modifiers);
  265. ev->set_button_mask(input_mask);
  266. ev->set_position(Point2(p_x, p_y));
  267. ev->set_global_position(ev->get_position());
  268. ev->set_relative(Vector2(p_rel_x, p_rel_y));
  269. os->input->set_mouse_position(ev->get_position());
  270. ev->set_speed(os->input->get_last_mouse_speed());
  271. os->input->parse_input_event(ev);
  272. }
  273. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  274. switch (p_shape) {
  275. case OS::CURSOR_ARROW:
  276. default:
  277. return "auto";
  278. case OS::CURSOR_IBEAM:
  279. return "text";
  280. case OS::CURSOR_POINTING_HAND:
  281. return "pointer";
  282. case OS::CURSOR_CROSS:
  283. return "crosshair";
  284. case OS::CURSOR_WAIT:
  285. return "progress";
  286. case OS::CURSOR_BUSY:
  287. return "wait";
  288. case OS::CURSOR_DRAG:
  289. return "grab";
  290. case OS::CURSOR_CAN_DROP:
  291. return "grabbing";
  292. case OS::CURSOR_FORBIDDEN:
  293. return "no-drop";
  294. case OS::CURSOR_VSIZE:
  295. return "ns-resize";
  296. case OS::CURSOR_HSIZE:
  297. return "ew-resize";
  298. case OS::CURSOR_BDIAGSIZE:
  299. return "nesw-resize";
  300. case OS::CURSOR_FDIAGSIZE:
  301. return "nwse-resize";
  302. case OS::CURSOR_MOVE:
  303. return "move";
  304. case OS::CURSOR_VSPLIT:
  305. return "row-resize";
  306. case OS::CURSOR_HSPLIT:
  307. return "col-resize";
  308. case OS::CURSOR_HELP:
  309. return "help";
  310. }
  311. }
  312. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  313. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  314. if (cursor_shape == p_shape) {
  315. return;
  316. }
  317. cursor_shape = p_shape;
  318. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  319. }
  320. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  321. if (p_cursor.is_valid()) {
  322. Ref<Texture> texture = p_cursor;
  323. Ref<AtlasTexture> atlas_texture = p_cursor;
  324. Ref<Image> image;
  325. Size2 texture_size;
  326. Rect2 atlas_rect;
  327. if (texture.is_valid()) {
  328. image = texture->get_data();
  329. if (image.is_valid()) {
  330. image->duplicate();
  331. }
  332. }
  333. if (!image.is_valid() && atlas_texture.is_valid()) {
  334. texture = atlas_texture->get_atlas();
  335. atlas_rect.size.width = texture->get_width();
  336. atlas_rect.size.height = texture->get_height();
  337. atlas_rect.position.x = atlas_texture->get_region().position.x;
  338. atlas_rect.position.y = atlas_texture->get_region().position.y;
  339. texture_size.width = atlas_texture->get_region().size.x;
  340. texture_size.height = atlas_texture->get_region().size.y;
  341. } else if (image.is_valid()) {
  342. texture_size.width = texture->get_width();
  343. texture_size.height = texture->get_height();
  344. }
  345. ERR_FAIL_COND(!texture.is_valid());
  346. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  347. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  348. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  349. image = texture->get_data();
  350. ERR_FAIL_COND(!image.is_valid());
  351. image = image->duplicate();
  352. if (atlas_texture.is_valid())
  353. image->crop_from_point(
  354. atlas_rect.position.x,
  355. atlas_rect.position.y,
  356. texture_size.width,
  357. texture_size.height);
  358. if (image->get_format() != Image::FORMAT_RGBA8) {
  359. image->convert(Image::FORMAT_RGBA8);
  360. }
  361. png_image png_meta;
  362. memset(&png_meta, 0, sizeof png_meta);
  363. png_meta.version = PNG_IMAGE_VERSION;
  364. png_meta.width = texture_size.width;
  365. png_meta.height = texture_size.height;
  366. png_meta.format = PNG_FORMAT_RGBA;
  367. PoolByteArray png;
  368. size_t len;
  369. PoolByteArray::Read r = image->get_data().read();
  370. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  371. png.resize(len);
  372. PoolByteArray::Write w = png.write();
  373. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  374. w = PoolByteArray::Write();
  375. r = png.read();
  376. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), r.ptr(), len, p_hotspot.x, p_hotspot.y);
  377. r = PoolByteArray::Read();
  378. } else {
  379. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), NULL, 0, 0, 0);
  380. }
  381. }
  382. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  383. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED, "MOUSE_MODE_CONFINED is not supported for the HTML5 platform.");
  384. if (p_mode == get_mouse_mode())
  385. return;
  386. if (p_mode == MOUSE_MODE_VISIBLE) {
  387. godot_js_display_cursor_set_visible(1);
  388. godot_js_display_cursor_lock_set(false);
  389. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  390. godot_js_display_cursor_set_visible(0);
  391. godot_js_display_cursor_lock_set(false);
  392. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  393. godot_js_display_cursor_set_visible(1);
  394. godot_js_display_cursor_lock_set(true);
  395. }
  396. }
  397. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  398. if (godot_js_display_cursor_is_hidden()) {
  399. return MOUSE_MODE_HIDDEN;
  400. }
  401. if (godot_js_display_cursor_is_locked()) {
  402. return MOUSE_MODE_CAPTURED;
  403. }
  404. return MOUSE_MODE_VISIBLE;
  405. }
  406. // Wheel
  407. int OS_JavaScript::mouse_wheel_callback(double p_delta_x, double p_delta_y) {
  408. OS_JavaScript *os = get_singleton();
  409. if (!godot_js_display_canvas_is_focused()) {
  410. if (os->cursor_inside_canvas) {
  411. godot_js_display_canvas_focus();
  412. } else {
  413. return false;
  414. }
  415. }
  416. InputDefault *input = os->input;
  417. Ref<InputEventMouseButton> ev;
  418. ev.instance();
  419. ev->set_position(input->get_mouse_position());
  420. ev->set_global_position(ev->get_position());
  421. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  422. ev->set_alt(input->is_key_pressed(KEY_ALT));
  423. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  424. ev->set_metakey(input->is_key_pressed(KEY_META));
  425. if (p_delta_y < 0) {
  426. ev->set_button_index(BUTTON_WHEEL_UP);
  427. } else if (p_delta_y > 0) {
  428. ev->set_button_index(BUTTON_WHEEL_DOWN);
  429. } else if (p_delta_x > 0) {
  430. ev->set_button_index(BUTTON_WHEEL_LEFT);
  431. } else if (p_delta_x < 0) {
  432. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  433. } else {
  434. return false;
  435. }
  436. // Different browsers give wildly different delta values, and we can't
  437. // interpret deltaMode, so use default value for wheel events' factor.
  438. int button_flag = 1 << (ev->get_button_index() - 1);
  439. ev->set_pressed(true);
  440. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  441. input->parse_input_event(ev);
  442. Ref<InputEventMouseButton> release = ev->duplicate();
  443. release->set_pressed(false);
  444. release->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  445. input->parse_input_event(release);
  446. return true;
  447. }
  448. // Touch
  449. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  450. return godot_js_display_touchscreen_is_available();
  451. }
  452. void OS_JavaScript::touch_callback(int p_type, int p_count) {
  453. OS_JavaScript *os = get_singleton();
  454. // Resume audio context after input in case autoplay was denied.
  455. os->resume_audio();
  456. const JSTouchEvent &touch_event = os->touch_event;
  457. for (int i = 0; i < p_count; i++) {
  458. Point2 point(touch_event.coords[i * 2], touch_event.coords[i * 2 + 1]);
  459. if (p_type == 2) {
  460. // touchmove
  461. Ref<InputEventScreenDrag> ev;
  462. ev.instance();
  463. ev->set_index(touch_event.identifier[i]);
  464. ev->set_position(point);
  465. Point2 &prev = os->touches[i];
  466. ev->set_relative(ev->get_position() - prev);
  467. prev = ev->get_position();
  468. os->input->parse_input_event(ev);
  469. } else {
  470. // touchstart/touchend
  471. Ref<InputEventScreenTouch> ev;
  472. ev.instance();
  473. ev->set_index(touch_event.identifier[i]);
  474. ev->set_position(point);
  475. ev->set_pressed(p_type == 0);
  476. os->touches[i] = point;
  477. os->input->parse_input_event(ev);
  478. // Make sure to flush all events so we can call restricted APIs inside the event.
  479. os->input->flush_buffered_events();
  480. }
  481. }
  482. }
  483. // Gamepad
  484. void OS_JavaScript::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  485. InputDefault *input = get_singleton()->input;
  486. if (p_connected) {
  487. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  488. } else {
  489. input->joy_connection_changed(p_index, false, "");
  490. }
  491. }
  492. void OS_JavaScript::process_joypads() {
  493. int32_t pads = godot_js_input_gamepad_sample_count();
  494. int32_t s_btns_num = 0;
  495. int32_t s_axes_num = 0;
  496. int32_t s_standard = 0;
  497. float s_btns[16];
  498. float s_axes[10];
  499. for (int idx = 0; idx < pads; idx++) {
  500. int err = godot_js_input_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  501. if (err) {
  502. continue;
  503. }
  504. for (int b = 0; b < s_btns_num; b++) {
  505. float value = s_btns[b];
  506. // Buttons 6 and 7 in the standard mapping need to be
  507. // axis to be handled as JOY_ANALOG by Godot.
  508. if (s_standard && (b == 6 || b == 7)) {
  509. InputDefault::JoyAxis joy_axis;
  510. joy_axis.min = 0;
  511. joy_axis.value = value;
  512. int a = b == 6 ? JOY_ANALOG_L2 : JOY_ANALOG_R2;
  513. input->joy_axis(idx, a, joy_axis);
  514. } else {
  515. input->joy_button(idx, b, value);
  516. }
  517. }
  518. for (int a = 0; a < s_axes_num; a++) {
  519. InputDefault::JoyAxis joy_axis;
  520. joy_axis.min = -1;
  521. joy_axis.value = s_axes[a];
  522. input->joy_axis(idx, a, joy_axis);
  523. }
  524. }
  525. }
  526. bool OS_JavaScript::is_joy_known(int p_device) {
  527. return input->is_joy_mapped(p_device);
  528. }
  529. String OS_JavaScript::get_joy_guid(int p_device) const {
  530. return input->get_joy_guid_remapped(p_device);
  531. }
  532. // Video
  533. int OS_JavaScript::get_video_driver_count() const {
  534. return VIDEO_DRIVER_MAX;
  535. }
  536. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  537. switch (p_driver) {
  538. case VIDEO_DRIVER_GLES3:
  539. return "GLES3";
  540. case VIDEO_DRIVER_GLES2:
  541. return "GLES2";
  542. }
  543. ERR_FAIL_V_MSG(NULL, "Invalid video driver index: " + itos(p_driver) + ".");
  544. }
  545. // Audio
  546. int OS_JavaScript::get_audio_driver_count() const {
  547. return audio_drivers.size();
  548. }
  549. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  550. if (audio_drivers.size() <= p_driver) {
  551. return "Unknown";
  552. }
  553. return audio_drivers[p_driver]->get_name();
  554. }
  555. // Clipboard
  556. void OS_JavaScript::update_clipboard_callback(const char *p_text) {
  557. // Only call set_clipboard from OS (sets local clipboard)
  558. get_singleton()->OS::set_clipboard(String::utf8(p_text));
  559. }
  560. void OS_JavaScript::set_clipboard(const String &p_text) {
  561. OS::set_clipboard(p_text);
  562. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  563. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  564. }
  565. String OS_JavaScript::get_clipboard() const {
  566. godot_js_display_clipboard_get(update_clipboard_callback);
  567. return this->OS::get_clipboard();
  568. }
  569. // Lifecycle
  570. int OS_JavaScript::get_current_video_driver() const {
  571. return video_driver_index;
  572. }
  573. void OS_JavaScript::initialize_core() {
  574. OS_Unix::initialize_core();
  575. }
  576. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  577. video_mode = p_desired;
  578. // fullscreen_change_callback will correct this if the request is successful.
  579. video_mode.fullscreen = false;
  580. // Handle contextmenu, webglcontextlost, initial canvas setup.
  581. godot_js_display_setup_canvas(video_mode.width, video_mode.height, video_mode.fullscreen, is_hidpi_allowed() ? 1 : 0);
  582. swap_ok_cancel = godot_js_display_is_swap_ok_cancel() == 1;
  583. EmscriptenWebGLContextAttributes attributes;
  584. emscripten_webgl_init_context_attributes(&attributes);
  585. attributes.alpha = GLOBAL_GET("display/window/per_pixel_transparency/allowed");
  586. attributes.antialias = false;
  587. attributes.explicitSwapControl = true;
  588. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  589. if (p_desired.layered) {
  590. set_window_per_pixel_transparency_enabled(true);
  591. }
  592. bool gles3 = true;
  593. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  594. gles3 = false;
  595. }
  596. bool gl_initialization_error = false;
  597. while (true) {
  598. if (gles3) {
  599. if (godot_js_display_has_webgl(2) && RasterizerGLES3::is_viable() == OK) {
  600. attributes.majorVersion = 2;
  601. RasterizerGLES3::register_config();
  602. RasterizerGLES3::make_current();
  603. break;
  604. } else {
  605. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  606. p_video_driver = VIDEO_DRIVER_GLES2;
  607. gles3 = false;
  608. continue;
  609. } else {
  610. gl_initialization_error = true;
  611. break;
  612. }
  613. }
  614. } else {
  615. if (godot_js_display_has_webgl(1) && RasterizerGLES2::is_viable() == OK) {
  616. attributes.majorVersion = 1;
  617. RasterizerGLES2::register_config();
  618. RasterizerGLES2::make_current();
  619. break;
  620. } else {
  621. gl_initialization_error = true;
  622. break;
  623. }
  624. }
  625. }
  626. webgl_ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  627. if (emscripten_webgl_make_context_current(webgl_ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  628. gl_initialization_error = true;
  629. }
  630. if (gl_initialization_error) {
  631. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  632. "Please update your browser version.",
  633. "Unable to initialize Video driver");
  634. return ERR_UNAVAILABLE;
  635. }
  636. video_driver_index = p_video_driver;
  637. AudioDriverManager::initialize(p_audio_driver);
  638. visual_server = memnew(VisualServerRaster());
  639. #ifndef NO_THREADS
  640. visual_server = memnew(VisualServerWrapMT(visual_server, false));
  641. #endif
  642. input = memnew(InputDefault);
  643. // JS Input interface (js/libs/library_godot_input.js)
  644. godot_js_input_mouse_button_cb(&OS_JavaScript::mouse_button_callback);
  645. godot_js_input_mouse_move_cb(&OS_JavaScript::mouse_move_callback);
  646. godot_js_input_mouse_wheel_cb(&OS_JavaScript::mouse_wheel_callback);
  647. godot_js_input_touch_cb(&OS_JavaScript::touch_callback, touch_event.identifier, touch_event.coords);
  648. godot_js_input_key_cb(&OS_JavaScript::key_callback, key_event.code, key_event.key);
  649. godot_js_input_gamepad_cb(&OS_JavaScript::gamepad_callback);
  650. godot_js_input_paste_cb(&OS_JavaScript::update_clipboard_callback);
  651. godot_js_input_drop_files_cb(&OS_JavaScript::drop_files_callback);
  652. // JS Display interface (js/libs/library_godot_display.js)
  653. godot_js_display_fullscreen_cb(&OS_JavaScript::fullscreen_change_callback);
  654. godot_js_display_window_blur_cb(&window_blur_callback);
  655. godot_js_display_notification_cb(&OS_JavaScript::send_notification_callback,
  656. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  657. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  658. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  659. MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  660. godot_js_display_vk_cb(&input_text_callback);
  661. visual_server->init();
  662. return OK;
  663. }
  664. void OS_JavaScript::input_text_callback(const char *p_text, int p_cursor) {
  665. OS_JavaScript *os = OS_JavaScript::get_singleton();
  666. if (!os || !os->get_main_loop()) {
  667. return;
  668. }
  669. os->get_main_loop()->input_text(String::utf8(p_text));
  670. Ref<InputEventKey> k;
  671. for (int i = 0; i < p_cursor; i++) {
  672. k.instance();
  673. k->set_pressed(true);
  674. k->set_echo(false);
  675. k->set_scancode(KEY_RIGHT);
  676. os->input->parse_input_event(k);
  677. k.instance();
  678. k->set_pressed(false);
  679. k->set_echo(false);
  680. k->set_scancode(KEY_RIGHT);
  681. os->input->parse_input_event(k);
  682. }
  683. }
  684. bool OS_JavaScript::has_virtual_keyboard() const {
  685. return godot_js_display_vk_available() != 0;
  686. }
  687. void OS_JavaScript::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, bool p_multiline, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  688. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_multiline, p_cursor_start, p_cursor_end);
  689. }
  690. void OS_JavaScript::hide_virtual_keyboard() {
  691. godot_js_display_vk_hide();
  692. }
  693. bool OS_JavaScript::get_swap_ok_cancel() {
  694. return swap_ok_cancel;
  695. }
  696. void OS_JavaScript::swap_buffers() {
  697. emscripten_webgl_commit_frame();
  698. }
  699. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  700. main_loop = p_main_loop;
  701. input->set_main_loop(p_main_loop);
  702. }
  703. MainLoop *OS_JavaScript::get_main_loop() const {
  704. return main_loop;
  705. }
  706. void OS_JavaScript::resume_audio() {
  707. AudioDriverJavaScript::resume();
  708. }
  709. void OS_JavaScript::fs_sync_callback() {
  710. get_singleton()->idb_is_syncing = false;
  711. }
  712. bool OS_JavaScript::main_loop_iterate() {
  713. if (is_userfs_persistent() && idb_needs_sync && !idb_is_syncing) {
  714. idb_is_syncing = true;
  715. idb_needs_sync = false;
  716. godot_js_os_fs_sync(&OS_JavaScript::fs_sync_callback);
  717. }
  718. input->flush_buffered_events();
  719. if (godot_js_input_gamepad_sample() == OK) {
  720. process_joypads();
  721. }
  722. return Main::iteration();
  723. }
  724. int OS_JavaScript::get_screen_dpi(int p_screen) const {
  725. return godot_js_display_screen_dpi_get();
  726. }
  727. float OS_JavaScript::get_screen_scale(int p_screen) const {
  728. return godot_js_display_pixel_ratio_get();
  729. }
  730. float OS_JavaScript::get_screen_max_scale() const {
  731. return get_screen_scale();
  732. }
  733. void OS_JavaScript::delete_main_loop() {
  734. memdelete(main_loop);
  735. main_loop = NULL;
  736. }
  737. void OS_JavaScript::finalize() {
  738. memdelete(input);
  739. visual_server->finish();
  740. emscripten_webgl_commit_frame();
  741. memdelete(visual_server);
  742. emscripten_webgl_destroy_context(webgl_ctx);
  743. for (int i = 0; i < audio_drivers.size(); i++) {
  744. memdelete(audio_drivers[i]);
  745. }
  746. audio_drivers.clear();
  747. }
  748. // Miscellaneous
  749. Error OS_JavaScript::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode, bool read_stderr, Mutex *p_pipe_mutex) {
  750. Array args;
  751. for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
  752. args.push_back(E->get());
  753. }
  754. String json_args = JSON::print(args);
  755. int failed = godot_js_os_execute(json_args.utf8().get_data());
  756. ERR_FAIL_COND_V_MSG(failed, ERR_UNAVAILABLE, "OS::execute() must be implemented in Javascript via 'engine.setOnExecute' if required.");
  757. return OK;
  758. }
  759. Error OS_JavaScript::kill(const ProcessID &p_pid) {
  760. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "OS::kill() is not available on the HTML5 platform.");
  761. }
  762. int OS_JavaScript::get_process_id() const {
  763. ERR_FAIL_V_MSG(0, "OS::get_process_id() is not available on the HTML5 platform.");
  764. }
  765. int OS_JavaScript::get_processor_count() const {
  766. return godot_js_os_hw_concurrency_get();
  767. }
  768. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  769. if (p_feature == "HTML5" || p_feature == "web") {
  770. return true;
  771. }
  772. #ifdef JAVASCRIPT_EVAL_ENABLED
  773. if (p_feature == "JavaScript") {
  774. return true;
  775. }
  776. #endif
  777. #ifndef NO_THREADS
  778. if (p_feature == "threads") {
  779. return true;
  780. }
  781. #endif
  782. #if WASM_GDNATIVE
  783. if (p_feature == "wasm32") {
  784. return true;
  785. }
  786. #endif
  787. return false;
  788. }
  789. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  790. godot_js_display_alert(p_alert.utf8().get_data());
  791. }
  792. void OS_JavaScript::set_window_title(const String &p_title) {
  793. godot_js_display_window_title_set(p_title.utf8().get_data());
  794. }
  795. void OS_JavaScript::set_icon(const Ref<Image> &p_icon) {
  796. ERR_FAIL_COND(p_icon.is_null());
  797. Ref<Image> icon = p_icon;
  798. if (icon->is_compressed()) {
  799. icon = icon->duplicate();
  800. ERR_FAIL_COND(icon->decompress() != OK);
  801. }
  802. if (icon->get_format() != Image::FORMAT_RGBA8) {
  803. if (icon == p_icon)
  804. icon = icon->duplicate();
  805. icon->convert(Image::FORMAT_RGBA8);
  806. }
  807. png_image png_meta;
  808. memset(&png_meta, 0, sizeof png_meta);
  809. png_meta.version = PNG_IMAGE_VERSION;
  810. png_meta.width = icon->get_width();
  811. png_meta.height = icon->get_height();
  812. png_meta.format = PNG_FORMAT_RGBA;
  813. PoolByteArray png;
  814. size_t len;
  815. PoolByteArray::Read r = icon->get_data().read();
  816. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, r.ptr(), 0, NULL));
  817. png.resize(len);
  818. PoolByteArray::Write w = png.write();
  819. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, w.ptr(), &len, 0, r.ptr(), 0, NULL));
  820. w = PoolByteArray::Write();
  821. r = png.read();
  822. godot_js_display_window_icon_set(r.ptr(), len);
  823. }
  824. String OS_JavaScript::get_executable_path() const {
  825. return OS::get_executable_path();
  826. }
  827. Error OS_JavaScript::shell_open(String p_uri) {
  828. // Open URI in a new tab, browser will deal with it by protocol.
  829. godot_js_os_shell_open(p_uri.utf8().get_data());
  830. return OK;
  831. }
  832. String OS_JavaScript::get_name() const {
  833. return "HTML5";
  834. }
  835. bool OS_JavaScript::can_draw() const {
  836. return true; // Always?
  837. }
  838. String OS_JavaScript::get_user_data_dir() const {
  839. return "/userfs";
  840. };
  841. String OS_JavaScript::get_cache_path() const {
  842. return "/home/web_user/.cache";
  843. }
  844. String OS_JavaScript::get_config_path() const {
  845. return "/home/web_user/.config";
  846. }
  847. String OS_JavaScript::get_data_path() const {
  848. return "/home/web_user/.local/share";
  849. }
  850. OS::PowerState OS_JavaScript::get_power_state() {
  851. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  852. return OS::POWERSTATE_UNKNOWN;
  853. }
  854. int OS_JavaScript::get_power_seconds_left() {
  855. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  856. return -1;
  857. }
  858. int OS_JavaScript::get_power_percent_left() {
  859. WARN_PRINT_ONCE("Power management is not supported for the HTML5 platform, defaulting to -1");
  860. return -1;
  861. }
  862. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  863. OS_JavaScript *os = get_singleton();
  864. if (!(os->is_userfs_persistent() && p_flags & FileAccess::WRITE)) {
  865. return; // FS persistence is not working or we are not writing.
  866. }
  867. bool is_file_persistent = p_file.begins_with("/userfs");
  868. #ifdef TOOLS_ENABLED
  869. // Hack for editor persistence (can we track).
  870. is_file_persistent = is_file_persistent || p_file.begins_with("/home/web_user/");
  871. #endif
  872. if (is_file_persistent) {
  873. os->idb_needs_sync = true;
  874. }
  875. }
  876. bool OS_JavaScript::is_userfs_persistent() const {
  877. return idb_available;
  878. }
  879. Error OS_JavaScript::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  880. String path = p_path.get_file();
  881. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  882. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  883. return OK;
  884. }
  885. OS_JavaScript *OS_JavaScript::get_singleton() {
  886. return static_cast<OS_JavaScript *>(OS::get_singleton());
  887. }
  888. OS_JavaScript::OS_JavaScript() {
  889. // Expose method for requesting quit.
  890. godot_js_os_request_quit_cb(&request_quit_callback);
  891. // Set canvas ID
  892. godot_js_config_canvas_id_get(canvas_id, sizeof(canvas_id));
  893. cursor_inside_canvas = true;
  894. cursor_shape = OS::CURSOR_ARROW;
  895. last_click_button_index = -1;
  896. last_click_ms = 0;
  897. last_click_pos = Point2(-100, -100);
  898. transparency_enabled = false;
  899. main_loop = NULL;
  900. visual_server = NULL;
  901. swap_ok_cancel = false;
  902. idb_available = godot_js_os_fs_is_persistent() != 0;
  903. idb_needs_sync = false;
  904. idb_is_syncing = false;
  905. if (AudioDriverJavaScript::is_available()) {
  906. #ifdef NO_THREADS
  907. audio_drivers.push_back(memnew(AudioDriverScriptProcessor));
  908. #endif
  909. audio_drivers.push_back(memnew(AudioDriverWorklet));
  910. }
  911. for (int i = 0; i < audio_drivers.size(); i++) {
  912. AudioDriverManager::add_driver(audio_drivers[i]);
  913. }
  914. Vector<Logger *> loggers;
  915. loggers.push_back(memnew(StdLogger));
  916. _set_logger(memnew(CompositeLogger(loggers)));
  917. FileAccessUnix::close_notification_func = file_access_close_callback;
  918. }