1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
5 #include "../app/Environment.hpp"
6 #include "../app/init.hpp"
7 #include "../geometry/distance.hpp"
8 #include "../model/Model.hpp"
9 #include "../io/WorldSave.hpp"
10 #include "../world/ChunkIndex.hpp"
11 #include "../world/ChunkStore.hpp"
14 #include <glm/gtx/io.hpp>
22 InitialState::InitialState(MasterState &master)
25 message.Position(glm::vec3(0.0f), Gravity::CENTER);
26 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
29 void InitialState::OnEnter() {
33 void InitialState::Handle(const SDL_Event &evt) {
34 if (evt.type == SDL_QUIT) {
39 void InitialState::Update(int dt) {
43 void InitialState::Render(Viewport &viewport) {
44 message.Render(viewport);
48 // TODO: this clutter is a giant mess
49 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
53 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
54 , world(res.block_types, master.GetWorldConf())
55 , player(*world.AddPlayer(master.GetConfig().player.name, player_id))
56 , hud(master.GetEnv(), master.GetConfig(), player)
57 , manip(master.GetEnv().audio, sounds, player.GetEntity())
58 , input(world, player, master.GetClient())
59 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
60 , chunk_receiver(master.GetClient(), world.Chunks(), save)
61 , chunk_renderer(player.GetChunks())
64 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
66 , chat(master.GetEnv(), *this, *this)
68 , packets_skipped(0) {
70 save.Write(master.GetWorldConf());
72 res.Load(master.GetEnv().loader, "default");
73 if (res.models.size() < 1) {
74 throw std::runtime_error("need at least one model to run");
76 res.models[0].Instantiate(player.GetEntity().GetModel());
77 sounds.Load(master.GetEnv().loader, res.snd_index);
78 interface.SetInventorySlots(res.block_types.size() - 1);
79 chunk_renderer.LoadTextures(master.GetEnv().loader, res.tex_index);
80 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
83 if (save.Exists(player)) {
88 void InteractiveState::OnResume() {
92 void InteractiveState::OnPause() {
96 void InteractiveState::OnFocus() {
97 if (master.GetConfig().input.mouse) {
98 master.GetEnv().window.GrabMouse();
103 void InteractiveState::OnBlur() {
104 master.GetEnv().window.ReleaseMouse();
108 void InteractiveState::Handle(const SDL_Event &event) {
109 switch (event.type) {
111 // TODO: move to interface
112 if (event.key.keysym.sym == SDLK_RETURN) {
114 master.GetEnv().state.Push(&chat);
115 hud.KeepMessages(true);
116 } else if (event.key.keysym.sym == SDLK_SLASH) {
118 master.GetEnv().state.Push(&chat);
119 hud.KeepMessages(true);
121 interface.HandlePress(event.key);
125 interface.HandleRelease(event.key);
127 case SDL_MOUSEBUTTONDOWN:
128 interface.HandlePress(event.button);
130 case SDL_MOUSEBUTTONUP:
131 interface.HandleRelease(event.button);
133 case SDL_MOUSEMOTION:
134 interface.Handle(event.motion);
137 interface.Handle(event.wheel);
147 void InteractiveState::Update(int dt) {
148 loop_timer.Update(dt);
149 stat_timer.Update(dt);
151 chunk_receiver.Update(dt);
154 while (loop_timer.HitOnce()) {
155 world.Update(loop_timer.Interval());
156 world_dt += loop_timer.Interval();
157 loop_timer.PopIteration();
159 chunk_renderer.Update(dt);
161 if (input.BlockFocus()) {
162 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
163 } else if (input.EntityFocus()) {
164 hud.FocusEntity(*input.EntityFocus().entity);
169 if (input.UpdateImportant() || packets_skipped >= master.NetStat().SuggestedPacketSkip()) {
170 input.PushPlayerUpdate(time_skipped + world_dt);
174 time_skipped += world_dt;
178 hud.Display(res.block_types[player.GetInventorySlot() + 1]);
179 if (stat_timer.Hit()) {
180 hud.UpdateNetStats(master.NetStat());
184 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
185 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
186 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
187 master.GetEnv().audio.Position(player.GetEntity().Position());
188 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
189 master.GetEnv().audio.Orientation(dir, up);
192 void InteractiveState::Render(Viewport &viewport) {
193 viewport.WorldPosition(player.GetEntity().ViewTransform(player.GetEntity().ChunkCoords()));
194 if (master.GetConfig().video.world) {
195 chunk_renderer.Render(viewport);
196 world.Render(viewport);
197 if (master.GetConfig().video.debug) {
198 world.RenderDebug(viewport);
200 sky.Render(viewport);
202 hud.Render(viewport);
205 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
207 pack.ReadEntityID(entity_id);
208 Entity &entity = world.ForceAddEntity(entity_id);
209 UpdateEntity(entity_id, pack.Seq());
210 pack.ReadEntity(entity);
212 pack.ReadModelID(model_id);
213 if (model_id > 0 && model_id <= res.models.size()) {
214 res.models.Get(model_id).Instantiate(entity.GetModel());
218 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
220 pack.ReadEntityID(entity_id);
221 ClearEntity(entity_id);
222 for (Entity &entity : world.Entities()) {
223 if (entity.ID() == entity_id) {
230 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
231 auto world_iter = world.Entities().begin();
232 auto world_end = world.Entities().end();
236 pack.ReadEntityCount(count);
237 pack.ReadChunkBase(base);
240 for (uint32_t i = 0; i < count; ++i) {
241 uint32_t entity_id = 0;
242 pack.ReadEntityID(entity_id, i);
244 while (world_iter != world_end && world_iter->ID() < entity_id) {
247 if (world_iter == world_end) {
248 // nothing can be done from here
251 if (world_iter->ID() == entity_id) {
252 if (UpdateEntity(entity_id, pack.Seq())) {
253 pack.ReadEntityState(state, base, i);
254 world_iter->SetState(state);
260 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
261 auto entry = update_status.find(entity_id);
262 if (entry == update_status.end()) {
263 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
267 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
268 int time_diff = loop_timer.Elapsed() - entry->second.last_update;
269 entry->second.last_update = loop_timer.Elapsed();
271 if (pack_diff > 0 || time_diff > 1500) {
272 entry->second.last_packet = seq;
279 void InteractiveState::ClearEntity(uint32_t entity_id) {
280 update_status.erase(entity_id);
283 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
285 EntityState corrected_state;
286 pack.ReadPacketSeq(pack_seq);
287 pack.ReadPlayerState(corrected_state);
288 input.MergePlayerCorrection(pack_seq, corrected_state);
291 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
293 pack.ReadChunkCoords(pos);
294 Chunk *chunk = player.GetChunks().Get(pos);
296 // this change doesn't concern us
300 pack.ReadBlockCount(count);
301 for (uint32_t i = 0; i < count; ++i) {
304 pack.ReadIndex(index, i);
305 pack.ReadBlock(block, i);
306 if (index < Chunk::size && block.type < res.block_types.size()) {
307 manip.SetBlock(*chunk, index, block);
312 void InteractiveState::Handle(const Packet::Message &pack) {
314 pack.ReadMessage(msg);
315 hud.PostMessage(msg);
318 void InteractiveState::SetAudio(bool b) {
319 master.GetConfig().audio.enabled = b;
321 hud.PostMessage("Audio enabled");
323 hud.PostMessage("Audio disabled");
327 void InteractiveState::SetVideo(bool b) {
328 master.GetConfig().video.world = b;
330 hud.PostMessage("World rendering enabled");
332 hud.PostMessage("World rendering disabled");
336 void InteractiveState::SetHUD(bool b) {
337 master.GetConfig().video.hud = b;
339 hud.PostMessage("HUD rendering enabled");
341 hud.PostMessage("HUD rendering disabled");
345 void InteractiveState::SetDebug(bool b) {
346 master.GetConfig().video.debug = b;
348 hud.PostMessage("Debug rendering enabled");
350 hud.PostMessage("Debug rendering disabled");
354 void InteractiveState::NextCamera() {
355 if (iszero(master.GetEnv().viewport.CameraOffset())) {
356 master.GetEnv().viewport.OffsetCamera(glm::vec3(0.0f, 0.0f, -5.0f));
358 master.GetEnv().viewport.OffsetCamera(glm::vec3(0.0f, 0.0f, 0.0f));
362 void InteractiveState::Exit() {
367 void InteractiveState::OnLineSubmit(const string &line) {
369 master.GetClient().SendMessage(1, 0, line);
374 MasterState::MasterState(
377 const World::Config &wc)
385 client.GetConnection().SetHandler(this);
388 void MasterState::Quit() {
389 if (!client.GetConnection().Closed()) {
392 env.state.PopUntil(this);
396 void MasterState::OnEnter() {
397 login_packet = client.SendLogin(config.player.name);
398 env.state.Push(&init_state);
402 void MasterState::Handle(const SDL_Event &event) {
407 void MasterState::Update(int dt) {
413 void MasterState::Render(Viewport &) {
418 void MasterState::OnPacketLost(uint16_t id) {
419 if (id == login_packet) {
420 login_packet = client.SendLogin(config.player.name);
424 void MasterState::OnTimeout() {
425 if (client.GetConnection().Closed()) {
427 env.ShowMessage("connection timed out");
431 void MasterState::On(const Packet::Join &pack) {
432 pack.ReadWorldName(world_conf.name);
436 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
439 cout << "joined game \"" << world_conf.name << '"' << endl;
440 // server received our login
445 pack.ReadPlayerID(player_id);
446 state.reset(new InteractiveState(*this, player_id));
448 EntityState player_state;
449 pack.ReadPlayerState(player_state);
450 state->GetPlayer().GetEntity().SetState(player_state);
452 env.state.PopAfter(this);
453 env.state.Push(state.get());
456 void MasterState::On(const Packet::Part &pack) {
460 env.ShowMessage("kicked by server");
463 env.ShowMessage("login refused by server");
467 void MasterState::On(const Packet::SpawnEntity &pack) {
469 cout << "got entity spawn before world was created" << endl;
475 void MasterState::On(const Packet::DespawnEntity &pack) {
477 cout << "got entity despawn before world was created" << endl;
483 void MasterState::On(const Packet::EntityUpdate &pack) {
485 cout << "got entity update before world was created" << endl;
491 void MasterState::On(const Packet::PlayerCorrection &pack) {
493 cout << "got player correction without a player :S" << endl;
499 void MasterState::On(const Packet::ChunkBegin &pack) {
501 cout << "got chunk data, but the world has not been created yet" << endl;
502 cout << "great, this will totally screw up everything :(" << endl;
505 state->GetChunkReceiver().Handle(pack);
508 void MasterState::On(const Packet::ChunkData &pack) {
510 cout << "got chunk data, but the world has not been created yet" << endl;
511 cout << "great, this will totally screw up everything :(" << endl;
514 state->GetChunkReceiver().Handle(pack);
517 void MasterState::On(const Packet::BlockUpdate &pack) {
519 cout << "received block update, but the world has not been created yet" << endl;
525 void MasterState::On(const Packet::Message &pack) {
530 pack.ReadMessage(msg);
531 cout << "got message before interface was created: " << msg << endl;