os.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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/input/input.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/json.h"
  36. #include "core/os/midi_driver.h"
  37. #include "core/version_generated.gen.h"
  38. #include <stdarg.h>
  39. #include <thread>
  40. OS *OS::singleton = nullptr;
  41. uint64_t OS::target_ticks = 0;
  42. OS *OS::get_singleton() {
  43. return singleton;
  44. }
  45. uint64_t OS::get_ticks_msec() const {
  46. return get_ticks_usec() / 1000ULL;
  47. }
  48. double OS::get_unix_time() const {
  49. return 0;
  50. }
  51. void OS::_set_logger(CompositeLogger *p_logger) {
  52. if (_logger) {
  53. memdelete(_logger);
  54. }
  55. _logger = p_logger;
  56. }
  57. void OS::add_logger(Logger *p_logger) {
  58. if (!_logger) {
  59. Vector<Logger *> loggers;
  60. loggers.push_back(p_logger);
  61. _logger = memnew(CompositeLogger(loggers));
  62. } else {
  63. _logger->add_logger(p_logger);
  64. }
  65. }
  66. String OS::get_identifier() const {
  67. return get_name().to_lower();
  68. }
  69. 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) {
  70. if (!_stderr_enabled) {
  71. return;
  72. }
  73. if (_logger) {
  74. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type);
  75. }
  76. }
  77. void OS::print(const char *p_format, ...) {
  78. if (!_stdout_enabled) {
  79. return;
  80. }
  81. va_list argp;
  82. va_start(argp, p_format);
  83. if (_logger) {
  84. _logger->logv(p_format, argp, false);
  85. }
  86. va_end(argp);
  87. }
  88. void OS::print_rich(const char *p_format, ...) {
  89. if (!_stdout_enabled) {
  90. return;
  91. }
  92. va_list argp;
  93. va_start(argp, p_format);
  94. if (_logger) {
  95. _logger->logv(p_format, argp, false);
  96. }
  97. va_end(argp);
  98. }
  99. void OS::printerr(const char *p_format, ...) {
  100. if (!_stderr_enabled) {
  101. return;
  102. }
  103. va_list argp;
  104. va_start(argp, p_format);
  105. if (_logger) {
  106. _logger->logv(p_format, argp, true);
  107. }
  108. va_end(argp);
  109. }
  110. void OS::alert(const String &p_alert, const String &p_title) {
  111. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  112. }
  113. void OS::set_low_processor_usage_mode(bool p_enabled) {
  114. low_processor_usage_mode = p_enabled;
  115. }
  116. bool OS::is_in_low_processor_usage_mode() const {
  117. return low_processor_usage_mode;
  118. }
  119. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  120. low_processor_usage_mode_sleep_usec = p_usec;
  121. }
  122. int OS::get_low_processor_usage_mode_sleep_usec() const {
  123. return low_processor_usage_mode_sleep_usec;
  124. }
  125. void OS::set_delta_smoothing(bool p_enabled) {
  126. _delta_smoothing_enabled = p_enabled;
  127. }
  128. bool OS::is_delta_smoothing_enabled() const {
  129. return _delta_smoothing_enabled;
  130. }
  131. String OS::get_executable_path() const {
  132. return _execpath;
  133. }
  134. int OS::get_process_id() const {
  135. return -1;
  136. }
  137. bool OS::is_stdout_verbose() const {
  138. return _verbose_stdout;
  139. }
  140. bool OS::is_stdout_debug_enabled() const {
  141. return _debug_stdout;
  142. }
  143. bool OS::is_stdout_enabled() const {
  144. return _stdout_enabled;
  145. }
  146. bool OS::is_stderr_enabled() const {
  147. return _stderr_enabled;
  148. }
  149. void OS::set_stdout_enabled(bool p_enabled) {
  150. _stdout_enabled = p_enabled;
  151. }
  152. void OS::set_stderr_enabled(bool p_enabled) {
  153. _stderr_enabled = p_enabled;
  154. }
  155. int OS::get_exit_code() const {
  156. return _exit_code;
  157. }
  158. void OS::set_exit_code(int p_code) {
  159. _exit_code = p_code;
  160. }
  161. String OS::get_locale() const {
  162. return "en";
  163. }
  164. // Non-virtual helper to extract the 2 or 3-letter language code from
  165. // `get_locale()` in a way that's consistent for all platforms.
  166. String OS::get_locale_language() const {
  167. return get_locale().left(3).replace("_", "");
  168. }
  169. // Embedded PCK offset.
  170. uint64_t OS::get_embedded_pck_offset() const {
  171. return 0;
  172. }
  173. // Helper function to ensure that a dir name/path will be valid on the OS
  174. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_paths) const {
  175. String safe_dir_name = p_dir_name;
  176. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  177. if (p_allow_paths) {
  178. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  179. invalid_chars.push_back("..");
  180. safe_dir_name = safe_dir_name.replace("\\", "/").strip_edges();
  181. } else {
  182. invalid_chars.push_back("/");
  183. invalid_chars.push_back("\\");
  184. safe_dir_name = safe_dir_name.strip_edges();
  185. // These directory names are invalid.
  186. if (safe_dir_name == ".") {
  187. safe_dir_name = "dot";
  188. } else if (safe_dir_name == "..") {
  189. safe_dir_name = "twodots";
  190. }
  191. }
  192. for (int i = 0; i < invalid_chars.size(); i++) {
  193. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  194. }
  195. return safe_dir_name;
  196. }
  197. // Path to data, config, cache, etc. OS-specific folders
  198. // Get properly capitalized engine name for system paths
  199. String OS::get_godot_dir_name() const {
  200. // Default to lowercase, so only override when different case is needed
  201. return String(VERSION_SHORT_NAME).to_lower();
  202. }
  203. // OS equivalent of XDG_DATA_HOME
  204. String OS::get_data_path() const {
  205. return ".";
  206. }
  207. // OS equivalent of XDG_CONFIG_HOME
  208. String OS::get_config_path() const {
  209. return ".";
  210. }
  211. // OS equivalent of XDG_CACHE_HOME
  212. String OS::get_cache_path() const {
  213. return ".";
  214. }
  215. // Path to macOS .app bundle resources
  216. String OS::get_bundle_resource_dir() const {
  217. return ".";
  218. }
  219. // Path to macOS .app bundle embedded icon
  220. String OS::get_bundle_icon_path() const {
  221. return String();
  222. }
  223. // OS specific path for user://
  224. String OS::get_user_data_dir() const {
  225. return ".";
  226. }
  227. // Absolute path to res://
  228. String OS::get_resource_dir() const {
  229. return ProjectSettings::get_singleton()->get_resource_path();
  230. }
  231. // Access system-specific dirs like Documents, Downloads, etc.
  232. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  233. return ".";
  234. }
  235. Error OS::shell_open(String p_uri) {
  236. return ERR_UNAVAILABLE;
  237. }
  238. Error OS::shell_show_in_file_manager(String p_path, bool p_open_folder) {
  239. p_path = p_path.trim_prefix("file://");
  240. if (!DirAccess::dir_exists_absolute(p_path)) {
  241. p_path = p_path.get_base_dir();
  242. }
  243. p_path = String("file://") + p_path;
  244. return shell_open(p_path);
  245. }
  246. // implement these with the canvas?
  247. uint64_t OS::get_static_memory_usage() const {
  248. return Memory::get_mem_usage();
  249. }
  250. uint64_t OS::get_static_memory_peak_usage() const {
  251. return Memory::get_mem_max_usage();
  252. }
  253. Error OS::set_cwd(const String &p_cwd) {
  254. return ERR_CANT_OPEN;
  255. }
  256. Dictionary OS::get_memory_info() const {
  257. Dictionary meminfo;
  258. meminfo["physical"] = -1;
  259. meminfo["free"] = -1;
  260. meminfo["available"] = -1;
  261. meminfo["stack"] = -1;
  262. return meminfo;
  263. }
  264. void OS::yield() {
  265. }
  266. void OS::ensure_user_data_dir() {
  267. String dd = get_user_data_dir();
  268. if (DirAccess::exists(dd)) {
  269. return;
  270. }
  271. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  272. Error err = da->make_dir_recursive(dd);
  273. ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
  274. }
  275. String OS::get_model_name() const {
  276. return "GenericDevice";
  277. }
  278. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
  279. _execpath = String::utf8(p_execpath);
  280. _cmdline = p_args;
  281. _user_args = p_user_args;
  282. }
  283. String OS::get_unique_id() const {
  284. ERR_FAIL_V("");
  285. }
  286. int OS::get_processor_count() const {
  287. return std::thread::hardware_concurrency();
  288. }
  289. String OS::get_processor_name() const {
  290. return "";
  291. }
  292. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  293. has_server_feature_callback = p_callback;
  294. }
  295. bool OS::has_feature(const String &p_feature) {
  296. // Feature tags are always lowercase for consistency.
  297. if (p_feature == get_identifier()) {
  298. return true;
  299. }
  300. if (p_feature == "movie") {
  301. return _writing_movie;
  302. }
  303. #ifdef DEBUG_ENABLED
  304. if (p_feature == "debug") {
  305. return true;
  306. }
  307. #endif // DEBUG_ENABLED
  308. #ifdef TOOLS_ENABLED
  309. if (p_feature == "editor") {
  310. return true;
  311. }
  312. #else
  313. if (p_feature == "template") {
  314. return true;
  315. }
  316. #ifdef DEBUG_ENABLED
  317. if (p_feature == "template_debug") {
  318. return true;
  319. }
  320. #else
  321. if (p_feature == "template_release" || p_feature == "release") {
  322. return true;
  323. }
  324. #endif // DEBUG_ENABLED
  325. #endif // TOOLS_ENABLED
  326. #ifdef REAL_T_IS_DOUBLE
  327. if (p_feature == "double") {
  328. return true;
  329. }
  330. #else
  331. if (p_feature == "single") {
  332. return true;
  333. }
  334. #endif // REAL_T_IS_DOUBLE
  335. if (sizeof(void *) == 8 && p_feature == "64") {
  336. return true;
  337. }
  338. if (sizeof(void *) == 4 && p_feature == "32") {
  339. return true;
  340. }
  341. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
  342. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
  343. if (p_feature == "x86_64") {
  344. return true;
  345. }
  346. #elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
  347. if (p_feature == "x86_32") {
  348. return true;
  349. }
  350. #endif
  351. if (p_feature == "x86") {
  352. return true;
  353. }
  354. #elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  355. #if defined(__aarch64__) || defined(_M_ARM64)
  356. if (p_feature == "arm64") {
  357. return true;
  358. }
  359. #elif defined(__arm__) || defined(_M_ARM)
  360. if (p_feature == "arm32") {
  361. return true;
  362. }
  363. #endif
  364. #if defined(__ARM_ARCH_7A__)
  365. if (p_feature == "armv7a" || p_feature == "armv7") {
  366. return true;
  367. }
  368. #endif
  369. #if defined(__ARM_ARCH_7S__)
  370. if (p_feature == "armv7s" || p_feature == "armv7") {
  371. return true;
  372. }
  373. #endif
  374. if (p_feature == "arm") {
  375. return true;
  376. }
  377. #elif defined(__riscv)
  378. #if __riscv_xlen == 8
  379. if (p_feature == "rv64") {
  380. return true;
  381. }
  382. #endif
  383. if (p_feature == "riscv") {
  384. return true;
  385. }
  386. #elif defined(__powerpc__)
  387. #if defined(__powerpc64__)
  388. if (p_feature == "ppc64") {
  389. return true;
  390. }
  391. #endif
  392. if (p_feature == "ppc") {
  393. return true;
  394. }
  395. #elif defined(__wasm__)
  396. #if defined(__wasm64__)
  397. if (p_feature == "wasm64") {
  398. return true;
  399. }
  400. #elif defined(__wasm32__)
  401. if (p_feature == "wasm32") {
  402. return true;
  403. }
  404. #endif
  405. if (p_feature == "wasm") {
  406. return true;
  407. }
  408. #endif
  409. if (_check_internal_feature_support(p_feature)) {
  410. return true;
  411. }
  412. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  413. return true;
  414. }
  415. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  416. return true;
  417. }
  418. return false;
  419. }
  420. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  421. restart_on_exit = p_restart;
  422. restart_commandline = p_restart_arguments;
  423. }
  424. bool OS::is_restart_on_exit_set() const {
  425. return restart_on_exit;
  426. }
  427. List<String> OS::get_restart_on_exit_arguments() const {
  428. return restart_commandline;
  429. }
  430. PackedStringArray OS::get_connected_midi_inputs() {
  431. if (MIDIDriver::get_singleton()) {
  432. return MIDIDriver::get_singleton()->get_connected_inputs();
  433. }
  434. PackedStringArray list;
  435. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  436. }
  437. void OS::open_midi_inputs() {
  438. if (MIDIDriver::get_singleton()) {
  439. MIDIDriver::get_singleton()->open();
  440. } else {
  441. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  442. }
  443. }
  444. void OS::close_midi_inputs() {
  445. if (MIDIDriver::get_singleton()) {
  446. MIDIDriver::get_singleton()->close();
  447. } else {
  448. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  449. }
  450. }
  451. void OS::add_frame_delay(bool p_can_draw) {
  452. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  453. if (frame_delay) {
  454. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  455. // the actual frame time into account.
  456. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  457. // to use this as a FPS limiter.
  458. delay_usec(frame_delay * 1000);
  459. }
  460. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  461. // previous frame time into account for a smoother result.
  462. uint64_t dynamic_delay = 0;
  463. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  464. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  465. }
  466. const int max_fps = Engine::get_singleton()->get_max_fps();
  467. if (max_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  468. // Override the low processor usage mode sleep delay if the target FPS is lower.
  469. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / max_fps));
  470. }
  471. if (dynamic_delay > 0) {
  472. target_ticks += dynamic_delay;
  473. uint64_t current_ticks = get_ticks_usec();
  474. if (current_ticks < target_ticks) {
  475. delay_usec(target_ticks - current_ticks);
  476. }
  477. current_ticks = get_ticks_usec();
  478. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  479. }
  480. }
  481. Error OS::setup_remote_filesystem(const String &p_server_host, int p_port, const String &p_password, String &r_project_path) {
  482. return default_rfs.synchronize_with_server(p_server_host, p_port, p_password, r_project_path);
  483. }
  484. OS::PreferredTextureFormat OS::get_preferred_texture_format() const {
  485. #if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  486. return PREFERRED_TEXTURE_FORMAT_ETC2_ASTC; // By rule, ARM hardware uses ETC texture compression.
  487. #elif defined(__x86_64__) || defined(_M_X64) || defined(i386) || defined(__i386__) || defined(__i386) || defined(_M_IX86)
  488. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // By rule, X86 hardware prefers S3TC and derivatives.
  489. #else
  490. return PREFERRED_TEXTURE_FORMAT_S3TC_BPTC; // Override in platform if needed.
  491. #endif
  492. }
  493. void OS::set_use_benchmark(bool p_use_benchmark) {
  494. use_benchmark = p_use_benchmark;
  495. }
  496. bool OS::is_use_benchmark_set() {
  497. return use_benchmark;
  498. }
  499. void OS::set_benchmark_file(const String &p_benchmark_file) {
  500. benchmark_file = p_benchmark_file;
  501. }
  502. String OS::get_benchmark_file() {
  503. return benchmark_file;
  504. }
  505. void OS::benchmark_begin_measure(const String &p_what) {
  506. #ifdef TOOLS_ENABLED
  507. start_benchmark_from[p_what] = OS::get_singleton()->get_ticks_usec();
  508. #endif
  509. }
  510. void OS::benchmark_end_measure(const String &p_what) {
  511. #ifdef TOOLS_ENABLED
  512. uint64_t total = OS::get_singleton()->get_ticks_usec() - start_benchmark_from[p_what];
  513. double total_f = double(total) / double(1000000);
  514. startup_benchmark_json[p_what] = total_f;
  515. #endif
  516. }
  517. void OS::benchmark_dump() {
  518. #ifdef TOOLS_ENABLED
  519. if (!use_benchmark) {
  520. return;
  521. }
  522. if (!benchmark_file.is_empty()) {
  523. Ref<FileAccess> f = FileAccess::open(benchmark_file, FileAccess::WRITE);
  524. if (f.is_valid()) {
  525. Ref<JSON> json;
  526. json.instantiate();
  527. f->store_string(json->stringify(startup_benchmark_json, "\t", false, true));
  528. }
  529. } else {
  530. List<Variant> keys;
  531. startup_benchmark_json.get_key_list(&keys);
  532. print_line("BENCHMARK:");
  533. for (const Variant &K : keys) {
  534. print_line("\t-", K, ": ", startup_benchmark_json[K], +" sec.");
  535. }
  536. }
  537. #endif
  538. }
  539. OS::OS() {
  540. singleton = this;
  541. Vector<Logger *> loggers;
  542. loggers.push_back(memnew(StdLogger));
  543. _set_logger(memnew(CompositeLogger(loggers)));
  544. }
  545. OS::~OS() {
  546. if (_logger) {
  547. memdelete(_logger);
  548. }
  549. singleton = nullptr;
  550. }