Skip to content

File NetworkHostResource.hpp

File List > Engine > include > Resources > NetworkHostResource.hpp

Go to the documentation of this file

/*
** EPITECH PROJECT, 2026
** G-ING-500-BAR-5-1-rtype-1
** File description:
** NetworkHost.hpp
*/
#ifndef G_ING_500_BAR_5_1_RTYPE_1_NETWORKHOST_HPP
#define G_ING_500_BAR_5_1_RTYPE_1_NETWORKHOST_HPP

#include "ECS/Registry.hpp"
#include "PacketRouterResource.hpp"

#include "Compat/EnetWrapper.hpp"
#include <cstddef>
#include <cstdint>
#include <glaze/glaze.hpp>
#include <optional>
#include <stdexcept>
#include <string_view>
#include <unordered_map>
#include <vector>

namespace Engine::Multiplayer {
class NetworkHostResource {
  public:
    static NetworkHostResource CreateServer(std::uint16_t port, std::size_t maxClients = 32,
                                            std::size_t channels = 3);

    static NetworkHostResource CreateClient(size_t channels = 3);

    ENetPeer* Connect(std::string_view host, uint16_t port, size_t channels = 3);

    void Poll(uint32_t timeoutMs, const PacketRouterResource& router, Registry& registry);

    static std::optional<Entity> GetEntityID(ENetPeer* peer);

    static void SetPeerEntity(ENetPeer* peer, Entity entity);

    void BindPeer(Entity entity, ENetPeer* peer) {
        m_entityToPeer[entity] = peer;
        SetPeerEntity(peer, entity);
    }

    bool IsServer() const {
        return m_isServer;
    }

    std::size_t GetNextNetworkId() {
        return m_nextNetworkId++;
    }

    void SetNextNetworkId(std::size_t id) {
        m_nextNetworkId = id;
    }

    std::size_t PeekNextNetworkId() const {
        return m_nextNetworkId;
    }

    std::optional<std::size_t> GetNetworkId(Registry& registry, Entity entity) const;

    std::optional<Entity> GetEntityByNetworkId(std::size_t networkId) const;

    std::optional<std::size_t> GetLocalNetworkId() const {
        return m_localNetworkId;
    }

    std::optional<Entity> GetLocalEntity() const {
        return m_localEntity;
    }

    void Flush() {
        if (m_host != nullptr) {
            enet_host_flush(m_host);
        }
    }

    std::optional<ENetPeer*> GetPeer(Entity entity) const;

    struct ConnectionEvent {
        enum class Type { Connect, Disconnect };
        Type type;
        ENetPeer* peer;
        Entity entity = static_cast<Entity>(-1);
        std::size_t networkId = 0;
    };
    void QueueEvent(ConnectionEvent::Type type, ENetPeer* peer,
                    Entity entity = static_cast<Entity>(-1), std::size_t networkId = 0) {
        m_eventQueue.push_back(ConnectionEvent{type, peer, entity, networkId});
    }
    std::vector<ConnectionEvent> DrainEvents() {
        std::vector<ConnectionEvent> out = std::move(m_eventQueue);
        m_eventQueue.clear();
        return out;
    }

    void TrackNetworkEntity(Registry& registry, Entity entity, std::size_t networkId);

    void UntrackNetworkEntity(Registry& registry, Entity entity);

    void UntrackNetworkId(std::size_t networkId);

    struct ConnectedPlayer {
        ENetPeer* peer;
        std::size_t networkId;
    };

    std::vector<ConnectedPlayer> ConnectedPlayers(Registry& registry) const;

    void ResetEntityBindings();

    void InvalidateQueuedEventEntities() {
        for (auto& event : m_eventQueue) {
            event.entity = static_cast<Entity>(-1);
        }
    }

    void SendAllHost(ENetPacket* packet, const uint8_t channel = 0) const {
        enet_host_broadcast(m_host, channel, packet);
    }

    static void Send(ENetPeer* peer, ENetPacket* packet, const uint8_t channel = 0) {
        enet_peer_send(peer, channel, packet);
    }

