From 88d68346ee9b6fa089e21626c50db9dec9a9edd3 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Mon, 12 Jul 2021 16:11:05 +0200 Subject: [Net] Rename NetworkedMultiplayerPeer to MultiplayerPeer. --- core/io/multiplayer_api.cpp | 28 ++--- core/io/multiplayer_api.h | 12 +-- core/io/multiplayer_peer.cpp | 67 ++++++++++++ core/io/multiplayer_peer.h | 82 ++++++++++++++ core/io/networked_multiplayer_peer.cpp | 67 ------------ core/io/networked_multiplayer_peer.h | 82 -------------- core/register_core_types.cpp | 4 +- doc/classes/MultiplayerAPI.xml | 8 +- doc/classes/MultiplayerPeer.xml | 119 +++++++++++++++++++++ doc/classes/NetworkedMultiplayerPeer.xml | 119 --------------------- doc/classes/Node.xml | 6 +- .../enet/doc_classes/NetworkedMultiplayerENet.xml | 6 +- modules/enet/networked_multiplayer_enet.cpp | 4 +- modules/enet/networked_multiplayer_enet.h | 6 +- .../doc_classes/MultiplayerPeerGDNative.xml | 2 +- modules/gdnative/include/net/godot_net.h | 2 +- modules/gdnative/net/multiplayer_peer_gdnative.cpp | 6 +- modules/gdnative/net/multiplayer_peer_gdnative.h | 8 +- modules/gdscript/gdscript.cpp | 2 +- modules/mono/csharp_script.cpp | 2 +- modules/visual_script/visual_script.cpp | 2 +- modules/webrtc/doc_classes/WebRTCMultiplayer.xml | 12 +-- modules/webrtc/webrtc_multiplayer.cpp | 6 +- modules/webrtc/webrtc_multiplayer.h | 8 +- modules/websocket/doc_classes/WebSocketClient.xml | 2 +- .../doc_classes/WebSocketMultiplayerPeer.xml | 4 +- modules/websocket/doc_classes/WebSocketServer.xml | 2 +- modules/websocket/emws_client.cpp | 2 +- modules/websocket/websocket_multiplayer_peer.cpp | 4 +- modules/websocket/websocket_multiplayer_peer.h | 8 +- modules/websocket/websocket_server.cpp | 2 +- modules/websocket/wsl_client.cpp | 2 +- scene/main/node.cpp | 4 +- scene/main/node.h | 2 +- 34 files changed, 346 insertions(+), 346 deletions(-) create mode 100644 core/io/multiplayer_peer.cpp create mode 100644 core/io/multiplayer_peer.h delete mode 100644 core/io/networked_multiplayer_peer.cpp delete mode 100644 core/io/networked_multiplayer_peer.h create mode 100644 doc/classes/MultiplayerPeer.xml delete mode 100644 doc/classes/NetworkedMultiplayerPeer.xml diff --git a/core/io/multiplayer_api.cpp b/core/io/multiplayer_api.cpp index 84f3608e0b..564397c88c 100644 --- a/core/io/multiplayer_api.cpp +++ b/core/io/multiplayer_api.cpp @@ -149,7 +149,7 @@ _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, i } void MultiplayerAPI::poll() { - if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) { + if (!network_peer.is_valid() || network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED) { return; } @@ -196,13 +196,13 @@ Node *MultiplayerAPI::get_root_node() { return root_node; } -void MultiplayerAPI::set_network_peer(const Ref &p_peer) { +void MultiplayerAPI::set_network_peer(const Ref &p_peer) { if (p_peer == network_peer) { return; // Nothing to do } - ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, - "Supplied NetworkedMultiplayerPeer must be connecting or connected."); + ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, + "Supplied MultiplayerPeer must be connecting or connected."); if (network_peer.is_valid()) { network_peer->disconnect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer)); @@ -224,7 +224,7 @@ void MultiplayerAPI::set_network_peer(const Ref &p_pee } } -Ref MultiplayerAPI::get_network_peer() const { +Ref MultiplayerAPI::get_network_peer() const { return network_peer; } @@ -513,7 +513,7 @@ void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, packet.write[1] = valid_rpc_checksum; encode_cstring(pname.get_data(), &packet.write[2]); - network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE); + network_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); network_peer->set_target_peer(p_from); network_peer->put_packet(packet.ptr(), packet.size()); } @@ -592,7 +592,7 @@ bool MultiplayerAPI::_send_confirm_path(Node *p_node, NodePath p_path, PathSentC for (List::Element *E = peers_to_add.front(); E; E = E->next()) { network_peer->set_target_peer(E->get()); // To all of you. - network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE); + network_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE); network_peer->put_packet(packet.ptr(), packet.size()); psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed. @@ -760,9 +760,9 @@ Error MultiplayerAPI::_decode_and_decompress_variant(Variant &r_variant, const u void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, const RPCConfig &p_config, const StringName &p_name, const Variant **p_arg, int p_argcount) { ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree."); - ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree."); + ERR_FAIL_COND_MSG(network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree."); - ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected."); + ERR_FAIL_COND_MSG(network_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected."); ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255."); @@ -974,7 +974,7 @@ void MultiplayerAPI::_server_disconnected() { void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) { ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active."); ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree."); - ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected."); + ERR_FAIL_COND_MSG(network_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected."); int node_id = network_peer->get_unique_id(); bool skip_rpc = node_id == p_peer_id; @@ -1033,10 +1033,10 @@ void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode."); } -Error MultiplayerAPI::send_bytes(Vector p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) { +Error MultiplayerAPI::send_bytes(Vector p_data, int p_to, MultiplayerPeer::TransferMode p_mode) { ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet."); ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active."); - ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected."); + ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected."); MAKE_ROOM(p_data.size() + 1); const uint8_t *r = p_data.ptr(); @@ -1105,7 +1105,7 @@ bool MultiplayerAPI::is_object_decoding_allowed() const { void MultiplayerAPI::_bind_methods() { ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node); ClassDB::bind_method(D_METHOD("get_root_node"), &MultiplayerAPI::get_root_node); - ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE)); + ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE)); ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer); ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer); ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id); @@ -1123,7 +1123,7 @@ void MultiplayerAPI::_bind_methods() { ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections"); - ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", PROPERTY_USAGE_NONE), "set_network_peer", "get_network_peer"); + ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerPeer", PROPERTY_USAGE_NONE), "set_network_peer", "get_network_peer"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root_node", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_root_node", "get_root_node"); ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false); diff --git a/core/io/multiplayer_api.h b/core/io/multiplayer_api.h index 43804a20ec..e9f96383c9 100644 --- a/core/io/multiplayer_api.h +++ b/core/io/multiplayer_api.h @@ -31,7 +31,7 @@ #ifndef MULTIPLAYER_API_H #define MULTIPLAYER_API_H -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "core/object/ref_counted.h" class MultiplayerAPI : public RefCounted { @@ -51,7 +51,7 @@ public: struct RPCConfig { StringName name; RPCMode rpc_mode = RPC_MODE_DISABLED; - NetworkedMultiplayerPeer::TransferMode transfer_mode = NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE; + MultiplayerPeer::TransferMode transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; int channel = 0; bool operator==(RPCConfig const &p_other) const { @@ -83,7 +83,7 @@ private: Map nodes; }; - Ref network_peer; + Ref network_peer; int rpc_sender_id = 0; Set connected_peers; HashMap path_send_cache; @@ -132,9 +132,9 @@ public: void clear(); void set_root_node(Node *p_node); Node *get_root_node(); - void set_network_peer(const Ref &p_peer); - Ref get_network_peer() const; - Error send_bytes(Vector p_data, int p_to = NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST, NetworkedMultiplayerPeer::TransferMode p_mode = NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE); + void set_network_peer(const Ref &p_peer); + Ref get_network_peer() const; + Error send_bytes(Vector p_data, int p_to = MultiplayerPeer::TARGET_PEER_BROADCAST, MultiplayerPeer::TransferMode p_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE); // Called by Node.rpc void rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount); diff --git a/core/io/multiplayer_peer.cpp b/core/io/multiplayer_peer.cpp new file mode 100644 index 0000000000..8126b4cea3 --- /dev/null +++ b/core/io/multiplayer_peer.cpp @@ -0,0 +1,67 @@ +/*************************************************************************/ +/* multiplayer_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 "multiplayer_peer.h" + +void MultiplayerPeer::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &MultiplayerPeer::set_transfer_mode); + ClassDB::bind_method(D_METHOD("get_transfer_mode"), &MultiplayerPeer::get_transfer_mode); + ClassDB::bind_method(D_METHOD("set_target_peer", "id"), &MultiplayerPeer::set_target_peer); + + ClassDB::bind_method(D_METHOD("get_packet_peer"), &MultiplayerPeer::get_packet_peer); + + ClassDB::bind_method(D_METHOD("poll"), &MultiplayerPeer::poll); + + ClassDB::bind_method(D_METHOD("get_connection_status"), &MultiplayerPeer::get_connection_status); + ClassDB::bind_method(D_METHOD("get_unique_id"), &MultiplayerPeer::get_unique_id); + + ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &MultiplayerPeer::set_refuse_new_connections); + ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &MultiplayerPeer::is_refusing_new_connections); + + ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_mode", PROPERTY_HINT_ENUM, "Unreliable,Unreliable Ordered,Reliable"), "set_transfer_mode", "get_transfer_mode"); + + BIND_ENUM_CONSTANT(TRANSFER_MODE_UNRELIABLE); + BIND_ENUM_CONSTANT(TRANSFER_MODE_UNRELIABLE_ORDERED); + BIND_ENUM_CONSTANT(TRANSFER_MODE_RELIABLE); + + BIND_ENUM_CONSTANT(CONNECTION_DISCONNECTED); + BIND_ENUM_CONSTANT(CONNECTION_CONNECTING); + BIND_ENUM_CONSTANT(CONNECTION_CONNECTED); + + BIND_CONSTANT(TARGET_PEER_BROADCAST); + BIND_CONSTANT(TARGET_PEER_SERVER); + + ADD_SIGNAL(MethodInfo("peer_connected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("peer_disconnected", PropertyInfo(Variant::INT, "id"))); + ADD_SIGNAL(MethodInfo("server_disconnected")); + ADD_SIGNAL(MethodInfo("connection_succeeded")); + ADD_SIGNAL(MethodInfo("connection_failed")); +} diff --git a/core/io/multiplayer_peer.h b/core/io/multiplayer_peer.h new file mode 100644 index 0000000000..432f47280f --- /dev/null +++ b/core/io/multiplayer_peer.h @@ -0,0 +1,82 @@ +/*************************************************************************/ +/* multiplayer_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 NETWORKED_MULTIPLAYER_PEER_H +#define NETWORKED_MULTIPLAYER_PEER_H + +#include "core/io/packet_peer.h" + +class MultiplayerPeer : public PacketPeer { + GDCLASS(MultiplayerPeer, PacketPeer); + +protected: + static void _bind_methods(); + +public: + enum { + TARGET_PEER_BROADCAST = 0, + TARGET_PEER_SERVER = 1 + }; + enum TransferMode { + TRANSFER_MODE_UNRELIABLE, + TRANSFER_MODE_UNRELIABLE_ORDERED, + TRANSFER_MODE_RELIABLE, + }; + + enum ConnectionStatus { + CONNECTION_DISCONNECTED, + CONNECTION_CONNECTING, + CONNECTION_CONNECTED, + }; + + virtual void set_transfer_mode(TransferMode p_mode) = 0; + virtual TransferMode get_transfer_mode() const = 0; + virtual void set_target_peer(int p_peer_id) = 0; + + virtual int get_packet_peer() const = 0; + + virtual bool is_server() const = 0; + + virtual void poll() = 0; + + virtual int get_unique_id() const = 0; + + virtual void set_refuse_new_connections(bool p_enable) = 0; + virtual bool is_refusing_new_connections() const = 0; + + virtual ConnectionStatus get_connection_status() const = 0; + + MultiplayerPeer() {} +}; + +VARIANT_ENUM_CAST(MultiplayerPeer::TransferMode) +VARIANT_ENUM_CAST(MultiplayerPeer::ConnectionStatus) + +#endif // NETWORKED_MULTIPLAYER_PEER_H diff --git a/core/io/networked_multiplayer_peer.cpp b/core/io/networked_multiplayer_peer.cpp deleted file mode 100644 index b6af046e77..0000000000 --- a/core/io/networked_multiplayer_peer.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/*************************************************************************/ -/* networked_multiplayer_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 "networked_multiplayer_peer.h" - -void NetworkedMultiplayerPeer::_bind_methods() { - ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &NetworkedMultiplayerPeer::set_transfer_mode); - ClassDB::bind_method(D_METHOD("get_transfer_mode"), &NetworkedMultiplayerPeer::get_transfer_mode); - ClassDB::bind_method(D_METHOD("set_target_peer", "id"), &NetworkedMultiplayerPeer::set_target_peer); - - ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer); - - ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll); - - ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status); - ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id); - - ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections); - ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections); - - ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections"); - ADD_PROPERTY(PropertyInfo(Variant::INT, "transfer_mode", PROPERTY_HINT_ENUM, "Unreliable,Unreliable Ordered,Reliable"), "set_transfer_mode", "get_transfer_mode"); - - BIND_ENUM_CONSTANT(TRANSFER_MODE_UNRELIABLE); - BIND_ENUM_CONSTANT(TRANSFER_MODE_UNRELIABLE_ORDERED); - BIND_ENUM_CONSTANT(TRANSFER_MODE_RELIABLE); - - BIND_ENUM_CONSTANT(CONNECTION_DISCONNECTED); - BIND_ENUM_CONSTANT(CONNECTION_CONNECTING); - BIND_ENUM_CONSTANT(CONNECTION_CONNECTED); - - BIND_CONSTANT(TARGET_PEER_BROADCAST); - BIND_CONSTANT(TARGET_PEER_SERVER); - - ADD_SIGNAL(MethodInfo("peer_connected", PropertyInfo(Variant::INT, "id"))); - ADD_SIGNAL(MethodInfo("peer_disconnected", PropertyInfo(Variant::INT, "id"))); - ADD_SIGNAL(MethodInfo("server_disconnected")); - ADD_SIGNAL(MethodInfo("connection_succeeded")); - ADD_SIGNAL(MethodInfo("connection_failed")); -} diff --git a/core/io/networked_multiplayer_peer.h b/core/io/networked_multiplayer_peer.h deleted file mode 100644 index 7c90f97d88..0000000000 --- a/core/io/networked_multiplayer_peer.h +++ /dev/null @@ -1,82 +0,0 @@ -/*************************************************************************/ -/* networked_multiplayer_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 NETWORKED_MULTIPLAYER_PEER_H -#define NETWORKED_MULTIPLAYER_PEER_H - -#include "core/io/packet_peer.h" - -class NetworkedMultiplayerPeer : public PacketPeer { - GDCLASS(NetworkedMultiplayerPeer, PacketPeer); - -protected: - static void _bind_methods(); - -public: - enum { - TARGET_PEER_BROADCAST = 0, - TARGET_PEER_SERVER = 1 - }; - enum TransferMode { - TRANSFER_MODE_UNRELIABLE, - TRANSFER_MODE_UNRELIABLE_ORDERED, - TRANSFER_MODE_RELIABLE, - }; - - enum ConnectionStatus { - CONNECTION_DISCONNECTED, - CONNECTION_CONNECTING, - CONNECTION_CONNECTED, - }; - - virtual void set_transfer_mode(TransferMode p_mode) = 0; - virtual TransferMode get_transfer_mode() const = 0; - virtual void set_target_peer(int p_peer_id) = 0; - - virtual int get_packet_peer() const = 0; - - virtual bool is_server() const = 0; - - virtual void poll() = 0; - - virtual int get_unique_id() const = 0; - - virtual void set_refuse_new_connections(bool p_enable) = 0; - virtual bool is_refusing_new_connections() const = 0; - - virtual ConnectionStatus get_connection_status() const = 0; - - NetworkedMultiplayerPeer() {} -}; - -VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::TransferMode) -VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::ConnectionStatus) - -#endif // NETWORKED_MULTIPLAYER_PEER_H diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp index 1cbb0bb597..0739a0336d 100644 --- a/core/register_core_types.cpp +++ b/core/register_core_types.cpp @@ -48,7 +48,7 @@ #include "core/io/json.h" #include "core/io/marshalls.h" #include "core/io/multiplayer_api.h" -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "core/io/packed_data_container.h" #include "core/io/packet_peer.h" #include "core/io/packet_peer_dtls.h" @@ -188,7 +188,7 @@ void register_core_types() { resource_format_loader_crypto.instantiate(); ResourceLoader::add_resource_format_loader(resource_format_loader_crypto); - ClassDB::register_virtual_class(); + ClassDB::register_virtual_class(); ClassDB::register_class(); ClassDB::register_class(); ClassDB::register_class(); diff --git a/doc/classes/MultiplayerAPI.xml b/doc/classes/MultiplayerAPI.xml index 5de5703d95..c4d8a5b1b9 100644 --- a/doc/classes/MultiplayerAPI.xml +++ b/doc/classes/MultiplayerAPI.xml @@ -4,7 +4,7 @@ High-level multiplayer API. - This class implements most of the logic behind the high-level multiplayer API. See also [NetworkedMultiplayerPeer]. + This class implements most of the logic behind the high-level multiplayer API. See also [MultiplayerPeer]. By default, [SceneTree] has a reference to this class that is used to provide multiplayer capabilities (i.e. RPC/RSET) across the whole scene. It is possible to override the MultiplayerAPI instance used by specific Nodes by setting the [member Node.custom_multiplayer] property, effectively allowing to run both client and server in the same scene. [b]Note:[/b] The high-level multiplayer API protocol is an implementation detail and isn't meant to be used by non-Godot servers. It may change without notice. @@ -70,10 +70,10 @@ - + - Sends the given raw [code]bytes[/code] to a specific peer identified by [code]id[/code] (see [method NetworkedMultiplayerPeer.set_target_peer]). Default ID is [code]0[/code], i.e. broadcast to all peers. + Sends the given raw [code]bytes[/code] to a specific peer identified by [code]id[/code] (see [method MultiplayerPeer.set_target_peer]). Default ID is [code]0[/code], i.e. broadcast to all peers. @@ -82,7 +82,7 @@ If [code]true[/code], the MultiplayerAPI will allow encoding and decoding of object during RPCs/RSETs. [b]Warning:[/b] Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution. - + The peer object to handle the RPC system (effectively enabling networking when set). Depending on the peer itself, the MultiplayerAPI will become a network server (check with [method is_network_server]) and will set root node's network mode to master, or it will become a regular peer with root node set to puppet. All child nodes are set to inherit the network mode by default. Handling of networking-related events (connection, disconnection, new clients) is done by connecting to MultiplayerAPI's signals. diff --git a/doc/classes/MultiplayerPeer.xml b/doc/classes/MultiplayerPeer.xml new file mode 100644 index 0000000000..713cd64b82 --- /dev/null +++ b/doc/classes/MultiplayerPeer.xml @@ -0,0 +1,119 @@ + + + + A high-level network interface to simplify multiplayer interactions. + + + Manages the connection to network peers. Assigns unique IDs to each client connected to the server. See also [MultiplayerAPI]. + [b]Note:[/b] The high-level multiplayer API protocol is an implementation detail and isn't meant to be used by non-Godot servers. It may change without notice. + + + https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html + https://godotengine.org/asset-library/asset/537 + + + + + + + Returns the current state of the connection. See [enum ConnectionStatus]. + + + + + + + Returns the ID of the [MultiplayerPeer] who sent the most recent packet. + + + + + + + Returns the ID of this [MultiplayerPeer]. + + + + + + + Waits up to 1 second to receive a new network event. + + + + + + + + + Sets the peer to which packets will be sent. + The [code]id[/code] can be one of: [constant TARGET_PEER_BROADCAST] to send to all connected peers, [constant TARGET_PEER_SERVER] to send to the peer acting as server, a valid peer ID to send to that specific peer, a negative peer ID to send to all peers except that one. By default, the target peer is [constant TARGET_PEER_BROADCAST]. + + + + + + If [code]true[/code], this [MultiplayerPeer] refuses new connections. + + + The manner in which to send packets to the [code]target_peer[/code]. See [enum TransferMode]. + + + + + + Emitted when a connection attempt fails. + + + + + Emitted when a connection attempt succeeds. + + + + + + + Emitted by the server when a client connects. + + + + + + + Emitted by the server when a client disconnects. + + + + + Emitted by clients when the server disconnects. + + + + + + Packets are not acknowledged, no resend attempts are made for lost packets. Packets may arrive in any order. Potentially faster than [constant TRANSFER_MODE_UNRELIABLE_ORDERED]. Use for non-critical data, and always consider whether the order matters. + + + Packets are not acknowledged, no resend attempts are made for lost packets. Packets are received in the order they were sent in. Potentially faster than [constant TRANSFER_MODE_RELIABLE]. Use for non-critical data or data that would be outdated if received late due to resend attempt(s) anyway, for example movement and positional data. + + + Packets must be received and resend attempts should be made until the packets are acknowledged. Packets must be received in the order they were sent in. Most reliable transfer mode, but potentially the slowest due to the overhead. Use for critical data that must be transmitted and arrive in order, for example an ability being triggered or a chat message. Consider carefully if the information really is critical, and use sparingly. + + + The ongoing connection disconnected. + + + A connection attempt is ongoing. + + + The connection attempt succeeded. + + + Packets are sent to the server and then redistributed to other peers. + + + Packets are sent to the server alone. + + + diff --git a/doc/classes/NetworkedMultiplayerPeer.xml b/doc/classes/NetworkedMultiplayerPeer.xml deleted file mode 100644 index 06ea46f023..0000000000 --- a/doc/classes/NetworkedMultiplayerPeer.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - A high-level network interface to simplify multiplayer interactions. - - - Manages the connection to network peers. Assigns unique IDs to each client connected to the server. See also [MultiplayerAPI]. - [b]Note:[/b] The high-level multiplayer API protocol is an implementation detail and isn't meant to be used by non-Godot servers. It may change without notice. - - - https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html - https://godotengine.org/asset-library/asset/537 - - - - - - - Returns the current state of the connection. See [enum ConnectionStatus]. - - - - - - - Returns the ID of the [NetworkedMultiplayerPeer] who sent the most recent packet. - - - - - - - Returns the ID of this [NetworkedMultiplayerPeer]. - - - - - - - Waits up to 1 second to receive a new network event. - - - - - - - - - Sets the peer to which packets will be sent. - The [code]id[/code] can be one of: [constant TARGET_PEER_BROADCAST] to send to all connected peers, [constant TARGET_PEER_SERVER] to send to the peer acting as server, a valid peer ID to send to that specific peer, a negative peer ID to send to all peers except that one. By default, the target peer is [constant TARGET_PEER_BROADCAST]. - - - - - - If [code]true[/code], this [NetworkedMultiplayerPeer] refuses new connections. - - - The manner in which to send packets to the [code]target_peer[/code]. See [enum TransferMode]. - - - - - - Emitted when a connection attempt fails. - - - - - Emitted when a connection attempt succeeds. - - - - - - - Emitted by the server when a client connects. - - - - - - - Emitted by the server when a client disconnects. - - - - - Emitted by clients when the server disconnects. - - - - - - Packets are not acknowledged, no resend attempts are made for lost packets. Packets may arrive in any order. Potentially faster than [constant TRANSFER_MODE_UNRELIABLE_ORDERED]. Use for non-critical data, and always consider whether the order matters. - - - Packets are not acknowledged, no resend attempts are made for lost packets. Packets are received in the order they were sent in. Potentially faster than [constant TRANSFER_MODE_RELIABLE]. Use for non-critical data or data that would be outdated if received late due to resend attempt(s) anyway, for example movement and positional data. - - - Packets must be received and resend attempts should be made until the packets are acknowledged. Packets must be received in the order they were sent in. Most reliable transfer mode, but potentially the slowest due to the overhead. Use for critical data that must be transmitted and arrive in order, for example an ability being triggered or a chat message. Consider carefully if the information really is critical, and use sparingly. - - - The ongoing connection disconnected. - - - A connection attempt is ongoing. - - - The connection attempt succeeded. - - - Packets are sent to the server and then redistributed to other peers. - - - Packets are sent to the server alone. - - - diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml index 15784eaab9..c3c85ce787 100644 --- a/doc/classes/Node.xml +++ b/doc/classes/Node.xml @@ -670,12 +670,12 @@ - + - Changes the RPC mode for the given [code]method[/code] to the given [code]rpc_mode[/code], optionally specifying the [code]transfer_mode[/code] and [code]channel[/code] (on supported peers). See [enum MultiplayerAPI.RPCMode] and [enum NetworkedMultiplayerPeer.TransferMode]. An alternative is annotating methods and properties with the corresponding keywords ([code]remote[/code], [code]master[/code], [code]puppet[/code], [code]remotesync[/code], [code]mastersync[/code], [code]puppetsync[/code]). By default, methods are not exposed to networking (and RPCs). + Changes the RPC mode for the given [code]method[/code] to the given [code]rpc_mode[/code], optionally specifying the [code]transfer_mode[/code] and [code]channel[/code] (on supported peers). See [enum MultiplayerAPI.RPCMode] and [enum MultiplayerPeer.TransferMode]. An alternative is annotating methods and properties with the corresponding keywords ([code]remote[/code], [code]master[/code], [code]puppet[/code], [code]remotesync[/code], [code]mastersync[/code], [code]puppetsync[/code]). By default, methods are not exposed to networking (and RPCs). @@ -686,7 +686,7 @@ - Sends a [method rpc] to a specific peer identified by [code]peer_id[/code] (see [method NetworkedMultiplayerPeer.set_target_peer]). Returns an empty [Variant]. + Sends a [method rpc] to a specific peer identified by [code]peer_id[/code] (see [method MultiplayerPeer.set_target_peer]). Returns an empty [Variant]. diff --git a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml index 92c735a4c2..9162823a38 100644 --- a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml +++ b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml @@ -1,5 +1,5 @@ - + PacketPeer implementation using the [url=http://enet.bespin.org/index.html]ENet[/url] library. @@ -150,7 +150,7 @@ - Enforce ordered packets when using [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE] (thus behaving similarly to [constant NetworkedMultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED]). This is the only way to use ordering with the RPC system. + 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. @@ -168,7 +168,7 @@ 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]. diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp index 94260e8c13..07fc59b885 100644 --- a/modules/enet/networked_multiplayer_enet.cpp +++ b/modules/enet/networked_multiplayer_enet.cpp @@ -37,7 +37,7 @@ void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) { transfer_mode = p_mode; } -NetworkedMultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const { +MultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const { return transfer_mode; } @@ -604,7 +604,7 @@ void NetworkedMultiplayerENet::_pop_current_packet() { } } -NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const { +MultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const { return connection_status; } diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/networked_multiplayer_enet.h index 2d928859fa..6fb7123b43 100644 --- a/modules/enet/networked_multiplayer_enet.h +++ b/modules/enet/networked_multiplayer_enet.h @@ -33,12 +33,12 @@ #include "core/crypto/crypto.h" #include "core/io/compression.h" -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include -class NetworkedMultiplayerENet : public NetworkedMultiplayerPeer { - GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer); +class NetworkedMultiplayerENet : public MultiplayerPeer { + GDCLASS(NetworkedMultiplayerENet, MultiplayerPeer); public: enum CompressionMode { diff --git a/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml b/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml index 9f33d32e81..b88f5e7e1e 100644 --- a/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml +++ b/modules/gdnative/doc_classes/MultiplayerPeerGDNative.xml @@ -1,5 +1,5 @@ - + diff --git a/modules/gdnative/include/net/godot_net.h b/modules/gdnative/include/net/godot_net.h index 2fa576a5bf..94e7739ef9 100644 --- a/modules/gdnative/include/net/godot_net.h +++ b/modules/gdnative/include/net/godot_net.h @@ -90,7 +90,7 @@ typedef struct { godot_int (*get_available_packet_count)(const void *); godot_int (*get_max_packet_size)(const void *); - /* This is NetworkedMultiplayerPeer */ + /* This is MultiplayerPeer */ void (*set_transfer_mode)(void *, godot_int); godot_int (*get_transfer_mode)(const void *); // 0 = broadcast, 1 = server, <0 = all but abs(value) diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.cpp b/modules/gdnative/net/multiplayer_peer_gdnative.cpp index 8b5fc8db5c..8ceba0f339 100644 --- a/modules/gdnative/net/multiplayer_peer_gdnative.cpp +++ b/modules/gdnative/net/multiplayer_peer_gdnative.cpp @@ -61,13 +61,13 @@ int MultiplayerPeerGDNative::get_available_packet_count() const { return interface->get_available_packet_count(interface->data); } -/* NetworkedMultiplayerPeer */ +/* MultiplayerPeer */ void MultiplayerPeerGDNative::set_transfer_mode(TransferMode p_mode) { ERR_FAIL_COND(interface == nullptr); interface->set_transfer_mode(interface->data, (godot_int)p_mode); } -NetworkedMultiplayerPeer::TransferMode MultiplayerPeerGDNative::get_transfer_mode() const { +MultiplayerPeer::TransferMode MultiplayerPeerGDNative::get_transfer_mode() const { ERR_FAIL_COND_V(interface == nullptr, TRANSFER_MODE_UNRELIABLE); return (TransferMode)interface->get_transfer_mode(interface->data); } @@ -107,7 +107,7 @@ bool MultiplayerPeerGDNative::is_refusing_new_connections() const { return interface->is_refusing_new_connections(interface->data); } -NetworkedMultiplayerPeer::ConnectionStatus MultiplayerPeerGDNative::get_connection_status() const { +MultiplayerPeer::ConnectionStatus MultiplayerPeerGDNative::get_connection_status() const { ERR_FAIL_COND_V(interface == nullptr, CONNECTION_DISCONNECTED); return (ConnectionStatus)interface->get_connection_status(interface->data); } diff --git a/modules/gdnative/net/multiplayer_peer_gdnative.h b/modules/gdnative/net/multiplayer_peer_gdnative.h index 593b2534dd..7c10ab77f7 100644 --- a/modules/gdnative/net/multiplayer_peer_gdnative.h +++ b/modules/gdnative/net/multiplayer_peer_gdnative.h @@ -31,12 +31,12 @@ #ifndef MULTIPLAYER_PEER_GDNATIVE_H #define MULTIPLAYER_PEER_GDNATIVE_H -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "modules/gdnative/gdnative.h" #include "modules/gdnative/include/net/godot_net.h" -class MultiplayerPeerGDNative : public NetworkedMultiplayerPeer { - GDCLASS(MultiplayerPeerGDNative, NetworkedMultiplayerPeer); +class MultiplayerPeerGDNative : public MultiplayerPeer { + GDCLASS(MultiplayerPeerGDNative, MultiplayerPeer); protected: static void _bind_methods(); @@ -55,7 +55,7 @@ public: virtual int get_max_packet_size() const override; virtual int get_available_packet_count() const override; - /* Specific to NetworkedMultiplayerPeer */ + /* Specific to MultiplayerPeer */ virtual void set_transfer_mode(TransferMode p_mode) override; virtual TransferMode get_transfer_mode() const override; virtual void set_target_peer(int p_peer_id) override; diff --git a/modules/gdscript/gdscript.cpp b/modules/gdscript/gdscript.cpp index 397776ba1a..8b12b1eae4 100644 --- a/modules/gdscript/gdscript.cpp +++ b/modules/gdscript/gdscript.cpp @@ -1170,7 +1170,7 @@ void GDScript::_init_rpc_methods_properties() { nd.name = E->key(); nd.rpc_mode = E->get()->get_rpc_mode(); // TODO - nd.transfer_mode = NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE; + nd.transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; nd.channel = 0; if (-1 == rpc_functions.find(nd)) { rpc_functions.push_back(nd); diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index be46e76d9c..ff6a47f59b 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -3038,7 +3038,7 @@ void CSharpScript::update_script_class_info(Ref p_script) { nd.name = methods[i]->get_name(); nd.rpc_mode = mode; // TODO Transfer mode, channel - nd.transfer_mode = NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE; + nd.transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; nd.channel = 0; if (-1 == p_script->rpc_functions.find(nd)) { p_script->rpc_functions.push_back(nd); diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index d49060bea8..c4b3f9ba44 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -1025,7 +1025,7 @@ void VisualScript::_set_data(const Dictionary &p_data) { MultiplayerAPI::RPCConfig nd; nd.name = E->get(); nd.rpc_mode = vsf->get_rpc_mode(); - nd.transfer_mode = NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE; // TODO + nd.transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE; // TODO if (rpc_functions.find(nd) == -1) { rpc_functions.push_back(nd); } diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml index 5b9459bc27..99c7236bfc 100644 --- a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml +++ b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml @@ -1,12 +1,12 @@ - + A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer]. You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections. - [signal NetworkedMultiplayerPeer.connection_succeeded] and [signal NetworkedMultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [NetworkedMultiplayerPeer]. + [signal MultiplayerPeer.connection_succeeded] and [signal MultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [MultiplayerPeer]. @@ -66,8 +66,8 @@ Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647). - If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED] and [signal NetworkedMultiplayerPeer.connection_succeeded] will not be emitted. - If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal NetworkedMultiplayerPeer.peer_connected] signals until a peer with id [constant NetworkedMultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal NetworkedMultiplayerPeer.connection_succeeded]. After that the signal [signal NetworkedMultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal NetworkedMultiplayerPeer.server_disconnected] will be emitted and state will become [constant NetworkedMultiplayerPeer.CONNECTION_CONNECTED]. + If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant MultiplayerPeer.CONNECTION_CONNECTED] and [signal MultiplayerPeer.connection_succeeded] will not be emitted. + If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal MultiplayerPeer.peer_connected] signals until a peer with id [constant MultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal MultiplayerPeer.connection_succeeded]. After that the signal [signal MultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal MultiplayerPeer.server_disconnected] will be emitted and state will become [constant MultiplayerPeer.CONNECTION_CONNECTED]. @@ -76,13 +76,13 @@ - Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal NetworkedMultiplayerPeer.peer_connected] was emitted for it, then [signal NetworkedMultiplayerPeer.peer_disconnected] will be emitted. + Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal MultiplayerPeer.peer_connected] was emitted for it, then [signal MultiplayerPeer.peer_disconnected] will be emitted. - + diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp index 741cad5640..019ac890b8 100644 --- a/modules/webrtc/webrtc_multiplayer.cpp +++ b/modules/webrtc/webrtc_multiplayer.cpp @@ -47,7 +47,7 @@ void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) { transfer_mode = p_mode; } -NetworkedMultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const { +MultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const { return transfer_mode; } @@ -55,7 +55,7 @@ void WebRTCMultiplayer::set_target_peer(int p_peer_id) { target_peer = p_peer_id; } -/* Returns the ID of the NetworkedMultiplayerPeer who sent the most recent packet: */ +/* Returns the ID of the MultiplayerPeer who sent the most recent packet: */ int WebRTCMultiplayer::get_packet_peer() const { return next_packet_peer; } @@ -188,7 +188,7 @@ bool WebRTCMultiplayer::is_refusing_new_connections() const { return refuse_connections; } -NetworkedMultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const { +MultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const { return connection_status; } diff --git a/modules/webrtc/webrtc_multiplayer.h b/modules/webrtc/webrtc_multiplayer.h index 2ddb98f656..5e8b6be24e 100644 --- a/modules/webrtc/webrtc_multiplayer.h +++ b/modules/webrtc/webrtc_multiplayer.h @@ -31,11 +31,11 @@ #ifndef WEBRTC_MULTIPLAYER_H #define WEBRTC_MULTIPLAYER_H -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "webrtc_peer_connection.h" -class WebRTCMultiplayer : public NetworkedMultiplayerPeer { - GDCLASS(WebRTCMultiplayer, NetworkedMultiplayerPeer); +class WebRTCMultiplayer : public MultiplayerPeer { + GDCLASS(WebRTCMultiplayer, MultiplayerPeer); protected: static void _bind_methods(); @@ -94,7 +94,7 @@ public: int get_available_packet_count() const override; int get_max_packet_size() const override; - // NetworkedMultiplayerPeer + // MultiplayerPeer void set_transfer_mode(TransferMode p_mode) override; TransferMode get_transfer_mode() const override; void set_target_peer(int p_peer_id) override; diff --git a/modules/websocket/doc_classes/WebSocketClient.xml b/modules/websocket/doc_classes/WebSocketClient.xml index 6af610c689..40c0ad17ad 100644 --- a/modules/websocket/doc_classes/WebSocketClient.xml +++ b/modules/websocket/doc_classes/WebSocketClient.xml @@ -6,7 +6,7 @@ This class implements a WebSocket client compatible with any RFC 6455-compliant WebSocket server. This client can be optionally used as a network peer for the [MultiplayerAPI]. - After starting the client ([method connect_to_url]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). + After starting the client ([method connect_to_url]), you will need to [method MultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). You will receive appropriate signals when connecting, disconnecting, or when new data is available. diff --git a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml index 0679acf78a..ee1b60f739 100644 --- a/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml +++ b/modules/websocket/doc_classes/WebSocketMultiplayerPeer.xml @@ -1,5 +1,5 @@ - + Base class for WebSocket server and client. @@ -39,7 +39,7 @@ - + diff --git a/modules/websocket/doc_classes/WebSocketServer.xml b/modules/websocket/doc_classes/WebSocketServer.xml index 7bc0d64718..26e09fd8b3 100644 --- a/modules/websocket/doc_classes/WebSocketServer.xml +++ b/modules/websocket/doc_classes/WebSocketServer.xml @@ -5,7 +5,7 @@ This class implements a WebSocket server that can also support the high-level multiplayer API. - After starting the server ([method listen]), you will need to [method NetworkedMultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal. + After starting the server ([method listen]), you will need to [method MultiplayerPeer.poll] it at regular intervals (e.g. inside [method Node._process]). When clients connect, disconnect, or send data, you will receive the appropriate signal. [b]Note:[/b] Not available in HTML5 exports. diff --git a/modules/websocket/emws_client.cpp b/modules/websocket/emws_client.cpp index 626498e1ae..744053b6e2 100644 --- a/modules/websocket/emws_client.cpp +++ b/modules/websocket/emws_client.cpp @@ -107,7 +107,7 @@ Ref EMWSClient::get_peer(int p_peer_id) const { return _peer; } -NetworkedMultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const { +MultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const { if (_peer->is_connected_to_host()) { if (_is_connecting) return CONNECTION_CONNECTING; diff --git a/modules/websocket/websocket_multiplayer_peer.cpp b/modules/websocket/websocket_multiplayer_peer.cpp index fa0ef7060f..1beeb67b91 100644 --- a/modules/websocket/websocket_multiplayer_peer.cpp +++ b/modules/websocket/websocket_multiplayer_peer.cpp @@ -123,13 +123,13 @@ Error WebSocketMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer } // -// NetworkedMultiplayerPeer +// MultiplayerPeer // void WebSocketMultiplayerPeer::set_transfer_mode(TransferMode p_mode) { // Websocket uses TCP, reliable } -NetworkedMultiplayerPeer::TransferMode WebSocketMultiplayerPeer::get_transfer_mode() const { +MultiplayerPeer::TransferMode WebSocketMultiplayerPeer::get_transfer_mode() const { // Websocket uses TCP, reliable return TRANSFER_MODE_RELIABLE; } diff --git a/modules/websocket/websocket_multiplayer_peer.h b/modules/websocket/websocket_multiplayer_peer.h index 48a6607d89..e3ccd1a795 100644 --- a/modules/websocket/websocket_multiplayer_peer.h +++ b/modules/websocket/websocket_multiplayer_peer.h @@ -32,12 +32,12 @@ #define WEBSOCKET_MULTIPLAYER_PEER_H #include "core/error/error_list.h" -#include "core/io/networked_multiplayer_peer.h" +#include "core/io/multiplayer_peer.h" #include "core/templates/list.h" #include "websocket_peer.h" -class WebSocketMultiplayerPeer : public NetworkedMultiplayerPeer { - GDCLASS(WebSocketMultiplayerPeer, NetworkedMultiplayerPeer); +class WebSocketMultiplayerPeer : public MultiplayerPeer { + GDCLASS(WebSocketMultiplayerPeer, MultiplayerPeer); private: Vector _make_pkt(uint8_t p_type, int32_t p_from, int32_t p_to, const uint8_t *p_data, uint32_t p_data_size); @@ -78,7 +78,7 @@ protected: int _gen_unique_id() const; public: - /* NetworkedMultiplayerPeer */ + /* MultiplayerPeer */ void set_transfer_mode(TransferMode p_mode) override; TransferMode get_transfer_mode() const override; void set_target_peer(int p_target_peer) override; diff --git a/modules/websocket/websocket_server.cpp b/modules/websocket/websocket_server.cpp index 9b2d04f14f..b996852f28 100644 --- a/modules/websocket/websocket_server.cpp +++ b/modules/websocket/websocket_server.cpp @@ -121,7 +121,7 @@ void WebSocketServer::set_handshake_timeout(float p_timeout) { handshake_timeout = p_timeout * 1000; } -NetworkedMultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const { +MultiplayerPeer::ConnectionStatus WebSocketServer::get_connection_status() const { if (is_listening()) { return CONNECTION_CONNECTED; } diff --git a/modules/websocket/wsl_client.cpp b/modules/websocket/wsl_client.cpp index 74017fedd7..49997b42d3 100644 --- a/modules/websocket/wsl_client.cpp +++ b/modules/websocket/wsl_client.cpp @@ -288,7 +288,7 @@ Ref WSLClient::get_peer(int p_peer_id) const { return _peer; } -NetworkedMultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const { +MultiplayerPeer::ConnectionStatus WSLClient::get_connection_status() const { if (_peer->is_connected_to_host()) { return CONNECTION_CONNECTED; } diff --git a/scene/main/node.cpp b/scene/main/node.cpp index ef6d2e72f6..787b283e8c 100644 --- a/scene/main/node.cpp +++ b/scene/main/node.cpp @@ -507,7 +507,7 @@ bool Node::is_network_master() const { /***** RPC CONFIG ********/ -uint16_t Node::rpc_config(const StringName &p_method, MultiplayerAPI::RPCMode p_rpc_mode, NetworkedMultiplayerPeer::TransferMode p_transfer_mode, int p_channel) { +uint16_t Node::rpc_config(const StringName &p_method, MultiplayerAPI::RPCMode p_rpc_mode, MultiplayerPeer::TransferMode p_transfer_mode, int p_channel) { for (int i = 0; i < data.rpc_methods.size(); i++) { if (data.rpc_methods[i].name == p_method) { MultiplayerAPI::RPCConfig &nd = data.rpc_methods.write[i]; @@ -2623,7 +2623,7 @@ void Node::_bind_methods() { ClassDB::bind_method(D_METHOD("get_multiplayer"), &Node::get_multiplayer); ClassDB::bind_method(D_METHOD("get_custom_multiplayer"), &Node::get_custom_multiplayer); ClassDB::bind_method(D_METHOD("set_custom_multiplayer", "api"), &Node::set_custom_multiplayer); - ClassDB::bind_method(D_METHOD("rpc_config", "method", "rpc_mode", "transfer_mode", "channel"), &Node::rpc_config, DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0)); + ClassDB::bind_method(D_METHOD("rpc_config", "method", "rpc_mode", "transfer_mode", "channel"), &Node::rpc_config, DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0)); ClassDB::bind_method(D_METHOD("set_editor_description", "editor_description"), &Node::set_editor_description); ClassDB::bind_method(D_METHOD("get_editor_description"), &Node::get_editor_description); diff --git a/scene/main/node.h b/scene/main/node.h index fc5af43829..c6727ce884 100644 --- a/scene/main/node.h +++ b/scene/main/node.h @@ -430,7 +430,7 @@ public: int get_network_master() const; bool is_network_master() const; - uint16_t rpc_config(const StringName &p_method, MultiplayerAPI::RPCMode p_rpc_mode, NetworkedMultiplayerPeer::TransferMode p_transfer_mode, int p_channel = 0); // config a local method for RPC + uint16_t rpc_config(const StringName &p_method, MultiplayerAPI::RPCMode p_rpc_mode, MultiplayerPeer::TransferMode p_transfer_mode, int p_channel = 0); // config a local method for RPC Vector get_node_rpc_methods() const; void rpc(const StringName &p_method, VARIANT_ARG_LIST); // RPC, honors RPCMode, TransferMode, channel -- cgit v1.2.3 From b31e8530b25b0ec3315df4e6354ab0186bf9f3b0 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Mon, 12 Jul 2021 16:18:43 +0200 Subject: [Net] Rename NetworkedMultiplayerENet to ENetMultiplayerPeer. --- doc/classes/Node.xml | 2 +- modules/enet/config.py | 2 +- modules/enet/doc_classes/ENetMultiplayerPeer.xml | 194 +++++ .../enet/doc_classes/NetworkedMultiplayerENet.xml | 194 ----- modules/enet/enet_multiplayer_peer.cpp | 926 +++++++++++++++++++++ modules/enet/enet_multiplayer_peer.h | 185 ++++ modules/enet/networked_multiplayer_enet.cpp | 926 --------------------- modules/enet/networked_multiplayer_enet.h | 185 ---- modules/enet/register_types.cpp | 4 +- 9 files changed, 1309 insertions(+), 1309 deletions(-) create mode 100644 modules/enet/doc_classes/ENetMultiplayerPeer.xml delete mode 100644 modules/enet/doc_classes/NetworkedMultiplayerENet.xml create mode 100644 modules/enet/enet_multiplayer_peer.cpp create mode 100644 modules/enet/enet_multiplayer_peer.h delete mode 100644 modules/enet/networked_multiplayer_enet.cpp delete mode 100644 modules/enet/networked_multiplayer_enet.h diff --git a/doc/classes/Node.xml b/doc/classes/Node.xml index c3c85ce787..fc971effd7 100644 --- a/doc/classes/Node.xml +++ b/doc/classes/Node.xml @@ -14,7 +14,7 @@ To keep track of the scene hierarchy (especially when instancing scenes into other scenes), an "owner" can be set for the node with the [member owner] property. This keeps track of who instantiated what. This is mostly useful when writing editors and tools, though. Finally, when a node is freed with [method Object.free] or [method queue_free], it will also free all its children. [b]Groups:[/b] Nodes can be added to as many groups as you want to be easy to manage, you could create groups like "enemies" or "collectables" for example, depending on your game. See [method add_to_group], [method is_in_group] and [method remove_from_group]. You can then retrieve all nodes in these groups, iterate them and even call methods on groups via the methods on [SceneTree]. - [b]Networking with nodes:[/b] After connecting to a server (or making one, see [NetworkedMultiplayerENet]), it is possible to use the built-in RPC (remote procedure call) system to communicate over the network. By calling [method rpc] with a method name, it will be called locally and in all connected peers (peers = clients and the server that accepts connections). To identify which node receives the RPC call, Godot will use its [NodePath] (make sure node names are the same on all peers). Also, take a look at the high-level networking tutorial and corresponding demos. + [b]Networking with nodes:[/b] After connecting to a server (or making one, see [ENetMultiplayerPeer]), it is possible to use the built-in RPC (remote procedure call) system to communicate over the network. By calling [method rpc] with a method name, it will be called locally and in all connected peers (peers = clients and the server that accepts connections). To identify which node receives the RPC call, Godot will use its [NodePath] (make sure node names are the same on all peers). Also, take a look at the high-level networking tutorial and corresponding demos. https://docs.godotengine.org/en/latest/getting_started/step_by_step/scenes_and_nodes.html diff --git a/modules/enet/config.py b/modules/enet/config.py index 5fd343c75d..3662b2d94e 100644 --- a/modules/enet/config.py +++ b/modules/enet/config.py @@ -8,7 +8,7 @@ def configure(env): def get_doc_classes(): return [ - "NetworkedMultiplayerENet", + "ENetMultiplayerPeer", ] diff --git a/modules/enet/doc_classes/ENetMultiplayerPeer.xml b/modules/enet/doc_classes/ENetMultiplayerPeer.xml new file mode 100644 index 0000000000..5b2c72dce4 --- /dev/null +++ b/modules/enet/doc_classes/ENetMultiplayerPeer.xml @@ -0,0 +1,194 @@ + + + + PacketPeer 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). + [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. + + + https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html + http://enet.bespin.org/usergroup0.html + + + + + + + + + Closes the connection. Ignored if no connection is currently established. If this is a server it tries to notify all clients before forcibly disconnecting them. If this is a client it simply closes the connection to the server. + + + + + + + + + + + + + + + + + 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 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. + + + + + + + + + + + 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. + + + + + + + + + Returns the remote port of the given peer. + + + + + + + + + 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. + + + Enable or disable certificate verification when [member use_dtls] [code]true[/code]. + + + + 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. + + + ENet's built-in range encoding. + + + [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. + + + diff --git a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml b/modules/enet/doc_classes/NetworkedMultiplayerENet.xml deleted file mode 100644 index 9162823a38..0000000000 --- a/modules/enet/doc_classes/NetworkedMultiplayerENet.xml +++ /dev/null @@ -1,194 +0,0 @@ - - - - PacketPeer 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). - [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. - - - https://docs.godotengine.org/en/latest/tutorials/networking/high_level_multiplayer.html - http://enet.bespin.org/usergroup0.html - - - - - - - - - Closes the connection. Ignored if no connection is currently established. If this is a server it tries to notify all clients before forcibly disconnecting them. If this is a client it simply closes the connection to the server. - - - - - - - - - - - - - - - - - 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 NetworkedMultiplayerENet 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 NetworkedMultiplayerENet 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. - - - - - - - - - - - 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. - - - - - - - - - Returns the remote port of the given peer. - - - - - - - - - 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. - - - Enable or disable certificate verification when [member use_dtls] [code]true[/code]. - - - - 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. - - - ENet's built-in range encoding. - - - [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. - - - diff --git a/modules/enet/enet_multiplayer_peer.cpp b/modules/enet/enet_multiplayer_peer.cpp new file mode 100644 index 0000000000..a9726426ad --- /dev/null +++ b/modules/enet/enet_multiplayer_peer.cpp @@ -0,0 +1,926 @@ +/*************************************************************************/ +/* enet_multiplayer_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_multiplayer_peer.h" +#include "core/io/ip.h" +#include "core/io/marshalls.h" +#include "core/os/os.h" + +void ENetMultiplayerPeer::set_transfer_mode(TransferMode p_mode) { + transfer_mode = p_mode; +} + +MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_transfer_mode() const { + return transfer_mode; +} + +void ENetMultiplayerPeer::set_target_peer(int p_peer) { + target_peer = 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(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()); + } + enet_host_refuse_new_connections(host, refuse_connections); +#endif + + _setup_compressor(); + active = true; + server = true; + refuse_connections = false; + unique_id = 1; + connection_status = CONNECTION_CONNECTED; + 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; + } else { + enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16); + } +#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(); + } +#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 = _gen_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."); + } + + // Technically safe to ignore the peer or anything else. + + connection_status = CONNECTION_CONNECTING; + active = true; + server = false; + refuse_connections = false; + + return OK; +} + +void ENetMultiplayerPeer::poll() { + ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); + + _pop_current_packet(); + + 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; + } + + int ret = enet_host_service(host, &event, 0); + + if (ret < 0) { + // Error, do something? + break; + } else if (ret == 0) { + break; + } + + switch (event.type) { + case ENET_EVENT_TYPE_CONNECT: { + // Store any relevant client information here. + + if (server && refuse_connections) { + enet_peer_reset(event.peer); + break; + } + + // 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); + } + + int *new_id = memnew(int); + *new_id = event.data; + + if (*new_id == 0) { // Data zero is sent by server (ENet won't let you configure this). Server is always 1. + *new_id = 1; + } + + 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("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("connection_succeeded"); + } + + } break; + case ENET_EVENT_TYPE_DISCONNECT: { + // Reset the peer's client information. + + int *id = (int *)event.peer->data; + + if (!id) { + if (!server) { + emit_signal("connection_failed"); + } + // Never fully connected. + break; + } + + if (!server) { + // Client just disconnected from server. + emit_signal("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); + } + } + + emit_signal("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("peer_connected", id); + + } break; + case SYSMSG_REMOVE_PEER: { + peer_map.erase(id); + emit_signal("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); + } + + } break; + case ENET_EVENT_TYPE_NONE: { + // Do nothing + } break; + } + } +} + +bool ENetMultiplayerPeer::is_server() const { + ERR_FAIL_COND_V_MSG(!active, false, "The multiplayer instance isn't currently active."); + + return server; +} + +void ENetMultiplayerPeer::close_connection(uint32_t wait_usec) { + ERR_FAIL_COND_MSG(!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); + peers_disconnected = true; + } + } + + if (peers_disconnected) { + enet_host_flush(host); + + if (wait_usec > 0) { + OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send + } + } + + enet_host_destroy(host); + active = false; + incoming_packets.clear(); + peer_map.clear(); + unique_id = 1; // Server is 1 + 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("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(); +} + +Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available."); + + _pop_current_packet(); + + current_packet = incoming_packets.front()->get(); + incoming_packets.pop_front(); + + *r_buffer = (const uint8_t *)(¤t_packet.packet->data[8]); + r_buffer_size = current_packet.packet->dataLength - 8; + + return OK; +} + +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(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client."); + + 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; + } + channel = SYSCH_UNRELIABLE; + } break; + case TRANSFER_MODE_UNRELIABLE_ORDERED: { + packet_flags = 0; + channel = SYSCH_UNRELIABLE; + } break; + case TRANSFER_MODE_RELIABLE: { + packet_flags = ENET_PACKET_FLAG_RELIABLE; + channel = SYSCH_RELIABLE; + } 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 (target_peer == 0) { + enet_host_broadcast(host, 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 + continue; + } + + ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags); + + enet_peer_send(F->get(), channel, packet2); + } + + enet_packet_destroy(packet); // Original packet no longer needed + } else { + enet_peer_send(E->get(), channel, packet); + } + } 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; +} + +int ENetMultiplayerPeer::get_max_packet_size() const { + return 1 << 24; // Anything is good +} + +void ENetMultiplayerPeer::_pop_current_packet() { + if (current_packet.packet) { + enet_packet_destroy(current_packet.packet); + current_packet.packet = nullptr; + current_packet.from = 0; + current_packet.channel = -1; + } +} + +MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const { + 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; +} + +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); + } +#endif +} + +bool ENetMultiplayerPeer::is_refusing_new_connections() const { + return refuse_connections; +} + +void ENetMultiplayerPeer::set_compression_mode(CompressionMode p_mode) { + compression_mode = p_mode; +} + +ENetMultiplayerPeer::CompressionMode ENetMultiplayerPeer::get_compression_mode() const { + return compression_mode; +} + +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); + + if (size_t(enet->src_compressor_mem.size()) < inLimit) { + enet->src_compressor_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(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy); + ofs += to_copy; + total -= to_copy; + } + } + + Compression::Mode mode; + + 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)); + } + } + + 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; +} + +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: { + } + } + if (ret < 0) { + return 0; + } else { + return ret; + } +} + +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::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("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); + + 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); +} + +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) { + close_connection(); + } +} + +// Sets IP for ENet to bind when using create_server or create_client +// if no IP is set, then ENet bind to ENET_HOST_ANY +void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) { + ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(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 new file mode 100644 index 0000000000..e6d45eb16a --- /dev/null +++ b/modules/enet/enet_multiplayer_peer.h @@ -0,0 +1,185 @@ +/*************************************************************************/ +/* enet_multiplayer_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 NETWORKED_MULTIPLAYER_ENET_H +#define NETWORKED_MULTIPLAYER_ENET_H + +#include "core/crypto/crypto.h" +#include "core/io/compression.h" +#include "core/io/multiplayer_peer.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, + SYSMSG_REMOVE_PEER + }; + + enum { + SYSCH_CONFIG, + SYSCH_RELIABLE, + SYSCH_UNRELIABLE, + SYSCH_MAX + }; + + bool active = false; + bool server = false; + + 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; + + struct Packet { + ENetPacket *packet = nullptr; + int from = 0; + int channel = 0; + }; + + CompressionMode compression_mode = COMPRESS_NONE; + + List incoming_packets; + + Packet current_packet; + + uint32_t _gen_unique_id() const; + 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(); + + IPAddress bind_ip; + + bool dtls_enabled = false; + Ref dtls_key; + Ref dtls_cert; + bool dtls_verify = true; + +protected: + static void _bind_methods(); + +public: + virtual void set_transfer_mode(TransferMode p_mode) override; + virtual TransferMode get_transfer_mode() const override; + virtual void set_target_peer(int p_peer) override; + + 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); + + void close_connection(uint32_t wait_usec = 100); + + void disconnect_peer(int p_peer, bool now = false); + + virtual void poll() override; + + virtual bool is_server() const override; + + virtual int get_available_packet_count() const override; + virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet + virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; + + virtual int get_max_packet_size() const override; + + virtual ConnectionStatus get_connection_status() const override; + + virtual void set_refuse_new_connections(bool p_enable) override; + virtual bool is_refusing_new_connections() const override; + + 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_server_relay_enabled(bool p_enabled); + bool is_server_relay_enabled() 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 diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp deleted file mode 100644 index 07fc59b885..0000000000 --- a/modules/enet/networked_multiplayer_enet.cpp +++ /dev/null @@ -1,926 +0,0 @@ -/*************************************************************************/ -/* networked_multiplayer_enet.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 "networked_multiplayer_enet.h" -#include "core/io/ip.h" -#include "core/io/marshalls.h" -#include "core/os/os.h" - -void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) { - transfer_mode = p_mode; -} - -MultiplayerPeer::TransferMode NetworkedMultiplayerENet::get_transfer_mode() const { - return transfer_mode; -} - -void NetworkedMultiplayerENet::set_target_peer(int p_peer) { - target_peer = p_peer; -} - -int NetworkedMultiplayerENet::get_packet_peer() 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().from; -} - -int NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::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()); - } - enet_host_refuse_new_connections(host, refuse_connections); -#endif - - _setup_compressor(); - active = true; - server = true; - refuse_connections = false; - unique_id = 1; - connection_status = CONNECTION_CONNECTED; - return OK; -} -Error NetworkedMultiplayerENet::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; - } else { - enet_address_set_ip(&c_client, bind_ip.get_ipv6(), 16); - } -#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(); - } -#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 = _gen_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."); - } - - // Technically safe to ignore the peer or anything else. - - connection_status = CONNECTION_CONNECTING; - active = true; - server = false; - refuse_connections = false; - - return OK; -} - -void NetworkedMultiplayerENet::poll() { - ERR_FAIL_COND_MSG(!active, "The multiplayer instance isn't currently active."); - - _pop_current_packet(); - - 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; - } - - int ret = enet_host_service(host, &event, 0); - - if (ret < 0) { - // Error, do something? - break; - } else if (ret == 0) { - break; - } - - switch (event.type) { - case ENET_EVENT_TYPE_CONNECT: { - // Store any relevant client information here. - - if (server && refuse_connections) { - enet_peer_reset(event.peer); - break; - } - - // 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); - } - - int *new_id = memnew(int); - *new_id = event.data; - - if (*new_id == 0) { // Data zero is sent by server (ENet won't let you configure this). Server is always 1. - *new_id = 1; - } - - 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("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("connection_succeeded"); - } - - } break; - case ENET_EVENT_TYPE_DISCONNECT: { - // Reset the peer's client information. - - int *id = (int *)event.peer->data; - - if (!id) { - if (!server) { - emit_signal("connection_failed"); - } - // Never fully connected. - break; - } - - if (!server) { - // Client just disconnected from server. - emit_signal("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); - } - } - - emit_signal("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("peer_connected", id); - - } break; - case SYSMSG_REMOVE_PEER: { - peer_map.erase(id); - emit_signal("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); - } - - } break; - case ENET_EVENT_TYPE_NONE: { - // Do nothing - } break; - } - } -} - -bool NetworkedMultiplayerENet::is_server() const { - ERR_FAIL_COND_V_MSG(!active, false, "The multiplayer instance isn't currently active."); - - return server; -} - -void NetworkedMultiplayerENet::close_connection(uint32_t wait_usec) { - ERR_FAIL_COND_MSG(!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); - peers_disconnected = true; - } - } - - if (peers_disconnected) { - enet_host_flush(host); - - if (wait_usec > 0) { - OS::get_singleton()->delay_usec(wait_usec); // Wait for disconnection packets to send - } - } - - enet_host_destroy(host); - active = false; - incoming_packets.clear(); - peer_map.clear(); - unique_id = 1; // Server is 1 - connection_status = CONNECTION_DISCONNECTED; -} - -void NetworkedMultiplayerENet::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("peer_disconnected", p_peer); - peer_map.erase(p_peer); - } else { - enet_peer_disconnect_later(peer_map[p_peer], 0); - } -} - -int NetworkedMultiplayerENet::get_available_packet_count() const { - return incoming_packets.size(); -} - -Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - ERR_FAIL_COND_V_MSG(incoming_packets.size() == 0, ERR_UNAVAILABLE, "No incoming packets available."); - - _pop_current_packet(); - - current_packet = incoming_packets.front()->get(); - incoming_packets.pop_front(); - - *r_buffer = (const uint8_t *)(¤t_packet.packet->data[8]); - r_buffer_size = current_packet.packet->dataLength - 8; - - return OK; -} - -Error NetworkedMultiplayerENet::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(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client."); - - 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; - } - channel = SYSCH_UNRELIABLE; - } break; - case TRANSFER_MODE_UNRELIABLE_ORDERED: { - packet_flags = 0; - channel = SYSCH_UNRELIABLE; - } break; - case TRANSFER_MODE_RELIABLE: { - packet_flags = ENET_PACKET_FLAG_RELIABLE; - channel = SYSCH_RELIABLE; - } 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 (target_peer == 0) { - enet_host_broadcast(host, 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 - continue; - } - - ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags); - - enet_peer_send(F->get(), channel, packet2); - } - - enet_packet_destroy(packet); // Original packet no longer needed - } else { - enet_peer_send(E->get(), channel, packet); - } - } 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; -} - -int NetworkedMultiplayerENet::get_max_packet_size() const { - return 1 << 24; // Anything is good -} - -void NetworkedMultiplayerENet::_pop_current_packet() { - if (current_packet.packet) { - enet_packet_destroy(current_packet.packet); - current_packet.packet = nullptr; - current_packet.from = 0; - current_packet.channel = -1; - } -} - -MultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const { - return connection_status; -} - -uint32_t NetworkedMultiplayerENet::_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 NetworkedMultiplayerENet::get_unique_id() const { - ERR_FAIL_COND_V_MSG(!active, 0, "The multiplayer instance isn't currently active."); - return unique_id; -} - -void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) { - refuse_connections = p_enable; -#ifdef GODOT_ENET - if (active) { - enet_host_refuse_new_connections(host, p_enable); - } -#endif -} - -bool NetworkedMultiplayerENet::is_refusing_new_connections() const { - return refuse_connections; -} - -void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) { - compression_mode = p_mode; -} - -NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const { - return compression_mode; -} - -size_t NetworkedMultiplayerENet::enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit) { - NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context); - - if (size_t(enet->src_compressor_mem.size()) < inLimit) { - enet->src_compressor_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(&enet->src_compressor_mem.write[ofs], inBuffers[i].data, to_copy); - ofs += to_copy; - total -= to_copy; - } - } - - Compression::Mode mode; - - 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)); - } - } - - 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; -} - -size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) { - NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(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: { - } - } - if (ret < 0) { - return 0; - } else { - return ret; - } -} - -void NetworkedMultiplayerENet::_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 NetworkedMultiplayerENet::enet_compressor_destroy(void *context) { - // Nothing to do -} - -IPAddress NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::get_local_port() const { - ERR_FAIL_COND_V_MSG(!active || !host, 0, "The multiplayer instance isn't currently active."); - return host->address.port; -} - -void NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::get_transfer_channel() const { - return transfer_channel; -} - -void NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::get_channel_count() const { - return channel_count; -} - -void NetworkedMultiplayerENet::set_always_ordered(bool p_ordered) { - always_ordered = p_ordered; -} - -bool NetworkedMultiplayerENet::is_always_ordered() const { - return always_ordered; -} - -void NetworkedMultiplayerENet::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 NetworkedMultiplayerENet::is_server_relay_enabled() const { - return server_relay; -} - -void NetworkedMultiplayerENet::_bind_methods() { - ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("create_client", "address", "port", "in_bandwidth", "out_bandwidth", "local_port"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0)); - ClassDB::bind_method(D_METHOD("close_connection", "wait_usec"), &NetworkedMultiplayerENet::close_connection, DEFVAL(100)); - ClassDB::bind_method(D_METHOD("disconnect_peer", "id", "now"), &NetworkedMultiplayerENet::disconnect_peer, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode); - ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode); - ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip); - ClassDB::bind_method(D_METHOD("set_dtls_enabled", "enabled"), &NetworkedMultiplayerENet::set_dtls_enabled); - ClassDB::bind_method(D_METHOD("is_dtls_enabled"), &NetworkedMultiplayerENet::is_dtls_enabled); - ClassDB::bind_method(D_METHOD("set_dtls_key", "key"), &NetworkedMultiplayerENet::set_dtls_key); - ClassDB::bind_method(D_METHOD("set_dtls_certificate", "certificate"), &NetworkedMultiplayerENet::set_dtls_certificate); - ClassDB::bind_method(D_METHOD("set_dtls_verify_enabled", "enabled"), &NetworkedMultiplayerENet::set_dtls_verify_enabled); - ClassDB::bind_method(D_METHOD("is_dtls_verify_enabled"), &NetworkedMultiplayerENet::is_dtls_verify_enabled); - ClassDB::bind_method(D_METHOD("get_peer_address", "id"), &NetworkedMultiplayerENet::get_peer_address); - ClassDB::bind_method(D_METHOD("get_peer_port", "id"), &NetworkedMultiplayerENet::get_peer_port); - ClassDB::bind_method(D_METHOD("get_local_port"), &NetworkedMultiplayerENet::get_local_port); - ClassDB::bind_method(D_METHOD("set_peer_timeout", "id", "timeout_limit", "timeout_min", "timeout_max"), &NetworkedMultiplayerENet::set_peer_timeout); - - ClassDB::bind_method(D_METHOD("get_packet_channel"), &NetworkedMultiplayerENet::get_packet_channel); - ClassDB::bind_method(D_METHOD("get_last_packet_channel"), &NetworkedMultiplayerENet::get_last_packet_channel); - ClassDB::bind_method(D_METHOD("set_transfer_channel", "channel"), &NetworkedMultiplayerENet::set_transfer_channel); - ClassDB::bind_method(D_METHOD("get_transfer_channel"), &NetworkedMultiplayerENet::get_transfer_channel); - ClassDB::bind_method(D_METHOD("set_channel_count", "channels"), &NetworkedMultiplayerENet::set_channel_count); - ClassDB::bind_method(D_METHOD("get_channel_count"), &NetworkedMultiplayerENet::get_channel_count); - ClassDB::bind_method(D_METHOD("set_always_ordered", "ordered"), &NetworkedMultiplayerENet::set_always_ordered); - ClassDB::bind_method(D_METHOD("is_always_ordered"), &NetworkedMultiplayerENet::is_always_ordered); - ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &NetworkedMultiplayerENet::set_server_relay_enabled); - ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &NetworkedMultiplayerENet::is_server_relay_enabled); - - 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); -} - -NetworkedMultiplayerENet::NetworkedMultiplayerENet() { - enet_compressor.context = this; - enet_compressor.compress = enet_compress; - enet_compressor.decompress = enet_decompress; - enet_compressor.destroy = enet_compressor_destroy; - - bind_ip = IPAddress("*"); -} - -NetworkedMultiplayerENet::~NetworkedMultiplayerENet() { - if (active) { - close_connection(); - } -} - -// Sets IP for ENet to bind when using create_server or create_client -// if no IP is set, then ENet bind to ENET_HOST_ANY -void NetworkedMultiplayerENet::set_bind_ip(const IPAddress &p_ip) { - ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip))); - - bind_ip = p_ip; -} - -void NetworkedMultiplayerENet::set_dtls_enabled(bool p_enabled) { - ERR_FAIL_COND(active); - dtls_enabled = p_enabled; -} - -bool NetworkedMultiplayerENet::is_dtls_enabled() const { - return dtls_enabled; -} - -void NetworkedMultiplayerENet::set_dtls_verify_enabled(bool p_enabled) { - ERR_FAIL_COND(active); - dtls_verify = p_enabled; -} - -bool NetworkedMultiplayerENet::is_dtls_verify_enabled() const { - return dtls_verify; -} - -void NetworkedMultiplayerENet::set_dtls_key(Ref p_key) { - ERR_FAIL_COND(active); - dtls_key = p_key; -} - -void NetworkedMultiplayerENet::set_dtls_certificate(Ref p_cert) { - ERR_FAIL_COND(active); - dtls_cert = p_cert; -} diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/networked_multiplayer_enet.h deleted file mode 100644 index 6fb7123b43..0000000000 --- a/modules/enet/networked_multiplayer_enet.h +++ /dev/null @@ -1,185 +0,0 @@ -/*************************************************************************/ -/* networked_multiplayer_enet.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 NETWORKED_MULTIPLAYER_ENET_H -#define NETWORKED_MULTIPLAYER_ENET_H - -#include "core/crypto/crypto.h" -#include "core/io/compression.h" -#include "core/io/multiplayer_peer.h" - -#include - -class NetworkedMultiplayerENet : public MultiplayerPeer { - GDCLASS(NetworkedMultiplayerENet, MultiplayerPeer); - -public: - enum CompressionMode { - COMPRESS_NONE, - COMPRESS_RANGE_CODER, - COMPRESS_FASTLZ, - COMPRESS_ZLIB, - COMPRESS_ZSTD - }; - -private: - enum { - SYSMSG_ADD_PEER, - SYSMSG_REMOVE_PEER - }; - - enum { - SYSCH_CONFIG, - SYSCH_RELIABLE, - SYSCH_UNRELIABLE, - SYSCH_MAX - }; - - bool active = false; - bool server = false; - - 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; - - struct Packet { - ENetPacket *packet = nullptr; - int from = 0; - int channel = 0; - }; - - CompressionMode compression_mode = COMPRESS_NONE; - - List incoming_packets; - - Packet current_packet; - - uint32_t _gen_unique_id() const; - 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(); - - IPAddress bind_ip; - - bool dtls_enabled = false; - Ref dtls_key; - Ref dtls_cert; - bool dtls_verify = true; - -protected: - static void _bind_methods(); - -public: - virtual void set_transfer_mode(TransferMode p_mode) override; - virtual TransferMode get_transfer_mode() const override; - virtual void set_target_peer(int p_peer) override; - - 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); - - void close_connection(uint32_t wait_usec = 100); - - void disconnect_peer(int p_peer, bool now = false); - - virtual void poll() override; - - virtual bool is_server() const override; - - virtual int get_available_packet_count() const override; - virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override; ///< buffer is GONE after next get_packet - virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override; - - virtual int get_max_packet_size() const override; - - virtual ConnectionStatus get_connection_status() const override; - - virtual void set_refuse_new_connections(bool p_enable) override; - virtual bool is_refusing_new_connections() const override; - - 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_server_relay_enabled(bool p_enabled); - bool is_server_relay_enabled() const; - - NetworkedMultiplayerENet(); - ~NetworkedMultiplayerENet(); - - 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(NetworkedMultiplayerENet::CompressionMode); - -#endif // NETWORKED_MULTIPLAYER_ENET_H diff --git a/modules/enet/register_types.cpp b/modules/enet/register_types.cpp index 8da2d17e13..7a32903d76 100644 --- a/modules/enet/register_types.cpp +++ b/modules/enet/register_types.cpp @@ -30,7 +30,7 @@ #include "register_types.h" #include "core/error/error_macros.h" -#include "networked_multiplayer_enet.h" +#include "enet_multiplayer_peer.h" static bool enet_ok = false; @@ -41,7 +41,7 @@ void register_enet_types() { enet_ok = true; } - ClassDB::register_class(); + ClassDB::register_class(); } void unregister_enet_types() { -- cgit v1.2.3 From 97e763dddf6aad72b7dd05ad52dfe16cecc1f221 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Mon, 12 Jul 2021 16:26:37 +0200 Subject: [Net] Rename WebRTCMultiplayer to WebRTCMultiplayerPeer. --- modules/webrtc/config.py | 2 +- modules/webrtc/doc_classes/WebRTCMultiplayer.xml | 89 ----- .../webrtc/doc_classes/WebRTCMultiplayerPeer.xml | 89 +++++ modules/webrtc/register_types.cpp | 4 +- modules/webrtc/webrtc_multiplayer.cpp | 392 --------------------- modules/webrtc/webrtc_multiplayer.h | 115 ------ modules/webrtc/webrtc_multiplayer_peer.cpp | 392 +++++++++++++++++++++ modules/webrtc/webrtc_multiplayer_peer.h | 115 ++++++ 8 files changed, 599 insertions(+), 599 deletions(-) delete mode 100644 modules/webrtc/doc_classes/WebRTCMultiplayer.xml create mode 100644 modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml delete mode 100644 modules/webrtc/webrtc_multiplayer.cpp delete mode 100644 modules/webrtc/webrtc_multiplayer.h create mode 100644 modules/webrtc/webrtc_multiplayer_peer.cpp create mode 100644 modules/webrtc/webrtc_multiplayer_peer.h diff --git a/modules/webrtc/config.py b/modules/webrtc/config.py index 0a075ccef1..3281415f38 100644 --- a/modules/webrtc/config.py +++ b/modules/webrtc/config.py @@ -10,7 +10,7 @@ def get_doc_classes(): return [ "WebRTCPeerConnection", "WebRTCDataChannel", - "WebRTCMultiplayer", + "WebRTCMultiplayerPeer", ] diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayer.xml deleted file mode 100644 index 99c7236bfc..0000000000 --- a/modules/webrtc/doc_classes/WebRTCMultiplayer.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. - - - This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer]. - You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections. - [signal MultiplayerPeer.connection_succeeded] and [signal MultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [MultiplayerPeer]. - - - - - - - - - - - - - - - Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW]. - Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]). - - - - - - - Close all the add peer connections and channels, freeing all resources. - - - - - - - - - Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open). - - - - - - - Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer]. - - - - - - - - - Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though). - - - - - - - - - - - Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647). - If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant MultiplayerPeer.CONNECTION_CONNECTED] and [signal MultiplayerPeer.connection_succeeded] will not be emitted. - If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal MultiplayerPeer.peer_connected] signals until a peer with id [constant MultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal MultiplayerPeer.connection_succeeded]. After that the signal [signal MultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal MultiplayerPeer.server_disconnected] will be emitted and state will become [constant MultiplayerPeer.CONNECTION_CONNECTED]. - - - - - - - - - Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal MultiplayerPeer.peer_connected] was emitted for it, then [signal MultiplayerPeer.peer_disconnected] will be emitted. - - - - - - - - - - diff --git a/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml new file mode 100644 index 0000000000..26c5bfa6ce --- /dev/null +++ b/modules/webrtc/doc_classes/WebRTCMultiplayerPeer.xml @@ -0,0 +1,89 @@ + + + + A simple interface to create a peer-to-peer mesh network composed of [WebRTCPeerConnection] that is compatible with the [MultiplayerAPI]. + + + This class constructs a full mesh of [WebRTCPeerConnection] (one connection for each peer) that can be used as a [member MultiplayerAPI.network_peer]. + You can add each [WebRTCPeerConnection] via [method add_peer] or remove them via [method remove_peer]. Peers must be added in [constant WebRTCPeerConnection.STATE_NEW] state to allow it to create the appropriate channels. This class will not create offers nor set descriptions, it will only poll them, and notify connections and disconnections. + [signal MultiplayerPeer.connection_succeeded] and [signal MultiplayerPeer.server_disconnected] will not be emitted unless [code]server_compatibility[/code] is [code]true[/code] in [method initialize]. Beside that data transfer works like in a [MultiplayerPeer]. + + + + + + + + + + + + + + + Add a new peer to the mesh with the given [code]peer_id[/code]. The [WebRTCPeerConnection] must be in state [constant WebRTCPeerConnection.STATE_NEW]. + Three channels will be created for reliable, unreliable, and ordered transport. The value of [code]unreliable_lifetime[/code] will be passed to the [code]maxPacketLifetime[/code] option when creating unreliable and ordered channels (see [method WebRTCPeerConnection.create_data_channel]). + + + + + + + Close all the add peer connections and channels, freeing all resources. + + + + + + + + + Return a dictionary representation of the peer with given [code]peer_id[/code] with three keys. [code]connection[/code] containing the [WebRTCPeerConnection] to this peer, [code]channels[/code] an array of three [WebRTCDataChannel], and [code]connected[/code] a boolean representing if the peer connection is currently connected (all three channels are open). + + + + + + + Returns a dictionary which keys are the peer ids and values the peer representation as in [method get_peer]. + + + + + + + + + Returns [code]true[/code] if the given [code]peer_id[/code] is in the peers map (it might not be connected though). + + + + + + + + + + + Initialize the multiplayer peer with the given [code]peer_id[/code] (must be between 1 and 2147483647). + If [code]server_compatibilty[/code] is [code]false[/code] (default), the multiplayer peer will be immediately in state [constant MultiplayerPeer.CONNECTION_CONNECTED] and [signal MultiplayerPeer.connection_succeeded] will not be emitted. + If [code]server_compatibilty[/code] is [code]true[/code] the peer will suppress all [signal MultiplayerPeer.peer_connected] signals until a peer with id [constant MultiplayerPeer.TARGET_PEER_SERVER] connects and then emit [signal MultiplayerPeer.connection_succeeded]. After that the signal [signal MultiplayerPeer.peer_connected] will be emitted for every already connected peer, and any new peer that might connect. If the server peer disconnects after that, signal [signal MultiplayerPeer.server_disconnected] will be emitted and state will become [constant MultiplayerPeer.CONNECTION_CONNECTED]. + + + + + + + + + Remove the peer with given [code]peer_id[/code] from the mesh. If the peer was connected, and [signal MultiplayerPeer.peer_connected] was emitted for it, then [signal MultiplayerPeer.peer_disconnected] will be emitted. + + + + + + + + + + diff --git a/modules/webrtc/register_types.cpp b/modules/webrtc/register_types.cpp index ecfaed9089..fcdf04fc2b 100644 --- a/modules/webrtc/register_types.cpp +++ b/modules/webrtc/register_types.cpp @@ -41,7 +41,7 @@ #include "webrtc_data_channel_gdnative.h" #include "webrtc_peer_connection_gdnative.h" #endif -#include "webrtc_multiplayer.h" +#include "webrtc_multiplayer_peer.h" void register_webrtc_types() { #define _SET_HINT(NAME, _VAL_, _MAX_) \ @@ -62,7 +62,7 @@ void register_webrtc_types() { ClassDB::register_class(); #endif ClassDB::register_virtual_class(); - ClassDB::register_class(); + ClassDB::register_class(); } void unregister_webrtc_types() {} diff --git a/modules/webrtc/webrtc_multiplayer.cpp b/modules/webrtc/webrtc_multiplayer.cpp deleted file mode 100644 index 019ac890b8..0000000000 --- a/modules/webrtc/webrtc_multiplayer.cpp +++ /dev/null @@ -1,392 +0,0 @@ -/*************************************************************************/ -/* webrtc_multiplayer.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 "webrtc_multiplayer.h" - -#include "core/io/marshalls.h" -#include "core/os/os.h" - -void WebRTCMultiplayer::_bind_methods() { - ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayer::initialize, DEFVAL(false)); - ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayer::add_peer, DEFVAL(1)); - ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayer::remove_peer); - ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayer::has_peer); - ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayer::get_peer); - ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayer::get_peers); - ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayer::close); -} - -void WebRTCMultiplayer::set_transfer_mode(TransferMode p_mode) { - transfer_mode = p_mode; -} - -MultiplayerPeer::TransferMode WebRTCMultiplayer::get_transfer_mode() const { - return transfer_mode; -} - -void WebRTCMultiplayer::set_target_peer(int p_peer_id) { - target_peer = p_peer_id; -} - -/* Returns the ID of the MultiplayerPeer who sent the most recent packet: */ -int WebRTCMultiplayer::get_packet_peer() const { - return next_packet_peer; -} - -bool WebRTCMultiplayer::is_server() const { - return unique_id == TARGET_PEER_SERVER; -} - -void WebRTCMultiplayer::poll() { - if (peer_map.size() == 0) { - return; - } - - List remove; - List add; - for (Map>::Element *E = peer_map.front(); E; E = E->next()) { - Ref peer = E->get(); - peer->connection->poll(); - // Check peer state - switch (peer->connection->get_connection_state()) { - case WebRTCPeerConnection::STATE_NEW: - case WebRTCPeerConnection::STATE_CONNECTING: - // Go to next peer, not ready yet. - continue; - case WebRTCPeerConnection::STATE_CONNECTED: - // Good to go, go ahead and check channel state. - break; - default: - // Peer is closed or in error state. Got to next peer. - remove.push_back(E->key()); - continue; - } - // Check channels state - int ready = 0; - for (List>::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) { - Ref ch = C->get(); - switch (ch->get_ready_state()) { - case WebRTCDataChannel::STATE_CONNECTING: - continue; - case WebRTCDataChannel::STATE_OPEN: - ready++; - continue; - default: - // Channel was closed or in error state, remove peer id. - remove.push_back(E->key()); - } - // We got a closed channel break out, the peer will be removed. - break; - } - // This peer has newly connected, and all channels are now open. - if (ready == peer->channels.size() && !peer->connected) { - peer->connected = true; - add.push_back(E->key()); - } - } - // Remove disconnected peers - for (List::Element *E = remove.front(); E; E = E->next()) { - remove_peer(E->get()); - if (next_packet_peer == E->get()) { - next_packet_peer = 0; - } - } - // Signal newly connected peers - for (List::Element *E = add.front(); E; E = E->next()) { - // Already connected to server: simply notify new peer. - // NOTE: Mesh is always connected. - if (connection_status == CONNECTION_CONNECTED) { - emit_signal("peer_connected", E->get()); - } - - // Server emulation mode suppresses peer_conencted until server connects. - if (server_compat && E->get() == TARGET_PEER_SERVER) { - // Server connected. - connection_status = CONNECTION_CONNECTED; - emit_signal("peer_connected", TARGET_PEER_SERVER); - emit_signal("connection_succeeded"); - // Notify of all previously connected peers - for (Map>::Element *F = peer_map.front(); F; F = F->next()) { - if (F->key() != 1 && F->get()->connected) { - emit_signal("peer_connected", F->key()); - } - } - break; // Because we already notified of all newly added peers. - } - } - // Fetch next packet - if (next_packet_peer == 0) { - _find_next_peer(); - } -} - -void WebRTCMultiplayer::_find_next_peer() { - Map>::Element *E = peer_map.find(next_packet_peer); - if (E) { - E = E->next(); - } - // After last. - while (E) { - for (List>::Element *F = E->get()->channels.front(); F; F = F->next()) { - if (F->get()->get_available_packet_count()) { - next_packet_peer = E->key(); - return; - } - } - E = E->next(); - } - E = peer_map.front(); - // Before last - while (E) { - for (List>::Element *F = E->get()->channels.front(); F; F = F->next()) { - if (F->get()->get_available_packet_count()) { - next_packet_peer = E->key(); - return; - } - } - if (E->key() == (int)next_packet_peer) { - break; - } - E = E->next(); - } - // No packet found - next_packet_peer = 0; -} - -void WebRTCMultiplayer::set_refuse_new_connections(bool p_enable) { - refuse_connections = p_enable; -} - -bool WebRTCMultiplayer::is_refusing_new_connections() const { - return refuse_connections; -} - -MultiplayerPeer::ConnectionStatus WebRTCMultiplayer::get_connection_status() const { - return connection_status; -} - -Error WebRTCMultiplayer::initialize(int p_self_id, bool p_server_compat) { - ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); - unique_id = p_self_id; - server_compat = p_server_compat; - - // Mesh and server are always connected - if (!server_compat || p_self_id == 1) { - connection_status = CONNECTION_CONNECTED; - } else { - connection_status = CONNECTION_CONNECTING; - } - return OK; -} - -int WebRTCMultiplayer::get_unique_id() const { - ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1); - return unique_id; -} - -void WebRTCMultiplayer::_peer_to_dict(Ref p_connected_peer, Dictionary &r_dict) { - Array channels; - for (List>::Element *F = p_connected_peer->channels.front(); F; F = F->next()) { - channels.push_back(F->get()); - } - r_dict["connection"] = p_connected_peer->connection; - r_dict["connected"] = p_connected_peer->connected; - r_dict["channels"] = channels; -} - -bool WebRTCMultiplayer::has_peer(int p_peer_id) { - return peer_map.has(p_peer_id); -} - -Dictionary WebRTCMultiplayer::get_peer(int p_peer_id) { - ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary()); - Dictionary out; - _peer_to_dict(peer_map[p_peer_id], out); - return out; -} - -Dictionary WebRTCMultiplayer::get_peers() { - Dictionary out; - for (Map>::Element *E = peer_map.front(); E; E = E->next()) { - Dictionary d; - _peer_to_dict(E->get(), d); - out[E->key()] = d; - } - return out; -} - -Error WebRTCMultiplayer::add_peer(Ref p_peer, int p_peer_id, int p_unreliable_lifetime) { - ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED); - // Peer must be valid, and in new state (to create data channels) - ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER); - ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER); - - Ref peer = memnew(ConnectedPeer); - peer->connection = p_peer; - - // Initialize data channels - Dictionary cfg; - cfg["negotiated"] = true; - cfg["ordered"] = true; - - cfg["id"] = 1; - peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg); - ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED); - - cfg["id"] = 2; - cfg["maxPacketLifetime"] = p_unreliable_lifetime; - peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg); - ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED); - - cfg["id"] = 3; - cfg["ordered"] = false; - peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg); - ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED); - - peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map - - return OK; -} - -void WebRTCMultiplayer::remove_peer(int p_peer_id) { - ERR_FAIL_COND(!peer_map.has(p_peer_id)); - Ref peer = peer_map[p_peer_id]; - peer_map.erase(p_peer_id); - if (peer->connected) { - peer->connected = false; - emit_signal("peer_disconnected", p_peer_id); - if (server_compat && p_peer_id == TARGET_PEER_SERVER) { - emit_signal("server_disconnected"); - connection_status = CONNECTION_DISCONNECTED; - } - } -} - -Error WebRTCMultiplayer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { - // Peer not available - if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) { - _find_next_peer(); - ERR_FAIL_V(ERR_UNAVAILABLE); - } - for (List>::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) { - if (E->get()->get_available_packet_count()) { - Error err = E->get()->get_packet(r_buffer, r_buffer_size); - _find_next_peer(); - return err; - } - } - // Channels for that peer were empty. Bug? - _find_next_peer(); - ERR_FAIL_V(ERR_BUG); -} - -Error WebRTCMultiplayer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { - ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED); - - int ch = CH_RELIABLE; - switch (transfer_mode) { - case TRANSFER_MODE_RELIABLE: - ch = CH_RELIABLE; - break; - case TRANSFER_MODE_UNRELIABLE_ORDERED: - ch = CH_ORDERED; - break; - case TRANSFER_MODE_UNRELIABLE: - ch = CH_UNRELIABLE; - break; - } - - Map>::Element *E = nullptr; - - if (target_peer > 0) { - E = peer_map.find(target_peer); - ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + "."); - - ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG); - ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG); - return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); - - } else { - int exclude = -target_peer; - - for (Map>::Element *F = peer_map.front(); F; F = F->next()) { - // Exclude packet. If target_peer == 0 then don't exclude any packets - if (target_peer != 0 && F->key() == exclude) { - continue; - } - - ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid()); - F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); - } - } - return OK; -} - -int WebRTCMultiplayer::get_available_packet_count() const { - if (next_packet_peer == 0) { - return 0; // To be sure next call to get_packet works if size > 0 . - } - int size = 0; - for (Map>::Element *E = peer_map.front(); E; E = E->next()) { - for (List>::Element *F = E->get()->channels.front(); F; F = F->next()) { - size += F->get()->get_available_packet_count(); - } - } - return size; -} - -int WebRTCMultiplayer::get_max_packet_size() const { - return 1200; -} - -void WebRTCMultiplayer::close() { - peer_map.clear(); - unique_id = 0; - next_packet_peer = 0; - target_peer = 0; - connection_status = CONNECTION_DISCONNECTED; -} - -WebRTCMultiplayer::WebRTCMultiplayer() { - unique_id = 0; - next_packet_peer = 0; - target_peer = 0; - client_count = 0; - transfer_mode = TRANSFER_MODE_RELIABLE; - refuse_connections = false; - connection_status = CONNECTION_DISCONNECTED; - server_compat = false; -} - -WebRTCMultiplayer::~WebRTCMultiplayer() { - close(); -} diff --git a/modules/webrtc/webrtc_multiplayer.h b/modules/webrtc/webrtc_multiplayer.h deleted file mode 100644 index 5e8b6be24e..0000000000 --- a/modules/webrtc/webrtc_multiplayer.h +++ /dev/null @@ -1,115 +0,0 @@ -/*************************************************************************/ -/* webrtc_multiplayer.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 WEBRTC_MULTIPLAYER_H -#define WEBRTC_MULTIPLAYER_H - -#include "core/io/multiplayer_peer.h" -#include "webrtc_peer_connection.h" - -class WebRTCMultiplayer : public MultiplayerPeer { - GDCLASS(WebRTCMultiplayer, MultiplayerPeer); - -protected: - static void _bind_methods(); - -private: - enum { - CH_RELIABLE = 0, - CH_ORDERED = 1, - CH_UNRELIABLE = 2, - CH_RESERVED_MAX = 3 - }; - - class ConnectedPeer : public RefCounted { - public: - Ref connection; - List> channels; - bool connected; - - ConnectedPeer() { - connected = false; - for (int i = 0; i < CH_RESERVED_MAX; i++) { - channels.push_front(Ref()); - } - } - }; - - uint32_t unique_id; - int target_peer; - int client_count; - bool refuse_connections; - ConnectionStatus connection_status; - TransferMode transfer_mode; - int next_packet_peer; - bool server_compat; - - Map> peer_map; - - void _peer_to_dict(Ref p_connected_peer, Dictionary &r_dict); - void _find_next_peer(); - -public: - WebRTCMultiplayer(); - ~WebRTCMultiplayer(); - - Error initialize(int p_self_id, bool p_server_compat = false); - Error add_peer(Ref p_peer, int p_peer_id, int p_unreliable_lifetime = 1); - void remove_peer(int p_peer_id); - bool has_peer(int p_peer_id); - Dictionary get_peer(int p_peer_id); - Dictionary get_peers(); - void close(); - - // PacketPeer - 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; - int get_available_packet_count() const override; - int get_max_packet_size() const override; - - // MultiplayerPeer - void set_transfer_mode(TransferMode p_mode) override; - TransferMode get_transfer_mode() const override; - void set_target_peer(int p_peer_id) override; - - int get_unique_id() const override; - int get_packet_peer() const override; - - bool is_server() const override; - - void poll() override; - - void set_refuse_new_connections(bool p_enable) override; - bool is_refusing_new_connections() const override; - - ConnectionStatus get_connection_status() const override; -}; - -#endif // WEBRTC_MULTIPLAYER_H diff --git a/modules/webrtc/webrtc_multiplayer_peer.cpp b/modules/webrtc/webrtc_multiplayer_peer.cpp new file mode 100644 index 0000000000..ac75f9e860 --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer_peer.cpp @@ -0,0 +1,392 @@ +/*************************************************************************/ +/* webrtc_multiplayer_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 "webrtc_multiplayer_peer.h" + +#include "core/io/marshalls.h" +#include "core/os/os.h" + +void WebRTCMultiplayerPeer::_bind_methods() { + ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility"), &WebRTCMultiplayerPeer::initialize, DEFVAL(false)); + ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayerPeer::add_peer, DEFVAL(1)); + ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayerPeer::remove_peer); + ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayerPeer::has_peer); + ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayerPeer::get_peer); + ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayerPeer::get_peers); + ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayerPeer::close); +} + +void WebRTCMultiplayerPeer::set_transfer_mode(TransferMode p_mode) { + transfer_mode = p_mode; +} + +MultiplayerPeer::TransferMode WebRTCMultiplayerPeer::get_transfer_mode() const { + return transfer_mode; +} + +void WebRTCMultiplayerPeer::set_target_peer(int p_peer_id) { + target_peer = p_peer_id; +} + +/* Returns the ID of the MultiplayerPeer who sent the most recent packet: */ +int WebRTCMultiplayerPeer::get_packet_peer() const { + return next_packet_peer; +} + +bool WebRTCMultiplayerPeer::is_server() const { + return unique_id == TARGET_PEER_SERVER; +} + +void WebRTCMultiplayerPeer::poll() { + if (peer_map.size() == 0) { + return; + } + + List remove; + List add; + for (Map>::Element *E = peer_map.front(); E; E = E->next()) { + Ref peer = E->get(); + peer->connection->poll(); + // Check peer state + switch (peer->connection->get_connection_state()) { + case WebRTCPeerConnection::STATE_NEW: + case WebRTCPeerConnection::STATE_CONNECTING: + // Go to next peer, not ready yet. + continue; + case WebRTCPeerConnection::STATE_CONNECTED: + // Good to go, go ahead and check channel state. + break; + default: + // Peer is closed or in error state. Got to next peer. + remove.push_back(E->key()); + continue; + } + // Check channels state + int ready = 0; + for (List>::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) { + Ref ch = C->get(); + switch (ch->get_ready_state()) { + case WebRTCDataChannel::STATE_CONNECTING: + continue; + case WebRTCDataChannel::STATE_OPEN: + ready++; + continue; + default: + // Channel was closed or in error state, remove peer id. + remove.push_back(E->key()); + } + // We got a closed channel break out, the peer will be removed. + break; + } + // This peer has newly connected, and all channels are now open. + if (ready == peer->channels.size() && !peer->connected) { + peer->connected = true; + add.push_back(E->key()); + } + } + // Remove disconnected peers + for (List::Element *E = remove.front(); E; E = E->next()) { + remove_peer(E->get()); + if (next_packet_peer == E->get()) { + next_packet_peer = 0; + } + } + // Signal newly connected peers + for (List::Element *E = add.front(); E; E = E->next()) { + // Already connected to server: simply notify new peer. + // NOTE: Mesh is always connected. + if (connection_status == CONNECTION_CONNECTED) { + emit_signal("peer_connected", E->get()); + } + + // Server emulation mode suppresses peer_conencted until server connects. + if (server_compat && E->get() == TARGET_PEER_SERVER) { + // Server connected. + connection_status = CONNECTION_CONNECTED; + emit_signal("peer_connected", TARGET_PEER_SERVER); + emit_signal("connection_succeeded"); + // Notify of all previously connected peers + for (Map>::Element *F = peer_map.front(); F; F = F->next()) { + if (F->key() != 1 && F->get()->connected) { + emit_signal("peer_connected", F->key()); + } + } + break; // Because we already notified of all newly added peers. + } + } + // Fetch next packet + if (next_packet_peer == 0) { + _find_next_peer(); + } +} + +void WebRTCMultiplayerPeer::_find_next_peer() { + Map>::Element *E = peer_map.find(next_packet_peer); + if (E) { + E = E->next(); + } + // After last. + while (E) { + for (List>::Element *F = E->get()->channels.front(); F; F = F->next()) { + if (F->get()->get_available_packet_count()) { + next_packet_peer = E->key(); + return; + } + } + E = E->next(); + } + E = peer_map.front(); + // Before last + while (E) { + for (List>::Element *F = E->get()->channels.front(); F; F = F->next()) { + if (F->get()->get_available_packet_count()) { + next_packet_peer = E->key(); + return; + } + } + if (E->key() == (int)next_packet_peer) { + break; + } + E = E->next(); + } + // No packet found + next_packet_peer = 0; +} + +void WebRTCMultiplayerPeer::set_refuse_new_connections(bool p_enable) { + refuse_connections = p_enable; +} + +bool WebRTCMultiplayerPeer::is_refusing_new_connections() const { + return refuse_connections; +} + +MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() const { + return connection_status; +} + +Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat) { + ERR_FAIL_COND_V(p_self_id < 0 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER); + unique_id = p_self_id; + server_compat = p_server_compat; + + // Mesh and server are always connected + if (!server_compat || p_self_id == 1) { + connection_status = CONNECTION_CONNECTED; + } else { + connection_status = CONNECTION_CONNECTING; + } + return OK; +} + +int WebRTCMultiplayerPeer::get_unique_id() const { + ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1); + return unique_id; +} + +void WebRTCMultiplayerPeer::_peer_to_dict(Ref p_connected_peer, Dictionary &r_dict) { + Array channels; + for (List>::Element *F = p_connected_peer->channels.front(); F; F = F->next()) { + channels.push_back(F->get()); + } + r_dict["connection"] = p_connected_peer->connection; + r_dict["connected"] = p_connected_peer->connected; + r_dict["channels"] = channels; +} + +bool WebRTCMultiplayerPeer::has_peer(int p_peer_id) { + return peer_map.has(p_peer_id); +} + +Dictionary WebRTCMultiplayerPeer::get_peer(int p_peer_id) { + ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary()); + Dictionary out; + _peer_to_dict(peer_map[p_peer_id], out); + return out; +} + +Dictionary WebRTCMultiplayerPeer::get_peers() { + Dictionary out; + for (Map>::Element *E = peer_map.front(); E; E = E->next()) { + Dictionary d; + _peer_to_dict(E->get(), d); + out[E->key()] = d; + } + return out; +} + +Error WebRTCMultiplayerPeer::add_peer(Ref p_peer, int p_peer_id, int p_unreliable_lifetime) { + ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(refuse_connections, ERR_UNAUTHORIZED); + // Peer must be valid, and in new state (to create data channels) + ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER); + + Ref peer = memnew(ConnectedPeer); + peer->connection = p_peer; + + // Initialize data channels + Dictionary cfg; + cfg["negotiated"] = true; + cfg["ordered"] = true; + + cfg["id"] = 1; + peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_RELIABLE].is_valid(), FAILED); + + cfg["id"] = 2; + cfg["maxPacketLifetime"] = p_unreliable_lifetime; + peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_ORDERED].is_valid(), FAILED); + + cfg["id"] = 3; + cfg["ordered"] = false; + peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg); + ERR_FAIL_COND_V(!peer->channels[CH_UNRELIABLE].is_valid(), FAILED); + + peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map + + return OK; +} + +void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) { + ERR_FAIL_COND(!peer_map.has(p_peer_id)); + Ref peer = peer_map[p_peer_id]; + peer_map.erase(p_peer_id); + if (peer->connected) { + peer->connected = false; + emit_signal("peer_disconnected", p_peer_id); + if (server_compat && p_peer_id == TARGET_PEER_SERVER) { + emit_signal("server_disconnected"); + connection_status = CONNECTION_DISCONNECTED; + } + } +} + +Error WebRTCMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) { + // Peer not available + if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) { + _find_next_peer(); + ERR_FAIL_V(ERR_UNAVAILABLE); + } + for (List>::Element *E = peer_map[next_packet_peer]->channels.front(); E; E = E->next()) { + if (E->get()->get_available_packet_count()) { + Error err = E->get()->get_packet(r_buffer, r_buffer_size); + _find_next_peer(); + return err; + } + } + // Channels for that peer were empty. Bug? + _find_next_peer(); + ERR_FAIL_V(ERR_BUG); +} + +Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED); + + int ch = CH_RELIABLE; + switch (transfer_mode) { + case TRANSFER_MODE_RELIABLE: + ch = CH_RELIABLE; + break; + case TRANSFER_MODE_UNRELIABLE_ORDERED: + ch = CH_ORDERED; + break; + case TRANSFER_MODE_UNRELIABLE: + ch = CH_UNRELIABLE; + break; + } + + Map>::Element *E = nullptr; + + if (target_peer > 0) { + E = peer_map.find(target_peer); + ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + "."); + + ERR_FAIL_COND_V(E->value()->channels.size() <= ch, ERR_BUG); + ERR_FAIL_COND_V(!E->value()->channels[ch].is_valid(), ERR_BUG); + return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); + + } else { + int exclude = -target_peer; + + for (Map>::Element *F = peer_map.front(); F; F = F->next()) { + // Exclude packet. If target_peer == 0 then don't exclude any packets + if (target_peer != 0 && F->key() == exclude) { + continue; + } + + ERR_CONTINUE(F->value()->channels.size() <= ch || !F->value()->channels[ch].is_valid()); + F->value()->channels[ch]->put_packet(p_buffer, p_buffer_size); + } + } + return OK; +} + +int WebRTCMultiplayerPeer::get_available_packet_count() const { + if (next_packet_peer == 0) { + return 0; // To be sure next call to get_packet works if size > 0 . + } + int size = 0; + for (Map>::Element *E = peer_map.front(); E; E = E->next()) { + for (List>::Element *F = E->get()->channels.front(); F; F = F->next()) { + size += F->get()->get_available_packet_count(); + } + } + return size; +} + +int WebRTCMultiplayerPeer::get_max_packet_size() const { + return 1200; +} + +void WebRTCMultiplayerPeer::close() { + peer_map.clear(); + unique_id = 0; + next_packet_peer = 0; + target_peer = 0; + connection_status = CONNECTION_DISCONNECTED; +} + +WebRTCMultiplayerPeer::WebRTCMultiplayerPeer() { + unique_id = 0; + next_packet_peer = 0; + target_peer = 0; + client_count = 0; + transfer_mode = TRANSFER_MODE_RELIABLE; + refuse_connections = false; + connection_status = CONNECTION_DISCONNECTED; + server_compat = false; +} + +WebRTCMultiplayerPeer::~WebRTCMultiplayerPeer() { + close(); +} diff --git a/modules/webrtc/webrtc_multiplayer_peer.h b/modules/webrtc/webrtc_multiplayer_peer.h new file mode 100644 index 0000000000..1d9387b6dc --- /dev/null +++ b/modules/webrtc/webrtc_multiplayer_peer.h @@ -0,0 +1,115 @@ +/*************************************************************************/ +/* webrtc_multiplayer_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 WEBRTC_MULTIPLAYER_H +#define WEBRTC_MULTIPLAYER_H + +#include "core/io/multiplayer_peer.h" +#include "webrtc_peer_connection.h" + +class WebRTCMultiplayerPeer : public MultiplayerPeer { + GDCLASS(WebRTCMultiplayerPeer, MultiplayerPeer); + +protected: + static void _bind_methods(); + +private: + enum { + CH_RELIABLE = 0, + CH_ORDERED = 1, + CH_UNRELIABLE = 2, + CH_RESERVED_MAX = 3 + }; + + class ConnectedPeer : public RefCounted { + public: + Ref connection; + List> channels; + bool connected; + + ConnectedPeer() { + connected = false; + for (int i = 0; i < CH_RESERVED_MAX; i++) { + channels.push_front(Ref()); + } + } + }; + + uint32_t unique_id; + int target_peer; + int client_count; + bool refuse_connections; + ConnectionStatus connection_status; + TransferMode transfer_mode; + int next_packet_peer; + bool server_compat; + + Map> peer_map; + + void _peer_to_dict(Ref p_connected_peer, Dictionary &r_dict); + void _find_next_peer(); + +public: + WebRTCMultiplayerPeer(); + ~WebRTCMultiplayerPeer(); + + Error initialize(int p_self_id, bool p_server_compat = false); + Error add_peer(Ref p_peer, int p_peer_id, int p_unreliable_lifetime = 1); + void remove_peer(int p_peer_id); + bool has_peer(int p_peer_id); + Dictionary get_peer(int p_peer_id); + Dictionary get_peers(); + void close(); + + // PacketPeer + 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; + int get_available_packet_count() const override; + int get_max_packet_size() const override; + + // MultiplayerPeer + void set_transfer_mode(TransferMode p_mode) override; + TransferMode get_transfer_mode() const override; + void set_target_peer(int p_peer_id) override; + + int get_unique_id() const override; + int get_packet_peer() const override; + + bool is_server() const override; + + void poll() override; + + void set_refuse_new_connections(bool p_enable) override; + bool is_refusing_new_connections() const override; + + ConnectionStatus get_connection_status() const override; +}; + +#endif // WEBRTC_MULTIPLAYER_H -- cgit v1.2.3