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