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