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