multiplayer_spawner.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. #ifdef TOOLS_ENABLED
  35. /* This is editor only */
  36. bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {
  37. if (p_name == "_spawnable_scene_count") {
  38. spawnable_scenes.resize(p_value);
  39. notify_property_list_changed();
  40. return true;
  41. } else {
  42. String ns = p_name;
  43. if (ns.begins_with("scenes/")) {
  44. uint32_t index = ns.get_slicec('/', 1).to_int();
  45. ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
  46. spawnable_scenes[index].path = p_value;
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {
  53. if (p_name == "_spawnable_scene_count") {
  54. r_ret = spawnable_scenes.size();
  55. return true;
  56. } else {
  57. String ns = p_name;
  58. if (ns.begins_with("scenes/")) {
  59. uint32_t index = ns.get_slicec('/', 1).to_int();
  60. ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
  61. r_ret = spawnable_scenes[index].path;
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {
  68. p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));
  69. List<String> exts;
  70. ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);
  71. String ext_hint;
  72. for (const String &E : exts) {
  73. if (!ext_hint.is_empty()) {
  74. ext_hint += ",";
  75. }
  76. ext_hint += "*." + E;
  77. }
  78. for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
  79. p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));
  80. }
  81. }
  82. #endif
  83. PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {
  84. PackedStringArray warnings = Node::get_configuration_warnings();
  85. if (spawn_path.is_empty() || !has_node(spawn_path)) {
  86. 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."));
  87. }
  88. return warnings;
  89. }
  90. void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {
  91. SpawnableScene sc;
  92. if (p_path.begins_with("uid://")) {
  93. sc.uid = p_path;
  94. sc.path = ResourceUID::uid_to_path(p_path);
  95. } else {
  96. sc.uid = ResourceUID::path_to_uid(p_path);
  97. sc.path = p_path;
  98. }
  99. if (Engine::get_singleton()->is_editor_hint()) {
  100. ERR_FAIL_COND(!ResourceLoader::exists(p_path));
  101. }
  102. spawnable_scenes.push_back(sc);
  103. #ifdef TOOLS_ENABLED
  104. if (Engine::get_singleton()->is_editor_hint()) {
  105. return;
  106. }
  107. #endif
  108. Node *node = get_spawn_node();
  109. if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  110. node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  111. }
  112. }
  113. int MultiplayerSpawner::get_spawnable_scene_count() const {
  114. return spawnable_scenes.size();
  115. }
  116. String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {
  117. ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");
  118. return spawnable_scenes[p_idx].path;
  119. }
  120. void MultiplayerSpawner::clear_spawnable_scenes() {
  121. spawnable_scenes.clear();
  122. #ifdef TOOLS_ENABLED
  123. if (Engine::get_singleton()->is_editor_hint()) {
  124. return;
  125. }
  126. #endif
  127. Node *node = get_spawn_node();
  128. if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  129. node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  130. }
  131. }
  132. Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {
  133. Vector<String> ss;
  134. ss.resize(spawnable_scenes.size());
  135. for (int i = 0; i < ss.size(); i++) {
  136. ss.write[i] = spawnable_scenes[i].uid;
  137. }
  138. return ss;
  139. }
  140. void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {
  141. clear_spawnable_scenes();
  142. for (int i = 0; i < p_scenes.size(); i++) {
  143. add_spawnable_scene(p_scenes[i]);
  144. }
  145. }
  146. void MultiplayerSpawner::_bind_methods() {
  147. ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);
  148. ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);
  149. ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);
  150. ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);
  151. ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);
  152. ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);
  153. ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");
  154. ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));
  155. ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);
  156. ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);
  157. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");
  158. ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);
  159. ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);
  160. ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");
  161. ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);
  162. ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);
  163. ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");
  164. ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  165. ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  166. }
  167. void MultiplayerSpawner::_update_spawn_node() {
  168. #ifdef TOOLS_ENABLED
  169. if (Engine::get_singleton()->is_editor_hint()) {
  170. return;
  171. }
  172. #endif
  173. if (spawn_node.is_valid()) {
  174. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(spawn_node));
  175. if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
  176. node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  177. }
  178. }
  179. Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);
  180. if (node) {
  181. spawn_node = node->get_instance_id();
  182. if (get_spawnable_scene_count()) {
  183. node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
  184. }
  185. } else {
  186. spawn_node = ObjectID();
  187. }
  188. }
  189. void MultiplayerSpawner::_notification(int p_what) {
  190. switch (p_what) {
  191. case NOTIFICATION_POST_ENTER_TREE: {
  192. _update_spawn_node();
  193. } break;
  194. case NOTIFICATION_EXIT_TREE: {
  195. _update_spawn_node();
  196. for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {
  197. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(E.key));
  198. ERR_CONTINUE(!node);
  199. node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit));
  200. get_multiplayer()->object_configuration_remove(node, this);
  201. }
  202. tracked_nodes.clear();
  203. } break;
  204. }
  205. }
  206. void MultiplayerSpawner::_node_added(Node *p_node) {
  207. if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {
  208. return;
  209. }
  210. if (tracked_nodes.has(p_node->get_instance_id())) {
  211. return;
  212. }
  213. const Node *parent = get_spawn_node();
  214. if (!parent || p_node->get_parent() != parent) {
  215. return;
  216. }
  217. int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());
  218. if (id == INVALID_ID) {
  219. return;
  220. }
  221. const String name = p_node->get_name();
  222. 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));
  223. _track(p_node, Variant(), id);
  224. }
  225. NodePath MultiplayerSpawner::get_spawn_path() const {
  226. return spawn_path;
  227. }
  228. void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {
  229. spawn_path = p_path;
  230. _update_spawn_node();
  231. update_configuration_warnings();
  232. }
  233. void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {
  234. ObjectID oid = p_node->get_instance_id();
  235. if (!tracked_nodes.has(oid)) {
  236. tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);
  237. p_node->connect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);
  238. _spawn_notify(p_node->get_instance_id());
  239. }
  240. }
  241. void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {
  242. get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);
  243. }
  244. void MultiplayerSpawner::_node_exit(ObjectID p_id) {
  245. Node *node = Object::cast_to<Node>(ObjectDB::get_instance(p_id));
  246. ERR_FAIL_NULL(node);
  247. if (tracked_nodes.has(p_id)) {
  248. tracked_nodes.erase(p_id);
  249. get_multiplayer()->object_configuration_remove(node, this);
  250. }
  251. }
  252. int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {
  253. for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
  254. if (spawnable_scenes[i].path == p_scene) {
  255. return i;
  256. }
  257. }
  258. return INVALID_ID;
  259. }
  260. int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {
  261. const SpawnInfo *info = tracked_nodes.getptr(p_id);
  262. return info ? info->id : INVALID_ID;
  263. }
  264. const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {
  265. const SpawnInfo *info = tracked_nodes.getptr(p_id);
  266. return info ? info->args : Variant();
  267. }
  268. Node *MultiplayerSpawner::instantiate_scene(int p_id) {
  269. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  270. ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);
  271. SpawnableScene &sc = spawnable_scenes[p_id];
  272. if (sc.cache.is_null()) {
  273. sc.cache = ResourceLoader::load(sc.path);
  274. }
  275. ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);
  276. return sc.cache->instantiate();
  277. }
  278. Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {
  279. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  280. ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");
  281. const Variant *argv[1] = { &p_data };
  282. Variant ret;
  283. Callable::CallError ce;
  284. spawn_function.callp(argv, 1, ret, ce);
  285. ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");
  286. ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");
  287. return Object::cast_to<Node>(ret.operator Object *());
  288. }
  289. Node *MultiplayerSpawner::spawn(const Variant &p_data) {
  290. ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);
  291. ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
  292. ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");
  293. Node *parent = get_spawn_node();
  294. ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");
  295. Node *node = instantiate_custom(p_data);
  296. ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");
  297. _track(node, p_data);
  298. parent->add_child(node, true);
  299. return node;
  300. }