multiplayer_api.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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 "multiplayer_api.h"
  31. #include "core/io/marshalls.h"
  32. #include "scene/main/node.h"
  33. #ifdef DEBUG_ENABLED
  34. #include "core/os/os.h"
  35. #endif
  36. _FORCE_INLINE_ bool _should_call_local(MultiplayerAPI::RPCMode mode, bool is_master, bool &r_skip_rpc) {
  37. switch (mode) {
  38. case MultiplayerAPI::RPC_MODE_DISABLED: {
  39. // Do nothing.
  40. } break;
  41. case MultiplayerAPI::RPC_MODE_REMOTE: {
  42. // Do nothing also. Remote cannot produce a local call.
  43. } break;
  44. case MultiplayerAPI::RPC_MODE_MASTERSYNC: {
  45. if (is_master)
  46. r_skip_rpc = true; // I am the master, so skip remote call.
  47. FALLTHROUGH;
  48. }
  49. case MultiplayerAPI::RPC_MODE_REMOTESYNC:
  50. case MultiplayerAPI::RPC_MODE_PUPPETSYNC: {
  51. // Call it, sync always results in a local call.
  52. return true;
  53. } break;
  54. case MultiplayerAPI::RPC_MODE_MASTER: {
  55. if (is_master)
  56. r_skip_rpc = true; // I am the master, so skip remote call.
  57. return is_master;
  58. } break;
  59. case MultiplayerAPI::RPC_MODE_PUPPET: {
  60. return !is_master;
  61. } break;
  62. }
  63. return false;
  64. }
  65. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  66. switch (mode) {
  67. case MultiplayerAPI::RPC_MODE_DISABLED: {
  68. return false;
  69. } break;
  70. case MultiplayerAPI::RPC_MODE_REMOTE:
  71. case MultiplayerAPI::RPC_MODE_REMOTESYNC: {
  72. return true;
  73. } break;
  74. case MultiplayerAPI::RPC_MODE_MASTERSYNC:
  75. case MultiplayerAPI::RPC_MODE_MASTER: {
  76. return p_node->is_network_master();
  77. } break;
  78. case MultiplayerAPI::RPC_MODE_PUPPETSYNC:
  79. case MultiplayerAPI::RPC_MODE_PUPPET: {
  80. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  81. } break;
  82. }
  83. return false;
  84. }
  85. void MultiplayerAPI::poll() {
  86. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
  87. return;
  88. network_peer->poll();
  89. if (!network_peer.is_valid()) // It's possible that polling might have resulted in a disconnection, so check here.
  90. return;
  91. while (network_peer->get_available_packet_count()) {
  92. int sender = network_peer->get_packet_peer();
  93. const uint8_t *packet;
  94. int len;
  95. Error err = network_peer->get_packet(&packet, len);
  96. if (err != OK) {
  97. ERR_PRINT("Error getting packet!");
  98. }
  99. rpc_sender_id = sender;
  100. _process_packet(sender, packet, len);
  101. rpc_sender_id = 0;
  102. if (!network_peer.is_valid()) {
  103. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  104. }
  105. }
  106. }
  107. void MultiplayerAPI::clear() {
  108. connected_peers.clear();
  109. path_get_cache.clear();
  110. path_send_cache.clear();
  111. packet_cache.clear();
  112. last_send_cache_id = 1;
  113. }
  114. void MultiplayerAPI::set_root_node(Node *p_node) {
  115. root_node = p_node;
  116. }
  117. void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer) {
  118. if (p_peer == network_peer) return; // Nothing to do
  119. if (network_peer.is_valid()) {
  120. network_peer->disconnect("peer_connected", this, "_add_peer");
  121. network_peer->disconnect("peer_disconnected", this, "_del_peer");
  122. network_peer->disconnect("connection_succeeded", this, "_connected_to_server");
  123. network_peer->disconnect("connection_failed", this, "_connection_failed");
  124. network_peer->disconnect("server_disconnected", this, "_server_disconnected");
  125. clear();
  126. }
  127. network_peer = p_peer;
  128. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Supplied NetworkedNetworkPeer must be connecting or connected.");
  129. if (network_peer.is_valid()) {
  130. network_peer->connect("peer_connected", this, "_add_peer");
  131. network_peer->connect("peer_disconnected", this, "_del_peer");
  132. network_peer->connect("connection_succeeded", this, "_connected_to_server");
  133. network_peer->connect("connection_failed", this, "_connection_failed");
  134. network_peer->connect("server_disconnected", this, "_server_disconnected");
  135. }
  136. }
  137. Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  138. return network_peer;
  139. }
  140. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  141. ERR_FAIL_COND_MSG(root_node == NULL, "Multiplayer root node was not initialized. If you are using custom multiplayer, remember to set the root node via MultiplayerAPI.set_root_node before using it.");
  142. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  143. #ifdef DEBUG_ENABLED
  144. if (profiling) {
  145. bandwidth_incoming_data.write[bandwidth_incoming_pointer].timestamp = OS::get_singleton()->get_ticks_msec();
  146. bandwidth_incoming_data.write[bandwidth_incoming_pointer].packet_size = p_packet_len;
  147. bandwidth_incoming_pointer = (bandwidth_incoming_pointer + 1) % bandwidth_incoming_data.size();
  148. }
  149. #endif
  150. uint8_t packet_type = p_packet[0];
  151. switch (packet_type) {
  152. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  153. _process_simplify_path(p_from, p_packet, p_packet_len);
  154. } break;
  155. case NETWORK_COMMAND_CONFIRM_PATH: {
  156. _process_confirm_path(p_from, p_packet, p_packet_len);
  157. } break;
  158. case NETWORK_COMMAND_REMOTE_CALL:
  159. case NETWORK_COMMAND_REMOTE_SET: {
  160. ERR_FAIL_COND_MSG(p_packet_len < 6, "Invalid packet received. Size too small.");
  161. Node *node = _process_get_node(p_from, p_packet, p_packet_len);
  162. ERR_FAIL_COND_MSG(node == NULL, "Invalid packet received. Requested node was not found.");
  163. // Detect cstring end.
  164. int len_end = 5;
  165. for (; len_end < p_packet_len; len_end++) {
  166. if (p_packet[len_end] == 0) {
  167. break;
  168. }
  169. }
  170. ERR_FAIL_COND_MSG(len_end >= p_packet_len, "Invalid packet received. Size too small.");
  171. StringName name = String::utf8((const char *)&p_packet[5]);
  172. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  173. _process_rpc(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  174. } else {
  175. _process_rset(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  176. }
  177. } break;
  178. case NETWORK_COMMAND_RAW: {
  179. _process_raw(p_from, p_packet, p_packet_len);
  180. } break;
  181. }
  182. }
  183. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, int p_packet_len) {
  184. uint32_t target = decode_uint32(&p_packet[1]);
  185. Node *node = NULL;
  186. if (target & 0x80000000) {
  187. // Use full path (not cached yet).
  188. int ofs = target & 0x7FFFFFFF;
  189. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, NULL, "Invalid packet received. Size smaller than declared.");
  190. String paths;
  191. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  192. NodePath np = paths;
  193. node = root_node->get_node(np);
  194. if (!node)
  195. ERR_PRINTS("Failed to get path from RPC: " + String(np) + ".");
  196. } else {
  197. // Use cached path.
  198. int id = target;
  199. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  200. ERR_FAIL_COND_V_MSG(!E, NULL, "Invalid packet received. Requests invalid peer cache.");
  201. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  202. ERR_FAIL_COND_V_MSG(!F, NULL, "Invalid packet received. Unabled to find requested cached node.");
  203. PathGetCache::NodeInfo *ni = &F->get();
  204. // Do proper caching later.
  205. node = root_node->get_node(ni->path);
  206. if (!node)
  207. ERR_PRINTS("Failed to get cached path from RPC: " + String(ni->path) + ".");
  208. }
  209. return node;
  210. }
  211. void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  212. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  213. // Check that remote can call the RPC on this node.
  214. RPCMode rpc_mode = RPC_MODE_DISABLED;
  215. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_name);
  216. if (E) {
  217. rpc_mode = E->get();
  218. } else if (p_node->get_script_instance()) {
  219. rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_name);
  220. }
  221. bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
  222. ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  223. int argc = p_packet[p_offset];
  224. Vector<Variant> args;
  225. Vector<const Variant *> argp;
  226. args.resize(argc);
  227. argp.resize(argc);
  228. p_offset++;
  229. #ifdef DEBUG_ENABLED
  230. if (profiling) {
  231. ObjectID id = p_node->get_instance_id();
  232. _init_node_profile(id);
  233. profiler_frame_data[id].incoming_rpc += 1;
  234. }
  235. #endif
  236. for (int i = 0; i < argc; i++) {
  237. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  238. int vlen;
  239. Error err = decode_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen, allow_object_decoding || network_peer->is_object_decoding_allowed());
  240. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
  241. argp.write[i] = &args[i];
  242. p_offset += vlen;
  243. }
  244. Variant::CallError ce;
  245. p_node->call(p_name, (const Variant **)argp.ptr(), argc, ce);
  246. if (ce.error != Variant::CallError::CALL_OK) {
  247. String error = Variant::get_call_error_text(p_node, p_name, (const Variant **)argp.ptr(), argc, ce);
  248. error = "RPC - " + error;
  249. ERR_PRINTS(error);
  250. }
  251. }
  252. void MultiplayerAPI::_process_rset(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  253. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  254. // Check that remote can call the RSET on this node.
  255. RPCMode rset_mode = RPC_MODE_DISABLED;
  256. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_name);
  257. if (E) {
  258. rset_mode = E->get();
  259. } else if (p_node->get_script_instance()) {
  260. rset_mode = p_node->get_script_instance()->get_rset_mode(p_name);
  261. }
  262. bool can_call = _can_call_mode(p_node, rset_mode, p_from);
  263. ERR_FAIL_COND_MSG(!can_call, "RSET '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  264. #ifdef DEBUG_ENABLED
  265. if (profiling) {
  266. ObjectID id = p_node->get_instance_id();
  267. _init_node_profile(id);
  268. profiler_frame_data[id].incoming_rset += 1;
  269. }
  270. #endif
  271. Variant value;
  272. Error err = decode_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL, allow_object_decoding || network_peer->is_object_decoding_allowed());
  273. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RSET value.");
  274. bool valid;
  275. p_node->set(p_name, value, &valid);
  276. if (!valid) {
  277. String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class() + ".";
  278. ERR_PRINTS(error);
  279. }
  280. }
  281. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  282. ERR_FAIL_COND_MSG(p_packet_len < 5, "Invalid packet received. Size too small.");
  283. int id = decode_uint32(&p_packet[1]);
  284. String paths;
  285. paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
  286. NodePath path = paths;
  287. if (!path_get_cache.has(p_from)) {
  288. path_get_cache[p_from] = PathGetCache();
  289. }
  290. PathGetCache::NodeInfo ni;
  291. ni.path = path;
  292. ni.instance = 0;
  293. path_get_cache[p_from].nodes[id] = ni;
  294. // Encode path to send ack.
  295. CharString pname = String(path).utf8();
  296. int len = encode_cstring(pname.get_data(), NULL);
  297. Vector<uint8_t> packet;
  298. packet.resize(1 + len);
  299. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  300. encode_cstring(pname.get_data(), &packet.write[1]);
  301. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  302. network_peer->set_target_peer(p_from);
  303. network_peer->put_packet(packet.ptr(), packet.size());
  304. }
  305. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  306. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  307. String paths;
  308. paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
  309. NodePath path = paths;
  310. PathSentCache *psc = path_send_cache.getptr(path);
  311. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  312. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  313. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  314. E->get() = true;
  315. }
  316. bool MultiplayerAPI::_send_confirm_path(NodePath p_path, PathSentCache *psc, int p_target) {
  317. bool has_all_peers = true;
  318. List<int> peers_to_add; // If one is missing, take note to add it.
  319. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  320. if (p_target < 0 && E->get() == -p_target)
  321. continue; // Continue, excluded.
  322. if (p_target > 0 && E->get() != p_target)
  323. continue; // Continue, not for this peer.
  324. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  325. if (!F || !F->get()) {
  326. // Path was not cached, or was cached but is unconfirmed.
  327. if (!F) {
  328. // Not cached at all, take note.
  329. peers_to_add.push_back(E->get());
  330. }
  331. has_all_peers = false;
  332. }
  333. }
  334. // Those that need to be added, send a message for this.
  335. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  336. // Encode function name.
  337. CharString pname = String(p_path).utf8();
  338. int len = encode_cstring(pname.get_data(), NULL);
  339. Vector<uint8_t> packet;
  340. packet.resize(1 + 4 + len);
  341. packet.write[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
  342. encode_uint32(psc->id, &packet.write[1]);
  343. encode_cstring(pname.get_data(), &packet.write[5]);
  344. network_peer->set_target_peer(E->get()); // To all of you.
  345. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  346. network_peer->put_packet(packet.ptr(), packet.size());
  347. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  348. }
  349. return has_all_peers;
  350. }
  351. void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  352. ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
  353. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree.");
  354. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
  355. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
  356. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  357. ERR_FAIL_COND_MSG(p_to == network_peer->get_unique_id(), "Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()) + ".");
  358. ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
  359. }
  360. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  361. ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  362. // See if the path is cached.
  363. PathSentCache *psc = path_send_cache.getptr(from_path);
  364. if (!psc) {
  365. // Path is not cached, create.
  366. path_send_cache[from_path] = PathSentCache();
  367. psc = path_send_cache.getptr(from_path);
  368. psc->id = last_send_cache_id++;
  369. }
  370. // Create base packet, lots of hardcode because it must be tight.
  371. int ofs = 0;
  372. #define MAKE_ROOM(m_amount) \
  373. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  374. // Encode type.
  375. MAKE_ROOM(1);
  376. packet_cache.write[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  377. ofs += 1;
  378. // Encode ID.
  379. MAKE_ROOM(ofs + 4);
  380. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  381. ofs += 4;
  382. // Encode function name.
  383. CharString name = String(p_name).utf8();
  384. int len = encode_cstring(name.get_data(), NULL);
  385. MAKE_ROOM(ofs + len);
  386. encode_cstring(name.get_data(), &(packet_cache.write[ofs]));
  387. ofs += len;
  388. if (p_set) {
  389. // Set argument.
  390. Error err = encode_variant(*p_arg[0], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  391. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  392. MAKE_ROOM(ofs + len);
  393. encode_variant(*p_arg[0], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  394. ofs += len;
  395. } else {
  396. // Call arguments.
  397. MAKE_ROOM(ofs + 1);
  398. packet_cache.write[ofs] = p_argcount;
  399. ofs += 1;
  400. for (int i = 0; i < p_argcount; i++) {
  401. Error err = encode_variant(*p_arg[i], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  402. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  403. MAKE_ROOM(ofs + len);
  404. encode_variant(*p_arg[i], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  405. ofs += len;
  406. }
  407. }
  408. #ifdef DEBUG_ENABLED
  409. if (profiling) {
  410. bandwidth_outgoing_data.write[bandwidth_outgoing_pointer].timestamp = OS::get_singleton()->get_ticks_msec();
  411. bandwidth_outgoing_data.write[bandwidth_outgoing_pointer].packet_size = ofs;
  412. bandwidth_outgoing_pointer = (bandwidth_outgoing_pointer + 1) % bandwidth_outgoing_data.size();
  413. }
  414. #endif
  415. // See if all peers have cached path (is so, call can be fast).
  416. bool has_all_peers = _send_confirm_path(from_path, psc, p_to);
  417. // Take chance and set transfer mode, since all send methods will use it.
  418. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  419. if (has_all_peers) {
  420. // They all have verified paths, so send fast.
  421. network_peer->set_target_peer(p_to); // To all of you.
  422. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  423. } else {
  424. // Not all verified path, so send one by one.
  425. // Append path at the end, since we will need it for some packets.
  426. CharString pname = String(from_path).utf8();
  427. int path_len = encode_cstring(pname.get_data(), NULL);
  428. MAKE_ROOM(ofs + path_len);
  429. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  430. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  431. if (p_to < 0 && E->get() == -p_to)
  432. continue; // Continue, excluded.
  433. if (p_to > 0 && E->get() != p_to)
  434. continue; // Continue, not for this peer.
  435. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  436. ERR_CONTINUE(!F); // Should never happen.
  437. network_peer->set_target_peer(E->get()); // To this one specifically.
  438. if (F->get()) {
  439. // This one confirmed path, so use id.
  440. encode_uint32(psc->id, &(packet_cache.write[1]));
  441. network_peer->put_packet(packet_cache.ptr(), ofs);
  442. } else {
  443. // This one did not confirm path yet, so use entire path (sorry!).
  444. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  445. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  446. }
  447. }
  448. }
  449. }
  450. void MultiplayerAPI::_add_peer(int p_id) {
  451. connected_peers.insert(p_id);
  452. path_get_cache.insert(p_id, PathGetCache());
  453. emit_signal("network_peer_connected", p_id);
  454. }
  455. void MultiplayerAPI::_del_peer(int p_id) {
  456. connected_peers.erase(p_id);
  457. path_get_cache.erase(p_id); // I no longer need your cache, sorry.
  458. emit_signal("network_peer_disconnected", p_id);
  459. }
  460. void MultiplayerAPI::_connected_to_server() {
  461. emit_signal("connected_to_server");
  462. }
  463. void MultiplayerAPI::_connection_failed() {
  464. emit_signal("connection_failed");
  465. }
  466. void MultiplayerAPI::_server_disconnected() {
  467. emit_signal("server_disconnected");
  468. }
  469. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  470. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
  471. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
  472. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected.");
  473. int node_id = network_peer->get_unique_id();
  474. bool skip_rpc = node_id == p_peer_id;
  475. bool call_local_native = false;
  476. bool call_local_script = false;
  477. bool is_master = p_node->is_network_master();
  478. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  479. // Check that send mode can use local call.
  480. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_method);
  481. if (E) {
  482. call_local_native = _should_call_local(E->get(), is_master, skip_rpc);
  483. }
  484. if (call_local_native) {
  485. // Done below.
  486. } else if (p_node->get_script_instance()) {
  487. // Attempt with script.
  488. RPCMode rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  489. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  490. }
  491. }
  492. if (!skip_rpc) {
  493. #ifdef DEBUG_ENABLED
  494. if (profiling) {
  495. ObjectID id = p_node->get_instance_id();
  496. _init_node_profile(id);
  497. profiler_frame_data[id].outgoing_rpc += 1;
  498. }
  499. #endif
  500. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  501. }
  502. if (call_local_native) {
  503. int temp_id = rpc_sender_id;
  504. rpc_sender_id = get_network_unique_id();
  505. Variant::CallError ce;
  506. p_node->call(p_method, p_arg, p_argcount, ce);
  507. rpc_sender_id = temp_id;
  508. if (ce.error != Variant::CallError::CALL_OK) {
  509. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  510. error = "rpc() aborted in local call: - " + error + ".";
  511. ERR_PRINTS(error);
  512. return;
  513. }
  514. }
  515. if (call_local_script) {
  516. int temp_id = rpc_sender_id;
  517. rpc_sender_id = get_network_unique_id();
  518. Variant::CallError ce;
  519. ce.error = Variant::CallError::CALL_OK;
  520. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  521. rpc_sender_id = temp_id;
  522. if (ce.error != Variant::CallError::CALL_OK) {
  523. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  524. error = "rpc() aborted in script local call: - " + error + ".";
  525. ERR_PRINTS(error);
  526. return;
  527. }
  528. }
  529. ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  530. }
  531. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  532. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to RSET while no network peer is active.");
  533. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to RSET on a node which is not inside SceneTree.");
  534. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to send an RSET via a network peer which is not connected.");
  535. int node_id = network_peer->get_unique_id();
  536. bool is_master = p_node->is_network_master();
  537. bool skip_rset = node_id == p_peer_id;
  538. bool set_local = false;
  539. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  540. // Check that send mode can use local call.
  541. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_property);
  542. if (E) {
  543. set_local = _should_call_local(E->get(), is_master, skip_rset);
  544. }
  545. if (set_local) {
  546. bool valid;
  547. int temp_id = rpc_sender_id;
  548. rpc_sender_id = get_network_unique_id();
  549. p_node->set(p_property, p_value, &valid);
  550. rpc_sender_id = temp_id;
  551. if (!valid) {
  552. String error = "rset() aborted in local set, property not found: - " + String(p_property) + ".";
  553. ERR_PRINTS(error);
  554. return;
  555. }
  556. } else if (p_node->get_script_instance()) {
  557. // Attempt with script.
  558. RPCMode rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  559. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  560. if (set_local) {
  561. int temp_id = rpc_sender_id;
  562. rpc_sender_id = get_network_unique_id();
  563. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  564. rpc_sender_id = temp_id;
  565. if (!valid) {
  566. String error = "rset() aborted in local script set, property not found: - " + String(p_property) + ".";
  567. ERR_PRINTS(error);
  568. return;
  569. }
  570. }
  571. }
  572. }
  573. if (skip_rset) {
  574. ERR_FAIL_COND_MSG(!set_local, "RSET for '" + p_property + "' on yourself is not allowed by selected mode.");
  575. return;
  576. }
  577. #ifdef DEBUG_ENABLED
  578. if (profiling) {
  579. ObjectID id = p_node->get_instance_id();
  580. _init_node_profile(id);
  581. profiler_frame_data[id].outgoing_rset += 1;
  582. }
  583. #endif
  584. const Variant *vptr = &p_value;
  585. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  586. }
  587. Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  588. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  589. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  590. ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected.");
  591. MAKE_ROOM(p_data.size() + 1);
  592. PoolVector<uint8_t>::Read r = p_data.read();
  593. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  594. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  595. network_peer->set_target_peer(p_to);
  596. network_peer->set_transfer_mode(p_mode);
  597. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  598. }
  599. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  600. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  601. PoolVector<uint8_t> out;
  602. int len = p_packet_len - 1;
  603. out.resize(len);
  604. {
  605. PoolVector<uint8_t>::Write w = out.write();
  606. memcpy(&w[0], &p_packet[1], len);
  607. }
  608. emit_signal("network_peer_packet", p_from, out);
  609. }
  610. int MultiplayerAPI::get_network_unique_id() const {
  611. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  612. return network_peer->get_unique_id();
  613. }
  614. bool MultiplayerAPI::is_network_server() const {
  615. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  616. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. I can't be a server.");
  617. return network_peer->is_server();
  618. }
  619. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  620. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  621. network_peer->set_refuse_new_connections(p_refuse);
  622. }
  623. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  624. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  625. return network_peer->is_refusing_new_connections();
  626. }
  627. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  628. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  629. Vector<int> ret;
  630. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  631. ret.push_back(E->get());
  632. }
  633. return ret;
  634. }
  635. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  636. allow_object_decoding = p_enable;
  637. }
  638. bool MultiplayerAPI::is_object_decoding_allowed() const {
  639. return allow_object_decoding;
  640. }
  641. void MultiplayerAPI::profiling_start() {
  642. #ifdef DEBUG_ENABLED
  643. profiling = true;
  644. profiler_frame_data.clear();
  645. bandwidth_incoming_pointer = 0;
  646. bandwidth_incoming_data.resize(16384); // ~128kB
  647. for (int i = 0; i < bandwidth_incoming_data.size(); ++i) {
  648. bandwidth_incoming_data.write[i].packet_size = -1;
  649. }
  650. bandwidth_outgoing_pointer = 0;
  651. bandwidth_outgoing_data.resize(16384); // ~128kB
  652. for (int i = 0; i < bandwidth_outgoing_data.size(); ++i) {
  653. bandwidth_outgoing_data.write[i].packet_size = -1;
  654. }
  655. #endif
  656. }
  657. void MultiplayerAPI::profiling_end() {
  658. #ifdef DEBUG_ENABLED
  659. profiling = false;
  660. bandwidth_incoming_data.clear();
  661. bandwidth_outgoing_data.clear();
  662. #endif
  663. }
  664. int MultiplayerAPI::get_profiling_frame(ProfilingInfo *r_info) {
  665. int i = 0;
  666. #ifdef DEBUG_ENABLED
  667. for (Map<ObjectID, ProfilingInfo>::Element *E = profiler_frame_data.front(); E; E = E->next()) {
  668. r_info[i] = E->get();
  669. ++i;
  670. }
  671. profiler_frame_data.clear();
  672. #endif
  673. return i;
  674. }
  675. int MultiplayerAPI::get_incoming_bandwidth_usage() {
  676. #ifdef DEBUG_ENABLED
  677. return _get_bandwidth_usage(bandwidth_incoming_data, bandwidth_incoming_pointer);
  678. #else
  679. return 0;
  680. #endif
  681. }
  682. int MultiplayerAPI::get_outgoing_bandwidth_usage() {
  683. #ifdef DEBUG_ENABLED
  684. return _get_bandwidth_usage(bandwidth_outgoing_data, bandwidth_outgoing_pointer);
  685. #else
  686. return 0;
  687. #endif
  688. }
  689. #ifdef DEBUG_ENABLED
  690. int MultiplayerAPI::_get_bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer) {
  691. int total_bandwidth = 0;
  692. uint32_t timestamp = OS::get_singleton()->get_ticks_msec();
  693. uint32_t final_timestamp = timestamp - 1000;
  694. int i = (p_pointer + p_buffer.size() - 1) % p_buffer.size();
  695. while (i != p_pointer && p_buffer[i].packet_size > 0) {
  696. if (p_buffer[i].timestamp < final_timestamp) {
  697. return total_bandwidth;
  698. }
  699. total_bandwidth += p_buffer[i].packet_size;
  700. i = (i + p_buffer.size() - 1) % p_buffer.size();
  701. }
  702. ERR_FAIL_COND_V_MSG(i == p_pointer, total_bandwidth, "Reached the end of the bandwidth profiler buffer, values might be inaccurate.");
  703. return total_bandwidth;
  704. }
  705. void MultiplayerAPI::_init_node_profile(ObjectID p_node) {
  706. if (profiler_frame_data.has(p_node))
  707. return;
  708. profiler_frame_data.insert(p_node, ProfilingInfo());
  709. profiler_frame_data[p_node].node = p_node;
  710. profiler_frame_data[p_node].node_path = Object::cast_to<Node>(ObjectDB::get_instance(p_node))->get_path();
  711. profiler_frame_data[p_node].incoming_rpc = 0;
  712. profiler_frame_data[p_node].incoming_rset = 0;
  713. profiler_frame_data[p_node].outgoing_rpc = 0;
  714. profiler_frame_data[p_node].outgoing_rset = 0;
  715. }
  716. #endif
  717. void MultiplayerAPI::_bind_methods() {
  718. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  719. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  720. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  721. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  722. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  723. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  724. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  725. ClassDB::bind_method(D_METHOD("_add_peer", "id"), &MultiplayerAPI::_add_peer);
  726. ClassDB::bind_method(D_METHOD("_del_peer", "id"), &MultiplayerAPI::_del_peer);
  727. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  728. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  729. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  730. ClassDB::bind_method(D_METHOD("_connected_to_server"), &MultiplayerAPI::_connected_to_server);
  731. ClassDB::bind_method(D_METHOD("_connection_failed"), &MultiplayerAPI::_connection_failed);
  732. ClassDB::bind_method(D_METHOD("_server_disconnected"), &MultiplayerAPI::_server_disconnected);
  733. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  734. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  735. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  736. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  737. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  738. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  739. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  740. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  741. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  742. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  743. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  744. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "packet")));
  745. ADD_SIGNAL(MethodInfo("connected_to_server"));
  746. ADD_SIGNAL(MethodInfo("connection_failed"));
  747. ADD_SIGNAL(MethodInfo("server_disconnected"));
  748. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  749. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  750. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  751. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  752. BIND_ENUM_CONSTANT(RPC_MODE_SLAVE); // Deprecated.
  753. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  754. BIND_ENUM_CONSTANT(RPC_MODE_SYNC); // Deprecated.
  755. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  756. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  757. }
  758. MultiplayerAPI::MultiplayerAPI() :
  759. allow_object_decoding(false) {
  760. rpc_sender_id = 0;
  761. root_node = NULL;
  762. #ifdef DEBUG_ENABLED
  763. profiling = false;
  764. #endif
  765. clear();
  766. }
  767. MultiplayerAPI::~MultiplayerAPI() {
  768. clear();
  769. }