]> git.localhorst.tv Git - blank.git/blob - src/server/net.cpp
e739922b60268062f4c6a708d0de334d03e401cf
[blank.git] / src / server / net.cpp
1 #include "ClientConnection.hpp"
2 #include "ChunkTransmitter.hpp"
3 #include "Server.hpp"
4
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"
11
12 #include <algorithm>
13 #include <iostream>
14 #include <zlib.h>
15 #include <glm/gtx/io.hpp>
16
17 using namespace std;
18
19
20 namespace blank {
21 namespace server {
22
23 ChunkTransmitter::ChunkTransmitter(ClientConnection &conn)
24 : conn(conn)
25 , current(nullptr)
26 , buffer_size(Chunk::BlockSize() + 10)
27 , buffer(new uint8_t[buffer_size])
28 , buffer_len(0)
29 , packet_len(Packet::ChunkData::MAX_DATA_LEN)
30 , cursor(0)
31 , num_packets(0)
32 , begin_packet(-1)
33 , data_packets()
34 , confirm_wait(0)
35 , trans_id(0)
36 , compressed(false) {
37
38 }
39
40 ChunkTransmitter::~ChunkTransmitter() {
41         Abort();
42 }
43
44 bool ChunkTransmitter::Idle() const noexcept {
45         return !Transmitting() && !Waiting();
46 }
47
48 bool ChunkTransmitter::Transmitting() const noexcept {
49         return cursor < num_packets;
50 }
51
52 void ChunkTransmitter::Transmit() {
53         if (cursor < num_packets) {
54                 SendData(cursor);
55                 ++cursor;
56         }
57 }
58
59 bool ChunkTransmitter::Waiting() const noexcept {
60         return confirm_wait > 0;
61 }
62
63 void ChunkTransmitter::Ack(uint16_t seq) {
64         if (!Waiting()) {
65                 return;
66         }
67         if (seq == begin_packet) {
68                 begin_packet = -1;
69                 --confirm_wait;
70                 if (Idle()) {
71                         Release();
72                 }
73                 return;
74         }
75         for (int i = 0, end = data_packets.size(); i < end; ++i) {
76                 if (seq == data_packets[i]) {
77                         data_packets[i] = -1;
78                         --confirm_wait;
79                         if (Idle()) {
80                                 Release();
81                         }
82                         return;
83                 }
84         }
85 }
86
87 void ChunkTransmitter::Nack(uint16_t seq) {
88         if (!Waiting()) {
89                 return;
90         }
91         if (seq == begin_packet) {
92                 SendBegin();
93                 return;
94         }
95         for (size_t i = 0, end = data_packets.size(); i < end; ++i) {
96                 if (seq == data_packets[i]) {
97                         SendData(i);
98                         return;
99                 }
100         }
101 }
102
103 void ChunkTransmitter::Abort() {
104         if (!current) return;
105
106         Release();
107
108         begin_packet = -1;
109         data_packets.clear();
110         confirm_wait = 0;
111 }
112
113 void ChunkTransmitter::Send(Chunk &chunk) {
114         // abort current chunk, if any
115         Abort();
116
117         current = &chunk;
118         current->Ref();
119
120         // load new chunk data
121         compressed = true;
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);
127                 compressed = false;
128         }
129         cursor = 0;
130         num_packets = (buffer_len / packet_len) + (buffer_len % packet_len != 0);
131         data_packets.resize(num_packets, -1);
132
133         ++trans_id;
134         SendBegin();
135 }
136
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) {
145                 ++confirm_wait;
146         }
147         begin_packet = conn.Send();
148 }
149
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];
154
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);
160
161         if (data_packets[i] == -1) {
162                 ++confirm_wait;
163         }
164         data_packets[i] = conn.Send();
165 }
166
167 void ChunkTransmitter::Release() {
168         if (current) {
169                 current->UnRef();
170                 current = nullptr;
171         }
172 }
173
174
175 ClientConnection::ClientConnection(Server &server, const IPaddress &addr)
176 : server(server)
177 , conn(addr)
178 , input()
179 , player_model(nullptr)
180 , spawns()
181 , confirm_wait(0)
182 , entity_updates()
183 , player_update_state()
184 , player_update_pack(0)
185 , player_update_timer(1500)
186 , old_actions(0)
187 , transmitter(*this)
188 , chunk_queue()
189 , old_base() {
190         conn.SetHandler(this);
191 }
192
193 ClientConnection::~ClientConnection() {
194         DetachPlayer();
195 }
196
197 void ClientConnection::Update(int dt) {
198         conn.Update(dt);
199         if (Disconnected()) {
200                 return;
201         }
202         if (HasPlayer()) {
203                 // sync entities
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();
208
209                 while (global_iter != global_end && local_iter != local_end) {
210                         if (global_iter->ID() == local_iter->entity->ID()) {
211                                 // they're the same
212                                 if (CanDespawn(*global_iter)) {
213                                         SendDespawn(*local_iter);
214                                 } else {
215                                         // update
216                                         QueueUpdate(*local_iter);
217                                 }
218                                 ++global_iter;
219                                 ++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);
224                                         SendSpawn(*spawned);
225                                 }
226                                 ++global_iter;
227                         } else {
228                                 // global entity was removed
229                                 SendDespawn(*local_iter);
230                                 ++local_iter;
231                         }
232                 }
233
234                 // leftover spawns
235                 while (global_iter != global_end) {
236                         if (CanSpawn(*global_iter)) {
237                                 spawns.emplace_back(*global_iter);
238                                 SendSpawn(spawns.back());
239                         }
240                         ++global_iter;
241                 }
242
243                 // leftover despawns
244                 while (local_iter != local_end) {
245                         SendDespawn(*local_iter);
246                         ++local_iter;
247                 }
248                 SendUpdates();
249
250                 input->Update(dt);
251                 CheckPlayerFix();
252                 CheckChunkQueue();
253         }
254         if (conn.ShouldPing()) {
255                 conn.SendPing(server.GetPacket(), server.GetSocket());
256         }
257 }
258
259 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
260 : entity(&e)
261 , spawn_pack(-1)
262 , despawn_pack(-1) {
263         entity->Ref();
264 }
265
266 ClientConnection::SpawnStatus::~SpawnStatus() {
267         entity->UnRef();
268 }
269
270 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
271         return
272                 &e != &PlayerEntity() &&
273                 !e.Dead() &&
274                 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
275 }
276
277 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
278         return
279                 e.Dead() ||
280                 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
281 }
282
283 uint16_t ClientConnection::Send() {
284         return conn.Send(server.GetPacket(), server.GetSocket());
285 }
286
287 uint16_t ClientConnection::Send(size_t len) {
288         server.GetPacket().len = sizeof(Packet::Header) + len;
289         return Send();
290 }
291
292 void ClientConnection::SendSpawn(SpawnStatus &status) {
293         // don't double spawn
294         if (status.spawn_pack != -1) return;
295
296         auto pack = Prepare<Packet::SpawnEntity>();
297         pack.WriteEntity(*status.entity);
298         status.spawn_pack = Send();
299         ++confirm_wait;
300 }
301
302 void ClientConnection::SendDespawn(SpawnStatus &status) {
303         // don't double despawn
304         if (status.despawn_pack != -1) return;
305
306         auto pack = Prepare<Packet::DespawnEntity>();
307         pack.WriteEntityID(status.entity->ID());
308         status.despawn_pack = Send();
309         ++confirm_wait;
310 }
311
312 void ClientConnection::QueueUpdate(SpawnStatus &status) {
313         // don't send updates while spawn not ack'd or despawn sent
314         if (status.spawn_pack == -1 && status.despawn_pack == -1) {
315                 entity_updates.push_back(&status);
316         }
317 }
318
319 void ClientConnection::SendUpdates() {
320         auto pack = Prepare<Packet::EntityUpdate>();
321         int entity_pos = 0;
322         for (SpawnStatus *status : entity_updates) {
323                 pack.WriteEntity(*status->entity, entity_pos);
324                 ++entity_pos;
325                 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
326                         pack.WriteEntityCount(entity_pos);
327                         Send(Packet::EntityUpdate::GetSize(entity_pos));
328                         pack = Prepare<Packet::EntityUpdate>();
329                         entity_pos = 0;
330                 }
331         }
332         if (entity_pos > 0) {
333                 pack.WriteEntityCount(entity_pos);
334                 Send(Packet::EntityUpdate::GetSize(entity_pos));
335         }
336         entity_updates.clear();
337 }
338
339 void ClientConnection::CheckPlayerFix() {
340         // player_update_state's position holds the client's most recent prediction
341         glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
342         float dist_squared = dot(diff, diff);
343
344         // if client's prediction is off by more than 1cm, send
345         // our (authoritative) state back so it can fix it
346         constexpr float fix_thresh = 0.0001f;
347
348         if (dist_squared > fix_thresh) {
349                 auto pack = Prepare<Packet::PlayerCorrection>();
350                 pack.WritePacketSeq(player_update_pack);
351                 pack.WritePlayer(PlayerEntity());
352                 Send();
353         }
354 }
355
356 namespace {
357
358 struct QueueCompare {
359         explicit QueueCompare(const glm::ivec3 &base)
360         : base(base) { }
361         bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
362                 const glm::ivec3 ld(left - base);
363                 const glm::ivec3 rd(right - base);
364                 return
365                         ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
366                         rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
367         }
368         const glm::ivec3 &base;
369 };
370
371 }
372
373 void ClientConnection::CheckChunkQueue() {
374         if (PlayerChunks().Base() != old_base) {
375                 Chunk::Pos begin = PlayerChunks().CoordsBegin();
376                 Chunk::Pos end = PlayerChunks().CoordsEnd();
377                 for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
378                         for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
379                                 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
380                                         if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
381                                                 chunk_queue.push_back(pos);
382                                         }
383                                 }
384                         }
385                 }
386                 old_base = PlayerChunks().Base();
387                 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
388         }
389         if (transmitter.Transmitting()) {
390                 transmitter.Transmit();
391                 return;
392         }
393         if (transmitter.Idle()) {
394                 int count = 0;
395                 constexpr int max = 64;
396                 while (count < max && !chunk_queue.empty()) {
397                         Chunk::Pos pos = chunk_queue.front();
398                         chunk_queue.pop_front();
399                         if (PlayerChunks().InRange(pos)) {
400                                 Chunk *chunk = PlayerChunks().Get(pos);
401                                 if (chunk) {
402                                         transmitter.Send(*chunk);
403                                         return;
404                                 } else {
405                                         chunk_queue.push_back(pos);
406                                 }
407                                 ++count;
408                         }
409                 }
410         }
411 }
412
413 void ClientConnection::AttachPlayer(Player &player) {
414         DetachPlayer();
415         input.reset(new DirectInput(server.GetWorld(), player, server));
416         PlayerEntity().Ref();
417
418         old_base = PlayerChunks().Base();
419         Chunk::Pos begin = PlayerChunks().CoordsBegin();
420         Chunk::Pos end = PlayerChunks().CoordsEnd();
421         for (Chunk::Pos pos = begin; pos.z < end.z; ++pos.z) {
422                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
423                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
424                                 chunk_queue.push_back(pos);
425                         }
426                 }
427         }
428         sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
429         // TODO: should the server do this?
430         if (HasPlayerModel()) {
431                 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
432         }
433
434         string msg = "player \"" + player.Name() + "\" joined";
435         cout << msg << endl;
436         server.DistributeMessage(0, 0, msg);
437 }
438
439 void ClientConnection::DetachPlayer() {
440         if (!HasPlayer()) return;
441         string msg = "player \"" + input->GetPlayer().Name() + "\" left";
442         cout << msg << endl;
443         server.DistributeMessage(0, 0, msg);
444
445         server.GetWorldSave().Write(input->GetPlayer());
446         PlayerEntity().Kill();
447         PlayerEntity().UnRef();
448         input.reset();
449         transmitter.Abort();
450         chunk_queue.clear();
451         old_actions = 0;
452 }
453
454 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
455         player_model = &m;
456         if (HasPlayer()) {
457                 m.Instantiate(PlayerEntity().GetModel());
458         }
459 }
460
461 bool ClientConnection::HasPlayerModel() const noexcept {
462         return player_model;
463 }
464
465 const Model &ClientConnection::GetPlayerModel() const noexcept {
466         return *player_model;
467 }
468
469 void ClientConnection::OnPacketReceived(uint16_t seq) {
470         if (transmitter.Waiting()) {
471                 transmitter.Ack(seq);
472         }
473         if (!confirm_wait) return;
474         for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
475                 if (seq == iter->spawn_pack) {
476                         iter->spawn_pack = -1;
477                         --confirm_wait;
478                         return;
479                 }
480                 if (seq == iter->despawn_pack) {
481                         spawns.erase(iter);
482                         --confirm_wait;
483                         return;
484                 }
485         }
486 }
487
488 void ClientConnection::OnPacketLost(uint16_t seq) {
489         if (transmitter.Waiting()) {
490                 transmitter.Nack(seq);
491         }
492         if (!confirm_wait) return;
493         for (SpawnStatus &status : spawns) {
494                 if (seq == status.spawn_pack) {
495                         status.spawn_pack = -1;
496                         --confirm_wait;
497                         SendSpawn(status);
498                         return;
499                 }
500                 if (seq == status.despawn_pack) {
501                         status.despawn_pack = -1;
502                         --confirm_wait;
503                         SendDespawn(status);
504                         return;
505                 }
506         }
507 }
508
509 void ClientConnection::On(const Packet::Login &pack) {
510         string name;
511         pack.ReadPlayerName(name);
512
513         Player *new_player = server.JoinPlayer(name);
514
515         if (new_player) {
516                 // success!
517                 AttachPlayer(*new_player);
518                 cout << "accepted login from player \"" << name << '"' << endl;
519                 auto response = Prepare<Packet::Join>();
520                 response.WritePlayer(new_player->GetEntity());
521                 response.WriteWorldName(server.GetWorld().Name());
522                 Send();
523                 // set up update tracking
524                 player_update_state = new_player->GetEntity().GetState();
525                 player_update_pack = pack.Seq();
526                 player_update_timer.Reset();
527                 player_update_timer.Start();
528         } else {
529                 // aw no :(
530                 cout << "rejected login from player \"" << name << '"' << endl;
531                 Prepare<Packet::Part>();
532                 Send();
533                 conn.Close();
534         }
535 }
536
537 void ClientConnection::On(const Packet::Part &) {
538         conn.Close();
539 }
540
541 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
542         if (!HasPlayer()) return;
543         int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
544         bool overdue = player_update_timer.HitOnce();
545         player_update_timer.Reset();
546         if (pack_diff <= 0 && !overdue) {
547                 // drop old packets if we have a fairly recent state
548                 return;
549         }
550         glm::vec3 movement(0.0f);
551         float pitch = 0.0f;
552         float yaw = 0.0f;
553         uint8_t new_actions;
554         uint8_t slot;
555
556         player_update_pack = pack.Seq();
557         pack.ReadPredictedState(player_update_state);
558         pack.ReadMovement(movement);
559         pack.ReadPitch(pitch);
560         pack.ReadYaw(yaw);
561         pack.ReadActions(new_actions);
562         pack.ReadSlot(slot);
563
564         input->SetMovement(movement);
565         input->TurnHead(pitch - input->GetPitch(), yaw - input->GetYaw());
566         input->SelectInventory(slot);
567
568         if ((new_actions & 0x01) && !(old_actions & 0x01)) {
569                 input->StartPrimaryAction();
570         } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
571                 input->StopPrimaryAction();
572         }
573         if ((new_actions & 0x02) && !(old_actions & 0x02)) {
574                 input->StartSecondaryAction();
575         } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
576                 input->StopSecondaryAction();
577         }
578         if ((new_actions & 0x04) && !(old_actions & 0x04)) {
579                 input->StartTertiaryAction();
580         } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
581                 input->StopTertiaryAction();
582         }
583         old_actions = new_actions;
584 }
585
586 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
587         return HasPlayer() && PlayerChunks().InRange(pos);
588 }
589
590 void ClientConnection::On(const Packet::Message &pack) {
591         uint8_t type;
592         uint32_t ref;
593         string msg;
594         pack.ReadType(type);
595         pack.ReadReferral(ref);
596         pack.ReadMessage(msg);
597
598         if (type == 1 && HasPlayer()) {
599                 server.DistributeMessage(1, PlayerEntity().ID(), msg);
600         }
601 }
602
603
604 Server::Server(
605         const Config::Network &conf,
606         World &world,
607         const World::Config &wc,
608         const WorldSave &save)
609 : serv_sock(nullptr)
610 , serv_pack{ -1, nullptr, 0 }
611 , clients()
612 , world(world)
613 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
614 , save(save)
615 , player_model(nullptr) {
616         serv_sock = SDLNet_UDP_Open(conf.port);
617         if (!serv_sock) {
618                 throw NetError("SDLNet_UDP_Open");
619         }
620
621         serv_pack.data = new Uint8[sizeof(Packet)];
622         serv_pack.maxlen = sizeof(Packet);
623 }
624
625 Server::~Server() {
626         world.Chunks().UnregisterIndex(spawn_index);
627         delete[] serv_pack.data;
628         SDLNet_UDP_Close(serv_sock);
629 }
630
631
632 void Server::Handle() {
633         int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
634         while (result > 0) {
635                 HandlePacket(serv_pack);
636                 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
637         }
638         if (result == -1) {
639                 // a boo boo happened
640                 throw NetError("SDLNet_UDP_Recv");
641         }
642 }
643
644 void Server::HandlePacket(const UDPpacket &udp_pack) {
645         if (udp_pack.len < int(sizeof(Packet::Header))) {
646                 // packet too small, drop
647                 return;
648         }
649         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
650         if (pack.header.tag != Packet::TAG) {
651                 // mistagged packet, drop
652                 return;
653         }
654
655         ClientConnection &client = GetClient(udp_pack.address);
656         client.GetConnection().Received(udp_pack);
657 }
658
659 ClientConnection &Server::GetClient(const IPaddress &addr) {
660         for (ClientConnection &client : clients) {
661                 if (client.Matches(addr)) {
662                         return client;
663                 }
664         }
665         clients.emplace_back(*this, addr);
666         if (HasPlayerModel()) {
667                 clients.back().SetPlayerModel(GetPlayerModel());
668         }
669         return clients.back();
670 }
671
672 void Server::Update(int dt) {
673         for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
674                 client->Update(dt);
675                 if (client->Disconnected()) {
676                         client = clients.erase(client);
677                 } else {
678                         ++client;
679                 }
680         }
681 }
682
683 void Server::SetPlayerModel(const Model &m) noexcept {
684         player_model = &m;
685         for (ClientConnection &client : clients) {
686                 client.SetPlayerModel(m);
687         }
688 }
689
690 bool Server::HasPlayerModel() const noexcept {
691         return player_model;
692 }
693
694 const Model &Server::GetPlayerModel() const noexcept {
695         return *player_model;
696 }
697
698 Player *Server::JoinPlayer(const string &name) {
699         if (spawn_index.MissingChunks() > 0) {
700                 return nullptr;
701         }
702         Player *player = world.AddPlayer(name);
703         if (!player) {
704                 return nullptr;
705         }
706         if (save.Exists(*player)) {
707                 save.Read(*player);
708         } else {
709                 // TODO: spawn
710         }
711         return player;
712 }
713
714 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
715         chunk.SetBlock(index, block);
716         // TODO: batch chunk changes
717         auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
718         pack.WriteChunkCoords(chunk.Position());
719         pack.WriteBlockCount(uint32_t(1));
720         pack.WriteIndex(index, 0);
721         pack.WriteBlock(chunk.BlockAt(index), 0);
722         GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
723         for (ClientConnection &client : clients) {
724                 if (client.ChunkInRange(chunk.Position())) {
725                         client.Send();
726                 }
727         }
728 }
729
730 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
731         auto pack = Packet::Make<Packet::Message>(serv_pack);
732         pack.WriteType(type);
733         pack.WriteReferral(ref);
734         pack.WriteMessage(msg);
735         serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
736         SendAll();
737 }
738
739 void Server::SendAll() {
740         for (ClientConnection &client : clients) {
741                 client.GetConnection().Send(serv_pack, serv_sock);
742         }
743 }
744
745 }
746 }