-#include "Client.hpp"
-#include "ClientConnection.hpp"
#include "Connection.hpp"
#include "ConnectionHandler.hpp"
#include "io.hpp"
#include "Packet.hpp"
-#include "Server.hpp"
#include "../app/init.hpp"
#include "../model/CompositeModel.hpp"
#include "../world/Entity.hpp"
#include "../world/EntityState.hpp"
-#include "../world/World.hpp"
#include <cstring>
-#include <iostream>
-#include <glm/gtx/io.hpp>
using namespace std;
constexpr size_t Packet::DespawnEntity::MAX_LEN;
constexpr size_t Packet::EntityUpdate::MAX_LEN;
constexpr size_t Packet::PlayerCorrection::MAX_LEN;
-
-namespace {
-
-UDPsocket client_bind(Uint16 port) {
- UDPsocket sock = SDLNet_UDP_Open(port);
- if (!sock) {
- throw NetError("SDLNet_UDP_Open");
- }
- return sock;
-}
-
-IPaddress client_resolve(const char *host, Uint16 port) {
- IPaddress addr;
- if (SDLNet_ResolveHost(&addr, host, port) != 0) {
- throw NetError("SDLNet_ResolveHost");
- }
- return addr;
-}
-
-}
-
-Client::Client(const Config &conf)
-: conn(client_resolve(conf.host.c_str(), conf.port))
-, client_sock(client_bind(0))
-, client_pack{ -1, nullptr, 0 } {
- client_pack.data = new Uint8[sizeof(Packet)];
- client_pack.maxlen = sizeof(Packet);
- // establish connection
- SendPing();
-}
-
-Client::~Client() {
- delete[] client_pack.data;
- SDLNet_UDP_Close(client_sock);
-}
-
-
-void Client::Handle() {
- int result = SDLNet_UDP_Recv(client_sock, &client_pack);
- while (result > 0) {
- HandlePacket(client_pack);
- result = SDLNet_UDP_Recv(client_sock, &client_pack);
- }
- if (result == -1) {
- // a boo boo happened
- throw NetError("SDLNet_UDP_Recv");
- }
-}
-
-void Client::HandlePacket(const UDPpacket &udp_pack) {
- if (!conn.Matches(udp_pack.address)) {
- // packet came from somewhere else, drop
- return;
- }
- const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
- if (pack.header.tag != Packet::TAG) {
- // mistagged packet, drop
- return;
- }
-
- conn.Received(udp_pack);
-}
-
-void Client::Update(int dt) {
- conn.Update(dt);
- if (conn.ShouldPing()) {
- SendPing();
- }
-}
-
-uint16_t Client::SendPing() {
- return conn.SendPing(client_pack, client_sock);
-}
-
-uint16_t Client::SendLogin(const string &name) {
- auto pack = Packet::Make<Packet::Login>(client_pack);
- pack.WritePlayerName(name);
- return conn.Send(client_pack, client_sock);
-}
-
-uint16_t Client::SendPlayerUpdate(const Entity &player) {
- auto pack = Packet::Make<Packet::PlayerUpdate>(client_pack);
- pack.WritePlayer(player);
- return conn.Send(client_pack, client_sock);
-}
-
-uint16_t Client::SendPart() {
- Packet::Make<Packet::Part>(client_pack);
- return conn.Send(client_pack, client_sock);
-}
-
-
-ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
-: server(server)
-, conn(addr)
-, player(nullptr)
-, spawns()
-, confirm_wait(0)
-, player_update_pack(0)
-, player_update_timer(1500) {
- conn.SetHandler(this);
-}
-
-ClientConnection::~ClientConnection() {
- DetachPlayer();
-}
-
-void ClientConnection::Update(int dt) {
- conn.Update(dt);
- if (Disconnected()) {
- return;
- }
- if (HasPlayer()) {
- // sync entities
- auto global_iter = server.GetWorld().Entities().begin();
- auto global_end = server.GetWorld().Entities().end();
- auto local_iter = spawns.begin();
- auto local_end = spawns.end();
-
- while (global_iter != global_end && local_iter != local_end) {
- if (global_iter->ID() == local_iter->entity->ID()) {
- // they're the same
- if (CanDespawn(*global_iter)) {
- SendDespawn(*local_iter);
- } else {
- // update
- SendUpdate(*local_iter);
- }
- ++global_iter;
- ++local_iter;
- } else if (global_iter->ID() < local_iter->entity->ID()) {
- // global entity was inserted
- if (CanSpawn(*global_iter)) {
- auto spawned = spawns.emplace(local_iter, *global_iter);
- SendSpawn(*spawned);
- }
- ++global_iter;
- } else {
- // global entity was removed
- SendDespawn(*local_iter);
- ++local_iter;
- }
- }
-
- // leftover spawns
- while (global_iter != global_end) {
- if (CanSpawn(*global_iter)) {
- spawns.emplace_back(*global_iter);
- SendSpawn(spawns.back());
- }
- ++global_iter;
- }
-
- // leftover despawns
- while (local_iter != local_end) {
- SendDespawn(*local_iter);
- ++local_iter;
- }
-
- CheckPlayerFix();
- }
- if (conn.ShouldPing()) {
- conn.SendPing(server.GetPacket(), server.GetSocket());
- }
-}
-
-ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
-: entity(&e)
-, spawn_pack(-1)
-, despawn_pack(-1) {
- entity->Ref();
-}
-
-ClientConnection::SpawnStatus::~SpawnStatus() {
- entity->UnRef();
-}
-
-bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
- return
- &e != player &&
- !e.Dead() &&
- manhattan_radius(e.ChunkCoords() - Player().ChunkCoords()) < 7;
-}
-
-bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
- return
- e.Dead() ||
- manhattan_radius(e.ChunkCoords() - Player().ChunkCoords()) > 7;
-}
-
-void ClientConnection::SendSpawn(SpawnStatus &status) {
- // don't double spawn
- if (status.spawn_pack != -1) return;
-
- auto pack = Packet::Make<Packet::SpawnEntity>(server.GetPacket());
- pack.WriteEntity(*status.entity);
- status.spawn_pack = conn.Send(server.GetPacket(), server.GetSocket());
- ++confirm_wait;
-}
-
-void ClientConnection::SendDespawn(SpawnStatus &status) {
- // don't double despawn
- if (status.despawn_pack != -1) return;
-
- auto pack = Packet::Make<Packet::DespawnEntity>(server.GetPacket());
- pack.WriteEntityID(status.entity->ID());
- status.despawn_pack = conn.Send(server.GetPacket(), server.GetSocket());
- ++confirm_wait;
-}
-
-void ClientConnection::SendUpdate(SpawnStatus &status) {
- // don't send updates while spawn not ack'd or despawn sent
- if (status.spawn_pack != -1 || status.despawn_pack != -1) return;
-
- // TODO: pack entity updates
- auto pack = Packet::Make<Packet::EntityUpdate>(server.GetPacket());
- pack.WriteEntityCount(1);
- pack.WriteEntity(*status.entity, 0);
- server.GetPacket().len = Packet::EntityUpdate::GetSize(1);
- conn.Send(server.GetPacket(), server.GetSocket());
-}
-
-void ClientConnection::CheckPlayerFix() {
- // check always succeeds for now ;)
- auto pack = Packet::Make<Packet::PlayerCorrection>(server.GetPacket());
- pack.WritePacketSeq(player_update_pack);
- pack.WritePlayer(Player());
- conn.Send(server.GetPacket(), server.GetSocket());
-}
-
-void ClientConnection::AttachPlayer(Entity &new_player) {
- DetachPlayer();
- player = &new_player;
- player->Ref();
- cout << "player \"" << player->Name() << "\" joined" << endl;
-}
-
-void ClientConnection::DetachPlayer() {
- if (!player) return;
- player->Kill();
- player->UnRef();
- cout << "player \"" << player->Name() << "\" left" << endl;
- player = nullptr;
-}
-
-void ClientConnection::OnPacketReceived(uint16_t seq) {
- if (!confirm_wait) return;
- for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
- if (seq == iter->spawn_pack) {
- iter->spawn_pack = -1;
- --confirm_wait;
- return;
- }
- if (seq == iter->despawn_pack) {
- spawns.erase(iter);
- --confirm_wait;
- return;
- }
- }
-}
-
-void ClientConnection::OnPacketLost(uint16_t seq) {
- if (!confirm_wait) return;
- for (SpawnStatus &status : spawns) {
- if (seq == status.spawn_pack) {
- status.spawn_pack = -1;
- --confirm_wait;
- SendSpawn(status);
- return;
- }
- if (seq == status.despawn_pack) {
- status.despawn_pack = -1;
- --confirm_wait;
- SendDespawn(status);
- return;
- }
- }
-}
-
-void ClientConnection::On(const Packet::Login &pack) {
- string name;
- pack.ReadPlayerName(name);
-
- Entity *new_player = server.GetWorld().AddPlayer(name).entity;
-
- if (new_player) {
- // success!
- AttachPlayer(*new_player);
- cout << "accepted login from player \"" << name << '"' << endl;
- auto response = Packet::Make<Packet::Join>(server.GetPacket());
- response.WritePlayer(*new_player);
- response.WriteWorldName(server.GetWorld().Name());
- conn.Send(server.GetPacket(), server.GetSocket());
- // set up update tracking
- player_update_pack = pack.Seq();
- player_update_timer.Reset();
- player_update_timer.Start();
- } else {
- // aw no :(
- cout << "rejected login from player \"" << name << '"' << endl;
- Packet::Make<Packet::Part>(server.GetPacket());
- conn.Send(server.GetPacket(), server.GetSocket());
- conn.Close();
- }
-}
-
-void ClientConnection::On(const Packet::Part &) {
- conn.Close();
-}
-
-void ClientConnection::On(const Packet::PlayerUpdate &pack) {
- if (!HasPlayer()) return;
- int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
- bool overdue = player_update_timer.HitOnce();
- player_update_timer.Reset();
- if (pack_diff > 0 || overdue) {
- player_update_pack = pack.Seq();
- // TODO: do client input validation here
- EntityState new_state;
- pack.ReadPlayerState(new_state);
- Player().Velocity(new_state.velocity);
- Player().Orientation(new_state.orient);
- }
-}
-
+constexpr size_t Packet::ChunkBegin::MAX_LEN;
+constexpr size_t Packet::ChunkData::MAX_LEN;
Connection::Connection(const IPaddress &addr)
: handler(nullptr)
}
}
// check for newly ack'd packets
- for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); ++s) {
+ for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
Handler().OnPacketReceived(s);
}
return "EntityUpdate";
case PlayerCorrection::TYPE:
return "PlayerCorrection";
+ case ChunkBegin::TYPE:
+ return "ChunkBegin";
+ case ChunkData::TYPE:
+ return "ChunkData";
default:
return "Unknown";
}
Read(state, 2);
}
+void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
+ Write(id, 0);
+}
+
+void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
+ Read(id, 0);
+}
+
+void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
+ Write(f, 4);
+}
+
+void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
+ Read(f, 4);
+}
+
+void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
+ Write(pos, 8);
+}
+
+void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
+ Read(pos, 8);
+}
+
+void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
+ Write(s, 20);
+}
+
+void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
+ Read(s, 20);
+}
+
+void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
+ Write(id, 0);
+}
+
+void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
+ Read(id, 0);
+}
+
+void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
+ Write(o, 4);
+}
+
+void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
+ Read(o, 4);
+}
+
+void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
+ Write(s, 8);
+}
+
+void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
+ Read(s, 8);
+}
+
+void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
+ size_t len = min(length - 12, l);
+ memcpy(&data[12], d, len);
+}
+
+void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
+ size_t len = min(length - 12, l);
+ memcpy(d, &data[12], len);
+}
+
void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
case Packet::PlayerCorrection::TYPE:
On(Packet::As<Packet::PlayerCorrection>(udp_pack));
break;
+ case Packet::ChunkBegin::TYPE:
+ On(Packet::As<Packet::ChunkBegin>(udp_pack));
+ break;
+ case Packet::ChunkData::TYPE:
+ On(Packet::As<Packet::ChunkData>(udp_pack));
+ break;
default:
// drop unknown or unhandled packets
break;
}
}
-
-Server::Server(const Config &conf, World &world)
-: serv_sock(nullptr)
-, serv_pack{ -1, nullptr, 0 }
-, clients()
-, world(world) {
- serv_sock = SDLNet_UDP_Open(conf.port);
- if (!serv_sock) {
- throw NetError("SDLNet_UDP_Open");
- }
-
- serv_pack.data = new Uint8[sizeof(Packet)];
- serv_pack.maxlen = sizeof(Packet);
-}
-
-Server::~Server() {
- delete[] serv_pack.data;
- SDLNet_UDP_Close(serv_sock);
-}
-
-
-void Server::Handle() {
- int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
- while (result > 0) {
- HandlePacket(serv_pack);
- result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
- }
- if (result == -1) {
- // a boo boo happened
- throw NetError("SDLNet_UDP_Recv");
- }
-}
-
-void Server::HandlePacket(const UDPpacket &udp_pack) {
- if (udp_pack.len < int(sizeof(Packet::Header))) {
- // packet too small, drop
- return;
- }
- const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
- if (pack.header.tag != Packet::TAG) {
- // mistagged packet, drop
- return;
- }
-
- ClientConnection &client = GetClient(udp_pack.address);
- client.GetConnection().Received(udp_pack);
-}
-
-ClientConnection &Server::GetClient(const IPaddress &addr) {
- for (ClientConnection &client : clients) {
- if (client.Matches(addr)) {
- return client;
- }
- }
- clients.emplace_back(*this, addr);
- return clients.back();
-}
-
-void Server::Update(int dt) {
- for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
- client->Update(dt);
- if (client->Disconnected()) {
- client = clients.erase(client);
- } else {
- ++client;
- }
- }
-}
-
}