]> git.localhorst.tv Git - blank.git/blob - src/client/client.cpp
split input handling
[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.GetConfig().net.host))
110 , world(block_types, master.GetWorldConf())
111 , player(*world.AddPlayer(master.GetConfig().player.name))
112 , hud(master.GetEnv(), master.GetConfig(), player)
113 , manip(master.GetEnv(), player.GetEntity())
114 , input(world, player, manip)
115 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
116 // TODO: looks like chunk requester and receiver can and should be merged
117 , chunk_requester(world.Chunks(), save)
118 , chunk_receiver(world.Chunks())
119 , chunk_renderer(player.GetChunks())
120 , skeletons()
121 , loop_timer(16)
122 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
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         loop_timer.Start();
133 }
134
135 void InteractiveState::OnEnter() {
136         master.GetEnv().window.GrabMouse();
137 }
138
139 void InteractiveState::Handle(const SDL_Event &event) {
140         switch (event.type) {
141                 case SDL_KEYDOWN:
142                         interface.HandlePress(event.key);
143                         break;
144                 case SDL_KEYUP:
145                         interface.HandleRelease(event.key);
146                         break;
147                 case SDL_MOUSEBUTTONDOWN:
148                         interface.HandlePress(event.button);
149                         break;
150                 case SDL_MOUSEBUTTONUP:
151                         interface.HandleRelease(event.button);
152                         break;
153                 case SDL_MOUSEMOTION:
154                         interface.Handle(event.motion);
155                         break;
156                 case SDL_MOUSEWHEEL:
157                         interface.Handle(event.wheel);
158                         break;
159                 case SDL_QUIT:
160                         master.Quit();
161                         break;
162                 default:
163                         break;
164         }
165 }
166
167 void InteractiveState::Update(int dt) {
168         input.Update(dt);
169         if (input.BlockFocus()) {
170                 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
171         } else if (input.EntityFocus()) {
172                 hud.FocusEntity(*input.EntityFocus().entity);
173         }
174         hud.Display(block_types[player.GetInventorySlot() + 1]);
175         loop_timer.Update(dt);
176         master.Update(dt);
177         chunk_receiver.Update(dt);
178         chunk_requester.Update(dt);
179
180         hud.Update(dt);
181         int world_dt = 0;
182         while (loop_timer.HitOnce()) {
183                 world.Update(loop_timer.Interval());
184                 world_dt += loop_timer.Interval();
185                 loop_timer.PopIteration();
186         }
187         chunk_renderer.Update(dt);
188
189         if (world_dt > 0) {
190                 PushPlayerUpdate(player.GetEntity(), world_dt);
191         }
192
193         glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
194         glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
195         glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
196         master.GetEnv().audio.Position(player.GetEntity().Position());
197         master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
198         master.GetEnv().audio.Orientation(dir, up);
199 }
200
201 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
202         std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
203         if (player_hist.size() < 16) {
204                 player_hist.emplace_back(player.GetState(), dt, packet);
205         } else {
206                 auto entry = player_hist.begin();
207                 entry->state = player.GetState();
208                 entry->delta_t = dt;
209                 entry->packet = packet;
210                 player_hist.splice(player_hist.end(), player_hist, entry);
211         }
212 }
213
214 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
215         if (player_hist.empty()) return;
216
217         auto entry = player_hist.begin();
218         auto end = player_hist.end();
219
220         // we may have received an older packet
221         int pack_diff = int16_t(seq) - int16_t(entry->packet);
222         if (pack_diff < 0) {
223                 // indeed we have, just ignore it
224                 return;
225         }
226
227         // drop anything older than the fix
228         while (entry != end) {
229                 pack_diff = int16_t(seq) - int16_t(entry->packet);
230                 if (pack_diff > 0) {
231                         entry = player_hist.erase(entry);
232                 } else {
233                         break;
234                 }
235         }
236
237         EntityState replay_state(corrected_state);
238         EntityState &player_state = player.GetEntity().GetState();
239
240         if (entry != end) {
241                 entry->state.chunk_pos = replay_state.chunk_pos;
242                 entry->state.block_pos = replay_state.block_pos;
243                 ++entry;
244         }
245
246         while (entry != end) {
247                 replay_state.velocity = entry->state.velocity;
248                 replay_state.Update(entry->delta_t);
249                 entry->state.chunk_pos = replay_state.chunk_pos;
250                 entry->state.block_pos = replay_state.block_pos;
251                 ++entry;
252         }
253
254         glm::vec3 displacement(replay_state.Diff(player_state));
255         const float disp_squared = dot(displacement, displacement);
256
257         if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
258                 return;
259         }
260
261         // if offset > 10cm, warp the player
262         // otherwise, move at most 1cm per frame towards
263         // the fixed position (160ms, so shouldn't be too noticeable)
264         constexpr float warp_thresh = 0.01f; // (1/10)^2
265         constexpr float max_disp = 0.0001f; // (1/100)^2
266
267         if (disp_squared > warp_thresh) {
268                 player_state.chunk_pos = replay_state.chunk_pos;
269                 player_state.block_pos = replay_state.block_pos;
270         } else if (disp_squared < max_disp) {
271                 player_state.block_pos += displacement;
272         } else {
273                 displacement *= 0.01f / sqrt(disp_squared);
274                 player_state.block_pos += displacement;
275         }
276 }
277
278 void InteractiveState::Render(Viewport &viewport) {
279         viewport.WorldPosition(player.GetEntity().Transform(player.GetEntity().ChunkCoords()));
280         if (master.GetConfig().video.world) {
281                 chunk_renderer.Render(viewport);
282                 world.Render(viewport);
283                 sky.Render(viewport);
284         }
285         hud.Render(viewport);
286 }
287
288 void InteractiveState::SetAudio(bool b) {
289         master.GetConfig().audio.enabled = b;
290         if (b) {
291                 hud.PostMessage("Audio enabled");
292         } else {
293                 hud.PostMessage("Audio disabled");
294         }
295 }
296
297 void InteractiveState::SetVideo(bool b) {
298         master.GetConfig().video.world = b;
299         if (b) {
300                 hud.PostMessage("World rendering enabled");
301         } else {
302                 hud.PostMessage("World rendering disabled");
303         }
304 }
305
306 void InteractiveState::SetHUD(bool b) {
307         master.GetConfig().video.hud = b;
308         if (b) {
309                 hud.PostMessage("HUD rendering enabled");
310         } else {
311                 hud.PostMessage("HUD rendering disabled");
312         }
313 }
314
315 void InteractiveState::SetDebug(bool b) {
316         master.GetConfig().video.debug = b;
317         if (b) {
318                 hud.PostMessage("Debug rendering enabled");
319         } else {
320                 hud.PostMessage("Debug rendering disabled");
321         }
322 }
323
324 void InteractiveState::Exit() {
325         master.Quit();
326 }
327
328
329 MasterState::MasterState(
330         Environment &env,
331         Config &config,
332         const World::Config &wc)
333 : env(env)
334 , config(config)
335 , world_conf(wc)
336 , state()
337 , client(config.net)
338 , init_state(*this)
339 , login_packet(-1)
340 , update_status()
341 , update_timer(16) {
342         client.GetConnection().SetHandler(this);
343         update_timer.Start();
344 }
345
346 void MasterState::Quit() {
347         if (!client.GetConnection().Closed()) {
348                 client.SendPart();
349         }
350         env.state.PopUntil(this);
351 }
352
353
354 void MasterState::OnEnter() {
355         login_packet = client.SendLogin(config.player.name);
356         env.state.Push(&init_state);
357 }
358
359
360 void MasterState::Handle(const SDL_Event &event) {
361
362 }
363
364
365 void MasterState::Update(int dt) {
366         update_timer.Update(dt);
367         client.Handle();
368         client.Update(dt);
369 }
370
371
372 void MasterState::Render(Viewport &) {
373
374 }
375
376
377 void MasterState::OnPacketLost(uint16_t id) {
378         if (id == login_packet) {
379                 login_packet = client.SendLogin(config.player.name);
380         }
381 }
382
383 void MasterState::OnTimeout() {
384         if (client.GetConnection().Closed()) {
385                 // TODO: push disconnected message
386                 cout << "connection timed out" << endl;
387                 Quit();
388         }
389 }
390
391 void MasterState::On(const Packet::Join &pack) {
392         pack.ReadWorldName(world_conf.name);
393
394         if (state) {
395                 // changing worlds
396                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
397         } else {
398                 // joining game
399                 cout << "joined game \"" << world_conf.name << '"' << endl;
400                 // server received our login
401                 login_packet = -1;
402         }
403
404         uint32_t player_id;
405         pack.ReadPlayerID(player_id);
406         state.reset(new InteractiveState(*this, player_id));
407
408         pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
409
410         env.state.PopAfter(this);
411         env.state.Push(state.get());
412 }
413
414 void MasterState::On(const Packet::Part &pack) {
415         if (state) {
416                 // kicked
417                 cout << "kicked by server" << endl;
418         } else {
419                 // join refused
420                 cout << "login refused by server" << endl;
421         }
422         Quit();
423 }
424
425 void MasterState::On(const Packet::SpawnEntity &pack) {
426         if (!state) {
427                 cout << "got entity spawn before world was created" << endl;
428                 Quit();
429                 return;
430         }
431         uint32_t entity_id;
432         pack.ReadEntityID(entity_id);
433         Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
434         UpdateEntity(entity_id, pack.Seq());
435         pack.ReadEntity(entity);
436         uint32_t skel_id;
437         pack.ReadSkeletonID(skel_id);
438         CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
439         if (skel) {
440                 skel->Instantiate(entity.GetModel());
441         }
442         cout << "spawned entity #" << entity_id << "  (" << entity.Name()
443                 << ") at " << entity.AbsolutePosition() << endl;
444 }
445
446 void MasterState::On(const Packet::DespawnEntity &pack) {
447         if (!state) {
448                 cout << "got entity despawn before world was created" << endl;
449                 Quit();
450                 return;
451         }
452         uint32_t entity_id;
453         pack.ReadEntityID(entity_id);
454         ClearEntity(entity_id);
455         for (Entity &entity : state->GetWorld().Entities()) {
456                 if (entity.ID() == entity_id) {
457                         entity.Kill();
458                         cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
459                         return;
460                 }
461         }
462 }
463
464 void MasterState::On(const Packet::EntityUpdate &pack) {
465         if (!state) {
466                 cout << "got entity update before world was created" << endl;
467                 Quit();
468                 return;
469         }
470
471         auto world_iter = state->GetWorld().Entities().begin();
472         auto world_end = state->GetWorld().Entities().end();
473
474         uint32_t count = 0;
475         pack.ReadEntityCount(count);
476
477         for (uint32_t i = 0; i < count; ++i) {
478                 uint32_t entity_id = 0;
479                 pack.ReadEntityID(entity_id, i);
480
481                 while (world_iter != world_end && world_iter->ID() < entity_id) {
482                         ++world_iter;
483                 }
484                 if (world_iter == world_end) {
485                         // nothing can be done from here
486                         return;
487                 }
488                 if (world_iter->ID() == entity_id) {
489                         if (UpdateEntity(entity_id, pack.Seq())) {
490                                 pack.ReadEntityState(world_iter->GetState(), i);
491                         }
492                 }
493         }
494 }
495
496 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
497         auto entry = update_status.find(entity_id);
498         if (entry == update_status.end()) {
499                 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
500                 return true;
501         }
502
503         int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
504         int time_diff = update_timer.Elapsed() - entry->second.last_update;
505         entry->second.last_update = update_timer.Elapsed();
506
507         if (pack_diff > 0 || time_diff > 1500) {
508                 entry->second.last_packet = seq;
509                 return true;
510         } else {
511                 return false;
512         }
513 }
514
515 void MasterState::ClearEntity(uint32_t entity_id) {
516         update_status.erase(entity_id);
517 }
518
519 void MasterState::On(const Packet::PlayerCorrection &pack) {
520         if (!state) {
521                 cout << "got player correction without a player :S" << endl;
522                 Quit();
523                 return;
524         }
525         uint16_t pack_seq;
526         EntityState corrected_state;
527         pack.ReadPacketSeq(pack_seq);
528         pack.ReadPlayerState(corrected_state);
529         state->MergePlayerCorrection(pack_seq, corrected_state);
530 }
531
532 void MasterState::On(const Packet::ChunkBegin &pack) {
533         if (!state) {
534                 cout << "got chunk data, but the world has not been created yet" << endl;
535                 cout << "great, this will totally screw up everything :(" << endl;
536                 return;
537         }
538         state->GetChunkReceiver().Handle(pack);
539 }
540
541 void MasterState::On(const Packet::ChunkData &pack) {
542         if (!state) {
543                 cout << "got chunk data, but the world has not been created yet" << endl;
544                 cout << "great, this will totally screw up everything :(" << endl;
545                 return;
546         }
547         state->GetChunkReceiver().Handle(pack);
548 }
549
550 }
551 }