multiplayer_api.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #include "core/multiplayer/multiplayer_replicator.h"
  34. #include "core/multiplayer/rpc_manager.h"
  35. #include "scene/main/node.h"
  36. #include <stdint.h>
  37. #ifdef DEBUG_ENABLED
  38. #include "core/os/os.h"
  39. #endif
  40. #ifdef DEBUG_ENABLED
  41. void MultiplayerAPI::profile_bandwidth(const String &p_inout, int p_size) {
  42. if (EngineDebugger::is_profiling("multiplayer")) {
  43. Array values;
  44. values.push_back("bandwidth");
  45. values.push_back(p_inout);
  46. values.push_back(OS::get_singleton()->get_ticks_msec());
  47. values.push_back(p_size);
  48. EngineDebugger::profiler_add_frame_data("multiplayer", values);
  49. }
  50. }
  51. #endif
  52. void MultiplayerAPI::poll() {
  53. if (!network_peer.is_valid() || network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  54. return;
  55. }
  56. network_peer->poll();
  57. if (!network_peer.is_valid()) { // It's possible that polling might have resulted in a disconnection, so check here.
  58. return;
  59. }
  60. while (network_peer->get_available_packet_count()) {
  61. int sender = network_peer->get_packet_peer();
  62. const uint8_t *packet;
  63. int len;
  64. Error err = network_peer->get_packet(&packet, len);
  65. if (err != OK) {
  66. ERR_PRINT("Error getting packet!");
  67. break; // Something is wrong!
  68. }
  69. remote_sender_id = sender;
  70. _process_packet(sender, packet, len);
  71. remote_sender_id = 0;
  72. if (!network_peer.is_valid()) {
  73. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  74. }
  75. }
  76. if (network_peer.is_valid() && network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTED) {
  77. replicator->poll();
  78. }
  79. }
  80. void MultiplayerAPI::clear() {
  81. replicator->clear();
  82. connected_peers.clear();
  83. path_get_cache.clear();
  84. path_send_cache.clear();
  85. packet_cache.clear();
  86. last_send_cache_id = 1;
  87. }
  88. void MultiplayerAPI::set_root_node(Node *p_node) {
  89. root_node = p_node;
  90. }
  91. Node *MultiplayerAPI::get_root_node() {
  92. return root_node;
  93. }
  94. void MultiplayerAPI::set_network_peer(const Ref<MultiplayerPeer> &p_peer) {
  95. if (p_peer == network_peer) {
  96. return; // Nothing to do
  97. }
  98. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED,
  99. "Supplied MultiplayerPeer must be connecting or connected.");
  100. if (network_peer.is_valid()) {
  101. network_peer->disconnect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer));
  102. network_peer->disconnect("peer_disconnected", callable_mp(this, &MultiplayerAPI::_del_peer));
  103. network_peer->disconnect("connection_succeeded", callable_mp(this, &MultiplayerAPI::_connected_to_server));
  104. network_peer->disconnect("connection_failed", callable_mp(this, &MultiplayerAPI::_connection_failed));
  105. network_peer->disconnect("server_disconnected", callable_mp(this, &MultiplayerAPI::_server_disconnected));
  106. clear();
  107. }
  108. network_peer = p_peer;
  109. if (network_peer.is_valid()) {
  110. network_peer->connect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer));
  111. network_peer->connect("peer_disconnected", callable_mp(this, &MultiplayerAPI::_del_peer));
  112. network_peer->connect("connection_succeeded", callable_mp(this, &MultiplayerAPI::_connected_to_server));
  113. network_peer->connect("connection_failed", callable_mp(this, &MultiplayerAPI::_connection_failed));
  114. network_peer->connect("server_disconnected", callable_mp(this, &MultiplayerAPI::_server_disconnected));
  115. }
  116. }
  117. Ref<MultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  118. return network_peer;
  119. }
  120. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  121. ERR_FAIL_COND_MSG(root_node == nullptr, "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.");
  122. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  123. #ifdef DEBUG_ENABLED
  124. profile_bandwidth("in", p_packet_len);
  125. #endif
  126. // Extract the `packet_type` from the LSB three bits:
  127. uint8_t packet_type = p_packet[0] & CMD_MASK;
  128. switch (packet_type) {
  129. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  130. _process_simplify_path(p_from, p_packet, p_packet_len);
  131. } break;
  132. case NETWORK_COMMAND_CONFIRM_PATH: {
  133. _process_confirm_path(p_from, p_packet, p_packet_len);
  134. } break;
  135. case NETWORK_COMMAND_REMOTE_CALL: {
  136. rpc_manager->process_rpc(p_from, p_packet, p_packet_len);
  137. } break;
  138. case NETWORK_COMMAND_RAW: {
  139. _process_raw(p_from, p_packet, p_packet_len);
  140. } break;
  141. case NETWORK_COMMAND_SPAWN: {
  142. replicator->process_spawn_despawn(p_from, p_packet, p_packet_len, true);
  143. } break;
  144. case NETWORK_COMMAND_DESPAWN: {
  145. replicator->process_spawn_despawn(p_from, p_packet, p_packet_len, false);
  146. } break;
  147. case NETWORK_COMMAND_SYNC: {
  148. replicator->process_sync(p_from, p_packet, p_packet_len);
  149. } break;
  150. }
  151. }
  152. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  153. ERR_FAIL_COND_MSG(p_packet_len < 38, "Invalid packet received. Size too small.");
  154. int ofs = 1;
  155. String methods_md5;
  156. methods_md5.parse_utf8((const char *)(p_packet + ofs), 32);
  157. ofs += 33;
  158. int id = decode_uint32(&p_packet[ofs]);
  159. ofs += 4;
  160. String paths;
  161. paths.parse_utf8((const char *)(p_packet + ofs), p_packet_len - ofs);
  162. NodePath path = paths;
  163. if (!path_get_cache.has(p_from)) {
  164. path_get_cache[p_from] = PathGetCache();
  165. }
  166. Node *node = root_node->get_node(path);
  167. ERR_FAIL_COND(node == nullptr);
  168. const bool valid_rpc_checksum = rpc_manager->get_rpc_md5(node) == methods_md5;
  169. if (valid_rpc_checksum == false) {
  170. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  171. }
  172. PathGetCache::NodeInfo ni;
  173. ni.path = path;
  174. path_get_cache[p_from].nodes[id] = ni;
  175. // Encode path to send ack.
  176. CharString pname = String(path).utf8();
  177. int len = encode_cstring(pname.get_data(), nullptr);
  178. Vector<uint8_t> packet;
  179. packet.resize(1 + 1 + len);
  180. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  181. packet.write[1] = valid_rpc_checksum;
  182. encode_cstring(pname.get_data(), &packet.write[2]);
  183. network_peer->set_transfer_channel(0);
  184. network_peer->set_transfer_mode(Multiplayer::TRANSFER_MODE_RELIABLE);
  185. network_peer->set_target_peer(p_from);
  186. network_peer->put_packet(packet.ptr(), packet.size());
  187. }
  188. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  189. ERR_FAIL_COND_MSG(p_packet_len < 3, "Invalid packet received. Size too small.");
  190. const bool valid_rpc_checksum = p_packet[1];
  191. String paths;
  192. paths.parse_utf8((const char *)&p_packet[2], p_packet_len - 2);
  193. NodePath path = paths;
  194. if (valid_rpc_checksum == false) {
  195. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  196. }
  197. PathSentCache *psc = path_send_cache.getptr(path);
  198. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  199. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  200. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  201. E->get() = true;
  202. }
  203. bool MultiplayerAPI::_send_confirm_path(Node *p_node, NodePath p_path, PathSentCache *psc, int p_target) {
  204. bool has_all_peers = true;
  205. List<int> peers_to_add; // If one is missing, take note to add it.
  206. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  207. if (p_target < 0 && E->get() == -p_target) {
  208. continue; // Continue, excluded.
  209. }
  210. if (p_target > 0 && E->get() != p_target) {
  211. continue; // Continue, not for this peer.
  212. }
  213. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  214. if (!F || !F->get()) {
  215. // Path was not cached, or was cached but is unconfirmed.
  216. if (!F) {
  217. // Not cached at all, take note.
  218. peers_to_add.push_back(E->get());
  219. }
  220. has_all_peers = false;
  221. }
  222. }
  223. if (peers_to_add.size() > 0) {
  224. // Those that need to be added, send a message for this.
  225. // Encode function name.
  226. const CharString path = String(p_path).utf8();
  227. const int path_len = encode_cstring(path.get_data(), nullptr);
  228. // Extract MD5 from rpc methods list.
  229. const String methods_md5 = rpc_manager->get_rpc_md5(p_node);
  230. const int methods_md5_len = 33; // 32 + 1 for the `0` that is added by the encoder.
  231. Vector<uint8_t> packet;
  232. packet.resize(1 + 4 + path_len + methods_md5_len);
  233. int ofs = 0;
  234. packet.write[ofs] = NETWORK_COMMAND_SIMPLIFY_PATH;
  235. ofs += 1;
  236. ofs += encode_cstring(methods_md5.utf8().get_data(), &packet.write[ofs]);
  237. ofs += encode_uint32(psc->id, &packet.write[ofs]);
  238. ofs += encode_cstring(path.get_data(), &packet.write[ofs]);
  239. for (int &E : peers_to_add) {
  240. network_peer->set_target_peer(E); // To all of you.
  241. network_peer->set_transfer_channel(0);
  242. network_peer->set_transfer_mode(Multiplayer::TRANSFER_MODE_RELIABLE);
  243. network_peer->put_packet(packet.ptr(), packet.size());
  244. psc->confirmed_peers.insert(E, false); // Insert into confirmed, but as false since it was not confirmed.
  245. }
  246. }
  247. return has_all_peers;
  248. }
  249. // The variant is compressed and encoded; The first byte contains all the meta
  250. // information and the format is:
  251. // - The first LSB 5 bits are used for the variant type.
  252. // - The next two bits are used to store the encoding mode.
  253. // - The most significant is used to store the boolean value.
  254. #define VARIANT_META_TYPE_MASK 0x1F
  255. #define VARIANT_META_EMODE_MASK 0x60
  256. #define VARIANT_META_BOOL_MASK 0x80
  257. #define ENCODE_8 0 << 5
  258. #define ENCODE_16 1 << 5
  259. #define ENCODE_32 2 << 5
  260. #define ENCODE_64 3 << 5
  261. Error MultiplayerAPI::encode_and_compress_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) {
  262. // Unreachable because `VARIANT_MAX` == 27 and `ENCODE_VARIANT_MASK` == 31
  263. CRASH_COND(p_variant.get_type() > VARIANT_META_TYPE_MASK);
  264. uint8_t *buf = r_buffer;
  265. r_len = 0;
  266. uint8_t encode_mode = 0;
  267. switch (p_variant.get_type()) {
  268. case Variant::BOOL: {
  269. if (buf) {
  270. // We still have 1 free bit in the meta, so let's use it.
  271. buf[0] = (p_variant.operator bool()) ? (1 << 7) : 0;
  272. buf[0] |= encode_mode | p_variant.get_type();
  273. }
  274. r_len += 1;
  275. } break;
  276. case Variant::INT: {
  277. if (buf) {
  278. // Reserve the first byte for the meta.
  279. buf += 1;
  280. }
  281. r_len += 1;
  282. int64_t val = p_variant;
  283. if (val <= (int64_t)INT8_MAX && val >= (int64_t)INT8_MIN) {
  284. // Use 8 bit
  285. encode_mode = ENCODE_8;
  286. if (buf) {
  287. buf[0] = val;
  288. }
  289. r_len += 1;
  290. } else if (val <= (int64_t)INT16_MAX && val >= (int64_t)INT16_MIN) {
  291. // Use 16 bit
  292. encode_mode = ENCODE_16;
  293. if (buf) {
  294. encode_uint16(val, buf);
  295. }
  296. r_len += 2;
  297. } else if (val <= (int64_t)INT32_MAX && val >= (int64_t)INT32_MIN) {
  298. // Use 32 bit
  299. encode_mode = ENCODE_32;
  300. if (buf) {
  301. encode_uint32(val, buf);
  302. }
  303. r_len += 4;
  304. } else {
  305. // Use 64 bit
  306. encode_mode = ENCODE_64;
  307. if (buf) {
  308. encode_uint64(val, buf);
  309. }
  310. r_len += 8;
  311. }
  312. // Store the meta
  313. if (buf) {
  314. buf -= 1;
  315. buf[0] = encode_mode | p_variant.get_type();
  316. }
  317. } break;
  318. default:
  319. // Any other case is not yet compressed.
  320. Error err = encode_variant(p_variant, r_buffer, r_len, allow_object_decoding);
  321. if (err != OK) {
  322. return err;
  323. }
  324. if (r_buffer) {
  325. // The first byte is not used by the marshalling, so store the type
  326. // so we know how to decompress and decode this variant.
  327. r_buffer[0] = p_variant.get_type();
  328. }
  329. }
  330. return OK;
  331. }
  332. Error MultiplayerAPI::decode_and_decompress_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) {
  333. const uint8_t *buf = p_buffer;
  334. int len = p_len;
  335. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  336. uint8_t type = buf[0] & VARIANT_META_TYPE_MASK;
  337. uint8_t encode_mode = buf[0] & VARIANT_META_EMODE_MASK;
  338. ERR_FAIL_COND_V(type >= Variant::VARIANT_MAX, ERR_INVALID_DATA);
  339. switch (type) {
  340. case Variant::BOOL: {
  341. bool val = (buf[0] & VARIANT_META_BOOL_MASK) > 0;
  342. r_variant = val;
  343. if (r_len) {
  344. *r_len = 1;
  345. }
  346. } break;
  347. case Variant::INT: {
  348. buf += 1;
  349. len -= 1;
  350. if (r_len) {
  351. *r_len = 1;
  352. }
  353. if (encode_mode == ENCODE_8) {
  354. // 8 bits.
  355. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  356. int8_t val = buf[0];
  357. r_variant = val;
  358. if (r_len) {
  359. (*r_len) += 1;
  360. }
  361. } else if (encode_mode == ENCODE_16) {
  362. // 16 bits.
  363. ERR_FAIL_COND_V(len < 2, ERR_INVALID_DATA);
  364. int16_t val = decode_uint16(buf);
  365. r_variant = val;
  366. if (r_len) {
  367. (*r_len) += 2;
  368. }
  369. } else if (encode_mode == ENCODE_32) {
  370. // 32 bits.
  371. ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
  372. int32_t val = decode_uint32(buf);
  373. r_variant = val;
  374. if (r_len) {
  375. (*r_len) += 4;
  376. }
  377. } else {
  378. // 64 bits.
  379. ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
  380. int64_t val = decode_uint64(buf);
  381. r_variant = val;
  382. if (r_len) {
  383. (*r_len) += 8;
  384. }
  385. }
  386. } break;
  387. default:
  388. Error err = decode_variant(r_variant, p_buffer, p_len, r_len, allow_object_decoding);
  389. if (err != OK) {
  390. return err;
  391. }
  392. }
  393. return OK;
  394. }
  395. void MultiplayerAPI::_add_peer(int p_id) {
  396. connected_peers.insert(p_id);
  397. path_get_cache.insert(p_id, PathGetCache());
  398. if (is_network_server()) {
  399. replicator->spawn_all(p_id);
  400. }
  401. emit_signal(SNAME("network_peer_connected"), p_id);
  402. }
  403. void MultiplayerAPI::_del_peer(int p_id) {
  404. connected_peers.erase(p_id);
  405. // Cleanup get cache.
  406. path_get_cache.erase(p_id);
  407. // Cleanup sent cache.
  408. // Some refactoring is needed to make this faster and do paths GC.
  409. List<NodePath> keys;
  410. path_send_cache.get_key_list(&keys);
  411. for (const NodePath &E : keys) {
  412. PathSentCache *psc = path_send_cache.getptr(E);
  413. psc->confirmed_peers.erase(p_id);
  414. }
  415. emit_signal(SNAME("network_peer_disconnected"), p_id);
  416. }
  417. void MultiplayerAPI::_connected_to_server() {
  418. emit_signal(SNAME("connected_to_server"));
  419. }
  420. void MultiplayerAPI::_connection_failed() {
  421. emit_signal(SNAME("connection_failed"));
  422. }
  423. void MultiplayerAPI::_server_disconnected() {
  424. emit_signal(SNAME("server_disconnected"));
  425. }
  426. Error MultiplayerAPI::send_bytes(Vector<uint8_t> p_data, int p_to, Multiplayer::TransferMode p_mode, int p_channel) {
  427. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  428. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  429. ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected.");
  430. if (packet_cache.size() < p_data.size() + 1) {
  431. packet_cache.resize(p_data.size() + 1);
  432. }
  433. const uint8_t *r = p_data.ptr();
  434. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  435. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  436. network_peer->set_target_peer(p_to);
  437. network_peer->set_transfer_channel(p_channel);
  438. network_peer->set_transfer_mode(p_mode);
  439. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  440. }
  441. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  442. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  443. Vector<uint8_t> out;
  444. int len = p_packet_len - 1;
  445. out.resize(len);
  446. {
  447. uint8_t *w = out.ptrw();
  448. memcpy(&w[0], &p_packet[1], len);
  449. }
  450. emit_signal(SNAME("network_peer_packet"), p_from, out);
  451. }
  452. bool MultiplayerAPI::is_cache_confirmed(NodePath p_path, int p_peer) {
  453. const PathSentCache *psc = path_send_cache.getptr(p_path);
  454. ERR_FAIL_COND_V(!psc, false);
  455. const Map<int, bool>::Element *F = psc->confirmed_peers.find(p_peer);
  456. ERR_FAIL_COND_V(!F, false); // Should never happen.
  457. return F->get();
  458. }
  459. bool MultiplayerAPI::send_confirm_path(Node *p_node, NodePath p_path, int p_peer_id, int &r_id) {
  460. // See if the path is cached.
  461. PathSentCache *psc = path_send_cache.getptr(p_path);
  462. if (!psc) {
  463. // Path is not cached, create.
  464. path_send_cache[p_path] = PathSentCache();
  465. psc = path_send_cache.getptr(p_path);
  466. psc->id = last_send_cache_id++;
  467. }
  468. r_id = psc->id;
  469. // See if all peers have cached path (if so, call can be fast).
  470. return _send_confirm_path(p_node, p_path, psc, p_peer_id);
  471. }
  472. Node *MultiplayerAPI::get_cached_node(int p_from, uint32_t p_node_id) {
  473. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  474. ERR_FAIL_COND_V_MSG(!E, nullptr, vformat("No cache found for peer %d.", p_from));
  475. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(p_node_id);
  476. ERR_FAIL_COND_V_MSG(!F, nullptr, vformat("ID %d not found in cache of peer %d.", p_node_id, p_from));
  477. PathGetCache::NodeInfo *ni = &F->get();
  478. Node *node = root_node->get_node(ni->path);
  479. if (!node) {
  480. ERR_PRINT("Failed to get cached path: " + String(ni->path) + ".");
  481. }
  482. return node;
  483. }
  484. int MultiplayerAPI::get_network_unique_id() const {
  485. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  486. return network_peer->get_unique_id();
  487. }
  488. bool MultiplayerAPI::is_network_server() const {
  489. return network_peer.is_valid() && network_peer->is_server();
  490. }
  491. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  492. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  493. network_peer->set_refuse_new_connections(p_refuse);
  494. }
  495. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  496. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  497. return network_peer->is_refusing_new_connections();
  498. }
  499. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  500. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  501. Vector<int> ret;
  502. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  503. ret.push_back(E->get());
  504. }
  505. return ret;
  506. }
  507. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  508. allow_object_decoding = p_enable;
  509. }
  510. bool MultiplayerAPI::is_object_decoding_allowed() const {
  511. return allow_object_decoding;
  512. }
  513. void MultiplayerAPI::scene_enter_exit_notify(const String &p_scene, Node *p_node, bool p_enter) {
  514. replicator->scene_enter_exit_notify(p_scene, p_node, p_enter);
  515. }
  516. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  517. rpc_manager->rpcp(p_node, p_peer_id, p_method, p_arg, p_argcount);
  518. }
  519. void MultiplayerAPI::_bind_methods() {
  520. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  521. ClassDB::bind_method(D_METHOD("get_root_node"), &MultiplayerAPI::get_root_node);
  522. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &MultiplayerAPI::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(Multiplayer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
  523. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  524. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  525. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  526. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  527. ClassDB::bind_method(D_METHOD("get_remote_sender_id"), &MultiplayerAPI::get_remote_sender_id);
  528. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  529. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  530. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  531. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  532. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  533. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  534. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  535. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  536. ClassDB::bind_method(D_METHOD("get_replicator"), &MultiplayerAPI::get_replicator);
  537. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  538. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  539. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerPeer", PROPERTY_USAGE_NONE), "set_network_peer", "get_network_peer");
  540. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root_node", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_root_node", "get_root_node");
  541. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  542. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "replicator", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerReplicator", PROPERTY_USAGE_NONE), "", "get_replicator");
  543. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  544. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  545. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  546. ADD_SIGNAL(MethodInfo("connected_to_server"));
  547. ADD_SIGNAL(MethodInfo("connection_failed"));
  548. ADD_SIGNAL(MethodInfo("server_disconnected"));
  549. }
  550. MultiplayerAPI::MultiplayerAPI() {
  551. replicator = memnew(MultiplayerReplicator(this));
  552. rpc_manager = memnew(RPCManager(this));
  553. clear();
  554. }
  555. MultiplayerAPI::~MultiplayerAPI() {
  556. clear();
  557. memdelete(replicator);
  558. memdelete(rpc_manager);
  559. }