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 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
47 if (dot(m, m) > 1.0f) {
48 move_dir = normalize(m);
55 glm::vec3 PlayerController::ControlForce(const EntityState &s) const {
56 glm::vec3 target(rotateY(move_dir * player.GetEntity().MaxVelocity(), s.yaw) - s.velocity);
57 return target * player.GetEntity().MaxControlForce();
60 void PlayerController::TurnHead(float dp, float dy) noexcept {
61 player.GetEntity().TurnHead(dp, dy);
64 float PlayerController::GetPitch() const noexcept {
65 return player.GetEntity().Pitch();
68 float PlayerController::GetYaw() const noexcept {
69 return player.GetEntity().Yaw();
72 void PlayerController::SelectInventory(int i) noexcept {
73 player.SetInventorySlot(i);
76 int PlayerController::InventorySlot() const noexcept {
77 return player.GetInventorySlot();
80 void PlayerController::Invalidate() noexcept {
84 void PlayerController::UpdatePlayer() noexcept {
86 Ray aim = player.Aim();
87 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity().ChunkCoords(), aim_world)) {
88 aim_world = WorldCollision();
90 if (!world.Intersection(aim, glm::mat4(1.0f), player.GetEntity(), aim_entity)) {
91 aim_entity = EntityCollision();
93 if (aim_world && aim_entity) {
94 // got both, pick the closest one
95 if (aim_world.depth < aim_entity.depth) {
96 aim_entity = EntityCollision();
98 aim_world = WorldCollision();
106 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
107 : PlayerController(world, player)
110 , remove_timer(0.25f) {
114 void DirectInput::Update(Entity &, float dt) {
115 Invalidate(); // world has changed in the meantime
118 remove_timer.Update(dt);
119 if (remove_timer.Hit()) {
123 place_timer.Update(dt);
124 if (place_timer.Hit()) {
129 void DirectInput::StartPrimaryAction() {
130 if (!remove_timer.Running()) {
132 remove_timer.Start();
136 void DirectInput::StopPrimaryAction() {
140 void DirectInput::StartSecondaryAction() {
141 if (!place_timer.Running()) {
147 void DirectInput::StopSecondaryAction() {
151 void DirectInput::StartTertiaryAction() {
155 void DirectInput::StopTertiaryAction() {
159 void DirectInput::PickBlock() {
161 if (!BlockFocus()) return;
162 SelectInventory(BlockFocus().GetBlock().type - 1);
165 void DirectInput::PlaceBlock() {
167 if (!BlockFocus()) return;
169 BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
173 manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
177 void DirectInput::RemoveBlock() {
179 if (!BlockFocus()) return;
180 manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
185 HUD::HUD(Environment &env, Config &config, const Player &player)
191 , outline_transform(1.0f)
192 , outline_visible(false)
196 , block_transform(1.0f)
198 , block_visible(false)
207 , messages(env.assets.small_ui_font)
212 const float ls = env.assets.small_ui_font.LineSkip();
215 block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
216 block_transform = glm::scale(block_transform, glm::vec3(50.0f));
217 block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
218 block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
219 block_label.Position(
220 glm::vec3(50.0f, 85.0f, 0.0f),
224 block_label.Foreground(glm::vec4(1.0f));
225 block_label.Background(glm::vec4(0.5f));
228 counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
229 counter_text.Foreground(glm::vec4(1.0f));
230 counter_text.Background(glm::vec4(0.5f));
231 position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
232 position_text.Foreground(glm::vec4(1.0f));
233 position_text.Background(glm::vec4(0.5f));
234 orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
235 orientation_text.Foreground(glm::vec4(1.0f));
236 orientation_text.Background(glm::vec4(0.5f));
237 block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
238 block_text.Foreground(glm::vec4(1.0f));
239 block_text.Background(glm::vec4(0.5f));
240 block_text.Set(env.assets.small_ui_font, "Block: none");
241 entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
242 entity_text.Foreground(glm::vec4(1.0f));
243 entity_text.Background(glm::vec4(0.5f));
244 entity_text.Set(env.assets.small_ui_font, "Entity: none");
247 messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
248 messages.Foreground(glm::vec4(1.0f));
249 messages.Background(glm::vec4(0.5f));
252 PrimitiveMesh::Buffer buf;
253 buf.vertices = std::vector<glm::vec3>({
254 { -10.0f, 0.0f, 0.0f }, { 10.0f, 0.0f, 0.0f },
255 { 0.0f, -10.0f, 0.0f }, { 0.0f, 10.0f, 0.0f },
257 buf.indices = std::vector<PrimitiveMesh::Index>({
260 buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
261 crosshair.Update(buf);
266 PrimitiveMesh::Buffer outl_buf;
270 void HUD::FocusBlock(const Chunk &chunk, int index) {
271 const Block &block = chunk.BlockAt(index);
272 const BlockType &type = chunk.Type(index);
274 type.OutlinePrimitiveMesh(outl_buf);
275 outline.Update(outl_buf);
276 outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
277 outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
278 outline_transform *= glm::scale(glm::vec3(1.005f));
279 outline_visible = true;
284 << ", face: " << block.GetFace()
285 << ", turn: " << block.GetTurn();
286 block_text.Set(env.assets.small_ui_font, s.str());
292 void HUD::FocusEntity(const Entity &entity) {
295 s << "Entity: " << entity.Name();
296 entity_text.Set(env.assets.small_ui_font, s.str());
302 void HUD::FocusNone() {
303 outline_visible = false;
308 void HUD::DisplayNone() {
309 block_visible = false;
312 void HUD::Display(const BlockType &type) {
314 type.FillEntityMesh(block_buf);
315 block.Update(block_buf);
317 block_label.Set(env.assets.small_ui_font, type.label);
319 block_visible = type.visible;
323 void HUD::UpdateDebug() {
329 void HUD::UpdateCounter() {
331 s << std::setprecision(3) <<
332 "avg: " << env.counter.Average().running << "ms, "
333 "peak: " << env.counter.Peak().running << "ms";
334 std::string text = s.str();
335 counter_text.Set(env.assets.small_ui_font, text);
338 void HUD::UpdatePosition() {
340 s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
341 position_text.Set(env.assets.small_ui_font, s.str());
344 void HUD::UpdateOrientation() {
345 //std::stringstream s;
346 //s << std::setprecision(3) << "pitch: " << rad2deg(ctrl.Pitch())
347 // << ", yaw: " << rad2deg(ctrl.Yaw());
348 //orientation_text.Set(env.assets.small_ui_font, s.str());
351 void HUD::PostMessage(const char *msg) {
352 messages.PushLine(msg);
355 std::cout << msg << std::endl;
359 void HUD::Update(int dt) {
360 msg_timer.Update(dt);
361 if (msg_timer.HitOnce()) {
365 if (config.video.debug) {
366 if (env.counter.Changed()) {
374 void HUD::Render(Viewport &viewport) noexcept {
376 if (outline_visible && config.video.world) {
377 PlainColor &outline_prog = viewport.WorldColorProgram();
378 outline_prog.SetM(outline_transform);
382 // clear depth buffer so everything renders above the world
383 viewport.ClearDepth();
385 if (config.video.hud) {
388 DirectionalLighting &world_prog = viewport.HUDProgram();
389 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
390 // disable distance fog
391 world_prog.SetFogDensity(0.0f);
393 viewport.DisableBlending();
394 world_prog.SetM(block_transform);
396 block_label.Render(viewport);
400 if (msg_keep || msg_timer.Running()) {
401 messages.Render(viewport);
405 PlainColor &outline_prog = viewport.HUDColorProgram();
406 viewport.EnableInvertBlending();
407 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
408 outline_prog.SetM(viewport.Cursor());
409 crosshair.DrawLines();
413 if (config.video.debug) {
414 counter_text.Render(viewport);
415 position_text.Render(viewport);
416 orientation_text.Render(viewport);
418 block_text.Render(viewport);
419 } else if (show_entity) {
420 entity_text.Render(viewport);
426 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
433 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
434 const BlockType &old_type = chunk.Type(index);
435 chunk.SetBlock(index, block);
436 const BlockType &new_type = chunk.Type(index);
437 glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
438 if (new_type.id == 0) {
439 if (old_type.remove_sound >= 0) {
440 audio.Play(sounds[old_type.remove_sound], coords);
443 if (new_type.place_sound >= 0) {
444 audio.Play(sounds[new_type.place_sound], coords);
450 Interface::Interface(
452 const Keymap &keymap,
453 PlayerController &pc,
454 ClientController &cc)
467 void Interface::Lock() {
473 void Interface::Unlock() {
477 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
478 if (!config.input.keyboard) return;
480 Keymap::Action action = keymap.Lookup(event);
482 case Keymap::MOVE_FORWARD:
486 case Keymap::MOVE_BACKWARD:
490 case Keymap::MOVE_LEFT:
494 case Keymap::MOVE_RIGHT:
498 case Keymap::MOVE_UP:
502 case Keymap::MOVE_DOWN:
507 case Keymap::PRIMARY:
508 player_ctrl.StartPrimaryAction();
510 case Keymap::SECONDARY:
511 player_ctrl.StartSecondaryAction();
513 case Keymap::TERTIARY:
514 player_ctrl.StartTertiaryAction();
517 case Keymap::INV_NEXT:
520 case Keymap::INV_PREVIOUS:
533 InvAbs(action - Keymap::INV_1);
540 case Keymap::TOGGLE_AUDIO:
541 config.audio.enabled = !config.audio.enabled;
542 client_ctrl.SetAudio(config.audio.enabled);
544 case Keymap::TOGGLE_VIDEO:
545 config.video.world = !config.video.world;
546 client_ctrl.SetVideo(config.video.world);
548 case Keymap::TOGGLE_HUD:
549 config.video.hud = !config.video.hud;
550 client_ctrl.SetHUD(config.video.hud);
552 case Keymap::TOGGLE_DEBUG:
553 config.video.debug = !config.video.debug;
554 client_ctrl.SetDebug(config.video.debug);
562 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
563 if (!config.input.keyboard) return;
565 switch (keymap.Lookup(event)) {
566 case Keymap::MOVE_FORWARD:
570 case Keymap::MOVE_BACKWARD:
574 case Keymap::MOVE_LEFT:
578 case Keymap::MOVE_RIGHT:
582 case Keymap::MOVE_UP:
586 case Keymap::MOVE_DOWN:
591 case Keymap::PRIMARY:
592 player_ctrl.StopPrimaryAction();
594 case Keymap::SECONDARY:
595 player_ctrl.StopSecondaryAction();
597 case Keymap::TERTIARY:
598 player_ctrl.StopTertiaryAction();
606 void Interface::Handle(const SDL_MouseMotionEvent &event) {
607 if (locked || !config.input.mouse) return;
608 player_ctrl.TurnHead(
609 event.yrel * config.input.pitch_sensitivity,
610 event.xrel * config.input.yaw_sensitivity);
613 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
614 if (!config.input.mouse) return;
616 switch (event.button) {
617 case SDL_BUTTON_LEFT:
618 player_ctrl.StartPrimaryAction();
620 case SDL_BUTTON_RIGHT:
621 player_ctrl.StartSecondaryAction();
623 case SDL_BUTTON_MIDDLE:
624 player_ctrl.StartTertiaryAction();
629 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
630 if (!config.input.mouse) return;
632 switch (event.button) {
633 case SDL_BUTTON_LEFT:
634 player_ctrl.StopPrimaryAction();
636 case SDL_BUTTON_RIGHT:
637 player_ctrl.StopSecondaryAction();
639 case SDL_BUTTON_MIDDLE:
640 player_ctrl.StopTertiaryAction();
646 void Interface::Handle(const SDL_MouseWheelEvent &event) {
647 if (!config.input.mouse) return;
651 } else if (event.y > 0) {
656 void Interface::UpdateMovement() {
657 player_ctrl.SetMovement(glm::vec3(fwd - rev));
660 void Interface::InvAbs(int s) {
661 slot = s % num_slots;
665 player_ctrl.SelectInventory(slot);
668 void Interface::InvRel(int delta) {
669 InvAbs(slot + delta);
678 void Keymap::Map(SDL_Scancode scancode, Action action) {
679 if (scancode > MAX_SCANCODE) {
680 throw std::runtime_error("refusing to map scancode: too damn high");
682 codemap[scancode] = action;
685 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
686 if (scancode < NUM_SCANCODES) {
687 return codemap[scancode];
694 void Keymap::LoadDefault() {
695 Map(SDL_SCANCODE_UP, MOVE_FORWARD);
696 Map(SDL_SCANCODE_W, MOVE_FORWARD);
697 Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
698 Map(SDL_SCANCODE_S, MOVE_BACKWARD);
699 Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
700 Map(SDL_SCANCODE_A, MOVE_LEFT);
701 Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
702 Map(SDL_SCANCODE_D, MOVE_RIGHT);
703 Map(SDL_SCANCODE_SPACE, MOVE_UP);
704 Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
705 Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
706 Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
707 Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
709 Map(SDL_SCANCODE_TAB, INV_NEXT);
710 Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
711 Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
712 Map(SDL_SCANCODE_1, INV_1);
713 Map(SDL_SCANCODE_2, INV_2);
714 Map(SDL_SCANCODE_3, INV_3);
715 Map(SDL_SCANCODE_4, INV_4);
716 Map(SDL_SCANCODE_5, INV_5);
717 Map(SDL_SCANCODE_6, INV_6);
718 Map(SDL_SCANCODE_7, INV_7);
719 Map(SDL_SCANCODE_8, INV_8);
720 Map(SDL_SCANCODE_9, INV_9);
721 Map(SDL_SCANCODE_0, INV_10);
723 Map(SDL_SCANCODE_INSERT, SECONDARY);
724 Map(SDL_SCANCODE_RETURN, SECONDARY);
725 Map(SDL_SCANCODE_MENU, TERTIARY);
726 Map(SDL_SCANCODE_DELETE, PRIMARY);
727 Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
729 Map(SDL_SCANCODE_F1, TOGGLE_HUD);
730 Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
731 Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
732 Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
734 Map(SDL_SCANCODE_ESCAPE, EXIT);
738 void Keymap::Load(std::istream &is) {
739 TokenStreamReader in(is);
740 std::string key_name;
741 std::string action_name;
744 while (in.HasMore()) {
745 if (in.Peek().type == Token::STRING) {
746 in.ReadString(key_name);
747 key = SDL_GetScancodeFromName(key_name.c_str());
749 key = SDL_Scancode(in.GetInt());
751 in.Skip(Token::EQUALS);
752 in.ReadIdentifier(action_name);
753 action = StringToAction(action_name);
754 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
755 in.Skip(Token::SEMICOLON);
761 void Keymap::Save(std::ostream &out) {
762 for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
763 if (codemap[i] == NONE) continue;
765 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
781 out << " = " << ActionToString(codemap[i]) << std::endl;;
788 std::map<std::string, Keymap::Action> action_map = {
789 { "none", Keymap::NONE },
790 { "move_forward", Keymap::MOVE_FORWARD },
791 { "move_backward", Keymap::MOVE_BACKWARD },
792 { "move_left", Keymap::MOVE_LEFT },
793 { "move_right", Keymap::MOVE_RIGHT },
794 { "move_up", Keymap::MOVE_UP },
795 { "move_down", Keymap::MOVE_DOWN },
797 { "primary", Keymap::PRIMARY },
798 { "secondary", Keymap::SECONDARY },
799 { "tertiary", Keymap::TERTIARY },
801 { "inventory_next", Keymap::INV_NEXT },
802 { "inventory_prev", Keymap::INV_PREVIOUS },
803 { "inventory_1", Keymap::INV_1 },
804 { "inventory_2", Keymap::INV_2 },
805 { "inventory_3", Keymap::INV_3 },
806 { "inventory_4", Keymap::INV_4 },
807 { "inventory_5", Keymap::INV_5 },
808 { "inventory_6", Keymap::INV_6 },
809 { "inventory_7", Keymap::INV_7 },
810 { "inventory_8", Keymap::INV_8 },
811 { "inventory_9", Keymap::INV_9 },
812 { "inventory_10", Keymap::INV_10 },
814 { "toggle_audio", Keymap::TOGGLE_AUDIO },
815 { "toggle_video", Keymap::TOGGLE_VIDEO },
816 { "toggle_hud", Keymap::TOGGLE_HUD },
817 { "toggle_debug", Keymap::TOGGLE_DEBUG },
819 { "exit", Keymap::EXIT },
824 const char *Keymap::ActionToString(Action action) {
825 for (const auto &entry : action_map) {
826 if (action == entry.second) {
827 return entry.first.c_str();
833 Keymap::Action Keymap::StringToAction(const std::string &str) {
834 auto entry = action_map.find(str);
835 if (entry != action_map.end()) {
836 return entry->second;
838 std::cerr << "unknown action \"" << str << '"' << std::endl;