Debian Codegraph @

main/main.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* main.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "main.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/core_globals.h"
35 #include "core/crypto/crypto.h"
36 #include "core/debugger/engine_debugger.h"
37 #include "core/extension/extension_api_dump.h"
38 #include "core/extension/gdextension_interface_dump.gen.h"
39 #include "core/extension/gdextension_interface_header_generator.h"
40 #include "core/extension/gdextension_manager.h"
41 #include "core/input/input.h"
42 #include "core/input/input_map.h"
43 #include "core/io/dir_access.h"
44 #include "core/io/file_access_pack.h"
45 #include "core/io/file_access_zip.h"
46 #include "core/io/image.h"
47 #include "core/io/image_loader.h"
48 #include "core/io/ip.h"
49 #include "core/io/resource_loader.h"
50 #include "core/object/message_queue.h"
51 #include "core/object/script_language.h"
52 #include "core/os/os.h"
53 #include "core/os/time.h"
54 #include "core/profiling/profiling.h"
55 #include "core/register_core_types.h"
56 #include "core/string/translation_server.h"
57 #include "core/version.h"
58 #include "drivers/register_driver_types.h"
59 #include "main/app_icon.gen.h"
60 #include "main/main_timer_sync.h"
61 #include "main/performance.h"
62 #include "main/splash.gen.h"
63 #include "modules/register_module_types.h"
64 #include "platform/register_platform_apis.h"
65 #include "scene/main/scene_tree.h"
66 #include "scene/main/window.h"
67 #include "scene/property_list_helper.h"
68 #include "scene/register_scene_types.h"
69 #include "scene/resources/packed_scene.h"
70 #include "scene/theme/theme_db.h"
71 #include "servers/audio/audio_driver_dummy.h"
72 #include "servers/audio/audio_server.h"
73 #include "servers/camera/camera_server.h"
74 #include "servers/display/display_server.h"
75 #include "servers/movie_writer/movie_writer.h"
76 #include "servers/register_server_types.h"
77 #include "servers/rendering/rendering_server_default.h"
78 #include "servers/text/text_server.h"
79 #include "servers/text/text_server_dummy.h"
80
81 // 2D
82 #ifndef NAVIGATION_2D_DISABLED
83 #include "servers/navigation_2d/navigation_server_2d.h"
84 #include "servers/navigation_2d/navigation_server_2d_dummy.h"
85 #endif // NAVIGATION_2D_DISABLED
86
87 #ifndef PHYSICS_2D_DISABLED
88 #include "servers/physics_2d/physics_server_2d.h"
89 #include "servers/physics_2d/physics_server_2d_dummy.h"
90 #endif // PHYSICS_2D_DISABLED
91
92 // 3D
93 #ifndef NAVIGATION_3D_DISABLED
94 #include "servers/navigation_3d/navigation_server_3d.h"
95 #include "servers/navigation_3d/navigation_server_3d_dummy.h"
96 #endif // NAVIGATION_3D_DISABLED
97
98 #ifndef PHYSICS_3D_DISABLED
99 #include "servers/physics_3d/physics_server_3d.h"
100 #include "servers/physics_3d/physics_server_3d_dummy.h"
101 #endif // PHYSICS_3D_DISABLED
102
103 #ifndef XR_DISABLED
104 #include "servers/xr/xr_server.h"
105 #endif // XR_DISABLED
106
107 #ifdef TESTS_ENABLED
108 #include "tests/test_main.h"
109 #endif
110
111 #ifdef TOOLS_ENABLED
112 #include "editor/debugger/debug_adapter/debug_adapter_server.h"
113 #include "editor/debugger/editor_debugger_node.h"
114 #include "editor/doc/doc_data_class_path.gen.h"
115 #include "editor/doc/doc_tools.h"
116 #include "editor/doc/editor_help.h"
117 #include "editor/editor_node.h"
118 #include "editor/file_system/editor_file_system.h"
119 #include "editor/file_system/editor_paths.h"
120 #include "editor/gui/progress_dialog.h"
121 #include "editor/project_manager/project_manager.h"
122 #include "editor/register_editor_types.h"
123 #include "editor/settings/editor_settings.h"
124 #include "editor/translations/editor_translation.h"
125
126 #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
127 #include "main/splash_editor.gen.h"
128 #endif
129
130 #ifndef DISABLE_DEPRECATED
131 #include "editor/project_upgrade/project_converter_3_to_4.h"
132 #endif // DISABLE_DEPRECATED
133 #endif // TOOLS_ENABLED
134
135 #if defined(STEAMAPI_ENABLED)
136 #include "main/steam_tracker.h"
137 #endif
138
139 #include "modules/modules_enabled.gen.h" // For mono.
140
141 #if defined(MODULE_MONO_ENABLED) && defined(TOOLS_ENABLED)
142 #include "modules/mono/editor/bindings_generator.h"
143 #endif
144
145 #ifdef MODULE_GDSCRIPT_ENABLED
146 #include "modules/gdscript/gdscript.h"
147 #if defined(TOOLS_ENABLED) && !defined(GDSCRIPT_NO_LSP)
148 #include "modules/gdscript/language_server/gdscript_language_server.h"
149 #endif // TOOLS_ENABLED && !GDSCRIPT_NO_LSP
150 #endif // MODULE_GDSCRIPT_ENABLED
151
152 /* Static members */
153
154 // Singletons
155
156 // Initialized in setup()
157 static Engine *engine = nullptr;
158 static ProjectSettings *globals = nullptr;
159 static Input *input = nullptr;
160 static InputMap *input_map = nullptr;
161 static TranslationServer *translation_server = nullptr;
162 static Performance *performance = nullptr;
163 static PackedData *packed_data = nullptr;
164 #ifdef MINIZIP_ENABLED
165 static ZipArchive *zip_packed_data = nullptr;
166 #endif
167 static MessageQueue *message_queue = nullptr;
168
169 #if defined(STEAMAPI_ENABLED)
170 static SteamTracker *steam_tracker = nullptr;
171 #endif
172
173 // Initialized in setup2()
174 static AudioServer *audio_server = nullptr;
175 static CameraServer *camera_server = nullptr;
176 static DisplayServer *display_server = nullptr;
177 static RenderingServer *rendering_server = nullptr;
178 static TextServerManager *tsman = nullptr;
179 static ThemeDB *theme_db = nullptr;
180 #ifndef PHYSICS_2D_DISABLED
181 static PhysicsServer2DManager *physics_server_2d_manager = nullptr;
182 static PhysicsServer2D *physics_server_2d = nullptr;
183 #endif // PHYSICS_2D_DISABLED
184 #ifndef PHYSICS_3D_DISABLED
185 static PhysicsServer3DManager *physics_server_3d_manager = nullptr;
186 static PhysicsServer3D *physics_server_3d = nullptr;
187 #endif // PHYSICS_3D_DISABLED
188 #ifndef XR_DISABLED
189 static XRServer *xr_server = nullptr;
190 #endif // XR_DISABLED
191 // We error out if setup2() doesn't turn this true
192 static bool _start_success = false;
193
194 // Drivers
195
196 String display_driver = "";
197 String tablet_driver = "";
198 String text_driver = "";
199 String rendering_driver = "";
200 String rendering_method = "";
201 static int text_driver_idx = -1;
202 static int audio_driver_idx = -1;
203
204 // Engine config/tools
205
206 static DisplayServer::AccessibilityMode accessibility_mode = DisplayServer::AccessibilityMode::ACCESSIBILITY_AUTO;
207 static bool accessibility_mode_set = false;
208 static bool single_window = false;
209 static bool editor = false;
210 static bool project_manager = false;
211 static bool cmdline_tool = false;
212 static String locale;
213 static String log_file;
214 static bool show_help = false;
215 static uint64_t quit_after = 0;
216 static OS::ProcessID editor_pid = 0;
217 #ifdef TOOLS_ENABLED
218 static bool found_project = false;
219 static bool recovery_mode = false;
220 static bool auto_build_solutions = false;
221 static String debug_server_uri;
222 static bool wait_for_import = false;
223 static bool restore_editor_window_layout = true;
224 #ifndef DISABLE_DEPRECATED
225 static int converter_max_kb_file = 4 * 1024; // 4MB
226 static int converter_max_line_length = 100000;
227 #endif // DISABLE_DEPRECATED
228
229 HashMap<Main::CLIScope, Vector<String>> forwardable_cli_arguments;
230 #endif
231 static bool single_threaded_scene = false;
232
233 // Display
234
235 static DisplayServer::WindowMode window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
236 static DisplayServer::ScreenOrientation window_orientation = DisplayServer::SCREEN_LANDSCAPE;
237 static DisplayServer::VSyncMode window_vsync_mode = DisplayServer::VSYNC_ENABLED;
238 static uint32_t window_flags = 0;
239 static Size2i window_size = Size2i(1152, 648);
240
241 static int init_screen = DisplayServer::SCREEN_PRIMARY;
242 static bool init_fullscreen = false;
243 static bool init_maximized = false;
244 static bool init_windowed = false;
245 static bool init_always_on_top = false;
246 static bool init_use_custom_pos = false;
247 static bool init_use_custom_screen = false;
248 static Vector2 init_custom_pos;
249 static int64_t init_embed_parent_window_id = 0;
250 #ifdef TOOLS_ENABLED
251 static bool init_display_scale_found = false;
252 static int init_display_scale = 0;
253 static bool init_custom_scale_found = false;
254 static float init_custom_scale = 1.0;
255 static bool init_expand_to_title = false;
256 static bool init_expand_to_title_found = false;
257 #endif
258 static bool use_custom_res = true;
259 static bool force_res = false;
260
261 // Debug
262
263 static bool use_debug_profiler = false;
264 #ifdef DEBUG_ENABLED
265 static bool debug_collisions = false;
266 static bool debug_paths = false;
267 static bool debug_navigation = false;
268 static bool debug_avoidance = false;
269 static bool debug_canvas_item_redraw = false;
270 static bool debug_mute_audio = false;
271 #endif
272 static int max_fps = -1;
273 static int frame_delay = 0;
274 static int audio_output_latency = 0;
275 static bool disable_render_loop = false;
276 static int fixed_fps = -1;
277 static MovieWriter *movie_writer = nullptr;
278 static bool disable_vsync = false;
279 static bool print_fps = false;
280 #ifdef TOOLS_ENABLED
281 static bool editor_pseudolocalization = false;
282 static bool dump_gdextension_interface = false;
283 static bool dump_gdextension_interface_header = false;
284 static bool dump_extension_api = false;
285 static bool include_docs_in_extension_api_dump = false;
286 static bool validate_extension_api = false;
287 static String validate_extension_api_file;
288 #endif
289 bool profile_gpu = false;
290
291 // Constants.
292
293 static const String NULL_DISPLAY_DRIVER("headless");
294 static const String EMBEDDED_DISPLAY_DRIVER("embedded");
295 static const String NULL_AUDIO_DRIVER("Dummy");
296
297 // The length of the longest column in the command-line help we should align to
298 // (excluding the 2-space left and right margins).
299 // Currently, this is `--export-release <preset> <path>`.
300 static const int OPTION_COLUMN_LENGTH = 32;
301
302 /* Helper methods */
303
304 bool Main::is_cmdline_tool() {
305 return cmdline_tool;
306 }
307
308 #ifdef TOOLS_ENABLED
309 const Vector<String> &Main::get_forwardable_cli_arguments(Main::CLIScope p_scope) {
310 return forwardable_cli_arguments[p_scope];
311 }
312 #endif
313
314 static String unescape_cmdline(const String &p_str) {
315 return p_str.replace("%20", " ");
316 }
317
318 static String get_full_version_string() {
319 String hash = String(GODOT_VERSION_HASH);
320 if (!hash.is_empty()) {
321 hash = "." + hash.left(9);
322 }
323 return String(GODOT_VERSION_FULL_BUILD) + hash;
324 }
325
326 #if defined(TOOLS_ENABLED) && defined(MODULE_GDSCRIPT_ENABLED)
327 static Vector<String> get_files_with_extension(const String &p_root, const String &p_extension) {
328 Vector<String> paths;
329
330 Ref<DirAccess> dir = DirAccess::open(p_root);
331 if (dir.is_valid()) {
332 dir->list_dir_begin();
333 String fn = dir->get_next();
334 while (!fn.is_empty()) {
335 if (!dir->current_is_hidden() && fn != "." && fn != "..") {
336 if (dir->current_is_dir()) {
337 paths.append_array(get_files_with_extension(p_root.path_join(fn), p_extension));
338 } else if (fn.get_extension() == p_extension) {
339 paths.append(p_root.path_join(fn));
340 }
341 }
342 fn = dir->get_next();
343 }
344 dir->list_dir_end();
345 }
346
347 return paths;
348 }
349 #endif
350
351 // FIXME: Could maybe be moved to have less code in main.cpp.
352 void initialize_physics() {
353 #ifndef PHYSICS_3D_DISABLED
354 /// 3D Physics Server
355 physics_server_3d = PhysicsServer3DManager::get_singleton()->new_server(
356 GLOBAL_GET(PhysicsServer3DManager::setting_property_name));
357 if (!physics_server_3d) {
358 // Physics server not found, Use the default physics
359 physics_server_3d = PhysicsServer3DManager::get_singleton()->new_default_server();
360 }
361
362 // Fall back to dummy if no default server has been registered.
363 if (!physics_server_3d) {
364 WARN_PRINT(vformat("Falling back to dummy PhysicsServer3D; 3D physics functionality will be disabled. If this is intended, set the %s project setting to Dummy.", PhysicsServer3DManager::setting_property_name));
365 physics_server_3d = memnew(PhysicsServer3DDummy);
366 }
367
368 // Should be impossible, but make sure it's not null.
369 ERR_FAIL_NULL_MSG(physics_server_3d, "Failed to initialize PhysicsServer3D.");
370 physics_server_3d->init();
371 #endif // PHYSICS_3D_DISABLED
372
373 #ifndef PHYSICS_2D_DISABLED
374 // 2D Physics server
375 physics_server_2d = PhysicsServer2DManager::get_singleton()->new_server(
376 GLOBAL_GET(PhysicsServer2DManager::get_singleton()->setting_property_name));
377 if (!physics_server_2d) {
378 // Physics server not found, Use the default physics
379 physics_server_2d = PhysicsServer2DManager::get_singleton()->new_default_server();
380 }
381
382 // Fall back to dummy if no default server has been registered.
383 if (!physics_server_2d) {
384 WARN_PRINT(vformat("Falling back to dummy PhysicsServer2D; 2D physics functionality will be disabled. If this is intended, set the %s project setting to Dummy.", PhysicsServer2DManager::setting_property_name));
385 physics_server_2d = memnew(PhysicsServer2DDummy);
386 }
387
388 // Should be impossible, but make sure it's not null.
389 ERR_FAIL_NULL_MSG(physics_server_2d, "Failed to initialize PhysicsServer2D.");
390 physics_server_2d->init();
391 #endif // PHYSICS_2D_DISABLED
392 }
393
394 void finalize_physics() {
395 #ifndef PHYSICS_3D_DISABLED
396 physics_server_3d->finish();
397 memdelete(physics_server_3d);
398 #endif // PHYSICS_3D_DISABLED
399
400 #ifndef PHYSICS_2D_DISABLED
401 physics_server_2d->finish();
402 memdelete(physics_server_2d);
403 #endif // PHYSICS_2D_DISABLED
404 }
405
406 void finalize_display() {
407 rendering_server->finish();
408 memdelete(rendering_server);
409
410 memdelete(display_server);
411 }
412
413 void initialize_theme_db() {
414 theme_db = memnew(ThemeDB);
415 }
416
417 void finalize_theme_db() {
418 memdelete(theme_db);
419 theme_db = nullptr;
420 }
421
422 //#define DEBUG_INIT
423 #ifdef DEBUG_INIT
424 #define MAIN_PRINT(m_txt) print_line(m_txt)
425 #else
426 #define MAIN_PRINT(m_txt)
427 #endif
428
429 void Main::print_header(bool p_rich) {
430 if (GODOT_VERSION_TIMESTAMP > 0) {
431 // Version timestamp available.
432 if (p_rich) {
433 Engine::get_singleton()->print_header_rich("\u001b[38;5;39m" + String(GODOT_VERSION_NAME) + "\u001b[0m v" + get_full_version_string() + " (" + Time::get_singleton()->get_datetime_string_from_unix_time(GODOT_VERSION_TIMESTAMP, true) + " UTC) - \u001b[4m" + String(GODOT_VERSION_WEBSITE));
434 } else {
435 Engine::get_singleton()->print_header(String(GODOT_VERSION_NAME) + " v" + get_full_version_string() + " (" + Time::get_singleton()->get_datetime_string_from_unix_time(GODOT_VERSION_TIMESTAMP, true) + " UTC) - " + String(GODOT_VERSION_WEBSITE));
436 }
437 } else {
438 if (p_rich) {
439 Engine::get_singleton()->print_header_rich("\u001b[38;5;39m" + String(GODOT_VERSION_NAME) + "\u001b[0m v" + get_full_version_string() + " - \u001b[4m" + String(GODOT_VERSION_WEBSITE));
440 } else {
441 Engine::get_singleton()->print_header(String(GODOT_VERSION_NAME) + " v" + get_full_version_string() + " - " + String(GODOT_VERSION_WEBSITE));
442 }
443 }
444 }
445
446 /**
447 * Prints a copyright notice in the command-line help with colored text. A newline is
448 * automatically added at the end.
449 */
450 void Main::print_help_copyright(const char *p_notice) {
451 OS::get_singleton()->print("\u001b[90m%s\u001b[0m\n", p_notice);
452 }
453
454 /**
455 * Prints a title in the command-line help with colored text. A newline is
456 * automatically added at beginning and at the end.
457 */
458 void Main::print_help_title(const char *p_title) {
459 OS::get_singleton()->print("\n\u001b[1;93m%s:\u001b[0m\n", p_title);
460 }
461
462 /**
463 * Returns the option string with required and optional arguments colored separately from the rest of the option.
464 * This color replacement must be done *after* calling `rpad()` for the length padding to be done correctly.
465 */
466 String Main::format_help_option(const char *p_option) {
467 return (String(p_option)
468 .rpad(OPTION_COLUMN_LENGTH)
469 .replace("[", "\u001b[96m[")
470 .replace("]", "]\u001b[0m")
471 .replace("<", "\u001b[95m<")
472 .replace(">", ">\u001b[0m"));
473 }
474
475 /**
476 * Prints an option in the command-line help with colored text. No newline is
477 * added at the end. `p_availability` denotes which build types the argument is
478 * available in. Support in release export templates implies support in debug
479 * export templates and editor. Support in debug export templates implies
480 * support in editor.
481 */
482 void Main::print_help_option(const char *p_option, const char *p_description, CLIOptionAvailability p_availability) {
483 const bool option_empty = (p_option && !p_option[0]);
484 if (!option_empty) {
485 const char *availability_badge = "";
486 switch (p_availability) {
487 case CLI_OPTION_AVAILABILITY_EDITOR:
488 availability_badge = "\u001b[1;91mE";
489 break;
490 case CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG:
491 availability_badge = "\u001b[1;94mD";
492 break;
493 case CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE:
494 availability_badge = "\u001b[1;93mX";
495 break;
496 case CLI_OPTION_AVAILABILITY_TEMPLATE_RELEASE:
497 availability_badge = "\u001b[1;92mR";
498 break;
499 case CLI_OPTION_AVAILABILITY_HIDDEN:
500 // Use for multiline option names (but not when the option name is empty).
501 availability_badge = " ";
502 break;
503 }
504 OS::get_singleton()->print(
505 " \u001b[92m%s %s\u001b[0m %s",
506 format_help_option(p_option).utf8().ptr(),
507 availability_badge,
508 p_description);
509 } else {
510 // Make continuation lines for descriptions faint if the option name is empty.
511 OS::get_singleton()->print(
512 " \u001b[92m%s \u001b[0m \u001b[90m%s",
513 format_help_option(p_option).utf8().ptr(),
514 p_description);
515 }
516 }
517
518 void Main::print_help(const char *p_binary) {
519 print_header(true);
520 print_help_copyright("Free and open source software under the terms of the MIT license.");
521 print_help_copyright("(c) 2014-present Godot Engine contributors. (c) 2007-present Juan Linietsky, Ariel Manzur.");
522
523 print_help_title("Usage");
524 OS::get_singleton()->print(" %s \u001b[96m[options] [path to \"project.godot\" file]\u001b[0m\n", p_binary);
525
526 #if defined(TOOLS_ENABLED)
527 print_help_title("Option legend (this build = editor)");
528 #elif defined(DEBUG_ENABLED)
529 print_help_title("Option legend (this build = debug export template)");
530 #else
531 print_help_title("Option legend (this build = release export template)");
532 #endif
533
534 OS::get_singleton()->print(" \u001b[1;92mR\u001b[0m Available in editor builds, debug export templates and release export templates.\n");
535 #ifdef DEBUG_ENABLED
536 OS::get_singleton()->print(" \u001b[1;94mD\u001b[0m Available in editor builds and debug export templates only.\n");
537 #endif
538 #if defined(OVERRIDE_PATH_ENABLED)
539 OS::get_singleton()->print(" \u001b[1;93mX\u001b[0m Only available in editor builds, and export templates compiled with `disable_path_overrides=false`.\n");
540 #endif
541 #ifdef TOOLS_ENABLED
542 OS::get_singleton()->print(" \u001b[1;91mE\u001b[0m Only available in editor builds.\n");
543 #endif
544
545 print_help_title("General options");
546 print_help_option("-h, --help", "Display this help message.\n");
547 print_help_option("--version", "Display the version string.\n");
548 print_help_option("-v, --verbose", "Use verbose stdout mode.\n");
549 print_help_option("--quiet", "Quiet mode, silences stdout messages. Errors are still displayed.\n");
550 print_help_option("--no-header", "Do not print engine version and rendering driver/method header on startup.\n");
551
552 print_help_title("Run options");
553 print_help_option("--, ++", "Separator for user-provided arguments. Following arguments are not used by the engine, but can be read from `OS.get_cmdline_user_args()`.\n");
554 #ifdef TOOLS_ENABLED
555 print_help_option("-e, --editor", "Start the editor instead of running the scene.\n", CLI_OPTION_AVAILABILITY_EDITOR);
556 print_help_option("-p, --project-manager", "Start the project manager, even if a project is auto-detected.\n", CLI_OPTION_AVAILABILITY_EDITOR);
557 print_help_option("--recovery-mode", "Start the editor in recovery mode, which disables features that can typically cause startup crashes, such as tool scripts, editor plugins, GDExtension addons, and others.\n", CLI_OPTION_AVAILABILITY_EDITOR);
558 print_help_option("--debug-server <uri>", "Start the editor debug server (<protocol>://<host/IP>[:port], e.g. tcp://127.0.0.1:6007)\n", CLI_OPTION_AVAILABILITY_EDITOR);
559 print_help_option("--dap-port <port>", "Use the specified port for the GDScript Debug Adapter Protocol. Recommended port range [1024, 49151].\n", CLI_OPTION_AVAILABILITY_EDITOR);
560 #if defined(MODULE_GDSCRIPT_ENABLED) && !defined(GDSCRIPT_NO_LSP)
561 print_help_option("--lsp-port <port>", "Use the specified port for the GDScript Language Server Protocol. Recommended port range [1024, 49151].\n", CLI_OPTION_AVAILABILITY_EDITOR);
562 #endif // MODULE_GDSCRIPT_ENABLED && !GDSCRIPT_NO_LSP
563 #endif
564 print_help_option("--quit", "Quit after the first iteration.\n");
565 print_help_option("--quit-after <int>", "Quit after the given number of iterations. Set to 0 to disable.\n");
566 print_help_option("-l, --language <locale>", "Use a specific locale (<locale> being a two-letter code).\n");
567 #if defined(OVERRIDE_PATH_ENABLED)
568 print_help_option("--path <directory>", "Path to a project (<directory> must contain a \"project.godot\" file).\n", CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE);
569 print_help_option("--scene <path>", "Path or UID of a scene in the project that should be started.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE);
570 #endif // defined(OVERRIDE_PATH_ENABLED)
571 #if defined(OVERRIDE_PATH_ENABLED) || defined(ANDROID_ENABLED) || defined(WEB_ENABLED)
572 print_help_option("--main-pack <file>", "Path to a pack (.pck) file to load.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE);
573 #endif // defined(OVERRIDE_PATH_ENABLED) || defined(ANDROID_ENABLED) || defined(WEB_ENABLED)
574
575 #ifdef DISABLE_DEPRECATED
576 print_help_option("--render-thread <mode>", "Render thread mode (\"safe\", \"separate\").\n");
577 #else
578 print_help_option("--render-thread <mode>", "Render thread mode (\"unsafe\" [deprecated], \"safe\", \"separate\").\n");
579 #endif // DISABLE_DEPRECATED
580 #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
581 print_help_option("--remote-fs <address>", "Remote filesystem (<host/IP>[:<port>] address).\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
582 print_help_option("--remote-fs-password <password>", "Password for remote filesystem.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
583 #endif // defined(DEBUG_ENABLED) || defined (TOOLS_ENABLED)
584
585 print_help_option("--audio-driver <driver>", "Audio driver [");
586 for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
587 if (i > 0) {
588 OS::get_singleton()->print(", ");
589 }
590 OS::get_singleton()->print("\"%s\"", AudioDriverManager::get_driver(i)->get_name());
591 }
592 OS::get_singleton()->print("].\n");
593
594 print_help_option("--display-driver <driver>", "Display driver (and rendering driver) [");
595 for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
596 if (i > 0) {
597 OS::get_singleton()->print(", ");
598 }
599 OS::get_singleton()->print("\"%s\" (", DisplayServer::get_create_function_name(i));
600 Vector<String> rd = DisplayServer::get_create_function_rendering_drivers(i);
601 for (int j = 0; j < rd.size(); j++) {
602 if (j > 0) {
603 OS::get_singleton()->print(", ");
604 }
605 OS::get_singleton()->print("\"%s\"", rd[j].utf8().get_data());
606 }
607 OS::get_singleton()->print(")");
608 }
609 OS::get_singleton()->print("].\n");
610 print_help_option("--audio-output-latency <ms>", "Override audio output latency in milliseconds (default is 15 ms).\n");
611 print_help_option("", "Lower values make sound playback more reactive but increase CPU usage, and may result in audio cracking if the CPU can't keep up.\n");
612
613 print_help_option("--rendering-method <renderer>", "Renderer name. Requires driver support.\n");
614 print_help_option("--rendering-driver <driver>", "Rendering driver (depends on display driver).\n");
615 print_help_option("--gpu-index <device_index>", "Use a specific GPU (run with --verbose to get a list of available devices).\n");
616 print_help_option("--text-driver <driver>", "Text driver (used for font rendering, bidirectional support and shaping).\n");
617 print_help_option("--tablet-driver <driver>", "Pen tablet input driver.\n");
618 print_help_option("--headless", "Enable headless mode (--display-driver headless --audio-driver Dummy). Useful for servers and with --script.\n");
619 print_help_option("--log-file <file>", "Write output/error log to the specified path instead of the default location defined by the project.\n");
620 print_help_option("", "<file> path should be absolute or relative to the project directory.\n");
621 print_help_option("--write-movie <file>", "Write a video to the specified path (usually with .avi or .png extension).\n");
622 print_help_option("", "--fixed-fps is forced when enabled, but it can be used to change movie FPS.\n");
623 print_help_option("", "--disable-vsync can speed up movie writing but makes interaction more difficult.\n");
624 print_help_option("", "--quit-after can be used to specify the number of frames to write.\n");
625
626 print_help_title("Display options");
627 print_help_option("-f, --fullscreen", "Request fullscreen mode.\n");
628 print_help_option("-m, --maximized", "Request a maximized window.\n");
629 print_help_option("-w, --windowed", "Request windowed mode.\n");
630 print_help_option("-t, --always-on-top", "Request an always-on-top window.\n");
631 print_help_option("--resolution <W>x<H>", "Request window resolution.\n");
632 print_help_option("--position <X>,<Y>", "Request window position.\n");
633 print_help_option("--screen <N>", "Request window screen.\n");
634 print_help_option("--single-window", "Use a single window (no separate subwindows).\n");
635 #ifndef _3D_DISABLED
636 print_help_option("--xr-mode <mode>", "Select XR (Extended Reality) mode [\"default\", \"off\", \"on\"].\n");
637 #endif
638 print_help_option("--wid <window_id>", "Request parented to window.\n");
639 print_help_option("--accessibility <mode>", "Select accessibility mode ['auto' (when screen reader is running, default), 'always', 'disabled'].\n");
640
641 print_help_title("Debug options");
642 print_help_option("-d, --debug", "Debug (local stdout debugger).\n");
643 print_help_option("-b, --breakpoints", "Breakpoint list as source::line comma-separated pairs, no spaces (use %%20 instead).\n");
644 print_help_option("--ignore-error-breaks", "If debugger is connected, prevents sending error breakpoints.\n");
645 print_help_option("--profiling", "Enable profiling in the script debugger.\n");
646 print_help_option("--gpu-profile", "Show a GPU profile of the tasks that took the most time during frame rendering.\n");
647 print_help_option("--gpu-validation", "Enable graphics API validation layers for debugging.\n");
648 #ifdef DEBUG_ENABLED
649 print_help_option("--gpu-abort", "Abort on graphics API usage errors (usually validation layer errors). May help see the problem if your system freezes.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
650 #endif
651 print_help_option("--generate-spirv-debug-info", "Generate SPIR-V debug information (Vulkan only). This allows source-level shader debugging with RenderDoc.\n");
652 #if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
653 print_help_option("--extra-gpu-memory-tracking", "Enables additional memory tracking (see class reference for `RenderingDevice.get_driver_and_device_memory_report()` and linked methods). Currently only implemented for Vulkan. Enabling this feature may cause crashes on some systems due to buggy drivers or bugs in the Vulkan Loader. See https://github.com/godotengine/godot/issues/95967\n");
654 print_help_option("--accurate-breadcrumbs", "Force barriers between breadcrumbs. Useful for narrowing down a command causing GPU resets. Currently only implemented for Vulkan.\n");
655 #endif
656 #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
657 print_help_option("--remote-debug <uri>", "Remote debug (<protocol>://<host/IP>[:<port>], e.g. tcp://127.0.0.1:6007).\n");
658 #endif
659 print_help_option("--single-threaded-scene", "Force scene tree to run in single-threaded mode. Sub-thread groups are disabled and run on the main thread.\n");
660 #ifdef DEBUG_ENABLED
661 print_help_option("--debug-collisions", "Show collision shapes when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
662 print_help_option("--debug-paths", "Show path lines when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
663 print_help_option("--debug-navigation", "Show navigation polygons when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
664 print_help_option("--debug-avoidance", "Show navigation avoidance debug visuals when running the scene.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
665 print_help_option("--debug-stringnames", "Print all StringName allocations to stdout when the engine quits.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
666 print_help_option("--debug-canvas-item-redraw", "Display a rectangle each time a canvas item requests a redraw (useful to troubleshoot low processor mode).\n", CLI_OPTION_AVAILABILITY_TEMPLATE_DEBUG);
667
668 #endif
669 print_help_option("--max-fps <fps>", "Set a maximum number of frames per second rendered (can be used to limit power usage). A value of 0 results in unlimited framerate.\n");
670 print_help_option("--frame-delay <ms>", "Simulate high CPU load (delay each frame by <ms> milliseconds). Do not use as a FPS limiter; use --max-fps instead.\n");
671 print_help_option("--time-scale <scale>", "Force time scale (higher values are faster, 1.0 is normal speed).\n");
672 print_help_option("--disable-vsync", "Forces disabling of vertical synchronization, even if enabled in the project settings. Does not override driver-level V-Sync enforcement.\n");
673 print_help_option("--disable-render-loop", "Disable render loop so rendering only occurs when called explicitly from script.\n");
674 print_help_option("--disable-crash-handler", "Disable crash handler when supported by the platform code.\n");
675 print_help_option("--fixed-fps <fps>", "Force a fixed number of frames per second. This setting disables real-time synchronization.\n");
676 print_help_option("--delta-smoothing <enable>", "Enable or disable frame delta smoothing [\"enable\", \"disable\"].\n");
677 print_help_option("--print-fps", "Print the frames per second to the stdout.\n");
678 #ifdef TOOLS_ENABLED
679 print_help_option("--editor-pseudolocalization", "Enable pseudolocalization for the editor and the project manager.\n", CLI_OPTION_AVAILABILITY_EDITOR);
680 #endif
681
682 #if defined(OVERRIDE_PATH_ENABLED) || defined(TESTS_ENABLED)
683 print_help_title("Standalone tools");
684 #endif // defined(OVERRIDE_PATH_ENABLED) || defined(TESTS_ENABLED)
685 #if defined(OVERRIDE_PATH_ENABLED)
686 print_help_option("-s, --script <script>", "Run a script.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE);
687 print_help_option("--main-loop <main_loop_name>", "Run a MainLoop specified by its global class name.\n", CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE);
688 print_help_option("--check-only", "Only parse for errors and quit (use with --script).\n", CLI_OPTION_AVAILABILITY_TEMPLATE_UNSAFE);
689 #endif // defined(OVERRIDE_PATH_ENABLED)
690 #ifdef TOOLS_ENABLED
691 print_help_option("--import", "Starts the editor, waits for any resources to be imported, and then quits.\n", CLI_OPTION_AVAILABILITY_EDITOR);
692 print_help_option("--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", CLI_OPTION_AVAILABILITY_EDITOR);
693 print_help_option("", "<path> should be absolute or relative to the project directory, and include the filename for the binary (e.g. \"builds/game.exe\").\n");
694 print_help_option("", "The target directory must exist.\n");
695 print_help_option("--export-debug <preset> <path>", "Export the project in debug mode using the given preset and output path. See --export-release description for other considerations.\n", CLI_OPTION_AVAILABILITY_EDITOR);
696 print_help_option("--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", CLI_OPTION_AVAILABILITY_EDITOR);
697 print_help_option("--export-patch <preset> <path>", "Export pack with changed files only. See --export-pack description for other considerations.\n", CLI_OPTION_AVAILABILITY_EDITOR);
698 print_help_option("--patches <paths>", "List of patches to use with --export-patch. The list is comma-separated.\n", CLI_OPTION_AVAILABILITY_EDITOR);
699 print_help_option("--install-android-build-template", "Install the Android build template. Used in conjunction with --export-release or --export-debug.\n", CLI_OPTION_AVAILABILITY_EDITOR);
700 #ifndef DISABLE_DEPRECATED
701 // Commands are long; split the description to a second line.
702 print_help_option("--convert-3to4 ", "\n", CLI_OPTION_AVAILABILITY_HIDDEN);
703 print_help_option(" [max_file_kb] [max_line_size]", "Converts project from Godot 3.x to Godot 4.x.\n", CLI_OPTION_AVAILABILITY_EDITOR);
704 print_help_option("--validate-conversion-3to4 ", "\n", CLI_OPTION_AVAILABILITY_HIDDEN);
705 print_help_option(" [max_file_kb] [max_line_size]", "Shows what elements will be renamed when converting project from Godot 3.x to Godot 4.x.\n", CLI_OPTION_AVAILABILITY_EDITOR);
706 #endif // DISABLE_DEPRECATED
707 print_help_option("--doctool [path]", "Dump the engine API reference to the given <path> (defaults to current directory) in XML format, merging if existing files are found.\n", CLI_OPTION_AVAILABILITY_EDITOR);
708 print_help_option("--no-docbase", "Disallow dumping the base types (used with --doctool).\n", CLI_OPTION_AVAILABILITY_EDITOR);
709 print_help_option("--gdextension-docs", "Rather than dumping the engine API, generate API reference from all the GDExtensions loaded in the current project (used with --doctool).\n", CLI_OPTION_AVAILABILITY_EDITOR);
710 #ifdef MODULE_GDSCRIPT_ENABLED
711 print_help_option("--gdscript-docs <path>", "Rather than dumping the engine API, generate API reference from the inline documentation in the GDScript files found in <path> (used with --doctool).\n", CLI_OPTION_AVAILABILITY_EDITOR);
712 #endif
713 print_help_option("--build-solutions", "Build the scripting solutions (e.g. for C# projects). Implies --editor and requires a valid project to edit.\n", CLI_OPTION_AVAILABILITY_EDITOR);
714 print_help_option("--dump-gdextension-interface", "Generate a GDExtension header file \"gdextension_interface.h\" in the current folder. This file is the base file required to implement a GDExtension.\n", CLI_OPTION_AVAILABILITY_EDITOR);
715 print_help_option("--dump-gdextension-interface-json", "Generate a JSON dump of the GDExtension interface named \"gdextension_interface.json\" in the current folder.\n", CLI_OPTION_AVAILABILITY_EDITOR);
716 print_help_option("--dump-extension-api", "Generate a JSON dump of the Godot API for GDExtension bindings named \"extension_api.json\" in the current folder.\n", CLI_OPTION_AVAILABILITY_EDITOR);
717 print_help_option("--dump-extension-api-with-docs", "Generate JSON dump of the Godot API like the previous option, but including documentation.\n", CLI_OPTION_AVAILABILITY_EDITOR);
718 print_help_option("--validate-extension-api <path>", "Validate an extension API file dumped (with one of the two previous options) from a previous version of the engine to ensure API compatibility.\n", CLI_OPTION_AVAILABILITY_EDITOR);
719 print_help_option("", "If incompatibilities or errors are detected, the exit code will be non-zero.\n");
720 print_help_option("--benchmark", "Benchmark the run time and print it to console.\n", CLI_OPTION_AVAILABILITY_EDITOR);
721 print_help_option("--benchmark-file <path>", "Benchmark the run time and save it to a given file in JSON format. The path should be absolute.\n", CLI_OPTION_AVAILABILITY_EDITOR);
722 #endif // TOOLS_ENABLED
723 #ifdef TESTS_ENABLED
724 print_help_option("--test [--help]", "Run unit tests. Use --test --help for more information.\n");
725 #endif // TESTS_ENABLED
726 OS::get_singleton()->print("\n");
727 }
728
729 #ifdef TESTS_ENABLED
730 // The order is the same as in `Main::setup()`, only core and some editor types
731 // are initialized here. This also combines `Main::setup2()` initialization.
732 Error Main::test_setup() {
733 Thread::make_main_thread();
734 set_current_thread_safe_for_nodes(true);
735
736 OS::get_singleton()->initialize();
737
738 CoreGlobals::print_ready = true;
739
740 engine = memnew(Engine);
741
742 register_core_types();
743 register_core_driver_types();
744
745 packed_data = memnew(PackedData);
746
747 globals = memnew(ProjectSettings);
748
749 register_core_settings(); // Here globals are present.
750
751 translation_server = memnew(TranslationServer);
752 tsman = memnew(TextServerManager);
753
754 if (tsman) {
755 Ref<TextServerDummy> ts;
756 ts.instantiate();
757 tsman->add_interface(ts);
758 }
759
760 #ifndef PHYSICS_3D_DISABLED
761 physics_server_3d_manager = memnew(PhysicsServer3DManager);
762 #endif // PHYSICS_3D_DISABLED
763 #ifndef PHYSICS_2D_DISABLED
764 physics_server_2d_manager = memnew(PhysicsServer2DManager);
765 #endif // PHYSICS_2D_DISABLED
766
767 #ifndef NAVIGATION_2D_DISABLED
768 NavigationServer2DManager::initialize_server_manager();
769 #endif // NAVIGATION_2D_DISABLED
770 #ifndef NAVIGATION_3D_DISABLED
771 NavigationServer3DManager::initialize_server_manager();
772 #endif // NAVIGATION_3D_DISABLED
773
774 // From `Main::setup2()`.
775 register_early_core_singletons();
776 initialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
777 register_core_extensions();
778
779 register_core_singletons();
780
781 /** INITIALIZE SERVERS **/
782 register_server_types();
783 #ifndef XR_DISABLED
784 XRServer::set_xr_mode(XRServer::XRMODE_OFF); // Skip in tests.
785 #endif // XR_DISABLED
786 initialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
787 GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
788
789 translation_server->setup(); //register translations, load them, etc.
790 if (!locale.is_empty()) {
791 translation_server->set_locale(locale);
792 }
793 translation_server->load_project_translations(translation_server->get_main_domain());
794 ResourceLoader::load_translation_remaps(); //load remaps for resources
795
796 // Initialize ThemeDB early so that scene types can register their theme items.
797 // Default theme will be initialized later, after modules and ScriptServer are ready.
798 initialize_theme_db();
799
800 #ifndef NAVIGATION_3D_DISABLED
801 NavigationServer3DManager::initialize_server();
802 #endif // NAVIGATION_3D_DISABLED
803 #ifndef NAVIGATION_2D_DISABLED
804 NavigationServer2DManager::initialize_server();
805 #endif // NAVIGATION_2D_DISABLED
806
807 register_scene_types();
808 register_driver_types();
809
810 register_scene_singletons();
811
812 initialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
813 GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
814
815 #ifdef TOOLS_ENABLED
816 ClassDB::set_current_api(ClassDB::API_EDITOR);
817 register_editor_types();
818
819 initialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
820 GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
821
822 ClassDB::set_current_api(ClassDB::API_CORE);
823 #endif
824 register_platform_apis();
825
826 // Theme needs modules to be initialized so that sub-resources can be loaded.
827 theme_db->initialize_theme_noproject();
828
829 ERR_FAIL_COND_V(TextServerManager::get_singleton()->get_interface_count() == 0, ERR_CANT_CREATE);
830
831 /* Use one with the most features available. */
832 int max_features = 0;
833 for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
834 uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
835 int feature_number = 0;
836 while (features) {
837 feature_number += features & 1;
838 features >>= 1;
839 }
840 if (feature_number >= max_features) {
841 max_features = feature_number;
842 text_driver_idx = i;
843 }
844 }
845 if (text_driver_idx >= 0) {
846 Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(text_driver_idx);
847 TextServerManager::get_singleton()->set_primary_interface(ts);
848 if (ts->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
849 ts->load_support_data("res://" + ts->get_support_data_filename());
850 }
851 } else {
852 ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
853 }
854
855 ClassDB::set_current_api(ClassDB::API_NONE);
856
857 _start_success = true;
858
859 return OK;
860 }
861
862 // The order is the same as in `Main::cleanup()`.
863 void Main::test_cleanup() {
864 ERR_FAIL_COND(!_start_success);
865
866 // Printing in the usual way can become problematic during/after cleanup.
867 CoreGlobals::print_ready = false;
868
869 for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
870 TextServerManager::get_singleton()->get_interface(i)->cleanup();
871 }
872
873 ResourceLoader::remove_custom_loaders();
874 ResourceSaver::remove_custom_savers();
875 PropertyListHelper::clear_base_helpers();
876
877 #ifdef TOOLS_ENABLED
878 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
879 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
880 unregister_editor_types();
881 #endif
882
883 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
884 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
885
886 unregister_platform_apis();
887 unregister_driver_types();
888 unregister_scene_types();
889
890 finalize_theme_db();
891
892 #ifndef NAVIGATION_2D_DISABLED
893 NavigationServer2DManager::finalize_server();
894 NavigationServer2DManager::finalize_server_manager();
895 #endif // NAVIGATION_2D_DISABLED
896 #ifndef NAVIGATION_3D_DISABLED
897 NavigationServer3DManager::finalize_server();
898 NavigationServer3DManager::finalize_server_manager();
899 #endif // NAVIGATION_3D_DISABLED
900
901 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
902 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
903 unregister_server_types();
904
905 EngineDebugger::deinitialize();
906 OS::get_singleton()->finalize();
907
908 if (packed_data) {
909 memdelete(packed_data);
910 }
911 if (translation_server) {
912 memdelete(translation_server);
913 }
914 if (tsman) {
915 memdelete(tsman);
916 }
917 #ifndef PHYSICS_3D_DISABLED
918 if (physics_server_3d_manager) {
919 memdelete(physics_server_3d_manager);
920 }
921 #endif // PHYSICS_3D_DISABLED
922 #ifndef PHYSICS_2D_DISABLED
923 if (physics_server_2d_manager) {
924 memdelete(physics_server_2d_manager);
925 }
926 #endif // PHYSICS_2D_DISABLED
927 if (globals) {
928 memdelete(globals);
929 }
930
931 unregister_core_driver_types();
932 unregister_core_extensions();
933 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
934
935 if (engine) {
936 memdelete(engine);
937 }
938
939 unregister_core_types();
940
941 OS::get_singleton()->finalize_core();
942 }
943 #endif
944
945 int Main::test_entrypoint(int argc, char *argv[], bool &tests_need_run) {
946 for (int x = 0; x < argc; x++) {
947 // Early return to ignore a possible user-provided "--test" argument.
948 if ((strlen(argv[x]) == 2) && ((strncmp(argv[x], "--", 2) == 0) || (strncmp(argv[x], "++", 2) == 0))) {
949 tests_need_run = false;
950 return EXIT_SUCCESS;
951 }
952 if ((strncmp(argv[x], "--test", 6) == 0) && (strlen(argv[x]) == 6)) {
953 tests_need_run = true;
954 #ifdef TESTS_ENABLED
955 // TODO: need to come up with different test contexts.
956 // Not every test requires high-level functionality like `ClassDB`.
957 test_setup();
958 int status = test_main(argc, argv);
959 test_cleanup();
960 return status;
961 #else
962 ERR_PRINT(
963 "`--test` was specified on the command line, but this Godot binary was compiled without support for unit tests. Aborting.\n"
964 "To be able to run unit tests, use the `tests=yes` SCons option when compiling Godot.\n");
965 return EXIT_FAILURE;
966 #endif
967 }
968 }
969 tests_need_run = false;
970 return EXIT_SUCCESS;
971 }
972
973 /* Engine initialization
974 *
975 * Consists of several methods that are called by each platform's specific main(argc, argv).
976 * To fully understand engine init, one should therefore start from the platform's main and
977 * see how it calls into the Main class' methods.
978 *
979 * The initialization is typically done in 3 steps (with the setup2 step triggered either
980 * automatically by setup, or manually in the platform's main).
981 *
982 * - setup(execpath, argc, argv, p_second_phase) is the main entry point for all platforms,
983 * responsible for the initialization of all low level singletons and core types, and parsing
984 * command line arguments to configure things accordingly.
985 * If p_second_phase is true, it will chain into setup2() (default behavior). This is
986 * disabled on some platforms (Android, iOS) which trigger the second step in their own time.
987 *
988 * - setup2(p_main_tid_override) registers high level servers and singletons, displays the
989 * boot splash, then registers higher level types (scene, editor, etc.).
990 *
991 * - start() is the last step and that's where command line tools can run, or the main loop
992 * can be created eventually and the project settings put into action. That's also where
993 * the editor node is created, if relevant.
994 * start() does it own argument parsing for a subset of the command line arguments described
995 * in help, it's a bit messy and should be globalized with the setup() parsing somehow.
996 */
997
998 Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
999 GodotProfileZone("setup");
1000 Thread::make_main_thread();
1001 set_current_thread_safe_for_nodes(true);
1002
1003 OS::get_singleton()->initialize();
1004
1005 CoreGlobals::print_ready = true;
1006
1007 #if !defined(OVERRIDE_PATH_ENABLED) && !defined(TOOLS_ENABLED)
1008 String old_cwd = OS::get_singleton()->get_cwd();
1009 #if defined(MACOS_ENABLED) || defined(APPLE_EMBEDDED_ENABLED)
1010 String new_cwd = OS::get_singleton()->get_bundle_resource_dir();
1011 if (new_cwd.is_empty() || !new_cwd.is_absolute_path()) {
1012 new_cwd = OS::get_singleton()->get_executable_path().get_base_dir();
1013 }
1014 #else
1015 String new_cwd = OS::get_singleton()->get_executable_path().get_base_dir();
1016 #endif
1017 if (!new_cwd.is_empty()) {
1018 OS::get_singleton()->set_cwd(new_cwd);
1019 }
1020 #endif
1021
1022 // Benchmark tracking must be done after `OS::get_singleton()->initialize()` as on some
1023 // platforms, it's used to set up the time utilities.
1024 OS::get_singleton()->benchmark_begin_measure("Startup", "Main::Setup");
1025
1026 engine = memnew(Engine);
1027
1028 MAIN_PRINT("Main: Initialize CORE");
1029
1030 register_core_types();
1031 register_core_driver_types();
1032
1033 MAIN_PRINT("Main: Initialize Globals");
1034
1035 input_map = memnew(InputMap);
1036 globals = memnew(ProjectSettings);
1037
1038 register_core_settings(); //here globals are present
1039
1040 translation_server = memnew(TranslationServer);
1041 performance = memnew(Performance);
1042 GDREGISTER_CLASS(Performance);
1043 engine->add_singleton(Engine::Singleton("Performance", performance));
1044
1045 // Only flush stdout in debug builds by default, as spamming `print()` will
1046 // decrease performance if this is enabled.
1047 GLOBAL_DEF_RST("application/run/flush_stdout_on_print", false);
1048 GLOBAL_DEF_RST("application/run/flush_stdout_on_print.debug", true);
1049
1050 MAIN_PRINT("Main: Parse CMDLine");
1051
1052 /* argument parsing and main creation */
1053 List<String> args;
1054 List<String> main_args;
1055 List<String> user_args;
1056 bool adding_user_args = false;
1057 List<String> platform_args = OS::get_singleton()->get_cmdline_platform_args();
1058
1059 // Add command line arguments.
1060 for (int i = 0; i < argc; i++) {
1061 args.push_back(String::utf8(argv[i]));
1062 }
1063
1064 // Add arguments received from macOS LaunchService (URL schemas, file associations).
1065 for (const String &arg : platform_args) {
1066 args.push_back(arg);
1067 }
1068
1069 List<String>::Element *I = args.front();
1070
1071 while (I) {
1072 I->get() = unescape_cmdline(I->get().strip_edges());
1073 I = I->next();
1074 }
1075
1076 String audio_driver = "";
1077 String project_path = ".";
1078 String debug_uri = "";
1079 #if defined(TOOLS_ENABLED) && (defined(WINDOWS_ENABLED) || defined(LINUXBSD_ENABLED))
1080 bool test_rd_creation = false;
1081 bool test_rd_support = false;
1082 #endif
1083 bool skip_breakpoints = false;
1084 bool ignore_error_breaks = false;
1085 String main_pack;
1086 bool quiet_stdout = false;
1087 int separate_thread_render = -1; // Tri-state: -1 = not set, 0 = false, 1 = true.
1088
1089 String remotefs;
1090 String remotefs_pass;
1091
1092 Vector<String> breakpoints;
1093 bool delta_smoothing_override = false;
1094 bool load_shell_env = false;
1095
1096 String default_renderer = "";
1097 String default_renderer_mobile = "";
1098 String renderer_hints = "";
1099
1100 packed_data = PackedData::get_singleton();
1101 if (!packed_data) {
1102 packed_data = memnew(PackedData);
1103 }
1104
1105 #ifdef MINIZIP_ENABLED
1106
1107 //XXX: always get_singleton() == 0x0
1108 zip_packed_data = ZipArchive::get_singleton();
1109 //TODO: remove this temporary fix
1110 if (!zip_packed_data) {
1111 zip_packed_data = memnew(ZipArchive);
1112 }
1113
1114 packed_data->add_pack_source(zip_packed_data);
1115 #endif
1116
1117 // Exit error code used in the `goto error` conditions.
1118 // It's returned as the program exit code. ERR_HELP is special cased and handled as success (0).
1119 Error exit_err = ERR_INVALID_PARAMETER;
1120
1121 I = args.front();
1122 while (I) {
1123 List<String>::Element *N = I->next();
1124
1125 const String &arg = I->get();
1126
1127 #ifdef MACOS_ENABLED
1128 // Ignore the process serial number argument passed by macOS Gatekeeper.
1129 // Otherwise, Godot would try to open a non-existent project on the first start and abort.
1130 if (arg.begins_with("-psn_")) {
1131 I = N;
1132 continue;
1133 }
1134 #endif
1135
1136 #ifdef TOOLS_ENABLED
1137 if (arg == "--debug" ||
1138 arg == "--verbose" ||
1139 arg == "--disable-crash-handler") {
1140 forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
1141 forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(arg);
1142 }
1143 if (arg == "--single-window" || arg == "--editor-pseudolocalization") {
1144 forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
1145 }
1146 if (arg == "--audio-driver" ||
1147 arg == "--display-driver" ||
1148 arg == "--rendering-method" ||
1149 arg == "--rendering-driver" ||
1150 arg == "--xr-mode" ||
1151 arg == "-l" ||
1152 arg == "--language") {
1153 if (N) {
1154 forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
1155 forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(N->get());
1156 }
1157 }
1158 // If gpu is specified, both editor and debug instances started from editor will inherit.
1159 if (arg == "--gpu-index") {
1160 if (N) {
1161 const String &next_arg = N->get();
1162 forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(arg);
1163 forwardable_cli_arguments[CLI_SCOPE_TOOL].push_back(next_arg);
1164 forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(arg);
1165 forwardable_cli_arguments[CLI_SCOPE_PROJECT].push_back(next_arg);
1166 }
1167 }
1168 #endif
1169
1170 if (adding_user_args) {
1171 user_args.push_back(arg);
1172 } else if (arg == "-h" || arg == "--help" || arg == "/?") { // display help
1173
1174 show_help = true;
1175 exit_err = ERR_HELP; // Hack to force an early exit in `main()` with a success code.
1176 goto error;
1177
1178 } else if (arg == "--version") {
1179 print_line(get_full_version_string());
1180 exit_err = ERR_HELP; // Hack to force an early exit in `main()` with a success code.
1181 goto error;
1182
1183 } else if (arg == "-v" || arg == "--verbose") { // verbose output
1184
1185 OS::get_singleton()->_verbose_stdout = true;
1186 } else if (arg == "-q" || arg == "--quiet") { // quieter output
1187
1188 quiet_stdout = true;
1189
1190 } else if (arg == "--no-header") {
1191 Engine::get_singleton()->_print_header = false;
1192
1193 } else if (arg == "--audio-driver") { // audio driver
1194
1195 if (N) {
1196 audio_driver = N->get();
1197
1198 bool found = false;
1199 for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
1200 if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
1201 found = true;
1202 }
1203 }
1204
1205 if (!found) {
1206 OS::get_singleton()->print("Unknown audio driver '%s', aborting.\nValid options are ",
1207 audio_driver.utf8().get_data());
1208
1209 for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
1210 if (i == AudioDriverManager::get_driver_count() - 1) {
1211 OS::get_singleton()->print(" and ");
1212 } else if (i != 0) {
1213 OS::get_singleton()->print(", ");
1214 }
1215
1216 OS::get_singleton()->print("'%s'", AudioDriverManager::get_driver(i)->get_name());
1217 }
1218
1219 OS::get_singleton()->print(".\n");
1220
1221 goto error;
1222 }
1223
1224 N = N->next();
1225 } else {
1226 OS::get_singleton()->print("Missing audio driver argument, aborting.\n");
1227 goto error;
1228 }
1229 } else if (arg == "--audio-output-latency") {
1230 if (N) {
1231 audio_output_latency = N->get().to_int();
1232 N = N->next();
1233 } else {
1234 OS::get_singleton()->print("Missing audio output latency argument, aborting.\n");
1235 goto error;
1236 }
1237 } else if (arg == "--text-driver") {
1238 if (N) {
1239 text_driver = N->get();
1240 N = N->next();
1241 } else {
1242 OS::get_singleton()->print("Missing text driver argument, aborting.\n");
1243 goto error;
1244 }
1245
1246 } else if (arg == "--display-driver") { // force video driver
1247
1248 if (N) {
1249 display_driver = N->get();
1250
1251 bool found = false;
1252 for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
1253 if (display_driver == DisplayServer::get_create_function_name(i)) {
1254 found = true;
1255 }
1256 }
1257
1258 if (!found) {
1259 OS::get_singleton()->print("Unknown display driver '%s', aborting.\nValid options are ",
1260 display_driver.utf8().get_data());
1261
1262 for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
1263 if (i == DisplayServer::get_create_function_count() - 1) {
1264 OS::get_singleton()->print(" and ");
1265 } else if (i != 0) {
1266 OS::get_singleton()->print(", ");
1267 }
1268
1269 OS::get_singleton()->print("'%s'", DisplayServer::get_create_function_name(i));
1270 }
1271
1272 OS::get_singleton()->print(".\n");
1273
1274 goto error;
1275 }
1276
1277 N = N->next();
1278 } else {
1279 OS::get_singleton()->print("Missing display driver argument, aborting.\n");
1280 goto error;
1281 }
1282 } else if (arg == "--rendering-method") {
1283 if (N) {
1284 rendering_method = N->get();
1285 N = N->next();
1286 } else {
1287 OS::get_singleton()->print("Missing renderer name argument, aborting.\n");
1288 goto error;
1289 }
1290 } else if (arg == "--rendering-driver") {
1291 if (N) {
1292 rendering_driver = N->get();
1293 N = N->next();
1294 } else {
1295 OS::get_singleton()->print("Missing rendering driver argument, aborting.\n");
1296 goto error;
1297 }
1298 } else if (arg == "-f" || arg == "--fullscreen") { // force fullscreen
1299 init_fullscreen = true;
1300 window_mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
1301 } else if (arg == "-m" || arg == "--maximized") { // force maximized window
1302 init_maximized = true;
1303 window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
1304 } else if (arg == "-w" || arg == "--windowed") { // force windowed window
1305
1306 init_windowed = true;
1307 } else if (arg == "--gpu-index") {
1308 if (N) {
1309 Engine::singleton->gpu_idx = N->get().to_int();
1310 N = N->next();
1311 } else {
1312 OS::get_singleton()->print("Missing GPU index argument, aborting.\n");
1313 goto error;
1314 }
1315 } else if (arg == "--gpu-validation") {
1316 Engine::singleton->use_validation_layers = true;
1317 #ifdef DEBUG_ENABLED
1318 } else if (arg == "--gpu-abort") {
1319 Engine::singleton->abort_on_gpu_errors = true;
1320 #endif
1321 } else if (arg == "--generate-spirv-debug-info") {
1322 Engine::singleton->generate_spirv_debug_info = true;
1323 #if defined(DEBUG_ENABLED) || defined(DEV_ENABLED)
1324 } else if (arg == "--extra-gpu-memory-tracking") {
1325 Engine::singleton->extra_gpu_memory_tracking = true;
1326 } else if (arg == "--accurate-breadcrumbs") {
1327 Engine::singleton->accurate_breadcrumbs = true;
1328 #endif
1329 } else if (arg == "--tablet-driver") {
1330 if (N) {
1331 tablet_driver = N->get();
1332 N = N->next();
1333 } else {
1334 OS::get_singleton()->print("Missing tablet driver argument, aborting.\n");
1335 goto error;
1336 }
1337 } else if (arg == "--delta-smoothing") {
1338 if (N) {
1339 String string = N->get();
1340 bool recognized = false;
1341 if (string == "enable") {
1342 OS::get_singleton()->set_delta_smoothing(true);
1343 delta_smoothing_override = true;
1344 recognized = true;
1345 }
1346 if (string == "disable") {
1347 OS::get_singleton()->set_delta_smoothing(false);
1348 delta_smoothing_override = false;
1349 recognized = true;
1350 }
1351 if (!recognized) {
1352 OS::get_singleton()->print("Delta-smoothing argument not recognized, aborting.\n");
1353 goto error;
1354 }
1355 N = N->next();
1356 } else {
1357 OS::get_singleton()->print("Missing delta-smoothing argument, aborting.\n");
1358 goto error;
1359 }
1360 } else if (arg == "--single-window") { // force single window
1361
1362 single_window = true;
1363 } else if (arg == "--accessibility") {
1364 if (N) {
1365 String string = N->get();
1366 if (string == "auto") {
1367 accessibility_mode = DisplayServer::AccessibilityMode::ACCESSIBILITY_AUTO;
1368 accessibility_mode_set = true;
1369 } else if (string == "always") {
1370 accessibility_mode = DisplayServer::AccessibilityMode::ACCESSIBILITY_ALWAYS;
1371 accessibility_mode_set = true;
1372 } else if (string == "disabled") {
1373 accessibility_mode = DisplayServer::AccessibilityMode::ACCESSIBILITY_DISABLED;
1374 accessibility_mode_set = true;
1375 } else {
1376 OS::get_singleton()->print("Accessibility mode argument not recognized, aborting.\n");
1377 goto error;
1378 }
1379 N = N->next();
1380 } else {
1381 OS::get_singleton()->print("Missing accessibility mode argument, aborting.\n");
1382 goto error;
1383 }
1384 } else if (arg == "-t" || arg == "--always-on-top") { // force always-on-top window
1385
1386 init_always_on_top = true;
1387 } else if (arg == "--resolution") { // force resolution
1388
1389 if (N) {
1390 String vm = N->get();
1391
1392 if (!vm.contains_char('x')) { // invalid parameter format
1393
1394 OS::get_singleton()->print("Invalid resolution '%s', it should be e.g. '1280x720'.\n",
1395 vm.utf8().get_data());
1396 goto error;
1397 }
1398
1399 int w = vm.get_slicec('x', 0).to_int();
1400 int h = vm.get_slicec('x', 1).to_int();
1401
1402 if (w <= 0 || h <= 0) {
1403 OS::get_singleton()->print("Invalid resolution '%s', width and height must be above 0.\n",
1404 vm.utf8().get_data());
1405 goto error;
1406 }
1407
1408 window_size.width = w;
1409 window_size.height = h;
1410 force_res = true;
1411
1412 N = N->next();
1413 } else {
1414 OS::get_singleton()->print("Missing resolution argument, aborting.\n");
1415 goto error;
1416 }
1417
1418 } else if (arg == "--screen") { // set window screen
1419
1420 if (N) {
1421 init_screen = N->get().to_int();
1422 init_use_custom_screen = true;
1423
1424 N = N->next();
1425 } else {
1426 OS::get_singleton()->print("Missing screen argument, aborting.\n");
1427 goto error;
1428 }
1429
1430 } else if (arg == "--position") { // set window position
1431
1432 if (N) {
1433 String vm = N->get();
1434
1435 if (!vm.contains_char(',')) { // invalid parameter format
1436
1437 OS::get_singleton()->print("Invalid position '%s', it should be e.g. '80,128'.\n",
1438 vm.utf8().get_data());
1439 goto error;
1440 }
1441
1442 int x = vm.get_slicec(',', 0).to_int();
1443 int y = vm.get_slicec(',', 1).to_int();
1444
1445 init_custom_pos = Point2(x, y);
1446 init_use_custom_pos = true;
1447
1448 N = N->next();
1449 } else {
1450 OS::get_singleton()->print("Missing position argument, aborting.\n");
1451 goto error;
1452 }
1453
1454 } else if (arg == "--headless") { // enable headless mode (no audio, no rendering).
1455
1456 audio_driver = NULL_AUDIO_DRIVER;
1457 display_driver = NULL_DISPLAY_DRIVER;
1458
1459 } else if (arg == "--embedded") { // Enable embedded mode.
1460 #ifdef MACOS_ENABLED
1461 display_driver = EMBEDDED_DISPLAY_DRIVER;
1462 #else
1463 OS::get_singleton()->print("--embedded is only supported on macOS, aborting.\n");
1464 goto error;
1465 #endif
1466 } else if (arg == "--log-file") { // write to log file
1467
1468 if (N) {
1469 log_file = N->get();
1470 N = N->next();
1471 } else {
1472 OS::get_singleton()->print("Missing log file path argument, aborting.\n");
1473 goto error;
1474 }
1475 } else if (arg == "--profiling") { // enable profiling
1476
1477 use_debug_profiler = true;
1478
1479 } else if (arg == "-l" || arg == "--language") { // language
1480
1481 if (N) {
1482 locale = N->get();
1483 N = N->next();
1484 } else {
1485 OS::get_singleton()->print("Missing language argument, aborting.\n");
1486 goto error;
1487 }
1488 } else if (arg == "--remote-fs") { // remote filesystem
1489
1490 #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
1491 if (N) {
1492 remotefs = N->get();
1493 N = N->next();
1494 } else {
1495 OS::get_singleton()->print("Missing remote filesystem address, aborting.\n");
1496 goto error;
1497 }
1498 #else
1499 ERR_PRINT(
1500 "`--remote-fs` was specified on the command line, but this Godot binary was compiled without debug. Aborting.\n"
1501 "To be able to use it, use the `target=template_debug` SCons option when compiling Godot.\n");
1502 #endif // defined(DEBUG_ENABLED) || defined (TOOLS_ENABLED)
1503 } else if (arg == "--remote-fs-password") { // remote filesystem password
1504
1505 #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
1506 if (N) {
1507 remotefs_pass = N->get();
1508 N = N->next();
1509 } else {
1510 OS::get_singleton()->print("Missing remote filesystem password, aborting.\n");
1511 goto error;
1512 }
1513 #else
1514 ERR_PRINT(
1515 "`--remote-fs-password` was specified on the command line, but this Godot binary was compiled without debug. Aborting.\n"
1516 "To be able to use it, use the `target=template_debug` SCons option when compiling Godot.\n");
1517 goto error;
1518 #endif // defined(DEBUG_ENABLED) || defined (TOOLS_ENABLED)
1519 } else if (arg == "--render-thread") { // render thread mode
1520
1521 if (N) {
1522 if (N->get() == "safe") {
1523 separate_thread_render = 0;
1524 #ifndef DISABLE_DEPRECATED
1525 } else if (N->get() == "unsafe") {
1526 OS::get_singleton()->print("The --render-thread unsafe option is unsupported in Godot 4 and will be removed.\n");
1527 separate_thread_render = 0;
1528 #endif
1529 } else if (N->get() == "separate") {
1530 separate_thread_render = 1;
1531 } else {
1532 OS::get_singleton()->print("Unknown render thread mode, aborting.\n");
1533 #ifdef DISABLE_DEPRECATED
1534 OS::get_singleton()->print("Valid options are 'safe' and 'separate'.\n");
1535 #else
1536 OS::get_singleton()->print("Valid options are 'unsafe', 'safe' and 'separate'.\n");
1537 #endif
1538 goto error;
1539 }
1540
1541 N = N->next();
1542 } else {
1543 OS::get_singleton()->print("Missing render thread mode argument, aborting.\n");
1544 goto error;
1545 }
1546 #ifdef TOOLS_ENABLED
1547 } else if (arg == "-e" || arg == "--editor") { // starts editor
1548
1549 editor = true;
1550 } else if (arg == "-p" || arg == "--project-manager") { // starts project manager
1551 project_manager = true;
1552 } else if (arg == "--recovery-mode") { // Enables recovery mode.
1553 recovery_mode = true;
1554 } else if (arg == "--debug-server") {
1555 if (N) {
1556 debug_server_uri = N->get();
1557 if (!debug_server_uri.contains("://")) { // wrong address
1558 OS::get_singleton()->print("Invalid debug server uri. It should be of the form <protocol>://<bind_address>:<port>.\n");
1559 goto error;
1560 }
1561 N = N->next();
1562 } else {
1563 OS::get_singleton()->print("Missing remote debug server uri, aborting.\n");
1564 goto error;
1565 }
1566 } else if (arg == "--single-threaded-scene") {
1567 single_threaded_scene = true;
1568 } else if (arg == "--build-solutions") { // Build the scripting solution such C#
1569
1570 auto_build_solutions = true;
1571 editor = true;
1572 cmdline_tool = true;
1573 } else if (arg == "--dump-gdextension-interface") {
1574 // Register as an editor instance to use low-end fallback if relevant.
1575 editor = true;
1576 cmdline_tool = true;
1577 dump_gdextension_interface_header = true;
1578 print_line("Dumping GDExtension interface header file");
1579 // Hack. Not needed but otherwise we end up detecting that this should
1580 // run the project instead of a cmdline tool.
1581 // Needs full refactoring to fix properly.
1582 main_args.push_back(arg);
1583 } else if (arg == "--dump-gdextension-interface-json") {
1584 // Register as an editor instance to use low-end fallback if relevant.
1585 editor = true;
1586 cmdline_tool = true;
1587 dump_gdextension_interface = true;
1588 print_line("Dumping GDExtension interface json file");
1589 // Hack. Not needed but otherwise we end up detecting that this should
1590 // run the project instead of a cmdline tool.
1591 // Needs full refactoring to fix properly.
1592 main_args.push_back(arg);
1593 } else if (arg == "--dump-extension-api") {
1594 // Register as an editor instance to use low-end fallback if relevant.
1595 editor = true;
1596 cmdline_tool = true;
1597 dump_extension_api = true;
1598 print_line("Dumping Extension API");
1599 // Hack. Not needed but otherwise we end up detecting that this should
1600 // run the project instead of a cmdline tool.
1601 // Needs full refactoring to fix properly.
1602 main_args.push_back(arg);
1603 } else if (arg == "--dump-extension-api-with-docs") {
1604 // Register as an editor instance to use low-end fallback if relevant.
1605 editor = true;
1606 cmdline_tool = true;
1607 dump_extension_api = true;
1608 include_docs_in_extension_api_dump = true;
1609 print_line("Dumping Extension API including documentation");
1610 // Hack. Not needed but otherwise we end up detecting that this should
1611 // run the project instead of a cmdline tool.
1612 // Needs full refactoring to fix properly.
1613 main_args.push_back(arg);
1614 } else if (arg == "--validate-extension-api") {
1615 // Register as an editor instance to use low-end fallback if relevant.
1616 editor = true;
1617 cmdline_tool = true;
1618 validate_extension_api = true;
1619 // Hack. Not needed but otherwise we end up detecting that this should
1620 // run the project instead of a cmdline tool.
1621 // Needs full refactoring to fix properly.
1622 main_args.push_back(arg);
1623
1624 if (N) {
1625 validate_extension_api_file = N->get();
1626
1627 N = N->next();
1628 } else {
1629 OS::get_singleton()->print("Missing file to load argument after --validate-extension-api, aborting.");
1630 goto error;
1631 }
1632 } else if (arg == "--import") {
1633 editor = true;
1634 cmdline_tool = true;
1635 wait_for_import = true;
1636 quit_after = 1;
1637 } else if (arg == "--export-release" || arg == "--export-debug" ||
1638 arg == "--export-pack" || arg == "--export-patch") { // Export project
1639 // Actually handling is done in start().
1640 editor = true;
1641 cmdline_tool = true;
1642 wait_for_import = true;
1643 main_args.push_back(arg);
1644 } else if (arg == "--patches") {
1645 if (N) {
1646 // Actually handling is done in start().
1647 main_args.push_back(arg);
1648 main_args.push_back(N->get());
1649
1650 N = N->next();
1651 } else {
1652 OS::get_singleton()->print("Missing comma-separated list of patches after --patches, aborting.\n");
1653 goto error;
1654 }
1655 #ifndef DISABLE_DEPRECATED
1656 } else if (arg == "--export") { // For users used to 3.x syntax.
1657 OS::get_singleton()->print("The Godot 3 --export option was changed to more explicit --export-release / --export-debug / --export-pack options.\nSee the --help output for details.\n");
1658 goto error;
1659 } else if (arg == "--convert-3to4") {
1660 // Actually handling is done in start().
1661 cmdline_tool = true;
1662 main_args.push_back(arg);
1663
1664 if (N && !N->get().begins_with("-")) {
1665 if (itos(N->get().to_int()) == N->get()) {
1666 converter_max_kb_file = N->get().to_int();
1667 }
1668 if (N->next() && !N->next()->get().begins_with("-")) {
1669 if (itos(N->next()->get().to_int()) == N->next()->get()) {
1670 converter_max_line_length = N->next()->get().to_int();
1671 }
1672 }
1673 }
1674 } else if (arg == "--validate-conversion-3to4") {
1675 // Actually handling is done in start().
1676 cmdline_tool = true;
1677 main_args.push_back(arg);
1678
1679 if (N && !N->get().begins_with("-")) {
1680 if (itos(N->get().to_int()) == N->get()) {
1681 converter_max_kb_file = N->get().to_int();
1682 }
1683 if (N->next() && !N->next()->get().begins_with("-")) {
1684 if (itos(N->next()->get().to_int()) == N->next()->get()) {
1685 converter_max_line_length = N->next()->get().to_int();
1686 }
1687 }
1688 }
1689 #endif // DISABLE_DEPRECATED
1690 } else if (arg == "--doctool") {
1691 // Actually handling is done in start().
1692 cmdline_tool = true;
1693
1694 // `--doctool` implies `--headless` to avoid spawning an unnecessary window
1695 // and speed up class reference generation.
1696 audio_driver = NULL_AUDIO_DRIVER;
1697 display_driver = NULL_DISPLAY_DRIVER;
1698 main_args.push_back(arg);
1699 #ifdef MODULE_GDSCRIPT_ENABLED
1700 } else if (arg == "--gdscript-docs") {
1701 if (N) {
1702 project_path = N->get();
1703 // Will be handled in start()
1704 main_args.push_back(arg);
1705 main_args.push_back(N->get());
1706 N = N->next();
1707 // GDScript docgen requires Autoloads, but loading those also creates a main loop.
1708 // This forces main loop to quit without adding more GDScript-specific exceptions to setup.
1709 quit_after = 1;
1710 } else {
1711 OS::get_singleton()->print("Missing relative or absolute path to project for --gdscript-docs, aborting.\n");
1712 goto error;
1713 }
1714 #endif // MODULE_GDSCRIPT_ENABLED
1715 #endif // TOOLS_ENABLED
1716
1717 } else if (arg == "--path") { // set path of project to start or edit
1718 #if defined(OVERRIDE_PATH_ENABLED)
1719 if (N) {
1720 String p = N->get();
1721 if (OS::get_singleton()->set_cwd(p) != OK) {
1722 OS::get_singleton()->print("Invalid project path specified: \"%s\", aborting.\n", p.utf8().get_data());
1723 goto error;
1724 }
1725 N = N->next();
1726 } else {
1727 OS::get_singleton()->print("Missing relative or absolute path, aborting.\n");
1728 goto error;
1729 }
1730 #else
1731 ERR_PRINT(
1732 "`--path` was specified on the command line, but this Godot binary was compiled without support for path overrides. Aborting.\n"
1733 "To be able to use it, use the `disable_path_overrides=no` SCons option when compiling Godot.\n");
1734 goto error;
1735 #endif // defined(OVERRIDE_PATH_ENABLED)
1736 } else if (arg == "--quit") { // Auto quit at the end of the first main loop iteration
1737 quit_after = 1;
1738 #ifdef TOOLS_ENABLED
1739 wait_for_import = true;
1740 #endif
1741 } else if (arg == "--quit-after") { // Quit after the given number of iterations
1742 if (N) {
1743 quit_after = N->get().to_int();
1744 N = N->next();
1745 } else {
1746 OS::get_singleton()->print("Missing number of iterations, aborting.\n");
1747 goto error;
1748 }
1749 } else if (arg.ends_with("project.godot")) {
1750 #if defined(OVERRIDE_PATH_ENABLED)
1751 String path;
1752 String file = arg;
1753 int sep = MAX(file.rfind_char('/'), file.rfind_char('\\'));
1754 if (sep == -1) {
1755 path = ".";
1756 } else {
1757 path = file.substr(0, sep);
1758 }
1759 if (OS::get_singleton()->set_cwd(path) == OK) {
1760 // path already specified, don't override
1761 } else {
1762 project_path = path;
1763 }
1764 #ifdef TOOLS_ENABLED
1765 editor = true;
1766 #endif
1767 #else
1768 ERR_PRINT(
1769 "`project.godot` path was specified on the command line, but this Godot binary was compiled without support for path overrides. Aborting.\n"
1770 "To be able to use it, use the `disable_path_overrides=no` SCons option when compiling Godot.\n");
1771 goto error;
1772 #endif // defined(OVERRIDE_PATH_ENABLED)
1773 } else if (arg == "-b" || arg == "--breakpoints") { // add breakpoints
1774
1775 if (N) {
1776 String bplist = N->get();
1777 breakpoints = bplist.split(",");
1778 N = N->next();
1779 } else {
1780 OS::get_singleton()->print("Missing list of breakpoints, aborting.\n");
1781 goto error;
1782 }
1783
1784 } else if (arg == "--max-fps") { // set maximum rendered FPS
1785
1786 if (N) {
1787 max_fps = N->get().to_int();
1788 N = N->next();
1789 } else {
1790 OS::get_singleton()->print("Missing maximum FPS argument, aborting.\n");
1791 goto error;
1792 }
1793
1794 } else if (arg == "--frame-delay") { // force frame delay
1795
1796 if (N) {
1797 frame_delay = N->get().to_int();
1798 N = N->next();
1799 } else {
1800 OS::get_singleton()->print("Missing frame delay argument, aborting.\n");
1801 goto error;
1802 }
1803
1804 } else if (arg == "--time-scale") { // force time scale
1805
1806 if (N) {
1807 Engine::get_singleton()->set_time_scale(N->get().to_float());
1808 N = N->next();
1809 } else {
1810 OS::get_singleton()->print("Missing time scale argument, aborting.\n");
1811 goto error;
1812 }
1813 } else if (arg == "--main-pack") {
1814 // Note: main-pack is always used on web and can't be disabled.
1815 // Note: main-pack can be used on Android so long as it's located within the 'assets' directory which is in the executable.
1816 #if defined(OVERRIDE_PATH_ENABLED) || defined(WEB_ENABLED) || defined(ANDROID_ENABLED)
1817 if (N) {
1818 main_pack = N->get();
1819 N = N->next();
1820
1821 #if defined(ANDROID_ENABLED) && !defined(OVERRIDE_PATH_ENABLED)
1822 // Validate that `main_pack` is located within the 'assets' directory.
1823 Ref<FileAccess> main_pack_fa = FileAccess::create_for_path(main_pack);
1824 if (main_pack_fa.is_valid()) {
1825 if (main_pack_fa->get_access_type() != FileAccess::ACCESS_RESOURCES) {
1826 ERR_PRINT(
1827 "--main-pack is attempting to load from outside of the executable, but this Godot binary was compiled without support for path overrides. Aborting.\n"
1828 "To be able to use it, use the `disable_path_overrides=no` SCons option when compiling Godot.\n");
1829 goto error;
1830 }
1831 } else {
1832 ERR_PRINT("Invalid path to main pack file, aborting.\n");
1833 goto error;
1834 }
1835 #endif // defined(ANDROID_ENABLED) && !defined(OVERRIDE_PATH_ENABLED)
1836 } else {
1837 OS::get_singleton()->print("Missing path to main pack file, aborting.\n");
1838 goto error;
1839 }
1840 #else
1841 ERR_PRINT(
1842 "`--main-pack` was specified on the command line, but this Godot binary was compiled without support for path overrides. Aborting.\n"
1843 "To be able to use it, use the `disable_path_overrides=no` SCons option when compiling Godot.\n");
1844 goto error;
1845 #endif // defined(OVERRIDE_PATH_ENABLED) || defined(WEB_ENABLED) || defined(ANDROID_ENABLED)
1846
1847 } else if (arg == "-d" || arg == "--debug") {
1848 debug_uri = "local://";
1849 OS::get_singleton()->_debug_stdout = true;
1850 #if defined(DEBUG_ENABLED)
1851 } else if (arg == "--debug-collisions") {
1852 debug_collisions = true;
1853 } else if (arg == "--debug-paths") {
1854 debug_paths = true;
1855 } else if (arg == "--debug-navigation") {
1856 debug_navigation = true;
1857 } else if (arg == "--debug-avoidance") {
1858 debug_avoidance = true;
1859 } else if (arg == "--debug-canvas-item-redraw") {
1860 debug_canvas_item_redraw = true;
1861 } else if (arg == "--debug-stringnames") {
1862 StringName::set_debug_stringnames(true);
1863 } else if (arg == "--debug-mute-audio") {
1864 debug_mute_audio = true;
1865 #endif // defined(DEBUG_ENABLED)
1866 #if defined(TOOLS_ENABLED) && (defined(WINDOWS_ENABLED) || defined(LINUXBSD_ENABLED))
1867 } else if (arg == "--test-rd-support") {
1868 test_rd_support = true;
1869 } else if (arg == "--test-rd-creation") {
1870 test_rd_creation = true;
1871 #endif // defined(TOOLS_ENABLED) && (defined(WINDOWS_ENABLED) || defined(LINUXBSD_ENABLED))
1872 } else if (arg == "--remote-debug") {
1873 #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
1874 if (N) {
1875 debug_uri = N->get();
1876 if (!debug_uri.contains("://")) { // wrong address
1877 OS::get_singleton()->print(
1878 "Invalid debug host address, it should be of the form <protocol>://<host/IP>:<port>.\n");
1879 goto error;
1880 }
1881 N = N->next();
1882 } else {
1883 OS::get_singleton()->print("Missing remote debug host address, aborting.\n");
1884 goto error;
1885 }
1886 #else
1887 ERR_PRINT(
1888 "`--remote-debug` was specified on the command line, but this Godot binary was compiled without debug. Aborting.\n"
1889 "To be able to use it, use the `target=template_debug` SCons option when compiling Godot.\n");
1890 goto error;
1891 #endif // defined(DEBUG_ENABLED) || defined (TOOLS_ENABLED)
1892 } else if (arg == "--editor-pid") { // not exposed to user
1893 if (N) {
1894 editor_pid = N->get().to_int();
1895 N = N->next();
1896 } else {
1897 OS::get_singleton()->print("Missing editor PID argument, aborting.\n");
1898 goto error;
1899 }
1900 } else if (arg == "--disable-render-loop") {
1901 disable_render_loop = true;
1902 } else if (arg == "--fixed-fps") {
1903 if (N) {
1904 fixed_fps = N->get().to_int();
1905 N = N->next();
1906 } else {
1907 OS::get_singleton()->print("Missing fixed-fps argument, aborting.\n");
1908 goto error;
1909 }
1910 } else if (arg == "--write-movie") {
1911 if (N) {
1912 Engine::get_singleton()->set_write_movie_path(N->get());
1913 N = N->next();
1914 if (fixed_fps == -1) {
1915 fixed_fps = 60;
1916 }
1917 OS::get_singleton()->_writing_movie = true;
1918 } else {
1919 OS::get_singleton()->print("Missing write-movie argument, aborting.\n");
1920 goto error;
1921 }
1922 } else if (arg == "--disable-vsync") {
1923 disable_vsync = true;
1924 } else if (arg == "--print-fps") {
1925 print_fps = true;
1926 #ifdef TOOLS_ENABLED
1927 } else if (arg == "--editor-pseudolocalization") {
1928 editor_pseudolocalization = true;
1929 main_args.push_back(arg);
1930 #endif // TOOLS_ENABLED
1931 } else if (arg == "--gpu-profile") {
1932 profile_gpu = true;
1933 } else if (arg == "--disable-crash-handler") {
1934 OS::get_singleton()->disable_crash_handler();
1935 } else if (arg == "--skip-breakpoints") {
1936 skip_breakpoints = true;
1937 } else if (I->get() == "--ignore-error-breaks") {
1938 ignore_error_breaks = true;
1939 #ifndef XR_DISABLED
1940 } else if (arg == "--xr-mode") {
1941 if (N) {
1942 String xr_mode = N->get().to_lower();
1943 N = N->next();
1944 if (xr_mode == "default") {
1945 XRServer::set_xr_mode(XRServer::XRMODE_DEFAULT);
1946 } else if (xr_mode == "off") {
1947 XRServer::set_xr_mode(XRServer::XRMODE_OFF);
1948 } else if (xr_mode == "on") {
1949 XRServer::set_xr_mode(XRServer::XRMODE_ON);
1950 } else {
1951 OS::get_singleton()->print("Unknown --xr-mode argument \"%s\", aborting.\n", xr_mode.ascii().get_data());
1952 goto error;
1953 }
1954 } else {
1955 OS::get_singleton()->print("Missing --xr-mode argument, aborting.\n");
1956 goto error;
1957 }
1958 #endif // XR_DISABLED
1959 } else if (arg == "--benchmark") {
1960 OS::get_singleton()->set_use_benchmark(true);
1961 } else if (arg == "--benchmark-file") {
1962 if (N) {
1963 OS::get_singleton()->set_use_benchmark(true);
1964 String benchmark_file = N->get();
1965 OS::get_singleton()->set_benchmark_file(benchmark_file);
1966 N = N->next();
1967 } else {
1968 OS::get_singleton()->print("Missing <path> argument for --benchmark-file <path>.\n");
1969 goto error;
1970 }
1971 #if defined(TOOLS_ENABLED) && defined(MODULE_GDSCRIPT_ENABLED) && !defined(GDSCRIPT_NO_LSP)
1972 } else if (arg == "--lsp-port") {
1973 if (N) {
1974 int port_override = N->get().to_int();
1975 if (port_override < 0 || port_override > 65535) {
1976 OS::get_singleton()->print("<port> argument for --lsp-port <port> must be between 0 and 65535.\n");
1977 goto error;
1978 }
1979 GDScriptLanguageServer::port_override = port_override;
1980 N = N->next();
1981 } else {
1982 OS::get_singleton()->print("Missing <port> argument for --lsp-port <port>.\n");
1983 goto error;
1984 }
1985 #endif // TOOLS_ENABLED && MODULE_GDSCRIPT_ENABLED && !GDSCRIPT_NO_LSP
1986 #if defined(TOOLS_ENABLED)
1987 } else if (arg == "--dap-port") {
1988 if (N) {
1989 int port_override = N->get().to_int();
1990 if (port_override < 0 || port_override > 65535) {
1991 OS::get_singleton()->print("<port> argument for --dap-port <port> must be between 0 and 65535.\n");
1992 goto error;
1993 }
1994 DebugAdapterServer::port_override = port_override;
1995 N = N->next();
1996 } else {
1997 OS::get_singleton()->print("Missing <port> argument for --dap-port <port>.\n");
1998 goto error;
1999 }
2000 #endif // TOOLS_ENABLED
2001 } else if (arg == "--wid") {
2002 if (N) {
2003 init_embed_parent_window_id = N->get().to_int();
2004 if (init_embed_parent_window_id == 0) {
2005 OS::get_singleton()->print("<window_id> argument for --wid <window_id> must be different then 0.\n");
2006 goto error;
2007 }
2008
2009 OS::get_singleton()->_embedded_in_editor = true;
2010 Engine::get_singleton()->set_embedded_in_editor(true);
2011
2012 N = N->next();
2013 } else {
2014 OS::get_singleton()->print("Missing <window_id> argument for --wid <window_id>.\n");
2015 goto error;
2016 }
2017
2018 } else if (arg == "--" || arg == "++") {
2019 adding_user_args = true;
2020 } else {
2021 main_args.push_back(arg);
2022 }
2023
2024 I = N;
2025 }
2026
2027 #ifdef TOOLS_ENABLED
2028 if (editor && project_manager) {
2029 OS::get_singleton()->print(
2030 "Error: Command line arguments implied opening both editor and project manager, which is not possible. Aborting.\n");
2031 goto error;
2032 }
2033 #endif
2034
2035 #if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
2036 // Network file system needs to be configured before globals, since globals are based on the
2037 // 'project.godot' file which will only be available through the network if this is enabled
2038 if (!remotefs.is_empty()) {
2039 int port;
2040 if (remotefs.contains_char(':')) {
2041 port = remotefs.get_slicec(':', 1).to_int();
2042 remotefs = remotefs.get_slicec(':', 0);
2043 } else {
2044 port = 6010;
2045 }
2046 Error err = OS::get_singleton()->setup_remote_filesystem(remotefs, port, remotefs_pass, project_path);
2047
2048 if (err) {
2049 OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i.\n", remotefs.utf8().get_data(), port);
2050 goto error;
2051 }
2052 }
2053 #endif // defined(DEBUG_ENABLED) || defined (TOOLS_ENABLED)
2054
2055 OS::get_singleton()->_in_editor = editor;
2056 if (globals->setup(project_path, main_pack, false, editor) == OK) {
2057 #ifdef TOOLS_ENABLED
2058 found_project = true;
2059 #endif
2060 } else {
2061 #ifdef TOOLS_ENABLED
2062 editor = false;
2063 #else
2064 String error_msg = "Error: Couldn't load project data at path \"" + (project_path == "." ? OS::get_singleton()->get_cwd() : project_path) + "\". Is the .pck file missing?\n\n";
2065 #if !defined(OVERRIDE_PATH_ENABLED) && !defined(TOOLS_ENABLED)
2066 String exec_path = OS::get_singleton()->get_executable_path();
2067 String exec_basename = exec_path.get_file().get_basename();
2068
2069 if (FileAccess::exists(old_cwd.path_join(exec_basename + ".pck"))) {
2070 error_msg += "\"" + exec_basename + ".pck\" was found in the current working directory. To be able to load a project from the CWD, use the `disable_path_overrides=no` SCons option when compiling Godot.\n";
2071 } else if (FileAccess::exists(old_cwd.path_join("project.godot"))) {
2072 error_msg += "\"project.godot\" was found in the current working directory. To be able to load a project from the CWD, use the `disable_path_overrides=no` SCons option when compiling Godot.\n";
2073 } else {
2074 error_msg += "If you've renamed the executable, the associated .pck file should also be renamed to match the executable's name (without the extension).\n";
2075 }
2076 #else
2077 error_msg += "If you've renamed the executable, the associated .pck file should also be renamed to match the executable's name (without the extension).\n";
2078 #endif
2079 ERR_PRINT(error_msg);
2080
2081 OS::get_singleton()->alert(error_msg);
2082
2083 goto error;
2084 #endif
2085 }
2086
2087 // Initialize WorkerThreadPool.
2088 {
2089 #ifdef THREADS_ENABLED
2090 if (editor || project_manager) {
2091 WorkerThreadPool::get_singleton()->init(-1, 0.75);
2092 } else {
2093 int worker_threads = GLOBAL_GET("threading/worker_pool/max_threads");
2094 float low_priority_ratio = GLOBAL_GET("threading/worker_pool/low_priority_thread_ratio");
2095 WorkerThreadPool::get_singleton()->init(worker_threads, low_priority_ratio);
2096 }
2097 #else
2098 WorkerThreadPool::get_singleton()->init(0, 0);
2099 #endif
2100 }
2101
2102 #ifdef TOOLS_ENABLED
2103 if (!project_manager && !editor) {
2104 // If we didn't find a project, we fall back to the project manager.
2105 project_manager = !found_project && !cmdline_tool;
2106 }
2107
2108 {
2109 // Synced with https://github.com/baldurk/renderdoc/blob/2b01465c7/renderdoc/driver/vulkan/vk_layer.cpp#L118-L165
2110 LocalVector<String> layers_to_disable = {
2111 "DISABLE_RTSS_LAYER", // GH-57937.
2112 "DISABLE_VULKAN_OBS_CAPTURE", // GH-103800.
2113 "DISABLE_VULKAN_OW_OBS_CAPTURE", // GH-104154.
2114 "DISABLE_SAMPLE_LAYER", // GH-104154.
2115 "DISABLE_GAMEPP_LAYER", // GH-104154.
2116 "DISABLE_VK_LAYER_TENCENT_wegame_cross_overlay_1", // GH-104154.
2117 // "NODEVICE_SELECT", // Kept as it's useful - GH-104592.
2118 "VK_LAYER_bandicam_helper_DEBUG_1", // GH-101480.
2119 "DISABLE_VK_LAYER_bandicam_helper_1", // GH-101480.
2120 "DISABLE_VK_LAYER_reshade_1", // GH-70849.
2121 "DISABLE_VK_LAYER_GPUOpen_GRS", // GH-104154.
2122 "DISABLE_LAYER", // GH-104154 (fpsmon).
2123 "DISABLE_MANGOHUD", // GH-57403.
2124 "DISABLE_VKBASALT",
2125 "DISABLE_FOSSILIZE", // GH-115139.
2126 };
2127
2128 #if defined(WINDOWS_ENABLED) || defined(LINUXBSD_ENABLED)
2129 if (editor || project_manager || test_rd_support || test_rd_creation) {
2130 #else
2131 if (editor || project_manager) {
2132 #endif
2133 // Disable Vulkan overlays in editor, they cause various issues.
2134 for (const String &layer_disable : layers_to_disable) {
2135 OS::get_singleton()->set_environment(layer_disable, "1");
2136 }
2137 } else {
2138 // Re-allow using Vulkan overlays, disabled while using the editor.
2139 for (const String &layer_disable : layers_to_disable) {
2140 OS::get_singleton()->unset_environment(layer_disable);
2141 }
2142 }
2143 }
2144 #endif
2145
2146 #if defined(TOOLS_ENABLED) && (defined(WINDOWS_ENABLED) || defined(LINUXBSD_ENABLED))
2147 if (test_rd_support) {
2148 // Test Rendering Device creation and exit.
2149
2150 OS::get_singleton()->set_crash_handler_silent();
2151 if (OS::get_singleton()->_test_create_rendering_device(display_driver)) {
2152 exit_err = ERR_HELP;
2153 } else {
2154 exit_err = ERR_UNAVAILABLE;
2155 }
2156 goto error;
2157 } else if (test_rd_creation) {
2158 // Test OpenGL context and Rendering Device simultaneous creation and exit.
2159
2160 OS::get_singleton()->set_crash_handler_silent();
2161 if (OS::get_singleton()->_test_create_rendering_device_and_gl(display_driver)) {
2162 exit_err = ERR_HELP;
2163 } else {
2164 exit_err = ERR_UNAVAILABLE;
2165 }
2166 goto error;
2167 }
2168 #endif
2169
2170 #ifdef TOOLS_ENABLED
2171 if (editor) {
2172 Engine::get_singleton()->set_editor_hint(true);
2173 Engine::get_singleton()->set_extension_reloading_enabled(true);
2174
2175 // Create initialization lock file to detect crashes during startup.
2176 OS::get_singleton()->create_lock_file();
2177
2178 main_args.push_back("--editor");
2179 if (!init_windowed && !init_fullscreen) {
2180 init_maximized = true;
2181 window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
2182 }
2183 }
2184
2185 if (project_manager) {
2186 Engine::get_singleton()->set_project_manager_hint(true);
2187 }
2188
2189 if (recovery_mode) {
2190 if (project_manager || !editor) {
2191 OS::get_singleton()->print("Error: Recovery mode can only be used in the editor. Aborting.\n");
2192 goto error;
2193 }
2194
2195 Engine::get_singleton()->set_recovery_mode_hint(true);
2196 }
2197 #endif
2198
2199 OS::get_singleton()->set_cmdline(execpath, main_args, user_args);
2200
2201 Engine::get_singleton()->set_physics_ticks_per_second(GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "physics/common/physics_ticks_per_second", PROPERTY_HINT_RANGE, "1,1000,1"), 60));
2202 Engine::get_singleton()->set_max_physics_steps_per_frame(GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "physics/common/max_physics_steps_per_frame", PROPERTY_HINT_RANGE, "1,100,1"), 8));
2203 Engine::get_singleton()->set_physics_jitter_fix(GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "physics/common/physics_jitter_fix", PROPERTY_HINT_RANGE, "0,2,0.001,or_greater"), 0.5));
2204 Engine::get_singleton()->set_max_fps(GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/max_fps", PROPERTY_HINT_RANGE, "0,1000,1"), 0));
2205 if (max_fps >= 0) {
2206 Engine::get_singleton()->set_max_fps(max_fps);
2207 }
2208
2209 // Initialize user data dir.
2210 OS::get_singleton()->ensure_user_data_dir();
2211
2212 OS::get_singleton()->set_low_processor_usage_mode(GLOBAL_DEF("application/run/low_processor_mode", false));
2213 OS::get_singleton()->set_low_processor_usage_mode_sleep_usec(
2214 GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/low_processor_mode_sleep_usec", PROPERTY_HINT_RANGE, "0,33200,1,or_greater"), 6900)); // Roughly 144 FPS
2215
2216 GLOBAL_DEF("application/run/delta_smoothing", true);
2217 if (!delta_smoothing_override) {
2218 OS::get_singleton()->set_delta_smoothing(GLOBAL_GET("application/run/delta_smoothing"));
2219 }
2220
2221 GLOBAL_DEF("debug/settings/stdout/print_fps", false);
2222 GLOBAL_DEF("debug/settings/stdout/print_gpu_profile", false);
2223 GLOBAL_DEF("debug/settings/stdout/verbose_stdout", false);
2224 GLOBAL_DEF("debug/settings/physics_interpolation/enable_warnings", true);
2225 if (!OS::get_singleton()->_verbose_stdout) { // Not manually overridden.
2226 OS::get_singleton()->_verbose_stdout = GLOBAL_GET("debug/settings/stdout/verbose_stdout");
2227 }
2228
2229 register_early_core_singletons();
2230 initialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
2231 register_core_extensions(); // core extensions must be registered after globals setup and before display
2232
2233 if (!editor) {
2234 ResourceUID::get_singleton()->enable_reverse_cache();
2235 }
2236 ResourceUID::get_singleton()->load_from_cache(true); // Load UUIDs from cache.
2237 ProjectSettings::get_singleton()->fix_autoload_paths(); // Handles autoloads saved as UID.
2238
2239 if (ProjectSettings::get_singleton()->has_custom_feature("dedicated_server")) {
2240 audio_driver = NULL_AUDIO_DRIVER;
2241 display_driver = NULL_DISPLAY_DRIVER;
2242 }
2243
2244 GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_chars_per_second", PROPERTY_HINT_RANGE, "256,4096,1,or_greater"), 32768);
2245 GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_queued_messages", PROPERTY_HINT_RANGE, "128,8192,1,or_greater"), 2048);
2246 GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_errors_per_second", PROPERTY_HINT_RANGE, "1,200,1,or_greater"), 400);
2247 GLOBAL_DEF(PropertyInfo(Variant::INT, "network/limits/debugger/max_warnings_per_second", PROPERTY_HINT_RANGE, "1,200,1,or_greater"), 400);
2248
2249 EngineDebugger::initialize(debug_uri, skip_breakpoints, ignore_error_breaks, breakpoints, []() {
2250 if (editor_pid) {
2251 DisplayServer::get_singleton()->enable_for_stealing_focus(editor_pid);
2252 }
2253 });
2254
2255 #ifdef TOOLS_ENABLED
2256 if (editor) {
2257 packed_data->set_disabled(true);
2258 }
2259 #endif
2260
2261 GLOBAL_DEF("debug/file_logging/enable_file_logging", false);
2262 // Only file logging by default on desktop platforms as logs can't be
2263 // accessed easily on mobile/Web platforms (if at all).
2264 // This also prevents logs from being created for the editor instance, as feature tags
2265 // are disabled while in the editor (even if they should logically apply).
2266 GLOBAL_DEF("debug/file_logging/enable_file_logging.pc", true);
2267 GLOBAL_DEF("debug/file_logging/log_path", "user://logs/godot.log");
2268 GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/file_logging/max_log_files", PROPERTY_HINT_RANGE, "0,20,1,or_greater"), 5);
2269
2270 // If `--log-file` is used to override the log path, allow creating logs for the project manager or editor
2271 // and even if file logging is disabled in the Project Settings.
2272 // `--log-file` can be used with any path (including absolute paths outside the project folder),
2273 // so check for filesystem access if it's used.
2274 if (FileAccess::get_create_func(!log_file.is_empty() ? FileAccess::ACCESS_FILESYSTEM : FileAccess::ACCESS_USERDATA) &&
2275 (!log_file.is_empty() || (!project_manager && !editor && GLOBAL_GET("debug/file_logging/enable_file_logging")))) {
2276 // Don't create logs for the project manager as they would be written to
2277 // the current working directory, which is inconvenient.
2278 String base_path;
2279 int max_files;
2280 if (!log_file.is_empty()) {
2281 base_path = log_file;
2282 // Ensure log file name respects the specified override by disabling log rotation.
2283 max_files = 1;
2284 } else {
2285 base_path = GLOBAL_GET("debug/file_logging/log_path");
2286 max_files = GLOBAL_GET("debug/file_logging/max_log_files");
2287 }
2288 OS::get_singleton()->add_logger(memnew(RotatedFileLogger(base_path, max_files)));
2289 }
2290
2291 if (main_args.is_empty() && String(GLOBAL_GET("application/run/main_scene")) == "") {
2292 #ifdef TOOLS_ENABLED
2293 if (!editor && !project_manager) {
2294 #endif
2295 const String error_msg = "Error: Can't run project: no main scene defined in the project.\n";
2296 OS::get_singleton()->print("%s", error_msg.utf8().get_data());
2297 OS::get_singleton()->alert(error_msg);
2298 goto error;
2299 #ifdef TOOLS_ENABLED
2300 }
2301 #endif
2302 }
2303
2304 if (editor || project_manager) {
2305 Engine::get_singleton()->set_editor_hint(true);
2306 use_custom_res = false;
2307 input_map->load_default(); //keys for editor
2308 } else {
2309 input_map->load_from_project_settings(); //keys for game
2310 }
2311
2312 if (bool(GLOBAL_GET("application/run/disable_stdout"))) {
2313 quiet_stdout = true;
2314 }
2315 if (bool(GLOBAL_GET("application/run/disable_stderr"))) {
2316 CoreGlobals::print_error_enabled = false;
2317 }
2318 if (!bool(GLOBAL_GET("application/run/print_header"))) {
2319 // --no-header option for project settings.
2320 Engine::get_singleton()->_print_header = false;
2321 }
2322
2323 if (quiet_stdout) {
2324 CoreGlobals::print_line_enabled = false;
2325 }
2326
2327 Logger::set_flush_stdout_on_print(GLOBAL_GET("application/run/flush_stdout_on_print"));
2328
2329 // Rendering drivers configuration.
2330
2331 // Always include all supported drivers as hint, as this is used by the editor host platform
2332 // for project settings. For example, a Linux user should be able to configure that they want
2333 // to export for D3D12 on Windows and Metal on macOS even if their host platform can't use those.
2334
2335 {
2336 // RenderingDevice driver overrides per platform.
2337 GLOBAL_DEF_RST("rendering/rendering_device/driver", "vulkan");
2338 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.windows", PROPERTY_HINT_ENUM, "vulkan,d3d12"), "vulkan");
2339 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.linuxbsd", PROPERTY_HINT_ENUM, "vulkan"), "vulkan");
2340 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.android", PROPERTY_HINT_ENUM, "vulkan"), "vulkan");
2341 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.ios", PROPERTY_HINT_ENUM, "metal,vulkan"), "metal");
2342 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.visionos", PROPERTY_HINT_ENUM, "metal"), "metal");
2343 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/rendering_device/driver.macos", PROPERTY_HINT_ENUM, "metal,vulkan"), "metal");
2344
2345 GLOBAL_DEF_RST("rendering/rendering_device/fallback_to_vulkan", true);
2346 GLOBAL_DEF_RST("rendering/rendering_device/fallback_to_d3d12", true);
2347 GLOBAL_DEF_RST("rendering/rendering_device/fallback_to_opengl3", true);
2348 }
2349
2350 {
2351 // GL Compatibility driver overrides per platform.
2352 GLOBAL_DEF_RST("rendering/gl_compatibility/driver", "opengl3");
2353 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.windows", PROPERTY_HINT_ENUM, "opengl3,opengl3_angle"), "opengl3");
2354 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.linuxbsd", PROPERTY_HINT_ENUM, "opengl3,opengl3_es"), "opengl3");
2355 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.web", PROPERTY_HINT_ENUM, "opengl3"), "opengl3");
2356 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.android", PROPERTY_HINT_ENUM, "opengl3"), "opengl3");
2357 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.ios", PROPERTY_HINT_ENUM, "opengl3"), "opengl3");
2358 GLOBAL_DEF_RST(PropertyInfo(Variant::STRING, "rendering/gl_compatibility/driver.macos", PROPERTY_HINT_ENUM, "opengl3,opengl3_angle"), "opengl3");
2359
2360 GLOBAL_DEF_RST("rendering/gl_compatibility/nvidia_disable_threaded_optimization", true);
2361 GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_angle", true);
2362 GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_native", true);
2363 GLOBAL_DEF_RST("rendering/gl_compatibility/fallback_to_gles", true);
2364
2365 Array force_angle_list;
2366
2367 #define FORCE_ANGLE(m_vendor, m_name) \
2368 { \
2369 Dictionary device; \
2370 device["vendor"] = m_vendor; \
2371 device["name"] = m_name; \
2372 force_angle_list.push_back(device); \
2373 }
2374
2375 // AMD GPUs.
2376 FORCE_ANGLE("ATI", "Radeon 9"); // ATI Radeon 9000 Series
2377 FORCE_ANGLE("ATI", "Radeon X"); // ATI Radeon X500-X2000 Series
2378 FORCE_ANGLE("ATI", "Radeon HD 2"); // AMD/ATI (Mobility) Radeon HD 2xxx Series
2379 FORCE_ANGLE("ATI", "Radeon HD 3"); // AMD/ATI (Mobility) Radeon HD 3xxx Series
2380 FORCE_ANGLE("ATI", "Radeon HD 4"); // AMD/ATI (Mobility) Radeon HD 4xxx Series
2381 FORCE_ANGLE("ATI", "Radeon HD 5"); // AMD/ATI (Mobility) Radeon HD 5xxx Series
2382 FORCE_ANGLE("ATI", "Radeon HD 6"); // AMD/ATI (Mobility) Radeon HD 6xxx Series
2383 FORCE_ANGLE("ATI", "Radeon HD 7"); // AMD/ATI (Mobility) Radeon HD 7xxx Series
2384 FORCE_ANGLE("ATI", "Radeon HD 8"); // AMD/ATI (Mobility) Radeon HD 8xxx Series
2385 FORCE_ANGLE("ATI", "Radeon(TM) R2 Graphics"); // APUs
2386 FORCE_ANGLE("ATI", "Radeon(TM) R3 Graphics");
2387 FORCE_ANGLE("ATI", "Radeon(TM) R4 Graphics");
2388 FORCE_ANGLE("ATI", "Radeon(TM) R5 Graphics");
2389 FORCE_ANGLE("ATI", "Radeon(TM) R6 Graphics");
2390 FORCE_ANGLE("ATI", "Radeon(TM) R7 Graphics");
2391 FORCE_ANGLE("AMD", "Radeon(TM) R7 Graphics");
2392 FORCE_ANGLE("AMD", "Radeon(TM) R8 Graphics");
2393 FORCE_ANGLE("ATI", "Radeon R5 Graphics");
2394 FORCE_ANGLE("ATI", "Radeon R6 Graphics");
2395 FORCE_ANGLE("ATI", "Radeon R7 Graphics");
2396 FORCE_ANGLE("AMD", "Radeon R7 Graphics");
2397 FORCE_ANGLE("AMD", "Radeon R8 Graphics");
2398 FORCE_ANGLE("ATI", "Radeon R5 2"); // Rx 2xx Series
2399 FORCE_ANGLE("ATI", "Radeon R7 2");
2400 FORCE_ANGLE("ATI", "Radeon R9 2");
2401 FORCE_ANGLE("ATI", "Radeon R5 M2"); // Rx M2xx Series
2402 FORCE_ANGLE("ATI", "Radeon R7 M2");
2403 FORCE_ANGLE("ATI", "Radeon R9 M2");
2404 FORCE_ANGLE("ATI", "Radeon (TM) R9 Fury");
2405 FORCE_ANGLE("ATI", "Radeon (TM) R5 3"); // Rx 3xx Series
2406 FORCE_ANGLE("AMD", "Radeon (TM) R5 3");
2407 FORCE_ANGLE("ATI", "Radeon (TM) R7 3");
2408 FORCE_ANGLE("AMD", "Radeon (TM) R7 3");
2409 FORCE_ANGLE("ATI", "Radeon (TM) R9 3");
2410 FORCE_ANGLE("AMD", "Radeon (TM) R9 3");
2411 FORCE_ANGLE("ATI", "Radeon (TM) R5 M3"); // Rx M3xx Series
2412 FORCE_ANGLE("AMD", "Radeon (TM) R5 M3");
2413 FORCE_ANGLE("ATI", "Radeon (TM) R7 M3");
2414 FORCE_ANGLE("AMD", "Radeon (TM) R7 M3");
2415 FORCE_ANGLE("ATI", "Radeon (TM) R9 M3");
2416 FORCE_ANGLE("AMD", "Radeon (TM) R9 M3");
2417
2418 // Intel GPUs (Gen7-Gen9.5 devices).
2419 FORCE_ANGLE("Intel", "Intel(R) HD Graphics");
2420 FORCE_ANGLE("Intel", "Intel HD Graphics");
2421 FORCE_ANGLE("Intel", "Intel(R) Vallyview Graphics");
2422 FORCE_ANGLE("Intel", "Intel(R) Iris(TM) Graphics 5100");
2423 FORCE_ANGLE("Intel", "Intel(R) Iris(TM) Pro Graphics 5200");
2424 FORCE_ANGLE("Intel", "Intel(R) Iris(TM) Graphics 6100");
2425 FORCE_ANGLE("Intel", "Intel(R) Iris(TM) Pro Graphics 6200");
2426 FORCE_ANGLE("Intel", "Intel(R) Iris(TM) Pro Graphics P6300");
2427 FORCE_ANGLE("Intel", "Intel(R) Iris Graphics 540");
2428 FORCE_ANGLE("Intel", "Intel(R) Iris Plus Graphics 640");
2429 FORCE_ANGLE("Intel", "Intel(R) Iris Plus Graphics 650");
2430 FORCE_ANGLE("Intel", "Intel(R) Iris Pro Graphics 580");
2431 FORCE_ANGLE("Intel", "Intel(R) Iris Pro Graphics P580");
2432
2433 #undef FORCE_ANGLE
2434
2435 GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::ARRAY, "rendering/gl_compatibility/force_angle_on_devices", PROPERTY_HINT_ARRAY_TYPE, vformat("%s/%s:%s", Variant::DICTIONARY, PROPERTY_HINT_NONE, String())), force_angle_list);
2436 }
2437
2438 // Start with RenderingDevice-based backends.
2439 #ifdef RD_ENABLED
2440 renderer_hints = "forward_plus,mobile";
2441 default_renderer_mobile = "mobile";
2442 #endif
2443
2444 // And Compatibility next, or first if Vulkan is disabled.
2445 #ifdef GLES3_ENABLED
2446 if (!renderer_hints.is_empty()) {
2447 renderer_hints += ",";
2448 }
2449 renderer_hints += "gl_compatibility";
2450 if (default_renderer_mobile.is_empty()) {
2451 default_renderer_mobile = "gl_compatibility";
2452 }
2453 // Default to Compatibility when using the project manager.
2454 if (rendering_driver.is_empty() && rendering_method.is_empty() && project_manager) {
2455 rendering_driver = "opengl3";
2456 rendering_method = "gl_compatibility";
2457 default_renderer_mobile = "gl_compatibility";
2458 }
2459 #endif
2460
2461 if (!rendering_method.is_empty()) {
2462 if (rendering_method != "forward_plus" &&
2463 rendering_method != "mobile" &&
2464 rendering_method != "gl_compatibility" &&
2465 rendering_method != "dummy") {
2466 OS::get_singleton()->print("Unknown rendering method '%s', aborting.\nValid options are ",
2467 rendering_method.utf8().get_data());
2468
2469 Vector<String> rendering_method_hints = renderer_hints.split(",");
2470 rendering_method_hints.push_back("dummy");
2471 for (int i = 0; i < rendering_method_hints.size(); i++) {
2472 if (i == rendering_method_hints.size() - 1) {
2473 OS::get_singleton()->print(" and ");
2474 } else if (i != 0) {
2475 OS::get_singleton()->print(", ");
2476 }
2477 OS::get_singleton()->print("'%s'", rendering_method_hints[i].utf8().get_data());
2478 }
2479
2480 OS::get_singleton()->print(".\n");
2481 goto error;
2482 }
2483 }
2484 if (renderer_hints.is_empty()) {
2485 renderer_hints = "dummy";
2486 }
2487
2488 if (!rendering_driver.is_empty()) {
2489 // As the rendering drivers available may depend on the display driver and renderer
2490 // selected, we can't do an exhaustive check here, but we can look through all
2491 // the options in all the display drivers for a match.
2492
2493 bool found = false;
2494 for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
2495 Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
2496
2497 for (int d = 0; d < r_drivers.size(); d++) {
2498 if (rendering_driver == r_drivers[d]) {
2499 found = true;
2500 break;
2501 }
2502 }
2503 }
2504
2505 if (!found) {
2506 OS::get_singleton()->print("Unknown rendering driver '%s', aborting.\nValid options are ",
2507 rendering_driver.utf8().get_data());
2508
2509 // Deduplicate driver entries, as a rendering driver may be supported by several display servers.
2510 Vector<String> unique_rendering_drivers;
2511 for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
2512 Vector<String> r_drivers = DisplayServer::get_create_function_rendering_drivers(i);
2513
2514 for (int d = 0; d < r_drivers.size(); d++) {
2515 if (!unique_rendering_drivers.has(r_drivers[d])) {
2516 unique_rendering_drivers.append(r_drivers[d]);
2517 }
2518 }
2519 }
2520
2521 for (int i = 0; i < unique_rendering_drivers.size(); i++) {
2522 if (i == unique_rendering_drivers.size() - 1) {
2523 OS::get_singleton()->print(" and ");
2524 } else if (i != 0) {
2525 OS::get_singleton()->print(", ");
2526 }
2527 OS::get_singleton()->print("'%s'", unique_rendering_drivers[i].utf8().get_data());
2528 }
2529
2530 OS::get_singleton()->print(".\n");
2531
2532 goto error;
2533 }
2534
2535 // Set a default renderer if none selected. Try to choose one that matches the driver.
2536 if (rendering_method.is_empty()) {
2537 if (rendering_driver == "dummy") {
2538 rendering_method = "dummy";
2539 } else if (rendering_driver == "opengl3" || rendering_driver == "opengl3_angle" || rendering_driver == "opengl3_es") {
2540 rendering_method = "gl_compatibility";
2541 } else {
2542 rendering_method = "forward_plus";
2543 }
2544 }
2545
2546 // Now validate whether the selected driver matches with the renderer.
2547 bool valid_combination = false;
2548 Vector<String> available_drivers;
2549 if (rendering_method == "forward_plus" || rendering_method == "mobile") {
2550 #ifdef VULKAN_ENABLED
2551 available_drivers.push_back("vulkan");
2552 #endif
2553 #ifdef D3D12_ENABLED
2554 available_drivers.push_back("d3d12");
2555 #endif
2556 #ifdef METAL_ENABLED
2557 available_drivers.push_back("metal");
2558 #endif
2559 }
2560 #ifdef GLES3_ENABLED
2561 if (rendering_method == "gl_compatibility") {
2562 available_drivers.push_back("opengl3");
2563 available_drivers.push_back("opengl3_angle");
2564 available_drivers.push_back("opengl3_es");
2565 }
2566 #endif
2567 if (rendering_method == "dummy") {
2568 available_drivers.push_back("dummy");
2569 }
2570 if (available_drivers.is_empty()) {
2571 OS::get_singleton()->print("Unknown renderer name '%s', aborting.\n", rendering_method.utf8().get_data());
2572 goto error;
2573 }
2574
2575 for (int i = 0; i < available_drivers.size(); i++) {
2576 if (rendering_driver == available_drivers[i]) {
2577 valid_combination = true;
2578 break;
2579 }
2580 }
2581
2582 if (!valid_combination) {
2583 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());
2584
2585 for (int d = 0; d < available_drivers.size(); d++) {
2586 OS::get_singleton()->print("'%s', ", available_drivers[d].utf8().get_data());
2587 }
2588
2589 OS::get_singleton()->print(".\n");
2590
2591 goto error;
2592 }
2593 }
2594
2595 default_renderer = renderer_hints.get_slicec(',', 0);
2596 GLOBAL_DEF_RST_BASIC(PropertyInfo(Variant::STRING, "rendering/renderer/rendering_method", PROPERTY_HINT_ENUM, renderer_hints), default_renderer);
2597 GLOBAL_DEF_RST_BASIC("rendering/renderer/rendering_method.mobile", default_renderer_mobile);
2598 GLOBAL_DEF_RST_BASIC(PropertyInfo(Variant::STRING, "rendering/renderer/rendering_method.web", PROPERTY_HINT_ENUM, "gl_compatibility"), "gl_compatibility"); // This is a bit of a hack until we have WebGPU support.
2599
2600 // Default to ProjectSettings default if nothing set on the command line.
2601 if (rendering_method.is_empty()) {
2602 rendering_method = GLOBAL_GET("rendering/renderer/rendering_method");
2603 }
2604
2605 if (rendering_driver.is_empty()) {
2606 if (rendering_method == "dummy") {
2607 rendering_driver = "dummy";
2608 } else if (rendering_method == "gl_compatibility") {
2609 rendering_driver = GLOBAL_GET("rendering/gl_compatibility/driver");
2610 } else {
2611 rendering_driver = GLOBAL_GET("rendering/rendering_device/driver");
2612 }
2613 }
2614
2615 // always convert to lower case for consistency in the code
2616 rendering_driver = rendering_driver.to_lower();
2617
2618 OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
2619 OS::get_singleton()->set_current_rendering_method(rendering_method);
2620
2621 #ifdef TOOLS_ENABLED
2622 if (!force_res && project_manager) {
2623 // Ensure splash screen size matches the project manager window size
2624 // (see `editor/project_manager.cpp` for defaults).
2625 window_size.width = ProjectManager::DEFAULT_WINDOW_WIDTH;
2626 window_size.height = ProjectManager::DEFAULT_WINDOW_HEIGHT;
2627 }
2628 #endif
2629
2630 if (use_custom_res) {
2631 if (!force_res) {
2632 window_size.width = GLOBAL_GET("display/window/size/viewport_width");
2633 window_size.height = GLOBAL_GET("display/window/size/viewport_height");
2634
2635 if (globals->has_setting("display/window/size/window_width_override") &&
2636 globals->has_setting("display/window/size/window_height_override")) {
2637 int desired_width = GLOBAL_GET("display/window/size/window_width_override");
2638 if (desired_width > 0) {
2639 window_size.width = desired_width;
2640 }
2641 int desired_height = GLOBAL_GET("display/window/size/window_height_override");
2642 if (desired_height > 0) {
2643 window_size.height = desired_height;
2644 }
2645 }
2646 }
2647
2648 if (!bool(GLOBAL_GET("display/window/size/resizable"))) {
2649 window_flags |= DisplayServer::WINDOW_FLAG_RESIZE_DISABLED_BIT;
2650 }
2651 if (bool(GLOBAL_GET("display/window/size/minimize_disabled"))) {
2652 window_flags |= DisplayServer::WINDOW_FLAG_MINIMIZE_DISABLED_BIT;
2653 }
2654 if (bool(GLOBAL_GET("display/window/size/maximize_disabled"))) {
2655 window_flags |= DisplayServer::WINDOW_FLAG_MAXIMIZE_DISABLED_BIT;
2656 }
2657 if (bool(GLOBAL_GET("display/window/size/borderless"))) {
2658 window_flags |= DisplayServer::WINDOW_FLAG_BORDERLESS_BIT;
2659 }
2660 if (bool(GLOBAL_GET("display/window/size/always_on_top"))) {
2661 window_flags |= DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP_BIT;
2662 }
2663 if (bool(GLOBAL_GET("display/window/size/transparent"))) {
2664 window_flags |= DisplayServer::WINDOW_FLAG_TRANSPARENT_BIT;
2665 }
2666 if (bool(GLOBAL_GET("display/window/size/extend_to_title"))) {
2667 window_flags |= DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE_BIT;
2668 }
2669 if (bool(GLOBAL_GET("display/window/size/no_focus"))) {
2670 window_flags |= DisplayServer::WINDOW_FLAG_NO_FOCUS_BIT;
2671 }
2672 if (bool(GLOBAL_GET("display/window/size/sharp_corners"))) {
2673 window_flags |= DisplayServer::WINDOW_FLAG_SHARP_CORNERS_BIT;
2674 }
2675 window_mode = (DisplayServer::WindowMode)(GLOBAL_GET("display/window/size/mode").operator int());
2676 int initial_position_type = GLOBAL_GET("display/window/size/initial_position_type").operator int();
2677 if (initial_position_type == Window::WINDOW_INITIAL_POSITION_ABSOLUTE) { // Absolute.
2678 if (!init_use_custom_pos) {
2679 init_custom_pos = GLOBAL_GET("display/window/size/initial_position").operator Vector2i();
2680 init_use_custom_pos = true;
2681 }
2682 } else if (initial_position_type == Window::WINDOW_INITIAL_POSITION_CENTER_PRIMARY_SCREEN || initial_position_type == Window::WINDOW_INITIAL_POSITION_CENTER_MAIN_WINDOW_SCREEN) { // Center of Primary Screen.
2683 if (!init_use_custom_screen) {
2684 init_screen = DisplayServer::SCREEN_PRIMARY;
2685 init_use_custom_screen = true;
2686 }
2687 } else if (initial_position_type == Window::WINDOW_INITIAL_POSITION_CENTER_OTHER_SCREEN) { // Center of Other Screen.
2688 if (!init_use_custom_screen) {
2689 init_screen = GLOBAL_GET("display/window/size/initial_screen").operator int();
2690 init_use_custom_screen = true;
2691 }
2692 } else if (initial_position_type == Window::WINDOW_INITIAL_POSITION_CENTER_SCREEN_WITH_MOUSE_FOCUS) { // Center of Screen With Mouse Pointer.
2693 if (!init_use_custom_screen) {
2694 init_screen = DisplayServer::SCREEN_WITH_MOUSE_FOCUS;
2695 init_use_custom_screen = true;
2696 }
2697 } else if (initial_position_type == Window::WINDOW_INITIAL_POSITION_CENTER_SCREEN_WITH_KEYBOARD_FOCUS) { // Center of Screen With Keyboard Focus.
2698 if (!init_use_custom_screen) {
2699 init_screen = DisplayServer::SCREEN_WITH_KEYBOARD_FOCUS;
2700 init_use_custom_screen = true;
2701 }
2702 }
2703 }
2704
2705 OS::get_singleton()->_allow_hidpi = GLOBAL_DEF("display/window/dpi/allow_hidpi", true);
2706 OS::get_singleton()->_allow_layered = GLOBAL_DEF_RST("display/window/per_pixel_transparency/allowed", false);
2707
2708 load_shell_env = GLOBAL_DEF("application/run/load_shell_environment", false);
2709
2710 #ifdef TOOLS_ENABLED
2711 if (editor || project_manager) {
2712 // The editor and project manager always detect and use hiDPI if needed.
2713 OS::get_singleton()->_allow_hidpi = true;
2714 load_shell_env = true;
2715 }
2716 #endif
2717 if (load_shell_env) {
2718 OS::get_singleton()->load_shell_environment();
2719 }
2720
2721 if (separate_thread_render == -1) {
2722 separate_thread_render = (int)GLOBAL_DEF("rendering/driver/threads/thread_model", OS::RENDER_THREAD_SAFE) == OS::RENDER_SEPARATE_THREAD;
2723 }
2724
2725 if (editor || project_manager) {
2726 // Editor and project manager cannot run with rendering in a separate thread (they will crash on startup).
2727 separate_thread_render = 0;
2728 }
2729 #if !defined(THREADS_ENABLED)
2730 separate_thread_render = 0;
2731 #endif
2732 OS::get_singleton()->_separate_thread_render = separate_thread_render;
2733
2734 /* Determine audio and video drivers */
2735
2736 // Display driver, e.g. X11, Wayland.
2737 // Make sure that headless is the last one, which it is assumed to be by design.
2738 DEV_ASSERT(NULL_DISPLAY_DRIVER == DisplayServer::get_create_function_name(DisplayServer::get_create_function_count() - 1));
2739
2740 GLOBAL_DEF_NOVAL("display/display_server/driver", "default");
2741 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.windows", PROPERTY_HINT_ENUM, "default,windows,headless"), "default");
2742 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.linuxbsd", PROPERTY_HINT_ENUM, "default,x11,wayland,headless"), "default");
2743 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.android", PROPERTY_HINT_ENUM, "default,android,headless"), "default");
2744 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.ios", PROPERTY_HINT_ENUM, "default,iOS,headless"), "default");
2745 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.visionos", PROPERTY_HINT_ENUM, "default,visionOS,headless"), "default");
2746 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::STRING, "display/display_server/driver.macos", PROPERTY_HINT_ENUM, "default,macos,headless"), "default");
2747
2748 GLOBAL_DEF_RST_NOVAL("audio/driver/driver", AudioDriverManager::get_driver(0)->get_name());
2749 if (audio_driver.is_empty()) { // Specified in project.godot.
2750 if (project_manager) {
2751 // The project manager doesn't need to play sound (TTS audio output is not emitted by Godot, but by the system itself).
2752 // Disable audio output so it doesn't appear in the list of applications outputting sound in the OS.
2753 // On macOS, this also prevents the project manager from inhibiting suspend.
2754 audio_driver = "Dummy";
2755 } else {
2756 audio_driver = GLOBAL_GET("audio/driver/driver");
2757 }
2758 }
2759
2760 // Make sure that dummy is the last one, which it is assumed to be by design.
2761 DEV_ASSERT(NULL_AUDIO_DRIVER == AudioDriverManager::get_driver(AudioDriverManager::get_driver_count() - 1)->get_name());
2762 for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
2763 if (audio_driver == AudioDriverManager::get_driver(i)->get_name()) {
2764 audio_driver_idx = i;
2765 break;
2766 }
2767 }
2768
2769 if (audio_driver_idx < 0) {
2770 // If the requested driver wasn't found, pick the first entry.
2771 // If all else failed it would be the dummy driver (no sound).
2772 audio_driver_idx = 0;
2773 }
2774
2775 if (Engine::get_singleton()->get_write_movie_path() != String()) {
2776 // Always use dummy driver for audio driver (which is last), also in no threaded mode.
2777 audio_driver_idx = AudioDriverManager::get_driver_count() - 1;
2778 AudioDriverDummy::get_dummy_singleton()->set_use_threads(false);
2779 }
2780
2781 {
2782 window_orientation = DisplayServer::ScreenOrientation(int(GLOBAL_DEF_BASIC("display/window/handheld/orientation", DisplayServer::ScreenOrientation::SCREEN_LANDSCAPE)));
2783 }
2784 {
2785 window_vsync_mode = DisplayServer::VSyncMode(int(GLOBAL_DEF_BASIC("display/window/vsync/vsync_mode", DisplayServer::VSyncMode::VSYNC_ENABLED)));
2786 if (disable_vsync) {
2787 window_vsync_mode = DisplayServer::VSyncMode::VSYNC_DISABLED;
2788 }
2789 }
2790
2791 GLOBAL_DEF_RST(PropertyInfo(Variant::INT, "audio/driver/output_latency", PROPERTY_HINT_RANGE, "1,100,1"), 15);
2792 // Use a safer default output_latency for web to avoid audio cracking on low-end devices, especially mobile.
2793 GLOBAL_DEF_RST("audio/driver/output_latency.web", 50);
2794
2795 Engine::get_singleton()->set_audio_output_latency(GLOBAL_GET("audio/driver/output_latency"));
2796
2797 #if defined(MACOS_ENABLED) || defined(IOS_ENABLED)
2798 OS::get_singleton()->set_environment("MVK_CONFIG_LOG_LEVEL", OS::get_singleton()->_verbose_stdout ? "3" : "1"); // 1 = Errors only, 3 = Info
2799 #endif
2800
2801 if (frame_delay == 0) {
2802 frame_delay = GLOBAL_DEF(PropertyInfo(Variant::INT, "application/run/frame_delay_msec", PROPERTY_HINT_RANGE, "0,100,1,or_greater"), 0);
2803 if (Engine::get_singleton()->is_editor_hint()) {
2804 frame_delay = 0;
2805 }
2806 }
2807
2808 if (audio_output_latency >= 1) {
2809 Engine::get_singleton()->set_audio_output_latency(audio_output_latency);
2810 }
2811
2812 GLOBAL_DEF("display/window/ios/allow_high_refresh_rate", true);
2813 GLOBAL_DEF("display/window/ios/hide_home_indicator", true);
2814 GLOBAL_DEF("display/window/ios/hide_status_bar", true);
2815 GLOBAL_DEF("display/window/ios/suppress_ui_gesture", true);
2816
2817 #ifndef _3D_DISABLED
2818 // XR project settings.
2819 GLOBAL_DEF_RST_BASIC("xr/openxr/enabled", false);
2820 GLOBAL_DEF(PropertyInfo(Variant::STRING, "xr/openxr/target_api_version"), "");
2821 GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "xr/openxr/default_action_map", PROPERTY_HINT_FILE, "*.tres"), "res://openxr_action_map.tres");
2822 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/form_factor", PROPERTY_HINT_ENUM, "Head Mounted,Handheld"), "0");
2823 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/view_configuration", PROPERTY_HINT_ENUM, "Mono,Stereo"), "1"); // "Mono,Stereo,Quad,Observer"
2824 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/reference_space", PROPERTY_HINT_ENUM, "Local,Stage,Local Floor"), "1");
2825 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/environment_blend_mode", PROPERTY_HINT_ENUM, "Opaque,Additive,Alpha"), "0");
2826 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/foveation_level", PROPERTY_HINT_ENUM, "Off,Low,Medium,High"), "0");
2827 GLOBAL_DEF_BASIC("xr/openxr/foveation_dynamic", false);
2828
2829 GLOBAL_DEF_BASIC("xr/openxr/submit_depth_buffer", false);
2830 GLOBAL_DEF_BASIC("xr/openxr/startup_alert", true);
2831
2832 // OpenXR project extensions settings.
2833 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/extensions/debug_utils", PROPERTY_HINT_ENUM, "Disabled,Error,Warning,Info,Verbose"), "0");
2834 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/extensions/debug_message_types", PROPERTY_HINT_FLAGS, "General,Validation,Performance,Conformance"), "15");
2835 GLOBAL_DEF_BASIC("xr/openxr/extensions/frame_synthesis", false);
2836 GLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking", false);
2837 GLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking_unobstructed_data_source", false); // XR_HAND_TRACKING_DATA_SOURCE_UNOBSTRUCTED_EXT
2838 GLOBAL_DEF_BASIC("xr/openxr/extensions/hand_tracking_controller_data_source", false); // XR_HAND_TRACKING_DATA_SOURCE_CONTROLLER_EXT
2839 GLOBAL_DEF_RST_BASIC("xr/openxr/extensions/hand_interaction_profile", false);
2840 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enabled", false);
2841 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_spatial_anchors", false);
2842 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_persistent_anchors", false);
2843 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_builtin_anchor_detection", false);
2844 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_plane_tracking", false);
2845 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_builtin_plane_detection", false);
2846 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_marker_tracking", false);
2847 GLOBAL_DEF_BASIC("xr/openxr/extensions/spatial_entity/enable_builtin_marker_tracking", false);
2848 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/extensions/spatial_entity/aruco_dict", PROPERTY_HINT_ENUM, "4x4 50 IDs,4x4 100 IDs,4x4 250 IDs,4x4 1000 IDs,5x5 50 IDs,5x5 100 IDs,5x5 250 IDs,5x5 1000 IDs,6x6 50 IDs,6x6 100 IDs,6x6 250 IDs,6x6 1000 IDs,7x7 50 IDs,7x7 100 IDs,7x7 250 IDs,7x7 1000 IDs"), "15");
2849 GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "xr/openxr/extensions/spatial_entity/april_tag_dict", PROPERTY_HINT_ENUM, "4x4H5,5x5H9,6x6H10,6x6H11"), "3");
2850 GLOBAL_DEF_RST_BASIC("xr/openxr/extensions/eye_gaze_interaction", false);
2851 GLOBAL_DEF_BASIC("xr/openxr/extensions/render_model", false);
2852
2853 // OpenXR Binding modifier settings
2854 GLOBAL_DEF_BASIC("xr/openxr/binding_modifiers/analog_threshold", false);
2855 GLOBAL_DEF_RST_BASIC("xr/openxr/binding_modifiers/dpad_binding", false);
2856
2857 #ifdef TOOLS_ENABLED
2858 // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
2859
2860 // editor settings (it seems we're too early in the process when setting up rendering, to access editor settings...)
2861 // EDITOR_DEF_RST("xr/openxr/in_editor", false);
2862 // GLOBAL_DEF("xr/openxr/in_editor", false);
2863 #endif // TOOLS_ENABLED
2864 #endif // _3D_DISABLED
2865
2866 Engine::get_singleton()->set_frame_delay(frame_delay);
2867
2868 message_queue = memnew(MessageQueue);
2869
2870 Thread::release_main_thread(); // If setup2() is called from another thread, that one will become main thread, so preventively release this one.
2871 set_current_thread_safe_for_nodes(false);
2872
2873 #if defined(STEAMAPI_ENABLED)
2874 if (editor || project_manager) {
2875 steam_tracker = memnew(SteamTracker);
2876 }
2877 #endif
2878
2879 OS::get_singleton()->benchmark_end_measure("Startup", "Main::Setup");
2880
2881 if (p_second_phase) {
2882 exit_err = setup2();
2883 if (exit_err != OK) {
2884 goto error;
2885 }
2886 }
2887
2888 return OK;
2889
2890 error:
2891
2892 text_driver = "";
2893 display_driver = "";
2894 audio_driver = "";
2895 tablet_driver = "";
2896 Engine::get_singleton()->set_write_movie_path(String());
2897 project_path = "";
2898
2899 args.clear();
2900 main_args.clear();
2901
2902 if (show_help) {
2903 print_help(execpath);
2904 }
2905
2906 if (editor) {
2907 OS::get_singleton()->remove_lock_file();
2908 }
2909
2910 EngineDebugger::deinitialize();
2911
2912 if (performance) {
2913 memdelete(performance);
2914 }
2915 if (input_map) {
2916 memdelete(input_map);
2917 }
2918 if (translation_server) {
2919 memdelete(translation_server);
2920 }
2921 if (globals) {
2922 memdelete(globals);
2923 }
2924 if (packed_data) {
2925 memdelete(packed_data);
2926 }
2927
2928 unregister_core_driver_types();
2929 unregister_core_extensions();
2930
2931 if (engine) {
2932 memdelete(engine);
2933 }
2934
2935 unregister_core_types();
2936
2937 OS::get_singleton()->_cmdline.clear();
2938 OS::get_singleton()->_user_args.clear();
2939
2940 if (message_queue) {
2941 memdelete(message_queue);
2942 }
2943
2944 OS::get_singleton()->benchmark_end_measure("Startup", "Main::Setup");
2945
2946 #if defined(STEAMAPI_ENABLED)
2947 if (steam_tracker) {
2948 memdelete(steam_tracker);
2949 }
2950 #endif
2951
2952 OS::get_singleton()->finalize_core();
2953 locale = String();
2954
2955 return exit_err;
2956 }
2957
2958 Error _parse_resource_dummy(void *p_data, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
2959 VariantParser::Token token;
2960 VariantParser::get_token(p_stream, token, line, r_err_str);
2961 if (token.type != VariantParser::TK_NUMBER && token.type != VariantParser::TK_STRING) {
2962 r_err_str = "Expected number (old style sub-resource index) or String (ext-resource ID)";
2963 return ERR_PARSE_ERROR;
2964 }
2965
2966 r_res.unref();
2967
2968 VariantParser::get_token(p_stream, token, line, r_err_str);
2969 if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
2970 r_err_str = "Expected ')'";
2971 return ERR_PARSE_ERROR;
2972 }
2973
2974 return OK;
2975 }
2976
2977 Error Main::setup2(bool p_show_boot_logo) {
2978 GodotProfileZone("setup2");
2979 OS::get_singleton()->benchmark_begin_measure("Startup", "Main::Setup2");
2980
2981 Thread::make_main_thread(); // Make whatever thread call this the main thread.
2982 set_current_thread_safe_for_nodes(true);
2983
2984 // Don't use rich formatting to prevent ANSI escape codes from being written to log files.
2985 print_header(false);
2986
2987 #ifdef TOOLS_ENABLED
2988 int accessibility_mode_editor = 0;
2989 int tablet_driver_editor = -1;
2990 if (editor || project_manager || cmdline_tool) {
2991 OS::get_singleton()->benchmark_begin_measure("Startup", "Initialize Early Settings");
2992
2993 EditorPaths::create();
2994
2995 // Editor setting class is not available, load config directly.
2996 if (!init_use_custom_screen && (editor || project_manager) && EditorPaths::get_singleton()->are_paths_valid()) {
2997 ERR_FAIL_COND_V(!DirAccess::dir_exists_absolute(EditorPaths::get_singleton()->get_config_dir()), FAILED);
2998
2999 String config_file_path = EditorSettings::get_existing_settings_path();
3000 if (FileAccess::exists(config_file_path)) {
3001 Error err;
3002 Ref<FileAccess> f = FileAccess::open(config_file_path, FileAccess::READ, &err);
3003 if (f.is_valid()) {
3004 VariantParser::StreamFile stream;
3005 stream.f = f;
3006
3007 String assign;
3008 Variant value;
3009 VariantParser::Tag next_tag;
3010
3011 int lines = 0;
3012 String error_text;
3013
3014 VariantParser::ResourceParser rp_new;
3015 rp_new.ext_func = _parse_resource_dummy;
3016 rp_new.sub_func = _parse_resource_dummy;
3017
3018 bool screen_found = false;
3019 String screen_property;
3020
3021 bool prefer_wayland_found = false;
3022 bool prefer_wayland = false;
3023
3024 bool tablet_found = false;
3025
3026 bool ac_found = false;
3027
3028 if (editor) {
3029 screen_property = "interface/editor/editor_screen";
3030 } else if (project_manager) {
3031 screen_property = "interface/editor/project_manager_screen";
3032 } else {
3033 // Skip.
3034 screen_found = true;
3035 }
3036
3037 if (!display_driver.is_empty()) {
3038 // Skip.
3039 prefer_wayland_found = true;
3040 }
3041
3042 while (!screen_found || !init_expand_to_title_found || !init_display_scale_found || !init_custom_scale_found || !prefer_wayland_found || !tablet_found || !ac_found) {
3043 assign = Variant();
3044 next_tag.fields.clear();
3045 next_tag.name = String();
3046
3047 err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp_new, true);
3048 if (err == ERR_FILE_EOF) {
3049 break;
3050 }
3051
3052 if (err == OK && !assign.is_empty()) {
3053 if (!screen_found && assign == screen_property) {
3054 init_screen = value;
3055 screen_found = true;
3056
3057 if (editor) {
3058 restore_editor_window_layout = value.operator int() == EditorSettings::InitialScreen::INITIAL_SCREEN_AUTO;
3059 }
3060 }
3061 if (!ac_found && assign == "interface/accessibility/accessibility_support") {
3062 accessibility_mode_editor = value;
3063 ac_found = true;
3064 } else if (!init_expand_to_title_found && assign == "interface/editor/expand_to_title") {
3065 init_expand_to_title = value;
3066 init_expand_to_title_found = true;
3067 } else if (!init_display_scale_found && assign == "interface/editor/display_scale") {
3068 init_display_scale = value;
3069 init_display_scale_found = true;
3070 } else if (!init_custom_scale_found && assign == "interface/editor/custom_display_scale") {
3071 init_custom_scale = value;
3072 init_custom_scale_found = true;
3073 } else if (!prefer_wayland_found && assign == "run/platforms/linuxbsd/prefer_wayland") {
3074 if (!OS::get_singleton()->get_environment("WAYLAND_DISPLAY").is_empty()) {
3075 // Do not prefer Wayland if not currently on a Wayland session.
3076 // This avoids error messages on startup when currently on X11
3077 // and the Prefer Wayland setting is enabled.
3078 prefer_wayland = value;
3079 }
3080 prefer_wayland_found = true;
3081 } else if (!tablet_found && assign == "interface/editor/tablet_driver") {
3082 tablet_driver_editor = value;
3083 tablet_found = true;
3084 }
3085 }
3086 }
3087
3088 if (display_driver.is_empty()) {
3089 if (prefer_wayland) {
3090 display_driver = "wayland";
3091 } else {
3092 display_driver = "default";
3093 }
3094 }
3095 }
3096 }
3097 }
3098
3099 if (found_project && EditorPaths::get_singleton()->is_self_contained()) {
3100 if (ProjectSettings::get_singleton()->get_resource_path() == OS::get_singleton()->get_executable_path().get_base_dir()) {
3101 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.");
3102 OS::get_singleton()->set_exit_code(EXIT_FAILURE);
3103 return FAILED;
3104 }
3105 }
3106
3107 bool has_command_line_window_override = init_use_custom_pos || init_use_custom_screen || init_windowed;
3108 if (editor && !has_command_line_window_override && restore_editor_window_layout) {
3109 Ref<ConfigFile> config;
3110 config.instantiate();
3111 // Load and amend existing config if it exists.
3112 Error err = config->load(EditorPaths::get_singleton()->get_project_settings_dir().path_join("editor_layout.cfg"));
3113 if (err == OK) {
3114 init_screen = config->get_value("EditorWindow", "screen", init_screen);
3115 String mode = config->get_value("EditorWindow", "mode", "maximized");
3116 window_size = config->get_value("EditorWindow", "size", window_size);
3117 if (mode == "windowed") {
3118 window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
3119 init_windowed = true;
3120 } else if (mode == "fullscreen") {
3121 window_mode = DisplayServer::WINDOW_MODE_FULLSCREEN;
3122 init_fullscreen = true;
3123 } else {
3124 window_mode = DisplayServer::WINDOW_MODE_MAXIMIZED;
3125 init_maximized = true;
3126 }
3127
3128 if (init_windowed) {
3129 init_use_custom_pos = true;
3130 init_custom_pos = config->get_value("EditorWindow", "position", Vector2i(0, 0));
3131 }
3132 }
3133 }
3134
3135 if (init_screen == EditorSettings::InitialScreen::INITIAL_SCREEN_AUTO) {
3136 init_screen = DisplayServer::SCREEN_PRIMARY;
3137 }
3138
3139 OS::get_singleton()->benchmark_end_measure("Startup", "Initialize Early Settings");
3140 }
3141 #endif
3142
3143 OS::get_singleton()->benchmark_begin_measure("Startup", "Servers");
3144
3145 tsman = memnew(TextServerManager);
3146 if (tsman) {
3147 Ref<TextServerDummy> ts;
3148 ts.instantiate();
3149 tsman->add_interface(ts);
3150 }
3151
3152 #ifndef PHYSICS_3D_DISABLED
3153 physics_server_3d_manager = memnew(PhysicsServer3DManager);
3154 #endif // PHYSICS_3D_DISABLED
3155 #ifndef PHYSICS_2D_DISABLED
3156 physics_server_2d_manager = memnew(PhysicsServer2DManager);
3157 #endif // PHYSICS_2D_DISABLED
3158
3159 #ifndef NAVIGATION_2D_DISABLED
3160 NavigationServer2DManager::initialize_server_manager();
3161 #endif // NAVIGATION_2D_DISABLED
3162 #ifndef NAVIGATION_3D_DISABLED
3163 NavigationServer3DManager::initialize_server_manager();
3164 #endif // NAVIGATION_3D_DISABLED
3165
3166 register_server_types();
3167 {
3168 OS::get_singleton()->benchmark_begin_measure("Servers", "Modules and Extensions");
3169
3170 initialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
3171 GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
3172
3173 OS::get_singleton()->benchmark_end_measure("Servers", "Modules and Extensions");
3174 }
3175
3176 /* Initialize Input */
3177
3178 {
3179 OS::get_singleton()->benchmark_begin_measure("Servers", "Input");
3180
3181 input = memnew(Input);
3182 OS::get_singleton()->initialize_joypads();
3183
3184 OS::get_singleton()->benchmark_end_measure("Servers", "Input");
3185 }
3186
3187 /* Initialize Display Server */
3188
3189 {
3190 OS::get_singleton()->benchmark_begin_measure("Servers", "Display");
3191
3192 if (display_driver.is_empty()) {
3193 display_driver = GLOBAL_GET("display/display_server/driver");
3194 }
3195
3196 int display_driver_idx = -1;
3197
3198 if (display_driver.is_empty() || display_driver == "default") {
3199 display_driver_idx = 0;
3200 } else {
3201 for (int i = 0; i < DisplayServer::get_create_function_count(); i++) {
3202 String name = DisplayServer::get_create_function_name(i);
3203 if (display_driver == name) {
3204 display_driver_idx = i;
3205 break;
3206 }
3207 }
3208
3209 if (display_driver_idx < 0) {
3210 // If the requested driver wasn't found, pick the first entry.
3211 // If all else failed it would be the headless server.
3212 display_driver_idx = 0;
3213 }
3214 }
3215
3216 Vector2i *window_position = nullptr;
3217 Vector2i position = init_custom_pos;
3218 if (init_use_custom_pos) {
3219 window_position = &position;
3220 }
3221
3222 Color boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", boot_splash_bg_color);
3223 DisplayServer::set_early_window_clear_color_override(true, boot_bg_color);
3224
3225 DisplayServer::Context context;
3226 if (editor) {
3227 context = DisplayServer::CONTEXT_EDITOR;
3228 } else if (project_manager) {
3229 context = DisplayServer::CONTEXT_PROJECTMAN;
3230 } else {
3231 context = DisplayServer::CONTEXT_ENGINE;
3232 }
3233
3234 if (init_embed_parent_window_id) {
3235 // Reset flags and other settings to be sure it's borderless and windowed. The position and size should have been initialized correctly
3236 // from --position and --resolution parameters.
3237 window_mode = DisplayServer::WINDOW_MODE_WINDOWED;
3238 window_flags = DisplayServer::WINDOW_FLAG_BORDERLESS_BIT;
3239 if (bool(GLOBAL_GET("display/window/size/transparent"))) {
3240 window_flags |= DisplayServer::WINDOW_FLAG_TRANSPARENT_BIT;
3241 }
3242 }
3243
3244 #ifdef TOOLS_ENABLED
3245 if ((project_manager || editor) && init_expand_to_title) {
3246 window_flags |= DisplayServer::WINDOW_FLAG_EXTEND_TO_TITLE_BIT;
3247 }
3248 #endif
3249
3250 if (!accessibility_mode_set) {
3251 #ifdef TOOLS_ENABLED
3252 if (editor || project_manager || cmdline_tool) {
3253 accessibility_mode = (DisplayServer::AccessibilityMode)accessibility_mode_editor;
3254 } else {
3255 #else
3256 {
3257 #endif
3258 accessibility_mode = (DisplayServer::AccessibilityMode)GLOBAL_GET("accessibility/general/accessibility_support").operator int64_t();
3259 }
3260 }
3261 DisplayServer::accessibility_set_mode(accessibility_mode);
3262
3263 // rendering_driver now held in static global String in main and initialized in setup()
3264 Error err;
3265 display_server = DisplayServer::create(display_driver_idx, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, context, init_embed_parent_window_id, err);
3266 if (err != OK || display_server == nullptr) {
3267 String last_name = DisplayServer::get_create_function_name(display_driver_idx);
3268
3269 // We can't use this display server, try other ones as fallback.
3270 // Skip headless (always last registered) because that's not what users
3271 // would expect if they didn't request it explicitly.
3272 for (int i = 0; i < DisplayServer::get_create_function_count() - 1; i++) {
3273 if (i == display_driver_idx) {
3274 continue; // Don't try the same twice.
3275 }
3276 String name = DisplayServer::get_create_function_name(i);
3277 WARN_PRINT(vformat("Display driver %s failed, falling back to %s.", last_name, name));
3278
3279 display_server = DisplayServer::create(i, rendering_driver, window_mode, window_vsync_mode, window_flags, window_position, window_size, init_screen, context, init_embed_parent_window_id, err);
3280 if (err == OK && display_server != nullptr) {
3281 break;
3282 }
3283 }
3284 }
3285
3286 if (err != OK || display_server == nullptr) {
3287 ERR_PRINT("Unable to create DisplayServer, all display drivers failed.\nUse \"--headless\" command line argument to run the engine in headless mode if this is desired (e.g. for continuous integration).");
3288
3289 if (display_server) {
3290 memdelete(display_server);
3291 }
3292
3293 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
3294 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
3295 unregister_server_types();
3296
3297 if (input) {
3298 memdelete(input);
3299 }
3300 if (tsman) {
3301 memdelete(tsman);
3302 }
3303 #ifndef PHYSICS_3D_DISABLED
3304 if (physics_server_3d_manager) {
3305 memdelete(physics_server_3d_manager);
3306 }
3307 #endif // PHYSICS_3D_DISABLED
3308 #ifndef PHYSICS_2D_DISABLED
3309 if (physics_server_2d_manager) {
3310 memdelete(physics_server_2d_manager);
3311 }
3312 #endif // PHYSICS_2D_DISABLED
3313
3314 return err;
3315 }
3316
3317 #ifdef TOOLS_ENABLED
3318 if (project_manager) {
3319 float ui_scale = init_custom_scale;
3320 switch (init_display_scale) {
3321 case 0:
3322 ui_scale = EditorSettings::get_auto_display_scale();
3323 break;
3324 case 1:
3325 ui_scale = 0.75;
3326 break;
3327 case 2:
3328 ui_scale = 1.0;
3329 break;
3330 case 3:
3331 ui_scale = 1.25;
3332 break;
3333 case 4:
3334 ui_scale = 1.5;
3335 break;
3336 case 5:
3337 ui_scale = 1.75;
3338 break;
3339 case 6:
3340 ui_scale = 2.0;
3341 break;
3342 default:
3343 break;
3344 }
3345 if (!(force_res || use_custom_res)) {
3346 display_server->window_set_size(Size2(window_size) * ui_scale, DisplayServer::MAIN_WINDOW_ID);
3347 }
3348 if (display_server->has_feature(DisplayServer::FEATURE_SUBWINDOWS) && !display_server->has_feature(DisplayServer::FEATURE_SELF_FITTING_WINDOWS)) {
3349 Size2 real_size = DisplayServer::get_singleton()->window_get_size();
3350 Rect2i scr_rect = display_server->screen_get_usable_rect(init_screen);
3351 display_server->window_set_position(scr_rect.position + (scr_rect.size - real_size) / 2, DisplayServer::MAIN_WINDOW_ID);
3352 }
3353 }
3354 #endif
3355 if (display_server->has_feature(DisplayServer::FEATURE_SUBWINDOWS)) {
3356 display_server->show_window(DisplayServer::MAIN_WINDOW_ID);
3357 }
3358
3359 if (display_server->has_feature(DisplayServer::FEATURE_ORIENTATION)) {
3360 display_server->screen_set_orientation(window_orientation);
3361 }
3362
3363 OS::get_singleton()->benchmark_end_measure("Servers", "Display");
3364 }
3365
3366 // Max FPS needs to be set after the DisplayServer is created.
3367 RenderingDevice *rd = RenderingDevice::get_singleton();
3368 if (rd) {
3369 rd->_set_max_fps(engine->get_max_fps());
3370 }
3371
3372 #ifdef TOOLS_ENABLED
3373 // If the editor is running in windowed mode, ensure the window rect fits
3374 // the screen in case screen count or position has changed.
3375 if (editor && init_windowed) {
3376 // We still need to check we are actually in windowed mode, because
3377 // certain platform might only support one fullscreen window.
3378 if (DisplayServer::get_singleton()->window_get_mode() == DisplayServer::WINDOW_MODE_WINDOWED) {
3379 Vector2i current_size = DisplayServer::get_singleton()->window_get_size();
3380 Vector2i current_pos = DisplayServer::get_singleton()->window_get_position();
3381 int screen = DisplayServer::get_singleton()->window_get_current_screen();
3382 Rect2i screen_rect = DisplayServer::get_singleton()->screen_get_usable_rect(screen);
3383
3384 Vector2i adjusted_end = screen_rect.get_end().min(current_pos + current_size);
3385 Vector2i adjusted_pos = screen_rect.get_position().max(adjusted_end - current_size);
3386 Vector2i adjusted_size = DisplayServer::get_singleton()->window_get_min_size().max(adjusted_end - adjusted_pos);
3387
3388 if (current_pos != adjusted_end || current_size != adjusted_size) {
3389 DisplayServer::get_singleton()->window_set_position(adjusted_pos);
3390 DisplayServer::get_singleton()->window_set_size(adjusted_size);
3391 }
3392 }
3393 }
3394 #endif
3395
3396 if (GLOBAL_GET("debug/settings/stdout/print_fps") || print_fps) {
3397 // Print requested V-Sync mode at startup to diagnose the printed FPS not going above the monitor refresh rate.
3398 switch (window_vsync_mode) {
3399 case DisplayServer::VSyncMode::VSYNC_DISABLED:
3400 print_line("Requested V-Sync mode: Disabled");
3401 break;
3402 case DisplayServer::VSyncMode::VSYNC_ENABLED:
3403 print_line("Requested V-Sync mode: Enabled - FPS will likely be capped to the monitor refresh rate.");
3404 break;
3405 case DisplayServer::VSyncMode::VSYNC_ADAPTIVE:
3406 print_line("Requested V-Sync mode: Adaptive");
3407 break;
3408 case DisplayServer::VSyncMode::VSYNC_MAILBOX:
3409 print_line("Requested V-Sync mode: Mailbox");
3410 break;
3411 }
3412 }
3413
3414 if (OS::get_singleton()->_separate_thread_render) {
3415 WARN_PRINT("The separate rendering thread feature is experimental. Feel free to try it since it will eventually become a stable feature.\n"
3416 "However, bear in mind that at the moment it can lead to project crashes or instability.\n"
3417 "So, unless you want to test the engine, set the \"rendering/driver/threads/thread_model\" project setting to 'Safe'.");
3418 }
3419
3420 /* Initialize Pen Tablet Driver */
3421
3422 {
3423 OS::get_singleton()->benchmark_begin_measure("Servers", "Tablet Driver");
3424
3425 GLOBAL_DEF_RST_NOVAL("input_devices/pen_tablet/driver", "");
3426 GLOBAL_DEF_RST_NOVAL(PropertyInfo(Variant::STRING, "input_devices/pen_tablet/driver.windows", PROPERTY_HINT_ENUM, "auto,winink,wintab,dummy"), "");
3427
3428 #ifdef TOOLS_ENABLED
3429 if (tablet_driver.is_empty() && tablet_driver_editor != -1) {
3430 tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(tablet_driver_editor);
3431 }
3432 #endif
3433
3434 if (tablet_driver.is_empty()) { // specified in project.godot
3435 tablet_driver = GLOBAL_GET("input_devices/pen_tablet/driver");
3436 if (tablet_driver.is_empty()) {
3437 tablet_driver = DisplayServer::get_singleton()->tablet_get_driver_name(0);
3438 }
3439 }
3440
3441 for (int i = 0; i < DisplayServer::get_singleton()->tablet_get_driver_count(); i++) {
3442 if (tablet_driver == DisplayServer::get_singleton()->tablet_get_driver_name(i)) {
3443 DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(i));
3444 break;
3445 }
3446 }
3447
3448 if (DisplayServer::get_singleton()->tablet_get_current_driver().is_empty()) {
3449 DisplayServer::get_singleton()->tablet_set_current_driver(DisplayServer::get_singleton()->tablet_get_driver_name(0));
3450 }
3451
3452 print_verbose("Using \"" + DisplayServer::get_singleton()->tablet_get_current_driver() + "\" pen tablet driver...");
3453
3454 OS::get_singleton()->benchmark_end_measure("Servers", "Tablet Driver");
3455 }
3456
3457 /* Initialize Rendering Server */
3458
3459 {
3460 OS::get_singleton()->benchmark_begin_measure("Servers", "Rendering");
3461
3462 rendering_server = memnew(RenderingServerDefault(OS::get_singleton()->is_separate_thread_rendering_enabled()));
3463
3464 rendering_server->init();
3465 //rendering_server->call_set_use_vsync(OS::get_singleton()->_use_vsync);
3466 rendering_server->set_render_loop_enabled(!disable_render_loop);
3467
3468 if (profile_gpu || (!editor && bool(GLOBAL_GET("debug/settings/stdout/print_gpu_profile")))) {
3469 rendering_server->set_print_gpu_profile(true);
3470 }
3471
3472 OS::get_singleton()->benchmark_end_measure("Servers", "Rendering");
3473 }
3474
3475 #ifdef UNIX_ENABLED
3476 // Print warning after initializing the renderer but before initializing audio.
3477 if (OS::get_singleton()->get_environment("USER") == "root" && !OS::get_singleton()->has_environment("GODOT_SILENCE_ROOT_WARNING")) {
3478 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.");
3479 }
3480 #endif
3481
3482 /* Initialize Audio Driver */
3483
3484 {
3485 OS::get_singleton()->benchmark_begin_measure("Servers", "Audio");
3486
3487 AudioDriverManager::initialize(audio_driver_idx);
3488
3489 // Right moment to create and initialize the audio server.
3490 audio_server = memnew(AudioServer);
3491 audio_server->init();
3492
3493 OS::get_singleton()->benchmark_end_measure("Servers", "Audio");
3494 }
3495
3496 #ifndef XR_DISABLED
3497 /* Initialize XR Server */
3498
3499 {
3500 OS::get_singleton()->benchmark_begin_measure("Servers", "XR");
3501
3502 xr_server = memnew(XRServer);
3503
3504 OS::get_singleton()->benchmark_end_measure("Servers", "XR");
3505 }
3506 #endif // XR_DISABLED
3507
3508 OS::get_singleton()->benchmark_end_measure("Startup", "Servers");
3509
3510 #ifndef WEB_ENABLED
3511 // Add a blank line for readability.
3512 Engine::get_singleton()->print_header("");
3513 #endif // WEB_ENABLED
3514
3515 register_core_singletons();
3516
3517 /* Initialize the main window and boot screen */
3518
3519 {
3520 OS::get_singleton()->benchmark_begin_measure("Startup", "Setup Window and Boot");
3521
3522 MAIN_PRINT("Main: Setup Logo");
3523
3524 if (!init_embed_parent_window_id) {
3525 if (init_windowed) {
3526 //do none..
3527 } else if (init_maximized) {
3528 DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_MAXIMIZED);
3529 } else if (init_fullscreen) {
3530 DisplayServer::get_singleton()->window_set_mode(DisplayServer::WINDOW_MODE_FULLSCREEN);
3531 }
3532 if (init_always_on_top) {
3533 DisplayServer::get_singleton()->window_set_flag(DisplayServer::WINDOW_FLAG_ALWAYS_ON_TOP, true);
3534 }
3535 }
3536
3537 Color clear = GLOBAL_DEF_BASIC("rendering/environment/defaults/default_clear_color", Color(0.3, 0.3, 0.3));
3538 RenderingServer::get_singleton()->set_default_clear_color(clear);
3539
3540 if (p_show_boot_logo) {
3541 setup_boot_logo();
3542 }
3543
3544 MAIN_PRINT("Main: Clear Color");
3545
3546 DisplayServer::set_early_window_clear_color_override(false);
3547
3548 GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "application/config/icon", PROPERTY_HINT_FILE, "*.png,*.bmp,*.hdr,*.jpg,*.jpeg,*.svg,*.tga,*.exr,*.webp"), String());
3549 GLOBAL_DEF(PropertyInfo(Variant::STRING, "application/config/macos_native_icon", PROPERTY_HINT_FILE, "*.icns"), String());
3550 GLOBAL_DEF(PropertyInfo(Variant::STRING, "application/config/windows_native_icon", PROPERTY_HINT_FILE, "*.ico"), String());
3551
3552 MAIN_PRINT("Main: Touch Input");
3553
3554 Input *id = Input::get_singleton();
3555 if (id) {
3556 bool agile_input_event_flushing = GLOBAL_DEF("input_devices/buffering/agile_event_flushing", false);
3557 id->set_agile_input_event_flushing(agile_input_event_flushing);
3558
3559 if (bool(GLOBAL_DEF_BASIC("input_devices/pointing/emulate_touch_from_mouse", false)) &&
3560 !(editor || project_manager)) {
3561 if (!DisplayServer::get_singleton()->is_touchscreen_available()) {
3562 //only if no touchscreen ui hint, set emulation
3563 id->set_emulate_touch_from_mouse(true);
3564 }
3565 }
3566
3567 id->set_emulate_mouse_from_touch(bool(GLOBAL_DEF_BASIC("input_devices/pointing/emulate_mouse_from_touch", true)));
3568
3569 if (editor) {
3570 id->set_emulate_mouse_from_touch(true);
3571 }
3572 }
3573
3574 OS::get_singleton()->benchmark_end_measure("Startup", "Setup Window and Boot");
3575 }
3576
3577 MAIN_PRINT("Main: Load Translations and Remaps");
3578
3579 /* Setup translations and remaps */
3580
3581 {
3582 OS::get_singleton()->benchmark_begin_measure("Startup", "Translations and Remaps");
3583
3584 translation_server->setup(); //register translations, load them, etc.
3585 if (!locale.is_empty()) {
3586 translation_server->set_locale(locale);
3587 }
3588 translation_server->load_project_translations(translation_server->get_main_domain());
3589 ResourceLoader::load_translation_remaps(); //load remaps for resources
3590
3591 OS::get_singleton()->benchmark_end_measure("Startup", "Translations and Remaps");
3592 }
3593
3594 MAIN_PRINT("Main: Load TextServer");
3595
3596 /* Setup Text Server */
3597
3598 {
3599 OS::get_singleton()->benchmark_begin_measure("Startup", "Text Server");
3600
3601 /* Enum text drivers */
3602 GLOBAL_DEF_RST("internationalization/rendering/text_driver", "");
3603 String text_driver_options;
3604 for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
3605 const String driver_name = TextServerManager::get_singleton()->get_interface(i)->get_name();
3606 if (driver_name == "Dummy") {
3607 // Dummy text driver cannot draw any text, making the editor unusable if selected.
3608 continue;
3609 }
3610 if (!text_driver_options.is_empty() && !text_driver_options.contains_char(',')) {
3611 // Not the first option; add a comma before it as a separator for the property hint.
3612 text_driver_options += ",";
3613 }
3614 text_driver_options += driver_name;
3615 }
3616 ProjectSettings::get_singleton()->set_custom_property_info(PropertyInfo(Variant::STRING, "internationalization/rendering/text_driver", PROPERTY_HINT_ENUM, text_driver_options));
3617
3618 /* Determine text driver */
3619 if (text_driver.is_empty()) {
3620 text_driver = GLOBAL_GET("internationalization/rendering/text_driver");
3621 }
3622
3623 if (!text_driver.is_empty()) {
3624 /* Load user selected text server. */
3625 for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
3626 if (TextServerManager::get_singleton()->get_interface(i)->get_name() == text_driver) {
3627 text_driver_idx = i;
3628 break;
3629 }
3630 }
3631 }
3632
3633 if (text_driver_idx < 0) {
3634 /* If not selected, use one with the most features available. */
3635 int max_features = 0;
3636 for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
3637 uint32_t features = TextServerManager::get_singleton()->get_interface(i)->get_features();
3638 int feature_number = 0;
3639 while (features) {
3640 feature_number += features & 1;
3641 features >>= 1;
3642 }
3643 if (feature_number >= max_features) {
3644 max_features = feature_number;
3645 text_driver_idx = i;
3646 }
3647 }
3648 }
3649 if (text_driver_idx >= 0) {
3650 Ref<TextServer> ts = TextServerManager::get_singleton()->get_interface(text_driver_idx);
3651 TextServerManager::get_singleton()->set_primary_interface(ts);
3652 if (ts->has_feature(TextServer::FEATURE_USE_SUPPORT_DATA)) {
3653 ts->load_support_data("res://" + ts->get_support_data_filename());
3654 }
3655 } else {
3656 ERR_FAIL_V_MSG(ERR_CANT_CREATE, "TextServer: Unable to create TextServer interface.");
3657 }
3658
3659 OS::get_singleton()->benchmark_end_measure("Startup", "Text Server");
3660 }
3661
3662 MAIN_PRINT("Main: Load Scene Types");
3663
3664 OS::get_singleton()->benchmark_begin_measure("Startup", "Scene");
3665
3666 // Initialize ThemeDB early so that scene types can register their theme items.
3667 // Default theme will be initialized later, after modules and ScriptServer are ready.
3668 initialize_theme_db();
3669
3670 #if !defined(NAVIGATION_2D_DISABLED) || !defined(NAVIGATION_3D_DISABLED)
3671 MAIN_PRINT("Main: Load Navigation");
3672 #endif // !defined(NAVIGATION_2D_DISABLED) || !defined(NAVIGATION_3D_DISABLED)
3673
3674 #ifndef NAVIGATION_3D_DISABLED
3675 NavigationServer3DManager::initialize_server();
3676 #endif // NAVIGATION_3D_DISABLED
3677 #ifndef NAVIGATION_2D_DISABLED
3678 NavigationServer2DManager::initialize_server();
3679 #endif // NAVIGATION_2D_DISABLED
3680
3681 register_scene_types();
3682 register_driver_types();
3683
3684 register_scene_singletons();
3685
3686 {
3687 OS::get_singleton()->benchmark_begin_measure("Scene", "Modules and Extensions");
3688
3689 initialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
3690 GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
3691
3692 OS::get_singleton()->benchmark_end_measure("Scene", "Modules and Extensions");
3693
3694 // We need to initialize the movie writer here in case
3695 // one of the user-provided GDExtensions subclasses MovieWriter.
3696 if (Engine::get_singleton()->get_write_movie_path() != String()) {
3697 movie_writer = MovieWriter::find_writer_for_file(Engine::get_singleton()->get_write_movie_path());
3698 if (movie_writer == nullptr) {
3699 ERR_PRINT("Can't find movie writer for file type, aborting: " + Engine::get_singleton()->get_write_movie_path());
3700 Engine::get_singleton()->set_write_movie_path(String());
3701 }
3702 }
3703 }
3704
3705 PackedStringArray extensions;
3706 extensions.push_back("gd");
3707 if (ClassDB::class_exists("CSharpScript")) {
3708 extensions.push_back("cs");
3709 }
3710 extensions.push_back("gdshader");
3711 GLOBAL_DEF_NOVAL(PropertyInfo(Variant::PACKED_STRING_ARRAY, "editor/script/search_in_file_extensions"), extensions); // Note: should be defined after Scene level modules init to see .NET.
3712
3713 OS::get_singleton()->benchmark_end_measure("Startup", "Scene");
3714
3715 #ifdef TOOLS_ENABLED
3716 ClassDB::set_current_api(ClassDB::API_EDITOR);
3717 register_editor_types();
3718
3719 {
3720 OS::get_singleton()->benchmark_begin_measure("Editor", "Modules and Extensions");
3721
3722 initialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
3723 GDExtensionManager::get_singleton()->initialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
3724
3725 OS::get_singleton()->benchmark_end_measure("Editor", "Modules and Extensions");
3726 }
3727
3728 ClassDB::set_current_api(ClassDB::API_CORE);
3729
3730 #endif
3731
3732 MAIN_PRINT("Main: Load Platforms");
3733
3734 OS::get_singleton()->benchmark_begin_measure("Startup", "Platforms");
3735
3736 register_platform_apis();
3737
3738 OS::get_singleton()->benchmark_end_measure("Startup", "Platforms");
3739
3740 GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "display/mouse_cursor/custom_image", PROPERTY_HINT_FILE, "*.png,*.bmp,*.hdr,*.jpg,*.jpeg,*.svg,*.tga,*.exr,*.webp"), String());
3741 GLOBAL_DEF_BASIC("display/mouse_cursor/custom_image_hotspot", Vector2());
3742 GLOBAL_DEF_BASIC("display/mouse_cursor/tooltip_position_offset", Point2(10, 10));
3743
3744 if (String(GLOBAL_GET("display/mouse_cursor/custom_image")) != String()) {
3745 Ref<Texture2D> cursor = ResourceLoader::load(
3746 GLOBAL_GET("display/mouse_cursor/custom_image"));
3747 if (cursor.is_valid()) {
3748 Vector2 hotspot = GLOBAL_GET("display/mouse_cursor/custom_image_hotspot");
3749 Input::get_singleton()->set_custom_mouse_cursor(cursor, Input::CURSOR_ARROW, hotspot);
3750 }
3751 }
3752
3753 OS::get_singleton()->benchmark_begin_measure("Startup", "Finalize Setup");
3754
3755 camera_server = CameraServer::create();
3756
3757 MAIN_PRINT("Main: Load Physics");
3758
3759 initialize_physics();
3760
3761 register_server_singletons();
3762
3763 // This loads global classes, so it must happen before custom loaders and savers are registered
3764 ScriptServer::init_languages();
3765
3766 #if TOOLS_ENABLED
3767
3768 // Setting up the callback to execute a scan for UIDs on disk when a UID
3769 // does not exist in the UID cache on startup. This prevents invalid UID errors
3770 // when opening a project without a UID cache file or with an invalid cache.
3771 if (editor) {
3772 ResourceUID::scan_for_uid_on_startup = EditorFileSystem::scan_for_uid;
3773 }
3774
3775 #endif
3776
3777 theme_db->initialize_theme();
3778 audio_server->load_default_bus_layout();
3779
3780 #if defined(MODULE_MONO_ENABLED) && defined(TOOLS_ENABLED)
3781 // Hacky to have it here, but we don't have good facility yet to let modules
3782 // register command line options to call at the right time. This needs to happen
3783 // after init'ing the ScriptServer, but also after init'ing the ThemeDB,
3784 // for the C# docs generation in the bindings.
3785 List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
3786 BindingsGenerator::handle_cmdline_args(cmdline_args);
3787 #endif
3788
3789 if (use_debug_profiler && EngineDebugger::is_active()) {
3790 // Start the "scripts" profiler, used in local debugging.
3791 // We could add more, and make the CLI arg require a comma-separated list of profilers.
3792 EngineDebugger::get_singleton()->profiler_enable("scripts", true);
3793 }
3794
3795 if (!project_manager) {
3796 // If not running the project manager, and now that the engine is
3797 // able to load resources, load the global shader variables.
3798 // If running on editor, don't load the textures because the editor
3799 // may want to import them first. Editor will reload those later.
3800 rendering_server->global_shader_parameters_load_settings(!editor);
3801 }
3802
3803 OS::get_singleton()->benchmark_end_measure("Startup", "Finalize Setup");
3804
3805 _start_success = true;
3806
3807 ClassDB::set_current_api(ClassDB::API_NONE); //no more APIs are registered at this point
3808
3809 print_verbose("CORE API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_CORE)));
3810 print_verbose("EDITOR API HASH: " + uitos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
3811 MAIN_PRINT("Main: Done");
3812
3813 OS::get_singleton()->benchmark_end_measure("Startup", "Main::Setup2");
3814
3815 return OK;
3816 }
3817
3818 void Main::setup_boot_logo() {
3819 GodotProfileZone("setup_boot_logo");
3820 MAIN_PRINT("Main: Load Boot Image");
3821
3822 #if !defined(TOOLS_ENABLED) && defined(WEB_ENABLED)
3823 bool show_logo = false;
3824 #else
3825 bool show_logo = true;
3826 #endif
3827
3828 if (show_logo) { //boot logo!
3829 const bool boot_logo_image = GLOBAL_DEF_BASIC("application/boot_splash/show_image", true);
3830
3831 const RenderingServer::SplashStretchMode boot_stretch_mode = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "application/boot_splash/stretch_mode", PROPERTY_HINT_ENUM, "Disabled,Keep,Keep Width,Keep Height,Cover,Ignore"), 1);
3832 const bool boot_logo_filter = GLOBAL_DEF_BASIC("application/boot_splash/use_filter", true);
3833 String boot_logo_path = GLOBAL_DEF_BASIC(PropertyInfo(Variant::STRING, "application/boot_splash/image", PROPERTY_HINT_FILE, "*.png"), String());
3834
3835 // If the UID cache is missing or invalid, it could be 'normal' for the UID to not exist in memory.
3836 // It's too soon to scan the project files since the ResourceFormatImporter is not loaded yet,
3837 // so to prevent printing errors, we will just skip the custom boot logo this time.
3838 if (boot_logo_path.begins_with("uid://")) {
3839 const ResourceUID::ID logo_id = ResourceUID::get_singleton()->text_to_id(boot_logo_path);
3840 if (ResourceUID::get_singleton()->has_id(logo_id)) {
3841 boot_logo_path = ResourceUID::get_singleton()->get_id_path(logo_id).strip_edges();
3842 } else {
3843 boot_logo_path = String();
3844 }
3845 }
3846
3847 Ref<Image> boot_logo;
3848
3849 if (boot_logo_image) {
3850 if (!boot_logo_path.is_empty()) {
3851 boot_logo.instantiate();
3852 Error load_err = ImageLoader::load_image(boot_logo_path, boot_logo);
3853 if (load_err) {
3854 String msg = (boot_logo_path.ends_with(".png") ? "" : "The only supported format is PNG.");
3855 ERR_PRINT("Non-existing or invalid boot splash at '" + boot_logo_path + +"'. " + msg + " Loading default splash.");
3856 }
3857 }
3858 } else {
3859 // Create a 1×1 transparent image. This will effectively hide the splash image.
3860 boot_logo.instantiate();
3861 boot_logo->initialize_data(1, 1, false, Image::FORMAT_RGBA8);
3862 boot_logo->set_pixel(0, 0, Color(0, 0, 0, 0));
3863 }
3864
3865 Color boot_bg_color = GLOBAL_GET("application/boot_splash/bg_color");
3866
3867 #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
3868 boot_bg_color = GLOBAL_DEF_BASIC("application/boot_splash/bg_color", (editor || project_manager) ? boot_splash_editor_bg_color : boot_splash_bg_color);
3869 #endif
3870 if (boot_logo.is_valid()) {
3871 RenderingServer::get_singleton()->set_boot_image_with_stretch(boot_logo, boot_bg_color, boot_stretch_mode, boot_logo_filter);
3872
3873 } else {
3874 #ifndef NO_DEFAULT_BOOT_LOGO
3875 MAIN_PRINT("Main: Create bootsplash");
3876 #if defined(TOOLS_ENABLED) && !defined(NO_EDITOR_SPLASH)
3877 Ref<Image> splash = (editor || project_manager) ? memnew(Image(boot_splash_editor_png)) : memnew(Image(boot_splash_png));
3878 #else
3879 Ref<Image> splash = memnew(Image(boot_splash_png));
3880 #endif
3881
3882 MAIN_PRINT("Main: ClearColor");
3883 RenderingServer::get_singleton()->set_default_clear_color(boot_bg_color);
3884 MAIN_PRINT("Main: Image");
3885 RenderingServer::get_singleton()->set_boot_image_with_stretch(splash, boot_bg_color, RenderingServer::SPLASH_STRETCH_MODE_DISABLED);
3886 #endif
3887 }
3888
3889 #if defined(TOOLS_ENABLED) && defined(MACOS_ENABLED)
3890 if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_ICON) && OS::get_singleton()->get_bundle_icon_path().is_empty()) {
3891 Ref<Image> icon = memnew(Image(app_icon_png));
3892 DisplayServer::get_singleton()->set_icon(icon);
3893 }
3894 #endif
3895 }
3896 RenderingServer::get_singleton()->set_default_clear_color(
3897 GLOBAL_GET("rendering/environment/defaults/default_clear_color"));
3898 }
3899
3900 String Main::get_rendering_driver_name() {
3901 return rendering_driver;
3902 }
3903
3904 String Main::get_locale_override() {
3905 return locale;
3906 }
3907
3908 // everything the main loop needs to know about frame timings
3909 static MainTimerSync main_timer_sync;
3910
3911 // Return value should be EXIT_SUCCESS if we start successfully
3912 // and should move on to `OS::run`, and EXIT_FAILURE otherwise for
3913 // an early exit with that error code.
3914 int Main::start() {
3915 GodotProfileZone("start");
3916 OS::get_singleton()->benchmark_begin_measure("Startup", "Main::Start");
3917
3918 ERR_FAIL_COND_V(!_start_success, EXIT_FAILURE);
3919
3920 bool has_icon = false;
3921 String positional_arg;
3922 String game_path;
3923 String script;
3924 String main_loop_type;
3925 bool check_only = false;
3926
3927 #ifdef TOOLS_ENABLED
3928 String doc_tool_path;
3929 bool doc_tool_implicit_cwd = false;
3930 BitField<DocTools::GenerateFlags> gen_flags = {};
3931 String _export_preset;
3932 Vector<String> patches;
3933 bool export_debug = false;
3934 bool export_pack_only = false;
3935 bool install_android_build_template = false;
3936 bool export_patch = false;
3937 #ifdef MODULE_GDSCRIPT_ENABLED
3938 String gdscript_docs_path;
3939 #endif
3940 #ifndef DISABLE_DEPRECATED
3941 bool converting_project = false;
3942 bool validating_converting_project = false;
3943 #endif // DISABLE_DEPRECATED
3944 #endif // TOOLS_ENABLED
3945
3946 main_timer_sync.init(OS::get_singleton()->get_ticks_usec());
3947 List<String> args = OS::get_singleton()->get_cmdline_args();
3948
3949 for (List<String>::Element *E = args.front(); E; E = E->next()) {
3950 // First check parameters that do not have an argument to the right.
3951
3952 // Doctest Unit Testing Handler
3953 // Designed to override and pass arguments to the unit test handler.
3954 if (E->get() == "--check-only") {
3955 check_only = true;
3956 #ifdef TOOLS_ENABLED
3957 } else if (E->get() == "--no-docbase") {
3958 gen_flags.set_flag(DocTools::GENERATE_FLAG_SKIP_BASIC_TYPES);
3959 } else if (E->get() == "--gdextension-docs") {
3960 gen_flags.set_flag(DocTools::GENERATE_FLAG_SKIP_BASIC_TYPES);
3961 gen_flags.set_flag(DocTools::GENERATE_FLAG_EXTENSION_CLASSES_ONLY);
3962 #ifndef DISABLE_DEPRECATED
3963 } else if (E->get() == "--convert-3to4") {
3964 converting_project = true;
3965 } else if (E->get() == "--validate-conversion-3to4") {
3966 validating_converting_project = true;
3967 #endif // DISABLE_DEPRECATED
3968 } else if (E->get() == "-e" || E->get() == "--editor") {
3969 editor = true;
3970 } else if (E->get() == "-p" || E->get() == "--project-manager") {
3971 project_manager = true;
3972 } else if (E->get() == "--recovery-mode") {
3973 recovery_mode = true;
3974 } else if (E->get() == "--install-android-build-template") {
3975 install_android_build_template = true;
3976 #endif // TOOLS_ENABLED
3977 } else if (E->get() == "--scene") {
3978 #if defined(OVERRIDE_PATH_ENABLED)
3979 E = E->next();
3980 if (E) {
3981 game_path = ResourceUID::ensure_path(E->get());
3982 } else {
3983 ERR_FAIL_V_MSG(EXIT_FAILURE, "Missing scene path, aborting.");
3984 }
3985 #else
3986 ERR_PRINT(
3987 "`--scene` was specified on the command line, but this Godot binary was compiled without support for path overrides. Aborting.\n"
3988 "To be able to use it, use the `disable_path_overrides=no` SCons option when compiling Godot.\n");
3989 return EXIT_FAILURE;
3990 #endif // defined(OVERRIDE_PATH_ENABLED)
3991 } else if (E->get().length() && E->get()[0] != '-' && positional_arg.is_empty() && game_path.is_empty()) {
3992 positional_arg = E->get();
3993
3994 String scene_path = ResourceUID::ensure_path(E->get());
3995 if (scene_path.ends_with(".scn") ||
3996 scene_path.ends_with(".tscn") ||
3997 scene_path.ends_with(".escn") ||
3998 scene_path.ends_with(".res") ||
3999 scene_path.ends_with(".tres")) {
4000 // Only consider the positional argument to be a scene path if it ends with
4001 // a file extension associated with Godot scenes. This makes it possible
4002 // for projects to parse command-line arguments for custom CLI arguments
4003 // or other file extensions without trouble. This can be used to implement
4004 // "drag-and-drop onto executable" logic, which can prove helpful
4005 // for non-game applications.
4006 #if defined(OVERRIDE_PATH_ENABLED)
4007 game_path = scene_path;
4008 #else
4009 ERR_PRINT(
4010 "Scene path was specified on the command line, but this Godot binary was compiled without support for path overrides. Aborting.\n"
4011 "To be able to use it, use the `disable_path_overrides=no` SCons option when compiling Godot.\n");
4012 return EXIT_FAILURE;
4013 #endif // defined(OVERRIDE_PATH_ENABLED)
4014 }
4015 }
4016 // Then parameters that have an argument to the right.
4017 else if (E->next()) {
4018 bool parsed_pair = true;
4019 if (E->get() == "-s" || E->get() == "--script") {
4020 script = E->next()->get();
4021 } else if (E->get() == "--main-loop") {
4022 main_loop_type = E->next()->get();
4023 #ifdef TOOLS_ENABLED
4024 } else if (E->get() == "--doctool") {
4025 doc_tool_path = E->next()->get();
4026 if (doc_tool_path.begins_with("-")) {
4027 // Assuming other command line arg, so default to cwd.
4028 doc_tool_path = ".";
4029 doc_tool_implicit_cwd = true;
4030 parsed_pair = false;
4031 }
4032 #ifdef MODULE_GDSCRIPT_ENABLED
4033 } else if (E->get() == "--gdscript-docs") {
4034 gdscript_docs_path = E->next()->get();
4035 #endif
4036 } else if (E->get() == "--export-release") {
4037 ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
4038 editor = true; //needs editor
4039 _export_preset = E->next()->get();
4040 } else if (E->get() == "--export-debug") {
4041 ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
4042 editor = true; //needs editor
4043 _export_preset = E->next()->get();
4044 export_debug = true;
4045 } else if (E->get() == "--export-pack") {
4046 ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
4047 editor = true;
4048 _export_preset = E->next()->get();
4049 export_pack_only = true;
4050 } else if (E->get() == "--export-patch") {
4051 ERR_FAIL_COND_V_MSG(!editor && !found_project, EXIT_FAILURE, "Please provide a valid project path when exporting, aborting.");
4052 editor = true;
4053 _export_preset = E->next()->get();
4054 export_pack_only = true;
4055 export_patch = true;
4056 } else if (E->get() == "--patches") {
4057 patches = E->next()->get().split(",", false);
4058 #endif
4059 } else {
4060 // The parameter does not match anything known, don't skip the next argument
4061 parsed_pair = false;
4062 }
4063 if (parsed_pair) {
4064 E = E->next();
4065 }
4066 } else if (E->get().begins_with("--export-")) {
4067 ERR_FAIL_V_MSG(EXIT_FAILURE, "Missing export preset name, aborting.");
4068 }
4069 #ifdef TOOLS_ENABLED
4070 // Handle case where no path is given to --doctool.
4071 else if (E->get() == "--doctool") {
4072 doc_tool_path = ".";
4073 doc_tool_implicit_cwd = true;
4074 }
4075 #endif
4076 }
4077
4078 uint64_t minimum_time_msec = GLOBAL_DEF(PropertyInfo(Variant::INT, "application/boot_splash/minimum_display_time", PROPERTY_HINT_RANGE, "0,100,1,or_greater,suffix:ms"), 0);
4079 if (Engine::get_singleton()->is_editor_hint()) {
4080 minimum_time_msec = 0;
4081 }
4082
4083 #ifdef TOOLS_ENABLED
4084 #ifdef MODULE_GDSCRIPT_ENABLED
4085 if (!doc_tool_path.is_empty() && gdscript_docs_path.is_empty()) {
4086 #else
4087 if (!doc_tool_path.is_empty()) {
4088 #endif
4089 // Needed to instance editor-only classes for their default values
4090 Engine::get_singleton()->set_editor_hint(true);
4091
4092 // Translate the class reference only when `-l LOCALE` parameter is given.
4093 if (!locale.is_empty() && locale != "en") {
4094 load_doc_translations(locale);
4095 }
4096
4097 {
4098 Ref<DirAccess> da = DirAccess::open(doc_tool_path);
4099 ERR_FAIL_COND_V_MSG(da.is_null(), EXIT_FAILURE, "Argument supplied to --doctool must be a valid directory path.");
4100 // Ensure that doctool is running in the root dir, but only if
4101 // user did not manually specify a path as argument.
4102 if (doc_tool_implicit_cwd) {
4103 ERR_FAIL_COND_V_MSG(!da->dir_exists("doc"), EXIT_FAILURE, "--doctool must be run from the Godot repository's root folder, or specify a path that points there.");
4104 }
4105 }
4106
4107 #ifndef MODULE_MONO_ENABLED
4108 // Hack to define .NET-specific project settings even on non-.NET builds,
4109 // so that we don't lose their descriptions and default values in DocTools.
4110 // Default values should be synced with mono_gd/gd_mono.cpp.
4111 GLOBAL_DEF("dotnet/project/assembly_name", "");
4112 GLOBAL_DEF("dotnet/project/solution_directory", "");
4113 GLOBAL_DEF(PropertyInfo(Variant::INT, "dotnet/project/assembly_reload_attempts", PROPERTY_HINT_RANGE, "1,16,1,or_greater"), 3);
4114 #endif
4115
4116 Error err;
4117 DocTools doc;
4118 doc.generate(gen_flags);
4119
4120 DocTools docsrc;
4121 HashMap<String, String> doc_data_classes;
4122 HashSet<String> checked_paths;
4123 print_line("Loading docs...");
4124
4125 const bool gdextension_docs = gen_flags.has_flag(DocTools::GENERATE_FLAG_EXTENSION_CLASSES_ONLY);
4126
4127 if (!gdextension_docs) {
4128 for (int i = 0; i < _doc_data_class_path_count; i++) {
4129 // Custom modules are always located by absolute path.
4130 String path = _doc_data_class_paths[i].path;
4131 if (path.is_relative_path()) {
4132 path = doc_tool_path.path_join(path);
4133 }
4134 String name = _doc_data_class_paths[i].name;
4135 doc_data_classes[name] = path;
4136 if (!checked_paths.has(path)) {
4137 checked_paths.insert(path);
4138
4139 // Create the module documentation directory if it doesn't exist
4140 Ref<DirAccess> da = DirAccess::create_for_path(path);
4141 err = da->make_dir_recursive(path);
4142 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error: Can't create directory: " + path + ": " + itos(err));
4143
4144 print_line("Loading docs from: " + path);
4145 err = docsrc.load_classes(path);
4146 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error loading docs from: " + path + ": " + itos(err));
4147 }
4148 }
4149 }
4150
4151 // For GDExtension docs, use a path that is compatible with Godot modules.
4152 String index_path = gdextension_docs ? doc_tool_path.path_join("doc_classes") : doc_tool_path.path_join("doc/classes");
4153 // Create the main documentation directory if it doesn't exist
4154 Ref<DirAccess> da = DirAccess::create_for_path(index_path);
4155 err = da->make_dir_recursive(index_path);
4156 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error: Can't create index directory: " + index_path + ": " + itos(err));
4157
4158 print_line("Loading classes from: " + index_path);
4159 err = docsrc.load_classes(index_path);
4160 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error loading classes from: " + index_path + ": " + itos(err));
4161 checked_paths.insert(index_path);
4162
4163 print_line("Merging docs...");
4164 doc.merge_from(docsrc);
4165
4166 for (const String &E : checked_paths) {
4167 print_line("Erasing old docs at: " + E);
4168 err = DocTools::erase_classes(E);
4169 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error erasing old docs at: " + E + ": " + itos(err));
4170 }
4171
4172 print_line("Generating new docs...");
4173 err = doc.save_classes(index_path, doc_data_classes, !gdextension_docs);
4174 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error saving new docs:" + itos(err));
4175
4176 print_line("Deleting docs cache...");
4177 if (FileAccess::exists(EditorHelp::get_cache_full_path())) {
4178 DirAccess::remove_file_or_error(EditorHelp::get_cache_full_path());
4179 }
4180
4181 return EXIT_SUCCESS;
4182 }
4183
4184 // GDExtension API and interface.
4185 {
4186 if (dump_gdextension_interface) {
4187 GDExtensionInterfaceDump::generate_gdextension_interface_file("gdextension_interface.json");
4188 }
4189
4190 if (dump_gdextension_interface_header) {
4191 GDExtensionInterfaceHeaderGenerator::generate_gdextension_interface_header("gdextension_interface.h");
4192 }
4193
4194 if (dump_extension_api) {
4195 Engine::get_singleton()->set_editor_hint(true); // "extension_api.json" should always contains editor singletons.
4196 GDExtensionAPIDump::generate_extension_json_file("extension_api.json", include_docs_in_extension_api_dump);
4197 }
4198
4199 if (dump_gdextension_interface || dump_gdextension_interface_header || dump_extension_api) {
4200 return EXIT_SUCCESS;
4201 }
4202
4203 if (validate_extension_api) {
4204 Engine::get_singleton()->set_editor_hint(true); // "extension_api.json" should always contains editor singletons.
4205 bool valid = GDExtensionAPIDump::validate_extension_json_file(validate_extension_api_file) == OK;
4206 return valid ? EXIT_SUCCESS : EXIT_FAILURE;
4207 }
4208 }
4209
4210 #ifndef DISABLE_DEPRECATED
4211 if (converting_project) {
4212 int ret = ProjectConverter3To4(converter_max_kb_file, converter_max_line_length).convert();
4213 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
4214 }
4215 if (validating_converting_project) {
4216 bool ret = ProjectConverter3To4(converter_max_kb_file, converter_max_line_length).validate_conversion();
4217 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
4218 }
4219 #endif // DISABLE_DEPRECATED
4220
4221 #endif // TOOLS_ENABLED
4222
4223 #if defined(OVERRIDE_PATH_ENABLED)
4224 bool disable_override = GLOBAL_GET("application/config/disable_project_settings_override");
4225 if (disable_override) {
4226 script = String();
4227 game_path = String();
4228 main_loop_type = String();
4229 }
4230 #else
4231 script = String();
4232 game_path = String();
4233 main_loop_type = String();
4234 #endif // defined(OVERRIDE_PATH_ENABLED)
4235
4236 if (script.is_empty() && game_path.is_empty()) {
4237 const String main_scene = GLOBAL_GET("application/run/main_scene");
4238 if (main_scene.begins_with("uid://")) {
4239 ResourceUID::ID id = ResourceUID::get_singleton()->text_to_id(main_scene);
4240 if (!editor && !ResourceUID::get_singleton()->has_id(id) && !FileAccess::exists(ResourceUID::get_singleton()->get_cache_file())) {
4241 OS::get_singleton()->alert("Main scene's path could not be resolved from UID. Make sure the project is imported first. Aborting.");
4242 ERR_FAIL_V_MSG(EXIT_FAILURE, "Main scene's path could not be resolved from UID. Make sure the project is imported first. Aborting.");
4243 }
4244 game_path = ResourceUID::get_singleton()->get_id_path(id);
4245 } else {
4246 game_path = main_scene;
4247 }
4248 }
4249
4250 #ifdef TOOLS_ENABLED
4251 if (!editor && !project_manager && !cmdline_tool && script.is_empty() && game_path.is_empty()) {
4252 // If we end up here, it means we didn't manage to detect what we want to run.
4253 // Let's throw an error gently. The code leading to this is pretty brittle so
4254 // this might end up triggered by valid usage, in which case we'll have to
4255 // fine-tune further.
4256 OS::get_singleton()->alert("Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
4257 ERR_FAIL_V_MSG(EXIT_FAILURE, "Couldn't detect whether to run the editor, the project manager or a specific project. Aborting.");
4258 }
4259 #endif
4260
4261 MainLoop *main_loop = nullptr;
4262 if (editor) {
4263 main_loop = memnew(SceneTree);
4264 }
4265 if (main_loop_type.is_empty()) {
4266 main_loop_type = GLOBAL_GET("application/run/main_loop_type");
4267 }
4268
4269 if (!script.is_empty()) {
4270 Ref<Script> script_res = ResourceLoader::load(script);
4271 ERR_FAIL_COND_V_MSG(script_res.is_null(), EXIT_FAILURE, "Can't load script: " + script);
4272
4273 if (check_only) {
4274 return script_res->is_valid() ? EXIT_SUCCESS : EXIT_FAILURE;
4275 }
4276
4277 if (script_res->can_instantiate()) {
4278 StringName instance_type = script_res->get_instance_base_type();
4279 Object *obj = ClassDB::instantiate(instance_type);
4280 MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
4281 if (!script_loop) {
4282 if (obj) {
4283 memdelete(obj);
4284 }
4285 OS::get_singleton()->alert(vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
4286 ERR_FAIL_V_MSG(EXIT_FAILURE, vformat("Can't load the script \"%s\" as it doesn't inherit from SceneTree or MainLoop.", script));
4287 }
4288
4289 script_loop->set_script(script_res);
4290 main_loop = script_loop;
4291 } else {
4292 return EXIT_FAILURE;
4293 }
4294 } else { // Not based on script path.
4295 if (!editor && !ClassDB::class_exists(main_loop_type) && ScriptServer::is_global_class(main_loop_type)) {
4296 String script_path = ScriptServer::get_global_class_path(main_loop_type);
4297 Ref<Script> script_res = ResourceLoader::load(script_path);
4298 if (script_res.is_null()) {
4299 OS::get_singleton()->alert("Error: Could not load MainLoop script type: " + main_loop_type);
4300 ERR_FAIL_V_MSG(EXIT_FAILURE, vformat("Could not load global class %s.", main_loop_type));
4301 }
4302 StringName script_base = script_res->get_instance_base_type();
4303 Object *obj = ClassDB::instantiate(script_base);
4304 MainLoop *script_loop = Object::cast_to<MainLoop>(obj);
4305 if (!script_loop) {
4306 if (obj) {
4307 memdelete(obj);
4308 }
4309 OS::get_singleton()->alert("Error: Invalid MainLoop script base type: " + script_base);
4310 ERR_FAIL_V_MSG(EXIT_FAILURE, vformat("The global class %s does not inherit from SceneTree or MainLoop.", main_loop_type));
4311 }
4312 script_loop->set_script(script_res);
4313 main_loop = script_loop;
4314 }
4315 }
4316
4317 if (!main_loop && main_loop_type.is_empty()) {
4318 main_loop_type = "SceneTree";
4319 }
4320
4321 if (!main_loop) {
4322 if (!ClassDB::class_exists(main_loop_type)) {
4323 OS::get_singleton()->alert("Error: MainLoop type doesn't exist: " + main_loop_type);
4324 return EXIT_FAILURE;
4325 } else {
4326 Object *ml = ClassDB::instantiate(main_loop_type);
4327 ERR_FAIL_NULL_V_MSG(ml, EXIT_FAILURE, "Can't instance MainLoop type.");
4328
4329 main_loop = Object::cast_to<MainLoop>(ml);
4330 if (!main_loop) {
4331 memdelete(ml);
4332 ERR_FAIL_V_MSG(EXIT_FAILURE, "Invalid MainLoop type.");
4333 }
4334 }
4335 }
4336
4337 OS::get_singleton()->set_main_loop(main_loop);
4338
4339 SceneTree *sml = Object::cast_to<SceneTree>(main_loop);
4340 if (sml) {
4341 #ifdef DEBUG_ENABLED
4342 if (debug_collisions) {
4343 sml->set_debug_collisions_hint(true);
4344 }
4345 if (debug_paths) {
4346 sml->set_debug_paths_hint(true);
4347 }
4348
4349 if (debug_navigation) {
4350 sml->set_debug_navigation_hint(true);
4351 #ifndef NAVIGATION_2D_DISABLED
4352 NavigationServer2D::get_singleton()->set_debug_navigation_enabled(true);
4353 #endif // NAVIGATION_2D_DISABLED
4354 #ifndef NAVIGATION_3D_DISABLED
4355 NavigationServer3D::get_singleton()->set_debug_navigation_enabled(true);
4356 #endif // NAVIGATION_3D_DISABLED
4357 }
4358 if (debug_avoidance) {
4359 #ifndef NAVIGATION_2D_DISABLED
4360 NavigationServer2D::get_singleton()->set_debug_avoidance_enabled(true);
4361 #endif // NAVIGATION_2D_DISABLED
4362 #ifndef NAVIGATION_3D_DISABLED
4363 NavigationServer3D::get_singleton()->set_debug_avoidance_enabled(true);
4364 #endif // NAVIGATION_3D_DISABLED
4365 }
4366 if (debug_navigation || debug_avoidance) {
4367 #ifndef NAVIGATION_2D_DISABLED
4368 NavigationServer2D::get_singleton()->set_active(true);
4369 NavigationServer2D::get_singleton()->set_debug_enabled(true);
4370 #endif // NAVIGATION_2D_DISABLED
4371 #ifndef NAVIGATION_3D_DISABLED
4372 NavigationServer3D::get_singleton()->set_active(true);
4373 NavigationServer3D::get_singleton()->set_debug_enabled(true);
4374 #endif // NAVIGATION_3D_DISABLED
4375 }
4376 if (debug_canvas_item_redraw) {
4377 RenderingServer::get_singleton()->canvas_item_set_debug_redraw(true);
4378 }
4379
4380 if (debug_mute_audio) {
4381 AudioServer::get_singleton()->set_debug_mute(true);
4382 }
4383 #endif
4384
4385 if (single_threaded_scene) {
4386 sml->set_disable_node_threading(true);
4387 }
4388
4389 bool embed_subwindows = GLOBAL_GET("display/window/subwindows/embed_subwindows");
4390
4391 if (single_window || (!project_manager && !editor && embed_subwindows) || !DisplayServer::get_singleton()->has_feature(DisplayServer::Feature::FEATURE_SUBWINDOWS)) {
4392 sml->get_root()->set_embedding_subwindows(true);
4393 }
4394
4395 ResourceLoader::add_custom_loaders();
4396 ResourceSaver::add_custom_savers();
4397
4398 if (!project_manager && !editor) { // game
4399 if (!game_path.is_empty() || !script.is_empty()) {
4400 //autoload
4401 OS::get_singleton()->benchmark_begin_measure("Startup", "Load Autoloads");
4402 HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
4403
4404 //first pass, add the constants so they exist before any script is loaded
4405 for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
4406 const ProjectSettings::AutoloadInfo &info = E.value;
4407
4408 if (info.is_singleton) {
4409 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
4410 ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
4411 }
4412 }
4413 }
4414
4415 //second pass, load into global constants
4416 List<Node *> to_add;
4417 for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : autoloads) {
4418 const ProjectSettings::AutoloadInfo &info = E.value;
4419
4420 Node *n = nullptr;
4421 if (ResourceLoader::get_resource_type(info.path) == "PackedScene") {
4422 // Cache the scene reference before loading it (for cyclic references)
4423 Ref<PackedScene> scn;
4424 scn.instantiate();
4425 scn->set_path(ResourceUID::ensure_path(info.path));
4426 scn->reload_from_file();
4427 ERR_CONTINUE_MSG(scn.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
4428
4429 if (scn.is_valid()) {
4430 n = scn->instantiate();
4431 }
4432 } else {
4433 Ref<Resource> res = ResourceLoader::load(info.path);
4434 ERR_CONTINUE_MSG(res.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
4435
4436 Ref<Script> script_res = res;
4437 if (script_res.is_valid()) {
4438 StringName ibt = script_res->get_instance_base_type();
4439 bool valid_type = ClassDB::is_parent_class(ibt, "Node");
4440 ERR_CONTINUE_MSG(!valid_type, vformat("Failed to instantiate an autoload, script '%s' does not inherit from 'Node'.", info.path));
4441
4442 Object *obj = ClassDB::instantiate(ibt);
4443 ERR_CONTINUE_MSG(!obj, vformat("Failed to instantiate an autoload, cannot instantiate '%s'.", ibt));
4444
4445 n = Object::cast_to<Node>(obj);
4446 n->set_script(script_res);
4447 }
4448 }
4449
4450 ERR_CONTINUE_MSG(!n, vformat("Failed to instantiate an autoload, path is not pointing to a scene or a script: %s.", info.path));
4451 n->set_name(info.name);
4452
4453 //defer so references are all valid on _ready()
4454 to_add.push_back(n);
4455
4456 if (info.is_singleton) {
4457 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
4458 ScriptServer::get_language(i)->add_global_constant(info.name, n);
4459 }
4460 }
4461 }
4462
4463 for (Node *E : to_add) {
4464 sml->get_root()->add_child(E);
4465 }
4466 OS::get_singleton()->benchmark_end_measure("Startup", "Load Autoloads");
4467 }
4468 }
4469
4470 #ifdef TOOLS_ENABLED
4471 #ifdef MODULE_GDSCRIPT_ENABLED
4472 if (!doc_tool_path.is_empty() && !gdscript_docs_path.is_empty()) {
4473 DocTools docs;
4474 Error err;
4475
4476 Vector<String> paths = get_files_with_extension(gdscript_docs_path, "gd");
4477 ERR_FAIL_COND_V_MSG(paths.is_empty(), EXIT_FAILURE, "Couldn't find any GDScript files under the given directory: " + gdscript_docs_path);
4478
4479 for (const String &path : paths) {
4480 Ref<GDScript> gdscript = ResourceLoader::load(path);
4481 for (const DocData::ClassDoc &class_doc : gdscript->get_documentation()) {
4482 docs.add_doc(class_doc);
4483 }
4484 }
4485
4486 if (doc_tool_implicit_cwd) {
4487 doc_tool_path = "./docs";
4488 }
4489
4490 Ref<DirAccess> da = DirAccess::create_for_path(doc_tool_path);
4491 err = da->make_dir_recursive(doc_tool_path);
4492 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error: Can't create GDScript docs directory: " + doc_tool_path + ": " + itos(err));
4493
4494 HashMap<String, String> doc_data_classes;
4495 err = docs.save_classes(doc_tool_path, doc_data_classes, false);
4496 ERR_FAIL_COND_V_MSG(err != OK, EXIT_FAILURE, "Error saving GDScript docs:" + itos(err));
4497
4498 return EXIT_SUCCESS;
4499 }
4500 #endif // MODULE_GDSCRIPT_ENABLED
4501
4502 EditorNode *editor_node = nullptr;
4503 if (editor) {
4504 OS::get_singleton()->benchmark_begin_measure("Startup", "Editor");
4505
4506 sml->get_root()->set_translation_domain("godot.editor");
4507 if (editor_pseudolocalization) {
4508 translation_server->get_editor_domain()->set_pseudolocalization_enabled(true);
4509 }
4510
4511 editor_node = memnew(EditorNode);
4512 sml->get_root()->add_child(editor_node);
4513
4514 if (!_export_preset.is_empty()) {
4515 editor_node->export_preset(_export_preset, positional_arg, export_debug, export_pack_only, install_android_build_template, export_patch, patches);
4516 game_path = ""; // Do not load anything.
4517 }
4518
4519 OS::get_singleton()->benchmark_end_measure("Startup", "Editor");
4520 }
4521 #endif
4522 sml->set_auto_accept_quit(GLOBAL_GET("application/config/auto_accept_quit"));
4523 sml->set_quit_on_go_back(GLOBAL_GET("application/config/quit_on_go_back"));
4524
4525 if (!editor && !project_manager) {
4526 //standard helpers that can be changed from main config
4527
4528 String stretch_mode = GLOBAL_GET("display/window/stretch/mode");
4529 String stretch_aspect = GLOBAL_GET("display/window/stretch/aspect");
4530 Size2i stretch_size = Size2i(GLOBAL_GET("display/window/size/viewport_width"),
4531 GLOBAL_GET("display/window/size/viewport_height"));
4532 real_t stretch_scale = GLOBAL_GET("display/window/stretch/scale");
4533 String stretch_scale_mode = GLOBAL_GET("display/window/stretch/scale_mode");
4534
4535 Window::ContentScaleMode cs_sm = Window::CONTENT_SCALE_MODE_DISABLED;
4536 if (stretch_mode == "canvas_items") {
4537 cs_sm = Window::CONTENT_SCALE_MODE_CANVAS_ITEMS;
4538 } else if (stretch_mode == "viewport") {
4539 cs_sm = Window::CONTENT_SCALE_MODE_VIEWPORT;
4540 }
4541
4542 Window::ContentScaleAspect cs_aspect = Window::CONTENT_SCALE_ASPECT_IGNORE;
4543 if (stretch_aspect == "keep") {
4544 cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP;
4545 } else if (stretch_aspect == "keep_width") {
4546 cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_WIDTH;
4547 } else if (stretch_aspect == "keep_height") {
4548 cs_aspect = Window::CONTENT_SCALE_ASPECT_KEEP_HEIGHT;
4549 } else if (stretch_aspect == "expand") {
4550 cs_aspect = Window::CONTENT_SCALE_ASPECT_EXPAND;
4551 }
4552
4553 Window::ContentScaleStretch cs_stretch = Window::CONTENT_SCALE_STRETCH_FRACTIONAL;
4554 if (stretch_scale_mode == "integer") {
4555 cs_stretch = Window::CONTENT_SCALE_STRETCH_INTEGER;
4556 }
4557
4558 sml->get_root()->set_content_scale_mode(cs_sm);
4559 sml->get_root()->set_content_scale_aspect(cs_aspect);
4560 sml->get_root()->set_content_scale_stretch(cs_stretch);
4561 sml->get_root()->set_content_scale_size(stretch_size);
4562 sml->get_root()->set_content_scale_factor(stretch_scale);
4563
4564 sml->set_auto_accept_quit(GLOBAL_GET("application/config/auto_accept_quit"));
4565 sml->set_quit_on_go_back(GLOBAL_GET("application/config/quit_on_go_back"));
4566 String appname = GLOBAL_GET("application/config/name");
4567 appname = TranslationServer::get_singleton()->translate(appname);
4568 #ifdef DEBUG_ENABLED
4569 // Append a suffix to the window title to denote that the project is running
4570 // from a debug build (including the editor). Since this results in lower performance,
4571 // this should be clearly presented to the user.
4572 DisplayServer::get_singleton()->window_set_title(vformat("%s (DEBUG)", appname));
4573 #else
4574 DisplayServer::get_singleton()->window_set_title(appname);
4575 #endif
4576
4577 bool snap_controls = GLOBAL_GET("gui/common/snap_controls_to_pixels");
4578 sml->get_root()->set_snap_controls_to_pixels(snap_controls);
4579
4580 int drag_threshold = GLOBAL_GET("gui/common/drag_threshold");
4581 sml->get_root()->set_drag_threshold(drag_threshold);
4582
4583 bool font_oversampling = GLOBAL_GET("gui/fonts/dynamic_fonts/use_oversampling");
4584 sml->get_root()->set_use_oversampling(font_oversampling);
4585
4586 int texture_filter = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_filter");
4587 int texture_repeat = GLOBAL_GET("rendering/textures/canvas_textures/default_texture_repeat");
4588 sml->get_root()->set_default_canvas_item_texture_filter(
4589 Viewport::DefaultCanvasItemTextureFilter(texture_filter));
4590 sml->get_root()->set_default_canvas_item_texture_repeat(
4591 Viewport::DefaultCanvasItemTextureRepeat(texture_repeat));
4592 }
4593
4594 #ifdef TOOLS_ENABLED
4595 if (editor) {
4596 bool editor_embed_subwindows = EDITOR_GET("interface/editor/single_window_mode");
4597
4598 if (editor_embed_subwindows) {
4599 sml->get_root()->set_embedding_subwindows(true);
4600 }
4601 restore_editor_window_layout = EDITOR_GET("interface/editor/editor_screen").operator int() == EditorSettings::InitialScreen::INITIAL_SCREEN_AUTO;
4602 }
4603 #endif
4604
4605 String local_game_path;
4606 if (!game_path.is_empty() && !project_manager) {
4607 local_game_path = game_path.replace_char('\\', '/');
4608
4609 if (!local_game_path.begins_with("res://")) {
4610 bool absolute =
4611 (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
4612
4613 if (!absolute) {
4614 if (ProjectSettings::get_singleton()->is_using_datapack()) {
4615 local_game_path = "res://" + local_game_path;
4616
4617 } else {
4618 int sep = local_game_path.rfind_char('/');
4619
4620 if (sep == -1) {
4621 Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
4622 ERR_FAIL_COND_V(da.is_null(), EXIT_FAILURE);
4623
4624 local_game_path = da->get_current_dir().path_join(local_game_path);
4625 } else {
4626 Ref<DirAccess> da = DirAccess::open(local_game_path.substr(0, sep));
4627 if (da.is_valid()) {
4628 local_game_path = da->get_current_dir().path_join(
4629 local_game_path.substr(sep + 1));
4630 }
4631 }
4632 }
4633 }
4634 }
4635
4636 local_game_path = ProjectSettings::get_singleton()->localize_path(local_game_path);
4637
4638 #ifdef TOOLS_ENABLED
4639 if (editor) {
4640 if (!recovery_mode && (game_path != ResourceUID::ensure_path(String(GLOBAL_GET("application/run/main_scene"))) || !editor_node->has_scenes_in_session())) {
4641 Error serr = editor_node->load_scene(local_game_path);
4642 if (serr != OK) {
4643 ERR_PRINT("Failed to load scene");
4644 }
4645 }
4646 if (!debug_server_uri.is_empty()) {
4647 EditorDebuggerNode::get_singleton()->start(debug_server_uri);
4648 EditorDebuggerNode::get_singleton()->set_keep_open(true);
4649 }
4650 }
4651 #endif
4652 }
4653
4654 if (!project_manager && !editor) { // game
4655
4656 OS::get_singleton()->benchmark_begin_measure("Startup", "Load Game");
4657
4658 // Load SSL Certificates from Project Settings (or builtin).
4659 Crypto::load_default_certificates(GLOBAL_GET("network/tls/certificate_bundle_override"));
4660
4661 if (!game_path.is_empty()) {
4662 Node *scene = nullptr;
4663 Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
4664 if (scenedata.is_valid()) {
4665 scene = scenedata->instantiate();
4666 }
4667
4668 ERR_FAIL_NULL_V_MSG(scene, EXIT_FAILURE, "Failed loading scene: " + local_game_path + ".");
4669 sml->add_current_scene(scene);
4670
4671 #ifdef MACOS_ENABLED
4672 #ifndef TOOLS_ENABLED
4673 if ((FileAccess::exists(OS::get_singleton()->get_bundle_resource_dir().path_join("Assets.car")) && !OS::get_singleton()->get_bundle_icon_name().is_empty()) || (!OS::get_singleton()->get_bundle_icon_path().is_empty())) {
4674 has_icon = true; // Bundle has embedded icon, do not override with project icon.
4675 }
4676 #endif
4677 String mac_icon_path = GLOBAL_GET("application/config/macos_native_icon");
4678 if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_NATIVE_ICON) && !mac_icon_path.is_empty() && !has_icon) {
4679 DisplayServer::get_singleton()->set_native_icon(mac_icon_path);
4680 has_icon = true;
4681 }
4682 #endif
4683
4684 #ifdef WINDOWS_ENABLED
4685 String win_icon_path = GLOBAL_GET("application/config/windows_native_icon");
4686 if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_NATIVE_ICON) && !win_icon_path.is_empty()) {
4687 DisplayServer::get_singleton()->set_native_icon(win_icon_path);
4688 has_icon = true;
4689 }
4690 #endif
4691
4692 String icon_path = GLOBAL_GET("application/config/icon");
4693 if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_ICON) && !icon_path.is_empty() && !has_icon) {
4694 Ref<Image> icon;
4695 icon.instantiate();
4696 if (ImageLoader::load_image(icon_path, icon) == OK) {
4697 DisplayServer::get_singleton()->set_icon(icon);
4698 has_icon = true;
4699 }
4700 }
4701 }
4702
4703 OS::get_singleton()->benchmark_end_measure("Startup", "Load Game");
4704 }
4705
4706 #ifdef TOOLS_ENABLED
4707 if (project_manager) {
4708 OS::get_singleton()->benchmark_begin_measure("Startup", "Project Manager");
4709 Engine::get_singleton()->set_editor_hint(true);
4710
4711 sml->get_root()->set_translation_domain("godot.editor");
4712 if (editor_pseudolocalization) {
4713 translation_server->get_editor_domain()->set_pseudolocalization_enabled(true);
4714 }
4715
4716 ProjectManager *pmanager = memnew(ProjectManager);
4717 ProgressDialog *progress_dialog = memnew(ProgressDialog);
4718 pmanager->add_child(progress_dialog);
4719
4720 sml->get_root()->add_child(pmanager);
4721 OS::get_singleton()->benchmark_end_measure("Startup", "Project Manager");
4722 }
4723
4724 if (project_manager || editor) {
4725 // Load SSL Certificates from Editor Settings (or builtin)
4726 Crypto::load_default_certificates(
4727 EditorSettings::get_singleton()->get_setting("network/tls/editor_tls_certificates").operator String());
4728 }
4729
4730 if (recovery_mode) {
4731 Engine::get_singleton()->set_recovery_mode_hint(true);
4732 }
4733 #endif
4734 }
4735
4736 if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_ICON) && !has_icon && OS::get_singleton()->get_bundle_icon_path().is_empty()) {
4737 Ref<Image> icon = memnew(Image(app_icon_png));
4738 DisplayServer::get_singleton()->set_icon(icon);
4739 }
4740
4741 if (movie_writer) {
4742 Size2i movie_size = Size2i(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
4743 String stretch_mode = GLOBAL_GET("display/window/stretch/mode");
4744 if (stretch_mode != "viewport") {
4745 // `canvas_items` and `disabled` modes use the window size override instead,
4746 // which allows for higher resolution recording with 2D elements designed for a lower resolution.
4747 const int window_width_override = GLOBAL_GET("display/window/size/window_width_override");
4748 if (window_width_override > 0) {
4749 movie_size.width = window_width_override;
4750 }
4751 const int window_height_override = GLOBAL_GET("display/window/size/window_height_override");
4752 if (window_height_override > 0) {
4753 movie_size.height = window_height_override;
4754 }
4755 }
4756 movie_writer->begin(movie_size, fixed_fps, Engine::get_singleton()->get_write_movie_path());
4757 }
4758
4759 GDExtensionManager::get_singleton()->startup();
4760
4761 #ifdef MACOS_ENABLED
4762 // TODO: Used to fix full-screen splash drawing on macOS, processing events before main loop is fully initialized cause issues on Wayland, and has no effect on other platforms.
4763 if (minimum_time_msec) {
4764 int64_t minimum_time = 1000 * minimum_time_msec;
4765 uint64_t prev_time = OS::get_singleton()->get_ticks_usec();
4766 while (minimum_time > 0) {
4767 DisplayServer::get_singleton()->process_events();
4768 OS::get_singleton()->delay_usec(100);
4769
4770 uint64_t next_time = OS::get_singleton()->get_ticks_usec();
4771 minimum_time -= (next_time - prev_time);
4772 prev_time = next_time;
4773 }
4774 } else {
4775 DisplayServer::get_singleton()->process_events();
4776 }
4777 #else
4778 if (minimum_time_msec) {
4779 uint64_t minimum_time = 1000 * minimum_time_msec;
4780 uint64_t elapsed_time = OS::get_singleton()->get_ticks_usec();
4781 if (elapsed_time < minimum_time) {
4782 OS::get_singleton()->delay_usec(minimum_time - elapsed_time);
4783 }
4784 }
4785 #endif
4786
4787 OS::get_singleton()->benchmark_end_measure("Startup", "Main::Start");
4788 OS::get_singleton()->benchmark_dump();
4789
4790 return EXIT_SUCCESS;
4791 }
4792
4793 /* Main iteration
4794 *
4795 * This is the iteration of the engine's game loop, advancing the state of physics,
4796 * rendering and audio.
4797 * It's called directly by the platform's OS::run method, where the loop is created
4798 * and monitored.
4799 *
4800 * The OS implementation can impact its draw step with the Main::force_redraw() method.
4801 */
4802
4803 uint64_t Main::last_ticks = 0;
4804 uint32_t Main::frames = 0;
4805 uint32_t Main::hide_print_fps_attempts = 3;
4806 uint32_t Main::frame = 0;
4807 bool Main::force_redraw_requested = false;
4808 int Main::iterating = 0;
4809
4810 bool Main::is_iterating() {
4811 return iterating > 0;
4812 }
4813
4814 // For performance metrics.
4815 static uint64_t physics_process_max = 0;
4816 static uint64_t process_max = 0;
4817 static uint64_t navigation_process_max = 0;
4818
4819 // Return false means iterating further, returning true means `OS::run`
4820 // will terminate the program. In case of failure, the OS exit code needs
4821 // to be set explicitly here (defaults to EXIT_SUCCESS).
4822 bool Main::iteration() {
4823 GodotProfileZone("Main::iteration");
4824 GodotProfileZoneGroupedFirst(_profile_zone, "prepare");
4825 iterating++;
4826
4827 const uint64_t ticks = OS::get_singleton()->get_ticks_usec();
4828 Engine::get_singleton()->_frame_ticks = ticks;
4829 main_timer_sync.set_cpu_ticks_usec(ticks);
4830 main_timer_sync.set_fixed_fps(fixed_fps);
4831
4832 const uint64_t ticks_elapsed = ticks - last_ticks;
4833
4834 const int physics_ticks_per_second = Engine::get_singleton()->get_user_physics_ticks_per_second();
4835 const double physics_step = 1.0 / physics_ticks_per_second;
4836
4837 const double time_scale = Engine::get_singleton()->get_effective_time_scale();
4838
4839 MainFrameTime advance = main_timer_sync.advance(physics_step, physics_ticks_per_second);
4840 double process_step = advance.process_step;
4841 double scaled_step = process_step * time_scale;
4842
4843 Engine::get_singleton()->_process_step = process_step;
4844 Engine::get_singleton()->_physics_interpolation_fraction = advance.interpolation_fraction;
4845
4846 uint64_t physics_process_ticks = 0;
4847 uint64_t process_ticks = 0;
4848 #if !defined(NAVIGATION_2D_DISABLED) || !defined(NAVIGATION_3D_DISABLED)
4849 uint64_t navigation_process_ticks = 0;
4850 #endif // !defined(NAVIGATION_2D_DISABLED) || !defined(NAVIGATION_3D_DISABLED)
4851
4852 frame += ticks_elapsed;
4853
4854 last_ticks = ticks;
4855
4856 const int max_physics_steps = Engine::get_singleton()->get_user_max_physics_steps_per_frame();
4857 if (fixed_fps == -1 && advance.physics_steps > max_physics_steps) {
4858 process_step -= (advance.physics_steps - max_physics_steps) * physics_step;
4859 advance.physics_steps = max_physics_steps;
4860 }
4861
4862 bool exit = false;
4863
4864 // process all our active interfaces
4865 #ifndef XR_DISABLED
4866 GodotProfileZoneGrouped(_profile_zone, "xr_server->_process");
4867 XRServer::get_singleton()->_process();
4868 #endif // XR_DISABLED
4869
4870 GodotProfileZoneGrouped(_profile_zone, "physics");
4871 for (int iters = 0; iters < advance.physics_steps; ++iters) {
4872 GodotProfileZone("Physics Step");
4873 GodotProfileZoneGroupedFirst(_physics_zone, "setup");
4874 if (Input::get_singleton()->is_agile_input_event_flushing()) {
4875 Input::get_singleton()->flush_buffered_events();
4876 }
4877
4878 Engine::get_singleton()->_in_physics = true;
4879 Engine::get_singleton()->_physics_frames++;
4880
4881 uint64_t physics_begin = OS::get_singleton()->get_ticks_usec();
4882
4883 // Prepare the fixed timestep interpolated nodes BEFORE they are updated
4884 // by the physics server, otherwise the current and previous transforms
4885 // may be the same, and no interpolation takes place.
4886 GodotProfileZoneGrouped(_physics_zone, "main loop iteration prepare");
4887 OS::get_singleton()->get_main_loop()->iteration_prepare();
4888
4889 #ifndef PHYSICS_3D_DISABLED
4890 GodotProfileZoneGrouped(_physics_zone, "PhysicsServer3D::sync");
4891 PhysicsServer3D::get_singleton()->sync();
4892 PhysicsServer3D::get_singleton()->flush_queries();
4893 #endif // PHYSICS_3D_DISABLED
4894
4895 #ifndef PHYSICS_2D_DISABLED
4896 GodotProfileZoneGrouped(_physics_zone, "PhysicsServer2D::sync");
4897 PhysicsServer2D::get_singleton()->sync();
4898 PhysicsServer2D::get_singleton()->flush_queries();
4899 #endif // PHYSICS_2D_DISABLED
4900
4901 GodotProfileZoneGrouped(_physics_zone, "physics_process");
4902 if (OS::get_singleton()->get_main_loop()->physics_process(physics_step * time_scale)) {
4903 #ifndef PHYSICS_3D_DISABLED
4904 PhysicsServer3D::get_singleton()->end_sync();
4905 #endif // PHYSICS_3D_DISABLED
4906 #ifndef PHYSICS_2D_DISABLED
4907 PhysicsServer2D::get_singleton()->end_sync();
4908 #endif // PHYSICS_2D_DISABLED
4909
4910 Engine::get_singleton()->_in_physics = false;
4911 exit = true;
4912 break;
4913 }
4914
4915 #if !defined(NAVIGATION_2D_DISABLED) || !defined(NAVIGATION_3D_DISABLED)
4916 uint64_t navigation_begin = OS::get_singleton()->get_ticks_usec();
4917
4918 #ifndef NAVIGATION_2D_DISABLED
4919 GodotProfileZoneGrouped(_profile_zone, "NavigationServer2D::physics_process");
4920 NavigationServer2D::get_singleton()->physics_process(physics_step * time_scale);
4921 #endif // NAVIGATION_2D_DISABLED
4922 #ifndef NAVIGATION_3D_DISABLED
4923 GodotProfileZoneGrouped(_profile_zone, "NavigationServer3D::physics_process");
4924 NavigationServer3D::get_singleton()->physics_process(physics_step * time_scale);
4925 #endif // NAVIGATION_3D_DISABLED
4926
4927 navigation_process_ticks = MAX(navigation_process_ticks, OS::get_singleton()->get_ticks_usec() - navigation_begin); // keep the largest one for reference
4928 navigation_process_max = MAX(OS::get_singleton()->get_ticks_usec() - navigation_begin, navigation_process_max);
4929
4930 message_queue->flush();
4931 #endif // !defined(NAVIGATION_2D_DISABLED) || !defined(NAVIGATION_3D_DISABLED)
4932
4933 #ifndef PHYSICS_3D_DISABLED
4934 GodotProfileZoneGrouped(_profile_zone, "3D physics");
4935 PhysicsServer3D::get_singleton()->end_sync();
4936 PhysicsServer3D::get_singleton()->step(physics_step * time_scale);
4937 #endif // PHYSICS_3D_DISABLED
4938
4939 #ifndef PHYSICS_2D_DISABLED
4940 GodotProfileZoneGrouped(_profile_zone, "2D physics");
4941 PhysicsServer2D::get_singleton()->end_sync();
4942 PhysicsServer2D::get_singleton()->step(physics_step * time_scale);
4943 #endif // PHYSICS_2D_DISABLED
4944
4945 message_queue->flush();
4946
4947 GodotProfileZoneGrouped(_profile_zone, "main loop iteration end");
4948 OS::get_singleton()->get_main_loop()->iteration_end();
4949
4950 physics_process_ticks = MAX(physics_process_ticks, OS::get_singleton()->get_ticks_usec() - physics_begin); // keep the largest one for reference
4951 physics_process_max = MAX(OS::get_singleton()->get_ticks_usec() - physics_begin, physics_process_max);
4952
4953 Engine::get_singleton()->_in_physics = false;
4954 }
4955
4956 if (Input::get_singleton()->is_agile_input_event_flushing()) {
4957 Input::get_singleton()->flush_buffered_events();
4958 }
4959
4960 uint64_t process_begin = OS::get_singleton()->get_ticks_usec();
4961
4962 GodotProfileZoneGrouped(_profile_zone, "process");
4963 if (OS::get_singleton()->get_main_loop()->process(process_step * time_scale)) {
4964 exit = true;
4965 }
4966 message_queue->flush();
4967
4968 #ifndef NAVIGATION_2D_DISABLED
4969 GodotProfileZoneGrouped(_profile_zone, "process 2D navigation");
4970 NavigationServer2D::get_singleton()->process(process_step * time_scale);
4971 #endif // NAVIGATION_2D_DISABLED
4972 #ifndef NAVIGATION_3D_DISABLED
4973 GodotProfileZoneGrouped(_profile_zone, "process 3D navigation");
4974 NavigationServer3D::get_singleton()->process(process_step * time_scale);
4975 #endif // NAVIGATION_3D_DISABLED
4976
4977 GodotProfileZoneGrouped(_profile_zone, "RenderingServer::sync");
4978 RenderingServer::get_singleton()->sync(); //sync if still drawing from previous frames.
4979
4980 GodotProfileZoneGrouped(_profile_zone, "RenderingServer::draw");
4981 const bool has_pending_resources_for_processing = RD::get_singleton() && RD::get_singleton()->has_pending_resources_for_processing();
4982 bool wants_present = (DisplayServer::get_singleton()->can_any_window_draw() ||
4983 DisplayServer::get_singleton()->has_additional_outputs()) &&
4984 RenderingServer::get_singleton()->is_render_loop_enabled();
4985
4986 if (wants_present || has_pending_resources_for_processing) {
4987 wants_present |= force_redraw_requested;
4988 if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
4989 if (RenderingServer::get_singleton()->has_changed()) {
4990 RenderingServer::get_singleton()->draw(wants_present, scaled_step); // flush visual commands
4991 Engine::get_singleton()->increment_frames_drawn();
4992 }
4993 } else {
4994 RenderingServer::get_singleton()->draw(wants_present, scaled_step); // flush visual commands
4995 Engine::get_singleton()->increment_frames_drawn();
4996 force_redraw_requested = false;
4997 }
4998 }
4999
5000 process_ticks = OS::get_singleton()->get_ticks_usec() - process_begin;
5001 process_max = MAX(process_ticks, process_max);
5002 uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
5003
5004 GodotProfileZoneGrouped(_profile_zone, "GDExtensionManager::frame");
5005 GDExtensionManager::get_singleton()->frame();
5006
5007 GodotProfileZoneGrouped(_profile_zone, "ScriptServer::frame");
5008 for (int i = 0; i < ScriptServer::get_language_count(); i++) {
5009 ScriptServer::get_language(i)->frame();
5010 }
5011
5012 GodotProfileZoneGrouped(_profile_zone, "AudioServer::update");
5013 AudioServer::get_singleton()->update();
5014
5015 if (EngineDebugger::is_active()) {
5016 EngineDebugger::get_singleton()->iteration(frame_time, process_ticks, physics_process_ticks, physics_step);
5017 }
5018
5019 frames++;
5020 Engine::get_singleton()->_process_frames++;
5021
5022 if (frame > 1000000) {
5023 // Wait a few seconds before printing FPS, as FPS reporting just after the engine has started is inaccurate.
5024 if (hide_print_fps_attempts == 0) {
5025 if (editor || project_manager) {
5026 if (print_fps) {
5027 print_line(vformat("Editor FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
5028 }
5029 } else if (print_fps || GLOBAL_GET("debug/settings/stdout/print_fps")) {
5030 print_line(vformat("Project FPS: %d (%s mspf)", frames, rtos(1000.0 / frames).pad_decimals(2)));
5031 }
5032 } else {
5033 hide_print_fps_attempts--;
5034 }
5035
5036 Engine::get_singleton()->_fps = frames;
5037 performance->set_process_time(USEC_TO_SEC(process_max));
5038 performance->set_physics_process_time(USEC_TO_SEC(physics_process_max));
5039 performance->set_navigation_process_time(USEC_TO_SEC(navigation_process_max));
5040 process_max = 0;
5041 physics_process_max = 0;
5042 navigation_process_max = 0;
5043
5044 frame %= 1000000;
5045 frames = 0;
5046 }
5047
5048 iterating--;
5049
5050 if (movie_writer) {
5051 GodotProfileZoneGrouped(_profile_zone, "movie_writer->add_frame");
5052 movie_writer->add_frame();
5053 }
5054
5055 #ifdef TOOLS_ENABLED
5056 bool quit_after_timeout = false;
5057 #endif
5058 if ((quit_after > 0) && (Engine::get_singleton()->_process_frames >= quit_after)) {
5059 #ifdef TOOLS_ENABLED
5060 quit_after_timeout = true;
5061 #endif
5062 exit = true;
5063 }
5064
5065 #ifdef TOOLS_ENABLED
5066 if (wait_for_import && EditorFileSystem::get_singleton() && EditorFileSystem::get_singleton()->doing_first_scan()) {
5067 exit = false;
5068 }
5069 #endif
5070
5071 if (fixed_fps != -1) {
5072 return exit;
5073 }
5074
5075 SceneTree *scene_tree = SceneTree::get_singleton();
5076 bool wake_for_events = scene_tree && scene_tree->is_accessibility_enabled();
5077
5078 GodotProfileZoneGrouped(_profile_zone, "OS::add_frame_delay");
5079 OS::get_singleton()->add_frame_delay(DisplayServer::get_singleton()->window_can_draw(), wake_for_events);
5080
5081 #ifdef TOOLS_ENABLED
5082 if (auto_build_solutions) {
5083 auto_build_solutions = false;
5084 // Only relevant when running the editor.
5085 if (!editor) {
5086 OS::get_singleton()->set_exit_code(EXIT_FAILURE);
5087 ERR_FAIL_V_MSG(true,
5088 "Command line option --build-solutions was passed, but no project is being edited. Aborting.");
5089 }
5090 if (!EditorNode::get_singleton()->call_build()) {
5091 OS::get_singleton()->set_exit_code(EXIT_FAILURE);
5092 ERR_FAIL_V_MSG(true,
5093 "Command line option --build-solutions was passed, but the build callback failed. Aborting.");
5094 }
5095 }
5096 #endif
5097
5098 #ifdef TOOLS_ENABLED
5099 if (exit && quit_after_timeout && EditorNode::get_singleton()) {
5100 EditorNode::get_singleton()->unload_editor_addons();
5101 }
5102 #endif
5103
5104 return exit;
5105 }
5106
5107 void Main::force_redraw() {
5108 force_redraw_requested = true;
5109 }
5110
5111 /* Engine deinitialization
5112 *
5113 * Responsible for freeing all the memory allocated by previous setup steps,
5114 * so that the engine closes cleanly without leaking memory or crashing.
5115 * The order matters as some of those steps are linked with each other.
5116 */
5117 void Main::cleanup(bool p_force) {
5118 GodotProfileZone("cleanup");
5119 OS::get_singleton()->benchmark_begin_measure("Shutdown", "Main::Cleanup");
5120 if (!p_force) {
5121 ERR_FAIL_COND(!_start_success);
5122 }
5123
5124 // Printing in the usual way can become problematic during/after cleanup.
5125 CoreGlobals::print_ready = false;
5126
5127 #ifdef DEBUG_ENABLED
5128 if (input) {
5129 input->flush_frame_parsed_events();
5130 }
5131 #endif
5132
5133 GDExtensionManager::get_singleton()->shutdown();
5134
5135 for (int i = 0; i < TextServerManager::get_singleton()->get_interface_count(); i++) {
5136 TextServerManager::get_singleton()->get_interface(i)->cleanup();
5137 }
5138
5139 if (movie_writer) {
5140 movie_writer->end();
5141 }
5142
5143 ResourceLoader::clear_thread_load_tasks();
5144
5145 ResourceLoader::remove_custom_loaders();
5146 ResourceSaver::remove_custom_savers();
5147 PropertyListHelper::clear_base_helpers();
5148
5149 // Remove the lock file if the engine exits successfully. Some automated processes such as
5150 // --export/--import can bypass and/or finish faster than the existing check to remove the lock file.
5151 if (OS::get_singleton()->get_exit_code() == EXIT_SUCCESS) {
5152 OS::get_singleton()->remove_lock_file();
5153 }
5154
5155 // Flush before uninitializing the scene, but delete the MessageQueue as late as possible.
5156 message_queue->flush();
5157
5158 OS::get_singleton()->delete_main_loop();
5159
5160 OS::get_singleton()->_cmdline.clear();
5161 OS::get_singleton()->_user_args.clear();
5162 OS::get_singleton()->_execpath = "";
5163 OS::get_singleton()->_local_clipboard = "";
5164
5165 ResourceLoader::clear_translation_remaps();
5166
5167 WorkerThreadPool::get_singleton()->exit_languages_threads();
5168
5169 ScriptServer::finish_languages();
5170
5171 // Sync pending commands that may have been queued from a different thread during ScriptServer finalization
5172 RenderingServer::get_singleton()->sync();
5173
5174 //clear global shader variables before scene and other graphics stuff are deinitialized.
5175 rendering_server->global_shader_parameters_clear();
5176
5177 #ifndef XR_DISABLED
5178 if (xr_server) {
5179 // Now that we're unregistering properly in plugins we need to keep access to xr_server for a little longer
5180 // We do however unset our primary interface
5181 xr_server->set_primary_interface(Ref<XRInterface>());
5182 }
5183 #endif // XR_DISABLED
5184
5185 #ifdef TOOLS_ENABLED
5186 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_EDITOR);
5187 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_EDITOR);
5188 unregister_editor_types();
5189
5190 #endif
5191
5192 ImageLoader::cleanup();
5193
5194 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SCENE);
5195 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SCENE);
5196
5197 unregister_platform_apis();
5198 unregister_driver_types();
5199 unregister_scene_types();
5200
5201 finalize_theme_db();
5202
5203 // Before deinitializing server extensions, finalize servers which may be loaded as extensions.
5204 #ifndef NAVIGATION_2D_DISABLED
5205 NavigationServer2DManager::finalize_server();
5206 NavigationServer2DManager::finalize_server_manager();
5207 #endif // NAVIGATION_2D_DISABLED
5208 #ifndef NAVIGATION_3D_DISABLED
5209 NavigationServer3DManager::finalize_server();
5210 NavigationServer3DManager::finalize_server_manager();
5211 #endif // NAVIGATION_3D_DISABLED
5212 finalize_physics();
5213
5214 GDExtensionManager::get_singleton()->deinitialize_extensions(GDExtension::INITIALIZATION_LEVEL_SERVERS);
5215 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_SERVERS);
5216 unregister_server_types();
5217
5218 EngineDebugger::deinitialize();
5219
5220 #ifndef XR_DISABLED
5221 if (xr_server) {
5222 memdelete(xr_server);
5223 }
5224 #endif // XR_DISABLED
5225
5226 if (audio_server) {
5227 audio_server->finish();
5228 memdelete(audio_server);
5229 }
5230
5231 if (camera_server) {
5232 memdelete(camera_server);
5233 }
5234
5235 OS::get_singleton()->finalize();
5236
5237 finalize_display();
5238
5239 if (input) {
5240 memdelete(input);
5241 }
5242
5243 if (packed_data) {
5244 memdelete(packed_data);
5245 }
5246 if (performance) {
5247 memdelete(performance);
5248 }
5249 if (input_map) {
5250 memdelete(input_map);
5251 }
5252 if (translation_server) {
5253 memdelete(translation_server);
5254 }
5255 if (tsman) {
5256 memdelete(tsman);
5257 }
5258 #ifndef PHYSICS_3D_DISABLED
5259 if (physics_server_3d_manager) {
5260 memdelete(physics_server_3d_manager);
5261 }
5262 #endif // PHYSICS_3D_DISABLED
5263 #ifndef PHYSICS_2D_DISABLED
5264 if (physics_server_2d_manager) {
5265 memdelete(physics_server_2d_manager);
5266 }
5267 #endif // PHYSICS_2D_DISABLED
5268 if (globals) {
5269 memdelete(globals);
5270 }
5271
5272 if (OS::get_singleton()->is_restart_on_exit_set()) {
5273 //attempt to restart with arguments
5274 List<String> args = OS::get_singleton()->get_restart_on_exit_arguments();
5275 OS::get_singleton()->create_instance(args);
5276 OS::get_singleton()->set_restart_on_exit(false, List<String>()); //clear list (uses memory)
5277 }
5278
5279 // Now should be safe to delete MessageQueue (famous last words).
5280 message_queue->flush();
5281 memdelete(message_queue);
5282
5283 #if defined(STEAMAPI_ENABLED)
5284 if (steam_tracker) {
5285 memdelete(steam_tracker);
5286 }
5287 #endif
5288
5289 unregister_core_driver_types();
5290 unregister_core_extensions();
5291 uninitialize_modules(MODULE_INITIALIZATION_LEVEL_CORE);
5292
5293 if (engine) {
5294 memdelete(engine);
5295 }
5296
5297 unregister_core_types();
5298
5299 OS::get_singleton()->benchmark_end_measure("Shutdown", "Main::Cleanup");
5300 OS::get_singleton()->benchmark_dump();
5301
5302 OS::get_singleton()->finalize_core();
5303 }