1 #include "InitialState.hpp"
2 #include "InteractiveState.hpp"
3 #include "MasterState.hpp"
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"
13 #include <glm/gtx/io.hpp>
21 InitialState::InitialState(MasterState &master)
24 message.Position(glm::vec3(0.0f), Gravity::CENTER);
25 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
28 void InitialState::OnEnter() {
32 void InitialState::Handle(const SDL_Event &evt) {
33 if (evt.type == SDL_QUIT) {
38 void InitialState::Update(int dt) {
42 void InitialState::Render(Viewport &viewport) {
43 message.Render(viewport);
47 // TODO: this clutter is a giant mess
48 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
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, player_id))
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())
62 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
64 , chat(master.GetEnv(), *this, *this) {
66 save.Write(master.GetWorldConf());
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");
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);
78 if (save.Exists(player)) {
83 void InteractiveState::OnResume() {
87 void InteractiveState::OnPause() {
91 void InteractiveState::OnFocus() {
92 if (master.GetConfig().input.mouse) {
93 master.GetEnv().window.GrabMouse();
98 void InteractiveState::OnBlur() {
99 master.GetEnv().window.ReleaseMouse();
103 void InteractiveState::Handle(const SDL_Event &event) {
104 switch (event.type) {
106 // TODO: move to interface
107 if (event.key.keysym.sym == SDLK_RETURN) {
109 master.GetEnv().state.Push(&chat);
110 hud.KeepMessages(true);
111 } else if (event.key.keysym.sym == SDLK_SLASH) {
113 master.GetEnv().state.Push(&chat);
114 hud.KeepMessages(true);
116 interface.HandlePress(event.key);
120 interface.HandleRelease(event.key);
122 case SDL_MOUSEBUTTONDOWN:
123 interface.HandlePress(event.button);
125 case SDL_MOUSEBUTTONUP:
126 interface.HandleRelease(event.button);
128 case SDL_MOUSEMOTION:
129 interface.Handle(event.motion);
132 interface.Handle(event.wheel);
142 void InteractiveState::Update(int dt) {
143 loop_timer.Update(dt);
145 chunk_receiver.Update(dt);
148 while (loop_timer.HitOnce()) {
149 world.Update(loop_timer.Interval());
150 world_dt += loop_timer.Interval();
151 loop_timer.PopIteration();
153 chunk_renderer.Update(dt);
155 if (input.BlockFocus()) {
156 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
157 } else if (input.EntityFocus()) {
158 hud.FocusEntity(*input.EntityFocus().entity);
163 input.PushPlayerUpdate(world_dt);
165 hud.Display(res.block_types[player.GetInventorySlot() + 1]);
168 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
169 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
170 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
171 master.GetEnv().audio.Position(player.GetEntity().Position());
172 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
173 master.GetEnv().audio.Orientation(dir, up);
176 void InteractiveState::Render(Viewport &viewport) {
177 viewport.WorldPosition(
178 player.GetEntity().Transform(player.GetEntity().ChunkCoords())
179 * player.GetEntity().GetModel().EyesTransform());
180 if (master.GetConfig().video.world) {
181 chunk_renderer.Render(viewport);
182 world.Render(viewport);
183 sky.Render(viewport);
185 hud.Render(viewport);
188 void InteractiveState::Handle(const Packet::SpawnEntity &pack) {
190 pack.ReadEntityID(entity_id);
191 Entity &entity = world.ForceAddEntity(entity_id);
192 UpdateEntity(entity_id, pack.Seq());
193 pack.ReadEntity(entity);
195 pack.ReadModelID(model_id);
196 if (model_id > 0 && model_id <= res.models.size()) {
197 res.models.Get(model_id).Instantiate(entity.GetModel());
199 cout << "spawned entity #" << entity_id << " (" << entity.Name()
200 << ") at " << entity.AbsolutePosition() << endl;
203 void InteractiveState::Handle(const Packet::DespawnEntity &pack) {
205 pack.ReadEntityID(entity_id);
206 ClearEntity(entity_id);
207 for (Entity &entity : world.Entities()) {
208 if (entity.ID() == entity_id) {
210 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
216 void InteractiveState::Handle(const Packet::EntityUpdate &pack) {
217 auto world_iter = world.Entities().begin();
218 auto world_end = world.Entities().end();
222 pack.ReadEntityCount(count);
223 pack.ReadChunkBase(base);
226 for (uint32_t i = 0; i < count; ++i) {
227 uint32_t entity_id = 0;
228 pack.ReadEntityID(entity_id, i);
230 while (world_iter != world_end && world_iter->ID() < entity_id) {
233 if (world_iter == world_end) {
234 // nothing can be done from here
237 if (world_iter->ID() == entity_id) {
238 if (UpdateEntity(entity_id, pack.Seq())) {
239 pack.ReadEntityState(state, base, i);
240 world_iter->SetState(state);
246 bool InteractiveState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
247 auto entry = update_status.find(entity_id);
248 if (entry == update_status.end()) {
249 update_status.emplace(entity_id, UpdateStatus{ seq, loop_timer.Elapsed() });
253 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
254 int time_diff = loop_timer.Elapsed() - entry->second.last_update;
255 entry->second.last_update = loop_timer.Elapsed();
257 if (pack_diff > 0 || time_diff > 1500) {
258 entry->second.last_packet = seq;
265 void InteractiveState::ClearEntity(uint32_t entity_id) {
266 update_status.erase(entity_id);
269 void InteractiveState::Handle(const Packet::PlayerCorrection &pack) {
271 EntityState corrected_state;
272 pack.ReadPacketSeq(pack_seq);
273 pack.ReadPlayerState(corrected_state);
274 input.MergePlayerCorrection(pack_seq, corrected_state);
277 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
279 pack.ReadChunkCoords(pos);
280 Chunk *chunk = player.GetChunks().Get(pos);
282 // this change doesn't concern us
286 pack.ReadBlockCount(count);
287 for (uint32_t i = 0; i < count; ++i) {
290 pack.ReadIndex(index, i);
291 pack.ReadBlock(block, i);
292 if (index < Chunk::size && block.type < res.block_types.size()) {
293 manip.SetBlock(*chunk, index, block);
298 void InteractiveState::Handle(const Packet::Message &pack) {
300 pack.ReadMessage(msg);
301 hud.PostMessage(msg);
304 void InteractiveState::SetAudio(bool b) {
305 master.GetConfig().audio.enabled = b;
307 hud.PostMessage("Audio enabled");
309 hud.PostMessage("Audio disabled");
313 void InteractiveState::SetVideo(bool b) {
314 master.GetConfig().video.world = b;
316 hud.PostMessage("World rendering enabled");
318 hud.PostMessage("World rendering disabled");
322 void InteractiveState::SetHUD(bool b) {
323 master.GetConfig().video.hud = b;
325 hud.PostMessage("HUD rendering enabled");
327 hud.PostMessage("HUD rendering disabled");
331 void InteractiveState::SetDebug(bool b) {
332 master.GetConfig().video.debug = b;
334 hud.PostMessage("Debug rendering enabled");
336 hud.PostMessage("Debug rendering disabled");
340 void InteractiveState::Exit() {
345 void InteractiveState::OnLineSubmit(const string &line) {
347 master.GetClient().SendMessage(1, 0, line);
352 MasterState::MasterState(
355 const World::Config &wc)
363 client.GetConnection().SetHandler(this);
366 void MasterState::Quit() {
367 if (!client.GetConnection().Closed()) {
370 env.state.PopUntil(this);
374 void MasterState::OnEnter() {
375 login_packet = client.SendLogin(config.player.name);
376 env.state.Push(&init_state);
380 void MasterState::Handle(const SDL_Event &event) {
385 void MasterState::Update(int dt) {
391 void MasterState::Render(Viewport &) {
396 void MasterState::OnPacketLost(uint16_t id) {
397 if (id == login_packet) {
398 login_packet = client.SendLogin(config.player.name);
402 void MasterState::OnTimeout() {
403 if (client.GetConnection().Closed()) {
405 env.ShowMessage("connection timed out");
409 void MasterState::On(const Packet::Join &pack) {
410 pack.ReadWorldName(world_conf.name);
414 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
417 cout << "joined game \"" << world_conf.name << '"' << endl;
418 // server received our login
423 pack.ReadPlayerID(player_id);
424 state.reset(new InteractiveState(*this, player_id));
426 EntityState player_state;
427 pack.ReadPlayerState(player_state);
428 state->GetPlayer().GetEntity().SetState(player_state);
430 env.state.PopAfter(this);
431 env.state.Push(state.get());
434 void MasterState::On(const Packet::Part &pack) {
438 env.ShowMessage("kicked by server");
441 env.ShowMessage("login refused by server");
445 void MasterState::On(const Packet::SpawnEntity &pack) {
447 cout << "got entity spawn before world was created" << endl;
453 void MasterState::On(const Packet::DespawnEntity &pack) {
455 cout << "got entity despawn before world was created" << endl;
461 void MasterState::On(const Packet::EntityUpdate &pack) {
463 cout << "got entity update before world was created" << endl;
469 void MasterState::On(const Packet::PlayerCorrection &pack) {
471 cout << "got player correction without a player :S" << endl;
477 void MasterState::On(const Packet::ChunkBegin &pack) {
479 cout << "got chunk data, but the world has not been created yet" << endl;
480 cout << "great, this will totally screw up everything :(" << endl;
483 state->GetChunkReceiver().Handle(pack);
486 void MasterState::On(const Packet::ChunkData &pack) {
488 cout << "got chunk data, but the world has not been created yet" << endl;
489 cout << "great, this will totally screw up everything :(" << endl;
492 state->GetChunkReceiver().Handle(pack);
495 void MasterState::On(const Packet::BlockUpdate &pack) {
497 cout << "received block update, but the world has not been created yet" << endl;
503 void MasterState::On(const Packet::Message &pack) {
508 pack.ReadMessage(msg);
509 cout << "got message before interface was created: " << msg << endl;