]> git.localhorst.tv Git - blank.git/blob - src/client/client.cpp
store players in world save
[blank.git] / src / client / client.cpp
1 #include "ChunkRequester.hpp"
2 #include "InitialState.hpp"
3 #include "InteractiveState.hpp"
4 #include "MasterState.hpp"
5
6 #include "../app/Environment.hpp"
7 #include "../app/init.hpp"
8 #include "../app/TextureIndex.hpp"
9 #include "../model/CompositeModel.hpp"
10 #include "../io/WorldSave.hpp"
11 #include "../world/ChunkIndex.hpp"
12 #include "../world/ChunkStore.hpp"
13
14 #include <iostream>
15 #include <glm/gtx/io.hpp>
16
17 using namespace std;
18
19
20 namespace blank {
21 namespace client {
22
23 ChunkRequester::ChunkRequester(
24         ChunkStore &store,
25         const WorldSave &save
26 ) noexcept
27 : store(store)
28 , save(save) {
29
30 }
31
32 void ChunkRequester::Update(int dt) {
33         // check if there's chunks waiting to be loaded
34         LoadN(10);
35
36         // store a few chunks as well
37         constexpr int max_save = 10;
38         int saved = 0;
39         for (Chunk &chunk : store) {
40                 if (chunk.ShouldUpdateSave()) {
41                         save.Write(chunk);
42                         ++saved;
43                         if (saved >= max_save) {
44                                 break;
45                         }
46                 }
47         }
48 }
49
50 int ChunkRequester::ToLoad() const noexcept {
51         return store.EstimateMissing();
52 }
53
54 void ChunkRequester::LoadOne() {
55         if (!store.HasMissing()) return;
56
57         Chunk::Pos pos = store.NextMissing();
58         Chunk *chunk = store.Allocate(pos);
59         if (!chunk) {
60                 // chunk store corrupted?
61                 return;
62         }
63
64         if (save.Exists(pos)) {
65                 save.Read(*chunk);
66                 // TODO: request chunk from server with cache tag
67         } else {
68                 // TODO: request chunk from server
69         }
70 }
71
72 void ChunkRequester::LoadN(std::size_t n) {
73         std::size_t end = std::min(n, std::size_t(ToLoad()));
74         for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
75                 LoadOne();
76         }
77 }
78
79
80 InitialState::InitialState(MasterState &master)
81 : master(master)
82 , message() {
83         message.Position(glm::vec3(0.0f), Gravity::CENTER);
84         message.Set(master.GetEnv().assets.large_ui_font, "logging in");
85 }
86
87 void InitialState::OnEnter() {
88
89 }
90
91 void InitialState::Handle(const SDL_Event &evt) {
92         if (evt.type == SDL_QUIT) {
93                 master.Quit();
94         }
95 }
96
97 void InitialState::Update(int dt) {
98         master.Update(dt);
99 }
100
101 void InitialState::Render(Viewport &viewport) {
102         message.Render(viewport);
103 }
104
105
106 // TODO: this clutter is a giant mess
107 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
108 : master(master)
109 , block_types()
110 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
111 , world(block_types, master.GetWorldConf())
112 , player(*world.AddPlayer(master.GetConfig().player.name))
113 , hud(master.GetEnv(), master.GetConfig(), player)
114 , manip(master.GetEnv(), player.GetEntity())
115 , input(world, player, master.GetClient())
116 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
117 // TODO: looks like chunk requester and receiver can and should be merged
118 , chunk_requester(world.Chunks(), save)
119 , chunk_receiver(world.Chunks())
120 , chunk_renderer(player.GetChunks())
121 , skeletons()
122 , loop_timer(16)
123 , sky(master.GetEnv().loader.LoadCubeMap("skybox")) {
124         if (!save.Exists()) {
125                 save.Write(master.GetWorldConf());
126         }
127         TextureIndex tex_index;
128         master.GetEnv().loader.LoadBlockTypes("default", block_types, tex_index);
129         interface.SetInventorySlots(block_types.Size() - 1);
130         chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
131         chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
132         skeletons.Load();
133         loop_timer.Start();
134         if (save.Exists(player)) {
135                 save.Read(player);
136         }
137 }
138
139 void InteractiveState::OnEnter() {
140         master.GetEnv().window.GrabMouse();
141 }
142
143 void InteractiveState::Handle(const SDL_Event &event) {
144         switch (event.type) {
145                 case SDL_KEYDOWN:
146                         interface.HandlePress(event.key);
147                         break;
148                 case SDL_KEYUP:
149                         interface.HandleRelease(event.key);
150                         break;
151                 case SDL_MOUSEBUTTONDOWN:
152                         interface.HandlePress(event.button);
153                         break;
154                 case SDL_MOUSEBUTTONUP:
155                         interface.HandleRelease(event.button);
156                         break;
157                 case SDL_MOUSEMOTION:
158                         interface.Handle(event.motion);
159                         break;
160                 case SDL_MOUSEWHEEL:
161                         interface.Handle(event.wheel);
162                         break;
163                 case SDL_QUIT:
164                         Exit();
165                         break;
166                 default:
167                         break;
168         }
169 }
170
171 void InteractiveState::Update(int dt) {
172         input.Update(dt);
173         if (input.BlockFocus()) {
174                 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
175         } else if (input.EntityFocus()) {
176                 hud.FocusEntity(*input.EntityFocus().entity);
177         } else {
178                 hud.FocusNone();
179         }
180         hud.Display(block_types[player.GetInventorySlot() + 1]);
181         loop_timer.Update(dt);
182         master.Update(dt);
183         chunk_receiver.Update(dt);
184         chunk_requester.Update(dt);
185
186         hud.Update(dt);
187         int world_dt = 0;
188         while (loop_timer.HitOnce()) {
189                 world.Update(loop_timer.Interval());
190                 world_dt += loop_timer.Interval();
191                 loop_timer.PopIteration();
192         }
193         chunk_renderer.Update(dt);
194
195         if (world_dt > 0) {
196                 input.PushPlayerUpdate(world_dt);
197         }
198
199         glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
200         glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
201         glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
202         master.GetEnv().audio.Position(player.GetEntity().Position());
203         master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
204         master.GetEnv().audio.Orientation(dir, up);
205 }
206
207 void InteractiveState::Render(Viewport &viewport) {
208         viewport.WorldPosition(player.GetEntity().Transform(player.GetEntity().ChunkCoords()));
209         if (master.GetConfig().video.world) {
210                 chunk_renderer.Render(viewport);
211                 world.Render(viewport);
212                 sky.Render(viewport);
213         }
214         hud.Render(viewport);
215 }
216
217 void InteractiveState::MergePlayerCorrection(std::uint16_t pack, const EntityState &state) {
218         input.MergePlayerCorrection(pack, state);
219 }
220
221 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
222         glm::ivec3 pos;
223         pack.ReadChunkCoords(pos);
224         Chunk *chunk = player.GetChunks().Get(pos);
225         if (!chunk) {
226                 // this change doesn't concern us
227                 return;
228         }
229         uint32_t count = 0;
230         pack.ReadBlockCount(count);
231         for (uint32_t i = 0; i < count; ++i) {
232                 uint16_t index;
233                 Block block;
234                 pack.ReadIndex(index, i);
235                 pack.ReadBlock(block, i);
236                 if (index < Chunk::size && block.type < block_types.Size()) {
237                         manip.SetBlock(*chunk, index, block);
238                 }
239         }
240 }
241
242 void InteractiveState::SetAudio(bool b) {
243         master.GetConfig().audio.enabled = b;
244         if (b) {
245                 hud.PostMessage("Audio enabled");
246         } else {
247                 hud.PostMessage("Audio disabled");
248         }
249 }
250
251 void InteractiveState::SetVideo(bool b) {
252         master.GetConfig().video.world = b;
253         if (b) {
254                 hud.PostMessage("World rendering enabled");
255         } else {
256                 hud.PostMessage("World rendering disabled");
257         }
258 }
259
260 void InteractiveState::SetHUD(bool b) {
261         master.GetConfig().video.hud = b;
262         if (b) {
263                 hud.PostMessage("HUD rendering enabled");
264         } else {
265                 hud.PostMessage("HUD rendering disabled");
266         }
267 }
268
269 void InteractiveState::SetDebug(bool b) {
270         master.GetConfig().video.debug = b;
271         if (b) {
272                 hud.PostMessage("Debug rendering enabled");
273         } else {
274                 hud.PostMessage("Debug rendering disabled");
275         }
276 }
277
278 void InteractiveState::Exit() {
279         save.Write(player);
280         master.Quit();
281 }
282
283
284 MasterState::MasterState(
285         Environment &env,
286         Config &config,
287         const World::Config &wc)
288 : env(env)
289 , config(config)
290 , world_conf(wc)
291 , state()
292 , client(config.net)
293 , init_state(*this)
294 , login_packet(-1)
295 , update_status()
296 , update_timer(16) {
297         client.GetConnection().SetHandler(this);
298         update_timer.Start();
299 }
300
301 void MasterState::Quit() {
302         if (!client.GetConnection().Closed()) {
303                 client.SendPart();
304         }
305         env.state.PopUntil(this);
306 }
307
308
309 void MasterState::OnEnter() {
310         login_packet = client.SendLogin(config.player.name);
311         env.state.Push(&init_state);
312 }
313
314
315 void MasterState::Handle(const SDL_Event &event) {
316
317 }
318
319
320 void MasterState::Update(int dt) {
321         update_timer.Update(dt);
322         client.Handle();
323         client.Update(dt);
324 }
325
326
327 void MasterState::Render(Viewport &) {
328
329 }
330
331
332 void MasterState::OnPacketLost(uint16_t id) {
333         if (id == login_packet) {
334                 login_packet = client.SendLogin(config.player.name);
335         }
336 }
337
338 void MasterState::OnTimeout() {
339         if (client.GetConnection().Closed()) {
340                 // TODO: push disconnected message
341                 cout << "connection timed out" << endl;
342                 Quit();
343         }
344 }
345
346 void MasterState::On(const Packet::Join &pack) {
347         pack.ReadWorldName(world_conf.name);
348
349         if (state) {
350                 // changing worlds
351                 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
352         } else {
353                 // joining game
354                 cout << "joined game \"" << world_conf.name << '"' << endl;
355                 // server received our login
356                 login_packet = -1;
357         }
358
359         uint32_t player_id;
360         pack.ReadPlayerID(player_id);
361         state.reset(new InteractiveState(*this, player_id));
362
363         pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
364
365         env.state.PopAfter(this);
366         env.state.Push(state.get());
367 }
368
369 void MasterState::On(const Packet::Part &pack) {
370         if (state) {
371                 // kicked
372                 cout << "kicked by server" << endl;
373         } else {
374                 // join refused
375                 cout << "login refused by server" << endl;
376         }
377         Quit();
378 }
379
380 void MasterState::On(const Packet::SpawnEntity &pack) {
381         if (!state) {
382                 cout << "got entity spawn before world was created" << endl;
383                 Quit();
384                 return;
385         }
386         uint32_t entity_id;
387         pack.ReadEntityID(entity_id);
388         Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
389         UpdateEntity(entity_id, pack.Seq());
390         pack.ReadEntity(entity);
391         uint32_t skel_id;
392         pack.ReadSkeletonID(skel_id);
393         CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
394         if (skel) {
395                 skel->Instantiate(entity.GetModel());
396         }
397         cout << "spawned entity #" << entity_id << "  (" << entity.Name()
398                 << ") at " << entity.AbsolutePosition() << endl;
399 }
400
401 void MasterState::On(const Packet::DespawnEntity &pack) {
402         if (!state) {
403                 cout << "got entity despawn before world was created" << endl;
404                 Quit();
405                 return;
406         }
407         uint32_t entity_id;
408         pack.ReadEntityID(entity_id);
409         ClearEntity(entity_id);
410         for (Entity &entity : state->GetWorld().Entities()) {
411                 if (entity.ID() == entity_id) {
412                         entity.Kill();
413                         cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
414                         return;
415                 }
416         }
417 }
418
419 void MasterState::On(const Packet::EntityUpdate &pack) {
420         if (!state) {
421                 cout << "got entity update before world was created" << endl;
422                 Quit();
423                 return;
424         }
425
426         auto world_iter = state->GetWorld().Entities().begin();
427         auto world_end = state->GetWorld().Entities().end();
428
429         uint32_t count = 0;
430         pack.ReadEntityCount(count);
431
432         for (uint32_t i = 0; i < count; ++i) {
433                 uint32_t entity_id = 0;
434                 pack.ReadEntityID(entity_id, i);
435
436                 while (world_iter != world_end && world_iter->ID() < entity_id) {
437                         ++world_iter;
438                 }
439                 if (world_iter == world_end) {
440                         // nothing can be done from here
441                         return;
442                 }
443                 if (world_iter->ID() == entity_id) {
444                         if (UpdateEntity(entity_id, pack.Seq())) {
445                                 pack.ReadEntityState(world_iter->GetState(), i);
446                         }
447                 }
448         }
449 }
450
451 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
452         auto entry = update_status.find(entity_id);
453         if (entry == update_status.end()) {
454                 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
455                 return true;
456         }
457
458         int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
459         int time_diff = update_timer.Elapsed() - entry->second.last_update;
460         entry->second.last_update = update_timer.Elapsed();
461
462         if (pack_diff > 0 || time_diff > 1500) {
463                 entry->second.last_packet = seq;
464                 return true;
465         } else {
466                 return false;
467         }
468 }
469
470 void MasterState::ClearEntity(uint32_t entity_id) {
471         update_status.erase(entity_id);
472 }
473
474 void MasterState::On(const Packet::PlayerCorrection &pack) {
475         if (!state) {
476                 cout << "got player correction without a player :S" << endl;
477                 Quit();
478                 return;
479         }
480         uint16_t pack_seq;
481         EntityState corrected_state;
482         pack.ReadPacketSeq(pack_seq);
483         pack.ReadPlayerState(corrected_state);
484         state->MergePlayerCorrection(pack_seq, corrected_state);
485 }
486
487 void MasterState::On(const Packet::ChunkBegin &pack) {
488         if (!state) {
489                 cout << "got chunk data, but the world has not been created yet" << endl;
490                 cout << "great, this will totally screw up everything :(" << endl;
491                 return;
492         }
493         state->GetChunkReceiver().Handle(pack);
494 }
495
496 void MasterState::On(const Packet::ChunkData &pack) {
497         if (!state) {
498                 cout << "got chunk data, but the world has not been created yet" << endl;
499                 cout << "great, this will totally screw up everything :(" << endl;
500                 return;
501         }
502         state->GetChunkReceiver().Handle(pack);
503 }
504
505 void MasterState::On(const Packet::BlockUpdate &pack) {
506         if (!state) {
507                 cout << "received block update, but the world has not been created yet" << endl;
508                 return;
509         }
510         state->Handle(pack);
511 }
512
513 }
514 }