os_uwp.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /*************************************************************************/
  2. /* os_uwp.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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_uwp.h"
  31. #include "drivers/gles2/rasterizer_gles2.h"
  32. #include "drivers/windows/dir_access_windows.h"
  33. #include "drivers/windows/file_access_windows.h"
  34. #include "drivers/windows/mutex_windows.h"
  35. #include "drivers/windows/semaphore_windows.h"
  36. #include "main/main.h"
  37. #include "os/memory_pool_dynamic_static.h"
  38. #include "servers/audio_server.h"
  39. #include "servers/visual/visual_server_raster.h"
  40. #include "thread_uwp.h"
  41. //#include "servers/visual/visual_server_wrap_mt.h"
  42. #include "drivers/unix/ip_unix.h"
  43. #include "global_config.h"
  44. #include "io/marshalls.h"
  45. #include "os/memory_pool_dynamic_prealloc.h"
  46. #include "platform/windows/packet_peer_udp_winsock.h"
  47. #include "platform/windows/stream_peer_winsock.h"
  48. #include "platform/windows/tcp_server_winsock.h"
  49. #include <ppltasks.h>
  50. #include <wrl.h>
  51. using namespace Windows::ApplicationModel::Core;
  52. using namespace Windows::ApplicationModel::Activation;
  53. using namespace Windows::UI::Core;
  54. using namespace Windows::UI::Input;
  55. using namespace Windows::UI::Popups;
  56. using namespace Windows::Foundation;
  57. using namespace Windows::Graphics::Display;
  58. using namespace Microsoft::WRL;
  59. using namespace Windows::UI::ViewManagement;
  60. using namespace Windows::Devices::Input;
  61. using namespace Windows::Devices::Sensors;
  62. using namespace Windows::ApplicationModel::DataTransfer;
  63. using namespace concurrency;
  64. int OSUWP::get_video_driver_count() const {
  65. return 1;
  66. }
  67. const char *OSUWP::get_video_driver_name(int p_driver) const {
  68. return "GLES2";
  69. }
  70. OS::VideoMode OSUWP::get_default_video_mode() const {
  71. return video_mode;
  72. }
  73. Size2 OSUWP::get_window_size() const {
  74. Size2 size;
  75. size.width = video_mode.width;
  76. size.height = video_mode.height;
  77. return size;
  78. }
  79. void OSUWP::set_window_size(const Size2 p_size) {
  80. Windows::Foundation::Size new_size;
  81. new_size.Width = p_size.width;
  82. new_size.Height = p_size.height;
  83. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  84. if (view->TryResizeView(new_size)) {
  85. video_mode.width = p_size.width;
  86. video_mode.height = p_size.height;
  87. }
  88. }
  89. void OSUWP::set_window_fullscreen(bool p_enabled) {
  90. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  91. video_mode.fullscreen = view->IsFullScreenMode;
  92. if (video_mode.fullscreen == p_enabled)
  93. return;
  94. if (p_enabled) {
  95. video_mode.fullscreen = view->TryEnterFullScreenMode();
  96. } else {
  97. view->ExitFullScreenMode();
  98. video_mode.fullscreen = false;
  99. }
  100. }
  101. bool OSUWP::is_window_fullscreen() const {
  102. return ApplicationView::GetForCurrentView()->IsFullScreenMode;
  103. }
  104. void OSUWP::set_keep_screen_on(bool p_enabled) {
  105. if (is_keep_screen_on() == p_enabled) return;
  106. if (p_enabled)
  107. display_request->RequestActive();
  108. else
  109. display_request->RequestRelease();
  110. OS::set_keep_screen_on(p_enabled);
  111. }
  112. int OSUWP::get_audio_driver_count() const {
  113. return AudioDriverManager::get_driver_count();
  114. }
  115. const char *OSUWP::get_audio_driver_name(int p_driver) const {
  116. AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
  117. ERR_FAIL_COND_V(!driver, "");
  118. return AudioDriverManager::get_driver(p_driver)->get_name();
  119. }
  120. static MemoryPoolStatic *mempool_static = NULL;
  121. static MemoryPoolDynamic *mempool_dynamic = NULL;
  122. void OSUWP::initialize_core() {
  123. last_button_state = 0;
  124. //RedirectIOToConsole();
  125. ThreadUWP::make_default();
  126. SemaphoreWindows::make_default();
  127. MutexWindows::make_default();
  128. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_RESOURCES);
  129. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_USERDATA);
  130. FileAccess::make_default<FileAccessWindows>(FileAccess::ACCESS_FILESYSTEM);
  131. //FileAccessBufferedFA<FileAccessWindows>::make_default();
  132. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_RESOURCES);
  133. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_USERDATA);
  134. DirAccess::make_default<DirAccessWindows>(DirAccess::ACCESS_FILESYSTEM);
  135. //TCPServerWinsock::make_default();
  136. //StreamPeerWinsock::make_default();
  137. TCPServerWinsock::make_default();
  138. StreamPeerWinsock::make_default();
  139. PacketPeerUDPWinsock::make_default();
  140. mempool_static = new MemoryPoolStaticMalloc;
  141. #if 1
  142. mempool_dynamic = memnew(MemoryPoolDynamicStatic);
  143. #else
  144. #define DYNPOOL_SIZE 4 * 1024 * 1024
  145. void *buffer = malloc(DYNPOOL_SIZE);
  146. mempool_dynamic = memnew(MemoryPoolDynamicPrealloc(buffer, DYNPOOL_SIZE));
  147. #endif
  148. // We need to know how often the clock is updated
  149. if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
  150. ticks_per_second = 1000;
  151. // If timeAtGameStart is 0 then we get the time since
  152. // the start of the computer when we call GetGameTime()
  153. ticks_start = 0;
  154. ticks_start = get_ticks_usec();
  155. IP_Unix::make_default();
  156. cursor_shape = CURSOR_ARROW;
  157. }
  158. bool OSUWP::can_draw() const {
  159. return !minimized;
  160. };
  161. void OSUWP::set_gl_context(ContextEGL *p_context) {
  162. gl_context = p_context;
  163. };
  164. void OSUWP::screen_size_changed() {
  165. gl_context->reset();
  166. };
  167. void OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  168. main_loop = NULL;
  169. outside = true;
  170. gl_context->initialize();
  171. VideoMode vm;
  172. vm.width = gl_context->get_window_width();
  173. vm.height = gl_context->get_window_height();
  174. vm.resizable = false;
  175. ApplicationView ^ view = ApplicationView::GetForCurrentView();
  176. vm.fullscreen = view->IsFullScreenMode;
  177. view->SetDesiredBoundsMode(ApplicationViewBoundsMode::UseVisible);
  178. view->PreferredLaunchWindowingMode = ApplicationViewWindowingMode::PreferredLaunchViewSize;
  179. if (p_desired.fullscreen != view->IsFullScreenMode) {
  180. if (p_desired.fullscreen) {
  181. vm.fullscreen = view->TryEnterFullScreenMode();
  182. } else {
  183. view->ExitFullScreenMode();
  184. vm.fullscreen = false;
  185. }
  186. }
  187. Windows::Foundation::Size desired;
  188. desired.Width = p_desired.width;
  189. desired.Height = p_desired.height;
  190. view->PreferredLaunchViewSize = desired;
  191. if (view->TryResizeView(desired)) {
  192. vm.width = view->VisibleBounds.Width;
  193. vm.height = view->VisibleBounds.Height;
  194. }
  195. set_video_mode(vm);
  196. gl_context->make_current();
  197. rasterizer = memnew(RasterizerGLES2);
  198. visual_server = memnew(VisualServerRaster(rasterizer));
  199. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  200. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  201. }
  202. //
  203. physics_server = memnew(PhysicsServerSW);
  204. physics_server->init();
  205. physics_2d_server = memnew(Physics2DServerSW);
  206. physics_2d_server->init();
  207. visual_server->init();
  208. input = memnew(InputDefault);
  209. joypad = ref new JoypadUWP(input);
  210. joypad->register_events();
  211. AudioDriverManager::get_driver(p_audio_driver)->set_singleton();
  212. if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
  213. ERR_PRINT("Initializing audio failed.");
  214. }
  215. power_manager = memnew(PowerWinRT);
  216. managed_object->update_clipboard();
  217. Clipboard::ContentChanged += ref new EventHandler<Platform::Object ^>(managed_object, &ManagedType::on_clipboard_changed);
  218. accelerometer = Accelerometer::GetDefault();
  219. if (accelerometer != nullptr) {
  220. // 60 FPS
  221. accelerometer->ReportInterval = (1.0f / 60.0f) * 1000;
  222. accelerometer->ReadingChanged +=
  223. ref new TypedEventHandler<Accelerometer ^, AccelerometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_accelerometer_reading_changed);
  224. }
  225. magnetometer = Magnetometer::GetDefault();
  226. if (magnetometer != nullptr) {
  227. // 60 FPS
  228. magnetometer->ReportInterval = (1.0f / 60.0f) * 1000;
  229. magnetometer->ReadingChanged +=
  230. ref new TypedEventHandler<Magnetometer ^, MagnetometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_magnetometer_reading_changed);
  231. }
  232. gyrometer = Gyrometer::GetDefault();
  233. if (gyrometer != nullptr) {
  234. // 60 FPS
  235. gyrometer->ReportInterval = (1.0f / 60.0f) * 1000;
  236. gyrometer->ReadingChanged +=
  237. ref new TypedEventHandler<Gyrometer ^, GyrometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_gyroscope_reading_changed);
  238. }
  239. _ensure_data_dir();
  240. if (is_keep_screen_on())
  241. display_request->RequestActive();
  242. set_keep_screen_on(GLOBAL_DEF("display/keep_screen_on", true));
  243. }
  244. void OSUWP::set_clipboard(const String &p_text) {
  245. DataPackage ^ clip = ref new DataPackage();
  246. clip->RequestedOperation = DataPackageOperation::Copy;
  247. clip->SetText(ref new Platform::String((const wchar_t *)p_text.c_str()));
  248. Clipboard::SetContent(clip);
  249. };
  250. String OSUWP::get_clipboard() const {
  251. if (managed_object->clipboard != nullptr)
  252. return managed_object->clipboard->Data();
  253. else
  254. return "";
  255. };
  256. void OSUWP::input_event(InputEvent &p_event) {
  257. input->parse_input_event(p_event);
  258. if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index > 3) {
  259. //send release for mouse wheel
  260. p_event.mouse_button.pressed = false;
  261. input->parse_input_event(p_event);
  262. }
  263. };
  264. void OSUWP::delete_main_loop() {
  265. if (main_loop)
  266. memdelete(main_loop);
  267. main_loop = NULL;
  268. }
  269. void OSUWP::set_main_loop(MainLoop *p_main_loop) {
  270. input->set_main_loop(p_main_loop);
  271. main_loop = p_main_loop;
  272. }
  273. void OSUWP::finalize() {
  274. if (main_loop)
  275. memdelete(main_loop);
  276. main_loop = NULL;
  277. visual_server->finish();
  278. memdelete(visual_server);
  279. #ifdef OPENGL_ENABLED
  280. if (gl_context)
  281. memdelete(gl_context);
  282. #endif
  283. if (rasterizer)
  284. memdelete(rasterizer);
  285. /*
  286. if (debugger_connection_console) {
  287. memdelete(debugger_connection_console);
  288. }
  289. */
  290. memdelete(input);
  291. physics_server->finish();
  292. memdelete(physics_server);
  293. physics_2d_server->finish();
  294. memdelete(physics_2d_server);
  295. joypad = nullptr;
  296. }
  297. void OSUWP::finalize_core() {
  298. if (mempool_dynamic)
  299. memdelete(mempool_dynamic);
  300. delete mempool_static;
  301. }
  302. void OSUWP::vprint(const char *p_format, va_list p_list, bool p_stderr) {
  303. char buf[16384 + 1];
  304. int len = vsnprintf(buf, 16384, p_format, p_list);
  305. if (len <= 0)
  306. return;
  307. buf[len] = 0;
  308. int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, len, NULL, 0);
  309. if (wlen < 0)
  310. return;
  311. wchar_t *wbuf = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
  312. MultiByteToWideChar(CP_UTF8, 0, buf, len, wbuf, wlen);
  313. wbuf[wlen] = 0;
  314. if (p_stderr)
  315. fwprintf(stderr, L"%s", wbuf);
  316. else
  317. wprintf(L"%s", wbuf);
  318. free(wbuf);
  319. fflush(stdout);
  320. };
  321. void OSUWP::alert(const String &p_alert, const String &p_title) {
  322. Platform::String ^ alert = ref new Platform::String(p_alert.c_str());
  323. Platform::String ^ title = ref new Platform::String(p_title.c_str());
  324. MessageDialog ^ msg = ref new MessageDialog(alert, title);
  325. UICommand ^ close = ref new UICommand("Close", ref new UICommandInvokedHandler(managed_object, &OSUWP::ManagedType::alert_close));
  326. msg->Commands->Append(close);
  327. msg->DefaultCommandIndex = 0;
  328. managed_object->alert_close_handle = true;
  329. msg->ShowAsync();
  330. }
  331. void OSUWP::ManagedType::alert_close(IUICommand ^ command) {
  332. alert_close_handle = false;
  333. }
  334. void OSUWP::ManagedType::on_clipboard_changed(Platform::Object ^ sender, Platform::Object ^ ev) {
  335. update_clipboard();
  336. }
  337. void OSUWP::ManagedType::update_clipboard() {
  338. DataPackageView ^ data = Clipboard::GetContent();
  339. if (data->Contains(StandardDataFormats::Text)) {
  340. create_task(data->GetTextAsync()).then([this](Platform::String ^ clipboard_content) {
  341. this->clipboard = clipboard_content;
  342. });
  343. }
  344. }
  345. void OSUWP::ManagedType::on_accelerometer_reading_changed(Accelerometer ^ sender, AccelerometerReadingChangedEventArgs ^ args) {
  346. AccelerometerReading ^ reading = args->Reading;
  347. os->input->set_accelerometer(Vector3(
  348. reading->AccelerationX,
  349. reading->AccelerationY,
  350. reading->AccelerationZ));
  351. }
  352. void OSUWP::ManagedType::on_magnetometer_reading_changed(Magnetometer ^ sender, MagnetometerReadingChangedEventArgs ^ args) {
  353. MagnetometerReading ^ reading = args->Reading;
  354. os->input->set_magnetometer(Vector3(
  355. reading->MagneticFieldX,
  356. reading->MagneticFieldY,
  357. reading->MagneticFieldZ));
  358. }
  359. void OSUWP::ManagedType::on_gyroscope_reading_changed(Gyrometer ^ sender, GyrometerReadingChangedEventArgs ^ args) {
  360. GyrometerReading ^ reading = args->Reading;
  361. os->input->set_magnetometer(Vector3(
  362. reading->AngularVelocityX,
  363. reading->AngularVelocityY,
  364. reading->AngularVelocityZ));
  365. }
  366. void OSUWP::set_mouse_mode(MouseMode p_mode) {
  367. if (p_mode == MouseMode::MOUSE_MODE_CAPTURED) {
  368. CoreWindow::GetForCurrentThread()->SetPointerCapture();
  369. } else {
  370. CoreWindow::GetForCurrentThread()->ReleasePointerCapture();
  371. }
  372. if (p_mode == MouseMode::MOUSE_MODE_CAPTURED || p_mode == MouseMode::MOUSE_MODE_HIDDEN) {
  373. CoreWindow::GetForCurrentThread()->PointerCursor = nullptr;
  374. } else {
  375. CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
  376. }
  377. mouse_mode = p_mode;
  378. SetEvent(mouse_mode_changed);
  379. }
  380. OSUWP::MouseMode OSUWP::get_mouse_mode() const {
  381. return mouse_mode;
  382. }
  383. Point2 OSUWP::get_mouse_position() const {
  384. return Point2(old_x, old_y);
  385. }
  386. int OSUWP::get_mouse_button_state() const {
  387. return last_button_state;
  388. }
  389. void OSUWP::set_window_title(const String &p_title) {
  390. }
  391. void OSUWP::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  392. video_mode = p_video_mode;
  393. }
  394. OS::VideoMode OSUWP::get_video_mode(int p_screen) const {
  395. return video_mode;
  396. }
  397. void OSUWP::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  398. }
  399. void OSUWP::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
  400. const char *err_details;
  401. if (p_rationale && p_rationale[0])
  402. err_details = p_rationale;
  403. else
  404. err_details = p_code;
  405. switch (p_type) {
  406. case ERR_ERROR:
  407. print("ERROR: %s: %s\n", p_function, err_details);
  408. print(" At: %s:%i\n", p_file, p_line);
  409. break;
  410. case ERR_WARNING:
  411. print("WARNING: %s: %s\n", p_function, err_details);
  412. print(" At: %s:%i\n", p_file, p_line);
  413. break;
  414. case ERR_SCRIPT:
  415. print("SCRIPT ERROR: %s: %s\n", p_function, err_details);
  416. print(" At: %s:%i\n", p_file, p_line);
  417. break;
  418. }
  419. }
  420. String OSUWP::get_name() {
  421. return "UWP";
  422. }
  423. OS::Date OSUWP::get_date(bool utc) const {
  424. SYSTEMTIME systemtime;
  425. if (utc)
  426. GetSystemTime(&systemtime);
  427. else
  428. GetLocalTime(&systemtime);
  429. Date date;
  430. date.day = systemtime.wDay;
  431. date.month = Month(systemtime.wMonth);
  432. date.weekday = Weekday(systemtime.wDayOfWeek);
  433. date.year = systemtime.wYear;
  434. date.dst = false;
  435. return date;
  436. }
  437. OS::Time OSUWP::get_time(bool utc) const {
  438. SYSTEMTIME systemtime;
  439. if (utc)
  440. GetSystemTime(&systemtime);
  441. else
  442. GetLocalTime(&systemtime);
  443. Time time;
  444. time.hour = systemtime.wHour;
  445. time.min = systemtime.wMinute;
  446. time.sec = systemtime.wSecond;
  447. return time;
  448. }
  449. OS::TimeZoneInfo OSUWP::get_time_zone_info() const {
  450. TIME_ZONE_INFORMATION info;
  451. bool daylight = false;
  452. if (GetTimeZoneInformation(&info) == TIME_ZONE_ID_DAYLIGHT)
  453. daylight = true;
  454. TimeZoneInfo ret;
  455. if (daylight) {
  456. ret.name = info.DaylightName;
  457. } else {
  458. ret.name = info.StandardName;
  459. }
  460. ret.bias = info.Bias;
  461. return ret;
  462. }
  463. uint64_t OSUWP::get_unix_time() const {
  464. FILETIME ft;
  465. SYSTEMTIME st;
  466. GetSystemTime(&st);
  467. SystemTimeToFileTime(&st, &ft);
  468. SYSTEMTIME ep;
  469. ep.wYear = 1970;
  470. ep.wMonth = 1;
  471. ep.wDayOfWeek = 4;
  472. ep.wDay = 1;
  473. ep.wHour = 0;
  474. ep.wMinute = 0;
  475. ep.wSecond = 0;
  476. ep.wMilliseconds = 0;
  477. FILETIME fep;
  478. SystemTimeToFileTime(&ep, &fep);
  479. return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
  480. };
  481. void OSUWP::delay_usec(uint32_t p_usec) const {
  482. int msec = p_usec < 1000 ? 1 : p_usec / 1000;
  483. // no Sleep()
  484. WaitForSingleObjectEx(GetCurrentThread(), msec, false);
  485. }
  486. uint64_t OSUWP::get_ticks_usec() const {
  487. uint64_t ticks;
  488. uint64_t time;
  489. // This is the number of clock ticks since start
  490. QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
  491. // Divide by frequency to get the time in seconds
  492. time = ticks * 1000000L / ticks_per_second;
  493. // Subtract the time at game start to get
  494. // the time since the game started
  495. time -= ticks_start;
  496. return time;
  497. }
  498. void OSUWP::process_events() {
  499. joypad->process_controllers();
  500. process_key_events();
  501. }
  502. void OSUWP::process_key_events() {
  503. for (int i = 0; i < key_event_pos; i++) {
  504. KeyEvent &kev = key_event_buffer[i];
  505. InputEvent iev;
  506. iev.type = InputEvent::KEY;
  507. iev.key.mod = kev.mod_state;
  508. iev.key.echo = kev.echo;
  509. iev.key.scancode = kev.scancode;
  510. iev.key.unicode = kev.unicode;
  511. iev.key.pressed = kev.pressed;
  512. input_event(iev);
  513. }
  514. key_event_pos = 0;
  515. }
  516. void OSUWP::queue_key_event(KeyEvent &p_event) {
  517. // This merges Char events with the previous Key event, so
  518. // the unicode can be retrieved without sending duplicate events.
  519. if (p_event.type == KeyEvent::MessageType::CHAR_EVENT_MESSAGE && key_event_pos > 0) {
  520. KeyEvent &old = key_event_buffer[key_event_pos - 1];
  521. ERR_FAIL_COND(old.type != KeyEvent::MessageType::KEY_EVENT_MESSAGE);
  522. key_event_buffer[key_event_pos - 1].unicode = p_event.unicode;
  523. return;
  524. }
  525. ERR_FAIL_COND(key_event_pos >= KEY_EVENT_BUFFER_SIZE);
  526. key_event_buffer[key_event_pos++] = p_event;
  527. }
  528. void OSUWP::set_cursor_shape(CursorShape p_shape) {
  529. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  530. if (cursor_shape == p_shape)
  531. return;
  532. static const CoreCursorType uwp_cursors[CURSOR_MAX] = {
  533. CoreCursorType::Arrow,
  534. CoreCursorType::IBeam,
  535. CoreCursorType::Hand,
  536. CoreCursorType::Cross,
  537. CoreCursorType::Wait,
  538. CoreCursorType::Wait,
  539. CoreCursorType::Arrow,
  540. CoreCursorType::Arrow,
  541. CoreCursorType::UniversalNo,
  542. CoreCursorType::SizeNorthSouth,
  543. CoreCursorType::SizeWestEast,
  544. CoreCursorType::SizeNortheastSouthwest,
  545. CoreCursorType::SizeNorthwestSoutheast,
  546. CoreCursorType::SizeAll,
  547. CoreCursorType::SizeNorthSouth,
  548. CoreCursorType::SizeWestEast,
  549. CoreCursorType::Help
  550. };
  551. CoreWindow::GetForCurrentThread()->PointerCursor = ref new CoreCursor(uwp_cursors[p_shape], 0);
  552. cursor_shape = p_shape;
  553. }
  554. Error OSUWP::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode) {
  555. return FAILED;
  556. };
  557. Error OSUWP::kill(const ProcessID &p_pid) {
  558. return FAILED;
  559. };
  560. Error OSUWP::set_cwd(const String &p_cwd) {
  561. return FAILED;
  562. }
  563. String OSUWP::get_executable_path() const {
  564. return "";
  565. }
  566. void OSUWP::set_icon(const Image &p_icon) {
  567. }
  568. bool OSUWP::has_environment(const String &p_var) const {
  569. return false;
  570. };
  571. String OSUWP::get_environment(const String &p_var) const {
  572. return "";
  573. };
  574. String OSUWP::get_stdin_string(bool p_block) {
  575. return String();
  576. }
  577. void OSUWP::move_window_to_foreground() {
  578. }
  579. Error OSUWP::shell_open(String p_uri) {
  580. return FAILED;
  581. }
  582. String OSUWP::get_locale() const {
  583. #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP // this should work on phone 8.1, but it doesn't
  584. return "en";
  585. #else
  586. Platform::String ^ language = Windows::Globalization::Language::CurrentInputMethodLanguageTag;
  587. return String(language->Data()).replace("-", "_");
  588. #endif
  589. }
  590. void OSUWP::release_rendering_thread() {
  591. gl_context->release_current();
  592. }
  593. void OSUWP::make_rendering_thread() {
  594. gl_context->make_current();
  595. }
  596. void OSUWP::swap_buffers() {
  597. gl_context->swap_buffers();
  598. }
  599. bool OSUWP::has_touchscreen_ui_hint() const {
  600. TouchCapabilities ^ tc = ref new TouchCapabilities();
  601. return tc->TouchPresent != 0 || UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
  602. }
  603. bool OSUWP::has_virtual_keyboard() const {
  604. return UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
  605. }
  606. void OSUWP::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
  607. InputPane ^ pane = InputPane::GetForCurrentView();
  608. pane->TryShow();
  609. }
  610. void OSUWP::hide_virtual_keyboard() {
  611. InputPane ^ pane = InputPane::GetForCurrentView();
  612. pane->TryHide();
  613. }
  614. void OSUWP::run() {
  615. if (!main_loop)
  616. return;
  617. main_loop->init();
  618. uint64_t last_ticks = get_ticks_usec();
  619. int frames = 0;
  620. uint64_t frame = 0;
  621. while (!force_quit) {
  622. CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
  623. if (managed_object->alert_close_handle) continue;
  624. process_events(); // get rid of pending events
  625. if (Main::iteration() == true)
  626. break;
  627. };
  628. main_loop->finish();
  629. }
  630. MainLoop *OSUWP::get_main_loop() const {
  631. return main_loop;
  632. }
  633. String OSUWP::get_data_dir() const {
  634. Windows::Storage::StorageFolder ^ data_folder = Windows::Storage::ApplicationData::Current->LocalFolder;
  635. return String(data_folder->Path->Data()).replace("\\", "/");
  636. }
  637. PowerState OSWinrt::get_power_state() {
  638. return power_manager->get_power_state();
  639. }
  640. int OSWinrt::get_power_seconds_left() {
  641. return power_manager->get_power_seconds_left();
  642. }
  643. int OSWinrt::get_power_percent_left() {
  644. return power_manager->get_power_percent_left();
  645. }
  646. OSUWP::OSUWP() {
  647. key_event_pos = 0;
  648. force_quit = false;
  649. alt_mem = false;
  650. gr_mem = false;
  651. shift_mem = false;
  652. control_mem = false;
  653. meta_mem = false;
  654. minimized = false;
  655. pressrc = 0;
  656. old_invalid = true;
  657. mouse_mode = MOUSE_MODE_VISIBLE;
  658. #ifdef STDOUT_FILE
  659. stdo = fopen("stdout.txt", "wb");
  660. #endif
  661. gl_context = NULL;
  662. display_request = ref new Windows::System::Display::DisplayRequest();
  663. managed_object = ref new ManagedType;
  664. managed_object->os = this;
  665. mouse_mode_changed = CreateEvent(NULL, TRUE, FALSE, L"os_mouse_mode_changed");
  666. AudioDriverManager::add_driver(&audio_driver);
  667. }
  668. OSUWP::~OSUWP() {
  669. #ifdef STDOUT_FILE
  670. fclose(stdo);
  671. #endif
  672. }