]> git.localhorst.tv Git - blank.git/blob - src/server/net.cpp
decrease packet frequency
[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(Packet::ChunkData::GetSize(len));
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 , chunk_blocks_skipped(0) {
193         conn.SetHandler(this);
194 }
195
196 ClientConnection::~ClientConnection() {
197         DetachPlayer();
198 }
199
200 void ClientConnection::Update(int dt) {
201         conn.Update(dt);
202         if (Disconnected()) {
203                 return;
204         }
205         if (HasPlayer()) {
206                 CheckPlayerFix();
207                 CheckChunkQueue();
208                 CheckEntities();
209                 SendUpdates();
210         }
211         if (conn.ShouldPing()) {
212                 conn.SendPing(server.GetPacket(), server.GetSocket());
213         }
214 }
215
216 void ClientConnection::CheckEntities() {
217         auto global_iter = server.GetWorld().Entities().begin();
218         auto global_end = server.GetWorld().Entities().end();
219         auto local_iter = spawns.begin();
220         auto local_end = spawns.end();
221
222         while (global_iter != global_end && local_iter != local_end) {
223                 if (global_iter->ID() == local_iter->entity->ID()) {
224                         // they're the same
225                         if (CanDespawn(*global_iter)) {
226                                 SendDespawn(*local_iter);
227                         } else if (SendingUpdates()) {
228                                 // update
229                                 QueueUpdate(*local_iter);
230                         }
231                         ++global_iter;
232                         ++local_iter;
233                 } else if (global_iter->ID() < local_iter->entity->ID()) {
234                         // global entity was inserted
235                         if (CanSpawn(*global_iter)) {
236                                 auto spawned = spawns.emplace(local_iter, *global_iter);
237                                 SendSpawn(*spawned);
238                         }
239                         ++global_iter;
240                 } else {
241                         // global entity was removed
242                         SendDespawn(*local_iter);
243                         ++local_iter;
244                 }
245         }
246
247         // leftover spawns
248         while (global_iter != global_end) {
249                 if (CanSpawn(*global_iter)) {
250                         spawns.emplace_back(*global_iter);
251                         SendSpawn(spawns.back());
252                 }
253                 ++global_iter;
254         }
255
256         // leftover despawns
257         while (local_iter != local_end) {
258                 SendDespawn(*local_iter);
259                 ++local_iter;
260         }
261 }
262
263 ClientConnection::SpawnStatus::SpawnStatus(Entity &e)
264 : entity(&e)
265 , spawn_pack(-1)
266 , despawn_pack(-1) {
267         entity->Ref();
268 }
269
270 ClientConnection::SpawnStatus::~SpawnStatus() {
271         entity->UnRef();
272 }
273
274 bool ClientConnection::CanSpawn(const Entity &e) const noexcept {
275         return
276                 &e != &PlayerEntity() &&
277                 !e.Dead() &&
278                 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) < 7;
279 }
280
281 bool ClientConnection::CanDespawn(const Entity &e) const noexcept {
282         return
283                 e.Dead() ||
284                 manhattan_radius(e.ChunkCoords() - PlayerEntity().ChunkCoords()) > 7;
285 }
286
287 uint16_t ClientConnection::Send() {
288         return conn.Send(server.GetPacket(), server.GetSocket());
289 }
290
291 uint16_t ClientConnection::Send(size_t len) {
292         server.GetPacket().len = sizeof(Packet::Header) + len;
293         return Send();
294 }
295
296 void ClientConnection::SendSpawn(SpawnStatus &status) {
297         // don't double spawn
298         if (status.spawn_pack != -1) return;
299
300         auto pack = Prepare<Packet::SpawnEntity>();
301         pack.WriteEntity(*status.entity);
302         status.spawn_pack = Send();
303         ++confirm_wait;
304 }
305
306 void ClientConnection::SendDespawn(SpawnStatus &status) {
307         // don't double despawn
308         if (status.despawn_pack != -1) return;
309
310         auto pack = Prepare<Packet::DespawnEntity>();
311         pack.WriteEntityID(status.entity->ID());
312         status.despawn_pack = Send();
313         ++confirm_wait;
314 }
315
316 bool ClientConnection::SendingUpdates() const noexcept {
317         return entity_updates_skipped >= NetStat().SuggestedPacketHold();
318 }
319
320 void ClientConnection::QueueUpdate(SpawnStatus &status) {
321         // don't send updates while spawn not ack'd or despawn sent
322         if (status.spawn_pack == -1 && status.despawn_pack == -1) {
323                 entity_updates.push_back(&status);
324         }
325 }
326
327 void ClientConnection::SendUpdates() {
328         if (!SendingUpdates()) {
329                 entity_updates.clear();
330                 ++entity_updates_skipped;
331                 return;
332         }
333         auto base = PlayerChunks().Base();
334         auto pack = Prepare<Packet::EntityUpdate>();
335         pack.WriteChunkBase(base);
336         int entity_pos = 0;
337         for (SpawnStatus *status : entity_updates) {
338                 pack.WriteEntity(*status->entity, base, entity_pos);
339                 ++entity_pos;
340                 if (entity_pos == Packet::EntityUpdate::MAX_ENTITIES) {
341                         pack.WriteEntityCount(entity_pos);
342                         Send(Packet::EntityUpdate::GetSize(entity_pos));
343                         pack = Prepare<Packet::EntityUpdate>();
344                         entity_pos = 0;
345                 }
346         }
347         if (entity_pos > 0) {
348                 pack.WriteEntityCount(entity_pos);
349                 Send(Packet::EntityUpdate::GetSize(entity_pos));
350         }
351         entity_updates.clear();
352         entity_updates_skipped = 0;
353 }
354
355 void ClientConnection::CheckPlayerFix() {
356         // player_update_state's position holds the client's most recent prediction
357         glm::vec3 diff = player_update_state.Diff(PlayerEntity().GetState());
358         float dist_squared = dot(diff, diff);
359
360         // if client's prediction is off by more than 1cm, send
361         // our (authoritative) state back so it can fix it
362         constexpr float fix_thresh = 0.0001f;
363
364         if (dist_squared > fix_thresh) {
365                 auto pack = Prepare<Packet::PlayerCorrection>();
366                 pack.WritePacketSeq(player_update_pack);
367                 pack.WritePlayer(PlayerEntity());
368                 Send();
369         }
370 }
371
372 namespace {
373
374 struct QueueCompare {
375         explicit QueueCompare(const glm::ivec3 &base)
376         : base(base) { }
377         bool operator ()(const glm::ivec3 &left, const glm::ivec3 &right) const noexcept {
378                 const glm::ivec3 ld(left - base);
379                 const glm::ivec3 rd(right - base);
380                 return
381                         ld.x * ld.x + ld.y * ld.y + ld.z * ld.z <
382                         rd.x * rd.x + rd.y * rd.y + rd.z * rd.z;
383         }
384         const glm::ivec3 &base;
385 };
386
387 }
388
389 void ClientConnection::CheckChunkQueue() {
390         if (PlayerChunks().Base() != old_base) {
391                 ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
392                 ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
393                 for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
394                         for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
395                                 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
396                                         if (manhattan_radius(pos - old_base) > PlayerChunks().Extent()) {
397                                                 chunk_queue.push_back(pos);
398                                         }
399                                 }
400                         }
401                 }
402                 old_base = PlayerChunks().Base();
403                 sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
404         }
405         // don't push entity updates and chunk data in the same tick
406         if (chunk_blocks_skipped >= NetStat().SuggestedPacketHold() && !SendingUpdates()) {
407                 ++chunk_blocks_skipped;
408                 return;
409         }
410         if (transmitter.Transmitting()) {
411                 transmitter.Transmit();
412                 chunk_blocks_skipped = 0;
413                 return;
414         }
415         if (transmitter.Idle()) {
416                 int count = 0;
417                 constexpr int max = 64;
418                 while (count < max && !chunk_queue.empty()) {
419                         ExactLocation::Coarse pos = chunk_queue.front();
420                         chunk_queue.pop_front();
421                         if (PlayerChunks().InRange(pos)) {
422                                 Chunk *chunk = PlayerChunks().Get(pos);
423                                 if (chunk) {
424                                         transmitter.Send(*chunk);
425                                         chunk_blocks_skipped = 0;
426                                         return;
427                                 } else {
428                                         chunk_queue.push_back(pos);
429                                 }
430                                 ++count;
431                         }
432                 }
433         }
434 }
435
436 void ClientConnection::AttachPlayer(Player &player) {
437         DetachPlayer();
438         input.reset(new DirectInput(server.GetWorld(), player, server));
439         PlayerEntity().Ref();
440
441         old_base = PlayerChunks().Base();
442         ExactLocation::Coarse begin = PlayerChunks().CoordsBegin();
443         ExactLocation::Coarse end = PlayerChunks().CoordsEnd();
444         for (ExactLocation::Coarse pos = begin; pos.z < end.z; ++pos.z) {
445                 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
446                         for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
447                                 chunk_queue.push_back(pos);
448                         }
449                 }
450         }
451         sort(chunk_queue.begin(), chunk_queue.end(), QueueCompare(old_base));
452         // TODO: should the server do this?
453         if (HasPlayerModel()) {
454                 GetPlayerModel().Instantiate(PlayerEntity().GetModel());
455         }
456
457         string msg = "player \"" + player.Name() + "\" joined";
458         cout << msg << endl;
459         server.DistributeMessage(0, 0, msg);
460 }
461
462 void ClientConnection::DetachPlayer() {
463         if (!HasPlayer()) return;
464         string msg = "player \"" + input->GetPlayer().Name() + "\" left";
465         cout << msg << endl;
466         server.DistributeMessage(0, 0, msg);
467
468         server.GetWorldSave().Write(input->GetPlayer());
469         PlayerEntity().Kill();
470         PlayerEntity().UnRef();
471         input.reset();
472         transmitter.Abort();
473         chunk_queue.clear();
474         old_actions = 0;
475 }
476
477 void ClientConnection::SetPlayerModel(const Model &m) noexcept {
478         player_model = &m;
479         if (HasPlayer()) {
480                 m.Instantiate(PlayerEntity().GetModel());
481         }
482 }
483
484 bool ClientConnection::HasPlayerModel() const noexcept {
485         return player_model;
486 }
487
488 const Model &ClientConnection::GetPlayerModel() const noexcept {
489         return *player_model;
490 }
491
492 void ClientConnection::OnPacketReceived(uint16_t seq) {
493         if (transmitter.Waiting()) {
494                 transmitter.Ack(seq);
495         }
496         if (!confirm_wait) return;
497         for (auto iter = spawns.begin(), end = spawns.end(); iter != end; ++iter) {
498                 if (seq == iter->spawn_pack) {
499                         iter->spawn_pack = -1;
500                         --confirm_wait;
501                         return;
502                 }
503                 if (seq == iter->despawn_pack) {
504                         spawns.erase(iter);
505                         --confirm_wait;
506                         return;
507                 }
508         }
509 }
510
511 void ClientConnection::OnPacketLost(uint16_t seq) {
512         if (transmitter.Waiting()) {
513                 transmitter.Nack(seq);
514         }
515         if (!confirm_wait) return;
516         for (SpawnStatus &status : spawns) {
517                 if (seq == status.spawn_pack) {
518                         status.spawn_pack = -1;
519                         --confirm_wait;
520                         SendSpawn(status);
521                         return;
522                 }
523                 if (seq == status.despawn_pack) {
524                         status.despawn_pack = -1;
525                         --confirm_wait;
526                         SendDespawn(status);
527                         return;
528                 }
529         }
530 }
531
532 void ClientConnection::On(const Packet::Login &pack) {
533         string name;
534         pack.ReadPlayerName(name);
535
536         Player *new_player = server.JoinPlayer(name);
537
538         if (new_player) {
539                 // success!
540                 AttachPlayer(*new_player);
541                 cout << "accepted login from player \"" << name << '"' << endl;
542                 auto response = Prepare<Packet::Join>();
543                 response.WritePlayer(new_player->GetEntity());
544                 response.WriteWorldName(server.GetWorld().Name());
545                 Send();
546                 // set up update tracking
547                 player_update_state = new_player->GetEntity().GetState();
548                 player_update_pack = pack.Seq();
549                 player_update_timer.Reset();
550                 player_update_timer.Start();
551         } else {
552                 // aw no :(
553                 cout << "rejected login from player \"" << name << '"' << endl;
554                 Prepare<Packet::Part>();
555                 Send();
556                 conn.Close();
557         }
558 }
559
560 void ClientConnection::On(const Packet::Part &) {
561         conn.Close();
562 }
563
564 void ClientConnection::On(const Packet::PlayerUpdate &pack) {
565         if (!HasPlayer()) return;
566         int pack_diff = int16_t(pack.Seq()) - int16_t(player_update_pack);
567         bool overdue = player_update_timer.HitOnce();
568         player_update_timer.Reset();
569         if (pack_diff <= 0 && !overdue) {
570                 // drop old packets if we have a fairly recent state
571                 return;
572         }
573         glm::vec3 movement(0.0f);
574         uint8_t new_actions;
575         uint8_t slot;
576
577         player_update_pack = pack.Seq();
578         pack.ReadPredictedState(player_update_state);
579         pack.ReadMovement(movement);
580         pack.ReadActions(new_actions);
581         pack.ReadSlot(slot);
582
583         // accept client's orientation as is
584         input->GetPlayer().GetEntity().Orientation(player_update_state.orient);
585         // simulate movement
586         input->SetMovement(movement);
587         // rotate head to match client's "prediction"
588         input->TurnHead(player_update_state.pitch - input->GetPitch(), player_update_state.yaw - input->GetYaw());
589         // select the given inventory slot
590         input->SelectInventory(slot);
591
592         // check if any actions have been started or stopped
593         if ((new_actions & 0x01) && !(old_actions & 0x01)) {
594                 input->StartPrimaryAction();
595         } else if (!(new_actions & 0x01) && (old_actions & 0x01)) {
596                 input->StopPrimaryAction();
597         }
598         if ((new_actions & 0x02) && !(old_actions & 0x02)) {
599                 input->StartSecondaryAction();
600         } else if (!(new_actions & 0x02) && (old_actions & 0x02)) {
601                 input->StopSecondaryAction();
602         }
603         if ((new_actions & 0x04) && !(old_actions & 0x04)) {
604                 input->StartTertiaryAction();
605         } else if (!(new_actions & 0x04) && (old_actions & 0x04)) {
606                 input->StopTertiaryAction();
607         }
608         old_actions = new_actions;
609 }
610
611 bool ClientConnection::ChunkInRange(const glm::ivec3 &pos) const noexcept {
612         return HasPlayer() && PlayerChunks().InRange(pos);
613 }
614
615 void ClientConnection::On(const Packet::Message &pack) {
616         uint8_t type;
617         uint32_t ref;
618         string msg;
619         pack.ReadType(type);
620         pack.ReadReferral(ref);
621         pack.ReadMessage(msg);
622
623         if (type == 1 && HasPlayer()) {
624                 server.DispatchMessage(input->GetPlayer(), msg);
625         }
626 }
627
628
629 Server::Server(
630         const Config::Network &conf,
631         World &world,
632         const World::Config &wc,
633         const WorldSave &save)
634 : serv_sock(nullptr)
635 , serv_pack{ -1, nullptr, 0 }
636 , clients()
637 , world(world)
638 , spawn_index(world.Chunks().MakeIndex(wc.spawn, 3))
639 , save(save)
640 , player_model(nullptr)
641 , cli(world) {
642         serv_sock = SDLNet_UDP_Open(conf.port);
643         if (!serv_sock) {
644                 throw NetError("SDLNet_UDP_Open");
645         }
646
647         serv_pack.data = new Uint8[sizeof(Packet)];
648         serv_pack.maxlen = sizeof(Packet);
649 }
650
651 Server::~Server() {
652         world.Chunks().UnregisterIndex(spawn_index);
653         delete[] serv_pack.data;
654         SDLNet_UDP_Close(serv_sock);
655 }
656
657
658 void Server::Handle() {
659         int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
660         while (result > 0) {
661                 HandlePacket(serv_pack);
662                 result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
663         }
664         if (result == -1) {
665                 // a boo boo happened
666                 throw NetError("SDLNet_UDP_Recv");
667         }
668 }
669
670 void Server::HandlePacket(const UDPpacket &udp_pack) {
671         if (udp_pack.len < int(sizeof(Packet::Header))) {
672                 // packet too small, drop
673                 return;
674         }
675         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
676         if (pack.header.tag != Packet::TAG) {
677                 // mistagged packet, drop
678                 return;
679         }
680
681         ClientConnection &client = GetClient(udp_pack.address);
682         client.GetConnection().Received(udp_pack);
683 }
684
685 ClientConnection &Server::GetClient(const IPaddress &addr) {
686         for (ClientConnection &client : clients) {
687                 if (client.Matches(addr)) {
688                         return client;
689                 }
690         }
691         clients.emplace_back(*this, addr);
692         if (HasPlayerModel()) {
693                 clients.back().SetPlayerModel(GetPlayerModel());
694         }
695         return clients.back();
696 }
697
698 void Server::Update(int dt) {
699         for (list<ClientConnection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
700                 client->Update(dt);
701                 if (client->Disconnected()) {
702                         client = clients.erase(client);
703                 } else {
704                         ++client;
705                 }
706         }
707 }
708
709 void Server::SetPlayerModel(const Model &m) noexcept {
710         player_model = &m;
711         for (ClientConnection &client : clients) {
712                 client.SetPlayerModel(m);
713         }
714 }
715
716 bool Server::HasPlayerModel() const noexcept {
717         return player_model;
718 }
719
720 const Model &Server::GetPlayerModel() const noexcept {
721         return *player_model;
722 }
723
724 Player *Server::JoinPlayer(const string &name) {
725         if (spawn_index.MissingChunks() > 0) {
726                 return nullptr;
727         }
728         Player *player = world.AddPlayer(name);
729         if (!player) {
730                 return nullptr;
731         }
732         if (save.Exists(*player)) {
733                 save.Read(*player);
734         } else {
735                 // TODO: spawn
736         }
737         return player;
738 }
739
740 void Server::SetBlock(Chunk &chunk, int index, const Block &block) {
741         chunk.SetBlock(index, block);
742         // TODO: batch chunk changes
743         auto pack = Packet::Make<Packet::BlockUpdate>(GetPacket());
744         pack.WriteChunkCoords(chunk.Position());
745         pack.WriteBlockCount(uint32_t(1));
746         pack.WriteIndex(index, 0);
747         pack.WriteBlock(chunk.BlockAt(index), 0);
748         GetPacket().len = sizeof(Packet::Header) + Packet::BlockUpdate::GetSize(1);
749         for (ClientConnection &client : clients) {
750                 if (client.ChunkInRange(chunk.Position())) {
751                         client.Send();
752                 }
753         }
754 }
755
756 void Server::DispatchMessage(Player &player, const string &msg) {
757         if (msg.empty()) {
758                 return;
759         }
760         if (msg[0] == '/' && msg.size() > 1 && msg[1] != '/') {
761                 cli.Execute(player, msg.substr(1));
762         } else {
763                 DistributeMessage(1, player.GetEntity().ID(), msg);
764         }
765 }
766
767 void Server::DistributeMessage(uint8_t type, uint32_t ref, const string &msg) {
768         auto pack = Packet::Make<Packet::Message>(serv_pack);
769         pack.WriteType(type);
770         pack.WriteReferral(ref);
771         pack.WriteMessage(msg);
772         serv_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
773         SendAll();
774 }
775
776 void Server::SendAll() {
777         for (ClientConnection &client : clients) {
778                 client.GetConnection().Send(serv_pack, serv_sock);
779         }
780 }
781
782 }
783 }