]> git.localhorst.tv Git - blank.git/blobdiff - src/net/net.cpp
glm backwards compatibility
[blank.git] / src / net / net.cpp
index 59176aac8251edcf5f18876d65060ccb80093657..4f7fc66647a2817eb8f87133f4f937e382096097 100644 (file)
@@ -1,9 +1,11 @@
+#include "CongestionControl.hpp"
 #include "Connection.hpp"
 #include "ConnectionHandler.hpp"
 #include "io.hpp"
 #include "Packet.hpp"
 
 #include "../app/init.hpp"
+#include "../geometry/const.hpp"
 #include "../model/Model.hpp"
 #include "../world/Entity.hpp"
 #include "../world/EntityState.hpp"
@@ -30,10 +32,175 @@ constexpr size_t Packet::BlockUpdate::MAX_LEN;
 constexpr size_t Packet::Message::MAX_LEN;
 constexpr size_t Packet::Message::MAX_MESSAGE_LEN;
 
+
+CongestionControl::CongestionControl()
+// I know, I know, it's an estimate (about 20 for IPv4, 48 for IPv6)
+: packet_overhead(20)
+// only sample every eighth packet for measuring RTT
+, sample_skip(8)
+, packets_lost(0)
+, packets_received(0)
+, packet_loss(0.0f)
+, stamp_last(0)
+, rtt(64.0f)
+, next_sample(1000)
+, tx_bytes(0)
+, rx_bytes(0)
+, tx_kbps(0.0f)
+, rx_kbps(0.0f)
+, mode(GOOD)
+// rtt > 75ms or packet loss > 5% is BAD
+, bad_rtt(75.0f)
+, bad_loss(0.05f)
+// rtt > 150ms or packet loss > 15% is UGLY
+, ugly_rtt(150.0f)
+, ugly_loss(0.15f)
+, mode_keep_time(1000) {
+       Uint32 now = SDL_GetTicks();
+       for (Uint32 &s : stamps) {
+               s = now;
+       }
+       next_sample += now;
+       mode_entered = now;
+       mode_reset = now;
+       mode_step = now;
+}
+
+void CongestionControl::PacketSent(uint16_t seq) noexcept {
+       if (!SamplePacket(seq)) {
+               return;
+       }
+       stamps[SampleIndex(seq)] = SDL_GetTicks();
+       stamp_last = seq;
+}
+
+void CongestionControl::PacketLost(uint16_t seq) noexcept {
+       ++packets_lost;
+       UpdatePacketLoss();
+       UpdateRTT(seq);
+}
+
+void CongestionControl::PacketReceived(uint16_t seq) noexcept {
+       ++packets_received;
+       UpdatePacketLoss();
+       UpdateRTT(seq);
+}
+
+void CongestionControl::UpdatePacketLoss() noexcept {
+       unsigned int packets_total = packets_lost + packets_received;
+       if (packets_total >= 256) {
+               packet_loss = float(packets_lost) / float(packets_total);
+               packets_lost = 0;
+               packets_received = 0;
+       }
+}
+
+void CongestionControl::UpdateRTT(uint16_t seq) noexcept {
+       if (!SamplePacket(seq)) return;
+       int16_t diff = int16_t(stamp_last) - int16_t(seq);
+       if (diff < 0 || diff > int(15 * sample_skip)) {
+               // packet outside observed frame
+               return;
+       }
+       int cur_rtt = SDL_GetTicks() - stamps[SampleIndex(seq)];
+       rtt += (cur_rtt - rtt) * 0.1f;
+}
+
+bool CongestionControl::SamplePacket(uint16_t seq) const noexcept {
+       return seq % sample_skip == 0;
+}
+
+size_t CongestionControl::SampleIndex(uint16_t seq) const noexcept {
+       return (seq / sample_skip) % 16;
+}
+
+void CongestionControl::PacketIn(const UDPpacket &pack) noexcept {
+       rx_bytes += pack.len + packet_overhead;
+       UpdateStats();
+}
+
+void CongestionControl::PacketOut(const UDPpacket &pack) noexcept {
+       tx_bytes += pack.len + packet_overhead;
+       UpdateStats();
+}
+
+void CongestionControl::UpdateStats() noexcept {
+       Uint32 now = SDL_GetTicks();
+       if (now < next_sample) {
+               // not yet
+               return;
+       }
+       tx_kbps = float(tx_bytes) * (1.0f / 1024.0f);
+       rx_kbps = float(rx_bytes) * (1.0f / 1024.0f);
+       tx_bytes = 0;
+       rx_bytes = 0;
+       next_sample += 1000;
+       UpdateMode();
+}
+
+void CongestionControl::UpdateMode() noexcept {
+       Mode now_mode = Conditions();
+       if (now_mode > mode) {
+               ChangeMode(now_mode);
+       } else if (now_mode < mode) {
+               CheckUpgrade(now_mode);
+       } else {
+               KeepMode();
+       }
+}
+
+void CongestionControl::CheckUpgrade(Mode m) noexcept {
+       Uint32 now = SDL_GetTicks();
+       Uint32 time_in_mode = now - mode_entered;
+       if (time_in_mode < mode_keep_time) {
+               return;
+       }
+       ChangeMode(m);
+}
+
+void CongestionControl::ChangeMode(Mode m) noexcept {
+       Uint32 now = SDL_GetTicks();
+       if (m > mode) {
+               // changed to worse mode
+               // if we spent less than 10 seconds in better mode
+               // double keep time till up to 64 seconds
+               if (now - mode_entered < 10000) {
+                       if (mode_keep_time < 64000) {
+                               mode_keep_time *= 2;
+                       }
+               }
+       }
+       mode = m;
+       mode_entered = now;
+       mode_reset = mode_entered;
+}
+
+void CongestionControl::KeepMode() noexcept {
+       mode_reset = SDL_GetTicks();
+       // if in good mode for 10 seconds, halve keep time till down to one second
+       if (mode == GOOD && mode_keep_time > 1000 && mode_step - mode_reset > 10000) {
+               mode_keep_time /= 2;
+               mode_step = mode_reset;
+       }
+}
+
+CongestionControl::Mode CongestionControl::Conditions() const noexcept {
+       if (rtt > ugly_rtt || packet_loss > ugly_loss) {
+               return UGLY;
+       } else if (rtt > bad_rtt || packet_loss > bad_loss) {
+               return BAD;
+       } else {
+               return GOOD;
+       }
+}
+
+
 Connection::Connection(const IPaddress &addr)
 : handler(nullptr)
 , addr(addr)
