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