diff options
59 files changed, 1605 insertions, 1056 deletions
diff --git a/editor/debugger/script_editor_debugger.cpp b/editor/debugger/script_editor_debugger.cpp index afa6aaf395..ff59911159 100644 --- a/editor/debugger/script_editor_debugger.cpp +++ b/editor/debugger/script_editor_debugger.cpp @@ -1347,20 +1347,20 @@ void ScriptEditorDebugger::_live_edit_set() { NodePath np = path; - EditorNode::get_singleton()->get_editor_data().set_edited_scene_live_edit_root(np); + EditorNode::get_editor_data().set_edited_scene_live_edit_root(np); update_live_edit_root(); } void ScriptEditorDebugger::_live_edit_clear() { NodePath np = NodePath("/root"); - EditorNode::get_singleton()->get_editor_data().set_edited_scene_live_edit_root(np); + EditorNode::get_editor_data().set_edited_scene_live_edit_root(np); update_live_edit_root(); } void ScriptEditorDebugger::update_live_edit_root() { - NodePath np = EditorNode::get_singleton()->get_editor_data().get_edited_scene_live_edit_root(); + NodePath np = EditorNode::get_editor_data().get_edited_scene_live_edit_root(); Array msg; msg.push_back(np); diff --git a/editor/editor_data.cpp b/editor/editor_data.cpp index 0b2c2bea15..5ea5553cd3 100644 --- a/editor/editor_data.cpp +++ b/editor/editor_data.cpp @@ -244,7 +244,7 @@ EditorSelectionHistory::EditorSelectionHistory() { //////////////////////////////////////////////////////////// -EditorPlugin *EditorData::get_editor(Object *p_object) { +EditorPlugin *EditorData::get_handling_main_editor(Object *p_object) { // We need to iterate backwards so that we can check user-created plugins first. // Otherwise, it would not be possible for plugins to handle CanvasItem and Spatial nodes. for (int i = editor_plugins.size() - 1; i > -1; i--) { @@ -256,7 +256,7 @@ EditorPlugin *EditorData::get_editor(Object *p_object) { return nullptr; } -Vector<EditorPlugin *> EditorData::get_subeditors(Object *p_object) { +Vector<EditorPlugin *> EditorData::get_handling_sub_editors(Object *p_object) { Vector<EditorPlugin *> sub_plugins; for (int i = editor_plugins.size() - 1; i > -1; i--) { if (!editor_plugins[i]->has_main_screen() && editor_plugins[i]->handles(p_object)) { @@ -266,7 +266,7 @@ Vector<EditorPlugin *> EditorData::get_subeditors(Object *p_object) { return sub_plugins; } -EditorPlugin *EditorData::get_editor(String p_name) { +EditorPlugin *EditorData::get_editor_by_name(String p_name) { for (int i = editor_plugins.size() - 1; i > -1; i--) { if (editor_plugins[i]->get_name() == p_name) { return editor_plugins[i]; diff --git a/editor/editor_data.h b/editor/editor_data.h index 28fe13e537..01e9dc4b07 100644 --- a/editor/editor_data.h +++ b/editor/editor_data.h @@ -150,9 +150,9 @@ private: Ref<Texture2D> _load_script_icon(const String &p_path) const; public: - EditorPlugin *get_editor(Object *p_object); - Vector<EditorPlugin *> get_subeditors(Object *p_object); - EditorPlugin *get_editor(String p_name); + EditorPlugin *get_handling_main_editor(Object *p_object); + Vector<EditorPlugin *> get_handling_sub_editors(Object *p_object); + EditorPlugin *get_editor_by_name(String p_name); void copy_object_params(Object *p_object); void paste_object_params(Object *p_object); diff --git a/editor/editor_inspector.cpp b/editor/editor_inspector.cpp index 7ac812101a..ae3cd35fca 100644 --- a/editor/editor_inspector.cpp +++ b/editor/editor_inspector.cpp @@ -880,8 +880,8 @@ void EditorProperty::_update_pin_flags() { // Avoid errors down the road by ignoring nodes which are not part of a scene if (!node->get_owner()) { bool is_scene_root = false; - for (int i = 0; i < EditorNode::get_singleton()->get_editor_data().get_edited_scene_count(); ++i) { - if (EditorNode::get_singleton()->get_editor_data().get_edited_scene_root(i) == node) { + for (int i = 0; i < EditorNode::get_editor_data().get_edited_scene_count(); ++i) { + if (EditorNode::get_editor_data().get_edited_scene_root(i) == node) { is_scene_root = true; break; } @@ -1719,7 +1719,7 @@ void EditorInspectorArray::_move_element(int p_element_index, int p_to_pos) { undo_redo->create_action(action_name); if (mode == MODE_USE_MOVE_ARRAY_ELEMENT_FUNCTION) { // Call the function. - Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name()); + Callable move_function = EditorNode::get_editor_data().get_move_array_element_function(object->get_class_name()); if (move_function.is_valid()) { Variant args[] = { undo_redo, object, array_element_prefix, p_element_index, p_to_pos }; const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] }; @@ -1864,7 +1864,7 @@ void EditorInspectorArray::_clear_array() { if (mode == MODE_USE_MOVE_ARRAY_ELEMENT_FUNCTION) { for (int i = count - 1; i >= 0; i--) { // Call the function. - Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name()); + Callable move_function = EditorNode::get_editor_data().get_move_array_element_function(object->get_class_name()); if (move_function.is_valid()) { Variant args[] = { undo_redo, object, array_element_prefix, i, -1 }; const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] }; @@ -1918,7 +1918,7 @@ void EditorInspectorArray::_resize_array(int p_size) { if (mode == MODE_USE_MOVE_ARRAY_ELEMENT_FUNCTION) { for (int i = count; i < p_size; i++) { // Call the function. - Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name()); + Callable move_function = EditorNode::get_editor_data().get_move_array_element_function(object->get_class_name()); if (move_function.is_valid()) { Variant args[] = { undo_redo, object, array_element_prefix, -1, -1 }; const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] }; @@ -1937,7 +1937,7 @@ void EditorInspectorArray::_resize_array(int p_size) { if (mode == MODE_USE_MOVE_ARRAY_ELEMENT_FUNCTION) { for (int i = count - 1; i > p_size - 1; i--) { // Call the function. - Callable move_function = EditorNode::get_singleton()->get_editor_data().get_move_array_element_function(object->get_class_name()); + Callable move_function = EditorNode::get_editor_data().get_move_array_element_function(object->get_class_name()); if (move_function.is_valid()) { Variant args[] = { undo_redo, object, array_element_prefix, i, -1 }; const Variant *args_p[] = { &args[0], &args[1], &args[2], &args[3], &args[4] }; @@ -3393,6 +3393,7 @@ void EditorInspector::edit(Object *p_object) { if (object == p_object) { return; } + if (object) { _clear(); object->disconnect("property_list_changed", callable_mp(this, &EditorInspector::_changed_callback)); @@ -3500,9 +3501,12 @@ void EditorInspector::_filter_changed(const String &p_text) { update_tree(); } -void EditorInspector::set_use_folding(bool p_enable) { - use_folding = p_enable; - update_tree(); +void EditorInspector::set_use_folding(bool p_use_folding, bool p_update_tree) { + use_folding = p_use_folding; + + if (p_update_tree) { + update_tree(); + } } bool EditorInspector::is_using_folding() { @@ -3693,7 +3697,7 @@ void EditorInspector::_edit_set(const String &p_name, const Variant &p_value, bo Variant v_undo_redo = undo_redo; Variant v_object = object; Variant v_name = p_name; - const Vector<Callable> &callbacks = EditorNode::get_singleton()->get_editor_data().get_undo_redo_inspector_hook_callback(); + const Vector<Callable> &callbacks = EditorNode::get_editor_data().get_undo_redo_inspector_hook_callback(); for (int i = 0; i < callbacks.size(); i++) { const Callable &callback = callbacks[i]; diff --git a/editor/editor_inspector.h b/editor/editor_inspector.h index ed0d0ec373..e41f18e350 100644 --- a/editor/editor_inspector.h +++ b/editor/editor_inspector.h @@ -589,7 +589,7 @@ public: void set_use_filter(bool p_use); void register_text_enter(Node *p_line_edit); - void set_use_folding(bool p_enable); + void set_use_folding(bool p_use_folding, bool p_update_tree = true); bool is_using_folding(); void collapse_all_folding(); diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp index 945372fbdf..d6dea2dc79 100644 --- a/editor/editor_node.cpp +++ b/editor/editor_node.cpp @@ -56,7 +56,6 @@ #include "scene/gui/popup.h" #include "scene/gui/rich_text_label.h" #include "scene/gui/split_container.h" -#include "scene/gui/tab_bar.h" #include "scene/gui/tab_container.h" #include "scene/main/window.h" #include "scene/property_utils.h" @@ -105,6 +104,7 @@ #include "editor/filesystem_dock.h" #include "editor/gui/editor_file_dialog.h" #include "editor/gui/editor_run_bar.h" +#include "editor/gui/editor_scene_tabs.h" #include "editor/gui/editor_title_bar.h" #include "editor/gui/editor_toaster.h" #include "editor/history_dock.h" @@ -271,90 +271,6 @@ void EditorNode::disambiguate_filenames(const Vector<String> p_full_paths, Vecto } } -// TODO: This REALLY should be done in a better way than replacing all tabs after almost EVERY action. -void EditorNode::_update_scene_tabs() { - bool show_rb = EDITOR_GET("interface/scene_tabs/show_script_button"); - - if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) { - DisplayServer::get_singleton()->global_menu_clear("_dock"); - } - - // Get all scene names, which may be ambiguous. - Vector<String> disambiguated_scene_names; - Vector<String> full_path_names; - for (int i = 0; i < editor_data.get_edited_scene_count(); i++) { - disambiguated_scene_names.append(editor_data.get_scene_title(i)); - full_path_names.append(editor_data.get_scene_path(i)); - } - - disambiguate_filenames(full_path_names, disambiguated_scene_names); - - // Workaround to ignore the tab_changed signal from the first added tab. - scene_tabs->disconnect("tab_changed", callable_mp(this, &EditorNode::_scene_tab_changed)); - - scene_tabs->clear_tabs(); - Ref<Texture2D> script_icon = gui_base->get_theme_icon(SNAME("Script"), SNAME("EditorIcons")); - for (int i = 0; i < editor_data.get_edited_scene_count(); i++) { - Node *type_node = editor_data.get_edited_scene_root(i); - Ref<Texture2D> icon; - if (type_node) { - icon = EditorNode::get_singleton()->get_object_icon(type_node, "Node"); - } - - bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(editor_data.get_scene_history_id(i)); - scene_tabs->add_tab(disambiguated_scene_names[i] + (unsaved ? "(*)" : ""), icon); - - if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) { - DisplayServer::get_singleton()->global_menu_add_item("_dock", editor_data.get_scene_title(i) + (unsaved ? "(*)" : ""), callable_mp(this, &EditorNode::_global_menu_scene), Callable(), i); - } - - if (show_rb && editor_data.get_scene_root_script(i).is_valid()) { - scene_tabs->set_tab_button_icon(i, script_icon); - } - } - - if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) { - DisplayServer::get_singleton()->global_menu_add_separator("_dock"); - DisplayServer::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), callable_mp(this, &EditorNode::_global_menu_new_window)); - } - - if (scene_tabs->get_tab_count() > 0) { - scene_tabs->set_current_tab(editor_data.get_edited_scene()); - } - - const Size2 add_button_size = Size2(scene_tab_add->get_size().x, scene_tabs->get_size().y); - if (scene_tabs->get_offset_buttons_visible()) { - // Move the add button to a fixed position. - if (scene_tab_add->get_parent() == scene_tabs) { - scene_tabs->remove_child(scene_tab_add); - scene_tab_add_ph->add_child(scene_tab_add); - scene_tab_add->set_rect(Rect2(Point2(), add_button_size)); - } - } else { - // Move the add button to be after the last tab. - if (scene_tab_add->get_parent() == scene_tab_add_ph) { - scene_tab_add_ph->remove_child(scene_tab_add); - scene_tabs->add_child(scene_tab_add); - } - - if (scene_tabs->get_tab_count() == 0) { - scene_tab_add->set_rect(Rect2(Point2(), add_button_size)); - return; - } - - Rect2 last_tab = scene_tabs->get_tab_rect(scene_tabs->get_tab_count() - 1); - int hsep = scene_tabs->get_theme_constant(SNAME("h_separation")); - if (scene_tabs->is_layout_rtl()) { - scene_tab_add->set_rect(Rect2(Point2(last_tab.position.x - add_button_size.x - hsep, last_tab.position.y), add_button_size)); - } else { - scene_tab_add->set_rect(Rect2(Point2(last_tab.position.x + last_tab.size.width + hsep, last_tab.position.y), add_button_size)); - } - } - - // Reconnect after everything is done. - scene_tabs->connect("tab_changed", callable_mp(this, &EditorNode::_scene_tab_changed)); -} - void EditorNode::_version_control_menu_option(int p_idx) { switch (vcs_actions_menu->get_item_id(p_idx)) { case RUN_VCS_METADATA: { @@ -391,16 +307,6 @@ void EditorNode::shortcut_input(const Ref<InputEvent> &p_event) { if ((k.is_valid() && k->is_pressed() && !k->is_echo()) || Object::cast_to<InputEventShortcut>(*p_event)) { EditorPlugin *old_editor = editor_plugin_screen; - if (ED_IS_SHORTCUT("editor/next_tab", p_event)) { - int next_tab = editor_data.get_edited_scene() + 1; - next_tab %= editor_data.get_edited_scene_count(); - _scene_tab_changed(next_tab); - } - if (ED_IS_SHORTCUT("editor/prev_tab", p_event)) { - int next_tab = editor_data.get_edited_scene() - 1; - next_tab = next_tab >= 0 ? next_tab : editor_data.get_edited_scene_count() - 1; - _scene_tab_changed(next_tab); - } if (ED_IS_SHORTCUT("editor/filter_files", p_event)) { FileSystemDock::get_singleton()->focus_on_filter(); } @@ -562,7 +468,7 @@ void EditorNode::_notification(int p_what) { } if (editor_data.is_scene_changed(-1)) { - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); } // Update the animation frame of the update spinner. @@ -707,7 +613,6 @@ void EditorNode::_notification(int p_what) { } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - scene_tabs->set_tab_close_display_policy((TabBar::CloseButtonDisplayPolicy)EDITOR_GET("interface/scene_tabs/display_close_button").operator int()); FileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files")); EditorFileDialog::set_default_show_hidden_files(EDITOR_GET("filesystem/file_dialog/show_hidden_files")); EditorFileDialog::set_default_display_mode((EditorFileDialog::DisplayMode)EDITOR_GET("filesystem/file_dialog/display_mode").operator int()); @@ -737,17 +642,10 @@ void EditorNode::_notification(int p_what) { main_vbox->add_theme_constant_override("separation", gui_base->get_theme_constant(SNAME("top_bar_separation"), SNAME("Editor"))); scene_root_parent->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("Content"), SNAME("EditorStyles"))); bottom_panel->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("BottomPanel"), SNAME("EditorStyles"))); - tabbar_panel->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("tabbar_background"), SNAME("TabContainer"))); - - scene_tabs->add_theme_constant_override("icon_max_width", gui_base->get_theme_constant(SNAME("class_icon_size"), SNAME("Editor"))); - scene_tab_add_ph->set_custom_minimum_size(scene_tab_add->get_minimum_size()); - main_menu->add_theme_style_override("hover", gui_base->get_theme_stylebox(SNAME("MenuHover"), SNAME("EditorStyles"))); } - scene_tabs->set_max_tab_width(int(EDITOR_GET("interface/scene_tabs/maximum_width")) * EDSCALE); - _update_scene_tabs(); - + scene_tabs->update_scene_tabs(); recent_scenes->reset_size(); // Update debugger area. @@ -772,7 +670,6 @@ void EditorNode::_notification(int p_what) { prev_scene->set_icon(gui_base->get_theme_icon(SNAME("PrevScene"), SNAME("EditorIcons"))); distraction_free->set_icon(gui_base->get_theme_icon(SNAME("DistractionFree"), SNAME("EditorIcons"))); - scene_tab_add->set_icon(gui_base->get_theme_icon(SNAME("Add"), SNAME("EditorIcons"))); bottom_panel_raise->set_icon(gui_base->get_theme_icon(SNAME("ExpandBottomDock"), SNAME("EditorIcons"))); @@ -1131,8 +1028,8 @@ void EditorNode::_reload_modified_scenes() { } } - set_current_scene(current_idx); - _update_scene_tabs(); + _set_current_scene(current_idx); + scene_tabs->update_scene_tabs(); disk_changed->hide(); } @@ -1378,6 +1275,10 @@ void EditorNode::_menu_confirm_current() { _menu_option_confirm(current_menu_option, true); } +void EditorNode::trigger_menu_option(int p_option, bool p_confirmed) { + _menu_option_confirm(p_option, p_confirmed); +} + void EditorNode::_dialog_display_save_error(String p_file, Error p_error) { if (p_error) { switch (p_error) { @@ -1813,7 +1714,7 @@ void EditorNode::_save_scene(String p_file, int idx) { editor_folding.save_scene_folding(scene, p_file); _update_title(); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); } else { _dialog_display_save_error(p_file, err); } @@ -1928,7 +1829,7 @@ void EditorNode::_mark_unsaved_scenes() { } _update_title(); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); } void EditorNode::_dialog_action(String p_file) { @@ -2136,52 +2037,61 @@ bool EditorNode::_is_class_editor_disabled_by_feature_profile(const StringName & void EditorNode::edit_item(Object *p_object, Object *p_editing_owner) { ERR_FAIL_NULL(p_editing_owner); - if (p_object && _is_class_editor_disabled_by_feature_profile(p_object->get_class())) { + // Editing for this type of object may be disabled by user's feature profile. + if (!p_object || _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; } - Vector<EditorPlugin *> item_plugins; - if (p_object) { - item_plugins = editor_data.get_subeditors(p_object); + // Get a list of editor plugins that can handle this type of object. + Vector<EditorPlugin *> available_plugins = 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; } - if (!item_plugins.is_empty()) { - ObjectID owner_id = p_editing_owner->get_instance_id(); + ObjectID owner_id = p_editing_owner->get_instance_id(); - List<EditorPlugin *> to_remove; - for (EditorPlugin *plugin : active_plugins[owner_id]) { - if (!item_plugins.has(plugin)) { - // Remove plugins no longer used by this editing owner. - to_remove.push_back(plugin); - _plugin_over_edit(plugin, nullptr); - } - } + // Remove editor plugins no longer used by this editing owner. Keep the ones that can + // still be reused by the new edited object. - for (EditorPlugin *plugin : to_remove) { - active_plugins[owner_id].erase(plugin); + List<EditorPlugin *> to_remove; + for (EditorPlugin *plugin : active_plugins[owner_id]) { + if (!available_plugins.has(plugin)) { + to_remove.push_back(plugin); + _plugin_over_edit(plugin, nullptr); } + } - for (EditorPlugin *plugin : item_plugins) { - if (active_plugins[owner_id].has(plugin)) { - plugin->edit(p_object); - continue; - } + for (EditorPlugin *plugin : to_remove) { + active_plugins[owner_id].erase(plugin); + } - for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : active_plugins) { - if (kv.key != owner_id) { - EditorPropertyResource *epres = Object::cast_to<EditorPropertyResource>(ObjectDB::get_instance(kv.key)); - if (epres && kv.value.has(plugin)) { - // If it's resource property editing the same resource type, fold it. - epres->fold_resource(); - } - kv.value.erase(plugin); + // Send the edited object to the plugins. + for (EditorPlugin *plugin : available_plugins) { + if (active_plugins[owner_id].has(plugin)) { + // Plugin was already active, just change the object. + plugin->edit(p_object); + continue; + } + + // If plugin is already associated with another owner, remove it from there first. + for (KeyValue<ObjectID, HashSet<EditorPlugin *>> &kv : active_plugins) { + if (kv.key != owner_id) { + EditorPropertyResource *epres = Object::cast_to<EditorPropertyResource>(ObjectDB::get_instance(kv.key)); + if (epres && kv.value.has(plugin)) { + // If it's resource property editing the same resource type, fold it. + epres->fold_resource(); } + kv.value.erase(plugin); } - active_plugins[owner_id].insert(plugin); - _plugin_over_edit(plugin, p_object); } - } else { - hide_unused_editors(p_editing_owner); + + // Activate previously inactive plugin and edit the object. + active_plugins[owner_id].insert(plugin); + _plugin_over_edit(plugin, p_object); } } @@ -2268,7 +2178,8 @@ void EditorNode::_edit_current(bool p_skip_foreign) { Ref<Resource> res = Object::cast_to<Resource>(current_obj); if (p_skip_foreign && res.is_valid()) { - if (res->get_path().find("::") > -1 && res->get_path().get_slice("::", 0) != editor_data.get_scene_path(get_current_tab())) { + const int current_tab = scene_tabs->get_current_tab(); + if (res->get_path().find("::") > -1 && res->get_path().get_slice("::", 0) != editor_data.get_scene_path(current_tab)) { // Trying to edit resource that belongs to another scene; abort. current_obj = nullptr; } @@ -2282,15 +2193,16 @@ void EditorNode::_edit_current(bool p_skip_foreign) { InspectorDock::get_inspector_singleton()->edit(nullptr); NodeDock::get_singleton()->set_node(nullptr); InspectorDock::get_singleton()->update(nullptr); - hide_unused_editors(); - return; } - Object *prev_inspected_object = InspectorDock::get_inspector_singleton()->get_edited_object(); - + // Update the use folding setting and state. bool disable_folding = bool(EDITOR_GET("interface/inspector/disable_folding")); + if (InspectorDock::get_inspector_singleton()->is_using_folding() == disable_folding) { + InspectorDock::get_inspector_singleton()->set_use_folding(!disable_folding, false); + } + bool is_resource = current_obj->is_class("Resource"); bool is_node = current_obj->is_class("Node"); bool stay_in_script_editor_on_node_selected = bool(EDITOR_GET("text_editor/behavior/navigation/stay_in_script_editor_on_node_selected")); @@ -2308,6 +2220,7 @@ void EditorNode::_edit_current(bool p_skip_foreign) { if (is_resource) { Resource *current_res = Object::cast_to<Resource>(current_obj); ERR_FAIL_COND(!current_res); + InspectorDock::get_inspector_singleton()->edit(current_res); SceneTreeDock::get_singleton()->set_selected(nullptr); NodeDock::get_singleton()->set_node(nullptr); @@ -2397,27 +2310,18 @@ void EditorNode::_edit_current(bool p_skip_foreign) { InspectorDock::get_singleton()->update(nullptr); } - if (current_obj == prev_inspected_object) { - // Make sure inspected properties are restored. - InspectorDock::get_inspector_singleton()->update_tree(); - } - InspectorDock::get_singleton()->set_info( info_is_warning ? TTR("Changes may be lost!") : TTR("This object is read-only."), editable_info, info_is_warning); - if (InspectorDock::get_inspector_singleton()->is_using_folding() == disable_folding) { - InspectorDock::get_inspector_singleton()->set_use_folding(!disable_folding); - } - Object *editor_owner = is_node ? (Object *)SceneTreeDock::get_singleton() : is_resource ? (Object *)InspectorDock::get_inspector_singleton() : (Object *)this; // Take care of the main editor plugin. if (!inspector_only) { - EditorPlugin *main_plugin = editor_data.get_editor(current_obj); + EditorPlugin *main_plugin = editor_data.get_handling_main_editor(current_obj); int plugin_index = 0; for (; plugin_index < editor_table.size(); plugin_index++) { @@ -3101,7 +3005,7 @@ void EditorNode::_discard_changes(const String &p_str) { // Don't close tabs when exiting the editor (required for "restore_scenes_on_load" setting). if (!_is_closing_editor()) { _remove_scene(tab_closing_idx); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); } _proceed_closing_scene_tabs(); } break; @@ -3439,11 +3343,11 @@ void EditorNode::_remove_edited_scene(bool p_change_tab) { } if (p_change_tab) { - _scene_tab_changed(new_index); + _set_current_scene(new_index); } editor_data.remove_scene(old_index); _update_title(); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); } void EditorNode::_remove_scene(int index, bool p_change_tab) { @@ -3565,7 +3469,15 @@ bool EditorNode::is_changing_scene() const { return changing_scene; } -void EditorNode::set_current_scene(int p_idx) { +void EditorNode::_set_current_scene(int p_idx) { + if (p_idx == editor_data.get_edited_scene()) { + return; // Pointless. + } + + _set_current_scene_nocheck(p_idx); +} + +void EditorNode::_set_current_scene_nocheck(int p_idx) { // Save the folding in case the scene gets reloaded. if (editor_data.get_scene_path(p_idx) != "" && editor_data.get_edited_scene_root(p_idx)) { editor_folding.save_scene_folding(editor_data.get_edited_scene_root(p_idx), editor_data.get_scene_path(p_idx)); @@ -3612,7 +3524,7 @@ void EditorNode::set_current_scene(int p_idx) { _edit_current(true); _update_title(); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); if (tabs_to_close.is_empty()) { call_deferred(SNAME("_set_main_scene_state"), state, get_edited_scene()); // Do after everything else is done setting up. @@ -3655,9 +3567,9 @@ int EditorNode::new_scene() { } idx = MAX(idx, 0); - _scene_tab_changed(idx); + _set_current_scene(idx); editor_data.clear_editor_states(); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); return idx; } @@ -3670,7 +3582,7 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b if (!p_set_inherited) { for (int i = 0; i < editor_data.get_edited_scene_count(); i++) { if (editor_data.get_scene_path(i) == p_scene) { - _scene_tab_changed(i); + _set_current_scene(i); return OK; } } @@ -3701,10 +3613,10 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b if (!editor_data.get_edited_scene_root() && editor_data.get_edited_scene_count() == 2) { _remove_edited_scene(); - } else if (!p_silent_change_tab) { - _scene_tab_changed(idx); + } else if (p_silent_change_tab) { + _set_current_scene_nocheck(idx); } else { - set_current_scene(idx); + _set_current_scene(idx); } dependency_errors.clear(); @@ -3716,7 +3628,7 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b opening_prev = false; if (prev != -1) { - set_current_scene(prev); + _set_current_scene(prev); editor_data.remove_scene(idx); } return ERR_FILE_NOT_FOUND; @@ -3732,7 +3644,7 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b opening_prev = false; if (prev != -1) { - set_current_scene(prev); + _set_current_scene(prev); editor_data.remove_scene(idx); } return ERR_FILE_MISSING_DEPENDENCIES; @@ -3768,7 +3680,7 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b _dialog_display_load_error(lpath, ERR_FILE_CORRUPT); opening_prev = false; if (prev != -1) { - set_current_scene(prev); + _set_current_scene(prev); editor_data.remove_scene(idx); } return ERR_FILE_CORRUPT; @@ -3794,7 +3706,7 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b } _update_title(); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); _add_to_recent_scenes(lpath); if (editor_folding.has_folding_data(lpath)) { @@ -3806,11 +3718,14 @@ Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, b prev_scene->set_disabled(previous_scenes.size() == 0); opening_prev = false; - SceneTreeDock::get_singleton()->set_selected(new_scene); EditorDebuggerNode::get_singleton()->update_live_edit_root(); - push_item(new_scene); + // Tell everything to edit this object, unless we're in the process of restoring scenes. + // If we are, we'll edit it after the restoration is done. + if (!restoring_scenes) { + push_item(new_scene); + } // Load the selected nodes. if (editor_state_cf->has_section_key("editor_states", "selected_nodes")) { @@ -3989,6 +3904,10 @@ void EditorNode::open_request(const String &p_path) { load_scene(p_path); // As it will be opened in separate tab. } +bool EditorNode::has_previous_scenes() const { + return !previous_scenes.is_empty(); +} + void EditorNode::edit_foreign_resource(Ref<Resource> p_resource) { load_scene(p_resource->get_path().get_slice("::", 0)); InspectorDock::get_singleton()->call_deferred("edit_resource", p_resource); @@ -5399,7 +5318,7 @@ void EditorNode::_load_open_scenes_from_config(Ref<ConfigFile> p_layout) { String current_scene = p_layout->get_value(EDITOR_NODE_CONFIG_SECTION, "current_scene"); int current_scene_idx = scenes.find(current_scene); if (current_scene_idx >= 0) { - set_current_scene(current_scene_idx); + _set_current_scene(current_scene_idx); } } @@ -5491,14 +5410,6 @@ void EditorNode::cleanup() { _init_callbacks.clear(); } -int EditorNode::get_current_tab() { - return scene_tabs->get_current_tab(); -} - -void EditorNode::set_current_tab(int p_tab) { - scene_tabs->set_current_tab(p_tab); -} - void EditorNode::_update_layouts_menu() { editor_layouts->clear(); overridden_default_layout = -1; @@ -5563,13 +5474,6 @@ void EditorNode::_layout_menu_option(int p_id) { } } -void EditorNode::_scene_tab_script_edited(int p_tab) { - Ref<Script> scr = editor_data.get_scene_root_script(p_tab); - if (scr.is_valid()) { - InspectorDock::get_singleton()->edit_resource(scr); - } -} - void EditorNode::_proceed_closing_scene_tabs() { List<String>::Element *E = tabs_to_close.front(); if (!E) { @@ -5601,8 +5505,8 @@ bool EditorNode::_is_closing_editor() const { return tab_closing_menu_option == FILE_QUIT || tab_closing_menu_option == RUN_PROJECT_MANAGER || tab_closing_menu_option == RELOAD_CURRENT_PROJECT; } -void EditorNode::_scene_tab_closed(int p_tab, int p_option) { - current_menu_option = p_option; +void EditorNode::_scene_tab_closed(int p_tab) { + current_menu_option = SCENE_TAB_CLOSE; tab_closing_idx = p_tab; Node *scene = editor_data.get_edited_scene_root(p_tab); if (!scene) { @@ -5630,17 +5534,12 @@ void EditorNode::_scene_tab_closed(int p_tab, int p_option) { } if (!unsaved_message.is_empty()) { - if (get_current_tab() != p_tab) { - set_current_scene(p_tab); + if (scene_tabs->get_current_tab() != p_tab) { + _set_current_scene(p_tab); } - if (current_menu_option == RELOAD_CURRENT_PROJECT) { - save_confirmation->set_ok_button_text(TTR("Save & Reload")); - save_confirmation->set_text(unsaved_message + "\n\n" + TTR("Save before reloading?")); - } else { - save_confirmation->set_ok_button_text(TTR("Save & Close")); - save_confirmation->set_text(unsaved_message + "\n\n" + TTR("Save before closing?")); - } + save_confirmation->set_ok_button_text(TTR("Save & Close")); + save_confirmation->set_text(unsaved_message + "\n\n" + TTR("Save before closing?")); save_confirmation->reset_size(); save_confirmation->popup_centered(); } else { @@ -5648,113 +5547,7 @@ void EditorNode::_scene_tab_closed(int p_tab, int p_option) { } save_editor_layout_delayed(); - _update_scene_tabs(); -} - -void EditorNode::_scene_tab_hovered(int p_tab) { - if (!bool(EDITOR_GET("interface/scene_tabs/show_thumbnail_on_hover"))) { - return; - } - int current_tab = scene_tabs->get_current_tab(); - - if (p_tab == current_tab || p_tab < 0) { - tab_preview_panel->hide(); - } else { - String path = editor_data.get_scene_path(p_tab); - if (!path.is_empty()) { - EditorResourcePreview::get_singleton()->queue_resource_preview(path, this, "_thumbnail_done", p_tab); - } - } -} - -void EditorNode::_scene_tab_exit() { - tab_preview_panel->hide(); -} - -void EditorNode::_scene_tab_input(const Ref<InputEvent> &p_input) { - int tab_id = scene_tabs->get_hovered_tab(); - Ref<InputEventMouseButton> mb = p_input; - - if (mb.is_valid()) { - if (tab_id >= 0) { - if (mb->get_button_index() == MouseButton::MIDDLE && mb->is_pressed()) { - _scene_tab_closed(tab_id); - } - } else if (mb->get_button_index() == MouseButton::LEFT && mb->is_double_click()) { - int tab_buttons = 0; - if (scene_tabs->get_offset_buttons_visible()) { - tab_buttons = theme->get_icon(SNAME("increment"), SNAME("TabBar"))->get_width() + theme->get_icon(SNAME("decrement"), SNAME("TabBar"))->get_width(); - } - - if ((gui_base->is_layout_rtl() && mb->get_position().x > tab_buttons) || (!gui_base->is_layout_rtl() && mb->get_position().x < scene_tabs->get_size().width - tab_buttons)) { - _menu_option_confirm(FILE_NEW_SCENE, true); - } - } - - if (mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed()) { - // Context menu. - scene_tabs_context_menu->clear(); - scene_tabs_context_menu->reset_size(); - - scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/new_scene"), FILE_NEW_SCENE); - if (tab_id >= 0) { - scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_scene"), FILE_SAVE_SCENE); - scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_scene_as"), FILE_SAVE_AS_SCENE); - } - scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_all_scenes"), FILE_SAVE_ALL_SCENES); - if (tab_id >= 0) { - scene_tabs_context_menu->add_separator(); - scene_tabs_context_menu->add_item(TTR("Show in FileSystem"), FILE_SHOW_IN_FILESYSTEM); - scene_tabs_context_menu->add_item(TTR("Play This Scene"), FILE_RUN_SCENE); - - scene_tabs_context_menu->add_separator(); - scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/close_scene"), FILE_CLOSE); - scene_tabs_context_menu->set_item_text(scene_tabs_context_menu->get_item_index(FILE_CLOSE), TTR("Close Tab")); - scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/reopen_closed_scene"), FILE_OPEN_PREV); - scene_tabs_context_menu->set_item_text(scene_tabs_context_menu->get_item_index(FILE_OPEN_PREV), TTR("Undo Close Tab")); - if (previous_scenes.is_empty()) { - scene_tabs_context_menu->set_item_disabled(scene_tabs_context_menu->get_item_index(FILE_OPEN_PREV), true); - } - scene_tabs_context_menu->add_item(TTR("Close Other Tabs"), FILE_CLOSE_OTHERS); - if (editor_data.get_edited_scene_count() <= 1) { - scene_tabs_context_menu->set_item_disabled(file_menu->get_item_index(FILE_CLOSE_OTHERS), true); - } - scene_tabs_context_menu->add_item(TTR("Close Tabs to the Right"), FILE_CLOSE_RIGHT); - if (editor_data.get_edited_scene_count() == tab_id + 1) { - scene_tabs_context_menu->set_item_disabled(file_menu->get_item_index(FILE_CLOSE_RIGHT), true); - } - scene_tabs_context_menu->add_item(TTR("Close All Tabs"), FILE_CLOSE_ALL); - } - scene_tabs_context_menu->set_position(scene_tabs->get_screen_position() + mb->get_position()); - scene_tabs_context_menu->reset_size(); - scene_tabs_context_menu->popup(); - } - } -} - -void EditorNode::_reposition_active_tab(int idx_to) { - editor_data.move_edited_scene_to_index(idx_to); - _update_scene_tabs(); -} - -void EditorNode::_thumbnail_done(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, const Variant &p_udata) { - int p_tab = p_udata.operator signed int(); - if (p_preview.is_valid()) { - Rect2 rect = scene_tabs->get_tab_rect(p_tab); - rect.position += scene_tabs->get_global_position(); - tab_preview->set_texture(p_preview); - tab_preview_panel->set_position(rect.position + Vector2(0, rect.size.height)); - tab_preview_panel->show(); - } -} - -void EditorNode::_scene_tab_changed(int p_tab) { - tab_preview_panel->hide(); - - if (p_tab == editor_data.get_edited_scene()) { - return; // Pointless. - } - set_current_scene(p_tab); + scene_tabs->update_scene_tabs(); } Button *EditorNode::add_bottom_panel_item(String p_text, Control *p_item) { @@ -6069,19 +5862,6 @@ PopupMenu *EditorNode::get_export_as_menu() { return export_as_menu; } -void EditorNode::_global_menu_scene(const Variant &p_tag) { - int idx = (int)p_tag; - scene_tabs->set_current_tab(idx); -} - -void EditorNode::_global_menu_new_window(const Variant &p_tag) { - if (OS::get_singleton()->get_main_loop()) { - List<String> args; - args.push_back("-p"); - OS::get_singleton()->create_instance(args); - } -} - void EditorNode::_dropped_files(const Vector<String> &p_files) { String to_path = ProjectSettings::get_singleton()->globalize_path(FileSystemDock::get_singleton()->get_current_directory()); @@ -6699,9 +6479,6 @@ void EditorNode::_feature_profile_changed() { } void EditorNode::_bind_methods() { - ClassDB::bind_method("edit_current", &EditorNode::edit_current); - ClassDB::bind_method("edit_node", &EditorNode::edit_node); - ClassDB::bind_method(D_METHOD("push_item", "object", "property", "inspector_only"), &EditorNode::push_item, DEFVAL(""), DEFVAL(false)); ClassDB::bind_method("set_edited_scene", &EditorNode::set_edited_scene); @@ -6711,13 +6488,9 @@ void EditorNode::_bind_methods() { ClassDB::bind_method("stop_child_process", &EditorNode::stop_child_process); - ClassDB::bind_method("set_current_scene", &EditorNode::set_current_scene); - ClassDB::bind_method("_thumbnail_done", &EditorNode::_thumbnail_done); ClassDB::bind_method("_set_main_scene_state", &EditorNode::_set_main_scene_state); ClassDB::bind_method("_update_recent_scenes", &EditorNode::_update_recent_scenes); - ClassDB::bind_method(D_METHOD("get_gui_base"), &EditorNode::get_gui_base); - ADD_SIGNAL(MethodInfo("request_help_search")); ADD_SIGNAL(MethodInfo("script_add_function_request", PropertyInfo(Variant::OBJECT, "obj"), PropertyInfo(Variant::STRING, "function"), PropertyInfo(Variant::PACKED_STRING_ARRAY, "args"))); ADD_SIGNAL(MethodInfo("resource_saved", PropertyInfo(Variant::OBJECT, "obj"))); @@ -7255,62 +7028,13 @@ EditorNode::EditorNode() { VBoxContainer *srt = memnew(VBoxContainer); srt->set_v_size_flags(Control::SIZE_EXPAND_FILL); - top_split->add_child(srt); srt->add_theme_constant_override("separation", 0); + top_split->add_child(srt); - tab_preview_panel = memnew(Panel); - tab_preview_panel->set_size(Size2(100, 100) * EDSCALE); - tab_preview_panel->hide(); - tab_preview_panel->set_self_modulate(Color(1, 1, 1, 0.7)); - gui_base->add_child(tab_preview_panel); - - tab_preview = memnew(TextureRect); - tab_preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); - tab_preview->set_size(Size2(96, 96) * EDSCALE); - tab_preview->set_position(Point2(2, 2) * EDSCALE); - tab_preview_panel->add_child(tab_preview); - - tabbar_panel = memnew(PanelContainer); - tabbar_panel->add_theme_style_override("panel", gui_base->get_theme_stylebox(SNAME("tabbar_background"), SNAME("TabContainer"))); - srt->add_child(tabbar_panel); - tabbar_container = memnew(HBoxContainer); - tabbar_panel->add_child(tabbar_container); - - scene_tabs = memnew(TabBar); - scene_tabs->set_select_with_rmb(true); - scene_tabs->add_tab("unsaved"); - scene_tabs->set_tab_close_display_policy((TabBar::CloseButtonDisplayPolicy)EDITOR_GET("interface/scene_tabs/display_close_button").operator int()); - scene_tabs->add_theme_constant_override("icon_max_width", gui_base->get_theme_constant(SNAME("class_icon_size"), SNAME("Editor"))); - scene_tabs->set_max_tab_width(int(EDITOR_GET("interface/scene_tabs/maximum_width")) * EDSCALE); - scene_tabs->set_drag_to_rearrange_enabled(true); - scene_tabs->set_auto_translate(false); - scene_tabs->connect("tab_changed", callable_mp(this, &EditorNode::_scene_tab_changed)); - scene_tabs->connect("tab_button_pressed", callable_mp(this, &EditorNode::_scene_tab_script_edited)); - scene_tabs->connect("tab_close_pressed", callable_mp(this, &EditorNode::_scene_tab_closed).bind(SCENE_TAB_CLOSE)); - scene_tabs->connect("tab_hovered", callable_mp(this, &EditorNode::_scene_tab_hovered)); - scene_tabs->connect("mouse_exited", callable_mp(this, &EditorNode::_scene_tab_exit)); - scene_tabs->connect("gui_input", callable_mp(this, &EditorNode::_scene_tab_input)); - scene_tabs->connect("active_tab_rearranged", callable_mp(this, &EditorNode::_reposition_active_tab)); - scene_tabs->connect("resized", callable_mp(this, &EditorNode::_update_scene_tabs)); - scene_tabs->set_h_size_flags(Control::SIZE_EXPAND_FILL); - tabbar_container->add_child(scene_tabs); - - scene_tabs_context_menu = memnew(PopupMenu); - tabbar_container->add_child(scene_tabs_context_menu); - scene_tabs_context_menu->connect("id_pressed", callable_mp(this, &EditorNode::_menu_option)); - - scene_tab_add = memnew(Button); - scene_tab_add->set_flat(true); - scene_tab_add->set_tooltip_text(TTR("Add a new scene.")); - scene_tab_add->set_icon(gui_base->get_theme_icon(SNAME("Add"), SNAME("EditorIcons"))); - scene_tab_add->add_theme_color_override("icon_normal_color", Color(0.6f, 0.6f, 0.6f, 0.8f)); - scene_tabs->add_child(scene_tab_add); - scene_tab_add->connect("pressed", callable_mp(this, &EditorNode::_menu_option).bind(FILE_NEW_SCENE)); - - scene_tab_add_ph = memnew(Control); - scene_tab_add_ph->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); - scene_tab_add_ph->set_custom_minimum_size(scene_tab_add->get_minimum_size()); - tabbar_container->add_child(scene_tab_add_ph); + scene_tabs = memnew(EditorSceneTabs); + srt->add_child(scene_tabs); + scene_tabs->connect("tab_changed", callable_mp(this, &EditorNode::_set_current_scene)); + scene_tabs->connect("tab_closed", callable_mp(this, &EditorNode::_scene_tab_closed)); distraction_free = memnew(Button); distraction_free->set_flat(true); @@ -7318,10 +7042,10 @@ EditorNode::EditorNode() { ED_SHORTCUT_OVERRIDE("editor/distraction_free_mode", "macos", KeyModifierMask::META | KeyModifierMask::CTRL | Key::D); distraction_free->set_shortcut(ED_GET_SHORTCUT("editor/distraction_free_mode")); distraction_free->set_tooltip_text(TTR("Toggle distraction-free mode.")); - distraction_free->connect("pressed", callable_mp(this, &EditorNode::_toggle_distraction_free_mode)); distraction_free->set_icon(gui_base->get_theme_icon(SNAME("DistractionFree"), SNAME("EditorIcons"))); distraction_free->set_toggle_mode(true); - tabbar_container->add_child(distraction_free); + scene_tabs->add_extra_button(distraction_free); + distraction_free->connect("pressed", callable_mp(this, &EditorNode::_toggle_distraction_free_mode)); scene_root_parent = memnew(PanelContainer); scene_root_parent->set_custom_minimum_size(Size2(0, 80) * EDSCALE); @@ -8144,7 +7868,7 @@ EditorNode::EditorNode() { editor_data.add_edited_scene(-1); editor_data.set_edited_scene(0); - _update_scene_tabs(); + scene_tabs->update_scene_tabs(); ImportDock::get_singleton()->initialize_import_options(); diff --git a/editor/editor_node.h b/editor/editor_node.h index a4dfacf60c..d39e848de8 100644 --- a/editor/editor_node.h +++ b/editor/editor_node.h @@ -93,6 +93,7 @@ class EditorResourcePreview; class EditorResourceConversionPlugin; class EditorRunBar; class EditorRunNative; +class EditorSceneTabs; class EditorSelectionHistory; class EditorSettingsDialog; class EditorTitleBar; @@ -154,6 +155,8 @@ public: }; private: + friend class EditorSceneTabs; + enum MenuOptions { FILE_NEW_SCENE, FILE_NEW_INHERITED_SCENE, @@ -216,6 +219,7 @@ private: SETTINGS_PICK_MAIN_SCENE, SETTINGS_TOGGLE_FULLSCREEN, SETTINGS_HELP, + SCENE_TAB_CLOSE, EDITOR_SCREENSHOT, @@ -235,9 +239,6 @@ private: SET_RENDERER_NAME_SAVE_AND_RESTART, - GLOBAL_NEW_WINDOW, - GLOBAL_SCENE, - IMPORT_PLUGIN_BASE = 100, TOOL_MENU_BASE = 1000 @@ -319,10 +320,7 @@ private: Vector<HSplitContainer *> hsplits; // Main tabs. - TabBar *scene_tabs = nullptr; - PopupMenu *scene_tabs_context_menu = nullptr; - Panel *tab_preview_panel = nullptr; - TextureRect *tab_preview = nullptr; + EditorSceneTabs *scene_tabs = nullptr; int tab_closing_idx = 0; List<String> tabs_to_close; @@ -437,11 +435,7 @@ private: int dock_popup_selected_idx = -1; int dock_select_rect_over_idx = -1; - PanelContainer *tabbar_panel = nullptr; - HBoxContainer *tabbar_container = nullptr; Button *distraction_free = nullptr; - Button *scene_tab_add = nullptr; - Control *scene_tab_add_ph = nullptr; Vector<BottomPanelItem> bottom_panel_items; PanelContainer *bottom_panel = nullptr; @@ -566,7 +560,6 @@ private: void _save_editor_states(const String &p_file, int p_idx = -1); void _load_editor_plugin_states_from_config(const Ref<ConfigFile> &p_config_file); void _update_title(); - void _update_scene_tabs(); void _version_control_menu_option(int p_idx); void _close_messages(); void _show_messages(); @@ -578,11 +571,14 @@ private: int _save_external_resources(); + void _set_current_scene(int p_idx); + void _set_current_scene_nocheck(int p_idx); bool _validate_scene_recursive(const String &p_filename, Node *p_node); void _save_scene(String p_file, int idx = -1); void _save_all_scenes(); int _next_unsaved_scene(bool p_valid_filename, int p_start = 0); void _discard_changes(const String &p_str = String()); + void _scene_tab_closed(int p_tab); void _inherit_request(String p_file); void _instantiate_request(const Vector<String> &p_files); @@ -596,8 +592,6 @@ private: void _add_to_recent_scenes(const String &p_scene); void _update_recent_scenes(); void _open_recent_scene(int p_idx); - void _global_menu_scene(const Variant &p_tag); - void _global_menu_new_window(const Variant &p_tag); void _dropped_files(const Vector<String> &p_files); void _add_dropped_files_recursive(const Vector<String> &p_files, String to_path); @@ -636,16 +630,9 @@ private: void _dock_floating_close_request(WindowWrapper *p_wrapper); void _dock_make_selected_float(); void _dock_make_float(Control *p_control, int p_slot_index, bool p_show_window = true); - void _scene_tab_changed(int p_tab); + void _proceed_closing_scene_tabs(); bool _is_closing_editor() const; - void _scene_tab_closed(int p_tab, int p_option = SCENE_TAB_CLOSE); - void _scene_tab_hovered(int p_tab); - void _scene_tab_exit(); - void _scene_tab_input(const Ref<InputEvent> &p_input); - void _reposition_active_tab(int idx_to); - void _thumbnail_done(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, const Variant &p_udata); - void _scene_tab_script_edited(int p_tab); Dictionary _get_main_scene_state(); void _set_main_scene_state(Dictionary p_state, Node *p_for_scene); @@ -705,9 +692,6 @@ protected: static void _bind_methods(); void _notification(int p_what); - int get_current_tab(); - void set_current_tab(int p_tab); - public: // Public for use with callable_mp. void _on_plugin_ready(Object *p_script, const String &p_activate_name); @@ -764,6 +748,9 @@ public: ProjectSettingsEditor *get_project_settings() { return project_settings_editor; } + void trigger_menu_option(int p_option, bool p_confirmed); + bool has_previous_scenes() const; + void new_inherited_scene() { _menu_option_confirm(FILE_NEW_INHERITED_SCENE, false); } void set_docks_visible(bool p_show); @@ -849,8 +836,6 @@ public: bool is_scene_open(const String &p_path); - void set_current_scene(int p_idx); - void setup_color_picker(ColorPicker *p_picker); void request_instantiate_scene(const String &p_path); diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp index 98e71203ff..2726a781b4 100644 --- a/editor/editor_plugin.cpp +++ b/editor/editor_plugin.cpp @@ -378,11 +378,11 @@ bool EditorPlugin::get_remove_list(List<Node *> *p_list) { } void EditorPlugin::add_undo_redo_inspector_hook_callback(Callable p_callable) { - EditorNode::get_singleton()->get_editor_data().add_undo_redo_inspector_hook_callback(p_callable); + EditorNode::get_editor_data().add_undo_redo_inspector_hook_callback(p_callable); } void EditorPlugin::remove_undo_redo_inspector_hook_callback(Callable p_callable) { - EditorNode::get_singleton()->get_editor_data().remove_undo_redo_inspector_hook_callback(p_callable); + EditorNode::get_editor_data().remove_undo_redo_inspector_hook_callback(p_callable); } void EditorPlugin::add_translation_parser_plugin(const Ref<EditorTranslationParserPlugin> &p_parser) { diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp index 6087ea3abc..b8a112859e 100644 --- a/editor/editor_themes.cpp +++ b/editor/editor_themes.cpp @@ -1507,6 +1507,11 @@ Ref<Theme> create_editor_theme(const Ref<Theme> p_theme) { style_theme_preview_bg_tab->set_expand_margin(SIDE_BOTTOM, 2 * EDSCALE); theme->set_stylebox("ThemeEditorPreviewBG", "EditorStyles", style_theme_preview_bg_tab); + Ref<StyleBoxFlat> style_texture_region_bg = style_tree_bg->duplicate(); + style_texture_region_bg->set_content_margin_all(0); + theme->set_stylebox("TextureRegionPreviewBG", "EditorStyles", style_texture_region_bg); + theme->set_stylebox("TextureRegionPreviewFG", "EditorStyles", make_empty_stylebox(0, 0, 0, 0)); + // Separators theme->set_stylebox("separator", "HSeparator", make_line_stylebox(separator_color, MAX(Math::round(EDSCALE), border_width))); theme->set_stylebox("separator", "VSeparator", make_line_stylebox(separator_color, MAX(Math::round(EDSCALE), border_width), 0, 0, true)); diff --git a/editor/editor_undo_redo_manager.cpp b/editor/editor_undo_redo_manager.cpp index abfbd5e7c0..2b059352a7 100644 --- a/editor/editor_undo_redo_manager.cpp +++ b/editor/editor_undo_redo_manager.cpp @@ -70,7 +70,7 @@ int EditorUndoRedoManager::get_history_id_for_object(Object *p_object) const { Node *edited_scene = EditorNode::get_singleton()->get_edited_scene(); if (edited_scene && (node == edited_scene || edited_scene->is_ancestor_of(node))) { - int idx = EditorNode::get_singleton()->get_editor_data().get_current_edited_scene_history_id(); + int idx = EditorNode::get_editor_data().get_current_edited_scene_history_id(); if (idx > 0) { history_id = idx; } @@ -80,12 +80,12 @@ int EditorUndoRedoManager::get_history_id_for_object(Object *p_object) const { if (Resource *res = Object::cast_to<Resource>(p_object)) { if (res->is_built_in()) { if (res->get_path().is_empty()) { - int idx = EditorNode::get_singleton()->get_editor_data().get_current_edited_scene_history_id(); + int idx = EditorNode::get_editor_data().get_current_edited_scene_history_id(); if (idx > 0) { history_id = idx; } } else { - int idx = EditorNode::get_singleton()->get_editor_data().get_scene_history_id_from_path(res->get_path().get_slice("::", 0)); + int idx = EditorNode::get_editor_data().get_scene_history_id_from_path(res->get_path().get_slice("::", 0)); if (idx > 0) { history_id = idx; } diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp index 751f1c575d..74345a6bcc 100644 --- a/editor/filesystem_dock.cpp +++ b/editor/filesystem_dock.cpp @@ -45,6 +45,7 @@ #include "editor/editor_scale.h" #include "editor/editor_settings.h" #include "editor/gui/editor_dir_dialog.h" +#include "editor/gui/editor_scene_tabs.h" #include "editor/import/resource_importer_scene.h" #include "editor/import_dock.h" #include "editor/plugins/editor_resource_tooltip_plugins.h" @@ -1361,7 +1362,7 @@ void FileSystemDock::_try_move_item(const FileOrFolder &p_item, const String &p_ for (int i = 0; i < file_changed_paths.size(); ++i) { String new_item_path = p_item.is_file ? new_path : file_changed_paths[i].replace_first(old_path, new_path); if (ResourceLoader::get_resource_type(new_item_path) == "PackedScene" && EditorNode::get_singleton()->is_scene_open(file_changed_paths[i])) { - EditorData *ed = &EditorNode::get_singleton()->get_editor_data(); + EditorData *ed = &EditorNode::get_editor_data(); for (int j = 0; j < ed->get_edited_scene_count(); j++) { if (ed->get_scene_path(j) == file_changed_paths[i]) { ed->get_edited_scene_root(j)->set_scene_file_path(new_item_path); @@ -1629,7 +1630,7 @@ void FileSystemDock::_make_scene_confirm() { const String scene_path = make_scene_dialog->get_scene_path(); int idx = EditorNode::get_singleton()->new_scene(); - EditorNode::get_singleton()->get_editor_data().set_scene_path(idx, scene_path); + EditorNode::get_editor_data().set_scene_path(idx, scene_path); EditorNode::get_singleton()->set_edited_scene(make_scene_dialog->create_scene_root()); EditorNode::get_singleton()->save_scene_list({ scene_path }); } @@ -1732,14 +1733,14 @@ void FileSystemDock::_rename_operation_confirm() { HashMap<String, String> folder_renames; _try_move_item(to_rename, new_path, file_renames, folder_renames); - int current_tab = EditorNode::get_singleton()->get_current_tab(); + int current_tab = EditorSceneTabs::get_singleton()->get_current_tab(); _save_scenes_after_move(file_renames); // save scenes before updating _update_dependencies_after_move(file_renames); _update_resource_paths_after_move(file_renames); _update_project_settings_after_move(file_renames); _update_favorites_list_after_move(file_renames, folder_renames); - EditorNode::get_singleton()->set_current_tab(current_tab); + EditorSceneTabs::get_singleton()->set_current_tab(current_tab); print_verbose("FileSystem: calling rescan."); _rescan(); @@ -1881,14 +1882,14 @@ void FileSystemDock::_move_operation_confirm(const String &p_to_path, bool p_cop } if (is_moved) { - int current_tab = EditorNode::get_singleton()->get_current_tab(); + int current_tab = EditorSceneTabs::get_singleton()->get_current_tab(); _save_scenes_after_move(file_renames); // Save scenes before updating. _update_dependencies_after_move(file_renames); _update_resource_paths_after_move(file_renames); _update_project_settings_after_move(file_renames); _update_favorites_list_after_move(file_renames, folder_renames); - EditorNode::get_singleton()->set_current_tab(current_tab); + EditorSceneTabs::get_singleton()->set_current_tab(current_tab); print_verbose("FileSystem: calling rescan."); _rescan(); diff --git a/editor/gui/editor_scene_tabs.cpp b/editor/gui/editor_scene_tabs.cpp new file mode 100644 index 0000000000..3732b922c7 --- /dev/null +++ b/editor/gui/editor_scene_tabs.cpp @@ -0,0 +1,384 @@ +/**************************************************************************/ +/* editor_scene_tabs.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* 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_tabs.h" + +#include "editor/editor_node.h" +#include "editor/editor_resource_preview.h" +#include "editor/editor_scale.h" +#include "editor/editor_settings.h" +#include "editor/editor_undo_redo_manager.h" +#include "editor/inspector_dock.h" +#include "scene/gui/box_container.h" +#include "scene/gui/button.h" +#include "scene/gui/panel.h" +#include "scene/gui/panel_container.h" +#include "scene/gui/popup_menu.h" +#include "scene/gui/tab_bar.h" +#include "scene/gui/texture_rect.h" + +EditorSceneTabs *EditorSceneTabs::singleton = nullptr; + +void EditorSceneTabs::_notification(int p_what) { + switch (p_what) { + case NOTIFICATION_THEME_CHANGED: { + tabbar_panel->add_theme_style_override("panel", get_theme_stylebox(SNAME("tabbar_background"), SNAME("TabContainer"))); + scene_tabs->add_theme_constant_override("icon_max_width", get_theme_constant(SNAME("class_icon_size"), SNAME("Editor"))); + + scene_tab_add->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons"))); + scene_tab_add->add_theme_color_override("icon_normal_color", Color(0.6f, 0.6f, 0.6f, 0.8f)); + + scene_tab_add_ph->set_custom_minimum_size(scene_tab_add->get_minimum_size()); + } break; + + case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { + scene_tabs->set_tab_close_display_policy((TabBar::CloseButtonDisplayPolicy)EDITOR_GET("interface/scene_tabs/display_close_button").operator int()); + scene_tabs->set_max_tab_width(int(EDITOR_GET("interface/scene_tabs/maximum_width")) * EDSCALE); + } break; + } +} + +void EditorSceneTabs::_scene_tab_changed(int p_tab) { + tab_preview_panel->hide(); + + emit_signal("tab_changed", p_tab); +} + +void EditorSceneTabs::_scene_tab_script_edited(int p_tab) { + Ref<Script> scr = EditorNode::get_editor_data().get_scene_root_script(p_tab); + if (scr.is_valid()) { + InspectorDock::get_singleton()->edit_resource(scr); + } +} + +void EditorSceneTabs::_scene_tab_closed(int p_tab) { + emit_signal("tab_closed", p_tab); +} + +void EditorSceneTabs::_scene_tab_hovered(int p_tab) { + if (!bool(EDITOR_GET("interface/scene_tabs/show_thumbnail_on_hover"))) { + return; + } + int current_tab = scene_tabs->get_current_tab(); + + if (p_tab == current_tab || p_tab < 0) { + tab_preview_panel->hide(); + } else { + String path = EditorNode::get_editor_data().get_scene_path(p_tab); + if (!path.is_empty()) { + EditorResourcePreview::get_singleton()->queue_resource_preview(path, this, "_tab_preview_done", p_tab); + } + } +} + +void EditorSceneTabs::_scene_tab_exit() { + tab_preview_panel->hide(); +} + +void EditorSceneTabs::_scene_tab_input(const Ref<InputEvent> &p_input) { + int tab_id = scene_tabs->get_hovered_tab(); + Ref<InputEventMouseButton> mb = p_input; + + if (mb.is_valid()) { + if (tab_id >= 0) { + if (mb->get_button_index() == MouseButton::MIDDLE && mb->is_pressed()) { + _scene_tab_closed(tab_id); + } + } else if (mb->get_button_index() == MouseButton::LEFT && mb->is_double_click()) { + int tab_buttons = 0; + if (scene_tabs->get_offset_buttons_visible()) { + tab_buttons = get_theme_icon(SNAME("increment"), SNAME("TabBar"))->get_width() + get_theme_icon(SNAME("decrement"), SNAME("TabBar"))->get_width(); + } + + if ((is_layout_rtl() && mb->get_position().x > tab_buttons) || (!is_layout_rtl() && mb->get_position().x < scene_tabs->get_size().width - tab_buttons)) { + EditorNode::get_singleton()->trigger_menu_option(EditorNode::FILE_NEW_SCENE, true); + } + } + if (mb->get_button_index() == MouseButton::RIGHT && mb->is_pressed()) { + // Context menu. + _update_context_menu(); + + scene_tabs_context_menu->set_position(scene_tabs->get_screen_position() + mb->get_position()); + scene_tabs_context_menu->reset_size(); + scene_tabs_context_menu->popup(); + } + } +} + +void EditorSceneTabs::_reposition_active_tab(int p_to_index) { + EditorNode::get_editor_data().move_edited_scene_to_index(p_to_index); + update_scene_tabs(); +} + +void EditorSceneTabs::_update_context_menu() { + scene_tabs_context_menu->clear(); + scene_tabs_context_menu->reset_size(); + + int tab_id = scene_tabs->get_hovered_tab(); + + scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/new_scene"), EditorNode::FILE_NEW_SCENE); + if (tab_id >= 0) { + scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_scene"), EditorNode::FILE_SAVE_SCENE); + scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_scene_as"), EditorNode::FILE_SAVE_AS_SCENE); + } + scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/save_all_scenes"), EditorNode::FILE_SAVE_ALL_SCENES); + if (tab_id >= 0) { + scene_tabs_context_menu->add_separator(); + scene_tabs_context_menu->add_item(TTR("Show in FileSystem"), EditorNode::FILE_SHOW_IN_FILESYSTEM); + scene_tabs_context_menu->add_item(TTR("Play This Scene"), EditorNode::FILE_RUN_SCENE); + + scene_tabs_context_menu->add_separator(); + scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/close_scene"), EditorNode::FILE_CLOSE); + scene_tabs_context_menu->set_item_text(scene_tabs_context_menu->get_item_index(EditorNode::FILE_CLOSE), TTR("Close Tab")); + scene_tabs_context_menu->add_shortcut(ED_GET_SHORTCUT("editor/reopen_closed_scene"), EditorNode::FILE_OPEN_PREV); + scene_tabs_context_menu->set_item_text(scene_tabs_context_menu->get_item_index(EditorNode::FILE_OPEN_PREV), TTR("Undo Close Tab")); + if (!EditorNode::get_singleton()->has_previous_scenes()) { + scene_tabs_context_menu->set_item_disabled(scene_tabs_context_menu->get_item_index(EditorNode::FILE_OPEN_PREV), true); + } + scene_tabs_context_menu->add_item(TTR("Close Other Tabs"), EditorNode::FILE_CLOSE_OTHERS); + if (EditorNode::get_editor_data().get_edited_scene_count() <= 1) { + scene_tabs_context_menu->set_item_disabled(scene_tabs_context_menu->get_item_index(EditorNode::FILE_CLOSE_OTHERS), true); + } + scene_tabs_context_menu->add_item(TTR("Close Tabs to the Right"), EditorNode::FILE_CLOSE_RIGHT); + if (EditorNode::get_editor_data().get_edited_scene_count() == tab_id + 1) { + scene_tabs_context_menu->set_item_disabled(scene_tabs_context_menu->get_item_index(EditorNode::FILE_CLOSE_RIGHT), true); + } + scene_tabs_context_menu->add_item(TTR("Close All Tabs"), EditorNode::FILE_CLOSE_ALL); + } +} + +// TODO: This REALLY should be done in a better way than replacing all tabs after almost EVERY action. +void EditorSceneTabs::update_scene_tabs() { + tab_preview_panel->hide(); + + bool show_rb = EDITOR_GET("interface/scene_tabs/show_script_button"); + + if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) { + DisplayServer::get_singleton()->global_menu_clear("_dock"); + } + + // Get all scene names, which may be ambiguous. + Vector<String> disambiguated_scene_names; + Vector<String> full_path_names; + for (int i = 0; i < EditorNode::get_editor_data().get_edited_scene_count(); i++) { + disambiguated_scene_names.append(EditorNode::get_editor_data().get_scene_title(i)); + full_path_names.append(EditorNode::get_editor_data().get_scene_path(i)); + } + + EditorNode::disambiguate_filenames(full_path_names, disambiguated_scene_names); + + // Workaround to ignore the tab_changed signal from the first added tab. + scene_tabs->disconnect("tab_changed", callable_mp(this, &EditorSceneTabs::_scene_tab_changed)); + + scene_tabs->clear_tabs(); + Ref<Texture2D> script_icon = get_theme_icon(SNAME("Script"), SNAME("EditorIcons")); + for (int i = 0; i < EditorNode::get_editor_data().get_edited_scene_count(); i++) { + Node *type_node = EditorNode::get_editor_data().get_edited_scene_root(i); + Ref<Texture2D> icon; + if (type_node) { + icon = EditorNode::get_singleton()->get_object_icon(type_node, "Node"); + } + + bool unsaved = EditorUndoRedoManager::get_singleton()->is_history_unsaved(EditorNode::get_editor_data().get_scene_history_id(i)); + scene_tabs->add_tab(disambiguated_scene_names[i] + (unsaved ? "(*)" : ""), icon); + + if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) { + DisplayServer::get_singleton()->global_menu_add_item("_dock", EditorNode::get_editor_data().get_scene_title(i) + (unsaved ? "(*)" : ""), callable_mp(this, &EditorSceneTabs::_global_menu_scene), Callable(), i); + } + + if (show_rb && EditorNode::get_editor_data().get_scene_root_script(i).is_valid()) { + scene_tabs->set_tab_button_icon(i, script_icon); + } + } + + if (DisplayServer::get_singleton()->has_feature(DisplayServer::FEATURE_GLOBAL_MENU)) { + DisplayServer::get_singleton()->global_menu_add_separator("_dock"); + DisplayServer::get_singleton()->global_menu_add_item("_dock", TTR("New Window"), callable_mp(this, &EditorSceneTabs::_global_menu_new_window)); + } + + if (scene_tabs->get_tab_count() > 0) { + scene_tabs->set_current_tab(EditorNode::get_editor_data().get_edited_scene()); + } + + const Size2 add_button_size = Size2(scene_tab_add->get_size().x, scene_tabs->get_size().y); + if (scene_tabs->get_offset_buttons_visible()) { + // Move the add button to a fixed position. + if (scene_tab_add->get_parent() == scene_tabs) { + scene_tabs->remove_child(scene_tab_add); + scene_tab_add_ph->add_child(scene_tab_add); + scene_tab_add->set_rect(Rect2(Point2(), add_button_size)); + } + } else { + // Move the add button to be after the last tab. + if (scene_tab_add->get_parent() == scene_tab_add_ph) { + scene_tab_add_ph->remove_child(scene_tab_add); + scene_tabs->add_child(scene_tab_add); + } + + if (scene_tabs->get_tab_count() == 0) { + scene_tab_add->set_rect(Rect2(Point2(), add_button_size)); + return; + } + + Rect2 last_tab = scene_tabs->get_tab_rect(scene_tabs->get_tab_count() - 1); + int hsep = scene_tabs->get_theme_constant(SNAME("h_separation")); + if (scene_tabs->is_layout_rtl()) { + scene_tab_add->set_rect(Rect2(Point2(last_tab.position.x - add_button_size.x - hsep, last_tab.position.y), add_button_size)); + } else { + scene_tab_add->set_rect(Rect2(Point2(last_tab.position.x + last_tab.size.width + hsep, last_tab.position.y), add_button_size)); + } + } + + // Reconnect after everything is done. + scene_tabs->connect("tab_changed", callable_mp(this, &EditorSceneTabs::_scene_tab_changed)); +} + +void EditorSceneTabs::_tab_preview_done(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, const Variant &p_udata) { + int p_tab = p_udata; + if (p_preview.is_valid()) { + tab_preview->set_texture(p_preview); + + Rect2 rect = scene_tabs->get_tab_rect(p_tab); + rect.position += scene_tabs->get_global_position(); + tab_preview_panel->set_global_position(rect.position + Vector2(0, rect.size.height)); + tab_preview_panel->show(); + } +} + +void EditorSceneTabs::_global_menu_scene(const Variant &p_tag) { + int idx = (int)p_tag; + scene_tabs->set_current_tab(idx); +} + +void EditorSceneTabs::_global_menu_new_window(const Variant &p_tag) { + if (OS::get_singleton()->get_main_loop()) { + List<String> args; + args.push_back("-p"); + OS::get_singleton()->create_instance(args); + } +} + +void EditorSceneTabs::shortcut_input(const Ref<InputEvent> &p_event) { + ERR_FAIL_COND(p_event.is_null()); + + Ref<InputEventKey> k = p_event; + if ((k.is_valid() && k->is_pressed() && !k->is_echo()) || Object::cast_to<InputEventShortcut>(*p_event)) { + if (ED_IS_SHORTCUT("editor/next_tab", p_event)) { + int next_tab = EditorNode::get_editor_data().get_edited_scene() + 1; + next_tab %= EditorNode::get_editor_data().get_edited_scene_count(); + _scene_tab_changed(next_tab); + } + if (ED_IS_SHORTCUT("editor/prev_tab", p_event)) { + int next_tab = EditorNode::get_editor_data().get_edited_scene() - 1; + next_tab = next_tab >= 0 ? next_tab : EditorNode::get_editor_data().get_edited_scene_count() - 1; + _scene_tab_changed(next_tab); + } + } +} + +void EditorSceneTabs::add_extra_button(Button *p_button) { + tabbar_container->add_child(p_button); +} + +void EditorSceneTabs::set_current_tab(int p_tab) { + scene_tabs->set_current_tab(p_tab); +} + +int EditorSceneTabs::get_current_tab() const { + return scene_tabs->get_current_tab(); +} + +void EditorSceneTabs::_bind_methods() { + ADD_SIGNAL(MethodInfo("tab_changed", PropertyInfo(Variant::INT, "tab_index"))); + ADD_SIGNAL(MethodInfo("tab_closed", PropertyInfo(Variant::INT, "tab_index"))); + + ClassDB::bind_method("_tab_preview_done", &EditorSceneTabs::_tab_preview_done); +} + +EditorSceneTabs::EditorSceneTabs() { + singleton = this; + + tabbar_panel = memnew(PanelContainer); + add_child(tabbar_panel); + tabbar_container = memnew(HBoxContainer); + tabbar_panel->add_child(tabbar_container); + + scene_tabs = memnew(TabBar); + scene_tabs->set_select_with_rmb(true); + scene_tabs->add_tab("unsaved"); + scene_tabs->set_tab_close_display_policy((TabBar::CloseButtonDisplayPolicy)EDITOR_GET("interface/scene_tabs/display_close_button").operator int()); + scene_tabs->set_max_tab_width(int(EDITOR_GET("interface/scene_tabs/maximum_width")) * EDSCALE); + scene_tabs->set_drag_to_rearrange_enabled(true); + scene_tabs->set_auto_translate(false); + scene_tabs->set_h_size_flags(Control::SIZE_EXPAND_FILL); + tabbar_container->add_child(scene_tabs); + + scene_tabs->connect("tab_changed", callable_mp(this, &EditorSceneTabs::_scene_tab_changed)); + scene_tabs->connect("tab_button_pressed", callable_mp(this, &EditorSceneTabs::_scene_tab_script_edited)); + scene_tabs->connect("tab_close_pressed", callable_mp(this, &EditorSceneTabs::_scene_tab_closed)); + scene_tabs->connect("tab_hovered", callable_mp(this, &EditorSceneTabs::_scene_tab_hovered)); + scene_tabs->connect("mouse_exited", callable_mp(this, &EditorSceneTabs::_scene_tab_exit)); + scene_tabs->connect("gui_input", callable_mp(this, &EditorSceneTabs::_scene_tab_input)); + scene_tabs->connect("active_tab_rearranged", callable_mp(this, &EditorSceneTabs::_reposition_active_tab)); + scene_tabs->connect("resized", callable_mp(this, &EditorSceneTabs::update_scene_tabs)); + + scene_tabs_context_menu = memnew(PopupMenu); + tabbar_container->add_child(scene_tabs_context_menu); + scene_tabs_context_menu->connect("id_pressed", callable_mp(EditorNode::get_singleton(), &EditorNode::trigger_menu_option).bind(false)); + + scene_tab_add = memnew(Button); + scene_tab_add->set_flat(true); + scene_tab_add->set_tooltip_text(TTR("Add a new scene.")); + scene_tabs->add_child(scene_tab_add); + scene_tab_add->connect("pressed", callable_mp(EditorNode::get_singleton(), &EditorNode::trigger_menu_option).bind(EditorNode::FILE_NEW_SCENE, false)); + + scene_tab_add_ph = memnew(Control); + scene_tab_add_ph->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); + scene_tab_add_ph->set_custom_minimum_size(scene_tab_add->get_minimum_size()); + tabbar_container->add_child(scene_tab_add_ph); + + // On-hover tab preview. + + Control *tab_preview_anchor = memnew(Control); + tab_preview_anchor->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); + add_child(tab_preview_anchor); + + tab_preview_panel = memnew(Panel); + tab_preview_panel->set_size(Size2(100, 100) * EDSCALE); + tab_preview_panel->hide(); + tab_preview_panel->set_self_modulate(Color(1, 1, 1, 0.7)); + tab_preview_anchor->add_child(tab_preview_panel); + + tab_preview = memnew(TextureRect); + tab_preview->set_stretch_mode(TextureRect::STRETCH_KEEP_ASPECT_CENTERED); + tab_preview->set_size(Size2(96, 96) * EDSCALE); + tab_preview->set_position(Point2(2, 2) * EDSCALE); + tab_preview_panel->add_child(tab_preview); +} diff --git a/editor/gui/editor_scene_tabs.h b/editor/gui/editor_scene_tabs.h new file mode 100644 index 0000000000..c0dbfccdab --- /dev/null +++ b/editor/gui/editor_scene_tabs.h @@ -0,0 +1,94 @@ +/**************************************************************************/ +/* editor_scene_tabs.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* 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. */ +/**************************************************************************/ + +#ifndef EDITOR_SCENE_TABS_H +#define EDITOR_SCENE_TABS_H + +#include "scene/gui/margin_container.h" + +class Button; +class HBoxContainer; +class Panel; +class PanelContainer; +class PopupMenu; +class TabBar; +class TextureRect; + +class EditorSceneTabs : public MarginContainer { + GDCLASS(EditorSceneTabs, MarginContainer); + + static EditorSceneTabs *singleton; + + PanelContainer *tabbar_panel = nullptr; + HBoxContainer *tabbar_container = nullptr; + + TabBar *scene_tabs = nullptr; + PopupMenu *scene_tabs_context_menu = nullptr; + Button *scene_tab_add = nullptr; + Control *scene_tab_add_ph = nullptr; + + Panel *tab_preview_panel = nullptr; + TextureRect *tab_preview = nullptr; + + void _scene_tab_changed(int p_tab); + void _scene_tab_script_edited(int p_tab); + void _scene_tab_closed(int p_tab); + void _scene_tab_hovered(int p_tab); + void _scene_tab_exit(); + void _scene_tab_input(const Ref<InputEvent> &p_input); + + void _reposition_active_tab(int p_to_index); + void _update_context_menu(); + + void _tab_preview_done(const String &p_path, const Ref<Texture2D> &p_preview, const Ref<Texture2D> &p_small_preview, const Variant &p_udata); + + void _global_menu_scene(const Variant &p_tag); + void _global_menu_new_window(const Variant &p_tag); + + virtual void shortcut_input(const Ref<InputEvent> &p_event) override; + +protected: + void _notification(int p_what); + static void _bind_methods(); + +public: + static EditorSceneTabs *get_singleton() { return singleton; } + + void add_extra_button(Button *p_button); + + void set_current_tab(int p_tab); + int get_current_tab() const; + + void update_scene_tabs(); + + EditorSceneTabs(); +}; + +#endif // EDITOR_SCENE_TABS_H diff --git a/editor/import_defaults_editor.cpp b/editor/import_defaults_editor.cpp index 532503bc58..1cee083fba 100644 --- a/editor/import_defaults_editor.cpp +++ b/editor/import_defaults_editor.cpp @@ -167,15 +167,13 @@ void ImportDefaultsEditor::_importer_selected(int p_index) { void ImportDefaultsEditor::clear() { String last_selected; - if (importers->get_selected() > 0) { + + if (importers->get_selected() >= 0) { last_selected = importers->get_item_text(importers->get_selected()); } importers->clear(); - importers->add_item("<" + TTR("Select Importer") + ">"); - importers->set_item_disabled(0, true); - List<Ref<ResourceImporter>> importer_list; ResourceFormatImporter::get_singleton()->get_importers(&importer_list); Vector<String> names; @@ -185,11 +183,17 @@ void ImportDefaultsEditor::clear() { } names.sort(); + // `last_selected.is_empty()` means it's the first time being called. + if (last_selected.is_empty() && !names.is_empty()) { + last_selected = names[0]; + } + for (int i = 0; i < names.size(); i++) { importers->add_item(names[i]); if (names[i] == last_selected) { - importers->select(i + 1); + importers->select(i); + _update_importer(); } } } diff --git a/editor/plugins/audio_stream_randomizer_editor_plugin.cpp b/editor/plugins/audio_stream_randomizer_editor_plugin.cpp index bb3b8a124e..e2ad69ac15 100644 --- a/editor/plugins/audio_stream_randomizer_editor_plugin.cpp +++ b/editor/plugins/audio_stream_randomizer_editor_plugin.cpp @@ -116,7 +116,7 @@ void AudioStreamRandomizerEditorPlugin::_move_stream_array_element(Object *p_und } AudioStreamRandomizerEditorPlugin::AudioStreamRandomizerEditorPlugin() { - EditorNode::get_singleton()->get_editor_data().add_move_array_element_function(SNAME("AudioStreamRandomizer"), callable_mp(this, &AudioStreamRandomizerEditorPlugin::_move_stream_array_element)); + EditorNode::get_editor_data().add_move_array_element_function(SNAME("AudioStreamRandomizer"), callable_mp(this, &AudioStreamRandomizerEditorPlugin::_move_stream_array_element)); } AudioStreamRandomizerEditorPlugin::~AudioStreamRandomizerEditorPlugin() {} diff --git a/editor/plugins/material_editor_plugin.cpp b/editor/plugins/material_editor_plugin.cpp index e24172e761..60119a5499 100644 --- a/editor/plugins/material_editor_plugin.cpp +++ b/editor/plugins/material_editor_plugin.cpp @@ -346,7 +346,7 @@ EditorInspectorPluginMaterial::EditorInspectorPluginMaterial() { env->set_ambient_source(Environment::AMBIENT_SOURCE_SKY); env->set_reflection_source(Environment::REFLECTION_SOURCE_SKY); - EditorNode::get_singleton()->get_editor_data().add_undo_redo_inspector_hook_callback(callable_mp(this, &EditorInspectorPluginMaterial::_undo_redo_inspector_callback)); + EditorNode::get_editor_data().add_undo_redo_inspector_hook_callback(callable_mp(this, &EditorInspectorPluginMaterial::_undo_redo_inspector_callback)); } MaterialEditorPlugin::MaterialEditorPlugin() { diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp index eb0e20a12e..d6a382f9dd 100644 --- a/editor/plugins/script_editor_plugin.cpp +++ b/editor/plugins/script_editor_plugin.cpp @@ -3627,7 +3627,7 @@ void ScriptEditor::_on_find_in_files_result_selected(String fpath, int line_numb Ref<Resource> res = ResourceLoader::load(fpath); if (fpath.get_extension() == "gdshader") { - ShaderEditorPlugin *shader_editor = Object::cast_to<ShaderEditorPlugin>(EditorNode::get_singleton()->get_editor_data().get_editor("Shader")); + ShaderEditorPlugin *shader_editor = Object::cast_to<ShaderEditorPlugin>(EditorNode::get_editor_data().get_editor_by_name("Shader")); shader_editor->edit(res.ptr()); shader_editor->make_visible(true); shader_editor->get_shader_editor(res)->goto_line_selection(line_number - 1, begin, end); diff --git a/editor/plugins/texture_region_editor_plugin.cpp b/editor/plugins/texture_region_editor_plugin.cpp index 19df31a0b3..124cd79126 100644 --- a/editor/plugins/texture_region_editor_plugin.cpp +++ b/editor/plugins/texture_region_editor_plugin.cpp @@ -38,64 +38,46 @@ #include "editor/editor_undo_redo_manager.h" #include "scene/gui/check_box.h" #include "scene/gui/option_button.h" +#include "scene/gui/panel_container.h" #include "scene/gui/separator.h" #include "scene/gui/spin_box.h" #include "scene/gui/view_panner.h" #include "scene/resources/atlas_texture.h" -void draw_margin_line(Control *edit_draw, Vector2 from, Vector2 to) { - Vector2 line = (to - from).normalized() * 10; +Transform2D TextureRegionEditor::_get_offset_transform() const { + Transform2D mtx; + mtx.columns[2] = -draw_ofs * draw_zoom; + mtx.scale_basis(Vector2(draw_zoom, draw_zoom)); - // Draw a translucent background line to make the foreground line visible on any background. - edit_draw->draw_line( - from, - to, - EditorNode::get_singleton()->get_theme_base()->get_theme_color(SNAME("mono_color"), SNAME("Editor")).inverted() * Color(1, 1, 1, 0.5), - Math::round(2 * EDSCALE)); - - while (from.distance_squared_to(to) > 200) { - edit_draw->draw_line( - from, - from + line, - EditorNode::get_singleton()->get_theme_base()->get_theme_color(SNAME("mono_color"), SNAME("Editor")), - Math::round(2 * EDSCALE)); - - from += line * 2; - } + return mtx; } -void TextureRegionEditor::_region_draw() { - Ref<Texture2D> base_tex = nullptr; - if (atlas_tex.is_valid()) { - base_tex = atlas_tex->get_atlas(); - } else if (node_sprite_2d) { - base_tex = node_sprite_2d->get_texture(); - } else if (node_sprite_3d) { - base_tex = node_sprite_3d->get_texture(); - } else if (node_ninepatch) { - base_tex = node_ninepatch->get_texture(); - } else if (obj_styleBox.is_valid()) { - base_tex = obj_styleBox->get_texture(); - } - - if (base_tex.is_null()) { +void TextureRegionEditor::_texture_preview_draw() { + Ref<Texture2D> object_texture = _get_edited_object_texture(); + if (object_texture.is_null()) { return; } - Transform2D mtx; - mtx.columns[2] = -draw_ofs * draw_zoom; - mtx.scale_basis(Vector2(draw_zoom, draw_zoom)); + Transform2D mtx = _get_offset_transform(); - RS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(), mtx); - edit_draw->draw_rect(Rect2(Point2(), preview_tex->get_size()), Color(0.5, 0.5, 0.5, 0.5), false); - edit_draw->draw_texture(preview_tex, Point2()); - RS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(), Transform2D()); + RS::get_singleton()->canvas_item_add_set_transform(texture_preview->get_canvas_item(), mtx); + texture_preview->draw_rect(Rect2(Point2(), object_texture->get_size()), Color(0.5, 0.5, 0.5, 0.5), false); + texture_preview->draw_texture(object_texture, Point2()); + RS::get_singleton()->canvas_item_add_set_transform(texture_preview->get_canvas_item(), Transform2D()); +} + +void TextureRegionEditor::_texture_overlay_draw() { + Ref<Texture2D> object_texture = _get_edited_object_texture(); + if (object_texture.is_null()) { + return; + } + Transform2D mtx = _get_offset_transform(); const Color color = get_theme_color(SNAME("mono_color"), SNAME("Editor")); if (snap_mode == SNAP_GRID) { const Color grid_color = Color(color.r, color.g, color.b, color.a * 0.15); - Size2 s = edit_draw->get_size(); + Size2 s = texture_overlay->get_size(); int last_cell = 0; if (snap_step.x != 0) { @@ -106,7 +88,7 @@ void TextureRegionEditor::_region_draw() { last_cell = cell; } if (last_cell != cell) { - edit_draw->draw_line(Point2(i, 0), Point2(i, s.height), grid_color); + texture_overlay->draw_line(Point2(i, 0), Point2(i, s.height), grid_color); } last_cell = cell; } @@ -117,7 +99,7 @@ void TextureRegionEditor::_region_draw() { last_cell = cell; } if (last_cell != cell) { - edit_draw->draw_rect(Rect2(i - snap_separation.x * draw_zoom, 0, snap_separation.x * draw_zoom, s.height), grid_color); + texture_overlay->draw_rect(Rect2(i - snap_separation.x * draw_zoom, 0, snap_separation.x * draw_zoom, s.height), grid_color); } last_cell = cell; } @@ -132,7 +114,7 @@ void TextureRegionEditor::_region_draw() { last_cell = cell; } if (last_cell != cell) { - edit_draw->draw_line(Point2(0, i), Point2(s.width, i), grid_color); + texture_overlay->draw_line(Point2(0, i), Point2(s.width, i), grid_color); } last_cell = cell; } @@ -143,7 +125,7 @@ void TextureRegionEditor::_region_draw() { last_cell = cell; } if (last_cell != cell) { - edit_draw->draw_rect(Rect2(0, i - snap_separation.y * draw_zoom, s.width, snap_separation.y * draw_zoom), grid_color); + texture_overlay->draw_rect(Rect2(0, i - snap_separation.y * draw_zoom, s.width, snap_separation.y * draw_zoom), grid_color); } last_cell = cell; } @@ -159,14 +141,14 @@ void TextureRegionEditor::_region_draw() { }; for (int i = 0; i < 4; i++) { int next = (i + 1) % 4; - edit_draw->draw_line(endpoints[i] - draw_ofs * draw_zoom, endpoints[next] - draw_ofs * draw_zoom, Color(0.3, 0.7, 1, 1), 2); + texture_overlay->draw_line(endpoints[i] - draw_ofs * draw_zoom, endpoints[next] - draw_ofs * draw_zoom, Color(0.3, 0.7, 1, 1), 2); } } } Ref<Texture2D> select_handle = get_theme_icon(SNAME("EditorHandle"), SNAME("EditorIcons")); - Rect2 scroll_rect(Point2(), base_tex->get_size()); + Rect2 scroll_rect(Point2(), object_texture->get_size()); const Vector2 raw_endpoints[4] = { rect.position, @@ -187,23 +169,23 @@ void TextureRegionEditor::_region_draw() { Vector2 ofs = ((endpoints[i] - endpoints[prev]).normalized() + ((endpoints[i] - endpoints[next]).normalized())).normalized(); ofs *= Math_SQRT2 * (select_handle->get_size().width / 2); - edit_draw->draw_line(endpoints[i] - draw_ofs * draw_zoom, endpoints[next] - draw_ofs * draw_zoom, color, 2); + texture_overlay->draw_line(endpoints[i] - draw_ofs * draw_zoom, endpoints[next] - draw_ofs * draw_zoom, color, 2); if (snap_mode != SNAP_AUTOSLICE) { - edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs * draw_zoom); + texture_overlay->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs * draw_zoom); } ofs = (endpoints[next] - endpoints[i]) / 2; ofs += (endpoints[next] - endpoints[i]).orthogonal().normalized() * (select_handle->get_size().width / 2); if (snap_mode != SNAP_AUTOSLICE) { - edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs * draw_zoom); + texture_overlay->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs * draw_zoom); } scroll_rect.expand_to(raw_endpoints[i]); } - const Size2 scroll_margin = edit_draw->get_size() / draw_zoom; + const Size2 scroll_margin = texture_overlay->get_size() / draw_zoom; scroll_rect.position -= scroll_margin; scroll_rect.size += scroll_margin * 2; @@ -244,21 +226,22 @@ void TextureRegionEditor::_region_draw() { vscroll->set_value((vscroll->get_min() + vscroll->get_max() - vscroll->get_page()) / 2); // This ensures that the view is updated correctly. callable_mp(this, &TextureRegionEditor::_pan_callback).bind(Vector2(1, 0)).call_deferred(); + callable_mp(this, &TextureRegionEditor::_scroll_changed).bind(0.0).call_deferred(); request_center = false; } - if (node_ninepatch || obj_styleBox.is_valid()) { + if (node_ninepatch || res_stylebox.is_valid()) { float margins[4] = { 0 }; if (node_ninepatch) { margins[0] = node_ninepatch->get_patch_margin(SIDE_TOP); margins[1] = node_ninepatch->get_patch_margin(SIDE_BOTTOM); margins[2] = node_ninepatch->get_patch_margin(SIDE_LEFT); margins[3] = node_ninepatch->get_patch_margin(SIDE_RIGHT); - } else if (obj_styleBox.is_valid()) { - margins[0] = obj_styleBox->get_texture_margin(SIDE_TOP); - margins[1] = obj_styleBox->get_texture_margin(SIDE_BOTTOM); - margins[2] = obj_styleBox->get_texture_margin(SIDE_LEFT); - margins[3] = obj_styleBox->get_texture_margin(SIDE_RIGHT); + } else if (res_stylebox.is_valid()) { + margins[0] = res_stylebox->get_texture_margin(SIDE_TOP); + margins[1] = res_stylebox->get_texture_margin(SIDE_BOTTOM); + margins[2] = res_stylebox->get_texture_margin(SIDE_LEFT); + margins[3] = res_stylebox->get_texture_margin(SIDE_RIGHT); } Vector2 pos[4] = { @@ -268,14 +251,36 @@ void TextureRegionEditor::_region_draw() { -mtx.basis_xform(Vector2(margins[3], 0)) + Vector2(endpoints[2].x - draw_ofs.x * draw_zoom, 0) }; - draw_margin_line(edit_draw, pos[0], pos[0] + Vector2(edit_draw->get_size().x, 0)); - draw_margin_line(edit_draw, pos[1], pos[1] + Vector2(edit_draw->get_size().x, 0)); - draw_margin_line(edit_draw, pos[2], pos[2] + Vector2(0, edit_draw->get_size().y)); - draw_margin_line(edit_draw, pos[3], pos[3] + Vector2(0, edit_draw->get_size().y)); + _draw_margin_line(pos[0], pos[0] + Vector2(texture_overlay->get_size().x, 0)); + _draw_margin_line(pos[1], pos[1] + Vector2(texture_overlay->get_size().x, 0)); + _draw_margin_line(pos[2], pos[2] + Vector2(0, texture_overlay->get_size().y)); + _draw_margin_line(pos[3], pos[3] + Vector2(0, texture_overlay->get_size().y)); } } -void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { +void TextureRegionEditor::_draw_margin_line(Vector2 p_from, Vector2 p_to) { + // Margin line is a dashed line with a normalized dash length. This method works + // for both vertical and horizontal lines. + + Vector2 dash_size = (p_to - p_from).normalized() * 10; + const int dash_thickness = Math::round(2 * EDSCALE); + const Color dash_color = get_theme_color(SNAME("mono_color"), SNAME("Editor")); + const Color dash_bg_color = dash_color.inverted() * Color(1, 1, 1, 0.5); + const int line_threshold = 200; + + // Draw a translucent background line to make the foreground line visible on any background. + texture_overlay->draw_line(p_from, p_to, dash_bg_color, dash_thickness); + + Vector2 dash_start = p_from; + while (dash_start.distance_squared_to(p_to) > line_threshold) { + texture_overlay->draw_line(dash_start, dash_start + dash_size, dash_color, dash_thickness); + + // Skip two size lengths, one for the drawn dash and one for the gap. + dash_start += dash_size * 2; + } +} + +void TextureRegionEditor::_texture_overlay_input(const Ref<InputEvent> &p_input) { if (panner->gui_input(p_input)) { return; } @@ -284,112 +289,28 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { mtx.columns[2] = -draw_ofs * draw_zoom; mtx.scale_basis(Vector2(draw_zoom, draw_zoom)); - const real_t handle_radius = 8 * EDSCALE; - const real_t handle_offset = 4 * EDSCALE; - - // Position of selection handles. - const Vector2 endpoints[8] = { - mtx.xform(rect.position) + Vector2(-handle_offset, -handle_offset), - mtx.xform(rect.position + Vector2(rect.size.x / 2, 0)) + Vector2(0, -handle_offset), - mtx.xform(rect.position + Vector2(rect.size.x, 0)) + Vector2(handle_offset, -handle_offset), - mtx.xform(rect.position + Vector2(rect.size.x, rect.size.y / 2)) + Vector2(handle_offset, 0), - mtx.xform(rect.position + rect.size) + Vector2(handle_offset, handle_offset), - mtx.xform(rect.position + Vector2(rect.size.x / 2, rect.size.y)) + Vector2(0, handle_offset), - mtx.xform(rect.position + Vector2(0, rect.size.y)) + Vector2(-handle_offset, handle_offset), - mtx.xform(rect.position + Vector2(0, rect.size.y / 2)) + Vector2(-handle_offset, 0) - }; - EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton(); Ref<InputEventMouseButton> mb = p_input; if (mb.is_valid()) { if (mb->get_button_index() == MouseButton::LEFT) { if (mb->is_pressed() && !panner->is_panning()) { - if (node_ninepatch || obj_styleBox.is_valid()) { - edited_margin = -1; - float margins[4] = { 0 }; - if (node_ninepatch) { - margins[0] = node_ninepatch->get_patch_margin(SIDE_TOP); - margins[1] = node_ninepatch->get_patch_margin(SIDE_BOTTOM); - margins[2] = node_ninepatch->get_patch_margin(SIDE_LEFT); - margins[3] = node_ninepatch->get_patch_margin(SIDE_RIGHT); - } else if (obj_styleBox.is_valid()) { - margins[0] = obj_styleBox->get_texture_margin(SIDE_TOP); - margins[1] = obj_styleBox->get_texture_margin(SIDE_BOTTOM); - margins[2] = obj_styleBox->get_texture_margin(SIDE_LEFT); - margins[3] = obj_styleBox->get_texture_margin(SIDE_RIGHT); - } - - Vector2 pos[4] = { - mtx.basis_xform(rect.position + Vector2(0, margins[0])) - draw_ofs * draw_zoom, - mtx.basis_xform(rect.position + rect.size - Vector2(0, margins[1])) - draw_ofs * draw_zoom, - mtx.basis_xform(rect.position + Vector2(margins[2], 0)) - draw_ofs * draw_zoom, - mtx.basis_xform(rect.position + rect.size - Vector2(margins[3], 0)) - draw_ofs * draw_zoom + // Check if we click on any handle first. + { + const real_t handle_radius = 16 * EDSCALE; + const real_t handle_offset = 8 * EDSCALE; + + // Position of selection handles. + const Vector2 endpoints[8] = { + mtx.xform(rect.position) + Vector2(-handle_offset, -handle_offset), + mtx.xform(rect.position + Vector2(rect.size.x / 2, 0)) + Vector2(0, -handle_offset), + mtx.xform(rect.position + Vector2(rect.size.x, 0)) + Vector2(handle_offset, -handle_offset), + mtx.xform(rect.position + Vector2(rect.size.x, rect.size.y / 2)) + Vector2(handle_offset, 0), + mtx.xform(rect.position + rect.size) + Vector2(handle_offset, handle_offset), + mtx.xform(rect.position + Vector2(rect.size.x / 2, rect.size.y)) + Vector2(0, handle_offset), + mtx.xform(rect.position + Vector2(0, rect.size.y)) + Vector2(-handle_offset, handle_offset), + mtx.xform(rect.position + Vector2(0, rect.size.y / 2)) + Vector2(-handle_offset, 0) }; - if (Math::abs(mb->get_position().y - pos[0].y) < 8) { - edited_margin = 0; - prev_margin = margins[0]; - } else if (Math::abs(mb->get_position().y - pos[1].y) < 8) { - edited_margin = 1; - prev_margin = margins[1]; - } else if (Math::abs(mb->get_position().x - pos[2].x) < 8) { - edited_margin = 2; - prev_margin = margins[2]; - } else if (Math::abs(mb->get_position().x - pos[3].x) < 8) { - edited_margin = 3; - prev_margin = margins[3]; - } - if (edited_margin >= 0) { - drag_from = mb->get_position(); - drag = true; - } - } - if (edited_margin < 0 && snap_mode == SNAP_AUTOSLICE) { - Vector2 point = mtx.affine_inverse().xform(mb->get_position()); - for (const Rect2 &E : autoslice_cache) { - if (E.has_point(point)) { - rect = E; - if (Input::get_singleton()->is_key_pressed(Key::CMD_OR_CTRL) && !(Input::get_singleton()->is_key_pressed(Key(Key::SHIFT | Key::ALT)))) { - Rect2 r; - if (atlas_tex.is_valid()) { - r = atlas_tex->get_region(); - } else if (node_sprite_2d) { - r = node_sprite_2d->get_region_rect(); - } else if (node_sprite_3d) { - r = node_sprite_3d->get_region_rect(); - } else if (node_ninepatch) { - r = node_ninepatch->get_region_rect(); - } else if (obj_styleBox.is_valid()) { - r = obj_styleBox->get_region_rect(); - } - rect.expand_to(r.position); - rect.expand_to(r.get_end()); - } - undo_redo->create_action(TTR("Set Region Rect")); - if (atlas_tex.is_valid()) { - undo_redo->add_do_method(atlas_tex.ptr(), "set_region", rect); - undo_redo->add_undo_method(atlas_tex.ptr(), "set_region", atlas_tex->get_region()); - } else if (node_sprite_2d) { - undo_redo->add_do_method(node_sprite_2d, "set_region_rect", rect); - undo_redo->add_undo_method(node_sprite_2d, "set_region_rect", node_sprite_2d->get_region_rect()); - } else if (node_sprite_3d) { - undo_redo->add_do_method(node_sprite_3d, "set_region_rect", rect); - undo_redo->add_undo_method(node_sprite_3d, "set_region_rect", node_sprite_3d->get_region_rect()); - } else if (node_ninepatch) { - undo_redo->add_do_method(node_ninepatch, "set_region_rect", rect); - undo_redo->add_undo_method(node_ninepatch, "set_region_rect", node_ninepatch->get_region_rect()); - } else if (obj_styleBox.is_valid()) { - undo_redo->add_do_method(obj_styleBox.ptr(), "set_region_rect", rect); - undo_redo->add_undo_method(obj_styleBox.ptr(), "set_region_rect", obj_styleBox->get_region_rect()); - } - undo_redo->add_do_method(this, "_update_rect"); - undo_redo->add_undo_method(this, "_update_rect"); - undo_redo->add_do_method(edit_draw, "queue_redraw"); - undo_redo->add_undo_method(edit_draw, "queue_redraw"); - undo_redo->commit_action(); - break; - } - } - } else if (edited_margin < 0) { + drag_from = mtx.affine_inverse().xform(mb->get_position()); if (snap_mode == SNAP_PIXEL) { drag_from = drag_from.snapped(Vector2(1, 1)); @@ -397,17 +318,8 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { drag_from = snap_point(drag_from); } drag = true; - if (atlas_tex.is_valid()) { - rect_prev = atlas_tex->get_region(); - } else if (node_sprite_2d) { - rect_prev = node_sprite_2d->get_region_rect(); - } else if (node_sprite_3d) { - rect_prev = node_sprite_3d->get_region_rect(); - } else if (node_ninepatch) { - rect_prev = node_ninepatch->get_region_rect(); - } else if (obj_styleBox.is_valid()) { - rect_prev = obj_styleBox->get_region_rect(); - } + + rect_prev = _get_edited_object_region(); for (int i = 0; i < 8; i++) { Vector2 tuv = endpoints[i]; @@ -415,10 +327,109 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { drag_index = i; } } + } + + // We didn't hit any handle, try other options. + if (drag_index < 0) { + if (node_ninepatch || res_stylebox.is_valid()) { + // For ninepatchable objects check if we are clicking on margin bars. + + edited_margin = -1; + float margins[4] = { 0 }; + if (node_ninepatch) { + margins[0] = node_ninepatch->get_patch_margin(SIDE_TOP); + margins[1] = node_ninepatch->get_patch_margin(SIDE_BOTTOM); + margins[2] = node_ninepatch->get_patch_margin(SIDE_LEFT); + margins[3] = node_ninepatch->get_patch_margin(SIDE_RIGHT); + } else if (res_stylebox.is_valid()) { + margins[0] = res_stylebox->get_texture_margin(SIDE_TOP); + margins[1] = res_stylebox->get_texture_margin(SIDE_BOTTOM); + margins[2] = res_stylebox->get_texture_margin(SIDE_LEFT); + margins[3] = res_stylebox->get_texture_margin(SIDE_RIGHT); + } - if (drag_index == -1) { - creating = true; - rect = Rect2(drag_from, Size2()); + Vector2 pos[4] = { + mtx.basis_xform(rect.position + Vector2(0, margins[0])) - draw_ofs * draw_zoom, + mtx.basis_xform(rect.position + rect.size - Vector2(0, margins[1])) - draw_ofs * draw_zoom, + mtx.basis_xform(rect.position + Vector2(margins[2], 0)) - draw_ofs * draw_zoom, + mtx.basis_xform(rect.position + rect.size - Vector2(margins[3], 0)) - draw_ofs * draw_zoom + }; + if (Math::abs(mb->get_position().y - pos[0].y) < 8) { + edited_margin = 0; + prev_margin = margins[0]; + } else if (Math::abs(mb->get_position().y - pos[1].y) < 8) { + edited_margin = 1; + prev_margin = margins[1]; + } else if (Math::abs(mb->get_position().x - pos[2].x) < 8) { + edited_margin = 2; + prev_margin = margins[2]; + } else if (Math::abs(mb->get_position().x - pos[3].x) < 8) { + edited_margin = 3; + prev_margin = margins[3]; + } + if (edited_margin >= 0) { + drag_from = mb->get_position(); + drag = true; + } + } + + if (edited_margin < 0 && snap_mode == SNAP_AUTOSLICE) { + // We didn't hit anything, but we're in the autoslice mode. Handle it. + + Vector2 point = mtx.affine_inverse().xform(mb->get_position()); + for (const Rect2 &E : autoslice_cache) { + if (E.has_point(point)) { + rect = E; + if (Input::get_singleton()->is_key_pressed(Key::CMD_OR_CTRL) && !(Input::get_singleton()->is_key_pressed(Key(Key::SHIFT | Key::ALT)))) { + Rect2 r; + if (node_sprite_2d) { + r = node_sprite_2d->get_region_rect(); + } else if (node_sprite_3d) { + r = node_sprite_3d->get_region_rect(); + } else if (node_ninepatch) { + r = node_ninepatch->get_region_rect(); + } else if (res_stylebox.is_valid()) { + r = res_stylebox->get_region_rect(); + } else if (res_atlas_texture.is_valid()) { + r = res_atlas_texture->get_region(); + } + rect.expand_to(r.position); + rect.expand_to(r.get_end()); + } + + undo_redo->create_action(TTR("Set Region Rect")); + if (node_sprite_2d) { + undo_redo->add_do_method(node_sprite_2d, "set_region_rect", rect); + undo_redo->add_undo_method(node_sprite_2d, "set_region_rect", node_sprite_2d->get_region_rect()); + } else if (node_sprite_3d) { + undo_redo->add_do_method(node_sprite_3d, "set_region_rect", rect); + undo_redo->add_undo_method(node_sprite_3d, "set_region_rect", node_sprite_3d->get_region_rect()); + } else if (node_ninepatch) { + undo_redo->add_do_method(node_ninepatch, "set_region_rect", rect); + undo_redo->add_undo_method(node_ninepatch, "set_region_rect", node_ninepatch->get_region_rect()); + } else if (res_stylebox.is_valid()) { + undo_redo->add_do_method(res_stylebox.ptr(), "set_region_rect", rect); + undo_redo->add_undo_method(res_stylebox.ptr(), "set_region_rect", res_stylebox->get_region_rect()); + } else if (res_atlas_texture.is_valid()) { + undo_redo->add_do_method(res_atlas_texture.ptr(), "set_region", rect); + undo_redo->add_undo_method(res_atlas_texture.ptr(), "set_region", res_atlas_texture->get_region()); + } + + undo_redo->add_do_method(this, "_update_rect"); + undo_redo->add_undo_method(this, "_update_rect"); + undo_redo->add_do_method(texture_overlay, "queue_redraw"); + undo_redo->add_undo_method(texture_overlay, "queue_redraw"); + undo_redo->commit_action(); + break; + } + } + } else if (edited_margin < 0) { + // We didn't hit anything and it's not autoslice, which means we try to create a new region. + + if (drag_index == -1) { + creating = true; + rect = Rect2(drag_from, Size2()); + } } } @@ -429,18 +440,15 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { if (node_ninepatch) { undo_redo->add_do_method(node_ninepatch, "set_patch_margin", side[edited_margin], node_ninepatch->get_patch_margin(side[edited_margin])); undo_redo->add_undo_method(node_ninepatch, "set_patch_margin", side[edited_margin], prev_margin); - } else if (obj_styleBox.is_valid()) { - undo_redo->add_do_method(obj_styleBox.ptr(), "set_texture_margin", side[edited_margin], obj_styleBox->get_texture_margin(side[edited_margin])); - undo_redo->add_undo_method(obj_styleBox.ptr(), "set_texture_margin", side[edited_margin], prev_margin); - obj_styleBox->emit_changed(); + } else if (res_stylebox.is_valid()) { + undo_redo->add_do_method(res_stylebox.ptr(), "set_texture_margin", side[edited_margin], res_stylebox->get_texture_margin(side[edited_margin])); + undo_redo->add_undo_method(res_stylebox.ptr(), "set_texture_margin", side[edited_margin], prev_margin); + res_stylebox->emit_changed(); } edited_margin = -1; } else { undo_redo->create_action(TTR("Set Region Rect")); - if (atlas_tex.is_valid()) { - undo_redo->add_do_method(atlas_tex.ptr(), "set_region", atlas_tex->get_region()); - undo_redo->add_undo_method(atlas_tex.ptr(), "set_region", rect_prev); - } else if (node_sprite_2d) { + if (node_sprite_2d) { undo_redo->add_do_method(node_sprite_2d, "set_region_rect", node_sprite_2d->get_region_rect()); undo_redo->add_undo_method(node_sprite_2d, "set_region_rect", rect_prev); } else if (node_sprite_3d) { @@ -449,16 +457,19 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { } else if (node_ninepatch) { undo_redo->add_do_method(node_ninepatch, "set_region_rect", node_ninepatch->get_region_rect()); undo_redo->add_undo_method(node_ninepatch, "set_region_rect", rect_prev); - } else if (obj_styleBox.is_valid()) { - undo_redo->add_do_method(obj_styleBox.ptr(), "set_region_rect", obj_styleBox->get_region_rect()); - undo_redo->add_undo_method(obj_styleBox.ptr(), "set_region_rect", rect_prev); + } else if (res_stylebox.is_valid()) { + undo_redo->add_do_method(res_stylebox.ptr(), "set_region_rect", res_stylebox->get_region_rect()); + undo_redo->add_undo_method(res_stylebox.ptr(), "set_region_rect", rect_prev); + } else if (res_atlas_texture.is_valid()) { + undo_redo->add_do_method(res_atlas_texture.ptr(), "set_region", res_atlas_texture->get_region()); + undo_redo->add_undo_method(res_atlas_texture.ptr(), "set_region", rect_prev); } drag_index = -1; } undo_redo->add_do_method(this, "_update_rect"); undo_redo->add_undo_method(this, "_update_rect"); - undo_redo->add_do_method(edit_draw, "queue_redraw"); - undo_redo->add_undo_method(edit_draw, "queue_redraw"); + undo_redo->add_do_method(texture_overlay, "queue_redraw"); + undo_redo->add_undo_method(texture_overlay, "queue_redraw"); undo_redo->commit_action(); drag = false; creating = false; @@ -472,14 +483,15 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { if (node_ninepatch) { node_ninepatch->set_patch_margin(side[edited_margin], prev_margin); } - if (obj_styleBox.is_valid()) { - obj_styleBox->set_texture_margin(side[edited_margin], prev_margin); + if (res_stylebox.is_valid()) { + res_stylebox->set_texture_margin(side[edited_margin], prev_margin); } edited_margin = -1; } else { - apply_rect(rect_prev); + _apply_rect(rect_prev); rect = rect_prev; - edit_draw->queue_redraw(); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); drag_index = -1; } } @@ -533,8 +545,8 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { if (node_ninepatch) { node_ninepatch->set_patch_margin(side[edited_margin], new_margin); } - if (obj_styleBox.is_valid()) { - obj_styleBox->set_texture_margin(side[edited_margin], new_margin); + if (res_stylebox.is_valid()) { + res_stylebox->set_texture_margin(side[edited_margin], new_margin); } } else { Vector2 new_pos = mtx.affine_inverse().xform(mm->get_position()); @@ -547,8 +559,9 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { if (creating) { rect = Rect2(drag_from, Size2()); rect.expand_to(new_pos); - apply_rect(rect); - edit_draw->queue_redraw(); + _apply_rect(rect); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); return; } @@ -557,53 +570,54 @@ void TextureRegionEditor::_region_input(const Ref<InputEvent> &p_input) { Vector2 p = rect_prev.get_end(); rect = Rect2(p, Size2()); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 1: { Vector2 p = rect_prev.position + Vector2(0, rect_prev.size.y); rect = Rect2(p, Size2(rect_prev.size.x, 0)); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 2: { Vector2 p = rect_prev.position + Vector2(0, rect_prev.size.y); rect = Rect2(p, Size2()); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 3: { Vector2 p = rect_prev.position; rect = Rect2(p, Size2(0, rect_prev.size.y)); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 4: { Vector2 p = rect_prev.position; rect = Rect2(p, Size2()); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 5: { Vector2 p = rect_prev.position; rect = Rect2(p, Size2(rect_prev.size.x, 0)); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 6: { Vector2 p = rect_prev.position + Vector2(rect_prev.size.x, 0); rect = Rect2(p, Size2()); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; case 7: { Vector2 p = rect_prev.position + Vector2(rect_prev.size.x, 0); rect = Rect2(p, Size2(0, rect_prev.size.y)); rect.expand_to(new_pos); - apply_rect(rect); + _apply_rect(rect); } break; } } - edit_draw->queue_redraw(); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); } } @@ -636,53 +650,50 @@ void TextureRegionEditor::_scroll_changed(float) { draw_ofs.x = hscroll->get_value(); draw_ofs.y = vscroll->get_value(); - edit_draw->queue_redraw(); + + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_mode(int p_mode) { - snap_mode = p_mode; - - if (snap_mode == SNAP_GRID) { - hb_grid->show(); - } else { - hb_grid->hide(); - } + snap_mode = (SnapMode)p_mode; + hb_grid->set_visible(snap_mode == SNAP_GRID); if (snap_mode == SNAP_AUTOSLICE && is_visible() && autoslice_is_dirty) { _update_autoslice(); } - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_off_x(float p_val) { snap_offset.x = p_val; - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_off_y(float p_val) { snap_offset.y = p_val; - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_step_x(float p_val) { snap_step.x = p_val; - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_step_y(float p_val) { snap_step.y = p_val; - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_sep_x(float p_val) { snap_separation.x = p_val; - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_set_snap_sep_y(float p_val) { snap_separation.y = p_val; - edit_draw->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_zoom_on_position(float p_zoom, Point2 p_position) { @@ -696,79 +707,52 @@ void TextureRegionEditor::_zoom_on_position(float p_zoom, Point2 p_position) { ofs = ofs / prev_zoom - ofs / draw_zoom; draw_ofs = (draw_ofs + ofs).round(); - edit_draw->queue_redraw(); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); } void TextureRegionEditor::_zoom_in() { - _zoom_on_position(draw_zoom * 1.5, edit_draw->get_size() / 2.0); + _zoom_on_position(draw_zoom * 1.5, texture_overlay->get_size() / 2.0); } void TextureRegionEditor::_zoom_reset() { - _zoom_on_position(1.0, edit_draw->get_size() / 2.0); + _zoom_on_position(1.0, texture_overlay->get_size() / 2.0); } void TextureRegionEditor::_zoom_out() { - _zoom_on_position(draw_zoom / 1.5, edit_draw->get_size() / 2.0); + _zoom_on_position(draw_zoom / 1.5, texture_overlay->get_size() / 2.0); } -void TextureRegionEditor::apply_rect(const Rect2 &p_rect) { - if (atlas_tex.is_valid()) { - atlas_tex->set_region(p_rect); - } else if (node_sprite_2d) { +void TextureRegionEditor::_apply_rect(const Rect2 &p_rect) { + if (node_sprite_2d) { node_sprite_2d->set_region_rect(p_rect); } else if (node_sprite_3d) { node_sprite_3d->set_region_rect(p_rect); } else if (node_ninepatch) { node_ninepatch->set_region_rect(p_rect); - } else if (obj_styleBox.is_valid()) { - obj_styleBox->set_region_rect(p_rect); + } else if (res_stylebox.is_valid()) { + res_stylebox->set_region_rect(p_rect); + } else if (res_atlas_texture.is_valid()) { + res_atlas_texture->set_region(p_rect); } } void TextureRegionEditor::_update_rect() { - if (atlas_tex.is_valid()) { - rect = atlas_tex->get_region(); - } else if (node_sprite_2d) { - rect = node_sprite_2d->get_region_rect(); - } else if (node_sprite_3d) { - rect = node_sprite_3d->get_region_rect(); - } else if (node_ninepatch) { - rect = node_ninepatch->get_region_rect(); - if (rect == Rect2()) { - rect = Rect2(Vector2(), node_ninepatch->get_texture()->get_size()); - } - } else if (obj_styleBox.is_valid()) { - rect = obj_styleBox->get_region_rect(); - if (rect == Rect2()) { - rect = Rect2(Vector2(), obj_styleBox->get_texture()->get_size()); - } - } + rect = _get_edited_object_region(); } void TextureRegionEditor::_update_autoslice() { autoslice_is_dirty = false; autoslice_cache.clear(); - Ref<Texture2D> texture = nullptr; - if (atlas_tex.is_valid()) { - texture = atlas_tex->get_atlas(); - } else if (node_sprite_2d) { - texture = node_sprite_2d->get_texture(); - } else if (node_sprite_3d) { - texture = node_sprite_3d->get_texture(); - } else if (node_ninepatch) { - texture = node_ninepatch->get_texture(); - } else if (obj_styleBox.is_valid()) { - texture = obj_styleBox->get_texture(); - } - - if (texture.is_null()) { + Ref<Texture2D> object_texture = _get_edited_object_texture(); + if (object_texture.is_null()) { return; } - for (int y = 0; y < texture->get_height(); y++) { - for (int x = 0; x < texture->get_width(); x++) { - if (texture->is_pixel_opaque(x, y)) { + for (int y = 0; y < object_texture->get_height(); y++) { + for (int x = 0; x < object_texture->get_width(); x++) { + if (object_texture->is_pixel_opaque(x, y)) { bool found = false; for (Rect2 &E : autoslice_cache) { Rect2 grown = E.grow(1.5); @@ -813,34 +797,37 @@ void TextureRegionEditor::_update_autoslice() { } } } - cache_map[texture->get_rid()] = autoslice_cache; + cache_map[object_texture->get_rid()] = autoslice_cache; } void TextureRegionEditor::_notification(int p_what) { switch (p_what) { - case NOTIFICATION_EXIT_TREE: { - get_tree()->disconnect("node_removed", callable_mp(this, &TextureRegionEditor::_node_removed)); + case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { + panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/sub_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning"))); } break; case NOTIFICATION_ENTER_TREE: { get_tree()->connect("node_removed", callable_mp(this, &TextureRegionEditor::_node_removed)); - [[fallthrough]]; - } - case NOTIFICATION_THEME_CHANGED: { - edit_draw->add_theme_style_override("panel", get_theme_stylebox(SNAME("panel"), SNAME("Tree"))); + + panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/sub_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning"))); + + hb_grid->set_visible(snap_mode == SNAP_GRID); + if (snap_mode == SNAP_AUTOSLICE && is_visible() && autoslice_is_dirty) { + _update_autoslice(); + } } break; - case NOTIFICATION_READY: { + case NOTIFICATION_EXIT_TREE: { + get_tree()->disconnect("node_removed", callable_mp(this, &TextureRegionEditor::_node_removed)); + } break; + + case NOTIFICATION_THEME_CHANGED: { + texture_preview->add_theme_style_override("panel", get_theme_stylebox(SNAME("TextureRegionPreviewBG"), SNAME("EditorStyles"))); + texture_overlay->add_theme_style_override("panel", get_theme_stylebox(SNAME("TextureRegionPreviewFG"), SNAME("EditorStyles"))); + zoom_out->set_icon(get_theme_icon(SNAME("ZoomLess"), SNAME("EditorIcons"))); zoom_reset->set_icon(get_theme_icon(SNAME("ZoomReset"), SNAME("EditorIcons"))); zoom_in->set_icon(get_theme_icon(SNAME("ZoomMore"), SNAME("EditorIcons"))); - - vscroll->set_anchors_and_offsets_preset(Control::PRESET_RIGHT_WIDE); - hscroll->set_anchors_and_offsets_preset(Control::PRESET_BOTTOM_WIDE); - [[fallthrough]]; - } - case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { - panner->setup((ViewPanner::ControlScheme)EDITOR_GET("editors/panning/sub_editors_panning_scheme").operator int(), ED_GET_SHORTCUT("canvas_item_editor/pan_view"), bool(EDITOR_GET("editors/panning/simple_panning"))); } break; case NOTIFICATION_VISIBILITY_CHANGED: { @@ -864,41 +851,19 @@ void TextureRegionEditor::_notification(int p_what) { } } -void TextureRegionEditor::_node_removed(Object *p_obj) { - if (p_obj == node_sprite_2d || p_obj == node_sprite_3d || p_obj == node_ninepatch || p_obj == obj_styleBox.ptr() || p_obj == atlas_tex.ptr()) { - node_sprite_2d = nullptr; - node_sprite_3d = nullptr; - node_ninepatch = nullptr; - obj_styleBox = Ref<StyleBox>(nullptr); - atlas_tex = Ref<AtlasTexture>(nullptr); +void TextureRegionEditor::_node_removed(Node *p_node) { + if (p_node == node_sprite_2d || p_node == node_sprite_3d || p_node == node_ninepatch) { + _clear_edited_object(); hide(); } } -void TextureRegionEditor::_bind_methods() { - ClassDB::bind_method(D_METHOD("_edit_region"), &TextureRegionEditor::_edit_region); - ClassDB::bind_method(D_METHOD("_zoom_on_position"), &TextureRegionEditor::_zoom_on_position); - ClassDB::bind_method(D_METHOD("_update_rect"), &TextureRegionEditor::_update_rect); -} - -bool TextureRegionEditor::is_stylebox() { - return obj_styleBox.is_valid(); -} - -bool TextureRegionEditor::is_atlas_texture() { - return atlas_tex.is_valid(); -} - -bool TextureRegionEditor::is_ninepatch() { - return node_ninepatch != nullptr; -} - -Sprite2D *TextureRegionEditor::get_sprite_2d() { - return node_sprite_2d; -} - -Sprite3D *TextureRegionEditor::get_sprite_3d() { - return node_sprite_3d; +void TextureRegionEditor::_clear_edited_object() { + node_sprite_2d = nullptr; + node_sprite_3d = nullptr; + node_ninepatch = nullptr; + res_stylebox = Ref<StyleBoxTexture>(); + res_atlas_texture = Ref<AtlasTexture>(); } void TextureRegionEditor::edit(Object *p_obj) { @@ -911,18 +876,14 @@ void TextureRegionEditor::edit(Object *p_obj) { if (node_ninepatch) { node_ninepatch->disconnect("texture_changed", callable_mp(this, &TextureRegionEditor::_texture_changed)); } - if (obj_styleBox.is_valid()) { - obj_styleBox->disconnect_changed(callable_mp(this, &TextureRegionEditor::_texture_changed)); + if (res_stylebox.is_valid()) { + res_stylebox->disconnect_changed(callable_mp(this, &TextureRegionEditor::_texture_changed)); } - if (atlas_tex.is_valid()) { - atlas_tex->disconnect_changed(callable_mp(this, &TextureRegionEditor::_texture_changed)); + if (res_atlas_texture.is_valid()) { + res_atlas_texture->disconnect_changed(callable_mp(this, &TextureRegionEditor::_texture_changed)); } - node_sprite_2d = nullptr; - node_sprite_3d = nullptr; - node_ninepatch = nullptr; - obj_styleBox = Ref<StyleBoxTexture>(nullptr); - atlas_tex = Ref<AtlasTexture>(nullptr); + _clear_edited_object(); if (p_obj) { node_sprite_2d = Object::cast_to<Sprite2D>(p_obj); @@ -931,11 +892,11 @@ void TextureRegionEditor::edit(Object *p_obj) { bool is_resource = false; if (Object::cast_to<StyleBoxTexture>(p_obj)) { - obj_styleBox = Ref<StyleBoxTexture>(Object::cast_to<StyleBoxTexture>(p_obj)); + res_stylebox = Ref<StyleBoxTexture>(p_obj); is_resource = true; } if (Object::cast_to<AtlasTexture>(p_obj)) { - atlas_tex = Ref<AtlasTexture>(Object::cast_to<AtlasTexture>(p_obj)); + res_atlas_texture = Ref<AtlasTexture>(p_obj); is_resource = true; } @@ -947,11 +908,54 @@ void TextureRegionEditor::edit(Object *p_obj) { _edit_region(); } - edit_draw->queue_redraw(); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); popup_centered_ratio(0.5); request_center = true; } +Ref<Texture2D> TextureRegionEditor::_get_edited_object_texture() const { + if (node_sprite_2d) { + return node_sprite_2d->get_texture(); + } + if (node_sprite_3d) { + return node_sprite_3d->get_texture(); + } + if (node_ninepatch) { + return node_ninepatch->get_texture(); + } + if (res_stylebox.is_valid()) { + return res_stylebox->get_texture(); + } + if (res_atlas_texture.is_valid()) { + return res_atlas_texture->get_atlas(); + } + + return Ref<Texture2D>(); +} + +Rect2 TextureRegionEditor::_get_edited_object_region() const { + Rect2 region; + + if (node_sprite_2d) { + region = node_sprite_2d->get_region_rect(); + } else if (node_sprite_3d) { + region = node_sprite_3d->get_region_rect(); + } else if (node_ninepatch) { + region = node_ninepatch->get_region_rect(); + } else if (res_stylebox.is_valid()) { + region = res_stylebox->get_region_rect(); + } else if (res_atlas_texture.is_valid()) { + region = res_atlas_texture->get_region(); + } + + if (region == Rect2()) { + region = Rect2(Vector2(), _get_edited_object_texture()->get_size()); + } + + return region; +} + void TextureRegionEditor::_texture_changed() { if (!is_visible()) { return; @@ -960,17 +964,20 @@ void TextureRegionEditor::_texture_changed() { } void TextureRegionEditor::_edit_region() { - CanvasItem::TextureFilter filter = CanvasItem::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS; + Ref<Texture2D> object_texture = _get_edited_object_texture(); + if (object_texture.is_null()) { + _zoom_reset(); + hscroll->hide(); + vscroll->hide(); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); + return; + } - Ref<Texture2D> texture = nullptr; - if (atlas_tex.is_valid()) { - texture = atlas_tex->get_atlas(); - } else if (node_sprite_2d) { - texture = node_sprite_2d->get_texture(); + CanvasItem::TextureFilter filter = CanvasItem::TEXTURE_FILTER_NEAREST_WITH_MIPMAPS; + if (node_sprite_2d) { filter = node_sprite_2d->get_texture_filter_in_tree(); } else if (node_sprite_3d) { - texture = node_sprite_3d->get_texture(); - StandardMaterial3D::TextureFilter filter_3d = node_sprite_3d->get_texture_filter(); switch (filter_3d) { @@ -998,10 +1005,7 @@ void TextureRegionEditor::_edit_region() { break; } } else if (node_ninepatch) { - texture = node_ninepatch->get_texture(); filter = node_ninepatch->get_texture_filter_in_tree(); - } else if (obj_styleBox.is_valid()) { - texture = obj_styleBox->get_texture(); } // occurs when get_texture_filter_in_tree reaches the scene root @@ -1032,20 +1036,11 @@ void TextureRegionEditor::_edit_region() { } } - if (texture.is_null()) { - preview_tex->set_diffuse_texture(nullptr); - _zoom_reset(); - hscroll->hide(); - vscroll->hide(); - edit_draw->queue_redraw(); - return; - } - - preview_tex->set_texture_filter(filter); - preview_tex->set_diffuse_texture(texture); + texture_preview->set_texture_filter(filter); + texture_preview->set_texture_repeat(CanvasItem::TEXTURE_REPEAT_DISABLED); - if (cache_map.has(texture->get_rid())) { - autoslice_cache = cache_map[texture->get_rid()]; + if (cache_map.has(object_texture->get_rid())) { + autoslice_cache = cache_map[object_texture->get_rid()]; autoslice_is_dirty = false; } else { if (is_visible() && snap_mode == SNAP_AUTOSLICE) { @@ -1056,7 +1051,8 @@ void TextureRegionEditor::_edit_region() { } _update_rect(); - edit_draw->queue_redraw(); + texture_preview->queue_redraw(); + texture_overlay->queue_redraw(); } Vector2 TextureRegionEditor::snap_point(Vector2 p_target) const { @@ -1068,25 +1064,24 @@ Vector2 TextureRegionEditor::snap_point(Vector2 p_target) const { return p_target; } +void TextureRegionEditor::_bind_methods() { + ClassDB::bind_method(D_METHOD("_update_rect"), &TextureRegionEditor::_update_rect); +} + TextureRegionEditor::TextureRegionEditor() { + set_title(TTR("Region Editor")); set_ok_button_text(TTR("Close")); - VBoxContainer *vb = memnew(VBoxContainer); - add_child(vb); - node_sprite_2d = nullptr; - node_sprite_3d = nullptr; - node_ninepatch = nullptr; - obj_styleBox = Ref<StyleBoxTexture>(nullptr); - atlas_tex = Ref<AtlasTexture>(nullptr); - - preview_tex = Ref<CanvasTexture>(memnew(CanvasTexture)); // A power-of-two value works better as a default grid size. snap_step = EditorSettings::get_singleton()->get_project_metadata("texture_region_editor", "snap_step", Vector2(8, 8)); snap_separation = EditorSettings::get_singleton()->get_project_metadata("texture_region_editor", "snap_separation", Vector2()); - snap_mode = EditorSettings::get_singleton()->get_project_metadata("texture_region_editor", "snap_mode", SNAP_NONE); - edited_margin = -1; - drag_index = -1; - drag = false; + snap_mode = (SnapMode)(int)EditorSettings::get_singleton()->get_project_metadata("texture_region_editor", "snap_mode", SNAP_NONE); + + panner.instantiate(); + panner->set_callbacks(callable_mp(this, &TextureRegionEditor::_pan_callback), callable_mp(this, &TextureRegionEditor::_zoom_callback)); + + VBoxContainer *vb = memnew(VBoxContainer); + add_child(vb); HBoxContainer *hb_tools = memnew(HBoxContainer); vb->add_child(hb_tools); @@ -1169,22 +1164,21 @@ TextureRegionEditor::TextureRegionEditor() { hb_grid->hide(); - panner.instantiate(); - panner->set_callbacks(callable_mp(this, &TextureRegionEditor::_pan_callback), callable_mp(this, &TextureRegionEditor::_zoom_callback)); - - edit_draw = memnew(Panel); - vb->add_child(edit_draw); - edit_draw->set_v_size_flags(Control::SIZE_EXPAND_FILL); - edit_draw->connect("draw", callable_mp(this, &TextureRegionEditor::_region_draw)); - edit_draw->connect("gui_input", callable_mp(this, &TextureRegionEditor::_region_input)); - edit_draw->connect("focus_exited", callable_mp(panner.ptr(), &ViewPanner::release_pan_key)); - edit_draw->set_focus_mode(Control::FOCUS_CLICK); + texture_preview = memnew(PanelContainer); + vb->add_child(texture_preview); + texture_preview->set_v_size_flags(Control::SIZE_EXPAND_FILL); + texture_preview->set_clip_contents(true); + texture_preview->connect("draw", callable_mp(this, &TextureRegionEditor::_texture_preview_draw)); - draw_zoom = 1.0; - edit_draw->set_clip_contents(true); + texture_overlay = memnew(Panel); + texture_preview->add_child(texture_overlay); + texture_overlay->set_focus_mode(Control::FOCUS_CLICK); + texture_overlay->connect("draw", callable_mp(this, &TextureRegionEditor::_texture_overlay_draw)); + texture_overlay->connect("gui_input", callable_mp(this, &TextureRegionEditor::_texture_overlay_input)); + texture_overlay->connect("focus_exited", callable_mp(panner.ptr(), &ViewPanner::release_pan_key)); HBoxContainer *zoom_hb = memnew(HBoxContainer); - edit_draw->add_child(zoom_hb); + texture_overlay->add_child(zoom_hb); zoom_hb->set_begin(Point2(5, 5)); zoom_out = memnew(Button); @@ -1206,18 +1200,16 @@ TextureRegionEditor::TextureRegionEditor() { zoom_hb->add_child(zoom_in); vscroll = memnew(VScrollBar); + vscroll->set_anchors_and_offsets_preset(Control::PRESET_RIGHT_WIDE); vscroll->set_step(0.001); - edit_draw->add_child(vscroll); vscroll->connect("value_changed", callable_mp(this, &TextureRegionEditor::_scroll_changed)); + texture_overlay->add_child(vscroll); + hscroll = memnew(HScrollBar); + hscroll->set_anchors_and_offsets_preset(Control::PRESET_BOTTOM_WIDE); hscroll->set_step(0.001); - edit_draw->add_child(hscroll); hscroll->connect("value_changed", callable_mp(this, &TextureRegionEditor::_scroll_changed)); - - updating_scroll = false; - autoslice_is_dirty = true; - - set_title(TTR("Region Editor")); + texture_overlay->add_child(hscroll); } //////////////////////// diff --git a/editor/plugins/texture_region_editor_plugin.h b/editor/plugins/texture_region_editor_plugin.h index 6b7a198246..eeae9dc205 100644 --- a/editor/plugins/texture_region_editor_plugin.h +++ b/editor/plugins/texture_region_editor_plugin.h @@ -42,6 +42,7 @@ class AtlasTexture; class OptionButton; +class PanelContainer; class ViewPanner; class TextureRegionEditor : public AcceptDialog { @@ -66,16 +67,18 @@ class TextureRegionEditor : public AcceptDialog { SpinBox *sb_off_x = nullptr; SpinBox *sb_sep_y = nullptr; SpinBox *sb_sep_x = nullptr; - Panel *edit_draw = nullptr; + + PanelContainer *texture_preview = nullptr; + Panel *texture_overlay = nullptr; VScrollBar *vscroll = nullptr; HScrollBar *hscroll = nullptr; Vector2 draw_ofs; - float draw_zoom = 0.0; + float draw_zoom = 1.0; bool updating_scroll = false; - int snap_mode = 0; + SnapMode snap_mode = SNAP_NONE; Vector2 snap_offset; Vector2 snap_step; Vector2 snap_separation; @@ -83,28 +86,28 @@ class TextureRegionEditor : public AcceptDialog { Sprite2D *node_sprite_2d = nullptr; Sprite3D *node_sprite_3d = nullptr; NinePatchRect *node_ninepatch = nullptr; - Ref<StyleBoxTexture> obj_styleBox; - Ref<AtlasTexture> atlas_tex; - - Ref<CanvasTexture> preview_tex; + Ref<StyleBoxTexture> res_stylebox; + Ref<AtlasTexture> res_atlas_texture; Rect2 rect; Rect2 rect_prev; float prev_margin = 0.0f; - int edited_margin = 0; + int edited_margin = -1; HashMap<RID, List<Rect2>> cache_map; List<Rect2> autoslice_cache; - bool autoslice_is_dirty = false; + bool autoslice_is_dirty = true; bool drag = false; bool creating = false; Vector2 drag_from; - int drag_index = 0; + int drag_index = -1; bool request_center = false; Ref<ViewPanner> panner; void _pan_callback(Vector2 p_scroll_vec, Ref<InputEvent> p_event); void _zoom_callback(float p_zoom_factor, Vector2 p_origin, Ref<InputEvent> p_event); + void _scroll_changed(float); + Transform2D _get_offset_transform() const; void _set_snap_mode(int p_mode); void _set_snap_off_x(float p_val); @@ -113,35 +116,39 @@ class TextureRegionEditor : public AcceptDialog { void _set_snap_step_y(float p_val); void _set_snap_sep_x(float p_val); void _set_snap_sep_y(float p_val); + void _zoom_on_position(float p_zoom, Point2 p_position = Point2()); void _zoom_in(); void _zoom_reset(); void _zoom_out(); - void apply_rect(const Rect2 &p_rect); + + void _apply_rect(const Rect2 &p_rect); void _update_rect(); void _update_autoslice(); + Ref<Texture2D> _get_edited_object_texture() const; + Rect2 _get_edited_object_region() const; void _texture_changed(); + void _node_removed(Node *p_node); + + void _edit_region(); + void _clear_edited_object(); + + void _draw_margin_line(Vector2 p_from, Vector2 p_to); protected: void _notification(int p_what); - void _node_removed(Object *p_obj); static void _bind_methods(); + void _texture_preview_draw(); + void _texture_overlay_draw(); + void _texture_overlay_input(const Ref<InputEvent> &p_input); + Vector2 snap_point(Vector2 p_target) const; public: - void _edit_region(); - void _region_draw(); - void _region_input(const Ref<InputEvent> &p_input); - void _scroll_changed(float); - bool is_stylebox(); - bool is_atlas_texture(); - bool is_ninepatch(); - Sprite2D *get_sprite_2d(); - Sprite3D *get_sprite_3d(); - void edit(Object *p_obj); + TextureRegionEditor(); }; diff --git a/editor/plugins/tiles/tile_map_editor.cpp b/editor/plugins/tiles/tile_map_editor.cpp index 5815c85718..6e1841090b 100644 --- a/editor/plugins/tiles/tile_map_editor.cpp +++ b/editor/plugins/tiles/tile_map_editor.cpp @@ -4123,7 +4123,7 @@ TileMapEditor::TileMapEditor() { _tab_changed(0); // Registers UndoRedo inspector callback. - EditorNode::get_singleton()->get_editor_data().add_move_array_element_function(SNAME("TileMap"), callable_mp(this, &TileMapEditor::_move_tile_map_array_element)); + EditorNode::get_editor_data().add_move_array_element_function(SNAME("TileMap"), callable_mp(this, &TileMapEditor::_move_tile_map_array_element)); } TileMapEditor::~TileMapEditor() { diff --git a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp index b1111be006..8836eac936 100644 --- a/editor/plugins/tiles/tile_set_atlas_source_editor.cpp +++ b/editor/plugins/tiles/tile_set_atlas_source_editor.cpp @@ -111,7 +111,7 @@ void TileSetAtlasSourceEditor::TileSetAtlasSourceProxyObject::_get_property_list p_list->push_back(PropertyInfo(Variant::STRING, PNAME("name"))); p_list->push_back(PropertyInfo(Variant::OBJECT, PNAME("texture"), PROPERTY_HINT_RESOURCE_TYPE, "Texture2D")); p_list->push_back(PropertyInfo(Variant::VECTOR2I, PNAME("margins"), PROPERTY_HINT_NONE, "suffix:px")); - p_list->push_back(PropertyInfo(Variant::VECTOR2I, PNAME("separation"))); + p_list->push_back(PropertyInfo(Variant::VECTOR2I, PNAME("separation"), PROPERTY_HINT_NONE, "suffix:px")); p_list->push_back(PropertyInfo(Variant::VECTOR2I, PNAME("texture_region_size"), PROPERTY_HINT_NONE, "suffix:px")); p_list->push_back(PropertyInfo(Variant::BOOL, PNAME("use_texture_padding"))); } @@ -990,7 +990,6 @@ void TileSetAtlasSourceEditor::_update_atlas_view() { // Create and position the button. Button *button = memnew(Button); - alternative_tiles_control->add_child(button); button->set_flat(true); button->set_icon(get_theme_icon(SNAME("Add"), SNAME("EditorIcons"))); button->add_theme_style_override("normal", memnew(StyleBoxEmpty)); @@ -1000,6 +999,7 @@ void TileSetAtlasSourceEditor::_update_atlas_view() { button->connect("pressed", callable_mp(tile_set_atlas_source, &TileSetAtlasSource::create_alternative_tile).bind(tile_id, TileSetSource::INVALID_TILE_ALTERNATIVE)); button->set_rect(Rect2(Vector2(pos.x, pos.y + (y_increment - texture_region_base_size.y) / 2.0), Vector2(texture_region_base_size_min, texture_region_base_size_min))); button->set_expand_icon(true); + alternative_tiles_control->add_child(button); pos.y += y_increment; } @@ -2635,7 +2635,7 @@ TileSetAtlasSourceEditor::TileSetAtlasSourceEditor() { tile_atlas_view->add_control_over_alternative_tiles(alternative_tiles_control_unscaled, false); alternative_tiles_control_unscaled->set_mouse_filter(Control::MOUSE_FILTER_IGNORE); - EditorNode::get_singleton()->get_editor_data().add_undo_redo_inspector_hook_callback(callable_mp(this, &TileSetAtlasSourceEditor::_undo_redo_inspector_callback)); + EditorNode::get_editor_data().add_undo_redo_inspector_hook_callback(callable_mp(this, &TileSetAtlasSourceEditor::_undo_redo_inspector_callback)); // -- Dialogs -- confirm_auto_create_tiles = memnew(AcceptDialog); diff --git a/editor/plugins/tiles/tile_set_editor.cpp b/editor/plugins/tiles/tile_set_editor.cpp index afff905f97..3aace96b5e 100644 --- a/editor/plugins/tiles/tile_set_editor.cpp +++ b/editor/plugins/tiles/tile_set_editor.cpp @@ -963,8 +963,8 @@ TileSetEditor::TileSetEditor() { expanded_area->hide(); // Registers UndoRedo inspector callback. - EditorNode::get_singleton()->get_editor_data().add_move_array_element_function(SNAME("TileSet"), callable_mp(this, &TileSetEditor::_move_tile_set_array_element)); - EditorNode::get_singleton()->get_editor_data().add_undo_redo_inspector_hook_callback(callable_mp(this, &TileSetEditor::_undo_redo_inspector_callback)); + EditorNode::get_editor_data().add_move_array_element_function(SNAME("TileSet"), callable_mp(this, &TileSetEditor::_move_tile_set_array_element)); + EditorNode::get_editor_data().add_undo_redo_inspector_hook_callback(callable_mp(this, &TileSetEditor::_undo_redo_inspector_callback)); } void TileSourceInspectorPlugin::_show_id_edit_dialog(Object *p_for_source) { diff --git a/editor/plugins/version_control_editor_plugin.cpp b/editor/plugins/version_control_editor_plugin.cpp index 89f1f86461..a4ff9143f2 100644 --- a/editor/plugins/version_control_editor_plugin.cpp +++ b/editor/plugins/version_control_editor_plugin.cpp @@ -458,7 +458,7 @@ void VersionControlEditorPlugin::_force_push() { } void VersionControlEditorPlugin::_update_opened_tabs() { - Vector<EditorData::EditedScene> open_scenes = EditorNode::get_singleton()->get_editor_data().get_edited_scenes(); + Vector<EditorData::EditedScene> open_scenes = EditorNode::get_editor_data().get_edited_scenes(); for (int i = 0; i < open_scenes.size(); i++) { if (open_scenes[i].root == NULL) { continue; diff --git a/editor/plugins/visual_shader_editor_plugin.cpp b/editor/plugins/visual_shader_editor_plugin.cpp index 76f19d2dff..330a9a36eb 100644 --- a/editor/plugins/visual_shader_editor_plugin.cpp +++ b/editor/plugins/visual_shader_editor_plugin.cpp @@ -6544,7 +6544,7 @@ void EditorPropertyVisualShaderMode::_option_selected(int p_which) { return; } - ShaderEditorPlugin *shader_editor = Object::cast_to<ShaderEditorPlugin>(EditorNode::get_singleton()->get_editor_data().get_editor("Shader")); + ShaderEditorPlugin *shader_editor = Object::cast_to<ShaderEditorPlugin>(EditorNode::get_editor_data().get_editor_by_name("Shader")); if (!shader_editor) { return; } diff --git a/editor/rename_dialog.cpp b/editor/rename_dialog.cpp index 39affdd9f8..9d3cb4f2ae 100644 --- a/editor/rename_dialog.cpp +++ b/editor/rename_dialog.cpp @@ -444,11 +444,11 @@ String RenameDialog::_substitute(const String &subject, const Node *node, int co result = result.replace("${TYPE}", node->get_class()); } - int current = EditorNode::get_singleton()->get_editor_data().get_edited_scene(); + int current = EditorNode::get_editor_data().get_edited_scene(); // Always request the scene title with the extension stripped. // Otherwise, the result could vary depending on whether a scene with the same name // (but different extension) is currently open. - result = result.replace("${SCENE}", EditorNode::get_singleton()->get_editor_data().get_scene_title(current, true)); + result = result.replace("${SCENE}", EditorNode::get_editor_data().get_scene_title(current, true)); Node *root_node = SceneTree::get_singleton()->get_edited_scene_root(); if (root_node) { diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp index 3096d20c19..b1e30d369f 100644 --- a/editor/scene_tree_dock.cpp +++ b/editor/scene_tree_dock.cpp @@ -1296,14 +1296,14 @@ void SceneTreeDock::_notification(int p_what) { EditorFeatureProfileManager::get_singleton()->connect("current_feature_profile_changed", callable_mp(this, &SceneTreeDock::_feature_profile_changed)); - CanvasItemEditorPlugin *canvas_item_plugin = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); + CanvasItemEditorPlugin *canvas_item_plugin = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor_by_name("2D")); if (canvas_item_plugin) { canvas_item_plugin->get_canvas_item_editor()->connect("item_lock_status_changed", callable_mp(scene_tree, &SceneTreeEditor::_update_tree).bind(false)); canvas_item_plugin->get_canvas_item_editor()->connect("item_group_status_changed", callable_mp(scene_tree, &SceneTreeEditor::_update_tree).bind(false)); scene_tree->connect("node_changed", callable_mp((CanvasItem *)canvas_item_plugin->get_canvas_item_editor()->get_viewport_control(), &CanvasItem::queue_redraw)); } - Node3DEditorPlugin *spatial_editor_plugin = Object::cast_to<Node3DEditorPlugin>(editor_data->get_editor("3D")); + Node3DEditorPlugin *spatial_editor_plugin = Object::cast_to<Node3DEditorPlugin>(editor_data->get_editor_by_name("3D")); spatial_editor_plugin->get_spatial_editor()->connect("item_lock_status_changed", callable_mp(scene_tree, &SceneTreeEditor::_update_tree).bind(false)); spatial_editor_plugin->get_spatial_editor()->connect("item_group_status_changed", callable_mp(scene_tree, &SceneTreeEditor::_update_tree).bind(false)); @@ -3229,10 +3229,10 @@ void SceneTreeDock::_focus_node() { ERR_FAIL_COND(!node); if (node->is_class("CanvasItem")) { - CanvasItemEditorPlugin *editor = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); + CanvasItemEditorPlugin *editor = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor_by_name("2D")); editor->get_canvas_item_editor()->focus_selection(); } else { - Node3DEditorPlugin *editor = Object::cast_to<Node3DEditorPlugin>(editor_data->get_editor("3D")); + Node3DEditorPlugin *editor = Object::cast_to<Node3DEditorPlugin>(editor_data->get_editor_by_name("3D")); editor->get_spatial_editor()->get_editor_viewport(0)->focus_selection(); } } diff --git a/modules/dds/image_loader_dds.cpp b/modules/dds/image_loader_dds.cpp index 13ca1e6bff..d661f6664a 100644 --- a/modules/dds/image_loader_dds.cpp +++ b/modules/dds/image_loader_dds.cpp @@ -196,9 +196,9 @@ Error ImageLoaderDDS::load_image(Ref<Image> p_image, Ref<FileAccess> f, BitField dds_format = DDS_BGR10A2; } else if (format_flags & DDPF_RGB && !(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0x0000f800 && format_green_mask == 0x000007e0 && format_blue_mask == 0x0000001f) { dds_format = DDS_BGR565; - } else if (!(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 8 && format_red_mask == 0xff && format_green_mask == 0xff && format_blue_mask == 0xff) { + } else if (!(format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 8 && format_red_mask == 0xff) { dds_format = DDS_LUMINANCE; - } else if ((format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0xff && format_green_mask == 0xff && format_blue_mask == 0xff && format_alpha_mask == 0xff00) { + } else if ((format_flags & DDPF_ALPHAPIXELS) && format_rgb_bits == 16 && format_red_mask == 0xff && format_alpha_mask == 0xff00) { dds_format = DDS_LUMINANCE_ALPHA; } else if (format_flags & DDPF_INDEXED && format_rgb_bits == 8) { dds_format = DDS_BGR565; diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index 214b484b12..18c69467dc 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -613,144 +613,183 @@ GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::Type return result; } - StringName first = p_type->type_chain[0]->name; - - if (first == SNAME("Variant")) { - if (p_type->type_chain.size() == 2) { - // May be nested enum. - StringName enum_name = p_type->type_chain[1]->name; - StringName qualified_name = String(first) + ENUM_SEPARATOR + String(p_type->type_chain[1]->name); - if (CoreConstants::is_global_enum(qualified_name)) { - result = make_global_enum_type(enum_name, first, true); - return result; + const GDScriptParser::IdentifierNode *first_id = p_type->type_chain[0]; + StringName first = first_id->name; + bool type_found = false; + + if (first_id->suite && first_id->suite->has_local(first)) { + const GDScriptParser::SuiteNode::Local &local = first_id->suite->get_local(first); + if (local.type == GDScriptParser::SuiteNode::Local::CONSTANT) { + result = local.get_datatype(); + if (!result.is_set()) { + // Don't try to resolve it as the constant can be declared below. + push_error(vformat(R"(Local constant "%s" is not resolved at this point.)", first), first_id); + return bad_type; + } + if (result.is_meta_type) { + type_found = true; + } else if (Ref<Script>(local.constant->initializer->reduced_value).is_valid()) { + Ref<GDScript> gdscript = local.constant->initializer->reduced_value; + if (gdscript.is_valid()) { + Ref<GDScriptParserRef> ref = get_parser_for(gdscript->get_script_path()); + if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), first_id); + return bad_type; + } + result = ref->get_parser()->head->get_datatype(); + } else { + result = make_script_meta_type(local.constant->initializer->reduced_value); + } + type_found = true; } else { - push_error(vformat(R"(Name "%s" is not a nested type of "Variant".)", enum_name), p_type->type_chain[1]); + push_error(vformat(R"(Local constant "%s" is not a valid type.)", first), first_id); return bad_type; } - } else if (p_type->type_chain.size() > 2) { - push_error(R"(Variant only contains enum types, which do not have nested types.)", p_type->type_chain[2]); - return bad_type; - } - result.kind = GDScriptParser::DataType::VARIANT; - } else if (first == SNAME("Object")) { - // Object is treated like a native type, not a built-in. - result.kind = GDScriptParser::DataType::NATIVE; - result.builtin_type = Variant::OBJECT; - result.native_type = SNAME("Object"); - } else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) { - // Built-in types. - if (p_type->type_chain.size() > 1) { - push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]); + } else { + push_error(vformat(R"(Local %s "%s" cannot be used as a type.)", local.get_name(), first), first_id); return bad_type; } - result.kind = GDScriptParser::DataType::BUILTIN; - result.builtin_type = GDScriptParser::get_builtin_type(first); + } - if (result.builtin_type == Variant::ARRAY) { - GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->container_type)); - if (container_type.kind != GDScriptParser::DataType::VARIANT) { - container_type.is_constant = false; - result.set_container_element_type(container_type); - } - } - } else if (class_exists(first)) { - // Native engine classes. - result.kind = GDScriptParser::DataType::NATIVE; - result.builtin_type = Variant::OBJECT; - result.native_type = first; - } else if (ScriptServer::is_global_class(first)) { - if (parser->script_path == ScriptServer::get_global_class_path(first)) { - result = parser->head->get_datatype(); - } else { - String path = ScriptServer::get_global_class_path(first); - String ext = path.get_extension(); - if (ext == GDScriptLanguage::get_singleton()->get_extension()) { - Ref<GDScriptParserRef> ref = get_parser_for(path); - if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { - push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); + if (!type_found) { + if (first == SNAME("Variant")) { + if (p_type->type_chain.size() == 2) { + // May be nested enum. + StringName enum_name = p_type->type_chain[1]->name; + StringName qualified_name = String(first) + ENUM_SEPARATOR + String(p_type->type_chain[1]->name); + if (CoreConstants::is_global_enum(qualified_name)) { + result = make_global_enum_type(enum_name, first, true); + return result; + } else { + push_error(vformat(R"(Name "%s" is not a nested type of "Variant".)", enum_name), p_type->type_chain[1]); return bad_type; } - result = ref->get_parser()->head->get_datatype(); - } else { - result = make_script_meta_type(ResourceLoader::load(path, "Script")); + } else if (p_type->type_chain.size() > 2) { + push_error(R"(Variant only contains enum types, which do not have nested types.)", p_type->type_chain[2]); + return bad_type; } - } - } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) { - const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first); - Ref<GDScriptParserRef> ref = get_parser_for(autoload.path); - if (ref.is_null()) { - push_error(vformat(R"(The referenced autoload "%s" (from "%s") could not be loaded.)", first, autoload.path), p_type); - return bad_type; - } - if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { - push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type); - return bad_type; - } - result = ref->get_parser()->head->get_datatype(); - } else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) { - // Native enum in current class. - result = make_native_enum_type(first, parser->current_class->base_type.native_type); - } else if (CoreConstants::is_global_enum(first)) { - if (p_type->type_chain.size() > 1) { - push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[1]); - return bad_type; - } - result = make_global_enum_type(first, StringName()); - } else { - // Classes in current scope. - List<GDScriptParser::ClassNode *> script_classes; - bool found = false; - get_class_node_current_scope_classes(parser->current_class, &script_classes); - for (GDScriptParser::ClassNode *script_class : script_classes) { - if (found) { - break; + result.kind = GDScriptParser::DataType::VARIANT; + } else if (first == SNAME("Object")) { + // Object is treated like a native type, not a built-in. + result.kind = GDScriptParser::DataType::NATIVE; + result.builtin_type = Variant::OBJECT; + result.native_type = SNAME("Object"); + } else if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) { + // Built-in types. + if (p_type->type_chain.size() > 1) { + push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]); + return bad_type; } + result.kind = GDScriptParser::DataType::BUILTIN; + result.builtin_type = GDScriptParser::get_builtin_type(first); - if (script_class->identifier && script_class->identifier->name == first) { - result = script_class->get_datatype(); - break; + if (result.builtin_type == Variant::ARRAY) { + GDScriptParser::DataType container_type = type_from_metatype(resolve_datatype(p_type->container_type)); + if (container_type.kind != GDScriptParser::DataType::VARIANT) { + container_type.is_constant = false; + result.set_container_element_type(container_type); + } } - if (script_class->members_indices.has(first)) { - resolve_class_member(script_class, first, p_type); + } else if (class_exists(first)) { + // Native engine classes. + result.kind = GDScriptParser::DataType::NATIVE; + result.builtin_type = Variant::OBJECT; + result.native_type = first; + } else if (ScriptServer::is_global_class(first)) { + if (parser->script_path == ScriptServer::get_global_class_path(first)) { + result = parser->head->get_datatype(); + } else { + String path = ScriptServer::get_global_class_path(first); + String ext = path.get_extension(); + if (ext == GDScriptLanguage::get_singleton()->get_extension()) { + Ref<GDScriptParserRef> ref = get_parser_for(path); + if (!ref.is_valid() || ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type); + return bad_type; + } + result = ref->get_parser()->head->get_datatype(); + } else { + result = make_script_meta_type(ResourceLoader::load(path, "Script")); + } + } + } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) { + const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first); + Ref<GDScriptParserRef> ref = get_parser_for(autoload.path); + if (ref.is_null()) { + push_error(vformat(R"(The referenced autoload "%s" (from "%s") could not be loaded.)", first, autoload.path), p_type); + return bad_type; + } + if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type); + return bad_type; + } + result = ref->get_parser()->head->get_datatype(); + } else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) { + // Native enum in current class. + result = make_native_enum_type(first, parser->current_class->base_type.native_type); + } else if (CoreConstants::is_global_enum(first)) { + if (p_type->type_chain.size() > 1) { + push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[1]); + return bad_type; + } + result = make_global_enum_type(first, StringName()); + } else { + // Classes in current scope. + List<GDScriptParser::ClassNode *> script_classes; + bool found = false; + get_class_node_current_scope_classes(parser->current_class, &script_classes); + for (GDScriptParser::ClassNode *script_class : script_classes) { + if (found) { + break; + } - GDScriptParser::ClassNode::Member member = script_class->get_member(first); - switch (member.type) { - case GDScriptParser::ClassNode::Member::CLASS: - result = member.get_datatype(); - found = true; - break; - case GDScriptParser::ClassNode::Member::ENUM: - result = member.get_datatype(); - found = true; - break; - case GDScriptParser::ClassNode::Member::CONSTANT: - if (member.get_datatype().is_meta_type) { + if (script_class->identifier && script_class->identifier->name == first) { + result = script_class->get_datatype(); + break; + } + if (script_class->members_indices.has(first)) { + resolve_class_member(script_class, first, p_type); + + GDScriptParser::ClassNode::Member member = script_class->get_member(first); + switch (member.type) { + case GDScriptParser::ClassNode::Member::CLASS: result = member.get_datatype(); found = true; break; - } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) { - Ref<GDScript> gdscript = member.constant->initializer->reduced_value; - if (gdscript.is_valid()) { - Ref<GDScriptParserRef> ref = get_parser_for(gdscript->get_script_path()); - if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { - push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), p_type); - return bad_type; - } - result = ref->get_parser()->head->get_datatype(); - } else { - result = make_script_meta_type(member.constant->initializer->reduced_value); - } + case GDScriptParser::ClassNode::Member::ENUM: + result = member.get_datatype(); found = true; break; - } - [[fallthrough]]; - default: - push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type); - return bad_type; + case GDScriptParser::ClassNode::Member::CONSTANT: + if (member.get_datatype().is_meta_type) { + result = member.get_datatype(); + found = true; + break; + } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) { + Ref<GDScript> gdscript = member.constant->initializer->reduced_value; + if (gdscript.is_valid()) { + Ref<GDScriptParserRef> ref = get_parser_for(gdscript->get_script_path()); + if (ref->raise_status(GDScriptParserRef::INHERITANCE_SOLVED) != OK) { + push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_script_path()), p_type); + return bad_type; + } + result = ref->get_parser()->head->get_datatype(); + } else { + result = make_script_meta_type(member.constant->initializer->reduced_value); + } + found = true; + break; + } + [[fallthrough]]; + default: + push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type); + return bad_type; + } } } } } + if (!result.is_set()) { push_error(vformat(R"(Could not find type "%s" in the current scope.)", first), p_type); return bad_type; @@ -882,9 +921,12 @@ void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, case GDScriptParser::ClassNode::Member::VARIABLE: { bool previous_static_context = static_context; static_context = member.variable->is_static; + check_class_member_name_conflict(p_class, member.variable->identifier->name, member.variable); + member.variable->set_datatype(resolving_datatype); resolve_variable(member.variable, false); + resolve_pending_lambda_bodies(); // Apply annotations. for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) { @@ -893,7 +935,9 @@ void GDScriptAnalyzer::resolve_class_member(GDScriptParser::ClassNode *p_class, E->apply(parser, member.variable); } } + static_context = previous_static_context; + #ifdef DEBUG_ENABLED if (member.variable->exported && member.variable->onready) { parser->push_warning(member.variable, GDScriptWarning::ONREADY_WITH_EXPORT); @@ -1345,6 +1389,11 @@ void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class, co } } + if (!pending_body_resolution_lambdas.is_empty()) { + ERR_PRINT("GDScript bug (please report): Not all pending lambda bodies were resolved in time."); + resolve_pending_lambda_bodies(); + } + parser->current_class = previous_class; } @@ -1757,6 +1806,7 @@ void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) { #endif // DEBUG_ENABLED resolve_node(stmt); + resolve_pending_lambda_bodies(); #ifdef DEBUG_ENABLED parser->ignored_warnings = previously_ignored_warnings; @@ -3080,7 +3130,7 @@ void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool p_is_a base_type.is_meta_type = false; is_self = true; - if (p_call->callee == nullptr && !lambda_stack.is_empty()) { + if (p_call->callee == nullptr && current_lambda != nullptr) { push_error("Cannot use `super()` inside a lambda.", p_call); } } else if (callee_type == GDScriptParser::Node::IDENTIFIER) { @@ -3753,7 +3803,7 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident } } - if (!lambda_stack.is_empty()) { + if (current_lambda != nullptr) { // If the identifier is a member variable (including the native class properties) or a signal, we consider the lambda to be using `self`, so we keep a reference to the current instance. if (source_is_variable || source_is_signal) { mark_lambda_use_self(); @@ -3765,7 +3815,7 @@ void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_ident return; } - GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function; + GDScriptParser::FunctionNode *function_test = current_lambda->function; // Make sure we aren't capturing variable in the same lambda. // This also add captures for nested lambdas. while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) { @@ -3920,34 +3970,12 @@ void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) { return; } - lambda_stack.push_back(p_lambda); + GDScriptParser::LambdaNode *previous_lambda = current_lambda; + current_lambda = p_lambda; resolve_function_signature(p_lambda->function, p_lambda, true); - resolve_function_body(p_lambda->function, true); - lambda_stack.pop_back(); - - int captures_amount = p_lambda->captures.size(); - if (captures_amount > 0) { - // Create space for lambda parameters. - // At the beginning to not mess with optional parameters. - int param_count = p_lambda->function->parameters.size(); - p_lambda->function->parameters.resize(param_count + captures_amount); - for (int i = param_count - 1; i >= 0; i--) { - p_lambda->function->parameters.write[i + captures_amount] = p_lambda->function->parameters[i]; - p_lambda->function->parameters_indices[p_lambda->function->parameters[i]->identifier->name] = i + captures_amount; - } + current_lambda = previous_lambda; - // Add captures as extra parameters at the beginning. - for (int i = 0; i < p_lambda->captures.size(); i++) { - GDScriptParser::IdentifierNode *capture = p_lambda->captures[i]; - GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>(); - capture_param->identifier = capture; - capture_param->usages = capture->usages; - capture_param->set_datatype(capture->get_datatype()); - - p_lambda->function->parameters.write[i] = capture_param; - p_lambda->function->parameters_indices[capture->name] = i; - } - } + pending_body_resolution_lambdas.push_back(p_lambda); } void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) { @@ -5288,9 +5316,53 @@ void GDScriptAnalyzer::downgrade_node_type_source(GDScriptParser::Node *p_node) } void GDScriptAnalyzer::mark_lambda_use_self() { - for (GDScriptParser::LambdaNode *lambda : lambda_stack) { + GDScriptParser::LambdaNode *lambda = current_lambda; + while (lambda != nullptr) { lambda->use_self = true; + lambda = lambda->parent_lambda; + } +} + +void GDScriptAnalyzer::resolve_pending_lambda_bodies() { + if (pending_body_resolution_lambdas.is_empty()) { + return; + } + + GDScriptParser::LambdaNode *previous_lambda = current_lambda; + + List<GDScriptParser::LambdaNode *> lambdas = pending_body_resolution_lambdas; + pending_body_resolution_lambdas.clear(); + + for (GDScriptParser::LambdaNode *lambda : lambdas) { + current_lambda = lambda; + resolve_function_body(lambda->function, true); + + int captures_amount = lambda->captures.size(); + if (captures_amount > 0) { + // Create space for lambda parameters. + // At the beginning to not mess with optional parameters. + int param_count = lambda->function->parameters.size(); + lambda->function->parameters.resize(param_count + captures_amount); + for (int i = param_count - 1; i >= 0; i--) { + lambda->function->parameters.write[i + captures_amount] = lambda->function->parameters[i]; + lambda->function->parameters_indices[lambda->function->parameters[i]->identifier->name] = i + captures_amount; + } + + // Add captures as extra parameters at the beginning. + for (int i = 0; i < lambda->captures.size(); i++) { + GDScriptParser::IdentifierNode *capture = lambda->captures[i]; + GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>(); + capture_param->identifier = capture; + capture_param->usages = capture->usages; + capture_param->set_datatype(capture->get_datatype()); + + lambda->function->parameters.write[i] = capture_param; + lambda->function->parameters_indices[capture->name] = i; + } + } } + + current_lambda = previous_lambda; } bool GDScriptAnalyzer::class_exists(const StringName &p_class) const { diff --git a/modules/gdscript/gdscript_analyzer.h b/modules/gdscript/gdscript_analyzer.h index 5bc2c89a87..ec155706df 100644 --- a/modules/gdscript/gdscript_analyzer.h +++ b/modules/gdscript/gdscript_analyzer.h @@ -43,7 +43,8 @@ class GDScriptAnalyzer { HashMap<String, Ref<GDScriptParserRef>> depended_parsers; const GDScriptParser::EnumNode *current_enum = nullptr; - List<GDScriptParser::LambdaNode *> lambda_stack; + GDScriptParser::LambdaNode *current_lambda = nullptr; + List<GDScriptParser::LambdaNode *> pending_body_resolution_lambdas; bool static_context = false; // Tests for detecting invalid overloading of script members @@ -129,6 +130,7 @@ class GDScriptAnalyzer { void mark_node_unsafe(const GDScriptParser::Node *p_node); void downgrade_node_type_source(GDScriptParser::Node *p_node); void mark_lambda_use_self(); + void resolve_pending_lambda_bodies(); bool class_exists(const StringName &p_class) const; Ref<GDScriptParserRef> get_parser_for(const String &p_path); void reduce_identifier_from_base_set_class(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType p_identifier_datatype); diff --git a/modules/gdscript/gdscript_parser.cpp b/modules/gdscript/gdscript_parser.cpp index 1dde67d2d1..0f7166c101 100644 --- a/modules/gdscript/gdscript_parser.cpp +++ b/modules/gdscript/gdscript_parser.cpp @@ -2291,9 +2291,7 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode IdentifierNode *identifier = alloc_node<IdentifierNode>(); complete_extents(identifier); identifier->name = previous.get_identifier(); -#ifdef DEBUG_ENABLED identifier->suite = current_suite; -#endif if (current_suite != nullptr && current_suite->has_local(identifier->name)) { const SuiteNode::Local &declaration = current_suite->get_local(identifier->name); @@ -3151,6 +3149,8 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_ GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) { LambdaNode *lambda = alloc_node<LambdaNode>(); lambda->parent_function = current_function; + lambda->parent_lambda = current_lambda; + FunctionNode *function = alloc_node<FunctionNode>(); function->source_lambda = lambda; @@ -3178,6 +3178,9 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_p FunctionNode *previous_function = current_function; current_function = function; + LambdaNode *previous_lambda = current_lambda; + current_lambda = lambda; + SuiteNode *body = alloc_node<SuiteNode>(); body->parent_function = current_function; body->parent_block = current_suite; @@ -3215,6 +3218,7 @@ GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_p } current_function = previous_function; + current_lambda = previous_lambda; in_lambda = previous_in_lambda; lambda->function = function; @@ -4283,7 +4287,7 @@ String GDScriptParser::SuiteNode::Local::get_name() const { case SuiteNode::Local::FOR_VARIABLE: return "for loop iterator"; case SuiteNode::Local::PATTERN_BIND: - return "pattern_bind"; + return "pattern bind"; case SuiteNode::Local::UNDEFINED: return "<undefined>"; default: diff --git a/modules/gdscript/gdscript_parser.h b/modules/gdscript/gdscript_parser.h index 652faaebc3..d1ab5f92cc 100644 --- a/modules/gdscript/gdscript_parser.h +++ b/modules/gdscript/gdscript_parser.h @@ -859,9 +859,7 @@ public: struct IdentifierNode : public ExpressionNode { StringName name; -#ifdef DEBUG_ENABLED SuiteNode *suite = nullptr; // The block in which the identifier is used. -#endif enum Source { UNDEFINED_SOURCE, @@ -908,6 +906,7 @@ public: struct LambdaNode : public ExpressionNode { FunctionNode *function = nullptr; FunctionNode *parent_function = nullptr; + LambdaNode *parent_lambda = nullptr; Vector<IdentifierNode *> captures; HashMap<StringName, int> captures_indices; bool use_self = false; @@ -1321,6 +1320,7 @@ private: ClassNode *current_class = nullptr; FunctionNode *current_function = nullptr; + LambdaNode *current_lambda = nullptr; SuiteNode *current_suite = nullptr; CompletionContext completion_context; diff --git a/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_call_arg.gd b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_call_arg.gd new file mode 100644 index 0000000000..4b72fb9daa --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_call_arg.gd @@ -0,0 +1,5 @@ +var f = (func (_a): return 0).call(x) +var x = f + +func test(): + pass diff --git a/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_call_arg.out b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_call_arg.out new file mode 100644 index 0000000000..6bca25b330 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_call_arg.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Could not resolve member "f": Cyclic reference. diff --git a/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_param.gd b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_param.gd new file mode 100644 index 0000000000..115e8be50a --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_param.gd @@ -0,0 +1,5 @@ +var f = func (_a = x): return 0 +var x = f + +func test(): + pass diff --git a/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_param.out b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_param.out new file mode 100644 index 0000000000..6bca25b330 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/lambda_cyclic_ref_param.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Could not resolve member "f": Cyclic reference. diff --git a/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_before_declared.gd b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_before_declared.gd new file mode 100644 index 0000000000..7cdc14685f --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_before_declared.gd @@ -0,0 +1,5 @@ +enum MyEnum {} + +func test(): + var e: E + const E = MyEnum diff --git a/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_before_declared.out b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_before_declared.out new file mode 100644 index 0000000000..e1d5837f32 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_before_declared.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Local constant "E" is not resolved at this point. diff --git a/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_const.gd b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_const.gd new file mode 100644 index 0000000000..68cf5efd8b --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_const.gd @@ -0,0 +1,5 @@ +enum MyEnum {} + +func test(): + var E = MyEnum + var e: E diff --git a/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_const.out b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_const.out new file mode 100644 index 0000000000..b1f4e7a2c8 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_const.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Local variable "E" cannot be used as a type. diff --git a/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_type.gd b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_type.gd new file mode 100644 index 0000000000..ac446183cb --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_type.gd @@ -0,0 +1,5 @@ +enum MyEnum {A} + +func test(): + const E = MyEnum.A + var e: E diff --git a/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_type.out b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_type.out new file mode 100644 index 0000000000..c3c2c8ca2f --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/errors/local_const_as_type_use_not_type.out @@ -0,0 +1,2 @@ +GDTEST_ANALYZER_ERROR +Local constant "E" is not a valid type. diff --git a/modules/gdscript/tests/scripts/analyzer/features/lambda_cyclic_ref_body.gd b/modules/gdscript/tests/scripts/analyzer/features/lambda_cyclic_ref_body.gd new file mode 100644 index 0000000000..e2f41a652c --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/lambda_cyclic_ref_body.gd @@ -0,0 +1,34 @@ +# GH-70592 + +var f: Callable = func (): + x = 2 + return 1 + +var x: int = f.call() + +var g: Array[Callable] = [ + func (): + y += 10 + return 1, + func (): + y += 20 + return 2, +] + +var y: int = g[0].call() + g[1].call() + +func test(): + print(x) + f.call() + print(x) + + print(y) + g[0].call() + g[1].call() + print(y) + + # This prevents memory leak in CI. TODO: Investigate it. + # Also you cannot run the `EditorScript` twice without the cleaning. Error: + # Condition "!p_keep_state && has_instances" is true. Returning: ERR_ALREADY_IN_USE + f = Callable() + g.clear() diff --git a/modules/gdscript/tests/scripts/analyzer/features/lambda_cyclic_ref_body.out b/modules/gdscript/tests/scripts/analyzer/features/lambda_cyclic_ref_body.out new file mode 100644 index 0000000000..6917fa7c2c --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/lambda_cyclic_ref_body.out @@ -0,0 +1,5 @@ +GDTEST_OK +1 +2 +3 +33 diff --git a/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.gd b/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.gd new file mode 100644 index 0000000000..90c7f893b1 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.gd @@ -0,0 +1,41 @@ +class InnerClass: + enum InnerEnum {A = 2} + const INNER_CONST = "INNER_CONST" + +enum Enum {A = 1} + +const Other = preload("./local_const_as_type.notest.gd") + +func test(): + const IC = InnerClass + const IE = IC.InnerEnum + const E = Enum + # Doesn't work in CI, but works in the editor. Looks like an unrelated bug. TODO: Investigate it. + # Error: Invalid call. Nonexistent function 'new' in base 'GDScript'. + var a1: IC = null # IC.new() + var a2: IE = IE.A + var a3: IC.InnerEnum = IE.A + var a4: E = E.A + print(a1.INNER_CONST) + print(a2) + print(a3) + print(a4) + + const O = Other + const OV: Variant = Other # Removes metatype. + const OIC = O.InnerClass + const OIE = OIC.InnerEnum + const OE = O.Enum + var b: O = O.new() + @warning_ignore("unsafe_method_access") + var bv: OV = OV.new() + var b1: OIC = OIC.new() + var b2: OIE = OIE.A + var b3: O.InnerClass.InnerEnum = OIE.A + var b4: OE = OE.A + print(b.CONST) + print(bv.CONST) + print(b1.INNER_CONST) + print(b2) + print(b3) + print(b4) diff --git a/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.notest.gd b/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.notest.gd new file mode 100644 index 0000000000..f16cdc18d8 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.notest.gd @@ -0,0 +1,6 @@ +class InnerClass: + enum InnerEnum {A = 20} + const INNER_CONST = "OTHER_INNER_CONST" + +enum Enum {A = 10} +const CONST = "OTHER_CONST" diff --git a/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.out b/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.out new file mode 100644 index 0000000000..b00024de2c --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/local_const_as_type.out @@ -0,0 +1,11 @@ +GDTEST_OK +INNER_CONST +2 +2 +1 +OTHER_CONST +OTHER_CONST +OTHER_INNER_CONST +20 +20 +10 diff --git a/editor/icons/RegEx.svg b/modules/regex/icons/RegEx.svg index 4df26f41c0..4df26f41c0 100644 --- a/editor/icons/RegEx.svg +++ b/modules/regex/icons/RegEx.svg diff --git a/editor/icons/RegExMatch.svg b/modules/regex/icons/RegExMatch.svg index 889cf6cc8a..889cf6cc8a 100644 --- a/editor/icons/RegExMatch.svg +++ b/modules/regex/icons/RegExMatch.svg diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp index 4b7fad5edf..fb3b199638 100644 --- a/scene/2d/node_2d.cpp +++ b/scene/2d/node_2d.cpp @@ -138,10 +138,6 @@ void Node2D::_update_transform() { RenderingServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), transform); - if (!is_inside_tree()) { - return; - } - _notify_transform(); } @@ -378,10 +374,6 @@ void Node2D::set_transform(const Transform2D &p_transform) { RenderingServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), transform); - if (!is_inside_tree()) { - return; - } - _notify_transform(); } diff --git a/scene/3d/occluder_instance_3d.cpp b/scene/3d/occluder_instance_3d.cpp index 7b535f6169..a76488e479 100644 --- a/scene/3d/occluder_instance_3d.cpp +++ b/scene/3d/occluder_instance_3d.cpp @@ -458,7 +458,7 @@ void OccluderInstance3D::set_occluder(const Ref<Occluder3D> &p_occluder) { #ifdef TOOLS_ENABLED // PolygonOccluder3D is edited via an editor plugin, this ensures the plugin is shown/hidden when necessary if (Engine::get_singleton()->is_editor_hint()) { - EditorNode::get_singleton()->call_deferred(SNAME("edit_current")); + callable_mp(EditorNode::get_singleton(), &EditorNode::edit_current).call_deferred(); } #endif } diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp index 0ca04faf9b..63692dd064 100644 --- a/scene/gui/control.cpp +++ b/scene/gui/control.cpp @@ -1734,6 +1734,10 @@ void Control::_size_changed() { if (pos_changed && !size_changed) { _update_canvas_item_transform(); //move because it won't be updated } + } else { + if (pos_changed) { + _notify_transform(); + } } } diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp index 070c79c0ee..b2dea05f2a 100644 --- a/scene/gui/rich_text_label.cpp +++ b/scene/gui/rich_text_label.cpp @@ -3095,15 +3095,17 @@ void RichTextLabel::_remove_item(Item *p_item, const int p_line, const int p_sub // If a newline was erased, all lines AFTER the newline need to be decremented. if (p_item->type == ITEM_NEWLINE) { current_frame->lines.remove_at(p_line); - for (int i = 0; i < current->subitems.size(); i++) { - if (current->subitems[i]->line > p_subitem_line) { - current->subitems[i]->line--; + if (p_line < (int)current_frame->lines.size() && current_frame->lines[p_line].from) { + for (List<Item *>::Element *E = current_frame->lines[p_line].from->E; E; E = E->next()) { + if (E->get()->line > p_subitem_line) { + E->get()->line--; + } } } } } else { // First, remove all child items for the provided item. - for (int i = 0; i < size; i++) { + while (p_item->subitems.size()) { _remove_item(p_item->subitems.front()->get(), p_line, p_subitem_line); } // Then remove the provided item itself. @@ -3199,19 +3201,23 @@ bool RichTextLabel::remove_paragraph(const int p_paragraph) { } // Remove all subitems with the same line as that provided. - Vector<int> subitem_indices_to_remove; - for (int i = 0; i < current->subitems.size(); i++) { - if (current->subitems[i]->line == p_paragraph) { - subitem_indices_to_remove.push_back(i); + Vector<List<Item *>::Element *> subitem_to_remove; + if (current_frame->lines[p_paragraph].from) { + for (List<Item *>::Element *E = current_frame->lines[p_paragraph].from->E; E; E = E->next()) { + if (E->get()->line == p_paragraph) { + subitem_to_remove.push_back(E); + } else { + break; + } } } bool had_newline = false; // Reverse for loop to remove items from the end first. - for (int i = subitem_indices_to_remove.size() - 1; i >= 0; i--) { - int subitem_idx = subitem_indices_to_remove[i]; - had_newline = had_newline || current->subitems[subitem_idx]->type == ITEM_NEWLINE; - _remove_item(current->subitems[subitem_idx], current->subitems[subitem_idx]->line, p_paragraph); + for (int i = subitem_to_remove.size() - 1; i >= 0; i--) { + List<Item *>::Element *subitem = subitem_to_remove[i]; + had_newline = had_newline || subitem->get()->type == ITEM_NEWLINE; + _remove_item(subitem->get(), subitem->get()->line, p_paragraph); } if (!had_newline) { @@ -5304,6 +5310,8 @@ void RichTextLabel::selection_copy() { } void RichTextLabel::select_all() { + _validate_line_caches(); + if (!selection.enabled) { return; } @@ -5316,13 +5324,12 @@ void RichTextLabel::select_all() { if (it->type != ITEM_FRAME) { if (!from_item) { from_item = it; - } else { - to_item = it; } + to_item = it; } it = _get_next_item(it, true); } - if (!from_item || !to_item) { + if (!from_item) { return; } diff --git a/scene/main/canvas_item.cpp b/scene/main/canvas_item.cpp index 2947d73552..855cad51e9 100644 --- a/scene/main/canvas_item.cpp +++ b/scene/main/canvas_item.cpp @@ -320,7 +320,6 @@ void CanvasItem::_notification(int p_what) { } } - _set_global_invalid(true); _enter_canvas(); RenderingServer::get_singleton()->canvas_item_set_visible(canvas_item, is_visible_in_tree()); // The visibility of the parent may change. @@ -367,7 +366,11 @@ void CanvasItem::_notification(int p_what) { case NOTIFICATION_WORLD_2D_CHANGED: { _exit_canvas(); _enter_canvas(); - } + } break; + case NOTIFICATION_PARENTED: { + // The node is not inside the tree during this notification. + _notify_transform(); + } break; } } diff --git a/scene/main/canvas_item.h b/scene/main/canvas_item.h index 7f6bbb17c3..51591e1ac6 100644 --- a/scene/main/canvas_item.h +++ b/scene/main/canvas_item.h @@ -152,11 +152,8 @@ private: protected: _FORCE_INLINE_ void _notify_transform() { - if (!is_inside_tree()) { - return; - } _notify_transform(this); - if (!block_transform_notify && notify_local_transform) { + if (is_inside_tree() && !block_transform_notify && notify_local_transform) { notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); } } diff --git a/scene/resources/atlas_texture.cpp b/scene/resources/atlas_texture.cpp index 24bf25f2db..6aed68849b 100644 --- a/scene/resources/atlas_texture.cpp +++ b/scene/resources/atlas_texture.cpp @@ -245,11 +245,16 @@ bool AtlasTexture::is_pixel_opaque(int p_x, int p_y) const { } Ref<Image> AtlasTexture::get_image() const { - if (!atlas.is_valid() || !atlas->get_image().is_valid()) { + if (atlas.is_null() || region.size.x <= 0 || region.size.y <= 0) { return Ref<Image>(); } - return atlas->get_image()->get_region(region); + Ref<Image> atlas_image = atlas->get_image(); + if (atlas_image.is_null()) { + return Ref<Image>(); + } + + return atlas_image->get_region(region); } AtlasTexture::AtlasTexture() {} diff --git a/scene/resources/particle_process_material.cpp b/scene/resources/particle_process_material.cpp index 72d38ec8ce..dbb286c6e7 100644 --- a/scene/resources/particle_process_material.cpp +++ b/scene/resources/particle_process_material.cpp @@ -762,7 +762,7 @@ void ParticleProcessMaterial::_update_shader() { code += " float base_angle = (tex_angle) * mix(initial_angle_min, initial_angle_max, angle_rand);\n"; code += " base_angle += CUSTOM.y * LIFETIME * (tex_angular_velocity) * mix(angular_velocity_min,angular_velocity_max, rand_from_seed(alt_seed));\n"; code += " CUSTOM.x = base_angle * degree_to_rad;\n"; // angle - code += " CUSTOM.z = (tex_anim_offset) * mix(anim_offset_min, anim_offset_max, rand_from_seed(alt_seed)) + tv * tex_anim_speed * mix(anim_speed_min, anim_speed_max, rand_from_seed(alt_seed));\n"; // angle + code += " CUSTOM.z = (tex_anim_offset) * mix(anim_offset_min, anim_offset_max, anim_offset_rand) + tv * tex_anim_speed * mix(anim_speed_min, anim_speed_max, rand_from_seed(alt_seed));\n"; // angle // apply color // apply hue rotation diff --git a/tests/scene/test_control.h b/tests/scene/test_control.h new file mode 100644 index 0000000000..3d7e389e0a --- /dev/null +++ b/tests/scene/test_control.h @@ -0,0 +1,66 @@ +/**************************************************************************/ +/* test_control.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* 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. */ +/**************************************************************************/ + +#ifndef TEST_CONTROL_H +#define TEST_CONTROL_H + +#include "scene/gui/control.h" + +#include "tests/test_macros.h" + +namespace TestControl { + +TEST_CASE("[SceneTree][Control]") { + SUBCASE("[Control][Global Transform] Global Transform should be accessible while not in SceneTree.") { // GH-79453 + Control *test_node = memnew(Control); + Control *test_child = memnew(Control); + test_node->add_child(test_child); + + test_node->set_global_position(Point2(1, 1)); + CHECK_EQ(test_node->get_global_position(), Point2(1, 1)); + CHECK_EQ(test_child->get_global_position(), Point2(1, 1)); + test_node->set_global_position(Point2(2, 2)); + CHECK_EQ(test_node->get_global_position(), Point2(2, 2)); + test_node->set_scale(Vector2(4, 4)); + CHECK_EQ(test_node->get_global_transform(), Transform2D(0, Size2(4, 4), 0, Vector2(2, 2))); + test_node->set_scale(Vector2(1, 1)); + test_node->set_rotation_degrees(90); + CHECK_EQ(test_node->get_global_transform(), Transform2D(Math_PI / 2, Vector2(2, 2))); + test_node->set_pivot_offset(Vector2(1, 0)); + CHECK_EQ(test_node->get_global_transform(), Transform2D(Math_PI / 2, Vector2(3, 1))); + + memdelete(test_child); + memdelete(test_node); + } +} + +} // namespace TestControl + +#endif // TEST_CONTROL_H diff --git a/tests/scene/test_node_2d.h b/tests/scene/test_node_2d.h new file mode 100644 index 0000000000..7e93c77e22 --- /dev/null +++ b/tests/scene/test_node_2d.h @@ -0,0 +1,63 @@ +/**************************************************************************/ +/* test_node_2d.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* 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. */ +/**************************************************************************/ + +#ifndef TEST_NODE_2D_H +#define TEST_NODE_2D_H + +#include "scene/2d/node_2d.h" + +#include "tests/test_macros.h" + +namespace TestNode2D { + +TEST_CASE("[SceneTree][Node2D]") { + SUBCASE("[Node2D][Global Transform] Global Transform should be accessible while not in SceneTree.") { // GH-79453 + Node2D *test_node = memnew(Node2D); + test_node->set_name("node"); + Node2D *test_child = memnew(Node2D); + test_child->set_name("child"); + test_node->add_child(test_child); + + test_node->set_global_position(Point2(1, 1)); + CHECK_EQ(test_node->get_global_position(), Point2(1, 1)); + CHECK_EQ(test_child->get_global_position(), Point2(1, 1)); + test_node->set_global_position(Point2(2, 2)); + CHECK_EQ(test_node->get_global_position(), Point2(2, 2)); + test_node->set_global_transform(Transform2D(0, Point2(3, 3))); + CHECK_EQ(test_node->get_global_position(), Point2(3, 3)); + + memdelete(test_child); + memdelete(test_node); + } +} + +} // namespace TestNode2D + +#endif // TEST_NODE_2D_H diff --git a/tests/test_main.cpp b/tests/test_main.cpp index f42fa517fe..6cc7aad48e 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -95,6 +95,7 @@ #include "tests/scene/test_bit_map.h" #include "tests/scene/test_code_edit.h" #include "tests/scene/test_color_picker.h" +#include "tests/scene/test_control.h" #include "tests/scene/test_curve.h" #include "tests/scene/test_curve_2d.h" #include "tests/scene/test_curve_3d.h" @@ -106,6 +107,7 @@ #include "tests/scene/test_navigation_region_2d.h" #include "tests/scene/test_navigation_region_3d.h" #include "tests/scene/test_node.h" +#include "tests/scene/test_node_2d.h" #include "tests/scene/test_packed_scene.h" #include "tests/scene/test_path_2d.h" #include "tests/scene/test_path_3d.h" |