main.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  1. /*************************************************************************/
  2. /* main.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "main.h"
  31. #include "app_icon.gen.h"
  32. #include "core/register_core_types.h"
  33. #include "drivers/register_driver_types.h"
  34. #include "message_queue.h"
  35. #include "modules/register_module_types.h"
  36. #include "os/os.h"
  37. #include "platform/register_platform_apis.h"
  38. #include "project_settings.h"
  39. #include "scene/register_scene_types.h"
  40. #include "script_debugger_local.h"
  41. #include "script_debugger_remote.h"
  42. #include "servers/register_server_types.h"
  43. #include "splash.gen.h"
  44. #include "splash_editor.gen.h"
  45. #include "input_map.h"
  46. #include "io/resource_loader.h"
  47. #include "scene/main/scene_tree.h"
  48. #include "servers/arvr_server.h"
  49. #include "servers/audio_server.h"
  50. #include "servers/physics_2d_server.h"
  51. #include "servers/physics_server.h"
  52. #include "io/resource_loader.h"
  53. #include "script_language.h"
  54. #include "core/io/ip.h"
  55. #include "main/tests/test_main.h"
  56. #include "os/dir_access.h"
  57. #include "scene/main/viewport.h"
  58. #include "scene/resources/packed_scene.h"
  59. #ifdef TOOLS_ENABLED
  60. #include "editor/doc/doc_data.h"
  61. #include "editor/doc/doc_data_class_path.gen.h"
  62. #include "editor/editor_node.h"
  63. #include "editor/project_manager.h"
  64. #endif
  65. #include "io/file_access_network.h"
  66. #include "servers/physics_2d_server.h"
  67. #include "core/io/file_access_pack.h"
  68. #include "core/io/file_access_zip.h"
  69. #include "core/io/stream_peer_ssl.h"
  70. #include "core/io/stream_peer_tcp.h"
  71. #include "main/input_default.h"
  72. #include "performance.h"
  73. #include "translation.h"
  74. #include "version.h"
  75. #include "version_hash.gen.h"
  76. static ProjectSettings *globals = NULL;
  77. static Engine *engine = NULL;
  78. static InputMap *input_map = NULL;
  79. static bool _start_success = false;
  80. static ScriptDebugger *script_debugger = NULL;
  81. AudioServer *audio_server = NULL;
  82. ARVRServer *arvr_server = NULL;
  83. PhysicsServer *physics_server = NULL;
  84. Physics2DServer *physics_2d_server = NULL;
  85. static MessageQueue *message_queue = NULL;
  86. static Performance *performance = NULL;
  87. static PackedData *packed_data = NULL;
  88. #ifdef MINIZIP_ENABLED
  89. static ZipArchive *zip_packed_data = NULL;
  90. #endif
  91. static FileAccessNetworkClient *file_access_network_client = NULL;
  92. static TranslationServer *translation_server = NULL;
  93. static OS::VideoMode video_mode;
  94. static bool init_maximized = false;
  95. static bool init_windowed = false;
  96. static bool init_fullscreen = false;
  97. static bool init_always_on_top = false;
  98. static bool init_use_custom_pos = false;
  99. #ifdef DEBUG_ENABLED
  100. static bool debug_collisions = false;
  101. static bool debug_navigation = false;
  102. #endif
  103. static int frame_delay = 0;
  104. static Vector2 init_custom_pos;
  105. static int video_driver_idx = -1;
  106. static int audio_driver_idx = -1;
  107. static String locale;
  108. static bool use_debug_profiler = false;
  109. static bool force_lowdpi = false;
  110. static int init_screen = -1;
  111. static bool use_vsync = true;
  112. static bool editor = false;
  113. static bool show_help = false;
  114. static bool disable_render_loop = false;
  115. static int fixed_fps = -1;
  116. static bool auto_build_solutions = false;
  117. static bool auto_quit = false;
  118. static bool print_fps = false;
  119. static OS::ProcessID allow_focus_steal_pid = 0;
  120. static bool project_manager = false;
  121. bool Main::is_project_manager() {
  122. return project_manager;
  123. }
  124. void initialize_physics() {
  125. /// 3D Physics Server
  126. physics_server = PhysicsServerManager::new_server(ProjectSettings::get_singleton()->get(PhysicsServerManager::setting_property_name));
  127. if (!physics_server) {
  128. // Physics server not found, Use the default physics
  129. physics_server = PhysicsServerManager::new_default_server();
  130. }
  131. ERR_FAIL_COND(!physics_server);
  132. physics_server->init();
  133. /// 2D Physics server
  134. physics_2d_server = Physics2DServerManager::new_server(ProjectSettings::get_singleton()->get(Physics2DServerManager::setting_property_name));
  135. if (!physics_2d_server) {
  136. // Physics server not found, Use the default physics
  137. physics_2d_server = Physics2DServerManager::new_default_server();
  138. }
  139. ERR_FAIL_COND(!physics_2d_server);
  140. physics_2d_server->init();
  141. }
  142. void finalize_physics() {
  143. physics_server->finish();
  144. memdelete(physics_server);
  145. physics_2d_server->finish();
  146. memdelete(physics_2d_server);
  147. }
  148. static String unescape_cmdline(const String &p_str) {
  149. return p_str.replace("%20", " ");
  150. }
  151. static String get_full_version_string() {
  152. String hash = String(VERSION_HASH);
  153. if (hash.length() != 0)
  154. hash = "." + hash.left(7);
  155. return String(VERSION_FULL_BUILD) + hash;
  156. }
  157. //#define DEBUG_INIT
  158. #ifdef DEBUG_INIT
  159. #define MAIN_PRINT(m_txt) print_line(m_txt)
  160. #else
  161. #define MAIN_PRINT(m_txt)
  162. #endif
  163. void Main::print_help(const char *p_binary) {
  164. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - https://godotengine.org");
  165. OS::get_singleton()->print("(c) 2007-2018 Juan Linietsky, Ariel Manzur.\n");
  166. OS::get_singleton()->print("(c) 2014-2018 Godot Engine contributors.\n");
  167. OS::get_singleton()->print("\n");
  168. OS::get_singleton()->print("Usage: %s [options] [path to scene or 'project.godot' file]\n", p_binary);
  169. OS::get_singleton()->print("\n");
  170. OS::get_singleton()->print("General options:\n");
  171. OS::get_singleton()->print(" -h, --help Display this help message.\n");
  172. OS::get_singleton()->print(" --version Display the version string.\n");
  173. OS::get_singleton()->print(" -v, --verbose Use verbose stdout mode.\n");
  174. OS::get_singleton()->print(" --quiet Quiet mode, silences stdout messages. Errors are still displayed.\n");
  175. OS::get_singleton()->print("\n");
  176. OS::get_singleton()->print("Run options:\n");
  177. #ifdef TOOLS_ENABLED
  178. OS::get_singleton()->print(" -e, --editor Start the editor instead of running the scene.\n");
  179. OS::get_singleton()->print(" -p, --project-manager Start the project manager, even if a project is auto-detected.\n");
  180. #endif
  181. OS::get_singleton()->print(" -q, --quit Quit after the first iteration.\n");
  182. OS::get_singleton()->print(" -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n");
  183. OS::get_singleton()->print(" --path <directory> Path to a project (<directory> must contain a 'project.godot' file).\n");
  184. OS::get_singleton()->print(" -u, --upwards Scan folders upwards for project.godot file.\n");
  185. OS::get_singleton()->print(" --main-pack <file> Path to a pack (.pck) file to load.\n");
  186. OS::get_singleton()->print(" --render-thread <mode> Render thread mode ('unsafe', 'safe', 'separate').\n");
  187. OS::get_singleton()->print(" --remote-fs <address> Remote filesystem (<host/IP>[:<port>] address).\n");
  188. OS::get_singleton()->print(" --remote-fs-password <password> Password for remote filesystem.\n");
  189. OS::get_singleton()->print(" --audio-driver <driver> Audio driver (");
  190. for (int i = 0; i < OS::get_singleton()->get_audio_driver_count(); i++) {
  191. if (i != 0)
  192. OS::get_singleton()->print(", ");
  193. OS::get_singleton()->print("'%s'", OS::get_singleton()->get_audio_driver_name(i));
  194. }
  195. OS::get_singleton()->print(").\n");
  196. OS::get_singleton()->print(" --video-driver <driver> Video driver (");
  197. for (int i = 0; i < OS::get_singleton()->get_video_driver_count(); i++) {
  198. if (i != 0)
  199. OS::get_singleton()->print(", ");
  200. OS::get_singleton()->print("'%s'", OS::get_singleton()->get_video_driver_name(i));
  201. }
  202. OS::get_singleton()->print(").\n");
  203. OS::get_singleton()->print("\n");
  204. OS::get_singleton()->print("Display options:\n");
  205. OS::get_singleton()->print(" -f, --fullscreen Request fullscreen mode.\n");
  206. OS::get_singleton()->print(" -m, --maximized Request a maximized window.\n");
  207. OS::get_singleton()->print(" -w, --windowed Request windowed mode.\n");
  208. OS::get_singleton()->print(" -t, --always-on-top Request an always-on-top window.\n");
  209. OS::get_singleton()->print(" --resolution <W>x<H> Request window resolution.\n");
  210. OS::get_singleton()->print(" --position <X>,<Y> Request window position.\n");
  211. OS::get_singleton()->print(" --low-dpi Force low-DPI mode (macOS and Windows only).\n");
  212. OS::get_singleton()->print(" --no-window Disable window creation (Windows only). Useful together with --script.\n");
  213. OS::get_singleton()->print("\n");
  214. OS::get_singleton()->print("Debug options:\n");
  215. OS::get_singleton()->print(" -d, --debug Debug (local stdout debugger).\n");
  216. OS::get_singleton()->print(" -b, --breakpoints Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n");
  217. OS::get_singleton()->print(" --profiling Enable profiling in the script debugger.\n");
  218. OS::get_singleton()->print(" --remote-debug <address> Remote debug (<host/IP>:<port> address).\n");
  219. #ifdef DEBUG_ENABLED
  220. OS::get_singleton()->print(" --debug-collisions Show collisions shapes when running the scene.\n");
  221. OS::get_singleton()->print(" --debug-navigation Show navigation polygons when running the scene.\n");
  222. #endif
  223. OS::get_singleton()->print(" --frame-delay <ms> Simulate high CPU load (delay each frame by <ms> milliseconds).\n");
  224. OS::get_singleton()->print(" --time-scale <scale> Force time scale (higher values are faster, 1.0 is normal speed).\n");
  225. OS::get_singleton()->print(" --disable-render-loop Disable render loop so rendering only occurs when called explicitly from script.\n");
  226. OS::get_singleton()->print(" --disable-crash-handler Disable crash handler when supported by the platform code.\n");
  227. OS::get_singleton()->print(" --fixed-fps <fps> Force a fixed number of frames per second. This setting disables real-time synchronization.\n");
  228. OS::get_singleton()->print(" --print-fps Print the frames per second to the stdout.\n");
  229. OS::get_singleton()->print("\n");
  230. OS::get_singleton()->print("Standalone tools:\n");
  231. OS::get_singleton()->print(" -s, --script <script> Run a script.\n");
  232. #ifdef TOOLS_ENABLED
  233. OS::get_singleton()->print(" --export <target> Export the project using the given export target. Export only main pack if path ends with .pck or .zip'.\n");
  234. OS::get_singleton()->print(" --export-debug <target> Like --export, but use debug template.\n");
  235. OS::get_singleton()->print(" --doctool <path> Dump the engine API reference to the given <path> in XML format, merging if existing files are found.\n");
  236. OS::get_singleton()->print(" --no-docbase Disallow dumping the base types (used with --doctool).\n");
  237. OS::get_singleton()->print(" --build-solutions Build the scripting solutions (e.g. for C# projects).\n");
  238. #ifdef DEBUG_METHODS_ENABLED
  239. OS::get_singleton()->print(" --gdnative-generate-json-api Generate JSON dump of the Godot API for GDNative bindings.\n");
  240. #endif
  241. OS::get_singleton()->print(" --test <test> Run a unit test (");
  242. const char **test_names = tests_get_names();
  243. const char *comma = "";
  244. while (*test_names) {
  245. OS::get_singleton()->print("%s'%s'", comma, *test_names);
  246. test_names++;
  247. comma = ", ";
  248. }
  249. OS::get_singleton()->print(").\n");
  250. #endif
  251. }
  252. Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
  253. RID_OwnerBase::init_rid();
  254. OS::get_singleton()->initialize_core();
  255. engine = memnew(Engine);
  256. ClassDB::init();
  257. MAIN_PRINT("Main: Initialize CORE");
  258. register_core_types();
  259. register_core_driver_types();
  260. MAIN_PRINT("Main: Initialize Globals");
  261. Thread::_main_thread_id = Thread::get_caller_id();
  262. globals = memnew(ProjectSettings);
  263. input_map = memnew(InputMap);
  264. register_core_settings(); //here globals is present
  265. translation_server = memnew(TranslationServer);
  266. performance = memnew(Performance);
  267. ClassDB::register_class<Performance>();
  268. engine->add_singleton(Engine::Singleton("Performance", performance));
  269. GLOBAL_DEF("debug/settings/crash_handler/message", String("Please include this when reporting the bug on https://github.com/godotengine/godot/issues"));
  270. MAIN_PRINT("Main: Parse CMDLine");
  271. /* argument parsing and main creation */
  272. List<String> args;
  273. List<String> main_args;
  274. for (int i = 0; i < argc; i++) {
  275. args.push_back(String::utf8(argv[i]));
  276. }
  277. List<String>::Element *I = args.front();
  278. I = args.front();
  279. while (I) {
  280. I->get() = unescape_cmdline(I->get().strip_escapes());
  281. I = I->next();
  282. }
  283. I = args.front();
  284. String video_driver = "";
  285. String audio_driver = "";
  286. String project_path = ".";
  287. bool upwards = false;
  288. String debug_mode;
  289. String debug_host;
  290. String main_pack;
  291. bool quiet_stdout = false;
  292. int rtm = -1;
  293. String remotefs;
  294. String remotefs_pass;
  295. Vector<String> breakpoints;
  296. bool use_custom_res = true;
  297. bool force_res = false;
  298. bool found_project = false;
  299. packed_data = PackedData::get_singleton();
  300. if (!packed_data)
  301. packed_data = memnew(PackedData);
  302. #ifdef MINIZIP_ENABLED
  303. //XXX: always get_singleton() == 0x0
  304. zip_packed_data = ZipArchive::get_singleton();
  305. //TODO: remove this temporary fix
  306. if (!zip_packed_data) {
  307. zip_packed_data = memnew(ZipArchive);
  308. }
  309. packed_data->add_pack_source(zip_packed_data);
  310. #endif
  311. I = args.front();
  312. while (I) {
  313. List<String>::Element *N = I->next();
  314. if (I->get() == "-h" || I->get() == "--help" || I->get() == "/?") { // display help
  315. show_help = true;
  316. goto error;
  317. } else if (I->get() == "--version") {
  318. print_line(get_full_version_string());
  319. goto error;
  320. } else if (I->get() == "--resolution") { // force resolution
  321. if (I->next()) {
  322. String vm = I->next()->get();
  323. if (vm.find("x") == -1) { // invalid parameter format
  324. OS::get_singleton()->print("Invalid resolution '%s', it should be e.g. '1280x720'.\n", vm.utf8().get_data());
  325. goto error;
  326. }
  327. int w = vm.get_slice("x", 0).to_int();
  328. int h = vm.get_slice("x", 1).to_int();
  329. if (w <= 0 || h <= 0) {
  330. OS::get_singleton()->print("Invalid resolution '%s', width and height must be above 0.\n", vm.utf8().get_data());
  331. goto error;
  332. }
  333. video_mode.width = w;
  334. video_mode.height = h;
  335. force_res = true;
  336. N = I->next()->next();
  337. } else {
  338. OS::get_singleton()->print("Missing resolution argument, aborting.\n");
  339. goto error;
  340. }
  341. } else if (I->get() == "--position") { // set window position
  342. if (I->next()) {
  343. String vm = I->next()->get();
  344. if (vm.find(",") == -1) { // invalid parameter format
  345. OS::get_singleton()->print("Invalid position '%s', it should be e.g. '80,128'.\n", vm.utf8().get_data());
  346. goto error;
  347. }
  348. int x = vm.get_slice(",", 0).to_int();
  349. int y = vm.get_slice(",", 1).to_int();
  350. init_custom_pos = Point2(x, y);
  351. init_use_custom_pos = true;
  352. N = I->next()->next();
  353. } else {
  354. OS::get_singleton()->print("Missing position argument, aborting.\n");
  355. goto error;
  356. }
  357. } else if (I->get() == "-m" || I->get() == "--maximized") { // force maximized window
  358. init_maximized = true;
  359. video_mode.maximized = true;
  360. } else if (I->get() == "-w" || I->get() == "--windowed") { // force windowed window
  361. init_windowed = true;
  362. } else if (I->get() == "-t" || I->get() == "--always-on-top") { // force always-on-top window
  363. init_always_on_top = true;
  364. } else if (I->get() == "--profiling") { // enable profiling
  365. use_debug_profiler = true;
  366. } else if (I->get() == "--video-driver") { // force video driver
  367. if (I->next()) {
  368. video_driver = I->next()->get();
  369. N = I->next()->next();
  370. } else {
  371. OS::get_singleton()->print("Missing video driver argument, aborting.\n");
  372. goto error;
  373. }
  374. } else if (I->get() == "-l" || I->get() == "--language") { // language
  375. if (I->next()) {
  376. locale = I->next()->get();
  377. N = I->next()->next();
  378. } else {
  379. OS::get_singleton()->print("Missing language argument, aborting.\n");
  380. goto error;
  381. }
  382. } else if (I->get() == "--low-dpi") { // force low DPI (macOS only)
  383. force_lowdpi = true;
  384. } else if (I->get() == "--remote-fs") { // remote filesystem
  385. if (I->next()) {
  386. remotefs = I->next()->get();
  387. N = I->next()->next();
  388. } else {
  389. OS::get_singleton()->print("Missing remote filesystem address, aborting.\n");
  390. goto error;
  391. }
  392. } else if (I->get() == "--remote-fs-password") { // remote filesystem password
  393. if (I->next()) {
  394. remotefs_pass = I->next()->get();
  395. N = I->next()->next();
  396. } else {
  397. OS::get_singleton()->print("Missing remote filesystem password, aborting.\n");
  398. goto error;
  399. }
  400. } else if (I->get() == "--render-thread") { // render thread mode
  401. if (I->next()) {
  402. if (I->next()->get() == "safe")
  403. rtm = OS::RENDER_THREAD_SAFE;
  404. else if (I->next()->get() == "unsafe")
  405. rtm = OS::RENDER_THREAD_UNSAFE;
  406. else if (I->next()->get() == "separate")
  407. rtm = OS::RENDER_SEPARATE_THREAD;
  408. N = I->next()->next();
  409. } else {
  410. OS::get_singleton()->print("Missing render thread mode argument, aborting.\n");
  411. goto error;
  412. }
  413. } else if (I->get() == "--audio-driver") { // audio driver
  414. if (I->next()) {
  415. audio_driver = I->next()->get();
  416. N = I->next()->next();
  417. } else {
  418. OS::get_singleton()->print("Missing audio driver argument, aborting.\n");
  419. goto error;
  420. }
  421. } else if (I->get() == "-f" || I->get() == "--fullscreen") { // force fullscreen
  422. //video_mode.fullscreen=false;
  423. init_fullscreen = true;
  424. #ifdef TOOLS_ENABLED
  425. } else if (I->get() == "-e" || I->get() == "--editor") { // starts editor
  426. editor = true;
  427. } else if (I->get() == "-p" || I->get() == "--project-manager") { // starts project manager
  428. project_manager = true;
  429. } else if (I->get() == "--build-solutions") { // Build the scripting solution such C#
  430. auto_build_solutions = true;
  431. #endif
  432. } else if (I->get() == "--no-window") { // disable window creation, Windows only
  433. OS::get_singleton()->set_no_window_mode(true);
  434. } else if (I->get() == "--quiet") { // quieter output
  435. quiet_stdout = true;
  436. } else if (I->get() == "-v" || I->get() == "--verbose") { // verbose output
  437. OS::get_singleton()->_verbose_stdout = true;
  438. } else if (I->get() == "--path") { // set path of project to start or edit
  439. if (I->next()) {
  440. String p = I->next()->get();
  441. if (OS::get_singleton()->set_cwd(p) == OK) {
  442. //nothing
  443. } else {
  444. project_path = I->next()->get(); //use project_path instead
  445. }
  446. N = I->next()->next();
  447. } else {
  448. OS::get_singleton()->print("Missing relative or absolute path, aborting.\n");
  449. goto error;
  450. }
  451. } else if (I->get() == "-u" || I->get() == "--upwards") { // scan folders upwards
  452. upwards = true;
  453. } else if (I->get() == "-q" || I->get() == "--quit") { // Auto quit at the end of the first main loop iteration
  454. auto_quit = true;
  455. } else if (I->get().ends_with("project.godot")) {
  456. String path;
  457. String file = I->get();
  458. int sep = MAX(file.find_last("/"), file.find_last("\\"));
  459. if (sep == -1)
  460. path = ".";
  461. else {
  462. path = file.substr(0, sep);
  463. }
  464. if (OS::get_singleton()->set_cwd(path) == OK) {
  465. // path already specified, don't override
  466. } else {
  467. project_path = path;
  468. }
  469. #ifdef TOOLS_ENABLED
  470. editor = true;
  471. #endif
  472. } else if (I->get() == "-b" || I->get() == "--breakpoints") { // add breakpoints
  473. if (I->next()) {
  474. String bplist = I->next()->get();
  475. breakpoints = bplist.split(",");
  476. N = I->next()->next();
  477. } else {
  478. OS::get_singleton()->print("Missing list of breakpoints, aborting.\n");
  479. goto error;
  480. }
  481. } else if (I->get() == "--frame-delay") { // force frame delay
  482. if (I->next()) {
  483. frame_delay = I->next()->get().to_int();
  484. N = I->next()->next();
  485. } else {
  486. OS::get_singleton()->print("Missing frame delay argument, aborting.\n");
  487. goto error;
  488. }
  489. } else if (I->get() == "--time-scale") { // force time scale
  490. if (I->next()) {
  491. Engine::get_singleton()->set_time_scale(I->next()->get().to_double());
  492. N = I->next()->next();
  493. } else {
  494. OS::get_singleton()->print("Missing time scale argument, aborting.\n");
  495. goto error;
  496. }
  497. } else if (I->get() == "--main-pack") {
  498. if (I->next()) {
  499. main_pack = I->next()->get();
  500. N = I->next()->next();
  501. } else {
  502. OS::get_singleton()->print("Missing path to main pack file, aborting.\n");
  503. goto error;
  504. };
  505. } else if (I->get() == "-d" || I->get() == "--debug") {
  506. debug_mode = "local";
  507. #ifdef DEBUG_ENABLED
  508. } else if (I->get() == "--debug-collisions") {
  509. debug_collisions = true;
  510. } else if (I->get() == "--debug-navigation") {
  511. debug_navigation = true;
  512. #endif
  513. } else if (I->get() == "--remote-debug") {
  514. if (I->next()) {
  515. debug_mode = "remote";
  516. debug_host = I->next()->get();
  517. if (debug_host.find(":") == -1) { // wrong address
  518. OS::get_singleton()->print("Invalid debug host address, it should be of the form <host/IP>:<port>.\n");
  519. goto error;
  520. }
  521. N = I->next()->next();
  522. } else {
  523. OS::get_singleton()->print("Missing remote debug host address, aborting.\n");
  524. goto error;
  525. }
  526. } else if (I->get() == "--allow_focus_steal_pid") { // not exposed to user
  527. if (I->next()) {
  528. allow_focus_steal_pid = I->next()->get().to_int64();
  529. N = I->next()->next();
  530. } else {
  531. OS::get_singleton()->print("Missing editor PID argument, aborting.\n");
  532. goto error;
  533. }
  534. } else if (I->get() == "--disable-render-loop") {
  535. disable_render_loop = true;
  536. } else if (I->get() == "--fixed-fps") {
  537. if (I->next()) {
  538. fixed_fps = I->next()->get().to_int();
  539. N = I->next()->next();
  540. } else {
  541. OS::get_singleton()->print("Missing fixed-fps argument, aborting.\n");
  542. goto error;
  543. }
  544. } else if (I->get() == "--print-fps") {
  545. print_fps = true;
  546. } else if (I->get() == "--disable-crash-handler") {
  547. OS::get_singleton()->disable_crash_handler();
  548. } else {
  549. main_args.push_back(I->get());
  550. }
  551. I = N;
  552. }
  553. if (globals->setup(project_path, main_pack, upwards) == OK) {
  554. found_project = true;
  555. } else {
  556. #ifdef TOOLS_ENABLED
  557. editor = false;
  558. #else
  559. OS::get_singleton()->print("Error: Could not load game path '%s'.\n", project_path.ascii().get_data());
  560. goto error;
  561. #endif
  562. }
  563. GLOBAL_DEF("memory/limits/multithreaded_server/rid_pool_prealloc", 60);
  564. GLOBAL_DEF("network/limits/debugger_stdout/max_chars_per_second", 2048);
  565. GLOBAL_DEF("network/limits/debugger_stdout/max_messages_per_frame", 10);
  566. GLOBAL_DEF("network/limits/debugger_stdout/max_errors_per_frame", 10);
  567. if (debug_mode == "remote") {
  568. ScriptDebuggerRemote *sdr = memnew(ScriptDebuggerRemote);
  569. uint16_t debug_port = 6007;
  570. if (debug_host.find(":") != -1) {
  571. int sep_pos = debug_host.find_last(":");
  572. debug_port = debug_host.substr(sep_pos + 1, debug_host.length()).to_int();
  573. debug_host = debug_host.substr(0, sep_pos);
  574. }
  575. Error derr = sdr->connect_to_host(debug_host, debug_port);
  576. if (derr != OK) {
  577. memdelete(sdr);
  578. } else {
  579. script_debugger = sdr;
  580. }
  581. } else if (debug_mode == "local") {
  582. script_debugger = memnew(ScriptDebuggerLocal);
  583. OS::get_singleton()->initialize_debugging();
  584. }
  585. FileAccessNetwork::configure();
  586. if (remotefs != "") {
  587. file_access_network_client = memnew(FileAccessNetworkClient);
  588. int port;
  589. if (remotefs.find(":") != -1) {
  590. port = remotefs.get_slicec(':', 1).to_int();
  591. remotefs = remotefs.get_slicec(':', 0);
  592. } else {
  593. port = 6010;
  594. }
  595. Error err = file_access_network_client->connect(remotefs, port, remotefs_pass);
  596. if (err) {
  597. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i.\n", remotefs.utf8().get_data(), port);
  598. goto error;
  599. }
  600. FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
  601. }
  602. if (script_debugger) {
  603. //there is a debugger, parse breakpoints
  604. for (int i = 0; i < breakpoints.size(); i++) {
  605. String bp = breakpoints[i];
  606. int sp = bp.find_last(":");
  607. if (sp == -1) {
  608. ERR_EXPLAIN("Invalid breakpoint: '" + bp + "', expected file:line format.");
  609. ERR_CONTINUE(sp == -1);
  610. }
  611. script_debugger->insert_breakpoint(bp.substr(sp + 1, bp.length()).to_int(), bp.substr(0, sp));
  612. }
  613. }
  614. #ifdef TOOLS_ENABLED
  615. if (editor) {
  616. packed_data->set_disabled(true);
  617. globals->set_disable_feature_overrides(true);
  618. StreamPeerSSL::initialize_certs = false; //will be initialized by editor
  619. }
  620. #endif
  621. GLOBAL_DEF("logging/file_logging/enable_file_logging", false);
  622. GLOBAL_DEF("logging/file_logging/log_path", "user://logs/log.txt");
  623. GLOBAL_DEF("logging/file_logging/max_log_files", 10);
  624. if (FileAccess::get_create_func(FileAccess::ACCESS_USERDATA) && GLOBAL_GET("logging/file_logging/enable_file_logging")) {
  625. String base_path = GLOBAL_GET("logging/file_logging/log_path");
  626. int max_files = GLOBAL_GET("logging/file_logging/max_log_files");
  627. OS::get_singleton()->add_logger(memnew(RotatedFileLogger(base_path, max_files)));
  628. }
  629. #ifdef TOOLS_ENABLED
  630. if (editor) {
  631. Engine::get_singleton()->set_editor_hint(true);
  632. main_args.push_back("--editor");
  633. if (!init_windowed) {
  634. init_maximized = true;
  635. video_mode.maximized = true;
  636. }
  637. }
  638. if (!project_manager) {
  639. // Determine if the project manager should be requested
  640. project_manager = main_args.size() == 0 && !found_project;
  641. }
  642. #endif
  643. if (main_args.size() == 0 && String(GLOBAL_DEF("application/run/main_scene", "")) == "") {
  644. #ifdef TOOLS_ENABLED
  645. if (!editor && !project_manager) {
  646. #endif
  647. OS::get_singleton()->print("Error: Can't run project: no main scene defined.\n");
  648. goto error;
  649. #ifdef TOOLS_ENABLED
  650. }
  651. #endif
  652. }
  653. if (editor || project_manager) {
  654. use_custom_res = false;
  655. input_map->load_default(); //keys for editor
  656. } else {
  657. input_map->load_from_globals(); //keys for game
  658. }
  659. if (bool(ProjectSettings::get_singleton()->get("application/run/disable_stdout"))) {
  660. quiet_stdout = true;
  661. }
  662. if (bool(ProjectSettings::get_singleton()->get("application/run/disable_stderr"))) {
  663. _print_error_enabled = false;
  664. };
  665. if (quiet_stdout)
  666. _print_line_enabled = false;
  667. OS::get_singleton()->set_cmdline(execpath, main_args);
  668. GLOBAL_DEF("rendering/quality/driver/driver_name", "GLES3");
  669. ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/driver/driver_name", PropertyInfo(Variant::STRING, "rendering/quality/driver/driver_name", PROPERTY_HINT_ENUM, "GLES3,GLES2"));
  670. if (video_driver == "") {
  671. video_driver = GLOBAL_GET("rendering/quality/driver/driver_name");
  672. }
  673. GLOBAL_DEF("display/window/size/width", 1024);
  674. GLOBAL_DEF("display/window/size/height", 600);
  675. GLOBAL_DEF("display/window/size/resizable", true);
  676. GLOBAL_DEF("display/window/size/borderless", false);
  677. GLOBAL_DEF("display/window/size/fullscreen", false);
  678. GLOBAL_DEF("display/window/size/always_on_top", false);
  679. GLOBAL_DEF("display/window/size/test_width", 0);
  680. GLOBAL_DEF("display/window/size/test_height", 0);
  681. if (use_custom_res) {
  682. if (!force_res) {
  683. video_mode.width = GLOBAL_GET("display/window/size/width");
  684. video_mode.height = GLOBAL_GET("display/window/size/height");
  685. if (globals->has_setting("display/window/size/test_width") && globals->has_setting("display/window/size/test_height")) {
  686. int tw = globals->get("display/window/size/test_width");
  687. int th = globals->get("display/window/size/test_height");
  688. if (tw > 0 && th > 0) {
  689. video_mode.width = tw;
  690. video_mode.height = th;
  691. }
  692. }
  693. }
  694. video_mode.resizable = GLOBAL_GET("display/window/size/resizable");
  695. video_mode.borderless_window = GLOBAL_GET("display/window/size/borderless");
  696. video_mode.fullscreen = GLOBAL_GET("display/window/size/fullscreen");
  697. video_mode.always_on_top = GLOBAL_GET("display/window/size/always_on_top");
  698. }
  699. if (!force_lowdpi) {
  700. OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", false);
  701. }
  702. OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/allow_per_pixel_transparency", false);
  703. video_mode.use_vsync = GLOBAL_DEF("display/window/vsync/use_vsync", true);
  704. video_mode.layered = GLOBAL_DEF("display/window/per_pixel_transparency", false);
  705. video_mode.layered_splash = GLOBAL_DEF("display/window/per_pixel_transparency_splash", false);
  706. GLOBAL_DEF("rendering/quality/intended_usage/framebuffer_allocation", 2);
  707. GLOBAL_DEF("rendering/quality/intended_usage/framebuffer_allocation.mobile", 3);
  708. if (editor || project_manager) {
  709. // The editor and project manager always detect and use hiDPI if needed
  710. OS::get_singleton()->_allow_hidpi = true;
  711. OS::get_singleton()->_allow_layered = false;
  712. }
  713. Engine::get_singleton()->_pixel_snap = GLOBAL_DEF("rendering/quality/2d/use_pixel_snap", false);
  714. OS::get_singleton()->_keep_screen_on = GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true);
  715. if (rtm == -1) {
  716. rtm = GLOBAL_DEF("rendering/threads/thread_model", OS::RENDER_THREAD_SAFE);
  717. }
  718. if (rtm >= 0 && rtm < 3) {
  719. if (editor) {
  720. rtm = OS::RENDER_THREAD_SAFE;
  721. }
  722. OS::get_singleton()->_render_thread_mode = OS::RenderThreadMode(rtm);
  723. }
  724. /* Determine audio and video drivers */
  725. for (int i = 0; i < OS::get_singleton()->get_video_driver_count(); i++) {
  726. if (video_driver == OS::get_singleton()->get_video_driver_name(i)) {
  727. video_driver_idx = i;
  728. break;
  729. }
  730. }
  731. if (video_driver_idx < 0) {
  732. //OS::get_singleton()->alert("Invalid Video Driver: " + video_driver);
  733. video_driver_idx = 0;
  734. //goto error;
  735. }
  736. if (audio_driver == "") { // specified in project.godot
  737. audio_driver = GLOBAL_DEF("audio/driver", OS::get_singleton()->get_audio_driver_name(0));
  738. }
  739. for (int i = 0; i < OS::get_singleton()->get_audio_driver_count(); i++) {
  740. if (audio_driver == OS::get_singleton()->get_audio_driver_name(i)) {
  741. audio_driver_idx = i;
  742. break;
  743. }
  744. }
  745. if (audio_driver_idx < 0) {
  746. OS::get_singleton()->alert("Invalid Audio Driver: " + audio_driver);
  747. audio_driver_idx = 0;
  748. //goto error;
  749. }
  750. {
  751. String orientation = GLOBAL_DEF("display/window/handheld/orientation", "landscape");
  752. if (orientation == "portrait")
  753. OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
  754. else if (orientation == "reverse_landscape")
  755. OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
  756. else if (orientation == "reverse_portrait")
  757. OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
  758. else if (orientation == "sensor_landscape")
  759. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
  760. else if (orientation == "sensor_portrait")
  761. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
  762. else if (orientation == "sensor")
  763. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
  764. else
  765. OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
  766. }
  767. Engine::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/common/physics_fps", 60));
  768. Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF("physics/common/physics_jitter_fix", 0.5));
  769. Engine::get_singleton()->set_target_fps(GLOBAL_DEF("debug/settings/fps/force_fps", 0));
  770. GLOBAL_DEF("debug/settings/stdout/print_fps", false);
  771. if (!OS::get_singleton()->_verbose_stdout) //overridden
  772. OS::get_singleton()->_verbose_stdout = GLOBAL_DEF("debug/settings/stdout/verbose_stdout", false);
  773. if (frame_delay == 0) {
  774. frame_delay = GLOBAL_DEF("application/run/frame_delay_msec", 0);
  775. }
  776. OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false));
  777. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(GLOBAL_DEF("application/run/low_processor_mode_sleep_usec", 8000));
  778. Engine::get_singleton()->set_frame_delay(frame_delay);
  779. message_queue = memnew(MessageQueue);
  780. ProjectSettings::get_singleton()->register_global_defaults();
  781. if (p_second_phase)
  782. return setup2();
  783. return OK;
  784. error:
  785. video_driver = "";
  786. audio_driver = "";
  787. project_path = "";
  788. args.clear();
  789. main_args.clear();
  790. if (show_help)
  791. print_help(execpath);
  792. if (performance)
  793. memdelete(performance);
  794. if (input_map)
  795. memdelete(input_map);
  796. if (translation_server)
  797. memdelete(translation_server);
  798. if (globals)
  799. memdelete(globals);
  800. if (engine)
  801. memdelete(engine);
  802. if (script_debugger)
  803. memdelete(script_debugger);
  804. if (packed_data)
  805. memdelete(packed_data);
  806. if (file_access_network_client)
  807. memdelete(file_access_network_client);
  808. // Note 1: *zip_packed_data live into *packed_data
  809. // Note 2: PackedData::~PackedData destroy this.
  810. /*
  811. #ifdef MINIZIP_ENABLED
  812. if (zip_packed_data)
  813. memdelete( zip_packed_data );
  814. #endif
  815. */
  816. unregister_core_driver_types();
  817. unregister_core_types();
  818. OS::get_singleton()->_cmdline.clear();
  819. if (message_queue)
  820. memdelete(message_queue);
  821. OS::get_singleton()->finalize_core();
  822. locale = String();
  823. return ERR_INVALID_PARAMETER;
  824. }
  825. Error Main::setup2(Thread::ID p_main_tid_override) {
  826. if (p_main_tid_override) {
  827. Thread::_main_thread_id = p_main_tid_override;
  828. }
  829. Error err = OS::get_singleton()->initialize(video_mode, video_driver_idx, audio_driver_idx);
  830. if (err != OK) {
  831. return err;
  832. }
  833. if (init_use_custom_pos) {
  834. OS::get_singleton()->set_window_position(init_custom_pos);
  835. }
  836. // right moment to create and initialize the audio server
  837. audio_server = memnew(AudioServer);
  838. audio_server->init();
  839. // also init our arvr_server from here
  840. arvr_server = memnew(ARVRServer);
  841. register_core_singletons();
  842. MAIN_PRINT("Main: Setup Logo");
  843. #ifdef JAVASCRIPT_ENABLED
  844. bool show_logo = false;
  845. #else
  846. bool show_logo = true;
  847. #endif
  848. if (init_screen != -1) {
  849. OS::get_singleton()->set_current_screen(init_screen);
  850. }
  851. if (init_windowed) {
  852. //do none..
  853. } else if (init_maximized) {
  854. OS::get_singleton()->set_window_maximized(true);
  855. } else if (init_fullscreen) {
  856. OS::get_singleton()->set_window_fullscreen(true);
  857. }
  858. if (init_always_on_top) {
  859. OS::get_singleton()->set_window_always_on_top(true);
  860. }
  861. register_server_types();
  862. MAIN_PRINT("Main: Load Remaps");
  863. Color clear = GLOBAL_DEF("rendering/environment/default_clear_color", Color(0.3, 0.3, 0.3));
  864. VisualServer::get_singleton()->set_default_clear_color(clear);
  865. if (show_logo) { //boot logo!
  866. String boot_logo_path = GLOBAL_DEF("application/boot_splash/image", String());
  867. bool boot_logo_scale = GLOBAL_DEF("application/boot_splash/fullsize", true);
  868. ProjectSettings::get_singleton()->set_custom_property_info("application/boot_splash/image", PropertyInfo(Variant::STRING, "application/boot_splash/image", PROPERTY_HINT_FILE, "*.png"));
  869. Ref<Image> boot_logo;
  870. boot_logo_path = boot_logo_path.strip_edges();
  871. if (boot_logo_path != String() /*&& FileAccess::exists(boot_logo_path)*/) {
  872. print_line("Boot splash path: " + boot_logo_path);
  873. boot_logo.instance();
  874. Error err = boot_logo->load(boot_logo_path);
  875. if (err)
  876. ERR_PRINTS("Non-existing or invalid boot splash at: " + boot_logo_path + ". Loading default splash.");
  877. }
  878. if (boot_logo.is_valid()) {
  879. OS::get_singleton()->_msec_splash = OS::get_singleton()->get_ticks_msec();
  880. Color boot_bg = GLOBAL_DEF("application/boot_splash/bg_color", clear);
  881. VisualServer::get_singleton()->set_boot_image(boot_logo, boot_bg, boot_logo_scale);
  882. #ifndef TOOLS_ENABLED
  883. //no tools, so free the boot logo (no longer needed)
  884. //ProjectSettings::get_singleton()->set("application/boot_logo",Image());
  885. #endif
  886. } else {
  887. #ifndef NO_DEFAULT_BOOT_LOGO
  888. MAIN_PRINT("Main: Create bootsplash");
  889. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  890. Ref<Image> splash = (editor || project_manager) ? memnew(Image(boot_splash_editor_png)) : memnew(Image(boot_splash_png));
  891. #else
  892. Ref<Image> splash = memnew(Image(boot_splash_png));
  893. #endif
  894. MAIN_PRINT("Main: ClearColor");
  895. VisualServer::get_singleton()->set_default_clear_color(boot_splash_bg_color);
  896. MAIN_PRINT("Main: Image");
  897. VisualServer::get_singleton()->set_boot_image(splash, boot_splash_bg_color, false);
  898. #endif
  899. }
  900. #ifdef TOOLS_ENABLED
  901. Ref<Image> icon = memnew(Image(app_icon_png));
  902. OS::get_singleton()->set_icon(icon);
  903. #endif
  904. }
  905. MAIN_PRINT("Main: DCC");
  906. VisualServer::get_singleton()->set_default_clear_color(GLOBAL_DEF("rendering/environment/default_clear_color", Color(0.3, 0.3, 0.3)));
  907. MAIN_PRINT("Main: END");
  908. GLOBAL_DEF("application/config/icon", String());
  909. ProjectSettings::get_singleton()->set_custom_property_info("application/config/icon", PropertyInfo(Variant::STRING, "application/config/icon", PROPERTY_HINT_FILE, "*.png,*.webp"));
  910. InputDefault *id = Object::cast_to<InputDefault>(Input::get_singleton());
  911. if (id) {
  912. if (bool(GLOBAL_DEF("input_devices/pointing/emulate_touch_from_mouse", false)) && !(editor || project_manager)) {
  913. if (!OS::get_singleton()->has_touchscreen_ui_hint()) {
  914. //only if no touchscreen ui hint, set emulation
  915. id->set_emulate_touch_from_mouse(true);
  916. }
  917. }
  918. id->set_emulate_mouse_from_touch(bool(GLOBAL_DEF("input_devices/pointing/emulate_mouse_from_touch", true)));
  919. }
  920. MAIN_PRINT("Main: Load Remaps");
  921. MAIN_PRINT("Main: Load Scene Types");
  922. register_scene_types();
  923. GLOBAL_DEF("display/mouse_cursor/custom_image", String());
  924. GLOBAL_DEF("display/mouse_cursor/custom_image_hotspot", Vector2());
  925. ProjectSettings::get_singleton()->set_custom_property_info("display/mouse_cursor/custom_image", PropertyInfo(Variant::STRING, "display/mouse_cursor/custom_image", PROPERTY_HINT_FILE, "*.png,*.webp"));
  926. if (String(ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image")) != String()) {
  927. //print_line("use custom cursor");
  928. Ref<Texture> cursor = ResourceLoader::load(ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image"));
  929. if (cursor.is_valid()) {
  930. //print_line("loaded ok");
  931. Vector2 hotspot = ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image_hotspot");
  932. Input::get_singleton()->set_custom_mouse_cursor(cursor, Input::CURSOR_ARROW, hotspot);
  933. }
  934. }
  935. #ifdef TOOLS_ENABLED
  936. ClassDB::set_current_api(ClassDB::API_EDITOR);
  937. EditorNode::register_editor_types();
  938. ClassDB::set_current_api(ClassDB::API_CORE);
  939. #endif
  940. if (allow_focus_steal_pid) {
  941. OS::get_singleton()->enable_for_stealing_focus(allow_focus_steal_pid);
  942. }
  943. MAIN_PRINT("Main: Load Modules, Physics, Drivers, Scripts");
  944. register_platform_apis();
  945. register_module_types();
  946. initialize_physics();
  947. register_server_singletons();
  948. register_driver_types();
  949. ScriptServer::init_languages();
  950. MAIN_PRINT("Main: Load Translations");
  951. translation_server->setup(); //register translations, load them, etc.
  952. if (locale != "") {
  953. translation_server->set_locale(locale);
  954. }
  955. translation_server->load_translations();
  956. ResourceLoader::load_translation_remaps(); //load remaps for resources
  957. ResourceLoader::load_path_remaps();
  958. audio_server->load_default_bus_layout();
  959. if (use_debug_profiler && script_debugger) {
  960. script_debugger->profiling_start();
  961. }
  962. _start_success = true;
  963. locale = String();
  964. ClassDB::set_current_api(ClassDB::API_NONE); //no more api is registered at this point
  965. if (OS::get_singleton()->is_stdout_verbose()) {
  966. print_line("CORE API HASH: " + itos(ClassDB::get_api_hash(ClassDB::API_CORE)));
  967. print_line("EDITOR API HASH: " + itos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
  968. }
  969. MAIN_PRINT("Main: Done");
  970. return OK;
  971. }
  972. // everything the main loop needs to know about frame timings
  973. struct _FrameTime {
  974. float animation_step; // time to advance animations for (argument to process())
  975. int physics_steps; // number of times to iterate the physics engine
  976. void clamp_animation(float min_animation_step, float max_animation_step) {
  977. if (animation_step < min_animation_step) {
  978. animation_step = min_animation_step;
  979. } else if (animation_step > max_animation_step) {
  980. animation_step = max_animation_step;
  981. }
  982. }
  983. };
  984. class _TimerSync {
  985. // wall clock time measured on the main thread
  986. uint64_t last_cpu_ticks_usec;
  987. uint64_t current_cpu_ticks_usec;
  988. // logical game time since last physics timestep
  989. float time_accum;
  990. // current difference between wall clock time and reported sum of animation_steps
  991. float time_deficit;
  992. // number of frames back for keeping accumulated physics steps roughly constant.
  993. // value of 12 chosen because that is what is required to make 144 Hz monitors
  994. // behave well with 60 Hz physics updates. The only worse commonly available refresh
  995. // would be 85, requiring CONTROL_STEPS = 17.
  996. static const int CONTROL_STEPS = 12;
  997. // sum of physics steps done over the last (i+1) frames
  998. int accumulated_physics_steps[CONTROL_STEPS];
  999. // typical value for accumulated_physics_steps[i] is either this or this plus one
  1000. int typical_physics_steps[CONTROL_STEPS];
  1001. protected:
  1002. // returns the fraction of p_frame_slice required for the timer to overshoot
  1003. // before advance_core considers changing the physics_steps return from
  1004. // the typical values as defined by typical_physics_steps
  1005. float get_physics_jitter_fix() {
  1006. return Engine::get_singleton()->get_physics_jitter_fix();
  1007. }
  1008. // gets our best bet for the average number of physics steps per render frame
  1009. // return value: number of frames back this data is consistent
  1010. int get_average_physics_steps(float &p_min, float &p_max) {
  1011. p_min = typical_physics_steps[0];
  1012. p_max = p_min + 1;
  1013. for (int i = 1; i < CONTROL_STEPS; ++i) {
  1014. const float typical_lower = typical_physics_steps[i];
  1015. const float current_min = typical_lower / (i + 1);
  1016. if (current_min > p_max)
  1017. return i; // bail out of further restrictions would void the interval
  1018. else if (current_min > p_min)
  1019. p_min = current_min;
  1020. const float current_max = (typical_lower + 1) / (i + 1);
  1021. if (current_max < p_min)
  1022. return i;
  1023. else if (current_max < p_max)
  1024. p_max = current_max;
  1025. }
  1026. return CONTROL_STEPS;
  1027. }
  1028. // advance physics clock by p_animation_step, return appropriate number of steps to simulate
  1029. _FrameTime advance_core(float p_frame_slice, int p_iterations_per_second, float p_animation_step) {
  1030. _FrameTime ret;
  1031. ret.animation_step = p_animation_step;
  1032. // simple determination of number of physics iteration
  1033. time_accum += ret.animation_step;
  1034. ret.physics_steps = floor(time_accum * p_iterations_per_second);
  1035. int min_typical_steps = typical_physics_steps[0];
  1036. int max_typical_steps = min_typical_steps + 1;
  1037. // given the past recorded steps and typcial steps to match, calculate bounds for this
  1038. // step to be typical
  1039. bool update_typical = false;
  1040. for (int i = 0; i < CONTROL_STEPS - 1; ++i) {
  1041. int steps_left_to_match_typical = typical_physics_steps[i + 1] - accumulated_physics_steps[i];
  1042. if (steps_left_to_match_typical > max_typical_steps ||
  1043. steps_left_to_match_typical + 1 < min_typical_steps) {
  1044. update_typical = true;
  1045. break;
  1046. }
  1047. if (steps_left_to_match_typical > min_typical_steps)
  1048. min_typical_steps = steps_left_to_match_typical;
  1049. if (steps_left_to_match_typical + 1 < max_typical_steps)
  1050. max_typical_steps = steps_left_to_match_typical + 1;
  1051. }
  1052. // try to keep it consistent with previous iterations
  1053. if (ret.physics_steps < min_typical_steps) {
  1054. const int max_possible_steps = floor((time_accum)*p_iterations_per_second + get_physics_jitter_fix());
  1055. if (max_possible_steps < min_typical_steps) {
  1056. ret.physics_steps = max_possible_steps;
  1057. update_typical = true;
  1058. } else {
  1059. ret.physics_steps = min_typical_steps;
  1060. }
  1061. } else if (ret.physics_steps > max_typical_steps) {
  1062. const int min_possible_steps = floor((time_accum)*p_iterations_per_second - get_physics_jitter_fix());
  1063. if (min_possible_steps > max_typical_steps) {
  1064. ret.physics_steps = min_possible_steps;
  1065. update_typical = true;
  1066. } else {
  1067. ret.physics_steps = max_typical_steps;
  1068. }
  1069. }
  1070. time_accum -= ret.physics_steps * p_frame_slice;
  1071. // keep track of accumulated step counts
  1072. for (int i = CONTROL_STEPS - 2; i >= 0; --i) {
  1073. accumulated_physics_steps[i + 1] = accumulated_physics_steps[i] + ret.physics_steps;
  1074. }
  1075. accumulated_physics_steps[0] = ret.physics_steps;
  1076. if (update_typical) {
  1077. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  1078. if (typical_physics_steps[i] > accumulated_physics_steps[i]) {
  1079. typical_physics_steps[i] = accumulated_physics_steps[i];
  1080. } else if (typical_physics_steps[i] < accumulated_physics_steps[i] - 1) {
  1081. typical_physics_steps[i] = accumulated_physics_steps[i] - 1;
  1082. }
  1083. }
  1084. }
  1085. return ret;
  1086. }
  1087. // calls advance_core, keeps track of deficit it adds to animaption_step, make sure the deficit sum stays close to zero
  1088. _FrameTime advance_checked(float p_frame_slice, int p_iterations_per_second, float p_animation_step) {
  1089. if (fixed_fps != -1)
  1090. p_animation_step = 1.0 / fixed_fps;
  1091. // compensate for last deficit
  1092. p_animation_step += time_deficit;
  1093. _FrameTime ret = advance_core(p_frame_slice, p_iterations_per_second, p_animation_step);
  1094. // we will do some clamping on ret.animation_step and need to sync those changes to time_accum,
  1095. // that's easiest if we just remember their fixed difference now
  1096. const double animation_minus_accum = ret.animation_step - time_accum;
  1097. // first, least important clamping: keep ret.animation_step consistent with typical_physics_steps.
  1098. // this smoothes out the animation steps and culls small but quick variations.
  1099. {
  1100. float min_average_physics_steps, max_average_physics_steps;
  1101. int consistent_steps = get_average_physics_steps(min_average_physics_steps, max_average_physics_steps);
  1102. if (consistent_steps > 3) {
  1103. ret.clamp_animation(min_average_physics_steps * p_frame_slice, max_average_physics_steps * p_frame_slice);
  1104. }
  1105. }
  1106. // second clamping: keep abs(time_deficit) < jitter_fix * frame_slise
  1107. float max_clock_deviation = get_physics_jitter_fix() * p_frame_slice;
  1108. ret.clamp_animation(p_animation_step - max_clock_deviation, p_animation_step + max_clock_deviation);
  1109. // last clamping: make sure time_accum is between 0 and p_frame_slice for consistency between physics and animation
  1110. ret.clamp_animation(animation_minus_accum, animation_minus_accum + p_frame_slice);
  1111. // restore time_accum
  1112. time_accum = ret.animation_step - animation_minus_accum;
  1113. // track deficit
  1114. time_deficit = p_animation_step - ret.animation_step;
  1115. return ret;
  1116. }
  1117. // determine wall clock step since last iteration
  1118. float get_cpu_animation_step() {
  1119. uint64_t cpu_ticks_elapsed = current_cpu_ticks_usec - last_cpu_ticks_usec;
  1120. last_cpu_ticks_usec = current_cpu_ticks_usec;
  1121. return cpu_ticks_elapsed / 1000000.0;
  1122. }
  1123. public:
  1124. explicit _TimerSync() :
  1125. last_cpu_ticks_usec(0),
  1126. current_cpu_ticks_usec(0),
  1127. time_accum(0),
  1128. time_deficit(0) {
  1129. for (int i = CONTROL_STEPS - 1; i >= 0; --i) {
  1130. typical_physics_steps[i] = i;
  1131. accumulated_physics_steps[i] = i;
  1132. }
  1133. }
  1134. // start the clock
  1135. void init(uint64_t p_cpu_ticks_usec) {
  1136. current_cpu_ticks_usec = last_cpu_ticks_usec = p_cpu_ticks_usec;
  1137. }
  1138. // set measured wall clock time
  1139. void set_cpu_ticks_usec(uint64_t p_cpu_ticks_usec) {
  1140. current_cpu_ticks_usec = p_cpu_ticks_usec;
  1141. }
  1142. // advance one frame, return timesteps to take
  1143. _FrameTime advance(float p_frame_slice, int p_iterations_per_second) {
  1144. float cpu_animation_step = get_cpu_animation_step();
  1145. return advance_checked(p_frame_slice, p_iterations_per_second, cpu_animation_step);
  1146. }
  1147. void before_start_render() {
  1148. VisualServer::get_singleton()->sync();
  1149. }
  1150. };
  1151. static _TimerSync _timer_sync;
  1152. bool Main::start() {
  1153. ERR_FAIL_COND_V(!_start_success, false);
  1154. bool hasicon = false;
  1155. String doc_tool;
  1156. List<String> removal_docs;
  1157. bool doc_base = true;
  1158. String game_path;
  1159. String script;
  1160. String test;
  1161. String _export_preset;
  1162. bool export_debug = false;
  1163. _timer_sync.init(OS::get_singleton()->get_ticks_usec());
  1164. List<String> args = OS::get_singleton()->get_cmdline_args();
  1165. for (int i = 0; i < args.size(); i++) {
  1166. //parameters that do not have an argument to the right
  1167. if (args[i] == "--no-docbase") {
  1168. doc_base = false;
  1169. #ifdef TOOLS_ENABLED
  1170. } else if (args[i] == "-e" || args[i] == "--editor") {
  1171. editor = true;
  1172. } else if (args[i] == "-p" || args[i] == "--project-manager") {
  1173. project_manager = true;
  1174. #endif
  1175. } else if (args[i].length() && args[i][0] != '-' && game_path == "") {
  1176. game_path = args[i];
  1177. }
  1178. //parameters that have an argument to the right
  1179. else if (i < (args.size() - 1)) {
  1180. bool parsed_pair = true;
  1181. if (args[i] == "-s" || args[i] == "--script") {
  1182. script = args[i + 1];
  1183. } else if (args[i] == "--test") {
  1184. test = args[i + 1];
  1185. #ifdef TOOLS_ENABLED
  1186. } else if (args[i] == "--doctool") {
  1187. doc_tool = args[i + 1];
  1188. for (int j = i + 2; j < args.size(); j++)
  1189. removal_docs.push_back(args[j]);
  1190. } else if (args[i] == "--export") {
  1191. editor = true; //needs editor
  1192. if (i + 1 < args.size()) {
  1193. _export_preset = args[i + 1];
  1194. } else {
  1195. ERR_PRINT("Export preset name not specified");
  1196. return false;
  1197. }
  1198. } else if (args[i] == "--export-debug") {
  1199. editor = true; //needs editor
  1200. if (i + 1 < args.size()) {
  1201. _export_preset = args[i + 1];
  1202. } else {
  1203. ERR_PRINT("Export preset name not specified");
  1204. return false;
  1205. }
  1206. export_debug = true;
  1207. #endif
  1208. } else {
  1209. // The parameter does not match anything known, don't skip the next argument
  1210. parsed_pair = false;
  1211. }
  1212. if (parsed_pair) {
  1213. i++;
  1214. }
  1215. }
  1216. }
  1217. GLOBAL_DEF("editor/active", editor);
  1218. String main_loop_type;
  1219. #ifdef TOOLS_ENABLED
  1220. if (doc_tool != "") {
  1221. {
  1222. DirAccessRef da = DirAccess::open(doc_tool);
  1223. if (!da) {
  1224. ERR_EXPLAIN("Argument supplied to --doctool must be a base godot build directory");
  1225. ERR_FAIL_V(false);
  1226. }
  1227. }
  1228. DocData doc;
  1229. doc.generate(doc_base);
  1230. DocData docsrc;
  1231. Map<String, String> doc_data_classes;
  1232. Set<String> checked_paths;
  1233. print_line("Loading docs...");
  1234. for (int i = 0; i < _doc_data_class_path_count; i++) {
  1235. String path = doc_tool.plus_file(_doc_data_class_paths[i].path);
  1236. String name = _doc_data_class_paths[i].name;
  1237. doc_data_classes[name] = path;
  1238. if (!checked_paths.has(path)) {
  1239. checked_paths.insert(path);
  1240. docsrc.load_classes(path);
  1241. print_line("Loading docs from: " + path);
  1242. }
  1243. }
  1244. String index_path = doc_tool.plus_file("doc/classes");
  1245. docsrc.load_classes(index_path);
  1246. checked_paths.insert(index_path);
  1247. print_line("Loading docs from: " + index_path);
  1248. print_line("Merging docs...");
  1249. doc.merge_from(docsrc);
  1250. for (Set<String>::Element *E = checked_paths.front(); E; E = E->next()) {
  1251. print_line("Erasing old docs at: " + E->get());
  1252. DocData::erase_classes(E->get());
  1253. }
  1254. print_line("Generating new docs...");
  1255. doc.save_classes(index_path, doc_data_classes);
  1256. return false;
  1257. }
  1258. #endif
  1259. if (_export_preset != "") {
  1260. if (game_path == "") {
  1261. String err = "Command line param ";
  1262. err += export_debug ? "--export-debug" : "--export";
  1263. err += " passed but no destination path given.\n";
  1264. err += "Please specify the binary's file path to export to. Aborting export.";
  1265. ERR_PRINT(err.utf8().get_data());
  1266. return false;
  1267. }
  1268. }
  1269. if (script == "" && game_path == "" && String(GLOBAL_DEF("application/run/main_scene", "")) != "") {
  1270. game_path = GLOBAL_DEF("application/run/main_scene", "");
  1271. }
  1272. MainLoop *main_loop = NULL;
  1273. if (editor) {
  1274. main_loop = memnew(SceneTree);
  1275. };
  1276. if (test != "") {
  1277. #ifdef DEBUG_ENABLED
  1278. main_loop = test_main(test, args);
  1279. if (!main_loop)
  1280. return false;
  1281. #endif
  1282. } else if (script != "") {
  1283. Ref<Script> script_res = ResourceLoader::load(script);
  1284. ERR_EXPLAIN("Can't load script: " + script);
  1285. ERR_FAIL_COND_V(script_res.is_null(), false);
  1286. if (script_res->can_instance() /*&& script_res->inherits_from("SceneTreeScripted")*/) {
  1287. StringName instance_type = script_res->get_instance_base_type();
  1288. Object *obj = ClassDB::instance(instance_type);
  1289. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  1290. if (!script_loop) {
  1291. if (obj)
  1292. memdelete(obj);
  1293. ERR_EXPLAIN("Can't load script '" + script + "', it does not inherit from a MainLoop type");
  1294. ERR_FAIL_COND_V(!script_loop, false);
  1295. }
  1296. script_loop->set_init_script(script_res);
  1297. main_loop = script_loop;
  1298. } else {
  1299. return false;
  1300. }
  1301. } else {
  1302. main_loop_type = GLOBAL_DEF("application/run/main_loop_type", "");
  1303. }
  1304. if (!main_loop && main_loop_type == "")
  1305. main_loop_type = "SceneTree";
  1306. if (!main_loop) {
  1307. if (!ClassDB::class_exists(main_loop_type)) {
  1308. OS::get_singleton()->alert("Error: MainLoop type doesn't exist: " + main_loop_type);
  1309. return false;
  1310. } else {
  1311. Object *ml = ClassDB::instance(main_loop_type);
  1312. if (!ml) {
  1313. ERR_EXPLAIN("Can't instance MainLoop type");
  1314. ERR_FAIL_V(false);
  1315. }
  1316. main_loop = Object::cast_to<MainLoop>(ml);
  1317. if (!main_loop) {
  1318. memdelete(ml);
  1319. ERR_EXPLAIN("Invalid MainLoop type");
  1320. ERR_FAIL_V(false);
  1321. }
  1322. }
  1323. }
  1324. if (main_loop->is_class("SceneTree")) {
  1325. SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
  1326. #ifdef DEBUG_ENABLED
  1327. if (debug_collisions) {
  1328. sml->set_debug_collisions_hint(true);
  1329. }
  1330. if (debug_navigation) {
  1331. sml->set_debug_navigation_hint(true);
  1332. }
  1333. #endif
  1334. #ifdef TOOLS_ENABLED
  1335. EditorNode *editor_node = NULL;
  1336. if (editor) {
  1337. editor_node = memnew(EditorNode);
  1338. sml->get_root()->add_child(editor_node);
  1339. //root_node->set_editor(editor);
  1340. //startup editor
  1341. if (_export_preset != "") {
  1342. editor_node->export_preset(_export_preset, game_path, export_debug, "", true);
  1343. game_path = ""; //no load anything
  1344. }
  1345. }
  1346. #endif
  1347. {
  1348. }
  1349. if (!editor && !project_manager) {
  1350. //standard helpers that can be changed from main config
  1351. String stretch_mode = GLOBAL_DEF("display/window/stretch/mode", "disabled");
  1352. String stretch_aspect = GLOBAL_DEF("display/window/stretch/aspect", "ignore");
  1353. Size2i stretch_size = Size2(GLOBAL_DEF("display/window/size/width", 0), GLOBAL_DEF("display/window/size/height", 0));
  1354. real_t stretch_shrink = GLOBAL_DEF("display/window/stretch/shrink", 1.0f);
  1355. SceneTree::StretchMode sml_sm = SceneTree::STRETCH_MODE_DISABLED;
  1356. if (stretch_mode == "2d")
  1357. sml_sm = SceneTree::STRETCH_MODE_2D;
  1358. else if (stretch_mode == "viewport")
  1359. sml_sm = SceneTree::STRETCH_MODE_VIEWPORT;
  1360. SceneTree::StretchAspect sml_aspect = SceneTree::STRETCH_ASPECT_IGNORE;
  1361. if (stretch_aspect == "keep")
  1362. sml_aspect = SceneTree::STRETCH_ASPECT_KEEP;
  1363. else if (stretch_aspect == "keep_width")
  1364. sml_aspect = SceneTree::STRETCH_ASPECT_KEEP_WIDTH;
  1365. else if (stretch_aspect == "keep_height")
  1366. sml_aspect = SceneTree::STRETCH_ASPECT_KEEP_HEIGHT;
  1367. else if (stretch_aspect == "expand")
  1368. sml_aspect = SceneTree::STRETCH_ASPECT_EXPAND;
  1369. sml->set_screen_stretch(sml_sm, sml_aspect, stretch_size, stretch_shrink);
  1370. sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true));
  1371. sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true));
  1372. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  1373. appname = TranslationServer::get_singleton()->translate(appname);
  1374. OS::get_singleton()->set_window_title(appname);
  1375. int shadow_atlas_size = GLOBAL_GET("rendering/quality/shadow_atlas/size");
  1376. int shadow_atlas_q0_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_0_subdiv");
  1377. int shadow_atlas_q1_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_1_subdiv");
  1378. int shadow_atlas_q2_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_2_subdiv");
  1379. int shadow_atlas_q3_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_3_subdiv");
  1380. sml->get_root()->set_shadow_atlas_size(shadow_atlas_size);
  1381. sml->get_root()->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q0_subdiv));
  1382. sml->get_root()->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q1_subdiv));
  1383. sml->get_root()->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q2_subdiv));
  1384. sml->get_root()->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q3_subdiv));
  1385. Viewport::Usage usage = Viewport::Usage(int(GLOBAL_GET("rendering/quality/intended_usage/framebuffer_allocation")));
  1386. sml->get_root()->set_usage(usage);
  1387. bool snap_controls = GLOBAL_DEF("gui/common/snap_controls_to_pixels", true);
  1388. sml->get_root()->set_snap_controls_to_pixels(snap_controls);
  1389. bool font_oversampling = GLOBAL_DEF("rendering/quality/dynamic_fonts/use_oversampling", true);
  1390. sml->set_use_font_oversampling(font_oversampling);
  1391. } else {
  1392. GLOBAL_DEF("display/window/stretch/mode", "disabled");
  1393. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/mode", PropertyInfo(Variant::STRING, "display/window/stretch/mode", PROPERTY_HINT_ENUM, "disabled,2d,viewport"));
  1394. GLOBAL_DEF("display/window/stretch/aspect", "ignore");
  1395. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/aspect", PropertyInfo(Variant::STRING, "display/window/stretch/aspect", PROPERTY_HINT_ENUM, "ignore,keep,keep_width,keep_height,expand"));
  1396. GLOBAL_DEF("display/window/stretch/shrink", 1);
  1397. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/shrink", PropertyInfo(Variant::STRING, "display/window/stretch/shrink", PROPERTY_HINT_RANGE, "1,8,1"));
  1398. sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true));
  1399. sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true));
  1400. GLOBAL_DEF("gui/common/snap_controls_to_pixels", true);
  1401. GLOBAL_DEF("rendering/quality/dynamic_fonts/use_oversampling", true);
  1402. }
  1403. String local_game_path;
  1404. if (game_path != "" && !project_manager) {
  1405. local_game_path = game_path.replace("\\", "/");
  1406. if (!local_game_path.begins_with("res://")) {
  1407. bool absolute = (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
  1408. if (!absolute) {
  1409. if (ProjectSettings::get_singleton()->is_using_datapack()) {
  1410. local_game_path = "res://" + local_game_path;
  1411. } else {
  1412. int sep = local_game_path.find_last("/");
  1413. if (sep == -1) {
  1414. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1415. local_game_path = da->get_current_dir() + "/" + local_game_path;
  1416. memdelete(da);
  1417. } else {
  1418. DirAccess *da = DirAccess::open(local_game_path.substr(0, sep));
  1419. if (da) {
  1420. local_game_path = da->get_current_dir() + "/" + local_game_path.substr(sep + 1, local_game_path.length());
  1421. memdelete(da);
  1422. }
  1423. }
  1424. }
  1425. }
  1426. }
  1427. local_game_path = ProjectSettings::get_singleton()->localize_path(local_game_path);
  1428. #ifdef TOOLS_ENABLED
  1429. if (editor) {
  1430. Error serr = editor_node->load_scene(local_game_path);
  1431. if (serr != OK)
  1432. ERR_PRINT("Failed to load scene");
  1433. OS::get_singleton()->set_context(OS::CONTEXT_EDITOR);
  1434. }
  1435. #endif
  1436. }
  1437. if (!project_manager && !editor) { // game
  1438. if (game_path != "" || script != "") {
  1439. //autoload
  1440. List<PropertyInfo> props;
  1441. ProjectSettings::get_singleton()->get_property_list(&props);
  1442. //first pass, add the constants so they exist before any script is loaded
  1443. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  1444. String s = E->get().name;
  1445. if (!s.begins_with("autoload/"))
  1446. continue;
  1447. String name = s.get_slicec('/', 1);
  1448. String path = ProjectSettings::get_singleton()->get(s);
  1449. bool global_var = false;
  1450. if (path.begins_with("*")) {
  1451. global_var = true;
  1452. }
  1453. if (global_var) {
  1454. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1455. ScriptServer::get_language(i)->add_global_constant(name, Variant());
  1456. }
  1457. }
  1458. }
  1459. //second pass, load into global constants
  1460. List<Node *> to_add;
  1461. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  1462. String s = E->get().name;
  1463. if (!s.begins_with("autoload/"))
  1464. continue;
  1465. String name = s.get_slicec('/', 1);
  1466. String path = ProjectSettings::get_singleton()->get(s);
  1467. bool global_var = false;
  1468. if (path.begins_with("*")) {
  1469. global_var = true;
  1470. path = path.substr(1, path.length() - 1);
  1471. }
  1472. RES res = ResourceLoader::load(path);
  1473. ERR_EXPLAIN("Can't autoload: " + path);
  1474. ERR_CONTINUE(res.is_null());
  1475. Node *n = NULL;
  1476. if (res->is_class("PackedScene")) {
  1477. Ref<PackedScene> ps = res;
  1478. n = ps->instance();
  1479. } else if (res->is_class("Script")) {
  1480. Ref<Script> s = res;
  1481. StringName ibt = s->get_instance_base_type();
  1482. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  1483. ERR_EXPLAIN("Script does not inherit a Node: " + path);
  1484. ERR_CONTINUE(!valid_type);
  1485. Object *obj = ClassDB::instance(ibt);
  1486. ERR_EXPLAIN("Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt));
  1487. ERR_CONTINUE(obj == NULL);
  1488. n = Object::cast_to<Node>(obj);
  1489. n->set_script(s.get_ref_ptr());
  1490. }
  1491. ERR_EXPLAIN("Path in autoload not a node or script: " + path);
  1492. ERR_CONTINUE(!n);
  1493. n->set_name(name);
  1494. //defer so references are all valid on _ready()
  1495. to_add.push_back(n);
  1496. if (global_var) {
  1497. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1498. ScriptServer::get_language(i)->add_global_constant(name, n);
  1499. }
  1500. }
  1501. }
  1502. for (List<Node *>::Element *E = to_add.front(); E; E = E->next()) {
  1503. sml->get_root()->add_child(E->get());
  1504. }
  1505. }
  1506. if (game_path != "") {
  1507. Node *scene = NULL;
  1508. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  1509. if (scenedata.is_valid())
  1510. scene = scenedata->instance();
  1511. ERR_EXPLAIN("Failed loading scene: " + local_game_path);
  1512. ERR_FAIL_COND_V(!scene, false)
  1513. sml->add_current_scene(scene);
  1514. String iconpath = GLOBAL_DEF("application/config/icon", "Variant()");
  1515. if (iconpath != "") {
  1516. Ref<Image> icon;
  1517. icon.instance();
  1518. if (icon->load(iconpath) == OK) {
  1519. OS::get_singleton()->set_icon(icon);
  1520. hasicon = true;
  1521. }
  1522. }
  1523. }
  1524. }
  1525. #ifdef TOOLS_ENABLED
  1526. if (project_manager || (script == "" && test == "" && game_path == "" && !editor)) {
  1527. ProjectManager *pmanager = memnew(ProjectManager);
  1528. ProgressDialog *progress_dialog = memnew(ProgressDialog);
  1529. pmanager->add_child(progress_dialog);
  1530. sml->get_root()->add_child(pmanager);
  1531. OS::get_singleton()->set_context(OS::CONTEXT_PROJECTMAN);
  1532. }
  1533. #endif
  1534. }
  1535. if (!hasicon) {
  1536. Ref<Image> icon = memnew(Image(app_icon_png));
  1537. OS::get_singleton()->set_icon(icon);
  1538. }
  1539. OS::get_singleton()->set_main_loop(main_loop);
  1540. return true;
  1541. }
  1542. uint64_t Main::last_ticks = 0;
  1543. uint64_t Main::target_ticks = 0;
  1544. uint32_t Main::frames = 0;
  1545. uint32_t Main::frame = 0;
  1546. bool Main::force_redraw_requested = false;
  1547. //for performance metrics
  1548. static uint64_t physics_process_max = 0;
  1549. static uint64_t idle_process_max = 0;
  1550. bool Main::iteration() {
  1551. uint64_t ticks = OS::get_singleton()->get_ticks_usec();
  1552. Engine::get_singleton()->_frame_ticks = ticks;
  1553. _timer_sync.set_cpu_ticks_usec(ticks);
  1554. uint64_t ticks_elapsed = ticks - last_ticks;
  1555. int physics_fps = Engine::get_singleton()->get_iterations_per_second();
  1556. float frame_slice = 1.0 / physics_fps;
  1557. _FrameTime advance = _timer_sync.advance(frame_slice, physics_fps);
  1558. double step = advance.animation_step;
  1559. Engine::get_singleton()->_frame_step = step;
  1560. /*
  1561. if (time_accum+step < frame_slice)
  1562. return false;
  1563. */
  1564. uint64_t physics_process_ticks = 0;
  1565. uint64_t idle_process_ticks = 0;
  1566. frame += ticks_elapsed;
  1567. last_ticks = ticks;
  1568. static const int max_physics_steps = 8;
  1569. if (fixed_fps == -1 && advance.physics_steps > max_physics_steps) {
  1570. step -= (advance.physics_steps - max_physics_steps) * frame_slice;
  1571. advance.physics_steps = max_physics_steps;
  1572. }
  1573. float time_scale = Engine::get_singleton()->get_time_scale();
  1574. bool exit = false;
  1575. Engine::get_singleton()->_in_physics = true;
  1576. for (int iters = 0; iters < advance.physics_steps; ++iters) {
  1577. uint64_t physics_begin = OS::get_singleton()->get_ticks_usec();
  1578. PhysicsServer::get_singleton()->sync();
  1579. PhysicsServer::get_singleton()->flush_queries();
  1580. Physics2DServer::get_singleton()->sync();
  1581. Physics2DServer::get_singleton()->flush_queries();
  1582. if (OS::get_singleton()->get_main_loop()->iteration(frame_slice * time_scale)) {
  1583. exit = true;
  1584. break;
  1585. }
  1586. message_queue->flush();
  1587. PhysicsServer::get_singleton()->step(frame_slice * time_scale);
  1588. Physics2DServer::get_singleton()->end_sync();
  1589. Physics2DServer::get_singleton()->step(frame_slice * time_scale);
  1590. message_queue->flush();
  1591. physics_process_ticks = MAX(physics_process_ticks, OS::get_singleton()->get_ticks_usec() - physics_begin); // keep the largest one for reference
  1592. physics_process_max = MAX(OS::get_singleton()->get_ticks_usec() - physics_begin, physics_process_max);
  1593. Engine::get_singleton()->_physics_frames++;
  1594. }
  1595. Engine::get_singleton()->_in_physics = false;
  1596. uint64_t idle_begin = OS::get_singleton()->get_ticks_usec();
  1597. OS::get_singleton()->get_main_loop()->idle(step * time_scale);
  1598. message_queue->flush();
  1599. _timer_sync.before_start_render(); //sync if still drawing from previous frames.
  1600. if (OS::get_singleton()->can_draw() && !disable_render_loop) {
  1601. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  1602. if (VisualServer::get_singleton()->has_changed()) {
  1603. VisualServer::get_singleton()->draw(); // flush visual commands
  1604. Engine::get_singleton()->frames_drawn++;
  1605. }
  1606. } else {
  1607. VisualServer::get_singleton()->draw(); // flush visual commands
  1608. Engine::get_singleton()->frames_drawn++;
  1609. force_redraw_requested = false;
  1610. }
  1611. }
  1612. if (AudioServer::get_singleton())
  1613. AudioServer::get_singleton()->update();
  1614. idle_process_ticks = OS::get_singleton()->get_ticks_usec() - idle_begin;
  1615. idle_process_max = MAX(idle_process_ticks, idle_process_max);
  1616. uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
  1617. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1618. ScriptServer::get_language(i)->frame();
  1619. }
  1620. if (script_debugger) {
  1621. if (script_debugger->is_profiling()) {
  1622. script_debugger->profiling_set_frame_times(USEC_TO_SEC(frame_time), USEC_TO_SEC(idle_process_ticks), USEC_TO_SEC(physics_process_ticks), frame_slice);
  1623. }
  1624. script_debugger->idle_poll();
  1625. }
  1626. frames++;
  1627. Engine::get_singleton()->_idle_frames++;
  1628. if (frame > 1000000) {
  1629. if (editor || project_manager) {
  1630. if (print_fps) {
  1631. print_line("Editor FPS: " + itos(frames));
  1632. }
  1633. } else if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
  1634. print_line("Game FPS: " + itos(frames));
  1635. }
  1636. Engine::get_singleton()->_fps = frames;
  1637. performance->set_process_time(USEC_TO_SEC(idle_process_max));
  1638. performance->set_physics_process_time(USEC_TO_SEC(physics_process_max));
  1639. idle_process_max = 0;
  1640. physics_process_max = 0;
  1641. frame %= 1000000;
  1642. frames = 0;
  1643. }
  1644. if (fixed_fps != -1)
  1645. return exit;
  1646. if (OS::get_singleton()->is_in_low_processor_usage_mode() || !OS::get_singleton()->can_draw())
  1647. OS::get_singleton()->delay_usec(OS::get_singleton()->get_low_processor_usage_mode_sleep_usec()); //apply some delay to force idle time (results in about 60 FPS max)
  1648. else {
  1649. uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  1650. if (frame_delay)
  1651. OS::get_singleton()->delay_usec(Engine::get_singleton()->get_frame_delay() * 1000);
  1652. }
  1653. int target_fps = Engine::get_singleton()->get_target_fps();
  1654. if (target_fps > 0) {
  1655. uint64_t time_step = 1000000L / target_fps;
  1656. target_ticks += time_step;
  1657. uint64_t current_ticks = OS::get_singleton()->get_ticks_usec();
  1658. if (current_ticks < target_ticks) OS::get_singleton()->delay_usec(target_ticks - current_ticks);
  1659. current_ticks = OS::get_singleton()->get_ticks_usec();
  1660. target_ticks = MIN(MAX(target_ticks, current_ticks - time_step), current_ticks + time_step);
  1661. }
  1662. #ifdef TOOLS_ENABLED
  1663. if (auto_build_solutions) {
  1664. auto_build_solutions = false;
  1665. if (!EditorNode::get_singleton()->call_build()) {
  1666. ERR_FAIL_V(true);
  1667. }
  1668. }
  1669. #endif
  1670. return exit || auto_quit;
  1671. }
  1672. void Main::force_redraw() {
  1673. force_redraw_requested = true;
  1674. };
  1675. void Main::cleanup() {
  1676. ERR_FAIL_COND(!_start_success);
  1677. message_queue->flush();
  1678. memdelete(message_queue);
  1679. if (script_debugger) {
  1680. if (use_debug_profiler) {
  1681. script_debugger->profiling_end();
  1682. }
  1683. memdelete(script_debugger);
  1684. }
  1685. OS::get_singleton()->delete_main_loop();
  1686. OS::get_singleton()->_cmdline.clear();
  1687. OS::get_singleton()->_execpath = "";
  1688. OS::get_singleton()->_local_clipboard = "";
  1689. ResourceLoader::clear_translation_remaps();
  1690. ResourceLoader::clear_path_remaps();
  1691. ScriptServer::finish_languages();
  1692. #ifdef TOOLS_ENABLED
  1693. EditorNode::unregister_editor_types();
  1694. #endif
  1695. if (arvr_server) {
  1696. // cleanup now before we pull the rug from underneath...
  1697. memdelete(arvr_server);
  1698. }
  1699. unregister_driver_types();
  1700. unregister_module_types();
  1701. unregister_platform_apis();
  1702. unregister_scene_types();
  1703. unregister_server_types();
  1704. if (audio_server) {
  1705. audio_server->finish();
  1706. memdelete(audio_server);
  1707. }
  1708. OS::get_singleton()->finalize();
  1709. finalize_physics();
  1710. if (packed_data)
  1711. memdelete(packed_data);
  1712. if (file_access_network_client)
  1713. memdelete(file_access_network_client);
  1714. if (performance)
  1715. memdelete(performance);
  1716. if (input_map)
  1717. memdelete(input_map);
  1718. if (translation_server)
  1719. memdelete(translation_server);
  1720. if (globals)
  1721. memdelete(globals);
  1722. if (engine)
  1723. memdelete(engine);
  1724. unregister_core_driver_types();
  1725. unregister_core_types();
  1726. OS::get_singleton()->clear_last_error();
  1727. OS::get_singleton()->finalize_core();
  1728. }