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