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