1 #include "Connection.hpp"
2 #include "ConnectionHandler.hpp"
6 #include "../app/init.hpp"
7 #include "../model/Model.hpp"
8 #include "../world/Entity.hpp"
9 #include "../world/EntityState.hpp"
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;
33 Connection::Connection(const IPaddress &addr)
38 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
39 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
45 bool Connection::Matches(const IPaddress &remote) const noexcept {
46 return memcmp(&addr, &remote, sizeof(IPaddress)) == 0;
49 void Connection::FlagSend() noexcept {
53 void Connection::FlagRecv() noexcept {
57 bool Connection::ShouldPing() const noexcept {
58 return !closed && send_timer.HitOnce();
61 bool Connection::TimedOut() const noexcept {
62 return recv_timer.HitOnce();
65 void Connection::Update(int dt) {
66 send_timer.Update(dt);
67 recv_timer.Update(dt);
71 Handler().OnTimeout();
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++;
82 udp_pack.address = addr;
83 if (SDLNet_UDP_Send(sock, -1, &udp_pack) == 0) {
84 throw NetError("SDLNet_UDP_Send");
88 Handler().PacketOut(udp_pack);
89 Handler().PacketSent(seq);
96 void Connection::Received(const UDPpacket &udp_pack) {
97 Packet &pack = *reinterpret_cast<Packet *>(udp_pack.data);
100 int16_t diff = int16_t(pack.header.ctrl.seq) - int16_t(ctrl_out.ack);
105 ctrl_out.hist <<= diff;
106 ctrl_out.hist |= 1 << (diff - 1);
108 } else if (diff < 0 && diff >= -32) {
109 ctrl_out.hist |= 1 << (-diff - 1);
111 ctrl_out.ack = pack.header.ctrl.seq;
118 Packet::TControl ctrl_new = pack.header.ctrl;
119 Handler().PacketIn(udp_pack);
120 Handler().Handle(udp_pack);
123 // if the packet holds more recent information
124 // check if remote failed to ack one of our packets
125 diff = int16_t(ctrl_new.ack) - int16_t(ctrl_in.ack);
126 // should always be true, but you never know…
128 for (int i = 0; i < diff; ++i) {
129 if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
130 Handler().PacketLost(ctrl_in.ack - 32 + i);
134 // check for newly ack'd packets
135 for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
136 if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
137 Handler().PacketReceived(s);
144 bool Packet::TControl::Acks(uint16_t s) const noexcept {
145 int16_t diff = int16_t(ack) - int16_t(s);
146 if (diff == 0) return true;
147 if (diff < 0 || diff > 32) return false;
148 return (hist & (1 << (diff - 1))) != 0;
151 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
152 Packet::Make<Packet::Ping>(udp_pack);
153 return Send(udp_pack, sock);
157 ConnectionHandler::ConnectionHandler()
159 , packets_received(0)
169 Uint32 now = SDL_GetTicks();
170 for (Uint32 &s : stamps) {
176 void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
177 if (!SamplePacket(seq)) {
180 stamp_cursor = (stamp_cursor + 1) % 16;
181 stamps[stamp_cursor] = SDL_GetTicks();
185 void ConnectionHandler::PacketLost(uint16_t seq) {
192 void ConnectionHandler::PacketReceived(uint16_t seq) {
193 OnPacketReceived(seq);
199 void ConnectionHandler::UpdatePacketLoss() noexcept {
200 unsigned int packets_total = packets_lost + packets_received;
201 if (packets_total >= 256) {
202 packet_loss = float(packets_lost) / float(packets_total);
204 packets_received = 0;
208 void ConnectionHandler::UpdateRTT(std::uint16_t seq) noexcept {
209 if (!SamplePacket(seq)) return;
210 int diff = HeadDiff(seq);
211 if (diff > 0 || diff < -15) {
212 // packet outside observed time frame
215 int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
216 rtt += (cur_rtt - rtt) * 0.1f;
219 bool ConnectionHandler::SamplePacket(std::uint16_t seq) const noexcept {
220 // only sample every eighth packet
224 int ConnectionHandler::HeadDiff(std::uint16_t seq) const noexcept {
225 int16_t diff = int16_t(seq) - int16_t(stamp_last);
229 void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
230 rx_bytes += pack.len + 20; // I know, I know, it's an estimate (about 48 for IPv6)
234 void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
235 tx_bytes += pack.len + 20;
239 void ConnectionHandler::UpdateStats() noexcept {
240 Uint32 now = SDL_GetTicks();
241 if (now >= next_sample) {
242 tx_kbps = float(tx_bytes) * (1.0f / 1024.0f);
243 rx_kbps = float(rx_bytes) * (1.0f / 1024.0f);
251 ostream &operator <<(ostream &out, const IPaddress &addr) {
252 const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
254 << '.' << int(host[1])
255 << '.' << int(host[2])
256 << '.' << int(host[3]);
258 out << ':' << SDLNet_Read16(&addr.port);
264 const char *Packet::Type2String(uint8_t t) noexcept {
274 case PlayerUpdate::TYPE:
275 return "PlayerUpdate";
276 case SpawnEntity::TYPE:
277 return "SpawnEntity";
278 case DespawnEntity::TYPE:
279 return "DespawnEntity";
280 case EntityUpdate::TYPE:
281 return "EntityUpdate";
282 case PlayerCorrection::TYPE:
283 return "PlayerCorrection";
284 case ChunkBegin::TYPE:
286 case ChunkData::TYPE:
288 case BlockUpdate::TYPE:
289 return "BlockUpdate";
298 void Packet::Payload::Write(const T &src, size_t off) noexcept {
299 if ((length - off) < sizeof(T)) {
300 // dismiss out of bounds write
303 *reinterpret_cast<T *>(&data[off]) = src;
307 void Packet::Payload::Read(T &dst, size_t off) const noexcept {
308 if ((length - off) < sizeof(T)) {
309 // dismiss out of bounds read
312 dst = *reinterpret_cast<T *>(&data[off]);
315 void Packet::Payload::WriteString(const string &src, size_t off, size_t maxlen) noexcept {
316 uint8_t *dst = &data[off];
317 size_t len = min(maxlen, length - off);
318 if (src.size() < len) {
319 memset(dst, '\0', len);
320 memcpy(dst, src.c_str(), src.size());
322 memcpy(dst, src.c_str(), len);
326 void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const noexcept {
327 size_t len = min(maxlen, length - off);
330 for (size_t i = 0; i < len && data[off + i] != '\0'; ++i) {
331 dst.push_back(data[off + i]);
335 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
336 WritePackN(val.w, off);
337 WritePackN(val.x, off + 2);
338 WritePackN(val.y, off + 4);
339 WritePackN(val.z, off + 6);
342 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
343 ReadPackN(val.w, off);
344 ReadPackN(val.x, off + 2);
345 ReadPackN(val.y, off + 4);
346 ReadPackN(val.z, off + 6);
347 val = normalize(val);
350 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
351 Write(state.chunk_pos, off);
352 WritePackU(state.block_pos * (1.0f / 16.0f), off + 12);
353 Write(state.velocity, off + 18);
354 Write(state.orient, off + 30);
355 WritePackN(state.pitch * PI_0p5_inv, off + 38);
356 WritePackN(state.yaw * PI_inv, off + 40);
359 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
360 Read(state.chunk_pos, off);
361 ReadPackU(state.block_pos, off + 12);
362 Read(state.velocity, off + 18);
363 Read(state.orient, off + 30);
364 ReadPackN(state.pitch, off + 38);
365 ReadPackN(state.yaw, off + 40);
366 state.block_pos *= 16.0f;
367 state.pitch *= PI_0p5;
371 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
372 WritePackB(state.chunk_pos - base, off);
373 WritePackU(state.block_pos * (1.0f / 16.0f), off + 3);
374 Write(state.velocity, off + 9);
375 Write(state.orient, off + 21);
376 WritePackN(state.pitch * PI_0p5_inv, off + 29);
377 WritePackN(state.yaw * PI_inv, off + 31);
380 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
381 ReadPackB(state.chunk_pos, off);
382 ReadPackU(state.block_pos, off + 3);
383 Read(state.velocity, off + 9);
384 Read(state.orient, off + 21);
385 ReadPackN(state.pitch, off + 29);
386 ReadPackN(state.yaw, off + 31);
387 state.chunk_pos += base;
388 state.block_pos *= 16.0f;
389 state.pitch *= PI_0p5;
393 void Packet::Payload::WritePackB(const glm::ivec3 &val, size_t off) noexcept {
394 Write(int8_t(val.x), off);
395 Write(int8_t(val.y), off + 1);
396 Write(int8_t(val.z), off + 2);
399 void Packet::Payload::ReadPackB(glm::ivec3 &val, size_t off) const noexcept {
409 void Packet::Payload::WritePackN(float val, size_t off) noexcept {
410 int16_t raw = glm::clamp(glm::round(val * 32767.0f), -32767.0f, 32767.0f);
414 void Packet::Payload::ReadPackN(float &val, size_t off) const noexcept {
417 val = raw * (1.0f/32767.0f);
420 void Packet::Payload::WritePackN(const glm::vec3 &val, size_t off) noexcept {
421 WritePackN(val.x, off);
422 WritePackN(val.y, off + 2);
423 WritePackN(val.z, off + 4);
426 void Packet::Payload::ReadPackN(glm::vec3 &val, size_t off) const noexcept {
427 ReadPackN(val.x, off);
428 ReadPackN(val.y, off + 2);
429 ReadPackN(val.z, off + 4);
432 void Packet::Payload::WritePackU(float val, size_t off) noexcept {
433 uint16_t raw = glm::clamp(glm::round(val * 65535.0f), 0.0f, 65535.0f);
437 void Packet::Payload::ReadPackU(float &val, size_t off) const noexcept {
440 val = raw * (1.0f/65535.0f);
443 void Packet::Payload::WritePackU(const glm::vec3 &val, size_t off) noexcept {
444 WritePackU(val.x, off);
445 WritePackU(val.y, off + 2);
446 WritePackU(val.z, off + 4);
449 void Packet::Payload::ReadPackU(glm::vec3 &val, size_t off) const noexcept {
450 ReadPackU(val.x, off);
451 ReadPackU(val.y, off + 2);
452 ReadPackU(val.z, off + 4);
456 void Packet::Login::WritePlayerName(const string &name) noexcept {
457 WriteString(name, 0, 32);
460 void Packet::Login::ReadPlayerName(string &name) const noexcept {
461 ReadString(name, 0, 32);
464 void Packet::Join::WritePlayer(const Entity &player) noexcept {
465 Write(player.ID(), 0);
466 Write(player.GetState(), 4);
469 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
473 void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
477 void Packet::Join::WriteWorldName(const string &name) noexcept {
478 WriteString(name, 46, 32);
481 void Packet::Join::ReadWorldName(string &name) const noexcept {
482 ReadString(name, 46, 32);
485 void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
489 void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
493 void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
497 void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
501 void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
505 void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
509 void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
513 void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
517 void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
520 Write(e.GetModel().GetModel().ID(), 4);
522 Write(uint32_t(0), 4);
524 Write(e.GetState(), 8);
525 Write(e.Bounds(), 50);
527 if (e.WorldCollidable()) {
531 WriteString(e.Name(), 78, 32);
534 void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
538 void Packet::SpawnEntity::ReadModelID(uint32_t &id) const noexcept {
542 void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
551 ReadString(name, 78, 32);
555 e.WorldCollidable(flags & 1);
559 void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
563 void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
567 void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
571 void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
575 void Packet::EntityUpdate::WriteChunkBase(const glm::ivec3 &base) noexcept {
579 void Packet::EntityUpdate::ReadChunkBase(glm::ivec3 &base) const noexcept {
583 void Packet::EntityUpdate::WriteEntity(const Entity &entity, const glm::ivec3 &base, uint32_t num) noexcept {
584 uint32_t off = GetSize(num);
586 Write(entity.ID(), off);
587 Write(entity.GetState(), base, off + 4);
590 void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
591 uint32_t off = GetSize(num);
595 void Packet::EntityUpdate::ReadEntityState(EntityState &state, const glm::ivec3 &base, uint32_t num) const noexcept {
596 uint32_t off = GetSize(num);
597 Read(state, base, off + 4);
600 void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
604 void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
608 void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
609 Write(player.GetState(), 2);
612 void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
616 void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
620 void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
624 void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
628 void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
632 void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
636 void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
640 void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
644 void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
648 void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
652 void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
656 void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
660 void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
664 void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
668 void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
672 void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
673 size_t len = min(length - 12, l);
674 memcpy(&data[12], d, len);
677 void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
678 size_t len = min(length - 12, l);
679 memcpy(d, &data[12], len);
682 void Packet::BlockUpdate::WriteChunkCoords(const glm::ivec3 &coords) noexcept {
686 void Packet::BlockUpdate::ReadChunkCoords(glm::ivec3 &coords) const noexcept {
690 void Packet::BlockUpdate::WriteBlockCount(uint32_t count) noexcept {
694 void Packet::BlockUpdate::ReadBlockCount(uint32_t &count) const noexcept {
698 void Packet::BlockUpdate::WriteIndex(uint16_t index, uint32_t num) noexcept {
699 uint32_t off = GetSize(num);
703 void Packet::BlockUpdate::ReadIndex(uint16_t &index, uint32_t num) const noexcept {
704 uint32_t off = GetSize(num);
708 void Packet::BlockUpdate::WriteBlock(const Block &block, uint32_t num) noexcept {
709 uint32_t off = GetSize(num) + 2;
713 void Packet::BlockUpdate::ReadBlock(Block &block, uint32_t num) const noexcept {
714 uint32_t off = GetSize(num) + 2;
718 void Packet::Message::WriteType(uint8_t type) noexcept {
722 void Packet::Message::ReadType(uint8_t &type) const noexcept {
726 void Packet::Message::WriteReferral(uint32_t ref) noexcept {
730 void Packet::Message::ReadReferral(uint32_t &ref) const noexcept {
734 void Packet::Message::WriteMessage(const string &msg) noexcept {
735 WriteString(msg, 5, MAX_MESSAGE_LEN);
738 void Packet::Message::ReadMessage(string &msg) const noexcept {
739 ReadString(msg, 5, MAX_MESSAGE_LEN);
743 void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
744 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
745 switch (pack.Type()) {
746 case Packet::Ping::TYPE:
747 On(Packet::As<Packet::Ping>(udp_pack));
749 case Packet::Login::TYPE:
750 On(Packet::As<Packet::Login>(udp_pack));
752 case Packet::Join::TYPE:
753 On(Packet::As<Packet::Join>(udp_pack));
755 case Packet::Part::TYPE:
756 On(Packet::As<Packet::Part>(udp_pack));
758 case Packet::PlayerUpdate::TYPE:
759 On(Packet::As<Packet::PlayerUpdate>(udp_pack));
761 case Packet::SpawnEntity::TYPE:
762 On(Packet::As<Packet::SpawnEntity>(udp_pack));
764 case Packet::DespawnEntity::TYPE:
765 On(Packet::As<Packet::DespawnEntity>(udp_pack));
767 case Packet::EntityUpdate::TYPE:
768 On(Packet::As<Packet::EntityUpdate>(udp_pack));
770 case Packet::PlayerCorrection::TYPE:
771 On(Packet::As<Packet::PlayerCorrection>(udp_pack));
773 case Packet::ChunkBegin::TYPE:
774 On(Packet::As<Packet::ChunkBegin>(udp_pack));
776 case Packet::ChunkData::TYPE:
777 On(Packet::As<Packet::ChunkData>(udp_pack));
779 case Packet::BlockUpdate::TYPE:
780 On(Packet::As<Packet::BlockUpdate>(udp_pack));
782 case Packet::Message::TYPE:
783 On(Packet::As<Packet::Message>(udp_pack));
786 // drop unknown or unhandled packets