1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
5 #include "../app/init.hpp"
6 #include "../world/ChunkIndex.hpp"
7 #include "../world/Entity.hpp"
8 #include "../world/World.hpp"
19 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
22 , buffer_size(Chunk::BlockSize() + 10)
23 , buffer(new uint8_t[buffer_size])
25 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
36 ChunkTransmitter::~ChunkTransmitter() {
40 bool ChunkTransmitter::Idle() const noexcept {
41 return !Transmitting() && !Waiting();
44 bool ChunkTransmitter::Transmitting() const noexcept {
45 return cursor < num_packets;
48 void ChunkTransmitter::Transmit() {
49 if (cursor < num_packets) {
55 bool ChunkTransmitter::Waiting() const noexcept {
56 return confirm_wait > 0;
59 void ChunkTransmitter::Ack(uint16_t seq) {
63 if (seq == begin_packet) {
71 for (int i = 0, end = data_packets.size(); i < end; ++i) {
72 if (seq == data_packets[i]) {
83 void ChunkTransmitter::Nack(uint16_t seq) {
87 if (seq == begin_packet) {
91 for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
92 if (seq == data_packets[i]) {
99 void ChunkTransmitter::Abort() {
100 if (!current) return;
105 data_packets.clear();
109 void ChunkTransmitter::Send(Chunk &chunk) {
110 // abort current chunk, if any
116 // load new chunk data
118 buffer_len = buffer_size;
119 if (compress(buffer.get(), &buffer_len, reinterpret_cast<const Bytef *>(chunk.BlockData()), Chunk::BlockSize()) != Z_OK) {
120 // compression failed, send it uncompressed
121 buffer_len = Chunk::BlockSize();
122 memcpy(buffer.get(), chunk.BlockData(), buffer_len);
126 num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
127 data_packets.resize(num_packets, -1);
133 void ChunkTransmitter::SendBegin() {
134 uint32_t flags = compressed;
135 auto pack = conn.Prepare<Packet::ChunkBegin>();
136 pack.WriteTransmissionId(trans_id);
137 pack.WriteFlags(flags);
138 pack.WriteChunkCoords(current->Position());
139 pack.WriteDataSize(buffer_len);
140 if (begin_packet == -1) {
143 begin_packet = conn.Send();
146 void ChunkTransmitter::SendData(size_t i) {
147 int pos = i * packet_len;
148 int len = min(packet_len, buffer_len - pos);
149 const uint8_t *data = &buffer[pos];
151 auto pack = conn.Prepare<Packet::ChunkData>();
152 pack.WriteTransmissionId(trans_id);
153 pack.WriteDataOffset(pos);
154 pack.WriteDataSize(len);
155 pack.WriteData(data, len);
157 if (data_packets[i] == -1) {
160 data_packets[i] = conn.Send();
163 void ChunkTransmitter::Release() {
171 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
174 , player(nullptr, nullptr)
178 , player_update_state()
179 , player_update_pack(0)
180 , player_update_timer(1500)
184 conn.SetHandler(this);
187 ClientConnection::~ClientConnection() {
191 void ClientConnection::Update(int dt) {
193 if (Disconnected()) {
198 auto global_iter = server.GetWorld().Entities().begin();
199 auto global_end = server.GetWorld().Entities().end();
200 auto local_iter = spawns.begin();
201 auto local_end = spawns.end();
203 while (global_iter != global_end && local_iter != local_end) {
204 if (global_iter->ID() == local_iter->entity->ID()) {
206 if (CanDespawn(*global_iter)) {
207 SendDespawn(*local_iter);
210 QueueUpdate(*local_iter);
214 } else if (global_iter->ID() < local_iter->entity->ID()) {
215 // global entity was inserted
216 if (CanSpawn(*global_iter)) {
217 auto spawned = spawns.emplace(local_iter, *global_iter);
222 // global entity was removed
223 SendDespawn(*local_iter);
229 while (global_iter != global_end) {
230 if (CanSpawn(*global_iter)) {
231 spawns.emplace_back(*global_iter);
232 SendSpawn(spawns.back());
238 while (local_iter != local_end) {
239 SendDespawn(*local_iter);
247 if (conn.ShouldPing()) {
248 conn.SendPing(server.GetPacket(), server.GetSocket());
252 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
259 ClientConnection::SpawnStatus::~SpawnStatus() {
263 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
265 &e != player.entity &&
267 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
270 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
273 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
276 uint16_t ClientConnection::Send() {
277 return conn.Send(server.GetPacket(), server.GetSocket());
280 uint16_t ClientConnection::Send(size_t len) {
281 server.GetPacket().len = len;
285 void ClientConnection::SendSpawn(SpawnStatus &status) {
286 // don't double spawn
287 if (status.spawn_pack != -1) return;
289 auto pack = Prepare<Packet::SpawnEntity>();
290 pack.WriteEntity(*status.entity);
291 status.spawn_pack = Send();
295 void ClientConnection::SendDespawn(SpawnStatus &status) {
296 // don't double despawn
297 if (status.despawn_pack != -1) return;
299 auto pack = Prepare<Packet::DespawnEntity>();
300 pack.WriteEntityID(status.entity->ID());
301 status.despawn_pack = Send();
305 void ClientConnection::QueueUpdate(SpawnStatus &status) {
306 // don't send updates while spawn not ack'd or despawn sent
307 if (status.spawn_pack == -1 && status.despawn_pack == -1) {
308 entity_updates.push_back(&status);
312 void ClientConnection::SendUpdates() {
313 auto pack = Prepare<Packet::EntityUpdate>();
315 for (SpawnStatus *status : entity_updates) {
316 pack.WriteEntity(*status->entity, entity_pos);
318 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
319 pack.WriteEntityCount(entity_pos);
320 Send(Packet::EntityUpdate::GetSize(entity_pos));
321 pack = Prepare<Packet::EntityUpdate>();
325 if (entity_pos > 0) {
326 pack.WriteEntityCount(entity_pos);
327 Send(Packet::EntityUpdate::GetSize(entity_pos));
329 entity_updates.clear();
332 void ClientConnection::CheckPlayerFix() {
333 // player_update_state's position holds the client's most recent prediction
334 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
335 float dist_squared = dot(diff, diff);
337 // if client's prediction is off by more than 1cm, send
338 // our (authoritative) state back so it can fix it
339 constexpr float fix_thresh = 0.0001f;
341 if (dist_squared > fix_thresh) {
342 auto pack = Prepare<Packet::PlayerCorrection>();
343 pack.WritePacketSeq(player_update_pack);
344 pack.WritePlayer(PlayerEntity());
349 void ClientConnection::CheckChunkQueue() {
350 if (PlayerChunks().Base() != old_base) {
351 Chunk::Pos begin = PlayerChunks().CoordsBegin();
352 Chunk::Pos end = PlayerChunks().CoordsEnd();
353 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
354 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
355 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
356 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
357 chunk_queue.push_back(pos);
362 old_base = PlayerChunks().Base();
364 if (transmitter.Transmitting()) {
365 transmitter.Transmit();
368 if (transmitter.Idle()) {
370 constexpr int max = 64;
371 while (count < max && !chunk_queue.empty()) {
372 Chunk::Pos pos = chunk_queue.front();
373 chunk_queue.pop_front();
374 if (PlayerChunks().InRange(pos)) {
375 Chunk *chunk = PlayerChunks().Get(pos);
377 transmitter.Send(*chunk);
380 chunk_queue.push_back(pos);
388 void ClientConnection::AttachPlayer(const Player &new_player) {
391 player.entity->Ref();
393 old_base = player.chunks->Base();
394 Chunk::Pos begin = player.chunks->CoordsBegin();
395 Chunk::Pos end = player.chunks->CoordsEnd();
396 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
397 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
398 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
399 chunk_queue.push_back(pos);
404 cout << "player \"" << player.entity->Name() << "\" joined" << endl;
407 void ClientConnection::DetachPlayer() {
408 if (!HasPlayer()) return;
409 cout << "player \"" << player.entity->Name() << "\" left" << endl;
410 player.entity->Kill();
411 player.entity->UnRef();
412 player.entity = nullptr;
413 player.chunks = nullptr;
418 void ClientConnection::OnPacketReceived(uint16_t seq) {
419 if (transmitter.Waiting()) {
420 transmitter.Ack(seq);
422 if (!confirm_wait) return;
423 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
424 if (seq == iter->spawn_pack) {
425 iter->spawn_pack = -1;
429 if (seq == iter->despawn_pack) {
437 void ClientConnection::OnPacketLost(uint16_t seq) {
438 if (transmitter.Waiting()) {
439 transmitter.Nack(seq);
441 if (!confirm_wait) return;
442 for (SpawnStatus &status : spawns) {
443 if (seq == status.spawn_pack) {
444 status.spawn_pack = -1;
449 if (seq == status.despawn_pack) {
450 status.despawn_pack = -1;
458 void ClientConnection::On(const Packet::Login &pack) {
460 pack.ReadPlayerName(name);
462 Player new_player = server.GetWorld().AddPlayer(name);
464 if (new_player.entity) {
466 AttachPlayer(new_player);
467 cout << "accepted login from player \"" << name << '"' << endl;
468 auto response = Prepare<Packet::Join>();
469 response.WritePlayer(*new_player.entity);
470 response.WriteWorldName(server.GetWorld().Name());
472 // set up update tracking
473 player_update_state = new_player.entity->GetState();
474 player_update_pack = pack.Seq();
475 player_update_timer.Reset();
476 player_update_timer.Start();
479 cout << "rejected login from player \"" << name << '"' << endl;
480 Prepare<Packet::Part>();
486 void ClientConnection::On(const Packet::Part &) {
490 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
491 if (!HasPlayer()) return;
492 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
493 bool overdue = player_update_timer.HitOnce();
494 player_update_timer.Reset();
495 if (pack_diff > 0 || overdue) {
496 player_update_pack = pack.Seq();
497 pack.ReadPlayerState(player_update_state);
498 // accept velocity and orientation as "user input"
499 PlayerEntity().Velocity(player_update_state.velocity);
500 PlayerEntity().Orientation(player_update_state.orient);
505 Server::Server(const Config &conf, World &world)
507 , serv_pack{ -1, nullptr, 0 }
510 serv_sock = SDLNet_UDP_Open(conf.port);
512 throw NetError("SDLNet_UDP_Open");
515 serv_pack.data = new Uint8[sizeof(Packet)];
516 serv_pack.maxlen = sizeof(Packet);
520 delete[] serv_pack.data;
521 SDLNet_UDP_Close(serv_sock);
525 void Server::Handle() {
526 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
528 HandlePacket(serv_pack);
529 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
532 // a boo boo happened
533 throw NetError("SDLNet_UDP_Recv");
537 void Server::HandlePacket(const UDPpacket &udp_pack) {
538 if (udp_pack.len < int(sizeof(Packet::Header))) {
539 // packet too small, drop
542 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
543 if (pack.header.tag != Packet::TAG) {
544 // mistagged packet, drop
548 ClientConnection &client = GetClient(udp_pack.address);
549 client.GetConnection().Received(udp_pack);
552 ClientConnection &Server::GetClient(const IPaddress &addr) {
553 for (ClientConnection &client : clients) {
554 if (client.Matches(addr)) {
558 clients.emplace_back(*this, addr);
559 return clients.back();
562 void Server::Update(int dt) {
563 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
565 if (client->Disconnected()) {
566 client = clients.erase(client);