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 "../geometry/distance.hpp"
17 #include "../graphics/Font.hpp"
18 #include "../graphics/Viewport.hpp"
19 #include "../io/TokenStreamReader.hpp"
20 #include "../model/bounds.hpp"
21 #include "../net/CongestionControl.hpp"
22 #include "../world/BlockLookup.hpp"
23 #include "../world/World.hpp"
24 #include "../world/WorldManipulator.hpp"
31 #include <glm/gtc/matrix_transform.hpp>
32 #include <glm/gtx/rotate_vector.hpp>
33 #include <glm/gtx/io.hpp>
38 PlayerController::PlayerController(World &world, Player &player)
45 player.GetEntity().SetController(*this);
46 player.GetEntity().GetSteering().SetAcceleration(5.0f);
49 PlayerController::~PlayerController() {
50 if (&player.GetEntity().GetController() == this) {
51 player.GetEntity().UnsetController();
55 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
56 if (dot(m, m) > 1.0f) {
57 move_dir = normalize(m);
64 void PlayerController::TurnHead(float dp, float dy) noexcept {
65 player.GetEntity().TurnHead(dp, dy);
68 float PlayerController::GetPitch() const noexcept {
69 return player.GetEntity().Pitch();
72 float PlayerController::GetYaw() const noexcept {
73 return player.GetEntity().Yaw();
76 void PlayerController::SelectInventory(int i) noexcept {
77 player.SetInventorySlot(i);
80 int PlayerController::InventorySlot() const noexcept {
81 return player.GetInventorySlot();
84 void PlayerController::Invalidate() noexcept {
88 void PlayerController::UpdatePlayer() noexcept {
90 Ray aim = player.Aim();
91 Entity &entity = player.GetEntity();
92 if (!world.Intersection(aim, entity.ChunkCoords(), aim_world)) {
93 aim_world = WorldCollision();
95 if (!world.Intersection(aim, entity, aim_entity)) {
96 aim_entity = EntityCollision();
98 if (aim_world && aim_entity) {
99 // got both, pick the closest one
100 if (aim_world.depth < aim_entity.depth) {
101 aim_entity = EntityCollision();
103 aim_world = WorldCollision();
106 Steering &steering = entity.GetSteering();
107 if (!iszero(move_dir)) {
108 // scale input by max velocity, apply yaw, and transform to world space
109 steering.SetTargetVelocity(glm::vec3(
110 glm::vec4(rotateY(move_dir * entity.MaxVelocity(), entity.Yaw()), 0.0f)
111 * transpose(entity.Transform())
113 steering.Enable(Steering::TARGET_VELOCITY);
114 steering.Disable(Steering::HALT);
116 // target velocity of 0 is the same as halt
117 steering.Enable(Steering::HALT);
118 steering.Disable(Steering::TARGET_VELOCITY);
125 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
126 : PlayerController(world, player)
129 , remove_timer(0.25f) {
133 void DirectInput::Update(Entity &, float dt) {
134 Invalidate(); // world has changed in the meantime
137 remove_timer.Update(dt);
138 if (remove_timer.Hit()) {
142 place_timer.Update(dt);
143 if (place_timer.Hit()) {
148 void DirectInput::StartPrimaryAction() {
149 if (!remove_timer.Running()) {
151 remove_timer.Start();
155 void DirectInput::StopPrimaryAction() {
159 void DirectInput::StartSecondaryAction() {
160 if (!place_timer.Running()) {
166 void DirectInput::StopSecondaryAction() {
170 void DirectInput::StartTertiaryAction() {
174 void DirectInput::StopTertiaryAction() {
178 void DirectInput::PickBlock() {
180 if (!BlockFocus()) return;
181 SelectInventory(BlockFocus().GetBlock().type - 1);
184 void DirectInput::PlaceBlock() {
186 if (!BlockFocus()) return;
188 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
192 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
196 void DirectInput::RemoveBlock() {
198 if (!BlockFocus()) return;
199 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
204 HUD::HUD(Environment &env, Config &config, const Player &player)
210 , outline_transform(1.0f)
211 , outline_visible(false)
215 , block_transform(1.0f)
217 , block_visible(false)
231 , messages(env.assets.small_ui_font)
236 const float ls = env.assets.small_ui_font.LineSkip();
239 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
240 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
241 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
242 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
243 block_label.Position(
244 glm::vec3(50.0f, 85.0f, 0.0f),
248 block_label.Foreground(glm::vec4(1.0f));
249 block_label.Background(glm::vec4(0.5f));
252 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
253 counter_text.Foreground(glm::vec4(1.0f));
254 counter_text.Background(glm::vec4(0.5f));
255 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
256 position_text.Foreground(glm::vec4(1.0f));
257 position_text.Background(glm::vec4(0.5f));
258 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
259 orientation_text.Foreground(glm::vec4(1.0f));
260 orientation_text.Background(glm::vec4(0.5f));
261 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
262 block_text.Foreground(glm::vec4(1.0f));
263 block_text.Background(glm::vec4(0.5f));
264 block_text.Set(env.assets.small_ui_font, "Block: none");
265 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
266 entity_text.Foreground(glm::vec4(1.0f));
267 entity_text.Background(glm::vec4(0.5f));
268 entity_text.Set(env.assets.small_ui_font, "Entity: none");
271 bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
272 bandwidth_text.Foreground(glm::vec4(1.0f));
273 bandwidth_text.Background(glm::vec4(0.5f));
274 bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
275 rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
276 rtt_text.Foreground(glm::vec4(1.0f));
277 rtt_text.Background(glm::vec4(0.5f));
278 rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
279 packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
280 packet_loss_text.Foreground(glm::vec4(1.0f));
281 packet_loss_text.Background(glm::vec4(0.5f));
282 packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
285 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
286 messages.Foreground(glm::vec4(1.0f));
287 messages.Background(glm::vec4(0.5f));
290 PrimitiveMesh::Buffer buf;
291 buf.vertices = std::vector<glm::vec3>({
292 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
293 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
295 buf.indices = std::vector<PrimitiveMesh::Index>({
298 buf.colors.resize(4, { 255, 255, 255, 255 });
299 crosshair.Update(buf);
304 PrimitiveMesh::Buffer outl_buf;
308 void HUD::FocusBlock(const Chunk &chunk, int index) {
309 const Block &block = chunk.BlockAt(index);
310 const BlockType &type = chunk.Type(index);
312 type.OutlinePrimitiveMesh(outl_buf);
313 outline.Update(outl_buf);
314 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
315 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
316 outline_transform *= glm::scale(glm::vec3(1.005f));
317 outline_visible = true;
322 << ", face: " << block.GetFace()
323 << ", turn: " << block.GetTurn();
324 block_text.Set(env.assets.small_ui_font, s.str());
330 void HUD::FocusEntity(const Entity &entity) {
333 s << "Entity: " << entity.Name();
334 entity_text.Set(env.assets.small_ui_font, s.str());
340 void HUD::FocusNone() {
341 outline_visible = false;
346 void HUD::DisplayNone() {
347 block_visible = false;
350 void HUD::Display(const BlockType &type) {
352 type.FillEntityMesh(block_buf);
353 block.Update(block_buf);
355 block_label.Set(env.assets.small_ui_font, type.label);
357 block_visible = type.visible;
361 void HUD::UpdateDebug() {
367 void HUD::UpdateCounter() {
369 s << std::setprecision(3) <<
370 "avg: " << env.counter.Average().running << "ms, "
371 "peak: " << env.counter.Peak().running << "ms";
372 std::string text = s.str();
373 counter_text.Set(env.assets.small_ui_font, text);
376 void HUD::UpdatePosition() {
378 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
379 position_text.Set(env.assets.small_ui_font, s.str());
382 void HUD::UpdateOrientation() {
384 s << std::setprecision(3) << "pitch: " << glm::degrees(player.GetEntity().Pitch())
385 << ", yaw: " << glm::degrees(player.GetEntity().Yaw());
386 orientation_text.Set(env.assets.small_ui_font, s.str());
389 void HUD::PostMessage(const char *msg) {
390 messages.PushLine(msg);
393 std::cout << msg << std::endl;
397 void HUD::UpdateNetStats(const CongestionControl &stat) {
398 if (!config.video.debug) return;
401 s << std::fixed << std::setprecision(1)
402 << "TX: " << stat.Upstream()
403 << "KB/s, RX: " << stat.Downstream() << "KB/s";
404 bandwidth_text.Set(env.assets.small_ui_font, s.str());
407 s << "RTT: " << stat.RoundTripTime() << "ms";
408 rtt_text.Set(env.assets.small_ui_font, s.str());
411 s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
412 packet_loss_text.Set(env.assets.small_ui_font, s.str());
418 void HUD::Update(int dt) {
419 msg_timer.Update(dt);
420 if (msg_timer.HitOnce()) {
424 if (config.video.debug) {
425 if (env.counter.Changed()) {
433 void HUD::Render(Viewport &viewport) noexcept {
435 if (outline_visible && config.video.world) {
436 PlainColor &outline_prog = viewport.WorldColorProgram();
437 outline_prog.SetM(outline_transform);
441 // clear depth buffer so everything renders above the world
442 viewport.ClearDepth();
444 if (config.video.hud) {
447 DirectionalLighting &world_prog = viewport.HUDProgram();
448 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
449 world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
450 world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
451 // disable distance fog
452 world_prog.SetFogDensity(0.0f);
454 viewport.DisableBlending();
455 world_prog.SetM(block_transform);
457 block_label.Render(viewport);
461 if (msg_keep || msg_timer.Running()) {
462 messages.Render(viewport);
466 PlainColor &outline_prog = viewport.HUDColorProgram();
467 viewport.EnableInvertBlending();
468 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
469 outline_prog.SetM(viewport.Cursor());
470 crosshair.DrawLines();
474 if (config.video.debug) {
475 counter_text.Render(viewport);
476 position_text.Render(viewport);
477 orientation_text.Render(viewport);
479 block_text.Render(viewport);
480 } else if (show_entity) {
481 entity_text.Render(viewport);
484 bandwidth_text.Render(viewport);
485 rtt_text.Render(viewport);
486 packet_loss_text.Render(viewport);
492 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
499 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
500 const BlockType &old_type = chunk.Type(index);
501 chunk.SetBlock(index, block);
502 const BlockType &new_type = chunk.Type(index);
503 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
504 if (new_type.id == 0) {
505 if (old_type.remove_sound >= 0) {
506 audio.Play(sounds[old_type.remove_sound], coords);
509 if (new_type.place_sound >= 0) {
510 audio.Play(sounds[new_type.place_sound], coords);
516 Interface::Interface(
518 const Keymap &keymap,
519 PlayerController &pc,
520 ClientController &cc)
532 void Interface::Lock() {
538 void Interface::Unlock() {
542 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
543 if (!config.input.keyboard) return;
545 Keymap::Action action = keymap.Lookup(event);
547 case Keymap::MOVE_FORWARD:
551 case Keymap::MOVE_BACKWARD:
555 case Keymap::MOVE_LEFT:
559 case Keymap::MOVE_RIGHT:
563 case Keymap::MOVE_UP:
567 case Keymap::MOVE_DOWN:
572 case Keymap::PRIMARY:
573 player_ctrl.StartPrimaryAction();
575 case Keymap::SECONDARY:
576 player_ctrl.StartSecondaryAction();
578 case Keymap::TERTIARY:
579 player_ctrl.StartTertiaryAction();
582 case Keymap::INV_NEXT:
585 case Keymap::INV_PREVIOUS:
598 InvAbs(action - Keymap::INV_1);
605 case Keymap::TOGGLE_AUDIO:
606 client_ctrl.SetAudio(!config.audio.enabled);
608 case Keymap::TOGGLE_VIDEO:
609 client_ctrl.SetVideo(!config.video.world);
611 case Keymap::TOGGLE_HUD:
612 client_ctrl.SetHUD(!config.video.hud);
614 case Keymap::TOGGLE_DEBUG:
615 client_ctrl.SetDebug(!config.video.debug);
617 case Keymap::CAMERA_NEXT:
618 client_ctrl.NextCamera();
626 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
627 if (!config.input.keyboard) return;
629 switch (keymap.Lookup(event)) {
630 case Keymap::MOVE_FORWARD:
634 case Keymap::MOVE_BACKWARD:
638 case Keymap::MOVE_LEFT:
642 case Keymap::MOVE_RIGHT:
646 case Keymap::MOVE_UP:
650 case Keymap::MOVE_DOWN:
655 case Keymap::PRIMARY:
656 player_ctrl.StopPrimaryAction();
658 case Keymap::SECONDARY:
659 player_ctrl.StopSecondaryAction();
661 case Keymap::TERTIARY:
662 player_ctrl.StopTertiaryAction();
670 void Interface::Handle(const SDL_MouseMotionEvent &event) {
671 if (locked || !config.input.mouse) return;
672 player_ctrl.TurnHead(
673 event.yrel * config.input.pitch_sensitivity,
674 event.xrel * config.input.yaw_sensitivity);
677 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
678 if (!config.input.mouse) return;
680 switch (event.button) {
681 case SDL_BUTTON_LEFT:
682 player_ctrl.StartPrimaryAction();
684 case SDL_BUTTON_RIGHT:
685 player_ctrl.StartSecondaryAction();
687 case SDL_BUTTON_MIDDLE:
688 player_ctrl.StartTertiaryAction();
693 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
694 if (!config.input.mouse) return;
696 switch (event.button) {
697 case SDL_BUTTON_LEFT:
698 player_ctrl.StopPrimaryAction();
700 case SDL_BUTTON_RIGHT:
701 player_ctrl.StopSecondaryAction();
703 case SDL_BUTTON_MIDDLE:
704 player_ctrl.StopTertiaryAction();
710 void Interface::Handle(const SDL_MouseWheelEvent &event) {
711 if (!config.input.mouse) return;
715 } else if (event.y > 0) {
720 void Interface::UpdateMovement() {
721 player_ctrl.SetMovement(glm::vec3(fwd - rev));
724 void Interface::InvAbs(int s) {
725 int slot = s % num_slots;
729 player_ctrl.SelectInventory(slot);
732 void Interface::InvRel(int delta) {
733 InvAbs(player_ctrl.GetPlayer().GetInventorySlot() + delta);
742 void Keymap::Map(SDL_Scancode scancode, Action action) {
743 if (scancode > MAX_SCANCODE) {
744 throw std::runtime_error("refusing to map scancode: too damn high");
746 codemap[scancode] = action;
749 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
750 if (scancode < NUM_SCANCODES) {
751 return codemap[scancode];
758 void Keymap::LoadDefault() {
759 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
760 Map(SDL_SCANCODE_W, MOVE_FORWARD);
761 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
762 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
763 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
764 Map(SDL_SCANCODE_A, MOVE_LEFT);
765 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
766 Map(SDL_SCANCODE_D, MOVE_RIGHT);
767 Map(SDL_SCANCODE_SPACE, MOVE_UP);
768 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
769 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
770 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
771 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
773 Map(SDL_SCANCODE_TAB, INV_NEXT);
774 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
775 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
776 Map(SDL_SCANCODE_1, INV_1);
777 Map(SDL_SCANCODE_2, INV_2);
778 Map(SDL_SCANCODE_3, INV_3);
779 Map(SDL_SCANCODE_4, INV_4);
780 Map(SDL_SCANCODE_5, INV_5);
781 Map(SDL_SCANCODE_6, INV_6);
782 Map(SDL_SCANCODE_7, INV_7);
783 Map(SDL_SCANCODE_8, INV_8);
784 Map(SDL_SCANCODE_9, INV_9);
785 Map(SDL_SCANCODE_0, INV_10);
787 Map(SDL_SCANCODE_INSERT, SECONDARY);
788 Map(SDL_SCANCODE_MENU, TERTIARY);
789 Map(SDL_SCANCODE_DELETE, PRIMARY);
790 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
792 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
793 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
794 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
795 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
796 Map(SDL_SCANCODE_F5, CAMERA_NEXT);
798 Map(SDL_SCANCODE_ESCAPE, EXIT);
802 void Keymap::Load(std::istream &is) {
803 TokenStreamReader in(is);
804 std::string key_name;
805 std::string action_name;
808 while (in.HasMore()) {
809 if (in.Peek().type == Token::STRING) {
810 in.ReadString(key_name);
811 key = SDL_GetScancodeFromName(key_name.c_str());
813 key = SDL_Scancode(in.GetInt());
815 in.Skip(Token::EQUALS);
816 in.ReadIdentifier(action_name);
817 action = StringToAction(action_name);
818 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
819 in.Skip(Token::SEMICOLON);
825 void Keymap::Save(std::ostream &out) {
826 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
827 if (codemap[i] == NONE) continue;
829 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
845 out << " = " << ActionToString(codemap[i]) << std::endl;;
852 std::map<std::string, Keymap::Action> action_map = {
853 { "none", Keymap::NONE },
854 { "move_forward", Keymap::MOVE_FORWARD },
855 { "move_backward", Keymap::MOVE_BACKWARD },
856 { "move_left", Keymap::MOVE_LEFT },
857 { "move_right", Keymap::MOVE_RIGHT },
858 { "move_up", Keymap::MOVE_UP },
859 { "move_down", Keymap::MOVE_DOWN },
861 { "primary", Keymap::PRIMARY },
862 { "secondary", Keymap::SECONDARY },
863 { "tertiary", Keymap::TERTIARY },
865 { "inventory_next", Keymap::INV_NEXT },
866 { "inventory_prev", Keymap::INV_PREVIOUS },
867 { "inventory_1", Keymap::INV_1 },
868 { "inventory_2", Keymap::INV_2 },
869 { "inventory_3", Keymap::INV_3 },
870 { "inventory_4", Keymap::INV_4 },
871 { "inventory_5", Keymap::INV_5 },
872 { "inventory_6", Keymap::INV_6 },
873 { "inventory_7", Keymap::INV_7 },
874 { "inventory_8", Keymap::INV_8 },
875 { "inventory_9", Keymap::INV_9 },
876 { "inventory_10", Keymap::INV_10 },
878 { "toggle_audio", Keymap::TOGGLE_AUDIO },
879 { "toggle_video", Keymap::TOGGLE_VIDEO },
880 { "toggle_hud", Keymap::TOGGLE_HUD },
881 { "toggle_debug", Keymap::TOGGLE_DEBUG },
882 { "camera_next", Keymap::CAMERA_NEXT },
884 { "exit", Keymap::EXIT },
889 const char *Keymap::ActionToString(Action action) {
890 for (const auto &entry : action_map) {
891 if (action == entry.second) {
892 return entry.first.c_str();
898 Keymap::Action Keymap::StringToAction(const std::string &str) {
899 auto entry = action_map.find(str);
900 if (entry != action_map.end()) {
901 return entry->second;
903 std::cerr << "unknown action \"" << str << '"' << std::endl;