]> git.localhorst.tv Git - blank.git/blob - src/ui/ui.cpp
move steering behaviours into entity
[blank.git] / src / ui / ui.cpp
1 #include "ClientController.hpp"
2 #include "DirectInput.hpp"
3 #include "HUD.hpp"
4 #include "InteractiveManipulator.hpp"
5 #include "Interface.hpp"
6 #include "Keymap.hpp"
7 #include "PlayerController.hpp"
8
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"
25
26 #include <algorithm>
27 #include <cmath>
28 #include <iostream>
29 #include <map>
30 #include <sstream>
31 #include <glm/gtc/matrix_transform.hpp>
32 #include <glm/gtx/rotate_vector.hpp>
33 #include <glm/gtx/io.hpp>
34
35
36 namespace blank {
37
38 PlayerController::PlayerController(World &world, Player &player)
39 : world(world)
40 , player(player)
41 , move_dir(0.0f)
42 , dirty(true)
43 , aim_world()
44 , aim_entity() {
45         player.GetEntity().SetController(*this);
46         player.GetEntity().GetSteering().SetAcceleration(5.0f);
47 }
48
49 PlayerController::~PlayerController() {
50         if (&player.GetEntity().GetController() == this) {
51                 player.GetEntity().UnsetController();
52         }
53 }
54
55 void PlayerController::SetMovement(const glm::vec3 &m) noexcept {
56         if (dot(m, m) > 1.0f) {
57                 move_dir = normalize(m);
58         } else {
59                 move_dir = m;
60         }
61         Invalidate();
62 }
63
64 void PlayerController::TurnHead(float dp, float dy) noexcept {
65         player.GetEntity().TurnHead(dp, dy);
66 }
67
68 float PlayerController::GetPitch() const noexcept {
69         return player.GetEntity().Pitch();
70 }
71
72 float PlayerController::GetYaw() const noexcept {
73         return player.GetEntity().Yaw();
74 }
75
76 void PlayerController::SelectInventory(int i) noexcept {
77         player.SetInventorySlot(i);
78 }
79
80 int PlayerController::InventorySlot() const noexcept {
81         return player.GetInventorySlot();
82 }
83
84 void PlayerController::Invalidate() noexcept {
85         dirty = true;
86 }
87
88 void PlayerController::UpdatePlayer() noexcept {
89         if (dirty) {
90                 Ray aim = player.Aim();
91                 Entity &entity = player.GetEntity();
92                 if (!world.Intersection(aim, entity.ChunkCoords(), aim_world)) {
93                         aim_world = WorldCollision();
94                 }
95                 if (!world.Intersection(aim, entity, aim_entity)) {
96                         aim_entity = EntityCollision();
97                 }
98                 if (aim_world && aim_entity) {
99                         // got both, pick the closest one
100                         if (aim_world.depth < aim_entity.depth) {
101                                 // FIXME: somehow this can get stuck on an entity?
102                                 aim_entity = EntityCollision();
103                         } else {
104                                 aim_world = WorldCollision();
105                         }
106                 }
107                 Steering &steering = entity.GetSteering();
108                 if (!iszero(move_dir)) {
109                         // scale input by max velocity, apply yaw, and transform to world space
110                         steering.SetTargetVelocity(glm::vec3(
111                                 glm::vec4(rotateY(move_dir * entity.MaxVelocity(), entity.Yaw()), 0.0f)
112                                 * transpose(entity.Transform())
113                         ));
114                         steering.Enable(Steering::TARGET_VELOCITY);
115                         steering.Disable(Steering::HALT);
116                 } else {
117                         // target velocity of 0 is the same as halt
118                         steering.Enable(Steering::HALT);
119                         steering.Disable(Steering::TARGET_VELOCITY);
120                 }
121                 dirty = false;
122         }
123 }
124
125
126 DirectInput::DirectInput(World &world, Player &player, WorldManipulator &manip)
127 : PlayerController(world, player)
128 , manip(manip)
129 , place_timer(0.25f)
130 , remove_timer(0.25f) {
131
132 }
133
134 void DirectInput::Update(Entity &, float dt) {
135         Invalidate(); // world has changed in the meantime
136         UpdatePlayer();
137
138         remove_timer.Update(dt);
139         if (remove_timer.Hit()) {
140                 RemoveBlock();
141         }
142
143         place_timer.Update(dt);
144         if (place_timer.Hit()) {
145                 PlaceBlock();
146         }
147 }
148
149 void DirectInput::StartPrimaryAction() {
150         if (!remove_timer.Running()) {
151                 RemoveBlock();
152                 remove_timer.Start();
153         }
154 }
155
156 void DirectInput::StopPrimaryAction() {
157         remove_timer.Stop();
158 }
159
160 void DirectInput::StartSecondaryAction() {
161         if (!place_timer.Running()) {
162                 PlaceBlock();
163                 place_timer.Start();
164         }
165 }
166
167 void DirectInput::StopSecondaryAction() {
168         place_timer.Stop();
169 }
170
171 void DirectInput::StartTertiaryAction() {
172         PickBlock();
173 }
174
175 void DirectInput::StopTertiaryAction() {
176         // nothing
177 }
178
179 void DirectInput::PickBlock() {
180         UpdatePlayer();
181         if (!BlockFocus()) return;
182         SelectInventory(BlockFocus().GetBlock().type - 1);
183 }
184
185 void DirectInput::PlaceBlock() {
186         UpdatePlayer();
187         if (!BlockFocus()) return;
188
189         BlockLookup next_block(BlockFocus().chunk, BlockFocus().BlockPos(), Block::NormalFace(BlockFocus().normal));
190         if (!next_block) {
191                 return;
192         }
193         manip.SetBlock(next_block.GetChunk(), next_block.GetBlockIndex(), Block(InventorySlot() + 1));
194         Invalidate();
195 }
196
197 void DirectInput::RemoveBlock() {
198         UpdatePlayer();
199         if (!BlockFocus()) return;
200         manip.SetBlock(BlockFocus().GetChunk(), BlockFocus().block, Block(0));
201         Invalidate();
202 }
203
204
205 HUD::HUD(Environment &env, Config &config, const Player &player)
206 : env(env)
207 , config(config)
208 , player(player)
209 // block focus
210 , outline()
211 , outline_transform(1.0f)
212 , outline_visible(false)
213 // "inventory"
214 , block()
215 , block_buf()
216 , block_transform(1.0f)
217 , block_label()
218 , block_visible(false)
219 // debug overlay
220 , counter_text()
221 , position_text()
222 , orientation_text()
223 , block_text()
224 , show_block(false)
225 , show_entity(false)
226 // net stats
227 , bandwidth_text()
228 , rtt_text()
229 , packet_loss_text()
230 , show_net(false)
231 // message box
232 , messages(env.assets.small_ui_font)
233 , msg_timer(5000)
234 , msg_keep(false)
235 // crosshair
236 , crosshair() {
237         const float ls = env.assets.small_ui_font.LineSkip();
238
239         // "inventory"
240         block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
241         block_transform = glm::scale(block_transform, glm::vec3(50.0f));
242         block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
243         block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
244         block_label.Position(
245                 glm::vec3(50.0f, 85.0f, 0.0f),
246                 Gravity::NORTH_WEST,
247                 Gravity::NORTH
248         );
249         block_label.Foreground(glm::vec4(1.0f));
250         block_label.Background(glm::vec4(0.5f));
251
252         // debug overlay
253         counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
254         counter_text.Foreground(glm::vec4(1.0f));
255         counter_text.Background(glm::vec4(0.5f));
256         position_text.Position(glm::vec3(-25.0f, 25.0f + ls, 0.0f), Gravity::NORTH_EAST);
257         position_text.Foreground(glm::vec4(1.0f));
258         position_text.Background(glm::vec4(0.5f));
259         orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * ls, 0.0f), Gravity::NORTH_EAST);
260         orientation_text.Foreground(glm::vec4(1.0f));
261         orientation_text.Background(glm::vec4(0.5f));
262         block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
263         block_text.Foreground(glm::vec4(1.0f));
264         block_text.Background(glm::vec4(0.5f));
265         block_text.Set(env.assets.small_ui_font, "Block: none");
266         entity_text.Position(glm::vec3(-25.0f, 25.0f + 4 * ls, 0.0f), Gravity::NORTH_EAST);
267         entity_text.Foreground(glm::vec4(1.0f));
268         entity_text.Background(glm::vec4(0.5f));
269         entity_text.Set(env.assets.small_ui_font, "Entity: none");
270
271         // net stats
272         bandwidth_text.Position(glm::vec3(-25.0f, 25.0f + 6 * ls, 0.0f), Gravity::NORTH_EAST);
273         bandwidth_text.Foreground(glm::vec4(1.0f));
274         bandwidth_text.Background(glm::vec4(0.5f));
275         bandwidth_text.Set(env.assets.small_ui_font, "TX: 0.0KB/s RX: 0.0KB/s");
276         rtt_text.Position(glm::vec3(-25.0f, 25.0f + 7 * ls, 0.0f), Gravity::NORTH_EAST);
277         rtt_text.Foreground(glm::vec4(1.0f));
278         rtt_text.Background(glm::vec4(0.5f));
279         rtt_text.Set(env.assets.small_ui_font, "RTT: unavailable");
280         packet_loss_text.Position(glm::vec3(-25.0f, 25.0f + 8 * ls, 0.0f), Gravity::NORTH_EAST);
281         packet_loss_text.Foreground(glm::vec4(1.0f));
282         packet_loss_text.Background(glm::vec4(0.5f));
283         packet_loss_text.Set(env.assets.small_ui_font, "Packet loss: 0.0%");
284
285         // message box
286         messages.Position(glm::vec3(25.0f, -25.0f - 2 * ls, 0.0f), Gravity::SOUTH_WEST);
287         messages.Foreground(glm::vec4(1.0f));
288         messages.Background(glm::vec4(0.5f));
289
290         // crosshair
291         PrimitiveMesh::Buffer buf;
292         buf.vertices = std::vector<glm::vec3>({
293                 { -10.0f,   0.0f, 0.0f }, { 10.0f,  0.0f, 0.0f },
294                 {   0.0f, -10.0f, 0.0f }, {  0.0f, 10.0f, 0.0f },
295         });
296         buf.indices = std::vector<PrimitiveMesh::Index>({
297                 0, 1, 2, 3
298         });
299         buf.colors.resize(4, { 10.0f, 10.0f, 10.0f, 1.0f });
300         crosshair.Update(buf);
301 }
302
303 namespace {
304
305 PrimitiveMesh::Buffer outl_buf;
306
307 }
308
309 void HUD::FocusBlock(const Chunk &chunk, int index) {
310         const Block &block = chunk.BlockAt(index);
311         const BlockType &type = chunk.Type(index);
312         outl_buf.Clear();
313         type.OutlinePrimitiveMesh(outl_buf);
314         outline.Update(outl_buf);
315         outline_transform = chunk.Transform(player.GetEntity().ChunkCoords());
316         outline_transform *= chunk.ToTransform(Chunk::ToPos(index), index);
317         outline_transform *= glm::scale(glm::vec3(1.005f));
318         outline_visible = true;
319         {
320                 std::stringstream s;
321                 s << "Block: "
322                         << type.label
323                         << ", face: " << block.GetFace()
324                         << ", turn: " << block.GetTurn();
325                 block_text.Set(env.assets.small_ui_font, s.str());
326         }
327         show_block = true;
328         show_entity = false;
329 }
330
331 void HUD::FocusEntity(const Entity &entity) {
332         {
333                 std::stringstream s;
334                 s << "Entity: " << entity.Name();
335                 entity_text.Set(env.assets.small_ui_font, s.str());
336         }
337         show_block = false;
338         show_entity = true;
339 }
340
341 void HUD::FocusNone() {
342         outline_visible = false;
343         show_block = false;
344         show_entity = false;
345 }
346
347 void HUD::DisplayNone() {
348         block_visible = false;
349 }
350
351 void HUD::Display(const BlockType &type) {
352         block_buf.Clear();
353         type.FillEntityMesh(block_buf);
354         block.Update(block_buf);
355
356         block_label.Set(env.assets.small_ui_font, type.label);
357
358         block_visible = type.visible;
359 }
360
361
362 void HUD::UpdateDebug() {
363         UpdateCounter();
364         UpdatePosition();
365         UpdateOrientation();
366 }
367
368 void HUD::UpdateCounter() {
369         std::stringstream s;
370         s << std::setprecision(3) <<
371                 "avg: " << env.counter.Average().running << "ms, "
372                 "peak: " << env.counter.Peak().running << "ms";
373         std::string text = s.str();
374         counter_text.Set(env.assets.small_ui_font, text);
375 }
376
377 void HUD::UpdatePosition() {
378         std::stringstream s;
379         s << std::setprecision(3) << "pos: " << player.GetEntity().AbsolutePosition();
380         position_text.Set(env.assets.small_ui_font, s.str());
381 }
382
383 void HUD::UpdateOrientation() {
384         std::stringstream s;
385         s << std::setprecision(3) << "pitch: " << glm::degrees(player.GetEntity().Pitch())
386                 << ", yaw: " << glm::degrees(player.GetEntity().Yaw());
387         orientation_text.Set(env.assets.small_ui_font, s.str());
388 }
389
390 void HUD::PostMessage(const char *msg) {
391         messages.PushLine(msg);
392         msg_timer.Reset();
393         msg_timer.Start();
394         std::cout << msg << std::endl;
395 }
396
397
398 void HUD::UpdateNetStats(const CongestionControl &stat) {
399         if (!config.video.debug) return;
400
401         std::stringstream s;
402         s << std::fixed << std::setprecision(1)
403                 << "TX: " << stat.Upstream()
404                 << "KB/s, RX: " << stat.Downstream() << "KB/s";
405         bandwidth_text.Set(env.assets.small_ui_font, s.str());
406
407         s.str("");
408         s << "RTT: " << stat.RoundTripTime() << "ms";
409         rtt_text.Set(env.assets.small_ui_font, s.str());
410
411         s.str("");
412         s << "Packet loss: " << (stat.PacketLoss() * 100.0f) << "%";
413         packet_loss_text.Set(env.assets.small_ui_font, s.str());
414
415         show_net = true;
416 }
417
418
419 void HUD::Update(int dt) {
420         msg_timer.Update(dt);
421         if (msg_timer.HitOnce()) {
422                 msg_timer.Stop();
423         }
424
425         if (config.video.debug) {
426                 if (env.counter.Changed()) {
427                         UpdateCounter();
428                 }
429                 UpdatePosition();
430                 UpdateOrientation();
431         }
432 }
433
434 void HUD::Render(Viewport &viewport) noexcept {
435         // block focus
436         if (outline_visible && config.video.world) {
437                 PlainColor &outline_prog = viewport.WorldColorProgram();
438                 outline_prog.SetM(outline_transform);
439                 outline.DrawLines();
440         }
441
442         // clear depth buffer so everything renders above the world
443         viewport.ClearDepth();
444
445         if (config.video.hud) {
446                 // "inventory"
447                 if (block_visible) {
448                         DirectionalLighting &world_prog = viewport.HUDProgram();
449                         world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
450                         world_prog.SetLightColor({ 1.0f, 1.0f, 1.0f });
451                         world_prog.SetAmbientColor({ 0.1f, 0.1f, 0.1f });
452                         // disable distance fog
453                         world_prog.SetFogDensity(0.0f);
454
455                         viewport.DisableBlending();
456                         world_prog.SetM(block_transform);
457                         block.Draw();
458                         block_label.Render(viewport);
459                 }
460
461                 // message box
462                 if (msg_keep || msg_timer.Running()) {
463                         messages.Render(viewport);
464                 }
465
466                 // crosshair
467                 PlainColor &outline_prog = viewport.HUDColorProgram();
468                 viewport.EnableInvertBlending();
469                 viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
470                 outline_prog.SetM(viewport.Cursor());
471                 crosshair.DrawLines();
472         }
473
474         // debug overlay
475         if (config.video.debug) {
476                 counter_text.Render(viewport);
477                 position_text.Render(viewport);
478                 orientation_text.Render(viewport);
479                 if (show_block) {
480                         block_text.Render(viewport);
481                 } else if (show_entity) {
482                         entity_text.Render(viewport);
483                 }
484                 if (show_net) {
485                         bandwidth_text.Render(viewport);
486                         rtt_text.Render(viewport);
487                         packet_loss_text.Render(viewport);
488                 }
489         }
490 }
491
492
493 InteractiveManipulator::InteractiveManipulator(Audio &audio, const SoundBank &sounds, Entity &player)
494 : player(player)
495 , audio(audio)
496 , sounds(sounds) {
497
498 }
499
500 void InteractiveManipulator::SetBlock(Chunk &chunk, int index, const Block &block) {
501         const BlockType &old_type = chunk.Type(index);
502         chunk.SetBlock(index, block);
503         const BlockType &new_type = chunk.Type(index);
504         glm::vec3 coords = chunk.ToSceneCoords(player.ChunkCoords(), Chunk::ToCoords(index));
505         if (new_type.id == 0) {
506                 if (old_type.remove_sound >= 0) {
507                         audio.Play(sounds[old_type.remove_sound], coords);
508                 }
509         } else {
510                 if (new_type.place_sound >= 0) {
511                         audio.Play(sounds[new_type.place_sound], coords);
512                 }
513         }
514 }
515
516
517 Interface::Interface(
518         Config &config,
519         const Keymap &keymap,
520         PlayerController &pc,
521         ClientController &cc)
522 : config(config)
523 , keymap(keymap)
524 , player_ctrl(pc)
525 , client_ctrl(cc)
526 , fwd(0)
527 , rev(0)
528 , num_slots(10)
529 , locked(false) {
530
531 }
532
533 void Interface::Lock() {
534         fwd = glm::ivec3(0);
535         rev = glm::ivec3(0);
536         locked = true;
537 }
538
539 void Interface::Unlock() {
540         locked = false;
541 }
542
543 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
544         if (!config.input.keyboard) return;
545
546         Keymap::Action action = keymap.Lookup(event);
547         switch (action) {
548                 case Keymap::MOVE_FORWARD:
549                         rev.z = 1;
550                         UpdateMovement();
551                         break;
552                 case Keymap::MOVE_BACKWARD:
553                         fwd.z = 1;
554                         UpdateMovement();
555                         break;
556                 case Keymap::MOVE_LEFT:
557                         rev.x = 1;
558                         UpdateMovement();
559                         break;
560                 case Keymap::MOVE_RIGHT:
561                         fwd.x = 1;
562                         UpdateMovement();
563                         break;
564                 case Keymap::MOVE_UP:
565                         fwd.y = 1;
566                         UpdateMovement();
567                         break;
568                 case Keymap::MOVE_DOWN:
569                         rev.y = 1;
570                         UpdateMovement();
571                         break;
572
573                 case Keymap::PRIMARY:
574                         player_ctrl.StartPrimaryAction();
575                         break;
576                 case Keymap::SECONDARY:
577                         player_ctrl.StartSecondaryAction();
578                         break;
579                 case Keymap::TERTIARY:
580                         player_ctrl.StartTertiaryAction();
581                         break;
582
583                 case Keymap::INV_NEXT:
584                         InvRel(1);
585                         break;
586                 case Keymap::INV_PREVIOUS:
587                         InvRel(-1);
588                         break;
589                 case Keymap::INV_1:
590                 case Keymap::INV_2:
591                 case Keymap::INV_3:
592                 case Keymap::INV_4:
593                 case Keymap::INV_5:
594                 case Keymap::INV_6:
595                 case Keymap::INV_7:
596                 case Keymap::INV_8:
597                 case Keymap::INV_9:
598                 case Keymap::INV_10:
599                         InvAbs(action - Keymap::INV_1);
600                         break;
601
602                 case Keymap::EXIT:
603                         client_ctrl.Exit();
604                         break;
605
606                 case Keymap::TOGGLE_AUDIO:
607                         client_ctrl.SetAudio(!config.audio.enabled);
608                         break;
609                 case Keymap::TOGGLE_VIDEO:
610                         client_ctrl.SetVideo(!config.video.world);
611                         break;
612                 case Keymap::TOGGLE_HUD:
613                         client_ctrl.SetHUD(!config.video.hud);
614                         break;
615                 case Keymap::TOGGLE_DEBUG:
616                         client_ctrl.SetDebug(!config.video.debug);
617                         break;
618                 case Keymap::CAMERA_NEXT:
619                         client_ctrl.NextCamera();
620                         break;
621
622                 default:
623                         break;
624         }
625 }
626
627 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
628         if (!config.input.keyboard) return;
629
630         switch (keymap.Lookup(event)) {
631                 case Keymap::MOVE_FORWARD:
632                         rev.z = 0;
633                         UpdateMovement();
634                         break;
635                 case Keymap::MOVE_BACKWARD:
636                         fwd.z = 0;
637                         UpdateMovement();
638                         break;
639                 case Keymap::MOVE_LEFT:
640                         rev.x = 0;
641                         UpdateMovement();
642                         break;
643                 case Keymap::MOVE_RIGHT:
644                         fwd.x = 0;
645                         UpdateMovement();
646                         break;
647                 case Keymap::MOVE_UP:
648                         fwd.y = 0;
649                         UpdateMovement();
650                         break;
651                 case Keymap::MOVE_DOWN:
652                         rev.y = 0;
653                         UpdateMovement();
654                         break;
655
656                 case Keymap::PRIMARY:
657                         player_ctrl.StopPrimaryAction();
658                         break;
659                 case Keymap::SECONDARY:
660                         player_ctrl.StopSecondaryAction();
661                         break;
662                 case Keymap::TERTIARY:
663                         player_ctrl.StopTertiaryAction();
664                         break;
665
666                 default:
667                         break;
668         }
669 }
670
671 void Interface::Handle(const SDL_MouseMotionEvent &event) {
672         if (locked || !config.input.mouse) return;
673         player_ctrl.TurnHead(
674                 event.yrel * config.input.pitch_sensitivity,
675                 event.xrel * config.input.yaw_sensitivity);
676 }
677
678 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
679         if (!config.input.mouse) return;
680
681         switch (event.button) {
682                 case SDL_BUTTON_LEFT:
683                         player_ctrl.StartPrimaryAction();
684                         break;
685                 case SDL_BUTTON_RIGHT:
686                         player_ctrl.StartSecondaryAction();
687                         break;
688                 case SDL_BUTTON_MIDDLE:
689                         player_ctrl.StartTertiaryAction();
690                         break;
691         }
692 }
693
694 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
695         if (!config.input.mouse) return;
696
697         switch (event.button) {
698                 case SDL_BUTTON_LEFT:
699                         player_ctrl.StopPrimaryAction();
700                         break;
701                 case SDL_BUTTON_RIGHT:
702                         player_ctrl.StopSecondaryAction();
703                         break;
704                 case SDL_BUTTON_MIDDLE:
705                         player_ctrl.StopTertiaryAction();
706                         break;
707         }
708 }
709
710
711 void Interface::Handle(const SDL_MouseWheelEvent &event) {
712         if (!config.input.mouse) return;
713
714         if (event.y < 0) {
715                 InvRel(1);
716         } else if (event.y > 0) {
717                 InvRel(-1);
718         }
719 }
720
721 void Interface::UpdateMovement() {
722         player_ctrl.SetMovement(glm::vec3(fwd - rev));
723 }
724
725 void Interface::InvAbs(int s) {
726         int slot = s % num_slots;
727         while (slot < 0) {
728                 slot += num_slots;
729         }
730         player_ctrl.SelectInventory(slot);
731 }
732
733 void Interface::InvRel(int delta) {
734         InvAbs(player_ctrl.GetPlayer().GetInventorySlot() + delta);
735 }
736
737
738 Keymap::Keymap()
739 : codemap{ NONE } {
740
741 }
742
743 void Keymap::Map(SDL_Scancode scancode, Action action) {
744         if (scancode > MAX_SCANCODE) {
745                 throw std::runtime_error("refusing to map scancode: too damn high");
746         }
747         codemap[scancode] = action;
748 }
749
750 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
751         if (scancode < NUM_SCANCODES) {
752                 return codemap[scancode];
753         } else {
754                 return NONE;
755         }
756 }
757
758
759 void Keymap::LoadDefault() {
760         Map(SDL_SCANCODE_UP, MOVE_FORWARD);
761         Map(SDL_SCANCODE_W, MOVE_FORWARD);
762         Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
763         Map(SDL_SCANCODE_S, MOVE_BACKWARD);
764         Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
765         Map(SDL_SCANCODE_A, MOVE_LEFT);
766         Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
767         Map(SDL_SCANCODE_D, MOVE_RIGHT);
768         Map(SDL_SCANCODE_SPACE, MOVE_UP);
769         Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
770         Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
771         Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
772         Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
773
774         Map(SDL_SCANCODE_TAB, INV_NEXT);
775         Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
776         Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
777         Map(SDL_SCANCODE_1, INV_1);
778         Map(SDL_SCANCODE_2, INV_2);
779         Map(SDL_SCANCODE_3, INV_3);
780         Map(SDL_SCANCODE_4, INV_4);
781         Map(SDL_SCANCODE_5, INV_5);
782         Map(SDL_SCANCODE_6, INV_6);
783         Map(SDL_SCANCODE_7, INV_7);
784         Map(SDL_SCANCODE_8, INV_8);
785         Map(SDL_SCANCODE_9, INV_9);
786         Map(SDL_SCANCODE_0, INV_10);
787
788         Map(SDL_SCANCODE_INSERT, SECONDARY);
789         Map(SDL_SCANCODE_MENU, TERTIARY);
790         Map(SDL_SCANCODE_DELETE, PRIMARY);
791         Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
792
793         Map(SDL_SCANCODE_F1, TOGGLE_HUD);
794         Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
795         Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
796         Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
797         Map(SDL_SCANCODE_F5, CAMERA_NEXT);
798
799         Map(SDL_SCANCODE_ESCAPE, EXIT);
800 }
801
802
803 void Keymap::Load(std::istream &is) {
804         TokenStreamReader in(is);
805         std::string key_name;
806         std::string action_name;
807         SDL_Scancode key;
808         Action action;
809         while (in.HasMore()) {
810                 if (in.Peek().type == Token::STRING) {
811                         in.ReadString(key_name);
812                         key = SDL_GetScancodeFromName(key_name.c_str());
813                 } else {
814                         key = SDL_Scancode(in.GetInt());
815                 }
816                 in.Skip(Token::EQUALS);
817                 in.ReadIdentifier(action_name);
818                 action = StringToAction(action_name);
819                 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
820                         in.Skip(Token::SEMICOLON);
821                 }
822                 Map(key, action);
823         }
824 }
825
826 void Keymap::Save(std::ostream &out) {
827         for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
828                 if (codemap[i] == NONE) continue;
829
830                 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
831                 if (str && *str) {
832                         out << '"';
833                         while (*str) {
834                                 if (*str == '"') {
835                                         out << "\\\"";
836                                 } else {
837                                         out << *str;
838                                 }
839                                 ++str;
840                         }
841                         out << '"';
842                 } else {
843                         out << i;
844                 }
845
846                 out << " = " << ActionToString(codemap[i]) << std::endl;;
847         }
848 }
849
850
851 namespace {
852
853 std::map<std::string, Keymap::Action> action_map = {
854         { "none", Keymap::NONE },
855         { "move_forward", Keymap::MOVE_FORWARD },
856         { "move_backward", Keymap::MOVE_BACKWARD },
857         { "move_left", Keymap::MOVE_LEFT },
858         { "move_right", Keymap::MOVE_RIGHT },
859         { "move_up", Keymap::MOVE_UP },
860         { "move_down", Keymap::MOVE_DOWN },
861
862         { "primary", Keymap::PRIMARY },
863         { "secondary", Keymap::SECONDARY },
864         { "tertiary", Keymap::TERTIARY },
865
866         { "inventory_next", Keymap::INV_NEXT },
867         { "inventory_prev", Keymap::INV_PREVIOUS },
868         { "inventory_1", Keymap::INV_1 },
869         { "inventory_2", Keymap::INV_2 },
870         { "inventory_3", Keymap::INV_3 },
871         { "inventory_4", Keymap::INV_4 },
872         { "inventory_5", Keymap::INV_5 },
873         { "inventory_6", Keymap::INV_6 },
874         { "inventory_7", Keymap::INV_7 },
875         { "inventory_8", Keymap::INV_8 },
876         { "inventory_9", Keymap::INV_9 },
877         { "inventory_10", Keymap::INV_10 },
878
879         { "toggle_audio", Keymap::TOGGLE_AUDIO },
880         { "toggle_video", Keymap::TOGGLE_VIDEO },
881         { "toggle_hud", Keymap::TOGGLE_HUD },
882         { "toggle_debug", Keymap::TOGGLE_DEBUG },
883         { "camera_next", Keymap::CAMERA_NEXT },
884
885         { "exit", Keymap::EXIT },
886 };
887
888 }
889
890 const char *Keymap::ActionToString(Action action) {
891         for (const auto &entry : action_map) {
892                 if (action == entry.second) {
893                         return entry.first.c_str();
894                 }
895         }
896         return "none";
897 }
898
899 Keymap::Action Keymap::StringToAction(const std::string &str) {
900         auto entry = action_map.find(str);
901         if (entry != action_map.end()) {
902                 return entry->second;
903         } else {
904                 std::cerr << "unknown action \"" << str << '"' << std::endl;
905                 return NONE;
906         }
907 }
908
909 }