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