1 #include "ChunkRequester.hpp"
2 #include "InitialState.hpp"
3 #include "InteractiveState.hpp"
4 #include "MasterState.hpp"
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"
15 #include <glm/gtx/io.hpp>
23 ChunkRequester::ChunkRequester(
32 void ChunkRequester::Update(int dt) {
33 // check if there's chunks waiting to be loaded
36 // store a few chunks as well
37 constexpr int max_save = 10;
39 for (Chunk &chunk : store) {
40 if (chunk.ShouldUpdateSave()) {
43 if (saved >= max_save) {
50 int ChunkRequester::ToLoad() const noexcept {
51 return store.EstimateMissing();
54 void ChunkRequester::LoadOne() {
55 if (!store.HasMissing()) return;
57 Chunk::Pos pos = store.NextMissing();
58 Chunk *chunk = store.Allocate(pos);
60 // chunk store corrupted?
64 if (save.Exists(pos)) {
66 // TODO: request chunk from server with cache tag
68 // TODO: request chunk from server
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) {
80 InitialState::InitialState(MasterState &master)
83 message.Position(glm::vec3(0.0f), Gravity::CENTER);
84 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
87 void InitialState::OnEnter() {
91 void InitialState::Handle(const SDL_Event &evt) {
92 if (evt.type == SDL_QUIT) {
97 void InitialState::Update(int dt) {
101 void InitialState::Render(Viewport &viewport) {
102 message.Render(viewport);
106 // TODO: this clutter is a giant mess
107 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
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())
123 , sky(master.GetEnv().loader.LoadCubeMap("skybox")) {
124 if (!save.Exists()) {
125 save.Write(master.GetWorldConf());
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);
134 if (save.Exists(player)) {
139 void InteractiveState::OnEnter() {
140 master.GetEnv().window.GrabMouse();
143 void InteractiveState::Handle(const SDL_Event &event) {
144 switch (event.type) {
146 interface.HandlePress(event.key);
149 interface.HandleRelease(event.key);
151 case SDL_MOUSEBUTTONDOWN:
152 interface.HandlePress(event.button);
154 case SDL_MOUSEBUTTONUP:
155 interface.HandleRelease(event.button);
157 case SDL_MOUSEMOTION:
158 interface.Handle(event.motion);
161 interface.Handle(event.wheel);
171 void InteractiveState::Update(int 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);
180 hud.Display(block_types[player.GetInventorySlot() + 1]);
181 loop_timer.Update(dt);
183 chunk_receiver.Update(dt);
184 chunk_requester.Update(dt);
188 while (loop_timer.HitOnce()) {
189 world.Update(loop_timer.Interval());
190 world_dt += loop_timer.Interval();
191 loop_timer.PopIteration();
193 chunk_renderer.Update(dt);
196 input.PushPlayerUpdate(world_dt);
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);
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);
214 hud.Render(viewport);
217 void InteractiveState::MergePlayerCorrection(std::uint16_t pack, const EntityState &state) {
218 input.MergePlayerCorrection(pack, state);
221 void InteractiveState::Handle(const Packet::BlockUpdate &pack) {
223 pack.ReadChunkCoords(pos);
224 Chunk *chunk = player.GetChunks().Get(pos);
226 // this change doesn't concern us
230 pack.ReadBlockCount(count);
231 for (uint32_t i = 0; i < count; ++i) {
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);
242 void InteractiveState::SetAudio(bool b) {
243 master.GetConfig().audio.enabled = b;
245 hud.PostMessage("Audio enabled");
247 hud.PostMessage("Audio disabled");
251 void InteractiveState::SetVideo(bool b) {
252 master.GetConfig().video.world = b;
254 hud.PostMessage("World rendering enabled");
256 hud.PostMessage("World rendering disabled");
260 void InteractiveState::SetHUD(bool b) {
261 master.GetConfig().video.hud = b;
263 hud.PostMessage("HUD rendering enabled");
265 hud.PostMessage("HUD rendering disabled");
269 void InteractiveState::SetDebug(bool b) {
270 master.GetConfig().video.debug = b;
272 hud.PostMessage("Debug rendering enabled");
274 hud.PostMessage("Debug rendering disabled");
278 void InteractiveState::Exit() {
284 MasterState::MasterState(
287 const World::Config &wc)
297 client.GetConnection().SetHandler(this);
298 update_timer.Start();
301 void MasterState::Quit() {
302 if (!client.GetConnection().Closed()) {
305 env.state.PopUntil(this);
309 void MasterState::OnEnter() {
310 login_packet = client.SendLogin(config.player.name);
311 env.state.Push(&init_state);
315 void MasterState::Handle(const SDL_Event &event) {
320 void MasterState::Update(int dt) {
321 update_timer.Update(dt);
327 void MasterState::Render(Viewport &) {
332 void MasterState::OnPacketLost(uint16_t id) {
333 if (id == login_packet) {
334 login_packet = client.SendLogin(config.player.name);
338 void MasterState::OnTimeout() {
339 if (client.GetConnection().Closed()) {
341 env.ShowMessage("connection timed out");
345 void MasterState::On(const Packet::Join &pack) {
346 pack.ReadWorldName(world_conf.name);
350 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
353 cout << "joined game \"" << world_conf.name << '"' << endl;
354 // server received our login
359 pack.ReadPlayerID(player_id);
360 state.reset(new InteractiveState(*this, player_id));
362 pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
364 env.state.PopAfter(this);
365 env.state.Push(state.get());
368 void MasterState::On(const Packet::Part &pack) {
372 env.ShowMessage("kicked by server");
375 env.ShowMessage("login refused by server");
379 void MasterState::On(const Packet::SpawnEntity &pack) {
381 cout << "got entity spawn before world was created" << endl;
385 pack.ReadEntityID(entity_id);
386 Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
387 UpdateEntity(entity_id, pack.Seq());
388 pack.ReadEntity(entity);
390 pack.ReadSkeletonID(skel_id);
391 CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
393 skel->Instantiate(entity.GetModel());
395 cout << "spawned entity #" << entity_id << " (" << entity.Name()
396 << ") at " << entity.AbsolutePosition() << endl;
399 void MasterState::On(const Packet::DespawnEntity &pack) {
401 cout << "got entity despawn before world was created" << endl;
405 pack.ReadEntityID(entity_id);
406 ClearEntity(entity_id);
407 for (Entity &entity : state->GetWorld().Entities()) {
408 if (entity.ID() == entity_id) {
410 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
416 void MasterState::On(const Packet::EntityUpdate &pack) {
418 cout << "got entity update before world was created" << endl;
422 auto world_iter = state->GetWorld().Entities().begin();
423 auto world_end = state->GetWorld().Entities().end();
426 pack.ReadEntityCount(count);
428 for (uint32_t i = 0; i < count; ++i) {
429 uint32_t entity_id = 0;
430 pack.ReadEntityID(entity_id, i);
432 while (world_iter != world_end && world_iter->ID() < entity_id) {
435 if (world_iter == world_end) {
436 // nothing can be done from here
439 if (world_iter->ID() == entity_id) {
440 if (UpdateEntity(entity_id, pack.Seq())) {
441 pack.ReadEntityState(world_iter->GetState(), i);
447 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
448 auto entry = update_status.find(entity_id);
449 if (entry == update_status.end()) {
450 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
454 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
455 int time_diff = update_timer.Elapsed() - entry->second.last_update;
456 entry->second.last_update = update_timer.Elapsed();
458 if (pack_diff > 0 || time_diff > 1500) {
459 entry->second.last_packet = seq;
466 void MasterState::ClearEntity(uint32_t entity_id) {
467 update_status.erase(entity_id);
470 void MasterState::On(const Packet::PlayerCorrection &pack) {
472 cout << "got player correction without a player :S" << endl;
476 EntityState corrected_state;
477 pack.ReadPacketSeq(pack_seq);
478 pack.ReadPlayerState(corrected_state);
479 state->MergePlayerCorrection(pack_seq, corrected_state);
482 void MasterState::On(const Packet::ChunkBegin &pack) {
484 cout << "got chunk data, but the world has not been created yet" << endl;
485 cout << "great, this will totally screw up everything :(" << endl;
488 state->GetChunkReceiver().Handle(pack);
491 void MasterState::On(const Packet::ChunkData &pack) {
493 cout << "got chunk data, but the world has not been created yet" << endl;
494 cout << "great, this will totally screw up everything :(" << endl;
497 state->GetChunkReceiver().Handle(pack);
500 void MasterState::On(const Packet::BlockUpdate &pack) {
502 cout << "received block update, but the world has not been created yet" << endl;