Merge pull request #164 from h1-mod/bots

custom bot names
This commit is contained in:
fed 2022-07-07 23:24:12 +00:00 committed by GitHub
commit 2defe7fa75

View File

@ -2,9 +2,11 @@
#include "loader/component_loader.hpp" #include "loader/component_loader.hpp"
#include "command.hpp" #include "command.hpp"
#include "console.hpp"
#include "scheduler.hpp" #include "scheduler.hpp"
#include "network.hpp" #include "network.hpp"
#include "party.hpp" #include "party.hpp"
#include "scripting.hpp"
#include "game/game.hpp" #include "game/game.hpp"
#include "game/scripting/execution.hpp" #include "game/scripting/execution.hpp"
@ -12,6 +14,7 @@
#include <utils/hook.hpp> #include <utils/hook.hpp>
#include <utils/string.hpp> #include <utils/string.hpp>
#include <utils/cryptography.hpp> #include <utils/cryptography.hpp>
#include <utils/io.hpp>
namespace bots namespace bots
{ {
@ -53,10 +56,8 @@ namespace bots
return; return;
} }
static auto first_bot = true; const auto* const bot_name = game::SV_BotGetRandomName();
const auto* bot_ent = game::SV_AddBot(bot_name);
const auto bot_name = game::SV_BotGetRandomName();
const auto bot_ent = game::SV_AddBot(bot_name);
if (bot_ent) if (bot_ent)
{ {
@ -70,6 +71,50 @@ namespace bots
}, scheduler::pipeline::server, 100ms); }, scheduler::pipeline::server, 100ms);
} }
} }
utils::hook::detour get_bot_name_hook;
std::vector<std::string> bot_names{};
void load_bot_data()
{
static const char* bots_txt = "h1-mod/bots.txt";
std::string bots_content;
if (!utils::io::read_file(bots_txt, &bots_content))
{
return;
}
auto names = utils::string::split(bots_content, '\n');
for (auto& name : names)
{
name = utils::string::replace(name, "\r", "");
if (!name.empty())
{
bot_names.emplace_back(name);
}
}
}
size_t bot_id = 0;
const char* get_random_bot_name()
{
if (bot_names.empty())
{
load_bot_data();
}
// only use bot names once, no dupes in names
if (!bot_names.empty() && bot_id < bot_names.size())
{
bot_id %= bot_names.size();
const auto& entry = bot_names.at(bot_id++);
return utils::string::va("%.*s", static_cast<int>(entry.size()), entry.data());
}
return get_bot_name_hook.invoke<const char*>();
}
} }
class component final : public component_interface class component final : public component_interface
@ -82,6 +127,8 @@ namespace bots
return; return;
} }
get_bot_name_hook.create(game::SV_BotGetRandomName, get_random_bot_name);
command::add("spawnBot", [](const command::params& params) command::add("spawnBot", [](const command::params& params)
{ {
if (!can_add()) if (!can_add())
@ -102,6 +149,13 @@ namespace bots
scheduler::once(add_bot, scheduler::pipeline::server, 100ms * i); scheduler::once(add_bot, scheduler::pipeline::server, 100ms * i);
} }
}); });
// Clear bot names and reset ID on game shutdown to allow new names to be added without restarting
scripting::on_shutdown([]
{
bot_names.clear();
bot_id = 0;
});
} }
}; };
} }