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