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