1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
5 #include "../app/init.hpp"
6 #include "../io/WorldSave.hpp"
7 #include "../model/Model.hpp"
8 #include "../world/ChunkIndex.hpp"
9 #include "../world/Entity.hpp"
10 #include "../world/World.hpp"
15 #include <glm/gtx/io.hpp>
23 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
26 , buffer_size(Chunk::BlockSize() + 10)
27 , buffer(new uint8_t[buffer_size])
29 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
40 ChunkTransmitter::~ChunkTransmitter() {
44 bool ChunkTransmitter::Idle() const noexcept {
45 return !Transmitting() && !Waiting();
48 bool ChunkTransmitter::Transmitting() const noexcept {
49 return cursor < num_packets;
52 void ChunkTransmitter::Transmit() {
53 if (cursor < num_packets) {
59 bool ChunkTransmitter::Waiting() const noexcept {
60 return confirm_wait > 0;
63 void ChunkTransmitter::Ack(uint16_t seq) {
67 if (seq == begin_packet) {
75 for (int i = 0, end = data_packets.size(); i < end; ++i) {
76 if (seq == data_packets[i]) {
87 void ChunkTransmitter::Nack(uint16_t seq) {
91 if (seq == begin_packet) {
95 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
96 if (seq == data_packets[i]) {
103 void ChunkTransmitter::Abort() {
104 if (!current) return;
109 data_packets.clear();
113 void ChunkTransmitter::Send(Chunk &chunk) {
114 // abort current chunk, if any
120 // load new chunk data
122 buffer_len = buffer_size;
123 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
124 // compression failed, send it uncompressed
125 buffer_len = Chunk::BlockSize();
126 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
130 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
131 data_packets.resize(num_packets, -1);
137 void ChunkTransmitter::SendBegin() {
138 uint32_t flags = compressed;
139 auto pack = conn.Prepare<Packet::ChunkBegin>();
140 pack.WriteTransmissionId(trans_id);
141 pack.WriteFlags(flags);
142 pack.WriteChunkCoords(current->Position());
143 pack.WriteDataSize(buffer_len);
144 if (begin_packet == -1) {
147 begin_packet = conn.Send();
150 void ChunkTransmitter::SendData(size_t i) {
151 int pos = i * packet_len;
152 int len = min(packet_len, buffer_len - pos);
153 const uint8_t *data = &buffer[pos];
155 auto pack = conn.Prepare<Packet::ChunkData>();
156 pack.WriteTransmissionId(trans_id);
157 pack.WriteDataOffset(pos);
158 pack.WriteDataSize(len);
159 pack.WriteData(data, len);
161 if (data_packets[i] == -1) {
164 data_packets[i] = conn.Send();
167 void ChunkTransmitter::Release() {
175 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
179 , player_model(nullptr)
183 , player_update_state()
184 , player_update_pack(0)
185 , player_update_timer(1500)
190 conn.SetHandler(this);
193 ClientConnection::~ClientConnection() {
197 void ClientConnection::Update(int dt) {
199 if (Disconnected()) {
204 auto global_iter = server.GetWorld().Entities().begin();
205 auto global_end = server.GetWorld().Entities().end();
206 auto local_iter = spawns.begin();
207 auto local_end = spawns.end();
209 while (global_iter != global_end && local_iter != local_end) {
210 if (global_iter->ID() == local_iter->entity->ID()) {
212 if (CanDespawn(*global_iter)) {
213 SendDespawn(*local_iter);
216 QueueUpdate(*local_iter);
220 } else if (global_iter->ID() < local_iter->entity->ID()) {
221 // global entity was inserted
222 if (CanSpawn(*global_iter)) {
223 auto spawned = spawns.emplace(local_iter, *global_iter);
228 // global entity was removed
229 SendDespawn(*local_iter);
235 while (global_iter != global_end) {
236 if (CanSpawn(*global_iter)) {
237 spawns.emplace_back(*global_iter);
238 SendSpawn(spawns.back());
244 while (local_iter != local_end) {
245 SendDespawn(*local_iter);
253 if (conn.ShouldPing()) {
254 conn.SendPing(server.GetPacket(), server.GetSocket());
258 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
265 ClientConnection::SpawnStatus::~SpawnStatus() {
269 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
271 &e != &PlayerEntity() &&
273 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
276 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
279 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
282 uint16_t ClientConnection::Send() {
283 return conn.Send(server.GetPacket(), server.GetSocket());
286 uint16_t ClientConnection::Send(size_t len) {
287 server.GetPacket().len = sizeof(Packet::Header) + len;
291 void ClientConnection::SendSpawn(SpawnStatus &status) {
292 // don't double spawn
293 if (status.spawn_pack != -1) return;
295 auto pack = Prepare<Packet::SpawnEntity>();
296 pack.WriteEntity(*status.entity);
297 status.spawn_pack = Send();
301 void ClientConnection::SendDespawn(SpawnStatus &status) {
302 // don't double despawn
303 if (status.despawn_pack != -1) return;
305 auto pack = Prepare<Packet::DespawnEntity>();
306 pack.WriteEntityID(status.entity->ID());
307 status.despawn_pack = Send();
311 void ClientConnection::QueueUpdate(SpawnStatus &status) {
312 // don't send updates while spawn not ack'd or despawn sent
313 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
314 entity_updates.push_back(&status);
318 void ClientConnection::SendUpdates() {
319 auto base = PlayerChunks().Base();
320 auto pack = Prepare<Packet::EntityUpdate>();
321 pack.WriteChunkBase(base);
323 for (SpawnStatus *status : entity_updates) {
324 pack.WriteEntity(*status->entity, base, entity_pos);
326 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
327 pack.WriteEntityCount(entity_pos);
328 Send(Packet::EntityUpdate::GetSize(entity_pos));
329 pack = Prepare<Packet::EntityUpdate>();
333 if (entity_pos > 0) {
334 pack.WriteEntityCount(entity_pos);
335 Send(Packet::EntityUpdate::GetSize(entity_pos));
337 entity_updates.clear();
340 void ClientConnection::CheckPlayerFix() {
341 // player_update_state's position holds the client's most recent prediction
342 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
343 float dist_squared = dot(diff, diff);
345 // if client's prediction is off by more than 1cm, send
346 // our (authoritative) state back so it can fix it
347 constexpr float fix_thresh = 0.0001f;
349 if (dist_squared > fix_thresh) {
350 auto pack = Prepare<Packet::PlayerCorrection>();
351 pack.WritePacketSeq(player_update_pack);
352 pack.WritePlayer(PlayerEntity());
359 struct QueueCompare {
360 explicit QueueCompare(const glm::ivec3 &base)
362 bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
363 const glm::ivec3 ld(left - base);
364 const glm::ivec3 rd(right - base);
366 ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
367 rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
369 const glm::ivec3 &base;
374 void ClientConnection::CheckChunkQueue() {
375 if (PlayerChunks().Base() != old_base) {
376 Chunk::Pos begin = PlayerChunks().CoordsBegin();
377 Chunk::Pos end = PlayerChunks().CoordsEnd();
378 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
379 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
380 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
381 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
382 chunk_queue.push_back(pos);
387 old_base = PlayerChunks().Base();
388 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
390 if (transmitter.Transmitting()) {
391 transmitter.Transmit();
394 if (transmitter.Idle()) {
396 constexpr int max = 64;
397 while (count < max && !chunk_queue.empty()) {
398 Chunk::Pos pos = chunk_queue.front();
399 chunk_queue.pop_front();
400 if (PlayerChunks().InRange(pos)) {
401 Chunk *chunk = PlayerChunks().Get(pos);
403 transmitter.Send(*chunk);
406 chunk_queue.push_back(pos);
414 void ClientConnection::AttachPlayer(Player &player) {
416 input.reset(new DirectInput(server.GetWorld(), player, server));
417 PlayerEntity().Ref();
419 old_base = PlayerChunks().Base();
420 Chunk::Pos begin = PlayerChunks().CoordsBegin();
421 Chunk::Pos end = PlayerChunks().CoordsEnd();
422 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
423 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
424 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
425 chunk_queue.push_back(pos);
429 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
430 // TODO: should the server do this?
431 if (HasPlayerModel()) {
432 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
435 string msg = "player \"" + player.Name() + "\" joined";
437 server.DistributeMessage(0, 0, msg);
440 void ClientConnection::DetachPlayer() {
441 if (!HasPlayer()) return;
442 string msg = "player \"" + input->GetPlayer().Name() + "\" left";
444 server.DistributeMessage(0, 0, msg);
446 server.GetWorldSave().Write(input->GetPlayer());
447 PlayerEntity().Kill();
448 PlayerEntity().UnRef();
455 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
458 m.Instantiate(PlayerEntity().GetModel());
462 bool ClientConnection::HasPlayerModel() const noexcept {
466 const Model &ClientConnection::GetPlayerModel() const noexcept {
467 return *player_model;
470 void ClientConnection::OnPacketReceived(uint16_t seq) {
471 if (transmitter.Waiting()) {
472 transmitter.Ack(seq);
474 if (!confirm_wait) return;
475 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
476 if (seq == iter->spawn_pack) {
477 iter->spawn_pack = -1;
481 if (seq == iter->despawn_pack) {
489 void ClientConnection::OnPacketLost(uint16_t seq) {
490 if (transmitter.Waiting()) {
491 transmitter.Nack(seq);
493 if (!confirm_wait) return;
494 for (SpawnStatus &status : spawns) {
495 if (seq == status.spawn_pack) {
496 status.spawn_pack = -1;
501 if (seq == status.despawn_pack) {
502 status.despawn_pack = -1;
510 void ClientConnection::On(const Packet::Login &pack) {
512 pack.ReadPlayerName(name);
514 Player *new_player = server.JoinPlayer(name);
518 AttachPlayer(*new_player);
519 cout << "accepted login from player \"" << name << '"' << endl;
520 auto response = Prepare<Packet::Join>();
521 response.WritePlayer(new_player->GetEntity());
522 response.WriteWorldName(server.GetWorld().Name());
524 // set up update tracking
525 player_update_state = new_player->GetEntity().GetState();
526 player_update_pack = pack.Seq();
527 player_update_timer.Reset();
528 player_update_timer.Start();
531 cout << "rejected login from player \"" << name << '"' << endl;
532 Prepare<Packet::Part>();
538 void ClientConnection::On(const Packet::Part &) {
542 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
543 if (!HasPlayer()) return;
544 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
545 bool overdue = player_update_timer.HitOnce();
546 player_update_timer.Reset();
547 if (pack_diff <= 0 && !overdue) {
548 // drop old packets if we have a fairly recent state
551 glm::vec3 movement(0.0f);
555 player_update_pack = pack.Seq();
556 pack.ReadPredictedState(player_update_state);
557 pack.ReadMovement(movement);
558 pack.ReadActions(new_actions);
561 input->SetMovement(movement);
562 input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
563 input->SelectInventory(slot);
565 if ((new_actions & 0x01) && !(old_actions & 0x01)) {
566 input->StartPrimaryAction();
567 } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
568 input->StopPrimaryAction();
570 if ((new_actions & 0x02) && !(old_actions & 0x02)) {
571 input->StartSecondaryAction();
572 } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
573 input->StopSecondaryAction();
575 if ((new_actions & 0x04) && !(old_actions & 0x04)) {
576 input->StartTertiaryAction();
577 } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
578 input->StopTertiaryAction();
580 old_actions = new_actions;
583 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
584 return HasPlayer() && PlayerChunks().InRange(pos);
587 void ClientConnection::On(const Packet::Message &pack) {
592 pack.ReadReferral(ref);
593 pack.ReadMessage(msg);
595 if (type == 1 && HasPlayer()) {
596 server.DispatchMessage(input->GetPlayer(), msg);
602 const Config::Network &conf,
604 const World::Config &wc,
605 const WorldSave &save)
607 , serv_pack{ -1, nullptr, 0 }
610 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
612 , player_model(nullptr)
614 serv_sock = SDLNet_UDP_Open(conf.port);
616 throw NetError("SDLNet_UDP_Open");
619 serv_pack.data = new Uint8[sizeof(Packet)];
620 serv_pack.maxlen = sizeof(Packet);
624 world.Chunks().UnregisterIndex(spawn_index);
625 delete[] serv_pack.data;
626 SDLNet_UDP_Close(serv_sock);
630 void Server::Handle() {
631 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
633 HandlePacket(serv_pack);
634 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
637 // a boo boo happened
638 throw NetError("SDLNet_UDP_Recv");
642 void Server::HandlePacket(const UDPpacket &udp_pack) {
643 if (udp_pack.len < int(sizeof(Packet::Header))) {
644 // packet too small, drop
647 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
648 if (pack.header.tag != Packet::TAG) {
649 // mistagged packet, drop
653 ClientConnection &client = GetClient(udp_pack.address);
654 client.GetConnection().Received(udp_pack);
657 ClientConnection &Server::GetClient(const IPaddress &addr) {
658 for (ClientConnection &client : clients) {
659 if (client.Matches(addr)) {
663 clients.emplace_back(*this, addr);
664 if (HasPlayerModel()) {
665 clients.back().SetPlayerModel(GetPlayerModel());
667 return clients.back();
670 void Server::Update(int dt) {
671 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
673 if (client->Disconnected()) {
674 client = clients.erase(client);
681 void Server::SetPlayerModel(const Model &m) noexcept {
683 for (ClientConnection &client : clients) {
684 client.SetPlayerModel(m);
688 bool Server::HasPlayerModel() const noexcept {
692 const Model &Server::GetPlayerModel() const noexcept {
693 return *player_model;
696 Player *Server::JoinPlayer(const string &name) {
697 if (spawn_index.MissingChunks() > 0) {
700 Player *player = world.AddPlayer(name);
704 if (save.Exists(*player)) {
712 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
713 chunk.SetBlock(index, block);
714 // TODO: batch chunk changes
715 auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
716 pack.WriteChunkCoords(chunk.Position());
717 pack.WriteBlockCount(uint32_t(1));
718 pack.WriteIndex(index, 0);
719 pack.WriteBlock(chunk.BlockAt(index), 0);
720 GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
721 for (ClientConnection &client : clients) {
722 if (client.ChunkInRange(chunk.Position())) {
728 void Server::DispatchMessage(Player &player, const string &msg) {
732 if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
733 cli.Execute(player, msg.substr(1));
735 DistributeMessage(1, player.GetEntity().ID(), msg);
739 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
740 auto pack = Packet::Make<Packet::Message>(serv_pack);
741 pack.WriteType(type);
742 pack.WriteReferral(ref);
743 pack.WriteMessage(msg);
744 serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
748 void Server::SendAll() {
749 for (ClientConnection &client : clients) {
750 client.GetConnection().Send(serv_pack, serv_sock);