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