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)
46 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
47 if (dot(m, m) > 1.0f) {
48 move_dir = normalize(m);
55 void PlayerController::TurnHead(float dp, float dy) noexcept {
56 player.GetEntity().TurnHead(dp, dy);
59 float PlayerController::GetPitch() const noexcept {
60 return player.GetEntity().Pitch();
63 float PlayerController::GetYaw() const noexcept {
64 return player.GetEntity().Yaw();
67 void PlayerController::SelectInventory(int i) noexcept {
68 player.SetInventorySlot(i);
71 int PlayerController::InventorySlot() const noexcept {
72 return player.GetInventorySlot();
75 void PlayerController::Invalidate() noexcept {
79 void PlayerController::UpdatePlayer() noexcept {
80 constexpr float max_vel = 5.0f; // in m/s
82 player.GetEntity().TargetVelocity(glm::rotateY(move_dir * max_vel, player.GetEntity().Yaw()));
84 Ray aim = player.Aim();
85 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
86 aim_world = WorldCollision();
88 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), aim_entity)) {
89 aim_entity = EntityCollision();
91 if (aim_world && aim_entity) {
92 // got both, pick the closest one
93 if (aim_world.depth < aim_entity.depth) {
94 aim_entity = EntityCollision();
96 aim_world = WorldCollision();
104 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
105 : PlayerController(world, player)
108 , remove_timer(256) {
112 void DirectInput::Update(int dt) {
113 Invalidate(); // world has changed in the meantime
116 remove_timer.Update(dt);
117 if (remove_timer.Hit()) {
121 place_timer.Update(dt);
122 if (place_timer.Hit()) {
127 void DirectInput::StartPrimaryAction() {
128 if (!remove_timer.Running()) {
130 remove_timer.Start();
134 void DirectInput::StopPrimaryAction() {
138 void DirectInput::StartSecondaryAction() {
139 if (!place_timer.Running()) {
145 void DirectInput::StopSecondaryAction() {
149 void DirectInput::StartTertiaryAction() {
153 void DirectInput::StopTertiaryAction() {
157 void DirectInput::PickBlock() {
159 if (!BlockFocus()) return;
160 SelectInventory(BlockFocus().GetBlock().type - 1);
163 void DirectInput::PlaceBlock() {
165 if (!BlockFocus()) return;
167 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
171 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
175 void DirectInput::RemoveBlock() {
177 if (!BlockFocus()) return;
178 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
183 HUD::HUD(Environment &env, Config &config, const Player &player)
189 , outline_transform(1.0f)
190 , outline_visible(false)
194 , block_transform(1.0f)
196 , block_visible(false)
205 , messages(env.assets.small_ui_font)
210 const float ls = env.assets.small_ui_font.LineSkip();
213 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
214 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
215 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
216 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
217 block_label.Position(
218 glm::vec3(50.0f, 85.0f, 0.0f),
222 block_label.Foreground(glm::vec4(1.0f));
223 block_label.Background(glm::vec4(0.5f));
226 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
227 counter_text.Foreground(glm::vec4(1.0f));
228 counter_text.Background(glm::vec4(0.5f));
229 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
230 position_text.Foreground(glm::vec4(1.0f));
231 position_text.Background(glm::vec4(0.5f));
232 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
233 orientation_text.Foreground(glm::vec4(1.0f));
234 orientation_text.Background(glm::vec4(0.5f));
235 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
236 block_text.Foreground(glm::vec4(1.0f));
237 block_text.Background(glm::vec4(0.5f));
238 block_text.Set(env.assets.small_ui_font, "Block: none");
239 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
240 entity_text.Foreground(glm::vec4(1.0f));
241 entity_text.Background(glm::vec4(0.5f));
242 entity_text.Set(env.assets.small_ui_font, "Entity: none");
245 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
246 messages.Foreground(glm::vec4(1.0f));
247 messages.Background(glm::vec4(0.5f));
250 PrimitiveMesh::Buffer buf;
251 buf.vertices = std::vector<glm::vec3>({
252 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
253 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
255 buf.indices = std::vector<PrimitiveMesh::Index>({
258 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
259 crosshair.Update(buf);
264 PrimitiveMesh::Buffer outl_buf;
268 void HUD::FocusBlock(const Chunk &chunk, int index) {
269 const Block &block = chunk.BlockAt(index);
270 const BlockType &type = chunk.Type(index);
272 type.OutlinePrimitiveMesh(outl_buf);
273 outline.Update(outl_buf);
274 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
275 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
276 outline_transform *= glm::scale(glm::vec3(1.005f));
277 outline_visible = true;
282 << ", face: " << block.GetFace()
283 << ", turn: " << block.GetTurn();
284 block_text.Set(env.assets.small_ui_font, s.str());
290 void HUD::FocusEntity(const Entity &entity) {
293 s << "Entity: " << entity.Name();
294 entity_text.Set(env.assets.small_ui_font, s.str());
300 void HUD::FocusNone() {
301 outline_visible = false;
306 void HUD::DisplayNone() {
307 block_visible = false;
310 void HUD::Display(const BlockType &type) {
312 type.FillEntityMesh(block_buf);
313 block.Update(block_buf);
315 block_label.Set(env.assets.small_ui_font, type.label);
317 block_visible = type.visible;
321 void HUD::UpdateDebug() {
327 void HUD::UpdateCounter() {
329 s << std::setprecision(3) <<
330 "avg: " << env.counter.Average().running << "ms, "
331 "peak: " << env.counter.Peak().running << "ms";
332 std::string text = s.str();
333 counter_text.Set(env.assets.small_ui_font, text);
336 void HUD::UpdatePosition() {
338 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
339 position_text.Set(env.assets.small_ui_font, s.str());
342 void HUD::UpdateOrientation() {
343 //std::stringstream s;
344 //s << std::setprecision(3) << "pitch: " << rad2deg(ctrl.Pitch())
345 // << ", yaw: " << rad2deg(ctrl.Yaw());
346 //orientation_text.Set(env.assets.small_ui_font, s.str());
349 void HUD::PostMessage(const char *msg) {
350 messages.PushLine(msg);
353 std::cout << msg << std::endl;
357 void HUD::Update(int dt) {
358 msg_timer.Update(dt);
359 if (msg_timer.HitOnce()) {
363 if (config.video.debug) {
364 if (env.counter.Changed()) {
372 void HUD::Render(Viewport &viewport) noexcept {
374 if (outline_visible && config.video.world) {
375 PlainColor &outline_prog = viewport.WorldColorProgram();
376 outline_prog.SetM(outline_transform);
380 // clear depth buffer so everything renders above the world
381 viewport.ClearDepth();
383 if (config.video.hud) {
386 DirectionalLighting &world_prog = viewport.HUDProgram();
387 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
388 // disable distance fog
389 world_prog.SetFogDensity(0.0f);
391 viewport.DisableBlending();
392 world_prog.SetM(block_transform);
394 block_label.Render(viewport);
398 if (msg_keep || msg_timer.Running()) {
399 messages.Render(viewport);
403 PlainColor &outline_prog = viewport.HUDColorProgram();
404 viewport.EnableInvertBlending();
405 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
406 outline_prog.SetM(viewport.Cursor());
407 crosshair.DrawLines();
411 if (config.video.debug) {
412 counter_text.Render(viewport);
413 position_text.Render(viewport);
414 orientation_text.Render(viewport);
416 block_text.Render(viewport);
417 } else if (show_entity) {
418 entity_text.Render(viewport);
424 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
431 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
432 const BlockType &old_type = chunk.Type(index);
433 chunk.SetBlock(index, block);
434 const BlockType &new_type = chunk.Type(index);
435 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
436 if (new_type.id == 0) {
437 if (old_type.remove_sound >= 0) {
438 audio.Play(sounds[old_type.remove_sound], coords);
441 if (new_type.place_sound >= 0) {
442 audio.Play(sounds[new_type.place_sound], coords);
448 Interface::Interface(
450 const Keymap &keymap,
451 PlayerController &pc,
452 ClientController &cc)
465 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
466 if (!config.input.keyboard) return;
468 Keymap::Action action = keymap.Lookup(event);
470 case Keymap::MOVE_FORWARD:
474 case Keymap::MOVE_BACKWARD:
478 case Keymap::MOVE_LEFT:
482 case Keymap::MOVE_RIGHT:
486 case Keymap::MOVE_UP:
490 case Keymap::MOVE_DOWN:
495 case Keymap::PRIMARY:
496 player_ctrl.StartPrimaryAction();
498 case Keymap::SECONDARY:
499 player_ctrl.StartSecondaryAction();
501 case Keymap::TERTIARY:
502 player_ctrl.StartTertiaryAction();
505 case Keymap::INV_NEXT:
508 case Keymap::INV_PREVIOUS:
521 InvAbs(action - Keymap::INV_1);
528 case Keymap::TOGGLE_AUDIO:
529 config.audio.enabled = !config.audio.enabled;
530 client_ctrl.SetAudio(config.audio.enabled);
532 case Keymap::TOGGLE_VIDEO:
533 config.video.world = !config.video.world;
534 client_ctrl.SetVideo(config.video.world);
536 case Keymap::TOGGLE_HUD:
537 config.video.hud = !config.video.hud;
538 client_ctrl.SetHUD(config.video.hud);
540 case Keymap::TOGGLE_DEBUG:
541 config.video.debug = !config.video.debug;
542 client_ctrl.SetDebug(config.video.debug);
550 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
551 if (!config.input.keyboard) return;
553 switch (keymap.Lookup(event)) {
554 case Keymap::MOVE_FORWARD:
558 case Keymap::MOVE_BACKWARD:
562 case Keymap::MOVE_LEFT:
566 case Keymap::MOVE_RIGHT:
570 case Keymap::MOVE_UP:
574 case Keymap::MOVE_DOWN:
579 case Keymap::PRIMARY:
580 player_ctrl.StopPrimaryAction();
582 case Keymap::SECONDARY:
583 player_ctrl.StopSecondaryAction();
585 case Keymap::TERTIARY:
586 player_ctrl.StopTertiaryAction();
594 void Interface::Handle(const SDL_MouseMotionEvent &event) {
595 if (!config.input.mouse) return;
596 player_ctrl.TurnHead(
597 event.yrel * config.input.pitch_sensitivity,
598 event.xrel * config.input.yaw_sensitivity);
601 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
602 if (!config.input.mouse) return;
604 switch (event.button) {
605 case SDL_BUTTON_LEFT:
606 player_ctrl.StartPrimaryAction();
608 case SDL_BUTTON_RIGHT:
609 player_ctrl.StartSecondaryAction();
611 case SDL_BUTTON_MIDDLE:
612 player_ctrl.StartTertiaryAction();
617 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
618 if (!config.input.mouse) return;
620 switch (event.button) {
621 case SDL_BUTTON_LEFT:
622 player_ctrl.StopPrimaryAction();
624 case SDL_BUTTON_RIGHT:
625 player_ctrl.StopSecondaryAction();
627 case SDL_BUTTON_MIDDLE:
628 player_ctrl.StopTertiaryAction();
634 void Interface::Handle(const SDL_MouseWheelEvent &event) {
635 if (!config.input.mouse) return;
639 } else if (event.y > 0) {
644 void Interface::UpdateMovement() {
645 player_ctrl.SetMovement(glm::vec3(fwd - rev));
648 void Interface::InvAbs(int s) {
649 slot = s % num_slots;
653 player_ctrl.SelectInventory(slot);
656 void Interface::InvRel(int delta) {
657 InvAbs(slot + delta);
666 void Keymap::Map(SDL_Scancode scancode, Action action) {
667 if (scancode > MAX_SCANCODE) {
668 throw std::runtime_error("refusing to map scancode: too damn high");
670 codemap[scancode] = action;
673 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
674 if (scancode < NUM_SCANCODES) {
675 return codemap[scancode];
682 void Keymap::LoadDefault() {
683 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
684 Map(SDL_SCANCODE_W, MOVE_FORWARD);
685 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
686 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
687 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
688 Map(SDL_SCANCODE_A, MOVE_LEFT);
689 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
690 Map(SDL_SCANCODE_D, MOVE_RIGHT);
691 Map(SDL_SCANCODE_SPACE, MOVE_UP);
692 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
693 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
694 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
695 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
697 Map(SDL_SCANCODE_TAB, INV_NEXT);
698 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
699 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
700 Map(SDL_SCANCODE_1, INV_1);
701 Map(SDL_SCANCODE_2, INV_2);
702 Map(SDL_SCANCODE_3, INV_3);
703 Map(SDL_SCANCODE_4, INV_4);
704 Map(SDL_SCANCODE_5, INV_5);
705 Map(SDL_SCANCODE_6, INV_6);
706 Map(SDL_SCANCODE_7, INV_7);
707 Map(SDL_SCANCODE_8, INV_8);
708 Map(SDL_SCANCODE_9, INV_9);
709 Map(SDL_SCANCODE_0, INV_10);
711 Map(SDL_SCANCODE_INSERT, SECONDARY);
712 Map(SDL_SCANCODE_RETURN, SECONDARY);
713 Map(SDL_SCANCODE_MENU, TERTIARY);
714 Map(SDL_SCANCODE_DELETE, PRIMARY);
715 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
717 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
718 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
719 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
720 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
722 Map(SDL_SCANCODE_ESCAPE, EXIT);
726 void Keymap::Load(std::istream &is) {
727 TokenStreamReader in(is);
728 std::string key_name;
729 std::string action_name;
732 while (in.HasMore()) {
733 if (in.Peek().type == Token::STRING) {
734 in.ReadString(key_name);
735 key = SDL_GetScancodeFromName(key_name.c_str());
737 key = SDL_Scancode(in.GetInt());
739 in.Skip(Token::EQUALS);
740 in.ReadIdentifier(action_name);
741 action = StringToAction(action_name);
742 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
743 in.Skip(Token::SEMICOLON);
749 void Keymap::Save(std::ostream &out) {
750 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
751 if (codemap[i] == NONE) continue;
753 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
769 out << " = " << ActionToString(codemap[i]) << std::endl;;
776 std::map<std::string, Keymap::Action> action_map = {
777 { "none", Keymap::NONE },
778 { "move_forward", Keymap::MOVE_FORWARD },
779 { "move_backward", Keymap::MOVE_BACKWARD },
780 { "move_left", Keymap::MOVE_LEFT },
781 { "move_right", Keymap::MOVE_RIGHT },
782 { "move_up", Keymap::MOVE_UP },
783 { "move_down", Keymap::MOVE_DOWN },
785 { "primary", Keymap::PRIMARY },
786 { "secondary", Keymap::SECONDARY },
787 { "tertiary", Keymap::TERTIARY },
789 { "inventory_next", Keymap::INV_NEXT },
790 { "inventory_prev", Keymap::INV_PREVIOUS },
791 { "inventory_1", Keymap::INV_1 },
792 { "inventory_2", Keymap::INV_2 },
793 { "inventory_3", Keymap::INV_3 },
794 { "inventory_4", Keymap::INV_4 },
795 { "inventory_5", Keymap::INV_5 },
796 { "inventory_6", Keymap::INV_6 },
797 { "inventory_7", Keymap::INV_7 },
798 { "inventory_8", Keymap::INV_8 },
799 { "inventory_9", Keymap::INV_9 },
800 { "inventory_10", Keymap::INV_10 },
802 { "toggle_audio", Keymap::TOGGLE_AUDIO },
803 { "toggle_video", Keymap::TOGGLE_VIDEO },
804 { "toggle_hud", Keymap::TOGGLE_HUD },
805 { "toggle_debug", Keymap::TOGGLE_DEBUG },
807 { "exit", Keymap::EXIT },
812 const char *Keymap::ActionToString(Action action) {
813 for (const auto &entry : action_map) {
814 if (action == entry.second) {
815 return entry.first.c_str();
821 Keymap::Action Keymap::StringToAction(const std::string &str) {
822 auto entry = action_map.find(str);
823 if (entry != action_map.end()) {
824 return entry->second;
826 std::cerr << "unknown action \"" << str << '"' << std::endl;