Web.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /******************************************************************************/
  2. #include "stdafx.h"
  3. #if WEB
  4. namespace EE{
  5. /******************************************************************************/
  6. static Bool BackgroundUpdateTimeSet, Firefox;
  7. static UInt BackgroundUpdateTime;
  8. Flt ScreenScale=1, MouseWheelScale;
  9. /******************************************************************************/
  10. static void SetMaximized(Int window_width=0, Int window_height=0)
  11. {
  12. VecI2 win_size(window_width ? window_width : JavaScriptRunI("window.outerWidth"),
  13. window_height ? window_height : JavaScriptRunI("window.outerHeight"));
  14. App._maximized=(win_size.x>=JavaScriptRunI("screen.availWidth") && win_size.y>=JavaScriptRunI("screen.availHeight")); // this sets if the browser window is maximized
  15. }
  16. /******************************************************************************/
  17. static EM_BOOL MouseMove(int eventType, const EmscriptenMouseEvent *e, void *userData)
  18. {
  19. Ms._delta_relative.x+=e->movementX;
  20. Ms._delta_relative.y-=e->movementY;
  21. VecI2 posi(RoundPos(e->screenX*ScreenScale),
  22. RoundPos(e->screenY*ScreenScale));
  23. Ms._deltai+=posi-Ms._desktop_posi;
  24. Ms._desktop_posi=posi;
  25. Ms. _window_posi.set(RoundPos(e->canvasX*ScreenScale), // have to use 'canvas' instead of 'client' because that one is the window client but not the canvas
  26. RoundPos(e->canvasY*ScreenScale));
  27. return 0;
  28. }
  29. static EM_BOOL MouseDown(int eventType, const EmscriptenMouseEvent *e, void *userData)
  30. {
  31. if(Ms._on_client)
  32. {
  33. Int b=e->button; switch(b){case 1: b=2; break; case 2: b=1; break;}
  34. Ms.push(b);
  35. return 1;
  36. }
  37. return 0;
  38. }
  39. static EM_BOOL MouseUp(int eventType, const EmscriptenMouseEvent *e, void *userData)
  40. {
  41. Int b=e->button; switch(b){case 1: b=2; break; case 2: b=1; break;}
  42. Ms.release(b);
  43. return 1;
  44. }
  45. static EM_BOOL MouseWheel(int eventType, const EmscriptenWheelEvent *e, void *userData)
  46. {
  47. if(Ms._on_client || Ms.b(0)) // process the wheel only if on client or if there's a mouse button pressed (dragging from the client)
  48. {
  49. Ms._wheel.x+=e->deltaX*MouseWheelScale;
  50. Ms._wheel.y-=e->deltaY*MouseWheelScale;
  51. return 1; // eat it so it won't be processed by the browser
  52. }
  53. return 0;
  54. }
  55. static EM_BOOL MouseLock(int eventType, const EmscriptenPointerlockChangeEvent *pointerlockChangeEvent, void *userData)
  56. {
  57. Ms._locked=pointerlockChangeEvent->isActive;
  58. return 1;
  59. }
  60. /******************************************************************************
  61. Currently used 'charCode' and 'keyCode' are deprecated in Emscripten, however they fit perfectly in the needs of the engine.
  62. 'keyCode' maps exactly to KB_KEY (which are mapped to Windows VK_ Virtual Keys) that was tested on Chrome on Win and Mac.
  63. The suggested replacements are 'key' and 'code',
  64. 'key' should be used only in 'KeyPressed' as WM_CHAR, however it's UTF8 based and would cause overhead to decode.
  65. 'code' should be treated as scan code, it produces different results than 'keyCode' on QWERTY/AZERTY leyouts, however it's UTF8 text-based and would cause overhead to decode.
  66. /******************************************************************************/
  67. static EM_BOOL KeyPressed(int eventType, const EmscriptenKeyboardEvent *e, void *userData)
  68. {
  69. //LogN(S+"KeyPressed, key:"+FromUTF8(e->key)+", code:"+FromUTF8(e->code)+", char:"+Char(e->charCode));
  70. Kb.queue(Char(e->charCode), e->keyCode);
  71. return 1;
  72. }
  73. static EM_BOOL KeyDown(int eventType, const EmscriptenKeyboardEvent *e, void *userData)
  74. {
  75. //LogN(S+"KeyDown, key:"+FromUTF8(e->key)+", code:"+FromUTF8(e->code)+", keyName:"+Kb.keyName(KB_KEY(e->keyCode))+", location:"+(Int)e->location);
  76. KB_KEY key=KB_KEY(e->keyCode);
  77. switch(e->location)
  78. {
  79. case DOM_KEY_LOCATION_LEFT: switch(key)
  80. {
  81. case KB_CTRL : key=KB_LCTRL ; break;
  82. case KB_SHIFT: key=KB_LSHIFT; break;
  83. case KB_ALT : key=KB_LALT ; break;
  84. //case KB_WIN : key=KB_LWIN ; break;
  85. }break;
  86. case DOM_KEY_LOCATION_RIGHT: switch(key)
  87. {
  88. case KB_CTRL : key=KB_RCTRL ; break;
  89. case KB_SHIFT: key=KB_RSHIFT; break;
  90. case KB_ALT : key=KB_RALT ; break;
  91. //case KB_WIN : key=KB_RWIN ; break;
  92. }break;
  93. }
  94. Kb.push(key, key);
  95. // !! queue characters after push !!
  96. if(e->ctrlKey) // if control is pressed then we need to eat it to avoid browser taking over Ctrl+A, Ctrl+C, Ctrl+V, etc.
  97. {
  98. if(key>='A' && key<='Z')Kb.queue(Char(key + (e->shiftKey ? 0 : 'a'-'A')), key);else
  99. if(key>='0' && key<='9')Kb.queue(Char(key ), key);
  100. return 1; // eat the key
  101. }
  102. return Kb.keyChar(key) ? 0 : 1; // if the key will generate a character then don't eat it (0) so KeyPress can get called, otherwise eat it (1)
  103. }
  104. static EM_BOOL KeyUp(int eventType, const EmscriptenKeyboardEvent *e, void *userData)
  105. {
  106. //LogN(S+"KeyUp, key:"+FromUTF8(e->key)+", code:"+FromUTF8(e->code)+", keyName:"+Kb.keyName(KB_KEY(e->keyCode))+", location:"+(Int)e->location);
  107. KB_KEY key=KB_KEY(e->keyCode);
  108. switch(e->location)
  109. {
  110. case DOM_KEY_LOCATION_LEFT: switch(key)
  111. {
  112. case KB_CTRL : key=KB_LCTRL ; break;
  113. case KB_SHIFT: key=KB_LSHIFT; break;
  114. case KB_ALT : key=KB_LALT ; break;
  115. //case KB_WIN : key=KB_LWIN ; break;
  116. }break;
  117. case DOM_KEY_LOCATION_RIGHT: switch(key)
  118. {
  119. case KB_CTRL : key=KB_RCTRL ; break;
  120. case KB_SHIFT: key=KB_RSHIFT; break;
  121. case KB_ALT : key=KB_RALT ; break;
  122. //case KB_WIN : key=KB_RWIN ; break;
  123. }break;
  124. }
  125. Kb.release(key);
  126. return 1;
  127. }
  128. /******************************************************************************/
  129. static EM_BOOL TouchStart(int eventType, const EmscriptenTouchEvent *e, void *userData)
  130. {
  131. REP(e->numTouches)
  132. {
  133. C EmscriptenTouchPoint &s=e->touches[i]; if(s.isChanged)
  134. {
  135. Bool stylus=false;
  136. CPtr pid=CPtr(s.identifier);
  137. VecI2 posi(RoundPos(s.screenX*ScreenScale),
  138. RoundPos(s.screenY*ScreenScale));
  139. Vec2 pos=D.windowPixelToScreen(Vec2(s.canvasX, s.canvasY)*ScreenScale);
  140. Touch *touch=FindTouchByHandle(pid);
  141. if( !touch)touch=&Touches.New().init(posi, pos, pid, stylus);else
  142. {
  143. touch->_remove=false; // disable 'remove' in case it was enabled (for example the same touch was released in same/previous frame)
  144. touch-> reinit(posi, pos);
  145. }
  146. touch->_state=BS_ON|BS_PUSHED;
  147. touch->_force=1;
  148. }
  149. }
  150. return 1;
  151. }
  152. static EM_BOOL TouchEnd(int eventType, const EmscriptenTouchEvent *e, void *userData)
  153. {
  154. REP(e->numTouches)
  155. {
  156. C EmscriptenTouchPoint &s=e->touches[i];
  157. if(s.isChanged)
  158. if(Touch *touch=FindTouchByHandle(CPtr(s.identifier)))
  159. {
  160. touch->_posi .set(RoundPos(s.screenX*ScreenScale),
  161. RoundPos(s.screenY*ScreenScale));
  162. touch->_pos =D.windowPixelToScreen(Vec2(s.canvasX, s.canvasY)*ScreenScale);
  163. touch->_remove=true;
  164. if(touch->_state&BS_ON) // check for state in case it was manually eaten
  165. {
  166. touch->_state|= BS_RELEASED;
  167. touch->_state&=~BS_ON;
  168. }
  169. }
  170. }
  171. return 1;
  172. }
  173. static EM_BOOL TouchMove(int eventType, const EmscriptenTouchEvent *e, void *userData)
  174. {
  175. REP(e->numTouches)
  176. {
  177. C EmscriptenTouchPoint &s=e->touches[i];
  178. if(s.isChanged)
  179. if(Touch *touch=FindTouchByHandle(CPtr(s.identifier)))
  180. {
  181. VecI2 posi(RoundPos(s.screenX*ScreenScale),
  182. RoundPos(s.screenY*ScreenScale));
  183. touch->_deltai+=posi-touch->_posi;
  184. touch->_posi =posi;
  185. touch->_pos =D.windowPixelToScreen(Vec2(s.canvasX, s.canvasY)*ScreenScale);
  186. }
  187. }
  188. return 1;
  189. }
  190. /******************************************************************************/
  191. static EM_BOOL LostFocus(int eventType, const EmscriptenFocusEvent *e, void *userData)
  192. {
  193. Kb.release(KB_LCTRL); Kb.release(KB_LSHIFT); Kb.release(KB_LALT); Kb.release(KB_LWIN);
  194. Kb.release(KB_RCTRL); Kb.release(KB_RSHIFT); Kb.release(KB_RALT); Kb.release(KB_RWIN);
  195. return 0;
  196. }
  197. static EM_BOOL VisibilityChanged(int eventType, const EmscriptenVisibilityChangeEvent *e, void *userData)
  198. {
  199. if(e->hidden)PauseSound();else ResumeSound();
  200. App.setActive(!e->hidden);
  201. BackgroundUpdateTimeSet=false; // if app just got deactivated then make sure that we will recalc the time instead of using an old out-dated value
  202. return 0;
  203. }
  204. static EM_BOOL OrientationChanged(int eventType, const EmscriptenOrientationChangeEvent *e, void *userData)
  205. {
  206. /* FIXME test on mobile devices
  207. switch(e->orientationIndex)
  208. {
  209. case EMSCRIPTEN_ORIENTATION_PORTRAIT_PRIMARY : App._orientation=DIR_UP ; break;
  210. case EMSCRIPTEN_ORIENTATION_PORTRAIT_SECONDARY : App._orientation=DIR_DOWN ; break;
  211. case EMSCRIPTEN_ORIENTATION_LANDSCAPE_PRIMARY : App._orientation=DIR_RIGHT; break;
  212. case EMSCRIPTEN_ORIENTATION_LANDSCAPE_SECONDARY: App._orientation=DIR_LEFT ; break;
  213. }*/
  214. return 0;
  215. }
  216. static EM_BOOL FullChanged(int eventType, const EmscriptenFullscreenChangeEvent *e, void *userData)
  217. {
  218. return 0;
  219. }
  220. static EM_BOOL Resized(int eventType, const EmscriptenUiEvent *e, void *userData) // this gets called when window is resized or zoom is changed
  221. {
  222. SetMaximized(e->windowOuterWidth, e->windowOuterHeight);
  223. int width, height; emscripten_get_canvas_element_size(null, &width, &height);
  224. EmscriptenFullscreenChangeEvent full; emscripten_get_fullscreen_status(&full);
  225. #if 0
  226. LogN(S+"Resized:"+width+'x'+height+' '+full.isFullscreen+", Zoom:"+D.browserZoom());
  227. LogN(S+"inner:"+e->windowInnerWidth+'x'+e->windowInnerHeight+' '+e->windowInnerWidth*D.browserZoom()+'x'+e->windowInnerHeight*D.browserZoom());
  228. LogN(S+"body:"+e->documentBodyClientWidth+'x'+e->documentBodyClientHeight+' '+e->documentBodyClientWidth*D.browserZoom()+'x'+e->documentBodyClientHeight*D.browserZoom());
  229. #endif
  230. if(!(App.flag&APP_WEB_DISABLE_AUTO_RESIZE) && !full.isFullscreen)
  231. {
  232. D._full=false; D._res.zero(); // clear values to make sure D.mode will get executed
  233. Flt zoom=D.browserZoom();
  234. #if 0 // can't use this because the values are always Int's
  235. D.mode(Max(1, RoundPos(e->windowInnerWidth *zoom)),
  236. Max(1, RoundPos(e->windowInnerHeight*zoom)));
  237. #else
  238. JavaScriptRun("var target=Module['canvas'];if(target){target.style.width='100vw';target.style.height='100vh';}"); // resize to max
  239. Dbl css_w, css_h; emscripten_get_element_css_size(null, &css_w, &css_h); // get actual size
  240. Int w=Max(1, RoundPos(css_w*zoom)), h=Max(1, RoundPos(css_h*zoom)); // calculate pixels
  241. //LogN(S+css_w+' '+css_h+' '+css_w*zoom+' '+css_h*zoom+' '+w+' '+h);
  242. D.mode(w, h);
  243. #endif
  244. }else
  245. if(width!=D.resW() || height!=D.resH() || full.isFullscreen!=D.full())
  246. {
  247. // handle bug when leaving fullscreen we still get the same full resolution, this can happen when pressing Esc in fullscreen, or just sometimes when manually disabling fullscreen
  248. if(D.full() && !full.isFullscreen // if leaving full screen
  249. && width==D.resW() && height==D.resH()) // but the resolution is the same
  250. {
  251. D._full=false; D._res.zero(); // clear values to make sure D.mode will get executed
  252. D.mode(App._window_size.x, App._window_size.y, false);
  253. }else D.modeSet(width, height, full.isFullscreen);
  254. }else // res wasn't changed but zoom may have been
  255. {
  256. Dbl css_w, css_h; emscripten_get_element_css_size(null, &css_w, &css_h);
  257. ScreenScale=D.resW()/css_w; // here can't use zoom, because we don't maintain 1:1 pixel ratio
  258. }
  259. return 0;
  260. }
  261. /******************************************************************************/
  262. static void SetCallbacks()
  263. {
  264. emscripten_set_fullscreenchange_callback (0, 0, 1, FullChanged);
  265. emscripten_set_resize_callback (0, 0, 1, Resized);
  266. emscripten_set_blur_callback (0, 0, 1, LostFocus);
  267. emscripten_set_visibilitychange_callback ( 0, 1, VisibilityChanged);
  268. emscripten_set_orientationchange_callback ( 0, 1, OrientationChanged);
  269. //TODO: WEB joypad support
  270. //emscripten_set_gamepadconnected_callback ( 0, 1, GamepadConnected);
  271. //emscripten_set_gamepaddisconnected_callback( 0, 1, GamepadDisconnected);
  272. //emscripten_get_num_gamepads();
  273. //emscripten_get_gamepad_status(int index, EmscriptenGamepadEvent *gamepadState);
  274. emscripten_set_mousemove_callback (0, 0, 1, MouseMove);
  275. emscripten_set_mousedown_callback (0, 0, 1, MouseDown);
  276. emscripten_set_mouseup_callback (0, 0, 1, MouseUp);
  277. emscripten_set_wheel_callback (0, 0, 1, MouseWheel);
  278. emscripten_set_pointerlockchange_callback(0, 0, 1, MouseLock);
  279. emscripten_set_keypress_callback (0, 0, 1, KeyPressed);
  280. emscripten_set_keydown_callback (0, 0, 1, KeyDown);
  281. emscripten_set_keyup_callback (0, 0, 1, KeyUp);
  282. emscripten_set_touchstart_callback (0, 0, 1, TouchStart);
  283. emscripten_set_touchend_callback (0, 0, 1, TouchEnd);
  284. emscripten_set_touchcancel_callback (0, 0, 1, TouchEnd);
  285. emscripten_set_touchmove_callback (0, 0, 1, TouchMove);
  286. }
  287. /******************************************************************************/
  288. static void MainLoop()
  289. {
  290. if(App._close)
  291. {
  292. App.del();
  293. emscripten_cancel_main_loop();
  294. }else
  295. {
  296. UpdateThreads();
  297. if(!App.active())
  298. if(Int wait=((App.flag&APP_WORK_IN_BACKGROUND) ? App.background_wait : -1))
  299. {
  300. if(wait>0) // finite wait
  301. {
  302. if(BackgroundUpdateTimeSet) // if we already have the end time limit
  303. {
  304. wait=BackgroundUpdateTime-Time.curTimeMs(); MAX(wait, 0); // calculate remaining time, convert to Int first before maximizing
  305. }else
  306. {
  307. BackgroundUpdateTime=Time.curTimeMs()+wait; BackgroundUpdateTimeSet=true;
  308. }
  309. }
  310. if(!wait)
  311. {
  312. App.update();
  313. BackgroundUpdateTime=Time.curTimeMs()+App.background_wait; BackgroundUpdateTimeSet=true; // for WEB immediately recalc new time, because browsers already introduce long delays between updates when app is not active
  314. }
  315. return;
  316. }
  317. App.update();
  318. }
  319. }
  320. static void PreloadLoop()
  321. {
  322. UpdateThreads();
  323. Time.update();
  324. App._callbacks.update();
  325. if(!Preload()) // user has finished preloading
  326. {
  327. emscripten_cancel_main_loop(); // clear main loop (needs to be called before 'emscripten_set_main_loop')
  328. if(App.create1())
  329. {
  330. Firefox=Contains(D.deviceName(), "Mozilla");
  331. MouseWheelScale=(Firefox ? 1.0f/3 : 1.0f/100); // FireFox uses a different scale
  332. ScreenScale=D.browserZoom();
  333. SetCallbacks();
  334. emscripten_set_main_loop(MainLoop, 0, false); // don't set 'true' as the exception has already been called in 'emscripten_exit_with_live_runtime' below
  335. }
  336. }
  337. }
  338. /******************************************************************************/
  339. } // namespace EE
  340. /******************************************************************************/
  341. extern "C" EMSCRIPTEN_KEEPALIVE void FileSystemReady()
  342. {
  343. SetMaximized();
  344. if(App.create0())
  345. {
  346. App.setActive(true);
  347. emscripten_set_main_loop(PreloadLoop, 0, false); // don't set 'true' as the exception has already been called in 'emscripten_exit_with_live_runtime' below
  348. }
  349. }
  350. int main() // initialize the FileSystem first
  351. {
  352. EM_ASM
  353. ({
  354. // can't mount IDBFS to root "/" - https://github.com/kripken/emscripten/issues/5632
  355. FS.mkdir('/data'); FS.mount(IDBFS, {}, '/data');
  356. FS.syncfs(true, function(err) // load data
  357. {
  358. FS.chdir('/data');
  359. ccall('FileSystemReady', 'v', '', []); // call once the filesystem is ready
  360. });
  361. }, FileSystemReady);
  362. emscripten_exit_with_live_runtime(); // this will prevent the app from exiting and calling destructors, instead we'll just wait until the FS is ready
  363. return 0;
  364. }
  365. /******************************************************************************/
  366. #endif // WEB
  367. /******************************************************************************/