enet_multiplayer_peer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /**************************************************************************/
  2. /* enet_multiplayer_peer.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 "enet_multiplayer_peer.h"
  31. void ENetMultiplayerPeer::set_target_peer(int p_peer) {
  32. target_peer = p_peer;
  33. }
  34. int ENetMultiplayerPeer::get_packet_peer() const {
  35. ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
  36. ERR_FAIL_COND_V(incoming_packets.is_empty(), 1);
  37. return incoming_packets.front()->get().from;
  38. }
  39. MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_packet_mode() const {
  40. ERR_FAIL_COND_V_MSG(!_is_active(), TRANSFER_MODE_RELIABLE, "The multiplayer instance isn't currently active.");
  41. ERR_FAIL_COND_V(incoming_packets.is_empty(), TRANSFER_MODE_RELIABLE);
  42. return incoming_packets.front()->get().transfer_mode;
  43. }
  44. int ENetMultiplayerPeer::get_packet_channel() const {
  45. ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");
  46. ERR_FAIL_COND_V(incoming_packets.is_empty(), 1);
  47. int ch = incoming_packets.front()->get().channel;
  48. if (ch >= SYSCH_MAX) { // First 2 channels are reserved.
  49. return ch - SYSCH_MAX + 1;
  50. }
  51. return 0;
  52. }
  53. Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {
  54. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  55. set_refuse_new_connections(false);
  56. Ref<ENetConnection> host;
  57. host.instantiate();
  58. 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);
  59. if (err != OK) {
  60. return err;
  61. }
  62. active_mode = MODE_SERVER;
  63. unique_id = 1;
  64. connection_status = CONNECTION_CONNECTED;
  65. hosts[0] = host;
  66. return OK;
  67. }
  68. 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) {
  69. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  70. set_refuse_new_connections(false);
  71. Ref<ENetConnection> host;
  72. host.instantiate();
  73. Error err;
  74. if (p_local_port) {
  75. err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth);
  76. } else {
  77. err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth);
  78. }
  79. if (err != OK) {
  80. return err;
  81. }
  82. unique_id = generate_unique_id();
  83. Ref<ENetPacketPeer> peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id);
  84. if (peer.is_null()) {
  85. host->destroy();
  86. ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server.");
  87. }
  88. // Need to wait for CONNECT event.
  89. connection_status = CONNECTION_CONNECTING;
  90. active_mode = MODE_CLIENT;
  91. peers[1] = peer;
  92. hosts[0] = host;
  93. return OK;
  94. }
  95. Error ENetMultiplayerPeer::create_mesh(int p_id) {
  96. ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0");
  97. ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");
  98. active_mode = MODE_MESH;
  99. unique_id = p_id;
  100. connection_status = CONNECTION_CONNECTED;
  101. return OK;
  102. }
  103. Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) {
  104. ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER);
  105. ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first.");
  106. List<Ref<ENetPacketPeer>> host_peers;
  107. p_host->get_peers(host_peers);
  108. ERR_FAIL_COND_V_MSG(host_peers.size() != 1 || host_peers.front()->get()->get_state() != ENetPacketPeer::STATE_CONNECTED, ERR_INVALID_PARAMETER, "The provided host must have exactly one peer in the connected state.");
  109. hosts[p_id] = p_host;
  110. peers[p_id] = host_peers.front()->get();
  111. emit_signal(SNAME("peer_connected"), p_id);
  112. return OK;
  113. }
  114. void ENetMultiplayerPeer::_store_packet(int32_t p_source, ENetConnection::Event &p_event) {
  115. Packet packet;
  116. packet.packet = p_event.packet;
  117. packet.channel = p_event.channel_id;
  118. packet.from = p_source;
  119. if (p_event.packet->flags & ENET_PACKET_FLAG_RELIABLE) {
  120. packet.transfer_mode = TRANSFER_MODE_RELIABLE;
  121. } else if (p_event.packet->flags & ENET_PACKET_FLAG_UNSEQUENCED) {
  122. packet.transfer_mode = TRANSFER_MODE_UNRELIABLE;
  123. } else {
  124. packet.transfer_mode = TRANSFER_MODE_UNRELIABLE_ORDERED;
  125. }
  126. packet.packet->referenceCount++;
  127. incoming_packets.push_back(packet);
  128. }
  129. void ENetMultiplayerPeer::_disconnect_inactive_peers() {
  130. HashSet<int> to_drop;
  131. for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  132. if (E.value->is_active()) {
  133. continue;
  134. }
  135. to_drop.insert(E.key);
  136. }
  137. for (const int &P : to_drop) {
  138. peers.erase(P);
  139. if (hosts.has(P)) {
  140. hosts.erase(P);
  141. }
  142. ERR_CONTINUE(active_mode == MODE_CLIENT && P != TARGET_PEER_SERVER);
  143. emit_signal(SNAME("peer_disconnected"), P);
  144. }
  145. }
  146. void ENetMultiplayerPeer::poll() {
  147. ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active.");
  148. _pop_current_packet();
  149. _disconnect_inactive_peers();
  150. switch (active_mode) {
  151. case MODE_CLIENT: {
  152. if (!peers.has(1)) {
  153. close();
  154. return;
  155. }
  156. ENetConnection::Event event;
  157. ENetConnection::EventType ret = hosts[0]->service(0, event);
  158. do {
  159. if (ret == ENetConnection::EVENT_CONNECT) {
  160. connection_status = CONNECTION_CONNECTED;
  161. emit_signal(SNAME("peer_connected"), 1);
  162. } else if (ret == ENetConnection::EVENT_DISCONNECT) {
  163. if (connection_status == CONNECTION_CONNECTED) {
  164. // Client just disconnected from server.
  165. emit_signal(SNAME("peer_disconnected"), 1);
  166. }
  167. close();
  168. } else if (ret == ENetConnection::EVENT_RECEIVE) {
  169. _store_packet(1, event);
  170. } else if (ret != ENetConnection::EVENT_NONE) {
  171. close(); // Error.
  172. }
  173. } while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0);
  174. } break;
  175. case MODE_SERVER: {
  176. ENetConnection::Event event;
  177. ENetConnection::EventType ret = hosts[0]->service(0, event);
  178. do {
  179. if (ret == ENetConnection::EVENT_CONNECT) {
  180. if (is_refusing_new_connections()) {
  181. event.peer->reset();
  182. continue;
  183. }
  184. // Client joined with invalid ID, probably trying to exploit us.
  185. if (event.data < 2 || peers.has((int)event.data)) {
  186. event.peer->reset();
  187. continue;
  188. }
  189. int id = event.data;
  190. event.peer->set_meta(SNAME("_net_id"), id);
  191. peers[id] = event.peer;
  192. emit_signal(SNAME("peer_connected"), id);
  193. } else if (ret == ENetConnection::EVENT_DISCONNECT) {
  194. int id = event.peer->get_meta(SNAME("_net_id"));
  195. if (!peers.has(id)) {
  196. // Never fully connected.
  197. continue;
  198. }
  199. emit_signal(SNAME("peer_disconnected"), id);
  200. peers.erase(id);
  201. } else if (ret == ENetConnection::EVENT_RECEIVE) {
  202. int32_t source = event.peer->get_meta(SNAME("_net_id"));
  203. _store_packet(source, event);
  204. } else if (ret != ENetConnection::EVENT_NONE) {
  205. close(); // Error
  206. }
  207. } while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0);
  208. } break;
  209. case MODE_MESH: {
  210. HashSet<int> to_drop;
  211. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  212. ENetConnection::Event event;
  213. ENetConnection::EventType ret = E.value->service(0, event);
  214. do {
  215. if (ret == ENetConnection::EVENT_CONNECT) {
  216. event.peer->reset();
  217. } else if (ret == ENetConnection::EVENT_RECEIVE) {
  218. _store_packet(E.key, event);
  219. } else if (ret == ENetConnection::EVENT_NONE) {
  220. break; // Keep polling the others.
  221. } else {
  222. to_drop.insert(E.key); // Error or disconnect.
  223. break; // Keep polling the others.
  224. }
  225. } while (E.value->check_events(ret, event) > 0);
  226. }
  227. for (const int &P : to_drop) {
  228. if (peers.has(P)) {
  229. emit_signal(SNAME("peer_disconnected"), P);
  230. peers.erase(P);
  231. }
  232. hosts.erase(P);
  233. }
  234. } break;
  235. default:
  236. return;
  237. }
  238. }
  239. bool ENetMultiplayerPeer::is_server() const {
  240. return active_mode == MODE_SERVER;
  241. }
  242. bool ENetMultiplayerPeer::is_server_relay_supported() const {
  243. return active_mode == MODE_SERVER || active_mode == MODE_CLIENT;
  244. }
  245. void ENetMultiplayerPeer::disconnect_peer(int p_peer, bool p_force) {
  246. ERR_FAIL_COND(!_is_active() || !peers.has(p_peer));
  247. peers[p_peer]->peer_disconnect(0); // Will be removed during next poll.
  248. if (active_mode == MODE_CLIENT || active_mode == MODE_SERVER) {
  249. hosts[0]->flush();
  250. } else {
  251. ERR_FAIL_COND(!hosts.has(p_peer));
  252. hosts[p_peer]->flush();
  253. }
  254. if (p_force) {
  255. peers.erase(p_peer);
  256. if (hosts.has(p_peer)) {
  257. hosts.erase(p_peer);
  258. }
  259. if (active_mode == MODE_CLIENT) {
  260. hosts.clear(); // Avoid flushing again.
  261. close();
  262. }
  263. }
  264. }
  265. void ENetMultiplayerPeer::close() {
  266. if (!_is_active()) {
  267. return;
  268. }
  269. _pop_current_packet();
  270. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  271. if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) {
  272. E.value->peer_disconnect_now(0);
  273. }
  274. }
  275. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  276. E.value->flush();
  277. }
  278. active_mode = MODE_NONE;
  279. incoming_packets.clear();
  280. peers.clear();
  281. hosts.clear();
  282. unique_id = 0;
  283. connection_status = CONNECTION_DISCONNECTED;
  284. set_refuse_new_connections(false);
  285. }
  286. int ENetMultiplayerPeer::get_available_packet_count() const {
  287. return incoming_packets.size();
  288. }
  289. Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  290. ERR_FAIL_COND_V_MSG(incoming_packets.is_empty(), ERR_UNAVAILABLE, "No incoming packets available.");
  291. _pop_current_packet();
  292. current_packet = incoming_packets.front()->get();
  293. incoming_packets.pop_front();
  294. *r_buffer = (const uint8_t *)(current_packet.packet->data);
  295. r_buffer_size = current_packet.packet->dataLength;
  296. return OK;
  297. }
  298. Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  299. ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");
  300. ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");
  301. ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(ABS(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));
  302. ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG);
  303. int packet_flags = 0;
  304. int channel = SYSCH_RELIABLE;
  305. int tr_channel = get_transfer_channel();
  306. switch (get_transfer_mode()) {
  307. case TRANSFER_MODE_UNRELIABLE: {
  308. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
  309. channel = SYSCH_UNRELIABLE;
  310. } break;
  311. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  312. packet_flags = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;
  313. channel = SYSCH_UNRELIABLE;
  314. } break;
  315. case TRANSFER_MODE_RELIABLE: {
  316. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  317. channel = SYSCH_RELIABLE;
  318. } break;
  319. }
  320. if (tr_channel > 0) {
  321. channel = SYSCH_MAX + tr_channel - 1;
  322. }
  323. #ifdef DEBUG_ENABLED
  324. if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size > ENET_HOST_DEFAULT_MTU) {
  325. WARN_PRINT_ONCE(vformat("Sending %d bytes unreliably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size, ENET_HOST_DEFAULT_MTU));
  326. }
  327. #endif
  328. ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size, packet_flags);
  329. memcpy(&packet->data[0], p_buffer, p_buffer_size);
  330. if (is_server()) {
  331. if (target_peer == 0) {
  332. hosts[0]->broadcast(channel, packet);
  333. } else if (target_peer < 0) {
  334. // Send to all but one and make copies for sending.
  335. int exclude = -target_peer;
  336. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  337. if (E.key == exclude) {
  338. continue;
  339. }
  340. E.value->send(channel, packet);
  341. }
  342. _destroy_unused(packet);
  343. } else {
  344. peers[target_peer]->send(channel, packet);
  345. }
  346. ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
  347. hosts[0]->flush();
  348. } else if (active_mode == MODE_CLIENT) {
  349. peers[1]->send(channel, packet); // Send to server for broadcast.
  350. ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);
  351. hosts[0]->flush();
  352. } else {
  353. if (target_peer <= 0) {
  354. int exclude = ABS(target_peer);
  355. for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {
  356. if (E.key == exclude) {
  357. continue;
  358. }
  359. E.value->send(channel, packet);
  360. ERR_CONTINUE(!hosts.has(E.key));
  361. hosts[E.key]->flush();
  362. }
  363. _destroy_unused(packet);
  364. } else {
  365. peers[target_peer]->send(channel, packet);
  366. ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG);
  367. hosts[target_peer]->flush();
  368. }
  369. }
  370. return OK;
  371. }
  372. int ENetMultiplayerPeer::get_max_packet_size() const {
  373. return 1 << 24; // Anything is good
  374. }
  375. void ENetMultiplayerPeer::_pop_current_packet() {
  376. if (current_packet.packet) {
  377. current_packet.packet->referenceCount--;
  378. _destroy_unused(current_packet.packet);
  379. current_packet.packet = nullptr;
  380. current_packet.from = 0;
  381. current_packet.channel = -1;
  382. }
  383. }
  384. MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const {
  385. return connection_status;
  386. }
  387. int ENetMultiplayerPeer::get_unique_id() const {
  388. ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active.");
  389. return unique_id;
  390. }
  391. void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) {
  392. #ifdef GODOT_ENET
  393. if (_is_active()) {
  394. for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {
  395. E.value->refuse_new_connections(p_enabled);
  396. }
  397. }
  398. #endif
  399. MultiplayerPeer::set_refuse_new_connections(p_enabled);
  400. }
  401. Ref<ENetConnection> ENetMultiplayerPeer::get_host() const {
  402. ERR_FAIL_COND_V(!_is_active(), nullptr);
  403. ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr);
  404. return hosts[0];
  405. }
  406. Ref<ENetPacketPeer> ENetMultiplayerPeer::get_peer(int p_id) const {
  407. ERR_FAIL_COND_V(!_is_active(), nullptr);
  408. ERR_FAIL_COND_V(!peers.has(p_id), nullptr);
  409. ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr);
  410. return peers[p_id];
  411. }
  412. void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) {
  413. if (p_packet->referenceCount == 0) {
  414. enet_packet_destroy(p_packet);
  415. }
  416. }
  417. void ENetMultiplayerPeer::_bind_methods() {
  418. 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));
  419. 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));
  420. ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh);
  421. ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer);
  422. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip);
  423. ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host);
  424. ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer);
  425. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host");
  426. }
  427. ENetMultiplayerPeer::ENetMultiplayerPeer() {
  428. bind_ip = IPAddress("*");
  429. }
  430. ENetMultiplayerPeer::~ENetMultiplayerPeer() {
  431. if (_is_active()) {
  432. close();
  433. }
  434. }
  435. // Sets IP for ENet to bind when using create_server or create_client
  436. // if no IP is set, then ENet bind to ENET_HOST_ANY
  437. void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) {
  438. ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip)));
  439. bind_ip = p_ip;
  440. }