1 #include "ClientController.hpp"
2 #include "DirectInput.hpp"
4 #include "InteractiveManipulator.hpp"
5 #include "Interface.hpp"
7 #include "PlayerController.hpp"
9 #include "../app/Assets.hpp"
10 #include "../app/Config.hpp"
11 #include "../app/Environment.hpp"
12 #include "../app/FrameCounter.hpp"
13 #include "../app/init.hpp"
14 #include "../audio/Audio.hpp"
15 #include "../audio/SoundBank.hpp"
16 #include "../graphics/Font.hpp"
17 #include "../graphics/Viewport.hpp"
18 #include "../io/TokenStreamReader.hpp"
19 #include "../model/bounds.hpp"
20 #include "../net/CongestionControl.hpp"
21 #include "../world/BlockLookup.hpp"
22 #include "../world/World.hpp"
23 #include "../world/WorldManipulator.hpp"
30 #include <glm/gtc/matrix_transform.hpp>
31 #include <glm/gtx/rotate_vector.hpp>
32 #include <glm/gtx/io.hpp>
37 PlayerController::PlayerController(World &world, Player &player)
44 player.GetEntity().SetController(*this);
47 PlayerController::~PlayerController() {
48 if (&player.GetEntity().GetController() == this) {
49 player.GetEntity().UnsetController();
53 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
54 if (dot(m, m) > 1.0f) {
55 move_dir = normalize(m);
62 glm::vec3 PlayerController::ControlForce(const Entity &e, const EntityState &s) const {
63 if (!iszero(move_dir)) {
64 // scale input by max velocity, apply yaw, and transform to world space
65 return TargetVelocity(glm::vec3(glm::vec4(rotateY(move_dir * e.MaxVelocity(), s.yaw), 0.0f) * transpose(e.Transform())), s, 5.0f);
67 // target velocity of 0 is the same as halt
72 void PlayerController::TurnHead(float dp, float dy) noexcept {
73 player.GetEntity().TurnHead(dp, dy);
76 float PlayerController::GetPitch() const noexcept {
77 return player.GetEntity().Pitch();
80 float PlayerController::GetYaw() const noexcept {
81 return player.GetEntity().Yaw();
84 void PlayerController::SelectInventory(int i) noexcept {
85 player.SetInventorySlot(i);
88 int PlayerController::InventorySlot() const noexcept {
89 return player.GetInventorySlot();
92 void PlayerController::Invalidate() noexcept {
96 void PlayerController::UpdatePlayer() noexcept {
98 Ray aim = player.Aim();
99 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
100 aim_world = WorldCollision();
102 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), aim_entity)) {
103 aim_entity = EntityCollision();
105 if (aim_world && aim_entity) {
106 // got both, pick the closest one
107 if (aim_world.depth < aim_entity.depth) {
108 aim_entity = EntityCollision();
110 aim_world = WorldCollision();
118 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
119 : PlayerController(world, player)
122 , remove_timer(0.25f) {
126 void DirectInput::Update(Entity &, float dt) {
127 Invalidate(); // world has changed in the meantime
130 remove_timer.Update(dt);
131 if (remove_timer.Hit()) {
135 place_timer.Update(dt);
136 if (place_timer.Hit()) {
141 void DirectInput::StartPrimaryAction() {
142 if (!remove_timer.Running()) {
144 remove_timer.Start();
148 void DirectInput::StopPrimaryAction() {
152 void DirectInput::StartSecondaryAction() {
153 if (!place_timer.Running()) {
159 void DirectInput::StopSecondaryAction() {
163 void DirectInput::StartTertiaryAction() {
167 void DirectInput::StopTertiaryAction() {
171 void DirectInput::PickBlock() {
173 if (!BlockFocus()) return;
174 SelectInventory(BlockFocus().GetBlock().type - 1);
177 void DirectInput::PlaceBlock() {
179 if (!BlockFocus()) return;
181 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
185 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
189 void DirectInput::RemoveBlock() {
191 if (!BlockFocus()) return;
192 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
197 HUD::HUD(Environment &env, Config &config, const Player &player)
203 , outline_transform(1.0f)
204 , outline_visible(false)
208 , block_transform(1.0f)
210 , block_visible(false)
224 , messages(env.assets.small_ui_font)
229 const float ls = env.assets.small_ui_font.LineSkip();
232 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
233 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
234 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
235 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
236 block_label.Position(
237 glm::vec3(50.0f, 85.0f, 0.0f),
241 block_label.Foreground(glm::vec4(1.0f));
242 block_label.Background(glm::vec4(0.5f));
245 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
246 counter_text.Foreground(glm::vec4(1.0f));
247 counter_text.Background(glm::vec4(0.5f));
248 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
249 position_text.Foreground(glm::vec4(1.0f));
250 position_text.Background(glm::vec4(0.5f));
251 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
252 orientation_text.Foreground(glm::vec4(1.0f));
253 orientation_text.Background(glm::vec4(0.5f));
254 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
255 block_text.Foreground(glm::vec4(1.0f));
256 block_text.Background(glm::vec4(0.5f));
257 block_text.Set(env.assets.small_ui_font, "Block: none");
258 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
259 entity_text.Foreground(glm::vec4(1.0f));
260 entity_text.Background(glm::vec4(0.5f));
261 entity_text.Set(env.assets.small_ui_font, "Entity: none");
264 bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
265 bandwidth_text.Foreground(glm::vec4(1.0f));
266 bandwidth_text.Background(glm::vec4(0.5f));
267 bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
268 rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
269 rtt_text.Foreground(glm::vec4(1.0f));
270 rtt_text.Background(glm::vec4(0.5f));
271 rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
272 packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
273 packet_loss_text.Foreground(glm::vec4(1.0f));
274 packet_loss_text.Background(glm::vec4(0.5f));
275 packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
278 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
279 messages.Foreground(glm::vec4(1.0f));
280 messages.Background(glm::vec4(0.5f));
283 PrimitiveMesh::Buffer buf;
284 buf.vertices = std::vector<glm::vec3>({
285 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
286 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
288 buf.indices = std::vector<PrimitiveMesh::Index>({
291 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
292 crosshair.Update(buf);
297 PrimitiveMesh::Buffer outl_buf;
301 void HUD::FocusBlock(const Chunk &chunk, int index) {
302 const Block &block = chunk.BlockAt(index);
303 const BlockType &type = chunk.Type(index);
305 type.OutlinePrimitiveMesh(outl_buf);
306 outline.Update(outl_buf);
307 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
308 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
309 outline_transform *= glm::scale(glm::vec3(1.005f));
310 outline_visible = true;
315 << ", face: " << block.GetFace()
316 << ", turn: " << block.GetTurn();
317 block_text.Set(env.assets.small_ui_font, s.str());
323 void HUD::FocusEntity(const Entity &entity) {
326 s << "Entity: " << entity.Name();
327 entity_text.Set(env.assets.small_ui_font, s.str());
333 void HUD::FocusNone() {
334 outline_visible = false;
339 void HUD::DisplayNone() {
340 block_visible = false;
343 void HUD::Display(const BlockType &type) {
345 type.FillEntityMesh(block_buf);
346 block.Update(block_buf);
348 block_label.Set(env.assets.small_ui_font, type.label);
350 block_visible = type.visible;
354 void HUD::UpdateDebug() {
360 void HUD::UpdateCounter() {
362 s << std::setprecision(3) <<
363 "avg: " << env.counter.Average().running << "ms, "
364 "peak: " << env.counter.Peak().running << "ms";
365 std::string text = s.str();
366 counter_text.Set(env.assets.small_ui_font, text);
369 void HUD::UpdatePosition() {
371 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
372 position_text.Set(env.assets.small_ui_font, s.str());
375 void HUD::UpdateOrientation() {
377 s << std::setprecision(3) << "pitch: " << rad2deg(player.GetEntity().Pitch())
378 << ", yaw: " << rad2deg(player.GetEntity().Yaw());
379 orientation_text.Set(env.assets.small_ui_font, s.str());
382 void HUD::PostMessage(const char *msg) {
383 messages.PushLine(msg);
386 std::cout << msg << std::endl;
390 void HUD::UpdateNetStats(const CongestionControl &stat) {
391 if (!config.video.debug) return;
394 s << std::fixed << std::setprecision(1)
395 << "TX: " << stat.Upstream()
396 << "KB/s, RX: " << stat.Downstream() << "KB/s";
397 bandwidth_text.Set(env.assets.small_ui_font, s.str());
400 s << "RTT: " << stat.RoundTripTime() << "ms";
401 rtt_text.Set(env.assets.small_ui_font, s.str());
404 s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
405 packet_loss_text.Set(env.assets.small_ui_font, s.str());
411 void HUD::Update(int dt) {
412 msg_timer.Update(dt);
413 if (msg_timer.HitOnce()) {
417 if (config.video.debug) {
418 if (env.counter.Changed()) {
426 void HUD::Render(Viewport &viewport) noexcept {
428 if (outline_visible && config.video.world) {
429 PlainColor &outline_prog = viewport.WorldColorProgram();
430 outline_prog.SetM(outline_transform);
434 // clear depth buffer so everything renders above the world
435 viewport.ClearDepth();
437 if (config.video.hud) {
440 DirectionalLighting &world_prog = viewport.HUDProgram();
441 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
442 world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
443 world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
444 // disable distance fog
445 world_prog.SetFogDensity(0.0f);
447 viewport.DisableBlending();
448 world_prog.SetM(block_transform);
450 block_label.Render(viewport);
454 if (msg_keep || msg_timer.Running()) {
455 messages.Render(viewport);
459 PlainColor &outline_prog = viewport.HUDColorProgram();
460 viewport.EnableInvertBlending();
461 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
462 outline_prog.SetM(viewport.Cursor());
463 crosshair.DrawLines();
467 if (config.video.debug) {
468 counter_text.Render(viewport);
469 position_text.Render(viewport);
470 orientation_text.Render(viewport);
472 block_text.Render(viewport);
473 } else if (show_entity) {
474 entity_text.Render(viewport);
477 bandwidth_text.Render(viewport);
478 rtt_text.Render(viewport);
479 packet_loss_text.Render(viewport);
485 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
492 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
493 const BlockType &old_type = chunk.Type(index);
494 chunk.SetBlock(index, block);
495 const BlockType &new_type = chunk.Type(index);
496 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
497 if (new_type.id == 0) {
498 if (old_type.remove_sound >= 0) {
499 audio.Play(sounds[old_type.remove_sound], coords);
502 if (new_type.place_sound >= 0) {
503 audio.Play(sounds[new_type.place_sound], coords);
509 Interface::Interface(
511 const Keymap &keymap,
512 PlayerController &pc,
513 ClientController &cc)
525 void Interface::Lock() {
531 void Interface::Unlock() {
535 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
536 if (!config.input.keyboard) return;
538 Keymap::Action action = keymap.Lookup(event);
540 case Keymap::MOVE_FORWARD:
544 case Keymap::MOVE_BACKWARD:
548 case Keymap::MOVE_LEFT:
552 case Keymap::MOVE_RIGHT:
556 case Keymap::MOVE_UP:
560 case Keymap::MOVE_DOWN:
565 case Keymap::PRIMARY:
566 player_ctrl.StartPrimaryAction();
568 case Keymap::SECONDARY:
569 player_ctrl.StartSecondaryAction();
571 case Keymap::TERTIARY:
572 player_ctrl.StartTertiaryAction();
575 case Keymap::INV_NEXT:
578 case Keymap::INV_PREVIOUS:
591 InvAbs(action - Keymap::INV_1);
598 case Keymap::TOGGLE_AUDIO:
599 config.audio.enabled = !config.audio.enabled;
600 client_ctrl.SetAudio(config.audio.enabled);
602 case Keymap::TOGGLE_VIDEO:
603 config.video.world = !config.video.world;
604 client_ctrl.SetVideo(config.video.world);
606 case Keymap::TOGGLE_HUD:
607 config.video.hud = !config.video.hud;
608 client_ctrl.SetHUD(config.video.hud);
610 case Keymap::TOGGLE_DEBUG:
611 config.video.debug = !config.video.debug;
612 client_ctrl.SetDebug(config.video.debug);
620 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
621 if (!config.input.keyboard) return;
623 switch (keymap.Lookup(event)) {
624 case Keymap::MOVE_FORWARD:
628 case Keymap::MOVE_BACKWARD:
632 case Keymap::MOVE_LEFT:
636 case Keymap::MOVE_RIGHT:
640 case Keymap::MOVE_UP:
644 case Keymap::MOVE_DOWN:
649 case Keymap::PRIMARY:
650 player_ctrl.StopPrimaryAction();
652 case Keymap::SECONDARY:
653 player_ctrl.StopSecondaryAction();
655 case Keymap::TERTIARY:
656 player_ctrl.StopTertiaryAction();
664 void Interface::Handle(const SDL_MouseMotionEvent &event) {
665 if (locked || !config.input.mouse) return;
666 player_ctrl.TurnHead(
667 event.yrel * config.input.pitch_sensitivity,
668 event.xrel * config.input.yaw_sensitivity);
671 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
672 if (!config.input.mouse) return;
674 switch (event.button) {
675 case SDL_BUTTON_LEFT:
676 player_ctrl.StartPrimaryAction();
678 case SDL_BUTTON_RIGHT:
679 player_ctrl.StartSecondaryAction();
681 case SDL_BUTTON_MIDDLE:
682 player_ctrl.StartTertiaryAction();
687 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
688 if (!config.input.mouse) return;
690 switch (event.button) {
691 case SDL_BUTTON_LEFT:
692 player_ctrl.StopPrimaryAction();
694 case SDL_BUTTON_RIGHT:
695 player_ctrl.StopSecondaryAction();
697 case SDL_BUTTON_MIDDLE:
698 player_ctrl.StopTertiaryAction();
704 void Interface::Handle(const SDL_MouseWheelEvent &event) {
705 if (!config.input.mouse) return;
709 } else if (event.y > 0) {
714 void Interface::UpdateMovement() {
715 player_ctrl.SetMovement(glm::vec3(fwd - rev));
718 void Interface::InvAbs(int s) {
719 int slot = s % num_slots;
723 player_ctrl.SelectInventory(slot);
726 void Interface::InvRel(int delta) {
727 InvAbs(player_ctrl.GetPlayer().GetInventorySlot() + delta);
736 void Keymap::Map(SDL_Scancode scancode, Action action) {
737 if (scancode > MAX_SCANCODE) {
738 throw std::runtime_error("refusing to map scancode: too damn high");
740 codemap[scancode] = action;
743 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
744 if (scancode < NUM_SCANCODES) {
745 return codemap[scancode];
752 void Keymap::LoadDefault() {
753 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
754 Map(SDL_SCANCODE_W, MOVE_FORWARD);
755 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
756 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
757 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
758 Map(SDL_SCANCODE_A, MOVE_LEFT);
759 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
760 Map(SDL_SCANCODE_D, MOVE_RIGHT);
761 Map(SDL_SCANCODE_SPACE, MOVE_UP);
762 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
763 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
764 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
765 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
767 Map(SDL_SCANCODE_TAB, INV_NEXT);
768 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
769 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
770 Map(SDL_SCANCODE_1, INV_1);
771 Map(SDL_SCANCODE_2, INV_2);
772 Map(SDL_SCANCODE_3, INV_3);
773 Map(SDL_SCANCODE_4, INV_4);
774 Map(SDL_SCANCODE_5, INV_5);
775 Map(SDL_SCANCODE_6, INV_6);
776 Map(SDL_SCANCODE_7, INV_7);
777 Map(SDL_SCANCODE_8, INV_8);
778 Map(SDL_SCANCODE_9, INV_9);
779 Map(SDL_SCANCODE_0, INV_10);
781 Map(SDL_SCANCODE_INSERT, SECONDARY);
782 Map(SDL_SCANCODE_RETURN, SECONDARY);
783 Map(SDL_SCANCODE_MENU, TERTIARY);
784 Map(SDL_SCANCODE_DELETE, PRIMARY);
785 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
787 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
788 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
789 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
790 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
792 Map(SDL_SCANCODE_ESCAPE, EXIT);
796 void Keymap::Load(std::istream &is) {
797 TokenStreamReader in(is);
798 std::string key_name;
799 std::string action_name;
802 while (in.HasMore()) {
803 if (in.Peek().type == Token::STRING) {
804 in.ReadString(key_name);
805 key = SDL_GetScancodeFromName(key_name.c_str());
807 key = SDL_Scancode(in.GetInt());
809 in.Skip(Token::EQUALS);
810 in.ReadIdentifier(action_name);
811 action = StringToAction(action_name);
812 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
813 in.Skip(Token::SEMICOLON);
819 void Keymap::Save(std::ostream &out) {
820 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
821 if (codemap[i] == NONE) continue;
823 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
839 out << " = " << ActionToString(codemap[i]) << std::endl;;
846 std::map<std::string, Keymap::Action> action_map = {
847 { "none", Keymap::NONE },
848 { "move_forward", Keymap::MOVE_FORWARD },
849 { "move_backward", Keymap::MOVE_BACKWARD },
850 { "move_left", Keymap::MOVE_LEFT },
851 { "move_right", Keymap::MOVE_RIGHT },
852 { "move_up", Keymap::MOVE_UP },
853 { "move_down", Keymap::MOVE_DOWN },
855 { "primary", Keymap::PRIMARY },
856 { "secondary", Keymap::SECONDARY },
857 { "tertiary", Keymap::TERTIARY },
859 { "inventory_next", Keymap::INV_NEXT },
860 { "inventory_prev", Keymap::INV_PREVIOUS },
861 { "inventory_1", Keymap::INV_1 },
862 { "inventory_2", Keymap::INV_2 },
863 { "inventory_3", Keymap::INV_3 },
864 { "inventory_4", Keymap::INV_4 },
865 { "inventory_5", Keymap::INV_5 },
866 { "inventory_6", Keymap::INV_6 },
867 { "inventory_7", Keymap::INV_7 },
868 { "inventory_8", Keymap::INV_8 },
869 { "inventory_9", Keymap::INV_9 },
870 { "inventory_10", Keymap::INV_10 },
872 { "toggle_audio", Keymap::TOGGLE_AUDIO },
873 { "toggle_video", Keymap::TOGGLE_VIDEO },
874 { "toggle_hud", Keymap::TOGGLE_HUD },
875 { "toggle_debug", Keymap::TOGGLE_DEBUG },
877 { "exit", Keymap::EXIT },
882 const char *Keymap::ActionToString(Action action) {
883 for (const auto &entry : action_map) {
884 if (action == entry.second) {
885 return entry.first.c_str();
891 Keymap::Action Keymap::StringToAction(const std::string &str) {
892 auto entry = action_map.find(str);
893 if (entry != action_map.end()) {
894 return entry->second;
896 std::cerr << "unknown action \"" << str << '"' << std::endl;