main.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388
  1. /*************************************************************************/
  2. /* main.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "core/crypto/crypto.h"
  32. #include "core/debugger/engine_debugger.h"
  33. #include "core/input/input.h"
  34. #include "core/input/input_map.h"
  35. #include "core/io/file_access_network.h"
  36. #include "core/io/file_access_pack.h"
  37. #include "core/io/file_access_zip.h"
  38. #include "core/io/image_loader.h"
  39. #include "core/io/ip.h"
  40. #include "core/io/resource_loader.h"
  41. #include "core/message_queue.h"
  42. #include "core/os/dir_access.h"
  43. #include "core/os/os.h"
  44. #include "core/project_settings.h"
  45. #include "core/register_core_types.h"
  46. #include "core/translation.h"
  47. #include "core/version.h"
  48. #include "core/version_hash.gen.h"
  49. #include "drivers/register_driver_types.h"
  50. #include "main/app_icon.gen.h"
  51. #include "main/main_timer_sync.h"
  52. #include "main/performance.h"
  53. #include "main/splash.gen.h"
  54. #include "main/splash_editor.gen.h"
  55. #include "main/tests/test_main.h"
  56. #include "modules/modules_enabled.gen.h"
  57. #include "modules/register_module_types.h"
  58. #include "platform/register_platform_apis.h"
  59. #include "scene/main/scene_tree.h"
  60. #include "scene/main/window.h"
  61. #include "scene/register_scene_types.h"
  62. #include "scene/resources/packed_scene.h"
  63. #include "servers/audio_server.h"
  64. #include "servers/camera_server.h"
  65. #include "servers/display_server.h"
  66. #include "servers/navigation_server_2d.h"
  67. #include "servers/navigation_server_3d.h"
  68. #include "servers/physics_server_2d.h"
  69. #include "servers/physics_server_3d.h"
  70. #include "servers/register_server_types.h"
  71. #include "servers/rendering/rendering_server_raster.h"
  72. #include "servers/rendering/rendering_server_wrap_mt.h"
  73. #include "servers/xr_server.h"
  74. #ifdef TOOLS_ENABLED
  75. #include "editor/doc_data.h"
  76. #include "editor/doc_data_class_path.gen.h"
  77. #include "editor/editor_node.h"
  78. #include "editor/editor_settings.h"
  79. #include "editor/progress_dialog.h"
  80. #include "editor/project_manager.h"
  81. #endif
  82. /* Static members */
  83. // Singletons
  84. // Initialized in setup()
  85. static Engine *engine = nullptr;
  86. static ProjectSettings *globals = nullptr;
  87. static Input *input = nullptr;
  88. static InputMap *input_map = nullptr;
  89. static TranslationServer *translation_server = nullptr;
  90. static Performance *performance = nullptr;
  91. static PackedData *packed_data = nullptr;
  92. #ifdef MINIZIP_ENABLED
  93. static ZipArchive *zip_packed_data = nullptr;
  94. #endif
  95. static FileAccessNetworkClient *file_access_network_client = nullptr;
  96. static MessageQueue *message_queue = nullptr;
  97. // Initialized in setup2()
  98. static AudioServer *audio_server = nullptr;
  99. static DisplayServer *display_server = nullptr;
  100. static RenderingServer *rendering_server = nullptr;
  101. static CameraServer *camera_server = nullptr;
  102. static XRServer *xr_server = nullptr;
  103. static PhysicsServer3D *physics_server = nullptr;
  104. static PhysicsServer2D *physics_2d_server = nullptr;
  105. static NavigationServer3D *navigation_server = nullptr;
  106. static NavigationServer2D *navigation_2d_server = nullptr;
  107. // We error out if setup2() doesn't turn this true
  108. static bool _start_success = false;
  109. // Drivers
  110. static int display_driver_idx = -1;
  111. static int audio_driver_idx = -1;
  112. // Engine config/tools
  113. static bool single_window = false;
  114. static bool editor = false;
  115. static bool project_manager = false;
  116. static String locale;
  117. static bool show_help = false;
  118. static bool auto_quit = false;
  119. static OS::ProcessID allow_focus_steal_pid = 0;
  120. #ifdef TOOLS_ENABLED
  121. static bool auto_build_solutions = false;
  122. #endif
  123. // Display
  124. static DisplayServer::WindowMode window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
  125. static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCREEN_LANDSCAPE;
  126. static uint32_t window_flags = 0;
  127. static Size2i window_size = Size2i(1024, 600);
  128. static bool window_vsync_via_compositor = false;
  129. static bool disable_wintab = false;
  130. static int init_screen = -1;
  131. static bool init_fullscreen = false;
  132. static bool init_maximized = false;
  133. static bool init_windowed = false;
  134. static bool init_always_on_top = false;
  135. static bool init_use_custom_pos = false;
  136. static Vector2 init_custom_pos;
  137. static bool force_lowdpi = false;
  138. // Debug
  139. static bool use_debug_profiler = false;
  140. #ifdef DEBUG_ENABLED
  141. static bool debug_collisions = false;
  142. static bool debug_navigation = false;
  143. #endif
  144. static int frame_delay = 0;
  145. static bool disable_render_loop = false;
  146. static int fixed_fps = -1;
  147. static bool print_fps = false;
  148. /* Helper methods */
  149. // Used by Mono module, should likely be registered in Engine singleton instead
  150. // FIXME: This is also not 100% accurate, `project_manager` is only true when it was requested,
  151. // but not if e.g. we fail to load and project and fallback to the manager.
  152. bool Main::is_project_manager() {
  153. return project_manager;
  154. }
  155. static String unescape_cmdline(const String &p_str) {
  156. return p_str.replace("%20", " ");
  157. }
  158. static String get_full_version_string() {
  159. String hash = String(VERSION_HASH);
  160. if (hash.length() != 0)
  161. hash = "." + hash.left(9);
  162. return String(VERSION_FULL_BUILD) + hash;
  163. }
  164. // FIXME: Could maybe be moved to PhysicsServer3DManager and PhysicsServer2DManager directly
  165. // to have less code in main.cpp.
  166. void initialize_physics() {
  167. /// 3D Physics Server
  168. physics_server = PhysicsServer3DManager::new_server(ProjectSettings::get_singleton()->get(PhysicsServer3DManager::setting_property_name));
  169. if (!physics_server) {
  170. // Physics server not found, Use the default physics
  171. physics_server = PhysicsServer3DManager::new_default_server();
  172. }
  173. ERR_FAIL_COND(!physics_server);
  174. physics_server->init();
  175. /// 2D Physics server
  176. physics_2d_server = PhysicsServer2DManager::new_server(ProjectSettings::get_singleton()->get(PhysicsServer2DManager::setting_property_name));
  177. if (!physics_2d_server) {
  178. // Physics server not found, Use the default physics
  179. physics_2d_server = PhysicsServer2DManager::new_default_server();
  180. }
  181. ERR_FAIL_COND(!physics_2d_server);
  182. physics_2d_server->init();
  183. }
  184. void finalize_physics() {
  185. physics_server->finish();
  186. memdelete(physics_server);
  187. physics_2d_server->finish();
  188. memdelete(physics_2d_server);
  189. }
  190. void finalize_display() {
  191. rendering_server->finish();
  192. memdelete(rendering_server);
  193. memdelete(display_server);
  194. }
  195. void initialize_navigation_server() {
  196. ERR_FAIL_COND(navigation_server != nullptr);
  197. navigation_server = NavigationServer3DManager::new_default_server();
  198. navigation_2d_server = memnew(NavigationServer2D);
  199. }
  200. void finalize_navigation_server() {
  201. memdelete(navigation_server);
  202. navigation_server = nullptr;
  203. memdelete(navigation_2d_server);
  204. navigation_2d_server = nullptr;
  205. }
  206. //#define DEBUG_INIT
  207. #ifdef DEBUG_INIT
  208. #define MAIN_PRINT(m_txt) print_line(m_txt)
  209. #else
  210. #define MAIN_PRINT(m_txt)
  211. #endif
  212. void Main::print_help(const char *p_binary) {
  213. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  214. OS::get_singleton()->print("Free and open source software under the terms of the MIT license.\n");
  215. OS::get_singleton()->print("(c) 2007-2020 Juan Linietsky, Ariel Manzur.\n");
  216. OS::get_singleton()->print("(c) 2014-2020 Godot Engine contributors.\n");
  217. OS::get_singleton()->print("\n");
  218. OS::get_singleton()->print("Usage: %s [options] [path to scene or 'project.godot' file]\n", p_binary);
  219. OS::get_singleton()->print("\n");
  220. OS::get_singleton()->print("General options:\n");
  221. OS::get_singleton()->print(" -h, --help Display this help message.\n");
  222. OS::get_singleton()->print(" --version Display the version string.\n");
  223. OS::get_singleton()->print(" -v, --verbose Use verbose stdout mode.\n");
  224. OS::get_singleton()->print(" --quiet Quiet mode, silences stdout messages. Errors are still displayed.\n");
  225. OS::get_singleton()->print("\n");
  226. OS::get_singleton()->print("Run options:\n");
  227. #ifdef TOOLS_ENABLED
  228. OS::get_singleton()->print(" -e, --editor Start the editor instead of running the scene.\n");
  229. OS::get_singleton()->print(" -p, --project-manager Start the project manager, even if a project is auto-detected.\n");
  230. #endif
  231. OS::get_singleton()->print(" -q, --quit Quit after the first iteration.\n");
  232. OS::get_singleton()->print(" -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n");
  233. OS::get_singleton()->print(" --path <directory> Path to a project (<directory> must contain a 'project.godot' file).\n");
  234. OS::get_singleton()->print(" -u, --upwards Scan folders upwards for project.godot file.\n");
  235. OS::get_singleton()->print(" --main-pack <file> Path to a pack (.pck) file to load.\n");
  236. OS::get_singleton()->print(" --render-thread <mode> Render thread mode ('unsafe', 'safe', 'separate').\n");
  237. OS::get_singleton()->print(" --remote-fs <address> Remote filesystem (<host/IP>[:<port>] address).\n");
  238. OS::get_singleton()->print(" --remote-fs-password <password> Password for remote filesystem.\n");
  239. OS::get_singleton()->print(" --audio-driver <driver> Audio driver [");
  240. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  241. if (i > 0) {
  242. OS::get_singleton()->print(", ");
  243. }
  244. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  245. }
  246. OS::get_singleton()->print("].\n");
  247. OS::get_singleton()->print(" --display-driver <driver> Display driver (and rendering driver) [");
  248. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  249. if (i > 0) {
  250. OS::get_singleton()->print(", ");
  251. }
  252. OS::get_singleton()->print("'%s' (", DisplayServer::get_create_function_name(i));
  253. Vector<String> rd = DisplayServer::get_create_function_rendering_drivers(i);
  254. for (int j = 0; j < rd.size(); j++) {
  255. if (j > 0) {
  256. OS::get_singleton()->print(", ");
  257. }
  258. OS::get_singleton()->print("'%s'", rd[j].utf8().get_data());
  259. }
  260. OS::get_singleton()->print(")");
  261. }
  262. OS::get_singleton()->print("].\n");
  263. OS::get_singleton()->print(" --rendering-driver <driver> Rendering driver (depends on display driver).\n");
  264. OS::get_singleton()->print("\n");
  265. #ifndef SERVER_ENABLED
  266. OS::get_singleton()->print("Display options:\n");
  267. OS::get_singleton()->print(" -f, --fullscreen Request fullscreen mode.\n");
  268. OS::get_singleton()->print(" -m, --maximized Request a maximized window.\n");
  269. OS::get_singleton()->print(" -w, --windowed Request windowed mode.\n");
  270. OS::get_singleton()->print(" -t, --always-on-top Request an always-on-top window.\n");
  271. OS::get_singleton()->print(" --resolution <W>x<H> Request window resolution.\n");
  272. OS::get_singleton()->print(" --position <X>,<Y> Request window position.\n");
  273. OS::get_singleton()->print(" --low-dpi Force low-DPI mode (macOS and Windows only).\n");
  274. OS::get_singleton()->print(" --no-window Disable window creation (Windows only). Useful together with --script.\n");
  275. OS::get_singleton()->print(" --enable-vsync-via-compositor When vsync is enabled, vsync via the OS' window compositor (Windows only).\n");
  276. OS::get_singleton()->print(" --disable-vsync-via-compositor Disable vsync via the OS' window compositor (Windows only).\n");
  277. OS::get_singleton()->print(" --single-window Use a single window (no separate subwindows).\n");
  278. OS::get_singleton()->print(" --disable-wintab Disable WinTab API and always use Windows Ink API for the pen input (Windows only).\n");
  279. OS::get_singleton()->print("\n");
  280. #endif
  281. OS::get_singleton()->print("Debug options:\n");
  282. OS::get_singleton()->print(" -d, --debug Debug (local stdout debugger).\n");
  283. OS::get_singleton()->print(" -b, --breakpoints Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n");
  284. OS::get_singleton()->print(" --profiling Enable profiling in the script debugger.\n");
  285. OS::get_singleton()->print(" --gpu-abort Abort on GPU errors (usually validation layer errors), may help see the problem if your system freezes.\n");
  286. OS::get_singleton()->print(" --remote-debug <address> Remote debug (<host/IP>:<port> address).\n");
  287. #if defined(DEBUG_ENABLED) && !defined(SERVER_ENABLED)
  288. OS::get_singleton()->print(" --debug-collisions Show collision shapes when running the scene.\n");
  289. OS::get_singleton()->print(" --debug-navigation Show navigation polygons when running the scene.\n");
  290. #endif
  291. OS::get_singleton()->print(" --frame-delay <ms> Simulate high CPU load (delay each frame by <ms> milliseconds).\n");
  292. OS::get_singleton()->print(" --time-scale <scale> Force time scale (higher values are faster, 1.0 is normal speed).\n");
  293. OS::get_singleton()->print(" --disable-render-loop Disable render loop so rendering only occurs when called explicitly from script.\n");
  294. OS::get_singleton()->print(" --disable-crash-handler Disable crash handler when supported by the platform code.\n");
  295. OS::get_singleton()->print(" --fixed-fps <fps> Force a fixed number of frames per second. This setting disables real-time synchronization.\n");
  296. OS::get_singleton()->print(" --print-fps Print the frames per second to the stdout.\n");
  297. OS::get_singleton()->print("\n");
  298. OS::get_singleton()->print("Standalone tools:\n");
  299. OS::get_singleton()->print(" -s, --script <script> Run a script.\n");
  300. OS::get_singleton()->print(" --check-only Only parse for errors and quit (use with --script).\n");
  301. #ifdef TOOLS_ENABLED
  302. OS::get_singleton()->print(" --export <preset> <path> Export the project using the given preset and matching release template. The preset name should match one defined in export_presets.cfg.\n");
  303. OS::get_singleton()->print(" <path> should be absolute or relative to the project directory, and include the filename for the binary (e.g. 'builds/game.exe'). The target directory should exist.\n");
  304. OS::get_singleton()->print(" --export-debug <preset> <path> Same as --export, but using the debug template.\n");
  305. OS::get_singleton()->print(" --export-pack <preset> <path> Same as --export, but only export the game pack for the given preset. The <path> extension determines whether it will be in PCK or ZIP format.\n");
  306. 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");
  307. OS::get_singleton()->print(" --no-docbase Disallow dumping the base types (used with --doctool).\n");
  308. OS::get_singleton()->print(" --build-solutions Build the scripting solutions (e.g. for C# projects). Implies --editor and requires a valid project to edit.\n");
  309. #ifdef DEBUG_METHODS_ENABLED
  310. OS::get_singleton()->print(" --gdnative-generate-json-api Generate JSON dump of the Godot API for GDNative bindings.\n");
  311. #endif
  312. OS::get_singleton()->print(" --test <test> Run a unit test [");
  313. const char **test_names = tests_get_names();
  314. const char *comma = "";
  315. while (*test_names) {
  316. OS::get_singleton()->print("%s'%s'", comma, *test_names);
  317. test_names++;
  318. comma = ", ";
  319. }
  320. OS::get_singleton()->print("].\n");
  321. #endif
  322. }
  323. /* Engine initialization
  324. *
  325. * Consists of several methods that are called by each platform's specific main(argc, argv).
  326. * To fully understand engine init, one should therefore start from the platform's main and
  327. * see how it calls into the Main class' methods.
  328. *
  329. * The initialization is typically done in 3 steps (with the setup2 step triggered either
  330. * automatically by setup, or manually in the platform's main).
  331. *
  332. * - setup(execpath, argc, argv, p_second_phase) is the main entry point for all platforms,
  333. * responsible for the initialization of all low level singletons and core types, and parsing
  334. * command line arguments to configure things accordingly.
  335. * If p_second_phase is true, it will chain into setup2() (default behaviour). This is
  336. * disabled on some platforms (Android, iOS, UWP) which trigger the second step in their
  337. * own time.
  338. *
  339. * - setup2(p_main_tid_override) registers high level servers and singletons, displays the
  340. * boot splash, then registers higher level types (scene, editor, etc.).
  341. *
  342. * - start() is the last step and that's where command line tools can run, or the main loop
  343. * can be created eventually and the project settings put into action. That's also where
  344. * the editor node is created, if relevant.
  345. * start() does it own argument parsing for a subset of the command line arguments described
  346. * in help, it's a bit messy and should be globalized with the setup() parsing somehow.
  347. */
  348. Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
  349. OS::get_singleton()->initialize();
  350. engine = memnew(Engine);
  351. ClassDB::init();
  352. MAIN_PRINT("Main: Initialize CORE");
  353. register_core_types();
  354. register_core_driver_types();
  355. MAIN_PRINT("Main: Initialize Globals");
  356. Thread::_main_thread_id = Thread::get_caller_id();
  357. globals = memnew(ProjectSettings);
  358. input_map = memnew(InputMap);
  359. register_core_settings(); //here globals is present
  360. translation_server = memnew(TranslationServer);
  361. performance = memnew(Performance);
  362. ClassDB::register_class<Performance>();
  363. engine->add_singleton(Engine::Singleton("Performance", performance));
  364. GLOBAL_DEF("debug/settings/crash_handler/message", String("Please include this when reporting the bug on https://github.com/godotengine/godot/issues"));
  365. MAIN_PRINT("Main: Parse CMDLine");
  366. /* argument parsing and main creation */
  367. List<String> args;
  368. List<String> main_args;
  369. for (int i = 0; i < argc; i++) {
  370. args.push_back(String::utf8(argv[i]));
  371. }
  372. List<String>::Element *I = args.front();
  373. I = args.front();
  374. while (I) {
  375. I->get() = unescape_cmdline(I->get().strip_edges());
  376. I = I->next();
  377. }
  378. I = args.front();
  379. String display_driver = "";
  380. String audio_driver = "";
  381. String project_path = ".";
  382. bool upwards = false;
  383. String debug_uri = "";
  384. bool skip_breakpoints = false;
  385. String main_pack;
  386. bool quiet_stdout = false;
  387. int rtm = -1;
  388. String remotefs;
  389. String remotefs_pass;
  390. Vector<String> breakpoints;
  391. bool use_custom_res = true;
  392. bool force_res = false;
  393. bool saw_vsync_via_compositor_override = false;
  394. #ifdef TOOLS_ENABLED
  395. bool found_project = false;
  396. #endif
  397. bool use_vsync = false;
  398. packed_data = PackedData::get_singleton();
  399. if (!packed_data)
  400. packed_data = memnew(PackedData);
  401. #ifdef MINIZIP_ENABLED
  402. //XXX: always get_singleton() == 0x0
  403. zip_packed_data = ZipArchive::get_singleton();
  404. //TODO: remove this temporary fix
  405. if (!zip_packed_data) {
  406. zip_packed_data = memnew(ZipArchive);
  407. }
  408. packed_data->add_pack_source(zip_packed_data);
  409. #endif
  410. I = args.front();
  411. while (I) {
  412. #ifdef OSX_ENABLED
  413. // Ignore the process serial number argument passed by macOS Gatekeeper.
  414. // Otherwise, Godot would try to open a non-existent project on the first start and abort.
  415. if (I->get().begins_with("-psn_")) {
  416. I = I->next();
  417. continue;
  418. }
  419. #endif
  420. List<String>::Element *N = I->next();
  421. if (I->get() == "-h" || I->get() == "--help" || I->get() == "/?") { // display help
  422. show_help = true;
  423. goto error;
  424. } else if (I->get() == "--version") {
  425. print_line(get_full_version_string());
  426. goto error;
  427. } else if (I->get() == "-v" || I->get() == "--verbose") { // verbose output
  428. OS::get_singleton()->_verbose_stdout = true;
  429. } else if (I->get() == "--quiet") { // quieter output
  430. quiet_stdout = true;
  431. } else if (I->get() == "--audio-driver") { // audio driver
  432. if (I->next()) {
  433. audio_driver = I->next()->get();
  434. bool found = false;
  435. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  436. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  437. found = true;
  438. }
  439. }
  440. if (!found) {
  441. OS::get_singleton()->print("Unknown audio driver '%s', aborting.\nValid options are ", audio_driver.utf8().get_data());
  442. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  443. if (i == AudioDriverManager::get_driver_count() - 1) {
  444. OS::get_singleton()->print(" and ");
  445. } else if (i != 0) {
  446. OS::get_singleton()->print(", ");
  447. }
  448. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  449. }
  450. OS::get_singleton()->print(".\n");
  451. goto error;
  452. }
  453. N = I->next()->next();
  454. } else {
  455. OS::get_singleton()->print("Missing audio driver argument, aborting.\n");
  456. goto error;
  457. }
  458. } else if (I->get() == "--display-driver") { // force video driver
  459. if (I->next()) {
  460. display_driver = I->next()->get();
  461. bool found = false;
  462. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  463. if (display_driver == DisplayServer::get_create_function_name(i)) {
  464. found = true;
  465. }
  466. }
  467. if (!found) {
  468. OS::get_singleton()->print("Unknown display driver '%s', aborting.\nValid options are ", display_driver.utf8().get_data());
  469. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  470. if (i == DisplayServer::get_create_function_count() - 1) {
  471. OS::get_singleton()->print(" and ");
  472. } else if (i != 0) {
  473. OS::get_singleton()->print(", ");
  474. }
  475. OS::get_singleton()->print("'%s'", DisplayServer::get_create_function_name(i));
  476. }
  477. OS::get_singleton()->print(".\n");
  478. goto error;
  479. }
  480. N = I->next()->next();
  481. } else {
  482. OS::get_singleton()->print("Missing video driver argument, aborting.\n");
  483. goto error;
  484. }
  485. #ifndef SERVER_ENABLED
  486. } else if (I->get() == "-f" || I->get() == "--fullscreen") { // force fullscreen
  487. init_fullscreen = true;
  488. } else if (I->get() == "-m" || I->get() == "--maximized") { // force maximized window
  489. init_maximized = true;
  490. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  491. } else if (I->get() == "-w" || I->get() == "--windowed") { // force windowed window
  492. init_windowed = true;
  493. } else if (I->get() == "--gpu-abort") { // force windowed window
  494. Engine::singleton->abort_on_gpu_errors = true;
  495. } else if (I->get() == "--disable-wintab") {
  496. disable_wintab = true;
  497. } else if (I->get() == "--single-window") { // force single window
  498. single_window = true;
  499. } else if (I->get() == "-t" || I->get() == "--always-on-top") { // force always-on-top window
  500. init_always_on_top = true;
  501. } else if (I->get() == "--resolution") { // force resolution
  502. if (I->next()) {
  503. String vm = I->next()->get();
  504. if (vm.find("x") == -1) { // invalid parameter format
  505. OS::get_singleton()->print("Invalid resolution '%s', it should be e.g. '1280x720'.\n", vm.utf8().get_data());
  506. goto error;
  507. }
  508. int w = vm.get_slice("x", 0).to_int();
  509. int h = vm.get_slice("x", 1).to_int();
  510. if (w <= 0 || h <= 0) {
  511. OS::get_singleton()->print("Invalid resolution '%s', width and height must be above 0.\n", vm.utf8().get_data());
  512. goto error;
  513. }
  514. window_size.width = w;
  515. window_size.height = h;
  516. force_res = true;
  517. N = I->next()->next();
  518. } else {
  519. OS::get_singleton()->print("Missing resolution argument, aborting.\n");
  520. goto error;
  521. }
  522. } else if (I->get() == "--position") { // set window position
  523. if (I->next()) {
  524. String vm = I->next()->get();
  525. if (vm.find(",") == -1) { // invalid parameter format
  526. OS::get_singleton()->print("Invalid position '%s', it should be e.g. '80,128'.\n", vm.utf8().get_data());
  527. goto error;
  528. }
  529. int x = vm.get_slice(",", 0).to_int();
  530. int y = vm.get_slice(",", 1).to_int();
  531. init_custom_pos = Point2(x, y);
  532. init_use_custom_pos = true;
  533. N = I->next()->next();
  534. } else {
  535. OS::get_singleton()->print("Missing position argument, aborting.\n");
  536. goto error;
  537. }
  538. } else if (I->get() == "--low-dpi") { // force low DPI (macOS only)
  539. force_lowdpi = true;
  540. } else if (I->get() == "--no-window") { // disable window creation (Windows only)
  541. OS::get_singleton()->set_no_window_mode(true);
  542. } else if (I->get() == "--enable-vsync-via-compositor") {
  543. window_vsync_via_compositor = true;
  544. saw_vsync_via_compositor_override = true;
  545. } else if (I->get() == "--disable-vsync-via-compositor") {
  546. window_vsync_via_compositor = false;
  547. saw_vsync_via_compositor_override = true;
  548. #endif
  549. } else if (I->get() == "--profiling") { // enable profiling
  550. use_debug_profiler = true;
  551. } else if (I->get() == "-l" || I->get() == "--language") { // language
  552. if (I->next()) {
  553. locale = I->next()->get();
  554. N = I->next()->next();
  555. } else {
  556. OS::get_singleton()->print("Missing language argument, aborting.\n");
  557. goto error;
  558. }
  559. } else if (I->get() == "--remote-fs") { // remote filesystem
  560. if (I->next()) {
  561. remotefs = I->next()->get();
  562. N = I->next()->next();
  563. } else {
  564. OS::get_singleton()->print("Missing remote filesystem address, aborting.\n");
  565. goto error;
  566. }
  567. } else if (I->get() == "--remote-fs-password") { // remote filesystem password
  568. if (I->next()) {
  569. remotefs_pass = I->next()->get();
  570. N = I->next()->next();
  571. } else {
  572. OS::get_singleton()->print("Missing remote filesystem password, aborting.\n");
  573. goto error;
  574. }
  575. } else if (I->get() == "--render-thread") { // render thread mode
  576. if (I->next()) {
  577. if (I->next()->get() == "safe")
  578. rtm = OS::RENDER_THREAD_SAFE;
  579. else if (I->next()->get() == "unsafe")
  580. rtm = OS::RENDER_THREAD_UNSAFE;
  581. else if (I->next()->get() == "separate")
  582. rtm = OS::RENDER_SEPARATE_THREAD;
  583. N = I->next()->next();
  584. } else {
  585. OS::get_singleton()->print("Missing render thread mode argument, aborting.\n");
  586. goto error;
  587. }
  588. #ifdef TOOLS_ENABLED
  589. } else if (I->get() == "-e" || I->get() == "--editor") { // starts editor
  590. editor = true;
  591. } else if (I->get() == "-p" || I->get() == "--project-manager") { // starts project manager
  592. project_manager = true;
  593. } else if (I->get() == "--build-solutions") { // Build the scripting solution such C#
  594. auto_build_solutions = true;
  595. editor = true;
  596. #ifdef DEBUG_METHODS_ENABLED
  597. } else if (I->get() == "--gdnative-generate-json-api") {
  598. // Register as an editor instance to use low-end fallback if relevant.
  599. editor = true;
  600. // We still pass it to the main arguments since the argument handling itself is not done in this function
  601. main_args.push_back(I->get());
  602. #endif
  603. } else if (I->get() == "--export" || I->get() == "--export-debug" || I->get() == "--export-pack") { // Export project
  604. editor = true;
  605. main_args.push_back(I->get());
  606. #endif
  607. } else if (I->get() == "--path") { // set path of project to start or edit
  608. if (I->next()) {
  609. String p = I->next()->get();
  610. if (OS::get_singleton()->set_cwd(p) == OK) {
  611. //nothing
  612. } else {
  613. project_path = I->next()->get(); //use project_path instead
  614. }
  615. N = I->next()->next();
  616. } else {
  617. OS::get_singleton()->print("Missing relative or absolute path, aborting.\n");
  618. goto error;
  619. }
  620. } else if (I->get() == "-u" || I->get() == "--upwards") { // scan folders upwards
  621. upwards = true;
  622. } else if (I->get() == "-q" || I->get() == "--quit") { // Auto quit at the end of the first main loop iteration
  623. auto_quit = true;
  624. } else if (I->get().ends_with("project.godot")) {
  625. String path;
  626. String file = I->get();
  627. int sep = MAX(file.find_last("/"), file.find_last("\\"));
  628. if (sep == -1)
  629. path = ".";
  630. else {
  631. path = file.substr(0, sep);
  632. }
  633. if (OS::get_singleton()->set_cwd(path) == OK) {
  634. // path already specified, don't override
  635. } else {
  636. project_path = path;
  637. }
  638. #ifdef TOOLS_ENABLED
  639. editor = true;
  640. #endif
  641. } else if (I->get() == "-b" || I->get() == "--breakpoints") { // add breakpoints
  642. if (I->next()) {
  643. String bplist = I->next()->get();
  644. breakpoints = bplist.split(",");
  645. N = I->next()->next();
  646. } else {
  647. OS::get_singleton()->print("Missing list of breakpoints, aborting.\n");
  648. goto error;
  649. }
  650. } else if (I->get() == "--frame-delay") { // force frame delay
  651. if (I->next()) {
  652. frame_delay = I->next()->get().to_int();
  653. N = I->next()->next();
  654. } else {
  655. OS::get_singleton()->print("Missing frame delay argument, aborting.\n");
  656. goto error;
  657. }
  658. } else if (I->get() == "--time-scale") { // force time scale
  659. if (I->next()) {
  660. Engine::get_singleton()->set_time_scale(I->next()->get().to_double());
  661. N = I->next()->next();
  662. } else {
  663. OS::get_singleton()->print("Missing time scale argument, aborting.\n");
  664. goto error;
  665. }
  666. } else if (I->get() == "--main-pack") {
  667. if (I->next()) {
  668. main_pack = I->next()->get();
  669. N = I->next()->next();
  670. } else {
  671. OS::get_singleton()->print("Missing path to main pack file, aborting.\n");
  672. goto error;
  673. };
  674. } else if (I->get() == "-d" || I->get() == "--debug") {
  675. debug_uri = "local://";
  676. #if defined(DEBUG_ENABLED) && !defined(SERVER_ENABLED)
  677. } else if (I->get() == "--debug-collisions") {
  678. debug_collisions = true;
  679. } else if (I->get() == "--debug-navigation") {
  680. debug_navigation = true;
  681. #endif
  682. } else if (I->get() == "--remote-debug") {
  683. if (I->next()) {
  684. debug_uri = I->next()->get();
  685. if (debug_uri.find(":") == -1) { // wrong address
  686. OS::get_singleton()->print("Invalid debug host address, it should be of the form <host/IP>:<port>.\n");
  687. goto error;
  688. }
  689. debug_uri = "tcp://" + debug_uri; // will support multiple protocols eventually.
  690. N = I->next()->next();
  691. } else {
  692. OS::get_singleton()->print("Missing remote debug host address, aborting.\n");
  693. goto error;
  694. }
  695. } else if (I->get() == "--allow_focus_steal_pid") { // not exposed to user
  696. if (I->next()) {
  697. allow_focus_steal_pid = I->next()->get().to_int64();
  698. N = I->next()->next();
  699. } else {
  700. OS::get_singleton()->print("Missing editor PID argument, aborting.\n");
  701. goto error;
  702. }
  703. } else if (I->get() == "--disable-render-loop") {
  704. disable_render_loop = true;
  705. } else if (I->get() == "--fixed-fps") {
  706. if (I->next()) {
  707. fixed_fps = I->next()->get().to_int();
  708. N = I->next()->next();
  709. } else {
  710. OS::get_singleton()->print("Missing fixed-fps argument, aborting.\n");
  711. goto error;
  712. }
  713. } else if (I->get() == "--print-fps") {
  714. print_fps = true;
  715. } else if (I->get() == "--disable-crash-handler") {
  716. OS::get_singleton()->disable_crash_handler();
  717. } else if (I->get() == "--skip-breakpoints") {
  718. skip_breakpoints = true;
  719. } else {
  720. main_args.push_back(I->get());
  721. }
  722. I = N;
  723. }
  724. #ifdef TOOLS_ENABLED
  725. if (editor && project_manager) {
  726. OS::get_singleton()->print("Error: Command line arguments implied opening both editor and project manager, which is not possible. Aborting.\n");
  727. goto error;
  728. }
  729. #endif
  730. // Network file system needs to be configured before globals, since globals are based on the
  731. // 'project.godot' file which will only be available through the network if this is enabled
  732. FileAccessNetwork::configure();
  733. if (remotefs != "") {
  734. file_access_network_client = memnew(FileAccessNetworkClient);
  735. int port;
  736. if (remotefs.find(":") != -1) {
  737. port = remotefs.get_slicec(':', 1).to_int();
  738. remotefs = remotefs.get_slicec(':', 0);
  739. } else {
  740. port = 6010;
  741. }
  742. Error err = file_access_network_client->connect(remotefs, port, remotefs_pass);
  743. if (err) {
  744. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i.\n", remotefs.utf8().get_data(), port);
  745. goto error;
  746. }
  747. FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
  748. }
  749. if (globals->setup(project_path, main_pack, upwards) == OK) {
  750. #ifdef TOOLS_ENABLED
  751. found_project = true;
  752. #endif
  753. } else {
  754. #ifdef TOOLS_ENABLED
  755. editor = false;
  756. #else
  757. const String error_msg = "Error: Couldn't load project data at path \"" + project_path + "\". Is the .pck file missing?\nIf you've renamed the executable, the associated .pck file should also be renamed to match the executable's name (without the extension).\n";
  758. OS::get_singleton()->print("%s", error_msg.ascii().get_data());
  759. DisplayServer::get_singleton()->alert(error_msg);
  760. goto error;
  761. #endif
  762. }
  763. GLOBAL_DEF("memory/limits/multithreaded_server/rid_pool_prealloc", 60);
  764. ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/multithreaded_server/rid_pool_prealloc", PropertyInfo(Variant::INT, "memory/limits/multithreaded_server/rid_pool_prealloc", PROPERTY_HINT_RANGE, "0,500,1")); // No negative and limit to 500 due to crashes
  765. GLOBAL_DEF("network/limits/debugger/max_chars_per_second", 32768);
  766. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_chars_per_second", PropertyInfo(Variant::INT, "network/limits/debugger/max_chars_per_second", PROPERTY_HINT_RANGE, "0, 4096, 1, or_greater"));
  767. GLOBAL_DEF("network/limits/debugger/max_queued_messages", 2048);
  768. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_queued_messages", PropertyInfo(Variant::INT, "network/limits/debugger/max_queued_messages", PROPERTY_HINT_RANGE, "0, 8192, 1, or_greater"));
  769. GLOBAL_DEF("network/limits/debugger/max_errors_per_second", 400);
  770. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_errors_per_second", PropertyInfo(Variant::INT, "network/limits/debugger/max_errors_per_second", PROPERTY_HINT_RANGE, "0, 200, 1, or_greater"));
  771. GLOBAL_DEF("network/limits/debugger/max_warnings_per_second", 400);
  772. ProjectSettings::get_singleton()->set_custom_property_info("network/limits/debugger/max_warnings_per_second", PropertyInfo(Variant::INT, "network/limits/debugger/max_warnings_per_second", PROPERTY_HINT_RANGE, "0, 200, 1, or_greater"));
  773. EngineDebugger::initialize(debug_uri, skip_breakpoints, breakpoints);
  774. #ifdef TOOLS_ENABLED
  775. if (editor) {
  776. packed_data->set_disabled(true);
  777. globals->set_disable_feature_overrides(true);
  778. }
  779. #endif
  780. GLOBAL_DEF("logging/file_logging/enable_file_logging", false);
  781. GLOBAL_DEF("logging/file_logging/log_path", "user://logs/log.txt");
  782. GLOBAL_DEF("logging/file_logging/max_log_files", 10);
  783. ProjectSettings::get_singleton()->set_custom_property_info("logging/file_logging/max_log_files", PropertyInfo(Variant::INT, "logging/file_logging/max_log_files", PROPERTY_HINT_RANGE, "0,20,1,or_greater")); //no negative numbers
  784. if (FileAccess::get_create_func(FileAccess::ACCESS_USERDATA) && GLOBAL_GET("logging/file_logging/enable_file_logging")) {
  785. String base_path = GLOBAL_GET("logging/file_logging/log_path");
  786. int max_files = GLOBAL_GET("logging/file_logging/max_log_files");
  787. OS::get_singleton()->add_logger(memnew(RotatedFileLogger(base_path, max_files)));
  788. }
  789. #ifdef TOOLS_ENABLED
  790. if (editor) {
  791. Engine::get_singleton()->set_editor_hint(true);
  792. main_args.push_back("--editor");
  793. if (!init_windowed) {
  794. init_maximized = true;
  795. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  796. }
  797. }
  798. if (!project_manager && !editor) {
  799. // Determine if the project manager should be requested
  800. project_manager = main_args.size() == 0 && !found_project;
  801. }
  802. #endif
  803. if (main_args.size() == 0 && String(GLOBAL_DEF("application/run/main_scene", "")) == "") {
  804. #ifdef TOOLS_ENABLED
  805. if (!editor && !project_manager) {
  806. #endif
  807. OS::get_singleton()->print("Error: Can't run project: no main scene defined.\n");
  808. goto error;
  809. #ifdef TOOLS_ENABLED
  810. }
  811. #endif
  812. }
  813. if (editor || project_manager) {
  814. Engine::get_singleton()->set_editor_hint(true);
  815. use_custom_res = false;
  816. input_map->load_default(); //keys for editor
  817. } else {
  818. input_map->load_from_globals(); //keys for game
  819. }
  820. if (bool(ProjectSettings::get_singleton()->get("application/run/disable_stdout"))) {
  821. quiet_stdout = true;
  822. }
  823. if (bool(ProjectSettings::get_singleton()->get("application/run/disable_stderr"))) {
  824. _print_error_enabled = false;
  825. };
  826. if (quiet_stdout)
  827. _print_line_enabled = false;
  828. OS::get_singleton()->set_cmdline(execpath, main_args);
  829. GLOBAL_DEF("rendering/quality/driver/driver_name", "Vulkan");
  830. ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/driver/driver_name", PropertyInfo(Variant::STRING, "rendering/quality/driver/driver_name", PROPERTY_HINT_ENUM, "Vulkan,GLES2"));
  831. if (display_driver == "") {
  832. display_driver = GLOBAL_GET("rendering/quality/driver/driver_name");
  833. }
  834. // Assigning here even though it's GLES2-specific, to be sure that it appears in docs
  835. GLOBAL_DEF("rendering/quality/2d/gles2_use_nvidia_rect_flicker_workaround", false);
  836. GLOBAL_DEF("display/window/size/width", 1024);
  837. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/width", PropertyInfo(Variant::INT, "display/window/size/width", PROPERTY_HINT_RANGE, "0,7680,or_greater")); // 8K resolution
  838. GLOBAL_DEF("display/window/size/height", 600);
  839. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/height", PropertyInfo(Variant::INT, "display/window/size/height", PROPERTY_HINT_RANGE, "0,4320,or_greater")); // 8K resolution
  840. GLOBAL_DEF("display/window/size/resizable", true);
  841. GLOBAL_DEF("display/window/size/borderless", false);
  842. GLOBAL_DEF("display/window/size/fullscreen", false);
  843. GLOBAL_DEF("display/window/size/always_on_top", false);
  844. GLOBAL_DEF("display/window/size/test_width", 0);
  845. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/test_width", PropertyInfo(Variant::INT, "display/window/size/test_width", PROPERTY_HINT_RANGE, "0,7680,or_greater")); // 8K resolution
  846. GLOBAL_DEF("display/window/size/test_height", 0);
  847. ProjectSettings::get_singleton()->set_custom_property_info("display/window/size/test_height", PropertyInfo(Variant::INT, "display/window/size/test_height", PROPERTY_HINT_RANGE, "0,4320,or_greater")); // 8K resolution
  848. if (use_custom_res) {
  849. if (!force_res) {
  850. window_size.width = GLOBAL_GET("display/window/size/width");
  851. window_size.height = GLOBAL_GET("display/window/size/height");
  852. if (globals->has_setting("display/window/size/test_width") && globals->has_setting("display/window/size/test_height")) {
  853. int tw = globals->get("display/window/size/test_width");
  854. if (tw > 0) {
  855. window_size.width = tw;
  856. }
  857. int th = globals->get("display/window/size/test_height");
  858. if (th > 0) {
  859. window_size.height = th;
  860. }
  861. }
  862. }
  863. if (!bool(GLOBAL_GET("display/window/size/resizable"))) {
  864. window_flags |= DisplayServer::WINDOW_FLAG_RESIZE_DISABLED_BIT;
  865. }
  866. if (bool(GLOBAL_GET("display/window/size/borderless"))) {
  867. window_flags |= DisplayServer::WINDOW_FLAG_BORDERLESS_BIT;
  868. }
  869. if (bool(GLOBAL_GET("display/window/size/fullscreen"))) {
  870. window_mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
  871. }
  872. if (bool(GLOBAL_GET("display/window/size/always_on_top"))) {
  873. window_flags |= DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP;
  874. }
  875. }
  876. if (!force_lowdpi) {
  877. OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", false);
  878. }
  879. use_vsync = GLOBAL_DEF_RST("display/window/vsync/use_vsync", true);
  880. OS::get_singleton()->_use_vsync = use_vsync;
  881. if (!saw_vsync_via_compositor_override) {
  882. // If one of the command line options to enable/disable vsync via the
  883. // window compositor ("--enable-vsync-via-compositor" or
  884. // "--disable-vsync-via-compositor") was present then it overrides the
  885. // project setting.
  886. window_vsync_via_compositor = GLOBAL_DEF("display/window/vsync/vsync_via_compositor", false);
  887. }
  888. OS::get_singleton()->_vsync_via_compositor = window_vsync_via_compositor;
  889. if (!disable_wintab) {
  890. // No "--disable_wintab" option
  891. disable_wintab = GLOBAL_DEF("display/window/disable_wintab_api", false);
  892. }
  893. OS::get_singleton()->_disable_wintab = disable_wintab;
  894. /* todo restore
  895. OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/per_pixel_transparency/allowed", false);
  896. video_mode.layered = GLOBAL_DEF("display/window/per_pixel_transparency/enabled", false);
  897. */
  898. GLOBAL_DEF("rendering/quality/intended_usage/framebuffer_allocation", 2);
  899. GLOBAL_DEF("rendering/quality/intended_usage/framebuffer_allocation.mobile", 3);
  900. if (editor || project_manager) {
  901. // The editor and project manager always detect and use hiDPI if needed
  902. OS::get_singleton()->_allow_hidpi = true;
  903. OS::get_singleton()->_allow_layered = false;
  904. }
  905. Engine::get_singleton()->_pixel_snap = GLOBAL_DEF("rendering/quality/2d/use_pixel_snap", false);
  906. OS::get_singleton()->_keep_screen_on = GLOBAL_DEF("display/window/energy_saving/keep_screen_on", true);
  907. if (rtm == -1) {
  908. rtm = GLOBAL_DEF("rendering/threads/thread_model", OS::RENDER_THREAD_SAFE);
  909. }
  910. if (rtm >= 0 && rtm < 3) {
  911. if (editor) {
  912. rtm = OS::RENDER_THREAD_SAFE;
  913. }
  914. OS::get_singleton()->_render_thread_mode = OS::RenderThreadMode(rtm);
  915. }
  916. /* Determine audio and video drivers */
  917. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  918. if (display_driver == DisplayServer::get_create_function_name(i)) {
  919. display_driver_idx = i;
  920. break;
  921. }
  922. }
  923. if (display_driver_idx < 0) {
  924. display_driver_idx = 0;
  925. }
  926. if (audio_driver == "") { // specified in project.godot
  927. audio_driver = GLOBAL_DEF_RST("audio/driver", AudioDriverManager::get_driver(0)->get_name());
  928. }
  929. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  930. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  931. audio_driver_idx = i;
  932. break;
  933. }
  934. }
  935. if (audio_driver_idx < 0) {
  936. audio_driver_idx = 0;
  937. }
  938. {
  939. String orientation = GLOBAL_DEF("display/window/handheld/orientation", "landscape");
  940. if (orientation == "portrait")
  941. window_orientation = DisplayServer::SCREEN_PORTRAIT;
  942. else if (orientation == "reverse_landscape")
  943. window_orientation = DisplayServer::SCREEN_REVERSE_LANDSCAPE;
  944. else if (orientation == "reverse_portrait")
  945. window_orientation = DisplayServer::SCREEN_REVERSE_PORTRAIT;
  946. else if (orientation == "sensor_landscape")
  947. window_orientation = DisplayServer::SCREEN_SENSOR_LANDSCAPE;
  948. else if (orientation == "sensor_portrait")
  949. window_orientation = DisplayServer::SCREEN_SENSOR_PORTRAIT;
  950. else if (orientation == "sensor")
  951. window_orientation = DisplayServer::SCREEN_SENSOR;
  952. else
  953. window_orientation = DisplayServer::SCREEN_LANDSCAPE;
  954. }
  955. Engine::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/common/physics_fps", 60));
  956. ProjectSettings::get_singleton()->set_custom_property_info("physics/common/physics_fps", PropertyInfo(Variant::INT, "physics/common/physics_fps", PROPERTY_HINT_RANGE, "1,120,1,or_greater"));
  957. Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF("physics/common/physics_jitter_fix", 0.5));
  958. Engine::get_singleton()->set_target_fps(GLOBAL_DEF("debug/settings/fps/force_fps", 0));
  959. ProjectSettings::get_singleton()->set_custom_property_info("debug/settings/fps/force_fps", PropertyInfo(Variant::INT, "debug/settings/fps/force_fps", PROPERTY_HINT_RANGE, "0,120,1,or_greater"));
  960. GLOBAL_DEF("debug/settings/stdout/print_fps", false);
  961. GLOBAL_DEF("debug/settings/stdout/verbose_stdout", false);
  962. if (!OS::get_singleton()->_verbose_stdout) { // Not manually overridden.
  963. OS::get_singleton()->_verbose_stdout = GLOBAL_GET("debug/settings/stdout/verbose_stdout");
  964. }
  965. if (frame_delay == 0) {
  966. frame_delay = GLOBAL_DEF("application/run/frame_delay_msec", 0);
  967. ProjectSettings::get_singleton()->set_custom_property_info("application/run/frame_delay_msec", PropertyInfo(Variant::INT, "application/run/frame_delay_msec", PROPERTY_HINT_RANGE, "0,100,1,or_greater")); // No negative numbers
  968. }
  969. OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false));
  970. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(GLOBAL_DEF("application/run/low_processor_mode_sleep_usec", 6900)); // Roughly 144 FPS
  971. ProjectSettings::get_singleton()->set_custom_property_info("application/run/low_processor_mode_sleep_usec", PropertyInfo(Variant::INT, "application/run/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "0,33200,1,or_greater")); // No negative numbers
  972. GLOBAL_DEF("display/window/ios/hide_home_indicator", true);
  973. Engine::get_singleton()->set_frame_delay(frame_delay);
  974. message_queue = memnew(MessageQueue);
  975. if (p_second_phase)
  976. return setup2();
  977. return OK;
  978. error:
  979. display_driver = "";
  980. audio_driver = "";
  981. project_path = "";
  982. args.clear();
  983. main_args.clear();
  984. if (show_help)
  985. print_help(execpath);
  986. EngineDebugger::deinitialize();
  987. if (performance)
  988. memdelete(performance);
  989. if (input_map)
  990. memdelete(input_map);
  991. if (translation_server)
  992. memdelete(translation_server);
  993. if (globals)
  994. memdelete(globals);
  995. if (engine)
  996. memdelete(engine);
  997. if (packed_data)
  998. memdelete(packed_data);
  999. if (file_access_network_client)
  1000. memdelete(file_access_network_client);
  1001. unregister_core_driver_types();
  1002. unregister_core_types();
  1003. OS::get_singleton()->_cmdline.clear();
  1004. if (message_queue)
  1005. memdelete(message_queue);
  1006. OS::get_singleton()->finalize_core();
  1007. locale = String();
  1008. return ERR_INVALID_PARAMETER;
  1009. }
  1010. Error Main::setup2(Thread::ID p_main_tid_override) {
  1011. preregister_module_types();
  1012. preregister_server_types();
  1013. // Print engine name and version
  1014. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  1015. if (p_main_tid_override) {
  1016. Thread::_main_thread_id = p_main_tid_override;
  1017. }
  1018. /* Initialize user data dir */
  1019. OS::get_singleton()->ensure_user_data_dir();
  1020. /* Initialize Input */
  1021. input = memnew(Input);
  1022. /* Iniitalize Display Server */
  1023. {
  1024. String rendering_driver; // temp broken
  1025. Error err;
  1026. display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_flags, window_size, err);
  1027. if (err != OK) {
  1028. //ok i guess we can't use this display server, try other ones
  1029. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1030. if (i == display_driver_idx) {
  1031. continue; //don't try the same twice
  1032. }
  1033. display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_flags, window_size, err);
  1034. if (err == OK) {
  1035. break;
  1036. }
  1037. }
  1038. }
  1039. if (!display_server) {
  1040. ERR_PRINT("Unable to create DisplayServer, all display drivers failed.");
  1041. return err;
  1042. }
  1043. }
  1044. if (display_server->has_feature(DisplayServer::FEATURE_ORIENTATION)) {
  1045. display_server->screen_set_orientation(window_orientation);
  1046. }
  1047. /* Initialize Visual Server */
  1048. rendering_server = memnew(RenderingServerRaster);
  1049. if (OS::get_singleton()->get_render_thread_mode() != OS::RENDER_THREAD_UNSAFE) {
  1050. rendering_server = memnew(RenderingServerWrapMT(rendering_server, OS::get_singleton()->get_render_thread_mode() == OS::RENDER_SEPARATE_THREAD));
  1051. }
  1052. rendering_server->init();
  1053. OS::get_singleton()->initialize_joypads();
  1054. /* Initialize Audio Driver */
  1055. AudioDriverManager::initialize(audio_driver_idx);
  1056. print_line(" "); //add a blank line for readability
  1057. if (init_use_custom_pos) {
  1058. display_server->window_set_position(init_custom_pos);
  1059. }
  1060. // right moment to create and initialize the audio server
  1061. audio_server = memnew(AudioServer);
  1062. audio_server->init();
  1063. // also init our xr_server from here
  1064. xr_server = memnew(XRServer);
  1065. register_core_singletons();
  1066. MAIN_PRINT("Main: Setup Logo");
  1067. #ifdef JAVASCRIPT_ENABLED
  1068. bool show_logo = false;
  1069. #else
  1070. bool show_logo = true;
  1071. #endif
  1072. if (init_screen != -1) {
  1073. DisplayServer::get_singleton()->window_set_current_screen(init_screen);
  1074. }
  1075. if (init_windowed) {
  1076. //do none..
  1077. } else if (init_maximized) {
  1078. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_MAXIMIZED);
  1079. } else if (init_fullscreen) {
  1080. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_FULLSCREEN);
  1081. }
  1082. if (init_always_on_top) {
  1083. DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP, true);
  1084. }
  1085. if (allow_focus_steal_pid) {
  1086. DisplayServer::get_singleton()->enable_for_stealing_focus(allow_focus_steal_pid);
  1087. }
  1088. register_server_types();
  1089. MAIN_PRINT("Main: Load Remaps");
  1090. Color clear = GLOBAL_DEF("rendering/environment/default_clear_color", Color(0.3, 0.3, 0.3));
  1091. RenderingServer::get_singleton()->set_default_clear_color(clear);
  1092. if (show_logo) { //boot logo!
  1093. String boot_logo_path = GLOBAL_DEF("application/boot_splash/image", String());
  1094. bool boot_logo_scale = GLOBAL_DEF("application/boot_splash/fullsize", true);
  1095. bool boot_logo_filter = GLOBAL_DEF("application/boot_splash/use_filter", true);
  1096. ProjectSettings::get_singleton()->set_custom_property_info("application/boot_splash/image", PropertyInfo(Variant::STRING, "application/boot_splash/image", PROPERTY_HINT_FILE, "*.png"));
  1097. Ref<Image> boot_logo;
  1098. boot_logo_path = boot_logo_path.strip_edges();
  1099. if (boot_logo_path != String()) {
  1100. boot_logo.instance();
  1101. Error load_err = ImageLoader::load_image(boot_logo_path, boot_logo);
  1102. if (load_err)
  1103. ERR_PRINT("Non-existing or invalid boot splash at '" + boot_logo_path + "'. Loading default splash.");
  1104. }
  1105. Color boot_bg_color = GLOBAL_DEF("application/boot_splash/bg_color", boot_splash_bg_color);
  1106. if (boot_logo.is_valid()) {
  1107. OS::get_singleton()->_msec_splash = OS::get_singleton()->get_ticks_msec();
  1108. RenderingServer::get_singleton()->set_boot_image(boot_logo, boot_bg_color, boot_logo_scale, boot_logo_filter);
  1109. } else {
  1110. #ifndef NO_DEFAULT_BOOT_LOGO
  1111. MAIN_PRINT("Main: Create bootsplash");
  1112. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  1113. Ref<Image> splash = (editor || project_manager) ? memnew(Image(boot_splash_editor_png)) : memnew(Image(boot_splash_png));
  1114. #else
  1115. Ref<Image> splash = memnew(Image(boot_splash_png));
  1116. #endif
  1117. MAIN_PRINT("Main: ClearColor");
  1118. RenderingServer::get_singleton()->set_default_clear_color(boot_bg_color);
  1119. MAIN_PRINT("Main: Image");
  1120. RenderingServer::get_singleton()->set_boot_image(splash, boot_bg_color, false);
  1121. #endif
  1122. }
  1123. #ifdef TOOLS_ENABLED
  1124. Ref<Image> icon = memnew(Image(app_icon_png));
  1125. DisplayServer::get_singleton()->set_icon(icon);
  1126. #endif
  1127. }
  1128. MAIN_PRINT("Main: DCC");
  1129. RenderingServer::get_singleton()->set_default_clear_color(GLOBAL_DEF("rendering/environment/default_clear_color", Color(0.3, 0.3, 0.3)));
  1130. MAIN_PRINT("Main: END");
  1131. GLOBAL_DEF("application/config/icon", String());
  1132. ProjectSettings::get_singleton()->set_custom_property_info("application/config/icon", PropertyInfo(Variant::STRING, "application/config/icon", PROPERTY_HINT_FILE, "*.png,*.webp"));
  1133. GLOBAL_DEF("application/config/macos_native_icon", String());
  1134. ProjectSettings::get_singleton()->set_custom_property_info("application/config/macos_native_icon", PropertyInfo(Variant::STRING, "application/config/macos_native_icon", PROPERTY_HINT_FILE, "*.icns"));
  1135. GLOBAL_DEF("application/config/windows_native_icon", String());
  1136. ProjectSettings::get_singleton()->set_custom_property_info("application/config/windows_native_icon", PropertyInfo(Variant::STRING, "application/config/windows_native_icon", PROPERTY_HINT_FILE, "*.ico"));
  1137. Input *id = Input::get_singleton();
  1138. if (id) {
  1139. if (bool(GLOBAL_DEF("input_devices/pointing/emulate_touch_from_mouse", false)) && !(editor || project_manager)) {
  1140. bool found_touchscreen = false;
  1141. for (int i = 0; i < DisplayServer::get_singleton()->get_screen_count(); i++) {
  1142. if (DisplayServer::get_singleton()->screen_is_touchscreen(i)) {
  1143. found_touchscreen = true;
  1144. }
  1145. }
  1146. if (!found_touchscreen) {
  1147. //only if no touchscreen ui hint, set emulation
  1148. id->set_emulate_touch_from_mouse(true);
  1149. }
  1150. }
  1151. id->set_emulate_mouse_from_touch(bool(GLOBAL_DEF("input_devices/pointing/emulate_mouse_from_touch", true)));
  1152. }
  1153. MAIN_PRINT("Main: Load Remaps");
  1154. MAIN_PRINT("Main: Load Scene Types");
  1155. register_scene_types();
  1156. GLOBAL_DEF("display/mouse_cursor/custom_image", String());
  1157. GLOBAL_DEF("display/mouse_cursor/custom_image_hotspot", Vector2());
  1158. GLOBAL_DEF("display/mouse_cursor/tooltip_position_offset", Point2(10, 10));
  1159. 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"));
  1160. if (String(ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image")) != String()) {
  1161. Ref<Texture2D> cursor = ResourceLoader::load(ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image"));
  1162. if (cursor.is_valid()) {
  1163. Vector2 hotspot = ProjectSettings::get_singleton()->get("display/mouse_cursor/custom_image_hotspot");
  1164. Input::get_singleton()->set_custom_mouse_cursor(cursor, Input::CURSOR_ARROW, hotspot);
  1165. }
  1166. }
  1167. #ifdef TOOLS_ENABLED
  1168. ClassDB::set_current_api(ClassDB::API_EDITOR);
  1169. EditorNode::register_editor_types();
  1170. ClassDB::set_current_api(ClassDB::API_CORE);
  1171. #endif
  1172. MAIN_PRINT("Main: Load Modules, Physics, Drivers, Scripts");
  1173. register_platform_apis();
  1174. register_module_types();
  1175. camera_server = CameraServer::create();
  1176. initialize_physics();
  1177. initialize_navigation_server();
  1178. register_server_singletons();
  1179. register_driver_types();
  1180. // This loads global classes, so it must happen before custom loaders and savers are registered
  1181. ScriptServer::init_languages();
  1182. MAIN_PRINT("Main: Load Translations");
  1183. translation_server->setup(); //register translations, load them, etc.
  1184. if (locale != "") {
  1185. translation_server->set_locale(locale);
  1186. }
  1187. translation_server->load_translations();
  1188. ResourceLoader::load_translation_remaps(); //load remaps for resources
  1189. ResourceLoader::load_path_remaps();
  1190. audio_server->load_default_bus_layout();
  1191. if (use_debug_profiler && EngineDebugger::is_active()) {
  1192. // Start the "scripts" profiler, used in local debugging.
  1193. // We could add more, and make the CLI arg require a comma-separated list of profilers.
  1194. EngineDebugger::get_singleton()->profiler_enable("scripts", true);
  1195. }
  1196. if (!project_manager) {
  1197. // If not running the project manager, and now that the engine is
  1198. // able to load resources, load the global shader variables.
  1199. // If running on editor, dont load the textures because the editor
  1200. // may want to import them first. Editor will reload those later.
  1201. rendering_server->global_variables_load_settings(!editor);
  1202. }
  1203. _start_success = true;
  1204. locale = String();
  1205. ClassDB::set_current_api(ClassDB::API_NONE); //no more api is registered at this point
  1206. print_verbose("CORE API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_CORE)));
  1207. print_verbose("EDITOR API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
  1208. MAIN_PRINT("Main: Done");
  1209. return OK;
  1210. }
  1211. // everything the main loop needs to know about frame timings
  1212. static MainTimerSync main_timer_sync;
  1213. bool Main::start() {
  1214. ERR_FAIL_COND_V(!_start_success, false);
  1215. bool hasicon = false;
  1216. String doc_tool;
  1217. List<String> removal_docs;
  1218. String positional_arg;
  1219. String game_path;
  1220. String script;
  1221. String test;
  1222. bool check_only = false;
  1223. #ifdef TOOLS_ENABLED
  1224. bool doc_base = true;
  1225. String _export_preset;
  1226. bool export_debug = false;
  1227. bool export_pack_only = false;
  1228. #endif
  1229. main_timer_sync.init(OS::get_singleton()->get_ticks_usec());
  1230. List<String> args = OS::get_singleton()->get_cmdline_args();
  1231. for (int i = 0; i < args.size(); i++) {
  1232. //parameters that do not have an argument to the right
  1233. if (args[i] == "--check-only") {
  1234. check_only = true;
  1235. #ifdef TOOLS_ENABLED
  1236. } else if (args[i] == "--no-docbase") {
  1237. doc_base = false;
  1238. } else if (args[i] == "-e" || args[i] == "--editor") {
  1239. editor = true;
  1240. } else if (args[i] == "-p" || args[i] == "--project-manager") {
  1241. project_manager = true;
  1242. #endif
  1243. } else if (args[i].length() && args[i][0] != '-' && positional_arg == "") {
  1244. positional_arg = args[i];
  1245. if (args[i].ends_with(".scn") || args[i].ends_with(".tscn") || args[i].ends_with(".escn")) {
  1246. // Only consider the positional argument to be a scene path if it ends with
  1247. // a file extension associated with Godot scenes. This makes it possible
  1248. // for projects to parse command-line arguments for custom CLI arguments
  1249. // or other file extensions without trouble. This can be used to implement
  1250. // "drag-and-drop onto executable" logic, which can prove helpful
  1251. // for non-game applications.
  1252. game_path = args[i];
  1253. }
  1254. }
  1255. //parameters that have an argument to the right
  1256. else if (i < (args.size() - 1)) {
  1257. bool parsed_pair = true;
  1258. if (args[i] == "-s" || args[i] == "--script") {
  1259. script = args[i + 1];
  1260. } else if (args[i] == "--test") {
  1261. test = args[i + 1];
  1262. #ifdef TOOLS_ENABLED
  1263. } else if (args[i] == "--doctool") {
  1264. doc_tool = args[i + 1];
  1265. for (int j = i + 2; j < args.size(); j++)
  1266. removal_docs.push_back(args[j]);
  1267. } else if (args[i] == "--export") {
  1268. editor = true; //needs editor
  1269. _export_preset = args[i + 1];
  1270. } else if (args[i] == "--export-debug") {
  1271. editor = true; //needs editor
  1272. _export_preset = args[i + 1];
  1273. export_debug = true;
  1274. } else if (args[i] == "--export-pack") {
  1275. editor = true;
  1276. _export_preset = args[i + 1];
  1277. export_pack_only = true;
  1278. #endif
  1279. } else {
  1280. // The parameter does not match anything known, don't skip the next argument
  1281. parsed_pair = false;
  1282. }
  1283. if (parsed_pair) {
  1284. i++;
  1285. }
  1286. }
  1287. }
  1288. String main_loop_type;
  1289. #ifdef TOOLS_ENABLED
  1290. if (doc_tool != "") {
  1291. Engine::get_singleton()->set_editor_hint(true); // Needed to instance editor-only classes for their default values
  1292. {
  1293. DirAccessRef da = DirAccess::open(doc_tool);
  1294. ERR_FAIL_COND_V_MSG(!da, false, "Argument supplied to --doctool must be a base Godot build directory.");
  1295. }
  1296. #ifndef MODULE_MONO_ENABLED
  1297. // Hack to define Mono-specific project settings even on non-Mono builds,
  1298. // so that we don't lose their descriptions and default values in DocData.
  1299. // Default values should be synced with mono_gd/gd_mono.cpp.
  1300. GLOBAL_DEF("mono/debugger_agent/port", 23685);
  1301. GLOBAL_DEF("mono/debugger_agent/wait_for_debugger", false);
  1302. GLOBAL_DEF("mono/debugger_agent/wait_timeout", 3000);
  1303. GLOBAL_DEF("mono/profiler/args", "log:calls,alloc,sample,output=output.mlpd");
  1304. GLOBAL_DEF("mono/profiler/enabled", false);
  1305. GLOBAL_DEF("mono/unhandled_exception_policy", 0);
  1306. #endif
  1307. DocData doc;
  1308. doc.generate(doc_base);
  1309. DocData docsrc;
  1310. Map<String, String> doc_data_classes;
  1311. Set<String> checked_paths;
  1312. print_line("Loading docs...");
  1313. for (int i = 0; i < _doc_data_class_path_count; i++) {
  1314. String path = doc_tool.plus_file(_doc_data_class_paths[i].path);
  1315. String name = _doc_data_class_paths[i].name;
  1316. doc_data_classes[name] = path;
  1317. if (!checked_paths.has(path)) {
  1318. checked_paths.insert(path);
  1319. // Create the module documentation directory if it doesn't exist
  1320. DirAccess *da = DirAccess::create_for_path(path);
  1321. da->make_dir_recursive(path);
  1322. memdelete(da);
  1323. docsrc.load_classes(path);
  1324. print_line("Loading docs from: " + path);
  1325. }
  1326. }
  1327. String index_path = doc_tool.plus_file("doc/classes");
  1328. // Create the main documentation directory if it doesn't exist
  1329. DirAccess *da = DirAccess::create_for_path(index_path);
  1330. da->make_dir_recursive(index_path);
  1331. memdelete(da);
  1332. docsrc.load_classes(index_path);
  1333. checked_paths.insert(index_path);
  1334. print_line("Loading docs from: " + index_path);
  1335. print_line("Merging docs...");
  1336. doc.merge_from(docsrc);
  1337. for (Set<String>::Element *E = checked_paths.front(); E; E = E->next()) {
  1338. print_line("Erasing old docs at: " + E->get());
  1339. DocData::erase_classes(E->get());
  1340. }
  1341. print_line("Generating new docs...");
  1342. doc.save_classes(index_path, doc_data_classes);
  1343. return false;
  1344. }
  1345. if (_export_preset != "") {
  1346. if (positional_arg == "") {
  1347. String err = "Command line includes export parameter option, but no destination path was given.\n";
  1348. err += "Please specify the binary's file path to export to. Aborting export.";
  1349. ERR_PRINT(err);
  1350. return false;
  1351. }
  1352. }
  1353. #endif
  1354. if (script == "" && game_path == "" && String(GLOBAL_DEF("application/run/main_scene", "")) != "") {
  1355. game_path = GLOBAL_DEF("application/run/main_scene", "");
  1356. }
  1357. MainLoop *main_loop = nullptr;
  1358. if (editor) {
  1359. main_loop = memnew(SceneTree);
  1360. };
  1361. if (test != "") {
  1362. #ifdef TOOLS_ENABLED
  1363. main_loop = test_main(test, args);
  1364. if (!main_loop)
  1365. return false;
  1366. #endif
  1367. } else if (script != "") {
  1368. Ref<Script> script_res = ResourceLoader::load(script);
  1369. ERR_FAIL_COND_V_MSG(script_res.is_null(), false, "Can't load script: " + script);
  1370. if (check_only) {
  1371. if (!script_res->is_valid()) {
  1372. OS::get_singleton()->set_exit_code(1);
  1373. }
  1374. return false;
  1375. }
  1376. if (script_res->can_instance()) {
  1377. StringName instance_type = script_res->get_instance_base_type();
  1378. Object *obj = ClassDB::instance(instance_type);
  1379. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  1380. if (!script_loop) {
  1381. if (obj)
  1382. memdelete(obj);
  1383. ERR_FAIL_V_MSG(false, vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  1384. }
  1385. script_loop->set_init_script(script_res);
  1386. main_loop = script_loop;
  1387. } else {
  1388. return false;
  1389. }
  1390. } else {
  1391. main_loop_type = GLOBAL_DEF("application/run/main_loop_type", "");
  1392. }
  1393. if (!main_loop && main_loop_type == "")
  1394. main_loop_type = "SceneTree";
  1395. if (!main_loop) {
  1396. if (!ClassDB::class_exists(main_loop_type)) {
  1397. DisplayServer::get_singleton()->alert("Error: MainLoop type doesn't exist: " + main_loop_type);
  1398. return false;
  1399. } else {
  1400. Object *ml = ClassDB::instance(main_loop_type);
  1401. ERR_FAIL_COND_V_MSG(!ml, false, "Can't instance MainLoop type.");
  1402. main_loop = Object::cast_to<MainLoop>(ml);
  1403. if (!main_loop) {
  1404. memdelete(ml);
  1405. ERR_FAIL_V_MSG(false, "Invalid MainLoop type.");
  1406. }
  1407. }
  1408. }
  1409. if (main_loop->is_class("SceneTree")) {
  1410. SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
  1411. #ifdef DEBUG_ENABLED
  1412. if (debug_collisions) {
  1413. sml->set_debug_collisions_hint(true);
  1414. }
  1415. if (debug_navigation) {
  1416. sml->set_debug_navigation_hint(true);
  1417. }
  1418. #endif
  1419. bool embed_subwindows = GLOBAL_DEF("display/window/subwindows/embed_subwindows", false);
  1420. if (single_window || (!project_manager && !editor && embed_subwindows)) {
  1421. sml->get_root()->set_embed_subwindows_hint(true);
  1422. }
  1423. ResourceLoader::add_custom_loaders();
  1424. ResourceSaver::add_custom_savers();
  1425. if (!project_manager && !editor) { // game
  1426. if (game_path != "" || script != "") {
  1427. //autoload
  1428. List<PropertyInfo> props;
  1429. ProjectSettings::get_singleton()->get_property_list(&props);
  1430. //first pass, add the constants so they exist before any script is loaded
  1431. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  1432. String s = E->get().name;
  1433. if (!s.begins_with("autoload/"))
  1434. continue;
  1435. String name = s.get_slicec('/', 1);
  1436. String path = ProjectSettings::get_singleton()->get(s);
  1437. bool global_var = false;
  1438. if (path.begins_with("*")) {
  1439. global_var = true;
  1440. }
  1441. if (global_var) {
  1442. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1443. ScriptServer::get_language(i)->add_global_constant(name, Variant());
  1444. }
  1445. }
  1446. }
  1447. //second pass, load into global constants
  1448. List<Node *> to_add;
  1449. for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
  1450. String s = E->get().name;
  1451. if (!s.begins_with("autoload/"))
  1452. continue;
  1453. String name = s.get_slicec('/', 1);
  1454. String path = ProjectSettings::get_singleton()->get(s);
  1455. bool global_var = false;
  1456. if (path.begins_with("*")) {
  1457. global_var = true;
  1458. path = path.substr(1, path.length() - 1);
  1459. }
  1460. RES res = ResourceLoader::load(path);
  1461. ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + path);
  1462. Node *n = nullptr;
  1463. if (res->is_class("PackedScene")) {
  1464. Ref<PackedScene> ps = res;
  1465. n = ps->instance();
  1466. } else if (res->is_class("Script")) {
  1467. Ref<Script> script_res = res;
  1468. StringName ibt = script_res->get_instance_base_type();
  1469. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  1470. ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + path);
  1471. Object *obj = ClassDB::instance(ibt);
  1472. ERR_CONTINUE_MSG(obj == nullptr, "Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt));
  1473. n = Object::cast_to<Node>(obj);
  1474. n->set_script(script_res);
  1475. }
  1476. ERR_CONTINUE_MSG(!n, "Path in autoload not a node or script: " + path);
  1477. n->set_name(name);
  1478. //defer so references are all valid on _ready()
  1479. to_add.push_back(n);
  1480. if (global_var) {
  1481. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1482. ScriptServer::get_language(i)->add_global_constant(name, n);
  1483. }
  1484. }
  1485. }
  1486. for (List<Node *>::Element *E = to_add.front(); E; E = E->next()) {
  1487. sml->get_root()->add_child(E->get());
  1488. }
  1489. }
  1490. }
  1491. #ifdef TOOLS_ENABLED
  1492. EditorNode *editor_node = nullptr;
  1493. if (editor) {
  1494. editor_node = memnew(EditorNode);
  1495. sml->get_root()->add_child(editor_node);
  1496. if (_export_preset != "") {
  1497. editor_node->export_preset(_export_preset, positional_arg, export_debug, export_pack_only);
  1498. game_path = ""; // Do not load anything.
  1499. }
  1500. }
  1501. #endif
  1502. {
  1503. int directional_atlas_size = GLOBAL_GET("rendering/quality/directional_shadow/size");
  1504. RenderingServer::get_singleton()->directional_shadow_atlas_set_size(directional_atlas_size);
  1505. }
  1506. if (!editor && !project_manager) {
  1507. //standard helpers that can be changed from main config
  1508. String stretch_mode = GLOBAL_DEF("display/window/stretch/mode", "disabled");
  1509. String stretch_aspect = GLOBAL_DEF("display/window/stretch/aspect", "ignore");
  1510. Size2i stretch_size = Size2(GLOBAL_DEF("display/window/size/width", 0), GLOBAL_DEF("display/window/size/height", 0));
  1511. Window::ContentScaleMode cs_sm = Window::CONTENT_SCALE_MODE_DISABLED;
  1512. if (stretch_mode == "objects")
  1513. cs_sm = Window::CONTENT_SCALE_MODE_OBJECTS;
  1514. else if (stretch_mode == "pixels")
  1515. cs_sm = Window::CONTENT_SCALE_MODE_PIXELS;
  1516. Window::ContentScaleAspect cs_aspect = Window::CONTENT_SCALE_ASPECT_IGNORE;
  1517. if (stretch_aspect == "keep")
  1518. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP;
  1519. else if (stretch_aspect == "keep_width")
  1520. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_WIDTH;
  1521. else if (stretch_aspect == "keep_height")
  1522. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_HEIGHT;
  1523. else if (stretch_aspect == "expand")
  1524. cs_aspect = Window::CONTENT_SCALE_ASPECT_EXPAND;
  1525. sml->get_root()->set_content_scale_mode(cs_sm);
  1526. sml->get_root()->set_content_scale_aspect(cs_aspect);
  1527. sml->get_root()->set_content_scale_size(stretch_size);
  1528. sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true));
  1529. sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true));
  1530. String appname = ProjectSettings::get_singleton()->get("application/config/name");
  1531. appname = TranslationServer::get_singleton()->translate(appname);
  1532. DisplayServer::get_singleton()->window_set_title(appname);
  1533. int shadow_atlas_size = GLOBAL_GET("rendering/quality/shadow_atlas/size");
  1534. int shadow_atlas_q0_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_0_subdiv");
  1535. int shadow_atlas_q1_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_1_subdiv");
  1536. int shadow_atlas_q2_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_2_subdiv");
  1537. int shadow_atlas_q3_subdiv = GLOBAL_GET("rendering/quality/shadow_atlas/quadrant_3_subdiv");
  1538. sml->get_root()->set_shadow_atlas_size(shadow_atlas_size);
  1539. sml->get_root()->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q0_subdiv));
  1540. sml->get_root()->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q1_subdiv));
  1541. sml->get_root()->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q2_subdiv));
  1542. sml->get_root()->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q3_subdiv));
  1543. bool snap_controls = GLOBAL_DEF("gui/common/snap_controls_to_pixels", true);
  1544. sml->get_root()->set_snap_controls_to_pixels(snap_controls);
  1545. bool font_oversampling = GLOBAL_DEF("rendering/quality/dynamic_fonts/use_oversampling", true);
  1546. sml->get_root()->set_use_font_oversampling(font_oversampling);
  1547. int texture_filter = GLOBAL_DEF("rendering/canvas_textures/default_texture_filter", 1);
  1548. int texture_repeat = GLOBAL_DEF("rendering/canvas_textures/default_texture_repeat", 0);
  1549. sml->get_root()->set_default_canvas_item_texture_filter(Viewport::DefaultCanvasItemTextureFilter(texture_filter));
  1550. sml->get_root()->set_default_canvas_item_texture_repeat(Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
  1551. } else {
  1552. GLOBAL_DEF("display/window/stretch/mode", "disabled");
  1553. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/mode", PropertyInfo(Variant::STRING, "display/window/stretch/mode", PROPERTY_HINT_ENUM, "disabled,2d,viewport"));
  1554. GLOBAL_DEF("display/window/stretch/aspect", "ignore");
  1555. 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"));
  1556. GLOBAL_DEF("display/window/stretch/shrink", 1.0);
  1557. ProjectSettings::get_singleton()->set_custom_property_info("display/window/stretch/shrink", PropertyInfo(Variant::FLOAT, "display/window/stretch/shrink", PROPERTY_HINT_RANGE, "1.0,8.0,0.1"));
  1558. sml->set_auto_accept_quit(GLOBAL_DEF("application/config/auto_accept_quit", true));
  1559. sml->set_quit_on_go_back(GLOBAL_DEF("application/config/quit_on_go_back", true));
  1560. GLOBAL_DEF("gui/common/snap_controls_to_pixels", true);
  1561. GLOBAL_DEF("rendering/quality/dynamic_fonts/use_oversampling", true);
  1562. GLOBAL_DEF("rendering/canvas_textures/default_texture_filter", 1);
  1563. ProjectSettings::get_singleton()->set_custom_property_info("rendering/canvas_textures/default_texture_filter", PropertyInfo(Variant::INT, "rendering/canvas_textures/default_texture_filter", PROPERTY_HINT_ENUM, "Nearest,Linear,MipmapLinear,MipmapNearest"));
  1564. GLOBAL_DEF("rendering/canvas_textures/default_texture_repeat", 0);
  1565. ProjectSettings::get_singleton()->set_custom_property_info("rendering/canvas_textures/default_texture_repeat", PropertyInfo(Variant::INT, "rendering/canvas_textures/default_texture_repeat", PROPERTY_HINT_ENUM, "Disable,Enable,Mirror"));
  1566. }
  1567. String local_game_path;
  1568. if (game_path != "" && !project_manager) {
  1569. local_game_path = game_path.replace("\\", "/");
  1570. if (!local_game_path.begins_with("res://")) {
  1571. bool absolute = (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
  1572. if (!absolute) {
  1573. if (ProjectSettings::get_singleton()->is_using_datapack()) {
  1574. local_game_path = "res://" + local_game_path;
  1575. } else {
  1576. int sep = local_game_path.find_last("/");
  1577. if (sep == -1) {
  1578. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  1579. local_game_path = da->get_current_dir().plus_file(local_game_path);
  1580. memdelete(da);
  1581. } else {
  1582. DirAccess *da = DirAccess::open(local_game_path.substr(0, sep));
  1583. if (da) {
  1584. local_game_path = da->get_current_dir().plus_file(local_game_path.substr(sep + 1, local_game_path.length()));
  1585. memdelete(da);
  1586. }
  1587. }
  1588. }
  1589. }
  1590. }
  1591. local_game_path = ProjectSettings::get_singleton()->localize_path(local_game_path);
  1592. #ifdef TOOLS_ENABLED
  1593. if (editor) {
  1594. bool editor_embed_subwindows = EditorSettings::get_singleton()->get_setting("interface/editor/single_window_mode");
  1595. if (editor_embed_subwindows) {
  1596. sml->get_root()->set_embed_subwindows_hint(true);
  1597. }
  1598. if (game_path != GLOBAL_GET("application/run/main_scene") || !editor_node->has_scenes_in_session()) {
  1599. Error serr = editor_node->load_scene(local_game_path);
  1600. if (serr != OK)
  1601. ERR_PRINT("Failed to load scene");
  1602. }
  1603. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_EDITOR);
  1604. }
  1605. #endif
  1606. if (!editor) {
  1607. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_ENGINE);
  1608. }
  1609. }
  1610. if (!project_manager && !editor) { // game
  1611. // Load SSL Certificates from Project Settings (or builtin).
  1612. Crypto::load_default_certificates(GLOBAL_DEF("network/ssl/certificates", ""));
  1613. if (game_path != "") {
  1614. Node *scene = nullptr;
  1615. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  1616. if (scenedata.is_valid())
  1617. scene = scenedata->instance();
  1618. ERR_FAIL_COND_V_MSG(!scene, false, "Failed loading scene: " + local_game_path);
  1619. sml->add_current_scene(scene);
  1620. #ifdef OSX_ENABLED
  1621. String mac_iconpath = GLOBAL_DEF("application/config/macos_native_icon", "Variant()");
  1622. if (mac_iconpath != "") {
  1623. DisplayServer::get_singleton()->set_native_icon(mac_iconpath);
  1624. hasicon = true;
  1625. }
  1626. #endif
  1627. #ifdef WINDOWS_ENABLED
  1628. String win_iconpath = GLOBAL_DEF("application/config/windows_native_icon", "Variant()");
  1629. if (win_iconpath != "") {
  1630. DisplayServer::get_singleton()->set_native_icon(win_iconpath);
  1631. hasicon = true;
  1632. }
  1633. #endif
  1634. String iconpath = GLOBAL_DEF("application/config/icon", "Variant()");
  1635. if ((iconpath != "") && (!hasicon)) {
  1636. Ref<Image> icon;
  1637. icon.instance();
  1638. if (ImageLoader::load_image(iconpath, icon) == OK) {
  1639. DisplayServer::get_singleton()->set_icon(icon);
  1640. hasicon = true;
  1641. }
  1642. }
  1643. }
  1644. }
  1645. #ifdef TOOLS_ENABLED
  1646. if (project_manager || (script == "" && test == "" && game_path == "" && !editor)) {
  1647. Engine::get_singleton()->set_editor_hint(true);
  1648. ProjectManager *pmanager = memnew(ProjectManager);
  1649. ProgressDialog *progress_dialog = memnew(ProgressDialog);
  1650. pmanager->add_child(progress_dialog);
  1651. sml->get_root()->add_child(pmanager);
  1652. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_PROJECTMAN);
  1653. project_manager = true;
  1654. }
  1655. if (project_manager || editor) {
  1656. // Hide console window if requested (Windows-only).
  1657. bool hide_console = EditorSettings::get_singleton()->get_setting("interface/editor/hide_console_window");
  1658. DisplayServer::get_singleton()->console_set_visible(!hide_console);
  1659. // Load SSL Certificates from Editor Settings (or builtin)
  1660. Crypto::load_default_certificates(EditorSettings::get_singleton()->get_setting("network/ssl/editor_ssl_certificates").operator String());
  1661. }
  1662. #endif
  1663. }
  1664. if (!hasicon) {
  1665. Ref<Image> icon = memnew(Image(app_icon_png));
  1666. DisplayServer::get_singleton()->set_icon(icon);
  1667. }
  1668. OS::get_singleton()->set_main_loop(main_loop);
  1669. return true;
  1670. }
  1671. /* Main iteration
  1672. *
  1673. * This is the iteration of the engine's game loop, advancing the state of physics,
  1674. * rendering and audio.
  1675. * It's called directly by the platform's OS::run method, where the loop is created
  1676. * and monitored.
  1677. *
  1678. * The OS implementation can impact its draw step with the Main::force_redraw() method.
  1679. */
  1680. uint64_t Main::last_ticks = 0;
  1681. uint64_t Main::target_ticks = 0;
  1682. uint32_t Main::frames = 0;
  1683. uint32_t Main::frame = 0;
  1684. bool Main::force_redraw_requested = false;
  1685. int Main::iterating = 0;
  1686. bool Main::is_iterating() {
  1687. return iterating > 0;
  1688. }
  1689. // For performance metrics.
  1690. static uint64_t physics_process_max = 0;
  1691. static uint64_t idle_process_max = 0;
  1692. bool Main::iteration() {
  1693. //for now do not error on this
  1694. //ERR_FAIL_COND_V(iterating, false);
  1695. iterating++;
  1696. uint64_t ticks = OS::get_singleton()->get_ticks_usec();
  1697. Engine::get_singleton()->_frame_ticks = ticks;
  1698. main_timer_sync.set_cpu_ticks_usec(ticks);
  1699. main_timer_sync.set_fixed_fps(fixed_fps);
  1700. uint64_t ticks_elapsed = ticks - last_ticks;
  1701. int physics_fps = Engine::get_singleton()->get_iterations_per_second();
  1702. float frame_slice = 1.0 / physics_fps;
  1703. float time_scale = Engine::get_singleton()->get_time_scale();
  1704. MainFrameTime advance = main_timer_sync.advance(frame_slice, physics_fps);
  1705. double step = advance.idle_step;
  1706. double scaled_step = step * time_scale;
  1707. Engine::get_singleton()->_frame_step = step;
  1708. Engine::get_singleton()->_physics_interpolation_fraction = advance.interpolation_fraction;
  1709. uint64_t physics_process_ticks = 0;
  1710. uint64_t idle_process_ticks = 0;
  1711. frame += ticks_elapsed;
  1712. last_ticks = ticks;
  1713. static const int max_physics_steps = 8;
  1714. if (fixed_fps == -1 && advance.physics_steps > max_physics_steps) {
  1715. step -= (advance.physics_steps - max_physics_steps) * frame_slice;
  1716. advance.physics_steps = max_physics_steps;
  1717. }
  1718. bool exit = false;
  1719. Engine::get_singleton()->_in_physics = true;
  1720. for (int iters = 0; iters < advance.physics_steps; ++iters) {
  1721. uint64_t physics_begin = OS::get_singleton()->get_ticks_usec();
  1722. PhysicsServer3D::get_singleton()->sync();
  1723. PhysicsServer3D::get_singleton()->flush_queries();
  1724. PhysicsServer2D::get_singleton()->sync();
  1725. PhysicsServer2D::get_singleton()->flush_queries();
  1726. if (OS::get_singleton()->get_main_loop()->iteration(frame_slice * time_scale)) {
  1727. exit = true;
  1728. break;
  1729. }
  1730. NavigationServer3D::get_singleton_mut()->process(frame_slice * time_scale);
  1731. message_queue->flush();
  1732. PhysicsServer3D::get_singleton()->step(frame_slice * time_scale);
  1733. PhysicsServer2D::get_singleton()->end_sync();
  1734. PhysicsServer2D::get_singleton()->step(frame_slice * time_scale);
  1735. message_queue->flush();
  1736. physics_process_ticks = MAX(physics_process_ticks, OS::get_singleton()->get_ticks_usec() - physics_begin); // keep the largest one for reference
  1737. physics_process_max = MAX(OS::get_singleton()->get_ticks_usec() - physics_begin, physics_process_max);
  1738. Engine::get_singleton()->_physics_frames++;
  1739. }
  1740. Engine::get_singleton()->_in_physics = false;
  1741. uint64_t idle_begin = OS::get_singleton()->get_ticks_usec();
  1742. if (OS::get_singleton()->get_main_loop()->idle(step * time_scale)) {
  1743. exit = true;
  1744. }
  1745. message_queue->flush();
  1746. RenderingServer::get_singleton()->sync(); //sync if still drawing from previous frames.
  1747. if (DisplayServer::get_singleton()->can_any_window_draw() && !disable_render_loop) {
  1748. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  1749. if (RenderingServer::get_singleton()->has_changed()) {
  1750. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  1751. Engine::get_singleton()->frames_drawn++;
  1752. }
  1753. } else {
  1754. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  1755. Engine::get_singleton()->frames_drawn++;
  1756. force_redraw_requested = false;
  1757. }
  1758. }
  1759. idle_process_ticks = OS::get_singleton()->get_ticks_usec() - idle_begin;
  1760. idle_process_max = MAX(idle_process_ticks, idle_process_max);
  1761. uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
  1762. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  1763. ScriptServer::get_language(i)->frame();
  1764. }
  1765. AudioServer::get_singleton()->update();
  1766. if (EngineDebugger::is_active())
  1767. EngineDebugger::get_singleton()->iteration(frame_time, idle_process_ticks, physics_process_ticks, frame_slice);
  1768. frames++;
  1769. Engine::get_singleton()->_idle_frames++;
  1770. if (frame > 1000000) {
  1771. if (editor || project_manager) {
  1772. if (print_fps) {
  1773. print_line("Editor FPS: " + itos(frames));
  1774. }
  1775. } else if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
  1776. print_line("Game FPS: " + itos(frames));
  1777. }
  1778. Engine::get_singleton()->_fps = frames;
  1779. performance->set_process_time(USEC_TO_SEC(idle_process_max));
  1780. performance->set_physics_process_time(USEC_TO_SEC(physics_process_max));
  1781. idle_process_max = 0;
  1782. physics_process_max = 0;
  1783. frame %= 1000000;
  1784. frames = 0;
  1785. }
  1786. iterating--;
  1787. if (fixed_fps != -1)
  1788. return exit;
  1789. if (OS::get_singleton()->is_in_low_processor_usage_mode() || !DisplayServer::get_singleton()->can_any_window_draw())
  1790. OS::get_singleton()->delay_usec(OS::get_singleton()->get_low_processor_usage_mode_sleep_usec()); //apply some delay to force idle time
  1791. else {
  1792. uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
  1793. if (frame_delay)
  1794. OS::get_singleton()->delay_usec(Engine::get_singleton()->get_frame_delay() * 1000);
  1795. }
  1796. int target_fps = Engine::get_singleton()->get_target_fps();
  1797. if (target_fps > 0 && !Engine::get_singleton()->is_editor_hint()) {
  1798. uint64_t time_step = 1000000L / target_fps;
  1799. target_ticks += time_step;
  1800. uint64_t current_ticks = OS::get_singleton()->get_ticks_usec();
  1801. if (current_ticks < target_ticks)
  1802. OS::get_singleton()->delay_usec(target_ticks - current_ticks);
  1803. current_ticks = OS::get_singleton()->get_ticks_usec();
  1804. target_ticks = MIN(MAX(target_ticks, current_ticks - time_step), current_ticks + time_step);
  1805. }
  1806. #ifdef TOOLS_ENABLED
  1807. if (auto_build_solutions) {
  1808. auto_build_solutions = false;
  1809. // Only relevant when running the editor.
  1810. if (!editor) {
  1811. ERR_FAIL_V_MSG(true, "Command line option --build-solutions was passed, but no project is being edited. Aborting.");
  1812. }
  1813. if (!EditorNode::get_singleton()->call_build()) {
  1814. ERR_FAIL_V_MSG(true, "Command line option --build-solutions was passed, but the build callback failed. Aborting.");
  1815. }
  1816. }
  1817. #endif
  1818. return exit || auto_quit;
  1819. }
  1820. void Main::force_redraw() {
  1821. force_redraw_requested = true;
  1822. }
  1823. /* Engine deinitialization
  1824. *
  1825. * Responsible for freeing all the memory allocated by previous setup steps,
  1826. * so that the engine closes cleanly without leaking memory or crashing.
  1827. * The order matters as some of those steps are linked with each other.
  1828. */
  1829. void Main::cleanup() {
  1830. ERR_FAIL_COND(!_start_success);
  1831. EngineDebugger::deinitialize();
  1832. ResourceLoader::remove_custom_loaders();
  1833. ResourceSaver::remove_custom_savers();
  1834. message_queue->flush();
  1835. memdelete(message_queue);
  1836. OS::get_singleton()->delete_main_loop();
  1837. OS::get_singleton()->_cmdline.clear();
  1838. OS::get_singleton()->_execpath = "";
  1839. OS::get_singleton()->_local_clipboard = "";
  1840. ResourceLoader::clear_translation_remaps();
  1841. ResourceLoader::clear_path_remaps();
  1842. ScriptServer::finish_languages();
  1843. // Sync pending commands that may have been queued from a different thread during ScriptServer finalization
  1844. RenderingServer::get_singleton()->sync();
  1845. //clear global shader variables before scene and other graphics stuff is deinitialized.
  1846. rendering_server->global_variables_clear();
  1847. #ifdef TOOLS_ENABLED
  1848. EditorNode::unregister_editor_types();
  1849. #endif
  1850. if (xr_server) {
  1851. // cleanup now before we pull the rug from underneath...
  1852. memdelete(xr_server);
  1853. }
  1854. ImageLoader::cleanup();
  1855. unregister_driver_types();
  1856. unregister_module_types();
  1857. unregister_platform_apis();
  1858. unregister_scene_types();
  1859. unregister_server_types();
  1860. if (audio_server) {
  1861. audio_server->finish();
  1862. memdelete(audio_server);
  1863. }
  1864. if (camera_server) {
  1865. memdelete(camera_server);
  1866. }
  1867. OS::get_singleton()->finalize();
  1868. finalize_physics();
  1869. finalize_navigation_server();
  1870. finalize_display();
  1871. if (input) {
  1872. memdelete(input);
  1873. }
  1874. if (packed_data)
  1875. memdelete(packed_data);
  1876. if (file_access_network_client)
  1877. memdelete(file_access_network_client);
  1878. if (performance)
  1879. memdelete(performance);
  1880. if (input_map)
  1881. memdelete(input_map);
  1882. if (translation_server)
  1883. memdelete(translation_server);
  1884. if (globals)
  1885. memdelete(globals);
  1886. if (engine)
  1887. memdelete(engine);
  1888. if (OS::get_singleton()->is_restart_on_exit_set()) {
  1889. //attempt to restart with arguments
  1890. String exec = OS::get_singleton()->get_executable_path();
  1891. List<String> args = OS::get_singleton()->get_restart_on_exit_arguments();
  1892. OS::ProcessID pid = 0;
  1893. OS::get_singleton()->execute(exec, args, false, &pid);
  1894. OS::get_singleton()->set_restart_on_exit(false, List<String>()); //clear list (uses memory)
  1895. }
  1896. unregister_core_driver_types();
  1897. unregister_core_types();
  1898. OS::get_singleton()->finalize_core();
  1899. }