]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
7de901e31f58b7f842461e2a2414e677db8ceca5
[blank.git] / src / net / net.cpp
1 #include "CongestionControl.hpp"
2 #include "Connection.hpp"
3 #include "ConnectionHandler.hpp"
4 #include "io.hpp"
5 #include "Packet.hpp"
6
7 #include "../app/init.hpp"
8 #include "../geometry/const.hpp"
9 #include "../model/Model.hpp"
10 #include "../world/Entity.hpp"
11 #include "../world/EntityState.hpp"
12
13 #include <cstring>
14
15 using namespace std;
16
17
18 namespace blank {
19
20 constexpr size_t Packet::Ping::MAX_LEN;
21 constexpr size_t Packet::Login::MAX_LEN;
22 constexpr size_t Packet::Join::MAX_LEN;
23 constexpr size_t Packet::Part::MAX_LEN;
24 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
25 constexpr size_t Packet::SpawnEntity::MAX_LEN;
26 constexpr size_t Packet::DespawnEntity::MAX_LEN;
27 constexpr size_t Packet::EntityUpdate::MAX_LEN;
28 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
29 constexpr size_t Packet::ChunkBegin::MAX_LEN;
30 constexpr size_t Packet::ChunkData::MAX_LEN;
31 constexpr size_t Packet::BlockUpdate::MAX_LEN;
32 constexpr size_t Packet::Message::MAX_LEN;
33 constexpr size_t Packet::Message::MAX_MESSAGE_LEN;
34
35
36 CongestionControl::CongestionControl()
37 // I know, I know, it's an estimate (about 20 for IPv4, 48 for IPv6)
38 : packet_overhead(20)
39 // only sample every eighth packet for measuring RTT
40 , sample_skip(8)
41 , packets_lost(0)
42 , packets_received(0)
43 , packet_loss(0.0f)
44 , stamp_last(0)
45 , rtt(64.0f)
46 , next_sample(1000)
47 , tx_bytes(0)
48 , rx_bytes(0)
49 , tx_kbps(0.0f)
50 , rx_kbps(0.0f)
51 , mode(GOOD)
52 // rtt > 75ms or packet loss > 5% is BAD
53 , bad_rtt(75.0f)
54 , bad_loss(0.05f)
55 // rtt > 150ms or packet loss > 15% is UGLY
56 , ugly_rtt(150.0f)
57 , ugly_loss(0.15f)
58 , mode_keep_time(1000) {
59         Uint32 now = SDL_GetTicks();
60         for (Uint32 &s : stamps) {
61                 s = now;
62         }
63         next_sample += now;
64         mode_entered = now;
65         mode_reset = now;
66         mode_step = now;
67 }
68
69 void CongestionControl::PacketSent(uint16_t seq) noexcept {
70         if (!SamplePacket(seq)) {
71                 return;
72         }
73         stamps[SampleIndex(seq)] = SDL_GetTicks();
74         stamp_last = seq;
75 }
76
77 void CongestionControl::PacketLost(uint16_t seq) noexcept {
78         ++packets_lost;
79         UpdatePacketLoss();
80         UpdateRTT(seq);
81 }
82
83 void CongestionControl::PacketReceived(uint16_t seq) noexcept {
84         ++packets_received;
85         UpdatePacketLoss();
86         UpdateRTT(seq);
87 }
88
89 void CongestionControl::UpdatePacketLoss() noexcept {
90         unsigned int packets_total = packets_lost + packets_received;
91         if (packets_total >= 256) {
92                 packet_loss = float(packets_lost) / float(packets_total);
93                 packets_lost = 0;
94                 packets_received = 0;
95         }
96 }
97
98 void CongestionControl::UpdateRTT(uint16_t seq) noexcept {
99         if (!SamplePacket(seq)) return;
100         int16_t diff = int16_t(stamp_last) - int16_t(seq);
101         if (diff < 0 || diff > int(15 * sample_skip)) {
102                 // packet outside observed frame
103                 return;
104         }
105         int cur_rtt = SDL_GetTicks() - stamps[SampleIndex(seq)];
106         rtt += (cur_rtt - rtt) * 0.1f;
107 }
108
109 bool CongestionControl::SamplePacket(uint16_t seq) const noexcept {
110         return seq % sample_skip == 0;
111 }
112
113 size_t CongestionControl::SampleIndex(uint16_t seq) const noexcept {
114         return (seq / sample_skip) % 16;
115 }
116
117 void CongestionControl::PacketIn(const UDPpacket &pack) noexcept {
118         rx_bytes += pack.len + packet_overhead;
119         UpdateStats();
120 }
121
122 void CongestionControl::PacketOut(const UDPpacket &pack) noexcept {
123         tx_bytes += pack.len + packet_overhead;
124         UpdateStats();
125 }
126
127 void CongestionControl::UpdateStats() noexcept {
128         Uint32 now = SDL_GetTicks();
129         if (now < next_sample) {
130                 // not yet
131                 return;
132         }
133         tx_kbps = float(tx_bytes) * (1.0f / 1024.0f);
134         rx_kbps = float(rx_bytes) * (1.0f / 1024.0f);
135         tx_bytes = 0;
136         rx_bytes = 0;
137         next_sample += 1000;
138         UpdateMode();
139 }
140
141 void CongestionControl::UpdateMode() noexcept {
142         Mode now_mode = Conditions();
143         if (now_mode > mode) {
144                 ChangeMode(now_mode);
145         } else if (now_mode < mode) {
146                 CheckUpgrade(now_mode);
147         } else {
148                 KeepMode();
149         }
150 }
151
152 void CongestionControl::CheckUpgrade(Mode m) noexcept {
153         Uint32 now = SDL_GetTicks();
154         Uint32 time_in_mode = now - mode_entered;
155         if (time_in_mode < mode_keep_time) {
156                 return;
157         }
158         ChangeMode(m);
159 }
160
161 void CongestionControl::ChangeMode(Mode m) noexcept {
162         Uint32 now = SDL_GetTicks();
163         if (m > mode) {
164                 // changed to worse mode
165                 // if we spent less than 10 seconds in better mode
166                 // double keep time till up to 64 seconds
167                 if (now - mode_entered < 10000) {
168                         if (mode_keep_time < 64000) {
169                                 mode_keep_time *= 2;
170                         }
171                 }
172         }
173         mode = m;
174         mode_entered = now;
175         mode_reset = mode_entered;
176 }
177
178 void CongestionControl::KeepMode() noexcept {
179         mode_reset = SDL_GetTicks();
180         // if in good mode for 10 seconds, halve keep time till down to one second
181         if (mode == GOOD && mode_keep_time > 1000 && mode_step - mode_reset > 10000) {
182                 mode_keep_time /= 2;
183                 mode_step = mode_reset;
184         }
185 }
186
187 CongestionControl::Mode CongestionControl::Conditions() const noexcept {
188         if (rtt > ugly_rtt || packet_loss > ugly_loss) {
189                 return UGLY;
190         } else if (rtt > bad_rtt || packet_loss > bad_loss) {
191                 return BAD;
192         } else {
193                 return GOOD;
194         }
195 }
196
197
198 Connection::Connection(const IPaddress &addr)
199 : handler(nullptr)
200 , addr(addr)
201 // make sure a packet is sent at least every 50ms since packets contains
202 // acks that the remote end will use to measure RTT
203 , send_timer(50)
204 , recv_timer(10000)
205 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
206 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
207 , closed(false) {
208         send_timer.Start();
209         recv_timer.Start();
210 }
211
212 bool Connection::Matches(const IPaddress &remote) const noexcept {
213         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
214 }
215
216 void Connection::FlagSend() noexcept {
217         send_timer.Reset();
218 }
219
220 void Connection::FlagRecv() noexcept {
221         recv_timer.Reset();
222 }
223
224 bool Connection::ShouldPing() const noexcept {
225         return !closed && send_timer.HitOnce();
226 }
227
228 bool Connection::TimedOut() const noexcept {
229         return recv_timer.HitOnce();
230 }
231
232 void Connection::Update(int dt) {
233         send_timer.Update(dt);
234         recv_timer.Update(dt);
235         if (TimedOut()) {
236                 Close();
237                 if (HasHandler()) {
238                         Handler().OnTimeout();
239                 }
240         }
241 }
242
243
244 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
245         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
246         pack.header.ctrl = ctrl_out;
247         uint16_t seq = ctrl_out.seq++;
248
249         udp_pack.address = addr;
250         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
251                 throw NetError("SDLNet_UDP_Send");
252         }
253
254         if (HasHandler()) {
255                 Handler().PacketOut(udp_pack);
256                 Handler().PacketSent(seq);
257         }
258
259         FlagSend();
260         return seq;
261 }
262
263 void Connection::Received(const UDPpacket &udp_pack) {
264         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
265
266         // ack to the remote
267         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
268         if (diff > 0) {
269                 if (diff >= 32) {
270                         ctrl_out.hist = 0;
271                 } else {
272                         ctrl_out.hist <<= diff;
273                         ctrl_out.hist |= 1 << (diff - 1);
274                 }
275         } else if (diff < 0 && diff >= -32) {
276                 ctrl_out.hist |= 1 << (-diff - 1);
277         }
278         ctrl_out.ack = pack.header.ctrl.seq;
279         FlagRecv();
280
281         if (!HasHandler()) {
282                 return;
283         }
284
285         Packet::TControl ctrl_new = pack.header.ctrl;
286         Handler().PacketIn(udp_pack);
287         Handler().Handle(udp_pack);
288
289         if (diff > 0) {
290                 // if the packet holds more recent information
291                 // check if remote failed to ack one of our packets
292                 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
293                 // should always be true, but you never know…
294                 if (diff > 0) {
295                         for (int i = 0; i < diff; ++i) {
296                                 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
297                                         Handler().PacketLost(ctrl_in.ack - 32 + i);
298                                 }
299                         }
300                 }
301                 // check for newly ack'd packets
302                 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
303                         if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
304                                 Handler().PacketReceived(s);
305                         }
306                 }
307                 ctrl_in = ctrl_new;
308         }
309 }
310
311 bool Packet::TControl::Acks(uint16_t s) const noexcept {
312         int16_t diff = int16_t(ack) - int16_t(s);
313         if (diff == 0) return true;
314         if (diff < 0 || diff > 32) return false;
315         return (hist & (1 << (diff - 1))) != 0;
316 }
317
318 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
319         Packet::Make<Packet::Ping>(udp_pack);
320         return Send(udp_pack, sock);
321 }
322
323
324 ConnectionHandler::ConnectionHandler()
325 : cc() {
326
327 }
328
329 void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
330         cc.PacketSent(seq);
331 }
332
333 void ConnectionHandler::PacketLost(uint16_t seq) {
334         OnPacketLost(seq);
335         cc.PacketLost(seq);
336 }
337
338 void ConnectionHandler::PacketReceived(uint16_t seq) {
339         OnPacketReceived(seq);
340         cc.PacketReceived(seq);
341 }
342
343 void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
344         cc.PacketIn(pack);
345 }
346
347 void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
348         cc.PacketOut(pack);
349 }
350
351
352 ostream &operator <<(ostream &out, const IPaddress &addr) {
353         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
354         out << int(host[0])
355                 << '.' << int(host[1])
356                 << '.' << int(host[2])
357                 << '.' << int(host[3]);
358         if (addr.port) {
359                 out << ':' << SDLNet_Read16(&addr.port);
360         }
361         return out;
362 }
363
364
365 const char *Packet::Type2String(uint8_t t) noexcept {
366         switch (t) {
367                 case Ping::TYPE:
368                         return "Ping";
369                 case Login::TYPE:
370                         return "Login";
371                 case Join::TYPE:
372                         return "Join";
373                 case Part::TYPE:
374                         return "Part";
375                 case PlayerUpdate::TYPE:
376                         return "PlayerUpdate";
377                 case SpawnEntity::TYPE:
378                         return "SpawnEntity";
379                 case DespawnEntity::TYPE:
380                         return "DespawnEntity";
381                 case EntityUpdate::TYPE:
382                         return "EntityUpdate";
383                 case PlayerCorrection::TYPE:
384                         return "PlayerCorrection";
385                 case ChunkBegin::TYPE:
386                         return "ChunkBegin";
387                 case ChunkData::TYPE:
388                         return "ChunkData";
389                 case BlockUpdate::TYPE:
390                         return "BlockUpdate";
391                 case Message::TYPE:
392                         return "Message";
393                 default:
394                         return "Unknown";
395         }
396 }
397
398 template<class T>
399 void Packet::Payload::Write(const T &src, size_t off) noexcept {
400         if ((length - off) < sizeof(T)) {
401                 // dismiss out of bounds write
402                 return;
403         }
404         *reinterpret_cast<T *>(&data[off]) = src;
405 }
406
407 template<class T>
408 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
409         if ((length - off) < sizeof(T)) {
410                 // dismiss out of bounds read
411                 return;
412         }
413         dst = *reinterpret_cast<T *>(&data[off]);
414 }
415
416 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
417         uint8_t *dst = &data[off];
418         size_t len = min(maxlen, length - off);
419         if (src.size() < len) {
420                 memset(dst, '\0', len);
421                 memcpy(dst, src.c_str(), src.size());
422         } else {
423                 memcpy(dst, src.c_str(), len);
424         }
425 }
426
427 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
428         size_t len = min(maxlen, length - off);
429         dst.clear();
430         dst.reserve(len);
431         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
432                 dst.push_back(data[off + i]);
433         }
434 }
435
436 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
437         // find the largest component
438         float largest = 0.0f;
439         int largest_index = -1;
440         for (int i = 0; i < 4; ++i) {
441                 float iabs = abs(val[i]);
442                 if (iabs > largest) {
443                         largest = iabs;
444                         largest_index = i;
445                 }
446         }
447         // make sure it's positive
448         const glm::quat q(val[largest_index] < 0.0f ? -val : val);
449         // move index to the two most significant bits
450         uint64_t packed = uint64_t(largest_index) << 62;
451         // we have to map from [-0.7072,0.7072] to [-524287,524287] and move into positive range
452         constexpr float conv = 524287.0f / 0.7072f;
453         // if largest is 1, the other three are 0
454         // precision of comparison is the interval of our mapping
455         if (abs(1.0 - largest) < (1.0f / conv)) {
456                 packed |= 0x7FFFF7FFFF7FFFF;
457         } else {
458                 // pack the three smaller components into 20bit ints each
459                 int shift = 40;
460                 for (int i = 0; i < 4; ++i) {
461                         if (i != largest_index) {
462                                 packed |= uint64_t(int(q[i] * conv) + 524287) << shift;
463                                 shift -= 20;
464                         }
465                 }
466         }
467         // and write it out
468         Write(packed, off);
469 }
470
471 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
472         // extract the 8 byte packed value
473         uint64_t packed = 0;
474         Read(packed, off);
475         // two most significant bits are the index of the largest (omitted) component
476         int largest_index = packed >> 62;
477         // if all other three are 0, largest is 1 and we can omit the conversion
478         if ((packed & 0xFFFFFFFFFFFFFFF) == 0x7FFFF7FFFF7FFFF) {
479                 val = { 0.0f, 0.0f, 0.0f, 0.0f };
480                 val[largest_index] = 1.0f;
481                 return;
482         }
483         // we have to map from [-524287,524287] to [-0.7072,0.7072]
484         constexpr float conv = 0.7072f / 524287.0f;
485         int shift = 40;
486         for (int i = 0; i < 4; ++i) {
487                 if (i != largest_index) {
488                         val[i] = float(int((packed >> shift) & 0xFFFFF) - 524287) * conv;
489                         shift -= 20;
490                 } else {
491                         // set to zero so the length of the other three can be determined
492                         val[i] = 0.0f;
493                 }
494         }
495         // omitted component squared is 1 - length squared of others
496         val[largest_index] = sqrt(1.0f - dot(val, val));
497         // and already normalized
498 }
499
500 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
501         Write(state.pos.chunk, off);
502         WritePackU(state.pos.block * (1.0f / ExactLocation::fscale), off + 12);
503         Write(state.velocity, off + 18);
504         Write(state.orient, off + 30);
505         WritePackN(state.pitch * PI_0p5_inv, off + 38);
506         WritePackN(state.yaw * PI_inv, off + 40);
507 }
508
509 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
510         Read(state.pos.chunk, off);
511         ReadPackU(state.pos.block, off + 12);
512         Read(state.velocity, off + 18);
513         Read(state.orient, off + 30);
514         ReadPackN(state.pitch, off + 38);
515         ReadPackN(state.yaw, off + 40);
516         state.pos.block *= ExactLocation::fscale;
517         state.pitch *= PI_0p5;
518         state.yaw *= PI;
519 }
520
521 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
522         WritePackB(state.pos.chunk - base, off);
523         WritePackU(state.pos.block * (1.0f / ExactLocation::fscale), off + 3);
524         Write(state.velocity, off + 9);
525         Write(state.orient, off + 21);
526         WritePackN(state.pitch * PI_0p5_inv, off + 29);
527         WritePackN(state.yaw * PI_inv, off + 31);
528 }
529
530 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
531         ReadPackB(state.pos.chunk, off);
532         ReadPackU(state.pos.block, off + 3);
533         Read(state.velocity, off + 9);
534         Read(state.orient, off + 21);
535         ReadPackN(state.pitch, off + 29);
536         ReadPackN(state.yaw, off + 31);
537         state.pos.chunk += base;
538         state.pos.block *= ExactLocation::fscale;
539         state.pitch *= PI_0p5;
540         state.yaw *= PI;
541 }
542
543 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
544         Write(int8_t(val.x), off);
545         Write(int8_t(val.y), off + 1);
546         Write(int8_t(val.z), off + 2);
547 }
548
549 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
550         int8_t conv = 0;
551         Read(conv, off);
552         val.x = conv;
553         Read(conv, off + 1);
554         val.y = conv;
555         Read(conv, off + 2);
556         val.z = conv;
557 }
558
559 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
560         int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
561         Write(raw, off);
562 }
563
564 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
565         int16_t raw = 0;
566         Read(raw, off);
567         val = raw * (1.0f/32767.0f);
568 }
569
570 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
571         WritePackN(val.x, off);
572         WritePackN(val.y, off + 2);
573         WritePackN(val.z, off + 4);
574 }
575
576 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
577         ReadPackN(val.x, off);
578         ReadPackN(val.y, off + 2);
579         ReadPackN(val.z, off + 4);
580 }
581
582 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
583         uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
584         Write(raw, off);
585 }
586
587 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
588         uint16_t raw = 0;
589         Read(raw, off);
590         val = raw * (1.0f/65535.0f);
591 }
592
593 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
594         WritePackU(val.x, off);
595         WritePackU(val.y, off + 2);
596         WritePackU(val.z, off + 4);
597 }
598
599 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
600         ReadPackU(val.x, off);
601         ReadPackU(val.y, off + 2);
602         ReadPackU(val.z, off + 4);
603 }
604
605
606 void Packet::Login::WritePlayerName(const string &name) noexcept {
607         WriteString(name, 0, 32);
608 }
609
610 void Packet::Login::ReadPlayerName(string &name) const noexcept {
611         ReadString(name, 0, 32);
612 }
613
614 void Packet::Join::WritePlayer(const Entity &player) noexcept {
615         Write(player.ID(), 0);
616         Write(player.GetState(), 4);
617 }
618
619 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
620         Read(id, 0);
621 }
622
623 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
624         Read(state, 4);
625 }
626
627 void Packet::Join::WriteWorldName(const string &name) noexcept {
628         WriteString(name, 46, 32);
629 }
630
631 void Packet::Join::ReadWorldName(string &name) const noexcept {
632         ReadString(name, 46, 32);
633 }
634
635 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
636         Write(state, 0);
637 }
638
639 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
640         Read(state, 0);
641 }
642
643 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
644         WritePackN(mov, 42);
645 }
646
647 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
648         ReadPackN(mov, 42);
649 }
650
651 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
652         Write(actions, 48);
653 }
654
655 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
656         Read(actions, 48);
657 }
658
659 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
660         Write(slot, 49);
661 }
662
663 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
664         Read(slot, 49);
665 }
666
667 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
668         Write(e.ID(), 0);
669         if (e.GetModel()) {
670                 Write(e.GetModel().GetModel().ID(), 4);
671         } else {
672                 Write(uint32_t(0), 4);
673         }
674         Write(e.GetState(), 8);
675         Write(e.Bounds(), 50);
676         uint32_t flags = 0;
677         if (e.WorldCollidable()) {
678                 flags |= 1;
679         }
680         Write(flags, 74);
681         WriteString(e.Name(), 78, 32);
682 }
683
684 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
685         Read(id, 0);
686 }
687
688 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
689         Read(id, 4);
690 }
691
692 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
693         EntityState state;
694         AABB bounds;
695         uint32_t flags = 0;
696         string name;
697
698         Read(state, 8);
699         Read(bounds, 50);
700         Read(flags, 74);
701         ReadString(name, 78, 32);
702
703         e.SetState(state);
704         e.Bounds(bounds);
705         e.WorldCollidable(flags & 1);
706         e.Name(name);
707 }
708
709 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
710         Write(id, 0);
711 }
712
713 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
714         Read(id, 0);
715 }
716
717 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
718         Write(count, 0);
719 }
720
721 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
722         Read(count, 0);
723 }
724
725 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
726         Write(base, 4);
727 }
728
729 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
730         Read(base, 4);
731 }
732
733 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
734         uint32_t off = GetSize(num);
735
736         Write(entity.ID(), off);
737         Write(entity.GetState(), base, off + 4);
738 }
739
740 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
741         uint32_t off = GetSize(num);
742         Read(id, off);
743 }
744
745 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
746         uint32_t off = GetSize(num);
747         Read(state, base, off + 4);
748 }
749
750 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
751         Write(s, 0);
752 }
753
754 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
755         Read(s, 0);
756 }
757
758 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
759         Write(player.GetState(), 2);
760 }
761
762 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
763         Read(state, 2);
764 }
765
766 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
767         Write(id, 0);
768 }
769
770 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
771         Read(id, 0);
772 }
773
774 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
775         Write(f, 4);
776 }
777
778 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
779         Read(f, 4);
780 }
781
782 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
783         Write(pos, 8);
784 }
785
786 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
787         Read(pos, 8);
788 }
789
790 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
791         Write(s, 20);
792 }
793
794 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
795         Read(s, 20);
796 }
797
798 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
799         Write(id, 0);
800 }
801
802 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
803         Read(id, 0);
804 }
805
806 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
807         Write(o, 4);
808 }
809
810 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
811         Read(o, 4);
812 }
813
814 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
815         Write(s, 8);
816 }
817
818 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
819         Read(s, 8);
820 }
821
822 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
823         size_t len = min(length - 12, l);
824         memcpy(&data[12], d, len);
825 }
826
827 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
828         size_t len = min(length - 12, l);
829         memcpy(d, &data[12], len);
830 }
831
832 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
833         Write(coords, 0);
834 }
835
836 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
837         Read(coords, 0);
838 }
839
840 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
841         Write(count, 12);
842 }
843
844 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
845         Read(count, 12);
846 }
847
848 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
849         uint32_t off = GetSize(num);
850         Write(index, off);
851 }
852
853 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
854         uint32_t off = GetSize(num);
855         Read(index, off);
856 }
857
858 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
859         uint32_t off = GetSize(num) + 2;
860         Write(block, off);
861 }
862
863 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
864         uint32_t off = GetSize(num) + 2;
865         Read(block, off);
866 }
867
868 void Packet::Message::WriteType(uint8_t type) noexcept {
869         Write(type, 0);
870 }
871
872 void Packet::Message::ReadType(uint8_t &type) const noexcept {
873         Read(type, 0);
874 }
875
876 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
877         Write(ref, 1);
878 }
879
880 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
881         Read(ref, 1);
882 }
883
884 void Packet::Message::WriteMessage(const string &msg) noexcept {
885         WriteString(msg, 5, MAX_MESSAGE_LEN);
886 }
887
888 void Packet::Message::ReadMessage(string &msg) const noexcept {
889         ReadString(msg, 5, MAX_MESSAGE_LEN);
890 }
891
892
893 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
894         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
895         switch (pack.Type()) {
896                 case Packet::Ping::TYPE:
897                         On(Packet::As<Packet::Ping>(udp_pack));
898                         break;
899                 case Packet::Login::TYPE:
900                         On(Packet::As<Packet::Login>(udp_pack));
901                         break;
902                 case Packet::Join::TYPE:
903                         On(Packet::As<Packet::Join>(udp_pack));
904                         break;
905                 case Packet::Part::TYPE:
906                         On(Packet::As<Packet::Part>(udp_pack));
907                         break;
908                 case Packet::PlayerUpdate::TYPE:
909                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
910                         break;
911                 case Packet::SpawnEntity::TYPE:
912                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
913                         break;
914                 case Packet::DespawnEntity::TYPE:
915                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
916                         break;
917                 case Packet::EntityUpdate::TYPE:
918                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
919                         break;
920                 case Packet::PlayerCorrection::TYPE:
921                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
922                         break;
923                 case Packet::ChunkBegin::TYPE:
924                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
925                         break;
926                 case Packet::ChunkData::TYPE:
927                         On(Packet::As<Packet::ChunkData>(udp_pack));
928                         break;
929                 case Packet::BlockUpdate::TYPE:
930                         On(Packet::As<Packet::BlockUpdate>(udp_pack));
931                         break;
932                 case Packet::Message::TYPE:
933                         On(Packet::As<Packet::Message>(udp_pack));
934                         break;
935                 default:
936                         // drop unknown or unhandled packets
937                         break;
938         }
939 }
940
941 }