2 #include "ClientConnection.hpp"
3 #include "Connection.hpp"
4 #include "ConnectionHandler.hpp"
9 #include "../app/init.hpp"
10 #include "../model/CompositeModel.hpp"
11 #include "../world/ChunkIndex.hpp"
12 #include "../world/Entity.hpp"
13 #include "../world/EntityState.hpp"
14 #include "../world/World.hpp"
18 #include <glm/gtx/io.hpp>
25 constexpr size_t Packet::Ping::MAX_LEN;
26 constexpr size_t Packet::Login::MAX_LEN;
27 constexpr size_t Packet::Join::MAX_LEN;
28 constexpr size_t Packet::Part::MAX_LEN;
29 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
30 constexpr size_t Packet::SpawnEntity::MAX_LEN;
31 constexpr size_t Packet::DespawnEntity::MAX_LEN;
32 constexpr size_t Packet::EntityUpdate::MAX_LEN;
33 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
34 constexpr size_t Packet::ChunkBegin::MAX_LEN;
35 constexpr size_t Packet::ChunkData::MAX_LEN;
39 UDPsocket client_bind(Uint16 port) {
40 UDPsocket sock = SDLNet_UDP_Open(port);
42 throw NetError("SDLNet_UDP_Open");
47 IPaddress client_resolve(const char *host, Uint16 port) {
49 if (SDLNet_ResolveHost(&addr, host, port) != 0) {
50 throw NetError("SDLNet_ResolveHost");
57 Client::Client(const Config &conf)
58 : conn(client_resolve(conf.host.c_str(), conf.port))
59 , client_sock(client_bind(0))
60 , client_pack{ -1, nullptr, 0 } {
61 client_pack.data = new Uint8[sizeof(Packet)];
62 client_pack.maxlen = sizeof(Packet);
63 // establish connection
68 delete[] client_pack.data;
69 SDLNet_UDP_Close(client_sock);
73 void Client::Handle() {
74 int result = SDLNet_UDP_Recv(client_sock, &client_pack);
76 HandlePacket(client_pack);
77 result = SDLNet_UDP_Recv(client_sock, &client_pack);
81 throw NetError("SDLNet_UDP_Recv");
85 void Client::HandlePacket(const UDPpacket &udp_pack) {
86 if (!conn.Matches(udp_pack.address)) {
87 // packet came from somewhere else, drop
90 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
91 if (pack.header.tag != Packet::TAG) {
92 // mistagged packet, drop
96 conn.Received(udp_pack);
99 void Client::Update(int dt) {
101 if (conn.ShouldPing()) {
106 uint16_t Client::SendPing() {
107 return conn.SendPing(client_pack, client_sock);
110 uint16_t Client::SendLogin(const string &name) {
111 auto pack = Packet::Make<Packet::Login>(client_pack);
112 pack.WritePlayerName(name);
113 return conn.Send(client_pack, client_sock);
116 uint16_t Client::SendPlayerUpdate(const Entity &player) {
117 auto pack = Packet::Make<Packet::PlayerUpdate>(client_pack);
118 pack.WritePlayer(player);
119 return conn.Send(client_pack, client_sock);
122 uint16_t Client::SendPart() {
123 Packet::Make<Packet::Part>(client_pack);
124 return conn.Send(client_pack, client_sock);
128 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
131 , player(nullptr, nullptr)
134 , player_update_state()
135 , player_update_pack(0)
136 , player_update_timer(1500)
140 conn.SetHandler(this);
143 ClientConnection::~ClientConnection() {
147 void ClientConnection::Update(int dt) {
149 if (Disconnected()) {
154 auto global_iter = server.GetWorld().Entities().begin();
155 auto global_end = server.GetWorld().Entities().end();
156 auto local_iter = spawns.begin();
157 auto local_end = spawns.end();
159 while (global_iter != global_end && local_iter != local_end) {
160 if (global_iter->ID() == local_iter->entity->ID()) {
162 if (CanDespawn(*global_iter)) {
163 SendDespawn(*local_iter);
166 SendUpdate(*local_iter);
170 } else if (global_iter->ID() < local_iter->entity->ID()) {
171 // global entity was inserted
172 if (CanSpawn(*global_iter)) {
173 auto spawned = spawns.emplace(local_iter, *global_iter);
178 // global entity was removed
179 SendDespawn(*local_iter);
185 while (global_iter != global_end) {
186 if (CanSpawn(*global_iter)) {
187 spawns.emplace_back(*global_iter);
188 SendSpawn(spawns.back());
194 while (local_iter != local_end) {
195 SendDespawn(*local_iter);
202 if (conn.ShouldPing()) {
203 conn.SendPing(server.GetPacket(), server.GetSocket());
207 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
214 ClientConnection::SpawnStatus::~SpawnStatus() {
218 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
220 &e != player.entity &&
222 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
225 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
228 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
231 uint16_t ClientConnection::Send() {
232 return conn.Send(server.GetPacket(), server.GetSocket());
235 uint16_t ClientConnection::Send(size_t len) {
236 server.GetPacket().len = len;
240 void ClientConnection::SendSpawn(SpawnStatus &status) {
241 // don't double spawn
242 if (status.spawn_pack != -1) return;
244 auto pack = Prepare<Packet::SpawnEntity>();
245 pack.WriteEntity(*status.entity);
246 status.spawn_pack = Send();
250 void ClientConnection::SendDespawn(SpawnStatus &status) {
251 // don't double despawn
252 if (status.despawn_pack != -1) return;
254 auto pack = Prepare<Packet::DespawnEntity>();
255 pack.WriteEntityID(status.entity->ID());
256 status.despawn_pack = Send();
260 void ClientConnection::SendUpdate(SpawnStatus &status) {
261 // don't send updates while spawn not ack'd or despawn sent
262 if (status.spawn_pack != -1 || status.despawn_pack != -1) return;
264 // TODO: pack entity updates
265 auto pack = Prepare<Packet::EntityUpdate>();
266 pack.WriteEntityCount(1);
267 pack.WriteEntity(*status.entity, 0);
268 Send(Packet::EntityUpdate::GetSize(1));
271 void ClientConnection::CheckPlayerFix() {
272 // player_update_state's position holds the client's most recent prediction
273 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
274 float dist_squared = dot(diff, diff);
276 // if client's prediction is off by more than 1cm, send
277 // our (authoritative) state back so it can fix it
278 constexpr float fix_thresh = 0.0001f;
280 if (dist_squared > fix_thresh) {
281 auto pack = Prepare<Packet::PlayerCorrection>();
282 pack.WritePacketSeq(player_update_pack);
283 pack.WritePlayer(PlayerEntity());
288 void ClientConnection::CheckChunkQueue() {
289 if (PlayerChunks().Base() != old_base) {
290 Chunk::Pos begin = PlayerChunks().CoordsBegin();
291 Chunk::Pos end = PlayerChunks().CoordsEnd();
292 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
293 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
294 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
295 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
296 chunk_queue.push_back(pos);
301 old_base = PlayerChunks().Base();
303 if (transmitter.Transmitting()) {
304 transmitter.Transmit();
307 if (transmitter.Idle()) {
309 constexpr int max = 64;
310 while (count < max && !chunk_queue.empty()) {
311 Chunk::Pos pos = chunk_queue.front();
312 chunk_queue.pop_front();
313 if (PlayerChunks().InRange(pos)) {
314 Chunk *chunk = PlayerChunks().Get(pos);
316 transmitter.Send(*chunk);
319 chunk_queue.push_back(pos);
327 void ClientConnection::AttachPlayer(const Player &new_player) {
330 player.entity->Ref();
332 old_base = player.chunks->Base();
333 Chunk::Pos begin = player.chunks->CoordsBegin();
334 Chunk::Pos end = player.chunks->CoordsEnd();
335 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
336 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
337 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
338 chunk_queue.push_back(pos);
343 cout << "player \"" << player.entity->Name() << "\" joined" << endl;
346 void ClientConnection::DetachPlayer() {
347 if (!HasPlayer()) return;
348 cout << "player \"" << player.entity->Name() << "\" left" << endl;
349 player.entity->Kill();
350 player.entity->UnRef();
351 player.entity = nullptr;
352 player.chunks = nullptr;
357 void ClientConnection::OnPacketReceived(uint16_t seq) {
358 if (transmitter.Waiting()) {
359 transmitter.Ack(seq);
361 if (!confirm_wait) return;
362 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
363 if (seq == iter->spawn_pack) {
364 iter->spawn_pack = -1;
368 if (seq == iter->despawn_pack) {
376 void ClientConnection::OnPacketLost(uint16_t seq) {
377 if (transmitter.Waiting()) {
378 transmitter.Nack(seq);
380 if (!confirm_wait) return;
381 for (SpawnStatus &status : spawns) {
382 if (seq == status.spawn_pack) {
383 status.spawn_pack = -1;
388 if (seq == status.despawn_pack) {
389 status.despawn_pack = -1;
397 void ClientConnection::On(const Packet::Login &pack) {
399 pack.ReadPlayerName(name);
401 Player new_player = server.GetWorld().AddPlayer(name);
403 if (new_player.entity) {
405 AttachPlayer(new_player);
406 cout << "accepted login from player \"" << name << '"' << endl;
407 auto response = Prepare<Packet::Join>();
408 response.WritePlayer(*new_player.entity);
409 response.WriteWorldName(server.GetWorld().Name());
411 // set up update tracking
412 player_update_state = new_player.entity->GetState();
413 player_update_pack = pack.Seq();
414 player_update_timer.Reset();
415 player_update_timer.Start();
418 cout << "rejected login from player \"" << name << '"' << endl;
419 Prepare<Packet::Part>();
425 void ClientConnection::On(const Packet::Part &) {
429 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
430 if (!HasPlayer()) return;
431 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
432 bool overdue = player_update_timer.HitOnce();
433 player_update_timer.Reset();
434 if (pack_diff > 0 || overdue) {
435 player_update_pack = pack.Seq();
436 pack.ReadPlayerState(player_update_state);
437 // accept velocity and orientation as "user input"
438 PlayerEntity().Velocity(player_update_state.velocity);
439 PlayerEntity().Orientation(player_update_state.orient);
444 Connection::Connection(const IPaddress &addr)
449 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
450 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
456 bool Connection::Matches(const IPaddress &remote) const noexcept {
457 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
460 void Connection::FlagSend() noexcept {
464 void Connection::FlagRecv() noexcept {
468 bool Connection::ShouldPing() const noexcept {
469 return !closed && send_timer.HitOnce();
472 bool Connection::TimedOut() const noexcept {
473 return recv_timer.HitOnce();
476 void Connection::Update(int dt) {
477 send_timer.Update(dt);
478 recv_timer.Update(dt);
482 Handler().OnTimeout();
488 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
489 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
490 pack.header.ctrl = ctrl_out;
491 uint16_t seq = ctrl_out.seq++;
493 udp_pack.address = addr;
494 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
495 throw NetError("SDLNet_UDP_Send");
502 void Connection::Received(const UDPpacket &udp_pack) {
503 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
506 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
511 ctrl_out.hist <<= diff;
512 ctrl_out.hist |= 1 << (diff - 1);
514 } else if (diff < 0 && diff >= -32) {
515 ctrl_out.hist |= 1 << (-diff - 1);
517 ctrl_out.ack = pack.header.ctrl.seq;
524 Packet::TControl ctrl_new = pack.header.ctrl;
525 Handler().Handle(udp_pack);
528 // if the packet holds more recent information
529 // check if remote failed to ack one of our packets
530 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
531 // should always be true, but you never know…
533 for (int i = 0; i < diff; ++i) {
534 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
535 Handler().OnPacketLost(ctrl_in.ack - 32 + i);
539 // check for newly ack'd packets
540 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
541 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
542 Handler().OnPacketReceived(s);
549 bool Packet::TControl::Acks(uint16_t s) const noexcept {
550 int16_t diff = int16_t(ack) - int16_t(s);
551 if (diff == 0) return true;
552 if (diff < 0 || diff > 32) return false;
553 return (hist & (1 << (diff - 1))) != 0;
556 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
557 Packet::Make<Packet::Ping>(udp_pack);
558 return Send(udp_pack, sock);
562 ostream &operator <<(ostream &out, const IPaddress &addr) {
563 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
565 << '.' << int(host[1])
566 << '.' << int(host[2])
567 << '.' << int(host[3]);
569 out << ':' << SDLNet_Read16(&addr.port);
575 const char *Packet::Type2String(uint8_t t) noexcept {
585 case PlayerUpdate::TYPE:
586 return "PlayerUpdate";
587 case SpawnEntity::TYPE:
588 return "SpawnEntity";
589 case DespawnEntity::TYPE:
590 return "DespawnEntity";
591 case EntityUpdate::TYPE:
592 return "EntityUpdate";
593 case PlayerCorrection::TYPE:
594 return "PlayerCorrection";
595 case ChunkBegin::TYPE:
597 case ChunkData::TYPE:
605 void Packet::Payload::Write(const T &src, size_t off) noexcept {
606 if ((length - off) < sizeof(T)) {
607 // dismiss out of bounds write
610 *reinterpret_cast<T *>(&data[off]) = src;
614 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
615 if ((length - off) < sizeof(T)) {
616 // dismiss out of bounds read
619 dst = *reinterpret_cast<T *>(&data[off]);
622 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
623 uint8_t *dst = &data[off];
624 size_t len = min(maxlen, length - off);
625 if (src.size() < len) {
626 memset(dst, '\0', len);
627 memcpy(dst, src.c_str(), src.size());
629 memcpy(dst, src.c_str(), len);
633 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
634 size_t len = min(maxlen, length - off);
637 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
638 dst.push_back(data[off + i]);
643 void Packet::Login::WritePlayerName(const string &name) noexcept {
644 WriteString(name, 0, 32);
647 void Packet::Login::ReadPlayerName(string &name) const noexcept {
648 ReadString(name, 0, 32);
651 void Packet::Join::WritePlayer(const Entity &player) noexcept {
652 Write(player.ID(), 0);
653 Write(player.GetState(), 4);
656 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
660 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
664 void Packet::Join::WriteWorldName(const string &name) noexcept {
665 WriteString(name, 68, 32);
668 void Packet::Join::ReadWorldName(string &name) const noexcept {
669 ReadString(name, 68, 32);
672 void Packet::PlayerUpdate::WritePlayer(const Entity &player) noexcept {
673 Write(player.GetState(), 0);
676 void Packet::PlayerUpdate::ReadPlayerState(EntityState &state) const noexcept {
680 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
683 Write(e.GetModel().GetModel().ID(), 4);
685 Write(uint32_t(0), 4);
687 Write(e.GetState(), 8);
688 Write(e.Bounds(), 72);
690 if (e.WorldCollidable()) {
694 WriteString(e.Name(), 100, 32);
697 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
701 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
705 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
714 ReadString(name, 100, 32);
718 e.WorldCollidable(flags & 1);
722 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
726 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
730 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
734 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
738 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
739 uint32_t off = 4 + (num * 64);
741 Write(entity.ID(), off);
742 Write(entity.GetState(), off + 4);
745 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
746 Read(id, 4 + (num * 64));
749 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
750 uint32_t off = 4 + (num * 64);
751 Read(state, off + 4);
754 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
758 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
762 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
763 Write(player.GetState(), 2);
766 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
770 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
774 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
778 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
782 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
786 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
790 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
794 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
798 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
802 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
806 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
810 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
814 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
818 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
822 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
826 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
827 size_t len = min(length - 12, l);
828 memcpy(&data[12], d, len);
831 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
832 size_t len = min(length - 12, l);
833 memcpy(d, &data[12], len);
837 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
838 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
839 switch (pack.Type()) {
840 case Packet::Ping::TYPE:
841 On(Packet::As<Packet::Ping>(udp_pack));
843 case Packet::Login::TYPE:
844 On(Packet::As<Packet::Login>(udp_pack));
846 case Packet::Join::TYPE:
847 On(Packet::As<Packet::Join>(udp_pack));
849 case Packet::Part::TYPE:
850 On(Packet::As<Packet::Part>(udp_pack));
852 case Packet::PlayerUpdate::TYPE:
853 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
855 case Packet::SpawnEntity::TYPE:
856 On(Packet::As<Packet::SpawnEntity>(udp_pack));
858 case Packet::DespawnEntity::TYPE:
859 On(Packet::As<Packet::DespawnEntity>(udp_pack));
861 case Packet::EntityUpdate::TYPE:
862 On(Packet::As<Packet::EntityUpdate>(udp_pack));
864 case Packet::PlayerCorrection::TYPE:
865 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
867 case Packet::ChunkBegin::TYPE:
868 On(Packet::As<Packet::ChunkBegin>(udp_pack));
870 case Packet::ChunkData::TYPE:
871 On(Packet::As<Packet::ChunkData>(udp_pack));
874 // drop unknown or unhandled packets
880 Server::Server(const Config &conf, World &world)
882 , serv_pack{ -1, nullptr, 0 }
885 serv_sock = SDLNet_UDP_Open(conf.port);
887 throw NetError("SDLNet_UDP_Open");
890 serv_pack.data = new Uint8[sizeof(Packet)];
891 serv_pack.maxlen = sizeof(Packet);
895 delete[] serv_pack.data;
896 SDLNet_UDP_Close(serv_sock);
900 void Server::Handle() {
901 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
903 HandlePacket(serv_pack);
904 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
907 // a boo boo happened
908 throw NetError("SDLNet_UDP_Recv");
912 void Server::HandlePacket(const UDPpacket &udp_pack) {
913 if (udp_pack.len < int(sizeof(Packet::Header))) {
914 // packet too small, drop
917 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
918 if (pack.header.tag != Packet::TAG) {
919 // mistagged packet, drop
923 ClientConnection &client = GetClient(udp_pack.address);
924 client.GetConnection().Received(udp_pack);
927 ClientConnection &Server::GetClient(const IPaddress &addr) {
928 for (ClientConnection &client : clients) {
929 if (client.Matches(addr)) {
933 clients.emplace_back(*this, addr);
934 return clients.back();
937 void Server::Update(int dt) {
938 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
940 if (client->Disconnected()) {
941 client = clients.erase(client);