2
0

main.cpp 82 KB

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