multiplayer_spawner.cpp 14 KB

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