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