scene_multiplayer.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. /**************************************************************************/
  2. /* scene_multiplayer.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "scene_multiplayer.h"
  31. #include "core/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #ifdef DEBUG_ENABLED
  34. #include "core/os/os.h"
  35. #endif
  36. #include <stdint.h>
  37. #ifdef DEBUG_ENABLED
  38. _FORCE_INLINE_ void SceneMultiplayer::_profile_bandwidth(const String &p_what, int p_value) {
  39. if (EngineDebugger::is_profiling("multiplayer:bandwidth")) {
  40. Array values;
  41. values.push_back(p_what);
  42. values.push_back(OS::get_singleton()->get_ticks_msec());
  43. values.push_back(p_value);
  44. EngineDebugger::profiler_add_frame_data("multiplayer:bandwidth", values);
  45. }
  46. }
  47. #endif
  48. void SceneMultiplayer::_update_status() {
  49. MultiplayerPeer::ConnectionStatus status = multiplayer_peer.is_valid() ? multiplayer_peer->get_connection_status() : MultiplayerPeer::CONNECTION_DISCONNECTED;
  50. if (last_connection_status != status) {
  51. if (status == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  52. if (last_connection_status == MultiplayerPeer::CONNECTION_CONNECTING) {
  53. emit_signal(SNAME("connection_failed"));
  54. } else {
  55. emit_signal(SNAME("server_disconnected"));
  56. }
  57. clear();
  58. }
  59. last_connection_status = status;
  60. }
  61. }
  62. Error SceneMultiplayer::poll() {
  63. _update_status();
  64. if (last_connection_status == MultiplayerPeer::CONNECTION_DISCONNECTED) {
  65. return OK;
  66. }
  67. multiplayer_peer->poll();
  68. _update_status();
  69. if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) {
  70. // We might be still connecting, or polling might have resulted in a disconnection.
  71. return OK;
  72. }
  73. while (multiplayer_peer->get_available_packet_count()) {
  74. int sender = multiplayer_peer->get_packet_peer();
  75. const uint8_t *packet;
  76. int len;
  77. int channel = multiplayer_peer->get_packet_channel();
  78. MultiplayerPeer::TransferMode mode = multiplayer_peer->get_packet_mode();
  79. Error err = multiplayer_peer->get_packet(&packet, len);
  80. ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Error getting packet! %d", err));
  81. #ifdef DEBUG_ENABLED
  82. _profile_bandwidth("in", len);
  83. #endif
  84. if (pending_peers.has(sender)) {
  85. ERR_CONTINUE(len < 2 || (packet[0] & CMD_MASK) != NETWORK_COMMAND_SYS || packet[1] != SYS_COMMAND_AUTH);
  86. // Auth message.
  87. PackedByteArray pba;
  88. pba.resize(len - 2);
  89. if (pba.size()) {
  90. memcpy(pba.ptrw(), &packet[2], len - 2);
  91. // User callback
  92. const Variant sv = sender;
  93. const Variant pbav = pba;
  94. const Variant *argv[2] = { &sv, &pbav };
  95. Variant ret;
  96. Callable::CallError ce;
  97. auth_callback.callp(argv, 2, ret, ce);
  98. ERR_CONTINUE_MSG(ce.error != Callable::CallError::CALL_OK, "Failed to call authentication callback");
  99. } else {
  100. // Remote complete notification.
  101. pending_peers[sender].remote = true;
  102. if (pending_peers[sender].local) {
  103. pending_peers.erase(sender);
  104. _admit_peer(sender);
  105. }
  106. }
  107. continue; // Auth in progress.
  108. }
  109. ERR_CONTINUE(!connected_peers.has(sender));
  110. if (len && (packet[0] & CMD_MASK) == NETWORK_COMMAND_SYS) {
  111. // Sys messages are processed separately since they might call _process_packet themselves.
  112. if (len > 1 && packet[1] == SYS_COMMAND_AUTH) {
  113. ERR_CONTINUE(len != 2);
  114. // If we are here, we already admitted the peer locally, and this is just a confirmation packet.
  115. continue;
  116. }
  117. _process_sys(sender, packet, len, mode, channel);
  118. } else {
  119. remote_sender_id = sender;
  120. _process_packet(sender, packet, len);
  121. remote_sender_id = 0;
  122. }
  123. _update_status();
  124. if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // It's possible that processing a packet might have resulted in a disconnection, so check here.
  125. return OK;
  126. }
  127. }
  128. if (pending_peers.size() && auth_timeout) {
  129. HashSet<int> to_drop;
  130. uint64_t time = OS::get_singleton()->get_ticks_msec();
  131. for (const KeyValue<int, PendingPeer> &pending : pending_peers) {
  132. if (pending.value.time + auth_timeout <= time) {
  133. multiplayer_peer->disconnect_peer(pending.key);
  134. to_drop.insert(pending.key);
  135. }
  136. }
  137. for (const int &P : to_drop) {
  138. // Each signal might trigger a disconnection.
  139. pending_peers.erase(P);
  140. emit_signal(SNAME("peer_authentication_failed"), P);
  141. }
  142. }
  143. _update_status();
  144. if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // Signals might have triggered disconnection.
  145. return OK;
  146. }
  147. replicator->on_network_process();
  148. return OK;
  149. }
  150. void SceneMultiplayer::clear() {
  151. last_connection_status = MultiplayerPeer::CONNECTION_DISCONNECTED;
  152. pending_peers.clear();
  153. connected_peers.clear();
  154. packet_cache.clear();
  155. replicator->on_reset();
  156. cache->clear();
  157. relay_buffer->clear();
  158. }
  159. void SceneMultiplayer::set_root_path(const NodePath &p_path) {
  160. ERR_FAIL_COND_MSG(!p_path.is_absolute() && !p_path.is_empty(), "SceneMultiplayer root path must be absolute.");
  161. root_path = p_path;
  162. }
  163. NodePath SceneMultiplayer::get_root_path() const {
  164. return root_path;
  165. }
  166. void SceneMultiplayer::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) {
  167. if (p_peer == multiplayer_peer) {
  168. return; // Nothing to do
  169. }
  170. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED,
  171. "Supplied MultiplayerPeer must be connecting or connected.");
  172. if (multiplayer_peer.is_valid()) {
  173. multiplayer_peer->disconnect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
  174. multiplayer_peer->disconnect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
  175. clear();
  176. }
  177. multiplayer_peer = p_peer;
  178. if (multiplayer_peer.is_valid()) {
  179. multiplayer_peer->connect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
  180. multiplayer_peer->connect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
  181. }
  182. _update_status();
  183. }
  184. Ref<MultiplayerPeer> SceneMultiplayer::get_multiplayer_peer() {
  185. return multiplayer_peer;
  186. }
  187. void SceneMultiplayer::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  188. ERR_FAIL_COND_MSG(root_path.is_empty(), "Multiplayer root was not initialized. If you are using custom multiplayer, remember to set the root path via SceneMultiplayer.set_root_path before using it.");
  189. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  190. // Extract the `packet_type` from the LSB three bits:
  191. uint8_t packet_type = p_packet[0] & CMD_MASK;
  192. switch (packet_type) {
  193. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  194. cache->process_simplify_path(p_from, p_packet, p_packet_len);
  195. } break;
  196. case NETWORK_COMMAND_CONFIRM_PATH: {
  197. cache->process_confirm_path(p_from, p_packet, p_packet_len);
  198. } break;
  199. case NETWORK_COMMAND_REMOTE_CALL: {
  200. rpc->process_rpc(p_from, p_packet, p_packet_len);
  201. } break;
  202. case NETWORK_COMMAND_RAW: {
  203. _process_raw(p_from, p_packet, p_packet_len);
  204. } break;
  205. case NETWORK_COMMAND_SPAWN: {
  206. replicator->on_spawn_receive(p_from, p_packet, p_packet_len);
  207. } break;
  208. case NETWORK_COMMAND_DESPAWN: {
  209. replicator->on_despawn_receive(p_from, p_packet, p_packet_len);
  210. } break;
  211. case NETWORK_COMMAND_SYNC: {
  212. replicator->on_sync_receive(p_from, p_packet, p_packet_len);
  213. } break;
  214. default: {
  215. ERR_FAIL_MSG("Invalid network command from " + itos(p_from));
  216. } break;
  217. }
  218. }
  219. #ifdef DEBUG_ENABLED
  220. _FORCE_INLINE_ Error SceneMultiplayer::_send(const uint8_t *p_packet, int p_packet_len) {
  221. _profile_bandwidth("out", p_packet_len);
  222. return multiplayer_peer->put_packet(p_packet, p_packet_len);
  223. }
  224. #endif
  225. Error SceneMultiplayer::send_command(int p_to, const uint8_t *p_packet, int p_packet_len) {
  226. if (server_relay && get_unique_id() != 1 && p_to != 1 && multiplayer_peer->is_server_relay_supported()) {
  227. // Send relay packet.
  228. relay_buffer->seek(0);
  229. relay_buffer->put_u8(NETWORK_COMMAND_SYS);
  230. relay_buffer->put_u8(SYS_COMMAND_RELAY);
  231. relay_buffer->put_32(p_to); // Set the destination.
  232. relay_buffer->put_data(p_packet, p_packet_len);
  233. multiplayer_peer->set_target_peer(1);
  234. const Vector<uint8_t> data = relay_buffer->get_data_array();
  235. return _send(data.ptr(), relay_buffer->get_position());
  236. }
  237. if (p_to > 0) {
  238. ERR_FAIL_COND_V(!connected_peers.has(p_to), ERR_BUG);
  239. multiplayer_peer->set_target_peer(p_to);
  240. return _send(p_packet, p_packet_len);
  241. } else {
  242. for (const int &pid : connected_peers) {
  243. if (p_to && pid == -p_to) {
  244. continue;
  245. }
  246. multiplayer_peer->set_target_peer(pid);
  247. _send(p_packet, p_packet_len);
  248. }
  249. return OK;
  250. }
  251. }
  252. void SceneMultiplayer::_process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel) {
  253. ERR_FAIL_COND_MSG(p_packet_len < SYS_CMD_SIZE, "Invalid packet received. Size too small.");
  254. uint8_t sys_cmd_type = p_packet[1];
  255. int32_t peer = int32_t(decode_uint32(&p_packet[2]));
  256. switch (sys_cmd_type) {
  257. case SYS_COMMAND_ADD_PEER: {
  258. ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
  259. _admit_peer(peer); // Relayed peers are automatically accepted.
  260. } break;
  261. case SYS_COMMAND_DEL_PEER: {
  262. ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
  263. _del_peer(peer);
  264. } break;
  265. case SYS_COMMAND_RELAY: {
  266. ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported());
  267. ERR_FAIL_COND(p_packet_len < SYS_CMD_SIZE + 1);
  268. const uint8_t *packet = p_packet + SYS_CMD_SIZE;
  269. int len = p_packet_len - SYS_CMD_SIZE;
  270. bool should_process = false;
  271. if (get_unique_id() == 1) { // I am the server.
  272. // The requested target might have disconnected while the packet was in transit.
  273. if (unlikely(peer > 0 && !connected_peers.has(peer))) {
  274. return;
  275. }
  276. // Send relay packet.
  277. relay_buffer->seek(0);
  278. relay_buffer->put_u8(NETWORK_COMMAND_SYS);
  279. relay_buffer->put_u8(SYS_COMMAND_RELAY);
  280. relay_buffer->put_32(p_from); // Set the source.
  281. relay_buffer->put_data(packet, len);
  282. const Vector<uint8_t> data = relay_buffer->get_data_array();
  283. multiplayer_peer->set_transfer_mode(p_mode);
  284. multiplayer_peer->set_transfer_channel(p_channel);
  285. if (peer > 0) {
  286. // Single destination.
  287. multiplayer_peer->set_target_peer(peer);
  288. _send(data.ptr(), relay_buffer->get_position());
  289. } else {
  290. // Multiple destinations.
  291. for (const int &P : connected_peers) {
  292. // Not to sender, nor excluded.
  293. if (P == p_from || P == -peer) {
  294. continue;
  295. }
  296. multiplayer_peer->set_target_peer(P);
  297. _send(data.ptr(), relay_buffer->get_position());
  298. }
  299. if (peer != -1) {
  300. // The server is one of the targets, process the packet with sender as source.
  301. should_process = true;
  302. peer = p_from;
  303. }
  304. }
  305. } else {
  306. ERR_FAIL_COND(p_from != 1); // Bug.
  307. should_process = true;
  308. }
  309. if (should_process) {
  310. remote_sender_id = peer;
  311. _process_packet(peer, packet, len);
  312. remote_sender_id = 0;
  313. }
  314. } break;
  315. default: {
  316. ERR_FAIL();
  317. }
  318. }
  319. }
  320. void SceneMultiplayer::_add_peer(int p_id) {
  321. if (auth_callback.is_valid()) {
  322. pending_peers[p_id] = PendingPeer();
  323. pending_peers[p_id].time = OS::get_singleton()->get_ticks_msec();
  324. emit_signal(SNAME("peer_authenticating"), p_id);
  325. return;
  326. } else {
  327. _admit_peer(p_id);
  328. }
  329. }
  330. void SceneMultiplayer::_admit_peer(int p_id) {
  331. if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
  332. // Notify others of connection, and send connected peers to newly connected one.
  333. uint8_t buf[SYS_CMD_SIZE];
  334. buf[0] = NETWORK_COMMAND_SYS;
  335. buf[1] = SYS_COMMAND_ADD_PEER;
  336. multiplayer_peer->set_transfer_channel(0);
  337. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  338. for (const int &P : connected_peers) {
  339. // Send new peer to already connected.
  340. encode_uint32(p_id, &buf[2]);
  341. multiplayer_peer->set_target_peer(P);
  342. _send(buf, sizeof(buf));
  343. // Send already connected to new peer.
  344. encode_uint32(P, &buf[2]);
  345. multiplayer_peer->set_target_peer(p_id);
  346. _send(buf, sizeof(buf));
  347. }
  348. }
  349. connected_peers.insert(p_id);
  350. cache->on_peer_change(p_id, true);
  351. replicator->on_peer_change(p_id, true);
  352. if (p_id == 1) {
  353. emit_signal(SNAME("connected_to_server"));
  354. }
  355. emit_signal(SNAME("peer_connected"), p_id);
  356. }
  357. void SceneMultiplayer::_del_peer(int p_id) {
  358. if (pending_peers.has(p_id)) {
  359. pending_peers.erase(p_id);
  360. emit_signal(SNAME("peer_authentication_failed"), p_id);
  361. return;
  362. } else if (!connected_peers.has(p_id)) {
  363. return;
  364. }
  365. if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
  366. // Notify others of disconnection.
  367. uint8_t buf[SYS_CMD_SIZE];
  368. buf[0] = NETWORK_COMMAND_SYS;
  369. buf[1] = SYS_COMMAND_DEL_PEER;
  370. multiplayer_peer->set_transfer_channel(0);
  371. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  372. encode_uint32(p_id, &buf[2]);
  373. for (const int &P : connected_peers) {
  374. if (P == p_id) {
  375. continue;
  376. }
  377. multiplayer_peer->set_target_peer(P);
  378. _send(buf, sizeof(buf));
  379. }
  380. }
  381. replicator->on_peer_change(p_id, false);
  382. cache->on_peer_change(p_id, false);
  383. connected_peers.erase(p_id);
  384. emit_signal(SNAME("peer_disconnected"), p_id);
  385. }
  386. void SceneMultiplayer::disconnect_peer(int p_id) {
  387. ERR_FAIL_COND(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED);
  388. // Block signals to avoid emitting peer_disconnected.
  389. bool blocking = is_blocking_signals();
  390. set_block_signals(true);
  391. _del_peer(p_id);
  392. set_block_signals(blocking);
  393. multiplayer_peer->disconnect_peer(p_id);
  394. }
  395. Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, MultiplayerPeer::TransferMode p_mode, int p_channel) {
  396. ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  397. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no multiplayer peer is active.");
  398. 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.");
  399. if (packet_cache.size() < p_data.size() + 1) {
  400. packet_cache.resize(p_data.size() + 1);
  401. }
  402. const uint8_t *r = p_data.ptr();
  403. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  404. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  405. multiplayer_peer->set_transfer_channel(p_channel);
  406. multiplayer_peer->set_transfer_mode(p_mode);
  407. return send_command(p_to, packet_cache.ptr(), p_data.size() + 1);
  408. }
  409. Error SceneMultiplayer::send_auth(int p_to, Vector<uint8_t> p_data) {
  410. ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  411. ERR_FAIL_COND_V(!pending_peers.has(p_to), ERR_INVALID_PARAMETER);
  412. ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_PARAMETER);
  413. ERR_FAIL_COND_V_MSG(pending_peers[p_to].local, ERR_FILE_CANT_WRITE, "The authentication session was previously marked as completed, no more authentication data can be sent.");
  414. ERR_FAIL_COND_V_MSG(pending_peers[p_to].remote, ERR_FILE_CANT_WRITE, "The remote peer notified that the authentication session was completed, no more authentication data can be sent.");
  415. if (packet_cache.size() < p_data.size() + 2) {
  416. packet_cache.resize(p_data.size() + 2);
  417. }
  418. packet_cache.write[0] = NETWORK_COMMAND_SYS;
  419. packet_cache.write[1] = SYS_COMMAND_AUTH;
  420. memcpy(&packet_cache.write[2], p_data.ptr(), p_data.size());
  421. multiplayer_peer->set_target_peer(p_to);
  422. multiplayer_peer->set_transfer_channel(0);
  423. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  424. return _send(packet_cache.ptr(), p_data.size() + 2);
  425. }
  426. Error SceneMultiplayer::complete_auth(int p_peer) {
  427. ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  428. ERR_FAIL_COND_V(!pending_peers.has(p_peer), ERR_INVALID_PARAMETER);
  429. ERR_FAIL_COND_V_MSG(pending_peers[p_peer].local, ERR_FILE_CANT_WRITE, "The authentication session was already marked as completed.");
  430. pending_peers[p_peer].local = true;
  431. // Notify the remote peer that the authentication has completed.
  432. uint8_t buf[2] = { NETWORK_COMMAND_SYS, SYS_COMMAND_AUTH };
  433. multiplayer_peer->set_target_peer(p_peer);
  434. multiplayer_peer->set_transfer_channel(0);
  435. multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
  436. Error err = _send(buf, 2);
  437. // The remote peer already reported the authentication as completed, so admit the peer.
  438. // May generate new packets, so it must happen after sending confirmation.
  439. if (pending_peers[p_peer].remote) {
  440. pending_peers.erase(p_peer);
  441. _admit_peer(p_peer);
  442. }
  443. return err;
  444. }
  445. void SceneMultiplayer::set_auth_callback(Callable p_callback) {
  446. auth_callback = p_callback;
  447. }
  448. Callable SceneMultiplayer::get_auth_callback() const {
  449. return auth_callback;
  450. }
  451. void SceneMultiplayer::set_auth_timeout(double p_timeout) {
  452. ERR_FAIL_COND_MSG(p_timeout < 0, "Timeout must be greater or equal to 0 (where 0 means no timeout)");
  453. auth_timeout = uint64_t(p_timeout * 1000);
  454. }
  455. double SceneMultiplayer::get_auth_timeout() const {
  456. return double(auth_timeout) / 1000.0;
  457. }
  458. void SceneMultiplayer::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  459. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  460. Vector<uint8_t> out;
  461. int len = p_packet_len - 1;
  462. out.resize(len);
  463. {
  464. uint8_t *w = out.ptrw();
  465. memcpy(&w[0], &p_packet[1], len);
  466. }
  467. emit_signal(SNAME("peer_packet"), p_from, out);
  468. }
  469. int SceneMultiplayer::get_unique_id() {
  470. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), 0, "No multiplayer peer is assigned. Unable to get unique ID.");
  471. return multiplayer_peer->get_unique_id();
  472. }
  473. void SceneMultiplayer::set_refuse_new_connections(bool p_refuse) {
  474. ERR_FAIL_COND_MSG(!multiplayer_peer.is_valid(), "No multiplayer peer is assigned. Unable to set 'refuse_new_connections'.");
  475. multiplayer_peer->set_refuse_new_connections(p_refuse);
  476. }
  477. bool SceneMultiplayer::is_refusing_new_connections() const {
  478. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), false, "No multiplayer peer is assigned. Unable to get 'refuse_new_connections'.");
  479. return multiplayer_peer->is_refusing_new_connections();
  480. }
  481. Vector<int> SceneMultiplayer::get_peer_ids() {
  482. ERR_FAIL_COND_V_MSG(!multiplayer_peer.is_valid(), Vector<int>(), "No multiplayer peer is assigned. Assume no peers are connected.");
  483. Vector<int> ret;
  484. for (const int &E : connected_peers) {
  485. ret.push_back(E);
  486. }
  487. return ret;
  488. }
  489. Vector<int> SceneMultiplayer::get_authenticating_peer_ids() {
  490. Vector<int> out;
  491. out.resize(pending_peers.size());
  492. int idx = 0;
  493. for (const KeyValue<int, PendingPeer> &E : pending_peers) {
  494. out.write[idx++] = E.key;
  495. }
  496. return out;
  497. }
  498. void SceneMultiplayer::set_allow_object_decoding(bool p_enable) {
  499. allow_object_decoding = p_enable;
  500. }
  501. bool SceneMultiplayer::is_object_decoding_allowed() const {
  502. return allow_object_decoding;
  503. }
  504. String SceneMultiplayer::get_rpc_md5(const Object *p_obj) {
  505. return rpc->get_rpc_md5(p_obj);
  506. }
  507. Error SceneMultiplayer::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  508. return rpc->rpcp(p_obj, p_peer_id, p_method, p_arg, p_argcount);
  509. }
  510. Error SceneMultiplayer::object_configuration_add(Object *p_obj, Variant p_config) {
  511. if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
  512. set_root_path(p_config);
  513. return OK;
  514. }
  515. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  516. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  517. if (spawner) {
  518. return replicator->on_spawn(p_obj, p_config);
  519. } else if (sync) {
  520. return replicator->on_replication_start(p_obj, p_config);
  521. }
  522. return ERR_INVALID_PARAMETER;
  523. }
  524. Error SceneMultiplayer::object_configuration_remove(Object *p_obj, Variant p_config) {
  525. if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
  526. ERR_FAIL_COND_V(root_path != p_config.operator NodePath(), ERR_INVALID_PARAMETER);
  527. set_root_path(NodePath());
  528. return OK;
  529. }
  530. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  531. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  532. if (spawner) {
  533. return replicator->on_despawn(p_obj, p_config);
  534. }
  535. if (sync) {
  536. return replicator->on_replication_stop(p_obj, p_config);
  537. }
  538. return ERR_INVALID_PARAMETER;
  539. }
  540. void SceneMultiplayer::set_server_relay_enabled(bool p_enabled) {
  541. server_relay = p_enabled;
  542. }
  543. bool SceneMultiplayer::is_server_relay_enabled() const {
  544. return server_relay;
  545. }
  546. void SceneMultiplayer::set_max_sync_packet_size(int p_size) {
  547. replicator->set_max_sync_packet_size(p_size);
  548. }
  549. int SceneMultiplayer::get_max_sync_packet_size() const {
  550. return replicator->get_max_sync_packet_size();
  551. }
  552. void SceneMultiplayer::set_max_delta_packet_size(int p_size) {
  553. replicator->set_max_delta_packet_size(p_size);
  554. }
  555. int SceneMultiplayer::get_max_delta_packet_size() const {
  556. return replicator->get_max_delta_packet_size();
  557. }
  558. void SceneMultiplayer::_bind_methods() {
  559. ClassDB::bind_method(D_METHOD("set_root_path", "path"), &SceneMultiplayer::set_root_path);
  560. ClassDB::bind_method(D_METHOD("get_root_path"), &SceneMultiplayer::get_root_path);
  561. ClassDB::bind_method(D_METHOD("clear"), &SceneMultiplayer::clear);
  562. ClassDB::bind_method(D_METHOD("disconnect_peer", "id"), &SceneMultiplayer::disconnect_peer);
  563. ClassDB::bind_method(D_METHOD("get_authenticating_peers"), &SceneMultiplayer::get_authenticating_peer_ids);
  564. ClassDB::bind_method(D_METHOD("send_auth", "id", "data"), &SceneMultiplayer::send_auth);
  565. ClassDB::bind_method(D_METHOD("complete_auth", "id"), &SceneMultiplayer::complete_auth);
  566. ClassDB::bind_method(D_METHOD("set_auth_callback", "callback"), &SceneMultiplayer::set_auth_callback);
  567. ClassDB::bind_method(D_METHOD("get_auth_callback"), &SceneMultiplayer::get_auth_callback);
  568. ClassDB::bind_method(D_METHOD("set_auth_timeout", "timeout"), &SceneMultiplayer::set_auth_timeout);
  569. ClassDB::bind_method(D_METHOD("get_auth_timeout"), &SceneMultiplayer::get_auth_timeout);
  570. ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "refuse"), &SceneMultiplayer::set_refuse_new_connections);
  571. ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &SceneMultiplayer::is_refusing_new_connections);
  572. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &SceneMultiplayer::set_allow_object_decoding);
  573. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &SceneMultiplayer::is_object_decoding_allowed);
  574. ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &SceneMultiplayer::set_server_relay_enabled);
  575. ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &SceneMultiplayer::is_server_relay_enabled);
  576. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &SceneMultiplayer::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
  577. ClassDB::bind_method(D_METHOD("get_max_sync_packet_size"), &SceneMultiplayer::get_max_sync_packet_size);
  578. ClassDB::bind_method(D_METHOD("set_max_sync_packet_size", "size"), &SceneMultiplayer::set_max_sync_packet_size);
  579. ClassDB::bind_method(D_METHOD("get_max_delta_packet_size"), &SceneMultiplayer::get_max_delta_packet_size);
  580. ClassDB::bind_method(D_METHOD("set_max_delta_packet_size", "size"), &SceneMultiplayer::set_max_delta_packet_size);
  581. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
  582. ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "auth_callback"), "set_auth_callback", "get_auth_callback");
  583. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "auth_timeout", PROPERTY_HINT_RANGE, "0,30,0.1,or_greater,suffix:s"), "set_auth_timeout", "get_auth_timeout");
  584. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  585. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections");
  586. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
  587. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_sync_packet_size"), "set_max_sync_packet_size", "get_max_sync_packet_size");
  588. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_delta_packet_size"), "set_max_delta_packet_size", "get_max_delta_packet_size");
  589. ADD_PROPERTY_DEFAULT("refuse_new_connections", false);
  590. ADD_SIGNAL(MethodInfo("peer_authenticating", PropertyInfo(Variant::INT, "id")));
  591. ADD_SIGNAL(MethodInfo("peer_authentication_failed", PropertyInfo(Variant::INT, "id")));
  592. ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  593. }
  594. SceneMultiplayer::SceneMultiplayer() {
  595. relay_buffer.instantiate();
  596. cache.instantiate(this);
  597. replicator.instantiate(this, cache.ptr());
  598. rpc.instantiate(this, cache.ptr(), replicator.ptr());
  599. set_multiplayer_peer(Ref<OfflineMultiplayerPeer>(memnew(OfflineMultiplayerPeer)));
  600. }
  601. SceneMultiplayer::~SceneMultiplayer() {
  602. clear();
  603. // Ensure unref in reverse order for safety (we shouldn't use those pointers in the deconstructors anyway).
  604. rpc.unref();
  605. replicator.unref();
  606. cache.unref();
  607. }