1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
5 #include "../app/init.hpp"
6 #include "../geometry/distance.hpp"
7 #include "../io/WorldSave.hpp"
8 #include "../model/Model.hpp"
9 #include "../shared/CommandService.hpp"
10 #include "../world/ChunkIndex.hpp"
11 #include "../world/Entity.hpp"
12 #include "../world/World.hpp"
17 #include <glm/gtx/io.hpp>
25 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
28 , buffer_size(Chunk::BlockSize() + 10)
29 , buffer(new uint8_t[buffer_size])
31 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
42 ChunkTransmitter::~ChunkTransmitter() {
46 bool ChunkTransmitter::Idle() const noexcept {
47 return !Transmitting() && !Waiting();
50 bool ChunkTransmitter::Transmitting() const noexcept {
51 return cursor < num_packets;
54 void ChunkTransmitter::Transmit() {
55 if (cursor < num_packets) {
61 bool ChunkTransmitter::Waiting() const noexcept {
62 return confirm_wait > 0;
65 void ChunkTransmitter::Ack(uint16_t seq) {
69 if (seq == begin_packet) {
77 for (int i = 0, end = data_packets.size(); i < end; ++i) {
78 if (seq == data_packets[i]) {
89 void ChunkTransmitter::Nack(uint16_t seq) {
93 if (seq == begin_packet) {
97 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
98 if (seq == data_packets[i]) {
105 void ChunkTransmitter::Abort() {
106 if (!current) return;
111 data_packets.clear();
115 void ChunkTransmitter::Send(Chunk &chunk) {
116 // abort current chunk, if any
122 // load new chunk data
124 buffer_len = buffer_size;
125 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
126 // compression failed, send it uncompressed
127 buffer_len = Chunk::BlockSize();
128 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
132 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
133 data_packets.resize(num_packets, -1);
139 void ChunkTransmitter::SendBegin() {
140 uint32_t flags = compressed;
141 auto pack = conn.Prepare<Packet::ChunkBegin>();
142 pack.WriteTransmissionId(trans_id);
143 pack.WriteFlags(flags);
144 pack.WriteChunkCoords(current->Position());
145 pack.WriteDataSize(buffer_len);
146 if (begin_packet == -1) {
149 begin_packet = conn.Send();
152 void ChunkTransmitter::SendData(size_t i) {
153 int pos = i * packet_len;
154 int len = min(packet_len, buffer_len - pos);
155 const uint8_t *data = &buffer[pos];
157 auto pack = conn.Prepare<Packet::ChunkData>();
158 pack.WriteTransmissionId(trans_id);
159 pack.WriteDataOffset(pos);
160 pack.WriteDataSize(len);
161 pack.WriteData(data, len);
163 if (data_packets[i] == -1) {
166 data_packets[i] = conn.Send(Packet::ChunkData::GetSize(len));
169 void ChunkTransmitter::Release() {
177 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
181 , player_model(nullptr)
185 , entity_updates_skipped(0)
186 , player_update_state()
187 , player_update_pack(0)
188 , player_update_timer(1500)
193 , chunk_blocks_skipped(0) {
194 conn.SetHandler(this);
197 ClientConnection::~ClientConnection() {
201 void ClientConnection::Update(int dt) {
203 if (Disconnected()) {
212 if (conn.ShouldPing()) {
213 conn.SendPing(server.GetPacket(), server.GetSocket());
217 void ClientConnection::CheckEntities() {
218 auto global_iter = server.GetWorld().Entities().begin();
219 auto global_end = server.GetWorld().Entities().end();
220 auto local_iter = spawns.begin();
221 auto local_end = spawns.end();
223 while (global_iter != global_end && local_iter != local_end) {
224 if (global_iter->ID() == local_iter->entity->ID()) {
226 if (CanDespawn(*global_iter)) {
227 SendDespawn(*local_iter);
228 } else if (SendingUpdates()) {
230 QueueUpdate(*local_iter);
234 } else if (global_iter->ID() < local_iter->entity->ID()) {
235 // global entity was inserted
236 if (CanSpawn(*global_iter)) {
237 auto spawned = spawns.emplace(local_iter, *global_iter);
242 // global entity was removed
243 SendDespawn(*local_iter);
249 while (global_iter != global_end) {
250 if (CanSpawn(*global_iter)) {
251 spawns.emplace_back(*global_iter);
252 SendSpawn(spawns.back());
258 while (local_iter != local_end) {
259 SendDespawn(*local_iter);
264 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
271 ClientConnection::SpawnStatus::~SpawnStatus() {
275 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
277 &e != &PlayerEntity() &&
279 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
282 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
285 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
288 uint16_t ClientConnection::Send() {
289 return conn.Send(server.GetPacket(), server.GetSocket());
292 uint16_t ClientConnection::Send(size_t len) {
293 server.GetPacket().len = sizeof(Packet::Header) + len;
297 void ClientConnection::SendSpawn(SpawnStatus &status) {
298 // don't double spawn
299 if (status.spawn_pack != -1) return;
301 auto pack = Prepare<Packet::SpawnEntity>();
302 pack.WriteEntity(*status.entity);
303 status.spawn_pack = Send();
307 void ClientConnection::SendDespawn(SpawnStatus &status) {
308 // don't double despawn
309 if (status.despawn_pack != -1) return;
311 auto pack = Prepare<Packet::DespawnEntity>();
312 pack.WriteEntityID(status.entity->ID());
313 status.despawn_pack = Send();
317 bool ClientConnection::SendingUpdates() const noexcept {
318 return entity_updates_skipped >= NetStat().SuggestedPacketHold();
321 void ClientConnection::QueueUpdate(SpawnStatus &status) {
322 // don't send updates while spawn not ack'd or despawn sent
323 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
324 entity_updates.push_back(&status);
328 void ClientConnection::SendUpdates() {
329 if (!SendingUpdates()) {
330 entity_updates.clear();
331 ++entity_updates_skipped;
334 auto base = PlayerChunks().Base();
335 auto pack = Prepare<Packet::EntityUpdate>();
336 pack.WriteChunkBase(base);
338 for (SpawnStatus *status : entity_updates) {
339 pack.WriteEntity(*status->entity, base, entity_pos);
341 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
342 pack.WriteEntityCount(entity_pos);
343 Send(Packet::EntityUpdate::GetSize(entity_pos));
344 pack = Prepare<Packet::EntityUpdate>();
348 if (entity_pos > 0) {
349 pack.WriteEntityCount(entity_pos);
350 Send(Packet::EntityUpdate::GetSize(entity_pos));
352 entity_updates.clear();
353 entity_updates_skipped = 0;
356 void ClientConnection::CheckPlayerFix() {
357 // player_update_state's position holds the client's most recent prediction
358 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
359 float dist_squared = glm::length2(diff);
361 // if client's prediction is off by more than 1cm, send
362 // our (authoritative) state back so it can fix it
363 constexpr float fix_thresh = 0.0001f;
365 if (dist_squared > fix_thresh) {
366 auto pack = Prepare<Packet::PlayerCorrection>();
367 pack.WritePacketSeq(player_update_pack);
368 pack.WritePlayer(PlayerEntity());
375 struct QueueCompare {
376 explicit QueueCompare(const glm::ivec3 &base)
378 bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
379 const glm::ivec3 ld(left - base);
380 const glm::ivec3 rd(right - base);
382 ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
383 rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
385 const glm::ivec3 &base;
390 void ClientConnection::CheckChunkQueue() {
391 if (PlayerChunks().Base() != old_base) {
392 ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
393 ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
394 for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
395 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
396 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
397 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
398 chunk_queue.push_back(pos);
403 old_base = PlayerChunks().Base();
404 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
405 chunk_queue.erase(unique(chunk_queue.begin(), chunk_queue.end()), chunk_queue.end());
407 // don't push entity updates and chunk data in the same tick
408 if (chunk_blocks_skipped >= NetStat().SuggestedPacketHold() && !SendingUpdates()) {
409 ++chunk_blocks_skipped;
412 if (transmitter.Transmitting()) {
413 transmitter.Transmit();
414 chunk_blocks_skipped = 0;
417 if (transmitter.Idle()) {
419 constexpr int max = 64;
420 while (count < max && !chunk_queue.empty()) {
421 ExactLocation::Coarse pos = chunk_queue.front();
422 chunk_queue.pop_front();
423 if (PlayerChunks().InRange(pos)) {
424 Chunk *chunk = PlayerChunks().Get(pos);
426 transmitter.Send(*chunk);
427 chunk_blocks_skipped = 0;
430 chunk_queue.push_back(pos);
438 void ClientConnection::AttachPlayer(Player &player) {
440 input.reset(new DirectInput(server.GetWorld(), player, server));
441 PlayerEntity().Ref();
443 cli_ctx.reset(new NetworkCLIFeedback(player, *this));
445 old_base = PlayerChunks().Base();
446 ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
447 ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
448 for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
449 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
450 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
451 chunk_queue.push_back(pos);
455 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
456 // TODO: should the server do this?
457 if (HasPlayerModel()) {
458 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
461 string msg = "player \"" + player.Name() + "\" joined";
463 server.DistributeMessage(0, 0, msg);
466 void ClientConnection::DetachPlayer() {
467 if (!HasPlayer()) return;
468 string msg = "player \"" + input->GetPlayer().Name() + "\" left";
470 server.DistributeMessage(0, 0, msg);
472 server.GetWorldSave().Write(input->GetPlayer());
473 PlayerEntity().Kill();
474 PlayerEntity().UnRef();
482 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
485 m.Instantiate(PlayerEntity().GetModel());
489 bool ClientConnection::HasPlayerModel() const noexcept {
493 const Model &ClientConnection::GetPlayerModel() const noexcept {
494 return *player_model;
497 void ClientConnection::OnPacketReceived(uint16_t seq) {
498 if (transmitter.Waiting()) {
499 transmitter.Ack(seq);
501 if (!confirm_wait) return;
502 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
503 if (seq == iter->spawn_pack) {
504 iter->spawn_pack = -1;
508 if (seq == iter->despawn_pack) {
516 void ClientConnection::OnPacketLost(uint16_t seq) {
517 if (transmitter.Waiting()) {
518 transmitter.Nack(seq);
520 if (!confirm_wait) return;
521 for (SpawnStatus &status : spawns) {
522 if (seq == status.spawn_pack) {
523 status.spawn_pack = -1;
528 if (seq == status.despawn_pack) {
529 status.despawn_pack = -1;
537 void ClientConnection::On(const Packet::Login &pack) {
539 pack.ReadPlayerName(name);
541 Player *new_player = server.JoinPlayer(name);
545 AttachPlayer(*new_player);
546 cout << "accepted login from player \"" << name << '"' << endl;
547 auto response = Prepare<Packet::Join>();
548 response.WritePlayer(new_player->GetEntity());
549 response.WriteWorldName(server.GetWorld().Name());
551 // set up update tracking
552 player_update_state = new_player->GetEntity().GetState();
553 player_update_pack = pack.Seq();
554 player_update_timer.Reset();
555 player_update_timer.Start();
558 cout << "rejected login from player \"" << name << '"' << endl;
559 Prepare<Packet::Part>();
565 void ClientConnection::On(const Packet::Part &) {
569 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
570 if (!HasPlayer()) return;
571 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
572 bool overdue = player_update_timer.HitOnce();
573 player_update_timer.Reset();
574 if (pack_diff <= 0 && !overdue) {
575 // drop old packets if we have a fairly recent state
578 glm::vec3 movement(0.0f);
582 player_update_pack = pack.Seq();
583 pack.ReadPredictedState(player_update_state);
584 pack.ReadMovement(movement);
585 pack.ReadActions(new_actions);
588 // accept client's orientation as is
589 input->GetPlayer().GetEntity().Orientation(player_update_state.orient);
591 input->SetMovement(movement);
592 // rotate head to match client's "prediction"
593 input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
594 // select the given inventory slot
595 input->SelectInventory(slot);
597 // check if any actions have been started or stopped
598 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
599 input->StartPrimaryAction();
600 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
601 input->StopPrimaryAction();
603 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
604 input->StartSecondaryAction();
605 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
606 input->StopSecondaryAction();
608 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
609 input->StartTertiaryAction();
610 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
611 input->StopTertiaryAction();
613 old_actions = new_actions;
616 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
617 return HasPlayer() && PlayerChunks().InRange(pos);
620 void ClientConnection::On(const Packet::ChunkBegin &pack) {
622 pack.ReadChunkCoords(pos);
623 if (ChunkInRange(pos)) {
624 chunk_queue.push_front(pos);
628 void ClientConnection::On(const Packet::Message &pack) {
633 pack.ReadReferral(ref);
634 pack.ReadMessage(msg);
636 if (type == 1 && cli_ctx) {
637 server.DispatchMessage(*cli_ctx, msg);
641 uint16_t ClientConnection::SendMessage(uint8_t type, uint32_t from, const string &msg) {
642 auto pack = Prepare<Packet::Message>();
643 pack.WriteType(type);
644 pack.WriteReferral(from);
645 pack.WriteMessage(msg);
646 return Send(Packet::Message::GetSize(msg));
650 NetworkCLIFeedback::NetworkCLIFeedback(Player &p, ClientConnection &c)
656 void NetworkCLIFeedback::Error(const string &msg) {
657 conn.SendMessage(0, 0, msg);
660 void NetworkCLIFeedback::Message(const string &msg) {
661 conn.SendMessage(0, 0, msg);
664 void NetworkCLIFeedback::Broadcast(const string &msg) {
665 conn.GetServer().DistributeMessage(0, GetPlayer().GetEntity().ID(), msg);
669 // relying on {} zero intitialization for UDPpacket, because
670 // the type and number of fields is not well defined
671 #pragma GCC diagnostic push
672 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
674 const Config::Network &conf,
676 const World::Config &wc,
677 const WorldSave &save)
679 , serv_pack{ -1, nullptr, 0 }
680 , serv_set(SDLNet_AllocSocketSet(1))
683 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
685 , player_model(nullptr)
688 #pragma GCC diagnostic pop
690 throw NetError("SDLNet_AllocSocketSet");
693 serv_sock = SDLNet_UDP_Open(conf.port);
695 SDLNet_FreeSocketSet(serv_set);
696 throw NetError("SDLNet_UDP_Open");
699 if (SDLNet_UDP_AddSocket(serv_set, serv_sock) == -1) {
700 SDLNet_UDP_Close(serv_sock);
701 SDLNet_FreeSocketSet(serv_set);
702 throw NetError("SDLNet_UDP_AddSocket");
705 serv_pack.data = new Uint8[sizeof(Packet)];
706 serv_pack.maxlen = sizeof(Packet);
709 cmd_srv.reset(new CommandService(cli, conf.cmd_port));
714 for (ClientConnection &client : clients) {
715 client.Disconnected();
718 world.Chunks().UnregisterIndex(spawn_index);
719 delete[] serv_pack.data;
720 SDLNet_UDP_DelSocket(serv_set, serv_sock);
721 SDLNet_UDP_Close(serv_sock);
722 SDLNet_FreeSocketSet(serv_set);
726 void Server::Wait(int dt) noexcept {
727 SDLNet_CheckSockets(serv_set, dt);
733 bool Server::Ready() noexcept {
734 if (SDLNet_CheckSockets(serv_set, 0) > 0) {
737 return cmd_srv && cmd_srv->Ready();
740 void Server::Handle() {
741 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
743 HandlePacket(serv_pack);
744 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
747 // a boo boo happened
748 throw NetError("SDLNet_UDP_Recv");
755 void Server::HandlePacket(const UDPpacket &udp_pack) {
756 if (udp_pack.len < int(sizeof(Packet::Header))) {
757 // packet too small, drop
760 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
761 if (pack.header.tag != Packet::TAG) {
762 // mistagged packet, drop
766 ClientConnection &client = GetClient(udp_pack.address);
767 client.GetConnection().Received(udp_pack);
770 ClientConnection &Server::GetClient(const IPaddress &addr) {
771 for (ClientConnection &client : clients) {
772 if (client.Matches(addr)) {
776 clients.emplace_back(*this, addr);
777 if (HasPlayerModel()) {
778 clients.back().SetPlayerModel(GetPlayerModel());
780 return clients.back();
783 void Server::Update(int dt) {
784 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
786 if (client->Disconnected()) {
787 client = clients.erase(client);
797 void Server::SetPlayerModel(const Model &m) noexcept {
799 for (ClientConnection &client : clients) {
800 client.SetPlayerModel(m);
804 bool Server::HasPlayerModel() const noexcept {
808 const Model &Server::GetPlayerModel() const noexcept {
809 return *player_model;
812 Player *Server::JoinPlayer(const string &name) {
813 if (spawn_index.MissingChunks() > 0) {
816 Player *player = world.AddPlayer(name);
820 if (save.Exists(*player)) {
828 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
829 chunk.SetBlock(index, block);
830 // TODO: batch chunk changes
831 auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
832 pack.WriteChunkCoords(chunk.Position());
833 pack.WriteBlockCount(uint32_t(1));
834 pack.WriteIndex(index, 0);
835 pack.WriteBlock(chunk.BlockAt(index), 0);
836 GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
837 for (ClientConnection &client : clients) {
838 if (client.ChunkInRange(chunk.Position())) {
844 void Server::DispatchMessage(CLIContext &ctx, const string &msg) {
848 if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
849 cli.Execute(ctx, msg.substr(1));
851 DistributeMessage(1, ctx.GetPlayer().GetEntity().ID(), msg);
855 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
856 auto pack = Packet::Make<Packet::Message>(serv_pack);
857 pack.WriteType(type);
858 pack.WriteReferral(ref);
859 pack.WriteMessage(msg);
860 serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
864 void Server::SendAll() {
865 for (ClientConnection &client : clients) {
866 client.GetConnection().Send(serv_pack, serv_sock);