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.GetClientConf().host))
110 , world(block_types, master.GetWorldConf())
112 master.GetInterfaceConf(),
115 world.AddPlayer(master.GetInterfaceConf().player_name, player_id)
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(*interface.GetPlayer().chunks)
123 , sky(master.GetEnv().loader.LoadCubeMap("skybox"))
125 if (!save.Exists()) {
126 save.Write(master.GetWorldConf());
128 TextureIndex tex_index;
129 master.GetEnv().loader.LoadBlockTypes("default", block_types, tex_index);
130 chunk_renderer.LoadTextures(master.GetEnv().loader, tex_index);
131 chunk_renderer.FogDensity(master.GetWorldConf().fog_density);
133 // TODO: better solution for initializing HUD
134 interface.SelectNext();
138 void InteractiveState::OnEnter() {
139 master.GetEnv().window.GrabMouse();
142 void InteractiveState::Handle(const SDL_Event &event) {
143 switch (event.type) {
145 interface.HandlePress(event.key);
148 interface.HandleRelease(event.key);
150 case SDL_MOUSEBUTTONDOWN:
151 interface.HandlePress(event.button);
153 case SDL_MOUSEBUTTONUP:
154 interface.HandleRelease(event.button);
156 case SDL_MOUSEMOTION:
157 interface.Handle(event.motion);
160 interface.Handle(event.wheel);
170 void InteractiveState::Update(int dt) {
171 loop_timer.Update(dt);
173 chunk_receiver.Update(dt);
174 chunk_requester.Update(dt);
176 interface.Update(dt);
178 while (loop_timer.HitOnce()) {
179 world.Update(loop_timer.Interval());
180 world_dt += loop_timer.Interval();
181 loop_timer.PopIteration();
183 chunk_renderer.Update(dt);
185 Entity &player = *interface.GetPlayer().entity;
188 PushPlayerUpdate(player, world_dt);
191 glm::mat4 trans = player.Transform(player.ChunkCoords());
192 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
193 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
194 master.GetEnv().audio.Position(player.Position());
195 master.GetEnv().audio.Velocity(player.Velocity());
196 master.GetEnv().audio.Orientation(dir, up);
199 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
200 std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
201 if (player_hist.size() < 16) {
202 player_hist.emplace_back(player.GetState(), dt, packet);
204 auto entry = player_hist.begin();
205 entry->state = player.GetState();
207 entry->packet = packet;
208 player_hist.splice(player_hist.end(), player_hist, entry);
212 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
213 if (player_hist.empty()) return;
215 auto entry = player_hist.begin();
216 auto end = player_hist.end();
218 // we may have received an older packet
219 int pack_diff = int16_t(seq) - int16_t(entry->packet);
221 // indeed we have, just ignore it
225 // drop anything older than the fix
226 while (entry != end) {
227 pack_diff = int16_t(seq) - int16_t(entry->packet);
229 entry = player_hist.erase(entry);
235 EntityState replay_state(corrected_state);
236 EntityState &player_state = interface.GetPlayer().entity->GetState();
239 entry->state.chunk_pos = replay_state.chunk_pos;
240 entry->state.block_pos = replay_state.block_pos;
244 while (entry != end) {
245 replay_state.velocity = entry->state.velocity;
246 replay_state.Update(entry->delta_t);
247 entry->state.chunk_pos = replay_state.chunk_pos;
248 entry->state.block_pos = replay_state.block_pos;
252 glm::vec3 displacement(replay_state.Diff(player_state));
253 const float disp_squared = dot(displacement, displacement);
255 if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
259 // if offset > 10cm, warp the player
260 // otherwise, move at most 1cm per frame towards
261 // the fixed position (160ms, so shouldn't be too noticeable)
262 constexpr float warp_thresh = 0.01f; // (1/10)^2
263 constexpr float max_disp = 0.0001f; // (1/100)^2
265 if (disp_squared > warp_thresh) {
266 player_state.chunk_pos = replay_state.chunk_pos;
267 player_state.block_pos = replay_state.block_pos;
268 } else if (disp_squared < max_disp) {
269 player_state.block_pos += displacement;
271 displacement *= 0.01f / sqrt(disp_squared);
272 player_state.block_pos += displacement;
276 void InteractiveState::Render(Viewport &viewport) {
277 Entity &player = *interface.GetPlayer().entity;
278 viewport.WorldPosition(player.Transform(player.ChunkCoords()));
279 chunk_renderer.Render(viewport);
280 world.Render(viewport);
281 sky.Render(viewport);
282 interface.Render(viewport);
286 MasterState::MasterState(
288 const World::Config &wc,
289 const Interface::Config &ic,
290 const Client::Config &cc)
301 client.GetConnection().SetHandler(this);
302 update_timer.Start();
305 void MasterState::Quit() {
306 if (!client.GetConnection().Closed()) {
309 env.state.PopUntil(this);
313 void MasterState::OnEnter() {
314 login_packet = client.SendLogin(intf_conf.player_name);
315 env.state.Push(&init_state);
319 void MasterState::Handle(const SDL_Event &event) {
324 void MasterState::Update(int dt) {
325 update_timer.Update(dt);
331 void MasterState::Render(Viewport &) {
336 void MasterState::OnPacketLost(uint16_t id) {
337 if (id == login_packet) {
338 login_packet = client.SendLogin(intf_conf.player_name);
342 void MasterState::OnTimeout() {
343 if (client.GetConnection().Closed()) {
344 // TODO: push disconnected message
345 cout << "connection timed out" << endl;
350 void MasterState::On(const Packet::Join &pack) {
351 pack.ReadWorldName(world_conf.name);
355 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
358 cout << "joined game \"" << world_conf.name << '"' << endl;
359 // server received our login
364 pack.ReadPlayerID(player_id);
365 state.reset(new InteractiveState(*this, player_id));
367 pack.ReadPlayerState(state->GetInterface().GetPlayer().entity->GetState());
369 env.state.PopAfter(this);
370 env.state.Push(state.get());
373 void MasterState::On(const Packet::Part &pack) {
376 cout << "kicked by server" << endl;
379 cout << "login refused by server" << endl;
384 void MasterState::On(const Packet::SpawnEntity &pack) {
386 cout << "got entity spawn before world was created" << endl;
391 pack.ReadEntityID(entity_id);
392 Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
393 UpdateEntity(entity_id, pack.Seq());
394 pack.ReadEntity(entity);
396 pack.ReadSkeletonID(skel_id);
397 CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
399 skel->Instantiate(entity.GetModel());
401 cout << "spawned entity #" << entity_id << " (" << entity.Name()
402 << ") at " << entity.AbsolutePosition() << endl;
405 void MasterState::On(const Packet::DespawnEntity &pack) {
407 cout << "got entity despawn before world was created" << endl;
412 pack.ReadEntityID(entity_id);
413 ClearEntity(entity_id);
414 for (Entity &entity : state->GetWorld().Entities()) {
415 if (entity.ID() == entity_id) {
417 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
423 void MasterState::On(const Packet::EntityUpdate &pack) {
425 cout << "got entity update before world was created" << endl;
430 auto world_iter = state->GetWorld().Entities().begin();
431 auto world_end = state->GetWorld().Entities().end();
434 pack.ReadEntityCount(count);
436 for (uint32_t i = 0; i < count; ++i) {
437 uint32_t entity_id = 0;
438 pack.ReadEntityID(entity_id, i);
440 while (world_iter != world_end && world_iter->ID() < entity_id) {
443 if (world_iter == world_end) {
444 // nothing can be done from here
447 if (world_iter->ID() == entity_id) {
448 if (UpdateEntity(entity_id, pack.Seq())) {
449 pack.ReadEntityState(world_iter->GetState(), i);
455 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
456 auto entry = update_status.find(entity_id);
457 if (entry == update_status.end()) {
458 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
462 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
463 int time_diff = update_timer.Elapsed() - entry->second.last_update;
464 entry->second.last_update = update_timer.Elapsed();
466 if (pack_diff > 0 || time_diff > 1500) {
467 entry->second.last_packet = seq;
474 void MasterState::ClearEntity(uint32_t entity_id) {
475 update_status.erase(entity_id);
478 void MasterState::On(const Packet::PlayerCorrection &pack) {
480 cout << "got player correction without a player :S" << endl;
485 EntityState corrected_state;
486 pack.ReadPacketSeq(pack_seq);
487 pack.ReadPlayerState(corrected_state);
488 state->MergePlayerCorrection(pack_seq, corrected_state);
491 void MasterState::On(const Packet::ChunkBegin &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::ChunkData &pack) {
502 cout << "got chunk data, but the world has not been created yet" << endl;
503 cout << "great, this will totally screw up everything :(" << endl;
506 state->GetChunkReceiver().Handle(pack);