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