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