multiplayer_api.cpp 26 KB

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