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 "../world/BlockLookup.hpp"
21 #include "../world/World.hpp"
22 #include "../world/WorldManipulator.hpp"
29 #include <glm/gtc/matrix_transform.hpp>
30 #include <glm/gtx/rotate_vector.hpp>
31 #include <glm/gtx/io.hpp>
36 PlayerController::PlayerController(World &world, Player &player)
43 player.GetEntity().SetController(*this);
46 PlayerController::~PlayerController() {
47 if (&player.GetEntity().GetController() == this) {
48 player.GetEntity().UnsetController();
52 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
53 if (dot(m, m) > 1.0f) {
54 move_dir = normalize(m);
61 glm::vec3 PlayerController::ControlForce(const Entity &e, const EntityState &s) const {
62 return TargetVelocity(rotateY(move_dir * e.MaxVelocity(), s.yaw), s, 5.0f);
65 void PlayerController::TurnHead(float dp, float dy) noexcept {
66 player.GetEntity().TurnHead(dp, dy);
69 float PlayerController::GetPitch() const noexcept {
70 return player.GetEntity().Pitch();
73 float PlayerController::GetYaw() const noexcept {
74 return player.GetEntity().Yaw();
77 void PlayerController::SelectInventory(int i) noexcept {
78 player.SetInventorySlot(i);
81 int PlayerController::InventorySlot() const noexcept {
82 return player.GetInventorySlot();
85 void PlayerController::Invalidate() noexcept {
89 void PlayerController::UpdatePlayer() noexcept {
91 Ray aim = player.Aim();
92 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
93 aim_world = WorldCollision();
95 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), 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();
111 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
112 : PlayerController(world, player)
115 , remove_timer(0.25f) {
119 void DirectInput::Update(Entity &, float dt) {
120 Invalidate(); // world has changed in the meantime
123 remove_timer.Update(dt);
124 if (remove_timer.Hit()) {
128 place_timer.Update(dt);
129 if (place_timer.Hit()) {
134 void DirectInput::StartPrimaryAction() {
135 if (!remove_timer.Running()) {
137 remove_timer.Start();
141 void DirectInput::StopPrimaryAction() {
145 void DirectInput::StartSecondaryAction() {
146 if (!place_timer.Running()) {
152 void DirectInput::StopSecondaryAction() {
156 void DirectInput::StartTertiaryAction() {
160 void DirectInput::StopTertiaryAction() {
164 void DirectInput::PickBlock() {
166 if (!BlockFocus()) return;
167 SelectInventory(BlockFocus().GetBlock().type - 1);
170 void DirectInput::PlaceBlock() {
172 if (!BlockFocus()) return;
174 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
178 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
182 void DirectInput::RemoveBlock() {
184 if (!BlockFocus()) return;
185 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
190 HUD::HUD(Environment &env, Config &config, const Player &player)
196 , outline_transform(1.0f)
197 , outline_visible(false)
201 , block_transform(1.0f)
203 , block_visible(false)
212 , messages(env.assets.small_ui_font)
217 const float ls = env.assets.small_ui_font.LineSkip();
220 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
221 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
222 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
223 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
224 block_label.Position(
225 glm::vec3(50.0f, 85.0f, 0.0f),
229 block_label.Foreground(glm::vec4(1.0f));
230 block_label.Background(glm::vec4(0.5f));
233 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
234 counter_text.Foreground(glm::vec4(1.0f));
235 counter_text.Background(glm::vec4(0.5f));
236 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
237 position_text.Foreground(glm::vec4(1.0f));
238 position_text.Background(glm::vec4(0.5f));
239 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
240 orientation_text.Foreground(glm::vec4(1.0f));
241 orientation_text.Background(glm::vec4(0.5f));
242 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
243 block_text.Foreground(glm::vec4(1.0f));
244 block_text.Background(glm::vec4(0.5f));
245 block_text.Set(env.assets.small_ui_font, "Block: none");
246 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
247 entity_text.Foreground(glm::vec4(1.0f));
248 entity_text.Background(glm::vec4(0.5f));
249 entity_text.Set(env.assets.small_ui_font, "Entity: none");
252 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
253 messages.Foreground(glm::vec4(1.0f));
254 messages.Background(glm::vec4(0.5f));
257 PrimitiveMesh::Buffer buf;
258 buf.vertices = std::vector<glm::vec3>({
259 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
260 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
262 buf.indices = std::vector<PrimitiveMesh::Index>({
265 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
266 crosshair.Update(buf);
271 PrimitiveMesh::Buffer outl_buf;
275 void HUD::FocusBlock(const Chunk &chunk, int index) {
276 const Block &block = chunk.BlockAt(index);
277 const BlockType &type = chunk.Type(index);
279 type.OutlinePrimitiveMesh(outl_buf);
280 outline.Update(outl_buf);
281 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
282 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
283 outline_transform *= glm::scale(glm::vec3(1.005f));
284 outline_visible = true;
289 << ", face: " << block.GetFace()
290 << ", turn: " << block.GetTurn();
291 block_text.Set(env.assets.small_ui_font, s.str());
297 void HUD::FocusEntity(const Entity &entity) {
300 s << "Entity: " << entity.Name();
301 entity_text.Set(env.assets.small_ui_font, s.str());
307 void HUD::FocusNone() {
308 outline_visible = false;
313 void HUD::DisplayNone() {
314 block_visible = false;
317 void HUD::Display(const BlockType &type) {
319 type.FillEntityMesh(block_buf);
320 block.Update(block_buf);
322 block_label.Set(env.assets.small_ui_font, type.label);
324 block_visible = type.visible;
328 void HUD::UpdateDebug() {
334 void HUD::UpdateCounter() {
336 s << std::setprecision(3) <<
337 "avg: " << env.counter.Average().running << "ms, "
338 "peak: " << env.counter.Peak().running << "ms";
339 std::string text = s.str();
340 counter_text.Set(env.assets.small_ui_font, text);
343 void HUD::UpdatePosition() {
345 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
346 position_text.Set(env.assets.small_ui_font, s.str());
349 void HUD::UpdateOrientation() {
351 s << std::setprecision(3) << "pitch: " << rad2deg(player.GetEntity().Pitch())
352 << ", yaw: " << rad2deg(player.GetEntity().Yaw());
353 orientation_text.Set(env.assets.small_ui_font, s.str());
356 void HUD::PostMessage(const char *msg) {
357 messages.PushLine(msg);
360 std::cout << msg << std::endl;
364 void HUD::Update(int dt) {
365 msg_timer.Update(dt);
366 if (msg_timer.HitOnce()) {
370 if (config.video.debug) {
371 if (env.counter.Changed()) {
379 void HUD::Render(Viewport &viewport) noexcept {
381 if (outline_visible && config.video.world) {
382 PlainColor &outline_prog = viewport.WorldColorProgram();
383 outline_prog.SetM(outline_transform);
387 // clear depth buffer so everything renders above the world
388 viewport.ClearDepth();
390 if (config.video.hud) {
393 DirectionalLighting &world_prog = viewport.HUDProgram();
394 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
395 // disable distance fog
396 world_prog.SetFogDensity(0.0f);
398 viewport.DisableBlending();
399 world_prog.SetM(block_transform);
401 block_label.Render(viewport);
405 if (msg_keep || msg_timer.Running()) {
406 messages.Render(viewport);
410 PlainColor &outline_prog = viewport.HUDColorProgram();
411 viewport.EnableInvertBlending();
412 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
413 outline_prog.SetM(viewport.Cursor());
414 crosshair.DrawLines();
418 if (config.video.debug) {
419 counter_text.Render(viewport);
420 position_text.Render(viewport);
421 orientation_text.Render(viewport);
423 block_text.Render(viewport);
424 } else if (show_entity) {
425 entity_text.Render(viewport);
431 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
438 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
439 const BlockType &old_type = chunk.Type(index);
440 chunk.SetBlock(index, block);
441 const BlockType &new_type = chunk.Type(index);
442 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
443 if (new_type.id == 0) {
444 if (old_type.remove_sound >= 0) {
445 audio.Play(sounds[old_type.remove_sound], coords);
448 if (new_type.place_sound >= 0) {
449 audio.Play(sounds[new_type.place_sound], coords);
455 Interface::Interface(
457 const Keymap &keymap,
458 PlayerController &pc,
459 ClientController &cc)
472 void Interface::Lock() {
478 void Interface::Unlock() {
482 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
483 if (!config.input.keyboard) return;
485 Keymap::Action action = keymap.Lookup(event);
487 case Keymap::MOVE_FORWARD:
491 case Keymap::MOVE_BACKWARD:
495 case Keymap::MOVE_LEFT:
499 case Keymap::MOVE_RIGHT:
503 case Keymap::MOVE_UP:
507 case Keymap::MOVE_DOWN:
512 case Keymap::PRIMARY:
513 player_ctrl.StartPrimaryAction();
515 case Keymap::SECONDARY:
516 player_ctrl.StartSecondaryAction();
518 case Keymap::TERTIARY:
519 player_ctrl.StartTertiaryAction();
522 case Keymap::INV_NEXT:
525 case Keymap::INV_PREVIOUS:
538 InvAbs(action - Keymap::INV_1);
545 case Keymap::TOGGLE_AUDIO:
546 config.audio.enabled = !config.audio.enabled;
547 client_ctrl.SetAudio(config.audio.enabled);
549 case Keymap::TOGGLE_VIDEO:
550 config.video.world = !config.video.world;
551 client_ctrl.SetVideo(config.video.world);
553 case Keymap::TOGGLE_HUD:
554 config.video.hud = !config.video.hud;
555 client_ctrl.SetHUD(config.video.hud);
557 case Keymap::TOGGLE_DEBUG:
558 config.video.debug = !config.video.debug;
559 client_ctrl.SetDebug(config.video.debug);
567 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
568 if (!config.input.keyboard) return;
570 switch (keymap.Lookup(event)) {
571 case Keymap::MOVE_FORWARD:
575 case Keymap::MOVE_BACKWARD:
579 case Keymap::MOVE_LEFT:
583 case Keymap::MOVE_RIGHT:
587 case Keymap::MOVE_UP:
591 case Keymap::MOVE_DOWN:
596 case Keymap::PRIMARY:
597 player_ctrl.StopPrimaryAction();
599 case Keymap::SECONDARY:
600 player_ctrl.StopSecondaryAction();
602 case Keymap::TERTIARY:
603 player_ctrl.StopTertiaryAction();
611 void Interface::Handle(const SDL_MouseMotionEvent &event) {
612 if (locked || !config.input.mouse) return;
613 player_ctrl.TurnHead(
614 event.yrel * config.input.pitch_sensitivity,
615 event.xrel * config.input.yaw_sensitivity);
618 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
619 if (!config.input.mouse) return;
621 switch (event.button) {
622 case SDL_BUTTON_LEFT:
623 player_ctrl.StartPrimaryAction();
625 case SDL_BUTTON_RIGHT:
626 player_ctrl.StartSecondaryAction();
628 case SDL_BUTTON_MIDDLE:
629 player_ctrl.StartTertiaryAction();
634 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
635 if (!config.input.mouse) return;
637 switch (event.button) {
638 case SDL_BUTTON_LEFT:
639 player_ctrl.StopPrimaryAction();
641 case SDL_BUTTON_RIGHT:
642 player_ctrl.StopSecondaryAction();
644 case SDL_BUTTON_MIDDLE:
645 player_ctrl.StopTertiaryAction();
651 void Interface::Handle(const SDL_MouseWheelEvent &event) {
652 if (!config.input.mouse) return;
656 } else if (event.y > 0) {
661 void Interface::UpdateMovement() {
662 player_ctrl.SetMovement(glm::vec3(fwd - rev));
665 void Interface::InvAbs(int s) {
666 slot = s % num_slots;
670 player_ctrl.SelectInventory(slot);
673 void Interface::InvRel(int delta) {
674 InvAbs(slot + delta);
683 void Keymap::Map(SDL_Scancode scancode, Action action) {
684 if (scancode > MAX_SCANCODE) {
685 throw std::runtime_error("refusing to map scancode: too damn high");
687 codemap[scancode] = action;
690 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
691 if (scancode < NUM_SCANCODES) {
692 return codemap[scancode];
699 void Keymap::LoadDefault() {
700 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
701 Map(SDL_SCANCODE_W, MOVE_FORWARD);
702 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
703 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
704 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
705 Map(SDL_SCANCODE_A, MOVE_LEFT);
706 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
707 Map(SDL_SCANCODE_D, MOVE_RIGHT);
708 Map(SDL_SCANCODE_SPACE, MOVE_UP);
709 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
710 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
711 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
712 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
714 Map(SDL_SCANCODE_TAB, INV_NEXT);
715 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
716 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
717 Map(SDL_SCANCODE_1, INV_1);
718 Map(SDL_SCANCODE_2, INV_2);
719 Map(SDL_SCANCODE_3, INV_3);
720 Map(SDL_SCANCODE_4, INV_4);
721 Map(SDL_SCANCODE_5, INV_5);
722 Map(SDL_SCANCODE_6, INV_6);
723 Map(SDL_SCANCODE_7, INV_7);
724 Map(SDL_SCANCODE_8, INV_8);
725 Map(SDL_SCANCODE_9, INV_9);
726 Map(SDL_SCANCODE_0, INV_10);
728 Map(SDL_SCANCODE_INSERT, SECONDARY);
729 Map(SDL_SCANCODE_RETURN, SECONDARY);
730 Map(SDL_SCANCODE_MENU, TERTIARY);
731 Map(SDL_SCANCODE_DELETE, PRIMARY);
732 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
734 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
735 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
736 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
737 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
739 Map(SDL_SCANCODE_ESCAPE, EXIT);
743 void Keymap::Load(std::istream &is) {
744 TokenStreamReader in(is);
745 std::string key_name;
746 std::string action_name;
749 while (in.HasMore()) {
750 if (in.Peek().type == Token::STRING) {
751 in.ReadString(key_name);
752 key = SDL_GetScancodeFromName(key_name.c_str());
754 key = SDL_Scancode(in.GetInt());
756 in.Skip(Token::EQUALS);
757 in.ReadIdentifier(action_name);
758 action = StringToAction(action_name);
759 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
760 in.Skip(Token::SEMICOLON);
766 void Keymap::Save(std::ostream &out) {
767 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
768 if (codemap[i] == NONE) continue;
770 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
786 out << " = " << ActionToString(codemap[i]) << std::endl;;
793 std::map<std::string, Keymap::Action> action_map = {
794 { "none", Keymap::NONE },
795 { "move_forward", Keymap::MOVE_FORWARD },
796 { "move_backward", Keymap::MOVE_BACKWARD },
797 { "move_left", Keymap::MOVE_LEFT },
798 { "move_right", Keymap::MOVE_RIGHT },
799 { "move_up", Keymap::MOVE_UP },
800 { "move_down", Keymap::MOVE_DOWN },
802 { "primary", Keymap::PRIMARY },
803 { "secondary", Keymap::SECONDARY },
804 { "tertiary", Keymap::TERTIARY },
806 { "inventory_next", Keymap::INV_NEXT },
807 { "inventory_prev", Keymap::INV_PREVIOUS },
808 { "inventory_1", Keymap::INV_1 },
809 { "inventory_2", Keymap::INV_2 },
810 { "inventory_3", Keymap::INV_3 },
811 { "inventory_4", Keymap::INV_4 },
812 { "inventory_5", Keymap::INV_5 },
813 { "inventory_6", Keymap::INV_6 },
814 { "inventory_7", Keymap::INV_7 },
815 { "inventory_8", Keymap::INV_8 },
816 { "inventory_9", Keymap::INV_9 },
817 { "inventory_10", Keymap::INV_10 },
819 { "toggle_audio", Keymap::TOGGLE_AUDIO },
820 { "toggle_video", Keymap::TOGGLE_VIDEO },
821 { "toggle_hud", Keymap::TOGGLE_HUD },
822 { "toggle_debug", Keymap::TOGGLE_DEBUG },
824 { "exit", Keymap::EXIT },
829 const char *Keymap::ActionToString(Action action) {
830 for (const auto &entry : action_map) {
831 if (action == entry.second) {
832 return entry.first.c_str();
838 Keymap::Action Keymap::StringToAction(const std::string &str) {
839 auto entry = action_map.find(str);
840 if (entry != action_map.end()) {
841 return entry->second;
843 std::cerr << "unknown action \"" << str << '"' << std::endl;