]> git.localhorst.tv Git - blank.git/blobdiff - src/net/net.cpp
transmit player input from client to server
[blank.git] / src / net / net.cpp
index 4d364124253d9e5d5e5668e77a6ec52ef29eb9b0..e766c76d0b1201892bd1f0393a0d108f9d640b96 100644 (file)
@@ -1,15 +1,14 @@
-#include "Client.hpp"
 #include "Connection.hpp"
 #include "ConnectionHandler.hpp"
 #include "io.hpp"
 #include "Packet.hpp"
-#include "Server.hpp"
 
 #include "../app/init.hpp"
-#include "../world/World.hpp"
+#include "../model/CompositeModel.hpp"
+#include "../world/Entity.hpp"
+#include "../world/EntityState.hpp"
 
 #include <cstring>
-#include <iostream>
 
 using namespace std;
 
@@ -20,86 +19,13 @@ constexpr size_t Packet::Ping::MAX_LEN;
 constexpr size_t Packet::Login::MAX_LEN;
 constexpr size_t Packet::Join::MAX_LEN;
 constexpr size_t Packet::Part::MAX_LEN;
-
-namespace {
-
-UDPsocket client_bind(Uint16 port) {
-       UDPsocket sock = SDLNet_UDP_Open(port);
-       if (!sock) {
-               throw NetError("SDLNet_UDP_Open");
-       }
-       return sock;
-}
-
-IPaddress client_resolve(const char *host, Uint16 port) {
-       IPaddress addr;
-       if (SDLNet_ResolveHost(&addr, host, port) != 0) {
-               throw NetError("SDLNet_ResolveHost");
-       }
-       return addr;
-}
-
-}
-
-Client::Client(const Config &conf)
-: conn(client_resolve(conf.host.c_str(), conf.port))
-, client_sock(client_bind(0))
-, client_pack{ -1, nullptr, 0 } {
-       client_pack.data = new Uint8[sizeof(Packet)];
-       client_pack.maxlen = sizeof(Packet);
-       // establish connection
-       SendPing();
-}
-
-Client::~Client() {
-       delete[] client_pack.data;
-       SDLNet_UDP_Close(client_sock);
-}
-
-
-void Client::Handle() {
-       int result = SDLNet_UDP_Recv(client_sock, &client_pack);
-       while (result > 0) {
-               HandlePacket(client_pack);
-               result = SDLNet_UDP_Recv(client_sock, &client_pack);
-       }
-       if (result == -1) {
-               // a boo boo happened
-               throw NetError("SDLNet_UDP_Recv");
-       }
-}
-
-void Client::HandlePacket(const UDPpacket &udp_pack) {
-       if (!conn.Matches(udp_pack.address)) {
-               // packet came from somewhere else, drop
-               return;
-       }
-       const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
-       if (pack.header.tag != Packet::TAG) {
-               // mistagged packet, drop
-               return;
-       }
-
-       conn.Received(udp_pack);
-}
-
-void Client::Update(int dt) {
-       conn.Update(dt);
-       if (conn.ShouldPing()) {
-               SendPing();
-       }
-}
-
-uint16_t Client::SendPing() {
-       return conn.SendPing(client_pack, client_sock);
-}
-
-uint16_t Client::SendLogin(const string &name) {
-       auto pack = Packet::Make<Packet::Login>(client_pack);
-       pack.WritePlayerName(name);
-       return conn.Send(client_pack, client_sock);
-}
-
+constexpr size_t Packet::PlayerUpdate::MAX_LEN;
+constexpr size_t Packet::SpawnEntity::MAX_LEN;
+constexpr size_t Packet::DespawnEntity::MAX_LEN;
+constexpr size_t Packet::EntityUpdate::MAX_LEN;
+constexpr size_t Packet::PlayerCorrection::MAX_LEN;
+constexpr size_t Packet::ChunkBegin::MAX_LEN;
+constexpr size_t Packet::ChunkData::MAX_LEN;
 
 Connection::Connection(const IPaddress &addr)
 : handler(nullptr)