-, send_timer(500)
+// make sure a packet is sent at least every 50ms since packets contains
+// acks that the remote end will use to measure RTT
+, send_timer(50)
 , recv_timer(10000)
 , ctrl_out{ 0, 0xFFFF, 0xFFFFFFFF }
 , ctrl_in{ 0, 0xFFFF, 0xFFFFFFFF }
@@ -85,6 +252,7 @@ uint16_t Connection::Send(UDPpacket &udp_pack, UDPsocket sock) {
        }
 
        if (HasHandler()) {
+               Handler().PacketOut(udp_pack);
                Handler().PacketSent(seq);
        }
 
@@ -115,6 +283,7 @@ void Connection::Received(const UDPpacket &udp_pack) {
        }
 
        Packet::TControl ctrl_new = pack.header.ctrl;
+       Handler().PacketIn(udp_pack);
        Handler().Handle(udp_pack);
 
        if (diff > 0) {
@@ -153,69 +322,30 @@ uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
 
 
 ConnectionHandler::ConnectionHandler()
-: packets_lost(0)
-, packets_received(0)
-, packet_loss(0.0f)
-, stamp_cursor(15)
-, stamp_last(0)
-, rtt(64.0f) {
-       Uint32 now = SDL_GetTicks();
-       for (Uint32 &s : stamps) {
-               s = now;
-       }
+: cc() {
+
 }
 
-void ConnectionHandler::PacketSent(uint16_t seq) {
-       if (!SamplePacket(seq)) {
-               return;
-       }
-       stamp_cursor = (stamp_cursor + 1) % 16;
-       stamps[stamp_cursor] = SDL_GetTicks();
-       stamp_last = seq;
+void ConnectionHandler::PacketSent(uint16_t seq) noexcept {
+       cc.PacketSent(seq);
 }
 
 void ConnectionHandler::PacketLost(uint16_t seq) {
        OnPacketLost(seq);
-       ++packets_lost;
-       UpdatePacketLoss();
-       UpdateRTT(seq);
+       cc.PacketLost(seq);
 }
 
 void ConnectionHandler::PacketReceived(uint16_t seq) {
        OnPacketReceived(seq);
-       ++packets_received;
-       UpdatePacketLoss();
-       UpdateRTT(seq);
+       cc.PacketReceived(seq);
 }
 
-void ConnectionHandler::UpdatePacketLoss() noexcept {
-       unsigned int packets_total = packets_lost + packets_received;
-       if (packets_total >= 256) {
-               packet_loss = float(packets_lost) / float(packets_total);
-               packets_lost = 0;
-               packets_received = 0;
-       }
+void ConnectionHandler::PacketIn(const UDPpacket &pack) noexcept {
+       cc.PacketIn(pack);
 }
 
-void ConnectionHandler::UpdateRTT(std::uint16_t seq) noexcept {
-       if (!SamplePacket(seq)) return;
-       int diff = HeadDiff(seq);
-       if (diff > 0 || diff < -15) {
-               // packet outside observed time frame
-               return;
-       }
-       int cur_rtt = SDL_GetTicks() - stamps[(stamp_cursor + diff + 16) % 16];
-       rtt += (cur_rtt - rtt) * 0.1f;
-}
-
-bool ConnectionHandler::SamplePacket(std::uint16_t seq) const noexcept {
-       // only sample every eighth packet
-       return seq % 8 == 0;
-}
-
-int ConnectionHandler::HeadDiff(std::uint16_t seq) const noexcept {
-       int16_t diff = int16_t(seq) - int16_t(stamp_last);
-       return diff / 8;
+void ConnectionHandler::PacketOut(const UDPpacket &pack) noexcept {
+       cc.PacketOut(pack);
 }
 
 
@@ -304,23 +434,72 @@ void Packet::Payload::ReadString(string &dst, size_t off, size_t maxlen) const n
 }
 
 void Packet::Payload::Write(const glm::quat &val, size_t off) noexcept {
-       WritePackN(val.w, off);
-       WritePackN(val.x, off + 2);
-       WritePackN(val.y, off + 4);
-       WritePackN(val.z, off + 6);
+       // find the largest component
+       float largest = 0.0f;
+       int largest_index = -1;
+       for (int i = 0; i < 4; ++i) {
+               float iabs = abs(val[i]);
+               if (iabs > largest) {
+                       largest = iabs;
+                       largest_index = i;
+               }
+       }
+       // make sure it's positive
+       const glm::quat q(val[largest_index] < 0.0f ? -val : val);
+       // move index to the two most significant bits
+       uint64_t packed = uint64_t(largest_index) << 62;
+       // we have to map from [-0.7072,0.7072] to [-524287,524287] and move into positive range
+       constexpr float conv = 524287.0f / 0.7072f;
+       // if largest is 1, the other three are 0
+       // precision of comparison is the interval of our mapping
+       if (abs(1.0 - largest) < (1.0f / conv)) {
+               packed |= 0x7FFFF7FFFF7FFFF;
+       } else {
+               // pack the three smaller components into 20bit ints each
+               int shift = 40;
+               for (int i = 0; i < 4; ++i) {
+                       if (i != largest_index) {
+                               packed |= uint64_t(int(q[i] * conv) + 524287) << shift;
+                               shift -= 20;
+                       }
+               }
+       }
+       // and write it out
+       Write(packed, off);
 }
 
 void Packet::Payload::Read(glm::quat &val, size_t off) const noexcept {
-       ReadPackN(val.w, off);
-       ReadPackN(val.x, off + 2);
-       ReadPackN(val.y, off + 4);
-       ReadPackN(val.z, off + 6);
-       val = normalize(val);
+       // extract the 8 byte packed value
+       uint64_t packed = 0;
+       Read(packed, off);
+       // two most significant bits are the index of the largest (omitted) component
+       int largest_index = packed >> 62;
+       // if all other three are 0, largest is 1 and we can omit the conversion
+       if ((packed & 0xFFFFFFFFFFFFFFF) == 0x7FFFF7FFFF7FFFF) {
+               val = { 0.0f, 0.0f, 0.0f, 0.0f };
+               val[largest_index] = 1.0f;
+               return;
+       }
+       // we have to map from [-524287,524287] to [-0.7072,0.7072]
+       constexpr float conv = 0.7072f / 524287.0f;
+       int shift = 40;
+       for (int i = 0; i < 4; ++i) {
+               if (i != largest_index) {
+                       val[i] = float(int((packed >> shift) & 0xFFFFF) - 524287) * conv;
+                       shift -= 20;
+               } else {
+                       // set to zero so the length of the other three can be determined
+                       val[i] = 0.0f;
+               }
+       }
+       // omitted component squared is 1 - length squared of others
+       val[largest_index] = sqrt(1.0f - glm::length2(val));
+       // and already normalized
 }
 
 void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
-       Write(state.chunk_pos, off);
-       WritePackU(state.block_pos * (1.0f / 16.0f), off + 12);
+       Write(state.pos.chunk, off);
+       WritePackU(state.pos.block * (1.0f / ExactLocation::fscale), off + 12);
        Write(state.velocity, off + 18);
        Write(state.orient, off + 30);
        WritePackN(state.pitch * PI_0p5_inv, off + 38);
@@ -328,20 +507,20 @@ void Packet::Payload::Write(const EntityState &state, size_t off) noexcept {
 }
 
 void Packet::Payload::Read(EntityState &state, size_t off) const noexcept {
-       Read(state.chunk_pos, off);
-       ReadPackU(state.block_pos, off + 12);
+       Read(state.pos.chunk, off);
+       ReadPackU(state.pos.block, off + 12);
        Read(state.velocity, off + 18);
        Read(state.orient, off + 30);
        ReadPackN(state.pitch, off + 38);
        ReadPackN(state.yaw, off + 40);
-       state.block_pos *= 16.0f;
+       state.pos.block *= ExactLocation::fscale;
        state.pitch *= PI_0p5;
        state.yaw *= PI;
 }
 
 void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, size_t off) noexcept {
-       WritePackB(state.chunk_pos - base, off);
-       WritePackU(state.block_pos * (1.0f / 16.0f), off + 3);
+       WritePackB(state.pos.chunk - base, off);
+       WritePackU(state.pos.block * (1.0f / ExactLocation::fscale), off + 3);
        Write(state.velocity, off + 9);
        Write(state.orient, off + 21);
        WritePackN(state.pitch * PI_0p5_inv, off + 29);
@@ -349,14 +528,14 @@ void Packet::Payload::Write(const EntityState &state, const glm::ivec3 &base, si
 }
 
 void Packet::Payload::Read(EntityState &state, const glm::ivec3 &base, size_t off) const noexcept {
-       ReadPackB(state.chunk_pos, off);
-       ReadPackU(state.block_pos, off + 3);
+       ReadPackB(state.pos.chunk, off);
+       ReadPackU(state.pos.block, off + 3);
        Read(state.velocity, off + 9);
        Read(state.orient, off + 21);
        ReadPackN(state.pitch, off + 29);
        ReadPackN(state.yaw, off + 31);
-       state.chunk_pos += base;
-       state.block_pos *= 16.0f;
+       state.pos.chunk += base;
+       state.pos.block *= ExactLocation::fscale;
        state.pitch *= PI_0p5;
        state.yaw *= PI;
 }