main.cpp 146 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946
  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/config/project_settings.h"
  32. #include "core/core_globals.h"
  33. #include "core/core_string_names.h"
  34. #include "core/crypto/crypto.h"
  35. #include "core/debugger/engine_debugger.h"
  36. #include "core/extension/extension_api_dump.h"
  37. #include "core/extension/gdextension_interface_dump.gen.h"
  38. #include "core/extension/gdextension_manager.h"
  39. #include "core/input/input.h"
  40. #include "core/input/input_map.h"
  41. #include "core/io/dir_access.h"
  42. #include "core/io/file_access_pack.h"
  43. #include "core/io/file_access_zip.h"
  44. #include "core/io/image_loader.h"
  45. #include "core/io/ip.h"
  46. #include "core/io/resource_loader.h"
  47. #include "core/object/message_queue.h"
  48. #include "core/os/os.h"
  49. #include "core/os/time.h"
  50. #include "core/register_core_types.h"
  51. #include "core/string/translation.h"
  52. #include "core/version.h"
  53. #include "drivers/register_driver_types.h"
  54. #include "main/app_icon.gen.h"
  55. #include "main/main_timer_sync.h"
  56. #include "main/performance.h"
  57. #include "main/splash.gen.h"
  58. #include "modules/register_module_types.h"
  59. #include "platform/register_platform_apis.h"
  60. #include "scene/main/scene_tree.h"
  61. #include "scene/main/window.h"
  62. #include "scene/register_scene_types.h"
  63. #include "scene/resources/packed_scene.h"
  64. #include "scene/theme/theme_db.h"
  65. #include "servers/audio_server.h"
  66. #include "servers/camera_server.h"
  67. #include "servers/display_server.h"
  68. #include "servers/movie_writer/movie_writer.h"
  69. #include "servers/movie_writer/movie_writer_mjpeg.h"
  70. #include "servers/navigation_server_2d.h"
  71. #include "servers/navigation_server_2d_dummy.h"
  72. #include "servers/navigation_server_3d.h"
  73. #include "servers/navigation_server_3d_dummy.h"
  74. #include "servers/physics_server_2d.h"
  75. #include "servers/physics_server_3d.h"
  76. #include "servers/register_server_types.h"
  77. #include "servers/rendering/rendering_server_default.h"
  78. #include "servers/text/text_server_dummy.h"
  79. #include "servers/text_server.h"
  80. #include "servers/xr_server.h"
  81. #ifdef TESTS_ENABLED
  82. #include "tests/test_main.h"
  83. #endif
  84. #ifdef TOOLS_ENABLED
  85. #include "editor/debugger/editor_debugger_node.h"
  86. #include "editor/doc_data_class_path.gen.h"
  87. #include "editor/doc_tools.h"
  88. #include "editor/editor_file_system.h"
  89. #include "editor/editor_help.h"
  90. #include "editor/editor_node.h"
  91. #include "editor/editor_paths.h"
  92. #include "editor/editor_settings.h"
  93. #include "editor/editor_translation.h"
  94. #include "editor/progress_dialog.h"
  95. #include "editor/project_manager.h"
  96. #include "editor/register_editor_types.h"
  97. #ifndef NO_EDITOR_SPLASH
  98. #include "main/splash_editor.gen.h"
  99. #endif
  100. #ifndef DISABLE_DEPRECATED
  101. #include "editor/project_converter_3_to_4.h"
  102. #endif // DISABLE_DEPRECATED
  103. #endif // TOOLS_ENABLED
  104. #include "modules/modules_enabled.gen.h" // For mono.
  105. #if defined(MODULE_MONO_ENABLED) && defined(TOOLS_ENABLED)
  106. #include "modules/mono/editor/bindings_generator.h"
  107. #endif
  108. #ifdef MODULE_GDSCRIPT_ENABLED
  109. #include "modules/gdscript/gdscript.h"
  110. #if defined(TOOLS_ENABLED) && !defined(GDSCRIPT_NO_LSP)
  111. #include "modules/gdscript/language_server/gdscript_language_server.h"
  112. #endif // TOOLS_ENABLED && !GDSCRIPT_NO_LSP
  113. #endif // MODULE_GDSCRIPT_ENABLED
  114. /* Static members */
  115. // Singletons
  116. // Initialized in setup()
  117. static Engine *engine = nullptr;
  118. static ProjectSettings *globals = nullptr;
  119. static Input *input = nullptr;
  120. static InputMap *input_map = nullptr;
  121. static TranslationServer *translation_server = nullptr;
  122. static Performance *performance = nullptr;
  123. static PackedData *packed_data = nullptr;
  124. static Time *time_singleton = nullptr;
  125. #ifdef MINIZIP_ENABLED
  126. static ZipArchive *zip_packed_data = nullptr;
  127. #endif
  128. static MessageQueue *message_queue = nullptr;
  129. // Initialized in setup2()
  130. static AudioServer *audio_server = nullptr;
  131. static DisplayServer *display_server = nullptr;
  132. static RenderingServer *rendering_server = nullptr;
  133. static CameraServer *camera_server = nullptr;
  134. static XRServer *xr_server = nullptr;
  135. static TextServerManager *tsman = nullptr;
  136. static PhysicsServer3DManager *physics_server_3d_manager = nullptr;
  137. static PhysicsServer3D *physics_server_3d = nullptr;
  138. static PhysicsServer2DManager *physics_server_2d_manager = nullptr;
  139. static PhysicsServer2D *physics_server_2d = nullptr;
  140. static NavigationServer3D *navigation_server_3d = nullptr;
  141. static NavigationServer2D *navigation_server_2d = nullptr;
  142. static ThemeDB *theme_db = nullptr;
  143. // We error out if setup2() doesn't turn this true
  144. static bool _start_success = false;
  145. // Drivers
  146. String tablet_driver = "";
  147. String text_driver = "";
  148. String rendering_driver = "";
  149. String rendering_method = "";
  150. static int text_driver_idx = -1;
  151. static int display_driver_idx = -1;
  152. static int audio_driver_idx = -1;
  153. // Engine config/tools
  154. static bool single_window = false;
  155. static bool editor = false;
  156. static bool project_manager = false;
  157. static bool cmdline_tool = false;
  158. static String locale;
  159. static bool show_help = false;
  160. static uint64_t quit_after = 0;
  161. static OS::ProcessID editor_pid = 0;
  162. #ifdef TOOLS_ENABLED
  163. static bool found_project = false;
  164. static bool auto_build_solutions = false;
  165. static String debug_server_uri;
  166. static bool wait_for_import = false;
  167. #ifndef DISABLE_DEPRECATED
  168. static int converter_max_kb_file = 4 * 1024; // 4MB
  169. static int converter_max_line_length = 100000;
  170. #endif // DISABLE_DEPRECATED
  171. HashMap<Main::CLIScope, Vector<String>> forwardable_cli_arguments;
  172. #endif
  173. static bool single_threaded_scene = false;
  174. // Display
  175. static DisplayServer::WindowMode window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
  176. static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCREEN_LANDSCAPE;
  177. static DisplayServer::VSyncMode window_vsync_mode = DisplayServer::VSYNC_ENABLED;
  178. static uint32_t window_flags = 0;
  179. static Size2i window_size = Size2i(1152, 648);
  180. static int init_screen = DisplayServer::SCREEN_PRIMARY;
  181. static bool init_fullscreen = false;
  182. static bool init_maximized = false;
  183. static bool init_windowed = false;
  184. static bool init_always_on_top = false;
  185. static bool init_use_custom_pos = false;
  186. static bool init_use_custom_screen = false;
  187. static Vector2 init_custom_pos;
  188. // Debug
  189. static bool use_debug_profiler = false;
  190. #ifdef DEBUG_ENABLED
  191. static bool debug_collisions = false;
  192. static bool debug_paths = false;
  193. static bool debug_navigation = false;
  194. static bool debug_avoidance = false;
  195. static bool debug_canvas_item_redraw = false;
  196. #endif
  197. static int max_fps = -1;
  198. static int frame_delay = 0;
  199. static int audio_output_latency = 0;
  200. static bool disable_render_loop = false;
  201. static int fixed_fps = -1;
  202. static MovieWriter *movie_writer = nullptr;
  203. static bool disable_vsync = false;
  204. static bool print_fps = false;
  205. #ifdef TOOLS_ENABLED
  206. static bool dump_gdextension_interface = false;
  207. static bool dump_extension_api = false;
  208. static bool include_docs_in_extension_api_dump = false;
  209. static bool validate_extension_api = false;
  210. static String validate_extension_api_file;
  211. #endif
  212. bool profile_gpu = false;
  213. // Constants.
  214. static const String NULL_DISPLAY_DRIVER("headless");
  215. static const String NULL_AUDIO_DRIVER("Dummy");
  216. /* Helper methods */
  217. bool Main::is_cmdline_tool() {
  218. return cmdline_tool;
  219. }
  220. #ifdef TOOLS_ENABLED
  221. const Vector<String> &Main::get_forwardable_cli_arguments(Main::CLIScope p_scope) {
  222. return forwardable_cli_arguments[p_scope];
  223. }
  224. #endif
  225. static String unescape_cmdline(const String &p_str) {
  226. return p_str.replace("%20", " ");
  227. }
  228. static String get_full_version_string() {
  229. String hash = String(VERSION_HASH);
  230. if (!hash.is_empty()) {
  231. hash = "." + hash.left(9);
  232. }
  233. return String(VERSION_FULL_BUILD) + hash;
  234. }
  235. #if defined(TOOLS_ENABLED) && defined(MODULE_GDSCRIPT_ENABLED)
  236. static Vector<String> get_files_with_extension(const String &p_root, const String &p_extension) {
  237. Vector<String> paths;
  238. Ref<DirAccess> dir = DirAccess::open(p_root);
  239. if (dir.is_valid()) {
  240. dir->list_dir_begin();
  241. String fn = dir->get_next();
  242. while (!fn.is_empty()) {
  243. if (!dir->current_is_hidden() && fn != "." && fn != "..") {
  244. if (dir->current_is_dir()) {
  245. paths.append_array(get_files_with_extension(p_root.path_join(fn), p_extension));
  246. } else if (fn.get_extension() == p_extension) {
  247. paths.append(p_root.path_join(fn));
  248. }
  249. }
  250. fn = dir->get_next();
  251. }
  252. dir->list_dir_end();
  253. }
  254. return paths;
  255. }
  256. #endif
  257. // FIXME: Could maybe be moved to have less code in main.cpp.
  258. void initialize_physics() {
  259. /// 3D Physics Server
  260. physics_server_3d = PhysicsServer3DManager::get_singleton()->new_server(
  261. GLOBAL_GET(PhysicsServer3DManager::setting_property_name));
  262. if (!physics_server_3d) {
  263. // Physics server not found, Use the default physics
  264. physics_server_3d = PhysicsServer3DManager::get_singleton()->new_default_server();
  265. }
  266. ERR_FAIL_NULL(physics_server_3d);
  267. physics_server_3d->init();
  268. // 2D Physics server
  269. physics_server_2d = PhysicsServer2DManager::get_singleton()->new_server(
  270. GLOBAL_GET(PhysicsServer2DManager::get_singleton()->setting_property_name));
  271. if (!physics_server_2d) {
  272. // Physics server not found, Use the default physics
  273. physics_server_2d = PhysicsServer2DManager::get_singleton()->new_default_server();
  274. }
  275. ERR_FAIL_NULL(physics_server_2d);
  276. physics_server_2d->init();
  277. }
  278. void finalize_physics() {
  279. physics_server_3d->finish();
  280. memdelete(physics_server_3d);
  281. physics_server_2d->finish();
  282. memdelete(physics_server_2d);
  283. }
  284. void finalize_display() {
  285. rendering_server->finish();
  286. memdelete(rendering_server);
  287. memdelete(display_server);
  288. }
  289. void initialize_navigation_server() {
  290. ERR_FAIL_COND(navigation_server_3d != nullptr);
  291. ERR_FAIL_COND(navigation_server_2d != nullptr);
  292. // Init 3D Navigation Server
  293. navigation_server_3d = NavigationServer3DManager::new_default_server();
  294. // Fall back to dummy if no default server has been registered.
  295. if (!navigation_server_3d) {
  296. WARN_PRINT_ONCE("No NavigationServer3D implementation has been registered! Falling back to a dummy implementation: navigation features will be unavailable.");
  297. navigation_server_3d = memnew(NavigationServer3DDummy);
  298. }
  299. // Should be impossible, but make sure it's not null.
  300. ERR_FAIL_NULL_MSG(navigation_server_3d, "Failed to initialize NavigationServer3D.");
  301. navigation_server_3d->init();
  302. // Init 2D Navigation Server
  303. navigation_server_2d = NavigationServer2DManager::new_default_server();
  304. if (!navigation_server_2d) {
  305. WARN_PRINT_ONCE("No NavigationServer2D implementation has been registered! Falling back to a dummy implementation: navigation features will be unavailable.");
  306. navigation_server_2d = memnew(NavigationServer2DDummy);
  307. }
  308. ERR_FAIL_NULL_MSG(navigation_server_2d, "Failed to initialize NavigationServer2D.");
  309. navigation_server_2d->init();
  310. }
  311. void finalize_navigation_server() {
  312. ERR_FAIL_NULL(navigation_server_3d);
  313. navigation_server_3d->finish();
  314. memdelete(navigation_server_3d);
  315. navigation_server_3d = nullptr;
  316. ERR_FAIL_NULL(navigation_server_2d);
  317. navigation_server_2d->finish();
  318. memdelete(navigation_server_2d);
  319. navigation_server_2d = nullptr;
  320. }
  321. void initialize_theme_db() {
  322. theme_db = memnew(ThemeDB);
  323. }
  324. void finalize_theme_db() {
  325. memdelete(theme_db);
  326. theme_db = nullptr;
  327. }
  328. //#define DEBUG_INIT
  329. #ifdef DEBUG_INIT
  330. #define MAIN_PRINT(m_txt) print_line(m_txt)
  331. #else
  332. #define MAIN_PRINT(m_txt)
  333. #endif
  334. void Main::print_help(const char *p_binary) {
  335. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  336. OS::get_singleton()->print("Free and open source software under the terms of the MIT license.\n");
  337. OS::get_singleton()->print("(c) 2014-present Godot Engine contributors.\n");
  338. OS::get_singleton()->print("(c) 2007-2014 Juan Linietsky, Ariel Manzur.\n");
  339. OS::get_singleton()->print("\n");
  340. OS::get_singleton()->print("Usage: %s [options] [path to scene or 'project.godot' file]\n", p_binary);
  341. OS::get_singleton()->print("\n");
  342. OS::get_singleton()->print("General options:\n");
  343. OS::get_singleton()->print(" -h, --help Display this help message.\n");
  344. OS::get_singleton()->print(" --version Display the version string.\n");
  345. OS::get_singleton()->print(" -v, --verbose Use verbose stdout mode.\n");
  346. OS::get_singleton()->print(" -q, --quiet Quiet mode, silences stdout messages. Errors are still displayed.\n");
  347. OS::get_singleton()->print("\n");
  348. OS::get_singleton()->print("Run options:\n");
  349. OS::get_singleton()->print(" --, ++ Separator for user-provided arguments. Following arguments are not used by the engine, but can be read from `OS.get_cmdline_user_args()`.\n");
  350. #ifdef TOOLS_ENABLED
  351. OS::get_singleton()->print(" -e, --editor Start the editor instead of running the scene.\n");
  352. OS::get_singleton()->print(" -p, --project-manager Start the project manager, even if a project is auto-detected.\n");
  353. OS::get_singleton()->print(" --debug-server <uri> Start the editor debug server (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007)\n");
  354. #if defined(MODULE_GDSCRIPT_ENABLED) && !defined(GDSCRIPT_NO_LSP)
  355. OS::get_singleton()->print(" --lsp-port <port> Use the specified port for the language server protocol. The port must be between 0 to 65535.\n");
  356. #endif // MODULE_GDSCRIPT_ENABLED && !GDSCRIPT_NO_LSP
  357. #endif // TOOLS_ENABLED
  358. OS::get_singleton()->print(" --quit Quit after the first iteration.\n");
  359. OS::get_singleton()->print(" --quit-after <int> Quit after the given number of iterations. Set to 0 to disable.\n");
  360. OS::get_singleton()->print(" -l, --language <locale> Use a specific locale (<locale> being a two-letter code).\n");
  361. OS::get_singleton()->print(" --path <directory> Path to a project (<directory> must contain a 'project.godot' file).\n");
  362. OS::get_singleton()->print(" -u, --upwards Scan folders upwards for project.godot file.\n");
  363. OS::get_singleton()->print(" --main-pack <file> Path to a pack (.pck) file to load.\n");
  364. OS::get_singleton()->print(" --render-thread <mode> Render thread mode ['unsafe', 'safe', 'separate'].\n");
  365. OS::get_singleton()->print(" --remote-fs <address> Remote filesystem (<host/IP>[:<port>] address).\n");
  366. OS::get_singleton()->print(" --remote-fs-password <password> Password for remote filesystem.\n");
  367. OS::get_singleton()->print(" --audio-driver <driver> Audio driver [");
  368. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  369. if (i > 0) {
  370. OS::get_singleton()->print(", ");
  371. }
  372. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  373. }
  374. OS::get_singleton()->print("].\n");
  375. OS::get_singleton()->print(" --display-driver <driver> Display driver (and rendering driver) [");
  376. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  377. if (i > 0) {
  378. OS::get_singleton()->print(", ");
  379. }
  380. OS::get_singleton()->print("'%s' (", DisplayServer::get_create_function_name(i));
  381. Vector<String> rd = DisplayServer::get_create_function_rendering_drivers(i);
  382. for (int j = 0; j < rd.size(); j++) {
  383. if (j > 0) {
  384. OS::get_singleton()->print(", ");
  385. }
  386. OS::get_singleton()->print("'%s'", rd[j].utf8().get_data());
  387. }
  388. OS::get_singleton()->print(")");
  389. }
  390. OS::get_singleton()->print("].\n");
  391. OS::get_singleton()->print(" --audio-output-latency <ms> Override audio output latency in milliseconds (default is 15 ms).\n");
  392. OS::get_singleton()->print(" Lower values make sound playback more reactive but increase CPU usage, and may result in audio cracking if the CPU can't keep up.\n");
  393. OS::get_singleton()->print(" --rendering-method <renderer> Renderer name. Requires driver support.\n");
  394. OS::get_singleton()->print(" --rendering-driver <driver> Rendering driver (depends on display driver).\n");
  395. OS::get_singleton()->print(" --gpu-index <device_index> Use a specific GPU (run with --verbose to get available device list).\n");
  396. OS::get_singleton()->print(" --text-driver <driver> Text driver (Fonts, BiDi, shaping).\n");
  397. OS::get_singleton()->print(" --tablet-driver <driver> Pen tablet input driver.\n");
  398. OS::get_singleton()->print(" --headless Enable headless mode (--display-driver headless --audio-driver Dummy). Useful for servers and with --script.\n");
  399. OS::get_singleton()->print(" --write-movie <file> Writes a video to the specified path (usually with .avi or .png extension).\n");
  400. OS::get_singleton()->print(" --fixed-fps is forced when enabled, but it can be used to change movie FPS.\n");
  401. OS::get_singleton()->print(" --disable-vsync can speed up movie writing but makes interaction more difficult.\n");
  402. OS::get_singleton()->print(" --quit-after can be used to specify the number of frames to write.\n");
  403. OS::get_singleton()->print("\n");
  404. OS::get_singleton()->print("Display options:\n");
  405. OS::get_singleton()->print(" -f, --fullscreen Request fullscreen mode.\n");
  406. OS::get_singleton()->print(" -m, --maximized Request a maximized window.\n");
  407. OS::get_singleton()->print(" -w, --windowed Request windowed mode.\n");
  408. OS::get_singleton()->print(" -t, --always-on-top Request an always-on-top window.\n");
  409. OS::get_singleton()->print(" --resolution <W>x<H> Request window resolution.\n");
  410. OS::get_singleton()->print(" --position <X>,<Y> Request window position (if set, screen argument is ignored).\n");
  411. OS::get_singleton()->print(" --screen <N> Request window screen.\n");
  412. OS::get_singleton()->print(" --single-window Use a single window (no separate subwindows).\n");
  413. OS::get_singleton()->print(" --xr-mode <mode> Select XR (Extended Reality) mode ['default', 'off', 'on'].\n");
  414. OS::get_singleton()->print("\n");
  415. OS::get_singleton()->print("Debug options:\n");
  416. OS::get_singleton()->print(" -d, --debug Debug (local stdout debugger).\n");
  417. OS::get_singleton()->print(" -b, --breakpoints Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n");
  418. OS::get_singleton()->print(" --profiling Enable profiling in the script debugger.\n");
  419. OS::get_singleton()->print(" --gpu-profile Show a GPU profile of the tasks that took the most time during frame rendering.\n");
  420. OS::get_singleton()->print(" --gpu-validation Enable graphics API validation layers for debugging.\n");
  421. #if DEBUG_ENABLED
  422. OS::get_singleton()->print(" --gpu-abort Abort on graphics API usage errors (usually validation layer errors). May help see the problem if your system freezes.\n");
  423. #endif
  424. OS::get_singleton()->print(" --generate-spirv-debug-info Generate SPIR-V debug information. This allows source-level shader debugging with RenderDoc.\n");
  425. OS::get_singleton()->print(" --remote-debug <uri> Remote debug (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007).\n");
  426. OS::get_singleton()->print(" --single-threaded-scene Scene tree runs in single-threaded mode. Sub-thread groups are disabled and run on the main thread.\n");
  427. #if defined(DEBUG_ENABLED)
  428. OS::get_singleton()->print(" --debug-collisions Show collision shapes when running the scene.\n");
  429. OS::get_singleton()->print(" --debug-paths Show path lines when running the scene.\n");
  430. OS::get_singleton()->print(" --debug-navigation Show navigation polygons when running the scene.\n");
  431. OS::get_singleton()->print(" --debug-avoidance Show navigation avoidance debug visuals when running the scene.\n");
  432. OS::get_singleton()->print(" --debug-stringnames Print all StringName allocations to stdout when the engine quits.\n");
  433. OS::get_singleton()->print(" --debug-canvas-item-redraw Display a rectangle each time a canvas item requests a redraw (useful to troubleshoot low processor mode).\n");
  434. #endif
  435. OS::get_singleton()->print(" --max-fps <fps> Set a maximum number of frames per second rendered (can be used to limit power usage). A value of 0 results in unlimited framerate.\n");
  436. OS::get_singleton()->print(" --frame-delay <ms> Simulate high CPU load (delay each frame by <ms> milliseconds). Do not use as a FPS limiter; use --max-fps instead.\n");
  437. OS::get_singleton()->print(" --time-scale <scale> Force time scale (higher values are faster, 1.0 is normal speed).\n");
  438. OS::get_singleton()->print(" --disable-vsync Forces disabling of vertical synchronization, even if enabled in the project settings. Does not override driver-level V-Sync enforcement.\n");
  439. OS::get_singleton()->print(" --disable-render-loop Disable render loop so rendering only occurs when called explicitly from script.\n");
  440. OS::get_singleton()->print(" --disable-crash-handler Disable crash handler when supported by the platform code.\n");
  441. OS::get_singleton()->print(" --fixed-fps <fps> Force a fixed number of frames per second. This setting disables real-time synchronization.\n");
  442. OS::get_singleton()->print(" --delta-smoothing <enable> Enable or disable frame delta smoothing ['enable', 'disable'].\n");
  443. OS::get_singleton()->print(" --print-fps Print the frames per second to the stdout.\n");
  444. OS::get_singleton()->print("\n");
  445. OS::get_singleton()->print("Standalone tools:\n");
  446. OS::get_singleton()->print(" -s, --script <script> Run a script.\n");
  447. OS::get_singleton()->print(" --main-loop <main_loop_name> Run a MainLoop specified by its global class name.\n");
  448. OS::get_singleton()->print(" --check-only Only parse for errors and quit (use with --script).\n");
  449. #ifdef TOOLS_ENABLED
  450. OS::get_singleton()->print(" --import Starts the editor, waits for any resources to be imported, and then quits.\n");
  451. OS::get_singleton()->print(" --export-release <preset> <path> Export the project in release mode using the given preset and output path. The preset name should match one defined in export_presets.cfg.\n");
  452. 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').\n");
  453. OS::get_singleton()->print(" The target directory must exist.\n");
  454. OS::get_singleton()->print(" --export-debug <preset> <path> Export the project in debug mode using the given preset and output path. See --export-release description for other considerations.\n");
  455. OS::get_singleton()->print(" --export-pack <preset> <path> Export the project data only using the given preset and output path. The <path> extension determines whether it will be in PCK or ZIP format.\n");
  456. #ifndef DISABLE_DEPRECATED
  457. OS::get_singleton()->print(" --convert-3to4 [<max_file_kb>] [<max_line_size>]\n");
  458. OS::get_singleton()->print(" Converts project from Godot 3.x to Godot 4.x.\n");
  459. OS::get_singleton()->print(" --validate-conversion-3to4 [<max_file_kb>] [<max_line_size>]\n");
  460. OS::get_singleton()->print(" Shows what elements will be renamed when converting project from Godot 3.x to Godot 4.x.\n");
  461. #endif // DISABLE_DEPRECATED
  462. 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");
  463. OS::get_singleton()->print(" --no-docbase Disallow dumping the base types (used with --doctool).\n");
  464. #ifdef MODULE_GDSCRIPT_ENABLED
  465. OS::get_singleton()->print(" --gdscript-docs <path> Rather than dumping the engine API, generate API reference from the inline documentation in the GDScript files found in <path> (used with --doctool).\n");
  466. #endif
  467. 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");
  468. OS::get_singleton()->print(" --dump-gdextension-interface Generate GDExtension header file 'gdextension_interface.h' in the current folder. This file is the base file required to implement a GDExtension.\n");
  469. OS::get_singleton()->print(" --dump-extension-api Generate JSON dump of the Godot API for GDExtension bindings named 'extension_api.json' in the current folder.\n");
  470. OS::get_singleton()->print(" --dump-extension-api-with-docs Generate JSON dump of the Godot API like the previous option, but including documentation.\n");
  471. OS::get_singleton()->print(" --validate-extension-api <path> Validate an extension API file dumped (with one of the two previous options) from a previous version of the engine to ensure API compatibility. If incompatibilities or errors are detected, the return code will be non zero.\n");
  472. OS::get_singleton()->print(" --benchmark Benchmark the run time and print it to console.\n");
  473. OS::get_singleton()->print(" --benchmark-file <path> Benchmark the run time and save it to a given file in JSON format. The path should be absolute.\n");
  474. #ifdef TESTS_ENABLED
  475. OS::get_singleton()->print(" --test [--help] Run unit tests. Use --test --help for more information.\n");
  476. #endif
  477. #endif
  478. OS::get_singleton()->print("\n");
  479. }
  480. #ifdef TESTS_ENABLED
  481. // The order is the same as in `Main::setup()`, only core and some editor types
  482. // are initialized here. This also combines `Main::setup2()` initialization.
  483. Error Main::test_setup() {
  484. Thread::make_main_thread();
  485. set_current_thread_safe_for_nodes(true);
  486. OS::get_singleton()->initialize();
  487. engine = memnew(Engine);
  488. register_core_types();
  489. register_core_driver_types();
  490. packed_data = memnew(PackedData);
  491. globals = memnew(ProjectSettings);
  492. register_core_settings(); // Here globals are present.
  493. translation_server = memnew(TranslationServer);
  494. tsman = memnew(TextServerManager);
  495. if (tsman) {
  496. Ref<TextServerDummy> ts;
  497. ts.instantiate();
  498. tsman->add_interface(ts);
  499. }
  500. physics_server_3d_manager = memnew(PhysicsServer3DManager);
  501. physics_server_2d_manager = memnew(PhysicsServer2DManager);
  502. // From `Main::setup2()`.
  503. initialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  504. register_core_extensions();
  505. register_core_singletons();
  506. /** INITIALIZE SERVERS **/
  507. register_server_types();
  508. XRServer::set_xr_mode(XRServer::XRMODE_OFF); // Skip in tests.
  509. initialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  510. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  511. translation_server->setup(); //register translations, load them, etc.
  512. if (!locale.is_empty()) {
  513. translation_server->set_locale(locale);
  514. }
  515. translation_server->load_translations();
  516. ResourceLoader::load_translation_remaps(); //load remaps for resources
  517. ResourceLoader::load_path_remaps();
  518. // Initialize ThemeDB early so that scene types can register their theme items.
  519. // Default theme will be initialized later, after modules and ScriptServer are ready.
  520. initialize_theme_db();
  521. register_scene_types();
  522. register_driver_types();
  523. register_scene_singletons();
  524. initialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  525. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  526. #ifdef TOOLS_ENABLED
  527. ClassDB::set_current_api(ClassDB::API_EDITOR);
  528. register_editor_types();
  529. initialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  530. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  531. ClassDB::set_current_api(ClassDB::API_CORE);
  532. #endif
  533. register_platform_apis();
  534. // Theme needs modules to be initialized so that sub-resources can be loaded.
  535. theme_db->initialize_theme_noproject();
  536. initialize_navigation_server();
  537. ERR_FAIL_COND_V(TextServerManager::get_singleton()->get_interface_count() == 0, ERR_CANT_CREATE);
  538. /* Use one with the most features available. */
  539. int max_features = 0;
  540. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  541. uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
  542. int feature_number = 0;
  543. while (features) {
  544. feature_number += features & 1;
  545. features >>= 1;
  546. }
  547. if (feature_number >= max_features) {
  548. max_features = feature_number;
  549. text_driver_idx = i;
  550. }
  551. }
  552. if (text_driver_idx >= 0) {
  553. Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(text_driver_idx);
  554. TextServerManager::get_singleton()->set_primary_interface(ts);
  555. if (ts->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
  556. ts->load_support_data("res://" + ts->get_support_data_filename());
  557. }
  558. } else {
  559. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
  560. }
  561. ClassDB::set_current_api(ClassDB::API_NONE);
  562. _start_success = true;
  563. return OK;
  564. }
  565. // The order is the same as in `Main::cleanup()`.
  566. void Main::test_cleanup() {
  567. ERR_FAIL_COND(!_start_success);
  568. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  569. TextServerManager::get_singleton()->get_interface(i)->cleanup();
  570. }
  571. ResourceLoader::remove_custom_loaders();
  572. ResourceSaver::remove_custom_savers();
  573. #ifdef TOOLS_ENABLED
  574. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  575. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  576. unregister_editor_types();
  577. #endif
  578. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  579. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  580. unregister_platform_apis();
  581. unregister_driver_types();
  582. unregister_scene_types();
  583. finalize_theme_db();
  584. finalize_navigation_server();
  585. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  586. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  587. unregister_server_types();
  588. EngineDebugger::deinitialize();
  589. OS::get_singleton()->finalize();
  590. if (packed_data) {
  591. memdelete(packed_data);
  592. }
  593. if (translation_server) {
  594. memdelete(translation_server);
  595. }
  596. if (tsman) {
  597. memdelete(tsman);
  598. }
  599. if (physics_server_3d_manager) {
  600. memdelete(physics_server_3d_manager);
  601. }
  602. if (physics_server_2d_manager) {
  603. memdelete(physics_server_2d_manager);
  604. }
  605. if (globals) {
  606. memdelete(globals);
  607. }
  608. if (engine) {
  609. memdelete(engine);
  610. }
  611. unregister_core_driver_types();
  612. unregister_core_extensions();
  613. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  614. unregister_core_types();
  615. OS::get_singleton()->finalize_core();
  616. }
  617. #endif
  618. int Main::test_entrypoint(int argc, char *argv[], bool &tests_need_run) {
  619. #ifdef TESTS_ENABLED
  620. for (int x = 0; x < argc; x++) {
  621. if ((strncmp(argv[x], "--test", 6) == 0) && (strlen(argv[x]) == 6)) {
  622. tests_need_run = true;
  623. // TODO: need to come up with different test contexts.
  624. // Not every test requires high-level functionality like `ClassDB`.
  625. test_setup();
  626. int status = test_main(argc, argv);
  627. test_cleanup();
  628. return status;
  629. }
  630. }
  631. #endif
  632. tests_need_run = false;
  633. return 0;
  634. }
  635. /* Engine initialization
  636. *
  637. * Consists of several methods that are called by each platform's specific main(argc, argv).
  638. * To fully understand engine init, one should therefore start from the platform's main and
  639. * see how it calls into the Main class' methods.
  640. *
  641. * The initialization is typically done in 3 steps (with the setup2 step triggered either
  642. * automatically by setup, or manually in the platform's main).
  643. *
  644. * - setup(execpath, argc, argv, p_second_phase) is the main entry point for all platforms,
  645. * responsible for the initialization of all low level singletons and core types, and parsing
  646. * command line arguments to configure things accordingly.
  647. * If p_second_phase is true, it will chain into setup2() (default behavior). This is
  648. * disabled on some platforms (Android, iOS) which trigger the second step in their own time.
  649. *
  650. * - setup2(p_main_tid_override) registers high level servers and singletons, displays the
  651. * boot splash, then registers higher level types (scene, editor, etc.).
  652. *
  653. * - start() is the last step and that's where command line tools can run, or the main loop
  654. * can be created eventually and the project settings put into action. That's also where
  655. * the editor node is created, if relevant.
  656. * start() does it own argument parsing for a subset of the command line arguments described
  657. * in help, it's a bit messy and should be globalized with the setup() parsing somehow.
  658. */
  659. Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
  660. Thread::make_main_thread();
  661. set_current_thread_safe_for_nodes(true);
  662. OS::get_singleton()->initialize();
  663. // Benchmark tracking must be done after `OS::get_singleton()->initialize()` as on some
  664. // platforms, it's used to set up the time utilities.
  665. OS::get_singleton()->benchmark_begin_measure("startup_begin");
  666. engine = memnew(Engine);
  667. MAIN_PRINT("Main: Initialize CORE");
  668. OS::get_singleton()->benchmark_begin_measure("core");
  669. register_core_types();
  670. register_core_driver_types();
  671. MAIN_PRINT("Main: Initialize Globals");
  672. input_map = memnew(InputMap);
  673. time_singleton = memnew(Time);
  674. globals = memnew(ProjectSettings);
  675. register_core_settings(); //here globals are present
  676. translation_server = memnew(TranslationServer);
  677. performance = memnew(Performance);
  678. GDREGISTER_CLASS(Performance);
  679. engine->add_singleton(Engine::Singleton("Performance", performance));
  680. // Only flush stdout in debug builds by default, as spamming `print()` will
  681. // decrease performance if this is enabled.
  682. GLOBAL_DEF_RST("application/run/flush_stdout_on_print", false);
  683. GLOBAL_DEF_RST("application/run/flush_stdout_on_print.debug", true);
  684. MAIN_PRINT("Main: Parse CMDLine");
  685. /* argument parsing and main creation */
  686. List<String> args;
  687. List<String> main_args;
  688. List<String> user_args;
  689. bool adding_user_args = false;
  690. List<String> platform_args = OS::get_singleton()->get_cmdline_platform_args();
  691. // Add command line arguments.
  692. for (int i = 0; i < argc; i++) {
  693. args.push_back(String::utf8(argv[i]));
  694. }
  695. // Add arguments received from macOS LaunchService (URL schemas, file associations).
  696. for (const String &arg : platform_args) {
  697. args.push_back(arg);
  698. }
  699. List<String>::Element *I = args.front();
  700. while (I) {
  701. I->get() = unescape_cmdline(I->get().strip_edges());
  702. I = I->next();
  703. }
  704. String display_driver = "";
  705. String audio_driver = "";
  706. String project_path = ".";
  707. bool upwards = false;
  708. String debug_uri = "";
  709. bool skip_breakpoints = false;
  710. String main_pack;
  711. bool quiet_stdout = false;
  712. int rtm = -1;
  713. String remotefs;
  714. String remotefs_pass;
  715. Vector<String> breakpoints;
  716. bool use_custom_res = true;
  717. bool force_res = false;
  718. bool delta_smoothing_override = false;
  719. String default_renderer = "";
  720. String default_renderer_mobile = "";
  721. String renderer_hints = "";
  722. packed_data = PackedData::get_singleton();
  723. if (!packed_data) {
  724. packed_data = memnew(PackedData);
  725. }
  726. #ifdef MINIZIP_ENABLED
  727. //XXX: always get_singleton() == 0x0
  728. zip_packed_data = ZipArchive::get_singleton();
  729. //TODO: remove this temporary fix
  730. if (!zip_packed_data) {
  731. zip_packed_data = memnew(ZipArchive);
  732. }
  733. packed_data->add_pack_source(zip_packed_data);
  734. #endif
  735. // Default exit code, can be modified for certain errors.
  736. Error exit_code = ERR_INVALID_PARAMETER;
  737. I = args.front();
  738. while (I) {
  739. #ifdef MACOS_ENABLED
  740. // Ignore the process serial number argument passed by macOS Gatekeeper.
  741. // Otherwise, Godot would try to open a non-existent project on the first start and abort.
  742. if (I->get().begins_with("-psn_")) {
  743. I = I->next();
  744. continue;
  745. }
  746. #endif
  747. List<String>::Element *N = I->next();
  748. #ifdef TOOLS_ENABLED
  749. if (I->get() == "--debug" ||
  750. I->get() == "--verbose" ||
  751. I->get() == "--disable-crash-handler") {
  752. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
  753. forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(I->get());
  754. }
  755. if (I->get() == "--single-window") {
  756. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
  757. }
  758. if (I->get() == "--audio-driver" ||
  759. I->get() == "--display-driver" ||
  760. I->get() == "--rendering-method" ||
  761. I->get() == "--rendering-driver") {
  762. if (I->next()) {
  763. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
  764. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->next()->get());
  765. }
  766. }
  767. // If gpu is specified, both editor and debug instances started from editor will inherit.
  768. if (I->get() == "--gpu-index") {
  769. if (I->next()) {
  770. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->get());
  771. forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(I->next()->get());
  772. forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(I->get());
  773. forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(I->next()->get());
  774. }
  775. }
  776. #endif
  777. if (adding_user_args) {
  778. user_args.push_back(I->get());
  779. } else if (I->get() == "-h" || I->get() == "--help" || I->get() == "/?") { // display help
  780. show_help = true;
  781. exit_code = ERR_HELP; // Hack to force an early exit in `main()` with a success code.
  782. goto error;
  783. } else if (I->get() == "--version") {
  784. print_line(get_full_version_string());
  785. exit_code = ERR_HELP; // Hack to force an early exit in `main()` with a success code.
  786. goto error;
  787. } else if (I->get() == "-v" || I->get() == "--verbose") { // verbose output
  788. OS::get_singleton()->_verbose_stdout = true;
  789. } else if (I->get() == "-q" || I->get() == "--quiet") { // quieter output
  790. quiet_stdout = true;
  791. } else if (I->get() == "--audio-driver") { // audio driver
  792. if (I->next()) {
  793. audio_driver = I->next()->get();
  794. bool found = false;
  795. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  796. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  797. found = true;
  798. }
  799. }
  800. if (!found) {
  801. OS::get_singleton()->print("Unknown audio driver '%s', aborting.\nValid options are ",
  802. audio_driver.utf8().get_data());
  803. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  804. if (i == AudioDriverManager::get_driver_count() - 1) {
  805. OS::get_singleton()->print(" and ");
  806. } else if (i != 0) {
  807. OS::get_singleton()->print(", ");
  808. }
  809. OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
  810. }
  811. OS::get_singleton()->print(".\n");
  812. goto error;
  813. }
  814. N = I->next()->next();
  815. } else {
  816. OS::get_singleton()->print("Missing audio driver argument, aborting.\n");
  817. goto error;
  818. }
  819. } else if (I->get() == "--audio-output-latency") {
  820. if (I->next()) {
  821. audio_output_latency = I->next()->get().to_int();
  822. N = I->next()->next();
  823. } else {
  824. OS::get_singleton()->print("Missing audio output latency argument, aborting.\n");
  825. goto error;
  826. }
  827. } else if (I->get() == "--text-driver") {
  828. if (I->next()) {
  829. text_driver = I->next()->get();
  830. N = I->next()->next();
  831. } else {
  832. OS::get_singleton()->print("Missing text driver argument, aborting.\n");
  833. goto error;
  834. }
  835. } else if (I->get() == "--display-driver") { // force video driver
  836. if (I->next()) {
  837. display_driver = I->next()->get();
  838. bool found = false;
  839. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  840. if (display_driver == DisplayServer::get_create_function_name(i)) {
  841. found = true;
  842. }
  843. }
  844. if (!found) {
  845. OS::get_singleton()->print("Unknown display driver '%s', aborting.\nValid options are ",
  846. display_driver.utf8().get_data());
  847. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  848. if (i == DisplayServer::get_create_function_count() - 1) {
  849. OS::get_singleton()->print(" and ");
  850. } else if (i != 0) {
  851. OS::get_singleton()->print(", ");
  852. }
  853. OS::get_singleton()->print("'%s'", DisplayServer::get_create_function_name(i));
  854. }
  855. OS::get_singleton()->print(".\n");
  856. goto error;
  857. }
  858. N = I->next()->next();
  859. } else {
  860. OS::get_singleton()->print("Missing display driver argument, aborting.\n");
  861. goto error;
  862. }
  863. } else if (I->get() == "--rendering-method") {
  864. if (I->next()) {
  865. rendering_method = I->next()->get();
  866. N = I->next()->next();
  867. } else {
  868. OS::get_singleton()->print("Missing renderer name argument, aborting.\n");
  869. goto error;
  870. }
  871. } else if (I->get() == "--rendering-driver") {
  872. if (I->next()) {
  873. rendering_driver = I->next()->get();
  874. N = I->next()->next();
  875. } else {
  876. OS::get_singleton()->print("Missing rendering driver argument, aborting.\n");
  877. goto error;
  878. }
  879. } else if (I->get() == "-f" || I->get() == "--fullscreen") { // force fullscreen
  880. init_fullscreen = true;
  881. window_mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
  882. } else if (I->get() == "-m" || I->get() == "--maximized") { // force maximized window
  883. init_maximized = true;
  884. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  885. } else if (I->get() == "-w" || I->get() == "--windowed") { // force windowed window
  886. init_windowed = true;
  887. } else if (I->get() == "--gpu-index") {
  888. if (I->next()) {
  889. Engine::singleton->gpu_idx = I->next()->get().to_int();
  890. N = I->next()->next();
  891. } else {
  892. OS::get_singleton()->print("Missing GPU index argument, aborting.\n");
  893. goto error;
  894. }
  895. } else if (I->get() == "--gpu-validation") {
  896. Engine::singleton->use_validation_layers = true;
  897. #ifdef DEBUG_ENABLED
  898. } else if (I->get() == "--gpu-abort") {
  899. Engine::singleton->abort_on_gpu_errors = true;
  900. #endif
  901. } else if (I->get() == "--generate-spirv-debug-info") {
  902. Engine::singleton->generate_spirv_debug_info = true;
  903. } else if (I->get() == "--tablet-driver") {
  904. if (I->next()) {
  905. tablet_driver = I->next()->get();
  906. N = I->next()->next();
  907. } else {
  908. OS::get_singleton()->print("Missing tablet driver argument, aborting.\n");
  909. goto error;
  910. }
  911. } else if (I->get() == "--delta-smoothing") {
  912. if (I->next()) {
  913. String string = I->next()->get();
  914. bool recognized = false;
  915. if (string == "enable") {
  916. OS::get_singleton()->set_delta_smoothing(true);
  917. delta_smoothing_override = true;
  918. recognized = true;
  919. }
  920. if (string == "disable") {
  921. OS::get_singleton()->set_delta_smoothing(false);
  922. delta_smoothing_override = false;
  923. recognized = true;
  924. }
  925. if (!recognized) {
  926. OS::get_singleton()->print("Delta-smoothing argument not recognized, aborting.\n");
  927. goto error;
  928. }
  929. N = I->next()->next();
  930. } else {
  931. OS::get_singleton()->print("Missing delta-smoothing argument, aborting.\n");
  932. goto error;
  933. }
  934. } else if (I->get() == "--single-window") { // force single window
  935. single_window = true;
  936. } else if (I->get() == "-t" || I->get() == "--always-on-top") { // force always-on-top window
  937. init_always_on_top = true;
  938. } else if (I->get() == "--resolution") { // force resolution
  939. if (I->next()) {
  940. String vm = I->next()->get();
  941. if (!vm.contains("x")) { // invalid parameter format
  942. OS::get_singleton()->print("Invalid resolution '%s', it should be e.g. '1280x720'.\n",
  943. vm.utf8().get_data());
  944. goto error;
  945. }
  946. int w = vm.get_slice("x", 0).to_int();
  947. int h = vm.get_slice("x", 1).to_int();
  948. if (w <= 0 || h <= 0) {
  949. OS::get_singleton()->print("Invalid resolution '%s', width and height must be above 0.\n",
  950. vm.utf8().get_data());
  951. goto error;
  952. }
  953. window_size.width = w;
  954. window_size.height = h;
  955. force_res = true;
  956. N = I->next()->next();
  957. } else {
  958. OS::get_singleton()->print("Missing resolution argument, aborting.\n");
  959. goto error;
  960. }
  961. } else if (I->get() == "--screen") { // set window screen
  962. if (I->next()) {
  963. init_screen = I->next()->get().to_int();
  964. init_use_custom_screen = true;
  965. N = I->next()->next();
  966. } else {
  967. OS::get_singleton()->print("Missing screen argument, aborting.\n");
  968. goto error;
  969. }
  970. } else if (I->get() == "--position") { // set window position
  971. if (I->next()) {
  972. String vm = I->next()->get();
  973. if (!vm.contains(",")) { // invalid parameter format
  974. OS::get_singleton()->print("Invalid position '%s', it should be e.g. '80,128'.\n",
  975. vm.utf8().get_data());
  976. goto error;
  977. }
  978. int x = vm.get_slice(",", 0).to_int();
  979. int y = vm.get_slice(",", 1).to_int();
  980. init_custom_pos = Point2(x, y);
  981. init_use_custom_pos = true;
  982. N = I->next()->next();
  983. } else {
  984. OS::get_singleton()->print("Missing position argument, aborting.\n");
  985. goto error;
  986. }
  987. } else if (I->get() == "--headless") { // enable headless mode (no audio, no rendering).
  988. audio_driver = NULL_AUDIO_DRIVER;
  989. display_driver = NULL_DISPLAY_DRIVER;
  990. } else if (I->get() == "--profiling") { // enable profiling
  991. use_debug_profiler = true;
  992. } else if (I->get() == "-l" || I->get() == "--language") { // language
  993. if (I->next()) {
  994. locale = I->next()->get();
  995. N = I->next()->next();
  996. } else {
  997. OS::get_singleton()->print("Missing language argument, aborting.\n");
  998. goto error;
  999. }
  1000. } else if (I->get() == "--remote-fs") { // remote filesystem
  1001. if (I->next()) {
  1002. remotefs = I->next()->get();
  1003. N = I->next()->next();
  1004. } else {
  1005. OS::get_singleton()->print("Missing remote filesystem address, aborting.\n");
  1006. goto error;
  1007. }
  1008. } else if (I->get() == "--remote-fs-password") { // remote filesystem password
  1009. if (I->next()) {
  1010. remotefs_pass = I->next()->get();
  1011. N = I->next()->next();
  1012. } else {
  1013. OS::get_singleton()->print("Missing remote filesystem password, aborting.\n");
  1014. goto error;
  1015. }
  1016. } else if (I->get() == "--render-thread") { // render thread mode
  1017. if (I->next()) {
  1018. if (I->next()->get() == "safe") {
  1019. rtm = OS::RENDER_THREAD_SAFE;
  1020. } else if (I->next()->get() == "unsafe") {
  1021. rtm = OS::RENDER_THREAD_UNSAFE;
  1022. } else if (I->next()->get() == "separate") {
  1023. rtm = OS::RENDER_SEPARATE_THREAD;
  1024. } else {
  1025. OS::get_singleton()->print("Unknown render thread mode, aborting.\nValid options are 'unsafe', 'safe' and 'separate'.\n");
  1026. goto error;
  1027. }
  1028. N = I->next()->next();
  1029. } else {
  1030. OS::get_singleton()->print("Missing render thread mode argument, aborting.\n");
  1031. goto error;
  1032. }
  1033. #ifdef TOOLS_ENABLED
  1034. } else if (I->get() == "-e" || I->get() == "--editor") { // starts editor
  1035. editor = true;
  1036. } else if (I->get() == "-p" || I->get() == "--project-manager") { // starts project manager
  1037. project_manager = true;
  1038. } else if (I->get() == "--debug-server") {
  1039. if (I->next()) {
  1040. debug_server_uri = I->next()->get();
  1041. if (!debug_server_uri.contains("://")) { // wrong address
  1042. OS::get_singleton()->print("Invalid debug server uri. It should be of the form <protocol>://<bind_address>:<port>.\n");
  1043. goto error;
  1044. }
  1045. N = I->next()->next();
  1046. } else {
  1047. OS::get_singleton()->print("Missing remote debug server uri, aborting.\n");
  1048. goto error;
  1049. }
  1050. } else if (I->get() == "--single-threaded-scene") {
  1051. single_threaded_scene = true;
  1052. } else if (I->get() == "--build-solutions") { // Build the scripting solution such C#
  1053. auto_build_solutions = true;
  1054. editor = true;
  1055. cmdline_tool = true;
  1056. } else if (I->get() == "--dump-gdextension-interface") {
  1057. // Register as an editor instance to use low-end fallback if relevant.
  1058. editor = true;
  1059. cmdline_tool = true;
  1060. dump_gdextension_interface = true;
  1061. print_line("Dumping GDExtension interface header file");
  1062. // Hack. Not needed but otherwise we end up detecting that this should
  1063. // run the project instead of a cmdline tool.
  1064. // Needs full refactoring to fix properly.
  1065. main_args.push_back(I->get());
  1066. } else if (I->get() == "--dump-extension-api") {
  1067. // Register as an editor instance to use low-end fallback if relevant.
  1068. editor = true;
  1069. cmdline_tool = true;
  1070. dump_extension_api = true;
  1071. print_line("Dumping Extension API");
  1072. // Hack. Not needed but otherwise we end up detecting that this should
  1073. // run the project instead of a cmdline tool.
  1074. // Needs full refactoring to fix properly.
  1075. main_args.push_back(I->get());
  1076. } else if (I->get() == "--dump-extension-api-with-docs") {
  1077. // Register as an editor instance to use low-end fallback if relevant.
  1078. editor = true;
  1079. cmdline_tool = true;
  1080. dump_extension_api = true;
  1081. include_docs_in_extension_api_dump = true;
  1082. print_line("Dumping Extension API including documentation");
  1083. // Hack. Not needed but otherwise we end up detecting that this should
  1084. // run the project instead of a cmdline tool.
  1085. // Needs full refactoring to fix properly.
  1086. main_args.push_back(I->get());
  1087. } else if (I->get() == "--validate-extension-api") {
  1088. // Register as an editor instance to use low-end fallback if relevant.
  1089. editor = true;
  1090. cmdline_tool = true;
  1091. validate_extension_api = true;
  1092. // Hack. Not needed but otherwise we end up detecting that this should
  1093. // run the project instead of a cmdline tool.
  1094. // Needs full refactoring to fix properly.
  1095. main_args.push_back(I->get());
  1096. if (I->next()) {
  1097. validate_extension_api_file = I->next()->get();
  1098. N = I->next()->next();
  1099. } else {
  1100. OS::get_singleton()->print("Missing file to load argument after --validate-extension-api, aborting.");
  1101. goto error;
  1102. }
  1103. } else if (I->get() == "--import") {
  1104. editor = true;
  1105. cmdline_tool = true;
  1106. wait_for_import = true;
  1107. quit_after = 1;
  1108. } else if (I->get() == "--export-release" || I->get() == "--export-debug" ||
  1109. I->get() == "--export-pack") { // Export project
  1110. // Actually handling is done in start().
  1111. editor = true;
  1112. cmdline_tool = true;
  1113. wait_for_import = true;
  1114. main_args.push_back(I->get());
  1115. #ifndef DISABLE_DEPRECATED
  1116. } else if (I->get() == "--export") { // For users used to 3.x syntax.
  1117. OS::get_singleton()->print("The Godot 3 --export option was changed to more explicit --export-release / --export-debug / --export-pack options.\nSee the --help output for details.\n");
  1118. goto error;
  1119. } else if (I->get() == "--convert-3to4") {
  1120. // Actually handling is done in start().
  1121. cmdline_tool = true;
  1122. main_args.push_back(I->get());
  1123. if (I->next() && !I->next()->get().begins_with("-")) {
  1124. if (itos(I->next()->get().to_int()) == I->next()->get()) {
  1125. converter_max_kb_file = I->next()->get().to_int();
  1126. }
  1127. if (I->next()->next() && !I->next()->next()->get().begins_with("-")) {
  1128. if (itos(I->next()->next()->get().to_int()) == I->next()->next()->get()) {
  1129. converter_max_line_length = I->next()->next()->get().to_int();
  1130. }
  1131. }
  1132. }
  1133. } else if (I->get() == "--validate-conversion-3to4") {
  1134. // Actually handling is done in start().
  1135. cmdline_tool = true;
  1136. main_args.push_back(I->get());
  1137. if (I->next() && !I->next()->get().begins_with("-")) {
  1138. if (itos(I->next()->get().to_int()) == I->next()->get()) {
  1139. converter_max_kb_file = I->next()->get().to_int();
  1140. }
  1141. if (I->next()->next() && !I->next()->next()->get().begins_with("-")) {
  1142. if (itos(I->next()->next()->get().to_int()) == I->next()->next()->get()) {
  1143. converter_max_line_length = I->next()->next()->get().to_int();
  1144. }
  1145. }
  1146. }
  1147. #endif // DISABLE_DEPRECATED
  1148. } else if (I->get() == "--doctool") {
  1149. // Actually handling is done in start().
  1150. cmdline_tool = true;
  1151. // `--doctool` implies `--headless` to avoid spawning an unnecessary window
  1152. // and speed up class reference generation.
  1153. audio_driver = NULL_AUDIO_DRIVER;
  1154. display_driver = NULL_DISPLAY_DRIVER;
  1155. main_args.push_back(I->get());
  1156. #ifdef MODULE_GDSCRIPT_ENABLED
  1157. } else if (I->get() == "--gdscript-docs") {
  1158. if (I->next()) {
  1159. project_path = I->next()->get();
  1160. // Will be handled in start()
  1161. main_args.push_back(I->get());
  1162. main_args.push_back(I->next()->get());
  1163. N = I->next()->next();
  1164. } else {
  1165. OS::get_singleton()->print("Missing relative or absolute path to project for --gdscript-docs, aborting.\n");
  1166. goto error;
  1167. }
  1168. #endif // MODULE_GDSCRIPT_ENABLED
  1169. #endif // TOOLS_ENABLED
  1170. } else if (I->get() == "--path") { // set path of project to start or edit
  1171. if (I->next()) {
  1172. String p = I->next()->get();
  1173. if (OS::get_singleton()->set_cwd(p) != OK) {
  1174. OS::get_singleton()->print("Invalid project path specified: \"%s\", aborting.\n", p.utf8().get_data());
  1175. goto error;
  1176. }
  1177. N = I->next()->next();
  1178. } else {
  1179. OS::get_singleton()->print("Missing relative or absolute path, aborting.\n");
  1180. goto error;
  1181. }
  1182. } else if (I->get() == "-u" || I->get() == "--upwards") { // scan folders upwards
  1183. upwards = true;
  1184. } else if (I->get() == "--quit") { // Auto quit at the end of the first main loop iteration
  1185. quit_after = 1;
  1186. } else if (I->get() == "--quit-after") { // Quit after the given number of iterations
  1187. if (I->next()) {
  1188. quit_after = I->next()->get().to_int();
  1189. N = I->next()->next();
  1190. } else {
  1191. OS::get_singleton()->print("Missing number of iterations, aborting.\n");
  1192. goto error;
  1193. }
  1194. } else if (I->get().ends_with("project.godot")) {
  1195. String path;
  1196. String file = I->get();
  1197. int sep = MAX(file.rfind("/"), file.rfind("\\"));
  1198. if (sep == -1) {
  1199. path = ".";
  1200. } else {
  1201. path = file.substr(0, sep);
  1202. }
  1203. if (OS::get_singleton()->set_cwd(path) == OK) {
  1204. // path already specified, don't override
  1205. } else {
  1206. project_path = path;
  1207. }
  1208. #ifdef TOOLS_ENABLED
  1209. editor = true;
  1210. #endif
  1211. } else if (I->get() == "-b" || I->get() == "--breakpoints") { // add breakpoints
  1212. if (I->next()) {
  1213. String bplist = I->next()->get();
  1214. breakpoints = bplist.split(",");
  1215. N = I->next()->next();
  1216. } else {
  1217. OS::get_singleton()->print("Missing list of breakpoints, aborting.\n");
  1218. goto error;
  1219. }
  1220. } else if (I->get() == "--max-fps") { // set maximum rendered FPS
  1221. if (I->next()) {
  1222. max_fps = I->next()->get().to_int();
  1223. N = I->next()->next();
  1224. } else {
  1225. OS::get_singleton()->print("Missing maximum FPS argument, aborting.\n");
  1226. goto error;
  1227. }
  1228. } else if (I->get() == "--frame-delay") { // force frame delay
  1229. if (I->next()) {
  1230. frame_delay = I->next()->get().to_int();
  1231. N = I->next()->next();
  1232. } else {
  1233. OS::get_singleton()->print("Missing frame delay argument, aborting.\n");
  1234. goto error;
  1235. }
  1236. } else if (I->get() == "--time-scale") { // force time scale
  1237. if (I->next()) {
  1238. Engine::get_singleton()->set_time_scale(I->next()->get().to_float());
  1239. N = I->next()->next();
  1240. } else {
  1241. OS::get_singleton()->print("Missing time scale argument, aborting.\n");
  1242. goto error;
  1243. }
  1244. } else if (I->get() == "--main-pack") {
  1245. if (I->next()) {
  1246. main_pack = I->next()->get();
  1247. N = I->next()->next();
  1248. } else {
  1249. OS::get_singleton()->print("Missing path to main pack file, aborting.\n");
  1250. goto error;
  1251. };
  1252. } else if (I->get() == "-d" || I->get() == "--debug") {
  1253. debug_uri = "local://";
  1254. OS::get_singleton()->_debug_stdout = true;
  1255. #if defined(DEBUG_ENABLED)
  1256. } else if (I->get() == "--debug-collisions") {
  1257. debug_collisions = true;
  1258. } else if (I->get() == "--debug-paths") {
  1259. debug_paths = true;
  1260. } else if (I->get() == "--debug-navigation") {
  1261. debug_navigation = true;
  1262. } else if (I->get() == "--debug-avoidance") {
  1263. debug_avoidance = true;
  1264. } else if (I->get() == "--debug-canvas-item-redraw") {
  1265. debug_canvas_item_redraw = true;
  1266. } else if (I->get() == "--debug-stringnames") {
  1267. StringName::set_debug_stringnames(true);
  1268. #endif
  1269. } else if (I->get() == "--remote-debug") {
  1270. if (I->next()) {
  1271. debug_uri = I->next()->get();
  1272. if (!debug_uri.contains("://")) { // wrong address
  1273. OS::get_singleton()->print(
  1274. "Invalid debug host address, it should be of the form <protocol>://<host/IP>:<port>.\n");
  1275. goto error;
  1276. }
  1277. N = I->next()->next();
  1278. } else {
  1279. OS::get_singleton()->print("Missing remote debug host address, aborting.\n");
  1280. goto error;
  1281. }
  1282. } else if (I->get() == "--editor-pid") { // not exposed to user
  1283. if (I->next()) {
  1284. editor_pid = I->next()->get().to_int();
  1285. N = I->next()->next();
  1286. } else {
  1287. OS::get_singleton()->print("Missing editor PID argument, aborting.\n");
  1288. goto error;
  1289. }
  1290. } else if (I->get() == "--disable-render-loop") {
  1291. disable_render_loop = true;
  1292. } else if (I->get() == "--fixed-fps") {
  1293. if (I->next()) {
  1294. fixed_fps = I->next()->get().to_int();
  1295. N = I->next()->next();
  1296. } else {
  1297. OS::get_singleton()->print("Missing fixed-fps argument, aborting.\n");
  1298. goto error;
  1299. }
  1300. } else if (I->get() == "--write-movie") {
  1301. if (I->next()) {
  1302. Engine::get_singleton()->set_write_movie_path(I->next()->get());
  1303. N = I->next()->next();
  1304. if (fixed_fps == -1) {
  1305. fixed_fps = 60;
  1306. }
  1307. OS::get_singleton()->_writing_movie = true;
  1308. } else {
  1309. OS::get_singleton()->print("Missing write-movie argument, aborting.\n");
  1310. goto error;
  1311. }
  1312. } else if (I->get() == "--disable-vsync") {
  1313. disable_vsync = true;
  1314. } else if (I->get() == "--print-fps") {
  1315. print_fps = true;
  1316. } else if (I->get() == "--profile-gpu") {
  1317. profile_gpu = true;
  1318. } else if (I->get() == "--disable-crash-handler") {
  1319. OS::get_singleton()->disable_crash_handler();
  1320. } else if (I->get() == "--skip-breakpoints") {
  1321. skip_breakpoints = true;
  1322. } else if (I->get() == "--xr-mode") {
  1323. if (I->next()) {
  1324. String xr_mode = I->next()->get().to_lower();
  1325. N = I->next()->next();
  1326. if (xr_mode == "default") {
  1327. XRServer::set_xr_mode(XRServer::XRMODE_DEFAULT);
  1328. } else if (xr_mode == "off") {
  1329. XRServer::set_xr_mode(XRServer::XRMODE_OFF);
  1330. } else if (xr_mode == "on") {
  1331. XRServer::set_xr_mode(XRServer::XRMODE_ON);
  1332. } else {
  1333. OS::get_singleton()->print("Unknown --xr-mode argument \"%s\", aborting.\n", xr_mode.ascii().get_data());
  1334. goto error;
  1335. }
  1336. } else {
  1337. OS::get_singleton()->print("Missing --xr-mode argument, aborting.\n");
  1338. goto error;
  1339. }
  1340. } else if (I->get() == "--benchmark") {
  1341. OS::get_singleton()->set_use_benchmark(true);
  1342. } else if (I->get() == "--benchmark-file") {
  1343. if (I->next()) {
  1344. OS::get_singleton()->set_use_benchmark(true);
  1345. String benchmark_file = I->next()->get();
  1346. OS::get_singleton()->set_benchmark_file(benchmark_file);
  1347. N = I->next()->next();
  1348. } else {
  1349. OS::get_singleton()->print("Missing <path> argument for --benchmark-file <path>.\n");
  1350. goto error;
  1351. }
  1352. #if defined(TOOLS_ENABLED) && defined(MODULE_GDSCRIPT_ENABLED) && !defined(GDSCRIPT_NO_LSP)
  1353. } else if (I->get() == "--lsp-port") {
  1354. if (I->next()) {
  1355. int port_override = I->next()->get().to_int();
  1356. if (port_override < 0 || port_override > 65535) {
  1357. OS::get_singleton()->print("<port> argument for --lsp-port <port> must be between 0 and 65535.\n");
  1358. goto error;
  1359. }
  1360. GDScriptLanguageServer::port_override = port_override;
  1361. N = I->next()->next();
  1362. } else {
  1363. OS::get_singleton()->print("Missing <port> argument for --lsp-port <port>.\n");
  1364. goto error;
  1365. }
  1366. #endif // TOOLS_ENABLED && MODULE_GDSCRIPT_ENABLED && !GDSCRIPT_NO_LSP
  1367. } else if (I->get() == "--" || I->get() == "++") {
  1368. adding_user_args = true;
  1369. } else {
  1370. main_args.push_back(I->get());
  1371. }
  1372. I = N;
  1373. }
  1374. #ifdef TOOLS_ENABLED
  1375. if (editor && project_manager) {
  1376. OS::get_singleton()->print(
  1377. "Error: Command line arguments implied opening both editor and project manager, which is not possible. Aborting.\n");
  1378. goto error;
  1379. }
  1380. #endif
  1381. // Network file system needs to be configured before globals, since globals are based on the
  1382. // 'project.godot' file which will only be available through the network if this is enabled
  1383. if (!remotefs.is_empty()) {
  1384. int port;
  1385. if (remotefs.contains(":")) {
  1386. port = remotefs.get_slicec(':', 1).to_int();
  1387. remotefs = remotefs.get_slicec(':', 0);
  1388. } else {
  1389. port = 6010;
  1390. }
  1391. Error err = OS::get_singleton()->setup_remote_filesystem(remotefs, port, remotefs_pass, project_path);
  1392. if (err) {
  1393. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i.\n", remotefs.utf8().get_data(), port);
  1394. goto error;
  1395. }
  1396. }
  1397. if (globals->setup(project_path, main_pack, upwards, editor) == OK) {
  1398. #ifdef TOOLS_ENABLED
  1399. found_project = true;
  1400. #endif
  1401. } else {
  1402. #ifdef TOOLS_ENABLED
  1403. editor = false;
  1404. #else
  1405. 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";
  1406. OS::get_singleton()->print("%s", error_msg.utf8().get_data());
  1407. OS::get_singleton()->alert(error_msg);
  1408. goto error;
  1409. #endif
  1410. }
  1411. // Initialize WorkerThreadPool.
  1412. {
  1413. int worker_threads = GLOBAL_GET("threading/worker_pool/max_threads");
  1414. bool low_priority_use_system_threads = GLOBAL_GET("threading/worker_pool/use_system_threads_for_low_priority_tasks");
  1415. float low_property_ratio = GLOBAL_GET("threading/worker_pool/low_priority_thread_ratio");
  1416. if (editor || project_manager) {
  1417. WorkerThreadPool::get_singleton()->init();
  1418. } else {
  1419. WorkerThreadPool::get_singleton()->init(worker_threads, low_priority_use_system_threads, low_property_ratio);
  1420. }
  1421. }
  1422. #ifdef TOOLS_ENABLED
  1423. if (editor) {
  1424. Engine::get_singleton()->set_editor_hint(true);
  1425. Engine::get_singleton()->set_extension_reloading_enabled(true);
  1426. }
  1427. #endif
  1428. // Initialize user data dir.
  1429. OS::get_singleton()->ensure_user_data_dir();
  1430. initialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  1431. register_core_extensions(); // core extensions must be registered after globals setup and before display
  1432. ResourceUID::get_singleton()->load_from_cache(); // load UUIDs from cache.
  1433. if (ProjectSettings::get_singleton()->has_custom_feature("dedicated_server")) {
  1434. audio_driver = NULL_AUDIO_DRIVER;
  1435. display_driver = NULL_DISPLAY_DRIVER;
  1436. }
  1437. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_chars_per_second", PROPERTY_HINT_RANGE, "0, 4096, 1, or_greater"), 32768);
  1438. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_queued_messages", PROPERTY_HINT_RANGE, "0, 8192, 1, or_greater"), 2048);
  1439. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_errors_per_second", PROPERTY_HINT_RANGE, "0, 200, 1, or_greater"), 400);
  1440. GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_warnings_per_second", PROPERTY_HINT_RANGE, "0, 200, 1, or_greater"), 400);
  1441. EngineDebugger::initialize(debug_uri, skip_breakpoints, breakpoints, []() {
  1442. if (editor_pid) {
  1443. DisplayServer::get_singleton()->enable_for_stealing_focus(editor_pid);
  1444. }
  1445. });
  1446. #ifdef TOOLS_ENABLED
  1447. if (editor) {
  1448. packed_data->set_disabled(true);
  1449. main_args.push_back("--editor");
  1450. if (!init_windowed && !init_fullscreen) {
  1451. init_maximized = true;
  1452. window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
  1453. }
  1454. }
  1455. if (!project_manager && !editor) {
  1456. // If we didn't find a project, we fall back to the project manager.
  1457. project_manager = !found_project && !cmdline_tool;
  1458. }
  1459. if (project_manager) {
  1460. Engine::get_singleton()->set_project_manager_hint(true);
  1461. }
  1462. #endif
  1463. GLOBAL_DEF("debug/file_logging/enable_file_logging", false);
  1464. // Only file logging by default on desktop platforms as logs can't be
  1465. // accessed easily on mobile/Web platforms (if at all).
  1466. // This also prevents logs from being created for the editor instance, as feature tags
  1467. // are disabled while in the editor (even if they should logically apply).
  1468. GLOBAL_DEF("debug/file_logging/enable_file_logging.pc", true);
  1469. GLOBAL_DEF("debug/file_logging/log_path", "user://logs/godot.log");
  1470. GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/file_logging/max_log_files", PROPERTY_HINT_RANGE, "0,20,1,or_greater"), 5);
  1471. if (!project_manager && !editor && FileAccess::get_create_func(FileAccess::ACCESS_USERDATA) &&
  1472. GLOBAL_GET("debug/file_logging/enable_file_logging")) {
  1473. // Don't create logs for the project manager as they would be written to
  1474. // the current working directory, which is inconvenient.
  1475. String base_path = GLOBAL_GET("debug/file_logging/log_path");
  1476. int max_files = GLOBAL_GET("debug/file_logging/max_log_files");
  1477. OS::get_singleton()->add_logger(memnew(RotatedFileLogger(base_path, max_files)));
  1478. }
  1479. if (main_args.size() == 0 && String(GLOBAL_GET("application/run/main_scene")) == "") {
  1480. #ifdef TOOLS_ENABLED
  1481. if (!editor && !project_manager) {
  1482. #endif
  1483. const String error_msg = "Error: Can't run project: no main scene defined in the project.\n";
  1484. OS::get_singleton()->print("%s", error_msg.utf8().get_data());
  1485. OS::get_singleton()->alert(error_msg);
  1486. goto error;
  1487. #ifdef TOOLS_ENABLED
  1488. }
  1489. #endif
  1490. }
  1491. if (editor || project_manager) {
  1492. Engine::get_singleton()->set_editor_hint(true);
  1493. use_custom_res = false;
  1494. input_map->load_default(); //keys for editor
  1495. } else {
  1496. input_map->load_from_project_settings(); //keys for game
  1497. }
  1498. if (bool(GLOBAL_GET("application/run/disable_stdout"))) {
  1499. quiet_stdout = true;
  1500. }
  1501. if (bool(GLOBAL_GET("application/run/disable_stderr"))) {
  1502. CoreGlobals::print_error_enabled = false;
  1503. }
  1504. if (quiet_stdout) {
  1505. CoreGlobals::print_line_enabled = false;
  1506. }
  1507. Logger::set_flush_stdout_on_print(GLOBAL_GET("application/run/flush_stdout_on_print"));
  1508. OS::get_singleton()->set_cmdline(execpath, main_args, user_args);
  1509. {
  1510. String driver_hints = "";
  1511. #ifdef VULKAN_ENABLED
  1512. driver_hints = "vulkan";
  1513. #endif
  1514. String default_driver = driver_hints.get_slice(",", 0);
  1515. // For now everything defaults to vulkan when available. This can change in future updates.
  1516. GLOBAL_DEF_RST_NOVAL("rendering/rendering_device/driver", default_driver);
  1517. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.windows", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1518. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.linuxbsd", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1519. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.android", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1520. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.ios", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1521. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.macos", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1522. }
  1523. {
  1524. String driver_hints = "";
  1525. String driver_hints_angle = "";
  1526. String driver_hints_egl = "";
  1527. #ifdef GLES3_ENABLED
  1528. driver_hints = "opengl3";
  1529. driver_hints_angle = "opengl3,opengl3_angle"; // macOS, Windows.
  1530. driver_hints_egl = "opengl3,opengl3_es"; // Linux.
  1531. #endif
  1532. String default_driver = driver_hints.get_slice(",", 0);
  1533. GLOBAL_DEF_RST_NOVAL("rendering/gl_compatibility/driver", default_driver);
  1534. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.windows", PROPERTY_HINT_ENUM, driver_hints_angle), default_driver);
  1535. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.linuxbsd", PROPERTY_HINT_ENUM, driver_hints_egl), default_driver);
  1536. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.web", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1537. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.android", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1538. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.ios", PROPERTY_HINT_ENUM, driver_hints), default_driver);
  1539. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.macos", PROPERTY_HINT_ENUM, driver_hints_angle), default_driver);
  1540. GLOBAL_DEF_RST("rendering/gl_compatibility/nvidia_disable_threaded_optimization", true);
  1541. GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_angle", true);
  1542. GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_native", true);
  1543. GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_gles", true);
  1544. Array device_blocklist;
  1545. #define BLOCK_DEVICE(m_vendor, m_name) \
  1546. { \
  1547. Dictionary device; \
  1548. device["vendor"] = m_vendor; \
  1549. device["name"] = m_name; \
  1550. device_blocklist.push_back(device); \
  1551. }
  1552. // AMD GPUs.
  1553. BLOCK_DEVICE("ATI", "Radeon 9"); // ATI Radeon 9000 Series
  1554. BLOCK_DEVICE("ATI", "Radeon X"); // ATI Radeon X500-X2000 Series
  1555. BLOCK_DEVICE("ATI", "Radeon HD 2"); // AMD/ATI (Mobility) Radeon HD 2xxx Series
  1556. BLOCK_DEVICE("ATI", "Radeon HD 3"); // AMD/ATI (Mobility) Radeon HD 3xxx Series
  1557. BLOCK_DEVICE("ATI", "Radeon HD 4"); // AMD/ATI (Mobility) Radeon HD 4xxx Series
  1558. BLOCK_DEVICE("ATI", "Radeon HD 5"); // AMD/ATI (Mobility) Radeon HD 5xxx Series
  1559. BLOCK_DEVICE("ATI", "Radeon HD 6"); // AMD/ATI (Mobility) Radeon HD 6xxx Series
  1560. BLOCK_DEVICE("ATI", "Radeon HD 7"); // AMD/ATI (Mobility) Radeon HD 7xxx Series
  1561. BLOCK_DEVICE("ATI", "Radeon HD 8"); // AMD/ATI (Mobility) Radeon HD 8xxx Series
  1562. BLOCK_DEVICE("ATI", "Radeon(TM) R2 Graphics"); // APUs
  1563. BLOCK_DEVICE("ATI", "Radeon(TM) R3 Graphics");
  1564. BLOCK_DEVICE("ATI", "Radeon(TM) R4 Graphics");
  1565. BLOCK_DEVICE("ATI", "Radeon(TM) R5 Graphics");
  1566. BLOCK_DEVICE("ATI", "Radeon(TM) R6 Graphics");
  1567. BLOCK_DEVICE("ATI", "Radeon(TM) R7 Graphics");
  1568. BLOCK_DEVICE("AMD", "Radeon(TM) R7 Graphics");
  1569. BLOCK_DEVICE("AMD", "Radeon(TM) R8 Graphics");
  1570. BLOCK_DEVICE("ATI", "Radeon R5 Graphics");
  1571. BLOCK_DEVICE("ATI", "Radeon R6 Graphics");
  1572. BLOCK_DEVICE("ATI", "Radeon R7 Graphics");
  1573. BLOCK_DEVICE("AMD", "Radeon R7 Graphics");
  1574. BLOCK_DEVICE("AMD", "Radeon R8 Graphics");
  1575. BLOCK_DEVICE("ATI", "Radeon R5 2"); // Rx 2xx Series
  1576. BLOCK_DEVICE("ATI", "Radeon R7 2");
  1577. BLOCK_DEVICE("ATI", "Radeon R9 2");
  1578. BLOCK_DEVICE("ATI", "Radeon R5 M2"); // Rx M2xx Series
  1579. BLOCK_DEVICE("ATI", "Radeon R7 M2");
  1580. BLOCK_DEVICE("ATI", "Radeon R9 M2");
  1581. BLOCK_DEVICE("ATI", "Radeon (TM) R9 Fury");
  1582. BLOCK_DEVICE("ATI", "Radeon (TM) R5 3"); // Rx 3xx Series
  1583. BLOCK_DEVICE("AMD", "Radeon (TM) R5 3");
  1584. BLOCK_DEVICE("ATI", "Radeon (TM) R7 3");
  1585. BLOCK_DEVICE("AMD", "Radeon (TM) R7 3");
  1586. BLOCK_DEVICE("ATI", "Radeon (TM) R9 3");
  1587. BLOCK_DEVICE("AMD", "Radeon (TM) R9 3");
  1588. BLOCK_DEVICE("ATI", "Radeon (TM) R5 M3"); // Rx M3xx Series
  1589. BLOCK_DEVICE("AMD", "Radeon (TM) R5 M3");
  1590. BLOCK_DEVICE("ATI", "Radeon (TM) R7 M3");
  1591. BLOCK_DEVICE("AMD", "Radeon (TM) R7 M3");
  1592. BLOCK_DEVICE("ATI", "Radeon (TM) R9 M3");
  1593. BLOCK_DEVICE("AMD", "Radeon (TM) R9 M3");
  1594. #undef BLOCK_DEVICE
  1595. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::ARRAY, "rendering/gl_compatibility/force_angle_on_devices", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::DICTIONARY, PROPERTY_HINT_NONE, String())), device_blocklist);
  1596. }
  1597. // Start with RenderingDevice-based backends. Should be included if any RD driver present.
  1598. #ifdef VULKAN_ENABLED
  1599. renderer_hints = "forward_plus,mobile";
  1600. default_renderer_mobile = "mobile";
  1601. #endif
  1602. // And Compatibility next, or first if Vulkan is disabled.
  1603. #ifdef GLES3_ENABLED
  1604. if (!renderer_hints.is_empty()) {
  1605. renderer_hints += ",";
  1606. }
  1607. renderer_hints += "gl_compatibility";
  1608. if (default_renderer_mobile.is_empty()) {
  1609. default_renderer_mobile = "gl_compatibility";
  1610. }
  1611. // Default to Compatibility when using the project manager.
  1612. if (rendering_driver.is_empty() && rendering_method.is_empty() && project_manager) {
  1613. rendering_driver = "opengl3";
  1614. rendering_method = "gl_compatibility";
  1615. default_renderer_mobile = "gl_compatibility";
  1616. }
  1617. #endif
  1618. if (renderer_hints.is_empty()) {
  1619. ERR_PRINT("No renderers available.");
  1620. }
  1621. if (!rendering_method.is_empty()) {
  1622. if (rendering_method != "forward_plus" &&
  1623. rendering_method != "mobile" &&
  1624. rendering_method != "gl_compatibility") {
  1625. OS::get_singleton()->print("Unknown renderer name '%s', aborting. Valid options are: %s\n", rendering_method.utf8().get_data(), renderer_hints.utf8().get_data());
  1626. goto error;
  1627. }
  1628. }
  1629. if (!rendering_driver.is_empty()) {
  1630. // As the rendering drivers available may depend on the display driver and renderer
  1631. // selected, we can't do an exhaustive check here, but we can look through all
  1632. // the options in all the display drivers for a match.
  1633. bool found = false;
  1634. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1635. Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
  1636. for (int d = 0; d < r_drivers.size(); d++) {
  1637. if (rendering_driver == r_drivers[d]) {
  1638. found = true;
  1639. break;
  1640. }
  1641. }
  1642. }
  1643. if (!found) {
  1644. OS::get_singleton()->print("Unknown rendering driver '%s', aborting.\nValid options are ",
  1645. rendering_driver.utf8().get_data());
  1646. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1647. Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
  1648. for (int d = 0; d < r_drivers.size(); d++) {
  1649. OS::get_singleton()->print("'%s', ", r_drivers[d].utf8().get_data());
  1650. }
  1651. }
  1652. OS::get_singleton()->print(".\n");
  1653. goto error;
  1654. }
  1655. // Set a default renderer if none selected. Try to choose one that matches the driver.
  1656. if (rendering_method.is_empty()) {
  1657. if (rendering_driver == "opengl3" || rendering_driver == "opengl3_angle" || rendering_driver == "opengl3_es") {
  1658. rendering_method = "gl_compatibility";
  1659. } else {
  1660. rendering_method = "forward_plus";
  1661. }
  1662. }
  1663. // Now validate whether the selected driver matches with the renderer.
  1664. bool valid_combination = false;
  1665. Vector<String> available_drivers;
  1666. #ifdef VULKAN_ENABLED
  1667. if (rendering_method == "forward_plus" || rendering_method == "mobile") {
  1668. available_drivers.push_back("vulkan");
  1669. }
  1670. #endif
  1671. #ifdef GLES3_ENABLED
  1672. if (rendering_method == "gl_compatibility") {
  1673. available_drivers.push_back("opengl3");
  1674. available_drivers.push_back("opengl3_angle");
  1675. available_drivers.push_back("opengl3_es");
  1676. }
  1677. #endif
  1678. if (available_drivers.is_empty()) {
  1679. OS::get_singleton()->print("Unknown renderer name '%s', aborting.\n", rendering_method.utf8().get_data());
  1680. goto error;
  1681. }
  1682. for (int i = 0; i < available_drivers.size(); i++) {
  1683. if (rendering_driver == available_drivers[i]) {
  1684. valid_combination = true;
  1685. break;
  1686. }
  1687. }
  1688. if (!valid_combination) {
  1689. OS::get_singleton()->print("Invalid renderer/driver combination '%s' and '%s', aborting. %s only supports the following drivers ", rendering_method.utf8().get_data(), rendering_driver.utf8().get_data(), rendering_method.utf8().get_data());
  1690. for (int d = 0; d < available_drivers.size(); d++) {
  1691. OS::get_singleton()->print("'%s', ", available_drivers[d].utf8().get_data());
  1692. }
  1693. OS::get_singleton()->print(".\n");
  1694. goto error;
  1695. }
  1696. }
  1697. default_renderer = renderer_hints.get_slice(",", 0);
  1698. GLOBAL_DEF_RST_BASIC(PropertyInfo(Variant::STRING, "rendering/renderer/rendering_method", PROPERTY_HINT_ENUM, renderer_hints), default_renderer);
  1699. GLOBAL_DEF_RST_BASIC("rendering/renderer/rendering_method.mobile", default_renderer_mobile);
  1700. GLOBAL_DEF_RST_BASIC("rendering/renderer/rendering_method.web", "gl_compatibility"); // This is a bit of a hack until we have WebGPU support.
  1701. // Default to ProjectSettings default if nothing set on the command line.
  1702. if (rendering_method.is_empty()) {
  1703. rendering_method = GLOBAL_GET("rendering/renderer/rendering_method");
  1704. }
  1705. if (rendering_driver.is_empty()) {
  1706. if (rendering_method == "gl_compatibility") {
  1707. rendering_driver = GLOBAL_GET("rendering/gl_compatibility/driver");
  1708. } else {
  1709. rendering_driver = GLOBAL_GET("rendering/rendering_device/driver");
  1710. }
  1711. }
  1712. // note this is the desired rendering driver, it doesn't mean we will get it.
  1713. // TODO - make sure this is updated in the case of fallbacks, so that the user interface
  1714. // shows the correct driver string.
  1715. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  1716. OS::get_singleton()->set_current_rendering_method(rendering_method);
  1717. // always convert to lower case for consistency in the code
  1718. rendering_driver = rendering_driver.to_lower();
  1719. if (use_custom_res) {
  1720. if (!force_res) {
  1721. window_size.width = GLOBAL_GET("display/window/size/viewport_width");
  1722. window_size.height = GLOBAL_GET("display/window/size/viewport_height");
  1723. if (globals->has_setting("display/window/size/window_width_override") &&
  1724. globals->has_setting("display/window/size/window_height_override")) {
  1725. int desired_width = globals->get("display/window/size/window_width_override");
  1726. if (desired_width > 0) {
  1727. window_size.width = desired_width;
  1728. }
  1729. int desired_height = globals->get("display/window/size/window_height_override");
  1730. if (desired_height > 0) {
  1731. window_size.height = desired_height;
  1732. }
  1733. }
  1734. }
  1735. if (!bool(GLOBAL_GET("display/window/size/resizable"))) {
  1736. window_flags |= DisplayServer::WINDOW_FLAG_RESIZE_DISABLED_BIT;
  1737. }
  1738. if (bool(GLOBAL_GET("display/window/size/borderless"))) {
  1739. window_flags |= DisplayServer::WINDOW_FLAG_BORDERLESS_BIT;
  1740. }
  1741. if (bool(GLOBAL_GET("display/window/size/always_on_top"))) {
  1742. window_flags |= DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP_BIT;
  1743. }
  1744. if (bool(GLOBAL_GET("display/window/size/transparent"))) {
  1745. window_flags |= DisplayServer::WINDOW_FLAG_TRANSPARENT_BIT;
  1746. }
  1747. if (bool(GLOBAL_GET("display/window/size/extend_to_title"))) {
  1748. window_flags |= DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE_BIT;
  1749. }
  1750. if (bool(GLOBAL_GET("display/window/size/no_focus"))) {
  1751. window_flags |= DisplayServer::WINDOW_FLAG_NO_FOCUS_BIT;
  1752. }
  1753. window_mode = (DisplayServer::WindowMode)(GLOBAL_GET("display/window/size/mode").operator int());
  1754. int initial_position_type = GLOBAL_GET("display/window/size/initial_position_type").operator int();
  1755. if (initial_position_type == 0) { // Absolute.
  1756. if (!init_use_custom_pos) {
  1757. init_custom_pos = GLOBAL_GET("display/window/size/initial_position").operator Vector2i();
  1758. init_use_custom_pos = true;
  1759. }
  1760. } else if (initial_position_type == 1) { // Center of Primary Screen.
  1761. if (!init_use_custom_screen) {
  1762. init_screen = DisplayServer::SCREEN_PRIMARY;
  1763. init_use_custom_screen = true;
  1764. }
  1765. } else if (initial_position_type == 2) { // Center of Other Screen.
  1766. if (!init_use_custom_screen) {
  1767. init_screen = GLOBAL_GET("display/window/size/initial_screen").operator int();
  1768. init_use_custom_screen = true;
  1769. }
  1770. } else if (initial_position_type == 3) { // Center of Screen With Mouse Pointer.
  1771. if (!init_use_custom_screen) {
  1772. init_screen = DisplayServer::SCREEN_WITH_MOUSE_FOCUS;
  1773. init_use_custom_screen = true;
  1774. }
  1775. } else if (initial_position_type == 4) { // Center of Screen With Keyboard Focus.
  1776. if (!init_use_custom_screen) {
  1777. init_screen = DisplayServer::SCREEN_WITH_KEYBOARD_FOCUS;
  1778. init_use_custom_screen = true;
  1779. }
  1780. }
  1781. }
  1782. GLOBAL_DEF("internationalization/locale/include_text_server_data", false);
  1783. OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", true);
  1784. OS::get_singleton()->_allow_layered = GLOBAL_DEF("display/window/per_pixel_transparency/allowed", false);
  1785. #ifdef TOOLS_ENABLED
  1786. if (editor || project_manager) {
  1787. // The editor and project manager always detect and use hiDPI if needed.
  1788. OS::get_singleton()->_allow_hidpi = true;
  1789. // Disable Vulkan overlays in editor, they cause various issues.
  1790. OS::get_singleton()->set_environment("DISABLE_MANGOHUD", "1"); // GH-57403.
  1791. OS::get_singleton()->set_environment("DISABLE_RTSS_LAYER", "1"); // GH-57937.
  1792. OS::get_singleton()->set_environment("DISABLE_VKBASALT", "1");
  1793. OS::get_singleton()->set_environment("DISABLE_VK_LAYER_reshade_1", "1"); // GH-70849.
  1794. } else {
  1795. // Re-allow using Vulkan overlays, disabled while using the editor.
  1796. OS::get_singleton()->unset_environment("DISABLE_MANGOHUD");
  1797. OS::get_singleton()->unset_environment("DISABLE_RTSS_LAYER");
  1798. OS::get_singleton()->unset_environment("DISABLE_VKBASALT");
  1799. OS::get_singleton()->unset_environment("DISABLE_VK_LAYER_reshade_1");
  1800. }
  1801. #endif
  1802. if (rtm == -1) {
  1803. rtm = GLOBAL_DEF("rendering/driver/threads/thread_model", OS::RENDER_THREAD_SAFE);
  1804. }
  1805. if (rtm >= 0 && rtm < 3) {
  1806. if (editor || project_manager) {
  1807. // Editor and project manager cannot run with rendering in a separate thread (they will crash on startup).
  1808. rtm = OS::RENDER_THREAD_SAFE;
  1809. }
  1810. OS::get_singleton()->_render_thread_mode = OS::RenderThreadMode(rtm);
  1811. }
  1812. /* Determine audio and video drivers */
  1813. // Display driver, e.g. X11, Wayland.
  1814. // Make sure that headless is the last one, which it is assumed to be by design.
  1815. DEV_ASSERT(NULL_DISPLAY_DRIVER == DisplayServer::get_create_function_name(DisplayServer::get_create_function_count() - 1));
  1816. for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
  1817. String name = DisplayServer::get_create_function_name(i);
  1818. if (display_driver == name) {
  1819. display_driver_idx = i;
  1820. break;
  1821. }
  1822. }
  1823. if (display_driver_idx < 0) {
  1824. // If the requested driver wasn't found, pick the first entry.
  1825. // If all else failed it would be the headless server.
  1826. display_driver_idx = 0;
  1827. }
  1828. // Store this in a globally accessible place, so we can retrieve the rendering drivers
  1829. // list from the display driver for the editor UI.
  1830. OS::get_singleton()->set_display_driver_id(display_driver_idx);
  1831. GLOBAL_DEF_RST_NOVAL("audio/driver/driver", AudioDriverManager::get_driver(0)->get_name());
  1832. if (audio_driver.is_empty()) { // Specified in project.godot.
  1833. audio_driver = GLOBAL_GET("audio/driver/driver");
  1834. }
  1835. // Make sure that dummy is the last one, which it is assumed to be by design.
  1836. DEV_ASSERT(NULL_AUDIO_DRIVER == AudioDriverManager::get_driver(AudioDriverManager::get_driver_count() - 1)->get_name());
  1837. for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
  1838. if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
  1839. audio_driver_idx = i;
  1840. break;
  1841. }
  1842. }
  1843. if (audio_driver_idx < 0) {
  1844. // If the requested driver wasn't found, pick the first entry.
  1845. // If all else failed it would be the dummy driver (no sound).
  1846. audio_driver_idx = 0;
  1847. }
  1848. if (Engine::get_singleton()->get_write_movie_path() != String()) {
  1849. // Always use dummy driver for audio driver (which is last), also in no threaded mode.
  1850. audio_driver_idx = AudioDriverManager::get_driver_count() - 1;
  1851. AudioDriverDummy::get_dummy_singleton()->set_use_threads(false);
  1852. }
  1853. {
  1854. window_orientation = DisplayServer::ScreenOrientation(int(GLOBAL_DEF_BASIC("display/window/handheld/orientation", DisplayServer::ScreenOrientation::SCREEN_LANDSCAPE)));
  1855. }
  1856. {
  1857. window_vsync_mode = DisplayServer::VSyncMode(int(GLOBAL_DEF_BASIC("display/window/vsync/vsync_mode", DisplayServer::VSyncMode::VSYNC_ENABLED)));
  1858. if (disable_vsync) {
  1859. window_vsync_mode = DisplayServer::VSyncMode::VSYNC_DISABLED;
  1860. }
  1861. }
  1862. Engine::get_singleton()->set_physics_ticks_per_second(GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "physics/common/physics_ticks_per_second", PROPERTY_HINT_RANGE, "1,1000,1"), 60));
  1863. Engine::get_singleton()->set_max_physics_steps_per_frame(GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "physics/common/max_physics_steps_per_frame", PROPERTY_HINT_RANGE, "1,100,1"), 8));
  1864. Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF("physics/common/physics_jitter_fix", 0.5));
  1865. Engine::get_singleton()->set_max_fps(GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/max_fps", PROPERTY_HINT_RANGE, "0,1000,1"), 0));
  1866. Engine::get_singleton()->set_audio_output_latency(GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "audio/driver/output_latency", PROPERTY_HINT_RANGE, "1,100,1"), 15));
  1867. // Use a safer default output_latency for web to avoid audio cracking on low-end devices, especially mobile.
  1868. GLOBAL_DEF_RST("audio/driver/output_latency.web", 50);
  1869. GLOBAL_DEF("debug/settings/stdout/print_fps", false);
  1870. GLOBAL_DEF("debug/settings/stdout/print_gpu_profile", false);
  1871. GLOBAL_DEF("debug/settings/stdout/verbose_stdout", false);
  1872. if (!OS::get_singleton()->_verbose_stdout) { // Not manually overridden.
  1873. OS::get_singleton()->_verbose_stdout = GLOBAL_GET("debug/settings/stdout/verbose_stdout");
  1874. }
  1875. #if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
  1876. OS::get_singleton()->set_environment("MVK_CONFIG_LOG_LEVEL", OS::get_singleton()->_verbose_stdout ? "3" : "1"); // 1 = Errors only, 3 = Info
  1877. #endif
  1878. if (max_fps >= 0) {
  1879. Engine::get_singleton()->set_max_fps(max_fps);
  1880. }
  1881. if (frame_delay == 0) {
  1882. frame_delay = GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/frame_delay_msec", PROPERTY_HINT_RANGE, "0,100,1,or_greater"), 0);
  1883. if (Engine::get_singleton()->is_editor_hint()) {
  1884. frame_delay = 0;
  1885. }
  1886. }
  1887. if (audio_output_latency >= 1) {
  1888. Engine::get_singleton()->set_audio_output_latency(audio_output_latency);
  1889. }
  1890. OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false));
  1891. OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(
  1892. GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "0,33200,1,or_greater"), 6900)); // Roughly 144 FPS
  1893. GLOBAL_DEF("application/run/delta_smoothing", true);
  1894. if (!delta_smoothing_override) {
  1895. OS::get_singleton()->set_delta_smoothing(GLOBAL_GET("application/run/delta_smoothing"));
  1896. }
  1897. GLOBAL_DEF("display/window/ios/allow_high_refresh_rate", true);
  1898. GLOBAL_DEF("display/window/ios/hide_home_indicator", true);
  1899. GLOBAL_DEF("display/window/ios/hide_status_bar", true);
  1900. GLOBAL_DEF("display/window/ios/suppress_ui_gesture", true);
  1901. // XR project settings.
  1902. GLOBAL_DEF_RST_BASIC("xr/openxr/enabled", false);
  1903. GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "xr/openxr/default_action_map", PROPERTY_HINT_FILE, "*.tres"), "res://openxr_action_map.tres");
  1904. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/form_factor", PROPERTY_HINT_ENUM, "Head Mounted,Handheld"), "0");
  1905. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/view_configuration", PROPERTY_HINT_ENUM, "Mono,Stereo"), "1"); // "Mono,Stereo,Quad,Observer"
  1906. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/reference_space", PROPERTY_HINT_ENUM, "Local,Stage"), "1");
  1907. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/environment_blend_mode", PROPERTY_HINT_ENUM, "Opaque,Additive,Alpha"), "0");
  1908. GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/foveation_level", PROPERTY_HINT_ENUM, "Off,Low,Medium,High"), "0");
  1909. GLOBAL_DEF_BASIC("xr/openxr/foveation_dynamic", false);
  1910. GLOBAL_DEF_BASIC("xr/openxr/submit_depth_buffer", false);
  1911. GLOBAL_DEF_BASIC("xr/openxr/startup_alert", true);
  1912. // OpenXR project extensions settings.
  1913. GLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking", true);
  1914. GLOBAL_DEF_BASIC("xr/openxr/extensions/eye_gaze_interaction", false);
  1915. #ifdef TOOLS_ENABLED
  1916. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  1917. // editor settings (it seems we're too early in the process when setting up rendering, to access editor settings...)
  1918. // EDITOR_DEF_RST("xr/openxr/in_editor", false);
  1919. // GLOBAL_DEF("xr/openxr/in_editor", false);
  1920. #endif
  1921. Engine::get_singleton()->set_frame_delay(frame_delay);
  1922. message_queue = memnew(MessageQueue);
  1923. Thread::release_main_thread(); // If setup2() is called from another thread, that one will become main thread, so preventively release this one.
  1924. set_current_thread_safe_for_nodes(false);
  1925. if (p_second_phase) {
  1926. return setup2();
  1927. }
  1928. OS::get_singleton()->benchmark_end_measure("core");
  1929. return OK;
  1930. error:
  1931. text_driver = "";
  1932. display_driver = "";
  1933. audio_driver = "";
  1934. tablet_driver = "";
  1935. Engine::get_singleton()->set_write_movie_path(String());
  1936. project_path = "";
  1937. args.clear();
  1938. main_args.clear();
  1939. if (show_help) {
  1940. print_help(execpath);
  1941. }
  1942. EngineDebugger::deinitialize();
  1943. if (performance) {
  1944. memdelete(performance);
  1945. }
  1946. if (input_map) {
  1947. memdelete(input_map);
  1948. }
  1949. if (time_singleton) {
  1950. memdelete(time_singleton);
  1951. }
  1952. if (translation_server) {
  1953. memdelete(translation_server);
  1954. }
  1955. if (globals) {
  1956. memdelete(globals);
  1957. }
  1958. if (engine) {
  1959. memdelete(engine);
  1960. }
  1961. if (packed_data) {
  1962. memdelete(packed_data);
  1963. }
  1964. unregister_core_driver_types();
  1965. unregister_core_extensions();
  1966. unregister_core_types();
  1967. OS::get_singleton()->_cmdline.clear();
  1968. OS::get_singleton()->_user_args.clear();
  1969. if (message_queue) {
  1970. memdelete(message_queue);
  1971. }
  1972. OS::get_singleton()->benchmark_end_measure("core");
  1973. OS::get_singleton()->finalize_core();
  1974. locale = String();
  1975. return exit_code;
  1976. }
  1977. Error _parse_resource_dummy(void *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
  1978. VariantParser::Token token;
  1979. VariantParser::get_token(p_stream, token, line, r_err_str);
  1980. if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
  1981. r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
  1982. return ERR_PARSE_ERROR;
  1983. }
  1984. r_res.unref();
  1985. VariantParser::get_token(p_stream, token, line, r_err_str);
  1986. if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
  1987. r_err_str = "Expected ')'";
  1988. return ERR_PARSE_ERROR;
  1989. }
  1990. return OK;
  1991. }
  1992. Error Main::setup2() {
  1993. Thread::make_main_thread(); // Make whatever thread call this the main thread.
  1994. set_current_thread_safe_for_nodes(true);
  1995. // Print engine name and version
  1996. print_line(String(VERSION_NAME) + " v" + get_full_version_string() + " - " + String(VERSION_WEBSITE));
  1997. OS::get_singleton()->benchmark_begin_measure("servers");
  1998. tsman = memnew(TextServerManager);
  1999. if (tsman) {
  2000. Ref<TextServerDummy> ts;
  2001. ts.instantiate();
  2002. tsman->add_interface(ts);
  2003. }
  2004. physics_server_3d_manager = memnew(PhysicsServer3DManager);
  2005. physics_server_2d_manager = memnew(PhysicsServer2DManager);
  2006. register_server_types();
  2007. initialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  2008. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  2009. #ifdef TOOLS_ENABLED
  2010. if (editor || project_manager || cmdline_tool) {
  2011. EditorPaths::create();
  2012. // Editor setting class is not available, load config directly.
  2013. if (!init_use_custom_screen && (editor || project_manager) && EditorPaths::get_singleton()->are_paths_valid()) {
  2014. Ref<DirAccess> dir = DirAccess::open(EditorPaths::get_singleton()->get_config_dir());
  2015. ERR_FAIL_COND_V(dir.is_null(), FAILED);
  2016. String config_file_name = "editor_settings-" + itos(VERSION_MAJOR) + ".tres";
  2017. String config_file_path = EditorPaths::get_singleton()->get_config_dir().path_join(config_file_name);
  2018. if (dir->file_exists(config_file_name)) {
  2019. Error err;
  2020. Ref<FileAccess> f = FileAccess::open(config_file_path, FileAccess::READ, &err);
  2021. if (f.is_valid()) {
  2022. VariantParser::StreamFile stream;
  2023. stream.f = f;
  2024. String assign;
  2025. Variant value;
  2026. VariantParser::Tag next_tag;
  2027. int lines = 0;
  2028. String error_text;
  2029. VariantParser::ResourceParser rp_new;
  2030. rp_new.ext_func = _parse_resource_dummy;
  2031. rp_new.sub_func = _parse_resource_dummy;
  2032. while (true) {
  2033. assign = Variant();
  2034. next_tag.fields.clear();
  2035. next_tag.name = String();
  2036. err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new, true);
  2037. if (err == ERR_FILE_EOF) {
  2038. break;
  2039. }
  2040. if (err == OK && !assign.is_empty()) {
  2041. if (project_manager) {
  2042. if (assign == "interface/editor/project_manager_screen") {
  2043. init_screen = value;
  2044. break;
  2045. }
  2046. } else if (editor) {
  2047. if (assign == "interface/editor/editor_screen") {
  2048. init_screen = value;
  2049. break;
  2050. }
  2051. }
  2052. }
  2053. }
  2054. }
  2055. }
  2056. }
  2057. if (found_project && EditorPaths::get_singleton()->is_self_contained()) {
  2058. if (ProjectSettings::get_singleton()->get_resource_path() == OS::get_singleton()->get_executable_path().get_base_dir()) {
  2059. ERR_PRINT("You are trying to run a self-contained editor at the same location as a project. This is not allowed, since editor files will mix with project files.");
  2060. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  2061. return FAILED;
  2062. }
  2063. }
  2064. }
  2065. #endif
  2066. /* Initialize Input */
  2067. input = memnew(Input);
  2068. /* Initialize Display Server */
  2069. {
  2070. String display_driver = DisplayServer::get_create_function_name(display_driver_idx);
  2071. Vector2i *window_position = nullptr;
  2072. Vector2i position = init_custom_pos;
  2073. if (init_use_custom_pos) {
  2074. window_position = &position;
  2075. }
  2076. Color boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", boot_splash_bg_color);
  2077. DisplayServer::set_early_window_clear_color_override(true, boot_bg_color);
  2078. // rendering_driver now held in static global String in main and initialized in setup()
  2079. Error err;
  2080. display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, err);
  2081. if (err != OK || display_server == nullptr) {
  2082. // We can't use this display server, try other ones as fallback.
  2083. // Skip headless (always last registered) because that's not what users
  2084. // would expect if they didn't request it explicitly.
  2085. for (int i = 0; i < DisplayServer::get_create_function_count() - 1; i++) {
  2086. if (i == display_driver_idx) {
  2087. continue; // Don't try the same twice.
  2088. }
  2089. display_server = DisplayServer::create(i, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, err);
  2090. if (err == OK && display_server != nullptr) {
  2091. break;
  2092. }
  2093. }
  2094. }
  2095. if (err != OK || display_server == nullptr) {
  2096. ERR_PRINT("Unable to create DisplayServer, all display drivers failed.");
  2097. return err;
  2098. }
  2099. }
  2100. if (display_server->has_feature(DisplayServer::FEATURE_ORIENTATION)) {
  2101. display_server->screen_set_orientation(window_orientation);
  2102. }
  2103. if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
  2104. // Print requested V-Sync mode at startup to diagnose the printed FPS not going above the monitor refresh rate.
  2105. switch (window_vsync_mode) {
  2106. case DisplayServer::VSyncMode::VSYNC_DISABLED:
  2107. print_line("Requested V-Sync mode: Disabled");
  2108. break;
  2109. case DisplayServer::VSyncMode::VSYNC_ENABLED:
  2110. print_line("Requested V-Sync mode: Enabled - FPS will likely be capped to the monitor refresh rate.");
  2111. break;
  2112. case DisplayServer::VSyncMode::VSYNC_ADAPTIVE:
  2113. print_line("Requested V-Sync mode: Adaptive");
  2114. break;
  2115. case DisplayServer::VSyncMode::VSYNC_MAILBOX:
  2116. print_line("Requested V-Sync mode: Mailbox");
  2117. break;
  2118. }
  2119. }
  2120. if (OS::get_singleton()->_render_thread_mode == OS::RENDER_SEPARATE_THREAD) {
  2121. WARN_PRINT("The Multi-Threaded rendering thread model is experimental, and has known issues which can lead to project crashes. Use the Single-Safe option in the project settings instead.");
  2122. }
  2123. /* Initialize Pen Tablet Driver */
  2124. {
  2125. GLOBAL_DEF_RST_NOVAL("input_devices/pen_tablet/driver", "");
  2126. GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "input_devices/pen_tablet/driver.windows", PROPERTY_HINT_ENUM, "wintab,winink"), "");
  2127. }
  2128. if (tablet_driver.is_empty()) { // specified in project.godot
  2129. tablet_driver = GLOBAL_GET("input_devices/pen_tablet/driver");
  2130. if (tablet_driver.is_empty()) {
  2131. tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(0);
  2132. }
  2133. }
  2134. for (int i = 0; i < DisplayServer::get_singleton()->tablet_get_driver_count(); i++) {
  2135. if (tablet_driver == DisplayServer::get_singleton()->tablet_get_driver_name(i)) {
  2136. DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(i));
  2137. break;
  2138. }
  2139. }
  2140. if (DisplayServer::get_singleton()->tablet_get_current_driver().is_empty()) {
  2141. DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(0));
  2142. }
  2143. print_verbose("Using \"" + tablet_driver + "\" pen tablet driver...");
  2144. /* Initialize Rendering Server */
  2145. rendering_server = memnew(RenderingServerDefault(OS::get_singleton()->get_render_thread_mode() == OS::RENDER_SEPARATE_THREAD));
  2146. rendering_server->init();
  2147. //rendering_server->call_set_use_vsync(OS::get_singleton()->_use_vsync);
  2148. rendering_server->set_render_loop_enabled(!disable_render_loop);
  2149. if (profile_gpu || (!editor && bool(GLOBAL_GET("debug/settings/stdout/print_gpu_profile")))) {
  2150. rendering_server->set_print_gpu_profile(true);
  2151. }
  2152. if (Engine::get_singleton()->get_write_movie_path() != String()) {
  2153. movie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());
  2154. if (movie_writer == nullptr) {
  2155. ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
  2156. Engine::get_singleton()->set_write_movie_path(String());
  2157. }
  2158. }
  2159. #ifdef UNIX_ENABLED
  2160. // Print warning after initializing the renderer but before initializing audio.
  2161. if (OS::get_singleton()->get_environment("USER") == "root" && !OS::get_singleton()->has_environment("GODOT_SILENCE_ROOT_WARNING")) {
  2162. 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.");
  2163. }
  2164. #endif
  2165. OS::get_singleton()->initialize_joypads();
  2166. /* Initialize Audio Driver */
  2167. AudioDriverManager::initialize(audio_driver_idx);
  2168. print_line(" "); //add a blank line for readability
  2169. // right moment to create and initialize the audio server
  2170. audio_server = memnew(AudioServer);
  2171. audio_server->init();
  2172. // also init our xr_server from here
  2173. xr_server = memnew(XRServer);
  2174. register_core_singletons();
  2175. MAIN_PRINT("Main: Setup Logo");
  2176. #if !defined(TOOLS_ENABLED) && (defined(WEB_ENABLED) || defined(ANDROID_ENABLED))
  2177. bool show_logo = false;
  2178. #else
  2179. bool show_logo = true;
  2180. #endif
  2181. if (init_windowed) {
  2182. //do none..
  2183. } else if (init_maximized) {
  2184. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_MAXIMIZED);
  2185. } else if (init_fullscreen) {
  2186. DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_FULLSCREEN);
  2187. }
  2188. if (init_always_on_top) {
  2189. DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP, true);
  2190. }
  2191. MAIN_PRINT("Main: Load Boot Image");
  2192. Color clear = GLOBAL_DEF_BASIC("rendering/environment/defaults/default_clear_color", Color(0.3, 0.3, 0.3));
  2193. RenderingServer::get_singleton()->set_default_clear_color(clear);
  2194. if (show_logo) { //boot logo!
  2195. const bool boot_logo_image = GLOBAL_DEF_BASIC("application/boot_splash/show_image", true);
  2196. const String boot_logo_path = String(GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "application/boot_splash/image", PROPERTY_HINT_FILE, "*.png"), String())).strip_edges();
  2197. const bool boot_logo_scale = GLOBAL_DEF_BASIC("application/boot_splash/fullsize", true);
  2198. const bool boot_logo_filter = GLOBAL_DEF_BASIC("application/boot_splash/use_filter", true);
  2199. Ref<Image> boot_logo;
  2200. if (boot_logo_image) {
  2201. if (!boot_logo_path.is_empty()) {
  2202. boot_logo.instantiate();
  2203. Error load_err = ImageLoader::load_image(boot_logo_path, boot_logo);
  2204. if (load_err) {
  2205. ERR_PRINT("Non-existing or invalid boot splash at '" + boot_logo_path + "'. Loading default splash.");
  2206. }
  2207. }
  2208. } else {
  2209. // Create a 1×1 transparent image. This will effectively hide the splash image.
  2210. boot_logo.instantiate();
  2211. boot_logo->initialize_data(1, 1, false, Image::FORMAT_RGBA8);
  2212. boot_logo->set_pixel(0, 0, Color(0, 0, 0, 0));
  2213. }
  2214. Color boot_bg_color = GLOBAL_GET("application/boot_splash/bg_color");
  2215. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  2216. boot_bg_color =
  2217. GLOBAL_DEF_BASIC("application/boot_splash/bg_color",
  2218. (editor || project_manager) ? boot_splash_editor_bg_color : boot_splash_bg_color);
  2219. #endif
  2220. if (boot_logo.is_valid()) {
  2221. RenderingServer::get_singleton()->set_boot_image(boot_logo, boot_bg_color, boot_logo_scale,
  2222. boot_logo_filter);
  2223. } else {
  2224. #ifndef NO_DEFAULT_BOOT_LOGO
  2225. MAIN_PRINT("Main: Create bootsplash");
  2226. #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
  2227. Ref<Image> splash = (editor || project_manager) ? memnew(Image(boot_splash_editor_png)) : memnew(Image(boot_splash_png));
  2228. #else
  2229. Ref<Image> splash = memnew(Image(boot_splash_png));
  2230. #endif
  2231. MAIN_PRINT("Main: ClearColor");
  2232. RenderingServer::get_singleton()->set_default_clear_color(boot_bg_color);
  2233. MAIN_PRINT("Main: Image");
  2234. RenderingServer::get_singleton()->set_boot_image(splash, boot_bg_color, false);
  2235. #endif
  2236. }
  2237. #if defined(TOOLS_ENABLED) && defined(MACOS_ENABLED)
  2238. if (OS::get_singleton()->get_bundle_icon_path().is_empty()) {
  2239. Ref<Image> icon = memnew(Image(app_icon_png));
  2240. DisplayServer::get_singleton()->set_icon(icon);
  2241. }
  2242. #endif
  2243. }
  2244. DisplayServer::set_early_window_clear_color_override(false);
  2245. MAIN_PRINT("Main: DCC");
  2246. RenderingServer::get_singleton()->set_default_clear_color(
  2247. GLOBAL_GET("rendering/environment/defaults/default_clear_color"));
  2248. GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "application/config/icon", PROPERTY_HINT_FILE, "*.png,*.webp,*.svg"), String());
  2249. GLOBAL_DEF(PropertyInfo(Variant::STRING, "application/config/macos_native_icon", PROPERTY_HINT_FILE, "*.icns"), String());
  2250. GLOBAL_DEF(PropertyInfo(Variant::STRING, "application/config/windows_native_icon", PROPERTY_HINT_FILE, "*.ico"), String());
  2251. Input *id = Input::get_singleton();
  2252. if (id) {
  2253. agile_input_event_flushing = GLOBAL_DEF("input_devices/buffering/agile_event_flushing", false);
  2254. if (bool(GLOBAL_DEF_BASIC("input_devices/pointing/emulate_touch_from_mouse", false)) &&
  2255. !(editor || project_manager)) {
  2256. if (!DisplayServer::get_singleton()->is_touchscreen_available()) {
  2257. //only if no touchscreen ui hint, set emulation
  2258. id->set_emulate_touch_from_mouse(true);
  2259. }
  2260. }
  2261. id->set_emulate_mouse_from_touch(bool(GLOBAL_DEF_BASIC("input_devices/pointing/emulate_mouse_from_touch", true)));
  2262. }
  2263. GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_long_press_as_right_click", false);
  2264. GLOBAL_DEF_BASIC("input_devices/pointing/android/enable_pan_and_scale_gestures", false);
  2265. MAIN_PRINT("Main: Load Translations and Remaps");
  2266. translation_server->setup(); //register translations, load them, etc.
  2267. if (!locale.is_empty()) {
  2268. translation_server->set_locale(locale);
  2269. }
  2270. translation_server->load_translations();
  2271. ResourceLoader::load_translation_remaps(); //load remaps for resources
  2272. ResourceLoader::load_path_remaps();
  2273. MAIN_PRINT("Main: Load TextServer");
  2274. /* Enum text drivers */
  2275. GLOBAL_DEF_RST("internationalization/rendering/text_driver", "");
  2276. String text_driver_options;
  2277. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  2278. const String driver_name = TextServerManager::get_singleton()->get_interface(i)->get_name();
  2279. if (driver_name == "Dummy") {
  2280. // Dummy text driver cannot draw any text, making the editor unusable if selected.
  2281. continue;
  2282. }
  2283. if (!text_driver_options.is_empty() && text_driver_options.find(",") == -1) {
  2284. // Not the first option; add a comma before it as a separator for the property hint.
  2285. text_driver_options += ",";
  2286. }
  2287. text_driver_options += driver_name;
  2288. }
  2289. ProjectSettings::get_singleton()->set_custom_property_info(PropertyInfo(Variant::STRING, "internationalization/rendering/text_driver", PROPERTY_HINT_ENUM, text_driver_options));
  2290. /* Determine text driver */
  2291. if (text_driver.is_empty()) {
  2292. text_driver = GLOBAL_GET("internationalization/rendering/text_driver");
  2293. }
  2294. if (!text_driver.is_empty()) {
  2295. /* Load user selected text server. */
  2296. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  2297. if (TextServerManager::get_singleton()->get_interface(i)->get_name() == text_driver) {
  2298. text_driver_idx = i;
  2299. break;
  2300. }
  2301. }
  2302. }
  2303. if (text_driver_idx < 0) {
  2304. /* If not selected, use one with the most features available. */
  2305. int max_features = 0;
  2306. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  2307. uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
  2308. int feature_number = 0;
  2309. while (features) {
  2310. feature_number += features & 1;
  2311. features >>= 1;
  2312. }
  2313. if (feature_number >= max_features) {
  2314. max_features = feature_number;
  2315. text_driver_idx = i;
  2316. }
  2317. }
  2318. }
  2319. if (text_driver_idx >= 0) {
  2320. Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(text_driver_idx);
  2321. TextServerManager::get_singleton()->set_primary_interface(ts);
  2322. if (ts->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
  2323. ts->load_support_data("res://" + ts->get_support_data_filename());
  2324. }
  2325. } else {
  2326. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
  2327. }
  2328. OS::get_singleton()->benchmark_end_measure("servers");
  2329. MAIN_PRINT("Main: Load Scene Types");
  2330. OS::get_singleton()->benchmark_begin_measure("scene");
  2331. // Initialize ThemeDB early so that scene types can register their theme items.
  2332. // Default theme will be initialized later, after modules and ScriptServer are ready.
  2333. initialize_theme_db();
  2334. register_scene_types();
  2335. register_driver_types();
  2336. register_scene_singletons();
  2337. initialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  2338. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  2339. #ifdef TOOLS_ENABLED
  2340. ClassDB::set_current_api(ClassDB::API_EDITOR);
  2341. register_editor_types();
  2342. initialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  2343. GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  2344. ClassDB::set_current_api(ClassDB::API_CORE);
  2345. #endif
  2346. MAIN_PRINT("Main: Load Modules");
  2347. register_platform_apis();
  2348. GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "display/mouse_cursor/custom_image", PROPERTY_HINT_FILE, "*.png,*.webp"), String());
  2349. GLOBAL_DEF_BASIC("display/mouse_cursor/custom_image_hotspot", Vector2());
  2350. GLOBAL_DEF_BASIC("display/mouse_cursor/tooltip_position_offset", Point2(10, 10));
  2351. if (String(GLOBAL_GET("display/mouse_cursor/custom_image")) != String()) {
  2352. Ref<Texture2D> cursor = ResourceLoader::load(
  2353. GLOBAL_GET("display/mouse_cursor/custom_image"));
  2354. if (cursor.is_valid()) {
  2355. Vector2 hotspot = GLOBAL_GET("display/mouse_cursor/custom_image_hotspot");
  2356. Input::get_singleton()->set_custom_mouse_cursor(cursor, Input::CURSOR_ARROW, hotspot);
  2357. }
  2358. }
  2359. camera_server = CameraServer::create();
  2360. MAIN_PRINT("Main: Load Physics");
  2361. initialize_physics();
  2362. initialize_navigation_server();
  2363. register_server_singletons();
  2364. // This loads global classes, so it must happen before custom loaders and savers are registered
  2365. ScriptServer::init_languages();
  2366. theme_db->initialize_theme();
  2367. audio_server->load_default_bus_layout();
  2368. #if defined(MODULE_MONO_ENABLED) && defined(TOOLS_ENABLED)
  2369. // Hacky to have it here, but we don't have good facility yet to let modules
  2370. // register command line options to call at the right time. This needs to happen
  2371. // after init'ing the ScriptServer, but also after init'ing the ThemeDB,
  2372. // for the C# docs generation in the bindings.
  2373. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  2374. BindingsGenerator::handle_cmdline_args(cmdline_args);
  2375. #endif
  2376. if (use_debug_profiler && EngineDebugger::is_active()) {
  2377. // Start the "scripts" profiler, used in local debugging.
  2378. // We could add more, and make the CLI arg require a comma-separated list of profilers.
  2379. EngineDebugger::get_singleton()->profiler_enable("scripts", true);
  2380. }
  2381. if (!project_manager) {
  2382. // If not running the project manager, and now that the engine is
  2383. // able to load resources, load the global shader variables.
  2384. // If running on editor, don't load the textures because the editor
  2385. // may want to import them first. Editor will reload those later.
  2386. rendering_server->global_shader_parameters_load_settings(!editor);
  2387. }
  2388. _start_success = true;
  2389. ClassDB::set_current_api(ClassDB::API_NONE); //no more APIs are registered at this point
  2390. print_verbose("CORE API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_CORE)));
  2391. print_verbose("EDITOR API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
  2392. MAIN_PRINT("Main: Done");
  2393. OS::get_singleton()->benchmark_end_measure("scene");
  2394. return OK;
  2395. }
  2396. String Main::get_rendering_driver_name() {
  2397. return rendering_driver;
  2398. }
  2399. // everything the main loop needs to know about frame timings
  2400. static MainTimerSync main_timer_sync;
  2401. bool Main::start() {
  2402. ERR_FAIL_COND_V(!_start_success, false);
  2403. bool has_icon = false;
  2404. String positional_arg;
  2405. String game_path;
  2406. String script;
  2407. String main_loop_type;
  2408. bool check_only = false;
  2409. #ifdef TOOLS_ENABLED
  2410. String doc_tool_path;
  2411. BitField<DocTools::GenerateFlags> gen_flags;
  2412. String _export_preset;
  2413. bool export_debug = false;
  2414. bool export_pack_only = false;
  2415. #ifdef MODULE_GDSCRIPT_ENABLED
  2416. String gdscript_docs_path;
  2417. #endif
  2418. #ifndef DISABLE_DEPRECATED
  2419. bool converting_project = false;
  2420. bool validating_converting_project = false;
  2421. #endif // DISABLE_DEPRECATED
  2422. #endif // TOOLS_ENABLED
  2423. main_timer_sync.init(OS::get_singleton()->get_ticks_usec());
  2424. List<String> args = OS::get_singleton()->get_cmdline_args();
  2425. for (int i = 0; i < args.size(); i++) {
  2426. // First check parameters that do not have an argument to the right.
  2427. // Doctest Unit Testing Handler
  2428. // Designed to override and pass arguments to the unit test handler.
  2429. if (args[i] == "--check-only") {
  2430. check_only = true;
  2431. #ifdef TOOLS_ENABLED
  2432. } else if (args[i] == "--no-docbase") {
  2433. gen_flags.set_flag(DocTools::GENERATE_FLAG_SKIP_BASIC_TYPES);
  2434. #ifndef DISABLE_DEPRECATED
  2435. } else if (args[i] == "--convert-3to4") {
  2436. converting_project = true;
  2437. } else if (args[i] == "--validate-conversion-3to4") {
  2438. validating_converting_project = true;
  2439. #endif // DISABLE_DEPRECATED
  2440. } else if (args[i] == "-e" || args[i] == "--editor") {
  2441. editor = true;
  2442. } else if (args[i] == "-p" || args[i] == "--project-manager") {
  2443. project_manager = true;
  2444. #endif // TOOLS_ENABLED
  2445. } else if (args[i].length() && args[i][0] != '-' && positional_arg.is_empty()) {
  2446. positional_arg = args[i];
  2447. if (args[i].ends_with(".scn") ||
  2448. args[i].ends_with(".tscn") ||
  2449. args[i].ends_with(".escn") ||
  2450. args[i].ends_with(".res") ||
  2451. args[i].ends_with(".tres")) {
  2452. // Only consider the positional argument to be a scene path if it ends with
  2453. // a file extension associated with Godot scenes. This makes it possible
  2454. // for projects to parse command-line arguments for custom CLI arguments
  2455. // or other file extensions without trouble. This can be used to implement
  2456. // "drag-and-drop onto executable" logic, which can prove helpful
  2457. // for non-game applications.
  2458. game_path = args[i];
  2459. }
  2460. }
  2461. // Then parameters that have an argument to the right.
  2462. else if (i < (args.size() - 1)) {
  2463. bool parsed_pair = true;
  2464. if (args[i] == "-s" || args[i] == "--script") {
  2465. script = args[i + 1];
  2466. } else if (args[i] == "--main-loop") {
  2467. main_loop_type = args[i + 1];
  2468. #ifdef TOOLS_ENABLED
  2469. } else if (args[i] == "--doctool") {
  2470. doc_tool_path = args[i + 1];
  2471. if (doc_tool_path.begins_with("-")) {
  2472. // Assuming other command line arg, so default to cwd.
  2473. doc_tool_path = ".";
  2474. parsed_pair = false;
  2475. }
  2476. #ifdef MODULE_GDSCRIPT_ENABLED
  2477. } else if (args[i] == "--gdscript-docs") {
  2478. gdscript_docs_path = args[i + 1];
  2479. #endif
  2480. } else if (args[i] == "--export-release") {
  2481. editor = true; //needs editor
  2482. _export_preset = args[i + 1];
  2483. } else if (args[i] == "--export-debug") {
  2484. editor = true; //needs editor
  2485. _export_preset = args[i + 1];
  2486. export_debug = true;
  2487. } else if (args[i] == "--export-pack") {
  2488. editor = true;
  2489. _export_preset = args[i + 1];
  2490. export_pack_only = true;
  2491. #endif
  2492. } else {
  2493. // The parameter does not match anything known, don't skip the next argument
  2494. parsed_pair = false;
  2495. }
  2496. if (parsed_pair) {
  2497. i++;
  2498. }
  2499. }
  2500. #ifdef TOOLS_ENABLED
  2501. // Handle case where no path is given to --doctool.
  2502. else if (args[i] == "--doctool") {
  2503. doc_tool_path = ".";
  2504. }
  2505. #endif
  2506. }
  2507. uint64_t minimum_time_msec = GLOBAL_DEF(PropertyInfo(Variant::INT, "application/boot_splash/minimum_display_time", PROPERTY_HINT_RANGE, "0,100,1,or_greater,suffix:ms"), 0);
  2508. if (Engine::get_singleton()->is_editor_hint()) {
  2509. minimum_time_msec = 0;
  2510. }
  2511. #ifdef TOOLS_ENABLED
  2512. #ifdef MODULE_GDSCRIPT_ENABLED
  2513. if (!doc_tool_path.is_empty() && gdscript_docs_path.is_empty()) {
  2514. #else
  2515. if (!doc_tool_path.is_empty()) {
  2516. #endif
  2517. // Needed to instance editor-only classes for their default values
  2518. Engine::get_singleton()->set_editor_hint(true);
  2519. // Translate the class reference only when `-l LOCALE` parameter is given.
  2520. if (!locale.is_empty() && locale != "en") {
  2521. load_doc_translations(locale);
  2522. }
  2523. {
  2524. Ref<DirAccess> da = DirAccess::open(doc_tool_path);
  2525. ERR_FAIL_COND_V_MSG(da.is_null(), false, "Argument supplied to --doctool must be a valid directory path.");
  2526. }
  2527. #ifndef MODULE_MONO_ENABLED
  2528. // Hack to define .NET-specific project settings even on non-.NET builds,
  2529. // so that we don't lose their descriptions and default values in DocTools.
  2530. // Default values should be synced with mono_gd/gd_mono.cpp.
  2531. GLOBAL_DEF("dotnet/project/assembly_name", "");
  2532. GLOBAL_DEF("dotnet/project/solution_directory", "");
  2533. GLOBAL_DEF(PropertyInfo(Variant::INT, "dotnet/project/assembly_reload_attempts", PROPERTY_HINT_RANGE, "1,16,1,or_greater"), 3);
  2534. #endif
  2535. Error err;
  2536. DocTools doc;
  2537. doc.generate(gen_flags);
  2538. DocTools docsrc;
  2539. HashMap<String, String> doc_data_classes;
  2540. HashSet<String> checked_paths;
  2541. print_line("Loading docs...");
  2542. for (int i = 0; i < _doc_data_class_path_count; i++) {
  2543. // Custom modules are always located by absolute path.
  2544. String path = _doc_data_class_paths[i].path;
  2545. if (path.is_relative_path()) {
  2546. path = doc_tool_path.path_join(path);
  2547. }
  2548. String name = _doc_data_class_paths[i].name;
  2549. doc_data_classes[name] = path;
  2550. if (!checked_paths.has(path)) {
  2551. checked_paths.insert(path);
  2552. // Create the module documentation directory if it doesn't exist
  2553. Ref<DirAccess> da = DirAccess::create_for_path(path);
  2554. err = da->make_dir_recursive(path);
  2555. ERR_FAIL_COND_V_MSG(err != OK, false, "Error: Can't create directory: " + path + ": " + itos(err));
  2556. print_line("Loading docs from: " + path);
  2557. err = docsrc.load_classes(path);
  2558. ERR_FAIL_COND_V_MSG(err != OK, false, "Error loading docs from: " + path + ": " + itos(err));
  2559. }
  2560. }
  2561. String index_path = doc_tool_path.path_join("doc/classes");
  2562. // Create the main documentation directory if it doesn't exist
  2563. Ref<DirAccess> da = DirAccess::create_for_path(index_path);
  2564. err = da->make_dir_recursive(index_path);
  2565. ERR_FAIL_COND_V_MSG(err != OK, false, "Error: Can't create index directory: " + index_path + ": " + itos(err));
  2566. print_line("Loading classes from: " + index_path);
  2567. err = docsrc.load_classes(index_path);
  2568. ERR_FAIL_COND_V_MSG(err != OK, false, "Error loading classes from: " + index_path + ": " + itos(err));
  2569. checked_paths.insert(index_path);
  2570. print_line("Merging docs...");
  2571. doc.merge_from(docsrc);
  2572. for (const String &E : checked_paths) {
  2573. print_line("Erasing old docs at: " + E);
  2574. err = DocTools::erase_classes(E);
  2575. ERR_FAIL_COND_V_MSG(err != OK, false, "Error erasing old docs at: " + E + ": " + itos(err));
  2576. }
  2577. print_line("Generating new docs...");
  2578. err = doc.save_classes(index_path, doc_data_classes);
  2579. ERR_FAIL_COND_V_MSG(err != OK, false, "Error saving new docs:" + itos(err));
  2580. print_line("Deleting docs cache...");
  2581. if (FileAccess::exists(EditorHelp::get_cache_full_path())) {
  2582. DirAccess::remove_file_or_error(EditorHelp::get_cache_full_path());
  2583. }
  2584. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  2585. return false;
  2586. }
  2587. if (dump_gdextension_interface) {
  2588. GDExtensionInterfaceDump::generate_gdextension_interface_file("gdextension_interface.h");
  2589. }
  2590. if (dump_extension_api) {
  2591. Engine::get_singleton()->set_editor_hint(true); // "extension_api.json" should always contains editor singletons.
  2592. GDExtensionAPIDump::generate_extension_json_file("extension_api.json", include_docs_in_extension_api_dump);
  2593. }
  2594. if (dump_gdextension_interface || dump_extension_api) {
  2595. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  2596. return false;
  2597. }
  2598. if (validate_extension_api) {
  2599. bool valid = GDExtensionAPIDump::validate_extension_json_file(validate_extension_api_file) == OK;
  2600. OS::get_singleton()->set_exit_code(valid ? EXIT_SUCCESS : EXIT_FAILURE);
  2601. return false;
  2602. }
  2603. #ifndef DISABLE_DEPRECATED
  2604. if (converting_project) {
  2605. int ret = ProjectConverter3To4(converter_max_kb_file, converter_max_line_length).convert();
  2606. if (ret) {
  2607. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  2608. }
  2609. return false;
  2610. }
  2611. if (validating_converting_project) {
  2612. bool ret = ProjectConverter3To4(converter_max_kb_file, converter_max_line_length).validate_conversion();
  2613. if (ret) {
  2614. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  2615. }
  2616. return false;
  2617. }
  2618. #endif // DISABLE_DEPRECATED
  2619. #endif // TOOLS_ENABLED
  2620. if (script.is_empty() && game_path.is_empty() && String(GLOBAL_GET("application/run/main_scene")) != "") {
  2621. game_path = GLOBAL_GET("application/run/main_scene");
  2622. }
  2623. #ifdef TOOLS_ENABLED
  2624. if (!editor && !project_manager && !cmdline_tool && script.is_empty() && game_path.is_empty()) {
  2625. // If we end up here, it means we didn't manage to detect what we want to run.
  2626. // Let's throw an error gently. The code leading to this is pretty brittle so
  2627. // this might end up triggered by valid usage, in which case we'll have to
  2628. // fine-tune further.
  2629. OS::get_singleton()->alert("Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
  2630. ERR_FAIL_V_MSG(false, "Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
  2631. }
  2632. #endif
  2633. MainLoop *main_loop = nullptr;
  2634. if (editor) {
  2635. main_loop = memnew(SceneTree);
  2636. }
  2637. if (main_loop_type.is_empty()) {
  2638. main_loop_type = GLOBAL_GET("application/run/main_loop_type");
  2639. }
  2640. if (!script.is_empty()) {
  2641. Ref<Script> script_res = ResourceLoader::load(script);
  2642. ERR_FAIL_COND_V_MSG(script_res.is_null(), false, "Can't load script: " + script);
  2643. if (check_only) {
  2644. if (!script_res->is_valid()) {
  2645. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  2646. } else {
  2647. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  2648. }
  2649. return false;
  2650. }
  2651. if (script_res->can_instantiate()) {
  2652. StringName instance_type = script_res->get_instance_base_type();
  2653. Object *obj = ClassDB::instantiate(instance_type);
  2654. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  2655. if (!script_loop) {
  2656. if (obj) {
  2657. memdelete(obj);
  2658. }
  2659. OS::get_singleton()->alert(vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  2660. ERR_FAIL_V_MSG(false, vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
  2661. }
  2662. script_loop->set_script(script_res);
  2663. main_loop = script_loop;
  2664. } else {
  2665. return false;
  2666. }
  2667. } else { // Not based on script path.
  2668. if (!editor && !ClassDB::class_exists(main_loop_type) && ScriptServer::is_global_class(main_loop_type)) {
  2669. String script_path = ScriptServer::get_global_class_path(main_loop_type);
  2670. Ref<Script> script_res = ResourceLoader::load(script_path);
  2671. if (script_res.is_null()) {
  2672. OS::get_singleton()->alert("Error: Could not load MainLoop script type: " + main_loop_type);
  2673. ERR_FAIL_V_MSG(false, vformat("Could not load global class %s.", main_loop_type));
  2674. }
  2675. StringName script_base = script_res->get_instance_base_type();
  2676. Object *obj = ClassDB::instantiate(script_base);
  2677. MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
  2678. if (!script_loop) {
  2679. if (obj) {
  2680. memdelete(obj);
  2681. }
  2682. OS::get_singleton()->alert("Error: Invalid MainLoop script base type: " + script_base);
  2683. ERR_FAIL_V_MSG(false, vformat("The global class %s does not inherit from SceneTree or MainLoop.", main_loop_type));
  2684. }
  2685. script_loop->set_script(script_res);
  2686. main_loop = script_loop;
  2687. }
  2688. }
  2689. if (!main_loop && main_loop_type.is_empty()) {
  2690. main_loop_type = "SceneTree";
  2691. }
  2692. if (!main_loop) {
  2693. if (!ClassDB::class_exists(main_loop_type)) {
  2694. OS::get_singleton()->alert("Error: MainLoop type doesn't exist: " + main_loop_type);
  2695. return false;
  2696. } else {
  2697. Object *ml = ClassDB::instantiate(main_loop_type);
  2698. ERR_FAIL_NULL_V_MSG(ml, false, "Can't instance MainLoop type.");
  2699. main_loop = Object::cast_to<MainLoop>(ml);
  2700. if (!main_loop) {
  2701. memdelete(ml);
  2702. ERR_FAIL_V_MSG(false, "Invalid MainLoop type.");
  2703. }
  2704. }
  2705. }
  2706. OS::get_singleton()->set_main_loop(main_loop);
  2707. SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
  2708. if (sml) {
  2709. #ifdef DEBUG_ENABLED
  2710. if (debug_collisions) {
  2711. sml->set_debug_collisions_hint(true);
  2712. }
  2713. if (debug_paths) {
  2714. sml->set_debug_paths_hint(true);
  2715. }
  2716. if (debug_navigation) {
  2717. sml->set_debug_navigation_hint(true);
  2718. NavigationServer3D::get_singleton()->set_debug_navigation_enabled(true);
  2719. }
  2720. if (debug_avoidance) {
  2721. NavigationServer3D::get_singleton()->set_debug_avoidance_enabled(true);
  2722. }
  2723. if (debug_navigation || debug_avoidance) {
  2724. NavigationServer3D::get_singleton()->set_active(true);
  2725. NavigationServer3D::get_singleton()->set_debug_enabled(true);
  2726. }
  2727. if (debug_canvas_item_redraw) {
  2728. RenderingServer::get_singleton()->canvas_item_set_debug_redraw(true);
  2729. }
  2730. #endif
  2731. if (single_threaded_scene) {
  2732. sml->set_disable_node_threading(true);
  2733. }
  2734. bool embed_subwindows = GLOBAL_GET("display/window/subwindows/embed_subwindows");
  2735. if (single_window || (!project_manager && !editor && embed_subwindows) || !DisplayServer::get_singleton()->has_feature(DisplayServer::Feature::FEATURE_SUBWINDOWS)) {
  2736. sml->get_root()->set_embedding_subwindows(true);
  2737. }
  2738. ResourceLoader::add_custom_loaders();
  2739. ResourceSaver::add_custom_savers();
  2740. if (!project_manager && !editor) { // game
  2741. if (!game_path.is_empty() || !script.is_empty()) {
  2742. //autoload
  2743. OS::get_singleton()->benchmark_begin_measure("load_autoloads");
  2744. HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  2745. //first pass, add the constants so they exist before any script is loaded
  2746. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
  2747. const ProjectSettings::AutoloadInfo &info = E.value;
  2748. if (info.is_singleton) {
  2749. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  2750. ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
  2751. }
  2752. }
  2753. }
  2754. //second pass, load into global constants
  2755. List<Node *> to_add;
  2756. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
  2757. const ProjectSettings::AutoloadInfo &info = E.value;
  2758. Node *n = nullptr;
  2759. if (ResourceLoader::get_resource_type(info.path) == "PackedScene") {
  2760. // Cache the scene reference before loading it (for cyclic references)
  2761. Ref<PackedScene> scn;
  2762. scn.instantiate();
  2763. scn->set_path(info.path);
  2764. scn->reload_from_file();
  2765. ERR_CONTINUE_MSG(!scn.is_valid(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
  2766. if (scn.is_valid()) {
  2767. n = scn->instantiate();
  2768. }
  2769. } else {
  2770. Ref<Resource> res = ResourceLoader::load(info.path);
  2771. ERR_CONTINUE_MSG(res.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
  2772. Ref<Script> script_res = res;
  2773. if (script_res.is_valid()) {
  2774. StringName ibt = script_res->get_instance_base_type();
  2775. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  2776. ERR_CONTINUE_MSG(!valid_type, vformat("Failed to instantiate an autoload, script '%s' does not inherit from 'Node'.", info.path));
  2777. Object *obj = ClassDB::instantiate(ibt);
  2778. ERR_CONTINUE_MSG(!obj, vformat("Failed to instantiate an autoload, cannot instantiate '%s'.", ibt));
  2779. n = Object::cast_to<Node>(obj);
  2780. n->set_script(script_res);
  2781. }
  2782. }
  2783. ERR_CONTINUE_MSG(!n, vformat("Failed to instantiate an autoload, path is not pointing to a scene or a script: %s.", info.path));
  2784. n->set_name(info.name);
  2785. //defer so references are all valid on _ready()
  2786. to_add.push_back(n);
  2787. if (info.is_singleton) {
  2788. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  2789. ScriptServer::get_language(i)->add_global_constant(info.name, n);
  2790. }
  2791. }
  2792. }
  2793. for (Node *E : to_add) {
  2794. sml->get_root()->add_child(E);
  2795. }
  2796. OS::get_singleton()->benchmark_end_measure("load_autoloads");
  2797. }
  2798. }
  2799. #ifdef TOOLS_ENABLED
  2800. #ifdef MODULE_GDSCRIPT_ENABLED
  2801. if (!doc_tool_path.is_empty() && !gdscript_docs_path.is_empty()) {
  2802. DocTools docs;
  2803. Error err;
  2804. Vector<String> paths = get_files_with_extension(gdscript_docs_path, "gd");
  2805. ERR_FAIL_COND_V_MSG(paths.size() == 0, false, "Couldn't find any GDScript files under the given directory: " + gdscript_docs_path);
  2806. for (const String &path : paths) {
  2807. Ref<GDScript> gdscript = ResourceLoader::load(path);
  2808. for (const DocData::ClassDoc &class_doc : gdscript->get_documentation()) {
  2809. docs.add_doc(class_doc);
  2810. }
  2811. }
  2812. if (doc_tool_path == ".") {
  2813. doc_tool_path = "./docs";
  2814. }
  2815. Ref<DirAccess> da = DirAccess::create_for_path(doc_tool_path);
  2816. err = da->make_dir_recursive(doc_tool_path);
  2817. ERR_FAIL_COND_V_MSG(err != OK, false, "Error: Can't create GDScript docs directory: " + doc_tool_path + ": " + itos(err));
  2818. HashMap<String, String> doc_data_classes;
  2819. err = docs.save_classes(doc_tool_path, doc_data_classes, false);
  2820. ERR_FAIL_COND_V_MSG(err != OK, false, "Error saving GDScript docs:" + itos(err));
  2821. OS::get_singleton()->set_exit_code(EXIT_SUCCESS);
  2822. return false;
  2823. }
  2824. #endif // MODULE_GDSCRIPT_ENABLED
  2825. EditorNode *editor_node = nullptr;
  2826. if (editor) {
  2827. OS::get_singleton()->benchmark_begin_measure("editor");
  2828. editor_node = memnew(EditorNode);
  2829. sml->get_root()->add_child(editor_node);
  2830. if (!_export_preset.is_empty()) {
  2831. editor_node->export_preset(_export_preset, positional_arg, export_debug, export_pack_only);
  2832. game_path = ""; // Do not load anything.
  2833. }
  2834. OS::get_singleton()->benchmark_end_measure("editor");
  2835. }
  2836. #endif
  2837. sml->set_auto_accept_quit(GLOBAL_GET("application/config/auto_accept_quit"));
  2838. sml->set_quit_on_go_back(GLOBAL_GET("application/config/quit_on_go_back"));
  2839. if (!editor && !project_manager) {
  2840. //standard helpers that can be changed from main config
  2841. String stretch_mode = GLOBAL_GET("display/window/stretch/mode");
  2842. String stretch_aspect = GLOBAL_GET("display/window/stretch/aspect");
  2843. Size2i stretch_size = Size2i(GLOBAL_GET("display/window/size/viewport_width"),
  2844. GLOBAL_GET("display/window/size/viewport_height"));
  2845. real_t stretch_scale = GLOBAL_GET("display/window/stretch/scale");
  2846. String stretch_scale_mode = GLOBAL_GET("display/window/stretch/scale_mode");
  2847. Window::ContentScaleMode cs_sm = Window::CONTENT_SCALE_MODE_DISABLED;
  2848. if (stretch_mode == "canvas_items") {
  2849. cs_sm = Window::CONTENT_SCALE_MODE_CANVAS_ITEMS;
  2850. } else if (stretch_mode == "viewport") {
  2851. cs_sm = Window::CONTENT_SCALE_MODE_VIEWPORT;
  2852. }
  2853. Window::ContentScaleAspect cs_aspect = Window::CONTENT_SCALE_ASPECT_IGNORE;
  2854. if (stretch_aspect == "keep") {
  2855. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP;
  2856. } else if (stretch_aspect == "keep_width") {
  2857. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_WIDTH;
  2858. } else if (stretch_aspect == "keep_height") {
  2859. cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_HEIGHT;
  2860. } else if (stretch_aspect == "expand") {
  2861. cs_aspect = Window::CONTENT_SCALE_ASPECT_EXPAND;
  2862. }
  2863. Window::ContentScaleStretch cs_stretch = Window::CONTENT_SCALE_STRETCH_FRACTIONAL;
  2864. if (stretch_scale_mode == "integer") {
  2865. cs_stretch = Window::CONTENT_SCALE_STRETCH_INTEGER;
  2866. }
  2867. sml->get_root()->set_content_scale_mode(cs_sm);
  2868. sml->get_root()->set_content_scale_aspect(cs_aspect);
  2869. sml->get_root()->set_content_scale_stretch(cs_stretch);
  2870. sml->get_root()->set_content_scale_size(stretch_size);
  2871. sml->get_root()->set_content_scale_factor(stretch_scale);
  2872. sml->set_auto_accept_quit(GLOBAL_GET("application/config/auto_accept_quit"));
  2873. sml->set_quit_on_go_back(GLOBAL_GET("application/config/quit_on_go_back"));
  2874. String appname = GLOBAL_GET("application/config/name");
  2875. appname = TranslationServer::get_singleton()->translate(appname);
  2876. #ifdef DEBUG_ENABLED
  2877. // Append a suffix to the window title to denote that the project is running
  2878. // from a debug build (including the editor). Since this results in lower performance,
  2879. // this should be clearly presented to the user.
  2880. DisplayServer::get_singleton()->window_set_title(vformat("%s (DEBUG)", appname));
  2881. #else
  2882. DisplayServer::get_singleton()->window_set_title(appname);
  2883. #endif
  2884. bool snap_controls = GLOBAL_GET("gui/common/snap_controls_to_pixels");
  2885. sml->get_root()->set_snap_controls_to_pixels(snap_controls);
  2886. bool font_oversampling = GLOBAL_GET("gui/fonts/dynamic_fonts/use_oversampling");
  2887. sml->get_root()->set_use_font_oversampling(font_oversampling);
  2888. int texture_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter");
  2889. int texture_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat");
  2890. sml->get_root()->set_default_canvas_item_texture_filter(
  2891. Viewport::DefaultCanvasItemTextureFilter(texture_filter));
  2892. sml->get_root()->set_default_canvas_item_texture_repeat(
  2893. Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
  2894. }
  2895. #ifdef TOOLS_ENABLED
  2896. if (editor) {
  2897. bool editor_embed_subwindows = EditorSettings::get_singleton()->get_setting(
  2898. "interface/editor/single_window_mode");
  2899. if (editor_embed_subwindows) {
  2900. sml->get_root()->set_embedding_subwindows(true);
  2901. }
  2902. }
  2903. #endif
  2904. String local_game_path;
  2905. if (!game_path.is_empty() && !project_manager) {
  2906. local_game_path = game_path.replace("\\", "/");
  2907. if (!local_game_path.begins_with("res://")) {
  2908. bool absolute =
  2909. (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
  2910. if (!absolute) {
  2911. if (ProjectSettings::get_singleton()->is_using_datapack()) {
  2912. local_game_path = "res://" + local_game_path;
  2913. } else {
  2914. int sep = local_game_path.rfind("/");
  2915. if (sep == -1) {
  2916. Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  2917. ERR_FAIL_COND_V(da.is_null(), false);
  2918. local_game_path = da->get_current_dir().path_join(local_game_path);
  2919. } else {
  2920. Ref<DirAccess> da = DirAccess::open(local_game_path.substr(0, sep));
  2921. if (da.is_valid()) {
  2922. local_game_path = da->get_current_dir().path_join(
  2923. local_game_path.substr(sep + 1, local_game_path.length()));
  2924. }
  2925. }
  2926. }
  2927. }
  2928. }
  2929. local_game_path = ProjectSettings::get_singleton()->localize_path(local_game_path);
  2930. #ifdef TOOLS_ENABLED
  2931. if (editor) {
  2932. if (game_path != String(GLOBAL_GET("application/run/main_scene")) || !editor_node->has_scenes_in_session()) {
  2933. Error serr = editor_node->load_scene(local_game_path);
  2934. if (serr != OK) {
  2935. ERR_PRINT("Failed to load scene");
  2936. }
  2937. }
  2938. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_EDITOR);
  2939. if (!debug_server_uri.is_empty()) {
  2940. EditorDebuggerNode::get_singleton()->start(debug_server_uri);
  2941. EditorDebuggerNode::get_singleton()->set_keep_open(true);
  2942. }
  2943. }
  2944. #endif
  2945. if (!editor) {
  2946. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_ENGINE);
  2947. }
  2948. }
  2949. if (!project_manager && !editor) { // game
  2950. OS::get_singleton()->benchmark_begin_measure("game_load");
  2951. // Load SSL Certificates from Project Settings (or builtin).
  2952. Crypto::load_default_certificates(GLOBAL_GET("network/tls/certificate_bundle_override"));
  2953. if (!game_path.is_empty()) {
  2954. Node *scene = nullptr;
  2955. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  2956. if (scenedata.is_valid()) {
  2957. scene = scenedata->instantiate();
  2958. }
  2959. ERR_FAIL_NULL_V_MSG(scene, false, "Failed loading scene: " + local_game_path + ".");
  2960. sml->add_current_scene(scene);
  2961. #ifdef MACOS_ENABLED
  2962. String mac_icon_path = GLOBAL_GET("application/config/macos_native_icon");
  2963. if (!mac_icon_path.is_empty()) {
  2964. DisplayServer::get_singleton()->set_native_icon(mac_icon_path);
  2965. has_icon = true;
  2966. }
  2967. #endif
  2968. #ifdef WINDOWS_ENABLED
  2969. String win_icon_path = GLOBAL_GET("application/config/windows_native_icon");
  2970. if (!win_icon_path.is_empty()) {
  2971. DisplayServer::get_singleton()->set_native_icon(win_icon_path);
  2972. has_icon = true;
  2973. }
  2974. #endif
  2975. String icon_path = GLOBAL_GET("application/config/icon");
  2976. if ((!icon_path.is_empty()) && (!has_icon)) {
  2977. Ref<Image> icon;
  2978. icon.instantiate();
  2979. if (ImageLoader::load_image(icon_path, icon) == OK) {
  2980. DisplayServer::get_singleton()->set_icon(icon);
  2981. has_icon = true;
  2982. }
  2983. }
  2984. }
  2985. OS::get_singleton()->benchmark_end_measure("game_load");
  2986. }
  2987. #ifdef TOOLS_ENABLED
  2988. if (project_manager) {
  2989. OS::get_singleton()->benchmark_begin_measure("project_manager");
  2990. Engine::get_singleton()->set_editor_hint(true);
  2991. ProjectManager *pmanager = memnew(ProjectManager);
  2992. ProgressDialog *progress_dialog = memnew(ProgressDialog);
  2993. pmanager->add_child(progress_dialog);
  2994. sml->get_root()->add_child(pmanager);
  2995. DisplayServer::get_singleton()->set_context(DisplayServer::CONTEXT_PROJECTMAN);
  2996. OS::get_singleton()->benchmark_end_measure("project_manager");
  2997. }
  2998. if (project_manager || editor) {
  2999. // Load SSL Certificates from Editor Settings (or builtin)
  3000. Crypto::load_default_certificates(
  3001. EditorSettings::get_singleton()->get_setting("network/tls/editor_tls_certificates").operator String());
  3002. }
  3003. #endif
  3004. }
  3005. if (!has_icon && OS::get_singleton()->get_bundle_icon_path().is_empty()) {
  3006. Ref<Image> icon = memnew(Image(app_icon_png));
  3007. DisplayServer::get_singleton()->set_icon(icon);
  3008. }
  3009. if (movie_writer) {
  3010. movie_writer->begin(DisplayServer::get_singleton()->window_get_size(), fixed_fps, Engine::get_singleton()->get_write_movie_path());
  3011. }
  3012. if (minimum_time_msec) {
  3013. uint64_t minimum_time = 1000 * minimum_time_msec;
  3014. uint64_t elapsed_time = OS::get_singleton()->get_ticks_usec();
  3015. if (elapsed_time < minimum_time) {
  3016. OS::get_singleton()->delay_usec(minimum_time - elapsed_time);
  3017. }
  3018. }
  3019. OS::get_singleton()->benchmark_end_measure("startup_begin");
  3020. OS::get_singleton()->benchmark_dump();
  3021. return true;
  3022. }
  3023. /* Main iteration
  3024. *
  3025. * This is the iteration of the engine's game loop, advancing the state of physics,
  3026. * rendering and audio.
  3027. * It's called directly by the platform's OS::run method, where the loop is created
  3028. * and monitored.
  3029. *
  3030. * The OS implementation can impact its draw step with the Main::force_redraw() method.
  3031. */
  3032. uint64_t Main::last_ticks = 0;
  3033. uint32_t Main::frames = 0;
  3034. uint32_t Main::hide_print_fps_attempts = 3;
  3035. uint32_t Main::frame = 0;
  3036. bool Main::force_redraw_requested = false;
  3037. int Main::iterating = 0;
  3038. bool Main::agile_input_event_flushing = false;
  3039. bool Main::is_iterating() {
  3040. return iterating > 0;
  3041. }
  3042. // For performance metrics.
  3043. static uint64_t physics_process_max = 0;
  3044. static uint64_t process_max = 0;
  3045. static uint64_t navigation_process_max = 0;
  3046. bool Main::iteration() {
  3047. //for now do not error on this
  3048. //ERR_FAIL_COND_V(iterating, false);
  3049. iterating++;
  3050. const uint64_t ticks = OS::get_singleton()->get_ticks_usec();
  3051. Engine::get_singleton()->_frame_ticks = ticks;
  3052. main_timer_sync.set_cpu_ticks_usec(ticks);
  3053. main_timer_sync.set_fixed_fps(fixed_fps);
  3054. const uint64_t ticks_elapsed = ticks - last_ticks;
  3055. const int physics_ticks_per_second = Engine::get_singleton()->get_physics_ticks_per_second();
  3056. const double physics_step = 1.0 / physics_ticks_per_second;
  3057. const double time_scale = Engine::get_singleton()->get_time_scale();
  3058. MainFrameTime advance = main_timer_sync.advance(physics_step, physics_ticks_per_second);
  3059. double process_step = advance.process_step;
  3060. double scaled_step = process_step * time_scale;
  3061. Engine::get_singleton()->_process_step = process_step;
  3062. Engine::get_singleton()->_physics_interpolation_fraction = advance.interpolation_fraction;
  3063. uint64_t physics_process_ticks = 0;
  3064. uint64_t process_ticks = 0;
  3065. uint64_t navigation_process_ticks = 0;
  3066. frame += ticks_elapsed;
  3067. last_ticks = ticks;
  3068. const int max_physics_steps = Engine::get_singleton()->get_max_physics_steps_per_frame();
  3069. if (fixed_fps == -1 && advance.physics_steps > max_physics_steps) {
  3070. process_step -= (advance.physics_steps - max_physics_steps) * physics_step;
  3071. advance.physics_steps = max_physics_steps;
  3072. }
  3073. bool exit = false;
  3074. // process all our active interfaces
  3075. XRServer::get_singleton()->_process();
  3076. NavigationServer2D::get_singleton()->sync();
  3077. NavigationServer3D::get_singleton()->sync();
  3078. for (int iters = 0; iters < advance.physics_steps; ++iters) {
  3079. if (Input::get_singleton()->is_using_input_buffering() && agile_input_event_flushing) {
  3080. Input::get_singleton()->flush_buffered_events();
  3081. }
  3082. Engine::get_singleton()->_in_physics = true;
  3083. uint64_t physics_begin = OS::get_singleton()->get_ticks_usec();
  3084. PhysicsServer3D::get_singleton()->sync();
  3085. PhysicsServer3D::get_singleton()->flush_queries();
  3086. PhysicsServer2D::get_singleton()->sync();
  3087. PhysicsServer2D::get_singleton()->flush_queries();
  3088. if (OS::get_singleton()->get_main_loop()->physics_process(physics_step * time_scale)) {
  3089. PhysicsServer3D::get_singleton()->end_sync();
  3090. PhysicsServer2D::get_singleton()->end_sync();
  3091. exit = true;
  3092. break;
  3093. }
  3094. uint64_t navigation_begin = OS::get_singleton()->get_ticks_usec();
  3095. NavigationServer3D::get_singleton()->process(physics_step * time_scale);
  3096. navigation_process_ticks = MAX(navigation_process_ticks, OS::get_singleton()->get_ticks_usec() - navigation_begin); // keep the largest one for reference
  3097. navigation_process_max = MAX(OS::get_singleton()->get_ticks_usec() - navigation_begin, navigation_process_max);
  3098. message_queue->flush();
  3099. PhysicsServer3D::get_singleton()->end_sync();
  3100. PhysicsServer3D::get_singleton()->step(physics_step * time_scale);
  3101. PhysicsServer2D::get_singleton()->end_sync();
  3102. PhysicsServer2D::get_singleton()->step(physics_step * time_scale);
  3103. message_queue->flush();
  3104. physics_process_ticks = MAX(physics_process_ticks, OS::get_singleton()->get_ticks_usec() - physics_begin); // keep the largest one for reference
  3105. physics_process_max = MAX(OS::get_singleton()->get_ticks_usec() - physics_begin, physics_process_max);
  3106. Engine::get_singleton()->_physics_frames++;
  3107. Engine::get_singleton()->_in_physics = false;
  3108. }
  3109. if (Input::get_singleton()->is_using_input_buffering() && agile_input_event_flushing) {
  3110. Input::get_singleton()->flush_buffered_events();
  3111. }
  3112. uint64_t process_begin = OS::get_singleton()->get_ticks_usec();
  3113. if (OS::get_singleton()->get_main_loop()->process(process_step * time_scale)) {
  3114. exit = true;
  3115. }
  3116. message_queue->flush();
  3117. RenderingServer::get_singleton()->sync(); //sync if still drawing from previous frames.
  3118. if (DisplayServer::get_singleton()->can_any_window_draw() &&
  3119. RenderingServer::get_singleton()->is_render_loop_enabled()) {
  3120. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  3121. if (RenderingServer::get_singleton()->has_changed()) {
  3122. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  3123. Engine::get_singleton()->frames_drawn++;
  3124. }
  3125. } else {
  3126. RenderingServer::get_singleton()->draw(true, scaled_step); // flush visual commands
  3127. Engine::get_singleton()->frames_drawn++;
  3128. force_redraw_requested = false;
  3129. }
  3130. }
  3131. process_ticks = OS::get_singleton()->get_ticks_usec() - process_begin;
  3132. process_max = MAX(process_ticks, process_max);
  3133. uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
  3134. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  3135. ScriptServer::get_language(i)->frame();
  3136. }
  3137. AudioServer::get_singleton()->update();
  3138. if (EngineDebugger::is_active()) {
  3139. EngineDebugger::get_singleton()->iteration(frame_time, process_ticks, physics_process_ticks, physics_step);
  3140. }
  3141. frames++;
  3142. Engine::get_singleton()->_process_frames++;
  3143. if (frame > 1000000) {
  3144. // Wait a few seconds before printing FPS, as FPS reporting just after the engine has started is inaccurate.
  3145. if (hide_print_fps_attempts == 0) {
  3146. if (editor || project_manager) {
  3147. if (print_fps) {
  3148. print_line(vformat("Editor FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
  3149. }
  3150. } else if (print_fps || GLOBAL_GET("debug/settings/stdout/print_fps")) {
  3151. print_line(vformat("Project FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
  3152. }
  3153. } else {
  3154. hide_print_fps_attempts--;
  3155. }
  3156. Engine::get_singleton()->_fps = frames;
  3157. performance->set_process_time(USEC_TO_SEC(process_max));
  3158. performance->set_physics_process_time(USEC_TO_SEC(physics_process_max));
  3159. performance->set_navigation_process_time(USEC_TO_SEC(navigation_process_max));
  3160. process_max = 0;
  3161. physics_process_max = 0;
  3162. navigation_process_max = 0;
  3163. frame %= 1000000;
  3164. frames = 0;
  3165. }
  3166. iterating--;
  3167. // Needed for OSs using input buffering regardless accumulation (like Android)
  3168. if (Input::get_singleton()->is_using_input_buffering() && !agile_input_event_flushing) {
  3169. Input::get_singleton()->flush_buffered_events();
  3170. }
  3171. if (movie_writer) {
  3172. movie_writer->add_frame();
  3173. }
  3174. if ((quit_after > 0) && (Engine::get_singleton()->_process_frames >= quit_after)) {
  3175. exit = true;
  3176. }
  3177. #ifdef TOOLS_ENABLED
  3178. if (wait_for_import && EditorFileSystem::get_singleton()->doing_first_scan()) {
  3179. exit = false;
  3180. }
  3181. #endif
  3182. if (fixed_fps != -1) {
  3183. return exit;
  3184. }
  3185. OS::get_singleton()->add_frame_delay(DisplayServer::get_singleton()->window_can_draw());
  3186. #ifdef TOOLS_ENABLED
  3187. if (auto_build_solutions) {
  3188. auto_build_solutions = false;
  3189. // Only relevant when running the editor.
  3190. if (!editor) {
  3191. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  3192. ERR_FAIL_V_MSG(true,
  3193. "Command line option --build-solutions was passed, but no project is being edited. Aborting.");
  3194. }
  3195. if (!EditorNode::get_singleton()->call_build()) {
  3196. OS::get_singleton()->set_exit_code(EXIT_FAILURE);
  3197. ERR_FAIL_V_MSG(true,
  3198. "Command line option --build-solutions was passed, but the build callback failed. Aborting.");
  3199. }
  3200. }
  3201. #endif
  3202. return exit;
  3203. }
  3204. void Main::force_redraw() {
  3205. force_redraw_requested = true;
  3206. }
  3207. /* Engine deinitialization
  3208. *
  3209. * Responsible for freeing all the memory allocated by previous setup steps,
  3210. * so that the engine closes cleanly without leaking memory or crashing.
  3211. * The order matters as some of those steps are linked with each other.
  3212. */
  3213. void Main::cleanup(bool p_force) {
  3214. OS::get_singleton()->benchmark_begin_measure("Main::cleanup");
  3215. if (!p_force) {
  3216. ERR_FAIL_COND(!_start_success);
  3217. }
  3218. for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
  3219. TextServerManager::get_singleton()->get_interface(i)->cleanup();
  3220. }
  3221. if (movie_writer) {
  3222. movie_writer->end();
  3223. }
  3224. ResourceLoader::clear_thread_load_tasks();
  3225. ResourceLoader::remove_custom_loaders();
  3226. ResourceSaver::remove_custom_savers();
  3227. // Flush before uninitializing the scene, but delete the MessageQueue as late as possible.
  3228. message_queue->flush();
  3229. OS::get_singleton()->delete_main_loop();
  3230. OS::get_singleton()->_cmdline.clear();
  3231. OS::get_singleton()->_user_args.clear();
  3232. OS::get_singleton()->_execpath = "";
  3233. OS::get_singleton()->_local_clipboard = "";
  3234. ResourceLoader::clear_translation_remaps();
  3235. ResourceLoader::clear_path_remaps();
  3236. ScriptServer::finish_languages();
  3237. // Sync pending commands that may have been queued from a different thread during ScriptServer finalization
  3238. RenderingServer::get_singleton()->sync();
  3239. //clear global shader variables before scene and other graphics stuff are deinitialized.
  3240. rendering_server->global_shader_parameters_clear();
  3241. if (xr_server) {
  3242. // Now that we're unregistering properly in plugins we need to keep access to xr_server for a little longer
  3243. // We do however unset our primary interface
  3244. xr_server->set_primary_interface(Ref<XRInterface>());
  3245. }
  3246. #ifdef TOOLS_ENABLED
  3247. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
  3248. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
  3249. unregister_editor_types();
  3250. #endif
  3251. ImageLoader::cleanup();
  3252. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
  3253. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
  3254. unregister_platform_apis();
  3255. unregister_driver_types();
  3256. unregister_scene_types();
  3257. finalize_theme_db();
  3258. // Before deinitializing server extensions, finalize servers which may be loaded as extensions.
  3259. finalize_navigation_server();
  3260. finalize_physics();
  3261. GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
  3262. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
  3263. unregister_server_types();
  3264. EngineDebugger::deinitialize();
  3265. if (xr_server) {
  3266. memdelete(xr_server);
  3267. }
  3268. if (audio_server) {
  3269. audio_server->finish();
  3270. memdelete(audio_server);
  3271. }
  3272. if (camera_server) {
  3273. memdelete(camera_server);
  3274. }
  3275. OS::get_singleton()->finalize();
  3276. finalize_display();
  3277. if (input) {
  3278. memdelete(input);
  3279. }
  3280. if (packed_data) {
  3281. memdelete(packed_data);
  3282. }
  3283. if (performance) {
  3284. memdelete(performance);
  3285. }
  3286. if (input_map) {
  3287. memdelete(input_map);
  3288. }
  3289. if (time_singleton) {
  3290. memdelete(time_singleton);
  3291. }
  3292. if (translation_server) {
  3293. memdelete(translation_server);
  3294. }
  3295. if (tsman) {
  3296. memdelete(tsman);
  3297. }
  3298. if (physics_server_3d_manager) {
  3299. memdelete(physics_server_3d_manager);
  3300. }
  3301. if (physics_server_2d_manager) {
  3302. memdelete(physics_server_2d_manager);
  3303. }
  3304. if (globals) {
  3305. memdelete(globals);
  3306. }
  3307. if (engine) {
  3308. memdelete(engine);
  3309. }
  3310. if (OS::get_singleton()->is_restart_on_exit_set()) {
  3311. //attempt to restart with arguments
  3312. List<String> args = OS::get_singleton()->get_restart_on_exit_arguments();
  3313. OS::get_singleton()->create_instance(args);
  3314. OS::get_singleton()->set_restart_on_exit(false, List<String>()); //clear list (uses memory)
  3315. }
  3316. // Now should be safe to delete MessageQueue (famous last words).
  3317. message_queue->flush();
  3318. memdelete(message_queue);
  3319. unregister_core_driver_types();
  3320. unregister_core_extensions();
  3321. uninitialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
  3322. unregister_core_types();
  3323. OS::get_singleton()->benchmark_end_measure("Main::cleanup");
  3324. OS::get_singleton()->benchmark_dump();
  3325. OS::get_singleton()->finalize_core();
  3326. }