networked_multiplayer_enet.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /*************************************************************************/
  2. /* networked_multiplayer_enet.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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 "networked_multiplayer_enet.h"
  31. #include "io/ip.h"
  32. #include "io/marshalls.h"
  33. #include "os/os.h"
  34. void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {
  35. transfer_mode = p_mode;
  36. }
  37. NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const {
  38. return transfer_mode;
  39. }
  40. void NetworkedMultiplayerENet::set_target_peer(int p_peer) {
  41. target_peer = p_peer;
  42. }
  43. int NetworkedMultiplayerENet::get_packet_peer() const {
  44. ERR_FAIL_COND_V(!active, 1);
  45. ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
  46. return incoming_packets.front()->get().from;
  47. }
  48. Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) {
  49. ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
  50. ERR_FAIL_COND_V(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER);
  51. ERR_FAIL_COND_V(p_max_clients < 0, ERR_INVALID_PARAMETER);
  52. ERR_FAIL_COND_V(p_in_bandwidth < 0, ERR_INVALID_PARAMETER);
  53. ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);
  54. ENetAddress address;
  55. #ifdef GODOT_ENET
  56. if (bind_ip.is_wildcard()) {
  57. address.wildcard = 1;
  58. } else {
  59. enet_address_set_ip(&address, bind_ip.get_ipv6(), 16);
  60. }
  61. #else
  62. if (bind_ip.is_wildcard()) {
  63. address.host = 0;
  64. } else {
  65. ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
  66. address.host = *(uint32_t *)bind_ip.get_ipv4();
  67. }
  68. #endif
  69. address.port = p_port;
  70. host = enet_host_create(&address /* the address to bind the server host to */,
  71. p_max_clients /* allow up to 32 clients and/or outgoing connections */,
  72. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  73. p_in_bandwidth /* limit incoming bandwith if > 0 */,
  74. p_out_bandwidth /* limit outgoing bandwith if > 0 */);
  75. ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
  76. _setup_compressor();
  77. active = true;
  78. server = true;
  79. refuse_connections = false;
  80. unique_id = 1;
  81. connection_status = CONNECTION_CONNECTED;
  82. return OK;
  83. }
  84. Error NetworkedMultiplayerENet::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_client_port) {
  85. ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
  86. ERR_FAIL_COND_V(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER);
  87. ERR_FAIL_COND_V(p_client_port < 0 || p_client_port > 65535, ERR_INVALID_PARAMETER);
  88. ERR_FAIL_COND_V(p_in_bandwidth < 0, ERR_INVALID_PARAMETER);
  89. ERR_FAIL_COND_V(p_out_bandwidth < 0, ERR_INVALID_PARAMETER);
  90. if (p_client_port != 0) {
  91. ENetAddress c_client;
  92. #ifdef GODOT_ENET
  93. if (bind_ip.is_wildcard()) {
  94. c_client.wildcard = 1;
  95. } else {
  96. enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16);
  97. }
  98. #else
  99. if (bind_ip.is_wildcard()) {
  100. c_client.host = 0;
  101. } else {
  102. ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER);
  103. c_client.host = *(uint32_t *)bind_ip.get_ipv4();
  104. }
  105. #endif
  106. c_client.port = p_client_port;
  107. host = enet_host_create(&c_client /* create a client host */,
  108. 1 /* only allow 1 outgoing connection */,
  109. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  110. p_in_bandwidth /* limit incoming bandwith if > 0 */,
  111. p_out_bandwidth /* limit outgoing bandwith if > 0 */);
  112. } else {
  113. host = enet_host_create(NULL /* create a client host */,
  114. 1 /* only allow 1 outgoing connection */,
  115. SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
  116. p_in_bandwidth /* limit incoming bandwith if > 0 */,
  117. p_out_bandwidth /* limit outgoing bandwith if > 0 */);
  118. }
  119. ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
  120. _setup_compressor();
  121. IP_Address ip;
  122. if (p_address.is_valid_ip_address()) {
  123. ip = p_address;
  124. } else {
  125. #ifdef GODOT_ENET
  126. ip = IP::get_singleton()->resolve_hostname(p_address);
  127. #else
  128. ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4);
  129. #endif
  130. ERR_FAIL_COND_V(!ip.is_valid(), ERR_CANT_RESOLVE);
  131. }
  132. ENetAddress address;
  133. #ifdef GODOT_ENET
  134. enet_address_set_ip(&address, ip.get_ipv6(), 16);
  135. #else
  136. ERR_FAIL_COND_V(!ip.is_ipv4(), ERR_INVALID_PARAMETER);
  137. address.host = *(uint32_t *)ip.get_ipv4();
  138. #endif
  139. address.port = p_port;
  140. unique_id = _gen_unique_id();
  141. // Initiate connection, allocating enough channels
  142. ENetPeer *peer = enet_host_connect(host, &address, SYSCH_MAX, unique_id);
  143. if (peer == NULL) {
  144. enet_host_destroy(host);
  145. ERR_FAIL_COND_V(!peer, ERR_CANT_CREATE);
  146. }
  147. // Technically safe to ignore the peer or anything else.
  148. connection_status = CONNECTION_CONNECTING;
  149. active = true;
  150. server = false;
  151. refuse_connections = false;
  152. return OK;
  153. }
  154. void NetworkedMultiplayerENet::poll() {
  155. ERR_FAIL_COND(!active);
  156. _pop_current_packet();
  157. ENetEvent event;
  158. /* Wait up to 1000 milliseconds for an event. */
  159. while (true) {
  160. if (!host || !active) // Might have been disconnected while emitting a notification
  161. return;
  162. int ret = enet_host_service(host, &event, 1);
  163. if (ret < 0) {
  164. // Error, do something?
  165. break;
  166. } else if (ret == 0) {
  167. break;
  168. }
  169. switch (event.type) {
  170. case ENET_EVENT_TYPE_CONNECT: {
  171. // Store any relevant client information here.
  172. if (server && refuse_connections) {
  173. enet_peer_reset(event.peer);
  174. break;
  175. }
  176. int *new_id = memnew(int);
  177. *new_id = event.data;
  178. if (*new_id == 0) { // Data zero is sent by server (enet won't let you configure this). Server is always 1.
  179. *new_id = 1;
  180. }
  181. event.peer->data = new_id;
  182. peer_map[*new_id] = event.peer;
  183. connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something!
  184. emit_signal("peer_connected", *new_id);
  185. if (server) {
  186. // Someone connected, notify all the peers available
  187. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  188. if (E->key() == *new_id)
  189. continue;
  190. // Send existing peers to new peer
  191. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  192. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  193. encode_uint32(E->key(), &packet->data[4]);
  194. enet_peer_send(event.peer, SYSCH_CONFIG, packet);
  195. // Send the new peer to existing peers
  196. packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  197. encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
  198. encode_uint32(*new_id, &packet->data[4]);
  199. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  200. }
  201. } else {
  202. emit_signal("connection_succeeded");
  203. }
  204. } break;
  205. case ENET_EVENT_TYPE_DISCONNECT: {
  206. // Reset the peer's client information.
  207. int *id = (int *)event.peer->data;
  208. if (!id) {
  209. if (!server) {
  210. emit_signal("connection_failed");
  211. }
  212. } else {
  213. if (server) {
  214. // Someone disconnected, notify everyone else
  215. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  216. if (E->key() == *id)
  217. continue;
  218. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  219. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  220. encode_uint32(*id, &packet->data[4]);
  221. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  222. }
  223. } else if (!server) {
  224. emit_signal("server_disconnected");
  225. close_connection();
  226. return;
  227. }
  228. emit_signal("peer_disconnected", *id);
  229. peer_map.erase(*id);
  230. memdelete(id);
  231. }
  232. } break;
  233. case ENET_EVENT_TYPE_RECEIVE: {
  234. if (event.channelID == SYSCH_CONFIG) {
  235. // Some config message
  236. ERR_CONTINUE(event.packet->dataLength < 8);
  237. // Only server can send config messages
  238. ERR_CONTINUE(server);
  239. int msg = decode_uint32(&event.packet->data[0]);
  240. int id = decode_uint32(&event.packet->data[4]);
  241. switch (msg) {
  242. case SYSMSG_ADD_PEER: {
  243. peer_map[id] = NULL;
  244. emit_signal("peer_connected", id);
  245. } break;
  246. case SYSMSG_REMOVE_PEER: {
  247. peer_map.erase(id);
  248. emit_signal("peer_disconnected", id);
  249. } break;
  250. }
  251. enet_packet_destroy(event.packet);
  252. } else if (event.channelID < SYSCH_MAX) {
  253. Packet packet;
  254. packet.packet = event.packet;
  255. uint32_t *id = (uint32_t *)event.peer->data;
  256. ERR_CONTINUE(event.packet->dataLength < 12)
  257. uint32_t source = decode_uint32(&event.packet->data[0]);
  258. int target = decode_uint32(&event.packet->data[4]);
  259. uint32_t flags = decode_uint32(&event.packet->data[8]);
  260. packet.from = source;
  261. if (server) {
  262. // Someone is cheating and trying to fake the source!
  263. ERR_CONTINUE(source != *id);
  264. packet.from = *id;
  265. if (target == 0) {
  266. // Re-send to everyone but sender :|
  267. incoming_packets.push_back(packet);
  268. // And make copies for sending
  269. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  270. if (uint32_t(E->key()) == source) // Do not resend to self
  271. continue;
  272. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
  273. enet_peer_send(E->get(), event.channelID, packet2);
  274. }
  275. } else if (target < 0) {
  276. // To all but one
  277. // And make copies for sending
  278. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  279. if (uint32_t(E->key()) == source || E->key() == -target) // Do not resend to self, also do not send to excluded
  280. continue;
  281. ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
  282. enet_peer_send(E->get(), event.channelID, packet2);
  283. }
  284. if (-target != 1) {
  285. // Server is not excluded
  286. incoming_packets.push_back(packet);
  287. } else {
  288. // Server is excluded, erase packet
  289. enet_packet_destroy(packet.packet);
  290. }
  291. } else if (target == 1) {
  292. // To myself and only myself
  293. incoming_packets.push_back(packet);
  294. } else {
  295. // To someone else, specifically
  296. ERR_CONTINUE(!peer_map.has(target));
  297. enet_peer_send(peer_map[target], event.channelID, packet.packet);
  298. }
  299. } else {
  300. incoming_packets.push_back(packet);
  301. }
  302. // Destroy packet later
  303. } else {
  304. ERR_CONTINUE(true);
  305. }
  306. } break;
  307. case ENET_EVENT_TYPE_NONE: {
  308. // Do nothing
  309. } break;
  310. }
  311. }
  312. }
  313. bool NetworkedMultiplayerENet::is_server() const {
  314. ERR_FAIL_COND_V(!active, false);
  315. return server;
  316. }
  317. void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) {
  318. ERR_FAIL_COND(!active);
  319. ERR_FAIL_COND(wait_usec < 0);
  320. _pop_current_packet();
  321. bool peers_disconnected = false;
  322. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  323. if (E->get()) {
  324. enet_peer_disconnect_now(E->get(), unique_id);
  325. peers_disconnected = true;
  326. }
  327. }
  328. if (peers_disconnected) {
  329. enet_host_flush(host);
  330. if (wait_usec > 0) {
  331. OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send
  332. }
  333. }
  334. enet_host_destroy(host);
  335. active = false;
  336. incoming_packets.clear();
  337. unique_id = 1; // Server is 1
  338. connection_status = CONNECTION_DISCONNECTED;
  339. }
  340. void NetworkedMultiplayerENet::disconnect_peer(int p_peer, bool now) {
  341. ERR_FAIL_COND(!active);
  342. ERR_FAIL_COND(!is_server());
  343. ERR_FAIL_COND(!peer_map.has(p_peer))
  344. if (now) {
  345. enet_peer_disconnect_now(peer_map[p_peer], 0);
  346. // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT,
  347. // notify everyone else, send disconnect signal & remove from peer_map like in poll()
  348. for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
  349. if (E->key() == p_peer)
  350. continue;
  351. ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
  352. encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
  353. encode_uint32(p_peer, &packet->data[4]);
  354. enet_peer_send(E->get(), SYSCH_CONFIG, packet);
  355. }
  356. emit_signal("peer_disconnected", p_peer);
  357. peer_map.erase(p_peer);
  358. } else {
  359. enet_peer_disconnect_later(peer_map[p_peer], 0);
  360. }
  361. }
  362. int NetworkedMultiplayerENet::get_available_packet_count() const {
  363. return incoming_packets.size();
  364. }
  365. Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  366. ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);
  367. _pop_current_packet();
  368. current_packet = incoming_packets.front()->get();
  369. incoming_packets.pop_front();
  370. *r_buffer = (const uint8_t *)(&current_packet.packet->data[12]);
  371. r_buffer_size = current_packet.packet->dataLength - 12;
  372. return OK;
  373. }
  374. Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  375. ERR_FAIL_COND_V(!active, ERR_UNCONFIGURED);
  376. ERR_FAIL_COND_V(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  377. int packet_flags = 0;
  378. int channel = SYSCH_RELIABLE;
  379. switch (transfer_mode) {
  380. case TRANSFER_MODE_UNRELIABLE: {
  381. packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
  382. channel = SYSCH_UNRELIABLE;
  383. } break;
  384. case TRANSFER_MODE_UNRELIABLE_ORDERED: {
  385. packet_flags = 0;
  386. channel = SYSCH_UNRELIABLE;
  387. } break;
  388. case TRANSFER_MODE_RELIABLE: {
  389. packet_flags = ENET_PACKET_FLAG_RELIABLE;
  390. channel = SYSCH_RELIABLE;
  391. } break;
  392. }
  393. Map<int, ENetPeer *>::Element *E = NULL;
  394. if (target_peer != 0) {
  395. E = peer_map.find(ABS(target_peer));
  396. if (!E) {
  397. ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
  398. ERR_FAIL_V(ERR_INVALID_PARAMETER);
  399. }
  400. }
  401. ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 12, packet_flags);
  402. encode_uint32(unique_id, &packet->data[0]); // Source ID
  403. encode_uint32(target_peer, &packet->data[4]); // Dest ID
  404. encode_uint32(packet_flags, &packet->data[8]); // Dest ID
  405. copymem(&packet->data[12], p_buffer, p_buffer_size);
  406. if (server) {
  407. if (target_peer == 0) {
  408. enet_host_broadcast(host, channel, packet);
  409. } else if (target_peer < 0) {
  410. // Send to all but one
  411. // and make copies for sending
  412. int exclude = -target_peer;
  413. for (Map<int, ENetPeer *>::Element *F = peer_map.front(); F; F = F->next()) {
  414. if (F->key() == exclude) // Exclude packet
  415. continue;
  416. ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);
  417. enet_peer_send(F->get(), channel, packet2);
  418. }
  419. enet_packet_destroy(packet); // Original packet no longer needed
  420. } else {
  421. enet_peer_send(E->get(), channel, packet);
  422. }
  423. } else {
  424. ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
  425. enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast
  426. }
  427. enet_host_flush(host);
  428. return OK;
  429. }
  430. int NetworkedMultiplayerENet::get_max_packet_size() const {
  431. return 1 << 24; // Anything is good
  432. }
  433. void NetworkedMultiplayerENet::_pop_current_packet() {
  434. if (current_packet.packet) {
  435. enet_packet_destroy(current_packet.packet);
  436. current_packet.packet = NULL;
  437. current_packet.from = 0;
  438. }
  439. }
  440. NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
  441. return connection_status;
  442. }
  443. uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
  444. uint32_t hash = 0;
  445. while (hash == 0 || hash == 1) {
  446. hash = hash_djb2_one_32(
  447. (uint32_t)OS::get_singleton()->get_ticks_usec());
  448. hash = hash_djb2_one_32(
  449. (uint32_t)OS::get_singleton()->get_unix_time(), hash);
  450. hash = hash_djb2_one_32(
  451. (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash);
  452. hash = hash_djb2_one_32(
  453. (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap
  454. hash = hash_djb2_one_32(
  455. (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack
  456. hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion
  457. }
  458. return hash;
  459. }
  460. int NetworkedMultiplayerENet::get_unique_id() const {
  461. ERR_FAIL_COND_V(!active, 0);
  462. return unique_id;
  463. }
  464. void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
  465. refuse_connections = p_enable;
  466. }
  467. bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
  468. return refuse_connections;
  469. }
  470. void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
  471. compression_mode = p_mode;
  472. }
  473. NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const {
  474. return compression_mode;
  475. }
  476. size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  477. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  478. if (size_t(enet->src_compressor_mem.size()) < inLimit) {
  479. enet->src_compressor_mem.resize(inLimit);
  480. }
  481. int total = inLimit;
  482. int ofs = 0;
  483. while (total) {
  484. for (size_t i = 0; i < inBufferCount; i++) {
  485. int to_copy = MIN(total, int(inBuffers[i].dataLength));
  486. copymem(&enet->src_compressor_mem[ofs], inBuffers[i].data, to_copy);
  487. ofs += to_copy;
  488. total -= to_copy;
  489. }
  490. }
  491. Compression::Mode mode;
  492. switch (enet->compression_mode) {
  493. case COMPRESS_FASTLZ: {
  494. mode = Compression::MODE_FASTLZ;
  495. } break;
  496. case COMPRESS_ZLIB: {
  497. mode = Compression::MODE_DEFLATE;
  498. } break;
  499. case COMPRESS_ZSTD: {
  500. mode = Compression::MODE_ZSTD;
  501. } break;
  502. default: { ERR_FAIL_V(0); }
  503. }
  504. int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
  505. if (enet->dst_compressor_mem.size() < req_size) {
  506. enet->dst_compressor_mem.resize(req_size);
  507. }
  508. int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode);
  509. if (ret < 0)
  510. return 0;
  511. if (ret > int(outLimit))
  512. return 0; // Do not bother
  513. copymem(outData, enet->dst_compressor_mem.ptr(), ret);
  514. return ret;
  515. }
  516. size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
  517. NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
  518. int ret = -1;
  519. switch (enet->compression_mode) {
  520. case COMPRESS_FASTLZ: {
  521. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ);
  522. } break;
  523. case COMPRESS_ZLIB: {
  524. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
  525. } break;
  526. case COMPRESS_ZSTD: {
  527. ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD);
  528. } break;
  529. default: {}
  530. }
  531. if (ret < 0) {
  532. return 0;
  533. } else {
  534. return ret;
  535. }
  536. }
  537. void NetworkedMultiplayerENet::_setup_compressor() {
  538. switch (compression_mode) {
  539. case COMPRESS_NONE: {
  540. enet_host_compress(host, NULL);
  541. } break;
  542. case COMPRESS_RANGE_CODER: {
  543. enet_host_compress_with_range_coder(host);
  544. } break;
  545. case COMPRESS_FASTLZ:
  546. case COMPRESS_ZLIB:
  547. case COMPRESS_ZSTD: {
  548. enet_host_compress(host, &enet_compressor);
  549. } break;
  550. }
  551. }
  552. void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {
  553. // Nothing to do
  554. }
  555. IP_Address NetworkedMultiplayerENet::get_peer_address(int p_peer_id) const {
  556. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), IP_Address());
  557. ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, IP_Address());
  558. ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, IP_Address());
  559. IP_Address out;
  560. #ifdef GODOT_ENET
  561. out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host));
  562. #else
  563. out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host));
  564. #endif
  565. return out;
  566. }
  567. int NetworkedMultiplayerENet::get_peer_port(int p_peer_id) const {
  568. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), 0);
  569. ERR_FAIL_COND_V(!is_server() && p_peer_id != 1, 0);
  570. ERR_FAIL_COND_V(peer_map[p_peer_id] == NULL, 0);
  571. #ifdef GODOT_ENET
  572. return peer_map[p_peer_id]->address.port;
  573. #else
  574. return peer_map[p_peer_id]->address.port;
  575. #endif
  576. }
  577. void NetworkedMultiplayerENet::_bind_methods() {
  578. ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0));
  579. ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "client_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0));
  580. ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100));
  581. ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false));
  582. ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode);
  583. ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode);
  584. ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip);
  585. ClassDB::bind_method(D_METHOD("get_peer_address"), &NetworkedMultiplayerENet::get_peer_address);
  586. ClassDB::bind_method(D_METHOD("get_peer_port"), &NetworkedMultiplayerENet::get_peer_port);
  587. ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode");
  588. BIND_ENUM_CONSTANT(COMPRESS_NONE);
  589. BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER);
  590. BIND_ENUM_CONSTANT(COMPRESS_FASTLZ);
  591. BIND_ENUM_CONSTANT(COMPRESS_ZLIB);
  592. BIND_ENUM_CONSTANT(COMPRESS_ZSTD);
  593. }
  594. NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
  595. active = false;
  596. server = false;
  597. refuse_connections = false;
  598. unique_id = 0;
  599. target_peer = 0;
  600. current_packet.packet = NULL;
  601. transfer_mode = TRANSFER_MODE_RELIABLE;
  602. connection_status = CONNECTION_DISCONNECTED;
  603. compression_mode = COMPRESS_NONE;
  604. enet_compressor.context = this;
  605. enet_compressor.compress = enet_compress;
  606. enet_compressor.decompress = enet_decompress;
  607. enet_compressor.destroy = enet_compressor_destroy;
  608. bind_ip = IP_Address("*");
  609. }
  610. NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
  611. close_connection();
  612. }
  613. // Sets IP for ENet to bind when using create_server or create_client
  614. // if no IP is set, then ENet bind to ENET_HOST_ANY
  615. void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) {
  616. ERR_FAIL_COND(!p_ip.is_valid() && !p_ip.is_wildcard());
  617. bind_ip = p_ip;
  618. }