@@ -192,20 +118,62 @@ void Connection::Received(const UDPpacket &udp_pack) {
                if (diff > 0) {
                        for (int i = 0; i < diff; ++i) {
                                if (i > 32 || (i < 32 && (ctrl_in.hist & (1 << (31 - i))) == 0)) {
-                                       Handler().OnPacketLost(ctrl_in.ack - 32 + i);
+                                       Handler().PacketLost(ctrl_in.ack - 32 + i);
                                }
                        }
                }
+               // check for newly ack'd packets
+               for (uint16_t s = ctrl_new.AckBegin(); s != ctrl_new.AckEnd(); --s) {
+                       if (ctrl_new.Acks(s) && !ctrl_in.Acks(s)) {
+                               Handler().PacketReceived(s);
+                       }
+               }
                ctrl_in = ctrl_new;
        }
 }
 
+bool Packet::TControl::Acks(uint16_t s) const noexcept {
+       int16_t diff = int16_t(ack) - int16_t(s);
+       if (diff == 0) return true;
+       if (diff < 0 || diff > 32) return false;
+       return (hist & (1 << (diff - 1))) != 0;
+}
+
 uint16_t Connection::SendPing(UDPpacket &udp_pack, UDPsocket sock) {
        Packet::Make<Packet::Ping>(udp_pack);
        return Send(udp_pack, sock);
 }
 
 
