multiplayer_spawner.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /**************************************************************************/
  2. /* multiplayer_spawner.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "multiplayer_spawner.h"
  31. #include "core/io/marshalls.h"
  32. #include "scene/main/multiplayer_api.h"
  33. #include "scene/main/window.h"
  34. #include "scene/scene_string_names.h"
  35. #ifdef TOOLS_ENABLED
  36. /* This is editor only */
  37. bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {
  38. if (p_name == "_spawnable_scene_count") {
  39. spawnable_scenes.resize(p_value);
  40. notify_property_list_changed();
  41. return true;
  42. } else {
  43. String ns = p_name;
  44. if (ns.begins_with("scenes/")) {
  45. uint32_t index = ns.get_slicec('/', 1).to_int();
  46. ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
  47. spawnable_scenes[index].path = p_value;
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {
  54. if (p_name == "_spawnable_scene_count") {
  55. r_ret = spawnable_scenes.size();
  56. return true;
  57. } else {
  58. String ns = p_name;
  59. if (ns.begins_with("scenes/")) {
  60. uint32_t index = ns.get_slicec('/', 1).to_int();
  61. ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
  62. r_ret = spawnable_scenes[index].path;
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {
  69. p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));
  70. List<String> exts;
  71. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);
  72. String ext_hint;
  73. for (const String &E : exts) {
  74. if (!ext_hint.is_empty()) {
  75. ext_hint += ",";
  76. }
  77. ext_hint += "*." + E;
  78. }
  79. for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
  80. p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));
  81. }
  82. }
  83. #endif
  84. PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {
  85. PackedStringArray warnings = Node::get_configuration_warnings();
  86. if (spawn_path.is_empty() || !has_node(spawn_path)) {
  87. warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes."));
  88. }
  89. return warnings;
  90. }
  91. void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {
  92. SpawnableScene sc;
  93. sc.path = p_path;
  94. if (Engine::get_singleton()->is_editor_hint()) {
  95. ERR_FAIL_COND(!FileAccess::exists(p_path));
  96. }
  97. spawnable_scenes.push_back(sc);
  98. #ifdef TOOLS_ENABLED
  99. if (Engine::get_singleton()->is_editor_hint()) {
  100. return;
  101. }
  102. #endif
  103. Node *node = get_spawn_node();
  104. if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  105. node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  106. }
  107. }
  108. int MultiplayerSpawner::get_spawnable_scene_count() const {
  109. return spawnable_scenes.size();
  110. }
  111. String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {
  112. ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");
  113. return spawnable_scenes[p_idx].path;
  114. }
  115. void MultiplayerSpawner::clear_spawnable_scenes() {
  116. spawnable_scenes.clear();
  117. #ifdef TOOLS_ENABLED
  118. if (Engine::get_singleton()->is_editor_hint()) {
  119. return;
  120. }
  121. #endif
  122. Node *node = get_spawn_node();
  123. if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  124. node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  125. }
  126. }
  127. Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {
  128. Vector<String> ss;
  129. ss.resize(spawnable_scenes.size());
  130. for (int i = 0; i < ss.size(); i++) {
  131. ss.write[i] = spawnable_scenes[i].path;
  132. }
  133. return ss;
  134. }
  135. void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {
  136. clear_spawnable_scenes();
  137. for (int i = 0; i < p_scenes.size(); i++) {
  138. add_spawnable_scene(p_scenes[i]);
  139. }
  140. }
  141. void MultiplayerSpawner::_bind_methods() {
  142. ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);
  143. ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);
  144. ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);
  145. ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);
  146. ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);
  147. ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);
  148. ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");
  149. ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));
  150. ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);
  151. ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);
  152. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");
  153. ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);
  154. ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);
  155. ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");
  156. ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);
  157. ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);
  158. ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");
  159. ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  160. ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  161. }
  162. void MultiplayerSpawner::_update_spawn_node() {
  163. #ifdef TOOLS_ENABLED
  164. if (Engine::get_singleton()->is_editor_hint()) {
  165. return;
  166. }
  167. #endif
  168. if (spawn_node.is_valid()) {
  169. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(spawn_node));
  170. if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  171. node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  172. }
  173. }
  174. Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);
  175. if (node) {
  176. spawn_node = node->get_instance_id();
  177. if (get_spawnable_scene_count()) {
  178. node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  179. }
  180. } else {
  181. spawn_node = ObjectID();
  182. }
  183. }
  184. void MultiplayerSpawner::_notification(int p_what) {
  185. switch (p_what) {
  186. case NOTIFICATION_POST_ENTER_TREE: {
  187. _update_spawn_node();
  188. } break;
  189. case NOTIFICATION_EXIT_TREE: {
  190. _update_spawn_node();
  191. for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {
  192. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(E.key));
  193. ERR_CONTINUE(!node);
  194. node->disconnect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &MultiplayerSpawner::_node_exit));
  195. get_multiplayer()->object_configuration_remove(node, this);
  196. }
  197. tracked_nodes.clear();
  198. } break;
  199. }
  200. }
  201. void MultiplayerSpawner::_node_added(Node *p_node) {
  202. if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {
  203. return;
  204. }
  205. if (tracked_nodes.has(p_node->get_instance_id())) {
  206. return;
  207. }
  208. const Node *parent = get_spawn_node();
  209. if (!parent || p_node->get_parent() != parent) {
  210. return;
  211. }
  212. int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());
  213. if (id == INVALID_ID) {
  214. return;
  215. }
  216. const String name = p_node->get_name();
  217. ERR_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));
  218. _track(p_node, Variant(), id);
  219. }
  220. NodePath MultiplayerSpawner::get_spawn_path() const {
  221. return spawn_path;
  222. }
  223. void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {
  224. spawn_path = p_path;
  225. _update_spawn_node();
  226. update_configuration_warnings();
  227. }
  228. void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {
  229. ObjectID oid = p_node->get_instance_id();
  230. if (!tracked_nodes.has(oid)) {
  231. tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);
  232. p_node->connect(SceneStringNames::get_singleton()->tree_exiting, callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);
  233. _spawn_notify(p_node->get_instance_id());
  234. }
  235. }
  236. void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {
  237. get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);
  238. }
  239. void MultiplayerSpawner::_node_exit(ObjectID p_id) {
  240. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(p_id));
  241. ERR_FAIL_NULL(node);
  242. if (tracked_nodes.has(p_id)) {
  243. tracked_nodes.erase(p_id);
  244. get_multiplayer()->object_configuration_remove(node, this);
  245. }
  246. }
  247. int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {
  248. for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
  249. if (spawnable_scenes[i].path == p_scene) {
  250. return i;
  251. }
  252. }
  253. return INVALID_ID;
  254. }
  255. int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {
  256. const SpawnInfo *info = tracked_nodes.getptr(p_id);
  257. return info ? info->id : INVALID_ID;
  258. }
  259. const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {
  260. const SpawnInfo *info = tracked_nodes.getptr(p_id);
  261. return info ? info->args : Variant();
  262. }
  263. Node *MultiplayerSpawner::instantiate_scene(int p_id) {
  264. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  265. ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);
  266. SpawnableScene &sc = spawnable_scenes[p_id];
  267. if (sc.cache.is_null()) {
  268. sc.cache = ResourceLoader::load(sc.path);
  269. }
  270. ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);
  271. return sc.cache->instantiate();
  272. }
  273. Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {
  274. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  275. ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");
  276. const Variant *argv[1] = { &p_data };
  277. Variant ret;
  278. Callable::CallError ce;
  279. spawn_function.callp(argv, 1, ret, ce);
  280. ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");
  281. ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");
  282. return Object::cast_to<Node>(ret.operator Object *());
  283. }
  284. Node *MultiplayerSpawner::spawn(const Variant &p_data) {
  285. ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);
  286. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  287. ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");
  288. Node *parent = get_spawn_node();
  289. ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");
  290. Node *node = instantiate_custom(p_data);
  291. ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");
  292. _track(node, p_data);
  293. parent->add_child(node, true);
  294. return node;
  295. }