    void Send(ENetPacket* packet, const uint8_t channel = 0) const {
        Send(server_peer, packet, channel);
    }

    template <typename TPacketId, typename TData>
    static ENetPacket* CreatePacket(TPacketId id, const TData& data, const bool reliable) {
        static_assert(std::is_integral_v<TPacketId>, "Packet ID must be an integral type");

        Buffer payload;
        if (glz::write_beve(data, payload)) {
            payload.clear();
        }

        return CreateRawPacket(static_cast<uint16_t>(id),
                               payload.empty() ? nullptr
                                               : reinterpret_cast<const uint8_t*>(payload.data()),
                               payload.size(), reliable);
    }

    static ENetPacket* CreateRawPacket(std::uint16_t id, const uint8_t* payload,
                                       std::size_t payloadSize, bool reliable) {
        Buffer buffer;
        buffer.reserve(sizeof(uint16_t) + payloadSize);
        buffer.push_back(static_cast<std::byte>(id & 0xFF));
        buffer.push_back(static_cast<std::byte>((id >> 8) & 0xFF));
        if (payload != nullptr && payloadSize > 0) {
            const auto* bytes = reinterpret_cast<const std::byte*>(payload);
            buffer.insert(buffer.end(), bytes, bytes + payloadSize);
        }
        const enet_uint32 flags = reliable ? ENET_PACKET_FLAG_RELIABLE : 0;
        return enet_packet_create(buffer.data(), buffer.size(), flags);
    }

    static ENetPacket* CreateRawPacket(std::uint16_t id, const Buffer& payload, bool reliable) {
        return CreateRawPacket(
            id, payload.empty() ? nullptr : reinterpret_cast<const uint8_t*>(payload.data()),
            payload.size(), reliable);
    }

    // disable host copy
    NetworkHostResource(NetworkHostResource&& other) noexcept
        : m_host(other.m_host), server_peer(other.server_peer), m_isServer(other.m_isServer),
          m_nextNetworkId(other.m_nextNetworkId), m_localNetworkId(other.m_localNetworkId),
          m_localEntity(other.m_localEntity), m_idToEntity(std::move(other.m_idToEntity)),
          m_entityToPeer(std::move(other.m_entityToPeer)),
          m_eventQueue(std::move(other.m_eventQueue)) {
        other.m_host = nullptr;
        other.server_peer = nullptr;
    }

    NetworkHostResource& operator=(NetworkHostResource&& other) noexcept {
        if (this != &other) {
            if (m_host) {
                enet_host_destroy(m_host);
            }
            m_host = other.m_host;
            server_peer = other.server_peer;
            m_isServer = other.m_isServer;
            m_nextNetworkId = other.m_nextNetworkId;
            m_localNetworkId = other.m_localNetworkId;
            m_localEntity = other.m_localEntity;
            m_idToEntity = std::move(other.m_idToEntity);
            m_entityToPeer = std::move(other.m_entityToPeer);
            m_eventQueue = std::move(other.m_eventQueue);
            other.m_host = nullptr;
            other.server_peer = nullptr;
        }
        return *this;
    }

    ~NetworkHostResource();

  private:
    NetworkHostResource(const ENetAddress* address, const size_t peerCount, const size_t channels,
                        bool isServer) {
        m_host = enet_host_create(address, peerCount, channels, 0, 0);
        if (!m_host) {
            throw std::runtime_error("Failed to create ENet host");
        }
        m_isServer = isServer;
    }

    ENetPeer* server_peer = nullptr;
    ENetHost* m_host = nullptr;
    bool m_isServer = false;
    std::size_t m_nextNetworkId = 1;
    std::optional<std::size_t> m_localNetworkId;
    std::optional<Entity> m_localEntity;
    std::unordered_map<std::size_t, Entity> m_idToEntity;
    std::unordered_map<Entity, ENetPeer*> m_entityToPeer;
    std::vector<ConnectionEvent> m_eventQueue;
};
} // namespace Engine::Multiplayer
#endif // G_ING_500_BAR_5_1_RTYPE_1_NETWORKHOST_HPP