/**************************************************************************/ /* node.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 "node.h" #include "core/config/project_settings.h" #include "core/core_string_names.h" #include "core/io/resource_loader.h" #include "core/object/message_queue.h" #include "core/object/script_language.h" #include "core/string/print_string.h" #include "instance_placeholder.h" #include "scene/animation/tween.h" #include "scene/debugger/scene_debugger.h" #include "scene/main/multiplayer_api.h" #include "scene/main/window.h" #include "scene/resources/packed_scene.h" #include "scene/scene_string_names.h" #include "viewport.h" #include int Node::orphan_node_count = 0; thread_local Node *Node::current_process_thread_group = nullptr; void Node::_notification(int p_notification) { switch (p_notification) { case NOTIFICATION_PROCESS: { GDVIRTUAL_CALL(_process, get_process_delta_time()); } break; case NOTIFICATION_PHYSICS_PROCESS: { GDVIRTUAL_CALL(_physics_process, get_physics_process_delta_time()); } break; case NOTIFICATION_ENTER_TREE: { ERR_FAIL_NULL(get_viewport()); ERR_FAIL_NULL(get_tree()); // Update process mode. if (data.process_mode == PROCESS_MODE_INHERIT) { if (data.parent) { data.process_owner = data.parent->data.process_owner; } else { ERR_PRINT("The root node can't be set to Inherit process mode, reverting to Pausable instead."); data.process_mode = PROCESS_MODE_PAUSABLE; data.process_owner = this; } } else { data.process_owner = this; } { // Update threaded process mode. if (data.process_thread_group == PROCESS_THREAD_GROUP_INHERIT) { if (data.parent) { data.process_thread_group_owner = data.parent->data.process_thread_group_owner; } if (data.process_thread_group_owner) { data.process_group = data.process_thread_group_owner->data.process_group; } else { data.process_group = &data.tree->default_process_group; } } else { data.process_thread_group_owner = this; _add_process_group(); } if (_is_any_processing()) { _add_to_process_thread_group(); } } if (data.input) { add_to_group("_vp_input" + itos(get_viewport()->get_instance_id())); } if (data.shortcut_input) { add_to_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); } if (data.unhandled_input) { add_to_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } if (data.unhandled_key_input) { add_to_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_id())); } get_tree()->nodes_in_tree_count++; orphan_node_count--; } break; case NOTIFICATION_EXIT_TREE: { ERR_FAIL_NULL(get_viewport()); ERR_FAIL_NULL(get_tree()); get_tree()->nodes_in_tree_count--; orphan_node_count++; if (data.input) { remove_from_group("_vp_input" + itos(get_viewport()->get_instance_id())); } if (data.shortcut_input) { remove_from_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); } if (data.unhandled_input) { remove_from_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } if (data.unhandled_key_input) { remove_from_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_id())); } // Remove from processing first if (_is_any_processing()) { _remove_from_process_thread_group(); } // Remove the process group if (data.process_thread_group_owner == this) { _remove_process_group(); } data.process_thread_group_owner = nullptr; data.process_owner = nullptr; if (data.path_cache) { memdelete(data.path_cache); data.path_cache = nullptr; } } break; case NOTIFICATION_PATH_RENAMED: { if (data.path_cache) { memdelete(data.path_cache); data.path_cache = nullptr; } } break; case NOTIFICATION_READY: { if (GDVIRTUAL_IS_OVERRIDDEN(_input)) { set_process_input(true); } if (GDVIRTUAL_IS_OVERRIDDEN(_shortcut_input)) { set_process_shortcut_input(true); } if (GDVIRTUAL_IS_OVERRIDDEN(_unhandled_input)) { set_process_unhandled_input(true); } if (GDVIRTUAL_IS_OVERRIDDEN(_unhandled_key_input)) { set_process_unhandled_key_input(true); } if (GDVIRTUAL_IS_OVERRIDDEN(_process)) { set_process(true); } if (GDVIRTUAL_IS_OVERRIDDEN(_physics_process)) { set_physics_process(true); } GDVIRTUAL_CALL(_ready); } break; case NOTIFICATION_POSTINITIALIZE: { data.in_constructor = false; } break; case NOTIFICATION_PREDELETE: { if (data.inside_tree && !Thread::is_main_thread()) { cancel_free(); ERR_PRINT("Attempted to free a node that is currently added to the SceneTree from a thread. This is not permitted, use queue_free() instead. Node has not been freed."); return; } if (data.owner) { _clean_up_owner(); } if (data.parent) { data.parent->remove_child(this); } // kill children as cleanly as possible while (data.children.size()) { Node *child = data.children.last()->value; // begin from the end because its faster and more consistent with creation memdelete(child); } } break; } } void Node::_propagate_ready() { data.ready_notified = true; data.blocked++; for (KeyValue &K : data.children) { K.value->_propagate_ready(); } data.blocked--; notification(NOTIFICATION_POST_ENTER_TREE); if (data.ready_first) { data.ready_first = false; notification(NOTIFICATION_READY); emit_signal(SceneStringNames::get_singleton()->ready); } } void Node::_propagate_enter_tree() { // this needs to happen to all children before any enter_tree if (data.parent) { data.tree = data.parent->data.tree; data.depth = data.parent->data.depth + 1; } else { data.depth = 1; } data.viewport = Object::cast_to(this); if (!data.viewport && data.parent) { data.viewport = data.parent->data.viewport; } data.inside_tree = true; for (KeyValue &E : data.grouped) { E.value.group = data.tree->add_to_group(E.key, this); } notification(NOTIFICATION_ENTER_TREE); GDVIRTUAL_CALL(_enter_tree); emit_signal(SceneStringNames::get_singleton()->tree_entered); data.tree->node_added(this); if (data.parent) { Variant c = this; const Variant *cptr = &c; data.parent->emit_signalp(SNAME("child_entered_tree"), &cptr, 1); } data.blocked++; //block while adding children for (KeyValue &K : data.children) { if (!K.value->is_inside_tree()) { // could have been added in enter_tree K.value->_propagate_enter_tree(); } } data.blocked--; #ifdef DEBUG_ENABLED SceneDebugger::add_to_cache(data.scene_file_path, this); #endif // enter groups } void Node::_propagate_after_exit_tree() { // Clear owner if it was not part of the pruned branch if (data.owner) { bool found = false; Node *parent = data.parent; while (parent) { if (parent == data.owner) { found = true; break; } parent = parent->data.parent; } if (!found) { _clean_up_owner(); } } data.blocked++; for (HashMap::Iterator I = data.children.last(); I; --I) { I->value->_propagate_after_exit_tree(); } data.blocked--; emit_signal(SceneStringNames::get_singleton()->tree_exited); } void Node::_propagate_exit_tree() { //block while removing children #ifdef DEBUG_ENABLED if (!data.scene_file_path.is_empty()) { // Only remove if file path is set (optimization). SceneDebugger::remove_from_cache(data.scene_file_path, this); } #endif data.blocked++; for (HashMap::Iterator I = data.children.last(); I; --I) { I->value->_propagate_exit_tree(); } data.blocked--; GDVIRTUAL_CALL(_exit_tree); emit_signal(SceneStringNames::get_singleton()->tree_exiting); notification(NOTIFICATION_EXIT_TREE, true); if (data.tree) { data.tree->node_removed(this); } if (data.parent) { Variant c = this; const Variant *cptr = &c; data.parent->emit_signalp(SNAME("child_exiting_tree"), &cptr, 1); } // exit groups for (KeyValue &E : data.grouped) { data.tree->remove_from_group(E.key, this); E.value.group = nullptr; } data.viewport = nullptr; if (data.tree) { data.tree->tree_changed(); } data.inside_tree = false; data.ready_notified = false; data.tree = nullptr; data.depth = -1; } void Node::move_child(Node *p_child, int p_index) { ERR_FAIL_COND_MSG(data.inside_tree && !Thread::is_main_thread(), "Moving child node positions inside the SceneTree is only allowed from the main thread. Use call_deferred(\"move_child\",child,index)."); ERR_FAIL_NULL(p_child); ERR_FAIL_COND_MSG(p_child->data.parent != this, "Child is not a child of this node."); _update_children_cache(); // We need to check whether node is internal and move it only in the relevant node range. if (p_child->data.internal_mode == INTERNAL_MODE_FRONT) { if (p_index < 0) { p_index += data.internal_children_front_count_cache; } ERR_FAIL_INDEX_MSG(p_index, data.internal_children_front_count_cache, vformat("Invalid new child index: %d. Child is internal.", p_index)); _move_child(p_child, p_index); } else if (p_child->data.internal_mode == INTERNAL_MODE_BACK) { if (p_index < 0) { p_index += data.internal_children_back_count_cache; } ERR_FAIL_INDEX_MSG(p_index, data.internal_children_back_count_cache, vformat("Invalid new child index: %d. Child is internal.", p_index)); _move_child(p_child, (int)data.children_cache.size() - data.internal_children_back_count_cache + p_index); } else { if (p_index < 0) { p_index += get_child_count(false); } ERR_FAIL_INDEX_MSG(p_index, (int)data.children_cache.size() + 1 - data.internal_children_front_count_cache - data.internal_children_back_count_cache, vformat("Invalid new child index: %d.", p_index)); _move_child(p_child, p_index + data.internal_children_front_count_cache); } } void Node::_move_child(Node *p_child, int p_index, bool p_ignore_end) { ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, `move_child()` failed. Consider using `move_child.call_deferred(child, index)` instead (or `popup.call_deferred()` if this is from a popup)."); // Specifying one place beyond the end // means the same as moving to the last index if (!p_ignore_end) { // p_ignore_end is a little hack to make back internal children work properly. if (p_child->data.internal_mode == INTERNAL_MODE_FRONT) { if (p_index == data.internal_children_front_count_cache) { p_index--; } } else if (p_child->data.internal_mode == INTERNAL_MODE_BACK) { if (p_index == (int)data.children_cache.size()) { p_index--; } } else { if (p_index == (int)data.children_cache.size() - data.internal_children_back_count_cache) { p_index--; } } } int child_index = p_child->get_index(); if (child_index == p_index) { return; //do nothing } int motion_from = MIN(p_index, child_index); int motion_to = MAX(p_index, child_index); data.children_cache.remove_at(child_index); data.children_cache.insert(p_index, p_child); if (data.tree) { data.tree->tree_changed(); } data.blocked++; //new pos first for (int i = motion_from; i <= motion_to; i++) { if (data.children_cache[i]->data.internal_mode == INTERNAL_MODE_DISABLED) { data.children_cache[i]->data.index = i - data.internal_children_front_count_cache; } else if (data.children_cache[i]->data.internal_mode == INTERNAL_MODE_BACK) { data.children_cache[i]->data.index = i - data.internal_children_front_count_cache - data.external_children_count_cache; } else { data.children_cache[i]->data.index = i; } } // notification second move_child_notify(p_child); notification(NOTIFICATION_CHILD_ORDER_CHANGED); emit_signal(SNAME("child_order_changed")); p_child->_propagate_groups_dirty(); data.blocked--; } void Node::_propagate_groups_dirty() { for (const KeyValue &E : data.grouped) { if (E.value.group) { E.value.group->changed = true; } } for (KeyValue &K : data.children) { K.value->_propagate_groups_dirty(); } } void Node::add_child_notify(Node *p_child) { // to be used when not wanted } void Node::remove_child_notify(Node *p_child) { // to be used when not wanted } void Node::move_child_notify(Node *p_child) { // to be used when not wanted } void Node::owner_changed_notify() { } void Node::set_physics_process(bool p_process) { ERR_THREAD_GUARD if (data.physics_process == p_process) { return; } if (!is_inside_tree()) { data.physics_process = p_process; return; } if (_is_any_processing()) { _remove_from_process_thread_group(); } data.physics_process = p_process; if (_is_any_processing()) { _add_to_process_thread_group(); } } bool Node::is_physics_processing() const { return data.physics_process; } void Node::set_physics_process_internal(bool p_process_internal) { ERR_THREAD_GUARD if (data.physics_process_internal == p_process_internal) { return; } if (!is_inside_tree()) { data.physics_process_internal = p_process_internal; return; } if (_is_any_processing()) { _remove_from_process_thread_group(); } data.physics_process_internal = p_process_internal; if (_is_any_processing()) { _add_to_process_thread_group(); } } bool Node::is_physics_processing_internal() const { return data.physics_process_internal; } void Node::set_process_mode(ProcessMode p_mode) { ERR_THREAD_GUARD if (data.process_mode == p_mode) { return; } if (!is_inside_tree()) { data.process_mode = p_mode; return; } bool prev_can_process = can_process(); bool prev_enabled = _is_enabled(); if (p_mode == PROCESS_MODE_INHERIT) { if (data.parent) { data.process_owner = data.parent->data.process_owner; } else { ERR_FAIL_MSG("The root node can't be set to Inherit process mode."); } } else { data.process_owner = this; } data.process_mode = p_mode; bool next_can_process = can_process(); bool next_enabled = _is_enabled(); int pause_notification = 0; if (prev_can_process && !next_can_process) { pause_notification = NOTIFICATION_PAUSED; } else if (!prev_can_process && next_can_process) { pause_notification = NOTIFICATION_UNPAUSED; } int enabled_notification = 0; if (prev_enabled && !next_enabled) { enabled_notification = NOTIFICATION_DISABLED; } else if (!prev_enabled && next_enabled) { enabled_notification = NOTIFICATION_ENABLED; } _propagate_process_owner(data.process_owner, pause_notification, enabled_notification); #ifdef TOOLS_ENABLED // This is required for the editor to update the visibility of disabled nodes // It's very expensive during runtime to change, so editor-only if (Engine::get_singleton()->is_editor_hint()) { get_tree()->emit_signal(SNAME("tree_process_mode_changed")); } #endif } void Node::_propagate_pause_notification(bool p_enable) { bool prev_can_process = _can_process(!p_enable); bool next_can_process = _can_process(p_enable); if (prev_can_process && !next_can_process) { notification(NOTIFICATION_PAUSED); } else if (!prev_can_process && next_can_process) { notification(NOTIFICATION_UNPAUSED); } data.blocked++; for (KeyValue &K : data.children) { K.value->_propagate_pause_notification(p_enable); } data.blocked--; } Node::ProcessMode Node::get_process_mode() const { return data.process_mode; } void Node::_propagate_process_owner(Node *p_owner, int p_pause_notification, int p_enabled_notification) { data.process_owner = p_owner; if (p_pause_notification != 0) { notification(p_pause_notification); } if (p_enabled_notification != 0) { notification(p_enabled_notification); } data.blocked++; for (KeyValue &K : data.children) { Node *c = K.value; if (c->data.process_mode == PROCESS_MODE_INHERIT) { c->_propagate_process_owner(p_owner, p_pause_notification, p_enabled_notification); } } data.blocked--; } void Node::set_multiplayer_authority(int p_peer_id, bool p_recursive) { ERR_THREAD_GUARD data.multiplayer_authority = p_peer_id; if (p_recursive) { for (KeyValue &K : data.children) { K.value->set_multiplayer_authority(p_peer_id, true); } } } int Node::get_multiplayer_authority() const { return data.multiplayer_authority; } bool Node::is_multiplayer_authority() const { ERR_FAIL_COND_V(!is_inside_tree(), false); Ref api = get_multiplayer(); return api.is_valid() && (api->get_unique_id() == data.multiplayer_authority); } /***** RPC CONFIG ********/ void Node::rpc_config(const StringName &p_method, const Variant &p_config) { ERR_THREAD_GUARD if (data.rpc_config.get_type() != Variant::DICTIONARY) { data.rpc_config = Dictionary(); } Dictionary node_config = data.rpc_config; if (p_config.get_type() == Variant::NIL) { node_config.erase(p_method); } else { ERR_FAIL_COND(p_config.get_type() != Variant::DICTIONARY); node_config[p_method] = p_config; } } const Variant Node::get_node_rpc_config() const { return data.rpc_config; } /***** RPC FUNCTIONS ********/ Error Node::_rpc_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { if (p_argcount < 1) { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.expected = 1; return ERR_INVALID_PARAMETER; } Variant::Type type = p_args[0]->get_type(); if (type != Variant::STRING_NAME && type != Variant::STRING) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 0; r_error.expected = Variant::STRING_NAME; return ERR_INVALID_PARAMETER; } StringName method = (*p_args[0]).operator StringName(); Error err = rpcp(0, method, &p_args[1], p_argcount - 1); r_error.error = Callable::CallError::CALL_OK; return err; } Error Node::_rpc_id_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { if (p_argcount < 2) { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.expected = 2; return ERR_INVALID_PARAMETER; } if (p_args[0]->get_type() != Variant::INT) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 0; r_error.expected = Variant::INT; return ERR_INVALID_PARAMETER; } Variant::Type type = p_args[1]->get_type(); if (type != Variant::STRING_NAME && type != Variant::STRING) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 1; r_error.expected = Variant::STRING_NAME; return ERR_INVALID_PARAMETER; } int peer_id = *p_args[0]; StringName method = (*p_args[1]).operator StringName(); Error err = rpcp(peer_id, method, &p_args[2], p_argcount - 2); r_error.error = Callable::CallError::CALL_OK; return err; } Error Node::rpcp(int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) { ERR_FAIL_COND_V(!is_inside_tree(), ERR_UNCONFIGURED); Ref api = get_multiplayer(); if (api.is_null()) { return ERR_UNCONFIGURED; } return api->rpcp(this, p_peer_id, p_method, p_arg, p_argcount); } Ref Node::get_multiplayer() const { if (!is_inside_tree()) { return Ref(); } return get_tree()->get_multiplayer(get_path()); } //////////// end of rpc bool Node::can_process_notification(int p_what) const { switch (p_what) { case NOTIFICATION_PHYSICS_PROCESS: return data.physics_process; case NOTIFICATION_PROCESS: return data.process; case NOTIFICATION_INTERNAL_PROCESS: return data.process_internal; case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: return data.physics_process_internal; } return true; } bool Node::can_process() const { ERR_FAIL_COND_V(!is_inside_tree(), false); return _can_process(get_tree()->is_paused()); } bool Node::_can_process(bool p_paused) const { ProcessMode process_mode; if (data.process_mode == PROCESS_MODE_INHERIT) { if (!data.process_owner) { process_mode = PROCESS_MODE_PAUSABLE; } else { process_mode = data.process_owner->data.process_mode; } } else { process_mode = data.process_mode; } // The owner can't be set to inherit, must be a bug. ERR_FAIL_COND_V(process_mode == PROCESS_MODE_INHERIT, false); if (process_mode == PROCESS_MODE_DISABLED) { return false; } else if (process_mode == PROCESS_MODE_ALWAYS) { return true; } if (p_paused) { return process_mode == PROCESS_MODE_WHEN_PAUSED; } else { return process_mode == PROCESS_MODE_PAUSABLE; } } bool Node::_is_enabled() const { ProcessMode process_mode; if (data.process_mode == PROCESS_MODE_INHERIT) { if (!data.process_owner) { process_mode = PROCESS_MODE_PAUSABLE; } else { process_mode = data.process_owner->data.process_mode; } } else { process_mode = data.process_mode; } return (process_mode != PROCESS_MODE_DISABLED); } bool Node::is_enabled() const { ERR_FAIL_COND_V(!is_inside_tree(), false); return _is_enabled(); } double Node::get_physics_process_delta_time() const { if (data.tree) { return data.tree->get_physics_process_time(); } else { return 0; } } double Node::get_process_delta_time() const { if (data.tree) { return data.tree->get_process_time(); } else { return 0; } } void Node::set_process(bool p_process) { ERR_THREAD_GUARD if (data.process == p_process) { return; } if (!is_inside_tree()) { data.process = p_process; return; } if (_is_any_processing()) { _remove_from_process_thread_group(); } data.process = p_process; if (_is_any_processing()) { _add_to_process_thread_group(); } } bool Node::is_processing() const { return data.process; } void Node::set_process_internal(bool p_process_internal) { ERR_THREAD_GUARD if (data.process_internal == p_process_internal) { return; } if (!is_inside_tree()) { data.process_internal = p_process_internal; return; } if (_is_any_processing()) { _remove_from_process_thread_group(); } data.process_internal = p_process_internal; if (_is_any_processing()) { _add_to_process_thread_group(); } } void Node::_add_process_group() { get_tree()->_add_process_group(this); } void Node::_remove_process_group() { get_tree()->_remove_process_group(this); } void Node::_remove_from_process_thread_group() { get_tree()->_remove_node_from_process_group(this, data.process_thread_group_owner); } void Node::_add_to_process_thread_group() { get_tree()->_add_node_to_process_group(this, data.process_thread_group_owner); } void Node::_remove_tree_from_process_thread_group() { if (!is_inside_tree()) { return; // May not be initialized yet. } for (KeyValue &K : data.children) { if (K.value->data.process_thread_group != PROCESS_THREAD_GROUP_INHERIT) { continue; } K.value->_remove_tree_from_process_thread_group(); } if (_is_any_processing()) { _remove_from_process_thread_group(); } } void Node::_add_tree_to_process_thread_group(Node *p_owner) { if (_is_any_processing()) { _add_to_process_thread_group(); } data.process_thread_group_owner = p_owner; if (p_owner != nullptr) { data.process_group = p_owner->data.process_group; } else { data.process_group = &data.tree->default_process_group; } for (KeyValue &K : data.children) { if (K.value->data.process_thread_group != PROCESS_THREAD_GROUP_INHERIT) { continue; } K.value->_add_to_process_thread_group(); } } bool Node::is_processing_internal() const { return data.process_internal; } void Node::set_process_thread_group_order(int p_order) { ERR_THREAD_GUARD if (data.process_thread_group_order == p_order) { return; } data.process_thread_group_order = p_order; // Not yet in the tree (or not a group owner, in whose case this is pointless but harmless); trivial update. if (!is_inside_tree() || data.process_thread_group_owner != this) { return; } get_tree()->process_groups_dirty = true; } int Node::get_process_thread_group_order() const { return data.process_thread_group_order; } void Node::set_process_priority(int p_priority) { ERR_THREAD_GUARD if (data.process_priority == p_priority) { return; } if (!is_inside_tree()) { // Not yet in the tree; trivial update. data.process_priority = p_priority; return; } if (_is_any_processing()) { _remove_from_process_thread_group(); } data.process_priority = p_priority; if (_is_any_processing()) { _add_to_process_thread_group(); } } int Node::get_process_priority() const { return data.process_priority; } void Node::set_physics_process_priority(int p_priority) { ERR_THREAD_GUARD if (data.physics_process_priority == p_priority) { return; } if (!is_inside_tree()) { // Not yet in the tree; trivial update. data.physics_process_priority = p_priority; return; } if (_is_any_processing()) { _remove_from_process_thread_group(); } data.physics_process_priority = p_priority; if (_is_any_processing()) { _add_to_process_thread_group(); } } int Node::get_physics_process_priority() const { return data.physics_process_priority; } void Node::set_process_thread_group(ProcessThreadGroup p_mode) { ERR_FAIL_COND_MSG(data.inside_tree && !Thread::is_main_thread(), "Changing the process thread group can only be done from the main thread. Use call_deferred(\"set_process_thread_group\",mode)."); if (data.process_thread_group == p_mode) { return; } if (!is_inside_tree()) { // Not yet in the tree; trivial update. data.process_thread_group = p_mode; return; } _remove_tree_from_process_thread_group(); if (data.process_thread_group != PROCESS_THREAD_GROUP_INHERIT) { _remove_process_group(); } data.process_thread_group = p_mode; if (p_mode == PROCESS_THREAD_GROUP_INHERIT) { if (data.parent) { data.process_thread_group_owner = data.parent->data.process_thread_group_owner; } else { data.process_thread_group_owner = nullptr; } } else { data.process_thread_group_owner = this; _add_process_group(); } _add_tree_to_process_thread_group(data.process_thread_group_owner); notify_property_list_changed(); } Node::ProcessThreadGroup Node::get_process_thread_group() const { return data.process_thread_group; } void Node::set_process_thread_messages(BitField p_flags) { ERR_THREAD_GUARD if (data.process_thread_messages == p_flags) { return; } data.process_thread_messages = p_flags; } BitField Node::get_process_thread_messages() const { return data.process_thread_messages; } void Node::set_process_input(bool p_enable) { ERR_THREAD_GUARD if (p_enable == data.input) { return; } data.input = p_enable; if (!is_inside_tree()) { return; } if (p_enable) { add_to_group("_vp_input" + itos(get_viewport()->get_instance_id())); } else { remove_from_group("_vp_input" + itos(get_viewport()->get_instance_id())); } } bool Node::is_processing_input() const { return data.input; } void Node::set_process_shortcut_input(bool p_enable) { ERR_THREAD_GUARD if (p_enable == data.shortcut_input) { return; } data.shortcut_input = p_enable; if (!is_inside_tree()) { return; } if (p_enable) { add_to_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); } else { remove_from_group("_vp_shortcut_input" + itos(get_viewport()->get_instance_id())); } } bool Node::is_processing_shortcut_input() const { return data.shortcut_input; } void Node::set_process_unhandled_input(bool p_enable) { ERR_THREAD_GUARD if (p_enable == data.unhandled_input) { return; } data.unhandled_input = p_enable; if (!is_inside_tree()) { return; } if (p_enable) { add_to_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } else { remove_from_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_id())); } } bool Node::is_processing_unhandled_input() const { return data.unhandled_input; } void Node::set_process_unhandled_key_input(bool p_enable) { ERR_THREAD_GUARD if (p_enable == data.unhandled_key_input) { return; } data.unhandled_key_input = p_enable; if (!is_inside_tree()) { return; } if (p_enable) { add_to_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_id())); } else { remove_from_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_id())); } } bool Node::is_processing_unhandled_key_input() const { return data.unhandled_key_input; } StringName Node::get_name() const { return data.name; } void Node::_set_name_nocheck(const StringName &p_name) { data.name = p_name; } void Node::set_name(const String &p_name) { ERR_FAIL_COND_MSG(data.inside_tree && !Thread::is_main_thread(), "Changing the name to nodes inside the SceneTree is only allowed from the main thread. Use `set_name.call_deferred(new_name)`."); String name = p_name.validate_node_name(); ERR_FAIL_COND(name.is_empty()); if (data.unique_name_in_owner && data.owner) { _release_unique_name_in_owner(); } String old_name = data.name; data.name = name; if (data.parent) { data.parent->_validate_child_name(this, true); bool success = data.parent->data.children.replace_key(old_name, data.name); ERR_FAIL_COND_MSG(!success, "Renaming child in hashtable failed, this is a bug."); } if (data.unique_name_in_owner && data.owner) { _acquire_unique_name_in_owner(); } propagate_notification(NOTIFICATION_PATH_RENAMED); if (is_inside_tree()) { emit_signal(SNAME("renamed")); get_tree()->node_renamed(this); get_tree()->tree_changed(); } } // Returns a clear description of this node depending on what is available. Useful for error messages. String Node::get_description() const { String description; if (is_inside_tree()) { description = get_path(); } else { description = get_name(); if (description.is_empty()) { description = get_class(); } } return description; } static SafeRefCount node_hrcr_count; void Node::init_node_hrcr() { node_hrcr_count.init(1); } #ifdef TOOLS_ENABLED String Node::validate_child_name(Node *p_child) { StringName name = p_child->data.name; _generate_serial_child_name(p_child, name); return name; } #endif String Node::adjust_name_casing(const String &p_name) { switch (GLOBAL_GET("editor/naming/node_name_casing").operator int()) { case NAME_CASING_PASCAL_CASE: return p_name.to_pascal_case(); case NAME_CASING_CAMEL_CASE: return p_name.to_camel_case(); case NAME_CASING_SNAKE_CASE: return p_name.to_snake_case(); } return p_name; } void Node::_validate_child_name(Node *p_child, bool p_force_human_readable) { /* Make sure the name is unique */ if (p_force_human_readable) { //this approach to autoset node names is human readable but very slow StringName name = p_child->data.name; _generate_serial_child_name(p_child, name); p_child->data.name = name; } else { //this approach to autoset node names is fast but not as readable //it's the default and reserves the '@' character for unique names. bool unique = true; if (p_child->data.name == StringName()) { //new unique name must be assigned unique = false; } else { const Node *const *existing = data.children.getptr(p_child->data.name); unique = !existing || *existing == p_child; } if (!unique) { ERR_FAIL_COND(!node_hrcr_count.ref()); // Optimized version of the code below: // String name = "@" + String(p_child->get_name()) + "@" + itos(node_hrcr_count.get()); uint32_t c = node_hrcr_count.get(); String cn = p_child->get_class_name().operator String(); const char32_t *cn_ptr = cn.ptr(); uint32_t cn_length = cn.length(); uint32_t c_chars = String::num_characters(c); uint32_t len = 2 + cn_length + c_chars; char32_t *str = (char32_t *)alloca(sizeof(char32_t) * (len + 1)); uint32_t idx = 0; str[idx++] = '@'; for (uint32_t i = 0; i < cn_length; i++) { str[idx++] = cn_ptr[i]; } str[idx++] = '@'; idx += c_chars; ERR_FAIL_COND(idx != len); str[idx] = 0; while (c) { str[--idx] = '0' + (c % 10); c /= 10; } p_child->data.name = String(str); } } } // Return s + 1 as if it were an integer String increase_numeric_string(const String &s) { String res = s; bool carry = res.length() > 0; for (int i = res.length() - 1; i >= 0; i--) { if (!carry) { break; } char32_t n = s[i]; if (n == '9') { // keep carry as true: 9 + 1 res[i] = '0'; } else { res[i] = s[i] + 1; carry = false; } } if (carry) { res = "1" + res; } return res; } void Node::_generate_serial_child_name(const Node *p_child, StringName &name) const { if (name == StringName()) { // No name and a new name is needed, create one. name = p_child->get_class(); } const Node *const *existing = data.children.getptr(name); if (!existing || *existing == p_child) { // Unused, or is current node. return; } // Extract trailing number String name_string = name; String nums; for (int i = name_string.length() - 1; i >= 0; i--) { char32_t n = name_string[i]; if (is_digit(n)) { nums = String::chr(name_string[i]) + nums; } else { break; } } String nnsep = _get_name_num_separator(); int name_last_index = name_string.length() - nnsep.length() - nums.length(); // Assign the base name + separator to name if we have numbers preceded by a separator if (nums.length() > 0 && name_string.substr(name_last_index, nnsep.length()) == nnsep) { name_string = name_string.substr(0, name_last_index + nnsep.length()); } else { nums = ""; } for (;;) { StringName attempt = name_string + nums; existing = data.children.getptr(attempt); bool exists = existing != nullptr && *existing != p_child; if (!exists) { name = attempt; return; } else { if (nums.length() == 0) { // Name was undecorated so skip to 2 for a more natural result nums = "2"; name_string += nnsep; // Add separator because nums.length() > 0 was false } else { nums = increase_numeric_string(nums); } } } } Node::InternalMode Node::get_internal_mode() const { return data.internal_mode; } void Node::_add_child_nocheck(Node *p_child, const StringName &p_name, InternalMode p_internal_mode) { //add a child node quickly, without name validation p_child->data.name = p_name; data.children.insert(p_name, p_child); p_child->data.internal_mode = p_internal_mode; switch (p_internal_mode) { case INTERNAL_MODE_FRONT: { p_child->data.index = data.internal_children_front_count_cache++; } break; case INTERNAL_MODE_BACK: { p_child->data.index = data.internal_children_back_count_cache++; } break; case INTERNAL_MODE_DISABLED: { p_child->data.index = data.external_children_count_cache++; } break; } p_child->data.parent = this; if (!data.children_cache_dirty && p_internal_mode == INTERNAL_MODE_DISABLED && data.internal_children_back_count_cache == 0) { // Special case, also add to the cached children array since its cheap. data.children_cache.push_back(p_child); } else { data.children_cache_dirty = true; } p_child->notification(NOTIFICATION_PARENTED); if (data.tree) { p_child->_set_tree(data.tree); } /* Notify */ //recognize children created in this node constructor p_child->data.parent_owned = data.in_constructor; add_child_notify(p_child); notification(NOTIFICATION_CHILD_ORDER_CHANGED); emit_signal(SNAME("child_order_changed")); } void Node::add_child(Node *p_child, bool p_force_readable_name, InternalMode p_internal) { ERR_FAIL_COND_MSG(data.inside_tree && !Thread::is_main_thread(), "Adding children to a node inside the SceneTree is only allowed from the main thread. Use call_deferred(\"add_child\",node)."); ERR_THREAD_GUARD ERR_FAIL_NULL(p_child); ERR_FAIL_COND_MSG(p_child == this, vformat("Can't add child '%s' to itself.", p_child->get_name())); // adding to itself! ERR_FAIL_COND_MSG(p_child->data.parent, vformat("Can't add child '%s' to '%s', already has a parent '%s'.", p_child->get_name(), get_name(), p_child->data.parent->get_name())); //Fail if node has a parent #ifdef DEBUG_ENABLED ERR_FAIL_COND_MSG(p_child->is_ancestor_of(this), vformat("Can't add child '%s' to '%s' as it would result in a cyclic dependency since '%s' is already a parent of '%s'.", p_child->get_name(), get_name(), p_child->get_name(), get_name())); #endif ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy setting up children, `add_child()` failed. Consider using `add_child.call_deferred(child)` instead."); _validate_child_name(p_child, p_force_readable_name); _add_child_nocheck(p_child, p_child->data.name, p_internal); } void Node::add_sibling(Node *p_sibling, bool p_force_readable_name) { ERR_FAIL_COND_MSG(data.inside_tree && !Thread::is_main_thread(), "Adding a sibling to a node inside the SceneTree is only allowed from the main thread. Use call_deferred(\"add_sibling\",node)."); ERR_FAIL_NULL(p_sibling); ERR_FAIL_COND_MSG(p_sibling == this, vformat("Can't add sibling '%s' to itself.", p_sibling->get_name())); // adding to itself! ERR_FAIL_NULL(data.parent); ERR_FAIL_COND_MSG(data.parent->data.blocked > 0, "Parent node is busy setting up children, `add_sibling()` failed. Consider using `add_sibling.call_deferred(sibling)` instead."); data.parent->add_child(p_sibling, p_force_readable_name, data.internal_mode); data.parent->_update_children_cache(); data.parent->_move_child(p_sibling, get_index() + 1); } void Node::remove_child(Node *p_child) { ERR_FAIL_COND_MSG(data.inside_tree && !Thread::is_main_thread(), "Removing children from a node inside the SceneTree is only allowed from the main thread. Use call_deferred(\"remove_child\",node)."); ERR_FAIL_NULL(p_child); ERR_FAIL_COND_MSG(data.blocked > 0, "Parent node is busy adding/removing children, `remove_child()` can't be called at this time. Consider using `remove_child.call_deferred(child)` instead."); ERR_FAIL_COND(p_child->data.parent != this); /** * Do not change the data.internal_children*cache counters here. * Because if nodes are re-added, the indices can remain * greater-than-everything indices and children added remain * properly ordered. * * All children indices and counters will be updated next time the * cache is re-generated. */ data.blocked++; p_child->_set_tree(nullptr); //} remove_child_notify(p_child); p_child->notification(NOTIFICATION_UNPARENTED); data.blocked--; data.children_cache_dirty = true; bool success = data.children.erase(p_child->data.name); ERR_FAIL_COND_MSG(!success, "Children name does not match parent name in hashtable, this is a bug."); p_child->data.parent = nullptr; p_child->data.index = -1; notification(NOTIFICATION_CHILD_ORDER_CHANGED); emit_signal(SNAME("child_order_changed")); if (data.inside_tree) { p_child->_propagate_after_exit_tree(); } } void Node::_update_children_cache_impl() const { // Assign children data.children_cache.resize(data.children.size()); int idx = 0; for (const KeyValue &K : data.children) { data.children_cache[idx] = K.value; idx++; } // Sort them data.children_cache.sort_custom(); // Update indices data.external_children_count_cache = 0; data.internal_children_back_count_cache = 0; data.internal_children_front_count_cache = 0; for (uint32_t i = 0; i < data.children_cache.size(); i++) { switch (data.children_cache[i]->data.internal_mode) { case INTERNAL_MODE_DISABLED: { data.children_cache[i]->data.index = data.external_children_count_cache++; } break; case INTERNAL_MODE_FRONT: { data.children_cache[i]->data.index = data.internal_children_front_count_cache++; } break; case INTERNAL_MODE_BACK: { data.children_cache[i]->data.index = data.internal_children_back_count_cache++; } break; } } data.children_cache_dirty = false; } int Node::get_child_count(bool p_include_internal) const { ERR_THREAD_GUARD_V(0); _update_children_cache(); if (p_include_internal) { return data.children_cache.size(); } else { return data.children_cache.size() - data.internal_children_front_count_cache - data.internal_children_back_count_cache; } } Node *Node::get_child(int p_index, bool p_include_internal) const { ERR_THREAD_GUARD_V(nullptr); _update_children_cache(); if (p_include_internal) { if (p_index < 0) { p_index += data.children_cache.size(); } ERR_FAIL_INDEX_V(p_index, (int)data.children_cache.size(), nullptr); return data.children_cache[p_index]; } else { if (p_index < 0) { p_index += (int)data.children_cache.size() - data.internal_children_front_count_cache - data.internal_children_back_count_cache; } ERR_FAIL_INDEX_V(p_index, (int)data.children_cache.size() - data.internal_children_front_count_cache - data.internal_children_back_count_cache, nullptr); p_index += data.internal_children_front_count_cache; return data.children_cache[p_index]; } } TypedArray Node::get_children(bool p_include_internal) const { ERR_THREAD_GUARD_V(TypedArray()); TypedArray arr; int cc = get_child_count(p_include_internal); arr.resize(cc); for (int i = 0; i < cc; i++) { arr[i] = get_child(i, p_include_internal); } return arr; } Node *Node::_get_child_by_name(const StringName &p_name) const { const Node *const *node = data.children.getptr(p_name); if (node) { return const_cast(*node); } else { return nullptr; } } Node *Node::get_node_or_null(const NodePath &p_path) const { ERR_THREAD_GUARD_V(nullptr); if (p_path.is_empty()) { return nullptr; } ERR_FAIL_COND_V_MSG(!data.inside_tree && p_path.is_absolute(), nullptr, "Can't use get_node() with absolute paths from outside the active scene tree."); Node *current = nullptr; Node *root = nullptr; if (!p_path.is_absolute()) { current = const_cast(this); //start from this } else { root = const_cast(this); while (root->data.parent) { root = root->data.parent; //start from root } } for (int i = 0; i < p_path.get_name_count(); i++) { StringName name = p_path.get_name(i); Node *next = nullptr; if (name == SceneStringNames::get_singleton()->dot) { // . next = current; } else if (name == SceneStringNames::get_singleton()->doubledot) { // .. if (current == nullptr || !current->data.parent) { return nullptr; } next = current->data.parent; } else if (current == nullptr) { if (name == root->get_name()) { next = root; } } else if (name.is_node_unique_name()) { if (current->data.owned_unique_nodes.size()) { // Has unique nodes in ownership Node **unique = current->data.owned_unique_nodes.getptr(name); if (!unique) { return nullptr; } next = *unique; } else if (current->data.owner) { Node **unique = current->data.owner->data.owned_unique_nodes.getptr(name); if (!unique) { return nullptr; } next = *unique; } else { return nullptr; } } else { next = nullptr; const Node *const *node = current->data.children.getptr(name); if (node) { next = const_cast(*node); } else { return nullptr; } } current = next; } return current; } Node *Node::get_node(const NodePath &p_path) const { Node *node = get_node_or_null(p_path); if (unlikely(!node)) { const String desc = get_description(); if (p_path.is_absolute()) { ERR_FAIL_V_MSG(nullptr, vformat(R"(Node not found: "%s" (absolute path attempted from "%s").)", p_path, desc)); } else { ERR_FAIL_V_MSG(nullptr, vformat(R"(Node not found: "%s" (relative to "%s").)", p_path, desc)); } } return node; } bool Node::has_node(const NodePath &p_path) const { return get_node_or_null(p_path) != nullptr; } // Finds the first child node (in tree order) whose name matches the given pattern. // Can be recursive or not, and limited to owned nodes. Node *Node::find_child(const String &p_pattern, bool p_recursive, bool p_owned) const { ERR_THREAD_GUARD_V(nullptr); ERR_FAIL_COND_V(p_pattern.is_empty(), nullptr); _update_children_cache(); Node *const *cptr = data.children_cache.ptr(); int ccount = data.children_cache.size(); for (int i = 0; i < ccount; i++) { if (p_owned && !cptr[i]->data.owner) { continue; } if (cptr[i]->data.name.operator String().match(p_pattern)) { return cptr[i]; } if (!p_recursive) { continue; } Node *ret = cptr[i]->find_child(p_pattern, true, p_owned); if (ret) { return ret; } } return nullptr; } // Finds child nodes based on their name using pattern matching, or class name, // or both (either pattern or type can be left empty). // Can be recursive or not, and limited to owned nodes. TypedArray Node::find_children(const String &p_pattern, const String &p_type, bool p_recursive, bool p_owned) const { ERR_THREAD_GUARD_V(TypedArray()); TypedArray ret; ERR_FAIL_COND_V(p_pattern.is_empty() && p_type.is_empty(), ret); _update_children_cache(); Node *const *cptr = data.children_cache.ptr(); int ccount = data.children_cache.size(); for (int i = 0; i < ccount; i++) { if (p_owned && !cptr[i]->data.owner) { continue; } if (p_pattern.is_empty() || cptr[i]->data.name.operator String().match(p_pattern)) { if (p_type.is_empty() || cptr[i]->is_class(p_type)) { ret.append(cptr[i]); } else if (cptr[i]->get_script_instance()) { Ref