Path: blob/master/modules/multiplayer/multiplayer_spawner.cpp
20920 views
/**************************************************************************/1/* multiplayer_spawner.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "multiplayer_spawner.h"3132#include "core/io/resource_loader.h"33#include "scene/main/multiplayer_api.h"3435#ifdef TOOLS_ENABLED36/* This is editor only */37bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {38if (p_name == "_spawnable_scene_count") {39spawnable_scenes.resize(p_value);40notify_property_list_changed();41return true;42} else {43String ns = p_name;44if (ns.begins_with("scenes/")) {45uint32_t index = ns.get_slicec('/', 1).to_int();46ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);47spawnable_scenes[index].path = ResourceUID::ensure_path(p_value);48return true;49}50}51return false;52}5354bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {55if (p_name == "_spawnable_scene_count") {56r_ret = spawnable_scenes.size();57return true;58} else {59String ns = p_name;60if (ns.begins_with("scenes/")) {61uint32_t index = ns.get_slicec('/', 1).to_int();62ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);63r_ret = ResourceUID::path_to_uid(spawnable_scenes[index].path);64return true;65}66}67return false;68}6970void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {71p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));72List<String> exts;73ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);74String ext_hint;75for (const String &E : exts) {76if (!ext_hint.is_empty()) {77ext_hint += ",";78}79ext_hint += "*." + E;80}81for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {82p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));83}84}85#endif8687PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {88PackedStringArray warnings = Node::get_configuration_warnings();8990if (spawn_path.is_empty() || !has_node(spawn_path)) {91warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes."));92}93return warnings;94}9596void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {97SpawnableScene sc;98sc.path = ResourceUID::ensure_path(p_path);99if (Engine::get_singleton()->is_editor_hint()) {100ERR_FAIL_COND(!ResourceLoader::exists(sc.path));101}102spawnable_scenes.push_back(sc);103#ifdef TOOLS_ENABLED104if (Engine::get_singleton()->is_editor_hint()) {105return;106}107#endif108Node *node = get_spawn_node();109if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {110node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));111}112}113114int MultiplayerSpawner::get_spawnable_scene_count() const {115return spawnable_scenes.size();116}117118String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {119ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");120return spawnable_scenes[p_idx].path;121}122123void MultiplayerSpawner::clear_spawnable_scenes() {124spawnable_scenes.clear();125#ifdef TOOLS_ENABLED126if (Engine::get_singleton()->is_editor_hint()) {127return;128}129#endif130Node *node = get_spawn_node();131if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {132node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));133}134}135136Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {137Vector<String> ss;138ss.resize(spawnable_scenes.size());139for (int i = 0; i < ss.size(); i++) {140ss.write[i] = ResourceUID::path_to_uid(spawnable_scenes[i].path);141}142return ss;143}144145void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {146clear_spawnable_scenes();147for (int i = 0; i < p_scenes.size(); i++) {148add_spawnable_scene(p_scenes[i]);149}150}151152void MultiplayerSpawner::_bind_methods() {153ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);154ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);155ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);156ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);157158ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);159ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);160161ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");162163ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));164165ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);166ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);167ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");168169ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);170ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);171ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");172173ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);174ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);175ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");176177ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, Node::get_class_static())));178ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, Node::get_class_static())));179}180181void MultiplayerSpawner::_update_spawn_node() {182#ifdef TOOLS_ENABLED183if (Engine::get_singleton()->is_editor_hint()) {184return;185}186#endif187if (spawn_node.is_valid()) {188Node *node = ObjectDB::get_instance<Node>(spawn_node);189if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {190node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));191}192}193Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);194if (node) {195spawn_node = node->get_instance_id();196if (get_spawnable_scene_count()) {197node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));198}199} else {200spawn_node = ObjectID();201}202}203204void MultiplayerSpawner::_notification(int p_what) {205switch (p_what) {206case NOTIFICATION_POST_ENTER_TREE: {207_update_spawn_node();208} break;209210case NOTIFICATION_EXIT_TREE: {211_update_spawn_node();212213for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {214Node *node = ObjectDB::get_instance<Node>(E.key);215ERR_CONTINUE(!node);216node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit));217get_multiplayer()->object_configuration_remove(node, this);218}219tracked_nodes.clear();220} break;221}222}223224void MultiplayerSpawner::_node_added(Node *p_node) {225if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {226return;227}228if (tracked_nodes.has(p_node->get_instance_id())) {229return;230}231const Node *parent = get_spawn_node();232if (!parent || p_node->get_parent() != parent) {233return;234}235int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());236if (id == INVALID_ID) {237return;238}239const String name = p_node->get_name();240ERR_FAIL_COND_MSG(name.validate_node_name() != name, vformat("Unable to auto-spawn node with reserved name: %s. Make sure to add your replicated scenes via 'add_child(node, true)' to produce valid names.", name));241_track(p_node, Variant(), id);242}243244NodePath MultiplayerSpawner::get_spawn_path() const {245return spawn_path;246}247248void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {249spawn_path = p_path;250_update_spawn_node();251update_configuration_warnings();252}253254void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {255ObjectID oid = p_node->get_instance_id();256if (!tracked_nodes.has(oid)) {257tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);258p_node->connect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);259_spawn_notify(p_node->get_instance_id());260}261}262263void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {264get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);265}266267void MultiplayerSpawner::_node_exit(ObjectID p_id) {268Node *node = ObjectDB::get_instance<Node>(p_id);269ERR_FAIL_NULL(node);270if (tracked_nodes.has(p_id)) {271tracked_nodes.erase(p_id);272get_multiplayer()->object_configuration_remove(node, this);273}274}275276int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {277for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {278if (spawnable_scenes[i].path == p_scene) {279return i;280}281}282return INVALID_ID;283}284285int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {286const SpawnInfo *info = tracked_nodes.getptr(p_id);287return info ? info->id : INVALID_ID;288}289290const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {291const SpawnInfo *info = tracked_nodes.getptr(p_id);292return info ? info->args : Variant();293}294295Node *MultiplayerSpawner::instantiate_scene(int p_id) {296ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");297ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);298SpawnableScene &sc = spawnable_scenes[p_id];299if (sc.cache.is_null()) {300sc.cache = ResourceLoader::load(sc.path);301}302ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);303return sc.cache->instantiate();304}305306Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {307ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");308ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");309const Variant *argv[1] = { &p_data };310Variant ret;311Callable::CallError ce;312spawn_function.callp(argv, 1, ret, ce);313ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");314ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");315return Object::cast_to<Node>(ret.operator Object *());316}317318Node *MultiplayerSpawner::spawn(const Variant &p_data) {319ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);320ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");321ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");322323Node *parent = get_spawn_node();324ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");325326Node *node = instantiate_custom(p_data);327ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");328329_track(node, p_data);330parent->add_child(node, true);331return node;332}333334335