enet_multiplayer_peer.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*************************************************************************/
  2. /* enet_multiplayer_peer.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 "enet_multiplayer_peer.h"
  31. #include "core/io/ip.h"
  32. #include "core/io/marshalls.h"
  33. #include "core/os/os.h"
  34. void ENetMultiplayerPeer::set_target_peer(int p_peer) {
  35. target_peer = p_peer;
  36. }
  37. int ENetMultiplayerPeer::get_packet_peer() const {
  38. ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
  39. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  40. return incoming_packets.front()->get().from;
  41. }
  42. Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
  43. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  44. set_refuse_new_connections(false);
  45. Ref<ENetConnection> host;
  46. host.instantiate();
  47. Error err = host->create_host_bound(bind_ip, p_port, p_max_clients, 0, p_max_channels > 0 ? p_max_channels + SYSCH_MAX : 0, p_out_bandwidth);
  48. if (err != OK) {
  49. return err;
  50. }
  51. active_mode = MODE_SERVER;
  52. unique_id = 1;
  53. connection_status = CONNECTION_CONNECTED;
  54. hosts[0] = host;
  55. return OK;
  56. }
  57. Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, int p_channel_count, int p_in_bandwidth, int p_out_bandwidth, int p_local_port) {
  58. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  59. set_refuse_new_connections(false);
  60. Ref<ENetConnection> host;
  61. host.instantiate();
  62. Error err;
  63. if (p_local_port) {
  64. err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth);
  65. } else {
  66. err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth);
  67. }
  68. if (err != OK) {
  69. return err;
  70. }
  71. unique_id = generate_unique_id();
  72. Ref<ENetPacketPeer> peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id);
  73. if (peer.is_null()) {
  74. host->destroy();
  75. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server.");
  76. }
  77. // Need to wait for CONNECT event.
  78. connection_status = CONNECTION_CONNECTING;
  79. active_mode = MODE_CLIENT;
  80. peers[1] = peer;
  81. hosts[0] = host;
  82. return OK;
  83. }
  84. Error ENetMultiplayerPeer::create_mesh(int p_id) {
  85. ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0");
  86. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  87. active_mode = MODE_MESH;
  88. unique_id = p_id;
  89. connection_status = CONNECTION_CONNECTED;
  90. return OK;
  91. }
  92. Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) {
  93. ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER);
  94. ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first.");
  95. List<Ref<ENetPacketPeer>> host_peers;
  96. p_host->get_peers(host_peers);
  97. ERR_FAIL_COND_V_MSG(host_peers.size() != 1 || host_peers[0]->get_state() != ENetPacketPeer::STATE_CONNECTED, ERR_INVALID_PARAMETER, "The provided host must have exactly one peer in the connected state.");
  98. hosts[p_id] = p_host;
  99. peers[p_id] = host_peers[0];
  100. emit_signal(SNAME("peer_connected"), p_id);
  101. return OK;
  102. }
  103. bool ENetMultiplayerPeer::_parse_server_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event) {
  104. switch (p_type) {
  105. case ENetConnection::EVENT_CONNECT: {
  106. if (is_refusing_new_connections()) {
  107. p_event.peer->reset();
  108. return false;
  109. }
  110. // Client joined with invalid ID, probably trying to exploit us.
  111. if (p_event.data < 2 || peers.has((int)p_event.data)) {
  112. p_event.peer->reset();
  113. return false;
  114. }
  115. int id = p_event.data;
  116. p_event.peer->set_meta(SNAME("_net_id"), id);
  117. peers[id] = p_event.peer;
  118. emit_signal(SNAME("peer_connected"), id);
  119. if (server_relay) {
  120. _notify_peers(id, true);
  121. }
  122. return false;
  123. }
  124. case ENetConnection::EVENT_DISCONNECT: {
  125. int id = p_event.peer->get_meta(SNAME("_net_id"));
  126. if (!peers.has(id)) {
  127. // Never fully connected.
  128. return false;
  129. }
  130. emit_signal(SNAME("peer_disconnected"), id);
  131. peers.erase(id);
  132. if (server_relay) {
  133. _notify_peers(id, false);
  134. }
  135. return false;
  136. }
  137. case ENetConnection::EVENT_RECEIVE: {
  138. if (p_event.channel_id == SYSCH_CONFIG) {
  139. _destroy_unused(p_event.packet);
  140. ERR_FAIL_V_MSG(false, "Only server can send config messages");
  141. } else {
  142. if (p_event.packet->dataLength < 8) {
  143. _destroy_unused(p_event.packet);
  144. ERR_FAIL_V_MSG(false, "Invalid packet size");
  145. }
  146. uint32_t source = decode_uint32(&p_event.packet->data[0]);
  147. int target = decode_uint32(&p_event.packet->data[4]);
  148. uint32_t id = p_event.peer->get_meta(SNAME("_net_id"));
  149. // Someone is cheating and trying to fake the source!
  150. if (source != id) {
  151. _destroy_unused(p_event.packet);
  152. ERR_FAIL_V_MSG(false, "Someone is cheating and trying to fake the source!");
  153. }
  154. Packet packet;
  155. packet.packet = p_event.packet;
  156. packet.channel = p_event.channel_id;
  157. packet.from = id;
  158. // Even if relaying is disabled, these targets are valid as incoming packets.
  159. if (target == 1 || target == 0 || target < -1) {
  160. packet.packet->referenceCount++;
  161. incoming_packets.push_back(packet);
  162. }
  163. if (server_relay && target != 1) {
  164. packet.packet->referenceCount++;
  165. _relay(source, target, p_event.channel_id, p_event.packet);
  166. packet.packet->referenceCount--;
  167. _destroy_unused(p_event.packet);
  168. }
  169. // Destroy packet later
  170. }
  171. return false;
  172. }
  173. default:
  174. return true;
  175. }
  176. }
  177. bool ENetMultiplayerPeer::_parse_client_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event) {
  178. switch (p_type) {
  179. case ENetConnection::EVENT_CONNECT: {
  180. connection_status = CONNECTION_CONNECTED;
  181. emit_signal(SNAME("peer_connected"), 1);
  182. emit_signal(SNAME("connection_succeeded"));
  183. return false;
  184. }
  185. case ENetConnection::EVENT_DISCONNECT: {
  186. if (connection_status == CONNECTION_CONNECTED) {
  187. // Client just disconnected from server.
  188. emit_signal(SNAME("server_disconnected"));
  189. } else {
  190. emit_signal(SNAME("connection_failed"));
  191. }
  192. close_connection();
  193. return true;
  194. }
  195. case ENetConnection::EVENT_RECEIVE: {
  196. if (p_event.channel_id == SYSCH_CONFIG) {
  197. // Config message
  198. if (p_event.packet->dataLength != 8) {
  199. _destroy_unused(p_event.packet);
  200. ERR_FAIL_V(false);
  201. }
  202. int msg = decode_uint32(&p_event.packet->data[0]);
  203. int id = decode_uint32(&p_event.packet->data[4]);
  204. switch (msg) {
  205. case SYSMSG_ADD_PEER: {
  206. peers[id] = Ref<ENetPacketPeer>();
  207. emit_signal(SNAME("peer_connected"), id);
  208. } break;
  209. case SYSMSG_REMOVE_PEER: {
  210. peers.erase(id);
  211. emit_signal(SNAME("peer_disconnected"), id);
  212. } break;
  213. }
  214. _destroy_unused(p_event.packet);
  215. } else {
  216. if (p_event.packet->dataLength < 8) {
  217. _destroy_unused(p_event.packet);
  218. ERR_FAIL_V_MSG(false, "Invalid packet size");
  219. }
  220. uint32_t source = decode_uint32(&p_event.packet->data[0]);
  221. Packet packet;
  222. packet.packet = p_event.packet;
  223. packet.from = source;
  224. packet.channel = p_event.channel_id;
  225. packet.packet->referenceCount++;
  226. incoming_packets.push_back(packet);
  227. // Destroy packet later
  228. }
  229. return false;
  230. }
  231. default:
  232. return true;
  233. }
  234. }
  235. bool ENetMultiplayerPeer::_parse_mesh_event(ENetConnection::EventType p_type, ENetConnection::Event &p_event, int p_peer_id) {
  236. switch (p_type) {
  237. case ENetConnection::EVENT_CONNECT:
  238. p_event.peer->reset();
  239. return false;
  240. case ENetConnection::EVENT_DISCONNECT:
  241. if (peers.has(p_peer_id)) {
  242. emit_signal(SNAME("peer_disconnected"), p_peer_id);
  243. peers.erase(p_peer_id);
  244. }
  245. hosts.erase(p_peer_id);
  246. return true;
  247. case ENetConnection::EVENT_RECEIVE: {
  248. if (p_event.packet->dataLength < 8) {
  249. _destroy_unused(p_event.packet);
  250. ERR_FAIL_V_MSG(false, "Invalid packet size");
  251. }
  252. Packet packet;
  253. packet.packet = p_event.packet;
  254. packet.from = p_peer_id;
  255. packet.channel = p_event.channel_id;
  256. packet.packet->referenceCount++;
  257. incoming_packets.push_back(packet);
  258. return false;
  259. } break;
  260. default:
  261. // Nothing to do
  262. return true;
  263. }
  264. }
  265. void ENetMultiplayerPeer::poll() {
  266. ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active.");
  267. _pop_current_packet();
  268. switch (active_mode) {
  269. case MODE_CLIENT: {
  270. if (peers.has(1) && !peers[1]->is_active()) {
  271. if (connection_status == CONNECTION_CONNECTED) {
  272. // Client just disconnected from server.
  273. emit_signal(SNAME("server_disconnected"));
  274. } else {
  275. emit_signal(SNAME("connection_failed"));
  276. }
  277. close_connection();
  278. return;
  279. }
  280. ENetConnection::Event event;
  281. ENetConnection::EventType ret = hosts[0]->service(0, event);
  282. if (ret == ENetConnection::EVENT_ERROR) {
  283. return;
  284. }
  285. do {
  286. if (_parse_client_event(ret, event)) {
  287. return;
  288. }
  289. } while (hosts[0]->check_events(ret, event) > 0);
  290. } break;
  291. case MODE_SERVER: {
  292. for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  293. if (!(E.value->is_active())) {
  294. emit_signal(SNAME("peer_disconnected"), E.value->get_meta(SNAME("_net_id")));
  295. peers.erase(E.key);
  296. }
  297. }
  298. ENetConnection::Event event;
  299. ENetConnection::EventType ret = hosts[0]->service(0, event);
  300. if (ret == ENetConnection::EVENT_ERROR) {
  301. return;
  302. }
  303. do {
  304. if (_parse_server_event(ret, event)) {
  305. return;
  306. }
  307. } while (hosts[0]->check_events(ret, event) > 0);
  308. } break;
  309. case MODE_MESH: {
  310. for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  311. if (!(E.value->is_active())) {
  312. emit_signal(SNAME("peer_disconnected"), E.key);
  313. peers.erase(E.key);
  314. if (hosts.has(E.key)) {
  315. hosts.erase(E.key);
  316. }
  317. }
  318. }
  319. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  320. ENetConnection::Event event;
  321. ENetConnection::EventType ret = E.value->service(0, event);
  322. if (ret == ENetConnection::EVENT_ERROR) {
  323. if (peers.has(E.key)) {
  324. emit_signal(SNAME("peer_disconnected"), E.key);
  325. peers.erase(E.key);
  326. }
  327. hosts.erase(E.key);
  328. continue;
  329. }
  330. do {
  331. if (_parse_mesh_event(ret, event, E.key)) {
  332. break; // Keep polling the others.
  333. }
  334. } while (E.value->check_events(ret, event) > 0);
  335. }
  336. } break;
  337. default:
  338. return;
  339. }
  340. }
  341. bool ENetMultiplayerPeer::is_server() const {
  342. return active_mode == MODE_SERVER;
  343. }
  344. void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) {
  345. if (!_is_active()) {
  346. return;
  347. }
  348. _pop_current_packet();
  349. bool peers_disconnected = false;
  350. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  351. if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) {
  352. E.value->peer_disconnect_now(unique_id);
  353. peers_disconnected = true;
  354. }
  355. }
  356. if (peers_disconnected) {
  357. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  358. E.value->flush();
  359. }
  360. if (wait_usec > 0) {
  361. OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send
  362. }
  363. }
  364. active_mode = MODE_NONE;
  365. incoming_packets.clear();
  366. peers.clear();
  367. hosts.clear();
  368. unique_id = 0;
  369. connection_status = CONNECTION_DISCONNECTED;
  370. set_refuse_new_connections(false);
  371. }
  372. int ENetMultiplayerPeer::get_available_packet_count() const {
  373. return incoming_packets.size();
  374. }
  375. Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  376. ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available.");
  377. _pop_current_packet();
  378. current_packet = incoming_packets.front()->get();
  379. incoming_packets.pop_front();
  380. *r_buffer = (const uint8_t *)(&current_packet.packet->data[8]);
  381. r_buffer_size = current_packet.packet->dataLength - 8;
  382. return OK;
  383. }
  384. Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  385. ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");
  386. ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");
  387. ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(ABS(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));
  388. ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG);
  389. int packet_flags = 0;
  390. int channel = SYSCH_RELIABLE;
  391. int transfer_channel = get_transfer_channel();
  392. if (transfer_channel > 0) {
  393. channel = SYSCH_MAX + transfer_channel - 1;
  394. } else {
  395. switch (get_transfer_mode()) {
  396. case TRANSFER_MODE_UNRELIABLE: {
  397. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
  398. channel = SYSCH_UNRELIABLE;
  399. } break;
  400. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  401. packet_flags = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
  402. channel = SYSCH_UNRELIABLE;
  403. } break;
  404. case TRANSFER_MODE_RELIABLE: {
  405. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  406. channel = SYSCH_RELIABLE;
  407. } break;
  408. }
  409. }
  410. #ifdef DEBUG_ENABLED
  411. if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size + 8 > ENET_HOST_DEFAULT_MTU) {
  412. WARN_PRINT_ONCE(vformat("Sending %d bytes unrealiably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size + 8, ENET_HOST_DEFAULT_MTU));
  413. }
  414. #endif
  415. ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size + 8, packet_flags);
  416. encode_uint32(unique_id, &packet->data[0]); // Source ID
  417. encode_uint32(target_peer, &packet->data[4]); // Dest ID
  418. memcpy(&packet->data[8], p_buffer, p_buffer_size);
  419. if (is_server()) {
  420. if (target_peer == 0) {
  421. hosts[0]->broadcast(channel, packet);
  422. } else if (target_peer < 0) {
  423. // Send to all but one and make copies for sending.
  424. int exclude = -target_peer;
  425. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  426. if (E.key == exclude) {
  427. continue;
  428. }
  429. E.value->send(channel, packet);
  430. }
  431. _destroy_unused(packet);
  432. } else {
  433. peers[target_peer]->send(channel, packet);
  434. }
  435. ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
  436. hosts[0]->flush();
  437. } else if (active_mode == MODE_CLIENT) {
  438. peers[1]->send(channel, packet); // Send to server for broadcast.
  439. ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
  440. hosts[0]->flush();
  441. } else {
  442. if (target_peer <= 0) {
  443. int exclude = ABS(target_peer);
  444. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  445. if (E.key == exclude) {
  446. continue;
  447. }
  448. E.value->send(channel, packet);
  449. ERR_CONTINUE(!hosts.has(E.key));
  450. hosts[E.key]->flush();
  451. }
  452. _destroy_unused(packet);
  453. } else {
  454. peers[target_peer]->send(channel, packet);
  455. ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG);
  456. hosts[target_peer]->flush();
  457. }
  458. }
  459. return OK;
  460. }
  461. int ENetMultiplayerPeer::get_max_packet_size() const {
  462. return 1 << 24; // Anything is good
  463. }
  464. void ENetMultiplayerPeer::_pop_current_packet() {
  465. if (current_packet.packet) {
  466. current_packet.packet->referenceCount--;
  467. _destroy_unused(current_packet.packet);
  468. current_packet.packet = nullptr;
  469. current_packet.from = 0;
  470. current_packet.channel = -1;
  471. }
  472. }
  473. MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const {
  474. return connection_status;
  475. }
  476. int ENetMultiplayerPeer::get_unique_id() const {
  477. ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active.");
  478. return unique_id;
  479. }
  480. void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) {
  481. #ifdef GODOT_ENET
  482. if (_is_active()) {
  483. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  484. E.value->refuse_new_connections(p_enabled);
  485. }
  486. }
  487. #endif
  488. MultiplayerPeer::set_refuse_new_connections(p_enabled);
  489. }
  490. void ENetMultiplayerPeer::set_server_relay_enabled(bool p_enabled) {
  491. ERR_FAIL_COND_MSG(_is_active(), "Server relaying can't be toggled while the multiplayer instance is active.");
  492. server_relay = p_enabled;
  493. }
  494. bool ENetMultiplayerPeer::is_server_relay_enabled() const {
  495. return server_relay;
  496. }
  497. Ref<ENetConnection> ENetMultiplayerPeer::get_host() const {
  498. ERR_FAIL_COND_V(!_is_active(), nullptr);
  499. ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr);
  500. return hosts[0];
  501. }
  502. Ref<ENetPacketPeer> ENetMultiplayerPeer::get_peer(int p_id) const {
  503. ERR_FAIL_COND_V(!_is_active(), nullptr);
  504. ERR_FAIL_COND_V(!peers.has(p_id), nullptr);
  505. ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr);
  506. return peers[p_id];
  507. }
  508. void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) {
  509. if (p_packet->referenceCount == 0) {
  510. enet_packet_destroy(p_packet);
  511. }
  512. }
  513. void ENetMultiplayerPeer::_relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet) {
  514. if (p_to == 0) {
  515. // Re-send to everyone but sender :|
  516. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  517. if (E.key == p_from) {
  518. continue;
  519. }
  520. E.value->send(p_channel, p_packet);
  521. }
  522. } else if (p_to < 0) {
  523. // Re-send to everyone but excluded and sender.
  524. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  525. if (E.key == p_from || E.key == -p_to) { // Do not resend to self, also do not send to excluded
  526. continue;
  527. }
  528. E.value->send(p_channel, p_packet);
  529. }
  530. } else {
  531. // To someone else, specifically
  532. ERR_FAIL_COND(!peers.has(p_to));
  533. ENetPacket *packet = enet_packet_create(p_packet->data, p_packet->dataLength, p_packet->flags);
  534. peers[p_to]->send(p_channel, packet);
  535. }
  536. }
  537. void ENetMultiplayerPeer::_notify_peers(int p_id, bool p_connected) {
  538. if (p_connected) {
  539. ERR_FAIL_COND(!peers.has(p_id));
  540. // Someone connected, notify all the peers available.
  541. Ref<ENetPacketPeer> peer = peers[p_id];
  542. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  543. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  544. encode_uint32(p_id, &packet->data[4]);
  545. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  546. if (E.key == p_id) {
  547. continue;
  548. }
  549. // Send new peer to existing peer.
  550. E.value->send(SYSCH_CONFIG, packet);
  551. // Send existing peer to new peer.
  552. // This packet will be automatically destroyed by ENet after send.
  553. ENetPacket *packet2 = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  554. encode_uint32(SYSMSG_ADD_PEER, &packet2->data[0]);
  555. encode_uint32(E.key, &packet2->data[4]);
  556. peer->send(SYSCH_CONFIG, packet2);
  557. }
  558. _destroy_unused(packet);
  559. } else {
  560. // Server just received a client disconnect and is in relay mode, notify everyone else.
  561. ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE);
  562. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  563. encode_uint32(p_id, &packet->data[4]);
  564. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  565. if (E.key == p_id) {
  566. continue;
  567. }
  568. E.value->send(SYSCH_CONFIG, packet);
  569. }
  570. _destroy_unused(packet);
  571. }
  572. }
  573. void ENetMultiplayerPeer::_bind_methods() {
  574. ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));
  575. ClassDB::bind_method(D_METHOD("create_client", "address", "port", "channel_count", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0), DEFVAL(0));
  576. ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh);
  577. ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer);
  578. ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &ENetMultiplayerPeer::close_connection, DEFVAL(100));
  579. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip);
  580. ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &ENetMultiplayerPeer::set_server_relay_enabled);
  581. ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &ENetMultiplayerPeer::is_server_relay_enabled);
  582. ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host);
  583. ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer);
  584. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
  585. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host");
  586. }
  587. ENetMultiplayerPeer::ENetMultiplayerPeer() {
  588. bind_ip = IPAddress("*");
  589. }
  590. ENetMultiplayerPeer::~ENetMultiplayerPeer() {
  591. if (_is_active()) {
  592. close_connection();
  593. }
  594. }
  595. // Sets IP for ENet to bind when using create_server or create_client
  596. // if no IP is set, then ENet bind to ENET_HOST_ANY
  597. void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) {
  598. ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip)));
  599. bind_ip = p_ip;
  600. }