]> git.localhorst.tv Git - blank.git/blob - src/net/net.cpp
added message packet
[blank.git] / src / net / net.cpp
1 #include "Connection.hpp"
2 #include "ConnectionHandler.hpp"
3 #include "io.hpp"
4 #include "Packet.hpp"
5
6 #include "../app/init.hpp"
7 #include "../model/Model.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/EntityState.hpp"
10
11 #include <cstring>
12
13 using namespace std;
14
15
16 namespace blank {
17
18 constexpr size_t Packet::Ping::MAX_LEN;
19 constexpr size_t Packet::Login::MAX_LEN;
20 constexpr size_t Packet::Join::MAX_LEN;
21 constexpr size_t Packet::Part::MAX_LEN;
22 constexpr size_t Packet::PlayerUpdate::MAX_LEN;
23 constexpr size_t Packet::SpawnEntity::MAX_LEN;
24 constexpr size_t Packet::DespawnEntity::MAX_LEN;
25 constexpr size_t Packet::EntityUpdate::MAX_LEN;
26 constexpr size_t Packet::PlayerCorrection::MAX_LEN;
27 constexpr size_t Packet::ChunkBegin::MAX_LEN;
28 constexpr size_t Packet::ChunkData::MAX_LEN;
29 constexpr size_t Packet::BlockUpdate::MAX_LEN;
30 constexpr size_t Packet::Message::MAX_LEN;
31 constexpr size_t Packet::Message::MAX_MESSAGE_LEN;
32
33 Connection::Connection(const IPaddress &addr)
34 : handler(nullptr)
35 , addr(addr)
36 , send_timer(500)
37 , recv_timer(10000)
38 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
39 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
40 , closed(false) {
41         send_timer.Start();
42         recv_timer.Start();
43 }
44
45 bool Connection::Matches(const IPaddress &remote) const noexcept {
46         return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
47 }
48
49 void Connection::FlagSend() noexcept {
50         send_timer.Reset();
51 }
52
53 void Connection::FlagRecv() noexcept {
54         recv_timer.Reset();
55 }
56
57 bool Connection::ShouldPing() const noexcept {
58         return !closed && send_timer.HitOnce();
59 }
60
61 bool Connection::TimedOut() const noexcept {
62         return recv_timer.HitOnce();
63 }
64
65 void Connection::Update(int dt) {
66         send_timer.Update(dt);
67         recv_timer.Update(dt);
68         if (TimedOut()) {
69                 Close();
70                 if (HasHandler()) {
71                         Handler().OnTimeout();
72                 }
73         }
74 }
75
76
77 uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
78         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
79         pack.header.ctrl = ctrl_out;
80         uint16_t seq = ctrl_out.seq++;
81
82         udp_pack.address = addr;
83         if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
84                 throw NetError("SDLNet_UDP_Send");
85         }
86
87         FlagSend();
88         return seq;
89 }
90
91 void Connection::Received(const UDPpacket &udp_pack) {
92         Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
93
94         // ack to the remote
95         int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
96         if (diff > 0) {
97                 if (diff >= 32) {
98                         ctrl_out.hist = 0;
99                 } else {
100                         ctrl_out.hist <<= diff;
101                         ctrl_out.hist |= 1 << (diff - 1);
102                 }
103         } else if (diff < 0 && diff >= -32) {
104                 ctrl_out.hist |= 1 << (-diff - 1);
105         }
106         ctrl_out.ack = pack.header.ctrl.seq;
107         FlagRecv();
108
109         if (!HasHandler()) {
110                 return;
111         }
112
113         Packet::TControl ctrl_new = pack.header.ctrl;
114         Handler().Handle(udp_pack);
115
116         if (diff > 0) {
117                 // if the packet holds more recent information
118                 // check if remote failed to ack one of our packets
119                 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
120                 // should always be true, but you never know…
121                 if (diff > 0) {
122                         for (int i = 0; i < diff; ++i) {
123                                 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
124                                         Handler().PacketLost(ctrl_in.ack - 32 + i);
125                                 }
126                         }
127                 }
128                 // check for newly ack'd packets
129                 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
130                         if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
131                                 Handler().PacketReceived(s);
132                         }
133                 }
134                 ctrl_in = ctrl_new;
135         }
136 }
137
138 bool Packet::TControl::Acks(uint16_t s) const noexcept {
139         int16_t diff = int16_t(ack) - int16_t(s);
140         if (diff == 0) return true;
141         if (diff < 0 || diff > 32) return false;
142         return (hist & (1 << (diff - 1))) != 0;
143 }
144
145 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
146         Packet::Make<Packet::Ping>(udp_pack);
147         return Send(udp_pack, sock);
148 }
149
150
151 ConnectionHandler::ConnectionHandler()
152 : packets_lost(0)
153 , packets_received(0)
154 , packet_loss(0.0f) {
155
156 }
157
158 void ConnectionHandler::PacketLost(uint16_t seq) {
159         OnPacketLost(seq);
160         ++packets_lost;
161         UpdatePacketLoss();
162 }
163
164 void ConnectionHandler::PacketReceived(uint16_t seq) {
165         OnPacketReceived(seq);
166         ++packets_received;
167         UpdatePacketLoss();
168 }
169
170 void ConnectionHandler::UpdatePacketLoss() noexcept {
171         unsigned int packets_total = packets_lost + packets_received;
172         if (packets_total >= 256) {
173                 packet_loss = float(packets_lost) / float(packets_total);
174                 packets_lost = 0;
175                 packets_received = 0;
176         }
177 }
178
179
180 ostream &operator <<(ostream &out, const IPaddress &addr) {
181         const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
182         out << int(host[0])
183                 << '.' << int(host[1])
184                 << '.' << int(host[2])
185                 << '.' << int(host[3]);
186         if (addr.port) {
187                 out << ':' << SDLNet_Read16(&addr.port);
188         }
189         return out;
190 }
191
192
193 const char *Packet::Type2String(uint8_t t) noexcept {
194         switch (t) {
195                 case Ping::TYPE:
196                         return "Ping";
197                 case Login::TYPE:
198                         return "Login";
199                 case Join::TYPE:
200                         return "Join";
201                 case Part::TYPE:
202                         return "Part";
203                 case PlayerUpdate::TYPE:
204                         return "PlayerUpdate";
205                 case SpawnEntity::TYPE:
206                         return "SpawnEntity";
207                 case DespawnEntity::TYPE:
208                         return "DespawnEntity";
209                 case EntityUpdate::TYPE:
210                         return "EntityUpdate";
211                 case PlayerCorrection::TYPE:
212                         return "PlayerCorrection";
213                 case ChunkBegin::TYPE:
214                         return "ChunkBegin";
215                 case ChunkData::TYPE:
216                         return "ChunkData";
217                 case BlockUpdate::TYPE:
218                         return "BlockUpdate";
219                 case Message::TYPE:
220                         return "Message";
221                 default:
222                         return "Unknown";
223         }
224 }
225
226 template<class T>
227 void Packet::Payload::Write(const T &src, size_t off) noexcept {
228         if ((length - off) < sizeof(T)) {
229                 // dismiss out of bounds write
230                 return;
231         }
232         *reinterpret_cast<T *>(&data[off]) = src;
233 }
234
235 template<class T>
236 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
237         if ((length - off) < sizeof(T)) {
238                 // dismiss out of bounds read
239                 return;
240         }
241         dst = *reinterpret_cast<T *>(&data[off]);
242 }
243
244 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
245         uint8_t *dst = &data[off];
246         size_t len = min(maxlen, length - off);
247         if (src.size() < len) {
248                 memset(dst, '\0', len);
249                 memcpy(dst, src.c_str(), src.size());
250         } else {
251                 memcpy(dst, src.c_str(), len);
252         }
253 }
254
255 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
256         size_t len = min(maxlen, length - off);
257         dst.clear();
258         dst.reserve(len);
259         for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
260                 dst.push_back(data[off + i]);
261         }
262 }
263
264
265 void Packet::Login::WritePlayerName(const string &name) noexcept {
266         WriteString(name, 0, 32);
267 }
268
269 void Packet::Login::ReadPlayerName(string &name) const noexcept {
270         ReadString(name, 0, 32);
271 }
272
273 void Packet::Join::WritePlayer(const Entity &player) noexcept {
274         Write(player.ID(), 0);
275         Write(player.GetState(), 4);
276 }
277
278 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
279         Read(id, 0);
280 }
281
282 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
283         Read(state, 4);
284 }
285
286 void Packet::Join::WriteWorldName(const string &name) noexcept {
287         WriteString(name, 68, 32);
288 }
289
290 void Packet::Join::ReadWorldName(string &name) const noexcept {
291         ReadString(name, 68, 32);
292 }
293
294 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
295         Write(state, 0);
296 }
297
298 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
299         Read(state, 0);
300 }
301
302 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
303         glm::ivec3 conv = clamp(glm::ivec3(mov * 32767.0f), -32767, 32767);
304         Write(int16_t(conv.x), 64);
305         Write(int16_t(conv.y), 66);
306         Write(int16_t(conv.z), 68);
307 }
308
309 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
310         int16_t x, y, z;
311         Read(x, 64);
312         Read(y, 66);
313         Read(z, 68);
314         mov = glm::vec3(x, y, z) * .00003051850947599719f;
315 }
316
317 void Packet::PlayerUpdate::WritePitch(float pitch) noexcept {
318         int16_t conv = pitch * 20860.12008116853786870640f;
319         Write(conv, 70);
320 }
321
322 void Packet::PlayerUpdate::ReadPitch(float &pitch) const noexcept {
323         int16_t conv = 0;
324         Read(conv, 70);
325         pitch = conv * .00004793836258415163f;
326 }
327
328 void Packet::PlayerUpdate::WriteYaw(float yaw) noexcept {
329         int16_t conv = yaw * 10430.06004058426893435320f;
330         Write(conv, 72);
331 }
332
333 void Packet::PlayerUpdate::ReadYaw(float &yaw) const noexcept {
334         int16_t conv = 0;
335         Read(conv, 72);
336         yaw = conv * .00009587672516830326f;
337 }
338
339 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
340         Write(actions, 74);
341 }
342
343 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
344         Read(actions, 74);
345 }
346
347 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
348         Write(slot, 75);
349 }
350
351 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
352         Read(slot, 75);
353 }
354
355 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
356         Write(e.ID(), 0);
357         if (e.GetModel()) {
358                 Write(e.GetModel().GetModel().ID(), 4);
359         } else {
360                 Write(uint32_t(0), 4);
361         }
362         Write(e.GetState(), 8);
363         Write(e.Bounds(), 72);
364         uint32_t flags = 0;
365         if (e.WorldCollidable()) {
366                 flags |= 1;
367         }
368         Write(flags, 96);
369         WriteString(e.Name(), 100, 32);
370 }
371
372 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
373         Read(id, 0);
374 }
375
376 void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
377         Read(id, 4);
378 }
379
380 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
381         EntityState state;
382         AABB bounds;
383         uint32_t flags = 0;
384         string name;
385
386         Read(state, 8);
387         Read(bounds, 72);
388         Read(flags, 96);
389         ReadString(name, 100, 32);
390
391         e.SetState(state);
392         e.Bounds(bounds);
393         e.WorldCollidable(flags & 1);
394         e.Name(name);
395 }
396
397 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
398         Write(id, 0);
399 }
400
401 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
402         Read(id, 0);
403 }
404
405 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
406         Write(count, 0);
407 }
408
409 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
410         Read(count, 0);
411 }
412
413 void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
414         uint32_t off = GetSize(num);
415
416         Write(entity.ID(), off);
417         Write(entity.GetState(), off + 4);
418 }
419
420 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
421         uint32_t off = GetSize(num);
422         Read(id, off);
423 }
424
425 void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
426         uint32_t off = GetSize(num);
427         Read(state, off + 4);
428 }
429
430 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
431         Write(s, 0);
432 }
433
434 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
435         Read(s, 0);
436 }
437
438 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
439         Write(player.GetState(), 2);
440 }
441
442 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
443         Read(state, 2);
444 }
445
446 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
447         Write(id, 0);
448 }
449
450 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
451         Read(id, 0);
452 }
453
454 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
455         Write(f, 4);
456 }
457
458 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
459         Read(f, 4);
460 }
461
462 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
463         Write(pos, 8);
464 }
465
466 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
467         Read(pos, 8);
468 }
469
470 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
471         Write(s, 20);
472 }
473
474 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
475         Read(s, 20);
476 }
477
478 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
479         Write(id, 0);
480 }
481
482 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
483         Read(id, 0);
484 }
485
486 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
487         Write(o, 4);
488 }
489
490 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
491         Read(o, 4);
492 }
493
494 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
495         Write(s, 8);
496 }
497
498 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
499         Read(s, 8);
500 }
501
502 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
503         size_t len = min(length - 12, l);
504         memcpy(&data[12], d, len);
505 }
506
507 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
508         size_t len = min(length - 12, l);
509         memcpy(d, &data[12], len);
510 }
511
512 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
513         Write(coords, 0);
514 }
515
516 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
517         Read(coords, 0);
518 }
519
520 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
521         Write(count, 12);
522 }
523
524 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
525         Read(count, 12);
526 }
527
528 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
529         uint32_t off = GetSize(num);
530         Write(index, off);
531 }
532
533 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
534         uint32_t off = GetSize(num);
535         Read(index, off);
536 }
537
538 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
539         uint32_t off = GetSize(num) + 2;
540         Write(block, off);
541 }
542
543 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
544         uint32_t off = GetSize(num) + 2;
545         Read(block, off);
546 }
547
548 void Packet::Message::WriteType(uint8_t type) noexcept {
549         Write(type, 0);
550 }
551
552 void Packet::Message::ReadType(uint8_t &type) const noexcept {
553         Read(type, 0);
554 }
555
556 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
557         Write(ref, 1);
558 }
559
560 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
561         Read(ref, 1);
562 }
563
564 void Packet::Message::WriteMessage(const string &msg) noexcept {
565         WriteString(msg, 5, MAX_MESSAGE_LEN);
566 }
567
568 void Packet::Message::ReadMessage(string &msg) const noexcept {
569         ReadString(msg, 5, MAX_MESSAGE_LEN);
570 }
571
572
573 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
574         const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
575         switch (pack.Type()) {
576                 case Packet::Ping::TYPE:
577                         On(Packet::As<Packet::Ping>(udp_pack));
578                         break;
579                 case Packet::Login::TYPE:
580                         On(Packet::As<Packet::Login>(udp_pack));
581                         break;
582                 case Packet::Join::TYPE:
583                         On(Packet::As<Packet::Join>(udp_pack));
584                         break;
585                 case Packet::Part::TYPE:
586                         On(Packet::As<Packet::Part>(udp_pack));
587                         break;
588                 case Packet::PlayerUpdate::TYPE:
589                         On(Packet::As<Packet::PlayerUpdate>(udp_pack));
590                         break;
591                 case Packet::SpawnEntity::TYPE:
592                         On(Packet::As<Packet::SpawnEntity>(udp_pack));
593                         break;
594                 case Packet::DespawnEntity::TYPE:
595                         On(Packet::As<Packet::DespawnEntity>(udp_pack));
596                         break;
597                 case Packet::EntityUpdate::TYPE:
598                         On(Packet::As<Packet::EntityUpdate>(udp_pack));
599                         break;
600                 case Packet::PlayerCorrection::TYPE:
601                         On(Packet::As<Packet::PlayerCorrection>(udp_pack));
602                         break;
603                 case Packet::ChunkBegin::TYPE:
604                         On(Packet::As<Packet::ChunkBegin>(udp_pack));
605                         break;
606                 case Packet::ChunkData::TYPE:
607                         On(Packet::As<Packet::ChunkData>(udp_pack));
608                         break;
609                 case Packet::BlockUpdate::TYPE:
610                         On(Packet::As<Packet::BlockUpdate>(udp_pack));
611                         break;
612                 case Packet::Message::TYPE:
613                         On(Packet::As<Packet::Message>(udp_pack));
614                         break;
615                 default:
616                         // drop unknown or unhandled packets
617                         break;
618         }
619 }
620
621 }