]> git.localhorst.tv Git - blank.git/blob - src/ui/ui.cpp
use collision structures for ray tests
[blank.git] / src / ui / ui.cpp
1 #include "HUD.hpp"
2 #include "Interface.hpp"
3 #include "Keymap.hpp"
4
5 #include "../app/Assets.hpp"
6 #include "../app/Environment.hpp"
7 #include "../app/FrameCounter.hpp"
8 #include "../app/init.hpp"
9 #include "../audio/Audio.hpp"
10 #include "../graphics/Font.hpp"
11 #include "../graphics/Viewport.hpp"
12 #include "../io/TokenStreamReader.hpp"
13 #include "../model/shapes.hpp"
14 #include "../world/BlockLookup.hpp"
15 #include "../world/World.hpp"
16
17 #include <algorithm>
18 #include <cmath>
19 #include <iostream>
20 #include <sstream>
21 #include <glm/gtc/matrix_transform.hpp>
22 #include <glm/gtx/io.hpp>
23
24
25 namespace blank {
26
27 HUD::HUD(const BlockTypeRegistry &types, const Font &font)
28 : types(types)
29 , font(font)
30 , block()
31 , block_buf()
32 , block_transform(1.0f)
33 , block_label()
34 , block_visible(false)
35 , crosshair() {
36         block_transform = glm::translate(block_transform, glm::vec3(50.0f, 50.0f, 0.0f));
37         block_transform = glm::scale(block_transform, glm::vec3(50.0f));
38         block_transform = glm::rotate(block_transform, 3.5f, glm::vec3(1.0f, 0.0f, 0.0f));
39         block_transform = glm::rotate(block_transform, 0.35f, glm::vec3(0.0f, 1.0f, 0.0f));
40
41         OutlineModel::Buffer buf;
42         buf.vertices = std::vector<glm::vec3>({
43                 { -10.0f,   0.0f, 0.0f }, { 10.0f,  0.0f, 0.0f },
44                 {   0.0f, -10.0f, 0.0f }, {  0.0f, 10.0f, 0.0f },
45         });
46         buf.indices = std::vector<OutlineModel::Index>({
47                 0, 1, 2, 3
48         });
49         buf.colors.resize(4, { 10.0f, 10.0f, 10.0f });
50         crosshair.Update(buf);
51
52         block_label.Position(
53                 glm::vec3(50.0f, 85.0f, 0.0f),
54                 Gravity::NORTH_WEST,
55                 Gravity::NORTH
56         );
57         block_label.Foreground(glm::vec4(1.0f));
58         block_label.Background(glm::vec4(0.5f));
59 }
60
61
62 void HUD::Display(const Block &b) {
63         const BlockType &type = types.Get(b.type);
64
65         block_buf.Clear();
66         type.FillEntityModel(block_buf, b.Transform());
67         block.Update(block_buf);
68
69         block_label.Set(font, type.label);
70
71         block_visible = type.visible;
72 }
73
74
75 void HUD::Render(Viewport &viewport) noexcept {
76         viewport.ClearDepth();
77
78         PlainColor &outline_prog = viewport.HUDOutlineProgram();
79         viewport.EnableInvertBlending();
80         viewport.SetCursor(glm::vec3(0.0f), Gravity::CENTER);
81         outline_prog.SetM(viewport.Cursor());
82         crosshair.Draw();
83
84         if (block_visible) {
85                 DirectionalLighting &world_prog = viewport.HUDProgram();
86                 world_prog.SetLightDirection({ 1.0f, 3.0f, 5.0f });
87                 // disable distance fog
88                 world_prog.SetFogDensity(0.0f);
89
90                 viewport.DisableBlending();
91                 world_prog.SetM(block_transform);
92                 block.Draw();
93                 block_label.Render(viewport);
94         }
95 }
96
97
98 Interface::Interface(
99         const Config &config,
100         Environment &env,
101         World &world)
102 : env(env)
103 , world(world)
104 , ctrl(world.Player())
105 , hud(world.BlockTypes(), env.assets.small_ui_font)
106 , aim{{ 0, 0, 0 }, { 0, 0, -1 }}
107 , aim_world()
108 , aim_entity()
109 , outline()
110 , outline_transform(1.0f)
111 , counter_text()
112 , position_text()
113 , orientation_text()
114 , block_text()
115 , last_displayed()
116 , messages(env.assets.small_ui_font)
117 , msg_timer(5000)
118 , config(config)
119 , place_timer(256)
120 , remove_timer(256)
121 , remove(0)
122 , selection(1)
123 , place_sound(env.assets.LoadSound("thump"))
124 , remove_sound(env.assets.LoadSound("plop"))
125 , fwd(0)
126 , rev(0)
127 , debug(false) {
128         counter_text.Position(glm::vec3(-25.0f, 25.0f, 0.0f), Gravity::NORTH_EAST);
129         counter_text.Foreground(glm::vec4(1.0f));
130         counter_text.Background(glm::vec4(0.5f));
131         position_text.Position(glm::vec3(-25.0f, 25.0f + env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
132         position_text.Foreground(glm::vec4(1.0f));
133         position_text.Background(glm::vec4(0.5f));
134         orientation_text.Position(glm::vec3(-25.0f, 25.0f + 2 * env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
135         orientation_text.Foreground(glm::vec4(1.0f));
136         orientation_text.Background(glm::vec4(0.5f));
137         block_text.Position(glm::vec3(-25.0f, 25.0f + 4 * env.assets.small_ui_font.LineSkip(), 0.0f), Gravity::NORTH_EAST);
138         block_text.Foreground(glm::vec4(1.0f));
139         block_text.Background(glm::vec4(0.5f));
140         block_text.Set(env.assets.small_ui_font, "Block: none");
141         messages.Position(glm::vec3(25.0f, -25.0f, 0.0f), Gravity::SOUTH_WEST);
142         messages.Foreground(glm::vec4(1.0f));
143         messages.Background(glm::vec4(0.5f));
144         hud.Display(selection);
145 }
146
147
148 void Interface::HandlePress(const SDL_KeyboardEvent &event) {
149         if (config.keyboard_disabled) return;
150
151         switch (env.keymap.Lookup(event)) {
152                 case Keymap::MOVE_FORWARD:
153                         rev.z = 1;
154                         break;
155                 case Keymap::MOVE_BACKWARD:
156                         fwd.z = 1;
157                         break;
158                 case Keymap::MOVE_LEFT:
159                         rev.x = 1;
160                         break;
161                 case Keymap::MOVE_RIGHT:
162                         fwd.x = 1;
163                         break;
164                 case Keymap::MOVE_UP:
165                         fwd.y = 1;
166                         break;
167                 case Keymap::MOVE_DOWN:
168                         rev.y = 1;
169                         break;
170
171                 case Keymap::BLOCK_FACE:
172                         FaceBlock();
173                         break;
174                 case Keymap::BLOCK_TURN:
175                         TurnBlock();
176                         break;
177                 case Keymap::BLOCK_NEXT:
178                         SelectNext();
179                         break;
180                 case Keymap::BLOCK_PREV:
181                         SelectPrevious();
182                         break;
183
184                 case Keymap::BLOCK_PLACE:
185                         PlaceBlock();
186                         break;
187                 case Keymap::BLOCK_PICK:
188                         PickBlock();
189                         break;
190                 case Keymap::BLOCK_REMOVE:
191                         RemoveBlock();
192                         break;
193
194                 case Keymap::TOGGLE_COLLISION:
195                         ToggleCollision();
196                         break;
197
198                 case Keymap::PRINT_BLOCK:
199                         PrintBlockInfo();
200                         break;
201                 case Keymap::PRINT_CHUNK:
202                         PrintChunkInfo();
203                         break;
204                 case Keymap::PRINT_LIGHT:
205                         PrintLightInfo();
206                         break;
207                 case Keymap::PRINT_SELECTION:
208                         PrintSelectionInfo();
209                         break;
210
211                 case Keymap::TOGGLE_VISUAL:
212                         ToggleVisual();
213                         break;
214                 case Keymap::TOGGLE_DEBUG:
215                         ToggleDebug();
216                         break;
217                 case Keymap::TOGGLE_AUDIO:
218                         ToggleAudio();
219                         break;
220
221                 case Keymap::EXIT:
222                         env.state.Pop();
223                         break;
224
225                 default:
226                         break;
227         }
228 }
229
230 void Interface::HandleRelease(const SDL_KeyboardEvent &event) {
231         if (config.keyboard_disabled) return;
232
233         switch (env.keymap.Lookup(event)) {
234                 case Keymap::MOVE_FORWARD:
235                         rev.z = 0;
236                         break;
237                 case Keymap::MOVE_BACKWARD:
238                         fwd.z = 0;
239                         break;
240                 case Keymap::MOVE_LEFT:
241                         rev.x = 0;
242                         break;
243                 case Keymap::MOVE_RIGHT:
244                         fwd.x = 0;
245                         break;
246                 case Keymap::MOVE_UP:
247                         fwd.y = 0;
248                         break;
249                 case Keymap::MOVE_DOWN:
250                         rev.y = 0;
251                         break;
252
253                 default:
254                         break;
255         }
256 }
257
258 void Interface::FaceBlock() {
259         selection.SetFace(Block::Face((selection.GetFace() + 1) % Block::FACE_COUNT));
260         hud.Display(selection);
261 }
262
263 void Interface::TurnBlock() {
264         selection.SetTurn(Block::Turn((selection.GetTurn() + 1) % Block::TURN_COUNT));
265         hud.Display(selection);
266 }
267
268 void Interface::ToggleCollision() {
269         ctrl.Controlled().WorldCollidable(!ctrl.Controlled().WorldCollidable());
270         if (ctrl.Controlled().WorldCollidable()) {
271                 PostMessage("collision on");
272         } else {
273                 PostMessage("collision off");
274         }
275 }
276
277 void Interface::PrintBlockInfo() {
278         std::cout << std::endl;
279         if (!aim_world) {
280                 PostMessage("not looking at any block");
281                 Ray aim = ctrl.Aim();
282                 std::stringstream s;
283                 s << "aim ray: " << aim.orig << ", " << aim.dir;
284                 PostMessage(s.str());
285                 return;
286         }
287         std::stringstream s;
288         s << "looking at block " << aim_world.block
289                 << " " << aim_world.BlockCoords()
290                 << " of chunk " << aim_world.GetChunk().Position()
291         ;
292         PostMessage(s.str());
293         Print(aim_world.GetBlock());
294 }
295
296 void Interface::PrintChunkInfo() {
297         std::cout << std::endl;
298         if (!aim_world) {
299                 PostMessage("not looking at any block");
300                 return;
301         }
302         std::stringstream s;
303         s << "looking at chunk " << aim_world.GetChunk().Position();
304         PostMessage(s.str());
305
306         PostMessage("  neighbors:");
307         if (aim_world.GetChunk().HasNeighbor(Block::FACE_LEFT)) {
308                 s.str("");
309                 s << " left  " << aim_world.GetChunk().GetNeighbor(Block::FACE_LEFT).Position();
310                 PostMessage(s.str());
311         }
312         if (aim_world.GetChunk().HasNeighbor(Block::FACE_RIGHT)) {
313                 s.str("");
314                 s << " right " << aim_world.GetChunk().GetNeighbor(Block::FACE_RIGHT).Position();
315                 PostMessage(s.str());
316         }
317         if (aim_world.GetChunk().HasNeighbor(Block::FACE_UP)) {
318                 s.str("");
319                 s << " up    " << aim_world.GetChunk().GetNeighbor(Block::FACE_UP).Position();
320                 PostMessage(s.str());
321         }
322         if (aim_world.GetChunk().HasNeighbor(Block::FACE_DOWN)) {
323                 s.str("");
324                 s << " down  " << aim_world.GetChunk().GetNeighbor(Block::FACE_DOWN).Position();
325                 PostMessage(s.str());
326         }
327         if (aim_world.GetChunk().HasNeighbor(Block::FACE_FRONT)) {
328                 s.str("");
329                 s << " front " << aim_world.GetChunk().GetNeighbor(Block::FACE_FRONT).Position();
330                 PostMessage(s.str());
331         }
332         if (aim_world.GetChunk().HasNeighbor(Block::FACE_BACK)) {
333                 s.str("");
334                 s << " back  " << aim_world.GetChunk().GetNeighbor(Block::FACE_BACK).Position();
335                 PostMessage(s.str());
336         }
337         std::cout << std::endl;
338 }
339
340 void Interface::PrintLightInfo() {
341         std::stringstream s;
342         s
343                 << "light level " << world.PlayerChunk().GetLight(world.Player().Position())
344                 << " at position " << world.Player().Position()
345         ;
346         PostMessage(s.str());
347 }
348
349 void Interface::PrintSelectionInfo() {
350         std::cout << std::endl;
351         Print(selection);
352 }
353
354 void Interface::Print(const Block &block) {
355         std::stringstream s;
356         s << "type: " << block.type
357                 << ", face: " << block.GetFace()
358                 << ", turn: " << block.GetTurn()
359         ;
360         PostMessage(s.str());
361 }
362
363 void Interface::ToggleAudio() {
364         config.audio_disabled = !config.audio_disabled;
365         if (config.audio_disabled) {
366                 PostMessage("audio off");
367         } else {
368                 PostMessage("audio on");
369         }
370 }
371
372 void Interface::ToggleVisual() {
373         config.visual_disabled = !config.visual_disabled;
374         if (config.visual_disabled) {
375                 PostMessage("visual off");
376         } else {
377                 PostMessage("visual on");
378         }
379 }
380
381 void Interface::ToggleDebug() {
382         debug = !debug;
383         if (debug) {
384                 UpdateCounter();
385                 UpdatePosition();
386                 UpdateOrientation();
387                 UpdateBlockInfo();
388         }
389 }
390
391 void Interface::UpdateCounter() {
392         std::stringstream s;
393         s << std::setprecision(3) <<
394                 "avg: " << env.counter.Average().running << "ms, "
395                 "peak: " << env.counter.Peak().running << "ms";
396         std::string text = s.str();
397         counter_text.Set(env.assets.small_ui_font, text);
398 }
399
400 void Interface::UpdatePosition() {
401         std::stringstream s;
402         s << std::setprecision(3) << "pos: " << ctrl.Controlled().AbsolutePosition();
403         position_text.Set(env.assets.small_ui_font, s.str());
404 }
405
406 void Interface::UpdateOrientation() {
407         std::stringstream s;
408         s << std::setprecision(3) << "pitch: " << rad2deg(ctrl.Pitch())
409                 << ", yaw: " << rad2deg(ctrl.Yaw());
410         orientation_text.Set(env.assets.small_ui_font, s.str());
411 }
412
413 void Interface::UpdateBlockInfo() {
414         if (aim_world) {
415                 const Block &block = aim_world.GetBlock();
416                 if (last_displayed != block) {
417                         std::stringstream s;
418                         s << "Block: "
419                                 << aim_world.GetType().label
420                                 << ", face: " << block.GetFace()
421                                 << ", turn: " << block.GetTurn();
422                         block_text.Set(env.assets.small_ui_font, s.str());
423                         last_displayed = block;
424                 }
425         } else {
426                 if (last_displayed != Block()) {
427                         std::stringstream s;
428                         s << "Block: none";
429                         block_text.Set(env.assets.small_ui_font, s.str());
430                         last_displayed = Block();
431                 }
432         }
433 }
434
435
436 void Interface::Handle(const SDL_MouseMotionEvent &event) {
437         if (config.mouse_disabled) return;
438         ctrl.RotateYaw(event.xrel * config.yaw_sensitivity);
439         ctrl.RotatePitch(event.yrel * config.pitch_sensitivity);
440 }
441
442 void Interface::HandlePress(const SDL_MouseButtonEvent &event) {
443         if (config.mouse_disabled) return;
444
445         if (event.button == SDL_BUTTON_LEFT) {
446                 RemoveBlock();
447                 remove_timer.Start();
448         } else if (event.button == SDL_BUTTON_MIDDLE) {
449                 PickBlock();
450         } else if (event.button == SDL_BUTTON_RIGHT) {
451                 PlaceBlock();
452                 place_timer.Start();
453         }
454 }
455
456 void Interface::HandleRelease(const SDL_MouseButtonEvent &event) {
457         if (config.mouse_disabled) return;
458
459         if (event.button == SDL_BUTTON_LEFT) {
460                 remove_timer.Stop();
461         } else if (event.button == SDL_BUTTON_RIGHT) {
462                 place_timer.Stop();
463         }
464 }
465
466 void Interface::PickBlock() {
467         if (!aim_world) return;
468         selection = aim_world.GetBlock();
469         hud.Display(selection);
470 }
471
472 void Interface::PlaceBlock() {
473         if (!aim_world) return;
474
475         glm::vec3 next_pos = aim_world.BlockCoords() + aim_world.normal;
476         BlockLookup next_block(&aim_world.GetChunk(), next_pos);
477         if (next_block) {
478         }
479         next_block.SetBlock(selection);
480
481         if (config.audio_disabled) return;
482         const Entity &player = ctrl.Controlled();
483         env.audio.Play(
484                 place_sound,
485                 aim_world.GetChunk().ToSceneCoords(player.ChunkCoords(), next_pos)
486         );
487 }
488
489 void Interface::RemoveBlock() noexcept {
490         if (!aim_world) return;
491         aim_world.SetBlock(remove);
492
493         if (config.audio_disabled) return;
494         const Entity &player = ctrl.Controlled();
495         env.audio.Play(
496                 remove_sound,
497                 aim_world.GetChunk().ToSceneCoords(player.ChunkCoords(), aim_world.BlockCoords())
498         );
499 }
500
501
502 void Interface::Handle(const SDL_MouseWheelEvent &event) {
503         if (config.mouse_disabled) return;
504
505         if (event.y < 0) {
506                 SelectNext();
507         } else if (event.y > 0) {
508                 SelectPrevious();
509         }
510 }
511
512 void Interface::SelectNext() {
513         ++selection.type;
514         if (size_t(selection.type) >= world.BlockTypes().Size()) {
515                 selection.type = 1;
516         }
517         hud.Display(selection);
518 }
519
520 void Interface::SelectPrevious() {
521         --selection.type;
522         if (selection.type <= 0) {
523                 selection.type = world.BlockTypes().Size() - 1;
524         }
525         hud.Display(selection);
526 }
527
528
529 void Interface::PostMessage(const char *msg) {
530         messages.PushLine(msg);
531         msg_timer.Reset();
532         msg_timer.Start();
533         std::cout << msg << std::endl;
534 }
535
536
537 void Interface::Update(int dt) {
538         ctrl.Velocity(glm::vec3(fwd - rev) * config.move_velocity);
539         ctrl.Update(dt);
540
541         msg_timer.Update(dt);
542         place_timer.Update(dt);
543         remove_timer.Update(dt);
544
545         aim = ctrl.Aim();
546         CheckAim();
547
548         if (msg_timer.HitOnce()) {
549                 msg_timer.Stop();
550         }
551
552         if (remove_timer.Hit()) {
553                 RemoveBlock();
554                 CheckAim();
555         }
556
557         if (place_timer.Hit()) {
558                 PlaceBlock();
559                 CheckAim();
560         }
561
562         if (debug) {
563                 if (env.counter.Changed()) {
564                         UpdateCounter();
565                 }
566                 UpdatePosition();
567                 UpdateOrientation();
568         }
569 }
570
571 namespace {
572
573 OutlineModel::Buffer outl_buf;
574
575 }
576
577 void Interface::CheckAim() {
578         if (!world.Intersection(aim, glm::mat4(1.0f), aim_world)) {
579                 aim_world = WorldCollision();
580         }
581         if (!world.Intersection(aim, glm::mat4(1.0f), aim_entity)) {
582                 aim_entity = EntityCollision();
583         }
584         if (aim_world && aim_entity) {
585                 // got both, pick the closest one
586                 if (aim_world.depth < aim_entity.depth) {
587                         UpdateOutline();
588                         aim_entity = EntityCollision();
589                 } else {
590                         aim_world = WorldCollision();
591                 }
592         } else if (aim_world) {
593                 UpdateOutline();
594         }
595         if (debug) {
596                 UpdateBlockInfo();
597         }
598 }
599
600 void Interface::UpdateOutline() {
601         outl_buf.Clear();
602         aim_world.GetType().FillOutlineModel(outl_buf);
603         outline.Update(outl_buf);
604         outline_transform = aim_world.GetChunk().Transform(world.Player().ChunkCoords());
605         outline_transform *= aim_world.BlockTransform();
606         outline_transform *= glm::scale(glm::vec3(1.005f));
607 }
608
609
610 void Interface::Render(Viewport &viewport) noexcept {
611         if (config.visual_disabled) return;
612
613         if (aim_world) {
614                 PlainColor &outline_prog = viewport.WorldOutlineProgram();
615                 outline_prog.SetM(outline_transform);
616                 outline.Draw();
617         }
618
619         if (debug) {
620                 counter_text.Render(viewport);
621                 position_text.Render(viewport);
622                 orientation_text.Render(viewport);
623                 block_text.Render(viewport);
624         }
625
626         if (msg_timer.Running()) {
627                 messages.Render(viewport);
628         }
629
630         hud.Render(viewport);
631 }
632
633
634 Keymap::Keymap()
635 : codemap{ NONE } {
636
637 }
638
639 void Keymap::Map(SDL_Scancode scancode, Action action) {
640         if (scancode > MAX_SCANCODE) {
641                 throw std::runtime_error("refusing to map scancode: too damn high");
642         }
643         codemap[scancode] = action;
644 }
645
646 Keymap::Action Keymap::Lookup(SDL_Scancode scancode) {
647         if (scancode < NUM_SCANCODES) {
648                 return codemap[scancode];
649         } else {
650                 return NONE;
651         }
652 }
653
654
655 void Keymap::LoadDefault() {
656         Map(SDL_SCANCODE_UP, MOVE_FORWARD);
657         Map(SDL_SCANCODE_W, MOVE_FORWARD);
658         Map(SDL_SCANCODE_DOWN, MOVE_BACKWARD);
659         Map(SDL_SCANCODE_S, MOVE_BACKWARD);
660         Map(SDL_SCANCODE_LEFT, MOVE_LEFT);
661         Map(SDL_SCANCODE_A, MOVE_LEFT);
662         Map(SDL_SCANCODE_RIGHT, MOVE_RIGHT);
663         Map(SDL_SCANCODE_D, MOVE_RIGHT);
664         Map(SDL_SCANCODE_SPACE, MOVE_UP);
665         Map(SDL_SCANCODE_RSHIFT, MOVE_UP);
666         Map(SDL_SCANCODE_LSHIFT, MOVE_DOWN);
667         Map(SDL_SCANCODE_LCTRL, MOVE_DOWN);
668         Map(SDL_SCANCODE_RCTRL, MOVE_DOWN);
669
670         Map(SDL_SCANCODE_Q, BLOCK_FACE);
671         Map(SDL_SCANCODE_E, BLOCK_TURN);
672         Map(SDL_SCANCODE_TAB, BLOCK_NEXT);
673         Map(SDL_SCANCODE_RIGHTBRACKET, BLOCK_NEXT);
674         Map(SDL_SCANCODE_LEFTBRACKET, BLOCK_PREV);
675
676         Map(SDL_SCANCODE_INSERT, BLOCK_PLACE);
677         Map(SDL_SCANCODE_RETURN, BLOCK_PLACE);
678         Map(SDL_SCANCODE_MENU, BLOCK_PICK);
679         Map(SDL_SCANCODE_DELETE, BLOCK_REMOVE);
680         Map(SDL_SCANCODE_BACKSPACE, BLOCK_REMOVE);
681
682         Map(SDL_SCANCODE_N, TOGGLE_COLLISION);
683         Map(SDL_SCANCODE_F1, TOGGLE_VISUAL);
684         Map(SDL_SCANCODE_F3, TOGGLE_DEBUG);
685         Map(SDL_SCANCODE_F4, TOGGLE_AUDIO);
686
687         Map(SDL_SCANCODE_B, PRINT_BLOCK);
688         Map(SDL_SCANCODE_C, PRINT_CHUNK);
689         Map(SDL_SCANCODE_L, PRINT_LIGHT);
690         Map(SDL_SCANCODE_P, PRINT_SELECTION);
691
692         Map(SDL_SCANCODE_ESCAPE, EXIT);
693 }
694
695
696 void Keymap::Load(std::istream &is) {
697         TokenStreamReader in(is);
698         std::string key_name;
699         std::string action_name;
700         SDL_Scancode key;
701         Action action;
702         while (in.HasMore()) {
703                 if (in.Peek().type == Token::STRING) {
704                         in.ReadString(key_name);
705                         key = SDL_GetScancodeFromName(key_name.c_str());
706                 } else {
707                         key = SDL_Scancode(in.GetInt());
708                 }
709                 in.Skip(Token::EQUALS);
710                 in.ReadIdentifier(action_name);
711                 action = StringToAction(action_name);
712                 if (in.HasMore() && in.Peek().type == Token::SEMICOLON) {
713                         in.Skip(Token::SEMICOLON);
714                 }
715                 Map(key, action);
716         }
717 }
718
719 void Keymap::Save(std::ostream &out) {
720         for (unsigned int i = 0; i < NUM_SCANCODES; ++i) {
721                 if (codemap[i] == NONE) continue;
722
723                 const char *str = SDL_GetScancodeName(SDL_Scancode(i));
724                 if (str && *str) {
725                         out << '"';
726                         while (*str) {
727                                 if (*str == '"') {
728                                         out << "\\\"";
729                                 } else {
730                                         out << *str;
731                                 }
732                                 ++str;
733                         }
734                         out << '"';
735                 } else {
736                         out << i;
737                 }
738
739                 out << " = " << ActionToString(codemap[i]) << std::endl;;
740         }
741 }
742
743
744 const char *Keymap::ActionToString(Action action) {
745         switch (action) {
746                 default:
747                 case NONE:
748                         return "none";
749                 case MOVE_FORWARD:
750                         return "move_forward";
751                 case MOVE_BACKWARD:
752                         return "move_backward";
753                 case MOVE_LEFT:
754                         return "move_left";
755                 case MOVE_RIGHT:
756                         return "move_right";
757                 case MOVE_UP:
758                         return "move_up";
759                 case MOVE_DOWN:
760                         return "move_down";
761                 case BLOCK_FACE:
762                         return "block_face";
763                 case BLOCK_TURN:
764                         return "block_turn";
765                 case BLOCK_NEXT:
766                         return "block_next";
767                 case BLOCK_PREV:
768                         return "block_prev";
769                 case BLOCK_PLACE:
770                         return "block_place";
771                 case BLOCK_PICK:
772                         return "block_pick";
773                 case BLOCK_REMOVE:
774                         return "block_remove";
775                 case TOGGLE_COLLISION:
776                         return "toggle_collision";
777                 case TOGGLE_AUDIO:
778                         return "toggle_audio";
779                 case TOGGLE_VISUAL:
780                         return "toggle_visual";
781                 case TOGGLE_DEBUG:
782                         return "toggle_debug";
783                 case PRINT_BLOCK:
784                         return "print_block";
785                 case PRINT_CHUNK:
786                         return "print_chunk";
787                 case PRINT_LIGHT:
788                         return "print_light";
789                 case PRINT_SELECTION:
790                         return "print_selection";
791                 case EXIT:
792                         return "exit";
793         }
794 }
795
796 Keymap::Action Keymap::StringToAction(const std::string &str) {
797         if (str == "move_forward") {
798                 return MOVE_FORWARD;
799         } else if (str == "move_backward") {
800                 return MOVE_BACKWARD;
801         } else if (str == "move_left") {
802                 return MOVE_LEFT;
803         } else if (str == "move_right") {
804                 return MOVE_RIGHT;
805         } else if (str == "move_up") {
806                 return MOVE_UP;
807         } else if (str == "move_down") {
808                 return MOVE_DOWN;
809         } else if (str == "block_face") {
810                 return BLOCK_FACE;
811         } else if (str == "block_turn") {
812                 return BLOCK_TURN;
813         } else if (str == "block_next") {
814                 return BLOCK_NEXT;
815         } else if (str == "block_prev") {
816                 return BLOCK_PREV;
817         } else if (str == "block_place") {
818                 return BLOCK_PLACE;
819         } else if (str == "block_pick") {
820                 return BLOCK_PICK;
821         } else if (str == "block_remove") {
822                 return BLOCK_REMOVE;
823         } else if (str == "toggle_collision") {
824                 return TOGGLE_COLLISION;
825         } else if (str == "toggle_audio") {
826                 return TOGGLE_AUDIO;
827         } else if (str == "toggle_visual") {
828                 return TOGGLE_VISUAL;
829         } else if (str == "toggle_debug") {
830                 return TOGGLE_DEBUG;
831         } else if (str == "print_block") {
832                 return PRINT_BLOCK;
833         } else if (str == "print_chunk") {
834                 return PRINT_CHUNK;
835         } else if (str == "print_light") {
836                 return PRINT_LIGHT;
837         } else if (str == "print_selection") {
838                 return PRINT_SELECTION;
839         } else if (str == "exit") {
840                 return EXIT;
841         } else {
842                 return NONE;
843         }
844 }
845
846 }