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)
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);
132 // TODO: better solution for initializing HUD
133 interface.SelectNext();
137 void InteractiveState::OnEnter() {
138 master.GetEnv().window.GrabMouse();
141 void InteractiveState::Handle(const SDL_Event &event) {
142 switch (event.type) {
144 interface.HandlePress(event.key);
147 interface.HandleRelease(event.key);
149 case SDL_MOUSEBUTTONDOWN:
150 interface.HandlePress(event.button);
152 case SDL_MOUSEBUTTONUP:
153 interface.HandleRelease(event.button);
155 case SDL_MOUSEMOTION:
156 interface.Handle(event.motion);
159 interface.Handle(event.wheel);
169 void InteractiveState::Update(int dt) {
170 loop_timer.Update(dt);
172 chunk_receiver.Update(dt);
173 chunk_requester.Update(dt);
175 interface.Update(dt);
177 while (loop_timer.HitOnce()) {
178 world.Update(loop_timer.Interval());
179 world_dt += loop_timer.Interval();
180 loop_timer.PopIteration();
182 chunk_renderer.Update(dt);
184 Entity &player = *interface.GetPlayer().entity;
187 PushPlayerUpdate(player, world_dt);
190 glm::mat4 trans = player.Transform(player.ChunkCoords());
191 glm::vec3 dir(trans * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
192 glm::vec3 up(trans * glm::vec4(0.0f, 1.0f, 0.0f, 0.0f));
193 master.GetEnv().audio.Position(player.Position());
194 master.GetEnv().audio.Velocity(player.Velocity());
195 master.GetEnv().audio.Orientation(dir, up);
198 void InteractiveState::PushPlayerUpdate(const Entity &player, int dt) {
199 std::uint16_t packet = master.GetClient().SendPlayerUpdate(player);
200 if (player_hist.size() < 16) {
201 player_hist.emplace_back(player.GetState(), dt, packet);
203 auto entry = player_hist.begin();
204 entry->state = player.GetState();
206 entry->packet = packet;
207 player_hist.splice(player_hist.end(), player_hist, entry);
211 void InteractiveState::MergePlayerCorrection(uint16_t seq, const EntityState &corrected_state) {
212 if (player_hist.empty()) return;
214 auto entry = player_hist.begin();
215 auto end = player_hist.end();
217 // we may have received an older packet
218 int pack_diff = int16_t(seq) - int16_t(entry->packet);
220 // indeed we have, just ignore it
224 // drop anything older than the fix
225 while (entry != end) {
226 pack_diff = int16_t(seq) - int16_t(entry->packet);
228 entry = player_hist.erase(entry);
234 EntityState replay_state(corrected_state);
235 EntityState &player_state = interface.GetPlayer().entity->GetState();
238 entry->state.chunk_pos = replay_state.chunk_pos;
239 entry->state.block_pos = replay_state.block_pos;
243 while (entry != end) {
244 replay_state.velocity = entry->state.velocity;
245 replay_state.Update(entry->delta_t);
246 entry->state.chunk_pos = replay_state.chunk_pos;
247 entry->state.block_pos = replay_state.block_pos;
251 glm::vec3 displacement(replay_state.Diff(player_state));
252 const float disp_squared = dot(displacement, displacement);
254 if (disp_squared < 16.0f * numeric_limits<float>::epsilon()) {
258 // if offset > 10cm, warp the player
259 // otherwise, move at most 1cm per frame towards
260 // the fixed position (160ms, so shouldn't be too noticeable)
261 constexpr float warp_thresh = 0.01f; // (1/10)^2
262 constexpr float max_disp = 0.0001f; // (1/100)^2
264 if (disp_squared > warp_thresh) {
265 player_state.chunk_pos = replay_state.chunk_pos;
266 player_state.block_pos = replay_state.block_pos;
267 } else if (disp_squared < max_disp) {
268 player_state.block_pos += displacement;
270 displacement *= 0.01f / sqrt(disp_squared);
271 player_state.block_pos += displacement;
275 void InteractiveState::Render(Viewport &viewport) {
276 Entity &player = *interface.GetPlayer().entity;
277 viewport.WorldPosition(player.Transform(player.ChunkCoords()));
278 chunk_renderer.Render(viewport);
279 world.Render(viewport);
280 interface.Render(viewport);
284 MasterState::MasterState(
286 const World::Config &wc,
287 const Interface::Config &ic,
288 const Client::Config &cc)
299 client.GetConnection().SetHandler(this);
300 update_timer.Start();
303 void MasterState::Quit() {
304 if (!client.GetConnection().Closed()) {
307 env.state.PopUntil(this);
311 void MasterState::OnEnter() {
312 login_packet = client.SendLogin(intf_conf.player_name);
313 env.state.Push(&init_state);
317 void MasterState::Handle(const SDL_Event &event) {
322 void MasterState::Update(int dt) {
323 update_timer.Update(dt);
329 void MasterState::Render(Viewport &) {
334 void MasterState::OnPacketLost(uint16_t id) {
335 if (id == login_packet) {
336 login_packet = client.SendLogin(intf_conf.player_name);
340 void MasterState::OnTimeout() {
341 if (client.GetConnection().Closed()) {
342 // TODO: push disconnected message
343 cout << "connection timed out" << endl;
348 void MasterState::On(const Packet::Join &pack) {
349 pack.ReadWorldName(world_conf.name);
353 cout << "server changing worlds to \"" << world_conf.name << '"' << endl;
356 cout << "joined game \"" << world_conf.name << '"' << endl;
357 // server received our login
362 pack.ReadPlayerID(player_id);
363 state.reset(new InteractiveState(*this, player_id));
365 pack.ReadPlayerState(state->GetInterface().GetPlayer().entity->GetState());
367 env.state.PopAfter(this);
368 env.state.Push(state.get());
371 void MasterState::On(const Packet::Part &pack) {
374 cout << "kicked by server" << endl;
377 cout << "login refused by server" << endl;
382 void MasterState::On(const Packet::SpawnEntity &pack) {
384 cout << "got entity spawn before world was created" << endl;
389 pack.ReadEntityID(entity_id);
390 Entity &entity = state->GetWorld().ForceAddEntity(entity_id);
391 UpdateEntity(entity_id, pack.Seq());
392 pack.ReadEntity(entity);
394 pack.ReadSkeletonID(skel_id);
395 CompositeModel *skel = state->GetSkeletons().ByID(skel_id);
397 skel->Instantiate(entity.GetModel());
399 cout << "spawned entity #" << entity_id << " (" << entity.Name()
400 << ") at " << entity.AbsolutePosition() << endl;
403 void MasterState::On(const Packet::DespawnEntity &pack) {
405 cout << "got entity despawn before world was created" << endl;
410 pack.ReadEntityID(entity_id);
411 ClearEntity(entity_id);
412 for (Entity &entity : state->GetWorld().Entities()) {
413 if (entity.ID() == entity_id) {
415 cout << "despawned entity #" << entity_id << " (" << entity.Name() << ") at " << entity.AbsolutePosition() << endl;
421 void MasterState::On(const Packet::EntityUpdate &pack) {
423 cout << "got entity update before world was created" << endl;
428 auto world_iter = state->GetWorld().Entities().begin();
429 auto world_end = state->GetWorld().Entities().end();
432 pack.ReadEntityCount(count);
434 for (uint32_t i = 0; i < count; ++i) {
435 uint32_t entity_id = 0;
436 pack.ReadEntityID(entity_id, i);
438 while (world_iter != world_end && world_iter->ID() < entity_id) {
441 if (world_iter == world_end) {
442 // nothing can be done from here
445 if (world_iter->ID() == entity_id) {
446 if (UpdateEntity(entity_id, pack.Seq())) {
447 pack.ReadEntityState(world_iter->GetState(), i);
453 bool MasterState::UpdateEntity(uint32_t entity_id, uint16_t seq) {
454 auto entry = update_status.find(entity_id);
455 if (entry == update_status.end()) {
456 update_status.emplace(entity_id, UpdateStatus{ seq, update_timer.Elapsed() });
460 int16_t pack_diff = int16_t(seq) - int16_t(entry->second.last_packet);
461 int time_diff = update_timer.Elapsed() - entry->second.last_update;
462 entry->second.last_update = update_timer.Elapsed();
464 if (pack_diff > 0 || time_diff > 1500) {
465 entry->second.last_packet = seq;
472 void MasterState::ClearEntity(uint32_t entity_id) {
473 update_status.erase(entity_id);
476 void MasterState::On(const Packet::PlayerCorrection &pack) {
478 cout << "got player correction without a player :S" << endl;
483 EntityState corrected_state;
484 pack.ReadPacketSeq(pack_seq);
485 pack.ReadPlayerState(corrected_state);
486 state->MergePlayerCorrection(pack_seq, corrected_state);
489 void MasterState::On(const Packet::ChunkBegin &pack) {
491 cout << "got chunk data, but the world has not been created yet" << endl;
492 cout << "great, this will totally screw up everything :(" << endl;
495 state->GetChunkReceiver().Handle(pack);
498 void MasterState::On(const Packet::ChunkData &pack) {
500 cout << "got chunk data, but the world has not been created yet" << endl;
501 cout << "great, this will totally screw up everything :(" << endl;
504 state->GetChunkReceiver().Handle(pack);