iw5-mod/src/module/command.cpp

55 lines
1.5 KiB
C++
Raw Normal View History

2018-12-28 06:50:34 -05:00
#include <std_include.hpp>
#include "command.hpp"
#include "utils/string.hpp"
#include "game/structs.hpp"
#include "game/game.hpp"
#include "scheduler.hpp"
utils::memory::allocator command::allocator_;
std::mutex command::mutex_;
std::unordered_map<std::string, std::function<void(const std::vector<std::string>&)>> command::callbacks_;
void command::add(const std::string& name, const std::function<void(const std::vector<std::string>&)>& callback)
{
std::lock_guard _(mutex_);
callbacks_[utils::string::to_lower(name)] = callback;
const auto cmd_name = allocator_.duplicate_string(name);
const auto cmd_function = allocator_.allocate<game::native::cmd_function_t>();
game::native::Cmd_AddCommand(cmd_name, dispatcher, cmd_function);
}
void command::pre_destroy()
{
std::lock_guard _(mutex_);
2019-01-09 06:09:34 -05:00
if (!callbacks_.empty())
2019-01-05 05:44:45 -05:00
{
callbacks_.clear();
}
2018-12-28 06:50:34 -05:00
}
void command::dispatcher()
{
2022-03-09 20:12:16 -05:00
const auto cmd_index = game::native::cmd_args->nesting;
const auto arg_count = game::native::cmd_args->argc[cmd_index];
2018-12-28 06:50:34 -05:00
2019-11-29 16:42:38 -05:00
if (arg_count < 1) return;
2022-03-09 20:12:16 -05:00
const auto command = utils::string::to_lower(game::native::cmd_args->argv[cmd_index][0]);
2018-12-28 06:50:34 -05:00
const auto handler = callbacks_.find(command);
if (handler == callbacks_.end()) return;
std::vector<std::string> arguments;
2019-11-29 16:42:38 -05:00
arguments.reserve(arg_count);
2018-12-28 06:50:34 -05:00
2022-03-09 20:12:16 -05:00
for (auto i = 0; i < game::native::cmd_args->argc[cmd_index]; ++i)
2018-12-28 06:50:34 -05:00
{
2022-03-09 20:12:16 -05:00
arguments.emplace_back(game::native::cmd_args->argv[cmd_index][i]);
2018-12-28 06:50:34 -05:00
}
handler->second(arguments);
}
REGISTER_MODULE(command);