]> git.localhorst.tv Git - blank.git/blob - src/client/client.cpp
fixed int rollover in client entity update
[blank.git] / src / client / client.cpp
1 #include "ChunkRequester.hpp"
2 #include "InitialState.hpp"
3 #include "InteractiveState.hpp"
4 #include "MasterState.hpp"
5
6 #include "../app/Environment.hpp"
7 #include "../app/init.hpp"
8 #include "../app/TextureIndex.hpp"
9 #include "../model/CompositeModel.hpp"
10 #include "../io/WorldSave.hpp"
11 #include "../world/ChunkStore.hpp"
12
13 #include <iostream>
14 #include <glm/gtx/io.hpp>
15
16 using namespace std;
17
18
19 namespace blank {
20 namespace client {
21
22 ChunkRequester::ChunkRequester(
23         ChunkStore &store,
24         const WorldSave &save
25 ) noexcept
26 : store(store)
27 , save(save) {
28
29 }
30
31 void ChunkRequester::Update(int dt) {
32         // check if there's chunks waiting to be loaded
33         LoadN(10);
34
35         // store a few chunks as well
36         constexpr int max_save = 10;
37         int saved = 0;
38         for (Chunk &chunk : store) {
39                 if (chunk.ShouldUpdateSave()) {
40                         save.Write(chunk);
41                         ++saved;
42                         if (saved >= max_save) {
43                                 break;
44                         }
45                 }
46         }
47 }
48
49 int ChunkRequester::ToLoad() const noexcept {
50         return store.EstimateMissing();
51 }
52
53 void ChunkRequester::LoadOne() {
54         if (!store.HasMissing()) return;
55
56         Chunk::Pos pos = store.NextMissing();
57         Chunk *chunk = store.Allocate(pos);
58         if (!chunk) {
59                 // chunk store corrupted?
60                 return;
61         }
62
63         if (save.Exists(pos)) {
64                 save.Read(*chunk);
65                 // TODO: request chunk from server with cache tag
66         } else {
67                 // TODO: request chunk from server
68         }
69 }
70
71 void ChunkRequester::LoadN(std::size_t n) {
72         std::size_t end = std::min(n, std::size_t(ToLoad()));
73         for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
74                 LoadOne();
75         }
76 }
77
78
79 InitialState::InitialState(MasterState &master)
80 : master(master)
81 , message() {
82         message.Position(glm::vec3(0.0f), Gravity::CENTER);
83         message.Set(master.GetEnv().assets.large_ui_font, "logging in");
84 }
85
86 void InitialState::OnEnter() {
87
88 }
89
90 void InitialState::Handle(const SDL_Event &evt) {
91         if (evt.type == SDL_QUIT) {
92                 master.Quit();
93         }
94 }
95
96 void InitialState::Update(int dt) {
97         master.Update(dt);
98 }
99
100 void InitialState::Render(Viewport &viewport) {
101         message.Render(viewport);
102 }
103
104
105 // TODO: this clutter is a giant mess
106 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
107 : master(master)
108 , block_types()
109 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetClientConf().host))
110 , world(block_types, master.GetWorldConf())
111 , interface(
112         master.GetInterfaceConf(),
113         master.GetEnv(),
114         world,
115         world.AddPlayer(master.GetInterfaceConf().player_name, player_id)
116 )
117 // TODO: looks like chunk requester and receiver can and should be merged
118 , chunk_requester(world.Chunks(), save)
119 , chunk_receiver(world.Chunks())
120 , chunk_renderer(*interface.GetPlayer().chunks)
121 , skeletons()
122 , loop_timer(16)
123 , player_hist() {
124         if (!save.Exists()) {
125                 save.Write(master.GetWorldConf());
126         }
127         TextureIndex tex_index;
128         master.GetEnv().loader.LoadBlockTypes("default", block_types, tex_index);
129         chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
130         chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
131         skeletons.Load();
132         // TODO: better solution for initializing HUD
133         interface.SelectNext();
134         loop_timer.Start();
135 }
136
137 void InteractiveState::OnEnter() {
138         master.GetEnv().window.GrabMouse();
139 }
140
141 void InteractiveState::Handle(const SDL_Event &event) {
142         switch (event.type) {
143                 case SDL_KEYDOWN:
144                         interface.HandlePress(event.key);
145                         break;
146                 case SDL_KEYUP:
147                         interface.HandleRelease(event.key);
148                         break;
149                 case SDL_MOUSEBUTTONDOWN:
150                         interface.HandlePress(event.button);
151                         break;
152                 case SDL_MOUSEBUTTONUP:
153                         interface.HandleRelease(event.button);
154                         break;
155                 case SDL_MOUSEMOTION:
156                         interface.Handle(event.motion);
157                         break;
158                 case SDL_MOUSEWHEEL:
159                         interface.Handle(event.wheel);
160                         break;
161                 case SDL_QUIT:
162                         master.Quit();
163                         break;
164                 default:
165                         break;
166         }
167 }
168
169 void InteractiveState::Update(int dt) {
170         loop_timer.Update(dt);
171         master.Update(dt);
172         chunk_receiver.Update(dt);
173         chunk_requester.Update(dt);
174
175         interface.Update(dt);
176         int world_dt = 0;
177         while (loop_timer.HitOnce()) {
178                 world.Update(loop_timer.Interval());
179                 world_dt += loop_timer.Interval();
180                 loop_timer.PopIteration();
181         }
182         chunk_renderer.Update(dt);
183
184         Entity &player = *interface.GetPlayer().entity;
185
186         if (world_dt > 0) {
187                 PushPlayerUpdate(player, world_dt);
188         }
189
190         glm::mat4 trans = player.Transform(player.ChunkCoords());
191         glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
192         glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
193         master.GetEnv().audio.Position(player.Position());
194         master.GetEnv().audio.Velocity(player.Velocity());
195         master.GetEnv().audio.Orientation(dir, up);
196 }
197
198 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
199         std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
200         if (player_hist.size() < 16) {
201                 player_hist.emplace_back(player.GetState(), dt, packet);
202         } else {
203                 auto entry = player_hist.begin();
204                 entry->state = player.GetState();
205                 entry->delta_t = dt;
206                 entry->packet = packet;
207                 player_hist.splice(player_hist.end(), player_hist, entry);
208         }
209 }
210
211 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
212         if (player_hist.empty()) return;
213
214         auto entry = player_hist.begin();
215         auto end = player_hist.end();
216
217         // we may have received an older packet
218         int pack_diff = int16_t(seq) - int16_t(entry->packet);
219         if (pack_diff < 0) {
220                 // indeed we have, just ignore it
221                 return;
222         }
223
224         // drop anything older than the fix
225         while (entry != end) {
226                 pack_diff = int16_t(seq) - int16_t(entry->packet);
227                 if (pack_diff > 0) {
228                         entry = player_hist.erase(entry);
229                 } else {
230                         break;
231                 }
232         }
233
234         EntityState replay_state(corrected_state);
235         EntityState &player_state = interface.GetPlayer().entity->GetState();
236
237         if (entry != end) {
238                 entry->state.chunk_pos = replay_state.chunk_pos;
239                 entry->state.block_pos = replay_state.block_pos;
240                 ++entry;
241         }
242
243         while (entry != end) {
244                 replay_state.velocity = entry->state.velocity;
245                 replay_state.Update(entry->delta_t);
246                 entry->state.chunk_pos = replay_state.chunk_pos;
247                 entry->state.block_pos = replay_state.block_pos;
248                 ++entry;
249         }
250
251         glm::vec3 displacement(replay_state.Diff(player_state));
252         const float disp_squared = dot(displacement, displacement);
253
254         if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
255                 return;
256         }
257
258         // if offset > 10cm, warp the player
259         // otherwise, move at most 1cm per frame towards
260         // the fixed position (160ms, so shouldn't be too noticeable)
261         constexpr float warp_thresh = 0.01f; // (1/10)^2
262         constexpr float max_disp = 0.0001f; // (1/100)^2
263
264         if (disp_squared > warp_thresh) {
265                 player_state.chunk_pos = replay_state.chunk_pos;
266                 player_state.block_pos = replay_state.block_pos;
267         } else if (disp_squared < max_disp) {
268                 player_state.block_pos += displacement;
269         } else {
270                 displacement *= 0.01f / sqrt(disp_squared);
271                 player_state.block_pos += displacement;
272         }
273 }
274
275 void InteractiveState::Render(Viewport &viewport) {
276         Entity &player = *interface.GetPlayer().entity;
277         viewport.WorldPosition(player.Transform(player.ChunkCoords()));
278         chunk_renderer.Render(viewport);
279         world.Render(viewport);
280         interface.Render(viewport);
281 }
282
283
284 MasterState::MasterState(
285         Environment &env,
286         const World::Config &wc,
287         const Interface::Config &ic,
288         const Client::Config &cc)
289 : env(env)
290 , world_conf(wc)
291 , intf_conf(ic)
292 , client_conf(cc)
293 , state()
294 , client(cc)
295 , init_state(*this)
296 , login_packet(-1)
297 , update_status()
298 , update_timer(16) {
299         client.GetConnection().SetHandler(this);
300         update_timer.Start();
301 }
302
303 void MasterState::Quit() {
304         if (!client.GetConnection().Closed()) {
305                 client.SendPart();
306         }
307         env.state.PopUntil(this);
308 }
309
310
311 void MasterState::OnEnter() {
312         login_packet = client.SendLogin(intf_conf.player_name);
313         env.state.Push(&init_state);
314 }
315
316
317 void MasterState::Handle(const SDL_Event &event) {
318
319 }
320
321
322 void MasterState::Update(int dt) {
323         update_timer.Update(dt);
324         client.Handle();
325         client.Update(dt);
326 }
327
328
329 void MasterState::Render(Viewport &) {
330
331 }
332
333
334 void MasterState::OnPacketLost(uint16_t id) {
335         if (id == login_packet) {
336                 login_packet = client.SendLogin(intf_conf.player_name);
337         }
338 }
339
340 void MasterState::OnTimeout() {
341         if (client.GetConnection().Closed()) {
342                 // TODO: push disconnected message
343                 cout << "connection timed out" << endl;
344                 Quit();
345         }
346 }
347
348 void MasterState::On(const Packet::Join &pack) {
349         pack.ReadWorldName(world_conf.name);
350
351         if (state) {
352                 // changing worlds
353                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
354         } else {
355                 // joining game
356                 cout << "joined game \"" << world_conf.name << '"' << endl;
357                 // server received our login
358                 login_packet = -1;
359         }
360
361         uint32_t player_id;
362         pack.ReadPlayerID(player_id);
363         state.reset(new InteractiveState(*this, player_id));
364
365         pack.ReadPlayerState(state->GetInterface().GetPlayer().entity->GetState());
366
367         env.state.PopAfter(this);
368         env.state.Push(state.get());
369 }
370
371 void MasterState::On(const Packet::Part &pack) {
372         if (state) {
373                 // kicked
374                 cout << "kicked by server" << endl;
375         } else {
376                 // join refused
377                 cout << "login refused by server" << endl;
378         }
379         Quit();
380 }
381
382 void MasterState::On(const Packet::SpawnEntity &pack) {
383         if (!state) {
384                 cout << "got entity spawn before world was created" << endl;
385                 Quit();
386                 return;
387         }
388         uint32_t entity_id;
389         pack.ReadEntityID(entity_id);
390         Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
391         UpdateEntity(entity_id, pack.Seq());
392         pack.ReadEntity(entity);
393         uint32_t skel_id;
394         pack.ReadSkeletonID(skel_id);
395         CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
396         if (skel) {
397                 skel->Instantiate(entity.GetModel());
398         }
399         cout << "spawned entity " << entity.Name() << " at " << entity.AbsolutePosition() << endl;
400 }
401
402 void MasterState::On(const Packet::DespawnEntity &pack) {
403         if (!state) {
404                 cout << "got entity despawn before world was created" << endl;
405                 Quit();
406                 return;
407         }
408         uint32_t entity_id;
409         pack.ReadEntityID(entity_id);
410         ClearEntity(entity_id);
411         for (Entity &entity : state->GetWorld().Entities()) {
412                 if (entity.ID() == entity_id) {
413                         entity.Kill();
414                         cout << "despawned entity " << entity.Name() << " at " << entity.AbsolutePosition() << endl;
415                         return;
416                 }
417         }
418 }
419
420 void MasterState::On(const Packet::EntityUpdate &pack) {
421         if (!state) {
422                 cout << "got entity update before world was created" << endl;
423                 Quit();
424                 return;
425         }
426
427         auto world_iter = state->GetWorld().Entities().begin();
428         auto world_end = state->GetWorld().Entities().end();
429
430         uint32_t count = 0;
431         pack.ReadEntityCount(count);
432
433         for (uint32_t i = 0; i < count; ++i) {
434                 uint32_t entity_id = 0;
435                 pack.ReadEntityID(entity_id, i);
436
437                 while (world_iter != world_end && world_iter->ID() < entity_id) {
438                         ++world_iter;
439                 }
440                 if (world_iter == world_end) {
441                         // nothing can be done from here
442                         return;
443                 }
444                 if (world_iter->ID() == entity_id) {
445                         if (UpdateEntity(entity_id, pack.Seq())) {
446                                 pack.ReadEntityState(world_iter->GetState(), i);
447                         }
448                 }
449         }
450 }
451
452 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
453         auto entry = update_status.find(entity_id);
454         if (entry == update_status.end()) {
455                 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
456                 return true;
457         }
458
459         int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
460         int time_diff = update_timer.Elapsed() - entry->second.last_update;
461         entry->second.last_update = update_timer.Elapsed();
462
463         if (pack_diff > 0 || time_diff > 1500) {
464                 entry->second.last_packet = seq;
465                 return true;
466         } else {
467                 return false;
468         }
469 }
470
471 void MasterState::ClearEntity(uint32_t entity_id) {
472         update_status.erase(entity_id);
473 }
474
475 void MasterState::On(const Packet::PlayerCorrection &pack) {
476         if (!state) {
477                 cout << "got player correction without a player :S" << endl;
478                 Quit();
479                 return;
480         }
481         uint16_t pack_seq;
482         EntityState corrected_state;
483         pack.ReadPacketSeq(pack_seq);
484         pack.ReadPlayerState(corrected_state);
485         state->MergePlayerCorrection(pack_seq, corrected_state);
486 }
487
488 void MasterState::On(const Packet::ChunkBegin &pack) {
489         if (!state) {
490                 cout << "got chunk data, but the world has not been created yet" << endl;
491                 cout << "great, this will totally screw up everything :(" << endl;
492                 return;
493         }
494         state->GetChunkReceiver().Handle(pack);
495 }
496
497 void MasterState::On(const Packet::ChunkData &pack) {
498         if (!state) {
499                 cout << "got chunk data, but the world has not been created yet" << endl;
500                 cout << "great, this will totally screw up everything :(" << endl;
501                 return;
502         }
503         state->GetChunkReceiver().Handle(pack);
504 }
505
506 }
507 }