scene_multiplayer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*************************************************************************/
  2. /* scene_multiplayer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 "scene_multiplayer.h"
  31. #include "core/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #include <stdint.h>
  34. #ifdef DEBUG_ENABLED
  35. #include "core/os/os.h"
  36. #endif
  37. #ifdef DEBUG_ENABLED
  38. void SceneMultiplayer::profile_bandwidth(const String &p_inout, int p_size) {
  39. if (EngineDebugger::is_profiling("multiplayer")) {
  40. Array values;
  41. values.push_back(p_inout);
  42. values.push_back(OS::get_singleton()->get_ticks_msec());
  43. values.push_back(p_size);
  44. EngineDebugger::profiler_add_frame_data("multiplayer", values);
  45. }
  46. }
  47. #endif
  48. Error SceneMultiplayer::poll() {
  49. if (!multiplayer_peer.is_valid() || multiplayer_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  50. return ERR_UNCONFIGURED;
  51. }
  52. multiplayer_peer->poll();
  53. if (!multiplayer_peer.is_valid()) { // It's possible that polling might have resulted in a disconnection, so check here.
  54. return OK;
  55. }
  56. while (multiplayer_peer->get_available_packet_count()) {
  57. int sender = multiplayer_peer->get_packet_peer();
  58. const uint8_t *packet;
  59. int len;
  60. Error err = multiplayer_peer->get_packet(&packet, len);
  61. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Error getting packet! %d", err));
  62. remote_sender_id = sender;
  63. _process_packet(sender, packet, len);
  64. remote_sender_id = 0;
  65. if (!multiplayer_peer.is_valid()) {
  66. return OK; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  67. }
  68. }
  69. replicator->on_network_process();
  70. return OK;
  71. }
  72. void SceneMultiplayer::clear() {
  73. connected_peers.clear();
  74. packet_cache.clear();
  75. cache->clear();
  76. }
  77. void SceneMultiplayer::set_root_path(const NodePath &p_path) {
  78. ERR_FAIL_COND_MSG(!p_path.is_absolute() && !p_path.is_empty(), "SceneMultiplayer root path must be absolute.");
  79. root_path = p_path;
  80. }
  81. NodePath SceneMultiplayer::get_root_path() const {
  82. return root_path;
  83. }
  84. void SceneMultiplayer::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) {
  85. if (p_peer == multiplayer_peer) {
  86. return; // Nothing to do
  87. }
  88. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED,
  89. "Supplied MultiplayerPeer must be connecting or connected.");
  90. if (multiplayer_peer.is_valid()) {
  91. multiplayer_peer->disconnect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
  92. multiplayer_peer->disconnect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
  93. multiplayer_peer->disconnect("connection_succeeded", callable_mp(this, &SceneMultiplayer::_connected_to_server));
  94. multiplayer_peer->disconnect("connection_failed", callable_mp(this, &SceneMultiplayer::_connection_failed));
  95. multiplayer_peer->disconnect("server_disconnected", callable_mp(this, &SceneMultiplayer::_server_disconnected));
  96. clear();
  97. }
  98. multiplayer_peer = p_peer;
  99. if (multiplayer_peer.is_valid()) {
  100. multiplayer_peer->connect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
  101. multiplayer_peer->connect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
  102. multiplayer_peer->connect("connection_succeeded", callable_mp(this, &SceneMultiplayer::_connected_to_server));
  103. multiplayer_peer->connect("connection_failed", callable_mp(this, &SceneMultiplayer::_connection_failed));
  104. multiplayer_peer->connect("server_disconnected", callable_mp(this, &SceneMultiplayer::_server_disconnected));
  105. }
  106. replicator->on_reset();
  107. }
  108. Ref<MultiplayerPeer> SceneMultiplayer::get_multiplayer_peer() {
  109. return multiplayer_peer;
  110. }
  111. void SceneMultiplayer::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  112. ERR_FAIL_COND_MSG(root_path.is_empty(), "Multiplayer root was not initialized. If you are using custom multiplayer, remember to set the root path via SceneMultiplayer.set_root_path before using it.");
  113. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  114. #ifdef DEBUG_ENABLED
  115. profile_bandwidth("in", p_packet_len);
  116. #endif
  117. // Extract the `packet_type` from the LSB three bits:
  118. uint8_t packet_type = p_packet[0] & CMD_MASK;
  119. switch (packet_type) {
  120. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  121. cache->process_simplify_path(p_from, p_packet, p_packet_len);
  122. } break;
  123. case NETWORK_COMMAND_CONFIRM_PATH: {
  124. cache->process_confirm_path(p_from, p_packet, p_packet_len);
  125. } break;
  126. case NETWORK_COMMAND_REMOTE_CALL: {
  127. rpc->process_rpc(p_from, p_packet, p_packet_len);
  128. } break;
  129. case NETWORK_COMMAND_RAW: {
  130. _process_raw(p_from, p_packet, p_packet_len);
  131. } break;
  132. case NETWORK_COMMAND_SPAWN: {
  133. replicator->on_spawn_receive(p_from, p_packet, p_packet_len);
  134. } break;
  135. case NETWORK_COMMAND_DESPAWN: {
  136. replicator->on_despawn_receive(p_from, p_packet, p_packet_len);
  137. } break;
  138. case NETWORK_COMMAND_SYNC: {
  139. replicator->on_sync_receive(p_from, p_packet, p_packet_len);
  140. } break;
  141. }
  142. }
  143. void SceneMultiplayer::_add_peer(int p_id) {
  144. connected_peers.insert(p_id);
  145. cache->on_peer_change(p_id, true);
  146. replicator->on_peer_change(p_id, true);
  147. emit_signal(SNAME("peer_connected"), p_id);
  148. }
  149. void SceneMultiplayer::_del_peer(int p_id) {
  150. replicator->on_peer_change(p_id, false);
  151. cache->on_peer_change(p_id, false);
  152. connected_peers.erase(p_id);
  153. emit_signal(SNAME("peer_disconnected"), p_id);
  154. }
  155. void SceneMultiplayer::_connected_to_server() {
  156. emit_signal(SNAME("connected_to_server"));
  157. }
  158. void SceneMultiplayer::_connection_failed() {
  159. emit_signal(SNAME("connection_failed"));
  160. }
  161. void SceneMultiplayer::_server_disconnected() {
  162. replicator->on_reset();
  163. emit_signal(SNAME("server_disconnected"));
  164. }
  165. Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, MultiplayerPeer::TransferMode p_mode, int p_channel) {
  166. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  167. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no multiplayer peer is active.");
  168. ERR_FAIL_COND_V_MSG(multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a multiplayer peer which is not connected.");
  169. if (packet_cache.size() < p_data.size() + 1) {
  170. packet_cache.resize(p_data.size() + 1);
  171. }
  172. const uint8_t *r = p_data.ptr();
  173. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  174. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  175. multiplayer_peer->set_target_peer(p_to);
  176. multiplayer_peer->set_transfer_channel(p_channel);
  177. multiplayer_peer->set_transfer_mode(p_mode);
  178. return multiplayer_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  179. }
  180. void SceneMultiplayer::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  181. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  182. Vector<uint8_t> out;
  183. int len = p_packet_len - 1;
  184. out.resize(len);
  185. {
  186. uint8_t *w = out.ptrw();
  187. memcpy(&w[0], &p_packet[1], len);
  188. }
  189. emit_signal(SNAME("peer_packet"), p_from, out);
  190. }
  191. int SceneMultiplayer::get_unique_id() {
  192. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), 0, "No multiplayer peer is assigned. Unable to get unique ID.");
  193. return multiplayer_peer->get_unique_id();
  194. }
  195. void SceneMultiplayer::set_refuse_new_connections(bool p_refuse) {
  196. ERR_FAIL_COND_MSG(!multiplayer_peer.is_valid(), "No multiplayer peer is assigned. Unable to set 'refuse_new_connections'.");
  197. multiplayer_peer->set_refuse_new_connections(p_refuse);
  198. }
  199. bool SceneMultiplayer::is_refusing_new_connections() const {
  200. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), false, "No multiplayer peer is assigned. Unable to get 'refuse_new_connections'.");
  201. return multiplayer_peer->is_refusing_new_connections();
  202. }
  203. Vector<int> SceneMultiplayer::get_peer_ids() {
  204. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), Vector<int>(), "No multiplayer peer is assigned. Assume no peers are connected.");
  205. Vector<int> ret;
  206. for (const int &E : connected_peers) {
  207. ret.push_back(E);
  208. }
  209. return ret;
  210. }
  211. void SceneMultiplayer::set_allow_object_decoding(bool p_enable) {
  212. allow_object_decoding = p_enable;
  213. }
  214. bool SceneMultiplayer::is_object_decoding_allowed() const {
  215. return allow_object_decoding;
  216. }
  217. String SceneMultiplayer::get_rpc_md5(const Object *p_obj) {
  218. return rpc->get_rpc_md5(p_obj);
  219. }
  220. Error SceneMultiplayer::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  221. return rpc->rpcp(p_obj, p_peer_id, p_method, p_arg, p_argcount);
  222. }
  223. Error SceneMultiplayer::object_configuration_add(Object *p_obj, Variant p_config) {
  224. if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
  225. set_root_path(p_config);
  226. return OK;
  227. }
  228. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  229. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  230. if (spawner) {
  231. return replicator->on_spawn(p_obj, p_config);
  232. } else if (sync) {
  233. return replicator->on_replication_start(p_obj, p_config);
  234. }
  235. return ERR_INVALID_PARAMETER;
  236. }
  237. Error SceneMultiplayer::object_configuration_remove(Object *p_obj, Variant p_config) {
  238. if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
  239. ERR_FAIL_COND_V(root_path != p_config.operator NodePath(), ERR_INVALID_PARAMETER);
  240. set_root_path(NodePath());
  241. return OK;
  242. }
  243. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  244. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  245. if (spawner) {
  246. return replicator->on_despawn(p_obj, p_config);
  247. }
  248. if (sync) {
  249. return replicator->on_replication_stop(p_obj, p_config);
  250. }
  251. return ERR_INVALID_PARAMETER;
  252. }
  253. void SceneMultiplayer::_bind_methods() {
  254. ClassDB::bind_method(D_METHOD("set_root_path", "path"), &SceneMultiplayer::set_root_path);
  255. ClassDB::bind_method(D_METHOD("get_root_path"), &SceneMultiplayer::get_root_path);
  256. ClassDB::bind_method(D_METHOD("clear"), &SceneMultiplayer::clear);
  257. ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "refuse"), &SceneMultiplayer::set_refuse_new_connections);
  258. ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &SceneMultiplayer::is_refusing_new_connections);
  259. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &SceneMultiplayer::set_allow_object_decoding);
  260. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &SceneMultiplayer::is_object_decoding_allowed);
  261. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &SceneMultiplayer::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
  262. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
  263. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  264. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections");
  265. ADD_PROPERTY_DEFAULT("refuse_new_connections", false);
  266. ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  267. }
  268. SceneMultiplayer::SceneMultiplayer() {
  269. replicator = Ref<SceneReplicationInterface>(memnew(SceneReplicationInterface(this)));
  270. rpc = Ref<SceneRPCInterface>(memnew(SceneRPCInterface(this)));
  271. cache = Ref<SceneCacheInterface>(memnew(SceneCacheInterface(this)));
  272. }
  273. SceneMultiplayer::~SceneMultiplayer() {
  274. clear();
  275. }