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)
177 , player_update_state()
178 , player_update_pack(0)
179 , player_update_timer(1500)
183 conn.SetHandler(this);
186 ClientConnection::~ClientConnection() {
190 void ClientConnection::Update(int dt) {
192 if (Disconnected()) {
197 auto global_iter = server.GetWorld().Entities().begin();
198 auto global_end = server.GetWorld().Entities().end();
199 auto local_iter = spawns.begin();
200 auto local_end = spawns.end();
202 while (global_iter != global_end && local_iter != local_end) {
203 if (global_iter->ID() == local_iter->entity->ID()) {
205 if (CanDespawn(*global_iter)) {
206 SendDespawn(*local_iter);
209 SendUpdate(*local_iter);
213 } else if (global_iter->ID() < local_iter->entity->ID()) {
214 // global entity was inserted
215 if (CanSpawn(*global_iter)) {
216 auto spawned = spawns.emplace(local_iter, *global_iter);
221 // global entity was removed
222 SendDespawn(*local_iter);
228 while (global_iter != global_end) {
229 if (CanSpawn(*global_iter)) {
230 spawns.emplace_back(*global_iter);
231 SendSpawn(spawns.back());
237 while (local_iter != local_end) {
238 SendDespawn(*local_iter);
245 if (conn.ShouldPing()) {
246 conn.SendPing(server.GetPacket(), server.GetSocket());
250 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
257 ClientConnection::SpawnStatus::~SpawnStatus() {
261 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
263 &e != player.entity &&
265 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
268 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
271 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
274 uint16_t ClientConnection::Send() {
275 return conn.Send(server.GetPacket(), server.GetSocket());
278 uint16_t ClientConnection::Send(size_t len) {
279 server.GetPacket().len = len;
283 void ClientConnection::SendSpawn(SpawnStatus &status) {
284 // don't double spawn
285 if (status.spawn_pack != -1) return;
287 auto pack = Prepare<Packet::SpawnEntity>();
288 pack.WriteEntity(*status.entity);
289 status.spawn_pack = Send();
293 void ClientConnection::SendDespawn(SpawnStatus &status) {
294 // don't double despawn
295 if (status.despawn_pack != -1) return;
297 auto pack = Prepare<Packet::DespawnEntity>();
298 pack.WriteEntityID(status.entity->ID());
299 status.despawn_pack = Send();
303 void ClientConnection::SendUpdate(SpawnStatus &status) {
304 // don't send updates while spawn not ack'd or despawn sent
305 if (status.spawn_pack != -1 || status.despawn_pack != -1) return;
307 // TODO: pack entity updates
308 auto pack = Prepare<Packet::EntityUpdate>();
309 pack.WriteEntityCount(1);
310 pack.WriteEntity(*status.entity, 0);
311 Send(Packet::EntityUpdate::GetSize(1));
314 void ClientConnection::CheckPlayerFix() {
315 // player_update_state's position holds the client's most recent prediction
316 glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
317 float dist_squared = dot(diff, diff);
319 // if client's prediction is off by more than 1cm, send
320 // our (authoritative) state back so it can fix it
321 constexpr float fix_thresh = 0.0001f;
323 if (dist_squared > fix_thresh) {
324 auto pack = Prepare<Packet::PlayerCorrection>();
325 pack.WritePacketSeq(player_update_pack);
326 pack.WritePlayer(PlayerEntity());
331 void ClientConnection::CheckChunkQueue() {
332 if (PlayerChunks().Base() != old_base) {
333 Chunk::Pos begin = PlayerChunks().CoordsBegin();
334 Chunk::Pos end = PlayerChunks().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 if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
339 chunk_queue.push_back(pos);
344 old_base = PlayerChunks().Base();
346 if (transmitter.Transmitting()) {
347 transmitter.Transmit();
350 if (transmitter.Idle()) {
352 constexpr int max = 64;
353 while (count < max && !chunk_queue.empty()) {
354 Chunk::Pos pos = chunk_queue.front();
355 chunk_queue.pop_front();
356 if (PlayerChunks().InRange(pos)) {
357 Chunk *chunk = PlayerChunks().Get(pos);
359 transmitter.Send(*chunk);
362 chunk_queue.push_back(pos);
370 void ClientConnection::AttachPlayer(const Player &new_player) {
373 player.entity->Ref();
375 old_base = player.chunks->Base();
376 Chunk::Pos begin = player.chunks->CoordsBegin();
377 Chunk::Pos end = player.chunks->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 chunk_queue.push_back(pos);
386 cout << "player \"" << player.entity->Name() << "\" joined" << endl;
389 void ClientConnection::DetachPlayer() {
390 if (!HasPlayer()) return;
391 cout << "player \"" << player.entity->Name() << "\" left" << endl;
392 player.entity->Kill();
393 player.entity->UnRef();
394 player.entity = nullptr;
395 player.chunks = nullptr;
400 void ClientConnection::OnPacketReceived(uint16_t seq) {
401 if (transmitter.Waiting()) {
402 transmitter.Ack(seq);
404 if (!confirm_wait) return;
405 for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
406 if (seq == iter->spawn_pack) {
407 iter->spawn_pack = -1;
411 if (seq == iter->despawn_pack) {
419 void ClientConnection::OnPacketLost(uint16_t seq) {
420 if (transmitter.Waiting()) {
421 transmitter.Nack(seq);
423 if (!confirm_wait) return;
424 for (SpawnStatus &status : spawns) {
425 if (seq == status.spawn_pack) {
426 status.spawn_pack = -1;
431 if (seq == status.despawn_pack) {
432 status.despawn_pack = -1;
440 void ClientConnection::On(const Packet::Login &pack) {
442 pack.ReadPlayerName(name);
444 Player new_player = server.GetWorld().AddPlayer(name);
446 if (new_player.entity) {
448 AttachPlayer(new_player);
449 cout << "accepted login from player \"" << name << '"' << endl;
450 auto response = Prepare<Packet::Join>();
451 response.WritePlayer(*new_player.entity);
452 response.WriteWorldName(server.GetWorld().Name());
454 // set up update tracking
455 player_update_state = new_player.entity->GetState();
456 player_update_pack = pack.Seq();
457 player_update_timer.Reset();
458 player_update_timer.Start();
461 cout << "rejected login from player \"" << name << '"' << endl;
462 Prepare<Packet::Part>();
468 void ClientConnection::On(const Packet::Part &) {
472 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
473 if (!HasPlayer()) return;
474 int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
475 bool overdue = player_update_timer.HitOnce();
476 player_update_timer.Reset();
477 if (pack_diff > 0 || overdue) {
478 player_update_pack = pack.Seq();
479 pack.ReadPlayerState(player_update_state);
480 // accept velocity and orientation as "user input"
481 PlayerEntity().Velocity(player_update_state.velocity);
482 PlayerEntity().Orientation(player_update_state.orient);
487 Server::Server(const Config &conf, World &world)
489 , serv_pack{ -1, nullptr, 0 }
492 serv_sock = SDLNet_UDP_Open(conf.port);
494 throw NetError("SDLNet_UDP_Open");
497 serv_pack.data = new Uint8[sizeof(Packet)];
498 serv_pack.maxlen = sizeof(Packet);
502 delete[] serv_pack.data;
503 SDLNet_UDP_Close(serv_sock);
507 void Server::Handle() {
508 int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
510 HandlePacket(serv_pack);
511 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
514 // a boo boo happened
515 throw NetError("SDLNet_UDP_Recv");
519 void Server::HandlePacket(const UDPpacket &udp_pack) {
520 if (udp_pack.len < int(sizeof(Packet::Header))) {
521 // packet too small, drop
524 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
525 if (pack.header.tag != Packet::TAG) {
526 // mistagged packet, drop
530 ClientConnection &client = GetClient(udp_pack.address);
531 client.GetConnection().Received(udp_pack);
534 ClientConnection &Server::GetClient(const IPaddress &addr) {
535 for (ClientConnection &client : clients) {
536 if (client.Matches(addr)) {
540 clients.emplace_back(*this, addr);
541 return clients.back();
544 void Server::Update(int dt) {
545 for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
547 if (client->Disconnected()) {
548 client = clients.erase(client);