main.cpp 124 KB

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