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/ChunkStore.hpp"
14 #include <glm/gtx/io.hpp>
22 ChunkRequester::ChunkRequester(
31 void ChunkRequester::Update(int dt) {
32 // check if there's chunks waiting to be loaded
35 // store a few chunks as well
36 constexpr int max_save = 10;
38 for (Chunk &chunk : store) {
39 if (chunk.ShouldUpdateSave()) {
42 if (saved >= max_save) {
49 int ChunkRequester::ToLoad() const noexcept {
50 return store.EstimateMissing();
53 void ChunkRequester::LoadOne() {
54 if (!store.HasMissing()) return;
56 Chunk::Pos pos = store.NextMissing();
57 Chunk *chunk = store.Allocate(pos);
59 // chunk store corrupted?
63 if (save.Exists(pos)) {
65 // TODO: request chunk from server with cache tag
67 // TODO: request chunk from server
71 void ChunkRequester::LoadN(std::size_t n) {
72 std::size_t end = std::min(n, std::size_t(ToLoad()));
73 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
79 InitialState::InitialState(MasterState &master)
82 message.Position(glm::vec3(0.0f), Gravity::CENTER);
83 message.Set(master.GetEnv().assets.large_ui_font, "logging in");
86 void InitialState::OnEnter() {
90 void InitialState::Handle(const SDL_Event &evt) {
91 if (evt.type == SDL_QUIT) {
96 void InitialState::Update(int dt) {
100 void InitialState::Render(Viewport &viewport) {
101 message.Render(viewport);
105 // TODO: this clutter is a giant mess
106 InteractiveState::InteractiveState(MasterState &master, uint32_t player_id)
109 , save(master.GetEnv().config.GetWorldPath(master.GetWorldConf().name, master.GetConfig().net.host))
110 , world(block_types, master.GetWorldConf())
111 , player(*world.AddPlayer(master.GetConfig().player.name))
112 , hud(master.GetEnv(), master.GetConfig(), player)
113 , manip(master.GetEnv(), player.GetEntity())
114 , input(world, player, manip)
115 , interface(master.GetConfig(), master.GetEnv().keymap, input, *this)
116 // TODO: looks like chunk requester and receiver can and should be merged
117 , chunk_requester(world.Chunks(), save)
118 , chunk_receiver(world.Chunks())
119 , chunk_renderer(player.GetChunks())
122 , 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 chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
130 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
135 void InteractiveState::OnEnter() {
136 master.GetEnv().window.GrabMouse();
139 void InteractiveState::Handle(const SDL_Event &event) {
140 switch (event.type) {
142 interface.HandlePress(event.key);
145 interface.HandleRelease(event.key);
147 case SDL_MOUSEBUTTONDOWN:
148 interface.HandlePress(event.button);
150 case SDL_MOUSEBUTTONUP:
151 interface.HandleRelease(event.button);
153 case SDL_MOUSEMOTION:
154 interface.Handle(event.motion);
157 interface.Handle(event.wheel);
167 void InteractiveState::Update(int dt) {
169 if (input.BlockFocus()) {
170 hud.FocusBlock(input.BlockFocus().GetChunk(), input.BlockFocus().block);
171 } else if (input.EntityFocus()) {
172 hud.FocusEntity(*input.EntityFocus().entity);
174 hud.Display(block_types[player.GetInventorySlot() + 1]);
175 loop_timer.Update(dt);
177 chunk_receiver.Update(dt);
178 chunk_requester.Update(dt);
182 while (loop_timer.HitOnce()) {
183 world.Update(loop_timer.Interval());
184 world_dt += loop_timer.Interval();
185 loop_timer.PopIteration();
187 chunk_renderer.Update(dt);
190 PushPlayerUpdate(player.GetEntity(), world_dt);
193 glm::mat4 trans = player.GetEntity().Transform(player.GetEntity().ChunkCoords());
194 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
195 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
196 master.GetEnv().audio.Position(player.GetEntity().Position());
197 master.GetEnv().audio.Velocity(player.GetEntity().Velocity());
198 master.GetEnv().audio.Orientation(dir, up);
201 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
202 std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
203 if (player_hist.size() < 16) {
204 player_hist.emplace_back(player.GetState(), dt, packet);
206 auto entry = player_hist.begin();
207 entry->state = player.GetState();
209 entry->packet = packet;
210 player_hist.splice(player_hist.end(), player_hist, entry);
214 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
215 if (player_hist.empty()) return;
217 auto entry = player_hist.begin();
218 auto end = player_hist.end();
220 // we may have received an older packet
221 int pack_diff = int16_t(seq) - int16_t(entry->packet);
223 // indeed we have, just ignore it
227 // drop anything older than the fix
228 while (entry != end) {
229 pack_diff = int16_t(seq) - int16_t(entry->packet);
231 entry = player_hist.erase(entry);
237 EntityState replay_state(corrected_state);
238 EntityState &player_state = player.GetEntity().GetState();
241 entry->state.chunk_pos = replay_state.chunk_pos;
242 entry->state.block_pos = replay_state.block_pos;
246 while (entry != end) {
247 replay_state.velocity = entry->state.velocity;
248 replay_state.Update(entry->delta_t);
249 entry->state.chunk_pos = replay_state.chunk_pos;
250 entry->state.block_pos = replay_state.block_pos;
254 glm::vec3 displacement(replay_state.Diff(player_state));
255 const float disp_squared = dot(displacement, displacement);
257 if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
261 // if offset > 10cm, warp the player
262 // otherwise, move at most 1cm per frame towards
263 // the fixed position (160ms, so shouldn't be too noticeable)
264 constexpr float warp_thresh = 0.01f; // (1/10)^2
265 constexpr float max_disp = 0.0001f; // (1/100)^2
267 if (disp_squared > warp_thresh) {
268 player_state.chunk_pos = replay_state.chunk_pos;
269 player_state.block_pos = replay_state.block_pos;
270 } else if (disp_squared < max_disp) {
271 player_state.block_pos += displacement;
273 displacement *= 0.01f / sqrt(disp_squared);
274 player_state.block_pos += displacement;
278 void InteractiveState::Render(Viewport &viewport) {
279 viewport.WorldPosition(player.GetEntity().Transform(player.GetEntity().ChunkCoords()));
280 if (master.GetConfig().video.world) {
281 chunk_renderer.Render(viewport);
282 world.Render(viewport);
283 sky.Render(viewport);
285 hud.Render(viewport);
288 void InteractiveState::SetAudio(bool b) {
289 master.GetConfig().audio.enabled = b;
291 hud.PostMessage("Audio enabled");
293 hud.PostMessage("Audio disabled");
297 void InteractiveState::SetVideo(bool b) {
298 master.GetConfig().video.world = b;
300 hud.PostMessage("World rendering enabled");
302 hud.PostMessage("World rendering disabled");
306 void InteractiveState::SetHUD(bool b) {
307 master.GetConfig().video.hud = b;
309 hud.PostMessage("HUD rendering enabled");
311 hud.PostMessage("HUD rendering disabled");
315 void InteractiveState::SetDebug(bool b) {
316 master.GetConfig().video.debug = b;
318 hud.PostMessage("Debug rendering enabled");
320 hud.PostMessage("Debug rendering disabled");
324 void InteractiveState::Exit() {
329 MasterState::MasterState(
332 const World::Config &wc)
342 client.GetConnection().SetHandler(this);
343 update_timer.Start();
346 void MasterState::Quit() {
347 if (!client.GetConnection().Closed()) {
350 env.state.PopUntil(this);
354 void MasterState::OnEnter() {
355 login_packet = client.SendLogin(config.player.name);
356 env.state.Push(&init_state);
360 void MasterState::Handle(const SDL_Event &event) {
365 void MasterState::Update(int dt) {
366 update_timer.Update(dt);
372 void MasterState::Render(Viewport &) {
377 void MasterState::OnPacketLost(uint16_t id) {
378 if (id == login_packet) {
379 login_packet = client.SendLogin(config.player.name);
383 void MasterState::OnTimeout() {
384 if (client.GetConnection().Closed()) {
385 // TODO: push disconnected message
386 cout << "connection timed out" << endl;
391 void MasterState::On(const Packet::Join &pack) {
392 pack.ReadWorldName(world_conf.name);
396 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
399 cout << "joined game \"" << world_conf.name << '"' << endl;
400 // server received our login
405 pack.ReadPlayerID(player_id);
406 state.reset(new InteractiveState(*this, player_id));
408 pack.ReadPlayerState(state->GetPlayer().GetEntity().GetState());
410 env.state.PopAfter(this);
411 env.state.Push(state.get());
414 void MasterState::On(const Packet::Part &pack) {
417 cout << "kicked by server" << endl;
420 cout << "login refused by server" << endl;
425 void MasterState::On(const Packet::SpawnEntity &pack) {
427 cout << "got entity spawn before world was created" << endl;
432 pack.ReadEntityID(entity_id);
433 Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
434 UpdateEntity(entity_id, pack.Seq());
435 pack.ReadEntity(entity);
437 pack.ReadSkeletonID(skel_id);
438 CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
440 skel->Instantiate(entity.GetModel());
442 cout << "spawned entity #" << entity_id << " (" << entity.Name()
443 << ") at " << entity.AbsolutePosition() << endl;
446 void MasterState::On(const Packet::DespawnEntity &pack) {
448 cout << "got entity despawn before world was created" << endl;
453 pack.ReadEntityID(entity_id);
454 ClearEntity(entity_id);
455 for (Entity &entity : state->GetWorld().Entities()) {
456 if (entity.ID() == entity_id) {
458 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
464 void MasterState::On(const Packet::EntityUpdate &pack) {
466 cout << "got entity update before world was created" << endl;
471 auto world_iter = state->GetWorld().Entities().begin();
472 auto world_end = state->GetWorld().Entities().end();
475 pack.ReadEntityCount(count);
477 for (uint32_t i = 0; i < count; ++i) {
478 uint32_t entity_id = 0;
479 pack.ReadEntityID(entity_id, i);
481 while (world_iter != world_end && world_iter->ID() < entity_id) {
484 if (world_iter == world_end) {
485 // nothing can be done from here
488 if (world_iter->ID() == entity_id) {
489 if (UpdateEntity(entity_id, pack.Seq())) {
490 pack.ReadEntityState(world_iter->GetState(), i);
496 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
497 auto entry = update_status.find(entity_id);
498 if (entry == update_status.end()) {
499 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
503 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
504 int time_diff = update_timer.Elapsed() - entry->second.last_update;
505 entry->second.last_update = update_timer.Elapsed();
507 if (pack_diff > 0 || time_diff > 1500) {
508 entry->second.last_packet = seq;
515 void MasterState::ClearEntity(uint32_t entity_id) {
516 update_status.erase(entity_id);
519 void MasterState::On(const Packet::PlayerCorrection &pack) {
521 cout << "got player correction without a player :S" << endl;
526 EntityState corrected_state;
527 pack.ReadPacketSeq(pack_seq);
528 pack.ReadPlayerState(corrected_state);
529 state->MergePlayerCorrection(pack_seq, corrected_state);
532 void MasterState::On(const Packet::ChunkBegin &pack) {
534 cout << "got chunk data, but the world has not been created yet" << endl;
535 cout << "great, this will totally screw up everything :(" << endl;
538 state->GetChunkReceiver().Handle(pack);
541 void MasterState::On(const Packet::ChunkData &pack) {
543 cout << "got chunk data, but the world has not been created yet" << endl;
544 cout << "great, this will totally screw up everything :(" << endl;
547 state->GetChunkReceiver().Handle(pack);