main.cpp 91 KB

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