Path: blob/master/modules/multiplayer/multiplayer_spawner.cpp
10277 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 "scene/main/multiplayer_api.h"3334#ifdef TOOLS_ENABLED35/* This is editor only */36bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {37if (p_name == "_spawnable_scene_count") {38spawnable_scenes.resize(p_value);39notify_property_list_changed();40return true;41} else {42String ns = p_name;43if (ns.begins_with("scenes/")) {44uint32_t index = ns.get_slicec('/', 1).to_int();45ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);46spawnable_scenes[index].path = ResourceUID::ensure_path(p_value);47return true;48}49}50return false;51}5253bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {54if (p_name == "_spawnable_scene_count") {55r_ret = spawnable_scenes.size();56return true;57} else {58String ns = p_name;59if (ns.begins_with("scenes/")) {60uint32_t index = ns.get_slicec('/', 1).to_int();61ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);62r_ret = ResourceUID::path_to_uid(spawnable_scenes[index].path);63return true;64}65}66return false;67}6869void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {70p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));71List<String> exts;72ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);73String ext_hint;74for (const String &E : exts) {75if (!ext_hint.is_empty()) {76ext_hint += ",";77}78ext_hint += "*." + E;79}80for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {81p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));82}83}84#endif8586PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {87PackedStringArray warnings = Node::get_configuration_warnings();8889if (spawn_path.is_empty() || !has_node(spawn_path)) {90warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes."));91}92return warnings;93}9495void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {96SpawnableScene sc;97sc.path = ResourceUID::ensure_path(p_path);98if (Engine::get_singleton()->is_editor_hint()) {99ERR_FAIL_COND(!ResourceLoader::exists(sc.path));100}101spawnable_scenes.push_back(sc);102#ifdef TOOLS_ENABLED103if (Engine::get_singleton()->is_editor_hint()) {104return;105}106#endif107Node *node = get_spawn_node();108if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {109node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));110}111}112113int MultiplayerSpawner::get_spawnable_scene_count() const {114return spawnable_scenes.size();115}116117String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {118ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");119return spawnable_scenes[p_idx].path;120}121122void MultiplayerSpawner::clear_spawnable_scenes() {123spawnable_scenes.clear();124#ifdef TOOLS_ENABLED125if (Engine::get_singleton()->is_editor_hint()) {126return;127}128#endif129Node *node = get_spawn_node();130if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {131node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));132}133}134135Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {136Vector<String> ss;137ss.resize(spawnable_scenes.size());138for (int i = 0; i < ss.size(); i++) {139ss.write[i] = ResourceUID::path_to_uid(spawnable_scenes[i].path);140}141return ss;142}143144void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {145clear_spawnable_scenes();146for (int i = 0; i < p_scenes.size(); i++) {147add_spawnable_scene(p_scenes[i]);148}149}150151void MultiplayerSpawner::_bind_methods() {152ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);153ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);154ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);155ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);156157ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);158ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);159160ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");161162ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));163164ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);165ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);166ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");167168ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);169ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);170ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");171172ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);173ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);174ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");175176ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));177ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));178}179180void MultiplayerSpawner::_update_spawn_node() {181#ifdef TOOLS_ENABLED182if (Engine::get_singleton()->is_editor_hint()) {183return;184}185#endif186if (spawn_node.is_valid()) {187Node *node = ObjectDB::get_instance<Node>(spawn_node);188if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {189node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));190}191}192Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);193if (node) {194spawn_node = node->get_instance_id();195if (get_spawnable_scene_count()) {196node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));197}198} else {199spawn_node = ObjectID();200}201}202203void MultiplayerSpawner::_notification(int p_what) {204switch (p_what) {205case NOTIFICATION_POST_ENTER_TREE: {206_update_spawn_node();207} break;208209case NOTIFICATION_EXIT_TREE: {210_update_spawn_node();211212for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {213Node *node = ObjectDB::get_instance<Node>(E.key);214ERR_CONTINUE(!node);215node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit));216get_multiplayer()->object_configuration_remove(node, this);217}218tracked_nodes.clear();219} break;220}221}222223void MultiplayerSpawner::_node_added(Node *p_node) {224if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {225return;226}227if (tracked_nodes.has(p_node->get_instance_id())) {228return;229}230const Node *parent = get_spawn_node();231if (!parent || p_node->get_parent() != parent) {232return;233}234int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());235if (id == INVALID_ID) {236return;237}238const String name = p_node->get_name();239ERR_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));240_track(p_node, Variant(), id);241}242243NodePath MultiplayerSpawner::get_spawn_path() const {244return spawn_path;245}246247void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {248spawn_path = p_path;249_update_spawn_node();250update_configuration_warnings();251}252253void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {254ObjectID oid = p_node->get_instance_id();255if (!tracked_nodes.has(oid)) {256tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);257p_node->connect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);258_spawn_notify(p_node->get_instance_id());259}260}261262void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {263get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);264}265266void MultiplayerSpawner::_node_exit(ObjectID p_id) {267Node *node = ObjectDB::get_instance<Node>(p_id);268ERR_FAIL_NULL(node);269if (tracked_nodes.has(p_id)) {270tracked_nodes.erase(p_id);271get_multiplayer()->object_configuration_remove(node, this);272}273}274275int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {276for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {277if (spawnable_scenes[i].path == p_scene) {278return i;279}280}281return INVALID_ID;282}283284int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {285const SpawnInfo *info = tracked_nodes.getptr(p_id);286return info ? info->id : INVALID_ID;287}288289const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {290const SpawnInfo *info = tracked_nodes.getptr(p_id);291return info ? info->args : Variant();292}293294Node *MultiplayerSpawner::instantiate_scene(int p_id) {295ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");296ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);297SpawnableScene &sc = spawnable_scenes[p_id];298if (sc.cache.is_null()) {299sc.cache = ResourceLoader::load(sc.path);300}301ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);302return sc.cache->instantiate();303}304305Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {306ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");307ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");308const Variant *argv[1] = { &p_data };309Variant ret;310Callable::CallError ce;311spawn_function.callp(argv, 1, ret, ce);312ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");313ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");314return Object::cast_to<Node>(ret.operator Object *());315}316317Node *MultiplayerSpawner::spawn(const Variant &p_data) {318ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);319ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");320ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");321322Node *parent = get_spawn_node();323ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");324325Node *node = instantiate_custom(p_data);326ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");327328_track(node, p_data);329parent->add_child(node, true);330return node;331}332333334