+ConnectionHandler::ConnectionHandler()
+: packets_lost(0)
+, packets_received(0)
+, packet_loss(0.0f) {
+
+}
+
+void ConnectionHandler::PacketLost(uint16_t seq) {
+       OnPacketLost(seq);
+       ++packets_lost;
+       UpdatePacketLoss();
+}
+
+void ConnectionHandler::PacketReceived(uint16_t seq) {
+       OnPacketReceived(seq);
+       ++packets_received;
+       UpdatePacketLoss();
+}
+
+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;
+       }
+}
+
+
 ostream &operator <<(ostream &out, const IPaddress &addr) {
        const unsigned char *host = reinterpret_cast<const unsigned char *>(&addr.host);
        out << int(host[0])
@@ -229,6 +197,20 @@ const char *Packet::Type2String(uint8_t t) noexcept {
                        return "Join";
                case Part::TYPE:
                        return "Part";
+               case PlayerUpdate::TYPE:
+                       return "PlayerUpdate";
+               case SpawnEntity::TYPE:
+                       return "SpawnEntity";
+               case DespawnEntity::TYPE:
+                       return "DespawnEntity";
+               case EntityUpdate::TYPE:
+                       return "EntityUpdate";
+               case PlayerCorrection::TYPE:
+                       return "PlayerCorrection";
+               case ChunkBegin::TYPE:
+                       return "ChunkBegin";
+               case ChunkData::TYPE:
+                       return "ChunkData";
                default:
                        return "Unknown";
        }
@@ -283,34 +265,15 @@ void Packet::Login::ReadPlayerName(string &name) const noexcept {
 
 void Packet::Join::WritePlayer(const Entity &player) noexcept {
        Write(player.ID(), 0);
-       Write(player.ChunkCoords(), 4);
-       Write(player.Position(), 16);
-       Write(player.Velocity(), 28);
-       Write(player.Orientation(), 40);
-       Write(player.AngularVelocity(), 56);
+       Write(player.GetState(), 4);
 }
 
 void Packet::Join::ReadPlayerID(uint32_t &id) const noexcept {
        Read(id, 0);
 }
 
-void Packet::Join::ReadPlayer(Entity &player) const noexcept {
-       glm::ivec3 chunk_coords(0);
-       glm::vec3 pos;
-       glm::vec3 vel;
-       glm::quat rot;
-       glm::vec3 ang;
-
-       Read(chunk_coords, 4);
-       Read(pos, 16);
-       Read(vel, 28);
-       Read(rot, 40);
-       Read(ang, 56);
-
-       player.Position(chunk_coords, pos);
-       player.Velocity(vel);
-       player.Orientation(rot);
-       player.AngularVelocity(ang);
+void Packet::Join::ReadPlayerState(EntityState &state) const noexcept {
+       Read(state, 4);
 }
 
 void Packet::Join::WriteWorldName(const string &name) noexcept {
@@ -321,151 +284,265 @@ void Packet::Join::ReadWorldName(string &name) const noexcept {
        ReadString(name, 68, 32);
 }
 
+void Packet::PlayerUpdate::WritePredictedState(const EntityState &state) noexcept {
+       Write(state, 0);
+}
 
-void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
-       const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
-       switch (pack.Type()) {
-               case Packet::Ping::TYPE:
-                       On(Packet::As<Packet::Ping>(udp_pack));
-                       break;
-               case Packet::Login::TYPE:
-                       On(Packet::As<Packet::Login>(udp_pack));
-                       break;
-               case Packet::Join::TYPE:
-                       On(Packet::As<Packet::Join>(udp_pack));
-                       break;
-               case Packet::Part::TYPE:
-                       On(Packet::As<Packet::Part>(udp_pack));
-                       break;
-               default:
-                       // drop unknown or unhandled packets
-                       break;
-       }
+void Packet::PlayerUpdate::ReadPredictedState(EntityState &state) const noexcept {
+       Read(state, 0);
+}
+
+void Packet::PlayerUpdate::WriteMovement(const glm::vec3 &mov) noexcept {
+       glm::ivec3 conv = clamp(glm::ivec3(mov * 32767.0f), -32767, 32767);
+       Write(int16_t(conv.x), 64);
+       Write(int16_t(conv.y), 66);
+       Write(int16_t(conv.z), 68);
 }
 
+void Packet::PlayerUpdate::ReadMovement(glm::vec3 &mov) const noexcept {
+       int16_t x, y, z;
+       Read(x, 64);
+       Read(y, 66);
+       Read(z, 68);
+       mov = glm::vec3(x, y, z) * .00003051850947599719f;
+}
 
-Server::Server(const Config &conf, World &world)
-: serv_sock(nullptr)
-, serv_pack{ -1, nullptr, 0 }
-, clients()
-, world(world) {
-       serv_sock = SDLNet_UDP_Open(conf.port);
-       if (!serv_sock) {
-               throw NetError("SDLNet_UDP_Open");
-       }
+void Packet::PlayerUpdate::WritePitch(float pitch) noexcept {
+       int16_t conv = pitch * 20860.12008116853786870640f;
+       Write(conv, 70);
+}
 
-       serv_pack.data = new Uint8[sizeof(Packet)];
-       serv_pack.maxlen = sizeof(Packet);
+void Packet::PlayerUpdate::ReadPitch(float &pitch) const noexcept {
+       int16_t conv = 0;
+       Read(conv, 70);
+       pitch = conv * .00004793836258415163f;
 }
 
-Server::~Server() {
-       delete[] serv_pack.data;
-       SDLNet_UDP_Close(serv_sock);
+void Packet::PlayerUpdate::WriteYaw(float yaw) noexcept {
+       int16_t conv = yaw * 10430.06004058426893435320f;
+       Write(conv, 72);
 }
 
+void Packet::PlayerUpdate::ReadYaw(float &yaw) const noexcept {
+       int16_t conv = 0;
+       Read(conv, 72);
+       yaw = conv * .00009587672516830326f;
+}
 
-void Server::Handle() {
-       int result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
-       while (result > 0) {
-               HandlePacket(serv_pack);
-               result = SDLNet_UDP_Recv(serv_sock, &serv_pack);
-       }
-       if (result == -1) {
-               // a boo boo happened
-               throw NetError("SDLNet_UDP_Recv");
-       }
+void Packet::PlayerUpdate::WriteActions(uint8_t actions) noexcept {
+       Write(actions, 74);
 }
 
-void Server::HandlePacket(const UDPpacket &udp_pack) {
-       if (udp_pack.len < int(sizeof(Packet::Header))) {
-               // packet too small, drop
-               return;
+void Packet::PlayerUpdate::ReadActions(uint8_t &actions) const noexcept {
+       Read(actions, 74);
+}
+
+void Packet::PlayerUpdate::WriteSlot(uint8_t slot) noexcept {
+       Write(slot, 75);
+}
+
+void Packet::PlayerUpdate::ReadSlot(uint8_t &slot) const noexcept {
+       Read(slot, 75);
+}
+
+void Packet::SpawnEntity::WriteEntity(const Entity &e) noexcept {
+       Write(e.ID(), 0);
+       if (e.GetModel()) {
+               Write(e.GetModel().GetModel().ID(), 4);
+       } else {
+               Write(uint32_t(0), 4);
        }
-       const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
-       if (pack.header.tag != Packet::TAG) {
-               // mistagged packet, drop
-               return;
+       Write(e.GetState(), 8);
+       Write(e.Bounds(), 72);
+       uint32_t flags = 0;
+       if (e.WorldCollidable()) {
+               flags |= 1;
        }
+       Write(flags, 96);
+       WriteString(e.Name(), 100, 32);
+}
+
+void Packet::SpawnEntity::ReadEntityID(uint32_t &id) const noexcept {
+       Read(id, 0);
+}
 
-       Connection &client = GetClient(udp_pack.address);
-       client.Received(udp_pack);
+void Packet::SpawnEntity::ReadSkeletonID(uint32_t &id) const noexcept {
+       Read(id, 4);
+}
 
-       switch (pack.header.type) {
-               case Packet::Login::TYPE:
-                       HandleLogin(client, udp_pack);
-                       break;
-               case Packet::Part::TYPE:
-                       HandlePart(client, udp_pack);
-                       break;
-               default:
-                       // just drop packets of unknown or unhandled type
-                       break;
-       }
+void Packet::SpawnEntity::ReadEntity(Entity &e) const noexcept {
+       EntityState state;
+       AABB bounds;
+       uint32_t flags = 0;
+       string name;
+
+       Read(state, 8);
+       Read(bounds, 72);
+       Read(flags, 96);
+       ReadString(name, 100, 32);
+
+       e.SetState(state);
+       e.Bounds(bounds);
+       e.WorldCollidable(flags & 1);
+       e.Name(name);
 }
 
-Connection &Server::GetClient(const IPaddress &addr) {
-       for (Connection &client : clients) {
-               if (client.Matches(addr)) {
-                       return client;
-               }
-       }
-       clients.emplace_back(addr);
-       OnConnect(clients.back());
-       return clients.back();
+void Packet::DespawnEntity::WriteEntityID(uint32_t id) noexcept {
+       Write(id, 0);
 }
 
-void Server::OnConnect(Connection &client) {
-       cout << "new connection from " << client.Address() << endl;
-       // tell it we're alive
-       client.SendPing(serv_pack, serv_sock);
+void Packet::DespawnEntity::ReadEntityID(uint32_t &id) const noexcept {
+       Read(id, 0);
 }
 
-void Server::Update(int dt) {
-       for (list<Connection>::iterator client(clients.begin()), end(clients.end()); client != end;) {
-               client->Update(dt);
-               if (client->Closed()) {
-                       OnDisconnect(*client);
-                       client = clients.erase(client);
-               } else {
-                       if (client->ShouldPing()) {
-                               client->SendPing(serv_pack, serv_sock);
-                       }
-                       ++client;
-               }
-       }
+void Packet::EntityUpdate::WriteEntityCount(uint32_t count) noexcept {
+       Write(count, 0);
 }
 
-void Server::OnDisconnect(Connection &client) {
-       cout << "connection timeout from " << client.Address() << endl;
+void Packet::EntityUpdate::ReadEntityCount(uint32_t &count) const noexcept {
+       Read(count, 0);
 }
 
+void Packet::EntityUpdate::WriteEntity(const Entity &entity, uint32_t num) noexcept {
+       uint32_t off = GetSize(num);
 
-void Server::HandleLogin(Connection &client, const UDPpacket &udp_pack) {
-       auto pack = Packet::As<Packet::Login>(udp_pack);
+       Write(entity.ID(), off);
+       Write(entity.GetState(), off + 4);
+}
 
-       string name;
-       pack.ReadPlayerName(name);
+void Packet::EntityUpdate::ReadEntityID(uint32_t &id, uint32_t num) const noexcept {
+       uint32_t off = GetSize(num);
+       Read(id, off);
+}
+
+void Packet::EntityUpdate::ReadEntityState(EntityState &state, uint32_t num) const noexcept {
+       uint32_t off = GetSize(num);
+       Read(state, off + 4);
+}
 
-       Entity *player = world.AddPlayer(name);
+void Packet::PlayerCorrection::WritePacketSeq(std::uint16_t s) noexcept {
+       Write(s, 0);
+}
 
-       if (player) {
-               // success!
-               cout << "accepted login from player \"" << name << '"' << endl;
-               auto response = Packet::Make<Packet::Join>(serv_pack);
-               response.WritePlayer(*player);
-               response.WriteWorldName(world.Name());
-               client.Send(serv_pack, serv_sock);
-       } else {
-               // aw no :(
-               cout << "rejected login from player \"" << name << '"' << endl;
-               Packet::Make<Packet::Part>(serv_pack);
-               client.Send(serv_pack, serv_sock);
-               client.Close();
-       }
+void Packet::PlayerCorrection::ReadPacketSeq(std::uint16_t &s) const noexcept {
+       Read(s, 0);
+}
+
+void Packet::PlayerCorrection::WritePlayer(const Entity &player) noexcept {
+       Write(player.GetState(), 2);
+}
+
+void Packet::PlayerCorrection::ReadPlayerState(EntityState &state) const noexcept {
+       Read(state, 2);
+}
+
+void Packet::ChunkBegin::WriteTransmissionId(uint32_t id) noexcept {
+       Write(id, 0);
+}
+
+void Packet::ChunkBegin::ReadTransmissionId(uint32_t &id) const noexcept {
+       Read(id, 0);
+}
+
+void Packet::ChunkBegin::WriteFlags(uint32_t f) noexcept {
+       Write(f, 4);
+}
+
+void Packet::ChunkBegin::ReadFlags(uint32_t &f) const noexcept {
+       Read(f, 4);
+}
+
+void Packet::ChunkBegin::WriteChunkCoords(const glm::ivec3 &pos) noexcept {
+       Write(pos, 8);
+}
+
+void Packet::ChunkBegin::ReadChunkCoords(glm::ivec3 &pos) const noexcept {
+       Read(pos, 8);
+}
+
+void Packet::ChunkBegin::WriteDataSize(uint32_t s) noexcept {
+       Write(s, 20);
 }
 
-void Server::HandlePart(Connection &client, const UDPpacket &udp_pack) {
-       client.Close();
+void Packet::ChunkBegin::ReadDataSize(uint32_t &s) const noexcept {
+       Read(s, 20);
+}
+
+void Packet::ChunkData::WriteTransmissionId(uint32_t id) noexcept {
+       Write(id, 0);
+}
+
+void Packet::ChunkData::ReadTransmissionId(uint32_t &id) const noexcept {
+       Read(id, 0);
+}
+
+void Packet::ChunkData::WriteDataOffset(uint32_t o) noexcept {
+       Write(o, 4);
+}
+
+void Packet::ChunkData::ReadDataOffset(uint32_t &o) const noexcept {
+       Read(o, 4);
+}
+
+void Packet::ChunkData::WriteDataSize(uint32_t s) noexcept {
+       Write(s, 8);
+}
+
+void Packet::ChunkData::ReadDataSize(uint32_t &s) const noexcept {
+       Read(s, 8);
+}
+
+void Packet::ChunkData::WriteData(const uint8_t *d, size_t l) noexcept {
+       size_t len = min(length - 12, l);
+       memcpy(&data[12], d, len);
+}
+
+void Packet::ChunkData::ReadData(uint8_t *d, size_t l) const noexcept {
+       size_t len = min(length - 12, l);
+       memcpy(d, &data[12], len);
+}
+
+
+void ConnectionHandler::Handle(const UDPpacket &udp_pack) {
+       const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
+       switch (pack.Type()) {
+               case Packet::Ping::TYPE:
+                       On(Packet::As<Packet::Ping>(udp_pack));
+                       break;
+               case Packet::Login::TYPE:
+                       On(Packet::As<Packet::Login>(udp_pack));
+                       break;
+               case Packet::Join::TYPE:
+                       On(Packet::As<Packet::Join>(udp_pack));
+                       break;
+               case Packet::Part::TYPE:
+                       On(Packet::As<Packet::Part>(udp_pack));
+                       break;
+               case Packet::PlayerUpdate::TYPE:
+                       On(Packet::As<Packet::PlayerUpdate>(udp_pack));
+                       break;
+               case Packet::SpawnEntity::TYPE:
+                       On(Packet::As<Packet::SpawnEntity>(udp_pack));
+                       break;
+               case Packet::DespawnEntity::TYPE:
+                       On(Packet::As<Packet::DespawnEntity>(udp_pack));
+                       break;
+               case Packet::EntityUpdate::TYPE:
+                       On(Packet::As<Packet::EntityUpdate>(udp_pack));
+                       break;
+               case Packet::PlayerCorrection::TYPE:
+                       On(Packet::As<Packet::PlayerCorrection>(udp_pack));
+                       break;
+               case Packet::ChunkBegin::TYPE:
+                       On(Packet::As<Packet::ChunkBegin>(udp_pack));
+                       break;
+               case Packet::ChunkData::TYPE:
+                       On(Packet::As<Packet::ChunkData>(udp_pack));
+                       break;
+               default:
+                       // drop unknown or unhandled packets
+                       break;
+       }
 }
 
 }