]> git.localhorst.tv Git - blank.git/blob - src/client/client.cpp
re-request incomplete or corrupted chunk transfers
[blank.git] / src / client / client.cpp
1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
4
5 #include "../app/Environment.hpp"
6 #include "../app/init.hpp"
7 #include "../model/Model.hpp"
8 #include "../io/WorldSave.hpp"
9 #include "../world/ChunkIndex.hpp"
10 #include "../world/ChunkStore.hpp"
11
12 #include <iostream>
13 #include <glm/gtx/io.hpp>
14
15 using namespace std;
16
17
18 namespace blank {
19 namespace client {
20
21 InitialState::InitialState(MasterState &master)
22 : master(master)
23 , message() {
24         message.Position(glm::vec3(0.0f), Gravity::CENTER);
25         message.Set(master.GetEnv().assets.large_ui_font, "logging in");
26 }
27
28 void InitialState::OnEnter() {
29
30 }
31
32 void InitialState::Handle(const SDL_Event &evt) {
33         if (evt.type == SDL_QUIT) {
34                 master.Quit();
35         }
36 }
37
38 void InitialState::Update(int dt) {
39         master.Update(dt);
40 }
41
42 void InitialState::Render(Viewport &viewport) {
43         message.Render(viewport);
44 }
45
46
47 // TODO: this clutter is a giant mess
48 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
49 : master(master)
50 , res()
51 , sounds()
52 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
53 , world(res.block_types, master.GetWorldConf())
54 , player(*world.AddPlayer(master.GetConfig().player.name, player_id))
55 , hud(master.GetEnv(), master.GetConfig(), player)
56 , manip(master.GetEnv().audio, sounds, player.GetEntity())
57 , input(world, player, master.GetClient())
58 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
59 , chunk_receiver(master.GetClient(), world.Chunks(), save)
60 , chunk_renderer(player.GetChunks())
61 , loop_timer(16)
62 , stat_timer(1000)
63 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
64 , update_status()
65 , chat(master.GetEnv(), *this, *this)
66 , time_skipped(0)
67 , packets_skipped(0) {
68         if (!save.Exists()) {
69                 save.Write(master.GetWorldConf());
70         }
71         res.Load(master.GetEnv().loader, "default");
72         if (res.models.size() < 1) {
73                 throw std::runtime_error("need at least one model to run");
74         }
75         res.models[0].Instantiate(player.GetEntity().GetModel());
76         sounds.Load(master.GetEnv().loader, res.snd_index);
77         interface.SetInventorySlots(res.block_types.size() - 1);
78         chunk_renderer.LoadTextures(master.GetEnv().loader, res.tex_index);
79         chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
80         loop_timer.Start();
81         stat_timer.Start();
82         if (save.Exists(player)) {
83                 save.Read(player);
84         }
85 }
86
87 void InteractiveState::OnResume() {
88         OnFocus();
89 }
90
91 void InteractiveState::OnPause() {
92         OnBlur();
93 }
94
95 void InteractiveState::OnFocus() {
96         if (master.GetConfig().input.mouse) {
97                 master.GetEnv().window.GrabMouse();
98         }
99         interface.Unlock();
100 }
101
102 void InteractiveState::OnBlur() {
103         master.GetEnv().window.ReleaseMouse();
104         interface.Lock();
105 }
106
107 void InteractiveState::Handle(const SDL_Event &event) {
108         switch (event.type) {
109                 case SDL_KEYDOWN:
110                         // TODO: move to interface
111                         if (event.key.keysym.sym == SDLK_RETURN) {
112                                 chat.Clear();
113                                 master.GetEnv().state.Push(&chat);
114                                 hud.KeepMessages(true);
115                         } else if (event.key.keysym.sym == SDLK_SLASH) {
116                                 chat.Preset("/");
117                                 master.GetEnv().state.Push(&chat);
118                                 hud.KeepMessages(true);
119                         } else {
120                                 interface.HandlePress(event.key);
121                         }
122                         break;
123                 case SDL_KEYUP:
124                         interface.HandleRelease(event.key);
125                         break;
126                 case SDL_MOUSEBUTTONDOWN:
127                         interface.HandlePress(event.button);
128                         break;
129                 case SDL_MOUSEBUTTONUP:
130                         interface.HandleRelease(event.button);
131                         break;
132                 case SDL_MOUSEMOTION:
133                         interface.Handle(event.motion);
134                         break;
135                 case SDL_MOUSEWHEEL:
136                         interface.Handle(event.wheel);
137                         break;
138                 case SDL_QUIT:
139                         Exit();
140                         break;
141                 default:
142                         break;
143         }
144 }
145
146 void InteractiveState::Update(int dt) {
147         loop_timer.Update(dt);
148         stat_timer.Update(dt);
149         master.Update(dt);
150         chunk_receiver.Update(dt);
151
152         int world_dt = 0;
153         while (loop_timer.HitOnce()) {
154                 world.Update(loop_timer.Interval());
155                 world_dt += loop_timer.Interval();
156                 loop_timer.PopIteration();
157         }
158         chunk_renderer.Update(dt);
159
160         if (input.BlockFocus()) {
161                 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
162         } else if (input.EntityFocus()) {
163                 hud.FocusEntity(*input.EntityFocus().entity);
164         } else {
165                 hud.FocusNone();
166         }
167         if (world_dt > 0) {
168                 if (input.UpdateImportant() || packets_skipped >= master.NetStat().SuggestedPacketSkip()) {
169                         input.PushPlayerUpdate(time_skipped + world_dt);
170                         time_skipped = 0;
171                         packets_skipped = 0;
172                 } else {
173                         time_skipped += world_dt;
174                         ++packets_skipped;
175                 }
176         }
177         hud.Display(res.block_types[player.GetInventorySlot() + 1]);
178         if (stat_timer.Hit()) {
179                 hud.UpdateNetStats(master.NetStat());
180         }
181         hud.Update(dt);
182
183         glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
184         glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
185         glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
186         master.GetEnv().audio.Position(player.GetEntity().Position());
187         master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
188         master.GetEnv().audio.Orientation(dir, up);
189 }
190
191 void InteractiveState::Render(Viewport &viewport) {
192         viewport.WorldPosition(player.GetEntity().ViewTransform(player.GetEntity().ChunkCoords()));
193         if (master.GetConfig().video.world) {
194                 chunk_renderer.Render(viewport);
195                 world.Render(viewport);
196                 if (master.GetConfig().video.debug) {
197                         world.RenderDebug(viewport);
198                 }
199                 sky.Render(viewport);
200         }
201         hud.Render(viewport);
202 }
203
204 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
205         uint32_t entity_id;
206         pack.ReadEntityID(entity_id);
207         Entity &entity = world.ForceAddEntity(entity_id);
208         UpdateEntity(entity_id, pack.Seq());
209         pack.ReadEntity(entity);
210         uint32_t model_id;
211         pack.ReadModelID(model_id);
212         if (model_id > 0 && model_id <= res.models.size()) {
213                 res.models.Get(model_id).Instantiate(entity.GetModel());
214         }
215 }
216
217 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
218         uint32_t entity_id;
219         pack.ReadEntityID(entity_id);
220         ClearEntity(entity_id);
221         for (Entity &entity : world.Entities()) {
222                 if (entity.ID() == entity_id) {
223                         entity.Kill();
224                         return;
225                 }
226         }
227 }
228
229 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
230         auto world_iter = world.Entities().begin();
231         auto world_end = world.Entities().end();
232
233         uint32_t count = 0;
234         glm::ivec3 base;
235         pack.ReadEntityCount(count);
236         pack.ReadChunkBase(base);
237         EntityState state;
238
239         for (uint32_t i = 0; i < count; ++i) {
240                 uint32_t entity_id = 0;
241                 pack.ReadEntityID(entity_id, i);
242
243                 while (world_iter != world_end && world_iter->ID() < entity_id) {
244                         ++world_iter;
245                 }
246                 if (world_iter == world_end) {
247                         // nothing can be done from here
248                         return;
249                 }
250                 if (world_iter->ID() == entity_id) {
251                         if (UpdateEntity(entity_id, pack.Seq())) {
252                                 pack.ReadEntityState(state, base, i);
253                                 world_iter->SetState(state);
254                         }
255                 }
256         }
257 }
258
259 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
260         auto entry = update_status.find(entity_id);
261         if (entry == update_status.end()) {
262                 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
263                 return true;
264         }
265
266         int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
267         int time_diff = loop_timer.Elapsed() - entry->second.last_update;
268         entry->second.last_update = loop_timer.Elapsed();
269
270         if (pack_diff > 0 || time_diff > 1500) {
271                 entry->second.last_packet = seq;
272                 return true;
273         } else {
274                 return false;
275         }
276 }
277
278 void InteractiveState::ClearEntity(uint32_t entity_id) {
279         update_status.erase(entity_id);
280 }
281
282 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
283         uint16_t pack_seq;
284         EntityState corrected_state;
285         pack.ReadPacketSeq(pack_seq);
286         pack.ReadPlayerState(corrected_state);
287         input.MergePlayerCorrection(pack_seq, corrected_state);
288 }
289
290 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
291         glm::ivec3 pos;
292         pack.ReadChunkCoords(pos);
293         Chunk *chunk = player.GetChunks().Get(pos);
294         if (!chunk) {
295                 // this change doesn't concern us
296                 return;
297         }
298         uint32_t count = 0;
299         pack.ReadBlockCount(count);
300         for (uint32_t i = 0; i < count; ++i) {
301                 uint16_t index;
302                 Block block;
303                 pack.ReadIndex(index, i);
304                 pack.ReadBlock(block, i);
305                 if (index < Chunk::size && block.type < res.block_types.size()) {
306                         manip.SetBlock(*chunk, index, block);
307                 }
308         }
309 }
310
311 void InteractiveState::Handle(const Packet::Message &pack) {
312         string msg;
313         pack.ReadMessage(msg);
314         hud.PostMessage(msg);
315 }
316
317 void InteractiveState::SetAudio(bool b) {
318         master.GetConfig().audio.enabled = b;
319         if (b) {
320                 hud.PostMessage("Audio enabled");
321         } else {
322                 hud.PostMessage("Audio disabled");
323         }
324 }
325
326 void InteractiveState::SetVideo(bool b) {
327         master.GetConfig().video.world = b;
328         if (b) {
329                 hud.PostMessage("World rendering enabled");
330         } else {
331                 hud.PostMessage("World rendering disabled");
332         }
333 }
334
335 void InteractiveState::SetHUD(bool b) {
336         master.GetConfig().video.hud = b;
337         if (b) {
338                 hud.PostMessage("HUD rendering enabled");
339         } else {
340                 hud.PostMessage("HUD rendering disabled");
341         }
342 }
343
344 void InteractiveState::SetDebug(bool b) {
345         master.GetConfig().video.debug = b;
346         if (b) {
347                 hud.PostMessage("Debug rendering enabled");
348         } else {
349                 hud.PostMessage("Debug rendering disabled");
350         }
351 }
352
353 void InteractiveState::Exit() {
354         save.Write(player);
355         master.Quit();
356 }
357
358 void InteractiveState::OnLineSubmit(const string &line) {
359         if (!line.empty()) {
360                 master.GetClient().SendMessage(1, 0, line);
361         }
362 }
363
364
365 MasterState::MasterState(
366         Environment &env,
367         Config &config,
368         const World::Config &wc)
369 : env(env)
370 , config(config)
371 , world_conf(wc)
372 , state()
373 , client(config.net)
374 , init_state(*this)
375 , login_packet(-1) {
376         client.GetConnection().SetHandler(this);
377 }
378
379 void MasterState::Quit() {
380         if (!client.GetConnection().Closed()) {
381                 client.SendPart();
382         }
383         env.state.PopUntil(this);
384 }
385
386
387 void MasterState::OnEnter() {
388         login_packet = client.SendLogin(config.player.name);
389         env.state.Push(&init_state);
390 }
391
392
393 void MasterState::Handle(const SDL_Event &event) {
394
395 }
396
397
398 void MasterState::Update(int dt) {
399         client.Handle();
400         client.Update(dt);
401 }
402
403
404 void MasterState::Render(Viewport &) {
405
406 }
407
408
409 void MasterState::OnPacketLost(uint16_t id) {
410         if (id == login_packet) {
411                 login_packet = client.SendLogin(config.player.name);
412         }
413 }
414
415 void MasterState::OnTimeout() {
416         if (client.GetConnection().Closed()) {
417                 Quit();
418                 env.ShowMessage("connection timed out");
419         }
420 }
421
422 void MasterState::On(const Packet::Join &pack) {
423         pack.ReadWorldName(world_conf.name);
424
425         if (state) {
426                 // changing worlds
427                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
428         } else {
429                 // joining game
430                 cout << "joined game \"" << world_conf.name << '"' << endl;
431                 // server received our login
432                 login_packet = -1;
433         }
434
435         uint32_t player_id;
436         pack.ReadPlayerID(player_id);
437         state.reset(new InteractiveState(*this, player_id));
438
439         EntityState player_state;
440         pack.ReadPlayerState(player_state);
441         state->GetPlayer().GetEntity().SetState(player_state);
442
443         env.state.PopAfter(this);
444         env.state.Push(state.get());
445 }
446
447 void MasterState::On(const Packet::Part &pack) {
448         Quit();
449         if (state) {
450                 // kicked
451                 env.ShowMessage("kicked by server");
452         } else {
453                 // join refused
454                 env.ShowMessage("login refused by server");
455         }
456 }
457
458 void MasterState::On(const Packet::SpawnEntity &pack) {
459         if (!state) {
460                 cout << "got entity spawn before world was created" << endl;
461                 return;
462         }
463         state->Handle(pack);
464 }
465
466 void MasterState::On(const Packet::DespawnEntity &pack) {
467         if (!state) {
468                 cout << "got entity despawn before world was created" << endl;
469                 return;
470         }
471         state->Handle(pack);
472 }
473
474 void MasterState::On(const Packet::EntityUpdate &pack) {
475         if (!state) {
476                 cout << "got entity update before world was created" << endl;
477                 return;
478         }
479         state->Handle(pack);
480 }
481
482 void MasterState::On(const Packet::PlayerCorrection &pack) {
483         if (!state) {
484                 cout << "got player correction without a player :S" << endl;
485                 return;
486         }
487         state->Handle(pack);
488 }
489
490 void MasterState::On(const Packet::ChunkBegin &pack) {
491         if (!state) {
492                 cout << "got chunk data, but the world has not been created yet" << endl;
493                 cout << "great, this will totally screw up everything :(" << endl;
494                 return;
495         }
496         state->GetChunkReceiver().Handle(pack);
497 }
498
499 void MasterState::On(const Packet::ChunkData &pack) {
500         if (!state) {
501                 cout << "got chunk data, but the world has not been created yet" << endl;
502                 cout << "great, this will totally screw up everything :(" << endl;
503                 return;
504         }
505         state->GetChunkReceiver().Handle(pack);
506 }
507
508 void MasterState::On(const Packet::BlockUpdate &pack) {
509         if (!state) {
510                 cout << "received block update, but the world has not been created yet" << endl;
511                 return;
512         }
513         state->Handle(pack);
514 }
515
516 void MasterState::On(const Packet::Message &pack) {
517         if (state) {
518                 state->Handle(pack);
519         } else {
520                 string msg;
521                 pack.ReadMessage(msg);
522                 cout << "got message before interface was created: " << msg << endl;
523         }
524 }
525
526 }
527 }