os_uwp.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. /**************************************************************************/
  2. /* os_uwp.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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_uwp.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/project_settings.h"
  33. #include "drivers/gles2/rasterizer_gles2.h"
  34. #include "drivers/gles3/rasterizer_gles3.h"
  35. #include "drivers/unix/ip_unix.h"
  36. #include "drivers/unix/net_socket_posix.h"
  37. #include "drivers/windows/dir_access_windows.h"
  38. #include "drivers/windows/file_access_windows.h"
  39. #include "main/main.h"
  40. #include "platform/windows/windows_terminal_logger.h"
  41. #include "servers/audio_server.h"
  42. #include "servers/visual/visual_server_raster.h"
  43. #include "servers/visual/visual_server_wrap_mt.h"
  44. #include <ppltasks.h>
  45. #include <wrl.h>
  46. using namespace Windows::ApplicationModel::Core;
  47. using namespace Windows::ApplicationModel::Activation;
  48. using namespace Windows::UI::Core;
  49. using namespace Windows::UI::Input;
  50. using namespace Windows::UI::Popups;
  51. using namespace Windows::Foundation;
  52. using namespace Windows::Graphics::Display;
  53. using namespace Microsoft::WRL;
  54. using namespace Windows::UI::ViewManagement;
  55. using namespace Windows::Devices::Input;
  56. using namespace Windows::Devices::Sensors;
  57. using namespace Windows::ApplicationModel::DataTransfer;
  58. using namespace concurrency;
  59. int OS_UWP::get_video_driver_count() const {
  60. return 2;
  61. }
  62. Size2 OS_UWP::get_window_size() const {
  63. Size2 size;
  64. size.width = video_mode.width;
  65. size.height = video_mode.height;
  66. return size;
  67. }
  68. int OS_UWP::get_current_video_driver() const {
  69. return video_driver_index;
  70. }
  71. void OS_UWP::set_window_size(const Size2 p_size) {
  72. Windows::Foundation::Size new_size;
  73. new_size.Width = p_size.width;
  74. new_size.Height = p_size.height;
  75. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  76. if (view->TryResizeView(new_size)) {
  77. video_mode.width = p_size.width;
  78. video_mode.height = p_size.height;
  79. }
  80. }
  81. void OS_UWP::set_window_fullscreen(bool p_enabled) {
  82. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  83. video_mode.fullscreen = view->IsFullScreenMode;
  84. if (video_mode.fullscreen == p_enabled)
  85. return;
  86. if (p_enabled) {
  87. video_mode.fullscreen = view->TryEnterFullScreenMode();
  88. } else {
  89. view->ExitFullScreenMode();
  90. video_mode.fullscreen = false;
  91. }
  92. }
  93. bool OS_UWP::is_window_fullscreen() const {
  94. return ApplicationView::GetForCurrentView()->IsFullScreenMode;
  95. }
  96. void OS_UWP::set_keep_screen_on(bool p_enabled) {
  97. if (is_keep_screen_on() == p_enabled)
  98. return;
  99. if (p_enabled)
  100. display_request->RequestActive();
  101. else
  102. display_request->RequestRelease();
  103. OS::set_keep_screen_on(p_enabled);
  104. }
  105. void OS_UWP::initialize_core() {
  106. last_button_state = 0;
  107. //RedirectIOToConsole();
  108. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  109. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  110. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  111. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  112. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  113. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  114. NetSocketPosix::make_default();
  115. // We need to know how often the clock is updated
  116. QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second);
  117. QueryPerformanceCounter((LARGE_INTEGER *)&ticks_start);
  118. IP_Unix::make_default();
  119. cursor_shape = CURSOR_ARROW;
  120. }
  121. bool OS_UWP::can_draw() const {
  122. return !minimized;
  123. };
  124. void OS_UWP::set_window(Windows::UI::Core::CoreWindow ^ p_window) {
  125. window = p_window;
  126. }
  127. void OS_UWP::screen_size_changed() {
  128. gl_context->reset();
  129. };
  130. Error OS_UWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  131. main_loop = NULL;
  132. outside = true;
  133. ContextEGL_UWP::Driver opengl_api_type = ContextEGL_UWP::GLES_2_0;
  134. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  135. opengl_api_type = ContextEGL_UWP::GLES_2_0;
  136. }
  137. bool gl_initialization_error = false;
  138. gl_context = NULL;
  139. while (!gl_context) {
  140. gl_context = memnew(ContextEGL_UWP(window, opengl_api_type));
  141. if (gl_context->initialize() != OK) {
  142. memdelete(gl_context);
  143. gl_context = NULL;
  144. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  145. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  146. gl_initialization_error = true;
  147. break;
  148. }
  149. p_video_driver = VIDEO_DRIVER_GLES2;
  150. opengl_api_type = ContextEGL_UWP::GLES_2_0;
  151. } else {
  152. gl_initialization_error = true;
  153. break;
  154. }
  155. }
  156. }
  157. while (true) {
  158. if (opengl_api_type == ContextEGL_UWP::GLES_3_0) {
  159. if (RasterizerGLES3::is_viable() == OK) {
  160. RasterizerGLES3::register_config();
  161. RasterizerGLES3::make_current();
  162. break;
  163. } else {
  164. if (GLOBAL_GET("rendering/quality/driver/fallback_to_gles2")) {
  165. p_video_driver = VIDEO_DRIVER_GLES2;
  166. opengl_api_type = ContextEGL_UWP::GLES_2_0;
  167. continue;
  168. } else {
  169. gl_initialization_error = true;
  170. break;
  171. }
  172. }
  173. }
  174. if (opengl_api_type == ContextEGL_UWP::GLES_2_0) {
  175. if (RasterizerGLES2::is_viable() == OK) {
  176. RasterizerGLES2::register_config();
  177. RasterizerGLES2::make_current();
  178. break;
  179. } else {
  180. gl_initialization_error = true;
  181. break;
  182. }
  183. }
  184. }
  185. if (gl_initialization_error) {
  186. OS::get_singleton()->alert("Your video card driver does not support any of the supported OpenGL versions.\n"
  187. "Please update your drivers or if you have a very old or integrated GPU, upgrade it.",
  188. "Unable to initialize Video driver");
  189. return ERR_UNAVAILABLE;
  190. }
  191. video_driver_index = p_video_driver;
  192. gl_context->make_current();
  193. gl_context->set_use_vsync(video_mode.use_vsync);
  194. VideoMode vm;
  195. vm.width = gl_context->get_window_width();
  196. vm.height = gl_context->get_window_height();
  197. vm.resizable = false;
  198. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  199. vm.fullscreen = view->IsFullScreenMode;
  200. view->SetDesiredBoundsMode(ApplicationViewBoundsMode::UseVisible);
  201. view->PreferredLaunchWindowingMode = ApplicationViewWindowingMode::PreferredLaunchViewSize;
  202. if (p_desired.fullscreen != view->IsFullScreenMode) {
  203. if (p_desired.fullscreen) {
  204. vm.fullscreen = view->TryEnterFullScreenMode();
  205. } else {
  206. view->ExitFullScreenMode();
  207. vm.fullscreen = false;
  208. }
  209. }
  210. Windows::Foundation::Size desired;
  211. desired.Width = p_desired.width;
  212. desired.Height = p_desired.height;
  213. view->PreferredLaunchViewSize = desired;
  214. if (view->TryResizeView(desired)) {
  215. vm.width = view->VisibleBounds.Width;
  216. vm.height = view->VisibleBounds.Height;
  217. }
  218. set_video_mode(vm);
  219. visual_server = memnew(VisualServerRaster);
  220. // FIXME: Reimplement threaded rendering
  221. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  222. visual_server = memnew(VisualServerWrapMT(visual_server, false));
  223. }
  224. visual_server->init();
  225. input = memnew(InputDefault);
  226. joypad = ref new JoypadUWP(input);
  227. joypad->register_events();
  228. AudioDriverManager::initialize(p_audio_driver);
  229. power_manager = memnew(PowerUWP);
  230. managed_object->update_clipboard();
  231. Clipboard::ContentChanged += ref new EventHandler<Platform::Object ^>(managed_object, &ManagedType::on_clipboard_changed);
  232. accelerometer = Accelerometer::GetDefault();
  233. if (accelerometer != nullptr) {
  234. // 60 FPS
  235. accelerometer->ReportInterval = (1.0f / 60.0f) * 1000;
  236. accelerometer->ReadingChanged +=
  237. ref new TypedEventHandler<Accelerometer ^, AccelerometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_accelerometer_reading_changed);
  238. }
  239. magnetometer = Magnetometer::GetDefault();
  240. if (magnetometer != nullptr) {
  241. // 60 FPS
  242. magnetometer->ReportInterval = (1.0f / 60.0f) * 1000;
  243. magnetometer->ReadingChanged +=
  244. ref new TypedEventHandler<Magnetometer ^, MagnetometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_magnetometer_reading_changed);
  245. }
  246. gyrometer = Gyrometer::GetDefault();
  247. if (gyrometer != nullptr) {
  248. // 60 FPS
  249. gyrometer->ReportInterval = (1.0f / 60.0f) * 1000;
  250. gyrometer->ReadingChanged +=
  251. ref new TypedEventHandler<Gyrometer ^, GyrometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_gyroscope_reading_changed);
  252. }
  253. if (is_keep_screen_on())
  254. display_request->RequestActive();
  255. set_keep_screen_on(GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true));
  256. return OK;
  257. }
  258. void OS_UWP::set_clipboard(const String &p_text) {
  259. DataPackage ^ clip = ref new DataPackage();
  260. clip->RequestedOperation = DataPackageOperation::Copy;
  261. clip->SetText(ref new Platform::String((const wchar_t *)p_text.c_str()));
  262. Clipboard::SetContent(clip);
  263. };
  264. String OS_UWP::get_clipboard() const {
  265. if (managed_object->clipboard != nullptr)
  266. return managed_object->clipboard->Data();
  267. else
  268. return "";
  269. };
  270. void OS_UWP::input_event(const Ref<InputEvent> &p_event) {
  271. input->parse_input_event(p_event);
  272. };
  273. void OS_UWP::delete_main_loop() {
  274. if (main_loop)
  275. memdelete(main_loop);
  276. main_loop = NULL;
  277. }
  278. void OS_UWP::set_main_loop(MainLoop *p_main_loop) {
  279. input->set_main_loop(p_main_loop);
  280. main_loop = p_main_loop;
  281. }
  282. void OS_UWP::finalize() {
  283. if (main_loop)
  284. memdelete(main_loop);
  285. main_loop = NULL;
  286. visual_server->finish();
  287. memdelete(visual_server);
  288. #ifdef OPENGL_ENABLED
  289. if (gl_context)
  290. memdelete(gl_context);
  291. #endif
  292. memdelete(input);
  293. joypad = nullptr;
  294. }
  295. void OS_UWP::finalize_core() {
  296. NetSocketPosix::cleanup();
  297. }
  298. void OS_UWP::alert(const String &p_alert, const String &p_title) {
  299. Platform::String ^ alert = ref new Platform::String(p_alert.c_str());
  300. Platform::String ^ title = ref new Platform::String(p_title.c_str());
  301. MessageDialog ^ msg = ref new MessageDialog(alert, title);
  302. UICommand ^ close = ref new UICommand("Close", ref new UICommandInvokedHandler(managed_object, &OS_UWP::ManagedType::alert_close));
  303. msg->Commands->Append(close);
  304. msg->DefaultCommandIndex = 0;
  305. managed_object->alert_close_handle = true;
  306. msg->ShowAsync();
  307. }
  308. void OS_UWP::ManagedType::alert_close(IUICommand ^ command) {
  309. alert_close_handle = false;
  310. }
  311. void OS_UWP::ManagedType::on_clipboard_changed(Platform::Object ^ sender, Platform::Object ^ ev) {
  312. update_clipboard();
  313. }
  314. void OS_UWP::ManagedType::update_clipboard() {
  315. DataPackageView ^ data = Clipboard::GetContent();
  316. if (data->Contains(StandardDataFormats::Text)) {
  317. create_task(data->GetTextAsync()).then([this](Platform::String ^ clipboard_content) {
  318. this->clipboard = clipboard_content;
  319. });
  320. }
  321. }
  322. void OS_UWP::ManagedType::on_accelerometer_reading_changed(Accelerometer ^ sender, AccelerometerReadingChangedEventArgs ^ args) {
  323. AccelerometerReading ^ reading = args->Reading;
  324. os->input->set_accelerometer(Vector3(
  325. reading->AccelerationX,
  326. reading->AccelerationY,
  327. reading->AccelerationZ));
  328. }
  329. void OS_UWP::ManagedType::on_magnetometer_reading_changed(Magnetometer ^ sender, MagnetometerReadingChangedEventArgs ^ args) {
  330. MagnetometerReading ^ reading = args->Reading;
  331. os->input->set_magnetometer(Vector3(
  332. reading->MagneticFieldX,
  333. reading->MagneticFieldY,
  334. reading->MagneticFieldZ));
  335. }
  336. void OS_UWP::ManagedType::on_gyroscope_reading_changed(Gyrometer ^ sender, GyrometerReadingChangedEventArgs ^ args) {
  337. GyrometerReading ^ reading = args->Reading;
  338. os->input->set_magnetometer(Vector3(
  339. reading->AngularVelocityX,
  340. reading->AngularVelocityY,
  341. reading->AngularVelocityZ));
  342. }
  343. void OS_UWP::set_mouse_mode(MouseMode p_mode) {
  344. if (p_mode == MouseMode::MOUSE_MODE_CAPTURED) {
  345. CoreWindow::GetForCurrentThread()->SetPointerCapture();
  346. } else {
  347. CoreWindow::GetForCurrentThread()->ReleasePointerCapture();
  348. }
  349. if (p_mode == MouseMode::MOUSE_MODE_HIDDEN || p_mode == MouseMode::MOUSE_MODE_CAPTURED || p_mode == MouseMode::MOUSE_MODE_CONFINED_HIDDEN) {
  350. CoreWindow::GetForCurrentThread()->PointerCursor = nullptr;
  351. } else {
  352. CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
  353. }
  354. mouse_mode = p_mode;
  355. SetEvent(mouse_mode_changed);
  356. }
  357. OS_UWP::MouseMode OS_UWP::get_mouse_mode() const {
  358. return mouse_mode;
  359. }
  360. Point2 OS_UWP::get_mouse_position() const {
  361. return Point2(old_x, old_y);
  362. }
  363. int OS_UWP::get_mouse_button_state() const {
  364. return last_button_state;
  365. }
  366. void OS_UWP::set_window_title(const String &p_title) {
  367. }
  368. void OS_UWP::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  369. video_mode = p_video_mode;
  370. }
  371. OS::VideoMode OS_UWP::get_video_mode(int p_screen) const {
  372. return video_mode;
  373. }
  374. void OS_UWP::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  375. }
  376. String OS_UWP::get_name() const {
  377. return "UWP";
  378. }
  379. OS::Date OS_UWP::get_date(bool utc) const {
  380. SYSTEMTIME systemtime;
  381. if (utc)
  382. GetSystemTime(&systemtime);
  383. else
  384. GetLocalTime(&systemtime);
  385. Date date;
  386. date.day = systemtime.wDay;
  387. date.month = Month(systemtime.wMonth);
  388. date.weekday = Weekday(systemtime.wDayOfWeek);
  389. date.year = systemtime.wYear;
  390. date.dst = false;
  391. return date;
  392. }
  393. OS::Time OS_UWP::get_time(bool utc) const {
  394. SYSTEMTIME systemtime;
  395. if (utc)
  396. GetSystemTime(&systemtime);
  397. else
  398. GetLocalTime(&systemtime);
  399. Time time;
  400. time.hour = systemtime.wHour;
  401. time.min = systemtime.wMinute;
  402. time.sec = systemtime.wSecond;
  403. return time;
  404. }
  405. OS::TimeZoneInfo OS_UWP::get_time_zone_info() const {
  406. TIME_ZONE_INFORMATION info;
  407. bool daylight = false;
  408. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  409. daylight = true;
  410. TimeZoneInfo ret;
  411. if (daylight) {
  412. ret.name = info.DaylightName;
  413. } else {
  414. ret.name = info.StandardName;
  415. }
  416. // Bias value returned by GetTimeZoneInformation is inverted of what we expect
  417. // For example on GMT-3 GetTimeZoneInformation return a Bias of 180, so invert the value to get -180
  418. ret.bias = -info.Bias;
  419. return ret;
  420. }
  421. uint64_t OS_UWP::get_unix_time() const {
  422. FILETIME ft;
  423. SYSTEMTIME st;
  424. GetSystemTime(&st);
  425. SystemTimeToFileTime(&st, &ft);
  426. SYSTEMTIME ep;
  427. ep.wYear = 1970;
  428. ep.wMonth = 1;
  429. ep.wDayOfWeek = 4;
  430. ep.wDay = 1;
  431. ep.wHour = 0;
  432. ep.wMinute = 0;
  433. ep.wSecond = 0;
  434. ep.wMilliseconds = 0;
  435. FILETIME fep;
  436. SystemTimeToFileTime(&ep, &fep);
  437. return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
  438. };
  439. double OS_UWP::get_subsecond_unix_time() const {
  440. // 1 Windows tick is 100ns
  441. const uint64_t WINDOWS_TICKS_PER_SECOND = 10000000;
  442. const uint64_t TICKS_TO_UNIX_EPOCH = 116444736000000000LL;
  443. SYSTEMTIME st;
  444. GetSystemTime(&st);
  445. FILETIME ft;
  446. SystemTimeToFileTime(&st, &ft);
  447. uint64_t ticks_time;
  448. ticks_time = ft.dwHighDateTime;
  449. ticks_time <<= 32;
  450. ticks_time |= ft.dwLowDateTime;
  451. return (double)(ticks_time - TICKS_TO_UNIX_EPOCH) / WINDOWS_TICKS_PER_SECOND;
  452. }
  453. void OS_UWP::delay_usec(uint32_t p_usec) const {
  454. int msec = p_usec < 1000 ? 1 : p_usec / 1000;
  455. // no Sleep()
  456. WaitForSingleObjectEx(GetCurrentThread(), msec, false);
  457. }
  458. uint64_t OS_UWP::get_ticks_usec() const {
  459. uint64_t ticks;
  460. // This is the number of clock ticks since start
  461. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  462. // Subtract the ticks at game start to get
  463. // the ticks since the game started
  464. ticks -= ticks_start;
  465. // Divide by frequency to get the time in seconds
  466. // original calculation shown below is subject to overflow
  467. // with high ticks_per_second and a number of days since the last reboot.
  468. // time = ticks * 1000000L / ticks_per_second;
  469. // we can prevent this by either using 128 bit math
  470. // or separating into a calculation for seconds, and the fraction
  471. uint64_t seconds = ticks / ticks_per_second;
  472. // compiler will optimize these two into one divide
  473. uint64_t leftover = ticks % ticks_per_second;
  474. // remainder
  475. uint64_t time = (leftover * 1000000L) / ticks_per_second;
  476. // seconds
  477. time += seconds * 1000000L;
  478. return time;
  479. }
  480. void OS_UWP::process_events() {
  481. joypad->process_controllers();
  482. process_key_events();
  483. input->flush_buffered_events();
  484. }
  485. void OS_UWP::process_key_events() {
  486. for (int i = 0; i < key_event_pos; i++) {
  487. KeyEvent &kev = key_event_buffer[i];
  488. Ref<InputEventKey> key_event;
  489. key_event.instance();
  490. key_event->set_alt(kev.alt);
  491. key_event->set_shift(kev.shift);
  492. key_event->set_control(kev.control);
  493. key_event->set_echo(kev.echo);
  494. key_event->set_scancode(kev.scancode);
  495. key_event->set_physical_scancode(kev.physical_scancode);
  496. key_event->set_unicode(kev.unicode);
  497. key_event->set_pressed(kev.pressed);
  498. input_event(key_event);
  499. }
  500. key_event_pos = 0;
  501. }
  502. void OS_UWP::queue_key_event(KeyEvent &p_event) {
  503. // This merges Char events with the previous Key event, so
  504. // the unicode can be retrieved without sending duplicate events.
  505. if (p_event.type == KeyEvent::MessageType::CHAR_EVENT_MESSAGE && key_event_pos > 0) {
  506. KeyEvent &old = key_event_buffer[key_event_pos - 1];
  507. ERR_FAIL_COND(old.type != KeyEvent::MessageType::KEY_EVENT_MESSAGE);
  508. key_event_buffer[key_event_pos - 1].unicode = p_event.unicode;
  509. return;
  510. }
  511. ERR_FAIL_COND(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  512. key_event_buffer[key_event_pos++] = p_event;
  513. }
  514. void OS_UWP::set_cursor_shape(CursorShape p_shape) {
  515. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  516. if (cursor_shape == p_shape)
  517. return;
  518. static const CoreCursorType uwp_cursors[CURSOR_MAX] = {
  519. CoreCursorType::Arrow,
  520. CoreCursorType::IBeam,
  521. CoreCursorType::Hand,
  522. CoreCursorType::Cross,
  523. CoreCursorType::Wait,
  524. CoreCursorType::Wait,
  525. CoreCursorType::Arrow,
  526. CoreCursorType::Arrow,
  527. CoreCursorType::UniversalNo,
  528. CoreCursorType::SizeNorthSouth,
  529. CoreCursorType::SizeWestEast,
  530. CoreCursorType::SizeNortheastSouthwest,
  531. CoreCursorType::SizeNorthwestSoutheast,
  532. CoreCursorType::SizeAll,
  533. CoreCursorType::SizeNorthSouth,
  534. CoreCursorType::SizeWestEast,
  535. CoreCursorType::Help
  536. };
  537. CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(uwp_cursors[p_shape], 0);
  538. cursor_shape = p_shape;
  539. }
  540. OS::CursorShape OS_UWP::get_cursor_shape() const {
  541. return cursor_shape;
  542. }
  543. void OS_UWP::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  544. // TODO
  545. }
  546. Error OS_UWP::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, bool p_open_console) {
  547. return FAILED;
  548. };
  549. Error OS_UWP::kill(const ProcessID &p_pid) {
  550. return FAILED;
  551. };
  552. bool OS_UWP::is_process_running(const ProcessID &p_pid) const {
  553. return false;
  554. }
  555. Error OS_UWP::set_cwd(const String &p_cwd) {
  556. return FAILED;
  557. }
  558. String OS_UWP::get_executable_path() const {
  559. return "";
  560. }
  561. void OS_UWP::set_icon(const Ref<Image> &p_icon) {
  562. }
  563. bool OS_UWP::has_environment(const String &p_var) const {
  564. return false;
  565. };
  566. String OS_UWP::get_environment(const String &p_var) const {
  567. return "";
  568. };
  569. bool OS_UWP::set_environment(const String &p_var, const String &p_value) const {
  570. return false;
  571. }
  572. String OS_UWP::get_stdin_string() {
  573. return String();
  574. }
  575. void OS_UWP::move_window_to_foreground() {
  576. }
  577. Error OS_UWP::shell_open(String p_uri) {
  578. return FAILED;
  579. }
  580. String OS_UWP::get_locale() const {
  581. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP // this should work on phone 8.1, but it doesn't
  582. return "en";
  583. #else
  584. Platform::String ^ language = Windows::Globalization::Language::CurrentInputMethodLanguageTag;
  585. return String(language->Data()).replace("-", "_");
  586. #endif
  587. }
  588. void OS_UWP::release_rendering_thread() {
  589. gl_context->release_current();
  590. }
  591. void OS_UWP::make_rendering_thread() {
  592. gl_context->make_current();
  593. }
  594. void OS_UWP::swap_buffers() {
  595. gl_context->swap_buffers();
  596. }
  597. bool OS_UWP::has_touchscreen_ui_hint() const {
  598. TouchCapabilities ^ tc = ref new TouchCapabilities();
  599. return tc->TouchPresent != 0 || UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
  600. }
  601. bool OS_UWP::has_virtual_keyboard() const {
  602. return UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
  603. }
  604. void OS_UWP::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect, VirtualKeyboardType p_type, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  605. InputPane ^ pane = InputPane::GetForCurrentView();
  606. pane->TryShow();
  607. }
  608. void OS_UWP::hide_virtual_keyboard() {
  609. InputPane ^ pane = InputPane::GetForCurrentView();
  610. pane->TryHide();
  611. }
  612. static String format_error_message(DWORD id) {
  613. LPWSTR messageBuffer = NULL;
  614. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  615. NULL, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL);
  616. String msg = "Error " + itos(id) + ": " + String(messageBuffer, size);
  617. LocalFree(messageBuffer);
  618. return msg;
  619. }
  620. Error OS_UWP::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  621. String full_path = "game/" + p_path;
  622. p_library_handle = (void *)LoadPackagedLibrary(full_path.c_str(), 0);
  623. ERR_FAIL_COND_V_MSG(!p_library_handle, ERR_CANT_OPEN, "Can't open dynamic library: " + full_path + ", error: " + format_error_message(GetLastError()) + ".");
  624. return OK;
  625. }
  626. Error OS_UWP::close_dynamic_library(void *p_library_handle) {
  627. if (!FreeLibrary((HMODULE)p_library_handle)) {
  628. return FAILED;
  629. }
  630. return OK;
  631. }
  632. Error OS_UWP::get_dynamic_library_symbol_handle(void *p_library_handle, const String p_name, void *&p_symbol_handle, bool p_optional) {
  633. p_symbol_handle = (void *)GetProcAddress((HMODULE)p_library_handle, p_name.utf8().get_data());
  634. if (!p_symbol_handle) {
  635. if (!p_optional) {
  636. ERR_FAIL_V_MSG(ERR_CANT_RESOLVE, "Can't resolve symbol " + p_name + ", error: " + String::num(GetLastError()) + ".");
  637. } else {
  638. return ERR_CANT_RESOLVE;
  639. }
  640. }
  641. return OK;
  642. }
  643. void OS_UWP::run() {
  644. if (!main_loop)
  645. return;
  646. main_loop->init();
  647. uint64_t last_ticks = get_ticks_usec();
  648. int frames = 0;
  649. uint64_t frame = 0;
  650. while (!force_quit) {
  651. CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
  652. if (managed_object->alert_close_handle)
  653. continue;
  654. process_events(); // get rid of pending events
  655. if (Main::iteration())
  656. break;
  657. };
  658. main_loop->finish();
  659. }
  660. MainLoop *OS_UWP::get_main_loop() const {
  661. return main_loop;
  662. }
  663. String OS_UWP::get_user_data_dir() const {
  664. Windows::Storage::StorageFolder ^ data_folder = Windows::Storage::ApplicationData::Current->LocalFolder;
  665. return String(data_folder->Path->Data()).replace("\\", "/");
  666. }
  667. bool OS_UWP::_check_internal_feature_support(const String &p_feature) {
  668. return p_feature == "pc";
  669. }
  670. OS::PowerState OS_UWP::get_power_state() {
  671. return power_manager->get_power_state();
  672. }
  673. int OS_UWP::get_power_seconds_left() {
  674. return power_manager->get_power_seconds_left();
  675. }
  676. int OS_UWP::get_power_percent_left() {
  677. return power_manager->get_power_percent_left();
  678. }
  679. OS_UWP::OS_UWP() {
  680. key_event_pos = 0;
  681. force_quit = false;
  682. alt_mem = false;
  683. gr_mem = false;
  684. shift_mem = false;
  685. control_mem = false;
  686. meta_mem = false;
  687. minimized = false;
  688. pressrc = 0;
  689. old_invalid = true;
  690. mouse_mode = MOUSE_MODE_VISIBLE;
  691. #ifdef STDOUT_FILE
  692. stdo = fopen("stdout.txt", "wb");
  693. #endif
  694. gl_context = NULL;
  695. display_request = ref new Windows::System::Display::DisplayRequest();
  696. managed_object = ref new ManagedType;
  697. managed_object->os = this;
  698. mouse_mode_changed = CreateEvent(NULL, TRUE, FALSE, L"os_mouse_mode_changed");
  699. AudioDriverManager::add_driver(&audio_driver);
  700. Vector<Logger *> loggers;
  701. loggers.push_back(memnew(WindowsTerminalLogger));
  702. _set_logger(memnew(CompositeLogger(loggers)));
  703. }
  704. OS_UWP::~OS_UWP() {
  705. #ifdef STDOUT_FILE
  706. fclose(stdo);
  707. #endif
  708. }