Path: blob/master/modules/enet/enet_multiplayer_peer.cpp
10277 views
/**************************************************************************/1/* enet_multiplayer_peer.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "enet_multiplayer_peer.h"3132void ENetMultiplayerPeer::set_target_peer(int p_peer) {33target_peer = p_peer;34}3536int ENetMultiplayerPeer::get_packet_peer() const {37ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");38ERR_FAIL_COND_V(incoming_packets.is_empty(), 1);3940return incoming_packets.front()->get().from;41}4243MultiplayerPeer::TransferMode ENetMultiplayerPeer::get_packet_mode() const {44ERR_FAIL_COND_V_MSG(!_is_active(), TRANSFER_MODE_RELIABLE, "The multiplayer instance isn't currently active.");45ERR_FAIL_COND_V(incoming_packets.is_empty(), TRANSFER_MODE_RELIABLE);46return incoming_packets.front()->get().transfer_mode;47}4849int ENetMultiplayerPeer::get_packet_channel() const {50ERR_FAIL_COND_V_MSG(!_is_active(), 1, "The multiplayer instance isn't currently active.");51ERR_FAIL_COND_V(incoming_packets.is_empty(), 1);52int ch = incoming_packets.front()->get().channel;53if (ch >= SYSCH_MAX) { // First 2 channels are reserved.54return ch - SYSCH_MAX + 1;55}56return 0;57}5859Error ENetMultiplayerPeer::create_server(int p_port, int p_max_clients, int p_max_channels, int p_in_bandwidth, int p_out_bandwidth) {60ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");61set_refuse_new_connections(false);62Ref<ENetConnection> host;63host.instantiate();64Error err = host->create_host_bound(bind_ip, p_port, p_max_clients, 0, p_max_channels > 0 ? p_max_channels + SYSCH_MAX : 0, p_out_bandwidth);65if (err != OK) {66return err;67}6869active_mode = MODE_SERVER;70unique_id = 1;71connection_status = CONNECTION_CONNECTED;72hosts[0] = host;73return OK;74}7576Error ENetMultiplayerPeer::create_client(const String &p_address, int p_port, int p_channel_count, int p_in_bandwidth, int p_out_bandwidth, int p_local_port) {77ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");78set_refuse_new_connections(false);79Ref<ENetConnection> host;80host.instantiate();81Error err;82if (p_local_port) {83err = host->create_host_bound(bind_ip, p_local_port, 1, 0, p_in_bandwidth, p_out_bandwidth);84} else {85err = host->create_host(1, 0, p_in_bandwidth, p_out_bandwidth);86}87if (err != OK) {88return err;89}9091unique_id = generate_unique_id();9293Ref<ENetPacketPeer> peer = host->connect_to_host(p_address, p_port, p_channel_count > 0 ? p_channel_count + SYSCH_MAX : 0, unique_id);94if (peer.is_null()) {95host->destroy();96ERR_FAIL_V_MSG(ERR_CANT_CREATE, "Couldn't connect to the ENet multiplayer server.");97}9899// Need to wait for CONNECT event.100connection_status = CONNECTION_CONNECTING;101active_mode = MODE_CLIENT;102peers[1] = peer;103hosts[0] = host;104105return OK;106}107108Error ENetMultiplayerPeer::create_mesh(int p_id) {109ERR_FAIL_COND_V_MSG(p_id <= 0, ERR_INVALID_PARAMETER, "The unique ID must be greater then 0");110ERR_FAIL_COND_V_MSG(_is_active(), ERR_ALREADY_IN_USE, "The multiplayer instance is already active.");111active_mode = MODE_MESH;112unique_id = p_id;113connection_status = CONNECTION_CONNECTED;114return OK;115}116117Error ENetMultiplayerPeer::add_mesh_peer(int p_id, Ref<ENetConnection> p_host) {118ERR_FAIL_COND_V(p_host.is_null(), ERR_INVALID_PARAMETER);119ERR_FAIL_COND_V_MSG(active_mode != MODE_MESH, ERR_UNCONFIGURED, "The multiplayer instance is not configured as a mesh. Call 'create_mesh' first.");120List<Ref<ENetPacketPeer>> host_peers;121p_host->get_peers(host_peers);122ERR_FAIL_COND_V_MSG(host_peers.size() != 1 || host_peers.front()->get()->get_state() != ENetPacketPeer::STATE_CONNECTED, ERR_INVALID_PARAMETER, "The provided host must have exactly one peer in the connected state.");123hosts[p_id] = p_host;124peers[p_id] = host_peers.front()->get();125emit_signal(SNAME("peer_connected"), p_id);126return OK;127}128129void ENetMultiplayerPeer::_store_packet(int32_t p_source, ENetConnection::Event &p_event) {130Packet packet;131packet.packet = p_event.packet;132packet.channel = p_event.channel_id;133packet.from = p_source;134if (p_event.packet->flags & ENET_PACKET_FLAG_RELIABLE) {135packet.transfer_mode = TRANSFER_MODE_RELIABLE;136} else if (p_event.packet->flags & ENET_PACKET_FLAG_UNSEQUENCED) {137packet.transfer_mode = TRANSFER_MODE_UNRELIABLE;138} else {139packet.transfer_mode = TRANSFER_MODE_UNRELIABLE_ORDERED;140}141packet.packet->referenceCount++;142incoming_packets.push_back(packet);143}144145void ENetMultiplayerPeer::_disconnect_inactive_peers() {146HashSet<int> to_drop;147for (const KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {148if (E.value->is_active()) {149continue;150}151to_drop.insert(E.key);152}153for (const int &P : to_drop) {154peers.erase(P);155if (hosts.has(P)) {156hosts.erase(P);157}158ERR_CONTINUE(active_mode == MODE_CLIENT && P != TARGET_PEER_SERVER);159emit_signal(SNAME("peer_disconnected"), P);160}161}162163void ENetMultiplayerPeer::poll() {164ERR_FAIL_COND_MSG(!_is_active(), "The multiplayer instance isn't currently active.");165166_pop_current_packet();167168_disconnect_inactive_peers();169170switch (active_mode) {171case MODE_CLIENT: {172if (!peers.has(1)) {173close();174return;175}176ENetConnection::Event event;177ENetConnection::EventType ret = hosts[0]->service(0, event);178do {179if (ret == ENetConnection::EVENT_CONNECT) {180connection_status = CONNECTION_CONNECTED;181emit_signal(SNAME("peer_connected"), 1);182} else if (ret == ENetConnection::EVENT_DISCONNECT) {183if (connection_status == CONNECTION_CONNECTED) {184// Client just disconnected from server.185emit_signal(SNAME("peer_disconnected"), 1);186}187close();188} else if (ret == ENetConnection::EVENT_RECEIVE) {189_store_packet(1, event);190} else if (ret != ENetConnection::EVENT_NONE) {191close(); // Error.192}193} while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0);194} break;195case MODE_SERVER: {196ENetConnection::Event event;197ENetConnection::EventType ret = hosts[0]->service(0, event);198do {199if (ret == ENetConnection::EVENT_CONNECT) {200if (is_refusing_new_connections()) {201event.peer->reset();202continue;203}204// Client joined with invalid ID, probably trying to exploit us.205if (event.data < 2 || peers.has((int)event.data)) {206event.peer->reset();207continue;208}209int id = event.data;210event.peer->set_meta(SNAME("_net_id"), id);211peers[id] = event.peer;212emit_signal(SNAME("peer_connected"), id);213} else if (ret == ENetConnection::EVENT_DISCONNECT) {214int id = event.peer->get_meta(SNAME("_net_id"));215if (!peers.has(id)) {216// Never fully connected.217continue;218}219emit_signal(SNAME("peer_disconnected"), id);220peers.erase(id);221} else if (ret == ENetConnection::EVENT_RECEIVE) {222int32_t source = event.peer->get_meta(SNAME("_net_id"));223_store_packet(source, event);224} else if (ret != ENetConnection::EVENT_NONE) {225close(); // Error226}227} while (hosts.has(0) && hosts[0]->check_events(ret, event) > 0);228} break;229case MODE_MESH: {230HashSet<int> to_drop;231for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {232ENetConnection::Event event;233ENetConnection::EventType ret = E.value->service(0, event);234do {235if (ret == ENetConnection::EVENT_CONNECT) {236event.peer->reset();237} else if (ret == ENetConnection::EVENT_RECEIVE) {238_store_packet(E.key, event);239} else if (ret == ENetConnection::EVENT_NONE) {240break; // Keep polling the others.241} else {242to_drop.insert(E.key); // Error or disconnect.243break; // Keep polling the others.244}245} while (E.value->check_events(ret, event) > 0);246}247for (const int &P : to_drop) {248if (peers.has(P)) {249emit_signal(SNAME("peer_disconnected"), P);250peers.erase(P);251}252hosts.erase(P);253}254} break;255default:256return;257}258}259260bool ENetMultiplayerPeer::is_server() const {261return active_mode == MODE_SERVER;262}263264bool ENetMultiplayerPeer::is_server_relay_supported() const {265return active_mode == MODE_SERVER || active_mode == MODE_CLIENT;266}267268void ENetMultiplayerPeer::disconnect_peer(int p_peer, bool p_force) {269ERR_FAIL_COND(!_is_active() || !peers.has(p_peer));270peers[p_peer]->peer_disconnect(0); // Will be removed during next poll.271if (active_mode == MODE_CLIENT || active_mode == MODE_SERVER) {272hosts[0]->flush();273} else {274ERR_FAIL_COND(!hosts.has(p_peer));275hosts[p_peer]->flush();276}277if (p_force) {278peers.erase(p_peer);279if (hosts.has(p_peer)) {280hosts.erase(p_peer);281}282if (active_mode == MODE_CLIENT) {283hosts.clear(); // Avoid flushing again.284close();285}286}287}288289void ENetMultiplayerPeer::close() {290if (!_is_active()) {291return;292}293294_pop_current_packet();295296for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {297if (E.value.is_valid() && E.value->get_state() == ENetPacketPeer::STATE_CONNECTED) {298E.value->peer_disconnect_now(0);299}300}301for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {302E.value->flush();303E.value->destroy();304}305306active_mode = MODE_NONE;307incoming_packets.clear();308peers.clear();309hosts.clear();310unique_id = 0;311connection_status = CONNECTION_DISCONNECTED;312set_refuse_new_connections(false);313}314315int ENetMultiplayerPeer::get_available_packet_count() const {316return incoming_packets.size();317}318319Error ENetMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {320ERR_FAIL_COND_V_MSG(incoming_packets.is_empty(), ERR_UNAVAILABLE, "No incoming packets available.");321322_pop_current_packet();323324current_packet = incoming_packets.front()->get();325incoming_packets.pop_front();326327*r_buffer = (const uint8_t *)(current_packet.packet->data);328r_buffer_size = current_packet.packet->dataLength;329330return OK;331}332333Error ENetMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {334ERR_FAIL_COND_V_MSG(!_is_active(), ERR_UNCONFIGURED, "The multiplayer instance isn't currently active.");335ERR_FAIL_COND_V_MSG(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED, "The multiplayer instance isn't currently connected to any server or client.");336ERR_FAIL_COND_V_MSG(target_peer != 0 && !peers.has(Math::abs(target_peer)), ERR_INVALID_PARAMETER, vformat("Invalid target peer: %d", target_peer));337ERR_FAIL_COND_V(active_mode == MODE_CLIENT && !peers.has(1), ERR_BUG);338339int packet_flags = 0;340int channel = SYSCH_RELIABLE;341int tr_channel = get_transfer_channel();342switch (get_transfer_mode()) {343case TRANSFER_MODE_UNRELIABLE: {344packet_flags = ENET_PACKET_FLAG_UNSEQUENCED | ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;345channel = SYSCH_UNRELIABLE;346} break;347case TRANSFER_MODE_UNRELIABLE_ORDERED: {348packet_flags = ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT;349channel = SYSCH_UNRELIABLE;350} break;351case TRANSFER_MODE_RELIABLE: {352packet_flags = ENET_PACKET_FLAG_RELIABLE;353channel = SYSCH_RELIABLE;354} break;355}356if (tr_channel > 0) {357channel = SYSCH_MAX + tr_channel - 1;358}359360#ifdef DEBUG_ENABLED361if ((packet_flags & ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT) && p_buffer_size > ENET_HOST_DEFAULT_MTU) {362WARN_PRINT_ONCE(vformat("Sending %d bytes unreliably which is above the MTU (%d), this will result in higher packet loss", p_buffer_size, ENET_HOST_DEFAULT_MTU));363}364#endif365366ENetPacket *packet = enet_packet_create(nullptr, p_buffer_size, packet_flags);367memcpy(&packet->data[0], p_buffer, p_buffer_size);368369if (is_server()) {370if (target_peer == 0) {371hosts[0]->broadcast(channel, packet);372373} else if (target_peer < 0) {374// Send to all but one and make copies for sending.375int exclude = -target_peer;376for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {377if (E.key == exclude) {378continue;379}380E.value->send(channel, packet);381}382_destroy_unused(packet);383} else {384peers[target_peer]->send(channel, packet);385}386ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);387hosts[0]->flush();388389} else if (active_mode == MODE_CLIENT) {390peers[1]->send(channel, packet); // Send to server for broadcast.391ERR_FAIL_COND_V(!hosts.has(0), ERR_BUG);392hosts[0]->flush();393394} else {395if (target_peer <= 0) {396int exclude = Math::abs(target_peer);397for (KeyValue<int, Ref<ENetPacketPeer>> &E : peers) {398if (E.key == exclude) {399continue;400}401E.value->send(channel, packet);402ERR_CONTINUE(!hosts.has(E.key));403hosts[E.key]->flush();404}405_destroy_unused(packet);406} else {407peers[target_peer]->send(channel, packet);408ERR_FAIL_COND_V(!hosts.has(target_peer), ERR_BUG);409hosts[target_peer]->flush();410}411}412413return OK;414}415416int ENetMultiplayerPeer::get_max_packet_size() const {417return 1 << 24; // Anything is good418}419420void ENetMultiplayerPeer::_pop_current_packet() {421if (current_packet.packet) {422current_packet.packet->referenceCount--;423_destroy_unused(current_packet.packet);424current_packet.packet = nullptr;425current_packet.from = 0;426current_packet.channel = -1;427}428}429430MultiplayerPeer::ConnectionStatus ENetMultiplayerPeer::get_connection_status() const {431return connection_status;432}433434int ENetMultiplayerPeer::get_unique_id() const {435ERR_FAIL_COND_V_MSG(!_is_active(), 0, "The multiplayer instance isn't currently active.");436return unique_id;437}438439void ENetMultiplayerPeer::set_refuse_new_connections(bool p_enabled) {440#ifdef GODOT_ENET441if (_is_active()) {442for (KeyValue<int, Ref<ENetConnection>> &E : hosts) {443E.value->refuse_new_connections(p_enabled);444}445}446#endif447MultiplayerPeer::set_refuse_new_connections(p_enabled);448}449450Ref<ENetConnection> ENetMultiplayerPeer::get_host() const {451ERR_FAIL_COND_V(!_is_active(), nullptr);452ERR_FAIL_COND_V(active_mode == MODE_MESH, nullptr);453return hosts[0];454}455456Ref<ENetPacketPeer> ENetMultiplayerPeer::get_peer(int p_id) const {457ERR_FAIL_COND_V(!_is_active(), nullptr);458ERR_FAIL_COND_V(!peers.has(p_id), nullptr);459ERR_FAIL_COND_V(active_mode == MODE_CLIENT && p_id != 1, nullptr);460return peers[p_id];461}462463void ENetMultiplayerPeer::_destroy_unused(ENetPacket *p_packet) {464if (p_packet->referenceCount == 0) {465enet_packet_destroy(p_packet);466}467}468469void ENetMultiplayerPeer::_bind_methods() {470ClassDB::bind_method(D_METHOD("create_server", "port", "max_clients", "max_channels", "in_bandwidth", "out_bandwidth"), &ENetMultiplayerPeer::create_server, DEFVAL(32), DEFVAL(0), DEFVAL(0), DEFVAL(0));471ClassDB::bind_method(D_METHOD("create_client", "address", "port", "channel_count", "in_bandwidth", "out_bandwidth", "local_port"), &ENetMultiplayerPeer::create_client, DEFVAL(0), DEFVAL(0), DEFVAL(0), DEFVAL(0));472ClassDB::bind_method(D_METHOD("create_mesh", "unique_id"), &ENetMultiplayerPeer::create_mesh);473ClassDB::bind_method(D_METHOD("add_mesh_peer", "peer_id", "host"), &ENetMultiplayerPeer::add_mesh_peer);474ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &ENetMultiplayerPeer::set_bind_ip);475476ClassDB::bind_method(D_METHOD("get_host"), &ENetMultiplayerPeer::get_host);477ClassDB::bind_method(D_METHOD("get_peer", "id"), &ENetMultiplayerPeer::get_peer);478479ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "host", PROPERTY_HINT_RESOURCE_TYPE, "ENetConnection", PROPERTY_USAGE_NONE), "", "get_host");480}481482ENetMultiplayerPeer::ENetMultiplayerPeer() {483bind_ip = IPAddress("*");484}485486ENetMultiplayerPeer::~ENetMultiplayerPeer() {487if (_is_active()) {488close();489}490}491492// Sets IP for ENet to bind when using create_server or create_client493// if no IP is set, then ENet bind to ENET_HOST_ANY494void ENetMultiplayerPeer::set_bind_ip(const IPAddress &p_ip) {495ERR_FAIL_COND_MSG(!p_ip.is_valid() && !p_ip.is_wildcard(), vformat("Invalid bind IP address: %s", String(p_ip)));496497bind_ip = p_ip;498}499500501