1 #include "ChunkReceiver.hpp"
2 #include "ChunkTransmission.hpp"
4 #include "NetworkedInput.hpp"
6 #include "../app/init.hpp"
7 #include "../geometry/distance.hpp"
8 #include "../io/WorldSave.hpp"
9 #include "../net/Packet.hpp"
10 #include "../world/Chunk.hpp"
11 #include "../world/ChunkStore.hpp"
12 #include "../world/Player.hpp"
13 #include "../world/World.hpp"
17 #include <glm/gtx/io.hpp>
26 ChunkReceiver::ChunkReceiver(Client &client, ChunkStore &store, const WorldSave &save)
35 ChunkReceiver::~ChunkReceiver() {
39 void ChunkReceiver::Update(int dt) {
41 for (ChunkTransmission &trans : transmissions) {
42 if (trans.active && (timer.Elapsed() - trans.last_update) > timer.Interval()) {
43 cout << "timeout for transmission of chunk " << trans.coords << endl;
44 if (trans.header_received) {
45 client.SendChunkRequest(trans.coords);
47 trans.last_update = timer.Elapsed();
54 if (transmissions.size() > 3) {
55 for (auto iter = transmissions.begin(), end = transmissions.end(); iter != end; ++iter) {
57 transmissions.erase(iter);
66 int ChunkReceiver::ToLoad() const noexcept {
67 return store.EstimateMissing();
70 void ChunkReceiver::LoadOne() {
71 if (!store.HasMissing()) return;
73 ExactLocation::Coarse pos = store.NextMissing();
74 Chunk *chunk = store.Allocate(pos);
76 // chunk store corrupted?
80 if (save.Exists(pos)) {
85 void ChunkReceiver::LoadN(size_t n) {
86 size_t end = min(n, size_t(ToLoad()));
87 for (size_t i = 0; i < end && store.HasMissing(); ++i) {
92 void ChunkReceiver::StoreN(size_t n) {
94 for (Chunk &chunk : store) {
95 if (chunk.ShouldUpdateSave()) {
106 void ChunkReceiver::Handle(const Packet::ChunkBegin &pack) {
108 pack.ReadTransmissionId(id);
109 ChunkTransmission &trans = GetTransmission(id);
110 pack.ReadFlags(trans.flags);
111 pack.ReadChunkCoords(trans.coords);
112 pack.ReadDataSize(trans.data_size);
113 trans.last_update = timer.Elapsed();
114 trans.header_received = true;
118 void ChunkReceiver::Handle(const Packet::ChunkData &pack) {
119 uint32_t id, pos, size;
120 pack.ReadTransmissionId(id);
121 pack.ReadDataOffset(pos);
122 if (pos >= sizeof(ChunkTransmission::buffer)) {
123 cout << "received chunk data offset outside of buffer size" << endl;
126 pack.ReadDataSize(size);
127 ChunkTransmission &trans = GetTransmission(id);
128 size_t len = min(size_t(size), sizeof(ChunkTransmission::buffer) - pos);
129 pack.ReadData(&trans.buffer[pos], len);
130 // TODO: this method breaks when a packet arrives twice
131 trans.data_received += len;
132 trans.last_update = timer.Elapsed();
136 ChunkTransmission &ChunkReceiver::GetTransmission(uint32_t id) {
137 // search for ongoing
138 for (ChunkTransmission &trans : transmissions) {
139 if (trans.active && trans.id == id) {
144 for (ChunkTransmission &trans : transmissions) {
152 transmissions.emplace_back();
153 transmissions.back().active = true;
154 transmissions.back().id = id;
155 return transmissions.back();
158 void ChunkReceiver::Commit(ChunkTransmission &trans) {
159 if (!trans.Complete()) return;
161 Chunk *chunk = store.Allocate(trans.coords);
163 // chunk no longer of interest, just drop the data
164 // it should probably be cached to disk, but not now :P
169 const Byte *src = &trans.buffer[0];
170 uLong src_len = min(size_t(trans.data_size), sizeof(ChunkTransmission::buffer));
171 Byte *dst = reinterpret_cast<Byte *>(chunk->BlockData());
172 uLong dst_len = Chunk::BlockSize();
174 if (trans.Compressed()) {
175 if (uncompress(dst, &dst_len, src, src_len) != Z_OK) {
177 cout << "got corruped chunk data for " << trans.coords << endl;
178 client.SendChunkRequest(trans.coords);
180 // chunk data can, and probably will, contain invalid block IDs, so
181 // zero it to be safe
182 memset(dst, 0, dst_len);
186 memcpy(dst, src, min(src_len, dst_len));
192 ChunkTransmission::ChunkTransmission()
199 , header_received(false)
205 void ChunkTransmission::Reset() noexcept {
209 header_received = false;
212 void ChunkTransmission::Clear() noexcept {
217 bool ChunkTransmission::Complete() const noexcept {
218 return header_received && data_received == data_size;
221 bool ChunkTransmission::Compressed() const noexcept {
228 UDPsocket client_bind(Uint16 port) {
229 UDPsocket sock = SDLNet_UDP_Open(port);
231 throw NetError("SDLNet_UDP_Open");
236 IPaddress client_resolve(const char *host, Uint16 port) {
238 if (SDLNet_ResolveHost(&addr, host, port) != 0) {
239 throw NetError("SDLNet_ResolveHost");
246 Client::Client(const Config::Network &conf)
247 : conn(client_resolve(conf.host.c_str(), conf.port))
248 , client_sock(client_bind(0))
249 , client_pack{ -1, nullptr, 0 } {
250 client_pack.data = new Uint8[sizeof(Packet)];
251 client_pack.maxlen = sizeof(Packet);
252 // establish connection
257 delete[] client_pack.data;
258 SDLNet_UDP_Close(client_sock);
262 void Client::Handle() {
263 int result = SDLNet_UDP_Recv(client_sock, &client_pack);
265 HandlePacket(client_pack);
266 result = SDLNet_UDP_Recv(client_sock, &client_pack);
269 // a boo boo happened
270 throw NetError("SDLNet_UDP_Recv");
274 void Client::HandlePacket(const UDPpacket &udp_pack) {
275 if (!conn.Matches(udp_pack.address)) {
276 // packet came from somewhere else, drop
279 const Packet &pack = *reinterpret_cast<const Packet *>(udp_pack.data);
280 if (pack.header.tag != Packet::TAG) {
281 // mistagged packet, drop
285 conn.Received(udp_pack);
288 void Client::Update(int dt) {
290 if (conn.ShouldPing()) {
295 uint16_t Client::SendPing() {
296 return conn.SendPing(client_pack, client_sock);
299 uint16_t Client::SendLogin(const string &name) {
300 auto pack = Packet::Make<Packet::Login>(client_pack);
301 pack.WritePlayerName(name);
302 return conn.Send(client_pack, client_sock);
305 uint16_t Client::SendPlayerUpdate(
306 const EntityState &prediction,
307 const glm::vec3 &movement,
313 auto pack = Packet::Make<Packet::PlayerUpdate>(client_pack);
314 pack.WritePredictedState(prediction);
315 pack.WriteMovement(movement);
316 pack.WriteActions(actions);
317 pack.WriteSlot(slot);
318 return conn.Send(client_pack, client_sock);
321 uint16_t Client::SendPart() {
322 Packet::Make<Packet::Part>(client_pack);
323 return conn.Send(client_pack, client_sock);
326 uint16_t Client::SendChunkRequest(
327 const glm::ivec3 &coords
329 auto pack = Packet::Make<Packet::ChunkBegin>(client_pack);
330 pack.WriteChunkCoords(coords);
331 return conn.Send(client_pack, client_sock);
334 uint16_t Client::SendMessage(
339 auto pack = Packet::Make<Packet::Message>(client_pack);
340 pack.WriteType(type);
341 pack.WriteReferral(ref);
342 pack.WriteMessage(msg);
343 client_pack.len = sizeof(Packet::Header) + Packet::Message::GetSize(msg);
344 return conn.Send(client_pack, client_sock);
347 NetworkedInput::NetworkedInput(World &world, Player &player, Client &client)
348 : PlayerController(world, player)
357 bool NetworkedInput::UpdateImportant() const noexcept {
358 return old_actions != actions || !iszero(old_movement - GetMovement());
361 void NetworkedInput::Update(Entity &, float dt) {
366 void NetworkedInput::PushPlayerUpdate(int dt) {
367 const EntityState &state = GetPlayer().GetEntity().GetState();
369 uint16_t packet = client.SendPlayerUpdate(
377 if (player_hist.size() < 16) {
378 player_hist.emplace_back(state, GetMovement(), dt * 0.001f, packet);
380 auto entry = player_hist.begin();
381 entry->state = state;
382 entry->movement = GetMovement();
383 entry->delta_t = dt * 0.001f;
384 entry->packet = packet;
385 player_hist.splice(player_hist.end(), player_hist, entry);
387 old_movement = GetMovement();
388 old_actions = actions;
391 void NetworkedInput::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
392 if (player_hist.empty()) return;
394 auto entry = player_hist.begin();
395 auto end = player_hist.end();
397 // we may have received an older packet
398 int pack_diff = int16_t(seq) - int16_t(entry->packet);
400 // indeed we have, just ignore it
404 // drop anything older than the fix
405 while (entry != end) {
406 pack_diff = int16_t(seq) - int16_t(entry->packet);
408 entry = player_hist.erase(entry);
414 glm::vec3 restore_movement(GetMovement());
416 EntityState player_state = GetPlayer().GetEntity().GetState();
417 Entity replay(GetPlayer().GetEntity());
418 replay.SetState(corrected_state);
421 entry->state.pos = replay.GetState().pos;
425 vector<WorldCollision> col;
426 while (entry != end) {
427 SetMovement(entry->movement);
428 GetWorld().Update(replay, entry->delta_t);
429 entry->state.pos = replay.GetState().pos;
433 glm::vec3 displacement(replay.GetState().Diff(player_state));
434 const float disp_squared = dot(displacement, displacement);
436 if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
437 SetMovement(restore_movement);
441 // if offset > 10cm, warp the player
442 // otherwise, move at most 1cm per frame towards
443 // the fixed position (160ms, so shouldn't be too noticeable)
444 constexpr float warp_thresh = 0.01f; // (1/10)^2
445 constexpr float max_disp = 0.0001f; // (1/100)^2
447 if (disp_squared > warp_thresh) {
448 player_state.pos = replay.GetState().pos;
449 } else if (disp_squared < max_disp) {
450 player_state.pos.block += displacement;
452 displacement *= 0.01f / sqrt(disp_squared);
453 player_state.pos.block += displacement;
455 GetPlayer().GetEntity().SetState(player_state);
456 SetMovement(restore_movement);
459 void NetworkedInput::StartPrimaryAction() {
463 void NetworkedInput::StopPrimaryAction() {
467 void NetworkedInput::StartSecondaryAction() {
471 void NetworkedInput::StopSecondaryAction() {
475 void NetworkedInput::StartTertiaryAction() {
479 void NetworkedInput::StopTertiaryAction() {