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