scene_multiplayer.cpp 26 KB

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