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 "../world/ChunkIndex.hpp"
10 #include "../world/Entity.hpp"
11 #include "../world/World.hpp"
16 #include <glm/gtx/io.hpp>
24 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
27 , buffer_size(Chunk::BlockSize() + 10)
28 , buffer(new uint8_t[buffer_size])
30 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
41 ChunkTransmitter::~ChunkTransmitter() {
45 bool ChunkTransmitter::Idle() const noexcept {
46 return !Transmitting() && !Waiting();
49 bool ChunkTransmitter::Transmitting() const noexcept {
50 return cursor < num_packets;
53 void ChunkTransmitter::Transmit() {
54 if (cursor < num_packets) {
60 bool ChunkTransmitter::Waiting() const noexcept {
61 return confirm_wait > 0;
64 void ChunkTransmitter::Ack(uint16_t seq) {
68 if (seq == begin_packet) {
76 for (int i = 0, end = data_packets.size(); i < end; ++i) {
77 if (seq == data_packets[i]) {
88 void ChunkTransmitter::Nack(uint16_t seq) {
92 if (seq == begin_packet) {
96 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
97 if (seq == data_packets[i]) {
104 void ChunkTransmitter::Abort() {
105 if (!current) return;
110 data_packets.clear();
114 void ChunkTransmitter::Send(Chunk &chunk) {
115 // abort current chunk, if any
121 // load new chunk data
123 buffer_len = buffer_size;
124 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
125 // compression failed, send it uncompressed
126 buffer_len = Chunk::BlockSize();
127 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
131 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
132 data_packets.resize(num_packets, -1);
138 void ChunkTransmitter::SendBegin() {
139 uint32_t flags = compressed;
140 auto pack = conn.Prepare<Packet::ChunkBegin>();
141 pack.WriteTransmissionId(trans_id);
142 pack.WriteFlags(flags);
143 pack.WriteChunkCoords(current->Position());
144 pack.WriteDataSize(buffer_len);
145 if (begin_packet == -1) {
148 begin_packet = conn.Send();
151 void ChunkTransmitter::SendData(size_t i) {
152 int pos = i * packet_len;
153 int len = min(packet_len, buffer_len - pos);
154 const uint8_t *data = &buffer[pos];
156 auto pack = conn.Prepare<Packet::ChunkData>();
157 pack.WriteTransmissionId(trans_id);
158 pack.WriteDataOffset(pos);
159 pack.WriteDataSize(len);
160 pack.WriteData(data, len);
162 if (data_packets[i] == -1) {
165 data_packets[i] = conn.Send();
168 void ChunkTransmitter::Release() {
176 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
180 , player_model(nullptr)
184 , entity_updates_skipped(0)
185 , player_update_state()
186 , player_update_pack(0)
187 , player_update_timer(1500)
192 conn.SetHandler(this);
195 ClientConnection::~ClientConnection() {
199 void ClientConnection::Update(int dt) {
201 if (Disconnected()) {
206 auto global_iter = server.GetWorld().Entities().begin();
207 auto global_end = server.GetWorld().Entities().end();
208 auto local_iter = spawns.begin();
209 auto local_end = spawns.end();
211 while (global_iter != global_end && local_iter != local_end) {
212 if (global_iter->ID() == local_iter->entity->ID()) {
214 if (CanDespawn(*global_iter)) {
215 SendDespawn(*local_iter);
216 } else if (SendingUpdates()) {
218 QueueUpdate(*local_iter);
222 } else if (global_iter->ID() < local_iter->entity->ID()) {
223 // global entity was inserted
224 if (CanSpawn(*global_iter)) {
225 auto spawned = spawns.emplace(local_iter, *global_iter);
230 // global entity was removed
231 SendDespawn(*local_iter);
237 while (global_iter != global_end) {
238 if (CanSpawn(*global_iter)) {
239 spawns.emplace_back(*global_iter);
240 SendSpawn(spawns.back());
246 while (local_iter != local_end) {
247 SendDespawn(*local_iter);
255 if (conn.ShouldPing()) {
256 conn.SendPing(server.GetPacket(), server.GetSocket());
260 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
267 ClientConnection::SpawnStatus::~SpawnStatus() {
271 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
273 &e != &PlayerEntity() &&
275 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
278 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
281 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
284 uint16_t ClientConnection::Send() {
285 return conn.Send(server.GetPacket(), server.GetSocket());
288 uint16_t ClientConnection::Send(size_t len) {
289 server.GetPacket().len = sizeof(Packet::Header) + len;
293 void ClientConnection::SendSpawn(SpawnStatus &status) {
294 // don't double spawn
295 if (status.spawn_pack != -1) return;
297 auto pack = Prepare<Packet::SpawnEntity>();
298 pack.WriteEntity(*status.entity);
299 status.spawn_pack = Send();
303 void ClientConnection::SendDespawn(SpawnStatus &status) {
304 // don't double despawn
305 if (status.despawn_pack != -1) return;
307 auto pack = Prepare<Packet::DespawnEntity>();
308 pack.WriteEntityID(status.entity->ID());
309 status.despawn_pack = Send();
313 bool ClientConnection::SendingUpdates() const noexcept {
314 return entity_updates_skipped >= NetStat().SuggestedPacketSkip();
317 void ClientConnection::QueueUpdate(SpawnStatus &status) {
318 // don't send updates while spawn not ack'd or despawn sent
319 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
320 entity_updates.push_back(&status);
324 void ClientConnection::SendUpdates() {
325 if (!SendingUpdates()) {
326 entity_updates.clear();
327 ++entity_updates_skipped;
330 auto base = PlayerChunks().Base();
331 auto pack = Prepare<Packet::EntityUpdate>();
332 pack.WriteChunkBase(base);
334 for (SpawnStatus *status : entity_updates) {
335 pack.WriteEntity(*status->entity, base, entity_pos);
337 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
338 pack.WriteEntityCount(entity_pos);
339 Send(Packet::EntityUpdate::GetSize(entity_pos));
340 pack = Prepare<Packet::EntityUpdate>();
344 if (entity_pos > 0) {
345 pack.WriteEntityCount(entity_pos);
346 Send(Packet::EntityUpdate::GetSize(entity_pos));
348 entity_updates.clear();
349 entity_updates_skipped = 0;
352 void ClientConnection::CheckPlayerFix() {
353 // player_update_state's position holds the client's most recent prediction
354 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
355 float dist_squared = dot(diff, diff);
357 // if client's prediction is off by more than 1cm, send
358 // our (authoritative) state back so it can fix it
359 constexpr float fix_thresh = 0.0001f;
361 if (dist_squared > fix_thresh) {
362 auto pack = Prepare<Packet::PlayerCorrection>();
363 pack.WritePacketSeq(player_update_pack);
364 pack.WritePlayer(PlayerEntity());
371 struct QueueCompare {
372 explicit QueueCompare(const glm::ivec3 &base)
374 bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
375 const glm::ivec3 ld(left - base);
376 const glm::ivec3 rd(right - base);
378 ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
379 rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
381 const glm::ivec3 &base;
386 void ClientConnection::CheckChunkQueue() {
387 if (PlayerChunks().Base() != old_base) {
388 Chunk::Pos begin = PlayerChunks().CoordsBegin();
389 Chunk::Pos end = PlayerChunks().CoordsEnd();
390 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
391 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
392 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
393 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
394 chunk_queue.push_back(pos);
399 old_base = PlayerChunks().Base();
400 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
402 // if we have packet skip enabled and just pushed an entity
403 // update, don't also send chunk data
404 if (NetStat().SuggestedPacketSkip() > 0 && entity_updates_skipped == 0) {
407 if (transmitter.Transmitting()) {
408 transmitter.Transmit();
411 if (transmitter.Idle()) {
413 constexpr int max = 64;
414 while (count < max && !chunk_queue.empty()) {
415 Chunk::Pos pos = chunk_queue.front();
416 chunk_queue.pop_front();
417 if (PlayerChunks().InRange(pos)) {
418 Chunk *chunk = PlayerChunks().Get(pos);
420 transmitter.Send(*chunk);
423 chunk_queue.push_back(pos);
431 void ClientConnection::AttachPlayer(Player &player) {
433 input.reset(new DirectInput(server.GetWorld(), player, server));
434 PlayerEntity().Ref();
436 old_base = PlayerChunks().Base();
437 Chunk::Pos begin = PlayerChunks().CoordsBegin();
438 Chunk::Pos end = PlayerChunks().CoordsEnd();
439 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
440 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
441 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
442 chunk_queue.push_back(pos);
446 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
447 // TODO: should the server do this?
448 if (HasPlayerModel()) {
449 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
452 string msg = "player \"" + player.Name() + "\" joined";
454 server.DistributeMessage(0, 0, msg);
457 void ClientConnection::DetachPlayer() {
458 if (!HasPlayer()) return;
459 string msg = "player \"" + input->GetPlayer().Name() + "\" left";
461 server.DistributeMessage(0, 0, msg);
463 server.GetWorldSave().Write(input->GetPlayer());
464 PlayerEntity().Kill();
465 PlayerEntity().UnRef();
472 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
475 m.Instantiate(PlayerEntity().GetModel());
479 bool ClientConnection::HasPlayerModel() const noexcept {
483 const Model &ClientConnection::GetPlayerModel() const noexcept {
484 return *player_model;
487 void ClientConnection::OnPacketReceived(uint16_t seq) {
488 if (transmitter.Waiting()) {
489 transmitter.Ack(seq);
491 if (!confirm_wait) return;
492 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
493 if (seq == iter->spawn_pack) {
494 iter->spawn_pack = -1;
498 if (seq == iter->despawn_pack) {
506 void ClientConnection::OnPacketLost(uint16_t seq) {
507 if (transmitter.Waiting()) {
508 transmitter.Nack(seq);
510 if (!confirm_wait) return;
511 for (SpawnStatus &status : spawns) {
512 if (seq == status.spawn_pack) {
513 status.spawn_pack = -1;
518 if (seq == status.despawn_pack) {
519 status.despawn_pack = -1;
527 void ClientConnection::On(const Packet::Login &pack) {
529 pack.ReadPlayerName(name);
531 Player *new_player = server.JoinPlayer(name);
535 AttachPlayer(*new_player);
536 cout << "accepted login from player \"" << name << '"' << endl;
537 auto response = Prepare<Packet::Join>();
538 response.WritePlayer(new_player->GetEntity());
539 response.WriteWorldName(server.GetWorld().Name());
541 // set up update tracking
542 player_update_state = new_player->GetEntity().GetState();
543 player_update_pack = pack.Seq();
544 player_update_timer.Reset();
545 player_update_timer.Start();
548 cout << "rejected login from player \"" << name << '"' << endl;
549 Prepare<Packet::Part>();
555 void ClientConnection::On(const Packet::Part &) {
559 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
560 if (!HasPlayer()) return;
561 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
562 bool overdue = player_update_timer.HitOnce();
563 player_update_timer.Reset();
564 if (pack_diff <= 0 && !overdue) {
565 // drop old packets if we have a fairly recent state
568 glm::vec3 movement(0.0f);
572 player_update_pack = pack.Seq();
573 pack.ReadPredictedState(player_update_state);
574 pack.ReadMovement(movement);
575 pack.ReadActions(new_actions);
578 input->SetMovement(movement);
579 input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
580 input->SelectInventory(slot);
582 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
583 input->StartPrimaryAction();
584 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
585 input->StopPrimaryAction();
587 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
588 input->StartSecondaryAction();
589 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
590 input->StopSecondaryAction();
592 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
593 input->StartTertiaryAction();
594 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
595 input->StopTertiaryAction();
597 old_actions = new_actions;
600 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
601 return HasPlayer() && PlayerChunks().InRange(pos);
604 void ClientConnection::On(const Packet::Message &pack) {
609 pack.ReadReferral(ref);
610 pack.ReadMessage(msg);
612 if (type == 1 && HasPlayer()) {
613 server.DispatchMessage(input->GetPlayer(), msg);
619 const Config::Network &conf,
621 const World::Config &wc,
622 const WorldSave &save)
624 , serv_pack{ -1, nullptr, 0 }
627 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
629 , player_model(nullptr)
631 serv_sock = SDLNet_UDP_Open(conf.port);
633 throw NetError("SDLNet_UDP_Open");
636 serv_pack.data = new Uint8[sizeof(Packet)];
637 serv_pack.maxlen = sizeof(Packet);
641 world.Chunks().UnregisterIndex(spawn_index);
642 delete[] serv_pack.data;
643 SDLNet_UDP_Close(serv_sock);
647 void Server::Handle() {
648 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
650 HandlePacket(serv_pack);
651 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
654 // a boo boo happened
655 throw NetError("SDLNet_UDP_Recv");
659 void Server::HandlePacket(const UDPpacket &udp_pack) {
660 if (udp_pack.len < int(sizeof(Packet::Header))) {
661 // packet too small, drop
664 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
665 if (pack.header.tag != Packet::TAG) {
666 // mistagged packet, drop
670 ClientConnection &client = GetClient(udp_pack.address);
671 client.GetConnection().Received(udp_pack);
674 ClientConnection &Server::GetClient(const IPaddress &addr) {
675 for (ClientConnection &client : clients) {
676 if (client.Matches(addr)) {
680 clients.emplace_back(*this, addr);
681 if (HasPlayerModel()) {
682 clients.back().SetPlayerModel(GetPlayerModel());
684 return clients.back();
687 void Server::Update(int dt) {
688 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
690 if (client->Disconnected()) {
691 client = clients.erase(client);
698 void Server::SetPlayerModel(const Model &m) noexcept {
700 for (ClientConnection &client : clients) {
701 client.SetPlayerModel(m);
705 bool Server::HasPlayerModel() const noexcept {
709 const Model &Server::GetPlayerModel() const noexcept {
710 return *player_model;
713 Player *Server::JoinPlayer(const string &name) {
714 if (spawn_index.MissingChunks() > 0) {
717 Player *player = world.AddPlayer(name);
721 if (save.Exists(*player)) {
729 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
730 chunk.SetBlock(index, block);
731 // TODO: batch chunk changes
732 auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
733 pack.WriteChunkCoords(chunk.Position());
734 pack.WriteBlockCount(uint32_t(1));
735 pack.WriteIndex(index, 0);
736 pack.WriteBlock(chunk.BlockAt(index), 0);
737 GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
738 for (ClientConnection &client : clients) {
739 if (client.ChunkInRange(chunk.Position())) {
745 void Server::DispatchMessage(Player &player, const string &msg) {
749 if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
750 cli.Execute(player, msg.substr(1));
752 DistributeMessage(1, player.GetEntity().ID(), msg);
756 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
757 auto pack = Packet::Make<Packet::Message>(serv_pack);
758 pack.WriteType(type);
759 pack.WriteReferral(ref);
760 pack.WriteMessage(msg);
761 serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
765 void Server::SendAll() {
766 for (ClientConnection &client : clients) {
767 client.GetConnection().Send(serv_pack, serv_sock);