From 1e8bf86379ca818bf7208de5f04f986be95dc102 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Fri, 16 Jul 2021 00:43:49 +0200 Subject: [Net] Add generate_unique_id to MultiplayerPeer. Used by ENetMultiplayerPeer and WebSocketServer to generate network IDs, and exposed to the user for p2p networks (e.g. WebRTCMultiplayerPeer) and custom MultiplayerPeer implementations. --- modules/enet/enet_multiplayer_peer.cpp | 23 +---------------------- modules/enet/enet_multiplayer_peer.h | 1 - 2 files changed, 1 insertion(+), 23 deletions(-) (limited to 'modules/enet') diff --git a/modules/enet/enet_multiplayer_peer.cpp b/modules/enet/enet_multiplayer_peer.cpp index b4ca93f4d9..14f9b3b1b9 100644 --- a/modules/enet/enet_multiplayer_peer.cpp +++ b/modules/enet/enet_multiplayer_peer.cpp @@ -179,7 +179,7 @@ Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, in #endif address.port = p_port; - unique_id = _gen_unique_id(); + unique_id = generate_unique_id(); // Initiate connection, allocating enough channels ENetPeer *peer = enet_host_connect(host, &address, channel_count, unique_id); @@ -608,27 +608,6 @@ MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() c return connection_status; } -uint32_t ENetMultiplayerPeer::_gen_unique_id() const { - uint32_t hash = 0; - - while (hash == 0 || hash == 1) { - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_ticks_usec()); - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_unix_time(), hash); - hash = hash_djb2_one_32( - (uint32_t)OS::get_singleton()->get_user_data_dir().hash64(), hash); - hash = hash_djb2_one_32( - (uint32_t)((uint64_t)this), hash); // Rely on ASLR heap - hash = hash_djb2_one_32( - (uint32_t)((uint64_t)&hash), hash); // Rely on ASLR stack - - hash = hash & 0x7FFFFFFF; // Make it compatible with unsigned, since negative ID is used for exclusion - } - - return hash; -} - int ENetMultiplayerPeer::get_unique_id() const { ERR_FAIL_COND_V_MSG(!active, 0, "The multiplayer instance isn't currently active."); return unique_id; diff --git a/modules/enet/enet_multiplayer_peer.h b/modules/enet/enet_multiplayer_peer.h index 63f2ec5870..db80953414 100644 --- a/modules/enet/enet_multiplayer_peer.h +++ b/modules/enet/enet_multiplayer_peer.h @@ -96,7 +96,6 @@ private: Packet current_packet; - uint32_t _gen_unique_id() const; void _pop_current_packet(); Vector src_compressor_mem; -- cgit v1.2.3 From 42a17775314424ba24974d072bb5f74bc4ff9467 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Mon, 14 Jun 2021 11:51:53 +0200 Subject: [Net] Implement lower level ENet wrappers. --- modules/enet/config.py | 2 + modules/enet/doc_classes/ENetConnection.xml | 240 ++++++++++++++ modules/enet/doc_classes/ENetPacketPeer.xml | 210 +++++++++++++ modules/enet/enet_connection.cpp | 470 ++++++++++++++++++++++++++++ modules/enet/enet_connection.h | 138 ++++++++ modules/enet/enet_packet_peer.cpp | 263 ++++++++++++++++ modules/enet/enet_packet_peer.h | 131 ++++++++ modules/enet/register_types.cpp | 4 + 8 files changed, 1458 insertions(+) create mode 100644 modules/enet/doc_classes/ENetConnection.xml create mode 100644 modules/enet/doc_classes/ENetPacketPeer.xml create mode 100644 modules/enet/enet_connection.cpp create mode 100644 modules/enet/enet_connection.h create mode 100644 modules/enet/enet_packet_peer.cpp create mode 100644 modules/enet/enet_packet_peer.h (limited to 'modules/enet') diff --git a/modules/enet/config.py b/modules/enet/config.py index 3662b2d94e..9102c74579 100644 --- a/modules/enet/config.py +++ b/modules/enet/config.py @@ -9,6 +9,8 @@ def configure(env): def get_doc_classes(): return [ "ENetMultiplayerPeer", + "ENetConnection", + "ENetPacketPeer", ] diff --git a/modules/enet/doc_classes/ENetConnection.xml b/modules/enet/doc_classes/ENetConnection.xml new file mode 100644 index 0000000000..523f2ad165 --- /dev/null +++ b/modules/enet/doc_classes/ENetConnection.xml @@ -0,0 +1,240 @@ + + + + A wrapper class for an [url=http://enet.bespin.org/group__host.html]ENetHost[/url]. + + + ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol). + + + http://enet.bespin.org/usergroup0.html + + + + + + + + + + + Adjusts the bandwidth limits of a host. + + + + + + + + + + + + + Queues a [code]packet[/code] to be sent to all peers associated with the host over the specified [code]channel[/code]. See [ENetPacketPeer] [code]FLAG_*[/code] constants for available packet flags. + + + + + + + + + Limits the maximum allowed channels of future incoming connections. + + + + + + + + + Sets the compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all. + [b]Note:[/b] Most games' network design involve sending many small packets frequently (smaller than 4 KB each). If in doubt, it is recommended to keep the default compression algorithm as it works best on these small packets. + + + + + + + + + + + + + + + Initiates a connection to a foreign [code]address[/code] using the specified [code]port[/code] and allocting the requested [code]channels[/code]. Optional [code]data[/code] can be passed during connection in the form of a 32 bit integer. + Note: You must call either [method create_host] or [method create_host_bound] before calling this method. + + + + + + + + + + + + + + + Create an ENetHost that will allow up to [code]max_peers[/code] connected peers, each allocating up to [code]max_channels[/code] channels, optionally limiting bandwith to [code]in_bandwidth[/code] and [code]out_bandwidth[/code]. + + + + + + + + + + + + + + + + + + + Create an ENetHost like [method create_host] which is also bound to the given [code]bind_address[/code] and [code]bind_port[/code]. + + + + + + + Destroys the host and all resources associated with it. + + + + + + + + + + + + + Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet clients. Call this before [method connect_to_host] to have ENet connect using DTLS with [code]certificate[/code] and [code]hostname[/code] verification. Verification can be optionally turned off via the [code]verify[/code] parameter. + + + + + + + + + + + Configure this ENetHost to use the custom Godot extension allowing DTLS encryption for ENet servers. Call this right after [method create_host_bound] to have ENet expect peers to connect using DTLS. + + + + + + + Sends any queued packets on the host specified to its designated peers. + + + + + + + Returns the local port to which this peer is bound. + + + + + + + Returns the maximum number of channels allowed for connected peers. + + + + + + + Returns the list of peers associated with this host. + Note: This list might include some peers that are not fully connected or are still being disconnected. + + + + + + + + + Returns and resets host statistics. See [enum HostStatistic] for more info. + + + + + + + + + Configures the DTLS server to automatically drop new connections. + Note: This method is only relevant after calling [method dtls_server_setup]. + + + + + + + + + Waits for events on the host specified and shuttles packets between the host and its peers. The returned [Array] will have 4 elements. An [enum EventType], the [ENetPacketPeer] which generated the event, the event associated data (if any), the event associated channel (if any). If the generated event is [constant EVENT_RECEIVE], the received packet will be queued to the associated [ENetPacketPeer]. + Call this function regularly to handle connections, disconnections, and to receive new packets. + + + + + + No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. This option may also be used to make network debugging using tools like Wireshark easier. + + + ENet's built-in range encoding. Works well on small packets, but is not the most efficient algorithm on packets larger than 4 KB. + + + [url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth. + + + [url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources. + + + [url=https://facebook.github.io/zstd/]Zstandard[/url] compression. Note that this algorithm is not very efficient on packets smaller than 4 KB. Therefore, it's recommended to use other compression algorithms in most cases. + + + An error occurred during [method service]. You will likely need to [method destroy] the host and recreate it. + + + No event occurred within the specified time limit. + + + A connection request initiated by enet_host_connect has completed. The array will contain the peer which successfully connected. + + + A peer has disconnected. This event is generated on a successful completion of a disconnect initiated by [method ENetPacketPeer.peer_disconnect], if a peer has timed out, or if a connection request intialized by [method connect_to_host] has timed out. The array will contain the peer which disconnected. The data field contains user supplied data describing the disconnection, or 0, if none is available. + + + A packet has been received from a peer. The array will contain the peer which sent the packet, the channel number upon which the packet was received, and the received packet. + + + Total data sent. + + + Total UDP packets sent. + + + Total data received. + + + Total UDP packets received. + + + diff --git a/modules/enet/doc_classes/ENetPacketPeer.xml b/modules/enet/doc_classes/ENetPacketPeer.xml new file mode 100644 index 0000000000..5c9f692974 --- /dev/null +++ b/modules/enet/doc_classes/ENetPacketPeer.xml @@ -0,0 +1,210 @@ + + + + A wrapper class for an [url=http://enet.bespin.org/group__peer.html]ENetPeer[/url]. + + + A PacketPeer implementation representing a peer of an [ENetConnection]. + This class cannot be instantiated directly but can be retrieved during [method ENetConnection.service] or via [method ENetConnection.get_peers]. + + + http://enet.bespin.org/usergroup0.html + + + + + + + Returns the number of channels allocated for communication with peer. + + + + + + + Returns the current peer state. See [enum PeerState]. + + + + + + + + + Returns the requested [code]statistic[/code] for this peer. See [enum PeerStatistic]. + + + + + + + Returns [code]true[/code] if the peer is currently active (i.e. the associated [ENetConnection] is still valid). + + + + + + + + + Request a disconnection from a peer. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete. + + + + + + + + + Request a disconnection from a peer, but only after all queued outgoing packets are sent. An [constant ENetConnection.EVENT_DISCONNECT] will be generated during [method ENetConnection.service] once the disconnection is complete. + + + + + + + + + Force an immediate disconnection from a peer. No [constant ENetConnection.EVENT_DISCONNECT] will be generated. The foreign peer is not guaranteed to receive the disconnect notification, and is reset immediately upon return from this function. + + + + + + + Sends a ping request to a peer. ENet automatically pings all connected peers at regular intervals, however, this function may be called to ensure more frequent ping requests. + + + + + + + + + Sets the [code]ping_interval[/code] in milliseconds at which pings will be sent to a peer. Pings are used both to monitor the liveness of the connection and also to dynamically adjust the throttle during periods of low traffic so that the throttle has reasonable responsiveness during traffic spikes. + + + + + + + Forcefully disconnects a peer. The foreign host represented by the peer is not notified of the disconnection and will timeout on its connection to the local host. + + + + + + + + + + + + + Queues a [code]packet[/code] to be sent over the specified [code]channel[/code]. See [code]FLAG_*[/code] constants for available packet flags. + + + + + + + + + + + + + Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds. + The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the average round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped. + + + + + + + + + + + + + Configures throttle parameter for a peer. + Unreliable packets are dropped by ENet in response to the varying conditions of the Internet connection to the peer. The throttle represents a probability that an unreliable packet should not be dropped and thus sent by ENet to the peer. By measuring fluctuations in round trip times of reliable packets over the specified [code]interval[/code], ENet will either increase the probably by the amount specified in the [code]acceleration[/code] parameter, or decrease it by the amount specified in the [code]deceleration[/code] parameter (both are ratios to [constant PACKET_THROTTLE_SCALE]). + When the throttle has a value of [constant PACKET_THROTTLE_SCALE], no unreliable packets are dropped by ENet, and so 100% of all unreliable packets will be sent. + When the throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all unreliable packets will be sent. + Intermediate values for the throttle represent intermediate probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits of the local and foreign hosts are taken into account to determine a sensible limit for the throttle probability above which it should not raise even in the best of conditions. + + + + + + + + + + + + + + + + + + + + + + + + + + Mean packet loss of reliable packets as a ratio with respect to the [constant PACKET_LOSS_SCALE]. + + + Packet loss variance. + + + + + Mean packet round trip time for reliable packets. + + + Variance of the mean round trip time. + + + Last recorded round trip time for a reliable packet. + + + Variance of the last trip time recorded. + + + + + + + + + + + + + + + + + The reference scale for packet loss. See [method get_statistic] and [constant PEER_PACKET_LOSS]. + + + The reference value for throttle configuration. See [method throttle_configure]. + + + Mark the packet to be sent as reliable. + + + Mark the packet to be sent unsequenced (unreliable). + + + Mark the packet to be sent unreliable even if the packet is too big and needs fragmentation (increasing the chance of it being dropped). + + + diff --git a/modules/enet/enet_connection.cpp b/modules/enet/enet_connection.cpp new file mode 100644 index 0000000000..0bda9402f8 --- /dev/null +++ b/modules/enet/enet_connection.cpp @@ -0,0 +1,470 @@ +/*************************************************************************/ +/* enet_connection.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "enet_connection.h" + +#include "enet_packet_peer.h" + +#include "core/io/compression.h" +#include "core/io/ip.h" + +void ENetConnection::broadcast(enet_uint8 p_channel, ENetPacket *p_packet) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_MSG(p_channel >= host->channelLimit, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)host->channelLimit)); + enet_host_broadcast(host, p_channel, p_packet); +} + +Error ENetConnection::create_host_bound(const IPAddress &p_bind_address, int p_port, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_V_MSG(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER, "Invalid bind IP."); + ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The local port number must be between 0 and 65535 (inclusive)."); + + ENetAddress address; + memset(&address, 0, sizeof(address)); + address.port = p_port; +#ifdef GODOT_ENET + if (p_bind_address.is_wildcard()) { + address.wildcard = 1; + } else { + enet_address_set_ip(&address, p_bind_address.get_ipv6(), 16); + } +#else + if (p_bind_address.is_wildcard()) { + address.host = 0; + } else { + ERR_FAIL_COND_V(!p_bind_address.is_ipv4(), ERR_INVALID_PARAMETER); + address.host = *(uint32_t *)p_bind_address.get_ipv4(); + } +#endif + return _create(&address, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth); +} + +Error ENetConnection::create_host(int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + return _create(nullptr, p_max_peers, p_max_channels, p_in_bandwidth, p_out_bandwidth); +} + +void ENetConnection::destroy() { + ERR_FAIL_COND_MSG(!host, "Host already destroyed"); + for (List>::Element *E = peers.front(); E; E = E->next()) { + E->get()->_on_disconnect(); + } + peers.clear(); + enet_host_destroy(host); + host = nullptr; +} + +Ref ENetConnection::connect_to_host(const String &p_address, int p_port, int p_channels, int p_data) { + Ref out; + ERR_FAIL_COND_V_MSG(!host, out, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_V_MSG(peers.size(), out, "The ENetConnection is already connected to a peer."); + ERR_FAIL_COND_V_MSG(p_port < 1 || p_port > 65535, out, "The remote port number must be between 1 and 65535 (inclusive)."); + + IPAddress ip; + if (p_address.is_valid_ip_address()) { + ip = p_address; + } else { +#ifdef GODOT_ENET + ip = IP::get_singleton()->resolve_hostname(p_address); +#else + ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4); +#endif + ERR_FAIL_COND_V_MSG(!ip.is_valid(), out, "Couldn't resolve the server IP address or domain name."); + } + + ENetAddress address; +#ifdef GODOT_ENET + enet_address_set_ip(&address, ip.get_ipv6(), 16); +#else + ERR_FAIL_COND_V_MSG(!ip.is_ipv4(), out, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library."); + address.host = *(uint32_t *)ip.get_ipv4(); +#endif + address.port = p_port; + + // Initiate connection, allocating enough channels + ENetPeer *peer = enet_host_connect(host, &address, p_channels, p_data); + + if (peer == nullptr) { + return nullptr; + } + out = Ref(memnew(ENetPacketPeer(peer))); + peers.push_back(out); + return out; +} + +ENetConnection::EventType ENetConnection::service(int p_timeout, Event &r_event) { + ERR_FAIL_COND_V_MSG(!host, EVENT_ERROR, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_V(r_event.peer.is_valid(), EVENT_ERROR); + + // Drop peers that have already been disconnected. + // NOTE: Forcibly disconnected peers (i.e. peers disconnected via + // enet_peer_disconnect*) do not trigger DISCONNECTED events. + List>::Element *E = peers.front(); + while (E) { + if (!E->get()->is_active()) { + peers.erase(E->get()); + } + E = E->next(); + } + + ENetEvent event; + int ret = enet_host_service(host, &event, p_timeout); + + if (ret < 0) { + return EVENT_ERROR; + } else if (ret == 0) { + return EVENT_NONE; + } + switch (event.type) { + case ENET_EVENT_TYPE_CONNECT: { + if (event.peer->data == nullptr) { + Ref pp = memnew(ENetPacketPeer(event.peer)); + peers.push_back(pp); + } + r_event.peer = Ref((ENetPacketPeer *)event.peer->data); + r_event.data = event.data; + return EVENT_CONNECT; + } break; + case ENET_EVENT_TYPE_DISCONNECT: { + // A peer disconnected. + if (event.peer->data != nullptr) { + Ref pp = Ref((ENetPacketPeer *)event.peer->data); + pp->_on_disconnect(); + peers.erase(pp); + r_event.peer = pp; + r_event.data = event.data; + return EVENT_DISCONNECT; + } + return EVENT_ERROR; + } break; + case ENET_EVENT_TYPE_RECEIVE: { + // Packet reveived. + if (event.peer->data != nullptr) { + Ref pp = Ref((ENetPacketPeer *)event.peer->data); + r_event.peer = Ref((ENetPacketPeer *)event.peer->data); + r_event.channel_id = event.channelID; + r_event.packet = event.packet; + return EVENT_RECEIVE; + } + return EVENT_ERROR; + } break; + case ENET_EVENT_TYPE_NONE: + return EVENT_NONE; + default: + return EVENT_NONE; + } +} + +void ENetConnection::flush() { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_flush(host); +} + +void ENetConnection::bandwidth_limit(int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_bandwidth_limit(host, p_in_bandwidth, p_out_bandwidth); +} + +void ENetConnection::channel_limit(int p_max_channels) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_channel_limit(host, p_max_channels); +} + +void ENetConnection::bandwidth_throttle() { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_bandwidth_throttle(host); +} + +void ENetConnection::compress(CompressionMode p_mode) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + Compressor::setup(host, p_mode); +} + +double ENetConnection::pop_statistic(HostStatistic p_stat) { + ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active."); + uint32_t *ptr = nullptr; + switch (p_stat) { + case HOST_TOTAL_SENT_DATA: + ptr = &(host->totalSentData); + break; + case HOST_TOTAL_SENT_PACKETS: + ptr = &(host->totalSentPackets); + break; + case HOST_TOTAL_RECEIVED_DATA: + ptr = &(host->totalReceivedData); + break; + case HOST_TOTAL_RECEIVED_PACKETS: + ptr = &(host->totalReceivedPackets); + break; + } + ERR_FAIL_COND_V_MSG(ptr == nullptr, 0, "Invalid statistic: " + itos(p_stat)); + uint32_t ret = *ptr; + *ptr = 0; + return ret; +} + +int ENetConnection::get_max_channels() const { + ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active."); + return host->channelLimit; +} + +int ENetConnection::get_local_port() const { + ERR_FAIL_COND_V_MSG(!host, 0, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_V_MSG(!(host->socket), 0, "The ENetConnection instance isn't currently bound"); + ENetAddress address; + ERR_FAIL_COND_V_MSG(enet_socket_get_address(host->socket, &address), 0, "Unable to get socket address"); + return address.port; +} + +void ENetConnection::get_peers(List> &r_peers) { + for (const Ref &I : peers) { + r_peers.push_back(I); + } +} + +Array ENetConnection::_get_peers() { + ERR_FAIL_COND_V_MSG(!host, Array(), "The ENetConnection instance isn't currently active."); + Array out; + for (const Ref &I : peers) { + out.push_back(I); + } + return out; +} + +Error ENetConnection::dtls_server_setup(Ref p_key, Ref p_cert) { +#ifdef GODOT_ENET + ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active."); + return enet_host_dtls_server_setup(host, p_key.ptr(), p_cert.ptr()) ? FAILED : OK; +#else + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build."); +#endif +} + +void ENetConnection::refuse_new_connections(bool p_refuse) { +#ifdef GODOT_ENET + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + enet_host_refuse_new_connections(host, p_refuse); +#else + ERR_FAIL_MSG("ENet DTLS support not available in this build."); +#endif +} + +Error ENetConnection::dtls_client_setup(Ref p_cert, const String &p_hostname, bool p_verify) { +#ifdef GODOT_ENET + ERR_FAIL_COND_V_MSG(!host, ERR_UNCONFIGURED, "The ENetConnection instance isn't currently active."); + return enet_host_dtls_client_setup(host, p_cert.ptr(), p_verify, p_hostname.utf8().get_data()) ? FAILED : OK; +#else + ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "ENet DTLS support not available in this build."); +#endif +} + +Error ENetConnection::_create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_V_MSG(host != nullptr, ERR_ALREADY_IN_USE, "The ENetConnection instance is already active."); + ERR_FAIL_COND_V_MSG(p_max_peers < 1 || p_max_peers > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive)."); + ERR_FAIL_COND_V_MSG(p_max_channels < 0 || p_max_channels > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, ERR_INVALID_PARAMETER, "Invalid channel count. Must be between 0 and 255 (0 means maximum, i.e. 255)"); + ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); + ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); + + host = enet_host_create(p_address /* the address to bind the server host to */, + p_max_peers /* allow up to p_max_peers connections */, + p_max_channels /* allow up to p_max_channel to be used */, + p_in_bandwidth /* limit incoming bandwidth if > 0 */, + p_out_bandwidth /* limit outgoing bandwidth if > 0 */); + + ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create an ENet host."); + return OK; +} + +Array ENetConnection::_service(int p_timeout) { + Array out; + Event event; + Ref peer; + EventType ret = service(p_timeout, event); + out.push_back(ret); + out.push_back(event.peer); + out.push_back(event.data); + out.push_back(event.channel_id); + if (event.packet && event.peer.is_valid()) { + event.peer->_queue_packet(event.packet); + } + return out; +} + +void ENetConnection::_broadcast(int p_channel, PackedByteArray p_packet, int p_flags) { + ERR_FAIL_COND_MSG(!host, "The ENetConnection instance isn't currently active."); + ERR_FAIL_COND_MSG(p_channel < 0 || p_channel > (int)host->channelLimit, "Invalid channel"); + ERR_FAIL_COND_MSG(p_flags & ~ENetPacketPeer::FLAG_ALLOWED, "Invalid flags"); + ENetPacket *pkt = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags); + broadcast(p_channel, pkt); +} + +void ENetConnection::_bind_methods() { + ClassDB::bind_method(D_METHOD("create_host_bound", "bind_address", "bind_port", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host_bound, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("create_host", "max_peers", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetConnection::create_host, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("destroy"), &ENetConnection::destroy); + ClassDB::bind_method(D_METHOD("connect_to_host", "address", "port", "channels", "data"), &ENetConnection::connect_to_host, DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("service", "timeout"), &ENetConnection::_service, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("flush"), &ENetConnection::flush); + ClassDB::bind_method(D_METHOD("bandwidth_limit", "in_bandwidth", "out_bandwidth"), &ENetConnection::bandwidth_limit, DEFVAL(0), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("channel_limit", "limit"), &ENetConnection::channel_limit); + ClassDB::bind_method(D_METHOD("broadcast", "channel", "packet", "flags"), &ENetConnection::_broadcast); + ClassDB::bind_method(D_METHOD("compress", "mode"), &ENetConnection::compress); + ClassDB::bind_method(D_METHOD("dtls_server_setup", "key", "certificate"), &ENetConnection::dtls_server_setup); + ClassDB::bind_method(D_METHOD("dtls_client_setup", "certificate", "hostname", "verify"), &ENetConnection::dtls_client_setup, DEFVAL(true)); + ClassDB::bind_method(D_METHOD("refuse_new_connections", "refuse"), &ENetConnection::refuse_new_connections); + ClassDB::bind_method(D_METHOD("pop_statistic", "statistic"), &ENetConnection::pop_statistic); + ClassDB::bind_method(D_METHOD("get_max_channels"), &ENetConnection::get_max_channels); + ClassDB::bind_method(D_METHOD("get_local_port"), &ENetConnection::get_local_port); + ClassDB::bind_method(D_METHOD("get_peers"), &ENetConnection::_get_peers); + + BIND_ENUM_CONSTANT(COMPRESS_NONE); + BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER); + BIND_ENUM_CONSTANT(COMPRESS_FASTLZ); + BIND_ENUM_CONSTANT(COMPRESS_ZLIB); + BIND_ENUM_CONSTANT(COMPRESS_ZSTD); + + BIND_ENUM_CONSTANT(EVENT_ERROR); + BIND_ENUM_CONSTANT(EVENT_NONE); + BIND_ENUM_CONSTANT(EVENT_CONNECT); + BIND_ENUM_CONSTANT(EVENT_DISCONNECT); + BIND_ENUM_CONSTANT(EVENT_RECEIVE); + + BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_DATA); + BIND_ENUM_CONSTANT(HOST_TOTAL_SENT_PACKETS); + BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_DATA); + BIND_ENUM_CONSTANT(HOST_TOTAL_RECEIVED_PACKETS); +} + +ENetConnection::~ENetConnection() { + if (host) { + destroy(); + } +} + +size_t ENetConnection::Compressor::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) { + Compressor *compressor = (Compressor *)(context); + + if (size_t(compressor->src_mem.size()) < inLimit) { + compressor->src_mem.resize(inLimit); + } + + int total = inLimit; + int ofs = 0; + while (total) { + for (size_t i = 0; i < inBufferCount; i++) { + int to_copy = MIN(total, int(inBuffers[i].dataLength)); + memcpy(&compressor->src_mem.write[ofs], inBuffers[i].data, to_copy); + ofs += to_copy; + total -= to_copy; + } + } + + Compression::Mode mode; + + switch (compressor->mode) { + case COMPRESS_FASTLZ: { + mode = Compression::MODE_FASTLZ; + } break; + case COMPRESS_ZLIB: { + mode = Compression::MODE_DEFLATE; + } break; + case COMPRESS_ZSTD: { + mode = Compression::MODE_ZSTD; + } break; + default: { + ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", compressor->mode)); + } + } + + int req_size = Compression::get_max_compressed_buffer_size(ofs, mode); + if (compressor->dst_mem.size() < req_size) { + compressor->dst_mem.resize(req_size); + } + int ret = Compression::compress(compressor->dst_mem.ptrw(), compressor->src_mem.ptr(), ofs, mode); + + if (ret < 0) { + return 0; + } + + if (ret > int(outLimit)) { + return 0; // Do not bother + } + + memcpy(outData, compressor->dst_mem.ptr(), ret); + + return ret; +} + +size_t ENetConnection::Compressor::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) { + Compressor *compressor = (Compressor *)(context); + int ret = -1; + switch (compressor->mode) { + case COMPRESS_FASTLZ: { + ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ); + } break; + case COMPRESS_ZLIB: { + ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE); + } break; + case COMPRESS_ZSTD: { + ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD); + } break; + default: { + } + } + if (ret < 0) { + return 0; + } else { + return ret; + } +} + +void ENetConnection::Compressor::setup(ENetHost *p_host, CompressionMode p_mode) { + ERR_FAIL_COND(!p_host); + switch (p_mode) { + case COMPRESS_NONE: { + enet_host_compress(p_host, nullptr); + } break; + case COMPRESS_RANGE_CODER: { + enet_host_compress_with_range_coder(p_host); + } break; + case COMPRESS_FASTLZ: + case COMPRESS_ZLIB: + case COMPRESS_ZSTD: { + Compressor *compressor = memnew(Compressor(p_mode)); + enet_host_compress(p_host, &(compressor->enet_compressor)); + } break; + } +} + +ENetConnection::Compressor::Compressor(CompressionMode p_mode) { + mode = p_mode; + enet_compressor.context = this; + enet_compressor.compress = enet_compress; + enet_compressor.decompress = enet_decompress; + enet_compressor.destroy = enet_compressor_destroy; +} diff --git a/modules/enet/enet_connection.h b/modules/enet/enet_connection.h new file mode 100644 index 0000000000..0f7744953e --- /dev/null +++ b/modules/enet/enet_connection.h @@ -0,0 +1,138 @@ +/*************************************************************************/ +/* enet_connection.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef ENET_CONNECTION_H +#define ENET_CONNECTION_H + +#include "core/object/ref_counted.h" + +#include "core/crypto/crypto.h" +#include "enet_packet_peer.h" + +#include + +class ENetConnection : public RefCounted { + GDCLASS(ENetConnection, RefCounted); + +public: + enum CompressionMode { + COMPRESS_NONE = 0, + COMPRESS_RANGE_CODER, + COMPRESS_FASTLZ, + COMPRESS_ZLIB, + COMPRESS_ZSTD, + }; + + enum HostStatistic { + HOST_TOTAL_SENT_DATA, + HOST_TOTAL_SENT_PACKETS, + HOST_TOTAL_RECEIVED_DATA, + HOST_TOTAL_RECEIVED_PACKETS, + }; + + enum EventType { + EVENT_ERROR = -1, + EVENT_NONE = 0, + EVENT_CONNECT, + EVENT_DISCONNECT, + EVENT_RECEIVE, + }; + + struct Event { + Ref peer; + enet_uint8 channel_id = 0; + enet_uint32 data = 0; + ENetPacket *packet = nullptr; + }; + +protected: + static void _bind_methods(); + +private: + ENetHost *host = nullptr; + List> peers; + + Error _create(ENetAddress *p_address, int p_max_peers, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth); + Array _service(int p_timeout = 0); + void _broadcast(int p_channel, PackedByteArray p_packet, int p_flags); + Array _get_peers(); + + class Compressor { + private: + CompressionMode mode = COMPRESS_NONE; + Vector src_mem; + Vector dst_mem; + ENetCompressor enet_compressor; + + Compressor(CompressionMode mode); + + static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit); + static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit); + static void enet_compressor_destroy(void *context) { + memdelete((Compressor *)context); + } + + public: + static void setup(ENetHost *p_host, CompressionMode p_mode); + }; + +public: + void broadcast(enet_uint8 p_channel, ENetPacket *p_packet); + Error create_host_bound(const IPAddress &p_bind_address = IPAddress("*"), int p_port = 0, int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0); + Error create_host(int p_max_peers = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0); + void destroy(); + Ref connect_to_host(const String &p_address, int p_port, int p_channels, int p_data = 0); + EventType service(int p_timeout, Event &r_event); + void flush(); + void bandwidth_limit(int p_in_bandwidth = 0, int p_out_bandwidth = 0); + void channel_limit(int p_max_channels); + void bandwidth_throttle(); + void compress(CompressionMode p_mode); + double pop_statistic(HostStatistic p_stat); + int get_max_channels() const; + + // Extras + void get_peers(List> &r_peers); + int get_local_port() const; + + // Godot additions + Error dtls_server_setup(Ref p_key, Ref p_cert); + Error dtls_client_setup(Ref p_cert, const String &p_hostname, bool p_verify = true); + void refuse_new_connections(bool p_refuse); + + ENetConnection() {} + ~ENetConnection(); +}; + +VARIANT_ENUM_CAST(ENetConnection::CompressionMode); +VARIANT_ENUM_CAST(ENetConnection::EventType); +VARIANT_ENUM_CAST(ENetConnection::HostStatistic); + +#endif // ENET_CONNECTION_H diff --git a/modules/enet/enet_packet_peer.cpp b/modules/enet/enet_packet_peer.cpp new file mode 100644 index 0000000000..d7d2ec9ebe --- /dev/null +++ b/modules/enet/enet_packet_peer.cpp @@ -0,0 +1,263 @@ +/*************************************************************************/ +/* enet_packet_peer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#include "enet_packet_peer.h" + +void ENetPacketPeer::peer_disconnect(int p_data) { + ERR_FAIL_COND(!peer); + enet_peer_disconnect(peer, p_data); +} + +void ENetPacketPeer::peer_disconnect_later(int p_data) { + ERR_FAIL_COND(!peer); + enet_peer_disconnect_later(peer, p_data); +} + +void ENetPacketPeer::peer_disconnect_now(int p_data) { + ERR_FAIL_COND(!peer); + enet_peer_disconnect_now(peer, p_data); + _on_disconnect(); +} + +void ENetPacketPeer::ping() { + ERR_FAIL_COND(!peer); + enet_peer_ping(peer); +} + +void ENetPacketPeer::ping_interval(int p_interval) { + ERR_FAIL_COND(!peer); + enet_peer_ping_interval(peer, p_interval); +} + +int ENetPacketPeer::send(uint8_t p_channel, ENetPacket *p_packet) { + ERR_FAIL_COND_V(peer == nullptr, -1); + ERR_FAIL_COND_V(p_packet == nullptr, -1); + ERR_FAIL_COND_V_MSG(p_channel >= peer->channelCount, -1, vformat("Unable to send packet on channel %d, max channels: %d", p_channel, (int)peer->channelCount)); + return enet_peer_send(peer, p_channel, p_packet); +} + +void ENetPacketPeer::reset() { + ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected"); + enet_peer_reset(peer); + _on_disconnect(); +} + +void ENetPacketPeer::throttle_configure(int p_interval, int p_acceleration, int p_deceleration) { + ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected"); + enet_peer_throttle_configure(peer, p_interval, p_acceleration, p_deceleration); +} + +void ENetPacketPeer::set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max) { + ERR_FAIL_COND_MSG(peer == nullptr, "Peer not connected"); + ERR_FAIL_COND_MSG(p_timeout > p_timeout_min || p_timeout_min > p_timeout_max, "Timeout limit must be less than minimum timeout, which itself must be less then maximum timeout"); + enet_peer_timeout(peer, p_timeout, p_timeout_min, p_timeout_max); +} + +int ENetPacketPeer::get_max_packet_size() const { + return 1 << 24; +} + +int ENetPacketPeer::get_available_packet_count() const { + return packet_queue.size(); +} + +Error ENetPacketPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED); + ERR_FAIL_COND_V(!packet_queue.size(), ERR_UNAVAILABLE); + if (last_packet) { + enet_packet_destroy(last_packet); + last_packet = nullptr; + } + last_packet = packet_queue.front()->get(); + packet_queue.pop_front(); + *r_buffer = (const uint8_t *)(last_packet->data); + r_buffer_size = last_packet->dataLength; + return OK; +} + +Error ENetPacketPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(!peer, ERR_UNCONFIGURED); + ENetPacket *packet = enet_packet_create(p_buffer, p_buffer_size, ENET_PACKET_FLAG_RELIABLE); + return send(0, packet) < 0 ? FAILED : OK; +} + +IPAddress ENetPacketPeer::get_remote_address() const { + ERR_FAIL_COND_V(!peer, IPAddress()); + IPAddress out; +#ifdef GODOT_ENET + out.set_ipv6((uint8_t *)&(peer->address.host)); +#else + out.set_ipv4((uint8_t *)&(peer->address.host)); +#endif + return out; +} + +int ENetPacketPeer::get_remote_port() const { + ERR_FAIL_COND_V(!peer, 0); + return peer->address.port; +} + +bool ENetPacketPeer::is_active() const { + return peer != nullptr; +} + +double ENetPacketPeer::get_statistic(PeerStatistic p_stat) { + ERR_FAIL_COND_V(!peer, 0); + switch (p_stat) { + case PEER_PACKET_LOSS: + return peer->packetLoss; + case PEER_PACKET_LOSS_VARIANCE: + return peer->packetLossVariance; + case PEER_PACKET_LOSS_EPOCH: + return peer->packetLossEpoch; + case PEER_ROUND_TRIP_TIME: + return peer->roundTripTime; + case PEER_ROUND_TRIP_TIME_VARIANCE: + return peer->roundTripTimeVariance; + case PEER_LAST_ROUND_TRIP_TIME: + return peer->lastRoundTripTime; + case PEER_LAST_ROUND_TRIP_TIME_VARIANCE: + return peer->lastRoundTripTimeVariance; + case PEER_PACKET_THROTTLE: + return peer->packetThrottle; + case PEER_PACKET_THROTTLE_LIMIT: + return peer->packetThrottleLimit; + case PEER_PACKET_THROTTLE_COUNTER: + return peer->packetThrottleCounter; + case PEER_PACKET_THROTTLE_EPOCH: + return peer->packetThrottleEpoch; + case PEER_PACKET_THROTTLE_ACCELERATION: + return peer->packetThrottleAcceleration; + case PEER_PACKET_THROTTLE_DECELERATION: + return peer->packetThrottleDeceleration; + case PEER_PACKET_THROTTLE_INTERVAL: + return peer->packetThrottleInterval; + } + ERR_FAIL_V(0); +} + +ENetPacketPeer::PeerState ENetPacketPeer::get_state() const { + if (!is_active()) { + return STATE_DISCONNECTED; + } + return (PeerState)peer->state; +} + +int ENetPacketPeer::get_channels() const { + ERR_FAIL_COND_V_MSG(!peer, 0, "The ENetConnection instance isn't currently active."); + return peer->channelCount; +} + +void ENetPacketPeer::_on_disconnect() { + if (peer) { + peer->data = nullptr; + } + peer = nullptr; +} + +void ENetPacketPeer::_queue_packet(ENetPacket *p_packet) { + ERR_FAIL_COND(!peer); + packet_queue.push_back(p_packet); +} + +Error ENetPacketPeer::_send(int p_channel, PackedByteArray p_packet, int p_flags) { + ERR_FAIL_COND_V_MSG(peer == nullptr, ERR_UNCONFIGURED, "Peer not connected"); + ERR_FAIL_COND_V_MSG(p_channel < 0 || p_channel > (int)peer->channelCount, ERR_INVALID_PARAMETER, "Invalid channel"); + ERR_FAIL_COND_V_MSG(p_flags & ~FLAG_ALLOWED, ERR_INVALID_PARAMETER, "Invalid flags"); + ENetPacket *packet = enet_packet_create(p_packet.ptr(), p_packet.size(), p_flags); + return send(p_channel, packet) == 0 ? OK : FAILED; +} + +void ENetPacketPeer::_bind_methods() { + ClassDB::bind_method(D_METHOD("peer_disconnect", "data"), &ENetPacketPeer::peer_disconnect, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("peer_disconnect_later", "data"), &ENetPacketPeer::peer_disconnect_later, DEFVAL(0)); + ClassDB::bind_method(D_METHOD("peer_disconnect_now", "data"), &ENetPacketPeer::peer_disconnect_now, DEFVAL(0)); + + ClassDB::bind_method(D_METHOD("ping"), &ENetPacketPeer::ping); + ClassDB::bind_method(D_METHOD("ping_interval", "ping_interval"), &ENetPacketPeer::ping_interval); + ClassDB::bind_method(D_METHOD("reset"), &ENetPacketPeer::reset); + ClassDB::bind_method(D_METHOD("send", "channel", "packet", "flags"), &ENetPacketPeer::_send); + ClassDB::bind_method(D_METHOD("throttle_configure", "interval", "acceleration", "deceleration"), &ENetPacketPeer::throttle_configure); + ClassDB::bind_method(D_METHOD("set_timeout", "timeout", "timeout_min", "timeout_max"), &ENetPacketPeer::set_timeout); + ClassDB::bind_method(D_METHOD("get_statistic", "statistic"), &ENetPacketPeer::get_statistic); + ClassDB::bind_method(D_METHOD("get_state"), &ENetPacketPeer::get_state); + ClassDB::bind_method(D_METHOD("get_channels"), &ENetPacketPeer::get_channels); + ClassDB::bind_method(D_METHOD("is_active"), &ENetPacketPeer::is_active); + + BIND_ENUM_CONSTANT(STATE_DISCONNECTED); + BIND_ENUM_CONSTANT(STATE_CONNECTING); + BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_CONNECT); + BIND_ENUM_CONSTANT(STATE_CONNECTION_PENDING); + BIND_ENUM_CONSTANT(STATE_CONNECTION_SUCCEEDED); + BIND_ENUM_CONSTANT(STATE_CONNECTED); + BIND_ENUM_CONSTANT(STATE_DISCONNECT_LATER); + BIND_ENUM_CONSTANT(STATE_DISCONNECTING); + BIND_ENUM_CONSTANT(STATE_ACKNOWLEDGING_DISCONNECT); + BIND_ENUM_CONSTANT(STATE_ZOMBIE); + + BIND_ENUM_CONSTANT(PEER_PACKET_LOSS); + BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_VARIANCE); + BIND_ENUM_CONSTANT(PEER_PACKET_LOSS_EPOCH); + BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME); + BIND_ENUM_CONSTANT(PEER_ROUND_TRIP_TIME_VARIANCE); + BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME); + BIND_ENUM_CONSTANT(PEER_LAST_ROUND_TRIP_TIME_VARIANCE); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_LIMIT); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_COUNTER); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_EPOCH); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_ACCELERATION); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_DECELERATION); + BIND_ENUM_CONSTANT(PEER_PACKET_THROTTLE_INTERVAL); + + BIND_CONSTANT(PACKET_LOSS_SCALE); + BIND_CONSTANT(PACKET_THROTTLE_SCALE); + + BIND_CONSTANT(FLAG_RELIABLE); + BIND_CONSTANT(FLAG_UNSEQUENCED); + BIND_CONSTANT(FLAG_UNRELIABLE_FRAGMENT); +} + +ENetPacketPeer::ENetPacketPeer(ENetPeer *p_peer) { + peer = p_peer; + peer->data = this; +} + +ENetPacketPeer::~ENetPacketPeer() { + _on_disconnect(); + if (last_packet) { + enet_packet_destroy(last_packet); + last_packet = nullptr; + } + for (List::Element *E = packet_queue.front(); E; E = E->next()) { + enet_packet_destroy(E->get()); + } + packet_queue.clear(); +} diff --git a/modules/enet/enet_packet_peer.h b/modules/enet/enet_packet_peer.h new file mode 100644 index 0000000000..9af004de2f --- /dev/null +++ b/modules/enet/enet_packet_peer.h @@ -0,0 +1,131 @@ +/*************************************************************************/ +/* enet_packet_peer.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/*************************************************************************/ + +#ifndef ENET_PACKET_PEER_H +#define ENET_PACKET_PEER_H + +#include "core/io/packet_peer.h" + +#include + +class ENetPacketPeer : public PacketPeer { + GDCLASS(ENetPacketPeer, PacketPeer); + +private: + ENetPeer *peer = nullptr; + List packet_queue; + ENetPacket *last_packet = nullptr; + + static void _bind_methods(); + Error _send(int p_channel, PackedByteArray p_packet, int p_flags); + +protected: + friend class ENetConnection; + // Internally used by ENetConnection during service, destroy, etc. + void _on_disconnect(); + void _queue_packet(ENetPacket *p_packet); + +public: + enum { + PACKET_THROTTLE_SCALE = ENET_PEER_PACKET_THROTTLE_SCALE, + PACKET_LOSS_SCALE = ENET_PEER_PACKET_LOSS_SCALE, + }; + + enum { + FLAG_RELIABLE = ENET_PACKET_FLAG_RELIABLE, + FLAG_UNSEQUENCED = ENET_PACKET_FLAG_UNSEQUENCED, + FLAG_UNRELIABLE_FRAGMENT = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, + FLAG_ALLOWED = ENET_PACKET_FLAG_RELIABLE | ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT, + }; + + enum PeerState { + STATE_DISCONNECTED = ENET_PEER_STATE_DISCONNECTED, + STATE_CONNECTING = ENET_PEER_STATE_CONNECTING, + STATE_ACKNOWLEDGING_CONNECT = ENET_PEER_STATE_ACKNOWLEDGING_CONNECT, + STATE_CONNECTION_PENDING = ENET_PEER_STATE_CONNECTION_PENDING, + STATE_CONNECTION_SUCCEEDED = ENET_PEER_STATE_CONNECTION_SUCCEEDED, + STATE_CONNECTED = ENET_PEER_STATE_CONNECTED, + STATE_DISCONNECT_LATER = ENET_PEER_STATE_DISCONNECT_LATER, + STATE_DISCONNECTING = ENET_PEER_STATE_DISCONNECTING, + STATE_ACKNOWLEDGING_DISCONNECT = ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT, + STATE_ZOMBIE = ENET_PEER_STATE_ZOMBIE, + }; + + enum PeerStatistic { + PEER_PACKET_LOSS, + PEER_PACKET_LOSS_VARIANCE, + PEER_PACKET_LOSS_EPOCH, + PEER_ROUND_TRIP_TIME, + PEER_ROUND_TRIP_TIME_VARIANCE, + PEER_LAST_ROUND_TRIP_TIME, + PEER_LAST_ROUND_TRIP_TIME_VARIANCE, + PEER_PACKET_THROTTLE, + PEER_PACKET_THROTTLE_LIMIT, + PEER_PACKET_THROTTLE_COUNTER, + PEER_PACKET_THROTTLE_EPOCH, + PEER_PACKET_THROTTLE_ACCELERATION, + PEER_PACKET_THROTTLE_DECELERATION, + PEER_PACKET_THROTTLE_INTERVAL, + }; + + int get_max_packet_size() const override; + int get_available_packet_count() const override; + Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet + Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; + + void peer_disconnect(int p_data = 0); + void peer_disconnect_later(int p_data = 0); + void peer_disconnect_now(int p_data = 0); + + void ping(); + void ping_interval(int p_interval); + void reset(); + int send(uint8_t p_channel, ENetPacket *p_packet); + void throttle_configure(int interval, int acceleration, int deceleration); + void set_timeout(int p_timeout, int p_timeout_min, int p_timeout_max); + double get_statistic(PeerStatistic p_stat); + PeerState get_state() const; + int get_channels() const; + + // Extras + IPAddress get_remote_address() const; + int get_remote_port() const; + + // Used by ENetMultiplayer (TODO use meta? If only they where StringNames) + bool is_active() const; + + ENetPacketPeer(ENetPeer *p_peer); + ~ENetPacketPeer(); +}; + +VARIANT_ENUM_CAST(ENetPacketPeer::PeerState); +VARIANT_ENUM_CAST(ENetPacketPeer::PeerStatistic); + +#endif // ENET_PACKET_PEER_H diff --git a/modules/enet/register_types.cpp b/modules/enet/register_types.cpp index 38870316e4..7570f5b643 100644 --- a/modules/enet/register_types.cpp +++ b/modules/enet/register_types.cpp @@ -30,7 +30,9 @@ #include "register_types.h" #include "core/error/error_macros.h" +#include "enet_connection.h" #include "enet_multiplayer_peer.h" +#include "enet_packet_peer.h" static bool enet_ok = false; @@ -42,6 +44,8 @@ void register_enet_types() { } GDREGISTER_CLASS(ENetMultiplayerPeer); + GDREGISTER_VIRTUAL_CLASS(ENetPacketPeer); + GDREGISTER_CLASS(ENetConnection); } void unregister_enet_types() { -- cgit v1.2.3 From f39547b9bdb6a09917845e7bf8ee04d64f96c582 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Fri, 16 Jul 2021 01:48:44 +0200 Subject: [Net] Refactor ENetMultiplayerPeer to use ENet wrappers. --- modules/enet/doc_classes/ENetMultiplayerPeer.xml | 159 +--- modules/enet/enet_multiplayer_peer.cpp | 1063 +++++++++------------- modules/enet/enet_multiplayer_peer.h | 90 +- 3 files changed, 481 insertions(+), 831 deletions(-) (limited to 'modules/enet') diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml index 30dec5987b..574010a4a2 100644 --- a/modules/enet/doc_classes/ENetMultiplayerPeer.xml +++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml @@ -1,11 +1,10 @@ - PacketPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. + A MultiplayerPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. - A PacketPeer implementation that should be passed to [member MultiplayerAPI.network_peer] after being initialized as either a client or server. Events can then be handled by connecting to [SceneTree] signals. - ENet's purpose is to provide a relatively thin, simple and robust network communication layer on top of UDP (User Datagram Protocol). + A MultiplayerPeer implementation that should be passed to [member MultiplayerAPI.network_peer] after being initialized as either a client, server, or mesh. Events can then be handled by connecting to [MultiplayerAPI] signals. See [ENetConnection] for more information on the ENet library wrapper. [b]Note:[/b] ENet only uses UDP, not TCP. When forwarding the server port to make your server accessible on the public Internet, you only need to forward the server port in UDP. You can use the [UPNP] class to try to forward the server port automatically when starting the server. @@ -13,6 +12,18 @@ http://enet.bespin.org/usergroup0.html + + + + + + + + + Add a new remote peer with the given [code]peer_id[/code] connected to the given [code]host[/code]. + Note: The [code]host[/code] must have exactly one peer in the [constant ENetPacketPeer.STATE_CONNECTED] state. + + @@ -29,79 +40,51 @@ - + - + - + + + - Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]local_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques. + Create client that connects to a server at [code]address[/code] using specified [code]port[/code]. The given address needs to be either a fully qualified domain name (e.g. [code]"www.example.com"[/code]) or an IP address in IPv4 or IPv6 format (e.g. [code]"192.168.1.1"[/code]). The [code]port[/code] is the port the server is listening on. The [code]channel_count[/code] parameter can be used to specify the number of ENet channels allocated for the connection. The [code]in_bandwidth[/code] and [code]out_bandwidth[/code] parameters can be used to limit the incoming and outgoing bandwidth to the given number of bytes per second. The default of 0 means unlimited bandwidth. Note that ENet will strategically drop packets on specific sides of a connection between peers to ensure the peer's bandwidth is not overwhelmed. The bandwidth parameters also determine the window size of a connection which limits the amount of reliable packets that may be in transit at any given time. Returns [constant OK] if a client was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the client could not be created. If [code]local_port[/code] is specified, the client will also listen to the given port; this is useful for some NAT traversal techniques. - + - - - - - - - + - Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4095 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the server could not be created. + Initialize this [MultiplayerPeer] in mesh mode. The provided [code]unique_id[/code] will be used as the local peer network unique ID once assigned as the [member MultiplayerAPI.network_peer]. In the mesh configuration you will need to set up each new peer manually using [ENetConnection] before calling [method add_mesh_peer]. While this technique is more advanced, it allows for better control over the connection process (e.g. when dealing with NAT punch-through) and for better distribution of the network load (which would otherwise be more taxing on the server). - - + + - + - + - - Disconnect the given peer. If "now" is set to [code]true[/code], the connection will be closed immediately without flushing queued messages. - - - - - - - Returns the channel of the last packet fetched via [method PacketPeer.get_packet]. - - - - - - - Returns the local port to which this peer is bound. - - - - - - - Returns the channel of the next packet that will be retrieved via [method PacketPeer.get_packet]. - - - - - - + + + + + - Returns the IP address of the given peer. + Create server that listens to connections via [code]port[/code]. The port needs to be an available, unused port between 0 and 65535. Note that ports below 1024 are privileged and may require elevated permissions depending on the platform. To change the interface the server listens on, use [method set_bind_ip]. The default IP is the wildcard [code]"*"[/code], which listens on all available interfaces. [code]max_clients[/code] is the maximum number of clients that are allowed at once, any number up to 4095 may be used, although the achievable number of simultaneous clients may be far lower and depends on the application. For additional details on the bandwidth parameters, see [method create_client]. Returns [constant OK] if a server was created, [constant ERR_ALREADY_IN_USE] if this ENetMultiplayerPeer instance already has an open connection (in which case you need to call [method close_connection] first) or [constant ERR_CANT_CREATE] if the server could not be created. - - + + - Returns the remote port of the given peer. + Return the [ENetPacketPeer] associated to the given [code]id[/code]. @@ -113,83 +96,17 @@ The IP used when creating a server. This is set to the wildcard [code]"*"[/code] by default, which binds to all available interfaces. The given IP needs to be in IPv4 or IPv6 address format, for example: [code]"192.168.1.1"[/code]. - - - - - - - Configure the [X509Certificate] to use when [member use_dtls] is [code]true[/code]. For servers, you must also setup the [CryptoKey] via [method set_dtls_key]. - - - - - - - - - Configure the [CryptoKey] to use when [member use_dtls] is [code]true[/code]. Remember to also call [method set_dtls_certificate] to setup your [X509Certificate]. - - - - - - - - - - - - - - - Sets the timeout parameters for a peer. The timeout parameters control how and when a peer will timeout from a failure to acknowledge reliable traffic. Timeout values are expressed in milliseconds. - The [code]timeout_limit[/code] is a factor that, multiplied by a value based on the average round trip time, will determine the timeout limit for a reliable packet. When that limit is reached, the timeout will be doubled, and the peer will be disconnected if that limit has reached [code]timeout_min[/code]. The [code]timeout_max[/code] parameter, on the other hand, defines a fixed timeout for which any packet must be acknowledged or the peer will be dropped. - - - - Enforce ordered packets when using [constant MultiplayerPeer.TRANSFER_MODE_UNRELIABLE] (thus behaving similarly to [constant MultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED]). This is the only way to use ordering with the RPC system. - - - The number of channels to be used by ENet. Channels are used to separate different kinds of data. In reliable or ordered mode, for example, the packet delivery order is ensured on a per-channel basis. This is done to combat latency and reduces ordering restrictions on packets. The delivery status of a packet in one channel won't stall the delivery of other packets in another channel. - - - The compression method used for network packets. These have different tradeoffs of compression speed versus bandwidth, you may need to test which one works best for your use case if you use compression at all. - [b]Note:[/b] Most games' network design involve sending many small packets frequently (smaller than 4 KB each). If in doubt, it is recommended to keep the default compression algorithm as it works best on these small packets. - - - Enable or disable certificate verification when [member use_dtls] [code]true[/code]. + + The underlying [ENetConnection] created after [method create_client] and [method create_server]. Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server. - - Set the default channel to be used to transfer data. By default, this value is [code]-1[/code] which means that ENet will only use 2 channels: one for reliable packets, and one for unreliable packets. The channel [code]0[/code] is reserved and cannot be used. Setting this member to any value between [code]0[/code] and [member channel_count] (excluded) will force ENet to use that channel for sending data. See [member channel_count] for more information about ENet channels. - - - When enabled, the client or server created by this peer, will use [PacketPeerDTLS] instead of raw UDP sockets for communicating with the remote peer. This will make the communication encrypted with DTLS at the cost of higher resource usage and potentially larger packet size. - Note: When creating a DTLS server, make sure you setup the key/certificate pair via [method set_dtls_key] and [method set_dtls_certificate]. For DTLS clients, have a look at the [member dtls_verify] option, and configure the certificate accordingly via [method set_dtls_certificate]. - - - No compression. This uses the most bandwidth, but has the upside of requiring the fewest CPU resources. This option may also be used to make network debugging using tools like Wireshark easier. - - - ENet's built-in range encoding. Works well on small packets, but is not the most efficient algorithm on packets larger than 4 KB. - - - [url=http://fastlz.org/]FastLZ[/url] compression. This option uses less CPU resources compared to [constant COMPRESS_ZLIB], at the expense of using more bandwidth. - - - [url=https://www.zlib.net/]Zlib[/url] compression. This option uses less bandwidth compared to [constant COMPRESS_FASTLZ], at the expense of using more CPU resources. - - - [url=https://facebook.github.io/zstd/]Zstandard[/url] compression. Note that this algorithm is not very efficient on packets smaller than 4 KB. Therefore, it's recommended to use other compression algorithms in most cases. - diff --git a/modules/enet/enet_multiplayer_peer.cpp b/modules/enet/enet_multiplayer_peer.cpp index 14f9b3b1b9..28b6bb035a 100644 --- a/modules/enet/enet_multiplayer_peer.cpp +++ b/modules/enet/enet_multiplayer_peer.cpp @@ -46,458 +46,375 @@ void ENetMultiplayerPeer::set_target_peer(int p_peer) { } int ENetMultiplayerPeer::get_packet_peer() const { - ERR_FAIL_COND_V_MSG(!active, 1, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active."); ERR_FAIL_COND_V(incoming_packets.size() == 0, 1); return incoming_packets.front()->get().from; } -int ENetMultiplayerPeer::get_packet_channel() const { - ERR_FAIL_COND_V_MSG(!active, -1, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_V(incoming_packets.size() == 0, -1); - - return incoming_packets.front()->get().channel; -} - -int ENetMultiplayerPeer::get_last_packet_channel() const { - ERR_FAIL_COND_V_MSG(!active, -1, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_V(!current_packet.packet, -1); - - return current_packet.channel; -} - -Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) { - ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); - ERR_FAIL_COND_V_MSG(p_port < 0 || p_port > 65535, ERR_INVALID_PARAMETER, "The local port number must be between 0 and 65535 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_max_clients < 1 || p_max_clients > 4095, ERR_INVALID_PARAMETER, "The number of clients must be set between 1 and 4095 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - ERR_FAIL_COND_V(dtls_enabled && (dtls_key.is_null() || dtls_cert.is_null()), ERR_INVALID_PARAMETER); - - ENetAddress address; - memset(&address, 0, sizeof(address)); - -#ifdef GODOT_ENET - if (bind_ip.is_wildcard()) { - address.wildcard = 1; - } else { - enet_address_set_ip(&address, bind_ip.get_ipv6(), 16); - } -#else - if (bind_ip.is_wildcard()) { - address.host = 0; - } else { - ERR_FAIL_COND_V(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER); - address.host = *(uint32_t *)bind_ip.get_ipv4(); - } -#endif - address.port = p_port; - - host = enet_host_create(&address /* the address to bind the server host to */, - p_max_clients /* allow up to 32 clients and/or outgoing connections */, - channel_count /* allow up to channel_count to be used */, - p_in_bandwidth /* limit incoming bandwidth if > 0 */, - p_out_bandwidth /* limit outgoing bandwidth if > 0 */); - - ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create an ENet multiplayer server."); -#ifdef GODOT_ENET - if (dtls_enabled) { - enet_host_dtls_server_setup(host, dtls_key.ptr(), dtls_cert.ptr()); +Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) { + ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); + Ref host; + host.instantiate(); + 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); + if (err != OK) { + return err; } - enet_host_refuse_new_connections(host, refuse_connections); -#endif - _setup_compressor(); - active = true; - server = true; + active_mode = MODE_SERVER; refuse_connections = false; unique_id = 1; connection_status = CONNECTION_CONNECTED; + hosts[0] = host; return OK; } -Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, int p_in_bandwidth, int p_out_bandwidth, int p_local_port) { - ERR_FAIL_COND_V_MSG(active, ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); - ERR_FAIL_COND_V_MSG(p_port < 1 || p_port > 65535, ERR_INVALID_PARAMETER, "The remote port number must be between 1 and 65535 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_local_port < 0 || p_local_port > 65535, ERR_INVALID_PARAMETER, "The local port number must be between 0 and 65535 (inclusive)."); - ERR_FAIL_COND_V_MSG(p_in_bandwidth < 0, ERR_INVALID_PARAMETER, "The incoming bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - ERR_FAIL_COND_V_MSG(p_out_bandwidth < 0, ERR_INVALID_PARAMETER, "The outgoing bandwidth limit must be greater than or equal to 0 (0 disables the limit)."); - - ENetAddress c_client; -#ifdef GODOT_ENET - if (bind_ip.is_wildcard()) { - c_client.wildcard = 1; +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) { + ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); + Ref host; + host.instantiate(); + Error err; + if (p_local_port) { + err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth); } else { - enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16); + err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth); } -#else - if (bind_ip.is_wildcard()) { - c_client.host = 0; - } else { - ERR_FAIL_COND_V_MSG(!bind_ip.is_ipv4(), ERR_INVALID_PARAMETER, "Wildcard IP addresses are only permitted in IPv4, not IPv6."); - c_client.host = *(uint32_t *)bind_ip.get_ipv4(); + if (err != OK) { + return err; } -#endif - - c_client.port = p_local_port; - - host = enet_host_create(&c_client /* create a client host */, - 1 /* only allow 1 outgoing connection */, - channel_count /* allow up to channel_count to be used */, - p_in_bandwidth /* limit incoming bandwidth if > 0 */, - p_out_bandwidth /* limit outgoing bandwidth if > 0 */); - - ERR_FAIL_COND_V_MSG(!host, ERR_CANT_CREATE, "Couldn't create the ENet client host."); -#ifdef GODOT_ENET - if (dtls_enabled) { - enet_host_dtls_client_setup(host, dtls_cert.ptr(), dtls_verify, p_address.utf8().get_data()); - } - enet_host_refuse_new_connections(host, refuse_connections); -#endif - - _setup_compressor(); - - IPAddress ip; - if (p_address.is_valid_ip_address()) { - ip = p_address; - } else { -#ifdef GODOT_ENET - ip = IP::get_singleton()->resolve_hostname(p_address); -#else - ip = IP::get_singleton()->resolve_hostname(p_address, IP::TYPE_IPV4); -#endif - - ERR_FAIL_COND_V_MSG(!ip.is_valid(), ERR_CANT_RESOLVE, "Couldn't resolve the server IP address or domain name."); - } - - ENetAddress address; -#ifdef GODOT_ENET - enet_address_set_ip(&address, ip.get_ipv6(), 16); -#else - ERR_FAIL_COND_V_MSG(!ip.is_ipv4(), ERR_INVALID_PARAMETER, "Connecting to an IPv6 server isn't supported when using vanilla ENet. Recompile Godot with the bundled ENet library."); - address.host = *(uint32_t *)ip.get_ipv4(); -#endif - address.port = p_port; unique_id = generate_unique_id(); - // Initiate connection, allocating enough channels - ENetPeer *peer = enet_host_connect(host, &address, channel_count, unique_id); - - if (peer == nullptr) { - enet_host_destroy(host); - ERR_FAIL_COND_V_MSG(!peer, ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server."); + Ref peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id); + if (peer.is_null()) { + host->destroy(); + ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server."); } - // Technically safe to ignore the peer or anything else. - + // Need to wait for CONNECT event. connection_status = CONNECTION_CONNECTING; - active = true; - server = false; + active_mode = MODE_CLIENT; refuse_connections = false; + peers[1] = peer; + hosts[0] = host; return OK; } -void ENetMultiplayerPeer::poll() { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); +Error ENetMultiplayerPeer::create_mesh(int p_id) { + ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0"); + ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active."); + active_mode = MODE_MESH; + refuse_connections = false; + unique_id = p_id; + connection_status = CONNECTION_CONNECTED; + return OK; +} - _pop_current_packet(); +Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref p_host) { + ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first."); + List> host_peers; + p_host->get_peers(host_peers); + 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 excatly one peer in the connected state."); + hosts[p_id] = p_host; + peers[p_id] = host_peers[0]; + emit_signal(SNAME("peer_connected"), p_id); + return OK; +} - ENetEvent event; - /* Keep servicing until there are no available events left in queue. */ - while (true) { - if (!host || !active) { // Might have been disconnected while emitting a notification - return; +bool ENetMultiplayerPeer::_poll_server() { + for (const KeyValue> &E : peers) { + if (!(E.value->is_active())) { + emit_signal(SNAME("peer_disconnected"), E.value->get_meta(SNAME("_net_id"))); + peers.erase(E.key); } + } + ENetConnection::Event event; + ENetConnection::EventType ret = hosts[0]->service(0, event); + if (ret == ENetConnection::EVENT_ERROR) { + return true; + } + switch (ret) { + case ENetConnection::EVENT_CONNECT: { + if (refuse_connections) { + event.peer->reset(); + return false; + } + // Client joined with invalid ID, probably trying to exploit us. + if (event.data < 2 || peers.has((int)event.data)) { + event.peer->reset(); + return false; + } + int id = event.data; + event.peer->set_meta(SNAME("_net_id"), id); + peers[id] = event.peer; - int ret = enet_host_service(host, &event, 0); + emit_signal(SNAME("peer_connected"), id); + if (server_relay) { + _notify_peers(id, true); + } + return false; + } + case ENetConnection::EVENT_DISCONNECT: { + int id = event.peer->get_meta(SNAME("_net_id")); + if (!peers.has(id)) { + // Never fully connected. + return false; + } - if (ret < 0) { - // Error, do something? - break; - } else if (ret == 0) { - break; + emit_signal(SNAME("peer_disconnected"), id); + peers.erase(id); + if (!server_relay) { + _notify_peers(id, false); + } + return false; } + case ENetConnection::EVENT_RECEIVE: { + if (event.channel_id == SYSCH_CONFIG) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Only server can send config messages"); + } else { + if (event.packet->dataLength < 8) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Invalid packet size"); + } - switch (event.type) { - case ENET_EVENT_TYPE_CONNECT: { - // Store any relevant client information here. + uint32_t source = decode_uint32(&event.packet->data[0]); + int target = decode_uint32(&event.packet->data[4]); - if (server && refuse_connections) { - enet_peer_reset(event.peer); - break; + uint32_t id = event.peer->get_meta(SNAME("_net_id")); + // Someone is cheating and trying to fake the source! + if (source != id) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Someone is cheating and trying to fake the source!"); } - // A client joined with an invalid ID (negative values, 0, and 1 are reserved). - // Probably trying to exploit us. - if (server && ((int)event.data < 2 || peer_map.has((int)event.data))) { - enet_peer_reset(event.peer); - ERR_CONTINUE(true); - } + Packet packet; + packet.packet = event.packet; + packet.channel = event.channel_id; + packet.from = id; - int *new_id = memnew(int); - *new_id = event.data; + // Even if relaying is disabled, these targets are valid as incoming packets. + if (target == 1 || target == 0 || target < -1) { + packet.packet->referenceCount++; + incoming_packets.push_back(packet); + } - if (*new_id == 0) { // Data zero is sent by server (ENet won't let you configure this). Server is always 1. - *new_id = 1; + if (server_relay && target != 1) { + packet.packet->referenceCount++; + _relay(source, target, event.channel_id, event.packet); + packet.packet->referenceCount--; + _destroy_unused(event.packet); } + // Destroy packet later + } + return false; + } + default: + return true; + } +} - event.peer->data = new_id; - - peer_map[*new_id] = event.peer; - - connection_status = CONNECTION_CONNECTED; // If connecting, this means it connected to something! - - emit_signal(SNAME("peer_connected"), *new_id); - - if (server) { - // Do not notify other peers when server_relay is disabled. - if (!server_relay) { - break; - } - - // Someone connected, notify all the peers available - for (Map::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == *new_id) { - continue; - } - // Send existing peers to new peer - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]); - encode_uint32(E->key(), &packet->data[4]); - enet_peer_send(event.peer, SYSCH_CONFIG, packet); - // Send the new peer to existing peers - packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]); - encode_uint32(*new_id, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } - } else { - emit_signal(SNAME("connection_succeeded")); +bool ENetMultiplayerPeer::_poll_client() { + if (peers.has(1) && !peers[1]->is_active()) { + if (connection_status == CONNECTION_CONNECTED) { + // Client just disconnected from server. + emit_signal(SNAME("server_disconnected")); + } else { + emit_signal(SNAME("connection_failed")); + } + close_connection(); + return true; + } + ENetConnection::Event event; + ENetConnection::EventType ret = hosts[0]->service(0, event); + if (ret == ENetConnection::EVENT_ERROR) { + return true; + } + switch (ret) { + case ENetConnection::EVENT_CONNECT: { + emit_signal(SNAME("peer_connected"), 1); + connection_status = CONNECTION_CONNECTED; + emit_signal(SNAME("connection_succeeded")); + return false; + } + case ENetConnection::EVENT_DISCONNECT: { + if (connection_status == CONNECTION_CONNECTED) { + // Client just disconnected from server. + emit_signal(SNAME("server_disconnected")); + } else { + emit_signal(SNAME("connection_failed")); + } + close_connection(); + return true; + } + case ENetConnection::EVENT_RECEIVE: { + if (event.channel_id == SYSCH_CONFIG) { + // Config message + if (event.packet->dataLength != 8) { + _destroy_unused(event.packet); + ERR_FAIL_V(false); } - } break; - case ENET_EVENT_TYPE_DISCONNECT: { - // Reset the peer's client information. + int msg = decode_uint32(&event.packet->data[0]); + int id = decode_uint32(&event.packet->data[4]); - int *id = (int *)event.peer->data; + switch (msg) { + case SYSMSG_ADD_PEER: { + peers[id] = Ref(); + emit_signal(SNAME("peer_connected"), id); - if (!id) { - if (!server) { - emit_signal(SNAME("connection_failed")); - } - // Never fully connected. - break; + } break; + case SYSMSG_REMOVE_PEER: { + peers.erase(id); + emit_signal(SNAME("peer_disconnected"), id); + } break; } - - if (!server) { - // Client just disconnected from server. - emit_signal(SNAME("server_disconnected")); - close_connection(); - return; - } else if (server_relay) { - // Server just received a client disconnect and is in relay mode, notify everyone else. - for (Map::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == *id) { - continue; - } - - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); - encode_uint32(*id, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } + _destroy_unused(event.packet); + } else { + if (event.packet->dataLength < 8) { + _destroy_unused(event.packet); + ERR_FAIL_V_MSG(false, "Invalid packet size"); } - emit_signal(SNAME("peer_disconnected"), *id); - peer_map.erase(*id); - memdelete(id); - } break; - case ENET_EVENT_TYPE_RECEIVE: { - if (event.channelID == SYSCH_CONFIG) { - // Some config message - ERR_CONTINUE(event.packet->dataLength < 8); - - // Only server can send config messages - ERR_CONTINUE(server); - - int msg = decode_uint32(&event.packet->data[0]); - int id = decode_uint32(&event.packet->data[4]); - - switch (msg) { - case SYSMSG_ADD_PEER: { - peer_map[id] = nullptr; - emit_signal(SNAME("peer_connected"), id); - - } break; - case SYSMSG_REMOVE_PEER: { - peer_map.erase(id); - emit_signal(SNAME("peer_disconnected"), id); - } break; - } - - enet_packet_destroy(event.packet); - } else if (event.channelID < channel_count) { - Packet packet; - packet.packet = event.packet; - - uint32_t *id = (uint32_t *)event.peer->data; - - ERR_CONTINUE(event.packet->dataLength < 8); - - uint32_t source = decode_uint32(&event.packet->data[0]); - int target = decode_uint32(&event.packet->data[4]); - - packet.from = source; - packet.channel = event.channelID; - - if (server) { - // Someone is cheating and trying to fake the source! - ERR_CONTINUE(source != *id); - - packet.from = *id; - - if (target == 1) { - // To myself and only myself - incoming_packets.push_back(packet); - } else if (!server_relay) { - // When relaying is disabled, other destinations will only be processed by the server. - if (target == 0 || target < -1) { - incoming_packets.push_back(packet); - } - continue; - } else if (target == 0) { - // Re-send to everyone but sender :| - - incoming_packets.push_back(packet); - // And make copies for sending - for (Map::Element *E = peer_map.front(); E; E = E->next()) { - if (uint32_t(E->key()) == source) { // Do not resend to self - continue; - } - - ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags); - - enet_peer_send(E->get(), event.channelID, packet2); - } - - } else if (target < 0) { - // To all but one - - // And make copies for sending - for (Map::Element *E = peer_map.front(); E; E = E->next()) { - if (uint32_t(E->key()) == source || E->key() == -target) { // Do not resend to self, also do not send to excluded - continue; - } - - ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, packet.packet->flags); - - enet_peer_send(E->get(), event.channelID, packet2); - } - - if (-target != 1) { - // Server is not excluded - incoming_packets.push_back(packet); - } else { - // Server is excluded, erase packet - enet_packet_destroy(packet.packet); - } - - } else { - // To someone else, specifically - ERR_CONTINUE(!peer_map.has(target)); - enet_peer_send(peer_map[target], event.channelID, packet.packet); - } - } else { - incoming_packets.push_back(packet); - } - - // Destroy packet later - } else { - ERR_CONTINUE(true); + uint32_t source = decode_uint32(&event.packet->data[0]); + Packet packet; + packet.packet = event.packet; + packet.from = source; + packet.channel = event.channel_id; + + packet.packet->referenceCount++; + incoming_packets.push_back(packet); + // Destroy packet later + } + return false; + } + default: + return true; + } +} + +bool ENetMultiplayerPeer::_poll_mesh() { + for (const KeyValue> &E : peers) { + if (!(E.value->is_active())) { + emit_signal(SNAME("peer_disconnected"), E.key); + peers.erase(E.key); + if (hosts.has(E.key)) { + hosts.erase(E.key); + } + } + } + bool should_stop = true; + for (KeyValue> &E : hosts) { + ENetConnection::Event event; + ENetConnection::EventType ret = E.value->service(0, event); + if (ret == ENetConnection::EVENT_ERROR) { + if (peers.has(E.key)) { + emit_signal(SNAME("peer_disconnected"), E.key); + peers.erase(E.key); + } + hosts.erase(E.key); + continue; + } + switch (ret) { + case ENetConnection::EVENT_CONNECT: + should_stop = false; + event.peer->reset(); + break; + case ENetConnection::EVENT_DISCONNECT: + should_stop = false; + if (peers.has(E.key)) { + emit_signal(SNAME("peer_disconnected"), E.key); + peers.erase(E.key); + } + hosts.erase(E.key); + break; + case ENetConnection::EVENT_RECEIVE: { + should_stop = false; + if (event.packet->dataLength < 8) { + _destroy_unused(event.packet); + ERR_CONTINUE_MSG(true, "Invalid packet size"); } + Packet packet; + packet.packet = event.packet; + packet.from = E.key; + packet.channel = event.channel_id; + + packet.packet->referenceCount++; + incoming_packets.push_back(packet); } break; - case ENET_EVENT_TYPE_NONE: { - // Do nothing - } break; + default: + break; // Nothing to do } } + return should_stop; } -bool ENetMultiplayerPeer::is_server() const { - ERR_FAIL_COND_V_MSG(!active, false, "The multiplayer instance isn't currently active."); +void ENetMultiplayerPeer::poll() { + ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active."); - return server; + _pop_current_packet(); + + while (true) { + switch (active_mode) { + case MODE_CLIENT: + if (_poll_client()) { + return; + } + break; + case MODE_SERVER: + if (_poll_server()) { + return; + } + break; + case MODE_MESH: + if (_poll_mesh()) { + return; + } + break; + default: + return; + } + } +} + +bool ENetMultiplayerPeer::is_server() const { + return active_mode == MODE_SERVER; } void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active."); _pop_current_packet(); bool peers_disconnected = false; - for (Map::Element *E = peer_map.front(); E; E = E->next()) { - if (E->get()) { - enet_peer_disconnect_now(E->get(), unique_id); - int *id = (int *)(E->get()->data); - memdelete(id); + for (KeyValue> &E : peers) { + if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) { + E.value->peer_disconnect_now(unique_id); peers_disconnected = true; } } if (peers_disconnected) { - enet_host_flush(host); + for (KeyValue> &E : hosts) { + E.value->flush(); + } if (wait_usec > 0) { OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send } } - enet_host_destroy(host); - active = false; + active_mode = MODE_NONE; incoming_packets.clear(); - peer_map.clear(); - unique_id = 1; // Server is 1 + peers.clear(); + hosts.clear(); + unique_id = 0; connection_status = CONNECTION_DISCONNECTED; } -void ENetMultiplayerPeer::disconnect_peer(int p_peer, bool now) { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); - ERR_FAIL_COND_MSG(!is_server(), "Can't disconnect a peer when not acting as a server."); - ERR_FAIL_COND_MSG(!peer_map.has(p_peer), vformat("Peer ID %d not found in the list of peers.", p_peer)); - - if (now) { - int *id = (int *)peer_map[p_peer]->data; - enet_peer_disconnect_now(peer_map[p_peer], 0); - - // enet_peer_disconnect_now doesn't generate ENET_EVENT_TYPE_DISCONNECT, - // notify everyone else, send disconnect signal & remove from peer_map like in poll() - if (server_relay) { - for (Map::Element *E = peer_map.front(); E; E = E->next()) { - if (E->key() == p_peer) { - continue; - } - - ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); - encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); - encode_uint32(p_peer, &packet->data[4]); - enet_peer_send(E->get(), SYSCH_CONFIG, packet); - } - } - - if (id) { - memdelete(id); - } - - emit_signal(SNAME("peer_disconnected"), p_peer); - peer_map.erase(p_peer); - } else { - enet_peer_disconnect_later(peer_map[p_peer], 0); - } -} - int ENetMultiplayerPeer::get_available_packet_count() const { return incoming_packets.size(); } @@ -517,19 +434,17 @@ Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_si } Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V_MSG(!active, ERR_UNCONFIGURED, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active."); ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client."); + ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(ABS(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer)); + ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG); int packet_flags = 0; int channel = SYSCH_RELIABLE; switch (transfer_mode) { case TRANSFER_MODE_UNRELIABLE: { - if (always_ordered) { - packet_flags = 0; - } else { - packet_flags = ENET_PACKET_FLAG_UNSEQUENCED; - } + packet_flags = ENET_PACKET_FLAG_UNSEQUENCED; channel = SYSCH_UNRELIABLE; } break; case TRANSFER_MODE_UNRELIABLE_ORDERED: { @@ -542,52 +457,55 @@ Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size } break; } - if (transfer_channel > SYSCH_CONFIG) { - channel = transfer_channel; - } - - Map::Element *E = nullptr; - - if (target_peer != 0) { - E = peer_map.find(ABS(target_peer)); - ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer)); - } - ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size + 8, packet_flags); encode_uint32(unique_id, &packet->data[0]); // Source ID encode_uint32(target_peer, &packet->data[4]); // Dest ID memcpy(&packet->data[8], p_buffer, p_buffer_size); - if (server) { + if (is_server()) { if (target_peer == 0) { - enet_host_broadcast(host, channel, packet); - } else if (target_peer < 0) { - // Send to all but one - // and make copies for sending + hosts[0]->broadcast(channel, packet); + } else if (target_peer < 0) { + // Send to all but one and make copies for sending. int exclude = -target_peer; - - for (Map::Element *F = peer_map.front(); F; F = F->next()) { - if (F->key() == exclude) { // Exclude packet + for (KeyValue> &E : peers) { + if (E.key == exclude) { continue; } + E.value->send(channel, packet); + } + _destroy_unused(packet); + } else { + peers[target_peer]->send(channel, packet); + } + ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG); + hosts[0]->flush(); - ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags); + } else if (active_mode == MODE_CLIENT) { + peers[1]->send(channel, packet); // Send to server for broadcast. + ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG); + hosts[0]->flush(); - enet_peer_send(F->get(), channel, packet2); + } else { + if (target_peer <= 0) { + int exclude = ABS(target_peer); + for (KeyValue> &E : peers) { + if (E.key == exclude) { + continue; + } + E.value->send(channel, packet); + ERR_CONTINUE(!hosts.has(E.key)); + hosts[E.key]->flush(); } - - enet_packet_destroy(packet); // Original packet no longer needed + _destroy_unused(packet); } else { - enet_peer_send(E->get(), channel, packet); + peers[target_peer]->send(channel, packet); + ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG); + hosts[target_peer]->flush(); } - } else { - ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG); - enet_peer_send(peer_map[1], channel, packet); // Send to server for broadcast } - enet_host_flush(host); - return OK; } @@ -597,7 +515,8 @@ int ENetMultiplayerPeer::get_max_packet_size() const { void ENetMultiplayerPeer::_pop_current_packet() { if (current_packet.packet) { - enet_packet_destroy(current_packet.packet); + current_packet.packet->referenceCount--; + _destroy_unused(current_packet.packet); current_packet.packet = nullptr; current_packet.from = 0; current_packet.channel = -1; @@ -609,15 +528,17 @@ MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() c } int ENetMultiplayerPeer::get_unique_id() const { - ERR_FAIL_COND_V_MSG(!active, 0, "The multiplayer instance isn't currently active."); + ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active."); return unique_id; } void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enable) { refuse_connections = p_enable; #ifdef GODOT_ENET - if (active) { - enet_host_refuse_new_connections(host, p_enable); + if (_is_active()) { + for (KeyValue> &E : hosts) { + E.value->refuse_new_connections(p_enable); + } } #endif } @@ -626,244 +547,122 @@ bool ENetMultiplayerPeer::is_refusing_new_connections() const { return refuse_connections; } -void ENetMultiplayerPeer::set_compression_mode(CompressionMode p_mode) { - compression_mode = p_mode; +void ENetMultiplayerPeer::set_server_relay_enabled(bool p_enabled) { + ERR_FAIL_COND_MSG(_is_active(), "Server relaying can't be toggled while the multiplayer instance is active."); + + server_relay = p_enabled; } -ENetMultiplayerPeer::CompressionMode ENetMultiplayerPeer::get_compression_mode() const { - return compression_mode; +bool ENetMultiplayerPeer::is_server_relay_enabled() const { + return server_relay; } -size_t ENetMultiplayerPeer::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) { - ENetMultiplayerPeer *enet = (ENetMultiplayerPeer *)(context); +Ref ENetMultiplayerPeer::get_host() const { + ERR_FAIL_COND_V(!_is_active(), nullptr); + ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr); + return hosts[0]; +} - if (size_t(enet->src_compressor_mem.size()) < inLimit) { - enet->src_compressor_mem.resize(inLimit); - } +Ref ENetMultiplayerPeer::get_peer(int p_id) const { + ERR_FAIL_COND_V(!_is_active(), nullptr); + ERR_FAIL_COND_V(!peers.has(p_id), nullptr); + ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr); + return peers[p_id]; +} - int total = inLimit; - int ofs = 0; - while (total) { - for (size_t i = 0; i < inBufferCount; i++) { - int to_copy = MIN(total, int(inBuffers[i].dataLength)); - memcpy(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy); - ofs += to_copy; - total -= to_copy; - } +void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) { + if (p_packet->referenceCount == 0) { + enet_packet_destroy(p_packet); } +} - Compression::Mode mode; +void ENetMultiplayerPeer::_relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet) { + if (p_to == 0) { + // Re-send to everyone but sender :| + for (KeyValue> &E : peers) { + if (E.key == p_from) { + continue; + } - switch (enet->compression_mode) { - case COMPRESS_FASTLZ: { - mode = Compression::MODE_FASTLZ; - } break; - case COMPRESS_ZLIB: { - mode = Compression::MODE_DEFLATE; - } break; - case COMPRESS_ZSTD: { - mode = Compression::MODE_ZSTD; - } break; - default: { - ERR_FAIL_V_MSG(0, vformat("Invalid ENet compression mode: %d", enet->compression_mode)); + E.value->send(p_channel, p_packet); } - } - - int req_size = Compression::get_max_compressed_buffer_size(ofs, mode); - if (enet->dst_compressor_mem.size() < req_size) { - enet->dst_compressor_mem.resize(req_size); - } - int ret = Compression::compress(enet->dst_compressor_mem.ptrw(), enet->src_compressor_mem.ptr(), ofs, mode); - - if (ret < 0) { - return 0; - } - - if (ret > int(outLimit)) { - return 0; // Do not bother - } - - memcpy(outData, enet->dst_compressor_mem.ptr(), ret); - - return ret; -} + } else if (p_to < 0) { + // Re-send to everyone but excluded and sender. + for (KeyValue> &E : peers) { + if (E.key == p_from || E.key == -p_to) { // Do not resend to self, also do not send to excluded + continue; + } -size_t ENetMultiplayerPeer::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) { - ENetMultiplayerPeer *enet = (ENetMultiplayerPeer *)(context); - int ret = -1; - switch (enet->compression_mode) { - case COMPRESS_FASTLZ: { - ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_FASTLZ); - } break; - case COMPRESS_ZLIB: { - ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE); - } break; - case COMPRESS_ZSTD: { - ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_ZSTD); - } break; - default: { + E.value->send(p_channel, p_packet); } - } - if (ret < 0) { - return 0; } else { - return ret; + // To someone else, specifically + ERR_FAIL_COND(!peers.has(p_to)); + ENetPacket *packet = enet_packet_create(p_packet->data, p_packet->dataLength, p_packet->flags); + peers[p_to]->send(p_channel, packet); } } -void ENetMultiplayerPeer::_setup_compressor() { - switch (compression_mode) { - case COMPRESS_NONE: { - enet_host_compress(host, nullptr); - } break; - case COMPRESS_RANGE_CODER: { - enet_host_compress_with_range_coder(host); - } break; - case COMPRESS_FASTLZ: - case COMPRESS_ZLIB: - case COMPRESS_ZSTD: { - enet_host_compress(host, &enet_compressor); - } break; +void ENetMultiplayerPeer::_notify_peers(int p_id, bool p_connected) { + if (p_connected) { + ERR_FAIL_COND(!peers.has(p_id)); + // Someone connected, notify all the peers available. + Ref peer = peers[p_id]; + ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); + encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]); + encode_uint32(p_id, &packet->data[4]); + for (KeyValue> &E : peers) { + if (E.key == p_id) { + continue; + } + // Send new peer to existing peer. + E.value->send(SYSCH_CONFIG, packet); + // Send existing peer to new peer. + // This packet will be automatically destroyed by ENet after send. + ENetPacket *packet2 = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); + encode_uint32(SYSMSG_ADD_PEER, &packet2->data[0]); + encode_uint32(E.key, &packet2->data[4]); + peer->send(SYSCH_CONFIG, packet2); + } + _destroy_unused(packet); + } else { + // Server just received a client disconnect and is in relay mode, notify everyone else. + ENetPacket *packet = enet_packet_create(nullptr, 8, ENET_PACKET_FLAG_RELIABLE); + encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]); + encode_uint32(p_id, &packet->data[4]); + for (KeyValue> &E : peers) { + if (E.key == p_id) { + continue; + } + E.value->send(SYSCH_CONFIG, packet); + } + _destroy_unused(packet); } } -void ENetMultiplayerPeer::enet_compressor_destroy(void *context) { - // Nothing to do -} - -IPAddress ENetMultiplayerPeer::get_peer_address(int p_peer_id) const { - ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), IPAddress(), vformat("Peer ID %d not found in the list of peers.", p_peer_id)); - ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, IPAddress(), "Can't get the address of peers other than the server (ID -1) when acting as a client."); - ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == nullptr, IPAddress(), vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id)); - - IPAddress out; -#ifdef GODOT_ENET - out.set_ipv6((uint8_t *)&(peer_map[p_peer_id]->address.host)); -#else - out.set_ipv4((uint8_t *)&(peer_map[p_peer_id]->address.host)); -#endif - - return out; -} - -int ENetMultiplayerPeer::get_peer_port(int p_peer_id) const { - ERR_FAIL_COND_V_MSG(!peer_map.has(p_peer_id), 0, vformat("Peer ID %d not found in the list of peers.", p_peer_id)); - ERR_FAIL_COND_V_MSG(!is_server() && p_peer_id != 1, 0, "Can't get the address of peers other than the server (ID -1) when acting as a client."); - ERR_FAIL_COND_V_MSG(peer_map[p_peer_id] == nullptr, 0, vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id)); -#ifdef GODOT_ENET - return peer_map[p_peer_id]->address.port; -#else - return peer_map[p_peer_id]->address.port; -#endif -} - -int ENetMultiplayerPeer::get_local_port() const { - ERR_FAIL_COND_V_MSG(!active || !host, 0, "The multiplayer instance isn't currently active."); - return host->address.port; -} - -void ENetMultiplayerPeer::set_peer_timeout(int p_peer_id, int p_timeout_limit, int p_timeout_min, int p_timeout_max) { - ERR_FAIL_COND_MSG(!peer_map.has(p_peer_id), vformat("Peer ID %d not found in the list of peers.", p_peer_id)); - ERR_FAIL_COND_MSG(!is_server() && p_peer_id != 1, "Can't change the timeout of peers other then the server when acting as a client."); - ERR_FAIL_COND_MSG(peer_map[p_peer_id] == nullptr, vformat("Peer ID %d found in the list of peers, but is null.", p_peer_id)); - ERR_FAIL_COND_MSG(p_timeout_limit > p_timeout_min || p_timeout_min > p_timeout_max, "Timeout limit must be less than minimum timeout, which itself must be less then maximum timeout"); - enet_peer_timeout(peer_map[p_peer_id], p_timeout_limit, p_timeout_min, p_timeout_max); -} - -void ENetMultiplayerPeer::set_transfer_channel(int p_channel) { - ERR_FAIL_COND_MSG(p_channel < -1 || p_channel >= channel_count, vformat("The transfer channel must be set between 0 and %d, inclusive (got %d).", channel_count - 1, p_channel)); - ERR_FAIL_COND_MSG(p_channel == SYSCH_CONFIG, vformat("The channel %d is reserved.", SYSCH_CONFIG)); - transfer_channel = p_channel; -} - -int ENetMultiplayerPeer::get_transfer_channel() const { - return transfer_channel; -} - -void ENetMultiplayerPeer::set_channel_count(int p_channel) { - ERR_FAIL_COND_MSG(active, "The channel count can't be set while the multiplayer instance is active."); - ERR_FAIL_COND_MSG(p_channel < SYSCH_MAX, vformat("The channel count must be greater than or equal to %d to account for reserved channels (got %d).", SYSCH_MAX, p_channel)); - channel_count = p_channel; -} - -int ENetMultiplayerPeer::get_channel_count() const { - return channel_count; -} - -void ENetMultiplayerPeer::set_always_ordered(bool p_ordered) { - always_ordered = p_ordered; -} - -bool ENetMultiplayerPeer::is_always_ordered() const { - return always_ordered; -} - -void ENetMultiplayerPeer::set_server_relay_enabled(bool p_enabled) { - ERR_FAIL_COND_MSG(active, "Server relaying can't be toggled while the multiplayer instance is active."); - - server_relay = p_enabled; -} - -bool ENetMultiplayerPeer::is_server_relay_enabled() const { - return server_relay; -} - void ENetMultiplayerPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0)); + 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)); + 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)); + ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh); + ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer); ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &ENetMultiplayerPeer::close_connection, DEFVAL(100)); - ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &ENetMultiplayerPeer::disconnect_peer, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &ENetMultiplayerPeer::set_compression_mode); - ClassDB::bind_method(D_METHOD("get_compression_mode"), &ENetMultiplayerPeer::get_compression_mode); ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip); - ClassDB::bind_method(D_METHOD("set_dtls_enabled", "enabled"), &ENetMultiplayerPeer::set_dtls_enabled); - ClassDB::bind_method(D_METHOD("is_dtls_enabled"), &ENetMultiplayerPeer::is_dtls_enabled); - ClassDB::bind_method(D_METHOD("set_dtls_key", "key"), &ENetMultiplayerPeer::set_dtls_key); - ClassDB::bind_method(D_METHOD("set_dtls_certificate", "certificate"), &ENetMultiplayerPeer::set_dtls_certificate); - ClassDB::bind_method(D_METHOD("set_dtls_verify_enabled", "enabled"), &ENetMultiplayerPeer::set_dtls_verify_enabled); - ClassDB::bind_method(D_METHOD("is_dtls_verify_enabled"), &ENetMultiplayerPeer::is_dtls_verify_enabled); - ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &ENetMultiplayerPeer::get_peer_address); - ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &ENetMultiplayerPeer::get_peer_port); - ClassDB::bind_method(D_METHOD("get_local_port"), &ENetMultiplayerPeer::get_local_port); - ClassDB::bind_method(D_METHOD("set_peer_timeout", "id", "timeout_limit", "timeout_min", "timeout_max"), &ENetMultiplayerPeer::set_peer_timeout); - - ClassDB::bind_method(D_METHOD("get_packet_channel"), &ENetMultiplayerPeer::get_packet_channel); - ClassDB::bind_method(D_METHOD("get_last_packet_channel"), &ENetMultiplayerPeer::get_last_packet_channel); - ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &ENetMultiplayerPeer::set_transfer_channel); - ClassDB::bind_method(D_METHOD("get_transfer_channel"), &ENetMultiplayerPeer::get_transfer_channel); - ClassDB::bind_method(D_METHOD("set_channel_count", "channels"), &ENetMultiplayerPeer::set_channel_count); - ClassDB::bind_method(D_METHOD("get_channel_count"), &ENetMultiplayerPeer::get_channel_count); - ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &ENetMultiplayerPeer::set_always_ordered); - ClassDB::bind_method(D_METHOD("is_always_ordered"), &ENetMultiplayerPeer::is_always_ordered); + ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &ENetMultiplayerPeer::set_server_relay_enabled); ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &ENetMultiplayerPeer::is_server_relay_enabled); + ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host); + ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer); - ADD_PROPERTY(PropertyInfo(Variant::INT, "compression_mode", PROPERTY_HINT_ENUM, "None,Range Coder,FastLZ,ZLib,ZStd"), "set_compression_mode", "get_compression_mode"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_channel"), "set_transfer_channel", "get_transfer_channel"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "channel_count"), "set_channel_count", "get_channel_count"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "always_ordered"), "set_always_ordered", "is_always_ordered"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dtls_verify"), "set_dtls_verify_enabled", "is_dtls_verify_enabled"); - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_dtls"), "set_dtls_enabled", "is_dtls_enabled"); - - BIND_ENUM_CONSTANT(COMPRESS_NONE); - BIND_ENUM_CONSTANT(COMPRESS_RANGE_CODER); - BIND_ENUM_CONSTANT(COMPRESS_FASTLZ); - BIND_ENUM_CONSTANT(COMPRESS_ZLIB); - BIND_ENUM_CONSTANT(COMPRESS_ZSTD); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host"); } ENetMultiplayerPeer::ENetMultiplayerPeer() { - enet_compressor.context = this; - enet_compressor.compress = enet_compress; - enet_compressor.decompress = enet_decompress; - enet_compressor.destroy = enet_compressor_destroy; - bind_ip = IPAddress("*"); } ENetMultiplayerPeer::~ENetMultiplayerPeer() { - if (active) { + if (_is_active()) { close_connection(); } } @@ -875,31 +674,3 @@ void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) { bind_ip = p_ip; } - -void ENetMultiplayerPeer::set_dtls_enabled(bool p_enabled) { - ERR_FAIL_COND(active); - dtls_enabled = p_enabled; -} - -bool ENetMultiplayerPeer::is_dtls_enabled() const { - return dtls_enabled; -} - -void ENetMultiplayerPeer::set_dtls_verify_enabled(bool p_enabled) { - ERR_FAIL_COND(active); - dtls_verify = p_enabled; -} - -bool ENetMultiplayerPeer::is_dtls_verify_enabled() const { - return dtls_verify; -} - -void ENetMultiplayerPeer::set_dtls_key(Ref p_key) { - ERR_FAIL_COND(active); - dtls_key = p_key; -} - -void ENetMultiplayerPeer::set_dtls_certificate(Ref p_cert) { - ERR_FAIL_COND(active); - dtls_cert = p_cert; -} diff --git a/modules/enet/enet_multiplayer_peer.h b/modules/enet/enet_multiplayer_peer.h index db80953414..703396d0cb 100644 --- a/modules/enet/enet_multiplayer_peer.h +++ b/modules/enet/enet_multiplayer_peer.h @@ -32,23 +32,14 @@ #define NETWORKED_MULTIPLAYER_ENET_H #include "core/crypto/crypto.h" -#include "core/io/compression.h" #include "core/io/multiplayer_peer.h" +#include "enet_connection.h" #include class ENetMultiplayerPeer : public MultiplayerPeer { GDCLASS(ENetMultiplayerPeer, MultiplayerPeer); -public: - enum CompressionMode { - COMPRESS_NONE, - COMPRESS_RANGE_CODER, - COMPRESS_FASTLZ, - COMPRESS_ZLIB, - COMPRESS_ZSTD - }; - private: enum { SYSMSG_ADD_PEER, @@ -62,27 +53,27 @@ private: SYSCH_MAX }; - bool active = false; - bool server = false; + enum Mode { + MODE_NONE, + MODE_SERVER, + MODE_CLIENT, + MODE_MESH, + }; + + Mode active_mode = MODE_NONE; uint32_t unique_id = 0; int target_peer = 0; TransferMode transfer_mode = TRANSFER_MODE_RELIABLE; - int transfer_channel = -1; - int channel_count = SYSCH_MAX; - bool always_ordered = false; - - ENetEvent event; - ENetPeer *peer = nullptr; - ENetHost *host = nullptr; bool refuse_connections = false; bool server_relay = true; ConnectionStatus connection_status = CONNECTION_DISCONNECTED; - Map peer_map; + Map> hosts; + Map> peers; struct Packet { ENetPacket *packet = nullptr; @@ -90,30 +81,21 @@ private: int channel = 0; }; - CompressionMode compression_mode = COMPRESS_RANGE_CODER; - List incoming_packets; Packet current_packet; void _pop_current_packet(); - - Vector src_compressor_mem; - Vector dst_compressor_mem; - - ENetCompressor enet_compressor; - static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit); - static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit); - static void enet_compressor_destroy(void *context); - void _setup_compressor(); + bool _poll_server(); + bool _poll_client(); + bool _poll_mesh(); + void _relay(int p_from, int p_to, enet_uint8 p_channel, ENetPacket *p_packet); + void _notify_peers(int p_id, bool p_connected); + void _destroy_unused(ENetPacket *p_packet); + _FORCE_INLINE_ bool _is_active() const { return active_mode != MODE_NONE; } IPAddress bind_ip; - bool dtls_enabled = false; - Ref dtls_key; - Ref dtls_cert; - bool dtls_verify = true; - protected: static void _bind_methods(); @@ -124,13 +106,10 @@ public: virtual int get_packet_peer() const override; - virtual IPAddress get_peer_address(int p_peer_id) const; - virtual int get_peer_port(int p_peer_id) const; - virtual int get_local_port() const; - void set_peer_timeout(int p_peer_id, int p_timeout_limit, int p_timeout_min, int p_timeout_max); - - Error create_server(int p_port, int p_max_clients = 32, int p_in_bandwidth = 0, int p_out_bandwidth = 0); - Error create_client(const String &p_address, int p_port, int p_in_bandwidth = 0, int p_out_bandwidth = 0, int p_local_port = 0); + Error create_server(int p_port, int p_max_clients = 32, int p_max_channels = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0); + Error create_client(const String &p_address, int p_port, int p_channel_count = 0, int p_in_bandwidth = 0, int p_out_bandwidth = 0, int p_local_port = 0); + Error create_mesh(int p_id); + Error add_mesh_peer(int p_id, Ref p_host); void close_connection(uint32_t wait_usec = 100); @@ -153,32 +132,15 @@ public: virtual int get_unique_id() const override; - void set_compression_mode(CompressionMode p_mode); - CompressionMode get_compression_mode() const; - - int get_packet_channel() const; - int get_last_packet_channel() const; - void set_transfer_channel(int p_channel); - int get_transfer_channel() const; - void set_channel_count(int p_channel); - int get_channel_count() const; - void set_always_ordered(bool p_ordered); - bool is_always_ordered() const; + void set_bind_ip(const IPAddress &p_ip); void set_server_relay_enabled(bool p_enabled); bool is_server_relay_enabled() const; + Ref get_host() const; + Ref get_peer(int p_id) const; + ENetMultiplayerPeer(); ~ENetMultiplayerPeer(); - - void set_bind_ip(const IPAddress &p_ip); - void set_dtls_enabled(bool p_enabled); - bool is_dtls_enabled() const; - void set_dtls_verify_enabled(bool p_enabled); - bool is_dtls_verify_enabled() const; - void set_dtls_key(Ref p_key); - void set_dtls_certificate(Ref p_cert); }; -VARIANT_ENUM_CAST(ENetMultiplayerPeer::CompressionMode); - #endif // NETWORKED_MULTIPLAYER_ENET_H -- cgit v1.2.3