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