1
0
Fork 0
Univerxel/src/core/net/data.hpp

126 lines
2.9 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
/// reliable
CHALLENGE = 0,
/// Set client position and instance id
/// size_t(playerId) voxel_pos reliable
TELEPORT = 1,
BROADCASTED = 16,
/// List all areas
/// {area_id, world::Area::params}[] reliable
AREAS = 16,
/// Full chunk update
/// {area_<chunk_pos>, zstd<chunk rle>} reliable
CHUNK = 17,
/// Chunk changes
/// {area_id, {chunk_pos, uint16_t(count), Chunk::Edit[]}[]} notify
/// FIXME: to big !!! MAYBE: compress
EDITS = 18,
/// Declare entities types
/// {size_t(index), vec3(size), vec3(scale)} reliable
/// TODO: zstd<chunk rle>
ENTITY_TYPES = 20,
/// Update entities instances position and velocity
/// {size_t(entity), size_t(count), {size_t(index), ifvec3(pos), vec3(velocity)}[]}[] notify
ENTITIES = 21,
/// World compression dictionary
/// zstd dict reliable
COMPRESSION = 24,
/// Server capabilities
/// uint16_t(loadDistance), MAYBE: more reliable
CAPABILITIES = 25,
/// Public chat message
/// char[] (not null terminated) reliable
MESSAGE = 29,
};
enum class client_packet_type: enet_uint8 {
/// Interact with voxels
/// actions::FillShape reliable
FILL_SHAPE = 0,
/// Request missing chunks
/// area_id, chunk_pos[] reliable
MISSING_CHUNKS = 8,
/// Send public text message
/// char[] (not null terminated) reliable
MESSAGE = 9,
/// 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();
}
}