os.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /*************************************************************************/
  2. /* os.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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.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/os/midi_driver.h"
  36. #include "core/version_generated.gen.h"
  37. #include <stdarg.h>
  38. OS *OS::singleton = nullptr;
  39. uint64_t OS::target_ticks = 0;
  40. OS *OS::get_singleton() {
  41. return singleton;
  42. }
  43. uint64_t OS::get_ticks_msec() const {
  44. return get_ticks_usec() / 1000ULL;
  45. }
  46. double OS::get_unix_time() const {
  47. return 0;
  48. }
  49. void OS::debug_break() {
  50. // something
  51. }
  52. void OS::_set_logger(CompositeLogger *p_logger) {
  53. if (_logger) {
  54. memdelete(_logger);
  55. }
  56. _logger = p_logger;
  57. }
  58. void OS::add_logger(Logger *p_logger) {
  59. if (!_logger) {
  60. Vector<Logger *> loggers;
  61. loggers.push_back(p_logger);
  62. _logger = memnew(CompositeLogger(loggers));
  63. } else {
  64. _logger->add_logger(p_logger);
  65. }
  66. }
  67. 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) {
  68. if (!_stderr_enabled) {
  69. return;
  70. }
  71. if (_logger) {
  72. _logger->log_error(p_function, p_file, p_line, p_code, p_rationale, p_editor_notify, p_type);
  73. }
  74. }
  75. void OS::print(const char *p_format, ...) {
  76. if (!_stdout_enabled) {
  77. return;
  78. }
  79. va_list argp;
  80. va_start(argp, p_format);
  81. if (_logger) {
  82. _logger->logv(p_format, argp, false);
  83. }
  84. va_end(argp);
  85. }
  86. void OS::print_rich(const char *p_format, ...) {
  87. if (!_stdout_enabled) {
  88. return;
  89. }
  90. va_list argp;
  91. va_start(argp, p_format);
  92. if (_logger) {
  93. _logger->logv(p_format, argp, false);
  94. }
  95. va_end(argp);
  96. }
  97. void OS::printerr(const char *p_format, ...) {
  98. if (!_stderr_enabled) {
  99. return;
  100. }
  101. va_list argp;
  102. va_start(argp, p_format);
  103. if (_logger) {
  104. _logger->logv(p_format, argp, true);
  105. }
  106. va_end(argp);
  107. }
  108. void OS::alert(const String &p_alert, const String &p_title) {
  109. fprintf(stderr, "%s: %s\n", p_title.utf8().get_data(), p_alert.utf8().get_data());
  110. }
  111. void OS::set_low_processor_usage_mode(bool p_enabled) {
  112. low_processor_usage_mode = p_enabled;
  113. }
  114. bool OS::is_in_low_processor_usage_mode() const {
  115. return low_processor_usage_mode;
  116. }
  117. void OS::set_low_processor_usage_mode_sleep_usec(int p_usec) {
  118. low_processor_usage_mode_sleep_usec = p_usec;
  119. }
  120. int OS::get_low_processor_usage_mode_sleep_usec() const {
  121. return low_processor_usage_mode_sleep_usec;
  122. }
  123. String OS::get_executable_path() const {
  124. return _execpath;
  125. }
  126. int OS::get_process_id() const {
  127. return -1;
  128. }
  129. void OS::vibrate_handheld(int p_duration_ms) {
  130. WARN_PRINT("vibrate_handheld() only works with Android, iOS and HTML5");
  131. }
  132. bool OS::is_stdout_verbose() const {
  133. return _verbose_stdout;
  134. }
  135. bool OS::is_stdout_debug_enabled() const {
  136. return _debug_stdout;
  137. }
  138. bool OS::is_stdout_enabled() const {
  139. return _stdout_enabled;
  140. }
  141. bool OS::is_stderr_enabled() const {
  142. return _stderr_enabled;
  143. }
  144. void OS::set_stdout_enabled(bool p_enabled) {
  145. _stdout_enabled = p_enabled;
  146. }
  147. void OS::set_stderr_enabled(bool p_enabled) {
  148. _stderr_enabled = p_enabled;
  149. }
  150. static Ref<FileAccess> _OSPRF;
  151. static void _OS_printres(Object *p_obj) {
  152. Resource *res = Object::cast_to<Resource>(p_obj);
  153. if (!res) {
  154. return;
  155. }
  156. String str = vformat("%s - %s - %s", res->to_string(), res->get_name(), res->get_path());
  157. if (_OSPRF.is_valid()) {
  158. _OSPRF->store_line(str);
  159. } else {
  160. print_line(str);
  161. }
  162. }
  163. void OS::print_all_resources(String p_to_file) {
  164. ERR_FAIL_COND(!p_to_file.is_empty() && _OSPRF.is_valid());
  165. if (!p_to_file.is_empty()) {
  166. Error err;
  167. _OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err);
  168. if (err != OK) {
  169. _OSPRF.unref();
  170. ERR_FAIL_MSG("Can't print all resources to file: " + String(p_to_file) + ".");
  171. }
  172. }
  173. ObjectDB::debug_objects(_OS_printres);
  174. _OSPRF.unref();
  175. }
  176. void OS::print_resources_in_use(bool p_short) {
  177. ResourceCache::dump(nullptr, p_short);
  178. }
  179. void OS::dump_resources_to_file(const char *p_file) {
  180. ResourceCache::dump(p_file);
  181. }
  182. int OS::get_exit_code() const {
  183. return _exit_code;
  184. }
  185. void OS::set_exit_code(int p_code) {
  186. _exit_code = p_code;
  187. }
  188. String OS::get_locale() const {
  189. return "en";
  190. }
  191. // Non-virtual helper to extract the 2 or 3-letter language code from
  192. // `get_locale()` in a way that's consistent for all platforms.
  193. String OS::get_locale_language() const {
  194. return get_locale().left(3).replace("_", "");
  195. }
  196. // Embedded PCK offset.
  197. uint64_t OS::get_embedded_pck_offset() const {
  198. return 0;
  199. }
  200. // Helper function to ensure that a dir name/path will be valid on the OS
  201. String OS::get_safe_dir_name(const String &p_dir_name, bool p_allow_dir_separator) const {
  202. Vector<String> invalid_chars = String(": * ? \" < > |").split(" ");
  203. if (p_allow_dir_separator) {
  204. // Dir separators are allowed, but disallow ".." to avoid going up the filesystem
  205. invalid_chars.push_back("..");
  206. } else {
  207. invalid_chars.push_back("/");
  208. }
  209. String safe_dir_name = p_dir_name.replace("\\", "/").strip_edges();
  210. for (int i = 0; i < invalid_chars.size(); i++) {
  211. safe_dir_name = safe_dir_name.replace(invalid_chars[i], "-");
  212. }
  213. return safe_dir_name;
  214. }
  215. // Path to data, config, cache, etc. OS-specific folders
  216. // Get properly capitalized engine name for system paths
  217. String OS::get_godot_dir_name() const {
  218. // Default to lowercase, so only override when different case is needed
  219. return String(VERSION_SHORT_NAME).to_lower();
  220. }
  221. // OS equivalent of XDG_DATA_HOME
  222. String OS::get_data_path() const {
  223. return ".";
  224. }
  225. // OS equivalent of XDG_CONFIG_HOME
  226. String OS::get_config_path() const {
  227. return ".";
  228. }
  229. // OS equivalent of XDG_CACHE_HOME
  230. String OS::get_cache_path() const {
  231. return ".";
  232. }
  233. // Path to macOS .app bundle resources
  234. String OS::get_bundle_resource_dir() const {
  235. return ".";
  236. }
  237. // Path to macOS .app bundle embedded icon
  238. String OS::get_bundle_icon_path() const {
  239. return String();
  240. }
  241. // OS specific path for user://
  242. String OS::get_user_data_dir() const {
  243. return ".";
  244. }
  245. // Absolute path to res://
  246. String OS::get_resource_dir() const {
  247. return ProjectSettings::get_singleton()->get_resource_path();
  248. }
  249. // Access system-specific dirs like Documents, Downloads, etc.
  250. String OS::get_system_dir(SystemDir p_dir, bool p_shared_storage) const {
  251. return ".";
  252. }
  253. Error OS::shell_open(String p_uri) {
  254. return ERR_UNAVAILABLE;
  255. }
  256. // implement these with the canvas?
  257. uint64_t OS::get_static_memory_usage() const {
  258. return Memory::get_mem_usage();
  259. }
  260. uint64_t OS::get_static_memory_peak_usage() const {
  261. return Memory::get_mem_max_usage();
  262. }
  263. Error OS::set_cwd(const String &p_cwd) {
  264. return ERR_CANT_OPEN;
  265. }
  266. uint64_t OS::get_free_static_memory() const {
  267. return Memory::get_mem_available();
  268. }
  269. void OS::yield() {
  270. }
  271. void OS::ensure_user_data_dir() {
  272. String dd = get_user_data_dir();
  273. if (DirAccess::exists(dd)) {
  274. return;
  275. }
  276. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  277. Error err = da->make_dir_recursive(dd);
  278. ERR_FAIL_COND_MSG(err != OK, "Error attempting to create data dir: " + dd + ".");
  279. }
  280. String OS::get_model_name() const {
  281. return "GenericDevice";
  282. }
  283. void OS::set_cmdline(const char *p_execpath, const List<String> &p_args, const List<String> &p_user_args) {
  284. _execpath = String::utf8(p_execpath);
  285. _cmdline = p_args;
  286. _user_args = p_user_args;
  287. }
  288. String OS::get_unique_id() const {
  289. ERR_FAIL_V("");
  290. }
  291. int OS::get_processor_count() const {
  292. return 1;
  293. }
  294. String OS::get_processor_name() const {
  295. return "";
  296. }
  297. bool OS::can_use_threads() const {
  298. #ifdef NO_THREADS
  299. return false;
  300. #else
  301. return true;
  302. #endif
  303. }
  304. void OS::set_has_server_feature_callback(HasServerFeatureCallback p_callback) {
  305. has_server_feature_callback = p_callback;
  306. }
  307. bool OS::has_feature(const String &p_feature) {
  308. // Feature tags are always lowercase for consistency.
  309. if (p_feature == get_name().to_lower()) {
  310. return true;
  311. }
  312. // Catch-all `linuxbsd` feature tag that matches on both Linux and BSD.
  313. // This is the one exposed in the project settings dialog.
  314. if (p_feature == "linuxbsd" && (get_name() == "Linux" || get_name() == "FreeBSD" || get_name() == "NetBSD" || get_name() == "OpenBSD" || get_name() == "BSD")) {
  315. return true;
  316. }
  317. if (p_feature == "movie") {
  318. return _writing_movie;
  319. }
  320. #ifdef DEBUG_ENABLED
  321. if (p_feature == "debug") {
  322. return true;
  323. }
  324. #else
  325. if (p_feature == "release") {
  326. return true;
  327. }
  328. #endif
  329. #ifdef TOOLS_ENABLED
  330. if (p_feature == "editor") {
  331. return true;
  332. }
  333. #else
  334. if (p_feature == "standalone") {
  335. return true;
  336. }
  337. #endif
  338. if (sizeof(void *) == 8 && p_feature == "64") {
  339. return true;
  340. }
  341. if (sizeof(void *) == 4 && p_feature == "32") {
  342. return true;
  343. }
  344. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64)
  345. #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(_M_X64)
  346. if (p_feature == "x86_64") {
  347. return true;
  348. }
  349. #elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
  350. if (p_feature == "x86_32") {
  351. return true;
  352. }
  353. #endif
  354. if (p_feature == "x86") {
  355. return true;
  356. }
  357. #elif defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64)
  358. #if defined(__aarch64__) || defined(_M_ARM64)
  359. if (p_feature == "arm64") {
  360. return true;
  361. }
  362. #elif defined(__arm__) || defined(_M_ARM)
  363. if (p_feature == "arm32") {
  364. return true;
  365. }
  366. #endif
  367. #if defined(__ARM_ARCH_7A__)
  368. if (p_feature == "armv7a" || p_feature == "armv7") {
  369. return true;
  370. }
  371. #endif
  372. #if defined(__ARM_ARCH_7S__)
  373. if (p_feature == "armv7s" || p_feature == "armv7") {
  374. return true;
  375. }
  376. #endif
  377. if (p_feature == "arm") {
  378. return true;
  379. }
  380. #elif defined(__riscv)
  381. #if __riscv_xlen == 8
  382. if (p_feature == "rv64") {
  383. return true;
  384. }
  385. #endif
  386. if (p_feature == "riscv") {
  387. return true;
  388. }
  389. #elif defined(__powerpc__)
  390. #if defined(__powerpc64__)
  391. if (p_feature == "ppc64") {
  392. return true;
  393. }
  394. #endif
  395. if (p_feature == "ppc") {
  396. return true;
  397. }
  398. #elif defined(__wasm__)
  399. #if defined(__wasm64__)
  400. if (p_feature == "wasm64") {
  401. return true;
  402. }
  403. #elif defined(__wasm32__)
  404. if (p_feature == "wasm32") {
  405. return true;
  406. }
  407. #endif
  408. if (p_feature == "wasm") {
  409. return true;
  410. }
  411. #endif
  412. if (_check_internal_feature_support(p_feature)) {
  413. return true;
  414. }
  415. if (has_server_feature_callback && has_server_feature_callback(p_feature)) {
  416. return true;
  417. }
  418. if (ProjectSettings::get_singleton()->has_custom_feature(p_feature)) {
  419. return true;
  420. }
  421. return false;
  422. }
  423. void OS::set_restart_on_exit(bool p_restart, const List<String> &p_restart_arguments) {
  424. restart_on_exit = p_restart;
  425. restart_commandline = p_restart_arguments;
  426. }
  427. bool OS::is_restart_on_exit_set() const {
  428. return restart_on_exit;
  429. }
  430. List<String> OS::get_restart_on_exit_arguments() const {
  431. return restart_commandline;
  432. }
  433. PackedStringArray OS::get_connected_midi_inputs() {
  434. if (MIDIDriver::get_singleton()) {
  435. return MIDIDriver::get_singleton()->get_connected_inputs();
  436. }
  437. PackedStringArray list;
  438. ERR_FAIL_V_MSG(list, vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  439. }
  440. void OS::open_midi_inputs() {
  441. if (MIDIDriver::get_singleton()) {
  442. MIDIDriver::get_singleton()->open();
  443. } else {
  444. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  445. }
  446. }
  447. void OS::close_midi_inputs() {
  448. if (MIDIDriver::get_singleton()) {
  449. MIDIDriver::get_singleton()->close();
  450. } else {
  451. ERR_PRINT(vformat("MIDI input isn't supported on %s.", OS::get_singleton()->get_name()));
  452. }
  453. }
  454. void OS::add_frame_delay(bool p_can_draw) {
  455. const uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  456. if (frame_delay) {
  457. // Add fixed frame delay to decrease CPU/GPU usage. This doesn't take
  458. // the actual frame time into account.
  459. // Due to the high fluctuation of the actual sleep duration, it's not recommended
  460. // to use this as a FPS limiter.
  461. delay_usec(frame_delay * 1000);
  462. }
  463. // Add a dynamic frame delay to decrease CPU/GPU usage. This takes the
  464. // previous frame time into account for a smoother result.
  465. uint64_t dynamic_delay = 0;
  466. if (is_in_low_processor_usage_mode() || !p_can_draw) {
  467. dynamic_delay = get_low_processor_usage_mode_sleep_usec();
  468. }
  469. const int target_fps = Engine::get_singleton()->get_target_fps();
  470. if (target_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  471. // Override the low processor usage mode sleep delay if the target FPS is lower.
  472. dynamic_delay = MAX(dynamic_delay, (uint64_t)(1000000 / target_fps));
  473. }
  474. if (dynamic_delay > 0) {
  475. target_ticks += dynamic_delay;
  476. uint64_t current_ticks = get_ticks_usec();
  477. if (current_ticks < target_ticks) {
  478. delay_usec(target_ticks - current_ticks);
  479. }
  480. current_ticks = get_ticks_usec();
  481. target_ticks = MIN(MAX(target_ticks, current_ticks - dynamic_delay), current_ticks + dynamic_delay);
  482. }
  483. }
  484. OS::OS() {
  485. singleton = this;
  486. Vector<Logger *> loggers;
  487. loggers.push_back(memnew(StdLogger));
  488. _set_logger(memnew(CompositeLogger(loggers)));
  489. }
  490. OS::~OS() {
  491. if (_logger) {
  492. memdelete(_logger);
  493. }
  494. singleton = nullptr;
  495. }