os_uwp.cpp 26 KB

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