os.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. /**************************************************************************/
  2. /* os.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.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/json.h"
  35. #include "core/os/midi_driver.h"
  36. #include "core/version_generated.gen.h"
  37. #include <cstdarg>
  38. #ifdef MINGW_ENABLED
  39. #define MINGW_STDTHREAD_REDUNDANCY_WARNING
  40. #include "thirdparty/mingw-std-threads/mingw.thread.h"
  41. #define THREADING_NAMESPACE mingw_stdthread
  42. #else
  43. #include <thread>
  44. #define THREADING_NAMESPACE std
  45. #endif
  46. OS *OS::singleton = nullptr;
  47. uint64_t OS::target_ticks = 0;
  48. OS *OS::get_singleton() {
  49. return singleton;
  50. }
  51. bool OS::prefer_meta_over_ctrl() {
  52. #if defined(MACOS_ENABLED) || defined(APPLE_EMBEDDED_ENABLED)
  53. return true;
  54. #elif defined(WEB_ENABLED)
  55. return singleton->has_feature("web_macos") || singleton->has_feature("web_ios");
  56. #else
  57. return false;
  58. #endif
  59. }
  60. uint64_t OS::get_ticks_msec() const {
  61. return get_ticks_usec() / 1000ULL;
  62. }
  63. double OS::get_unix_time() const {
  64. return 0;
  65. }
  66. void OS::_set_logger(CompositeLogger *p_logger) {
  67. if (_logger) {
  68. memdelete(_logger);
  69. }
  70. _logger = p_logger;
  71. }
  72. void OS::add_logger(Logger *p_logger) {
  73. if (!_logger) {
  74. Vector<Logger *> loggers;
  75. loggers.push_back(p_logger);
  76. _logger = memnew(CompositeLogger(loggers));
  77. } else {
  78. _logger->add_logger(p_logger);
  79. }
  80. }
  81. String OS::get_identifier() const {
  82. return get_name().to_lower();
  83. }
  84. void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, bool p_editor_notify, Logger::ErrorType p_type, const Vector<Ref<ScriptBacktrace>> &p_script_backtraces) {
  85. if (!_stderr_enabled) {
  86. return;
  87. }
  88. if (_logger) {
  89. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type, p_script_backtraces);
  90. }
  91. }
  92. void OS::print(const char *p_format, ...) {
  93. if (!_stdout_enabled) {
  94. return;
  95. }
  96. va_list argp;
  97. va_start(argp, p_format);
  98. if (_logger) {
  99. _logger->logv(p_format, argp, false);
  100. }
  101. va_end(argp);
  102. }
  103. void OS::print_rich(const char *p_format, ...) {
  104. if (!_stdout_enabled) {
  105. return;
  106. }
  107. va_list argp;
  108. va_start(argp, p_format);
  109. if (_logger) {
  110. _logger->logv(p_format, argp, false);
  111. }
  112. va_end(argp);
  113. }
  114. void OS::printerr(const char *p_format, ...) {
  115. if (!_stderr_enabled) {
  116. return;
  117. }
  118. va_list argp;
  119. va_start(argp, p_format);
  120. if (_logger) {
  121. _logger->logv(p_format, argp, true);
  122. }
  123. va_end(argp);
  124. }
  125. void OS::alert(const String &p_alert, const String &p_title) {
  126. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  127. }
  128. void OS::set_low_processor_usage_mode(bool p_enabled) {
  129. low_processor_usage_mode = p_enabled;
  130. }
  131. bool OS::is_in_low_processor_usage_mode() const {
  132. return low_processor_usage_mode;
  133. }
  134. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  135. low_processor_usage_mode_sleep_usec = p_usec;
  136. }
  137. int OS::get_low_processor_usage_mode_sleep_usec() const {
  138. return low_processor_usage_mode_sleep_usec;
  139. }
  140. void OS::set_delta_smoothing(bool p_enabled) {
  141. _delta_smoothing_enabled = p_enabled;
  142. }
  143. bool OS::is_delta_smoothing_enabled() const {
  144. return _delta_smoothing_enabled;
  145. }
  146. String OS::get_executable_path() const {
  147. return _execpath;
  148. }
  149. int OS::get_process_id() const {
  150. return -1;
  151. }
  152. bool OS::is_stdout_verbose() const {
  153. return _verbose_stdout;
  154. }
  155. bool OS::is_stdout_debug_enabled() const {
  156. return _debug_stdout;
  157. }
  158. bool OS::is_stdout_enabled() const {
  159. return _stdout_enabled;
  160. }
  161. bool OS::is_stderr_enabled() const {
  162. return _stderr_enabled;
  163. }
  164. void OS::set_stdout_enabled(bool p_enabled) {
  165. _stdout_enabled = p_enabled;
  166. }
  167. void OS::set_stderr_enabled(bool p_enabled) {
  168. _stderr_enabled = p_enabled;
  169. }
  170. String OS::multibyte_to_string(const String &p_encoding, const PackedByteArray &p_array) const {
  171. return String();
  172. }
  173. PackedByteArray OS::string_to_multibyte(const String &p_encoding, const String &p_string) const {
  174. return PackedByteArray();
  175. }
  176. int OS::get_exit_code() const {
  177. return _exit_code;
  178. }
  179. void OS::set_exit_code(int p_code) {
  180. _exit_code = p_code;
  181. }
  182. String OS::get_locale() const {
  183. return "en";
  184. }
  185. // Non-virtual helper to extract the 2 or 3-letter language code from
  186. // `get_locale()` in a way that's consistent for all platforms.
  187. String OS::get_locale_language() const {
  188. return get_locale().left(3).remove_char('_');
  189. }
  190. // Embedded PCK offset.
  191. uint64_t OS::get_embedded_pck_offset() const {
  192. return 0;
  193. }
  194. // Default boot screen rect scale mode is "Keep Aspect Centered"
  195. Rect2 OS::calculate_boot_screen_rect(const Size2 &p_window_size, const Size2 &p_imgrect_size) const {
  196. Rect2 screenrect;
  197. if (p_window_size.width > p_window_size.height) {
  198. // Scale horizontally.
  199. screenrect.size.y = p_window_size.height;
  200. screenrect.size.x = p_imgrect_size.x * p_window_size.height / p_imgrect_size.y;
  201. screenrect.position.x = (p_window_size.width - screenrect.size.x) / 2;
  202. } else {
  203. // Scale vertically.
  204. screenrect.size.x = p_window_size.width;
  205. screenrect.size.y = p_imgrect_size.y * p_window_size.width / p_imgrect_size.x;
  206. screenrect.position.y = (p_window_size.height - screenrect.size.y) / 2;
  207. }
  208. return screenrect;
  209. }
  210. // Helper function to ensure that a dir name/path will be valid on the OS
  211. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_paths) const {
  212. String safe_dir_name = p_dir_name;
  213. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  214. if (p_allow_paths) {
  215. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  216. invalid_chars.push_back("..");
  217. safe_dir_name = safe_dir_name.replace_char('\\', '/').replace("//", "/").strip_edges();
  218. } else {
  219. invalid_chars.push_back("/");
  220. invalid_chars.push_back("\\");
  221. safe_dir_name = safe_dir_name.strip_edges();
  222. // These directory names are invalid.
  223. if (safe_dir_name == ".") {
  224. safe_dir_name = "dot";
  225. } else if (safe_dir_name == "..") {
  226. safe_dir_name = "twodots";
  227. }
  228. }
  229. for (int i = 0; i < invalid_chars.size(); i++) {
  230. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  231. }
  232. // Trim trailing periods from the returned value as it's not valid for folder names on Windows.
  233. // This check is still applied on non-Windows platforms so the returned value is consistent across platforms.
  234. return safe_dir_name.rstrip(".");
  235. }
  236. // Path to data, config, cache, etc. OS-specific folders
  237. // Get properly capitalized engine name for system paths
  238. String OS::get_godot_dir_name() const {
  239. // Default to lowercase, so only override when different case is needed
  240. return String(GODOT_VERSION_SHORT_NAME).to_lower();
  241. }
  242. // OS equivalent of XDG_DATA_HOME
  243. String OS::get_data_path() const {
  244. return ".";
  245. }
  246. // OS equivalent of XDG_CONFIG_HOME
  247. String OS::get_config_path() const {
  248. return ".";
  249. }
  250. // OS equivalent of XDG_CACHE_HOME
  251. String OS::get_cache_path() const {
  252. return ".";
  253. }
  254. String OS::get_temp_path() const {
  255. return ".";
  256. }
  257. // Path to macOS .app bundle resources
  258. String OS::get_bundle_resource_dir() const {
  259. return ".";
  260. }
  261. // Path to macOS .app bundle embedded icon (.icns file).
  262. String OS::get_bundle_icon_path() const {
  263. return String();
  264. }
  265. // Name of macOS .app bundle embedded icon (Liquid Glass asset name).
  266. String OS::get_bundle_icon_name() const {
  267. return String();
  268. }
  269. // OS specific path for user://
  270. String OS::get_user_data_dir(const String &p_user_dir) const {
  271. return ".";
  272. }
  273. String OS::get_user_data_dir() const {
  274. String appname = get_safe_dir_name(GLOBAL_GET("application/config/name"));
  275. if (!appname.is_empty()) {
  276. bool use_custom_dir = GLOBAL_GET("application/config/use_custom_user_dir");
  277. if (use_custom_dir) {
  278. String custom_dir = get_safe_dir_name(GLOBAL_GET("application/config/custom_user_dir_name"), true);
  279. if (custom_dir.is_empty()) {
  280. custom_dir = appname;
  281. }
  282. return get_user_data_dir(custom_dir);
  283. } else {
  284. return get_user_data_dir(get_godot_dir_name().path_join("app_userdata").path_join(appname));
  285. }
  286. } else {
  287. return get_user_data_dir(get_godot_dir_name().path_join("app_userdata").path_join("[unnamed project]"));
  288. }
  289. }
  290. // Absolute path to res://
  291. String OS::get_resource_dir() const {
  292. return ProjectSettings::get_singleton()->get_resource_path();
  293. }
  294. // Access system-specific dirs like Documents, Downloads, etc.
  295. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  296. return ".";
  297. }
  298. void OS::create_lock_file() {
  299. if (Engine::get_singleton()->is_recovery_mode_hint()) {
  300. return;
  301. }
  302. String lock_file_path = get_user_data_dir().path_join(".recovery_mode_lock");
  303. Ref<FileAccess> lock_file = FileAccess::open(lock_file_path, FileAccess::WRITE);
  304. if (lock_file.is_valid()) {
  305. lock_file->close();
  306. }
  307. }
  308. void OS::remove_lock_file() {
  309. String lock_file_path = get_user_data_dir().path_join(".recovery_mode_lock");
  310. DirAccess::remove_absolute(lock_file_path);
  311. }
  312. Error OS::shell_open(const String &p_uri) {
  313. return ERR_UNAVAILABLE;
  314. }
  315. Error OS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  316. p_path = p_path.trim_prefix("file://");
  317. if (!DirAccess::dir_exists_absolute(p_path)) {
  318. p_path = p_path.get_base_dir();
  319. }
  320. p_path = String("file://") + p_path;
  321. return shell_open(p_path);
  322. }
  323. // implement these with the canvas?
  324. uint64_t OS::get_static_memory_usage() const {
  325. return Memory::get_mem_usage();
  326. }
  327. uint64_t OS::get_static_memory_peak_usage() const {
  328. return Memory::get_mem_max_usage();
  329. }
  330. Error OS::set_cwd(const String &p_cwd) {
  331. return ERR_CANT_OPEN;
  332. }
  333. String OS::get_cwd() const {
  334. return ".";
  335. }
  336. Dictionary OS::get_memory_info() const {
  337. Dictionary meminfo;
  338. meminfo["physical"] = -1;
  339. meminfo["free"] = -1;
  340. meminfo["available"] = -1;
  341. meminfo["stack"] = -1;
  342. return meminfo;
  343. }
  344. void OS::yield() {
  345. }
  346. void OS::ensure_user_data_dir() {
  347. String dd = get_user_data_dir();
  348. if (DirAccess::exists(dd)) {
  349. return;
  350. }
  351. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  352. Error err = da->make_dir_recursive(dd);
  353. ERR_FAIL_COND_MSG(err != OK, vformat("Error attempting to create data dir: %s.", dd));
  354. }
  355. String OS::get_model_name() const {
  356. return "GenericDevice";
  357. }
  358. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
  359. _execpath = String::utf8(p_execpath);
  360. _cmdline = p_args;
  361. _user_args = p_user_args;
  362. }
  363. String OS::get_unique_id() const {
  364. return "";
  365. }
  366. int OS::get_processor_count() const {
  367. return THREADING_NAMESPACE::thread::hardware_concurrency();
  368. }
  369. String OS::get_processor_name() const {
  370. return "";
  371. }
  372. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  373. has_server_feature_callback = p_callback;
  374. }
  375. bool OS::has_feature(const String &p_feature) {
  376. // Feature tags are always lowercase for consistency.
  377. if (p_feature == get_identifier()) {
  378. return true;
  379. }
  380. if (p_feature == "movie") {
  381. return _writing_movie;
  382. }
  383. #ifdef DEBUG_ENABLED
  384. if (p_feature == "debug") {
  385. return true;
  386. }
  387. #endif // DEBUG_ENABLED
  388. #ifdef TOOLS_ENABLED
  389. if (p_feature == "editor") {
  390. return true;
  391. }
  392. if (p_feature == "editor_hint") {
  393. return _in_editor;
  394. } else if (p_feature == "editor_runtime") {
  395. return !_in_editor;
  396. } else if (p_feature == "embedded_in_editor") {
  397. return _embedded_in_editor;
  398. }
  399. #else
  400. if (p_feature == "template") {
  401. return true;
  402. }
  403. #ifdef DEBUG_ENABLED
  404. if (p_feature == "template_debug") {
  405. return true;
  406. }
  407. #else
  408. if (p_feature == "template_release" || p_feature == "release") {
  409. return true;
  410. }
  411. #endif // DEBUG_ENABLED
  412. #endif // TOOLS_ENABLED
  413. #ifdef REAL_T_IS_DOUBLE
  414. if (p_feature == "double") {
  415. return true;
  416. }
  417. #else
  418. if (p_feature == "single") {
  419. return true;
  420. }
  421. #endif // REAL_T_IS_DOUBLE
  422. if (sizeof(void *) == 8 && p_feature == "64") {
  423. return true;
  424. }
  425. if (sizeof(void *) == 4 && p_feature == "32") {
  426. return true;
  427. }
  428. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
  429. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
  430. #if defined(MACOS_ENABLED)
  431. if (p_feature == "universal") {
  432. return true;
  433. }
  434. #endif
  435. if (p_feature == "x86_64") {
  436. return true;
  437. }
  438. #elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
  439. if (p_feature == "x86_32") {
  440. return true;
  441. }
  442. #endif
  443. if (p_feature == "x86") {
  444. return true;
  445. }
  446. #elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  447. #if defined(__aarch64__) || defined(_M_ARM64)
  448. #if defined(MACOS_ENABLED)
  449. if (p_feature == "universal") {
  450. return true;
  451. }
  452. #endif
  453. if (p_feature == "arm64") {
  454. return true;
  455. }
  456. #elif defined(__arm__) || defined(_M_ARM)
  457. if (p_feature == "arm32") {
  458. return true;
  459. }
  460. #endif
  461. #if defined(__ARM_ARCH_7A__)
  462. if (p_feature == "armv7a" || p_feature == "armv7") {
  463. return true;
  464. }
  465. #endif
  466. #if defined(__ARM_ARCH_7S__)
  467. if (p_feature == "armv7s" || p_feature == "armv7") {
  468. return true;
  469. }
  470. #endif
  471. if (p_feature == "arm") {
  472. return true;
  473. }
  474. #elif defined(__riscv)
  475. #if __riscv_xlen == 8
  476. if (p_feature == "rv64") {
  477. return true;
  478. }
  479. #endif
  480. if (p_feature == "riscv") {
  481. return true;
  482. }
  483. #elif defined(__powerpc__)
  484. #if defined(__powerpc64__)
  485. if (p_feature == "ppc64") {
  486. return true;
  487. }
  488. #endif
  489. if (p_feature == "ppc") {
  490. return true;
  491. }
  492. #elif defined(__wasm__)
  493. #if defined(__wasm64__)
  494. if (p_feature == "wasm64") {
  495. return true;
  496. }
  497. #elif defined(__wasm32__)
  498. if (p_feature == "wasm32") {
  499. return true;
  500. }
  501. #endif
  502. if (p_feature == "wasm") {
  503. return true;
  504. }
  505. #elif defined(__loongarch64)
  506. if (p_feature == "loongarch64") {
  507. return true;
  508. }
  509. #endif
  510. #if defined(IOS_SIMULATOR) || defined(VISIONOS_SIMULATOR)
  511. if (p_feature == "simulator") {
  512. return true;
  513. }
  514. #endif
  515. if (p_feature == "threads") {
  516. #ifdef THREADS_ENABLED
  517. return true;
  518. #else
  519. return false;
  520. #endif
  521. }
  522. if (p_feature == "nothreads") {
  523. #ifdef THREADS_ENABLED
  524. return false;
  525. #else
  526. return true;
  527. #endif
  528. }
  529. if (_check_internal_feature_support(p_feature)) {
  530. return true;
  531. }
  532. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  533. return true;
  534. }
  535. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  536. return true;
  537. }
  538. return false;
  539. }
  540. bool OS::is_sandboxed() const {
  541. return false;
  542. }
  543. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  544. restart_on_exit = p_restart;
  545. restart_commandline = p_restart_arguments;
  546. }
  547. bool OS::is_restart_on_exit_set() const {
  548. return restart_on_exit;
  549. }
  550. List<String> OS::get_restart_on_exit_arguments() const {
  551. return restart_commandline;
  552. }
  553. PackedStringArray OS::get_connected_midi_inputs() {
  554. if (MIDIDriver::get_singleton()) {
  555. return MIDIDriver::get_singleton()->get_connected_inputs();
  556. }
  557. PackedStringArray list;
  558. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  559. }
  560. void OS::open_midi_inputs() {
  561. if (MIDIDriver::get_singleton()) {
  562. MIDIDriver::get_singleton()->open();
  563. } else {
  564. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  565. }
  566. }
  567. void OS::close_midi_inputs() {
  568. if (MIDIDriver::get_singleton()) {
  569. MIDIDriver::get_singleton()->close();
  570. } else {
  571. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  572. }
  573. }
  574. uint64_t OS::get_frame_delay(bool p_can_draw) const {
  575. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  576. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  577. // previous frame time into account for a smoother result.
  578. uint64_t dynamic_delay = 0;
  579. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  580. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  581. }
  582. const int max_fps = Engine::get_singleton()->get_max_fps();
  583. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  584. // Override the low processor usage mode sleep delay if the target FPS is lower.
  585. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  586. }
  587. return frame_delay + dynamic_delay;
  588. }
  589. void OS::add_frame_delay(bool p_can_draw, bool p_wake_for_events) {
  590. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  591. if (frame_delay) {
  592. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  593. // the actual frame time into account.
  594. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  595. // to use this as a FPS limiter.
  596. delay_usec(frame_delay * 1000);
  597. }
  598. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  599. // previous frame time into account for a smoother result.
  600. uint64_t dynamic_delay = 0;
  601. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  602. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  603. }
  604. const int max_fps = Engine::get_singleton()->get_max_fps();
  605. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  606. // Override the low processor usage mode sleep delay if the target FPS is lower.
  607. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  608. }
  609. if (dynamic_delay > 0) {
  610. target_ticks += dynamic_delay;
  611. uint64_t current_ticks = get_ticks_usec();
  612. if (current_ticks < target_ticks) {
  613. delay_usec(target_ticks - current_ticks);
  614. }
  615. current_ticks = get_ticks_usec();
  616. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  617. }
  618. }
  619. Error OS::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
  620. return default_rfs.synchronize_with_server(p_server_host, p_port, p_password, r_project_path);
  621. }
  622. OS::PreferredTextureFormat OS::get_preferred_texture_format() const {
  623. #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  624. return PREFERRED_TEXTURE_FORMAT_ETC2_ASTC; // By rule, ARM hardware uses ETC texture compression.
  625. #elif defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
  626. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // By rule, X86 hardware prefers S3TC and derivatives.
  627. #else
  628. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // Override in platform if needed.
  629. #endif
  630. }
  631. void OS::set_use_benchmark(bool p_use_benchmark) {
  632. use_benchmark = p_use_benchmark;
  633. }
  634. bool OS::is_use_benchmark_set() {
  635. return use_benchmark;
  636. }
  637. void OS::set_benchmark_file(const String &p_benchmark_file) {
  638. benchmark_file = p_benchmark_file;
  639. }
  640. String OS::get_benchmark_file() {
  641. return benchmark_file;
  642. }
  643. void OS::benchmark_begin_measure(const String &p_context, const String &p_what) {
  644. #ifdef TOOLS_ENABLED
  645. Pair<String, String> mark_key(p_context, p_what);
  646. ERR_FAIL_COND_MSG(benchmark_marks_from.has(mark_key), vformat("Benchmark key '%s:%s' already exists.", p_context, p_what));
  647. benchmark_marks_from[mark_key] = OS::get_singleton()->get_ticks_usec();
  648. #endif
  649. }
  650. void OS::benchmark_end_measure(const String &p_context, const String &p_what) {
  651. #ifdef TOOLS_ENABLED
  652. Pair<String, String> mark_key(p_context, p_what);
  653. ERR_FAIL_COND_MSG(!benchmark_marks_from.has(mark_key), vformat("Benchmark key '%s:%s' doesn't exist.", p_context, p_what));
  654. uint64_t total = OS::get_singleton()->get_ticks_usec() - benchmark_marks_from[mark_key];
  655. double total_f = double(total) / double(1000000);
  656. benchmark_marks_final[mark_key] = total_f;
  657. #endif
  658. }
  659. void OS::benchmark_dump() {
  660. #ifdef TOOLS_ENABLED
  661. if (!use_benchmark) {
  662. return;
  663. }
  664. if (!benchmark_file.is_empty()) {
  665. Ref<FileAccess> f = FileAccess::open(benchmark_file, FileAccess::WRITE);
  666. if (f.is_valid()) {
  667. Dictionary benchmark_marks;
  668. for (const KeyValue<Pair<String, String>, double> &E : benchmark_marks_final) {
  669. const String mark_key = vformat("[%s] %s", E.key.first, E.key.second);
  670. benchmark_marks[mark_key] = E.value;
  671. }
  672. Ref<JSON> json;
  673. json.instantiate();
  674. f->store_string(json->stringify(benchmark_marks, "\t", false, true));
  675. }
  676. } else {
  677. HashMap<String, String> results;
  678. for (const KeyValue<Pair<String, String>, double> &E : benchmark_marks_final) {
  679. if (E.key.first == "Startup" && !results.has(E.key.first)) {
  680. results.insert(E.key.first, "", true); // Hack to make sure "Startup" always comes first.
  681. }
  682. results[E.key.first] += vformat("\t\t- %s: %.3f msec.\n", E.key.second, (E.value * 1000));
  683. }
  684. print_line("BENCHMARK:");
  685. for (const KeyValue<String, String> &E : results) {
  686. print_line(vformat("\t[%s]\n%s", E.key, E.value));
  687. }
  688. }
  689. #endif
  690. }
  691. OS::OS() {
  692. singleton = this;
  693. Vector<Logger *> loggers;
  694. loggers.push_back(memnew(StdLogger));
  695. _set_logger(memnew(CompositeLogger(loggers)));
  696. }
  697. OS::~OS() {
  698. if (_logger) {
  699. memdelete(_logger);
  700. }
  701. singleton = nullptr;
  702. }