]> git.localhorst.tv Git - blank.git/blob - src/ui/ui.cpp
treat head pitch and yaw as entity state
[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
462 }
463
464
465 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
466         if (!config.input.keyboard) return;
467
468         Keymap::Action action = keymap.Lookup(event);
469         switch (action) {
470                 case Keymap::MOVE_FORWARD:
471                         rev.z = 1;
472                         UpdateMovement();
473                         break;
474                 case Keymap::MOVE_BACKWARD:
475                         fwd.z = 1;
476                         UpdateMovement();
477                         break;
478                 case Keymap::MOVE_LEFT:
479                         rev.x = 1;
480                         UpdateMovement();
481                         break;
482                 case Keymap::MOVE_RIGHT:
483                         fwd.x = 1;
484                         UpdateMovement();
485                         break;
486                 case Keymap::MOVE_UP:
487                         fwd.y = 1;
488                         UpdateMovement();
489                         break;
490                 case Keymap::MOVE_DOWN:
491                         rev.y = 1;
492                         UpdateMovement();
493                         break;
494
495                 case Keymap::PRIMARY:
496                         player_ctrl.StartPrimaryAction();
497                         break;
498                 case Keymap::SECONDARY:
499                         player_ctrl.StartSecondaryAction();
500                         break;
501                 case Keymap::TERTIARY:
502                         player_ctrl.StartTertiaryAction();
503                         break;
504
505                 case Keymap::INV_NEXT:
506                         InvRel(1);
507                         break;
508                 case Keymap::INV_PREVIOUS:
509                         InvRel(-1);
510                         break;
511                 case Keymap::INV_1:
512                 case Keymap::INV_2:
513                 case Keymap::INV_3:
514                 case Keymap::INV_4:
515                 case Keymap::INV_5:
516                 case Keymap::INV_6:
517                 case Keymap::INV_7:
518                 case Keymap::INV_8:
519                 case Keymap::INV_9:
520                 case Keymap::INV_10:
521                         InvAbs(action - Keymap::INV_1);
522                         break;
523
524                 case Keymap::EXIT:
525                         client_ctrl.Exit();
526                         break;
527
528                 case Keymap::TOGGLE_AUDIO:
529                         config.audio.enabled = !config.audio.enabled;
530                         client_ctrl.SetAudio(config.audio.enabled);
531                         break;
532                 case Keymap::TOGGLE_VIDEO:
533                         config.video.world = !config.video.world;
534                         client_ctrl.SetVideo(config.video.world);
535                         break;
536                 case Keymap::TOGGLE_HUD:
537                         config.video.hud = !config.video.hud;
538                         client_ctrl.SetHUD(config.video.hud);
539                         break;
540                 case Keymap::TOGGLE_DEBUG:
541                         config.video.debug = !config.video.debug;
542                         client_ctrl.SetDebug(config.video.debug);
543                         break;
544
545                 default:
546                         break;
547         }
548 }
549
550 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
551         if (!config.input.keyboard) return;
552
553         switch (keymap.Lookup(event)) {
554                 case Keymap::MOVE_FORWARD:
555                         rev.z = 0;
556                         UpdateMovement();
557                         break;
558                 case Keymap::MOVE_BACKWARD:
559                         fwd.z = 0;
560                         UpdateMovement();
561                         break;
562                 case Keymap::MOVE_LEFT:
563                         rev.x = 0;
564                         UpdateMovement();
565                         break;
566                 case Keymap::MOVE_RIGHT:
567                         fwd.x = 0;
568                         UpdateMovement();
569                         break;
570                 case Keymap::MOVE_UP:
571                         fwd.y = 0;
572                         UpdateMovement();
573                         break;
574                 case Keymap::MOVE_DOWN:
575                         rev.y = 0;
576                         UpdateMovement();
577                         break;
578
579                 case Keymap::PRIMARY:
580                         player_ctrl.StopPrimaryAction();
581                         break;
582                 case Keymap::SECONDARY:
583                         player_ctrl.StopSecondaryAction();
584                         break;
585                 case Keymap::TERTIARY:
586                         player_ctrl.StopTertiaryAction();
587                         break;
588
589                 default:
590                         break;
591         }
592 }
593
594 void Interface::Handle(const SDL_MouseMotionEvent &event) {
595         if (!config.input.mouse) return;
596         player_ctrl.TurnHead(
597                 event.yrel * config.input.pitch_sensitivity,
598                 event.xrel * config.input.yaw_sensitivity);
599 }
600
601 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
602         if (!config.input.mouse) return;
603
604         switch (event.button) {
605                 case SDL_BUTTON_LEFT:
606                         player_ctrl.StartPrimaryAction();
607                         break;
608                 case SDL_BUTTON_RIGHT:
609                         player_ctrl.StartSecondaryAction();
610                         break;
611                 case SDL_BUTTON_MIDDLE:
612                         player_ctrl.StartTertiaryAction();
613                         break;
614         }
615 }
616
617 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
618         if (!config.input.mouse) return;
619
620         switch (event.button) {
621                 case SDL_BUTTON_LEFT:
622                         player_ctrl.StopPrimaryAction();
623                         break;
624                 case SDL_BUTTON_RIGHT:
625                         player_ctrl.StopSecondaryAction();
626                         break;
627                 case SDL_BUTTON_MIDDLE:
628                         player_ctrl.StopTertiaryAction();
629                         break;
630         }
631 }
632
633
634 void Interface::Handle(const SDL_MouseWheelEvent &event) {
635         if (!config.input.mouse) return;
636
637         if (event.y < 0) {
638                 InvRel(1);
639         } else if (event.y > 0) {
640                 InvRel(-1);
641         }
642 }
643
644 void Interface::UpdateMovement() {
645         player_ctrl.SetMovement(glm::vec3(fwd - rev));
646 }
647
648 void Interface::InvAbs(int s) {
649         slot = s % num_slots;
650         while (slot < 0) {
651                 slot += num_slots;
652         }
653         player_ctrl.SelectInventory(slot);
654 }
655
656 void Interface::InvRel(int delta) {
657         InvAbs(slot + delta);
658 }
659
660
661 Keymap::Keymap()
662 : codemap{ NONE } {
663
664 }
665
666 void Keymap::Map(SDL_Scancode scancode, Action action) {
667         if (scancode > MAX_SCANCODE) {
668                 throw std::runtime_error("refusing to map scancode: too damn high");
669         }
670         codemap[scancode] = action;
671 }
672
673 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) const {
674         if (scancode < NUM_SCANCODES) {
675                 return codemap[scancode];
676         } else {
677                 return NONE;
678         }
679 }
680
681
682 void Keymap::LoadDefault() {
683         Map(SDL_SCANCODE_UP, MOVE_FORWARD);
684         Map(SDL_SCANCODE_W, MOVE_FORWARD);
685         Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
686         Map(SDL_SCANCODE_S, MOVE_BACKWARD);
687         Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
688         Map(SDL_SCANCODE_A, MOVE_LEFT);
689         Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
690         Map(SDL_SCANCODE_D, MOVE_RIGHT);
691         Map(SDL_SCANCODE_SPACE, MOVE_UP);
692         Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
693         Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
694         Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
695         Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
696
697         Map(SDL_SCANCODE_TAB, INV_NEXT);
698         Map(SDL_SCANCODE_RIGHTBRACKET, INV_NEXT);
699         Map(SDL_SCANCODE_LEFTBRACKET, INV_PREVIOUS);
700         Map(SDL_SCANCODE_1, INV_1);
701         Map(SDL_SCANCODE_2, INV_2);
702         Map(SDL_SCANCODE_3, INV_3);
703         Map(SDL_SCANCODE_4, INV_4);
704         Map(SDL_SCANCODE_5, INV_5);
705         Map(SDL_SCANCODE_6, INV_6);
706         Map(SDL_SCANCODE_7, INV_7);
707         Map(SDL_SCANCODE_8, INV_8);
708         Map(SDL_SCANCODE_9, INV_9);
709         Map(SDL_SCANCODE_0, INV_10);
710
711         Map(SDL_SCANCODE_INSERT, SECONDARY);
712         Map(SDL_SCANCODE_RETURN, SECONDARY);
713         Map(SDL_SCANCODE_MENU, TERTIARY);
714         Map(SDL_SCANCODE_DELETE, PRIMARY);
715         Map(SDL_SCANCODE_BACKSPACE, PRIMARY);
716
717         Map(SDL_SCANCODE_F1, TOGGLE_HUD);
718         Map(SDL_SCANCODE_F2, TOGGLE_VIDEO);
719         Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
720         Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
721
722         Map(SDL_SCANCODE_ESCAPE, EXIT);
723 }
724
725
726 void Keymap::Load(std::istream &is) {
727         TokenStreamReader in(is);
728         std::string key_name;
729         std::string action_name;
730         SDL_Scancode key;
731         Action action;
732         while (in.HasMore()) {
733                 if (in.Peek().type == Token::STRING) {
734                         in.ReadString(key_name);
735                         key = SDL_GetScancodeFromName(key_name.c_str());
736                 } else {
737                         key = SDL_Scancode(in.GetInt());
738                 }
739                 in.Skip(Token::EQUALS);
740                 in.ReadIdentifier(action_name);
741                 action = StringToAction(action_name);
742                 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
743                         in.Skip(Token::SEMICOLON);
744                 }
745                 Map(key, action);
746         }
747 }
748
749 void Keymap::Save(std::ostream &out) {
750         for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
751                 if (codemap[i] == NONE) continue;
752
753                 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
754                 if (str && *str) {
755                         out << '"';
756                         while (*str) {
757                                 if (*str == '"') {
758                                         out << "\\\"";
759                                 } else {
760                                         out << *str;
761                                 }
762                                 ++str;
763                         }
764                         out << '"';
765                 } else {
766                         out << i;
767                 }
768
769                 out << " = " << ActionToString(codemap[i]) << std::endl;;
770         }
771 }
772
773
774 namespace {
775
776 std::map<std::string, Keymap::Action> action_map = {
777         { "none", Keymap::NONE },
778         { "move_forward", Keymap::MOVE_FORWARD },
779         { "move_backward", Keymap::MOVE_BACKWARD },
780         { "move_left", Keymap::MOVE_LEFT },
781         { "move_right", Keymap::MOVE_RIGHT },
782         { "move_up", Keymap::MOVE_UP },
783         { "move_down", Keymap::MOVE_DOWN },
784
785         { "primary", Keymap::PRIMARY },
786         { "secondary", Keymap::SECONDARY },
787         { "tertiary", Keymap::TERTIARY },
788
789         { "inventory_next", Keymap::INV_NEXT },
790         { "inventory_prev", Keymap::INV_PREVIOUS },
791         { "inventory_1", Keymap::INV_1 },
792         { "inventory_2", Keymap::INV_2 },
793         { "inventory_3", Keymap::INV_3 },
794         { "inventory_4", Keymap::INV_4 },
795         { "inventory_5", Keymap::INV_5 },
796         { "inventory_6", Keymap::INV_6 },
797         { "inventory_7", Keymap::INV_7 },
798         { "inventory_8", Keymap::INV_8 },
799         { "inventory_9", Keymap::INV_9 },
800         { "inventory_10", Keymap::INV_10 },
801
802         { "toggle_audio", Keymap::TOGGLE_AUDIO },
803         { "toggle_video", Keymap::TOGGLE_VIDEO },
804         { "toggle_hud", Keymap::TOGGLE_HUD },
805         { "toggle_debug", Keymap::TOGGLE_DEBUG },
806
807         { "exit", Keymap::EXIT },
808 };
809
810 }
811
812 const char *Keymap::ActionToString(Action action) {
813         for (const auto &entry : action_map) {
814                 if (action == entry.second) {
815                         return entry.first.c_str();
816                 }
817         }
818         return "none";
819 }
820
821 Keymap::Action Keymap::StringToAction(const std::string &str) {
822         auto entry = action_map.find(str);
823         if (entry != action_map.end()) {
824                 return entry->second;
825         } else {
826                 std::cerr << "unknown action \"" << str << '"' << std::endl;
827                 return NONE;
828         }
829 }
830
831 }