]> git.localhorst.tv Git - blank.git/blob - src/shared/cli.cpp
add TCP based CLI
[blank.git] / src / shared / cli.cpp
1 #include "CLI.hpp"
2 #include "CLIContext.hpp"
3 #include "commands.hpp"
4
5 #include "../io/TokenStreamReader.hpp"
6 #include "../world/Entity.hpp"
7 #include "../world/Player.hpp"
8
9 #include <iostream>
10 #include <sstream>
11 #include <glm/gtx/io.hpp>
12
13 using namespace std;
14
15
16 namespace blank {
17
18 CLI::CLI(World &world)
19 : world(world)
20 , commands() {
21         AddCommand("tp", new TeleportCommand);
22 }
23
24 CLI::~CLI() {
25         for (auto &entry : commands) {
26                 delete entry.second;
27         }
28 }
29
30 void CLI::AddCommand(const string &name, Command *cmd) {
31         commands[name] = cmd;
32 }
33
34 void CLI::Execute(CLIContext &ctx, const string &line) {
35         stringstream s(line);
36         TokenStreamReader args(s);
37         if (!args.HasMore()) {
38                 // ignore empty command line
39                 return;
40         }
41         if (args.Peek().type != Token::IDENTIFIER) {
42                 ctx.Error("I don't understand");
43                 return;
44         }
45         string name;
46         args.ReadIdentifier(name);
47         auto entry = commands.find(name);
48         if (entry == commands.end()) {
49                 ctx.Error(name + ": command not found");
50                 return;
51         }
52         try {
53                 entry->second->Execute(*this, ctx, args);
54         } catch (exception &e) {
55                 ctx.Error(name + ": " + e.what());
56         } catch (...) {
57                 ctx.Error(name + ": unknown execution error");
58         }
59 }
60
61 CLI::Command::~Command() {
62
63 }
64
65
66 void TeleportCommand::Execute(CLI &, CLIContext &ctx, TokenStreamReader &args) {
67         if (!ctx.HasPlayer()) {
68                 ctx.Error("teleport needs player to operate on");
69                 return;
70         }
71
72         glm::vec3 pos(args.GetFloat(), args.GetFloat(), args.GetFloat());
73         EntityState state = ctx.GetPlayer().GetEntity().GetState();
74         state.pos = ExactLocation(pos).Sanitize();
75         ctx.GetPlayer().GetEntity().SetState(state);
76
77         stringstream msg;
78         msg << ctx.GetPlayer().Name() << " teleported to " << pos;
79         ctx.Broadcast(msg.str());
80 }
81
82 }