/**************************************************************************/ /* editor_scene_manager.cpp */ /**************************************************************************/ /* This file is part of: */ /* REDOT ENGINE */ /* https://redotengine.org */ /**************************************************************************/ /* Copyright (c) 2024-present Redot Engine contributors */ /* (see REDOT_AUTHORS.md) */ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #include "editor_scene_manager.h" #include "core/config/project_settings.h" // ProjectSettings #include "core/io/dir_access.h" // DirAccess #include "core/io/file_access.h" // FileAccess #include "core/io/resource_loader.h" #include "core/io/resource_saver.h" #include "core/io/resource_uid.h" // ResourceUID #include "core/os/time.h" #include "editor/animation/animation_player_editor_plugin.h" #include "editor/debugger/editor_debugger_node.h" #include "editor/docks/inspector_dock.h" #include "editor/docks/node_dock.h" #include "editor/docks/scene_tree_dock.h" #include "editor/editor_core.h" #include "editor/editor_main_screen.h" #include "editor/editor_progress.h" #include "editor/editor_shell.h" #include "editor/editor_undo_redo_manager.h" #include "editor/file_system/dependency_editor.h" #include "editor/file_system/editor_file_system.h" #include "editor/file_system/editor_paths.h" #include "editor/gui/editor_file_dialog.h" #include "editor/inspector/editor_properties.h" #include "editor/inspector/multi_node_edit.h" #include "editor/run/editor_run_bar.h" #include "editor/scene/editor_scene_tabs.h" // EditorSceneTabs (scene_tabs calls) #include "editor/script/script_editor_plugin.h" #include "editor/settings/editor_settings.h" #include "scene/2d/node_2d.h" #include "scene/3d/bone_attachment_3d.h" #include "scene/3d/node_3d.h" #include "scene/3d/skeleton_3d.h" #include "scene/animation/animation_node_state_machine.h" #include "scene/animation/animation_player.h" #include "scene/animation/animation_tree.h" #include "scene/gui/dialogs.h" // ConfirmationDialog, AcceptDialog, FileDialog #include "scene/property_utils.h" #include "scene/resources/packed_scene.h" EditorSceneManager *EditorSceneManager::singleton = nullptr; // Layout config section shared with the shell's layout save/restore. static const String EDITOR_NODE_CONFIG_SECTION = "EditorNode"; String EditorSceneManager::_get_unsaved_scene_dialog_text(String p_scene_filename, uint64_t p_started_timestamp) { String unsaved_message; // Consider editor startup to be a point of saving, so that when you // close and reopen the editor, you don't get an excessively long // "modified X hours ago". const uint64_t last_modified_seconds = Time::get_singleton()->get_unix_time_from_system() - MAX(p_started_timestamp, FileAccess::get_modified_time(p_scene_filename)); String last_modified_string; if (last_modified_seconds < 120) { last_modified_string = vformat(TTRN("%d second ago", "%d seconds ago", last_modified_seconds), last_modified_seconds); } else if (last_modified_seconds < 7200) { last_modified_string = vformat(TTRN("%d minute ago", "%d minutes ago", last_modified_seconds / 60), last_modified_seconds / 60); } else { last_modified_string = vformat(TTRN("%d hour ago", "%d hours ago", last_modified_seconds / 3600), last_modified_seconds / 3600); } unsaved_message = vformat(TTR("Scene \"%s\" has unsaved changes.\nLast saved: %s."), p_scene_filename, last_modified_string); return unsaved_message; } void EditorSceneManager::_reset_animation_mixers(Node *p_node, List>> *r_anim_backups) { for (int i = 0; i < p_node->get_child_count(); i++) { AnimationMixer *mixer = Object::cast_to(p_node->get_child(i)); if (mixer && mixer->is_active() && mixer->is_reset_on_save_enabled() && mixer->can_apply_reset()) { AnimationTree *tree = Object::cast_to(p_node->get_child(i)); if (tree) { AnimationPlayer *player = Object::cast_to(tree->get_node_or_null(tree->get_animation_player())); if (player && player->is_active() && player->is_reset_on_save_enabled() && player->can_apply_reset()) { continue; // Avoid to process reset/restore many times. } } Ref backup = mixer->apply_reset(); if (backup.is_valid()) { Pair> pair; pair.first = mixer; pair.second = backup; r_anim_backups->push_back(pair); } } _reset_animation_mixers(p_node->get_child(i), r_anim_backups); } } Node *EditorSceneManager::get_edited_scene() { return core->get_editor_data().get_edited_scene_root(); } int EditorSceneManager::new_scene() { int idx = core->get_editor_data().add_edited_scene(-1); EditorSceneManager::get_singleton()->_set_current_scene(idx); // Before trying to remove an empty scene, set the current tab index to the newly added tab index. // Remove placeholder empty scene. if (core->get_editor_data().get_edited_scene_count() > 1) { for (int i = 0; i < core->get_editor_data().get_edited_scene_count() - 1; i++) { bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(core->get_editor_data().get_scene_history_id(i)); if (!unsaved && core->get_editor_data().get_scene_path(i).is_empty() && core->get_editor_data().get_edited_scene_root(i) == nullptr) { core->get_editor_data().remove_scene(i); idx--; } } } core->get_editor_data().clear_editor_states(); shell->get_scene_tabs()->update_scene_tabs(); return idx; } Error EditorSceneManager::load_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_force_open_imported, bool p_silent_change_tab) { if (!is_inside_tree()) { defer_load_scene = p_scene; return OK; } return _load_scene(p_scene, p_ignore_broken_deps, p_set_inherited, p_force_open_imported, p_silent_change_tab, -1); } Error EditorSceneManager::_load_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_force_open_imported, bool p_silent_change_tab, int p_replace_index) { const String lpath = ProjectSettings::get_singleton()->localize_path(ResourceUID::ensure_path(p_scene)); const bool replacing_scene = p_replace_index >= 0; if (!p_set_inherited && !replacing_scene) { for (int i = 0; i < core->get_editor_data().get_edited_scene_count(); i++) { if (core->get_editor_data().get_scene_path(i) == lpath) { _update_prev_closed_scenes(lpath, false); _set_current_scene(i); return OK; } } if (!p_force_open_imported && FileAccess::exists(lpath + ".import")) { shell->get_open_imported_dialog()->set_text(vformat(TTR("Scene '%s' was automatically imported, so it can't be modified.\nTo make changes to it, a new inherited scene can be created."), lpath.get_file())); shell->get_open_imported_dialog()->popup_centered(); shell->get_new_inherited_button()->grab_focus(); open_import_request = lpath; return OK; } } if (!lpath.begins_with("res://")) { shell->show_accept(TTR("Error loading scene, it must be inside the project path. Use 'Import' to open the scene, then save it inside the project path."), TTR("OK")); return ERR_FILE_NOT_FOUND; } core->get_dependency_errors().clear(); Error err; // Keep the open scene and its cached resources intact until the replacement is ready. const ResourceFormatLoader::CacheMode cache_mode = replacing_scene ? ResourceFormatLoader::CACHE_MODE_IGNORE : ResourceFormatLoader::CACHE_MODE_REPLACE; Ref sdata = ResourceLoader::load(lpath, "", cache_mode, &err); if (!p_ignore_broken_deps && core->get_dependency_errors().has(lpath)) { shell->set_current_menu_option(-1); Vector errors; for (const String &E : core->get_dependency_errors()[lpath]) { errors.push_back(E); } shell->get_dependency_error_dialog()->show(lpath, errors); return ERR_FILE_MISSING_DEPENDENCIES; } if (sdata.is_null()) { shell->_dialog_display_load_error(lpath, err); return ERR_FILE_NOT_FOUND; } core->get_dependency_errors().erase(lpath); // At least not self path. for (KeyValue> &E : core->get_dependency_errors()) { String txt = vformat(TTR("Scene '%s' has broken dependencies:"), E.key) + "\n"; for (const String &F : E.value) { txt += "\t" + F + "\n"; } shell->add_io_error(txt); } Node *new_scene = sdata->instantiate(p_set_inherited ? PackedScene::GEN_EDIT_STATE_MAIN_INHERITED : PackedScene::GEN_EDIT_STATE_MAIN); if (!new_scene) { shell->_dialog_display_load_error(lpath, ERR_FILE_CORRUPT); return ERR_FILE_CORRUPT; } if (ResourceCache::has(lpath)) { // Used from somewhere else? No problem! Update state and replace sdata. Ref ps = ResourceCache::get_ref(lpath); if (ps.is_valid()) { ps->replace_state(sdata->get_state()); ps->set_last_modified_time(sdata->get_last_modified_time()); sdata = ps; } } else { if (replacing_scene) { sdata->set_path_cache(String()); // CACHE_MODE_IGNORE sets the path without registering the resource. } sdata->set_path(lpath, true); // Take over path. } _update_prev_closed_scenes(lpath, false); // Only reuse the empty placeholder created when removing the last open scene. const bool keep_empty_tab = replacing_scene && core->get_editor_data().get_edited_scene_count() > 1; if (replacing_scene) { _remove_scene(p_replace_index, false); } const int prev = core->get_editor_data().get_edited_scene(); if (keep_empty_tab || prev == -1 || core->get_editor_data().get_edited_scene_root() || !core->get_editor_data().get_scene_path(prev).is_empty()) { const int idx = core->get_editor_data().add_edited_scene(-1); if (p_silent_change_tab) { _set_current_scene_nocheck(idx); } else { _set_current_scene(idx); } } else { EditorUndoRedoManager::get_singleton()->clear_history(core->get_editor_data().get_current_edited_scene_history_id(), false); } if (p_set_inherited) { Ref state = sdata->get_state(); state->set_path(lpath); new_scene->set_scene_inherited_state(state); new_scene->set_scene_file_path(String()); } new_scene->set_scene_instance_state(Ref()); set_edited_scene(new_scene); String config_file_path = EditorPaths::get_singleton()->get_project_settings_dir().path_join(lpath.get_file() + "-editstate-" + lpath.md5_text() + ".cfg"); Ref editor_state_cf; editor_state_cf.instantiate(); Error editor_state_cf_err = editor_state_cf->load(config_file_path); if (editor_state_cf_err == OK || editor_state_cf->has_section("editor_states")) { plugin_manager->_load_editor_plugin_states_from_config(editor_state_cf); } if (core->get_editor_folding().has_folding_data(lpath)) { core->get_editor_folding().load_scene_folding(new_scene, lpath); } else if (EDITOR_GET("interface/inspector/auto_unfold_foreign_scenes")) { core->get_editor_folding().unfold_scene(new_scene); core->get_editor_folding().save_scene_folding(new_scene, lpath); } EditorDebuggerNode::get_singleton()->update_live_edit_root(); if (restoring_scenes) { // Initialize history for restored scenes. ObjectID id = new_scene->get_instance_id(); if (id != core->get_editor_selection_history()->get_current()) { core->get_editor_selection_history()->add_object(id); } } // Load the selected nodes. if (editor_state_cf->has_section_key("editor_states", "selected_nodes")) { TypedArray selected_node_list = editor_state_cf->get_value("editor_states", "selected_nodes", TypedArray()); for (int i = 0; i < selected_node_list.size(); i++) { Node *selected_node = new_scene->get_node_or_null(selected_node_list[i]); if (selected_node) { core->get_editor_selection()->add_node(selected_node); } } } if (!restoring_scenes) { shell->save_editor_layout_delayed(); } if (p_set_inherited) { EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(core->get_editor_data().get_current_edited_scene_history_id()); } shell->_update_title(); shell->get_scene_tabs()->update_scene_tabs(); if (!restoring_scenes) { shell->_add_to_recent_scenes(lpath); } return OK; } void EditorSceneManager::set_edited_scene(Node *p_scene) { set_edited_scene_root(p_scene, true); } void EditorSceneManager::set_edited_scene_root(Node *p_scene, bool p_auto_add) { Node *old_edited_scene_root = core->get_editor_data().get_edited_scene_root(); ERR_FAIL_COND_MSG(p_scene && p_scene != old_edited_scene_root && p_scene->get_parent(), "Non-null nodes that are set as edited scene should not have a parent node."); if (p_auto_add && old_edited_scene_root && old_edited_scene_root->get_parent() == shell->get_scene_root()) { shell->get_scene_root()->remove_child(old_edited_scene_root); } core->get_editor_data().set_edited_scene_root(p_scene); if (Object::cast_to(p_scene)) { Object::cast_to(p_scene)->show(); } SceneTreeDock::get_singleton()->set_edited_scene(p_scene); if (get_tree()) { get_tree()->set_edited_scene_root(p_scene); } if (p_auto_add && p_scene) { shell->get_scene_root()->add_child(p_scene, true); } } void EditorSceneManager::edit_node(Node *p_node) { push_item(p_node); } void EditorSceneManager::edit_resource(const Ref &p_resource) { InspectorDock::get_singleton()->edit_resource(p_resource); } void EditorSceneManager::edit_item(Object *p_object, Object *p_editing_owner) { ERR_FAIL_NULL(p_editing_owner); // Editing for this type of object may be disabled by user's feature profile. if (!p_object || shell->_is_class_editor_disabled_by_feature_profile(p_object->get_class())) { // Nothing to edit, clean up the owner context and return. hide_unused_editors(p_editing_owner); return; } // Get a list of editor plugins that can handle this type of object. Vector available_plugins = core->get_editor_data().get_handling_sub_editors(p_object); if (available_plugins.is_empty()) { // None, clean up the owner context and return. hide_unused_editors(p_editing_owner); return; } ObjectID owner_id = p_editing_owner->get_instance_id(); // Remove editor plugins no longer used by this editing owner. Keep the ones that can // still be reused by the new edited object. List to_remove; for (EditorPlugin *plugin : plugin_manager->get_active_plugins()[owner_id]) { if (!available_plugins.has(plugin)) { to_remove.push_back(plugin); if (plugin->can_auto_hide()) { plugin_manager->_plugin_over_edit(plugin, nullptr); } else { // If plugin can't be hidden, make it own itself and become responsible for closing. plugin_manager->_plugin_over_self_own(plugin); } } } for (EditorPlugin *plugin : to_remove) { plugin_manager->get_active_plugins()[owner_id].erase(plugin); } LocalVector to_over_edit; // Send the edited object to the plugins. for (EditorPlugin *plugin : available_plugins) { if (plugin_manager->get_active_plugins()[owner_id].has(plugin)) { // Plugin was already active, just change the object and ensure it's visible. plugin->make_visible(true); plugin->edit(p_object); continue; } if (plugin_manager->get_active_plugins().has(plugin->get_instance_id())) { // Plugin is already active, but as self-owning, so it needs a separate check. plugin->make_visible(true); plugin->edit(p_object); continue; } bool need_to_add = true; List to_fold; // If plugin is already associated with another owner, remove it from there first. for (KeyValue> &kv : plugin_manager->get_active_plugins()) { if (kv.key == owner_id || !kv.value.has(plugin)) { continue; } EditorPropertyResource *epres = ObjectDB::get_instance(kv.key); if (epres) { // If it's resource property editing the same resource type, fold it later to avoid premature modifications // that may result in unsafe iteration of active_plugins. to_fold.push_back(epres); } else { kv.value.erase(plugin); need_to_add = false; } } if (!need_to_add && to_fold.is_empty()) { plugin->make_visible(true); plugin->edit(p_object); } else { for (EditorPropertyResource *epres : to_fold) { epres->fold_resource(); } /// @todo Call the function directly once a proper priority system is implemented. to_over_edit.push_back(plugin); } // Activate previously inactive plugin and edit the object. plugin_manager->get_active_plugins()[owner_id].insert(plugin); } for (EditorPlugin *plugin : to_over_edit) { plugin_manager->_plugin_over_edit(plugin, p_object); } } void EditorSceneManager::push_item(Object *p_object, const String &p_property, bool p_inspector_only) { if (!p_object) { InspectorDock::get_inspector_singleton()->edit(nullptr); NodeDock::get_singleton()->set_node(nullptr); SceneTreeDock::get_singleton()->set_selected(nullptr); InspectorDock::get_singleton()->update(nullptr); hide_unused_editors(); return; } shell->_add_to_history(p_object, p_property, p_inspector_only); shell->_edit_current(); } void EditorSceneManager::push_item_no_inspector(Object *p_object) { shell->_add_to_history(p_object, "", false); shell->_edit_current(false, true); } void EditorSceneManager::push_node_item(Node *p_node) { if (p_node || !InspectorDock::get_inspector_singleton()->get_edited_object() || Object::cast_to(InspectorDock::get_inspector_singleton()->get_edited_object()) || Object::cast_to(InspectorDock::get_inspector_singleton()->get_edited_object())) { // Don't push null if the currently edited object is not a Node. push_item(p_node); } } void EditorSceneManager::edit_previous_item() { if (core->get_editor_selection_history()->previous()) { shell->_edit_current(); } } void EditorSceneManager::hide_unused_editors(const Object *p_editing_owner) { if (p_editing_owner) { const ObjectID id = p_editing_owner->get_instance_id(); for (EditorPlugin *plugin : plugin_manager->get_active_plugins()[id]) { if (plugin->can_auto_hide()) { plugin_manager->_plugin_over_edit(plugin, nullptr); } else { plugin_manager->_plugin_over_self_own(plugin); } } plugin_manager->get_active_plugins().erase(id); } else { // If no editing owner is provided, this method will go over all owners and check if they are valid. // This is to sweep properties that were removed from the inspector. List to_remove; for (KeyValue> &kv : plugin_manager->get_active_plugins()) { Object *context = ObjectDB::get_instance(kv.key); if (context) { // In case of self-owning plugins, they are disabled here if they can auto hide. const EditorPlugin *self_owning = Object::cast_to(context); if (self_owning && self_owning->can_auto_hide()) { context = nullptr; } } if (!context || context->call(SNAME("_should_stop_editing"))) { to_remove.push_back(kv.key); for (EditorPlugin *plugin : kv.value) { if (plugin->can_auto_hide()) { plugin_manager->_plugin_over_edit(plugin, nullptr); } else { plugin_manager->_plugin_over_self_own(plugin); } } } } for (const ObjectID &id : to_remove) { plugin_manager->get_active_plugins().erase(id); } } } void EditorSceneManager::_update_unsaved_cache() { bool is_unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(EditorUndoRedoManager::GLOBAL_HISTORY) || EditorUndoRedoManager::get_singleton()->is_history_unsaved(core->get_editor_data().get_current_edited_scene_history_id()); if (unsaved_cache != is_unsaved) { unsaved_cache = is_unsaved; shell->_update_title(); } } void EditorSceneManager::_update_undo_redo_allowed() { EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); shell->get_file_menu()->set_item_disabled(shell->get_file_menu()->get_item_index(EditorShell::SCENE_UNDO), !undo_redo->has_undo()); shell->get_file_menu()->set_item_disabled(shell->get_file_menu()->get_item_index(EditorShell::SCENE_REDO), !undo_redo->has_redo()); } void EditorSceneManager::_set_current_scene(int p_idx) { if (p_idx == core->get_editor_data().get_edited_scene()) { return; // Pointless. } _set_current_scene_nocheck(p_idx); } void EditorSceneManager::_set_current_scene_nocheck(int p_idx) { // Save the folding in case the scene gets reloaded. if (core->get_editor_data().get_scene_path(p_idx) != "" && core->get_editor_data().get_edited_scene_root(p_idx)) { core->get_editor_folding().save_scene_folding(core->get_editor_data().get_edited_scene_root(p_idx), core->get_editor_data().get_scene_path(p_idx)); } changing_scene = true; core->get_editor_data().save_edited_scene_state(core->get_editor_selection(), core->get_editor_selection_history(), _get_main_scene_state()); Node *old_scene = core->get_editor_data().get_edited_scene_root(); core->get_editor_selection()->clear(); SceneTreeDock::get_singleton()->clear_previous_node_selection(); core->get_editor_data().set_edited_scene(p_idx); Node *new_scene = core->get_editor_data().get_edited_scene_root(); // Remove the scene only if it's a new scene, preventing performance issues when adding and removing scenes. if (old_scene && new_scene != old_scene && old_scene->get_parent() == shell->get_scene_root()) { shell->get_scene_root()->remove_child(old_scene); } if (Popup *p = Object::cast_to(new_scene)) { p->show(); } SceneTreeDock::get_singleton()->set_edited_scene(new_scene); if (get_tree()) { get_tree()->set_edited_scene_root(new_scene); } if (new_scene) { if (new_scene->get_parent() != shell->get_scene_root()) { shell->get_scene_root()->add_child(new_scene, true); } } if (core->get_editor_data().check_and_update_scene(p_idx)) { if (!core->get_editor_data().get_scene_path(p_idx).is_empty()) { core->get_editor_folding().load_scene_folding(core->get_editor_data().get_edited_scene_root(p_idx), core->get_editor_data().get_scene_path(p_idx)); } EditorUndoRedoManager::get_singleton()->clear_history(core->get_editor_data().get_scene_history_id(p_idx), false); } Dictionary state = core->get_editor_data().restore_edited_scene_state(core->get_editor_selection(), core->get_editor_selection_history()); shell->_edit_current(true); shell->_update_title(); callable_mp(shell->get_scene_tabs(), &EditorSceneTabs::update_scene_tabs).call_deferred(); if (tabs_to_close.is_empty()) { callable_mp(this, &EditorSceneManager::_set_main_scene_state).call_deferred(state, get_edited_scene()); // Do after everything else is done setting up. } _update_undo_redo_allowed(); _update_unsaved_cache(); } Error EditorSceneManager::save_scene_to_path(String p_file, bool p_with_preview) { if (p_with_preview) { return shell->_save_scene_with_preview(p_file); } return _save_scene(p_file); } bool EditorSceneManager::_validate_scene_recursive(const String &p_filename, Node *p_node) { for (int i = 0; i < p_node->get_child_count(); i++) { Node *child = p_node->get_child(i); if (child->get_scene_file_path() == p_filename) { return true; } if (_validate_scene_recursive(p_filename, child)) { return true; } } return false; } Error EditorSceneManager::_save_scene(String p_file, int p_idx) { ERR_FAIL_COND_V_MSG(!saving_scene.is_empty() && saving_scene == p_file, ERR_BUSY, "Scene saved while already being saved!"); const int idx = p_idx == -1 ? core->get_editor_data().get_edited_scene() : p_idx; Node *scene = core->get_editor_data().get_edited_scene_root(idx); if (!scene) { shell->show_accept(TTR("This operation can't be done without a tree root."), TTR("OK")); return ERR_CANT_CREATE; } if (!scene->get_scene_file_path().is_empty() && _validate_scene_recursive(scene->get_scene_file_path(), scene)) { shell->show_accept(TTR("This scene can't be saved because there is a cyclic instance inclusion.\nPlease resolve it and then attempt to save again."), TTR("OK")); return ERR_CYCLIC_LINK; } scene->propagate_notification(NOTIFICATION_EDITOR_PRE_SAVE); core->get_editor_data().apply_changes_in_editors(); EditorCore::get_singleton()->save_default_environment(); List>> anim_backups; _reset_animation_mixers(scene, &anim_backups); Ref sdata = ResourceCache::get_ref(p_file); Ref previous_state; if (sdata.is_valid()) { // Something may be referencing this resource and we are good with that. // Keep its old state available in case the save fails. previous_state = sdata->get_state(); sdata->recreate_state(); } else { sdata.instantiate(); } Error err = sdata->pack(scene); if (err != OK) { shell->show_accept(TTR("Couldn't save scene. Likely dependencies (instances or inheritance) couldn't be satisfied."), TTR("OK")); } else { int flags = ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS; if (EDITOR_GET("filesystem/on_save/compress_binary_resources")) { flags |= ResourceSaver::FLAG_COMPRESS; } err = ResourceSaver::save(sdata, p_file, flags); if (err != OK) { shell->_dialog_display_save_error(p_file, err); } } if (err == OK) { _save_editor_states(p_file, idx); // This needs to be emitted before saving external resources. emit_signal(SNAME("scene_saved"), p_file); core->get_editor_data().notify_scene_saved(p_file); _save_external_resources(); const String previous_saving_scene = saving_scene; saving_scene = p_file; // Some editors may save scenes of built-in resources as external data, so avoid saving this scene again. core->get_editor_data().save_editor_external_data(); saving_scene = previous_saving_scene; } else if (previous_state.is_valid()) { sdata->replace_state(previous_state); } for (Pair> &E : anim_backups) { E.first->restore(E.second); } if (err == OK) { core->get_editor_data().set_scene_path(idx, ProjectSettings::get_singleton()->localize_path(p_file)); core->get_editor_data().set_scene_as_saved(idx); core->get_editor_data().set_scene_modified_time(idx, FileAccess::get_modified_time(p_file)); core->get_editor_folding().save_scene_folding(scene, p_file); shell->_update_title(); shell->get_scene_tabs()->update_scene_tabs(); } scene->propagate_notification(NOTIFICATION_EDITOR_POST_SAVE); _update_unsaved_cache(); return err; } void EditorSceneManager::_save_all_scenes() { scenes_to_save_as.clear(); // In case saving was canceled before. for (int i = 0; i < core->get_editor_data().get_edited_scene_count(); i++) { if (!_is_scene_unsaved(i)) { continue; } const Node *scene = core->get_editor_data().get_edited_scene_root(i); ERR_FAIL_NULL(scene); const String &scene_path = scene->get_scene_file_path(); if (scene_path.is_empty() || !DirAccess::exists(scene_path.get_base_dir())) { scenes_to_save_as.push_back(i); continue; } if (i == core->get_editor_data().get_edited_scene()) { shell->_save_scene_with_preview(scene_path); } else { _save_scene(scene_path, i); } } EditorCore::get_singleton()->save_default_environment(); if (!scenes_to_save_as.is_empty()) { _proceed_save_asing_scene_tabs(); } } int EditorSceneManager::_next_unsaved_scene(int p_start) { for (int i = p_start; i < core->get_editor_data().get_edited_scene_count(); i++) { if (!core->get_editor_data().get_edited_scene_root(i)) { continue; } const String &scene_filename = core->get_editor_data().get_edited_scene_root(i)->get_scene_file_path(); bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(core->get_editor_data().get_scene_history_id(i)); if (unsaved) { return i; } else { for (int j = 0; j < core->get_editor_data().get_editor_plugin_count(); j++) { if (!core->get_editor_data().get_editor_plugin(j)->get_unsaved_status(scene_filename).is_empty()) { return i; } } } } return -1; } void EditorSceneManager::_discard_changes(const String &p_str) { switch (shell->get_current_menu_option()) { case EditorShell::SCENE_CLOSE: case EditorShell::SCENE_TAB_CLOSE: { Node *scene = core->get_editor_data().get_edited_scene_root(tab_closing_idx); if (scene != nullptr) { _update_prev_closed_scenes(scene->get_scene_file_path(), true); } // Don't close tabs when exiting the editor (required for "restore_scenes_on_load" setting). if (!shell->_is_closing_editor()) { _remove_scene(tab_closing_idx); shell->get_scene_tabs()->update_scene_tabs(); } _proceed_closing_scene_tabs(); } break; case EditorShell::SCENE_RELOAD_SAVED_SCENE: { shell->get_confirmation_dialog()->hide(); const String scene_path = get_edited_scene()->get_scene_file_path(); _reload_scene(core->get_editor_data().get_edited_scene(), scene_path, false); } break; case EditorShell::SCENE_QUIT: { shell->get_project_run_bar()->stop_playing(); shell->_exit_editor(EXIT_SUCCESS); } break; case EditorShell::PROJECT_QUIT_TO_PROJECT_MANAGER: { shell->_restart_editor(true); } break; case EditorShell::PROJECT_RELOAD_CURRENT_PROJECT: { shell->_restart_editor(); } break; } } void EditorSceneManager::_scene_tab_closed(int p_tab) { shell->set_current_menu_option(EditorShell::SCENE_TAB_CLOSE); tab_closing_idx = p_tab; Node *scene = core->get_editor_data().get_edited_scene_root(p_tab); if (!scene) { _discard_changes(); return; } String scene_filename = scene->get_scene_file_path(); String unsaved_message; if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(core->get_editor_data().get_scene_history_id(p_tab))) { if (scene_filename.is_empty()) { unsaved_message = TTR("This scene was never saved."); } else { unsaved_message = _get_unsaved_scene_dialog_text(scene_filename, EditorCore::get_singleton()->get_started_timestamp()); } } else { // Check if any plugin has unsaved changes in that scene. for (int i = 0; i < core->get_editor_data().get_editor_plugin_count(); i++) { unsaved_message = core->get_editor_data().get_editor_plugin(i)->get_unsaved_status(scene_filename); if (!unsaved_message.is_empty()) { break; } } } if (!unsaved_message.is_empty()) { if (shell->get_scene_tabs()->get_current_tab() != p_tab) { _set_current_scene(p_tab); } shell->get_save_confirmation_dialog()->set_ok_button_text(TTR("Save & Close")); shell->get_save_confirmation_dialog()->set_text(unsaved_message + "\n\n" + TTR("Save before closing?")); shell->get_save_confirmation_dialog()->reset_size(); shell->get_save_confirmation_dialog()->popup_centered(); } else { _discard_changes(); } shell->save_editor_layout_delayed(); shell->get_scene_tabs()->update_scene_tabs(); } void EditorSceneManager::_cancel_close_scene_tab() { if (shell->_is_closing_editor()) { tab_closing_menu_option = -1; } changing_scene = false; tabs_to_close.clear(); } void EditorSceneManager::_remove_edited_scene(bool p_change_tab) { hide_unused_editors(SceneTreeDock::get_singleton()); SceneTreeDock::get_singleton()->clear_previous_node_selection(); int new_index = core->get_editor_data().get_edited_scene(); int old_index = new_index; if (new_index > 0) { new_index = new_index - 1; } else if (core->get_editor_data().get_edited_scene_count() > 1) { new_index = 1; } else { core->get_editor_data().add_edited_scene(-1); new_index = 1; } if (p_change_tab) { _set_current_scene(new_index); } core->get_editor_data().remove_scene(old_index); shell->_update_title(); shell->get_scene_tabs()->update_scene_tabs(); } void EditorSceneManager::_remove_scene(int index, bool p_change_tab) { /// Clear icon cache in case some scripts are no longer needed or class icons are outdated. /// @todo FIXME: Ideally the cache should never be cleared and only updated on per-script basis, when an icon changes. core->get_editor_data().clear_script_icon_cache(); core->get_class_icon_cache().clear(); if (core->get_editor_data().get_edited_scene() == index) { // Scene to remove is current scene. _remove_edited_scene(p_change_tab); } else { // Scene to remove is not active scene. core->get_editor_data().remove_scene(index); } } void EditorSceneManager::_mark_unsaved_scenes() { for (int i = 0; i < core->get_editor_data().get_edited_scene_count(); i++) { Node *node = core->get_editor_data().get_edited_scene_root(i); if (!node) { continue; } String path = node->get_scene_file_path(); if (!path.is_empty() && !FileAccess::exists(path)) { // Mark scene tab as unsaved if the file is gone. EditorUndoRedoManager::get_singleton()->set_history_as_unsaved(core->get_editor_data().get_scene_history_id(i)); } } shell->_update_title(); shell->get_scene_tabs()->update_scene_tabs(); } bool EditorSceneManager::_is_scene_unsaved(int p_idx) { const Node *scene = core->get_editor_data().get_edited_scene_root(p_idx); if (!scene) { return false; } if (EditorUndoRedoManager::get_singleton()->is_history_unsaved(core->get_editor_data().get_scene_history_id(p_idx))) { return true; } const String &scene_path = scene->get_scene_file_path(); if (!scene_path.is_empty()) { // Check if scene has unsaved changes in built-in resources. for (int j = 0; j < core->get_editor_data().get_editor_plugin_count(); j++) { if (!core->get_editor_data().get_editor_plugin(j)->get_unsaved_status(scene_path).is_empty()) { return true; } } } return false; } void EditorSceneManager::_update_prev_closed_scenes(const String &p_scene_path, bool p_add_scene) { if (!p_scene_path.is_empty()) { if (p_add_scene) { prev_closed_scenes.push_back(p_scene_path); } else { prev_closed_scenes.erase(p_scene_path); } shell->get_file_menu()->set_item_disabled(shell->get_file_menu()->get_item_index(EditorShell::SCENE_OPEN_PREV), prev_closed_scenes.is_empty()); } } void EditorSceneManager::queue_tab_close(int p_tab) { tabs_to_close.push_back(core->get_editor_data().get_scene_history_id(p_tab)); } void EditorSceneManager::_proceed_closing_scene_tabs() { List::Element *E = tabs_to_close.front(); if (!E) { if (shell->_is_closing_editor()) { shell->set_current_menu_option(tab_closing_menu_option); tab_closing_menu_option = -1; _save_external_resources(); _discard_changes(); } else { shell->set_current_menu_option(-1); shell->get_save_confirmation_dialog()->hide(); } return; } const int scene_to_close = E->get(); tabs_to_close.pop_front(); int tab_idx = -1; for (int i = 0; i < core->get_editor_data().get_edited_scene_count(); i++) { if (core->get_editor_data().get_scene_history_id(i) == scene_to_close) { tab_idx = i; break; } } ERR_FAIL_COND(tab_idx < 0); _scene_tab_closed(tab_idx); } void EditorSceneManager::_proceed_save_asing_scene_tabs() { if (scenes_to_save_as.is_empty()) { return; } int scene_idx = scenes_to_save_as.front()->get(); scenes_to_save_as.pop_front(); _set_current_scene(scene_idx); shell->_menu_option_confirm(EditorShell::SCENE_MULTI_SAVE_AS_SCENE, false); } Dictionary EditorSceneManager::_get_main_scene_state() { Dictionary state; state["scene_tree_offset"] = SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_value(); state["property_edit_offset"] = InspectorDock::get_inspector_singleton()->get_scroll_offset(); state["node_filter"] = SceneTreeDock::get_singleton()->get_filter(); return state; } void EditorSceneManager::_set_main_scene_state(Dictionary p_state, Node *p_for_scene) { if (get_edited_scene() != p_for_scene && p_for_scene != nullptr) { return; // Not for this scene. } changing_scene = false; if (get_edited_scene()) { if (shell->get_editor_main_screen()->can_auto_switch_screens()) { // Switch between 2D and 3D if currently in 2D or 3D. Node *selected_node = SceneTreeDock::get_singleton()->get_tree_editor()->get_selected(); if (!selected_node) { selected_node = get_edited_scene(); } const int plugin_index = shell->get_editor_main_screen()->get_plugin_index(core->get_editor_data().get_handling_main_editor(selected_node)); if (plugin_index >= 0) { shell->get_editor_main_screen()->select(plugin_index); } } } if (p_state.has("scene_tree_offset")) { SceneTreeDock::get_singleton()->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->set_value(p_state["scene_tree_offset"]); } if (p_state.has("property_edit_offset")) { InspectorDock::get_inspector_singleton()->set_scroll_offset(p_state["property_edit_offset"]); } if (p_state.has("node_filter")) { SceneTreeDock::get_singleton()->set_filter(p_state["node_filter"]); } // This should only happen at the very end. EditorDebuggerNode::get_singleton()->update_live_edit_root(); ScriptEditor::get_singleton()->set_scene_root_script(core->get_editor_data().get_scene_root_script(core->get_editor_data().get_edited_scene())); core->get_editor_data().notify_edited_scene_changed(); emit_signal(SNAME("scene_changed")); // Reset SDFGI after everything else so that any last-second scene modifications will be processed. RenderingServer::get_singleton()->sdfgi_reset(); } void EditorSceneManager::_save_editor_states(const String &p_file, int p_idx) { Node *scene = core->get_editor_data().get_edited_scene_root(p_idx); if (!scene) { return; } String path = EditorPaths::get_singleton()->get_project_settings_dir().path_join(p_file.get_file() + "-editstate-" + p_file.md5_text() + ".cfg"); Ref cf; cf.instantiate(); Dictionary md; if (p_idx < 0 || core->get_editor_data().get_edited_scene() == p_idx) { md = core->get_editor_data().get_editor_plugin_states(); } else { md = core->get_editor_data().get_scene_editor_states(p_idx); } for (const KeyValue &kv : md) { cf->set_value("editor_states", kv.key, kv.value); } // Save the currently selected nodes. List selection = core->get_editor_selection()->get_full_selected_node_list(); TypedArray selection_paths; for (Node *selected_node : selection) { selection_paths.push_back(selected_node->get_path()); } cf->set_value("editor_states", "selected_nodes", selection_paths); Error err = cf->save(path); ERR_FAIL_COND_MSG(err != OK, "Cannot save config file to '" + path + "'."); } void EditorSceneManager::_bind_methods() { ClassDB::bind_method(D_METHOD("push_item", "object", "property", "inspector_only"), &EditorSceneManager::push_item, DEFVAL(""), DEFVAL(false)); ClassDB::bind_method("set_edited_scene", &EditorSceneManager::set_edited_scene); ADD_SIGNAL(MethodInfo("scene_saved", PropertyInfo(Variant::STRING, "path"))); ADD_SIGNAL(MethodInfo("scene_changed")); ADD_SIGNAL(MethodInfo("scene_closed", PropertyInfo(Variant::STRING, "path"))); } EditorSceneManager::EditorSceneManager() { DEV_ASSERT(!singleton); singleton = this; core = EditorCore::get_singleton(); } void EditorSceneManager::_resources_reimporting(const Vector &p_resources) { scenes_modification_table.clear(); scenes_reimported.clear(); resources_reimported.clear(); EditorFileSystem *editor_file_system = EditorFileSystem::get_singleton(); for (const String &res_path : p_resources) { // It's faster to use EditorFileSystem::get_file_type than fetching the resource type from disk. // This makes a big difference when reimporting many resources. String file_type = editor_file_system->get_file_type(res_path); if (file_type.is_empty()) { file_type = ResourceLoader::get_resource_type(res_path); } if (file_type == "PackedScene") { scenes_reimported.push_back(res_path); } else { resources_reimported.push_back(res_path); } } if (scenes_reimported.size() > 0) { preload_reimporting_with_path_in_edited_scenes(scenes_reimported); } } void EditorSceneManager::_resources_reimported(const Vector &p_resources) { int current_tab = shell->get_scene_tabs()->get_current_tab(); for (const String &res_path : resources_reimported) { if (!ResourceCache::has(res_path)) { // Not loaded, no need to reload. continue; } // Reload normally. Ref resource = ResourceCache::get_ref(res_path); if (resource.is_valid()) { resource->reload_from_file(); } } // Editor may crash when related animation is playing while re-importing GLTF scene, stop it in advance. AnimationPlayer *ap = AnimationPlayerEditor::get_singleton()->get_player(); if (ap && scenes_reimported.size() > 0) { ap->stop(true); } // Only refresh the current scene tab if it's been reimported. // Otherwise the scene tab will try to grab focus unnecessarily. bool should_refresh_current_scene_tab = false; const String current_scene_tab = core->get_editor_data().get_scene_path(current_tab); for (const String &E : scenes_reimported) { if (!should_refresh_current_scene_tab && E == current_scene_tab) { should_refresh_current_scene_tab = true; } reload_scene(E); } reload_instances_with_path_in_edited_scenes(); scenes_modification_table.clear(); scenes_reimported.clear(); resources_reimported.clear(); if (should_refresh_current_scene_tab) { _set_current_scene_nocheck(current_tab); } } HashMap EditorSceneManager::get_modified_properties_for_node(Node *p_node, bool p_node_references_only) { HashMap modified_property_map; List pinfo; p_node->get_property_list(&pinfo); for (const PropertyInfo &E : pinfo) { if (E.usage & PROPERTY_USAGE_STORAGE) { bool node_reference = (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE); if (p_node_references_only && !node_reference) { continue; } bool is_valid_revert = false; Variant revert_value = EditorPropertyRevert::get_property_revert_value(p_node, E.name, &is_valid_revert); Variant current_value = p_node->get(E.name); if (is_valid_revert) { if (PropertyUtils::is_property_value_different(p_node, current_value, revert_value)) { // If this property is a direct node reference, save a NodePath instead to prevent corrupted references. if (node_reference) { Node *target_node = Object::cast_to(current_value); if (target_node) { modified_property_map[E.name] = p_node->get_path_to(target_node); } } else { modified_property_map[E.name] = current_value; } } } } } return modified_property_map; } HashMap EditorSceneManager::get_modified_properties_reference_to_nodes(Node *p_node, List &p_nodes_referenced_by) { HashMap modified_property_map; List pinfo; p_node->get_property_list(&pinfo); for (const PropertyInfo &E : pinfo) { if (E.usage & PROPERTY_USAGE_STORAGE) { if (E.type != Variant::OBJECT || E.hint != PROPERTY_HINT_NODE_TYPE) { continue; } Variant current_value = p_node->get(E.name); Node *target_node = Object::cast_to(current_value); if (target_node && p_nodes_referenced_by.find(target_node)) { modified_property_map[E.name] = p_node->get_path_to(target_node); } } } return modified_property_map; } void EditorSceneManager::update_node_from_node_modification_entry(Node *p_node, ModificationNodeEntry &p_node_modification) { if (p_node) { // First, attempt to restore the script property since it may affect the get_property_list method. Variant *script_property_table_entry = p_node_modification.property_table.getptr(CoreStringName(script)); if (script_property_table_entry) { p_node->set_script(*script_property_table_entry); } // Get properties for this node. List pinfo; p_node->get_property_list(&pinfo); // Get names of all valid property names. HashMap property_node_reference_table; for (const PropertyInfo &E : pinfo) { if (E.usage & PROPERTY_USAGE_STORAGE) { if (E.type == Variant::OBJECT && E.hint == PROPERTY_HINT_NODE_TYPE) { property_node_reference_table[E.name] = true; } else { property_node_reference_table[E.name] = false; } } } // Restore the modified properties for this node. for (const KeyValue &E : p_node_modification.property_table) { bool *property_node_reference_table_entry = property_node_reference_table.getptr(E.key); if (property_node_reference_table_entry) { // If the property is a node reference, attempt to restore from the node path instead. bool is_node_reference = *property_node_reference_table_entry; if (is_node_reference) { if (E.value.get_type() == Variant::NODE_PATH) { p_node->set(E.key, p_node->get_node_or_null(E.value)); } } else { p_node->set(E.key, E.value); } } } // Restore the connections to other nodes. for (const ConnectionWithNodePath &E : p_node_modification.connections_to) { Connection conn = E.connection; // Get the node the callable is targeting. Node *target_node = Object::cast_to(conn.callable.get_object()); // If the callable object no longer exists or is marked for deletion, // attempt to reaccquire the closest match by using the node path // we saved earlier. if (!target_node || !target_node->is_queued_for_deletion()) { target_node = p_node->get_node_or_null(E.node_path); } if (target_node) { // Reconstruct the callable. Callable new_callable = Callable(target_node, conn.callable.get_method()); if (!p_node->is_connected(conn.signal.get_name(), new_callable)) { ERR_FAIL_COND(p_node->connect(conn.signal.get_name(), new_callable, conn.flags) != OK); } } } // Restore the connections from other nodes. for (const Connection &E : p_node_modification.connections_from) { Connection conn = E; bool valid = p_node->has_method(conn.callable.get_method()) || Ref