106 lines
2.3 KiB
C++
106 lines
2.3 KiB
C++
#pragma once
|
|
#include <string>
|
|
#include <optional>
|
|
#include <enet/enet.h>
|
|
#include "../utils/logger.hpp"
|
|
|
|
namespace net {
|
|
|
|
constexpr auto TIMEOUT = 5000;
|
|
constexpr auto CHANNEL_COUNT = 2;
|
|
enum class channel_type: enet_uint8 {
|
|
RELIABLE = 0,
|
|
NOTIFY = 1,
|
|
};
|
|
|
|
enum class disconnect_reason: enet_uint32 {
|
|
UNEXPECTED = 0,
|
|
QUIT = 1,
|
|
WRONG_SALT = 15,
|
|
};
|
|
|
|
using salt_t = enet_uint32;
|
|
using peer_t = ENetPeer;
|
|
using packet_t = ENetPacket;
|
|
|
|
enum class server_packet_type: enet_uint8 {
|
|
PERSONAL = 0,
|
|
/// Get server salt
|
|
/// realable
|
|
CHALLENGE = 0,
|
|
|
|
BROADCASTED = 16,
|
|
/// List all areas
|
|
/// {area_id, world::Area::params}[] realable
|
|
AREAS = 16,
|
|
/// Full chunk update
|
|
/// {area_<chunk_pos>, zstd<chunk rle>} realable
|
|
CHUNK = 17,
|
|
/// Chunk changes
|
|
/// {area_id, {chunk_pos, ushort(count), Chunk::Edit[]}[]} notify
|
|
/// FIXME: to big !!! MAYBE: compress
|
|
EDITS = 18,
|
|
|
|
/// World compression dictionary
|
|
/// zstd dict realable
|
|
COMPRESSION = 24,
|
|
/// Server capabilities
|
|
/// ushort(loadDistance), MAYBE: more realable
|
|
CAPABILITIES = 25,
|
|
};
|
|
enum class client_packet_type: enet_uint8 {
|
|
/// Interact with voxels
|
|
/// actions::FillCube realable
|
|
FILL_CUBE = 0,
|
|
|
|
/// Request missing chunks
|
|
/// area_id, chunk_pos[] realable
|
|
MISSING_CHUNKS = 8,
|
|
|
|
/// Position update
|
|
/// voxel_pos notify
|
|
MOVE = 16,
|
|
};
|
|
|
|
struct connection {
|
|
std::string address;
|
|
int port;
|
|
|
|
std::optional<ENetAddress> toAddress() const {
|
|
ENetAddress addr;
|
|
addr.port = port;
|
|
if(enet_address_set_host(&addr, address.c_str()) != 0)
|
|
return {};
|
|
|
|
return std::make_optional(addr);
|
|
}
|
|
|
|
friend inline std::ostream& operator<<(std::ostream& os, const connection& ct) {
|
|
return os << ct.address << ':' << ct.port;
|
|
}
|
|
};
|
|
|
|
inline std::ostream &operator<<(std::ostream &os, const ENetAddress &addr) {
|
|
constexpr auto LEN = 16;
|
|
char *buf = (char*)enet_malloc(LEN);
|
|
if(enet_address_get_host_ip(&addr, buf, LEN) == 0) {
|
|
os << buf;
|
|
} else {
|
|
os << addr.host;
|
|
}
|
|
enet_free(buf);
|
|
os << ':' << addr.port;
|
|
return os;
|
|
}
|
|
|
|
void inline Setup() {
|
|
if(enet_initialize() != 0) {
|
|
FATAL("Enet initialization failed");
|
|
}
|
|
std::srand(enet_host_random_seed());
|
|
}
|
|
void inline Destroy() {
|
|
enet_deinitialize();
|
|
}
|
|
|
|
} |