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