id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,537,345
MiningControl.cpp
TheStarport_FLHook/plugins/minecontrol/MiningControl.cpp
/** * @date Feb, 2010 * @author Cannon (Ported by Raikkonen) * @defgroup MiningControl Mining Control * @brief * Adds bonuses to mining. * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * There are no players commands in this plugin. * * @paragraph adminCmds Admin Commands * All commands are prefixed with '.' unless explicitly specified. * - printminezones - Prints all the configured mining zones. * * @paragraph configuration Configuration * @code * { * "GenericFactor": 1.0, * "PlayerBonus": [ * { * "Ammo": [ * "missile01_mark01" * ], * "Bonus": 0.0, * "Items": [ * "ge_s_battery_01" * ], * "Loot": "commodity_gold", * "Rep": "", * "Ships": [ * "ge_fighter" * ] * } * ], * "PluginDebug": 0, * "ZoneBonus": [ * { * "Bonus": 0.0, * "CurrentReserve": 100000.0, * "MaxReserve": 50000.0, * "Mined": 0.0, * "RechargeRate": 0.0, * "ReplacementLoot": "commodity_gold", * "Zone": "ExampleZone" * } * ] * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * This plugin has no dependencies. */ #include "MiningControl.h" namespace Plugins::MiningControl { const std::unique_ptr<Global> global = std::make_unique<Global>(); /** @ingroup MiningControl * @brief Return true if the cargo list contains the specified good. */ static bool ContainsEquipment(const std::list<CARGO_INFO>& cargoList, uint archId) { return std::ranges::any_of(cargoList, [archId](const CARGO_INFO& c) { return c.bMounted && c.iArchId == archId; }); } /** @ingroup MiningControl * @brief Return the factor to modify a mining loot drop by. */ static float GetBonus(uint reputation, uint shipId, const std::list<CARGO_INFO>& cargoList, uint lootId) { if (!global->PlayerBonus.size()) return 0.0f; // Get all player bonuses for this commodity. auto start = global->PlayerBonus.lower_bound(lootId); auto end = global->PlayerBonus.upper_bound(lootId); for (; start != end; start++) { // Check for matching reputation if reputation is required. if (start->second.RepId != -1 && reputation != start->second.RepId) continue; // Check for matching ship. if (std::ranges::find(start->second.ShipIds, shipId) == start->second.ShipIds.end()) continue; // Check that every simple item in the equipment list is present and // mounted. bool bEquipMatch = true; for (auto item : start->second.ItemIds) { if (!ContainsEquipment(cargoList, item)) { bEquipMatch = false; break; } } // This is a match. if (bEquipMatch) return start->second.Bonus; } return 0.0f; } /** @ingroup MiningControl * @brief Check if the client qualifies for bonuses */ void CheckClientSetup(ClientId client) { if (!global->Clients[client].Setup) { if (global->config->PluginDebug > 1) Console::ConInfo(std::format("client={} setup bonuses", client)); global->Clients[client].Setup = true; // Get the player affiliation uint repGroupId = -1; if (const auto shipObj = Hk::Client::GetInspect(client); shipObj.has_value()) shipObj.value()->get_affiliation(repGroupId); // Get the ship type uint shipId = Hk::Player::GetShipID(client).value(); // Get the ship cargo so that we can check ids, guns, etc. int remainingHoldSize = 0; const auto lstCargo = Hk::Player::EnumCargo((const wchar_t*)Players.GetActiveCharacterName(client), remainingHoldSize); if (lstCargo.has_error()) { return; } if (global->config->PluginDebug > 1) { Console::ConInfo(std::format("client={} iRepGroupId={} shipId={} lstCargo=", client, repGroupId, shipId)); for (auto& ci : lstCargo.value()) { Console::ConInfo(std::format("{} ", ci.iArchId)); } } // Check the player bonus list and if this player has the right ship and // equipment then record the bonus and the weapon types that can be used // to gather the ore. global->Clients[client].LootBonus.clear(); global->Clients[client].LootAmmo.clear(); global->Clients[client].LootShip.clear(); for (const auto& [lootId, playerBonus] : global->PlayerBonus) { float bonus = GetBonus(repGroupId, shipId, lstCargo.value(), lootId); if (bonus > 0.0f) { global->Clients[client].LootBonus[lootId] = bonus; global->Clients[client].LootAmmo[lootId] = playerBonus.AmmoIds; global->Clients[client].LootShip[lootId] = playerBonus.ShipIds; if (global->config->PluginDebug > 1) { Console::ConInfo(std::format("client={} LootId={} Bonus={}\n", client, lootId, bonus)); } } } const auto rights = Hk::Admin::GetAdmin((const wchar_t*)Players.GetActiveCharacterName(client)); if (rights.has_value()) global->Clients[client].Debug = global->config->PluginDebug; } } /** @ingroup MiningControl * @brief Timer hook to update mining stats to file */ void UpdateStatsFile() { MiningStats stats; // Recharge the fields for (auto& [_, zoneBonus] : global->ZoneBonus) { zoneBonus.CurrentReserve += zoneBonus.RechargeRate; if (zoneBonus.CurrentReserve > zoneBonus.MaxReserve) zoneBonus.CurrentReserve = zoneBonus.MaxReserve; ZoneStats zs; zs.CurrentReserve = zoneBonus.CurrentReserve; zs.Mined = zoneBonus.Mined; zs.Zone = zoneBonus.Zone; stats.Stats.emplace_back(zs); } Serializer::SaveToJson(stats); } const std::vector<Timer> timers = {{UpdateStatsFile, 60}}; /** @ingroup MiningControl * @brief Clear client info when a client connects. */ void ClearClientInfo(const uint& client) { global->Clients[client].Setup = false; global->Clients[client].LootBonus.clear(); global->Clients[client].LootAmmo.clear(); global->Clients[client].Debug = 0; global->Clients[client].MineAsteroidEvents = 0; global->Clients[client].MineAsteroidSampleStart = 0; } /** @ingroup MiningControl * @brief Load the configuration */ void LoadSettingsAfterStartup() { global->ZoneBonus.clear(); global->PlayerBonus.clear(); // Patch Archetype::GetEquipment & Archetype::GetShip to suppress annoying // warnings flserver-errors.log unsigned char patch1[] = {0x90, 0x90}; WriteProcMem((char*)0x62F327E, &patch1, 2); WriteProcMem((char*)0x62F944E, &patch1, 2); WriteProcMem((char*)0x62F123E, &patch1, 2); auto config = Serializer::JsonToObject<Config>(); if (config.PluginDebug) Console::ConInfo(std::format("generic_factor={:.2f} debug={}", config.GenericFactor, config.PluginDebug)); for (auto& pb : config.PlayerBonus) { pb.LootId = CreateID(pb.Loot.c_str()); if (!Archetype::GetEquipment(pb.LootId) && !Archetype::GetSimple(pb.LootId)) { Console::ConErr(std::format("Item '{}' not valid", pb.Loot)); continue; } if (pb.Bonus <= 0.0f) { Console::ConErr(std::format("{}:{:5f}: bonus not valid", pb.Loot, pb.Bonus)); continue; } pb.RepId = -1; pub::Reputation::GetReputationGroup(pb.RepId, pb.Rep.c_str()); if (pb.RepId == UINT_MAX) { Console::ConErr(std::format("{}: reputation not valid", pb.Rep)); continue; } for (const auto& ship : pb.Ships) { uint ShipId = CreateID(ship.c_str()); if (!Archetype::GetShip(ShipId)) { Console::ConErr(std::format("{}: ship not valid", ship)); continue; } pb.ShipIds.push_back(ShipId); } for (const auto& item : pb.Items) { uint ItemId = CreateID(item.c_str()); if (auto equipment = Archetype::GetEquipment(ItemId); equipment && equipment->get_class_type() != Archetype::GUN) pb.ItemIds.push_back(ItemId); else { Console::ConErr(std::format("{}: item not valid", item)); continue; } } for (const auto& ammo : pb.Ammo) { uint ItemId = CreateID(ammo.c_str()); if (auto equipment = Archetype::GetEquipment(ItemId); equipment && equipment->get_class_type() == Archetype::GUN) { const Archetype::Gun* gun = static_cast<Archetype::Gun*>(equipment); if (gun->iProjectileArchId && gun->iProjectileArchId != 0xBAADF00D && gun->iProjectileArchId != 0x3E07E70) { pb.AmmoIds.push_back(gun->iProjectileArchId); continue; } } Console::ConErr(std::format("{}: ammo not valid", ammo)); } global->PlayerBonus.insert(std::multimap<uint, PlayerBonus>::value_type(pb.LootId, pb)); if (config.PluginDebug) { Console::ConInfo(std::format("mining player bonus LootId: {} Bonus: {:.2f} RepId: {}\n", pb.LootId, pb.Bonus, pb.Rep)); } } for (auto& zb : config.ZoneBonus) { if (zb.Zone.empty()) { Console::ConErr(std::format("{}: zone not valid", zb.Zone)); continue; } if (zb.Bonus <= 0.0f) { Console::ConErr(std::format("{}:{:.2f}: bonus not valid", zb.Zone, zb.Bonus)); continue; } uint iReplacementLootId = 0; if (!zb.ReplacementLoot.empty()) zb.ReplacementLootId = CreateID(zb.ReplacementLoot.c_str()); if (zb.RechargeRate <= 0.0f) zb.RechargeRate = 50; if (zb.MaxReserve <= 0.0f) zb.MaxReserve = 100000; global->ZoneBonus[CreateID(zb.Zone.c_str())] = zb; if (config.PluginDebug) { Console::ConInfo(std::format("zone bonus {} Bonus={:5f} ReplacementLootId={}({}) RechargeRate={:.2f} MaxReserve={:.2f}\n", zb.Zone, zb.Bonus, zb.ReplacementLoot, iReplacementLootId, zb.RechargeRate, zb.MaxReserve)); } } for (const auto miningStats = Serializer::JsonToObject<MiningStats>(); auto& zone : miningStats.Stats) { uint ZoneId = CreateID(zone.Zone.c_str()); if (global->ZoneBonus.contains(ZoneId)) { global->ZoneBonus[ZoneId].CurrentReserve = zone.CurrentReserve; global->ZoneBonus[ZoneId].Mined = zone.Mined; } } global->config = std::make_unique<Config>(config); // Remove patch now that we've finished loading. unsigned char patch2[] = {0xFF, 0x12}; WriteProcMem((char*)0x62F327E, &patch2, 2); WriteProcMem((char*)0x62F944E, &patch2, 2); WriteProcMem((char*)0x62F123E, &patch2, 2); PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { uint client = playerData->iOnlineId; ClearClientInfo(client); } } /** @ingroup MiningControl * @brief PlayerLaunch hook. Calls ClearClientInfo. */ void PlayerLaunch([[maybe_unused]] ShipId& ship, ClientId& client) { ClearClientInfo(client); } /** @ingroup MiningControl * @brief Called when a gun hits something. */ void SPMunitionCollision(struct SSPMunitionCollisionInfo const& ci, ClientId& client) { // If this is not a lootable rock, do no other processing. if (ci.dwTargetShip != 0) return; global->returnCode = ReturnCode::SkipAll; // Initialise the mining setup for this client if it hasn't been done // already. CheckClientSetup(client); uint ship = Hk::Player::GetShip(client).value(); auto [shipPosition, _] = Hk::Solar::GetLocation(ship, IdType::Ship).value(); SystemId iClientSystemId = Hk::Player::GetSystem(client).value(); CmnAsteroid::CAsteroidSystem* csys = CmnAsteroid::Find(iClientSystemId); if (csys) { // Find asteroid field that matches the best. for (CmnAsteroid::CAsteroidField* cfield = csys->FindFirst(); cfield; cfield = csys->FindNext()) { try { const Universe::IZone* zone = cfield->get_lootable_zone(shipPosition); if (cfield->near_field(shipPosition) && zone && zone->lootableZone) { ClientData& cd = global->Clients[client]; // Adjust the bonus based on the zone. float zoneBonus = 0.25f; if (global->ZoneBonus[zone->iZoneId].Bonus != 0.0f) zoneBonus = global->ZoneBonus[zone->iZoneId].Bonus; // If the field is getting mined out, reduce the bonus zoneBonus *= global->ZoneBonus[zone->iZoneId].CurrentReserve / global->ZoneBonus[zone->iZoneId].MaxReserve; uint lootId = zone->lootableZone->dynamic_loot_commodity; uint crateId = zone->lootableZone->dynamic_loot_container; // Change the commodity if appropriate. if (global->ZoneBonus[zone->iZoneId].ReplacementLootId) lootId = global->ZoneBonus[zone->iZoneId].ReplacementLootId; // If no mining bonus entry for this commodity is found, // flag as no bonus auto ammolst = cd.LootAmmo.find(lootId); bool miningBonusEligible = true; if (ammolst == cd.LootAmmo.end()) { miningBonusEligible = false; if (cd.Debug) PrintUserCmdText(client, L"* Wrong ship/equip/rep"); } // If this minable commodity was not hit by the right type // of gun, flag as no bonus else if (std::ranges::find(ammolst->second, ci.iProjectileArchId) == ammolst->second.end()) { miningBonusEligible = false; if (cd.Debug) PrintUserCmdText(client, L"* Wrong gun"); } // If either no mining gun was used in the shot, or the // character isn't using a valid mining combo for this // commodity, set bonus to *0.5 float fPlayerBonus = 0.5f; if (miningBonusEligible) fPlayerBonus = cd.LootBonus[lootId]; // If this ship is has another ship targetted then send the // ore into the cargo hold of the other ship. uint sendToClientId = client; if (!miningBonusEligible) { auto targetShip = Hk::Player::GetTarget(client); if (targetShip.has_value()) { const auto targetClientId = Hk::Client::GetClientIdByShip(targetShip.value()); if (targetClientId.value() && Hk::Math::Distance3DByShip(ship, targetShip.value()) < 1000.0f) { sendToClientId = targetClientId.value(); } } } // Calculate the loot drop count const float random = static_cast<float>(rand()) / static_cast<float>(RAND_MAX); // Calculate the loot drop and drop it. auto lootCount = static_cast<int>( random * global->config->GenericFactor * zoneBonus * fPlayerBonus * static_cast<float>(zone->lootableZone->dynamic_loot_count2)); // Remove this lootCount from the field global->ZoneBonus[zone->iZoneId].CurrentReserve -= static_cast<float>(lootCount); global->ZoneBonus[zone->iZoneId].Mined += static_cast<float>(lootCount); if (global->ZoneBonus[zone->iZoneId].CurrentReserve <= 0) { global->ZoneBonus[zone->iZoneId].CurrentReserve = 0; lootCount = 0; } if (global->Clients[client].Debug) { PrintUserCmdText(client, std::format(L"* fRand={} fGenericBonus={} fPlayerBonus={} fZoneBonus{} iLootCount={} LootId={}/{} CurrentReserve={:.1f}", random, global->config->GenericFactor, fPlayerBonus, zoneBonus, lootCount, lootId, crateId, global->ZoneBonus[zone->iZoneId].CurrentReserve)); } global->Clients[client].MineAsteroidEvents++; if (global->Clients[client].MineAsteroidSampleStart < time(0)) { if (float average = static_cast<float>(global->Clients[client].MineAsteroidEvents) / 30.0f; average > 2.0f) { std::wstring CharName = (const wchar_t*)Players.GetActiveCharacterName(client); AddLog(LogType::Normal, LogLevel::Info, std::format("High mining rate charname={} rate={:.1f}/sec location={:.1f},{:.1f},{:.1f} system={} zone={}", wstos(CharName.c_str()), average, shipPosition.x, shipPosition.y, shipPosition.z, zone->systemId, zone->iZoneId)); } global->Clients[client].MineAsteroidSampleStart = time(0) + 30; global->Clients[client].MineAsteroidEvents = 0; } if (lootCount) { float fHoldRemaining; pub::Player::GetRemainingHoldSize(sendToClientId, fHoldRemaining); if (fHoldRemaining < static_cast<float>(lootCount)) { lootCount = (int)fHoldRemaining; } if (lootCount == 0) { pub::Player::SendNNMessage(client, CreateID("insufficient_cargo_space")); return; } Hk::Player::AddCargo(sendToClientId, lootId, lootCount, false); } return; } } catch (...) { } } } } /** @ingroup MiningControl * @brief Called when an asteriod is mined. We ignore all of the parameters from the client. */ void MineAsteroid([[maybe_unused]] SystemId& clientSystemId, [[maybe_unused]] const class Vector& vPos, [[maybe_unused]] const uint& crateId, [[maybe_unused]] const uint& lootId, [[maybe_unused]] const uint& count, [[maybe_unused]] ClientId& client) { global->returnCode = ReturnCode::SkipAll; return; } } // namespace Plugins::MiningControl using namespace Plugins::MiningControl; REFL_AUTO(type(PlayerBonus), field(Loot), field(Bonus), field(Rep), field(Ships), field(Items), field(Ammo)) REFL_AUTO(type(ZoneBonus), field(Zone), field(Bonus), field(ReplacementLoot), field(RechargeRate), field(CurrentReserve), field(MaxReserve), field(Mined)) REFL_AUTO(type(ZoneStats), field(Zone), field(CurrentReserve), field(Mined)) REFL_AUTO(type(MiningStats), field(Stats)) REFL_AUTO(type(Config), field(PlayerBonus), field(ZoneBonus), field(GenericFactor), field(PluginDebug)); DefaultDllMainSettings(LoadSettingsAfterStartup); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Mine Control"); pi->shortName("minecontrol"); pi->mayUnload(true); pi->timers(&timers); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::IServerImpl__Startup, &LoadSettingsAfterStartup, HookStep::After); pi->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch); pi->emplaceHook(HookedCall::IServerImpl__MineAsteroid, &MineAsteroid); pi->emplaceHook(HookedCall::IServerImpl__SPMunitionCollision, &SPMunitionCollision); }
18,493
C++
.cpp
507
31.639053
154
0.662946
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,346
SoundManager.cpp
TheStarport_FLHook/plugins/sound_manager/SoundManager.cpp
/** * @date 2022 * @author Raikkonen * @defgroup SoundManager Sound Manager * @brief * The plugin plays a random sound upon player login. To be expanded upon. * * @paragraph cmds Player Commands * None * * @paragraph adminCmds Admin Commands * None * * @paragraph configuration Configuration * @code * { * "sounds": ["dock_not_allowed", "dock_granted"] * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. */ // Includes #include "SoundManager.h" namespace Plugins::SoundManager { const std::unique_ptr<Global> global = std::make_unique<Global>(); void LoadSettings() { Config conf = Serializer::JsonToObject<Config>(); for (const auto& sound : conf.sounds) conf.sound_ids.push_back(CreateID(sound.c_str())); global->config = std::make_unique<Config>(std::move(conf)); } void Login([[maybe_unused]] struct SLoginInfo const& li, ClientId& client) { // Player sound when player logs in if (global->config->sound_ids.size()) Hk::Client::PlaySoundEffect(client, global->config->sound_ids[rand() % global->config->sound_ids.size()]); } } // namespace Plugins::SoundManager /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FLHOOK STUFF /////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace Plugins::SoundManager; // REFL_AUTO must be global namespace REFL_AUTO(type(Config), field(sounds)) DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Sound Manager"); pi->shortName("sound_manager"); pi->mayUnload(true); pi->returnCode(&global->returncode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__Login, &Login, HookStep::After); }
2,012
C++
.cpp
60
31.483333
111
0.659114
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,347
CrashCatcher.cpp
TheStarport_FLHook/plugins/crash_catcher/CrashCatcher.cpp
/** * @date Feb, 2010 * @author Cannon (Ported by Laz 2022) * @defgroup CrashCatcher Crash Catcher * @brief * This plugin is used to catch and handle known crashes in FLServer * * @paragraph cmds Player Commands * There are no player commands in this plugin. * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * No configuration file is needed. * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * This plugin has no dependencies. */ #include "CrashCatcher.h" namespace Plugins::CrashCatcher { const std::unique_ptr<Global> global = std::make_unique<Global>(); /** @ingroup CrashCatcher * @brief Need to use our own logging functions since the nature of this plugin isn't compatible with FLHook's standard logging functionality. */ void AddLogInternal(const char* szString, ...) { char szBufString[1024]; va_list marker; va_start(marker, szString); _vsnprintf_s(szBufString, sizeof(szBufString) - 1, szString, marker); FILE* log; fopen_s(&log, "logs\\crashes.log", "a"); char szBuf[64]; time_t tNow = time(nullptr); tm t; localtime_s(&t, &tNow); strftime(szBuf, sizeof(szBuf), "%d.%m.%Y %H:%M:%S", &t); fprintf(log, "[%s] %s\n", szBuf, szBufString); fflush(log); if (IsDebuggerPresent()) { OutputDebugString(("[LOG] " + std::string(szBufString) + "\n").c_str()); } fclose(log); } /** @ingroup CrashCatcher * @brief Save after a tractor to prevent cargo duplication loss on crash */ void TractorObjects(ClientId& client, [[maybe_unused]] struct XTractorObjects const& objs) { if (global->mapSaveTimes[client] == 0) { global->mapSaveTimes[client] = Hk::Time::GetUnixMiliseconds() + 60000; } } /** @ingroup CrashCatcher * @brief Save after jettison to reduce chance of duplication on crash */ void JettisonCargo(ClientId& client, [[maybe_unused]] struct XJettisonCargo const& objs) { if (global->mapSaveTimes[client] == 0) { global->mapSaveTimes[client] = Hk::Time::GetUnixMiliseconds() + 60000; } } /** @ingroup CrashCatcher * @brief Action the save times recorded in the above two functions */ void SaveCrashingCharacter() { mstime currTime = Hk::Time::GetUnixMiliseconds(); for (auto& [client, saveTime] : global->mapSaveTimes) { if (saveTime != 0 && saveTime < currTime) { if (Hk::Client::IsValidClientID(client) && !Hk::Client::IsInCharSelectMenu(client)) Hk::Player::SaveChar(client); saveTime = 0; } } } const std::vector<Timer> timers = {{SaveCrashingCharacter, 1}}; /** @ingroup CrashCatcher * @brief Originally in Main.cpp of PlayerControl */ void RequestBestPath(ClientId& p1, const uint& p2, const int& p3) { global->returncode = ReturnCode::SkipFunctionCall; try { Server.RequestBestPath(p1, (unsigned char*)p2, p3); } catch (...) { AddLog(LogType::Normal, LogLevel::Err, std::format("Exception in RequestBestPath p1={}", p1)); } } static FARPROC fpOldGetRootProc = nullptr; /** @ingroup CrashCatcher * @brief GetRoot hook to stop crashes at engbase.dll offset 0x000124bd */ struct CObject* __cdecl Cb_GetRoot(struct CObject* child) { try { return GetRoot(child); } catch (...) { AddLog(LogType::Normal, LogLevel::Err, std::format("Crash suppression in GetRoot(child={})", child->get_archetype()->iArchId)); Console::ConErr(std::format("Crash suppression in GetRoot(child={})", child->get_archetype()->iArchId)); return child; } } static FARPROC fpCrashProc1b221Old = nullptr; /** @ingroup CrashCatcher * @brief This crash will happen if you have broken path finding or more than 10 connections per system. */ int __cdecl Cb_CrashProc1b221(unsigned int const& system, struct pub::System::ConnectionEnumerator& conn, int type) { __try { return pub::System::EnumerateConnections(system, conn, (enum ConnectionType)type); } __except (EXCEPTION_EXECUTE_HANDLER) { AddLogInternal("Crash suppression in pub::System::EnumerateConnections(system=%08x,type=%d)", system, type); LOG_EXCEPTION_INTERNAL() return -2; } } static FARPROC fpCrashProc1b113470Old = nullptr; uint __cdecl Cb_PubZoneSystem(uint system) { int res = pub::Zone::GetSystem(system); // AddLog(LogType::Normal, LogLevel::Info,L"pub::Zone::GetSystem %u %u", system, res); return res; } static void* dwSavedECX = nullptr; static FARPROC fpCrashProc6F8B330Old = nullptr; char __stdcall Cb_CrashProc6F8B330(int arg1) { int res = 0; try { if (FLHookConfig::i()->general.debugMode) Console::ConInfo(std::format("Cb_CrashProc6F8B330(arg1={:#X})", arg1)); __asm { pushad push arg1 mov ecx, dwSavedECX call [fpCrashProc6F8B330Old] mov [res], eax popad } } catch (...) { LOG_EXCEPTION_INTERNAL() } return res; } __declspec(naked) void Cb_CrashProc6F8B330Naked() { __asm { mov dwSavedECX, ecx jmp Cb_CrashProc6F8B330 } } static FARPROC fpCrashProc6F78DD0Old = nullptr; void __stdcall Cb_CrashProc6F78DD0(int arg1, int arg2) { try { if (FLHookConfig::i()->general.debugMode) Console::ConInfo(std::format("Cb_CrashProc6F78DD0(arg1={:#X},arg2={:#X})", arg1, arg2)); __asm { pushad push arg2 push arg1 mov ecx, dwSavedECX call [fpCrashProc6F78DD0Old] popad } } catch (...) { LOG_EXCEPTION_INTERNAL() } } __declspec(naked) void Cb_CrashProc6F78DD0Naked() { __asm { mov dwSavedECX, ecx jmp Cb_CrashProc6F78DD0 } } static FARPROC fpCrashProc6F671A0Old = nullptr; void __cdecl Cb_CrashProc6F671A0(int arg1) { try { if (FLHookConfig::i()->general.debugMode) Console::ConInfo(std::format("Cb_CrashProc6F671A0(arg1={:#X})", arg1)); __asm { pushad push arg1 call [fpCrashProc6F671A0Old] add esp, 4 popad } } catch (...) { LOG_EXCEPTION_INTERNAL() } } static char cmp[256], part[256]; const BYTE* __stdcall EngBase124BD_Log(const BYTE* data) { __try { DWORD addr = *(DWORD*)(data + 12); if (addr) addr = *(DWORD*)(addr + 4); if (addr) { strncpy_s(cmp, (LPCSTR)addr, sizeof(cmp)); cmp[sizeof(cmp) - 1] = '\0'; } else { *cmp = '\0'; } addr = *(DWORD*)(data + 8); if (addr) addr = *(DWORD*)(addr + 4); if (addr) { strncpy_s(part, (LPCSTR)addr, sizeof(part)); part[sizeof(part) - 1] = '\0'; } else { *part = '\0'; } data = *(PBYTE*)(data + 16); } __except (EXCEPTION_EXECUTE_HANDLER) { AddLogInternal("Exception/Crash suppression engbase.dll:0x124BD"); AddLogInternal("Cmp=%s Part=%s", cmp, part); data = 0; } return data; } __declspec(naked) void Cb_EngBase124BDNaked() { __asm { push eax call EngBase124BD_Log test eax, eax ret } } const DWORD __stdcall Cb_EngBase11a6dNaked_Log(const BYTE* data) { __try { return *(DWORD*)(data + 0x28); } __except (EXCEPTION_EXECUTE_HANDLER) { AddLogInternal("Exception/Crash suppression engbase.dll:0x11A6D"); return 0; } } __declspec(naked) void Cb_EngBase11a6dNaked() { __asm { push eax call Cb_EngBase11a6dNaked_Log ret 8 } } void __stdcall Cb_47bc4Naked_Log() { AddLog(LogType::Normal, LogLevel::Err, "Exception/Crash in content.dll:0x47bc4 - probably missing formation in faction_props.ini/formations.ini - exiting"); exit(-1); } __declspec(naked) void Cb_47bc4Naked() { __asm { test eax, eax jz will_crash mov edi, eax mov edx, [edi] mov ecx, edi ret will_crash: call Cb_47bc4Naked_Log xor ecx, ecx ret } } static HMODULE modContentAc = nullptr; // or whatever value that is void __stdcall Cb_C4800HookNaked() { modContentAc = global->hModContentAC; } int Cb_C4800Hook(int* a1, int* a2, int* zone, double* a4, int a5, int a6) { __try { int res = 0; __asm { pushad push a6 push a5 push a4 push zone push a2 push a1 mov eax, [Cb_C4800HookNaked] add eax, 0xC4800 call eax add esp, 24 mov [res], eax popad } return res; } __except (EXCEPTION_EXECUTE_HANDLER) { AddLogInternal("Exception/Crash suppression content.dll:0xC608D(zone=%08x)", (zone ? *zone : 0)); LOG_EXCEPTION_INTERNAL() return 0; } } static double __cdecl Cb_TimingSeconds(int64& ticks_delta) { double seconds = Timing::seconds(ticks_delta); if (seconds < 0 || seconds > 10.0) { AddLog(LogType::Normal, LogLevel::Err, std::format("Time delta invalid seconds={:.2f} ticks_delta={}", seconds, ticks_delta)); Console::ConErr(std::format("Time delta invalid seconds={:.2f} ticks_delta={}", seconds, ticks_delta)); ticks_delta = 1000000; seconds = Timing::seconds(ticks_delta); } else if (seconds > 1.0) { AddLog(LogType::Normal, LogLevel::Err, std::format("Time lag detected seconds={:.2f} ticks_delta={}", seconds, ticks_delta)); Console::ConErr(std::format("Time lag detected seconds={:.2f} ticks_delta={}", seconds, ticks_delta)); } return seconds; } /** @ingroup CrashCatcher * @brief Install hooks */ void LoadSettings() { try { if (!global->bPatchInstalled) { global->bPatchInstalled = true; // Load the settings auto config = Serializer::JsonToObject<Config>(); global->hModServerAC = GetModuleHandle("server.dll"); if (global->hModServerAC && config.npcVisibilityDistance > 0.f) { // Patch the NPC visibility distance in MP to 6.5km (default // is 2.5km) float visDistance = std::powf(config.npcVisibilityDistance, 2.f); WriteProcMem((char*)global->hModServerAC + 0x86AEC, &visDistance, 4); FARPROC fpHook = (FARPROC)Cb_GetRoot; ReadProcMem((char*)global->hModServerAC + 0x84018, &fpOldGetRootProc, 4); WriteProcMem((char*)global->hModServerAC + 0x84018, &fpHook, 4); } // Patch the time functions to work around bugs on multiprocessor // and virtual machines. FARPROC fpTimingSeconds = (FARPROC)Cb_TimingSeconds; ReadProcMem((char*)GetModuleHandle(nullptr) + 0x1B0A0, &global->fpOldTimingSeconds, 4); WriteProcMem((char*)GetModuleHandle(nullptr) + 0x1B0A0, &fpTimingSeconds, 4); global->hEngBase = GetModuleHandle("engbase.dll"); global->hModContentAC = GetModuleHandle("content.dll"); if (global->hModContentAC) { if (FLHookConfig::i()->general.debugMode) Console::ConInfo("Installing patches into content.dll"); // Patch for crash at content.dll + blarg { PatchCallAddr((char*)global->hModContentAC, 0xC608D, (char*)Cb_C4800Hook); } // Patch for crash at content.dll + c458f ~ adoxa (thanks man) // Crash if solar has wrong destructible archetype (NewArk for // example is fuchu_core with hit_pts = 0 - different from // client and server in my case) and player taken off from // nearest base of this archetype (Manhattan) This is caused by // multiple players dying in the same planet death zone. Also // 000c458f error arises when nearby stations within a zone ) // are reputed not coinciding with reputation on the // client-side. { // alternative: 0C458F, 8B0482->33C090 uchar patch[] = {0x74, 0x11, 0xeb, 0x05}; WriteProcMem((char*)global->hModContentAC + 0xC457F, patch, 4); } // Patch for crash at content.dll + 47bc4 // This appears to be related to NPCs and/or their chatter. // What's missing contains the from, to and cargo entries // (amongst other stuff). Original Bytes: 8B F8 8B 17 8B CF { uchar patch[] = {0x90, 0xe8}; // nop call WriteProcMem((char*)global->hModContentAC + 0x47bc2, patch, 2); PatchCallAddr((char*)global->hModContentAC, 0x47bc2 + 1, (char*)Cb_47bc4Naked); } // Patch for crash at engbase.dll + 0x0124BD ~ adoxa (thanks // man) This is caused by a bad cmp. { uchar patch[] = {0xe8}; WriteProcMem((char*)global->hEngBase + 0x0124BD, patch, 1); PatchCallAddr((char*)global->hEngBase, 0x0124BD, (char*)Cb_EngBase124BDNaked); } // Patch for crash at engbase.dll + 0x011a6d // This is caused by a bad cmp I suspect { uchar patch[] = {0x90, 0xe9}; // nop jmpr WriteProcMem((char*)global->hEngBase + 0x011a6d, patch, 2); PatchCallAddr((char*)global->hEngBase, 0x011a6d + 1, (char*)Cb_EngBase11a6dNaked); } // Hook for crash at 1b221 in server.dll //{ // FARPROC fpHook = (FARPROC)Cb_CrashProc1b221; // ReadProcMem((char*)hModContentAC + 0x1134f4, //&fpCrashProc1b221Old, 4); WriteProcMem((char*)hModContentAC //+ // 0x1134f4, &fpHook, 4); //} //{ // FARPROC fpHook = (FARPROC)Cb_PubZoneSystem; // ReadProcMem((char*)hModContentAC + 0x113470, //&fpCrashProc1b113470Old, 4); WriteProcMem((char*)hModContentAC //+ // 0x113470, &fpHook, 4); //} // Hook for crash at 0xEB4B5 (confirmed) auto fpHook = (FARPROC)Cb_CrashProc6F8B330Naked; ReadProcMem((char*)global->hModContentAC + 0x11C970, &fpCrashProc6F8B330Old, 4); WriteProcMem((char*)global->hModContentAC + 0x11C970, &fpHook, 4); WriteProcMem((char*)global->hModContentAC + 0x11CA00, &fpHook, 4); // Hook for crash at 0xD8E14 (confirmed) fpCrashProc6F78DD0Old = PatchCallAddr((char*)global->hModContentAC, 0x5ED4B, (char*)Cb_CrashProc6F78DD0Naked); PatchCallAddr((char*)global->hModContentAC, 0xBD96A, (char*)Cb_CrashProc6F78DD0Naked); // Hook for crash at 0xC71AE (confirmed) fpCrashProc6F671A0Old = PatchCallAddr((char*)global->hModContentAC, 0xBDC80, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xBDCF9, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xBE41C, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC67E2, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC6AA5, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC6BE8, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC6F71, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC702A, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC713B, (char*)Cb_CrashProc6F671A0); PatchCallAddr((char*)global->hModContentAC, 0xC7180, (char*)Cb_CrashProc6F671A0); // Patch the NPC persist distance in MP to 6.5km and patch the // max spawn distance to 6.5km if (config.npcPersistDistance > 0.f) { WriteProcMem((char*)global->hModContentAC + 0xD3D6E, &config.npcPersistDistance, 4); } if (config.npcSpawnDistance > 0.f) { WriteProcMem((char*)global->hModContentAC + 0x58F46, &config.npcSpawnDistance, 4); } } } } catch (...) { LOG_EXCEPTION } } /** @ingroup CrashCatcher * @brief Uninstall hooks */ void Shutdown() { if (global->bPatchInstalled) { // Unhook getroot if (global->hModServerAC) { WriteProcMem((char*)global->hModServerAC + 0x84018, &fpOldGetRootProc, 4); } // Unload the timing patches. WriteProcMem((char*)GetModuleHandle(nullptr) + 0x1B0A0, &global->fpOldTimingSeconds, 4); if (global->hModContentAC) { if (FLHookConfig::i()->general.debugMode) Console::ConInfo("Uninstalling patches from content.dll"); { uchar patch[] = {0xe8, 0x6e, 0xe7, 0xff, 0xff}; WriteProcMem((char*)global->hModContentAC + 0xC608D, patch, 5); } { uchar patch[] = {0x8B, 0xF8, 0x8B, 0x17, 0x8B, 0xCF}; WriteProcMem((char*)global->hModContentAC + 0x47bc2, patch, 6); } { uchar patch[] = {0x8B, 0x40, 0x10, 0x85, 0xc0}; WriteProcMem((char*)global->hEngBase + 0x0124BD, patch, 5); } { uchar patch[] = {0x8B, 0x40, 0x28, 0xC2, 0x08, 0x00}; WriteProcMem((char*)global->hEngBase + 0x011a6d, patch, 6); } // WriteProcMem((char*)hModContentAC + 0x1134f4, // &fpCrashProc1b221Old, 4); WriteProcMem((char*)hModContentAC + // 0x113470, &fpCrashProc1b113470Old, 4); WriteProcMem((char*)global->hModContentAC + 0x11C970, &fpCrashProc6F8B330Old, 4); WriteProcMem((char*)global->hModContentAC + 0x11CA00, &fpCrashProc6F8B330Old, 4); PatchCallAddr((char*)global->hModContentAC, 0x5ED4B, (char*)fpCrashProc6F78DD0Old); PatchCallAddr((char*)global->hModContentAC, 0xBD96A, (char*)fpCrashProc6F78DD0Old); PatchCallAddr((char*)global->hModContentAC, 0xBDC80, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xBDCF9, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xBE41C, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC67E2, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC6AA5, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC6BE8, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC6F71, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC702A, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC713B, (char*)fpCrashProc6F671A0Old); PatchCallAddr((char*)global->hModContentAC, 0xC7180, (char*)fpCrashProc6F671A0Old); } } } } // namespace Plugins::CrashCatcher /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FLHOOK STUFF /////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace Plugins::CrashCatcher; REFL_AUTO(type(Config), field(npcVisibilityDistance), field(npcPersistDistance), field(npcSpawnDistance)) // Do things when the dll is loaded BOOL WINAPI DllMain([[maybe_unused]] HINSTANCE hinstDLL, DWORD fdwReason, [[maybe_unused]] LPVOID lpvReserved) { if (fdwReason == DLL_PROCESS_ATTACH && CoreGlobals::c()->flhookReady) LoadSettings(); if (fdwReason == DLL_PROCESS_DETACH) Shutdown(); return true; } // Functions to hook extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Crash Catcher"); pi->shortName("CrashCatcher"); pi->mayUnload(true); pi->timers(&timers); pi->returnCode(&global->returncode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__RequestBestPath, &RequestBestPath); pi->emplaceHook(HookedCall::IServerImpl__TractorObjects, &TractorObjects); pi->emplaceHook(HookedCall::IServerImpl__JettisonCargo, &JettisonCargo); }
19,214
C++
.cpp
574
29.006969
143
0.673631
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,348
Betting.cpp
TheStarport_FLHook/plugins/betting/Betting.cpp
/** * @date Jan, 2023 * @author Raikkonen * @defgroup Betting Betting * @brief * A plugin that allows players to place bets and then duel, the winner getting the pot. * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - acceptduel - Accepts the current duel request. * - acceptffa - Accept the current ffa request. * - cancel - Cancel the current duel/ffa request. * - duel <amount> - Create a duel request to the targeted player. Winner gets the pot. * - ffa <amount> - Create an ffa and send an invite to everyone in the system. Winner gets the pot. * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * This plugin has no configuration file. * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * This plugin has no dependencies. */ #include "Betting.h" namespace Plugins::Betting { const std::unique_ptr<Global> global = std::make_unique<Global>(); /** @ingroup Betting * @brief If the player who died is in an FreeForAll, mark them as a loser. Also handles payouts to winner. */ void processFFA(ClientId client) { for (const auto& [system, freeForAll] : global->freeForAlls) { if (global->freeForAlls[system].contestants[client].accepted && !global->freeForAlls[system].contestants[client].loser) { if (global->freeForAlls[system].contestants.contains(client)) { global->freeForAlls[system].contestants[client].loser = true; PrintLocalUserCmdText(client, std::wstring(reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client))) + L" has been knocked out the FFA.", 100000); } // Is the FreeForAll over? int count = 0; uint contestantId = 0; for (const auto& [id, contestant] : global->freeForAlls[system].contestants) { if (contestant.loser == false && contestant.accepted == true) { count++; contestantId = id; } } // Has the FreeForAll been won? if (count <= 1) { if (Hk::Client::IsValidClientID(contestantId)) { // Announce and pay winner std::wstring winner = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(contestantId)); Hk::Player::AddCash(winner, global->freeForAlls[system].pot); const std::wstring message = winner + L" has won the FFA and receives " + std::to_wstring(global->freeForAlls[system].pot) + L" credits."; PrintLocalUserCmdText(contestantId, message, 100000); } else { struct PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId localClient = playerData->iOnlineId; if (SystemId systemId = Hk::Player::GetSystem(localClient).value(); system == systemId) PrintUserCmdText(localClient, L"No one has won the FFA."); } } // Delete event global->freeForAlls.erase(system); return; } } } } /** @ingroup Betting * @brief This method is called when a player types /ffa in an attempt to start a pvp event */ void UserCmdStartFreeForAll(ClientId& client, const std::wstring& param) { // Convert string to uint uint amount = MultiplyUIntBySuffix(param); // Check its a valid amount of cash if (amount == 0) { PrintUserCmdText(client, L"Must specify a cash amount. Usage: /ffa <amount> e.g. /ffa 5000"); return; } // Check the player can afford it std::wstring characterName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); const auto cash = Hk::Player::GetCash(client); if (cash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(cash.error())); return; } if (amount > 0 && cash.value() < amount) { PrintUserCmdText(client, L"You don't have enough credits to create this FFA."); return; } // Get the player's current system and location in the system. SystemId systemId = Hk::Player::GetSystem(client).value(); // Look in FreeForAll map, is an ffa happening in this system already? // If system doesn't have an ongoing ffa if (!global->freeForAlls.contains(systemId)) { // Get a list of other players in the system // Add them and the player into the ffa map struct PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { // Get the this player's current system ClientId client2 = playerData->iOnlineId; if (SystemId clientSystemId = Hk::Player::GetSystem(client2).value(); systemId != clientSystemId) continue; // Add them to the contestants freeForAlls global->freeForAlls[systemId].contestants[client2].loser = false; if (client == client2) global->freeForAlls[systemId].contestants[client2].accepted = true; else { global->freeForAlls[systemId].contestants[client2].accepted = false; PrintUserCmdText(client2, std::format( L"{} has started a Free-For-All tournament. Cost to enter is {} credits. Type \"/acceptffa\" to enter.", characterName, amount)); } } // Are there any other players in this system? if (!global->freeForAlls[systemId].contestants.empty()) { PrintUserCmdText(client, L"Challenge issued. Waiting for others to accept."); global->freeForAlls[systemId].entryAmount = amount; global->freeForAlls[systemId].pot = amount; Hk::Player::RemoveCash(characterName, amount); } else { global->freeForAlls.erase(systemId); PrintUserCmdText(client, L"There are no other players in this system."); } } else PrintUserCmdText(client, L"There is an FFA already happening in this system."); } /** @ingroup Betting * @brief This method is called when a player types /acceptffa */ void UserCmd_AcceptFFA(ClientId& client, [[maybe_unused]] const std::wstring& param) { // Is player in space? if (uint ship = Hk::Player::GetShip(client).value(); !ship) { PrintUserCmdText(client, L"You must be in space to accept this."); return; } // Get the player's current system and location in the system. SystemId systemId = Hk::Player::GetSystem(client).value(); if (!global->freeForAlls.contains(systemId)) { PrintUserCmdText(client, L"There isn't an FFA in this system. Use /ffa to create one."); } else { std::wstring characterName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); // Check the player can afford it const auto cash = Hk::Player::GetCash(client); if (cash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(cash.error())); return; } if (global->freeForAlls[systemId].entryAmount > 0 && cash.value() < global->freeForAlls[systemId].entryAmount) { PrintUserCmdText(client, L"You don't have enough credits to join this FFA."); return; } // Accept if (global->freeForAlls[systemId].contestants[client].accepted == false) { global->freeForAlls[systemId].contestants[client].accepted = true; global->freeForAlls[systemId].contestants[client].loser = false; global->freeForAlls[systemId].pot = global->freeForAlls[systemId].pot + global->freeForAlls[systemId].entryAmount; PrintUserCmdText(client, std::to_wstring(global->freeForAlls[systemId].entryAmount) + L" credits have been deducted from " L"your Neural Net account."); const std::wstring msg = characterName + L" has joined the FFA. Pot is now at " + std::to_wstring(global->freeForAlls[systemId].pot) + L" credits."; PrintLocalUserCmdText(client, msg, 100000); // Deduct cash Hk::Player::RemoveCash(characterName, global->freeForAlls[systemId].entryAmount); } else PrintUserCmdText(client, L"You have already accepted the FFA."); } } /** @ingroup Betting * @brief Removes any duels with this client and handles payouts. */ void ProcessDuel(ClientId client) { auto duel = global->duels.begin(); while (duel != global->duels.end()) { uint clientKiller = 0; if (duel->client == client) clientKiller = duel->client2; if (duel->client2 == client) clientKiller = duel->client; if (clientKiller == 0) { duel++; continue; } if (duel->accepted) { // Get player names std::wstring victim = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); std::wstring killer = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(clientKiller)); // Prepare and send message const std::wstring msg = killer + L" has won a duel against " + victim + L" for " + std::to_wstring(duel->amount) + L" credits."; PrintLocalUserCmdText(clientKiller, msg, 10000); // Change cash Hk::Player::AddCash(killer, duel->amount); Hk::Player::RemoveCash(victim, duel->amount); } else { PrintUserCmdText(duel->client, L"Duel cancelled."); PrintUserCmdText(duel->client2, L"Duel cancelled."); } duel = global->duels.erase(duel); return; } } /** @ingroup Betting * @brief This method is called when a player types /duel in an attempt to start a duel */ void UserCmdDuel(ClientId& client, const std::wstring& param) { // Get the object the player is targetting const auto targetShip = Hk::Player::GetTarget(client); if (targetShip.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(targetShip.error())); return; } // Check ship is a player const auto clientTarget = Hk::Client::GetClientIdByShip(targetShip.value()); if (clientTarget.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(clientTarget.error())); return; } // Convert string to uint const uint amount = MultiplyUIntBySuffix(param); // Check its a valid amount of cash if (amount == 0) { PrintUserCmdText(client, L"Must specify a cash amount. Usage: /duel " L"<amount> e.g. /duel 5000"); return; } std::wstring characterName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); // Check the player can afford it auto const cash = Hk::Player::GetCash(client); if (cash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(cash.error())); return; } if (amount > 0 && cash.value() < amount) { PrintUserCmdText(client, L"You don't have enough credits to issue this challenge."); return; } // Do either players already have a duel? for (const auto& duel : global->duels) { // Target already has a bet if (duel.client == clientTarget || duel.client2 == clientTarget) { PrintUserCmdText(client, L"This player already has an ongoing duel."); return; } // Player already has a bet if (duel.client == client || duel.client2 == client) { PrintUserCmdText(client, L"You already have an ongoing duel. Type /cancel"); return; } } // Create duel Duel duel; duel.client = client; duel.client2 = clientTarget.value(); duel.amount = amount; duel.accepted = false; global->duels.push_back(duel); // Message players const std::wstring characterName2 = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(clientTarget.value())); const std::wstring message = characterName + L" has challenged " + characterName2 + L" to a duel for " + std::to_wstring(amount) + L" credits."; PrintLocalUserCmdText(client, message, 10000); PrintUserCmdText(clientTarget.value(), L"Type \"/acceptduel\" to accept."); } /** @ingroup Betting * @brief This method is called when a player types /acceptduel to accept a duel request. */ void UserCmdAcceptDuel(ClientId& client, [[maybe_unused]] const std::wstring& param) { // Is player in space? if (uint ship = Hk::Player::GetShip(client).value(); !ship) { PrintUserCmdText(client, L"You must be in space to accept this."); return; } for (auto& duel : global->duels) { if (duel.client2 == client) { // Has player already accepted the bet? if (duel.accepted == true) { PrintUserCmdText(client, L"You have already accepted the challenge."); return; } // Check the player can afford it std::wstring characterName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); const auto cash = Hk::Player::GetCash(client); if (cash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(cash.error())); return; } if (cash.value() < duel.amount) { PrintUserCmdText(client, L"You don't have enough credits to accept this challenge"); return; } duel.accepted = true; const std::wstring message = characterName + L" has accepted the duel with " + reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(duel.client)) + L" for " + std::to_wstring(duel.amount) + L" credits."; PrintLocalUserCmdText(client, message, 10000); return; } } PrintUserCmdText(client, L"You have no duel requests. To challenge " L"someone, target them and type /duel <amount>"); } /** @ingroup Betting * @brief This method is called when a player types /cancel to cancel a duel/ffa request. */ void UserCmd_Cancel(ClientId& client, [[maybe_unused]] const std::wstring& param) { processFFA(client); ProcessDuel(client); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Client command processing /////////////////////////////////////////////////////////////////////////////////////////////////////////////// const std::vector commands = {CreateUserCommand(L"/acceptduel", L"", UserCmdAcceptDuel, L"Accepts the current duel request."), CreateUserCommand(L"/acceptffa", L"", UserCmd_AcceptFFA, L"Accept the current ffa request."), CreateUserCommand(L"/cancel", L"", UserCmd_Cancel, L"Cancel the current duel/ffa request."), CreateUserCommand(L"/duel", L"<amount>", UserCmdDuel, L"Create a duel request to the targeted player. Winner gets the pot."), CreateUserCommand(L"/ffa", L"<amount>", UserCmdStartFreeForAll, L"Create an ffa and send an invite to everyone in the system. Winner gets the pot.")}; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Hooks /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** @ingroup Betting * @brief Hook for dock call. Treats a player as if they died if they were part of a duel */ int __cdecl DockCall(unsigned int const& ship, [[maybe_unused]] unsigned int const& d, [[maybe_unused]] const int& cancel, [[maybe_unused]] const enum DOCK_HOST_RESPONSE& response) { if (const auto client = Hk::Client::GetClientIdByShip(ship); client.has_value() && Hk::Client::IsValidClientID(client.value())) { processFFA(client.value()); ProcessDuel(client.value()); } return 0; } /** @ingroup Betting * @brief Hook for disconnect. Treats a player as if they died if they were part of a duel */ void DisConnect(ClientId& client, [[maybe_unused]] const enum EFLConnection& state) { processFFA(client); ProcessDuel(client); } /** @ingroup Betting * @brief Hook for char info request (F1). Treats a player as if they died if they were part of a duel */ void CharacterInfoReq(ClientId& client, [[maybe_unused]] const bool& p2) { processFFA(client); ProcessDuel(client); } /** @ingroup Betting * @brief Hook for death to kick player out of duel */ void SendDeathMessage([[maybe_unused]] const std::wstring& message, [[maybe_unused]] const uint& system, ClientId& clientVictim, [[maybe_unused]] const ClientId& clientKiller) { ProcessDuel(clientVictim); processFFA(clientVictim); } } // namespace Plugins::Betting using namespace Plugins::Betting; DefaultDllMain(); /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Functions to hook /////////////////////////////////////////////////////////////////////////////////////////////////////////////// extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Betting"); pi->shortName("betting"); pi->mayUnload(true); pi->returnCode(&global->returnCode); pi->commands(&commands); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::IEngine__SendDeathMessage, &SendDeathMessage); pi->emplaceHook(HookedCall::IServerImpl__CharacterInfoReq, &CharacterInfoReq); pi->emplaceHook(HookedCall::IEngine__DockCall, &DockCall); pi->emplaceHook(HookedCall::IServerImpl__DisConnect, &DisConnect); }
16,785
C++
.cpp
441
34.113379
155
0.675322
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,349
Rename.cpp
TheStarport_FLHook/plugins/rename/Rename.cpp
/** * @date Feb 2010 * @author Cannon, ported by Raikkonen * @defgroup Rename Rename * @brief * The plugin allows players to rename their characters, move them between accounts and * create password-protected player tags. * * @paragraph cmds Player Commands * maketag <tag> <master password> <description> - registers a tag and creates master password used to manage password used for renames using the tag * droptag <tag> <master password> - deregisters the player tag * tagpass <tag> <master password> <rename password> - sets the password used to apply the tag * rename <name> [password] - renames the character to the specified name, requires password if includes a protected tag * movecode <code> - registers a move code for this character * movechar <name> <code> - moves the selected character onto the account of currently logged-in character. * * @paragraph adminCmds Admin Commands * None * * @paragraph configuration Configuration * @code * { * "asciiCharNameOnly": false, * "enableMoveChar": true, * "enableRename": true, * "enableTagProtection": false, * "makeTagCost": 2500000, * "moveCost": 0, * "renameCost": 0, * "renameTimeLimit": 0 * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. */ #include "Rename.h" #include "Features/Mail.hpp" namespace Plugins::Rename { const auto global = std::make_unique<Global>(); void LoadSettings() { global->tagList = Serializer::JsonToObject<TagList>(); global->config = std::make_unique<Config>(Serializer::JsonToObject<Config>()); } void SaveSettings() { Serializer::SaveToJson(global->tagList); } bool CreateNewCharacter(SCreateCharacterInfo const& si, ClientId& client) { if (global->config->enableTagProtection) { // If this ship name starts with a restricted tag then the ship may only be created using rename and the faction password const std::wstring charName(si.wszCharname); if (const auto& tag = global->tagList.FindTagPartial(charName); tag != global->tagList.tags.end() && !tag->renamePassword.empty()) { Server.CharacterInfoReq(client, true); return true; } // If this ship name is too short, reject the request if (charName.size() < MinCharacterNameLength + 1) { Server.CharacterInfoReq(client, true); return true; } } if (global->config->asciiCharNameOnly) { const std::wstring charname(si.wszCharname); for (const wchar_t ch : charname) { if (ch & 0xFF80) return true; } } return false; } bool DeleteCharacter(const std::string& charFilename, ClientId& client) { const auto dir = Hk::Client::GetAccountDirName(Hk::Client::GetAccountByClientID(client)); const std::string accDir = CoreGlobals::c()->accPath + wstos(dir) + "\\"; const std::string renameIniDir = accDir + "rename.ini"; if (!std::filesystem::exists(renameIniDir)) return true; const std::string charDir = accDir + charFilename.c_str(); std::wstring charName = IniGetWS(charDir, "Player", "Name", L""); IniDelete(renameIniDir, "General", wstos(charName)); return true; } // Update the tag list when a character is selected update the tag list to // indicate that this tag is in use. If a tag is not used after 60 days, remove // it. void CharacterSelect_AFTER([[maybe_unused]] const std::string& charFilename, ClientId& client) { if (!global->config->enableTagProtection) return; const auto charName = Hk::Client::GetCharacterNameByID(client); if (const auto& tag = global->tagList.FindTagPartial(charName.value()); tag != global->tagList.tags.end() && !tag->renamePassword.empty()) { tag->lastAccess = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); } } void UserCmd_MakeTag(ClientId& client, const std::wstring& param) { if (!global->config->enableTagProtection) { PrintUserCmdText(client, L"Command disabled"); return; } const std::wstring usage = L"Usage: /maketag <tag> <master password> <description>"; // Indicate an error if the command does not appear to be formatted // correctly and stop processing but tell FLHook that we processed the command. if (param.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, usage); return; } if (auto base = Hk::Player::GetCurrentBase(client); base.has_error()) { PrintUserCmdText(client, L"ERR Not in base"); return; } std::wstring tag = GetParam(param, ' ', 0); std::wstring pass = GetParam(param, ' ', 1); std::wstring description = GetParamToEnd(param, ' ', 2); if (tag.size() < MinCharacterNameLength) { PrintUserCmdText(client, L"ERR Tag too short"); PrintUserCmdText(client, usage); return; } if (pass.empty()) { PrintUserCmdText(client, L"ERR Password not set"); PrintUserCmdText(client, usage); return; } if (description.empty()) { PrintUserCmdText(client, L"ERR Description not set"); PrintUserCmdText(client, usage); return; } // If this tag is in use then reject the request. for (const auto& i : global->tagList.tags) { if (tag.find(i.tag) == 0 || i.tag.find(tag) == 0) { PrintUserCmdText(client, L"ERR Tag already exists or conflicts with existing tag"); return; } } // Save character and exit if kicked on save. const auto charName = Hk::Client::GetCharacterNameByID(client); Hk::Player::SaveChar(charName.value()); if (Hk::Client::GetClientIdFromCharName(charName.value()) == UINT_MAX) return; if (const auto iCash = Hk::Player::GetCash(client); global->config->makeTagCost > 0 && iCash < global->config->makeTagCost) { PrintUserCmdText(client, L"ERR Insufficient credits"); return; } Hk::Player::RemoveCash(client, global->config->makeTagCost); TagData data; data.masterPassword = pass; data.renamePassword = L""; data.lastAccess = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); data.description = description; data.tag = tag; global->tagList.tags.emplace_back(data); PrintUserCmdText(client, std::format(L"Created faction tag {} with master password {}", tag, pass)); AddLog(LogType::Normal, LogLevel::Info, wstos(std::format(L"Tag {} created by {} ({})", tag.c_str(), charName.value().c_str(), Hk::Client::GetAccountIdByClientID(client).c_str()))); SaveSettings(); } void UserCmd_DropTag(ClientId& client, const std::wstring& param) { if (!global->config->enableTagProtection) { PrintUserCmdText(client, L"Command disabled"); return; } // Indicate an error if the command does not appear to be formatted // correctly and stop processing but tell FLHook that we processed the // command. if (param.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /droptag <tag> <master password>"); return; } std::wstring charname = (const wchar_t*)Players.GetActiveCharacterName(client); std::wstring tag = GetParam(param, ' ', 0); std::wstring pass = GetParam(param, ' ', 1); // If this tag is in use then reject the request. if (const auto& data = global->tagList.FindTag(tag); data != global->tagList.tags.end() && pass == data->masterPassword) { const auto [first, last] = std::ranges::remove_if(global->tagList.tags, [&tag](const TagData& tg) { return tg.tag == tag; }); global->tagList.tags.erase(first, last); SaveSettings(); PrintUserCmdText(client, L"OK Tag dropped"); AddLog(LogType::Normal, LogLevel::Info, wstos(std::format(L"Tag {} dropped by {} ({})", tag.c_str(), charname.c_str(), Hk::Client::GetAccountIdByClientID(client).c_str()))); return; } PrintUserCmdText(client, L"ERR tag or master password are invalid"); } // Make tag password void UserCmd_SetTagPass(ClientId& client, const std::wstring& param) { if (global->config->enableTagProtection) { // Indicate an error if the command does not appear to be formatted // correctly and stop processing but tell FLHook that we processed the command. if (param.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /settagpass <tag> <master password> <rename password>"); return; } const std::wstring tag = GetParam(param, ' ', 0); const std::wstring masterPassword = GetParam(param, ' ', 1); const std::wstring renamePassword = GetParam(param, ' ', 2); // If this tag is in use then reject the request. if (const auto& data = global->tagList.FindTag(tag); data != global->tagList.tags.end() && masterPassword == data->masterPassword) { data->renamePassword = renamePassword; SaveSettings(); PrintUserCmdText(client, std::format(L"OK Created rename password {} for tag {}", renamePassword, tag)); return; } PrintUserCmdText(client, L"ERR tag or master password are invalid"); } else { PrintUserCmdText(client, L"Command disabled"); } } void RenameTimer() { // Check for pending renames and execute them. We do this on a timer so that // the player is definitely not online when we do the rename. while (!global->pendingRenames.empty()) { Rename o = global->pendingRenames.front(); if (Hk::Client::GetClientIdFromCharName(o.charName).has_value()) return; global->pendingRenames.erase(global->pendingRenames.begin()); CAccount* acc = Hk::Client::GetAccountByCharName(o.charName).value(); // Delete the character from the existing account, create a new // character with the same name in this account and then copy over it // with the save character file. try { if (!acc) throw std::runtime_error("no acc"); Hk::Client::LockAccountAccess(acc, true); Hk::Client::UnlockAccountAccess(acc); // Move files around if (!::MoveFileExA(o.sourceFile.c_str(), o.destFile.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) throw std::runtime_error("move failed"); if (std::filesystem::exists(o.sourceFile.c_str())) throw std::runtime_error("src still exists"); if (!std::filesystem::exists(o.destFile.c_str())) throw std::runtime_error("dest does not exist"); // Decode the char file, update the char name and re-encode it. // Add a space to the value so the ini file line looks like "<key> = // <value>" otherwise Ioncross Server Operator can't decode the file // correctly FlcDecodeFile(o.destFile.c_str(), o.destFile.c_str()); IniWriteW(o.destFile, "Player", "Name", o.newCharName); if (!FLHookConfig::i()->general.disableCharfileEncryption) { FlcEncodeFile(o.destFile.c_str(), o.destFile.c_str()); } // Update any mail references this character had before MailManager::i()->UpdateCharacterName(wstos(o.charName), wstos(o.newCharName)); // The rename worked. Log it and save the rename time. AddLog(LogType::Normal, LogLevel::Info, wstos(std::format(L"User rename {} to {} ({})", o.charName.c_str(), o.newCharName.c_str(), Hk::Client::GetAccountID(acc).value().c_str()))); } catch (char* err) { AddLog(LogType::Normal, LogLevel::Err, wstos(std::format(L"User rename failed ({}) from {} to {} ({})", stows(err), o.charName.c_str(), o.newCharName.c_str(), Hk::Client::GetAccountID(acc).value().c_str()))); } } while (!global->pendingMoves.empty()) { Move o = global->pendingMoves.front(); if (Hk::Client::GetClientIdFromCharName(o.destinationCharName).has_value() || Hk::Client::GetClientIdFromCharName(o.movingCharName).has_value()) return; global->pendingMoves.erase(global->pendingMoves.begin()); CAccount* acc = Hk::Client::GetAccountByCharName(o.destinationCharName).value(); CAccount* oldAcc = Hk::Client::GetAccountByCharName(o.movingCharName).value(); // Delete the character from the existing account, create a new // character with the same name in this account and then copy over it // with the save character file. try { Hk::Client::LockAccountAccess(acc, true); Hk::Client::UnlockAccountAccess(acc); Hk::Client::LockAccountAccess(oldAcc, true); Hk::Client::UnlockAccountAccess(oldAcc); // Move files around if (!::MoveFileExA(o.sourceFile.c_str(), o.destFile.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) throw std::runtime_error("move failed"); if (std::filesystem::exists(o.sourceFile.c_str())) throw std::runtime_error("src still exists"); if (!std::filesystem::exists(o.destFile.c_str())) throw std::runtime_error("dest does not exist"); std::string oldAccDir = CoreGlobals::c()->accPath + wstos(Hk::Client::GetAccountDirName(oldAcc)); if (std::wstring oldCharRenameLimit = IniGetWS(oldAccDir + "\\rename.ini", "General", wstos(o.movingCharName), L""); !oldCharRenameLimit.empty()) { std::string newAccDir = CoreGlobals::c()->accPath + wstos(Hk::Client::GetAccountDirName(acc)); IniWriteW(newAccDir + "\\rename.ini", "General", wstos(o.movingCharName), oldCharRenameLimit); IniDelete(oldAccDir + "\\rename.ini", "General", wstos(o.movingCharName)); } // The move worked. Log it. AddLog(LogType::Normal, LogLevel::Info, wstos(std::format(L"Character {} moved from {} to {}", o.movingCharName.c_str(), Hk::Client::GetAccountID(oldAcc).value().c_str(), Hk::Client::GetAccountID(acc).value().c_str()))); } catch (char* err) { AddLog(LogType::Normal, LogLevel::Err, wstos(std::format(L"Character {} move failed ({}) from {} to {}", o.movingCharName, stows(std::string(err)), Hk::Client::GetAccountID(oldAcc).value().c_str(), Hk::Client::GetAccountID(acc).value().c_str()))); } } } const std::vector<Timer> timers = {{RenameTimer, 5}}; void UserCmd_Rename(ClientId& client, const std::wstring& param) { if (!global->config->enableRename) { PrintUserCmdText(client, L"Command disabled"); return; } // Indicate an error if the command does not appear to be formatted // correctly and stop processing but tell FLHook that we processed the // command. if (param.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /renameme <charname> [password]"); return; } if (auto base = Hk::Player::GetCurrentBase(client); base.has_error()) { PrintUserCmdText(client, L"ERR Not in base"); return; } // If the new name contains spaces then flag this as an // error. std::wstring newCharName = Trim(GetParam(param, L' ', 0)); if (newCharName.find(L" ") != -1) { PrintUserCmdText(client, L"ERR Space characters not allowed in name"); return; } if (Hk::Client::GetAccountByCharName(newCharName).has_value()) { PrintUserCmdText(client, L"ERR Name already exists"); return; } if (newCharName.length() > 23) { PrintUserCmdText(client, L"ERR Name too long"); return; } if (newCharName.length() < MinCharacterNameLength) { PrintUserCmdText(client, L"ERR Name too short"); return; } if (global->config->enableTagProtection) { std::wstring password = Trim(GetParam(param, L' ', 1)); for (const auto& i : global->tagList.tags) { if (newCharName.find(i.tag) == 0 && !i.renamePassword.empty()) { if (!password.length()) { PrintUserCmdText(client, L"ERR Name starts with an owned tag. Password is required."); return; } else if (password != i.masterPassword && password != i.renamePassword) { PrintUserCmdText(client, L"ERR Name starts with an owned tag. Password is wrong."); return; } // Password is valid for owned tag. break; } } } // Get the character name for this connection. std::wstring charname = (const wchar_t*)Players.GetActiveCharacterName(client); // Saving the characters forces an anti-cheat checks and fixes // up a multitude of other problems. Hk::Player::SaveChar(charname); if (!Hk::Client::IsValidClientID(client)) return; // Read the current number of credits for the player // and check that the character has enough cash. const auto cash = Hk::Player::GetCash(charname); if (cash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(cash.error())); return; } if (global->config->renameCost > 0 && cash < global->config->renameCost) { PrintUserCmdText(client, L"ERR Insufficient credits"); return; } // Read the last time a rename was done on this character const auto dir = Hk::Client::GetAccountDirName(Hk::Client::GetAccountByClientID(client)); std::string renameFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + "rename.ini"; // If a rename was done recently by this player then reject the request. // I know that time() returns time_t...shouldn't matter for a few years // yet. if (uint lastRenameTime = IniGetI(renameFile, "General", wstos(charname), 0); (lastRenameTime + 300) < Hk::Time::GetUnixSeconds() && (lastRenameTime + global->config->renameTimeLimit) > Hk::Time::GetUnixSeconds()) { PrintUserCmdText(client, L"ERR Rename time limit"); return; } std::string accPath = CoreGlobals::c()->accPath; const auto sourceFile = Hk::Client::GetCharFileName(charname); if (sourceFile.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(sourceFile.error())); return; } const auto destFile = Hk::Client::GetCharFileName(newCharName, true); if (destFile.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(destFile.error())); return; } // Remove cash if we're charging for it. if (global->config->renameCost > 0) Hk::Player::RemoveCash(charname, global->config->renameCost); Rename o; o.charName = charname; o.newCharName = newCharName; o.sourceFile = accPath + wstos(dir) + "\\" + wstos(sourceFile.value()) + ".fl"; o.destFile = accPath + wstos(dir) + "\\" + wstos(destFile.value()) + ".fl"; global->pendingRenames.emplace_back(o); Hk::Player::KickReason(o.charName, L"Updating character, please wait 10 seconds before reconnecting"); IniWrite(renameFile, "General", wstos(o.newCharName), std::to_string(Hk::Time::GetUnixSeconds())); } /** Process a set the move char code command */ void UserCmd_SetMoveCharCode(ClientId& client, const std::wstring& param) { if (!global->config->enableMoveChar) { PrintUserCmdText(client, L"Command disabled"); return; } if (param.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /setmovecode <code>"); return; } std::wstring charname = (const wchar_t*)Players.GetActiveCharacterName(client); std::string scFile = GetUserFilePath(charname, "-movechar.ini"); if (scFile.empty()) { PrintUserCmdText(client, L"ERR Character does not exist"); return; } if (std::wstring code = Trim(GetParam(param, L' ', 0)); code == L"none") { IniWriteW(scFile, "Settings", "Code", L""); PrintUserCmdText(client, L"OK Movechar code cleared"); } else { IniWriteW(scFile, "Settings", "Code", code); PrintUserCmdText(client, L"OK Movechar code set to " + code); } return; } static bool IsBanned(const std::wstring& charname) { std::wstring dir = Hk::Client::GetAccountDirName(Hk::Client::GetAccountByCharName(charname).value()); std::string banfile = CoreGlobals::c()->accPath + wstos(dir) + "\\banned"; // Prevent ships from banned accounts from being moved. FILE* f; fopen_s(&f, banfile.c_str(), "r"); if (f) { fclose(f); return true; } return false; } /** Move a character from a remote account into this one. */ void UserCmd_MoveChar(ClientId& client, const std::wstring& param) { if (!global->config->enableMoveChar) { PrintUserCmdText(client, L"Command disabled"); return; } // Indicate an error if the command does not appear to be formatted // correctly and stop processing but tell FLHook that we processed the // command. if (param.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /movechar <charname> <code>"); return; } if (auto base = Hk::Player::GetCurrentBase(client); base.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(base.error())); return; } // Get the target account directory. std::wstring movingCharName = Trim(GetParam(param, L' ', 0)); std::string scFile = GetUserFilePath(movingCharName, "-movechar.ini"); if (scFile.empty()) { PrintUserCmdText(client, L"ERR Character does not exist"); return; } // Check the move char code. std::wstring code = Trim(GetParam(param, L' ', 1)); if (std::wstring targetCode = IniGetWS(scFile, "Settings", "Code", L""); targetCode != code) { PrintUserCmdText(client, L"ERR Move character access denied"); return; } // Prevent ships from banned accounts from being moved. if (IsBanned(movingCharName)) { PrintUserCmdText(client, L"ERR not permitted"); return; } std::wstring charname = (const wchar_t*)Players.GetActiveCharacterName(client); // Saving the characters forces an anti-cheat checks and fixes // up a multitude of other problems. Hk::Player::SaveChar(charname); Hk::Player::SaveChar(movingCharName); // Read the current number of credits for the player // and check that the character has enough cash. const auto cash = Hk::Player::GetCash(charname); if (cash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(cash.error())); return; } if (global->config->moveCost > 0 && cash.value() < global->config->moveCost) { PrintUserCmdText(client, L"ERR Insufficient credits"); return; } // Check there is room in this account. CAccount const* acc = Players.FindAccountFromClientID(client); if (acc && acc->iNumberOfCharacters >= 5) { PrintUserCmdText(client, L"ERR Too many characters in account"); return; } // Copy character file into this account with a temp name. std::string acctPath = CoreGlobals::c()->accPath; const auto sourceAcc = Hk::Client::GetAccountByCharName(movingCharName); std::wstring dir = Hk::Client::GetAccountDirName(acc); std::wstring sourceDir = Hk::Client::GetAccountDirName(sourceAcc.value()); const auto sourceFile = Hk::Client::GetCharFileName(movingCharName); if (sourceFile.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(sourceFile.error())); return; } // Remove cash if we're charging for it. if (global->config->moveCost > 0) { Hk::Player::RemoveCash(charname, global->config->moveCost); } Hk::Player::SaveChar(charname); // Schedule the move Move o; o.destinationCharName = charname; o.movingCharName = movingCharName; o.sourceFile = acctPath + wstos(sourceDir) + "\\" + wstos(sourceFile.value()) + ".fl"; o.destFile = acctPath + wstos(dir) + "\\" + wstos(sourceFile.value()) + ".fl"; global->pendingMoves.emplace_back(o); // Delete the move code ::DeleteFileA(scFile.c_str()); // Kick Hk::Player::KickReason(o.destinationCharName, L"Moving character, please wait 10 seconds before reconnecting"); Hk::Player::KickReason(o.movingCharName, L"Moving character, please wait 10 seconds before reconnecting"); } /// Set the move char code for all characters in the account void AdminCmd_SetAccMoveCode(CCmds* cmds, const std::wstring& charname, const std::wstring& code) { // Don't indicate an error if moving is disabled. if (!global->config->enableMoveChar) return; if (!(cmds->rights & RIGHT_SUPERADMIN)) { cmds->Print("ERR No permission"); return; } const auto acc = Hk::Client::GetAccountByCharName(charname); if (acc.has_error()) { cmds->Print("ERR Charname not found"); return; } if (code.length() == 0) { cmds->Print("ERR Code too small, set to none to clear."); return; } std::wstring dir = Hk::Client::GetAccountDirName(acc.value()); // Get the account path. std::string path = CoreGlobals::c()->accPath + "\\*.fl"; // Open the directory iterator. WIN32_FIND_DATA FindFileData; HANDLE hFileFind = FindFirstFile(path.c_str(), &FindFileData); if (hFileFind == INVALID_HANDLE_VALUE) { cmds->Print("ERR Account directory not found"); return; } // Iterate it do { std::string charFile = FindFileData.cFileName; std::string moveCodeFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + charFile.substr(0, charFile.size() - 3) + "-movechar.ini"; if (code == L"none") { IniWriteW(moveCodeFile, "Settings", "Code", L""); cmds->Print(std::format("OK Movechar code cleared on {} \n", charFile)); } else { IniWriteW(moveCodeFile, "Settings", "Code", code); cmds->Print(std::format("OK Movechar code set to {} on {} \n", wstos(code), charFile)); } } while (FindNextFile(hFileFind, &FindFileData)); FindClose(hFileFind); cmds->Print("OK"); } /// Set the move char code for all characters in the account void AdminCmd_ShowTags(CCmds* cmds) { if (!(cmds->rights & RIGHT_SUPERADMIN)) { cmds->Print("ERR No permission"); return; } const auto curr_time = Hk::Time::GetUnixSeconds(); for (const auto& tag : global->tagList.tags) { auto last_access = static_cast<int>(tag.lastAccess); int days = (curr_time - last_access) / (24 * 3600); cmds->Print(wstos(std::format(L"tag={} master_password={} rename_password={} last_access={} days description={}\n", tag.tag, tag.masterPassword, tag.renamePassword, days, tag.description))); } cmds->Print("OK"); } void AdminCmd_AddTag(CCmds* cmds, const std::wstring& tag, const std::wstring& password, [[maybe_unused]] const std::wstring& description) { if (!(cmds->rights & RIGHT_SUPERADMIN)) { cmds->Print("ERR No permission"); return; } if (tag.size() < 3) { cmds->Print("ERR Tag too short"); return; } if (password.empty()) { cmds->Print("ERR Password not set"); return; } if (description.empty()) { cmds->Print("ERR Description not set"); return; } // If this tag is in use then reject the request. if (global->tagList.FindTagPartial(tag) == global->tagList.tags.end()) { cmds->Print("ERR Tag already exists or conflicts with another tag\n"); return; } TagData data; data.tag = tag; data.masterPassword = password; data.renamePassword = L""; data.lastAccess = Hk::Time::GetUnixSeconds(); data.description = description; cmds->Print(wstos(std::format(L"Created faction tag {} with master password {}", tag, password))); global->tagList.tags.emplace_back(data); SaveSettings(); } void AdminCmd_DropTag(CCmds* cmds, const std::wstring& tag) { if (!(cmds->rights & RIGHT_SUPERADMIN)) { cmds->Print("ERR No permission"); return; } if (global->tagList.FindTag(tag) != global->tagList.tags.end()) { auto [first, last] = std::ranges::remove_if(global->tagList.tags, [&tag](const TagData& tg) { return tg.tag == tag; }); global->tagList.tags.erase(first, last); SaveSettings(); cmds->Print("OK Tag dropped"); return; } cmds->Print("ERR tag is invalid"); return; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Client command processing const std::vector commands = {{ CreateUserCommand(L"/maketag", L"<tag> <master password> <description>", UserCmd_MakeTag, L"Creates a faction tag and prevents others from creating said tag without a password."), CreateUserCommand(L"/droptag", L"<tag> <master password>", UserCmd_DropTag, L"Deletes a faction tag"), CreateUserCommand(L"/tagpass", L"<tag> <master password> <rename password>", UserCmd_SetTagPass, L"Set the passwords. Master is to manage the tag. Rename is the password to give to people who you wish to use the tag with the /rename command."), CreateUserCommand(L"/rename", L"<charname> [password]", UserCmd_Rename, L"Renames the current character"), CreateUserCommand(L"/movechar", L"<charname> <code>", UserCmd_MoveChar, L"Move a character from a remote account into this one"), CreateUserCommand( L"/movecode", L"<code>", UserCmd_SetMoveCharCode, L"Set the password for this account if you wish to move it's characters to another account"), }}; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Admin help command callback */ void CmdHelp(CCmds* classptr) { classptr->Print("setaccmovecode <charname> <code>"); classptr->Print("showtags"); classptr->Print("addtag <tag> <password>"); classptr->Print("droptag <tag> <password>"); } bool ExecuteCommandString(CCmds* cmds, const std::wstring& cmd) { if (cmd == L"setaccmovecode") { global->returnCode = ReturnCode::SkipAll; AdminCmd_SetAccMoveCode(cmds, cmds->ArgCharname(1), cmds->ArgStr(2)); return true; } if (cmd == L"showtags") { global->returnCode = ReturnCode::SkipAll; AdminCmd_ShowTags(cmds); return true; } if (cmd == L"addtag") { global->returnCode = ReturnCode::SkipAll; AdminCmd_AddTag(cmds, cmds->ArgStr(1), cmds->ArgStr(2), cmds->ArgStrToEnd(3)); return true; } if (cmd == L"droptag") { global->returnCode = ReturnCode::SkipAll; AdminCmd_DropTag(cmds, cmds->ArgStr(1)); } return true; } std::vector<TagData>::iterator TagList::FindTag(const std::wstring& tag) { return std::ranges::find_if(tags, [&tag](const TagData& data) { return data.tag == tag; }); } std::vector<TagData>::iterator TagList::FindTagPartial(const std::wstring& tag) { return std::ranges::find_if(tags, [&tag](const TagData& data) { return data.tag.find(tag) || tag.find(data.tag); }); } } // namespace Plugins::Rename /////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace Plugins::Rename; REFL_AUTO(type(TagData), field(tag), field(masterPassword), field(renamePassword), field(lastAccess), field(description)); REFL_AUTO(type(TagList), field(tags)); REFL_AUTO(type(Config), field(enableRename), field(enableMoveChar), field(moveCost), field(renameCost), field(renameTimeLimit), field(enableTagProtection), field(asciiCharNameOnly), field(makeTagCost)); DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Rename"); pi->shortName("rename"); pi->mayUnload(true); pi->commands(&commands); pi->timers(&timers); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::IServerImpl__CharacterSelect, &CharacterSelect_AFTER, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__CreateNewCharacter, &CreateNewCharacter); pi->emplaceHook(HookedCall::IServerImpl__DestroyCharacter, &DeleteCharacter); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::FLHook__AdminCommand__Process, &ExecuteCommandString); }
31,359
C++
.cpp
832
33.9375
156
0.689478
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,350
Autobuy.cpp
TheStarport_FLHook/plugins/autobuy/Autobuy.cpp
/** * @date Unknown * @author unknown (Ported by Aingar 2023) * @defgroup Autobuy Autobuy * @brief * The "Autobuy" plugin allows players to set up automatic purchases of various munition/consumable type items. * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - autobuy info - Lists status of autobuy features for this character. * - autobuy <all/munition type> <on/off> - enables or disables autobuy feature for selected munition types on this character. * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * @code * { * "nanobot_nickname": "ge_s_repair_01"; * "shield_battery_nickname": "ge_s_battery_01"; * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * None */ // Includes #include "Autobuy.h" namespace Plugins::Autobuy { const std::unique_ptr<Global> global = std::make_unique<Global>(); void LoadPlayerAutobuy(ClientId client) { AutobuyInfo playerAutobuyInfo {}; playerAutobuyInfo.missiles = Hk::Ini::GetCharacterIniBool(client, L"autobuy.missiles"); playerAutobuyInfo.mines = Hk::Ini::GetCharacterIniBool(client, L"autobuy.mines"); playerAutobuyInfo.torps = Hk::Ini::GetCharacterIniBool(client, L"autobuy.torps"); playerAutobuyInfo.cd = Hk::Ini::GetCharacterIniBool(client, L"autobuy.cd"); playerAutobuyInfo.cm = Hk::Ini::GetCharacterIniBool(client, L"autobuy.cm"); playerAutobuyInfo.bb = Hk::Ini::GetCharacterIniBool(client, L"autobuy.bb"); playerAutobuyInfo.repairs = Hk::Ini::GetCharacterIniBool(client, L"autobuy.repairs"); playerAutobuyInfo.shells = Hk::Ini::GetCharacterIniBool(client, L"autobuy.shells"); global->autobuyInfo[client] = playerAutobuyInfo; } void ClearClientInfo(ClientId& client) { global->autobuyInfo.erase(client); } int PlayerGetAmmoCount(const std::list<CARGO_INFO>& cargoList, uint itemArchId) { if (auto foundCargo = std::ranges::find_if(cargoList, [itemArchId](const CARGO_INFO& cargo) { return cargo.iArchId == itemArchId; }); foundCargo != cargoList.end()) { return foundCargo->iCount; } return 0; } void handleRepairs(ClientId& client) { auto base = Hk::Player::GetCurrentBase(client); // If there is no error with finding the base the correct repair cost can be calculated auto baseCost = 0.33; if (base.has_value()) { baseCost = BaseDataList_get()->get_base_data(base.value())->get_ship_repair_cost(); } auto repairCost = static_cast<uint>((1 - Players[client].fRelativeHealth) * Archetype::GetShip(Players[client].shipArchetype)->fHitPoints * baseCost); std::set<short> eqToFix; for (const auto& item : Players[client].equipDescList.equip) { if (!item.bMounted || item.fHealth == 1) continue; const GoodInfo* info = GoodList_get()->find_by_archetype(item.iArchId); if (!info) continue; repairCost += static_cast<uint>(info->fPrice * (1.0f - item.fHealth) / 3); eqToFix.insert(item.sId); } if (uint playerCash = Hk::Player::GetCash(client).value(); playerCash < repairCost) { PrintUserCmdText(client, L"Insufficient Cash"); return; } if (repairCost) { PrintUserCmdText(client, std::format(L"Auto-Buy: Ship repair costed {}$", repairCost)); Hk::Player::RemoveCash(client, repairCost); } if (!eqToFix.empty()) { for (auto& item : Players[client].equipDescList.equip) { if (eqToFix.contains(item.sId)) item.fHealth = 1.0f; } auto& equip = Players[client].equipDescList.equip; if (&equip != &Players[client].lShadowEquipDescList.equip) Players[client].lShadowEquipDescList.equip = equip; st6::vector<EquipDesc> eqVector; for (auto& eq : equip) { if (eq.bMounted) eq.fHealth = 1.0f; eqVector.push_back(eq); } HookClient->Send_FLPACKET_SERVER_SETEQUIPMENT(client, eqVector); } if (auto& playerCollision = Players[client].collisionGroupDesc.data; !playerCollision.empty()) { st6::list<XCollision> componentList; for (auto& colGrp : playerCollision) { auto* newColGrp = reinterpret_cast<XCollision*>(colGrp.data); newColGrp->componentHP = 1.0f; componentList.push_back(*newColGrp); } HookClient->Send_FLPACKET_SERVER_SETCOLLISIONGROUPS(client, componentList); } if (Players[client].fRelativeHealth < 1.0f) { Players[client].fRelativeHealth = 1.0f; HookClient->Send_FLPACKET_SERVER_SETHULLSTATUS(client, 1.0f); } } void AddEquipToCart(const Archetype::Launcher* launcher, const std::list<CARGO_INFO>& cargo, std::list<AutobuyCartItem>& cart, AutobuyCartItem& item, const std::wstring_view& desc) { item.archId = launcher->iProjectileArchId; uint itemId = Arch2Good(item.archId); if (global->ammoLimits.contains(Arch2Good(item.archId))) { item.count = global->ammoLimits[itemId] - PlayerGetAmmoCount(cargo, item.archId); } else { item.count = MAX_PLAYER_AMMO - PlayerGetAmmoCount(cargo, item.archId); } item.description = desc; cart.emplace_back(item); } AutobuyInfo& LoadAutobuyInfo(ClientId& client) { if (!global->autobuyInfo.contains(client)) { LoadPlayerAutobuy(client); } return global->autobuyInfo[client]; } void OnBaseEnter(BaseId& baseId, ClientId& client) { const AutobuyInfo& clientInfo = LoadAutobuyInfo(client); Archetype::Ship const* ship = Archetype::GetShip(Players[client].shipArchetype); // player cargo int remHoldSize; const auto cargo = Hk::Player::EnumCargo(client, remHoldSize); if (cargo.has_error()) { return; } // shopping cart std::list<AutobuyCartItem> cartList; if (clientInfo.bb) { // shield bats & nanobots uint nanobotsId; pub::GetGoodID(nanobotsId, global->config->nanobot_nickname.c_str()); uint shieldBatsId; pub::GetGoodID(shieldBatsId, global->config->shield_battery_nickname.c_str()); bool nanobotsFound = false; bool shieldBattsFound = false; for (auto& item : cargo.value()) { AutobuyCartItem aci; if (item.iArchId == nanobotsId) { aci.archId = nanobotsId; aci.count = ship->iMaxNanobots - item.iCount; aci.description = L"Nanobots"; cartList.push_back(aci); nanobotsFound = true; } else if (item.iArchId == shieldBatsId) { aci.archId = shieldBatsId; aci.count = ship->iMaxShieldBats - item.iCount; aci.description = L"Shield Batteries"; cartList.push_back(aci); shieldBattsFound = true; } } if (!nanobotsFound) { // no nanos found -> add all AutobuyCartItem aci; aci.archId = nanobotsId; aci.count = ship->iMaxNanobots; aci.description = L"Nanobots"; cartList.push_back(aci); } if (!shieldBattsFound) { // no batts found -> add all AutobuyCartItem aci; aci.archId = shieldBatsId; aci.count = ship->iMaxShieldBats; aci.description = L"Shield Batteries"; cartList.push_back(aci); } } if (clientInfo.cd || clientInfo.cm || clientInfo.mines || clientInfo.missiles || clientInfo.torps || clientInfo.shells) { // add mounted equip to a new list and eliminate double equipment(such // as 2x lancer etc) std::list<CARGO_INFO> mountedList; for (auto& item : cargo.value()) { if (!item.bMounted) continue; bool found = false; for (const auto& mounted : mountedList) { if (mounted.iArchId == item.iArchId) { found = true; break; } } if (!found) mountedList.push_back(item); } // check mounted equip for (const auto& mounted : mountedList) { AutobuyCartItem aci; Archetype::Equipment* eq = Archetype::GetEquipment(mounted.iArchId); auto eqType = Hk::Client::GetEqType(eq); switch (eqType) { case ET_MINE: { if (clientInfo.mines) AddEquipToCart(static_cast<Archetype::Launcher*>(eq), cargo.value(), cartList, aci, L"Mines"); break; } case ET_CM: { if (clientInfo.cm) AddEquipToCart(static_cast<Archetype::Launcher*>(eq), cargo.value(), cartList, aci, L"Countermeasures"); break; } case ET_TORPEDO: { if (clientInfo.torps) AddEquipToCart(static_cast<Archetype::Launcher*>(eq), cargo.value(), cartList, aci, L"Torpedoes"); break; } case ET_CD: { if (clientInfo.cd) AddEquipToCart(static_cast<Archetype::Launcher*>(eq), cargo.value(), cartList, aci, L"Cruise Disrupters"); break; } case ET_MISSILE: { if (clientInfo.missiles) AddEquipToCart(static_cast<Archetype::Launcher*>(eq), cargo.value(), cartList, aci, L"Missiles"); break; } case ET_GUN: { if (clientInfo.shells) AddEquipToCart(static_cast<Archetype::Launcher*>(eq), cargo.value(), cartList, aci, L"Shells"); break; } default: break; } } } if (clientInfo.repairs) { handleRepairs(client); } // search base in base-info list BaseInfo const* bi = nullptr; if (auto foundBase = std::ranges::find_if(CoreGlobals::c()->allBases, [baseId](const BaseInfo& base) { return base.baseId == baseId; }); foundBase != CoreGlobals::c()->allBases.end()) { bi = std::to_address(foundBase); } if (!bi) return; // base not found const auto cashErr = Hk::Player::GetCash(client); if (cashErr.has_error()) { return; } auto cash = cashErr.value(); for (auto& buy : cartList) { if (!buy.count || !Arch2Good(buy.archId)) continue; // check if good is available and if player has the neccessary rep bool goodAvailable = false; for (const auto& available : bi->lstMarketMisc) { if (available.iArchId == buy.archId) { auto baseRep = Hk::Solar::GetAffiliation(bi->iObjectId); if (baseRep.has_error()) PrintUserCmdText(client, Hk::Err::ErrGetText(baseRep.error())); const auto playerRep = Hk::Player::GetRep(client, baseRep.value()); if (playerRep.has_error()) PrintUserCmdText(client, Hk::Err::ErrGetText(playerRep.error())); // good rep, allowed to buy if (playerRep.value() >= available.fRep) goodAvailable = true; break; } } if (!goodAvailable) continue; // base does not sell this item or bad rep auto goodPrice = Hk::Solar::GetCommodityPrice(baseId, buy.archId); if (goodPrice.has_error()) continue; // good not available const Archetype::Equipment* eq = Archetype::GetEquipment(buy.archId); // will always fail for fVolume == 0, no need to worry about potential div by 0 if (static_cast<float>(remHoldSize) < std::ceil(eq->fVolume * static_cast<float>(buy.count))) { // round to the nearest possible auto newCount = static_cast<uint>(static_cast<float>(remHoldSize) / eq->fVolume); if (!newCount) { PrintUserCmdText(client, std::format(L"Auto-Buy({}): FAILED! Insufficient Cargo Space", buy.description)); continue; } else buy.count = newCount; } if (uint uCost = (static_cast<uint>(goodPrice.value()) * buy.count); cash < uCost) PrintUserCmdText(client, std::format(L"Auto-Buy({}): FAILED! Insufficient Credits", buy.description)); else { Hk::Player::RemoveCash(client, uCost); remHoldSize -= ((int)eq->fVolume * buy.count); // add the item, dont use addcargo for performance/bug reasons // assume we only mount multicount goods (missiles, ammo, bots Hk::Player::AddCargo(client, buy.archId, buy.count, false); PrintUserCmdText(client, std::format(L"Auto-Buy({}): Bought {} unit(s), cost: {}$", buy.description, buy.count, ToMoneyStr(uCost))); } } Hk::Player::SaveChar(client); } void UserCmdAutobuy(ClientId& client, const std::wstring& param) { AutobuyInfo& autobuyInfo = LoadAutobuyInfo(client); const std::wstring autobuyType = GetParam(param, ' ', 0); const std::wstring newState = GetParam(param, ' ', 1); if (autobuyType.empty()) { PrintUserCmdText(client, L"Error: Invalid parameters"); PrintUserCmdText(client, L"Usage: /autobuy <param> [<on/off>]"); PrintUserCmdText(client, L"<Param>:"); PrintUserCmdText(client, L"| info - display current autobuy-settings"); PrintUserCmdText(client, L"| missiles - enable/disable autobuy for missiles"); PrintUserCmdText(client, L"| torps - enable/disable autobuy for torpedos"); PrintUserCmdText(client, L"| mines - enable/disable autobuy for mines"); PrintUserCmdText(client, L"| shells - enable/disable autobuy for shells and miscellaneous ammo"); PrintUserCmdText(client, L"| cd - enable/disable autobuy for cruise disruptors"); PrintUserCmdText(client, L"| cm - enable/disable autobuy for countermeasures"); PrintUserCmdText(client, L"| bb - enable/disable autobuy for nanobots/shield batteries"); PrintUserCmdText(client, L"| repairs - enable/disable automatic repair of ship and equipment"); PrintUserCmdText(client, L"| all: enable/disable autobuy for all of the above"); PrintUserCmdText(client, L"Examples:"); PrintUserCmdText(client, L"| \"/autobuy missiles on\" enable autobuy for missiles"); PrintUserCmdText(client, L"| \"/autobuy all off\" completely disable autobuy"); PrintUserCmdText(client, L"| \"/autobuy info\" show autobuy info"); } if (autobuyType == L"info") { PrintUserCmdText(client, std::format(L"Missiles: {}", autobuyInfo.missiles ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Mines: {}", autobuyInfo.mines ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Shells: {}", autobuyInfo.shells ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Torpedos: {}", autobuyInfo.torps ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Cruise Disruptors: {}", autobuyInfo.cd ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Countermeasures: {}", autobuyInfo.cm ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Nanobots/Shield Batteries: {}", autobuyInfo.bb ? L"On" : L"Off")); PrintUserCmdText(client, std::format(L"Repairs: {}", autobuyInfo.repairs ? L"On" : L"Off")); return; } if (newState.empty() || (newState != L"on" && newState != L"off")) { PrintUserCmdText(client, L"ERR invalid parameters"); return; } const auto fileName = Hk::Client::GetCharFileName(client); std::string scSection = "autobuy_" + wstos(fileName.value()); bool enable = newState == L"on"; if (autobuyType == L"all") { autobuyInfo.missiles = enable; autobuyInfo.mines = enable; autobuyInfo.shells = enable; autobuyInfo.torps = enable; autobuyInfo.cd = enable; autobuyInfo.cm = enable; autobuyInfo.bb = enable; autobuyInfo.repairs = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.missiles", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.mines", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.shells", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.torps", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.cd", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.cm", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.bb", stows(enable ? "true" : "false")); Hk::Ini::SetCharacterIni(client, L"autobuy.repairs", stows(enable ? "true" : "false")); } else if (autobuyType == L"missiles") { autobuyInfo.missiles = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.missiles", stows(enable ? "true" : "false")); } else if (autobuyType == L"mines") { autobuyInfo.mines = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.mines", stows(enable ? "true" : "false")); } else if (autobuyType == L"shells") { autobuyInfo.shells = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.shells", stows(enable ? "true" : "false")); } else if (autobuyType == L"torps") { autobuyInfo.torps = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.torps", stows(enable ? "true" : "false")); } else if (autobuyType == L"cd") { autobuyInfo.cd = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.cd", stows(enable ? "true" : "false")); } else if (autobuyType == L"cm") { autobuyInfo.cm = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.cm", stows(enable ? "true" : "false")); } else if (autobuyType == L"bb") { autobuyInfo.bb = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.bb", stows(enable ? "true" : "false")); } else if (autobuyType == L"repairs") { autobuyInfo.repairs = enable; Hk::Ini::SetCharacterIni(client, L"autobuy.repairs", stows(enable ? "true" : "false")); } else { PrintUserCmdText(client, L"ERR invalid parameters"); return; } Hk::Player::SaveChar(client); PrintUserCmdText(client, L"OK"); } // Define usable chat commands here const std::vector commands = {{ CreateUserCommand(L"/autobuy", L"<consumable type/info> <on/off>", UserCmdAutobuy, L"Sets up automatic purchases for consumables."), }}; // Load Settings void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(config); // Get ammo limits for (const auto& iniPath : global->config->ammoIniPaths) { INI_Reader ini; if (!ini.open(iniPath.c_str(), false)) { Console::ConErr(std::format("Was unable to read ammo limits from the following file: {}", iniPath)); return; } while (ini.read_header()) { if (ini.is_header("Munition")) { uint itemname = 0; int itemlimit = 0; bool valid = false; while (ini.read_value()) { if (ini.is_value("nickname")) { itemname = CreateID(ini.get_value_string(0)); } else if (ini.is_value("ammo_limit")) { valid = true; itemlimit = ini.get_value_int(0); } } if (valid) { global->ammoLimits.insert(std::pair<uint, int>(itemname, itemlimit)); } } } } } } // namespace Plugins::Autobuy using namespace Plugins::Autobuy; REFL_AUTO(type(Config), field(nanobot_nickname), field(shield_battery_nickname), field(ammoIniPaths)) DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Autobuy"); pi->shortName("autobuy"); pi->mayUnload(true); pi->commands(&commands); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__BaseEnter, &OnBaseEnter, HookStep::After); }
18,874
C++
.cpp
522
32.099617
152
0.69155
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,352
Wardrobe.cpp
TheStarport_FLHook/plugins/wardrobe/Wardrobe.cpp
/** * @date Jan, 2023 * @author Raikkonen, ported by Nen * @defgroup Wardrobe Wardrobe * @brief * The Wardrobe plugin allows players to change their body and head models from a defined list of allowed models. * * @paragraph cmds Player Commands * -wardrobe show <head/body> - lists available heads or bodies * -wardrobe change <head/body> - changes your character model to selected head or body * * @paragraph adminCmds Admin Commands * None * * @paragraph configuration Configuration * @code * { * "bodies": { * "ExampleBody": "ku_edo_body" * }, * "heads": { * "ExampleHead": "ku_edo_head" * } * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. */ #include "Wardrobe.h" namespace Plugins::Wardrobe { const std::unique_ptr<Global> global = std::make_unique<Global>(); void UserCmdShowWardrobe(ClientId& client, const std::wstring& param) { const std::wstring type = GetParam(param, ' ', 0); if (ToLower(type) == L"head") { PrintUserCmdText(client, L"Heads:"); std::wstring heads; for (const auto& [name, id] : global->config->heads) heads += (stows(name) + L" | "); PrintUserCmdText(client, heads); } else if (ToLower(type) == L"body") { PrintUserCmdText(client, L"Bodies:"); std::wstring bodies; for (const auto& [name, id] : global->config->bodies) bodies += (stows(name) + L" | "); PrintUserCmdText(client, bodies); } } void UserCmdChangeCostume(ClientId& client, const std::wstring& param) { const std::wstring type = GetParam(param, ' ', 0); const std::wstring costume = GetParam(param, ' ', 1); if (type.empty() || costume.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); return; } Wardrobe restart; if (ToLower(type) == L"head") { if (!global->config->heads.contains(wstos(costume))) { PrintUserCmdText(client, L"ERR Head not found. Use \"/warehouse show head\" to get available heads."); return; } restart.head = true; restart.costume = global->config->heads[wstos(costume)]; } else if (ToLower(type) == L"body") { if (!global->config->bodies.contains(wstos(costume))) { PrintUserCmdText(client, L"ERR Body not found. Use \"/warehouse show body\" to get available bodies."); return; } restart.head = false; restart.costume = global->config->bodies[wstos(costume)]; } else { PrintUserCmdText(client, L"ERR Invalid parameters"); return; } // Saving the characters forces an anti-cheat checks and fixes // up a multitude of other problems. Hk::Player::SaveChar(client); if (!Hk::Client::IsValidClientID(client)) return; restart.characterName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); if (const CAccount* account = Players.FindAccountFromClientID(client)) { restart.directory = Hk::Client::GetAccountDirName(account); restart.characterFile = Hk::Client::GetCharFileName(restart.characterName).value(); global->pendingRestarts.push_back(restart); Hk::Player::KickReason(restart.characterName, L"Updating character, please wait 10 seconds before reconnecting"); } } void ProcessWardrobeRestarts() { while (!global->pendingRestarts.empty()) { Wardrobe restart = global->pendingRestarts.back(); if (Hk::Client::GetClientIdFromCharName(restart.characterName).has_value()) return; global->pendingRestarts.pop_back(); try { // Overwrite the existing character file std::string scCharFile = CoreGlobals::c()->accPath + wstos(restart.directory) + "\\" + wstos(restart.characterFile) + ".fl"; FlcDecodeFile(scCharFile.c_str(), scCharFile.c_str()); if (restart.head) { IniWrite(scCharFile, "Player", "head", " " + restart.costume); } else IniWrite(scCharFile, "Player", "body", " " + restart.costume); if (!FLHookConfig::i()->general.disableCharfileEncryption) FlcEncodeFile(scCharFile.c_str(), scCharFile.c_str()); AddLog(LogType::Normal, LogLevel::Info, std::format("User {} costume change to {}", wstos(restart.characterFile).c_str(), restart.costume)); } catch (char* err) { AddLog(LogType::Normal, LogLevel::Err, std::format("User {} costume change to {} ({})", wstos(restart.characterName).c_str(), restart.costume, err)); } catch (...) { AddLog(LogType::Normal, LogLevel::Err, std::format("User {} costume change to {}", wstos(restart.characterName).c_str(), restart.costume)); } } } void UserCmdHandle(ClientId& client, const std::wstring& param) { // Check character is in base if (auto base = Hk::Player::GetCurrentBase(client); base.has_error()) { PrintUserCmdText(client, L"ERR Not in base"); return; } const std::wstring command = GetParam(param, ' ', 0); if (command == L"list") { UserCmdShowWardrobe(client, GetParamToEnd(param, ' ', 1)); } else if (command == L"change") { UserCmdChangeCostume(client, GetParamToEnd(param, ' ', 1)); } else { PrintUserCmdText(client, L"Command usage:"); PrintUserCmdText(client, L"/wardrobe list <head/body> - lists available bodies/heads"); PrintUserCmdText(client, L"/wardrobe change <head/body> <name> - changes your head/body to the chosen model"); } } const std::vector<Timer> timers = {{ProcessWardrobeRestarts, 1}}; void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(config); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // USER COMMAND PROCESSING /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Define usable chat commands here const std::vector commands = {{ CreateUserCommand(L"/wardrobe", L"<show/change> <head/body> [name]", UserCmdHandle, L"Shows the available heads or bodies."), }}; } // namespace Plugins::Wardrobe using namespace Plugins::Wardrobe; REFL_AUTO(type(Config), field(heads), field(bodies)) DefaultDllMainSettings(LoadSettings); // Functions to hook extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Wardrobe Plugin"); pi->shortName("wardrobe"); pi->mayUnload(true); pi->commands(&commands); pi->timers(&timers); pi->returnCode(&global->returncode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); }
6,589
C++
.cpp
191
31.240838
144
0.673364
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,353
Functions.cpp
TheStarport_FLHook/plugins/mark/Functions.cpp
#include "Mark.h" namespace Plugins::Mark { const uint UI_SELECT_ADD_SOUND = 2460046221; const uint UI_SELECT_REMOVE_SOUND = 2939827141; char MarkObject(ClientId client, uint iObject) { if (!iObject) return 1; SystemId iSystemId = Hk::Player::GetSystem(client).value(); SystemId iObjectSystemId = Hk::Solar::GetSystemBySpaceId(iObject).value(); if (iSystemId == iObjectSystemId) { for (uint i = 0; i < global->Mark[client].MarkedObjects.size(); i++) { if (global->Mark[client].MarkedObjects[i] == iObject) return 3; // already marked } } else { for (uint j = 0; j < global->Mark[client].DelayedSystemMarkedObjects.size(); j++) { if (global->Mark[client].DelayedSystemMarkedObjects[j] == iObject) return 3; // already marked } global->Mark[client].DelayedSystemMarkedObjects.push_back(iObject); Hk::Client::PlaySoundEffect(client, UI_SELECT_ADD_SOUND); return 0; } Hk::Player::MarkObj(client, iObject, 1); for (uint i = 0; i < global->Mark[client].AutoMarkedObjects.size(); i++) // remove from automarked vector { if (global->Mark[client].AutoMarkedObjects[i] == iObject) { if (i != global->Mark[client].AutoMarkedObjects.size() - 1) { global->Mark[client].AutoMarkedObjects[i] = global->Mark[client].AutoMarkedObjects[global->Mark[client].AutoMarkedObjects.size() - 1]; } global->Mark[client].AutoMarkedObjects.pop_back(); break; } } global->Mark[client].MarkedObjects.push_back(iObject); Hk::Client::PlaySoundEffect(client, UI_SELECT_ADD_SOUND); return 0; } char UnMarkObject(ClientId client, uint iObject) { if (!iObject) return 1; for (uint i = 0; i < global->Mark[client].MarkedObjects.size(); i++) { if (global->Mark[client].MarkedObjects[i] == iObject) { if (i != global->Mark[client].MarkedObjects.size() - 1) { global->Mark[client].MarkedObjects[i] = global->Mark[client].MarkedObjects[global->Mark[client].MarkedObjects.size() - 1]; } global->Mark[client].MarkedObjects.pop_back(); Hk::Player::MarkObj(client, iObject, 0); Hk::Client::PlaySoundEffect(client, UI_SELECT_REMOVE_SOUND); return 0; } } for (uint j = 0; j < global->Mark[client].AutoMarkedObjects.size(); j++) { if (global->Mark[client].AutoMarkedObjects[j] == iObject) { if (j != global->Mark[client].AutoMarkedObjects.size() - 1) { global->Mark[client].AutoMarkedObjects[j] = global->Mark[client].AutoMarkedObjects[global->Mark[client].AutoMarkedObjects.size() - 1]; } global->Mark[client].AutoMarkedObjects.pop_back(); Hk::Player::MarkObj(client, iObject, 0); Hk::Client::PlaySoundEffect(client, UI_SELECT_REMOVE_SOUND); return 0; } } for (uint k = 0; k < global->Mark[client].DelayedSystemMarkedObjects.size(); k++) { if (global->Mark[client].DelayedSystemMarkedObjects[k] == iObject) { if (k != global->Mark[client].DelayedSystemMarkedObjects.size() - 1) { global->Mark[client].DelayedSystemMarkedObjects[k] = global->Mark[client].DelayedSystemMarkedObjects[global->Mark[client].DelayedSystemMarkedObjects.size() - 1]; } global->Mark[client].DelayedSystemMarkedObjects.pop_back(); Hk::Client::PlaySoundEffect(client, UI_SELECT_REMOVE_SOUND); return 0; } } return 2; } void UnMarkAllObjects(ClientId client) { for (uint i = 0; i < global->Mark[client].MarkedObjects.size(); i++) { Hk::Player::MarkObj(client, (global->Mark[client].MarkedObjects[i]), 0); } global->Mark[client].MarkedObjects.clear(); for (uint i = 0; i < global->Mark[client].AutoMarkedObjects.size(); i++) { Hk::Player::MarkObj(client, (global->Mark[client].AutoMarkedObjects[i]), 0); } global->Mark[client].AutoMarkedObjects.clear(); global->Mark[client].DelayedSystemMarkedObjects.clear(); Hk::Client::PlaySoundEffect(client, UI_SELECT_REMOVE_SOUND); } } // namespace Plugins::Mark
3,940
C++
.cpp
111
31.657658
139
0.691704
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,354
Mark.cpp
TheStarport_FLHook/plugins/mark/Mark.cpp
/** * @date Unknown * @author M0tah (Ported by Raikkonen) * @defgroup Mark Mark * @brief * A plugin that allows players to mark objects for themselves or group * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - mark - Mark the selected object. * - unmark - Unmark the selected object. * - unmarkall - Unmark all objects. * - groupmark - Mark an object for your group. * - groupunmark - Unmark an object for your group. * - ignoregroupmarks - Ignore any marks your group make. * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * @code * { * "AutoMarkRadiusInM": 2000.0 * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * This plugin has no dependencies. */ #include "Mark.h" namespace Plugins::Mark { std::unique_ptr<Global> global = std::make_unique<Global>(); void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); global->Timers = {{TimerMarkDelay, 50, 0}, {TimerSpaceObjMark, 50, 0}}; global->config = std::make_unique<Config>(config); } /** @ingroup Mark * @brief Clear the mark settings for the specified client */ void ClearClientMark(ClientId client) { global->Mark[client].MarkEverything = false; global->Mark[client].MarkedObjects.clear(); global->Mark[client].DelayedSystemMarkedObjects.clear(); global->Mark[client].AutoMarkedObjects.clear(); global->Mark[client].DelayedAutoMarkedObjects.clear(); } /** @ingroup Mark * @brief Hook on JumpInComplete. This marks objects in the new system (for example, a group member might have marked in when they were out of system). */ void JumpInComplete(uint& iSystemId, uint& ship) { const auto err = Hk::Client::GetClientIdByShip(ship); if (!err.has_error()) return; ClientId client = err.value(); std::vector<uint> vTempMark; for (uint i = 0; i < global->Mark[client].DelayedSystemMarkedObjects.size(); i++) { if (pub::SpaceObj::ExistsAndAlive(global->Mark[client].DelayedSystemMarkedObjects[i])) { if (i != global->Mark[client].DelayedSystemMarkedObjects.size() - 1) { global->Mark[client].DelayedSystemMarkedObjects[i] = global->Mark[client].DelayedSystemMarkedObjects[global->Mark[client].DelayedSystemMarkedObjects.size() - 1]; i--; } global->Mark[client].DelayedSystemMarkedObjects.pop_back(); continue; } SystemId iTargetSystem = Hk::Solar::GetSystemBySpaceId(global->Mark[client].DelayedSystemMarkedObjects[i]).value(); if (iTargetSystem == iSystemId) { Hk::Player::MarkObj(client, global->Mark[client].DelayedSystemMarkedObjects[i], 1); vTempMark.push_back(global->Mark[client].DelayedSystemMarkedObjects[i]); if (i != global->Mark[client].DelayedSystemMarkedObjects.size() - 1) { global->Mark[client].DelayedSystemMarkedObjects[i] = global->Mark[client].DelayedSystemMarkedObjects[global->Mark[client].DelayedSystemMarkedObjects.size() - 1]; i--; } global->Mark[client].DelayedSystemMarkedObjects.pop_back(); } } for (uint i = 0; i < global->Mark[client].MarkedObjects.size(); i++) { if (!pub::SpaceObj::ExistsAndAlive(global->Mark[client].MarkedObjects[i])) global->Mark[client].DelayedSystemMarkedObjects.push_back(global->Mark[client].MarkedObjects[i]); } global->Mark[client].MarkedObjects = vTempMark; } /** @ingroup Mark * @brief Hook on LaunchComplete. Sets all the objects in the system to be marked. */ void LaunchComplete([[maybe_unused]] BaseId& iBaseId, ShipId& ship) { const auto err = Hk::Client::GetClientIdByShip(ship); if (!err.has_error()) return; ClientId client = err.value(); for (uint i = 0; i < global->Mark[client].MarkedObjects.size(); i++) { if (pub::SpaceObj::ExistsAndAlive(global->Mark[client].MarkedObjects[i])) { if (i != global->Mark[client].MarkedObjects.size() - 1) { global->Mark[client].MarkedObjects[i] = global->Mark[client].MarkedObjects[global->Mark[client].MarkedObjects.size() - 1]; i--; } global->Mark[client].MarkedObjects.pop_back(); continue; } Hk::Player::MarkObj(client, global->Mark[client].MarkedObjects[i], 1); } } /** @ingroup Mark * @brief Hook on BaseEnter. Clear marked objects. */ void BaseEnter(uint& iBaseId, ClientId& client) { global->Mark[client].AutoMarkedObjects.clear(); global->Mark[client].DelayedAutoMarkedObjects.clear(); } /** @ingroup Mark * @brief Hook on Update. Calls timers. */ int Update() { static bool bFirstTime = true; if (bFirstTime) { bFirstTime = false; // check for logged in players and reset their connection data PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) ClearClientMark(playerData->iOnlineId); } for (auto& timer : global->Timers) { if (Hk::Time::GetUnixMiliseconds() - timer.LastCall >= timer.IntervalMS) { timer.LastCall = Hk::Time::GetUnixMiliseconds(); timer.proc(); } } return 0; } /** @ingroup Mark * @brief Hook on Disconnect. CallsClearClientMark. */ void DisConnect(ClientId& client, enum EFLConnection& p2) { ClearClientMark(client); } /** @ingroup Mark * @brief Hook on LoadUserCharSettings. Loads the character's settings from the flhookuser.ini file. */ void LoadUserCharSettings(ClientId& client) { const auto* acc = Players.FindAccountFromClientID(client); const auto dir = Hk::Client::GetAccountDirName(acc); const std::string userFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; const auto fileName = Hk::Client::GetCharFileName(client); const std::string section = "general_" + wstos(fileName.value()); global->Mark[client].MarkEverything = IniGetB(userFile, section, "automarkenabled", false); global->Mark[client].IgnoreGroupMark = IniGetB(userFile, section, "ignoregroupmarkenabled", false); global->Mark[client].AutoMarkRadius = IniGetF(userFile, section, "automarkradius", global->config->AutoMarkRadiusInM); } const std::vector commands = {{ CreateUserCommand(L"/mark", L"", UserCmd_MarkObj, L"Makes the selected object appear in the important section of the contacts and have an arrow on the side of the screen, as well as have > and < " L"on the sides of the selection box."), CreateUserCommand(L"/m", L"", UserCmd_MarkObj, L"Shortcut for /mark."), CreateUserCommand(L"/unmark", L"", UserCmd_UnMarkObj, L"Unmarks the selected object marked with the /mark (/m) command."), CreateUserCommand(L"/um", L"", UserCmd_UnMarkObj, L"Shortcut from /unmark."), CreateUserCommand(L"/unmarkall", L"", UserCmd_UnMarkAllObj, L"Unmarks all objects that have been marked."), CreateUserCommand(L"/uma", L"", UserCmd_UnMarkAllObj, L"Shortcut for /unmarkall."), CreateUserCommand(L"/groupmark", L"", UserCmd_MarkObjGroup, L"Marks selected object for the entire group."), CreateUserCommand(L"/gm", L"", UserCmd_MarkObjGroup, L"Shortcut for /groupmark."), CreateUserCommand(L"/groupunmark", L"", UserCmd_UnMarkObjGroup, L"Unmarks the selected object for the entire group."), CreateUserCommand(L"/gum", L"", UserCmd_UnMarkObjGroup, L"Shortcut for /groupunmark."), CreateUserCommand(L"/ignoregroupmarks", L"<on|off>", UserCmd_SetIgnoreGroupMark, L"Ignores marks from others in your group."), CreateUserCommand(L"/automark", L"<on|off> [radius in KM]", UserCmd_AutoMark, L"Automatically marks all ships in KM radius.Bots are marked automatically in the range specified whether on or off. If you want to completely " L"disable automarking, set the radius to a number <= 0."), }}; } // namespace Plugins::Mark using namespace Plugins::Mark; // REFL_AUTO must be global namespace REFL_AUTO(type(Config), field(AutoMarkRadiusInM)) DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Mark plugin"); pi->shortName("mark"); pi->mayUnload(false); pi->commands(&commands); pi->returnCode(&global->returncode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__JumpInComplete, &JumpInComplete); pi->emplaceHook(HookedCall::IServerImpl__LaunchComplete, &LaunchComplete); pi->emplaceHook(HookedCall::IServerImpl__BaseEnter, &BaseEnter); pi->emplaceHook(HookedCall::IServerImpl__Update, &Update); pi->emplaceHook(HookedCall::IServerImpl__DisConnect, &DisConnect); pi->emplaceHook(HookedCall::FLHook__LoadCharacterSettings, &LoadUserCharSettings); }
8,850
C++
.cpp
214
38.004673
155
0.727684
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,355
UserCommands.cpp
TheStarport_FLHook/plugins/mark/UserCommands.cpp
#include "Mark.h" namespace Plugins::Mark { void UserCmd_MarkObj(ClientId& client, const std::wstring& wscParam) { auto target = Hk::Player::GetTarget(client); if (target.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(target.error())); return; } char err = MarkObject(client, target.value()); switch (err) { case 0: PrintUserCmdText(client, L"OK"); break; case 1: PrintUserCmdText(client, L"Error: You must have something targeted to mark it."); break; case 2: PrintUserCmdText(client, L"Error: You cannot mark cloaked ships."); break; case 3: PrintUserCmdText(client, L"Error: Object is already marked."); break; } } void UserCmd_UnMarkObj(ClientId& client, const std::wstring& wscParam) { auto target = Hk::Player::GetTarget(client); if (target.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(target.error())); return; } char err = UnMarkObject(client, target.value()); switch (err) { case 0: PrintUserCmdText(client, L"OK"); break; case 1: PrintUserCmdText(client, L"Error: You must have something targeted to unmark it."); break; case 2: PrintUserCmdText(client, L"Error: Object is not marked."); break; } } void UserCmd_UnMarkAllObj(ClientId& client, const std::wstring& wscParam) { UnMarkAllObjects(client); } void UserCmd_MarkObjGroup(ClientId& client, const std::wstring& wscParam) { auto target = Hk::Player::GetTarget(client); char err = MarkObject(client, target.value()); if (target.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(target.error())); return; } const auto lstMembers = Hk::Player::GetGroupMembers(client); if (lstMembers.has_error()) { return; } for (const auto& [groupClient, _] : lstMembers.value()) { if (global->Mark[groupClient].IgnoreGroupMark) continue; uint iClientShip = Hk::Player::GetShip(client).value(); if (iClientShip == target) continue; MarkObject(groupClient, target.value()); } } void UserCmd_UnMarkObjGroup(ClientId& client, const std::wstring& wscParam) { auto target = Hk::Player::GetTarget(client); char err = UnMarkObject(client, target.value()); if (target.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(target.error())); return; } const auto lstMembers = Hk::Player::GetGroupMembers(client); if (lstMembers.has_error()) { return; } for (const auto& [groupClient, _] : lstMembers.value()) { UnMarkObject(groupClient, target.value()); } } void UserCmd_SetIgnoreGroupMark(ClientId& client, const std::wstring& wscParam) { const std::wstring wscError[] = { L"Error: Invalid parameters", L"Usage: /ignoregroupmarks <on|off>", }; const auto param = ViewToWString(wscParam); if (ToLower(param) == L"off") { global->Mark[client].IgnoreGroupMark = false; CAccount const* acc = Players.FindAccountFromClientID(client); const auto fileName = Hk::Client::GetCharFileName(client); const auto dir = Hk::Client::GetAccountDirName(acc); if (fileName.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(fileName.value()); IniWrite(scUserFile, scSection, "automarkenabled", "no"); PrintUserCmdText(client, L"Accepting marks from the group"); } } else if (ToLower(param) == L"on") { global->Mark[client].IgnoreGroupMark = true; CAccount const* acc = Players.FindAccountFromClientID(client); const auto fileName = Hk::Client::GetCharFileName(client); const auto dir = Hk::Client::GetAccountDirName(acc); if (fileName.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(fileName.value()); IniWrite(scUserFile, scSection, "automarkenabled", "yes"); PrintUserCmdText(client, L"Ignoring marks from the group"); } } else { PRINT_ERROR(); } } void UserCmd_AutoMark(ClientId& client, const std::wstring& wscParam) { if (global->config->AutoMarkRadiusInM <= 0.0f) // automarking disabled { PrintUserCmdText(client, L"Command disabled"); return; } std::wstring wscError[] = { L"Error: Invalid parameters", L"Usage: /automark <on|off> [radius in KM]", }; std::wstring wscEnabled = ToLower(GetParam(wscParam, ' ', 0)); if (!wscParam.length() || (wscEnabled != L"on" && wscEnabled != L"off")) { PRINT_ERROR(); return; } std::wstring wscRadius = GetParam(wscParam, ' ', 1); float fRadius = 0.0f; if (wscRadius.length()) { fRadius = ToFloat(wscRadius); } // I think this section could be done better, but I can't think of it now.. if (!global->Mark[client].MarkEverything) { if (wscRadius.length()) global->Mark[client].AutoMarkRadius = fRadius * 1000; if (wscEnabled == L"on") // AutoMark is being enabled { global->Mark[client].MarkEverything = true; CAccount const* acc = Players.FindAccountFromClientID(client); const auto fileName = Hk::Client::GetCharFileName(client); const auto dir = Hk::Client::GetAccountDirName(acc); if (fileName.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(fileName.value()); IniWrite(scUserFile, scSection, "automark", "yes"); if (wscRadius.length()) IniWrite(scUserFile, scSection, "automarkradius", std::to_string(global->Mark[client].AutoMarkRadius)); } PrintUserCmdText(client, std::format(L"Automarking turned on within a {:.2f} KM radius", global->Mark[client].AutoMarkRadius / 1000)); } else if (wscRadius.length()) { CAccount const* acc = Players.FindAccountFromClientID(client); const auto fileName = Hk::Client::GetCharFileName(client); const auto dir = Hk::Client::GetAccountDirName(acc); if (fileName.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(fileName.value()); IniWrite(scUserFile, scSection, "automarkradius", std::to_string(global->Mark[client].AutoMarkRadius)); } PrintUserCmdText(client, std::format(L"Radius changed to {:.2f} KMs", fRadius)); } } else { if (wscRadius.length()) global->Mark[client].AutoMarkRadius = fRadius * 1000; if (wscEnabled == L"off") // AutoMark is being disabled { global->Mark[client].MarkEverything = false; CAccount const* acc = Players.FindAccountFromClientID(client); const auto fileName = Hk::Client::GetCharFileName(client); const auto dir = Hk::Client::GetAccountDirName(acc); if (fileName.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(fileName.value()); IniWrite(scUserFile, scSection, "automark", "no"); if (wscRadius.length()) IniWrite(scUserFile, scSection, "automarkradius", std::to_string(global->Mark[client].AutoMarkRadius)); } if (wscRadius.length()) PrintUserCmdText(client, std::format(L"Automarking turned off; radius changed to {:.2f} KMs", global->Mark[client].AutoMarkRadius / 1000)); else PrintUserCmdText(client, L"Automarking turned off"); } else if (wscRadius.length()) { CAccount const* acc = Players.FindAccountFromClientID(client); const auto fileName = Hk::Client::GetCharFileName(client); const auto dir = Hk::Client::GetAccountDirName(acc); if (fileName.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(fileName.value()); IniWrite(scUserFile, scSection, "automarkradius", std::to_string(global->Mark[client].AutoMarkRadius)); } PrintUserCmdText(client, std::format(L"Radius changed to {:.2f} KMs", fRadius)); } } } }
8,069
C++
.cpp
234
30.491453
144
0.689355
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,356
Timers.cpp
TheStarport_FLHook/plugins/mark/Timers.cpp
#include "Mark.h" namespace Plugins::Mark { void TimerSpaceObjMark() { try { if (global->config->AutoMarkRadiusInM <= 0.0f) // automarking disabled return; PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { uint client = playerData->iOnlineId; auto ship = Hk::Player::GetShip(client); if (ship.has_error() || global->Mark[client].AutoMarkRadius <= 0.0f) // docked or does not want any marking continue; auto [clientPosition, _] = Hk::Solar::GetLocation(ship.value(), IdType::Ship).value(); for (uint i = 0; i < global->Mark[client].AutoMarkedObjects.size(); i++) { auto [targetPosition, _] = Hk::Solar::GetLocation(global->Mark[client].AutoMarkedObjects[i], IdType::Solar).value(); if (Hk::Math::Distance3D(targetPosition, clientPosition) > global->Mark[client].AutoMarkRadius) { Hk::Player::MarkObj(client, global->Mark[client].AutoMarkedObjects[i], 0); global->Mark[client].DelayedAutoMarkedObjects.push_back(global->Mark[client].AutoMarkedObjects[i]); if (i != global->Mark[client].AutoMarkedObjects.size() - 1) { global->Mark[client].AutoMarkedObjects[i] = global->Mark[client].AutoMarkedObjects[global->Mark[client].AutoMarkedObjects.size() - 1]; i--; } global->Mark[client].AutoMarkedObjects.pop_back(); } } for (uint i = 0; i < global->Mark[client].DelayedAutoMarkedObjects.size(); i++) { if (pub::SpaceObj::ExistsAndAlive(global->Mark[client].DelayedAutoMarkedObjects[i])) { if (i != global->Mark[client].DelayedAutoMarkedObjects.size() - 1) { global->Mark[client].DelayedAutoMarkedObjects[i] = global->Mark[client].DelayedAutoMarkedObjects[global->Mark[client].DelayedAutoMarkedObjects.size() - 1]; i--; } global->Mark[client].DelayedAutoMarkedObjects.pop_back(); continue; } auto [targetPosition, _] = Hk::Solar::GetLocation(global->Mark[client].DelayedAutoMarkedObjects[i], IdType::Solar).value(); if (!(Hk::Math::Distance3D(targetPosition, clientPosition) > global->Mark[client].AutoMarkRadius)) { Hk::Player::MarkObj(client, global->Mark[client].DelayedAutoMarkedObjects[i], 1); global->Mark[client].AutoMarkedObjects.push_back(global->Mark[client].DelayedAutoMarkedObjects[i]); if (i != global->Mark[client].DelayedAutoMarkedObjects.size() - 1) { global->Mark[client].DelayedAutoMarkedObjects[i] = global->Mark[client].DelayedAutoMarkedObjects[global->Mark[client].DelayedAutoMarkedObjects.size() - 1]; i--; } global->Mark[client].DelayedAutoMarkedObjects.pop_back(); } } } } catch (...) { } } void TimerMarkDelay() { if (!global->DelayedMarks.size()) return; mstime tmTimeNow = Hk::Time::GetUnixMiliseconds(); for (auto mark = global->DelayedMarks.begin(); mark != global->DelayedMarks.end();) { if (tmTimeNow - mark->time > 50) { auto [itemPosition, _] = Hk::Solar::GetLocation(mark->iObj, IdType::Solar).value(); SystemId iItemSystem = Hk::Solar::GetSystemBySpaceId(mark->iObj).value(); // for all players PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; if (Players[client].systemId == iItemSystem) { auto [playerPosition, _] = Hk::Solar::GetLocation(Players[client].shipId, IdType::Ship).value(); if (Hk::Math::Distance3D(playerPosition, itemPosition) <= LOOT_UNSEEN_RADIUS) { MarkObject(client, mark->iObj); } } } mark = global->DelayedMarks.erase(mark); } else { mark++; } } } } // namespace Plugins::Mark
3,798
C++
.cpp
100
32.58
128
0.668564
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,357
BountyHunt.cpp
TheStarport_FLHook/plugins/bountyhunt/BountyHunt.cpp
/** * @date Unknown * @author ||KOS||Acid (Ported by Raikkonen 2022) * @defgroup BountyHunt Bounty Hunt * @brief * The "Bounty Hunt" plugin allows players to put bounties on each other that can be collected by destroying that player. * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - bountyhunt <player> <amount> [timelimit] - Places a bounty on the specified player. When another player kills them, they gain <credits>. * - bountyhuntid <id> <amount> [timelimit] - Same as above but with an id instead of a player name. Use /ids * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * @code * { * "enableBountyHunt": true, * "levelProtect": 0, * "minimalHuntTime": 1, * "maximumHuntTime": 240, * "defaultHuntTime": 30 * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * None */ #include "BountyHunt.h" namespace Plugins::BountyHunt { const std::unique_ptr<Global> global = std::make_unique<Global>(); /** @ingroup BountyHunt * @brief Removed an active bounty hunt */ void RemoveBountyHunt(const BountyHunt& bounty) { auto it = global->bountyHunt.begin(); while (it != global->bountyHunt.end()) { if (it->targetId == bounty.targetId && it->initiatorId == bounty.initiatorId) { it = global->bountyHunt.erase(it); } else { ++it; } } } /** @ingroup BountyHunt * @brief Print all the active bounty hunts to the player */ void PrintBountyHunts(ClientId& client) { if (global->bountyHunt.begin() != global->bountyHunt.end()) { PrintUserCmdText(client, L"Offered Bounty Hunts:"); for (auto const& [targetId, initiatorId, target, initiator, cash, end] : global->bountyHunt) { PrintUserCmdText( client, std::format(L"Kill {} and earn {} credits ({} minutes left)", target, cash, ((end - Hk::Time::GetUnixSeconds()) / 60))); } } } /** @ingroup BountyHunt * @brief User Command for /bountyhunt. Creates a bounty against a specified player. */ void UserCmdBountyHunt(ClientId& client, const std::wstring& param) { if (!global->config->enableBountyHunt) return; const std::wstring target = GetParam(param, ' ', 0); const uint prize = MultiplyUIntBySuffix(GetParam(param, ' ', 1)); const std::wstring timeString = GetParam(param, ' ', 2); if (!target.length() || prize == 0) { PrintUserCmdText(client, L"Usage: /bountyhunt <playername> <credits> <time>"); PrintBountyHunts(client); return; } uint time = wcstol(timeString.c_str(), nullptr, 10); const auto targetId = Hk::Client::GetClientIdFromCharName(target); int rankTarget = Hk::Player::GetRank(targetId.value()).value(); if (targetId == UINT_MAX || Hk::Client::IsInCharSelectMenu(targetId.value())) { PrintUserCmdText(client, std::format(L"{} is not online.", target)); return; } if (rankTarget < global->config->levelProtect) { PrintUserCmdText(client, L"Low level players may not be hunted."); return; } // clamp the hunting time to configured range, or set default if not specified if (time) { time = std::min(global->config->maximumHuntTime, std::max(global->config->minimalHuntTime, time)); } else { time = global->config->defaultHuntTime; } if (uint clientCash = Hk::Player::GetCash(client).value(); clientCash < prize) { PrintUserCmdText(client, L"You do not possess enough credits."); return; } for (const auto& bh : global->bountyHunt) { if (bh.initiatorId == client && bh.targetId == targetId) { PrintUserCmdText(client, L"You already have a bounty on this player."); return; } } Hk::Player::RemoveCash(client, prize); const std::wstring initiator = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); BountyHunt bh; bh.initiatorId = client; bh.end = Hk::Time::GetUnixMiliseconds() + (static_cast<mstime>(time) * 60000); bh.initiator = initiator; bh.cash = prize; bh.target = target; bh.targetId = targetId.value(); global->bountyHunt.push_back(bh); Hk::Message::MsgU( bh.initiator + L" offers " + std::to_wstring(bh.cash) + L" credits for killing " + bh.target + L" in " + std::to_wstring(time) + L" minutes."); } /** @ingroup BountyHunt * @brief User Command for /bountyhuntid. Creates a bounty against a specified player. */ void UserCmdBountyHuntID(ClientId& client, const std::wstring& param) { if (!global->config->enableBountyHunt) return; const std::wstring target = GetParam(param, ' ', 0); const std::wstring credits = GetParam(param, ' ', 1); const std::wstring time = GetParam(param, ' ', 2); if (!target.length() || !credits.length()) { PrintUserCmdText(client, L"Usage: /bountyhuntid <id> <credits> <time>"); PrintBountyHunts(client); return; } ClientId clientTarget = ToInt(target); if (!Hk::Client::IsValidClientID(clientTarget) || Hk::Client::IsInCharSelectMenu(clientTarget)) { PrintUserCmdText(client, L"Error: Invalid client id."); return; } const std::wstring charName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(clientTarget)); const auto paramNew = std::wstring(charName + L" " + credits + L" " + time); UserCmdBountyHunt(client, paramNew); } /** @ingroup BountyHunt * @brief Checks for expired bounties. */ void BhTimeOutCheck() { auto bounty = global->bountyHunt.begin(); while (bounty != global->bountyHunt.end()) { if (bounty->end < Hk::Time::GetUnixMiliseconds()) { if (const auto cashError = Hk::Player::AddCash(bounty->target, bounty->cash); cashError.has_error()) { Console::ConWarn(wstos(Hk::Err::ErrGetText(cashError.error()))); return; } Hk::Message::MsgU(bounty->target + L" was not hunted down and earned " + std::to_wstring(bounty->cash) + L" credits."); bounty = global->bountyHunt.erase(bounty); } else { ++bounty; } } } /** @ingroup BountyHunt * @brief Processes a ship death to see if it was part of a bounty. */ void BillCheck(ClientId& client, ClientId& killer) { for (auto& bounty : global->bountyHunt) { if (bounty.targetId == client) { if (killer == 0 || client == killer) { Hk::Message::MsgU(L"The hunt for " + bounty.target + L" still goes on."); continue; } if (std::wstring winnerCharacterName = reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(killer)); !winnerCharacterName.empty()) { if (const auto cashError = Hk::Player::AddCash(winnerCharacterName, bounty.cash); cashError.has_error()) { Console::ConWarn(wstos(Hk::Err::ErrGetText(cashError.error()))); return; } Hk::Message::MsgU(winnerCharacterName + L" has killed " + bounty.target + L" and earned " + std::to_wstring(bounty.cash) + L" credits."); } else { if (const auto cashError = Hk::Player::AddCash(bounty.initiator, bounty.cash); cashError.has_error()) { Console::ConWarn(wstos(Hk::Err::ErrGetText(cashError.error()))); return; } } RemoveBountyHunt(bounty); BillCheck(killer, killer); break; } } } // Timer Hook const std::vector<Timer> timers = {{BhTimeOutCheck, 60}}; /** @ingroup BountyHunt * @brief Hook for SendDeathMsg to call BillCheck */ void SendDeathMsg([[maybe_unused]] const std::wstring& msg, [[maybe_unused]] const SystemId& system, ClientId& clientVictim, ClientId& clientKiller) { if (global->config->enableBountyHunt) { BillCheck(clientVictim, clientKiller); } } void checkIfPlayerFled(ClientId& client) { for (auto& it : global->bountyHunt) { if (it.targetId == client) { if (const auto cashError = Hk::Player::AddCash(it.initiator, it.cash); cashError.has_error()) { Console::ConWarn(wstos(Hk::Err::ErrGetText(cashError.error()))); return; } Hk::Message::MsgU(L"The coward " + it.target + L" has fled. " + it.initiator + L" has been refunded."); RemoveBountyHunt(it); return; } } } /** @ingroup BountyHunt * @brief Hook for Disconnect to see if the player had a bounty on them */ void DisConnect(ClientId& client, [[maybe_unused]] const enum EFLConnection& state) { checkIfPlayerFled(client); } /** @ingroup BountyHunt * @brief Hook for CharacterSelect to see if the player had a bounty on them */ void CharacterSelect([[maybe_unused]] const std::string& charFilename, ClientId& client) { checkIfPlayerFled(client); } // Client command processing const std::vector commands = {{ CreateUserCommand(L"/bountyhunt", L"<charname> <credits> [minutes]", UserCmdBountyHunt, L"Places a bounty on the specified player. When another player kills them, they gain <credits>."), CreateUserCommand( L"/bountyhuntid", L"<id> <credits> [minutes]", UserCmdBountyHuntID, L"Same as above but with an id instead of a player name. Use /ids"), }}; // Load Settings void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(config); } } // namespace Plugins::BountyHunt /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FLHOOK STUFF /////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace Plugins::BountyHunt; REFL_AUTO(type(Config), field(enableBountyHunt), field(levelProtect), field(minimalHuntTime), field(maximumHuntTime), field(defaultHuntTime)) DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Bounty Hunt"); pi->shortName("bountyhunt"); pi->mayUnload(false); pi->commands(&commands); pi->timers(&timers); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::IEngine__SendDeathMessage, &SendDeathMsg); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__DisConnect, &DisConnect); pi->emplaceHook(HookedCall::IServerImpl__CharacterSelect, &CharacterSelect, HookStep::After); }
10,397
C++
.cpp
298
31.543624
149
0.68419
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,358
CashManager.cpp
TheStarport_FLHook/plugins/cash_manager/CashManager.cpp
/** * @date July 2022 * @author Lazrius & MrNen * @defgroup CashManager Cash Manager * @brief * The "Cash Manager" plugin serves as a utility for which players can manage their money through a shared bank * and transfer money between characters with ease. It also exposes functionality for other plugins to leverage * this shared pool of money. * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - bank withdraw <cash> - Withdraw money from the bank of the active account * - bank withdraw <bankId> <password> - Withdraw cash from a different account bank using an id and password. * - bank deposit <cash> - Deposit cash into the current account bank * - bank transfer <bankId> <cash> - Transfer money from the current account bank to another one. * - bank password [confirm] - Generates a password for the current bank, will warn if confirm not specified. * - bank info [pass] - Shows your bank account information, if pass provided, will include the password (if set) * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * @code * { * "minimumTransfer": 0, * "maximumTransfer": 0, * "depositSurplusOnDock": true, * "cashThreshold": 1800000000, * "blockedSystems": [], * "cheatDetection": true, * "minimumTime": 60, * "eraseTransactionsAfterDaysPassed": 365, * "transferFee": 0 * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * - ConsumeBankCash - Use this to take money directly from the current account bank for an action. * * @paragraph optional Optional Plugin Dependencies * This plugin has no dependencies. */ #include "CashManager.h" #include "refl.hpp" constexpr int TransactionsPerPage = 10; // Setup Doxygen Group /** @defgroup CashManager Cash Manager */ namespace Plugins::CashManager { const std::unique_ptr<Global> global = std::make_unique<Global>(); std::wstring GetHumanTime(long long unix) { tm ts; localtime_s(&ts, &unix); std::wstring time; time.reserve(80); wcsftime(time.data(), time.size(), L"%a %Y-%m-%d %H:%M:%S %Z", &ts); return time; } void LoadSettings() { const auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(config); for (const auto& system : global->config->blockedSystems) { global->config->blockedSystemsHashed.emplace_back(CreateID(system.c_str())); } Sql::CreateSqlTables(); Sql::RemoveTransactionsOverSpecifiedDays(global->config->eraseTransactionsAfterDaysPassed); } void WithdrawMoneyFromBank(const Bank& bank, uint withdrawal, ClientId client) { if (const auto currentValue = Hk::Player::GetShipValue(client); currentValue.has_error() || (global->config->cashThreshold > 0 && currentValue.value() > global->config->cashThreshold)) { PrintUserCmdText(client, L"Error: Your ship value is too high. Unload some credits or decrease ship value before withdrawing."); } if (bank.cash < withdrawal) { PrintUserCmdText(client, std::format(L"Error: Not enough credits, this bank only has {} credits", bank.cash)); return; } if (withdrawal == 0) { PrintUserCmdText(client, std::format(L"Error: Invalid withdraw amount, please input a positive number. {}", bank.cash)); return; } const int64 fee = static_cast<long long>(withdrawal) + global->config->transferFee; if (global->config->transferFee > 0 && static_cast<int64>(bank.cash) - fee < 0) { PrintUserCmdText(client, std::format(L"Error: Not enough cash in bank for withdrawal and fee ({}).", ToMoneyStr(static_cast<int>(fee)))); return; } if (Sql::WithdrawCash(bank, fee)) { Hk::Player::AddCash(client, withdrawal); PrintUserCmdText(client, std::format(L"Successfully withdrawn {} credits", ToMoneyStr(withdrawal))); return; } PrintUserCmdText(client, L"Unknown error. Unable to withdraw cash."); } void DepositMoney(const Bank& bank, uint deposit, ClientId client) { if (deposit == 0) { PrintUserCmdText(client, L"Error: Invalid deposit amount, please input a positive number."); return; } if (const uint playerCash = Hk::Player::GetCash(client).value(); playerCash < deposit) { PrintUserCmdText(client, L"Error: Not enough credits, make sure to input a deposit number less than your balance."); return; } if (Sql::DepositCash(bank, deposit)) { Hk::Player::RemoveCash(client, deposit); PrintUserCmdText(client, std::format(L"Successfully deposited {} credits", ToMoneyStr(deposit))); return; } PrintUserCmdText(client, L"Unknown Error. Unable to deposit cash."); } // /bank withdraw account password amount void UserCmdWithdrawMoneyByPassword(ClientId& client, const std::wstring& param) { const auto accountIdentifier = GetParam(param, ' ', 1); const auto password = GetParam(param, ' ', 2); const auto withdrawal = MultiplyUIntBySuffix(GetParam(param, ' ', 3)); if (withdrawal == 0) { PrintUserCmdText(client, L"Error: Invalid withdraw amount, please input a positive number."); return; } const auto bank = Sql::GetBankByIdentifier(accountIdentifier); if (!bank.has_value()) { PrintUserCmdText(client, L"Error: Bank identifier could was not valid."); return; } if (password != bank->bankPassword) { PrintUserCmdText(client, L"Error: Invalid Password."); return; } WithdrawMoneyFromBank(bank.value(), withdrawal, client); } // /bank transfer targetBank amount void TransferMoney(ClientId client, const std::wstring& param, const Bank& bank) { const auto targetBankIdentifier = GetParam(param, ' ', 1); const auto amount = MultiplyUIntBySuffix(GetParam(param, ' ', 2)); if (targetBankIdentifier.empty() || bank.identifier.empty()) { PrintUserCmdText(client, L"Error: No bank identifier provided or sending from a bank without an identifier."); return; } if (amount == 0) { PrintUserCmdText(client, L"Error: Invalid amount, please input a positive number."); return; } const auto fee = amount + global->config->transferFee; if (static_cast<int64>(bank.cash) - (amount + fee) < 0) { const auto ifFee = std::format(L"and fee ({})", amount + fee); PrintUserCmdText(client, std::format(L"Error: Not enough cash in bank for transfer {}.", fee > 0 ? ifFee : L"")); return; } const auto targetBank = Sql::GetBankByIdentifier(targetBankIdentifier); if (!targetBank) { PrintUserCmdText(client, L"Error: Target Bank not found"); return; } if (!Sql::TransferCash(bank, targetBank.value(), amount, fee)) { PrintUserCmdText(client, L"Internal server error. Failed to transfer cash."); return; } PrintUserCmdText(client, std::format(L"Successfully transferred {} credits to {}", ToMoneyStr(amount), bank.identifier)); Sql::AddTransaction( bank, std::format("Bank {} -> Bank {}", wstos(bank.identifier), wstos(targetBank->identifier)), -(static_cast<int>((amount + fee)))); } void ShowBankInfo(ClientId& client, const Bank& bank, bool showPass) { PrintUserCmdText(client, std::format(L"Your Bank Information:\n" L"| Identifier: {} \n" L"| Password: {}\n" L"| Credits: {}", bank.identifier.empty() ? L"N/A" : bank.identifier, showPass ? bank.bankPassword : L"*****", ToMoneyStr(bank.cash))); if (!showPass) { PrintUserCmdText(client, L"Use /bank info pass to make the password visible."); } } void DepositSurplusCash(ClientId& client) { if (!global->config->depositSurplusOnDock) return; if (const auto currentValue = Hk::Player::GetShipValue(client).value(); global->config->cashThreshold < currentValue) { uint playerCash = Hk::Player::GetCash(client).value(); uint surplusCash = currentValue - global->config->cashThreshold + global->config->safetyMargin; if (!playerCash) return; if (playerCash < surplusCash) surplusCash = playerCash; const CAccount* acc = Players.FindAccountFromClientID(client); if (const auto bank = Sql::GetOrCreateBank(acc); Sql::DepositCash(bank, surplusCash)) { Hk::Player::RemoveCash(client, surplusCash); PrintUserCmdText( client, std::format(L"You have reached maximum credit threshold, surplus of {} credits has been deposited to your bank.", surplusCash)); Hk::Player::SaveChar(client); return; } PrintUserCmdText(client, L"Transaction barred. Your ship value is too high. Deposit some cash into your bank using the /bank command."); global->returnCode = ReturnCode::SkipAll; } } void UserCommandHandler(ClientId& client, const std::wstring& param) { // Checks before we handle any sort of command or process. if (const int secs = Hk::Player::GetOnlineTime(Hk::Client::GetCharacterNameByID(client).value()).value(); static_cast<uint>(secs) < global->config->minimumTime / 60) { PrintUserCmdText(client, L"Error: You cannot interact with the bank. This character is too new."); return; } if (ClientInfo[client].iTradePartner) { PrintUserCmdText(client, L"Error: You are currently in a trade."); return; } const auto currentSystem = Hk::Player::GetSystem(client); if (currentSystem.has_error()) { PrintUserCmdText(client, L"Unable to decipher player location."); return; } if (const auto& blockedSystems = global->config->blockedSystemsHashed; std::ranges::find(blockedSystems, currentSystem.value()) != blockedSystems.end()) { PrintUserCmdText(client, L"Error: You are in a blocked system, you are unable to access the bank."); return; } const CAccount* acc = Players.FindAccountFromClientID(client); // Sending money from one bank to another if (const auto cmd = GetParam(param, L' ', 0); cmd == L"transfer") { const auto bank = Sql::GetOrCreateBank(acc); TransferMoney(client, param, bank); } else if (cmd == L"password") { const auto bank = Sql::GetOrCreateBank(acc); if (GetParam(param, ' ', 1) == L"confirm") { Sql::SetNewPassword(bank); ShowBankInfo(client, bank, true); return; } PrintUserCmdText(client, L"This will generate a new password and the previous will be invalid"); PrintUserCmdText(client, std::format(L"Your currently set password is {} if you are sure you want to regenerate your password type \"/bank password confirm\". ", bank.bankPassword)); } else if (cmd == L"identifier") { const auto bank = Sql::GetOrCreateBank(acc); const auto identifier = GetParam(param, ' ', 1); if (bank.identifier.empty() && identifier.empty()) { PrintUserCmdText(client, L"Your bank currently does not have an identifier set.\n" L"Generating an identifier means anybody with the identifier and password can access your bank.\n" L"Are you sure you want to generate an identifier for this account?\n" L"Please type \"/bank identifier <your banks identifier>\" to set one."); return; } if (const auto existingBank = Sql::GetBankByIdentifier(identifier); existingBank.has_value()) { PrintUserCmdText(client, L"Another bank is already using this identifier. Identifiers must be unique."); return; } Sql::SetOrClearIdentifier(bank, wstos(identifier)); PrintUserCmdText(client, std::format(L"Bank identifier set to: {}", identifier)); } else if (cmd == L"withdraw") { if (const uint withdrawAmount = MultiplyUIntBySuffix(GetParam(param, ' ', 1)); withdrawAmount > 0) { const auto bank = Sql::GetOrCreateBank(acc); WithdrawMoneyFromBank(bank, withdrawAmount, client); return; } UserCmdWithdrawMoneyByPassword(client, param); } else if (cmd == L"deposit") { const uint depositAmount = MultiplyUIntBySuffix(GetParam(param, ' ', 1)); const auto bank = Sql::GetOrCreateBank(acc); DepositMoney(bank, depositAmount, client); DepositSurplusCash(client); } else if (cmd == L"info") { const auto bank = Sql::GetOrCreateBank(acc); const bool showPass = GetParam(param, ' ', 1) == L"pass"; ShowBankInfo(client, bank, showPass); } else if (cmd == L"transactions") { const auto bank = Sql::GetOrCreateBank(acc); if (const auto list = GetParam(param, ' ', 1); list == L"list") { int totalTransactions = Sql::CountTransactions(bank); const auto page = ToInt(GetParam(param, ' ', 2)); if (!page) { PrintUserCmdText(client, std::format(L"You currently have a total of {} transactions, spanning {} pages. Run this command again, adding a page number to view " L"the desired transactions.", totalTransactions, totalTransactions / TransactionsPerPage)); return; } if (page > totalTransactions / TransactionsPerPage) { PrintUserCmdText(client, L"Page not found."); return; } uint i = page * TransactionsPerPage; for (const auto transactions = Sql::ListTransactions(bank, TransactionsPerPage, i); const auto& transaction : transactions) { PrintUserCmdText(client, std::format(L"%{}.) {} {}", i, transaction.accessor, transaction.amount)); i++; } return; } const auto transactions = Sql::ListTransactions(bank, TransactionsPerPage); if (transactions.empty()) { PrintUserCmdText(client, L"You have no transactions for this bank currently."); return; } int currentTransactions = Sql::CountTransactions(bank); PrintUserCmdText(client, std::format(L"Showing you {} of {} total transactions (most recent):", transactions.size(), currentTransactions)); uint i = 0; for (const auto& transaction : transactions) { i++; PrintUserCmdText(client, std::format(L"{}.) {} {}", i, transaction.accessor, transaction.amount)); } } else { PrintUserCmdText(client, std::format(L"Here are the available commands for the bank plugin.\n" L"\"/bank withdraw <amount>\" will withdraw money from your account's bank.\n" L"\"/bank withdraw <amount>\" will withdraw money from your account's bank.\n" L"\"/bank withdraw <identifier> <password> <amount>\" will withdraw money from a specified bank that has a password set up.\n" L"\"/bank deposit <amount>\" will deposit money from your character to your bank.\n" L"\"/bank transfer <identifier> <amount>\" transfer money from your current bank to the target bank's identifier.\n" L"\"/bank password \" will regenerate your password.\n" L"\"/bank identifier \" will allow you set an identifier. This will allow you to make transfers to other banks and access money " L"from other accounts.\n" L"\"/bank transactions \" will display the last {} transactions.\n" L"\"/bank transactions <list> [page]\" will display the full list of transactions.", TransactionsPerPage)); } } const std::vector commands = {{CreateUserCommand(L"/bank", L"", UserCommandHandler, std::format(L"A series of commands for storing money that can be shared among multiple characters.\n" L"\"/bank withdraw <amount>\" will withdraw money from your account's bank.\n" L"\"/bank withdraw <amount>\" will withdraw money from your account's bank.\n" L"\"/bank withdraw <identifier> <password> <amount>\" will withdraw money from a specified bank that has a password set up.\n" L"\"/bank deposit <amount>\" will deposit money from your character to your bank.\n" L"\"/bank transfer <identifier> <amount>\" transfer money from your current bank to the target bank's identifier.\n" L"\"/bank password \" will regenerate your password.\n" L"\"/bank identifier \" will allow you set an identifier. This will allow you to make transfers to other banks and access money from other " L"accounts.\n" L"\"/bank transactions \" will display the last {} transactions.\n" L"\"/bank transactions <list> [page]\" will display the full list of transactions.", TransactionsPerPage))}}; BankCode IpcConsumeBankCash(const CAccount* account, uint cashAmount, const std::string& transactionSource) { if (cashAmount <= 0) { return BankCode::CannotWithdrawNegativeNumber; } if (cashAmount > global->config->maximumTransfer) { return BankCode::AboveMaximumTransferThreshold; } if (cashAmount < global->config->minimumTransfer) { return BankCode::BelowMinimumTransferThreshold; } const auto bank = Sql::GetOrCreateBank(account); if (bank.cash < cashAmount) { return BankCode::NotEnoughMoney; } const uint fee = cashAmount + global->config->transferFee; if (global->config->transferFee > 0 && static_cast<int64>(bank.cash) - fee < 0) { return BankCode::BankCouldNotAffordTransfer; } if (Sql::WithdrawCash(bank, fee)) { Sql::AddTransaction(bank, transactionSource, cashAmount); return BankCode::Success; } return BankCode::InternalServerError; } void BaseEnter([[maybe_unused]] BaseId& baseId, ClientId& client) { DepositSurplusCash(client); } void PlayerLaunch([[maybe_unused]] ShipId& shipId, ClientId& client) { DepositSurplusCash(client); } CashManagerCommunicator::CashManagerCommunicator(const std::string& plugin) : PluginCommunicator(plugin) { this->ConsumeBankCash = IpcConsumeBankCash; } } // namespace Plugins::CashManager using namespace Plugins::CashManager; // REFL_AUTO must be global namespace REFL_AUTO(type(Config), field(minimumTransfer), field(eraseTransactionsAfterDaysPassed), field(blockedSystems), field(depositSurplusOnDock), field(maximumTransfer), field(cheatDetection), field(minimumTime), field(transferFee), field(cashThreshold), field(safetyMargin)); DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name(CashManagerCommunicator::pluginName); pi->shortName("cash_manager"); pi->mayUnload(true); pi->commands(&commands); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__BaseEnter, &BaseEnter, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch, HookStep::After); }
18,594
C++
.cpp
448
37.03125
157
0.703861
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,359
Sql.cpp
TheStarport_FLHook/plugins/cash_manager/Sql.cpp
#include <random> #include "CashManager.h" namespace Plugins::CashManager::Sql { void CreateSqlTables() { if (global->sql.tableExists("banks")) { return; } global->sql.exec("CREATE TABLE banks " "(id TEXT(36, 36) PRIMARY KEY UNIQUE NOT NULL, " "bankPassword TEXT(5, 5) NOT NULL, " "cash INTEGER NOT NULL DEFAULT(0), " "identifier TEXT(12, 12) UNIQUE);" "CREATE TABLE transactions(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, " "timestamp INTEGER NOT NULL, " "amount INTEGER NOT NULL, " "accessor TEXT(32, 32) NOT NULL, " "bankId TEXT(36, 36) REFERENCES banks(id) ON UPDATE CASCADE NOT NULL);"); global->sql.exec("CREATE INDEX IDX_bankId ON transactions (bankId DESC);"); } std::string GenerateBankPassword() { const std::vector letters = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; std::random_device dev; std::mt19937 r(dev()); std::uniform_int_distribution<std::size_t> randLetter(0, letters.size() - 1); std::uniform_int_distribution<std::size_t> randNumber(0, 9); std::stringstream ss; ss << letters[randLetter(r)] << randNumber(r) << randNumber(r) << randNumber(r) << randNumber(r); return ss.str(); } std::optional<Bank> GetBankByIdentifier(std::wstring identifier) { SQLite::Statement findExistingQuery(global->sql, "SELECT id, bankPassword, cash FROM banks WHERE identifier = ?"); findExistingQuery.bind(1, wstos(identifier)); if (!findExistingQuery.executeStep()) { return std::nullopt; } return std::make_optional<Bank>({findExistingQuery.getColumn(0).getString(), stows(findExistingQuery.getColumn(1).getString()), identifier, static_cast<uint64>(findExistingQuery.getColumn(2).getInt64())}); } std::wstring SetNewPassword(const Bank& bank) { const auto newPass = GenerateBankPassword(); SQLite::Statement replacePassword(global->sql, "UPDATE banks SET bankPassword = ? WHERE id = ?;"); replacePassword.bind(1, newPass); replacePassword.bind(2, bank.accountId); return stows(newPass); } Bank GetOrCreateBank(const CAccount* account) { const auto accountIdString = wstos(account->wszAccId); SQLite::Statement findExistingQuery(global->sql, "SELECT bankPassword, identifier, cash FROM banks WHERE id = ?"); findExistingQuery.bind(1, accountIdString); // If already exists if (findExistingQuery.executeStep()) { return {accountIdString, stows(findExistingQuery.getColumn(0).getString()), stows(findExistingQuery.getColumn(1).getString()), static_cast<uint64>(findExistingQuery.getColumn(2).getInt64())}; } const auto password = GenerateBankPassword(); SQLite::Statement createBankQuery(global->sql, "INSERT INTO banks (id, bankPassword) VALUES(?, ?);"); createBankQuery.bind(1, accountIdString); createBankQuery.bind(2, password); createBankQuery.exec(); return {accountIdString, stows(password), L"", 0}; } // Returns 0 if it failed to withdraw cash, 1 otherwise. bool WithdrawCash(const Bank& bank, int64 withdrawalAmount) { SQLite::Statement transaction(global->sql, "UPDATE banks SET cash = cash - ? WHERE id = ? AND cash - ? >= 0 ;"); transaction.bind(1, withdrawalAmount); transaction.bind(2, bank.accountId); transaction.bind(3, withdrawalAmount); return static_cast<bool>(transaction.exec()); } // Returns 0 if it failed to deposit cash, 1 otherwise. bool DepositCash(const Bank& bank, uint depositAmount) { SQLite::Statement transaction(global->sql, "UPDATE banks SET cash = cash + ? WHERE id = ?;"); transaction.bind(1, depositAmount); transaction.bind(2, bank.accountId); return static_cast<bool>(transaction.exec()); } bool TransferCash(const Bank& source, const Bank& target, const int amount, const int fee) { SQLite::Transaction transferTransaction(global->sql); SQLite::Statement sourceQuery(global->sql, "UPDATE banks SET cash = cash - ? - ? WHERE id = ?;"); sourceQuery.bind(1, amount); sourceQuery.bind(2, fee); sourceQuery.bind(3, source.accountId); int rowsAffected = sourceQuery.exec(); SQLite::Statement targetQuery(global->sql, "UPDATE banks SET cash = cash + ? WHERE id = ?;"); targetQuery.bind(1, amount); targetQuery.bind(2, target.accountId); rowsAffected += targetQuery.exec(); if (rowsAffected == 2) { transferTransaction.commit(); return true; } return false; } int CountTransactions(const Bank& bank) { SQLite::Statement transactionCount(global->sql, "SELECT id FROM banks WHERE bankId = ? ORDER BY DESC;"); transactionCount.bind(bank.accountId); transactionCount.executeStep(); return transactionCount.getColumnCount(); } std::vector<Transaction> ListTransactions(const Bank& bank, int amount, int skip) { SQLite::Statement transactions(global->sql, "SELECT id, timestamp, accessor, amount FROM transactions " "WHERE bankId = ? " "ORDER BY timestamp DESC " "LIMIT ? " "OFFSET ?;"); transactions.bind(1, bank.accountId); transactions.bind(2, amount); transactions.bind(3, skip); std::vector<Transaction> transactionsList; while (transactions.executeStep()) { transactionsList.emplace_back(static_cast<uint64>(transactions.getColumn(0).getInt64()), stows(transactions.getColumn(1).getString()), transactions.getColumn(2).getInt64(), bank.accountId); } return transactionsList; } void AddTransaction(const Bank& receiver, const std::string& sender, const int64& amount) { SQLite::Statement transaction(global->sql, "INSERT INTO transactions (bankId, accessor, amount, timestamp) VALUES(?, ?, ?, ?);"); transaction.bind(1, receiver.accountId); transaction.bind(2, sender); transaction.bind(3, amount); transaction.bind(4, std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count()); transaction.exec(); } void SetOrClearIdentifier(const Bank& bank, const std::string& identifier) { if (identifier.empty()) { SQLite::Statement clearQuery(global->sql, "UPDATE banks SET identifier = NULL WHERE id = ?;"); clearQuery.bind(1, bank.accountId); return; } SQLite::Statement clearQuery(global->sql, "UPDATE banks SET identifier = ? WHERE id = ?;"); clearQuery.bind(1, identifier); clearQuery.bind(2, bank.accountId); } using namespace std::literals::chrono_literals; constexpr int64 SecondsInADay = std::chrono::duration_cast<std::chrono::seconds>(24h).count(); int RemoveTransactionsOverSpecifiedDays(uint days) { if (!days) { return 0; } const int64 currentTime = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); const int64 oldestPossibleEntry = currentTime - days * SecondsInADay; SQLite::Statement cleaningQuery(global->sql, "DELETE FROM transactions WHERE timestamp < ?;"); cleaningQuery.bind(1, oldestPossibleEntry); return cleaningQuery.exec(); } } // namespace Plugins::CashManager
7,192
C++
.cpp
175
36.891429
138
0.703868
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,360
SolarControl.cpp
TheStarport_FLHook/plugins/solar_control/SolarControl.cpp
/** * @date August, 2023 * @author Raikkonen * @defgroup SolarControl Solar Control * @brief * The Solar Control plugin allows Solar Objects to be spawned. * It also contains fixes for Nomad Airlocks not being dockable, and mission solars missing a loadout * * @paragraph cmds Player Commands * None * * @paragraph adminCmds Admin Commands * All commands are prefixed with '.' unless explicitly specified. * - solarcreate [number] [name] - Creates X amount of the specified Solars. The name for the Solar is configured in the json file. * - solarcreateformation [name] - Creates a specified premade formation of solars. The name for the formation is configured in the json file. * - solardestroy - Destroys all spawned solars. * * @paragraph configuration Configuration * @code * { * "baseRedirects": { * "li01_01_base": "li01_02_base" * }, * "solarArchFormations": { * "wplatform_form": { * "components": [ * { * "relativePosition": [ * 0.0, * 0.0, * 0.0 * ], * "rotation": [ * 0.0, * 0.0, * 0.0 * ], * "solarArchName": "wplatform" * }, * { * "relativePosition": [ * 0.0, * 100.0, * 0.0 * ], * "rotation": [ * 0.0, * 0.0, * 0.0 * ], * "solarArchName": "wplatform" * } * ] * } * }, * "solarArches": { * "largestation1": { * "base": "li01_01_base", * "iff": "li_n_grp", * "infocard": 197808, * "loadout": "", * "pilot": "pilot_solar_hardest", * "solarArch": "largestation1" * }, * "wplatform": { * "base": "", * "iff": "li_p_grp", * "infocard": 197808, * "loadout": "weapon_platform_1", * "pilot": "pilot_solar_hardest", * "solarArch": "wplatform" * } * }, * "startupSolars": [ * { * "name": "largestation1", * "position": [ * -30367.0, * 120.0, * -25810.0 * ], * "rotation": [ * 0.0, * 0.0, * 0.0 * ], * "system": "li01" * } * ] * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * SolarCommunicator: exposes CreateUserDefinedSolar method with parameters (const std::wstring& name, Vector position, const Matrix& rotation, SystemId * systemId, bool varyPosition, bool mission) and CreateUserDefinedSolarFormation method with parameters (SolarArchFormation& formation, const Vector& position, * uint system) */ #include "SolarControl.h" #include <ranges> namespace Plugins::SolarControl { const std::unique_ptr<Global> global = std::make_unique<Global>(); /** @ingroup SolarControl * @brief Returns a random float between two numbers */ float RandomFloatRange(const float firstNumber, const float secondNumber) { return ((secondNumber - firstNumber) * (static_cast<float>(rand()) / RAND_MAX)) + firstNumber; } /** @ingroup SolarControl * @brief Sends a custom Solar Packet for the spaceId using the solarInfo struct. A modified packet is needed because vanilla misses the loadout */ void SendSolarPacket(uint& spaceId, pub::SpaceObj::SolarInfo& solarInfo) { uint unknown; if (IObjInspectImpl * inspect; GetShipInspect(spaceId, inspect, unknown)) { auto const* solar = reinterpret_cast<CSolar const*>(inspect->cobject()); solar->launch_pos(solarInfo.vPos, solarInfo.mOrientation, 1); struct SolarStruct { std::byte unknown[0x100]; }; SolarStruct solarPacket {}; const std::byte* address1 = reinterpret_cast<std::byte*>(hModServer) + 0x163F0; const std::byte* address2 = reinterpret_cast<std::byte*>(hModServer) + 0x27950; // fill struct // clang-format off __asm { lea ecx, solarPacket mov eax, address1 call eax push solar lea ecx, solarPacket push ecx mov eax, address2 call eax add esp, 8 } // clang-format on // Send packet to every client in the system PlayerData* playerData = nullptr; while (playerData = Players.traverse_active(playerData)) { if (playerData->systemId == solarInfo.systemId) { GetClientInterface()->Send_FLPACKET_SERVER_CREATESOLAR(playerData->iOnlineId, reinterpret_cast<FLPACKET_CREATESOLAR&>(solarPacket)); } } } } /** @ingroup SolarControl * @brief Creates a solar from a solarInfo struct */ void CreateSolar(uint& spaceId, pub::SpaceObj::SolarInfo& solarInfo) { // Hack server.dll so it does not call create solar packet send char* serverHackAddress = reinterpret_cast<char*>(hModServer) + 0x2A62A; constexpr char serverHack[] = {'\xEB'}; WriteProcMem(serverHackAddress, &serverHack, 1); // Create the Solar pub::SpaceObj::CreateSolar(spaceId, solarInfo); // Send solar creation packet SendSolarPacket(spaceId, solarInfo); // Undo the server.dll hack constexpr char serverUnHack[] = {'\x74'}; WriteProcMem(serverHackAddress, &serverUnHack, 1); } /** @ingroup SolarControl * @brief Returns a loaded personality */ pub::AI::SetPersonalityParams GetPersonality(const std::string& personalityString) { pub::AI::SetPersonalityParams p; p.iStateGraph = pub::StateGraph::get_state_graph("NOTHING", pub::StateGraph::TYPE_STANDARD); p.bStateId = true; if (const auto personality = Hk::Personalities::GetPersonality(personalityString); personality.has_error()) { AddLog(LogType::Normal, LogLevel::Critical, std::format("{} is not recognised as a pilot name.", personalityString)); } else { p.personality = personality.value(); } return p; } /** @ingroup SolarControl * @brief Checks to ensure a solarArch is valid before attempting to spawn it. loadout, iff, base and pilot are all optional, but do require valid values to * avoid a crash if populated */ bool CheckSolar(const std::wstring& solarArch) { auto arch = global->config->solarArches[solarArch]; bool validity = true; // Check solar solarArch is valid if (!Archetype::GetSolar(CreateID(arch.solarArch.c_str()))) { Console::ConErr( std::format("The solarArch '{}' loaded for '{}' is invalid. Spawning this solar may cause a crash", arch.solarArch, wstos(solarArch))); validity = false; } // Check the loadout is valid EquipDescVector loadout; pub::GetLoadout(loadout, arch.loadoutId); if (!arch.loadout.empty() && loadout.equip.empty()) { Console::ConErr(std::format("The loadout '{}' loaded for '{}' is invalid. Spawning this solar may cause a crash", arch.loadout, wstos(solarArch))); validity = false; } // Check if solar iff is valid uint npcIff; pub::Reputation::GetReputationGroup(npcIff, arch.iff.c_str()); if (!arch.iff.empty() && npcIff == UINT_MAX) { Console::ConErr(std::format("The reputation '{}' loaded for '{}' is invalid. Spawning this solar may cause a crash", arch.iff, wstos(solarArch))); validity = false; } // Check solar base is valid if (!arch.base.empty() && !Universe::get_base(arch.baseId)) { Console::ConWarn(std::format("The base '{}' loaded for '{}' is invalid. Docking with this solar may cause a crash", arch.base, wstos(solarArch))); validity = false; } // Check solar pilot is valid if (!arch.pilot.empty() && !Hk::Personalities::GetPersonality(arch.pilot).has_value()) { Console::ConErr(std::format("The pilot '{}' loaded for '{}' is invalid. Spawning this solar may cause a crash", arch.pilot, wstos(solarArch))); validity = false; } return validity; } /** @ingroup SolarControl * @brief Creates a solar defined in the solar json file */ uint CreateUserDefinedSolar(const std::wstring& name, Vector position, const Matrix& rotation, SystemId system, bool varyPosition, bool mission) { if (!CheckSolar(name)) { Console::ConWarn(std::format("Unable to spawn '{}', invalid data was found in the solarArch", wstos(name))); return 0; } Console::ConDebug(std::format("Spawning solar '{}'", wstos(name))); SolarArch arch = global->config->solarArches[name]; pub::SpaceObj::SolarInfo si {}; memset(&si, 0, sizeof(si)); si.iFlag = 4; // Prepare the settings for the space object si.iArchId = arch.solarArchId; if (!arch.loadout.empty()) { si.iLoadoutId = arch.loadoutId; } si.iHitPointsLeft = 1000; si.systemId = system; si.mOrientation = rotation; si.Costume.head = CreateID("benchmark_male_head"); si.Costume.body = CreateID("benchmark_male_body"); si.Costume.lefthand = 0; si.Costume.righthand = 0; si.Costume.accessories = 0; si.iVoiceId = CreateID("atc_leg_m01"); std::string npcId = wstos(name) + std::to_string(global->spawnedSolars.size()); strncpy_s(si.cNickName, sizeof(si.cNickName), npcId.c_str(), name.size() + global->spawnedSolars.size()); // Do we need to vary the starting position slightly? Useful when spawning multiple objects si.vPos = position; if (varyPosition) { si.vPos.x = position.x + RandomFloatRange(0, 1000); si.vPos.y = position.y + RandomFloatRange(0, 1000); si.vPos.z = position.z + RandomFloatRange(0, 2000); } else { si.vPos.x = position.x; si.vPos.y = position.y; si.vPos.z = position.z; } if (arch.baseId) { // Which base this links to si.baseId = arch.baseId; } // Mission base? if (mission) { si.mission = 1; } // Define the string used for the scanner name.ad. FmtStr scannerName(arch.infocard, nullptr); scannerName.begin_mad_lib(arch.infocard); scannerName.end_mad_lib(); // Define the string used for the solar name. FmtStr solarName(arch.infocard, nullptr); solarName.begin_mad_lib(arch.infocard); solarName.end_mad_lib(); // Set Reputation pub::Reputation::Alloc(si.iRep, scannerName, solarName); if (!arch.iff.empty()) { uint iff; pub::Reputation::GetReputationGroup(iff, arch.iff.c_str()); pub::Reputation::SetAffiliation(si.iRep, iff); } // Spawn the solar object uint spaceId; CreateSolar(spaceId, si); if (!arch.pilot.empty()) { pub::AI::SetPersonalityParams personalityParams = GetPersonality(arch.pilot); pub::AI::SubmitState(spaceId, &personalityParams); } // Set the visible health for the Space Object pub::SpaceObj::SetRelativeHealth(spaceId, 1); global->spawnedSolars[spaceId] = si; return spaceId; } /** @ingroup SolarControl * @brief Creates a premade group of solars defined in the solar json file */ std::vector<uint> CreateUserDefinedSolarFormation(const std::wstring& formation, const Vector& position, uint system) { std::vector<uint> formationSpaceIds; auto group = global->config->solarArchFormations.find(formation); if (group == global->config->solarArchFormations.end()) { Console::ConErr(std::format("Unable to find {} while attempting to spawn user defined formation", wstos(formation))); return {}; } for (auto& component : group->second.components) { if (component.relativePosition.size() != 3 || component.rotation.size() != 3) { Console::ConErr(std::format("Invalid rotation or coordinate values provided for '{}', failed to create", component.solarArchName)); return {}; } auto solar = CreateUserDefinedSolar(stows(component.solarArchName), Vector { {position.x + component.relativePosition[0]}, {position.y + component.relativePosition[1]}, {position.z + component.relativePosition[2]}}, EulerMatrix(Vector {component.rotation[0], component.rotation[1], component.rotation[2]}), system, false, false); formationSpaceIds.emplace_back(solar); } return formationSpaceIds; } /** @ingroup SolarControl * @brief Admin command to create a user defined solar */ void AdminCommandSolarCreate(CCmds* commands, int amount, const std::wstring& solarType) { if (!(commands->rights & RIGHT_SUPERADMIN)) { commands->Print("ERR No permission\n"); return; } if (amount == 0) { amount = 1; } if (const auto iter = global->config->solarArches.find(solarType); iter != global->config->solarArches.end()) { SolarArch arch = iter->second; } else { commands->Print("ERR Wrong Solar name\n"); return; } const uint client = Hk::Client::GetClientIdFromCharName(commands->GetAdminName()).value(); uint ship; pub::Player::GetShip(client, ship); if (!ship) { return; } uint system; pub::Player::GetSystem(client, system); Vector pos {}; Matrix rot {}; pub::SpaceObj::GetLocation(ship, pos, rot); for (int i = 0; i < amount; i++) { CreateUserDefinedSolar(solarType, pos, rot, system, true, false); } } void AdminCommandSolarFormationCreate(CCmds* commands, const std::wstring& formationName) { if (!(commands->rights & RIGHT_SUPERADMIN)) { commands->Print("ERR No permission\n"); return; } if (const auto iter = global->config->solarArchFormations.find(formationName); iter != global->config->solarArchFormations.end()) { SolarArchFormation arch = iter->second; } else { commands->Print("ERR Wrong Solar formation name\n"); return; } const uint client = Hk::Client::GetClientIdFromCharName(commands->GetAdminName()).value(); uint ship; pub::Player::GetShip(client, ship); if (!ship) { return; } uint system; pub::Player::GetSystem(client, system); Vector pos {}; Matrix rot {}; pub::SpaceObj::GetLocation(ship, pos, rot); CreateUserDefinedSolarFormation(formationName, pos, system); } /** @ingroup SolarControl * @brief Admin command to delete all spawned solars */ void AdminCommandSolarKill(CCmds* commands) { if (!(commands->rights & RIGHT_SUPERADMIN)) { commands->Print("ERR No permission\n"); return; } for (auto const& [id, name] : global->spawnedSolars) { pub::SpaceObj::SetRelativeHealth(id, 0.0f); } global->spawnedSolars.clear(); commands->Print("OK\n"); return; } /** @ingroup SolarControl * @brief Processing for admin commands */ bool AdminCommandProcessing(CCmds* commands, const std::wstring& command) { if (command == L"solarcreate") { global->returnCode = ReturnCode::SkipAll; AdminCommandSolarCreate(commands, commands->ArgInt(1), commands->ArgStr(2)); return true; } if (command == L"solarformationcreate") { global->returnCode = ReturnCode::SkipAll; AdminCommandSolarFormationCreate(commands, commands->ArgStr(1)); return true; } else if (command == L"solardestroy") { global->returnCode = ReturnCode::SkipAll; AdminCommandSolarKill(commands); return true; } else { global->returnCode = ReturnCode::Default; return false; } } /** @ingroup SolarControl * @brief Load settings hook */ void LoadSettings() { // Hook solar creation to fix fl-bug in MP where loadout is not sent std::byte* addressCreateSolar = (reinterpret_cast<std::byte*>(GetModuleHandle("content.dll")) + 0x1134D4); auto const createSolar = reinterpret_cast<FARPROC>(CreateSolar); WriteProcMem(addressCreateSolar, &createSolar, 4); auto config = Serializer::JsonToObject<Config>(); global->spawnedSolars.clear(); global->log = spdlog::basic_logger_mt<spdlog::async_factory>("solars", "logs/solar.log"); for (auto& solar : config.solarArches | std::views::values) { solar.baseId = CreateID(solar.base.c_str()); solar.loadoutId = CreateID(solar.loadout.c_str()); solar.solarArchId = CreateID(solar.solarArch.c_str()); } for (auto& solar : config.startupSolars) { solar.systemId = CreateID(solar.system.c_str()); solar.pos.x = solar.position[0]; solar.pos.y = solar.position[1]; solar.pos.z = solar.position[2]; solar.rot = EulerMatrix({solar.rotation[0], solar.rotation[1], solar.rotation[2]}); } for (const auto& [baseFrom, baseTo] : config.baseRedirects) { config.hashedBaseRedirects[CreateID(baseFrom.c_str())] = CreateID(baseTo.c_str()); } global->config = std::make_unique<Config>(config); } /** @ingroup SolarControl * @brief We have to spawn here since the Startup/LoadSettings hooks are too early */ void Login([[maybe_unused]] struct SLoginInfo const& loginInfo, [[maybe_unused]] const uint& client) { if (global->firstRun) { for (const auto& [key, value] : global->config->solarArches) { CheckSolar(key); } for (const auto& solar : global->config->startupSolars) { if (!global->config->solarArches.contains(solar.name)) { Console::ConWarn( std::format("Attempted to load the startupSolar {}, but it was not defined in solarArches as a startupSolar", wstos(solar.name))); continue; } CreateUserDefinedSolar(solar.name, solar.pos, solar.rot, solar.systemId, false, false); } global->firstRun = false; } } /** @ingroup SolarControl * @brief Set target hook. Used to send a docking request if an airlock is selected since vanilla doesn't make this dockable by default */ void SetTarget(const ClientId& client, struct XSetTarget const& target) { uint type; pub::SpaceObj::GetType(target.iSpaceId, type); if ((type & OBJ_AIRLOCK_GATE) && std::ranges::find(global->pendingDockingRequests, client) == global->pendingDockingRequests.end()) { pub::SpaceObj::DockRequest(Hk::Player::GetShip(client).value(), target.iSpaceId); global->pendingDockingRequests.emplace_back(client); } } /** @ingroup SolarControl * @brief Timer to set the relative health of spawned solars. This fixes the glitch where spawned solars are not dockable */ void RelativeHealthTimer() { for (const auto& name : global->spawnedSolars | std::views::keys) { if (Universe::get_base(global->spawnedSolars[name].baseId)) { pub::SpaceObj::SetRelativeHealth(name, 1.0f); } } } /** @ingroup SolarControl * @brief Timer to clear the docking requests vector. This vector exists to stop the server from spamming docking requests when using SetTarget */ void ClearDockingRequestsTimer() { global->pendingDockingRequests.clear(); } // Timers const std::vector<Timer> timers = {{RelativeHealthTimer, 5}, {ClearDockingRequestsTimer, 5}}; void PlayerLaunch([[maybe_unused]] ShipId& shipId, ClientId& client) { if (global->pendingRedirects.contains(client)) { const auto beamResult = Hk::Player::Beam(client, global->pendingRedirects[client]); if (beamResult.has_error()) { AddLog(LogType::Normal, LogLevel::Err, std::format("Error when beaming player: {}", wstos(Hk::Err::ErrGetText(beamResult.error())))); } else { PrintUserCmdText(client, L"Redirecting undock. Please launch again."); } } } //! Base Enter hook void BaseEnter(const uint& baseId, ClientId& client) { if (global->pendingRedirects.contains(client)) { global->pendingRedirects.erase(client); } else { global->pendingRedirects[client] = global->config->hashedBaseRedirects[baseId]; } } void ClearClientInfo(ClientId& client) { global->pendingRedirects.erase(client); } // IPC SolarCommunicator::SolarCommunicator(const std::string& plug) : PluginCommunicator(plug) { this->CreateSolar = CreateUserDefinedSolar; this->CreateSolarFormation = CreateUserDefinedSolarFormation; } } // namespace Plugins::SolarControl using namespace Plugins::SolarControl; DefaultDllMainSettings(LoadSettings); REFL_AUTO(type(SolarArchFormation), field(components)); REFL_AUTO(type(SolarArchFormationComponent), field(solarArchName), field(relativePosition), field(rotation)); REFL_AUTO(type(SolarArch), field(solarArch), field(loadout), field(iff), field(infocard), field(base), field(pilot)); REFL_AUTO(type(StartupSolar), field(name), field(system), field(position), field(rotation)); REFL_AUTO(type(Config), field(startupSolars), field(solarArches), field(baseRedirects), field(solarArchFormations)); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pluginInfo) { pluginInfo->name(SolarCommunicator::pluginName); pluginInfo->shortName("solar_control"); pluginInfo->mayUnload(true); pluginInfo->returnCode(&global->returnCode); pluginInfo->timers(&timers); pluginInfo->versionMajor(PluginMajorVersion::VERSION_04); pluginInfo->versionMinor(PluginMinorVersion::VERSION_00); using enum HookStep; pluginInfo->emplaceHook(HookedCall::IServerImpl__Login, &Login); pluginInfo->emplaceHook(HookedCall::FLHook__AdminCommand__Process, &AdminCommandProcessing); pluginInfo->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, After); pluginInfo->emplaceHook(HookedCall::IServerImpl__SetTarget, &SetTarget, After); pluginInfo->emplaceHook(HookedCall::IServerImpl__BaseEnter, &BaseEnter); pluginInfo->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch, After); pluginInfo->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, After); // Register IPC global->communicator = new SolarCommunicator(SolarCommunicator::pluginName); PluginCommunicator::ExportPluginCommunicator(global->communicator); }
21,372
C++
.cpp
621
31.289855
160
0.689076
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,361
PurchaseRestrictions.cpp
TheStarport_FLHook/plugins/purchase_restrictions/PurchaseRestrictions.cpp
/** * @date Feb, 2010 * @author Cannon. Ported by Raikkonen, Nen and Laz * @defgroup PurchaseRestrictions Purchase Restrictions * @brief * The Purchase Restrictions plugin restricts the purchase of equipment, goods and ships unless the player holds a certain item. * * @paragraph cmds Player Commands * None * * @paragraph adminCmds Admin Commands * None * * @paragraph configuration Configuration * @code * { * "checkItemRestrictions": false, * "enforceItemRestrictions": false, * "goodItemRestrictions": { * "li_gun01_mark02": [ * "li_gun01_mark03" * ] * }, * "goodPurchaseDenied": "You are not authorized to buy this item.", * "itemsOfInterest": [ * "li_gun01_mark01" * ], * "shipItemRestrictions": { * "li_fighter": [ * "li_gun01_mark03" * ] * }, * "shipPurchaseDenied": "You are not authorized to buy this ship.", * "unbuyableItems": [ * "li_gun01_mark01" * ] * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. */ #include "PurchaseRestrictions.h" namespace Plugins::PurchaseRestrictions { const auto global = std::make_unique<Global>(); //! Log items of interest so we can see what cargo cheats people are using. static void LogItemsOfInterest(ClientId& client, uint iGoodId, const std::string& details) { const auto iter = global->itemsOfInterestHashed.find(iGoodId); if (iter != global->itemsOfInterestHashed.end()) { const auto charName = Hk::Client::GetCharacterNameByID(client); AddLog(LogType::Normal, LogLevel::Info, std::format("Item '{}' found in cargo of {} - {}", iter->second.c_str(), wstos(charName.value()), details.c_str())); } } //! Load settings from json file void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); for (const auto& str : config.itemsOfInterest) { global->itemsOfInterestHashed[CreateID(str.c_str())] = str; } for (const auto& str : config.unbuyableItems) { global->unbuyableItemsHashed.emplace_back(CreateID(str.c_str())); } for (const auto& [key, value] : config.goodItemRestrictions) { auto& map = global->goodItemRestrictionsHashed[CreateID(key.c_str())] = {}; for (const auto& i : value) map.emplace_back(CreateID(i.c_str())); } for (const auto& [key, value] : config.shipItemRestrictions) { auto& map = global->shipItemRestrictionsHashed[CreateID(key.c_str())] = {}; for (const auto& i : value) map.emplace_back(CreateID(i.c_str())); } global->config = std::make_unique<Config>(config); } //! Check that this client is allowed to buy/mount this piece of equipment or ship Return true if the equipment is mounted to allow this good. bool CheckIdEquipRestrictions(ClientId client, uint iGoodId, bool isShip) { const auto list = isShip ? global->shipItemRestrictionsHashed : global->goodItemRestrictionsHashed; const auto validItem = list.find(iGoodId); if (validItem == list.end()) return true; int remainingHoldSize; const auto cargoList = Hk::Player::EnumCargo(client, remainingHoldSize); return std::ranges::any_of(cargoList.value(), [validItem](const CARGO_INFO& cargo) { return cargo.bMounted && std::ranges::find(validItem->second, cargo.iArchId) != validItem->second.end(); }); } //! Clear Client Info hook void ClearClientInfo(ClientId& client) { global->clientSuppressBuy[client] = false; } //! PlayerLaunch hook void PlayerLaunch([[maybe_unused]] const uint& ship, ClientId& client) { global->clientSuppressBuy[client] = false; } //! Base Enter hook void BaseEnter([[maybe_unused]] const uint& baseId, ClientId& client) { global->clientSuppressBuy[client] = false; } //! Suppress the buying of goods. void GFGoodBuy(struct SGFGoodBuyInfo const& gbi, ClientId& client) { global->clientSuppressBuy[client] = false; auto& suppress = global->clientSuppressBuy[client]; LogItemsOfInterest(client, gbi.iGoodId, "good-buy"); if (std::ranges::find(global->unbuyableItemsHashed, gbi.iGoodId) != global->unbuyableItemsHashed.end()) { suppress = true; pub::Player::SendNNMessage(client, pub::GetNicknameId("info_access_denied")); PrintUserCmdText(client, global->config->goodPurchaseDenied); global->returnCode = ReturnCode::SkipAll; return; } /// Check restrictions for the Id that a player has. if (global->config->checkItemRestrictions) { // Check Item if (global->goodItemRestrictionsHashed.contains(gbi.iGoodId)) { if (!CheckIdEquipRestrictions(client, gbi.iGoodId, false)) { const auto charName = Hk::Client::GetCharacterNameByID(client); AddLog(LogType::Normal, LogLevel::Info, std::format("{} attempting to buy {} without correct Id", wstos(charName.value()), gbi.iGoodId)); if (global->config->enforceItemRestrictions) { PrintUserCmdText(client, global->config->goodPurchaseDenied); pub::Player::SendNNMessage(client, pub::GetNicknameId("info_access_denied")); suppress = true; global->returnCode = ReturnCode::SkipAll; } } } else { // Check Ship const GoodInfo* packageInfo = GoodList::find_by_id(gbi.iGoodId); if (packageInfo->iType != 3) { return; } const GoodInfo* hullInfo = GoodList::find_by_id(packageInfo->iHullGoodId); if (hullInfo->iType != 2) { return; } if (global->shipItemRestrictionsHashed.contains(hullInfo->shipGoodId) && !CheckIdEquipRestrictions(client, hullInfo->shipGoodId, true)) { const auto charName = Hk::Client::GetCharacterNameByID(client); AddLog(LogType::Normal, LogLevel::Info, std::format("{} attempting to buy {} without correct Id", wstos(charName.value()), hullInfo->shipGoodId)); if (global->config->enforceItemRestrictions) { PrintUserCmdText(client, global->config->shipPurchaseDenied); pub::Player::SendNNMessage(client, pub::GetNicknameId("info_access_denied")); suppress = true; global->returnCode = ReturnCode::SkipAll; } } } } } //! Suppress the buying of goods. void ReqAddItem(const uint& goodId, [[maybe_unused]] char const* hardpoint, [[maybe_unused]] const int& count, [[maybe_unused]] const float& status, [[maybe_unused]] const bool& mounted, ClientId& client) { LogItemsOfInterest(client, goodId, "add-item"); if (global->clientSuppressBuy[client]) { global->returnCode = ReturnCode::SkipAll; } } //! Suppress the buying of goods. void ReqChangeCash([[maybe_unused]] const int& moneyDiff, ClientId& client) { if (global->clientSuppressBuy[client]) { global->clientSuppressBuy[client] = false; global->returnCode = ReturnCode::SkipAll; } } //! Suppress ship purchases void ReqSetCash([[maybe_unused]] const int& money, ClientId& client) { if (global->clientSuppressBuy[client]) { global->returnCode = ReturnCode::SkipAll; } } //! Suppress ship purchases void ReqEquipment([[maybe_unused]] class EquipDescList const& eqDesc, ClientId& client) { if (global->clientSuppressBuy[client]) { global->returnCode = ReturnCode::SkipAll; } } //! Suppress ship purchases void ReqShipArch([[maybe_unused]] const uint& archId, ClientId& client) { if (global->clientSuppressBuy[client]) { global->returnCode = ReturnCode::SkipAll; } } //! Suppress ship purchases void ReqHullStatus([[maybe_unused]] const float& status, ClientId& client) { if (global->clientSuppressBuy[client]) { global->clientSuppressBuy[client] = false; global->returnCode = ReturnCode::SkipAll; } } } // namespace Plugins::PurchaseRestrictions /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FLHOOK STUFF /////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace Plugins::PurchaseRestrictions; REFL_AUTO(type(Config), field(checkItemRestrictions), field(enforceItemRestrictions), field(shipPurchaseDenied), field(goodPurchaseDenied), field(itemsOfInterest), field(unbuyableItems), field(goodItemRestrictions), field(shipItemRestrictions)); DefaultDllMainSettings(LoadSettings); // Functions to hook extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Purchase Restrictions"); pi->shortName("PurchaseRestrictions"); pi->mayUnload(true); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::IServerImpl__BaseEnter, &BaseEnter); pi->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__GFGoodBuy, &GFGoodBuy); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch); pi->emplaceHook(HookedCall::IServerImpl__ReqAddItem, &ReqAddItem); pi->emplaceHook(HookedCall::IServerImpl__ReqChangeCash, &ReqChangeCash); pi->emplaceHook(HookedCall::IServerImpl__ReqEquipment, &ReqEquipment); pi->emplaceHook(HookedCall::IServerImpl__ReqHullStatus, &ReqHullStatus); pi->emplaceHook(HookedCall::IServerImpl__ReqSetCash, &ReqSetCash); pi->emplaceHook(HookedCall::IServerImpl__ReqShipArch, &ReqShipArch); }
9,418
C++
.cpp
255
33.729412
153
0.703854
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,362
Condata.cpp
TheStarport_FLHook/plugins/condata/Condata.cpp
/** * @date August, 2022 * @author w0dk4 * @defgroup Condata Connection Data * @brief * This plugin is used to provide connection data e.g. ping * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - ping - This shows connection data to the player. * * @paragraph adminCmds Admin Commands * All commands are prefixed with '.' unless explicitly specified. * - getstats - Gets connection stats on all connected clients. * - kick <character> - Kicks the specified character. * * @paragraph configuration Configuration * No configuration file is needed. * * @paragraph ipc IPC Interfaces Exposed * - ReceiveData - See function documentation below * - ReceiveException - See function documentation below * * @paragraph optional Optional Plugin Dependencies * This plugin uses the "Tempban" plugin. */ #include "Condata.h" #include "Features/TempBan.hpp" #define PRINT_ERROR() \ { \ for (uint i = 0; (i < sizeof(wscError) / sizeof(std::wstring)); i++) \ PrintUserCmdText(client, wscError[i]); \ return; \ } #define PRINT_OK() PrintUserCmdText(client, L"OK"); #define PRINT_DISABLED() PrintUserCmdText(client, L"Command disabled"); namespace Plugins::ConData { constexpr int KickTimer = 10; const std::unique_ptr<Global> global = std::make_unique<Global>(); /** @ingroup Condata * @brief Clears our connection data for the specified client. */ void ClearConData(ClientId client) { auto con = global->connections[client]; con.averageLoss = 0; con.averagePing = 0; con.lastLoss = 0; con.lastPacketsDropped = 0; con.lastPacketsReceived = 0; con.lastPacketsSent = 0; con.pingFluctuation = 0; con.lossList.clear(); con.pingList.clear(); con.objUpdateIntervalsList.clear(); con.lags = 0; con.lastObjUpdate = 0; con.lastObjTimestamp = 0; con.exception = false; con.exceptionReason = ""; } /** @ingroup Condata * @brief ClearClientInfo hook. Calls ClearConData(). */ void ClearClientInfo(ClientId& client) { ClearConData(client); } /** @ingroup Condata * @brief Hook on TimerCheckKick. Checks clients's connections against a threshold and kicks them if they are above it. */ void TimerCheckKick() { if (CoreGlobals::c()->serverLoadInMs > global->config->kickThreshold) { // for all players struct PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; if (client < 1 || client > MaxClientId) continue; auto& con = global->connections[client]; if (global->config->lossKick && con.averageLoss > global->config->lossKick) { con.lossList.clear(); AddKickLog(client, "High loss"); TempBanManager::i()->AddTempBan(client, 60, L"High loss"); } if (global->config->pingKick && con.averagePing > (global->config->pingKick)) { con.pingList.clear(); AddKickLog(client, "High ping"); TempBanManager::i()->AddTempBan(client, 60, L"High ping"); } if (global->config->fluctKick && con.pingFluctuation > (global->config->fluctKick)) { con.pingList.clear(); AddKickLog(client, "High fluct"); TempBanManager::i()->AddTempBan(client, 60, L"High ping fluctuation"); } if (global->config->lagKick && con.lags > (global->config->lagKick)) { con.objUpdateIntervalsList.clear(); AddKickLog(client, "High Lag"); TempBanManager::i()->AddTempBan(client, 60, L"High lag"); } } } // Are there accounts connected with client Ids greater than max player // count? If so, kick them as FLServer is buggy and will use high client Ids // but will not allow character selection on them. for (uint client = Players.GetMaxPlayerCount() + 1; client <= MaxClientId; client++) { if (Players[client].iOnlineId) { if (CAccount* acc = Players.FindAccountFromClientID(client)) { acc->ForceLogout(); Players.logout(client); } } } } /** @ingroup Condata * @brief Update average ping data. */ void TimerUpdatePingData() { // for all players struct PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; const auto connectionInfo = Hk::Admin::GetConnectionStats(client); if (client < 1 || client > MaxClientId || ClientInfo[client].tmF1TimeDisconnect || connectionInfo.has_error()) continue; auto& con = global->connections[client]; /////////////////////////////////////////////////////////////// // update ping data if (con.pingList.size() >= global->config->pingKickFrame) { // calculate average ping and ping fluctuation unsigned int lastPing = 0; con.averagePing = 0; con.pingFluctuation = 0; for (const auto& ping : con.pingList) { con.averagePing += ping; if (lastPing != 0) { con.pingFluctuation += static_cast<uint>(sqrt(pow(static_cast<float>(ping) - static_cast<float>(lastPing), 2))); } lastPing = ping; } con.pingFluctuation /= con.pingList.size(); con.averagePing /= con.pingList.size(); } // remove old pingdata while (con.pingList.size() >= global->config->pingKickFrame) con.pingList.pop_back(); con.pingList.push_front(connectionInfo->dwRoundTripLatencyMS); } } /** @ingroup Condata * @brief Update average loss data. */ void TimerUpdateLossData() { // for all players float lossPercentage; PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; if (client < 1 || client > MaxClientId) continue; if (ClientInfo[client].tmF1TimeDisconnect) continue; const auto connectionInfo = Hk::Admin::GetConnectionStats(client); if (connectionInfo.has_error()) continue; const auto& connInfo = connectionInfo.value(); auto& con = global->connections[client]; /////////////////////////////////////////////////////////////// // update loss data if (con.lossList.size() >= (global->config->lossKickFrame / LossInterval)) { // calculate average loss con.averageLoss = 0; for (const auto& loss : con.lossList) con.averageLoss += loss; con.averageLoss /= con.lossList.size(); } // remove old lossdata while (con.lossList.size() >= (global->config->lossKickFrame / LossInterval)) con.lossList.pop_back(); // sum of Drops = Drops guaranteed + drops non-guaranteed const uint newDrops = (connInfo.dwPacketsRetried + connInfo.dwPacketsDropped) - con.lastPacketsDropped; // % of Packets Lost = Drops / (sent+received) * 100 if (const uint newSent = (connInfo.dwPacketsSentGuaranteed + connInfo.dwPacketsSentNonGuaranteed) - con.lastPacketsSent; newSent > 0) // division by zero check lossPercentage = static_cast<float>(newDrops) / static_cast<float>(newSent) * 100.0f; else lossPercentage = 0.0; if (lossPercentage > 100) lossPercentage = 100; // add last loss to List lossList and put current value into lastLoss con.lossList.push_front(con.lastLoss); con.lastLoss = static_cast<uint>(lossPercentage); // Fill new ClientInfo-variables with current values con.lastPacketsSent = connInfo.dwPacketsSentGuaranteed + connInfo.dwPacketsSentNonGuaranteed; con.lastPacketsDropped = connInfo.dwPacketsRetried + connInfo.dwPacketsDropped; } } /** @ingroup Condata * @brief Hook on PlayerLaunch. Sets lastObjUpdate to 0. */ void PlayerLaunch([[maybe_unused]] ShipId& ship, ClientId& client) { global->connections[client].lastObjUpdate = 0; } /** @ingroup Condata * @brief Hook on SPObjUpdate. Updates timestamps for lag detection. */ void SPObjUpdate(struct SSPObjUpdateInfo const& ui, ClientId& client) { // lag detection if (const auto ins = Hk::Client::GetInspect(client); ins.has_error()) return; // ??? 8[ const mstime timeNow = Hk::Time::GetUnixMiliseconds(); const auto timestamp = static_cast<mstime>(ui.dTimestamp * 1000); auto& con = global->connections[client]; if (global->config->lagDetectionFrame && con.lastObjUpdate && (Hk::Client::GetEngineState(client) != ES_TRADELANE) && (ui.cState != 7)) { const auto timeDiff = static_cast<uint>(timeNow - con.lastObjUpdate); const auto timestampDiff = static_cast<uint>(timestamp - con.lastObjTimestamp); auto diff = static_cast<int>(sqrt(pow(static_cast<long double>(static_cast<int>(timeDiff) - static_cast<int>(timestampDiff)), 2))); diff -= CoreGlobals::c()->serverLoadInMs; if (diff < 0) diff = 0; uint perc; if (timestampDiff != 0) perc = static_cast<uint>(static_cast<float>(diff) / static_cast<float>(timestampDiff) * 100.0f); else perc = 0; if (con.objUpdateIntervalsList.size() >= global->config->lagDetectionFrame) { uint lags = 0; for (const auto& iv : con.objUpdateIntervalsList) { if (iv > global->config->lagDetectionMin) lags++; } con.lags = (lags * 100) / global->config->lagDetectionFrame; while (con.objUpdateIntervalsList.size() >= global->config->lagDetectionFrame) con.objUpdateIntervalsList.pop_front(); } con.objUpdateIntervalsList.push_back(perc); } con.lastObjUpdate = timeNow; con.lastObjTimestamp = timestamp; } /** @ingroup Condata * @brief Gets called when the player types /ping */ void UserCmdPing(ClientId& client, [[maybe_unused]] const std::wstring& param) { if (!global->config->allowPing) { PRINT_DISABLED(); return; } uint clientTarget = client; std::wstring response = L"Ping"; // If they have a target selected, and that target is a player, get their target's ping instead if (auto target = Hk::Player::GetTarget(client); target.has_value()) { const auto id = Hk::Client::GetClientIdByShip(target.value()); if (id.has_value() && Hk::Client::IsValidClientID(id.value())) { clientTarget = id.value(); response += L" (target)"; } } const auto& con = global->connections[clientTarget]; response += L": "; if (con.pingList.size() < global->config->pingKickFrame) response += L"n/a Fluct: n/a "; else { response += std::to_wstring(con.averagePing); response += L"ms "; if (global->config->pingKick > 0) { response += L"(Max: "; response += std::to_wstring(global->config->pingKick); response += L"ms) "; } response += L"Fluct: "; response += std::to_wstring(con.pingFluctuation); response += L"ms "; if (global->config->fluctKick > 0) { response += L"(Max: "; response += std::to_wstring(global->config->fluctKick); response += L"ms) "; } } response += L"Loss: "; if (con.lossList.size() < (global->config->lossKickFrame / LossInterval)) response += L"n/a "; else { response += std::to_wstring(con.averageLoss); response += L"% "; if (global->config->lossKick > 0) { response += L"(Max: "; response += std::to_wstring(global->config->lossKick); response += L"%) "; } } response += L"Lag: "; if (con.objUpdateIntervalsList.size() < global->config->lagDetectionFrame) response += L"n/a"; else { response += std::to_wstring(con.lags).c_str(); response += L"% "; if (global->config->lagKick > 0) { response += L"(Max: "; response += std::to_wstring(global->config->lagKick); response += L"%)"; } } // Send the message to the user PrintUserCmdText(client, response); } const std::vector commands = {{ CreateUserCommand(L"/ping", L"", UserCmdPing, L"Gets the ping of your current target, if you have no player as a target it will return your ping."), }}; /** @ingroup Condata * @brief Receive Exception from inter-plugin communication. */ void ReceiveExceptionData(const ConnectionDataException& exc) { global->connections[exc.client].exception = exc.isException; global->connections[exc.client].exceptionReason = exc.reason; if (!global->connections[exc.client].exception) ClearConData(exc.client); } /** @ingroup Condata * @brief Receive Connection data from inter-plugin communication. */ void ReceiveConnectionData(ConnectionData& cd) { cd.averageLoss = global->connections[cd.client].averageLoss; cd.averagePing = global->connections[cd.client].averagePing; cd.lags = global->connections[cd.client].lags; cd.pingFluctuation = global->connections[cd.client].pingFluctuation; } /** @ingroup Condata * @brief Process admin commands. */ bool ExecuteCommandString(CCmds* classptr, const std::wstring& command) { if (command == L"getstats") { struct PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; if (Hk::Client::IsInCharSelectMenu(client)) continue; CDPClientProxy* cdpClient = clientProxyArray[client - 1]; if (!cdpClient) continue; auto& con = global->connections[client]; auto saturation = static_cast<int>(cdpClient->GetLinkSaturation() * 100); int txqueue = cdpClient->GetSendQSize(); classptr->Print(wstos(std::format(L"charname={} clientid={} loss={} lag={} pingfluct={} saturation={} txqueue={}\n", Hk::Client::GetCharacterNameByID(client).value(), client, con.averageLoss, con.lags, con.pingFluctuation, saturation, txqueue))); } classptr->Print("OK"); global->returncode = ReturnCode::SkipAll; return true; } else if (command == L"kick") { // Find by charname. If this fails, fall through to default behaviour. const auto acc = Hk::Client::GetAccountByCharName(classptr->ArgCharname(1)); if (acc.has_error()) return false; // Logout. global->returncode = ReturnCode::SkipAll; acc.value()->ForceLogout(); classptr->Print("OK"); // If the client is still active then force the disconnect. if (const auto client = Hk::Client::GetClientIdFromAccount(acc.value()); client.has_value()) { classptr->Print(std::format("Forcing logout on client={}", client.value())); Players.logout(client.value()); } return true; } return false; } /** @ingroup Condata * @brief Exposes functions for inter-plugin communication. */ ConDataCommunicator::ConDataCommunicator(const std::string& plug) : PluginCommunicator(plug) { this->ReceiveData = ReceiveConnectionData; this->ReceiveException = ReceiveExceptionData; } void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(config); // check for logged in players and reset their connection data struct PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { if (ClientId client = playerData->iOnlineId; client < 1 || client > MaxClientId) continue; ClearConData(playerData->iOnlineId); } } const std::vector<Timer> timers = { {TimerUpdatePingData, 1, 0}, {TimerUpdateLossData, LossInterval, 0}, }; } // namespace Plugins::ConData using namespace Plugins::ConData; DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name(ConDataCommunicator::pluginName); pi->shortName("condata"); pi->mayUnload(true); pi->commands(&commands); pi->timers(&timers); pi->returnCode(&global->returncode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, HookStep::After); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::FLHook__TimerCheckKick, &TimerCheckKick); pi->emplaceHook(HookedCall::IServerImpl__SPObjUpdate, &SPObjUpdate); pi->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch); pi->emplaceHook(HookedCall::FLHook__AdminCommand__Process, &ExecuteCommandString); // Register plugin for IPC global->communicator = new ConDataCommunicator(ConDataCommunicator::pluginName); PluginCommunicator::ExportPluginCommunicator(global->communicator); }
16,384
C++
.cpp
464
31.564655
153
0.689196
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,363
SystemSensor.cpp
TheStarport_FLHook/plugins/system_sensor/SystemSensor.cpp
/** * @date Feb, 2010 * @author Cannon, ported by Raikkonen * @defgroup SystemSensor System Sensor * @brief * The plugin allows players with proper equipment to see player traffic coming through * Trade Lanes and Jump Gates in the system, as well as being able to look up * their equipment and cargo at the time of using them. * * @paragraph cmds Player Commands * -net <all/jumponly/off> - if player has proper equipment, toggles his scanner between showing JG/TL transits, * JG transits only, and disabling the feature * -showscan <name> - shows equipment and cargo carried by the specified player * -showscan$ <playerID> - same as above, but using player ID as paramenter, useful for to type difficult names * * @paragraph adminCmds Admin Commands * None * * @paragraph configuration Configuration * @code * { * "sensors": [ * {"systemId": "Li01", * "equipId": "li_gun01_mark01", * "networkId": 1} * ] * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. */ #include "SystemSensor.h" #include <Tools/Serialization/Attributes.hpp> namespace Plugins::SystemSensor { const auto global = std::make_unique<Global>(); void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); std::ranges::for_each(config.sensors, [](const ReflectableSensor& sensor) { Sensor s = {sensor.systemId, sensor.equipId, sensor.networkId}; global->sensorEquip.insert(std::multimap<EquipId, Sensor>::value_type(CreateID(sensor.equipId.c_str()), s)); global->sensorSystem.insert(std::multimap<SystemId, Sensor>::value_type(CreateID(sensor.systemId.c_str()), s)); }); } void UserCmd_Net(ClientId& client, const std::wstring& param) { const std::wstring mode = ToLower(GetParam(param, ' ', 0)); if (mode.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /net [all|jumponly|off]"); return; } if (!global->networks[client].availableNetworkId) { PrintUserCmdText(client, L"ERR Sensor network monitoring is not available"); global->networks[client].mode = Mode::Off; return; } if (mode == L"all") { PrintUserCmdText(client, L"OK Sensor network monitoring all traffic"); global->networks[client].mode = Mode::Both; } else if (mode == L"jumponly") { PrintUserCmdText(client, L"OK Sensor network monitoring jumpgate traffic only"); global->networks[client].mode = Mode::JumpGate; } else { PrintUserCmdText(client, L"OK Sensor network monitoring disabled"); global->networks[client].mode = Mode::Off; } return; } void UserCmd_ShowScan(ClientId& client, const std::wstring& param) { std::wstring targetCharname = GetParam(param, ' ', 0); if (targetCharname.empty()) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage:"); PrintUserCmdText(client, L"/showscan <charname>"); PrintUserCmdText(client, L"/showscan$ <playerID>"); return; } const auto targetClientId = Hk::Client::GetClientIdFromCharName(targetCharname); if (targetClientId.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(targetClientId.error())); return; } const auto& [targetSensorClientId, targetSensor] = *global->networks.find(targetClientId.value()); if (!targetSensorClientId || !global->networks[client].availableNetworkId || !targetSensor.lastScanNetworkId || global->networks[client].availableNetworkId != targetSensor.lastScanNetworkId) { PrintUserCmdText(client, L"ERR Scan data not available"); return; } std::wstring eqList; for (auto const& ci : targetSensor.lastScanList) { std::string hardpoint = ci.hardpoint.value; if (!hardpoint.empty()) { Archetype::Equipment* eq = Archetype::GetEquipment(ci.iArchId); if (eq && eq->iIdsName) { std::wstring result; switch (Hk::Client::GetEqType(eq)) { case ET_GUN: case ET_MISSILE: case ET_CD: case ET_CM: case ET_TORPEDO: case ET_OTHER: if (eqList.length()) eqList += L","; result = Hk::Message::GetWStringFromIdS(eq->iIdsName); eqList += result; break; default: break; } } } } PrintUserCmdText(client, eqList); PrintUserCmdText(client, L"OK"); } void UserCmd_ShowScanID(ClientId& client, const std::wstring& param) { ClientId client2 = ToInt(GetParam(param, ' ', 0)); std::wstring targetCharname = L""; if (Hk::Client::IsValidClientID(client2)) targetCharname = (wchar_t*)Players.GetActiveCharacterName(client2); UserCmd_ShowScan(client, targetCharname); } void ClearClientInfo(ClientId& client) { global->networks.erase(client); } static void EnableSensorAccess(ClientId client) { // Retrieve the location and cargo list. int holdSize; const auto cargo = Hk::Player::EnumCargo(client, holdSize); SystemId systemId = Hk::Player::GetSystem(client).value(); // If this is ship has the right equipment and is in the right system then // enable access. uint availableNetworkId = 0; for (auto& ci : cargo.value()) { if (ci.bMounted) { auto start = global->sensorEquip.lower_bound(ci.iArchId); auto end = global->sensorEquip.upper_bound(ci.iArchId); while (start != end) { if (start->second.systemId == systemId) { availableNetworkId = start->second.networkId; break; } ++start; } } } if (availableNetworkId != global->networks[client].availableNetworkId) { global->networks[client].availableNetworkId = availableNetworkId; if (availableNetworkId) PrintUserCmdText(client, L"Connection to tradelane sensor network " L"established. Type /net access network."); else PrintUserCmdText(client, L"Connection to tradelane sensor network lost."); } } void PlayerLaunch([[maybe_unused]] const uint& ship, ClientId& client) { EnableSensorAccess(client); } static void DumpSensorAccess(ClientId client, const std::wstring& type, Mode mode) { SystemId systemId = Hk::Player::GetSystem(client).value(); // Find the sensor network for this system. auto siter = global->sensorSystem.lower_bound(systemId); if (auto send = global->sensorSystem.upper_bound(systemId); siter == send) return; if (global->networks.contains(client)) { ClearClientInfo(client); } // Record the ship's cargo. int holdSize; global->networks[client].lastScanList = Hk::Player::EnumCargo(client, holdSize).value(); global->networks[client].lastScanNetworkId = siter->second.networkId; // Notify any players connected to the the sensor network that this ship is // in for (const auto& [playerId, sensor] : global->networks) { if (sensor.availableNetworkId == siter->second.networkId) { const Universe::ISystem* system = Universe::get_system(systemId); if (system && magic_enum::enum_integer(sensor.mode & mode)) { std::wstring sysName = Hk::Message::GetWStringFromIdS(system->strid_name); const auto location = Hk::Solar::GetLocation(client, IdType::Client); const auto playerSystem = Hk::Player::GetSystem(client); const Vector& position = location.value().first; const std::wstring curLocation = Hk::Math::VectorToSectorCoord<std::wstring>(playerSystem.value(), position); PrintUserCmdText( playerId, std::format(L"{}[${}] {} at {} {}", Hk::Client::GetCharacterNameByID(client).value(), client, type, sysName, curLocation)); } } } } // Record jump type. int Dock_Call(unsigned int const& ship, unsigned int const& dockTarget, const int& cancel, const enum DOCK_HOST_RESPONSE& response) { if (const auto client = Hk::Client::GetClientIdByShip(ship); client.has_value() && (response == PROCEED_DOCK || response == DOCK) && cancel >= 0) { auto spaceObjType = Hk::Solar::GetType(dockTarget); if (spaceObjType.has_error()) { Console::ConWarn(wstos(Hk::Err::ErrGetText(spaceObjType.error()))); } global->networks[client.value()].inJumpGate = spaceObjType.value() == OBJ_JUMP_GATE; } return 0; } void JumpInComplete([[maybe_unused]] SystemId& system, [[maybe_unused]] ShipId& ship) { ClientId client = Hk::Client::GetClientIdByShip(ship).value(); EnableSensorAccess(client); if (global->networks[client].inJumpGate) { global->networks[client].inJumpGate = false; DumpSensorAccess(client, L"exited jumpgate", Mode::JumpGate); } } void GoTradelane(ClientId& client, [[maybe_unused]] struct XGoTradelane const& xgt) { DumpSensorAccess(client, L"entered tradelane", Mode::TradeLane); } void StopTradelane(ClientId& client, [[maybe_unused]] const uint& p1, [[maybe_unused]] const uint& p2, [[maybe_unused]] const uint& p3) { DumpSensorAccess(client, L"exited tradelane", Mode::TradeLane); } // Client command processing const std::vector commands = {{ CreateUserCommand(L"/showscan", L"<name>", UserCmd_ShowScan, L"Shows equipment and cargo carried by the specified player."), CreateUserCommand(L"/showscan$", L"<playerID>", UserCmd_ShowScanID, L"Same as /showscan, but using player ID as paramenter, useful for to type difficult names"), CreateUserCommand(L"/net", L"<all/jumponly/off>", UserCmd_Net, L"Toggles your scanner between off, jump gates only, and both tradelanes and jump gates"), }}; } // namespace Plugins::SystemSensor /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // FLHOOK STUFF /////////////////////////////////////////////////////////////////////////////////////////////////////////////// using namespace Plugins::SystemSensor; REFL_AUTO(type(ReflectableSensor), field(equipId), field(systemId), field(networkId)); REFL_AUTO(type(Config), field(sensors, AttrNotEmpty<std::vector<ReflectableSensor>> {})); DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("System Sensor"); pi->shortName("system_sensor"); pi->mayUnload(true); pi->commands(&commands); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, HookStep::After); pi->emplaceHook(HookedCall::IEngine__DockCall, &Dock_Call); pi->emplaceHook(HookedCall::IServerImpl__GoTradelane, &GoTradelane); pi->emplaceHook(HookedCall::IServerImpl__StopTradelane, &StopTradelane); pi->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch); pi->emplaceHook(HookedCall::IServerImpl__JumpInComplete, &JumpInComplete); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); }
10,782
C++
.cpp
285
34.350877
166
0.704359
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,364
AdvancedStartupSolars.cpp
TheStarport_FLHook/plugins/advanced_startup_solars/AdvancedStartupSolars.cpp
/** * @date April, 2024 * @author IrateRedKite * @defgroup AdvancedStartupSolars Advanced Startup Solars * @brief * This plugin allows server owners to specify startupSolars with more finesse, allowing for mutually exclusive spawns * * @paragraph cmds Player Commands * None * * @paragraph adminCmds Admin Commands * None * * @paragraph configuration Configuration * @code * * { * "solarFamilies": [ * { * "name": "largestation1", * "solarFormations": [ * { * "formation": "largestation1", * "npcs": { * "example": 2 * }, * "spawnWeight": 1 * } * ], * "spawnChance": 75, * "spawnLocations": [ * { * "location": [ * -31630.4453125, * 1000.0, * -25773.7421875 * ], * "system": "li01" * }, * { * "location": [ * -30401.986328125, * -1000.0, * -25730.84375 * ], * "system": "li01" * } * ], * "spawnQuantity": 1 * } * ] * } * * @endcode * * @paragraph ipc IPC Interfaces Exposed * None * * @paragraph optional Optional Plugin Dependencies * Solar Control and NPC Control */ // This is free software; you can redistribute it and/or modify it as // you wish without restriction. If you do then I would appreciate // being notified and/or mentioned somewhere. // Includes #include "AdvancedStartupSolars.hpp" #include <random> namespace Plugins::AdvancedStartupSolars { const auto global = std::make_unique<Global>(); // Function: Generates a random int between min and max int RandomNumber(int min, int max) { static std::random_device dev; static auto engine = std::mt19937(dev()); auto range = std::uniform_int_distribution(min, max); return range(engine); } SolarFormation SelectSolarFormation(SolarFamily family) { std::vector<int> weights {}; for (auto formation : family.solarFormations) { weights.emplace_back(formation.spawnWeight); } std::discrete_distribution<> dist(weights.begin(), weights.end()); static std::mt19937 engine; auto numberIndex = dist(engine); auto solarFormation = family.solarFormations[numberIndex]; family.solarFormations.erase(family.solarFormations.begin() + numberIndex); return solarFormation; } Position SelectSpawnLocation(SolarFamily& family) { auto locationIndex = RandomNumber(0, family.spawnLocations.size() - 1); Position spawnPosition; spawnPosition.location = {{family.spawnLocations[locationIndex].location[0]}, {family.spawnLocations[locationIndex].location[1]}, {family.spawnLocations[locationIndex].location[2]}}; spawnPosition.system = family.spawnLocations[locationIndex].system; // Remove the spawnLocation from the pool of possible locations before returning the vector; family.spawnLocations.erase(family.spawnLocations.begin() + locationIndex); return spawnPosition; } // Put things that are performed on plugin load here! void LoadSettings() { // Load JSON config auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(std::move(config)); // Set the npcCommunicator and solarCommunicator interfaces and check if they are availlable global->npcCommunicator = static_cast<Plugins::Npc::NpcCommunicator*>(PluginCommunicator::ImportPluginCommunicator(Plugins::Npc::NpcCommunicator::pluginName)); global->solarCommunicator = static_cast<Plugins::SolarControl::SolarCommunicator*>( PluginCommunicator::ImportPluginCommunicator(Plugins::SolarControl::SolarCommunicator::pluginName)); // Prevent the plugin from progressing further and disable all functions if either interface is not found. if (!global->npcCommunicator) { Console::ConErr(std::format("npc.dll not found. The plugin is required for this module to function.")); global->pluginActive = false; } if (!global->solarCommunicator) { Console::ConErr(std::format("solar.dll not found. The plugin is required for this module to function.")); global->pluginActive = false; } if (!global->pluginActive) { Console::ConErr( std::format("Critical components of Advanced Startup Solars were not found or were configured incorrectly. The plugin has been disabled.")); return; } // Validate our user defined config int formationCount = 0; for (auto solarFamily : global->config->solarFamilies) { // Clamps spawnChance between 0 and 100 solarFamily.spawnChance = std::clamp(solarFamily.spawnChance, 0, 100); for (const auto& formation : solarFamily.solarFormations) { Console::ConDebug(std::format("Loaded formation '{}' into the {} solarFamily pool", wstos(formation.formation), solarFamily.name)); formationCount++; } } Console::ConDebug(std::format("Loaded {} solarFamilies into the spawn pool", global->config->solarFamilies.size())); Console::ConDebug(std::format("Loaded a total of {} formations between the collective solarFamily pool", formationCount)); } // We have to spawn here since the Startup/LoadSettings hooks are too early void Login([[maybe_unused]] struct SLoginInfo const& loginInfo, [[maybe_unused]] const uint& client) { if (!global->firstRun) { return; } for (auto& family : global->config->solarFamilies) { auto dist = RandomNumber(0, 100); if (dist <= family.spawnChance) { for (int i = 0; i < family.spawnQuantity; i++) { auto spawnPosition = SelectSpawnLocation(family); auto solarFormation = SelectSolarFormation(family); auto spawnSystem = CreateID(spawnPosition.system.c_str()); Vector spawnLocation = {{spawnPosition.location[0]}, {spawnPosition.location[1]}, {spawnPosition.location[2]}}; global->solarCommunicator->CreateSolarFormation(solarFormation.formation, spawnLocation, spawnSystem); for (const auto& [key, value] : solarFormation.npcs) { for (int j = 0; j < value; j++) { global->npcCommunicator->CreateNpc(key, spawnLocation, EulerMatrix({0, 0, 0}), spawnSystem, true); } } } } } global->firstRun = false; } } // namespace Plugins::AdvancedStartupSolars using namespace Plugins::AdvancedStartupSolars; REFL_AUTO(type(SolarFormation), field(formation), field(npcs), field(spawnWeight)); REFL_AUTO(type(Position), field(location), field(system)); REFL_AUTO(type(SolarFamily), field(name), field(solarFormations), field(spawnLocations), field(spawnChance), field(spawnQuantity)); REFL_AUTO(type(Config), field(solarFamilies)); DefaultDllMainSettings(LoadSettings); extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Advanced Startup Solars"); pi->shortName("advanced_startup_solars"); pi->mayUnload(true); pi->returnCode(&global->returnCode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::IServerImpl__Login, &Login); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); }
7,333
C++
.cpp
196
34.408163
147
0.688592
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,365
DeathPenalty.cpp
TheStarport_FLHook/plugins/death_penalty/DeathPenalty.cpp
/** * @date August, 2022 * @author Ported from 88Flak by Raikkonen * @defgroup DeathPenalty Death Penalty * @brief * This plugin charges players credits for dying based on their ship worth. If the killer was a player it also rewards them. * * @paragraph cmds Player Commands * All commands are prefixed with '/' unless explicitly specified. * - dp - Shows the credits you would be charged if you died. * * @paragraph adminCmds Admin Commands * There are no admin commands in this plugin. * * @paragraph configuration Configuration * @code * { * "DeathPenaltyFraction": 1.0, * "DeathPenaltyFractionKiller": 1.0, * "ExcludedSystems": ["li01"], * "FractionOverridesByShip": {"ge_fighter": 1.0} * } * @endcode * * @paragraph ipc IPC Interfaces Exposed * This plugin does not expose any functionality. * * @paragraph optional Optional Plugin Dependencies * This plugin has no dependencies. */ #include "DeathPenalty.h" namespace Plugins::DeathPenalty { const std::unique_ptr<Global> global = std::make_unique<Global>(); // Load configuration file void LoadSettings() { auto config = Serializer::JsonToObject<Config>(); global->config = std::make_unique<Config>(config); for (const auto& system : config.ExcludedSystems) global->ExcludedSystemsIds.push_back(CreateID(system.c_str())); for (const auto& [shipNickname, penaltyFraction] : config.FractionOverridesByShip) global->FractionOverridesByShipIds[CreateID(shipNickname.c_str())] = penaltyFraction; } void ClearClientInfo(ClientId& client) { global->MapClients.erase(client); } /** @ingroup DeathPenalty * @brief Is the player is a system that is excluded from death penalty? */ bool IsInExcludedSystem(ClientId client) { // Get System Id SystemId iSystemId = Hk::Player::GetSystem(client).value(); // Search list for system return std::ranges::find(global->ExcludedSystemsIds, iSystemId) != global->ExcludedSystemsIds.end(); } /** @ingroup DeathPenalty * @brief This returns the override for the specific ship as defined in the json file. * If there is not override it returns the default value defined as * "DeathPenaltyFraction" in the json file */ float GetShipFractionOverride(ClientId client) { // Get ShipArchId uint shipArchId = Hk::Player::GetShipID(client).value(); // Default return value is the default death penalty fraction float overrideValue = global->config->DeathPenaltyFraction; // See if the ship has an override fraction if (global->FractionOverridesByShipIds.contains(shipArchId)) overrideValue = global->FractionOverridesByShipIds[shipArchId]; return overrideValue; } /** @ingroup DeathPenalty * @brief Hook on Player Launch. Used to work out the death penalty and display a message to the player warning them of such */ void PlayerLaunch([[maybe_unused]] const uint& ship, ClientId& client) { // No point in processing anything if there is no death penalty if (global->config->DeathPenaltyFraction > 0.00001f) { // Check to see if the player is in a system that doesn't have death // penalty if (!IsInExcludedSystem(client)) { // Get the players net worth auto shipValue = Hk::Player::GetShipValue(client); if (shipValue.has_error()) { Console::ConWarn(std::format("Unable to get ship value of undocking player: {}", wstos(Hk::Err::ErrGetText(shipValue.error())))); return; } const auto cash = Hk::Player::GetCash(client); if (cash.has_error()) { Console::ConWarn(std::format("Unable to get cash of undocking player: {}", wstos(Hk::Err::ErrGetText(cash.error())))); return; } auto dpCredits = static_cast<uint>(static_cast<float>(shipValue.value()) * GetShipFractionOverride(client)); if (cash < dpCredits) dpCredits = cash.value(); // Calculate what the death penalty would be upon death global->MapClients[client].DeathPenaltyCredits = dpCredits; // Should we print a death penalty notice? if (global->MapClients[client].bDisplayDPOnLaunch) PrintUserCmdText(client, std::format(L"Notice: the death penalty for your ship will be {} credits. Type /dp for more information.", ToMoneyStr(global->MapClients[client].DeathPenaltyCredits))); } else global->MapClients[client].DeathPenaltyCredits = 0; } } /** @ingroup DeathPenalty * @brief Load settings directly from the player's save directory */ void LoadUserCharSettings(ClientId& client) { // Get Account directory then flhookuser.ini file const CAccount* acc = Players.FindAccountFromClientID(client); std::wstring dir = Hk::Client::GetAccountDirName(acc); std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; // Get char filename and save setting to flhookuser.ini const auto wscFilename = Hk::Client::GetCharFileName(client); std::string scFilename = wstos(wscFilename.value()); std::string scSection = "general_" + scFilename; // read death penalty settings CLIENT_DATA c; c.bDisplayDPOnLaunch = IniGetB(scUserFile, scSection, "DPnotice", true); global->MapClients[client] = c; } /** @ingroup DeathPenalty * @brief Apply the death penalty on a player death */ void PenalizeDeath(ClientId client, uint iKillerId) { if (global->config->DeathPenaltyFraction < 0.00001f) return; // Valid client and the ShipArch or System isnt in the excluded list? if (client != UINT_MAX && !IsInExcludedSystem(client)) { // Get the players cash const auto cash = Hk::Player::GetCash(client); if (cash.has_error()) { Console::ConWarn("Unable to get cash from client."); return; } // Get how much the player owes uint cashOwed = global->MapClients[client].DeathPenaltyCredits; // If the amount the player owes is more than they have, set the // amount to their total cash if (cashOwed > cash.value()) cashOwed = cash.value(); // If another player has killed the player if (iKillerId != client && (global->config->DeathPenaltyFractionKiller > 0.0f)) { auto killerReward = static_cast<uint>(static_cast<float>(cashOwed) * global->config->DeathPenaltyFractionKiller); if (killerReward) { // Reward the killer, print message to them Hk::Player::AddCash(iKillerId, killerReward); PrintUserCmdText(iKillerId, std::format(L"Death penalty: given {} credits from {}'s death penalty.", ToMoneyStr(killerReward), Hk::Client::GetCharacterNameByID(client).value())); } } if (cashOwed) { // Print message to the player and remove cash PrintUserCmdText(client, L"Death penalty: charged " + ToMoneyStr(cashOwed) + L" credits."); Hk::Player::RemoveCash(client, cashOwed); } } } /** @ingroup DeathPenalty * @brief Hook on ShipDestroyed to kick off PenalizeDeath */ void ShipDestroyed(DamageList** _dmg, const DWORD** ecx, const uint& kill) { if (kill) { // Get client const CShip* cShip = Hk::Player::CShipFromShipDestroyed(ecx); ClientId client = cShip->GetOwnerPlayer(); // Get Killer Id if there is one uint killerId = 0; if (client) { const DamageList* dmg = *_dmg; const auto inflictor = dmg->get_cause() == DamageCause::Unknown ? Hk::Client::GetClientIdByShip(ClientInfo[client].dmgLast.get_inflictor_id()) : Hk::Client::GetClientIdByShip(dmg->get_inflictor_id()); if (inflictor.has_value()) { killerId = inflictor.value(); } // Call function to penalize player and reward killer PenalizeDeath(client, killerId); } } } /** @ingroup DeathPenalty * @brief This will save whether the player wants to receieve the /dp notice or not to the flhookuser.ini file */ void SaveDPNoticeToCharFile(ClientId client, const std::string& value) { const CAccount* acc = Players.FindAccountFromClientID(client); std::wstring dir = Hk::Client::GetAccountDirName(acc); if (const auto file = Hk::Client::GetCharFileName(client); file.has_value()) { std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; std::string scSection = "general_" + wstos(file.value()); IniWrite(scUserFile, scSection, "DPnotice", value); } } /** @ingroup DeathPenalty * @brief /dp command. Shows information about death penalty */ void UserCmd_DP(ClientId& client, const std::wstring& wscParam) { // If there is no death penalty, no point in having death penalty commands if (std::abs(global->config->DeathPenaltyFraction) < 0.0001f) { Console::ConWarn("DP Plugin active, but no/too low death penalty fraction is set."); return; } const auto param = ViewToWString(wscParam); if (wscParam.length()) // Arguments passed { if (ToLower(Trim(param)) == L"off") { global->MapClients[client].bDisplayDPOnLaunch = false; SaveDPNoticeToCharFile(client, "no"); PrintUserCmdText(client, L"Death penalty notices disabled."); } else if (ToLower(Trim(param)) == L"on") { global->MapClients[client].bDisplayDPOnLaunch = true; SaveDPNoticeToCharFile(client, "yes"); PrintUserCmdText(client, L"Death penalty notices enabled."); } else { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"/dp on | /dp off"); } } else { PrintUserCmdText(client, L"The death penalty is charged immediately when you die."); if (!IsInExcludedSystem(client)) { auto shipValue = Hk::Player::GetShipValue(client); if (shipValue.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(shipValue.error())); } auto cashOwed = static_cast<uint>(static_cast<float>(shipValue.value()) * GetShipFractionOverride(client)); uint playerCash = Hk::Player::GetCash(client).value(); PrintUserCmdText(client, std::format(L"The death penalty for your ship will be {} credits.", ToMoneyStr(std::min(cashOwed, playerCash)))); PrintUserCmdText(client, L"If you would like to turn off the death penalty notices, run " L"this command with the argument \"off\"."); } else { PrintUserCmdText(client, L"You don't have to pay the death penalty " L"because you are in a specific system."); } } } // Define usable chat commands here const std::vector commands = {{ CreateUserCommand(L"/dp", L"", UserCmd_DP, L"Shows the credits you would be charged if you died."), }}; } // namespace Plugins::DeathPenalty using namespace Plugins::DeathPenalty; REFL_AUTO(type(Config), field(DeathPenaltyFraction), field(DeathPenaltyFractionKiller), field(ExcludedSystems), field(FractionOverridesByShip)) DefaultDllMainSettings(LoadSettings); // Functions to hook extern "C" EXPORT void ExportPluginInfo(PluginInfo* pi) { pi->name("Death Penalty"); pi->shortName("death_penalty"); pi->mayUnload(true); pi->commands(&commands); pi->returnCode(&global->returncode); pi->versionMajor(PluginMajorVersion::VERSION_04); pi->versionMinor(PluginMinorVersion::VERSION_00); pi->emplaceHook(HookedCall::FLHook__LoadSettings, &LoadSettings, HookStep::After); pi->emplaceHook(HookedCall::IEngine__ShipDestroyed, &ShipDestroyed); pi->emplaceHook(HookedCall::IServerImpl__PlayerLaunch, &PlayerLaunch); pi->emplaceHook(HookedCall::FLHook__LoadCharacterSettings, &LoadUserCharSettings); pi->emplaceHook(HookedCall::FLHook__ClearClientInfo, &ClearClientInfo, HookStep::After); }
11,493
C++
.cpp
298
34.704698
146
0.718344
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,366
CConsole.cpp
TheStarport_FLHook/source/CConsole.cpp
#include "CConsole.h" // I hate this void CConsole::DoPrint(const std::string& text) { if (text.find("ERROR", 0) == 0) { Console::ConErr(ReplaceStr(text, "ERROR", "")); } else if (text.find("error", 0) == 0) { Console::ConErr(ReplaceStr(text, "error", "")); } else if (text.find("Error", 0) == 0) { Console::ConErr(ReplaceStr(text, "Error", "")); } else if (text.find("ERR", 0) == 0) { Console::ConErr(ReplaceStr(text, "ERR", "")); } else if (text.find("err", 0) == 0) { Console::ConErr(ReplaceStr(text, "err", "")); } else Console::ConPrint(text); } std::wstring CConsole::GetAdminName() { return L"Admin console"; }
685
C++
.cpp
31
18.935484
50
0.598145
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,367
FLPacket.cpp
TheStarport_FLHook/source/FLPacket.cpp
#include <FLHook.hpp> // Common packets are being sent from server to client and from client to server. FLPACKET* FLPACKET::Create(uint size, FLPACKET::CommonPacket kind) { auto* packet = static_cast<FLPACKET*>(malloc(size + 6)); packet->Size = size + 2; packet->type = 1; packet->kind = kind; return packet; } // Server packets are being sent only from server to client. FLPACKET* FLPACKET::Create(uint size, FLPACKET::ServerPacket kind) { auto* packet = static_cast<FLPACKET*>(malloc(size + 6)); packet->Size = size + 2; packet->type = 2; packet->kind = kind; return packet; } // Client packets are being sent only from client to server. Can't imagine why you ever need to create such a packet at side of server. FLPACKET* FLPACKET::Create(uint size, FLPACKET::ClientPacket kind) { auto* packet = static_cast<FLPACKET*>(malloc(size + 6)); packet->Size = size + 2; packet->type = 3; packet->kind = kind; return packet; } // Returns true if sent succesfully, false if not. Frees memory allocated for packet. bool FLPACKET::SendTo(ClientId client) { CDPClientProxy* cdpClient = clientProxyArray[client - 1]; // We don't include first 4 bytes directly in packet, it is info about size. Type and kind are already included. bool result = cdpClient->Send((byte*)this + 4, Size); // No mistakes, free allocated memory. free(this); return result; }
1,372
C++
.cpp
38
34.315789
135
0.741887
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,368
Debug.cpp
TheStarport_FLHook/source/Debug.cpp
#include "Global.hpp" #define SPDLOG_USE_STD_FORMAT #include "spdlog/spdlog.h" #include "spdlog/async.h" #include "spdlog/sinks/basic_file_sink.h" #include <Tools/Detour.hpp> using CreateIDType = uint (*)(const char*); std::map<std::string, uint> DebugTools::hashMap; std::shared_ptr<spdlog::logger> hashList = nullptr; const auto detour = std::make_unique<FunctionDetour<CreateIDType>>(CreateID); uint DebugTools::CreateIdDetour(const char* str) { if (!str) return 0; detour->UnDetour(); uint hash = CreateID(str); detour->Detour(CreateIdDetour); std::string fullStr = str; if (hashMap.contains(fullStr)) { return hash; } hashMap[fullStr] = hash; hashList->log(spdlog::level::debug, std::format("{} {:#X} {}", hash, hash, fullStr)); return hash; } void DebugTools::Init() { if (!FLHookConfig::i()->general.debugMode) { return; } hashList = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_hashmap", "logs/flhook_hashmap.log"); spdlog::flush_on(spdlog::level::debug); hashList->set_level(spdlog::level::debug); detour->Detour(CreateIdDetour); };
1,088
C++
.cpp
37
27.486486
104
0.732949
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,369
HkIChatServer.cpp
TheStarport_FLHook/source/HkIChatServer.cpp
#include "Global.hpp" /************************************************************************************************************** called when chat-text is being sent to a player, we reformat it(/set chatfont) **************************************************************************************************************/ #define HAS_FLAG(a, b) ((a).wscFlags.find(b) != -1) void __stdcall SendChat(ClientId client, ClientId clientTo, uint size, void* rdl) { CallPluginsBefore(HookedCall::IChat__SendChat, client, clientTo, size, rdl); TRY_HOOK { if (IServerImplHook::chatData->inSubmitChat && (clientTo != 0x10004)) { std::wstring buffer; buffer.resize(size); // extract text from rdlReader BinaryRDLReader r; uint iRet; r.extract_text_from_buffer((unsigned short*)buffer.data(), buffer.size(), iRet, (const char*)rdl, size); std::erase(buffer, '\0'); const std::wstring sender = IServerImplHook::chatData->characterName; const int spaceAfterColonOffset = buffer[sender.length() + 1] == ' ' ? sender.length() + 2 : 0; const std::wstring text = buffer.substr(spaceAfterColonOffset, buffer.length() - spaceAfterColonOffset); if (FLHookConfig::i()->userCommands.userCmdIgnore && ((clientTo & 0xFFFF) != 0)) { // check ignores for (const auto& ci : ClientInfo[client].lstIgnore) { if (HAS_FLAG(ci, L"p") && (clientTo & 0x10000)) continue; // no privchat else if (!HAS_FLAG(ci, L"i") && !(ToLower(sender).compare(ToLower(ci.character)))) return; // ignored else if (HAS_FLAG(ci, L"i") && (ToLower(sender).find(ToLower(ci.character)) != -1)) return; // ignored } } uchar format = 0x00; if (FLHookConfig::i()->userCommands.userCmdSetChatFont) { // adjust chat size switch (ClientInfo[client].chatSize) { case CS_SMALL: format = 0x90; break; case CS_BIG: format = 0x10; break; default: format = 0x00; break; } // adjust chat style switch (ClientInfo[client].chatStyle) { case CST_BOLD: format += 0x01; break; case CST_ITALIC: format += 0x02; break; case CST_UNDERLINE: format += 0x04; break; default: format += 0x00; break; } } wchar_t formatBuf[8]; swprintf_s(formatBuf, L"%02X", (long)format); std::wstring traDataFormat = formatBuf; std::wstring traDataColor; std::wstring traDataSenderColor = L"FFFFFF"; if (CoreGlobals::c()->messagePrivate) { traDataColor = L"19BD3A"; // pm chat color } else if (CoreGlobals::c()->messageSystem) { traDataSenderColor = L"00FF00"; traDataColor = L"E6C684"; // system chat color } else if (CoreGlobals::c()->messageUniverse) { traDataSenderColor = L"00FF00"; traDataColor = L"FFFFFF"; // universe chat color } else if (clientTo == 0x10000) traDataColor = L"FFFFFF"; // universe chat color else if (clientTo == 0) traDataColor = L"FFFFFF"; // console else if (clientTo == 0x10003) traDataColor = L"FF7BFF"; // group chat else if (clientTo == 0x10002) traDataColor = L"FF8F40"; // local chat color else if (clientTo & 0x10000) traDataColor = L"E6C684"; // system chat color else traDataColor = L"19BD3A"; // pm chat color std::wstringstream wos; wos << L"<TRA data=\"0x" << traDataSenderColor + traDataFormat << L"\" mask=\"-1\"/><TEXT>" << XMLText(sender) << L": </TEXT>" << L"<TRA data =\"0x" << traDataColor + traDataFormat << L"\" mask=\"-1\"/>" << "<TEXT>" << XMLText(text) + L"</TEXT>"; Hk::Message::FMsg(client, wos.str()); } else { uint sz = size; __asm { pushad push [rdl] push [sz] push [clientTo] push [client] mov ecx, [Client] add ecx, 4 call [RCSendChatMsg] popad } } } CATCH_HOOK({}) }
3,994
C++
.cpp
122
27.122951
111
0.579808
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,371
Tools.cpp
TheStarport_FLHook/source/Tools.cpp
#include "Global.hpp" /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string itohexs(uint value) { char buf[16]; sprintf_s(buf, "%08X", value); return buf; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string IniGetS(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::string& scDefault) { char szRet[2048 * 2]; GetPrivateProfileString(scApp.c_str(), scKey.c_str(), scDefault.c_str(), szRet, sizeof(szRet), scFile.c_str()); return szRet; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// int IniGetI(const std::string& scFile, const std::string& scApp, const std::string& scKey, int iDefault) { return GetPrivateProfileInt(scApp.c_str(), scKey.c_str(), iDefault, scFile.c_str()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// float IniGetF(const std::string& scFile, const std::string& scApp, const std::string& scKey, float fDefault) { char szRet[2048 * 2]; char szDefault[16]; sprintf_s(szDefault, "%f", fDefault); GetPrivateProfileString(scApp.c_str(), scKey.c_str(), szDefault, szRet, sizeof(szRet), scFile.c_str()); return (float)atof(szRet); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IniGetB(const std::string& scFile, const std::string& scApp, const std::string& scKey, bool bDefault) { std::string val = ToLower(IniGetS(scFile, scApp, scKey, bDefault ? "true" : "false")); return val.compare("yes") == 0 || val.compare("true") == 0 ? true : false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void IniWrite(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::string& scValue) { WritePrivateProfileString(scApp.c_str(), scKey.c_str(), scValue.c_str(), scFile.c_str()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void IniWriteW(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::wstring& wscValue) { std::string scValue = ""; for (uint i = 0; (i < wscValue.length()); i++) { char cHiByte = wscValue[i] >> 8; char cLoByte = wscValue[i] & 0xFF; char szBuf[8]; sprintf_s(szBuf, "%02X%02X", ((uint)cHiByte) & 0xFF, ((uint)cLoByte) & 0xFF); scValue += szBuf; } WritePrivateProfileString(scApp.c_str(), scKey.c_str(), scValue.c_str(), scFile.c_str()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::wstring IniGetWS(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::wstring& wscDefault) { char szRet[2048 * 2]; GetPrivateProfileString(scApp.c_str(), scKey.c_str(), "", szRet, sizeof(szRet), scFile.c_str()); std::string scValue = szRet; if (!scValue.length()) return wscDefault; std::wstring wscValue = L""; long lHiByte; long lLoByte; while (sscanf_s(scValue.c_str(), "%02X%02X", &lHiByte, &lLoByte) == 2) { scValue = scValue.substr(4); wchar_t wChar = (wchar_t)((lHiByte << 8) | lLoByte); wscValue.append(1, wChar); } return wscValue; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void IniDelete(const std::string& scFile, const std::string& scApp, const std::string& scKey) { WritePrivateProfileString(scApp.c_str(), scKey.c_str(), NULL, scFile.c_str()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void IniDelSection(const std::string& scFile, const std::string& scApp) { WritePrivateProfileString(scApp.c_str(), NULL, NULL, scFile.c_str()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Determine the path name of a file in the charname account directory with the provided extension. The resulting path is returned in the path parameter. */ std::string GetUserFilePath(const std::variant<uint, std::wstring>& player, const std::string& scExtension) { // init variables char szDataPath[MAX_PATH]; GetUserDataPath(szDataPath); std::string scAcctPath = std::string(szDataPath) + "\\Accts\\MultiPlayer\\"; const auto acc = Hk::Client::GetAccountByCharName(std::get<std::wstring>(player)); if (acc.has_error()) return ""; auto dir = Hk::Client::GetAccountDirName(acc.value()); const auto file = Hk::Client::GetCharFileName(player); if (file.has_error()) return ""; return scAcctPath + wstos(dir) + "\\" + wstos(file.value()) + scExtension; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL FileExists(LPCTSTR szPath) { DWORD dwAttrib = GetFileAttributes(szPath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::wstring GetTimeString(bool bLocalTime) { SYSTEMTIME st; if (bLocalTime) GetLocalTime(&st); else GetSystemTime(&st); wchar_t wszBuf[100]; _snwprintf_s( wszBuf, sizeof(wszBuf), L"%04d-%02d-%02d %02d:%02d:%02d ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); return wszBuf; } void ini_write_wstring(FILE* file, const std::string& parmname, const std::wstring& in) { fprintf(file, "%s=", parmname.c_str()); for (int i = 0; i < (int)in.size(); i++) { UINT v1 = in[i] >> 8; UINT v2 = in[i] & 0xFF; fprintf(file, "%02x%02x", v1, v2); } fprintf(file, "\n"); } void ini_get_wstring(INI_Reader& ini, std::wstring& wscValue) { std::string scValue = ini.get_value_string(); wscValue = L""; long lHiByte; long lLoByte; while (sscanf_s(scValue.c_str(), "%02X%02X", &lHiByte, &lLoByte) == 2) { scValue = scValue.substr(4); wchar_t wChar = (wchar_t)((lHiByte << 8) | lLoByte); wscValue.append(1, wChar); } }
6,411
C++
.cpp
147
40.346939
133
0.523348
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,372
FLHook.cpp
TheStarport_FLHook/source/FLHook.cpp
#include "Global.hpp" #include "CConsole.h" #include "Memory/MemoryManager.hpp" // structs struct SOCKET_CONNECTION { std::wstring wscPending; CSocket csock; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// HANDLE hProcFL = 0; HMODULE hModServer = 0; HMODULE hModCommon = 0; HMODULE hModRemoteClient = 0; HMODULE hMe = 0; HMODULE hModDPNet = 0; HMODULE hModDaLib = 0; HMODULE hModContent = 0; HANDLE hConsoleThread; HANDLE hConsoleIn; HANDLE hConsoleOut; HANDLE hConsoleErr; SOCKET sListen = INVALID_SOCKET; SOCKET sWListen = INVALID_SOCKET; SOCKET sEListen = INVALID_SOCKET; SOCKET sEWListen = INVALID_SOCKET; std::list<std::wstring*> lstConsoleCmds; std::list<SOCKET_CONNECTION*> lstSockets; std::list<SOCKET_CONNECTION*> lstDelete; CRITICAL_SECTION cs; bool bExecuted = false; CConsole AdminConsole; st6_malloc_t st6_malloc; st6_free_t st6_free; bool flhookReady; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Init(); /************************************************************************************************************** DllMain **************************************************************************************************************/ FARPROC fpOldUpdate; namespace IServerImplHook { bool __stdcall Startup(SStartupInfo const& si); void __stdcall Shutdown(); int __stdcall Update(); } // namespace IServerImplHook BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if (bExecuted) return TRUE; char szFile[MAX_PATH]; GetModuleFileName(0, szFile, sizeof(szFile)); if (std::wstring wscFileName = ToLower(stows(szFile)); wscFileName.find(L"flserver.exe") != -1) { // We need to init our memory hooks before anything is loaded! MemoryManager::i()->AddHooks(); bExecuted = true; // redirect IServerImpl::Update FARPROC fpLoop = (FARPROC)IServerImplHook::Update; void* pAddress = (void*)((char*)GetModuleHandle(0) + ADDR_UPDATE); ReadProcMem(pAddress, &fpOldUpdate, 4); WriteProcMem(pAddress, &fpLoop, 4); // install startup hook FARPROC fpStartup = (FARPROC)IServerImplHook::Startup; pAddress = (void*)((char*)GetModuleHandle(0) + ADDR_STARTUP); WriteProcMem(pAddress, &fpStartup, 4); // install shutdown hook FARPROC fpShutdown = (FARPROC)IServerImplHook::Shutdown; pAddress = (void*)((char*)GetModuleHandle(0) + ADDR_SHUTDOWN); WriteProcMem(pAddress, &fpShutdown, 4); // create log dirs CreateDirectoryA("./logs/", NULL); CreateDirectoryA("./logs/debug", NULL); } return TRUE; } /************************************************************************************************************** Replace FLServer's exception handler with our own. **************************************************************************************************************/ #ifndef DISABLE_EXTENDED_EXCEPTION_LOGGING BYTE oldSetUnhandledExceptionFilter[5]; LONG WINAPI FLHookTopLevelFilter(struct _EXCEPTION_POINTERS* pExceptionInfo) { AddLog(LogType::Normal, LogLevel::Critical, "!!TOP LEVEL EXCEPTION!!"); SEHException ex(0, pExceptionInfo); WriteMiniDump(&ex); return EXCEPTION_EXECUTE_HANDLER; // EXCEPTION_CONTINUE_SEARCH; } LPTOP_LEVEL_EXCEPTION_FILTER WINAPI Cb_SetUnhandledExceptionFilter(LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter) { return NULL; } #endif /************************************************************************************************************** thread that reads console input **************************************************************************************************************/ void __stdcall ReadConsoleEvents() { while (true) { DWORD dwBytesRead; std::string cmd; cmd.resize(1024); if (ReadConsole(hConsoleIn, cmd.data(), cmd.size(), &dwBytesRead, nullptr)) { if (cmd[cmd.length() - 1] == '\n') cmd = cmd.substr(0, cmd.length() - 1); if (cmd[cmd.length() - 1] == '\r') cmd = cmd.substr(0, cmd.length() - 1); std::wstring wscCmd = stows(cmd); EnterCriticalSection(&cs); auto pwscCmd = new std::wstring; *pwscCmd = wscCmd; lstConsoleCmds.push_back(pwscCmd); LeaveCriticalSection(&cs); } } } /************************************************************************************************************** handles console events **************************************************************************************************************/ BOOL WINAPI ConsoleHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_CLOSE_EVENT: { return TRUE; } break; } return FALSE; } /************************************************************************************************************** init **************************************************************************************************************/ const std::array<const char*, 4> PluginLibs = { "pcre2-posix.dll", "pcre2-8.dll", "pcre2-16.dll", "pcre2-32.dll", }; void FLHookInit_Pre() { InitializeCriticalSection(&cs); hProcFL = GetModuleHandle(0); // Get direct pointers to malloc and free for st6 to prevent debug heap // issues { const auto dll = GetModuleHandle(TEXT("msvcrt.dll")); if (!dll) throw std::runtime_error("msvcrt.dll"); st6_malloc = reinterpret_cast<st6_malloc_t>(GetProcAddress(dll, "malloc")); st6_free = reinterpret_cast<st6_free_t>(GetProcAddress(dll, "free")); } // start console AllocConsole(); SetConsoleTitle("FLHook"); HWND console = GetConsoleWindow(); RECT r; GetWindowRect(console, &r); MoveWindow(console, r.left, r.top, 1366, 768, TRUE); SetConsoleCtrlHandler(ConsoleHandler, TRUE); hConsoleIn = GetStdHandle(STD_INPUT_HANDLE); hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE); hConsoleErr = GetStdHandle(STD_ERROR_HANDLE); // change version number here: // https://patorjk.com/software/taag/#p=display&f=Big&t=FLHook%204.0 std::string welcomeText = R"( ______ _ _ _ _ _ _ ___ | ____| | | | | | | | | || | / _ \ | |__ | | | |__| | ___ ___ | | __ | || |_| | | | | __| | | | __ |/ _ \ / _ \| |/ / |__ _| | | | | | | |____| | | | (_) | (_) | < | |_| |_| | |_| |______|_| |_|\___/ \___/|_|\_\ |_(_)\___/ )"; welcomeText += "\n\n"; DWORD _; WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), welcomeText.c_str(), DWORD(welcomeText.length()), &_, nullptr); try { // Load our settings before anything that might need access to debug mode LoadSettings(); // Initialize the log files and throw exception if there is a problem if (!InitLogs()) throw std::runtime_error("Log files cannot be created."); // Setup needed debug tools DebugTools::i()->Init(); // get module handles if (!(hModServer = GetModuleHandle("server"))) throw std::runtime_error("server.dll not loaded"); DWORD id; hConsoleThread = CreateThread(nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(ReadConsoleEvents), nullptr, 0, &id); PluginManager::i(); if (const auto config = FLHookConfig::c(); config->plugins.loadAllPlugins) { PluginManager::i()->loadAll(true, &AdminConsole); } else { for (auto& i : config->plugins.plugins) { PluginManager::i()->load(stows(i), &AdminConsole, true); } } if (!std::filesystem::exists("config")) { std::filesystem::create_directory("config"); } // Load required libs that plugins might leverage for (const auto& lib : PluginLibs) { LoadLibrary(lib); } Console::ConInfo("Loading Freelancer INIs"); const auto dataManager = DataManager::i(); dataManager->LoadLights(); Hk::Ini::CharacterInit(); Hk::Personalities::LoadPersonalities(); PatchClientImpl(); #ifndef DISABLE_EXTENDED_EXCEPTION_LOGGING // Install our own exception handler to automatically log minidumps. ::SetUnhandledExceptionFilter(FLHookTopLevelFilter); // Hook the kernel SetUnhandledExceptionFilter function to prevent // newer versions of the crt disabling our filter function if a buffer // overrun is detected. HMODULE ernel32 = LoadLibrary("kernel32.dll"); if (ernel32) { void* dwOrgEntry = GetProcAddress(ernel32, "SetUnhandledExceptionFilter"); if (dwOrgEntry) { DWORD offset = (char*)dwOrgEntry - (char*)ernel32; ReadProcMem((char*)ernel32 + offset, oldSetUnhandledExceptionFilter, 5); BYTE patch[] = {0xE9}; WriteProcMem((char*)ernel32 + offset, patch, 1); PatchCallAddr((char*)ernel32, offset, (char*)Cb_SetUnhandledExceptionFilter); } } #endif CallPluginsAfter(HookedCall::FLHook__LoadSettings); } catch (char* szError) { Console::ConErr(std::format("CRITICAL! {}\n", szError)); exit(EXIT_FAILURE); } catch (std::filesystem::filesystem_error& error) { Console::ConErr(std::format("Failed to create directory {}\n{}", error.path1().generic_string(), error.what())); } } bool FLHookInit() { bool bInitHookExports = false; try { // get module handles if (!(hModServer = GetModuleHandle("server"))) throw std::runtime_error("server.dll not loaded"); if (!(hModRemoteClient = GetModuleHandle("remoteclient"))) throw std::runtime_error("remoteclient.dll not loaded"); if (!(hModCommon = GetModuleHandle("common"))) throw std::runtime_error("common.dll not loaded"); if (!(hModDPNet = GetModuleHandle("dpnet"))) throw std::runtime_error("dpnet.dll not loaded"); if (!(hModDaLib = GetModuleHandle("dalib"))) throw std::runtime_error("dalib.dll not loaded"); if (!(hModContent = GetModuleHandle("content"))) throw std::runtime_error("content.dll not loaded"); if (!(hMe = GetModuleHandle("FLHook"))) throw std::runtime_error("FLHook.dll not loaded"); // init hooks if (!InitHookExports()) throw std::runtime_error("InitHookExports failed"); bInitHookExports = true; const auto* config = FLHookConfig::c(); if (config->socket.activated) { // listen to socket WSADATA wsa; WSAStartup(MAKEWORD(2, 0), &wsa); if (config->socket.port > 0) { sListen = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in adr; memset(&adr, 0, sizeof(adr)); adr.sin_family = AF_INET; adr.sin_port = htons(config->socket.port); if (::bind(sListen, (sockaddr*)&adr, sizeof(adr)) != 0) throw std::runtime_error("ascii: socket-bind failed, port already in use?"); if (listen(sListen, SOMAXCONN) != 0) throw std::runtime_error("ascii: socket-listen failed"); Console::ConInfo("socket(ascii): socket connection listening"); } if (config->socket.wPort > 0) { sWListen = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in adr; memset(&adr, 0, sizeof(adr)); adr.sin_family = AF_INET; adr.sin_port = htons(config->socket.wPort); if (::bind(sWListen, (sockaddr*)&adr, sizeof(adr)) != 0) throw std::runtime_error("unicode: socket-bind failed, port already in use?"); if (listen(sWListen, SOMAXCONN) != 0) throw std::runtime_error("unicode: socket-listen failed"); Console::ConInfo("socket(unicode): socket connection listening"); } if (config->socket.ePort > 0) { sEListen = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in adr; memset(&adr, 0, sizeof(adr)); adr.sin_family = AF_INET; adr.sin_port = htons(config->socket.ePort); if (::bind(sEListen, (sockaddr*)&adr, sizeof(adr)) != 0) throw std::runtime_error("encrypted: socket-bind failed, port already in use?"); if (listen(sEListen, SOMAXCONN) != 0) throw std::runtime_error("encrypted: socket-listen failed"); Console::ConInfo("socket(encrypted-ascii): socket connection listening"); } if (config->socket.eWPort > 0) { sEWListen = socket(AF_INET, SOCK_STREAM, 0); sockaddr_in adr; memset(&adr, 0, sizeof(adr)); adr.sin_family = AF_INET; adr.sin_port = htons(config->socket.eWPort); if (::bind(sEWListen, (sockaddr*)&adr, sizeof(adr)) != 0) throw std::runtime_error("encrypted-unicode: socket-bind failed, port already in use?"); if (listen(sEWListen, SOMAXCONN) != 0) throw std::runtime_error("encrypted-unicode: socket-listen failed"); Console::ConInfo("socket(encrypted-unicode): socket connection listening"); } } } catch (char* szError) { if (bInitHookExports) UnloadHookExports(); if (sListen != INVALID_SOCKET) { closesocket(sListen); sListen = INVALID_SOCKET; } if (sWListen != INVALID_SOCKET) { closesocket(sWListen); sWListen = INVALID_SOCKET; } if (sEListen != INVALID_SOCKET) { closesocket(sEListen); sEListen = INVALID_SOCKET; } if (sEWListen != INVALID_SOCKET) { closesocket(sEWListen); sEWListen = INVALID_SOCKET; } Console::ConErr(szError); return false; } return true; } /************************************************************************************************************** shutdown **************************************************************************************************************/ void FLHookUnload() { // bad but working.. Sleep(1000); // unload console TerminateThread(hConsoleThread, 0); SetConsoleCtrlHandler(ConsoleHandler, FALSE); FreeConsole(); // quit network sockets if (sListen != INVALID_SOCKET) closesocket(sListen); if (sWListen != INVALID_SOCKET) closesocket(sWListen); if (sEListen != INVALID_SOCKET) closesocket(sEListen); if (sEWListen != INVALID_SOCKET) closesocket(sEWListen); for (auto i : lstSockets) { closesocket(i->csock.s); delete i; } lstSockets.clear(); // free blowfish encryption data if (const FLHookConfig* config = FLHookConfig::i(); config->socket.bfCTX) { ZeroMemory(config->socket.bfCTX, sizeof(config->socket.bfCTX)); free(config->socket.bfCTX); } // misc DeleteCriticalSection(&cs); // finish FreeLibraryAndExitThread(hMe, 0); } void FLHookShutdown() { TerminateThread(hThreadResolver, 0); // unload update hook void* pAddress = (void*)((char*)hProcFL + ADDR_UPDATE); WriteProcMem(pAddress, &fpOldUpdate, 4); // unload hooks UnloadHookExports(); #ifndef DISABLE_EXTENDED_EXCEPTION_LOGGING // If extended exception logging is in use, restore patched functions HMODULE ernel32 = GetModuleHandle("kernel32.dll"); if (ernel32) { void* dwOrgEntry = GetProcAddress(ernel32, "SetUnhandledExceptionFilter"); if (dwOrgEntry) { DWORD offset = (char*)dwOrgEntry - (char*)ernel32; WriteProcMem((char*)ernel32 + offset, oldSetUnhandledExceptionFilter, 5); } } // And restore the default exception filter. SetUnhandledExceptionFilter(0); #endif AddLog(LogType::Normal, LogLevel::Err, "-------------------"); // unload rest DWORD id; DWORD dwParam; CreateThread(0, 0, (LPTHREAD_START_ROUTINE)FLHookUnload, &dwParam, 0, &id); } /************************************************************************************************************** process a socket command return true -> close socket connection **************************************************************************************************************/ bool ProcessSocketCmd(SOCKET_CONNECTION* sc, std::wstring wscCmd) { if (!ToLower(wscCmd).find(L"quit")) { // quit connection sc->csock.DoPrint("Goodbye.\r"); Console::ConInfo("socket: connection closed"); return true; } else if (!(sc->csock.bAuthed)) { const std::wstring wscLwr = ToLower(wscCmd); auto passFind = wscLwr.find(L"pass "); if (passFind == std::wstring::npos) { sc->csock.Print("ERR Please authenticate first"); return false; } if (wscCmd.length() >= 256) { sc->csock.DoPrint("ERR Wrong password"); sc->csock.DoPrint("Goodbye.\r"); Console::ConInfo("socket: connection closed (invalid pass)"); AddLog(LogType::Normal, LogLevel::Info, std::format("socket: socket connection from {}:{} closed (invalid pass)", sc->csock.sIP, sc->csock.iPort)); return true; } const auto* config = FLHookConfig::c(); // Remove the string "pass " from the string auto pass = wscCmd.substr(passFind + 5); pass = Trim(pass); const auto auth = config->socket.passRightsMap.find(pass); if (auth == config->socket.passRightsMap.end()) { sc->csock.DoPrint("ERR Wrong password"); sc->csock.DoPrint("Goodbye.\r"); Console::ConInfo("socket: connection closed (invalid pass)"); AddLog(LogType::Normal, LogLevel::Info, std::format("socket: socket connection from {}:{} closed (invalid pass)", sc->csock.sIP.c_str(), sc->csock.iPort)); return true; } sc->csock.bAuthed = true; sc->csock.SetRightsByString(auth->second); sc->csock.Print("OK"); Console::ConInfo("socket: socket authentication successful"); return false; } else { if (const auto cmd = Trim(wscCmd); cmd == L"eventmode") { if (sc->csock.rights & RIGHT_EVENTMODE) { sc->csock.Print("OK"); sc->csock.bEventMode = true; } else { sc->csock.Print("ERR No permission"); } } else sc->csock.ExecuteCommandString(cmd); return false; } } /************************************************************************************************************** send event to all sockets which are in eventmode **************************************************************************************************************/ void ProcessEvent(std::wstring text, ...) { wchar_t wszBuf[1024] = L""; va_list marker; va_start(marker, text); _vsnwprintf_s(wszBuf, (sizeof(wszBuf) / 2) - 1, text.c_str(), marker); text = wszBuf; CallPluginsBefore(HookedCall::FLHook__ProcessEvent, static_cast<std::wstring&>(text)); for (auto& socket : lstSockets) { if (socket->csock.bEventMode) socket->csock.Print(wstos(text)); } } /************************************************************************************************************** check for pending admin commands in console or socket and execute them **************************************************************************************************************/ struct timeval tv = {0, 0}; void ProcessPendingCommands() { TRY_HOOK { // check for new console commands EnterCriticalSection(&cs); while (!lstConsoleCmds.empty()) { std::wstring* pwscCmd = lstConsoleCmds.front(); lstConsoleCmds.pop_front(); if (pwscCmd) { AdminConsole.ExecuteCommandString(Trim(*pwscCmd)); delete pwscCmd; } } LeaveCriticalSection(&cs); if (sListen != INVALID_SOCKET) { // check for new ascii socket connections FD_SET fds; FD_ZERO(&fds); FD_SET(sListen, &fds); if (select(0, &fds, 0, 0, &tv)) { // accept new connection sockaddr_in adr; int iLen = sizeof(adr); SOCKET s = accept(sListen, (sockaddr*)&adr, &iLen); ulong lNB = 1; ioctlsocket(s, FIONBIO, &lNB); SOCKET_CONNECTION* sc = new SOCKET_CONNECTION; sc->csock.s = s; sc->csock.sIP = (std::string)inet_ntoa(adr.sin_addr); sc->csock.iPort = adr.sin_port; sc->csock.bUnicode = false; sc->csock.bEncrypted = false; sc->wscPending = L""; lstSockets.push_back(sc); Console::ConInfo(std::format("socket(ascii): new socket connection from {}:{}", sc->csock.sIP, sc->csock.iPort)); sc->csock.Print("Welcome to FLHack, please authenticate"); } } if (sWListen != INVALID_SOCKET) { // check for new ascii socket connections FD_SET fds; FD_ZERO(&fds); FD_SET(sWListen, &fds); if (select(0, &fds, 0, 0, &tv)) { // accept new connection sockaddr_in adr; int iLen = sizeof(adr); SOCKET s = accept(sWListen, (sockaddr*)&adr, &iLen); ulong lNB = 1; ioctlsocket(s, FIONBIO, &lNB); SOCKET_CONNECTION* sc = new SOCKET_CONNECTION; sc->csock.s = s; sc->csock.sIP = (std::string)inet_ntoa(adr.sin_addr); sc->csock.iPort = adr.sin_port; sc->csock.bUnicode = true; sc->wscPending = L""; sc->csock.bEncrypted = false; lstSockets.push_back(sc); Console::ConInfo(std::format("socket(unicode): new socket connection from {}:{}", sc->csock.sIP, sc->csock.iPort)); sc->csock.Print("Welcome to FLHack, please authenticate"); } } if (sEListen != INVALID_SOCKET) { // check for new ascii socket connections FD_SET fds; FD_ZERO(&fds); FD_SET(sEListen, &fds); if (select(0, &fds, nullptr, 0, &tv)) { // accept new connection sockaddr_in adr; int iLen = sizeof(adr); SOCKET s = accept(sEListen, (sockaddr*)&adr, &iLen); ulong lNB = 1; ioctlsocket(s, FIONBIO, &lNB); SOCKET_CONNECTION* sc = new SOCKET_CONNECTION; sc->csock.s = s; sc->csock.sIP = (std::string)inet_ntoa(adr.sin_addr); sc->csock.iPort = adr.sin_port; sc->csock.bUnicode = false; sc->wscPending = L""; sc->csock.bEncrypted = true; sc->csock.bfc = static_cast<BLOWFISH_CTX*>(FLHookConfig::c()->socket.bfCTX); lstSockets.push_back(sc); Console::ConInfo(std::format("socket(encrypted-ascii): new socket connection from {}:{}", sc->csock.sIP, sc->csock.iPort)); sc->csock.Print("Welcome to FLHack, please authenticate"); } } if (sEWListen != INVALID_SOCKET) { // check for new ascii socket connections FD_SET fds; FD_ZERO(&fds); FD_SET(sEWListen, &fds); if (select(0, &fds, 0, 0, &tv)) { // accept new connection sockaddr_in adr; int iLen = sizeof(adr); SOCKET s = accept(sEWListen, (sockaddr*)&adr, &iLen); ulong lNB = 1; ioctlsocket(s, FIONBIO, &lNB); SOCKET_CONNECTION* sc = new SOCKET_CONNECTION; sc->csock.s = s; sc->csock.sIP = (std::string)inet_ntoa(adr.sin_addr); sc->csock.iPort = adr.sin_port; sc->csock.bUnicode = true; sc->wscPending = L""; sc->csock.bEncrypted = true; sc->csock.bfc = static_cast<BLOWFISH_CTX*>(FLHookConfig::c()->socket.bfCTX); lstSockets.push_back(sc); Console::ConInfo(std::format("socket(encrypted-unicode): new socket connection from {}:{}", sc->csock.sIP, sc->csock.iPort)); sc->csock.Print("Welcome to FLHack, please authenticate"); } } // check for pending socket-commands for (auto& sc : lstSockets) { FD_SET fds; FD_ZERO(&fds); FD_SET(sc->csock.s, &fds); struct timeval tv = {0, 0}; if (select(0, &fds, 0, 0, &tv)) { // data to be read ulong lSize; ioctlsocket(sc->csock.s, FIONREAD, &lSize); char* szData = new char[lSize + 1]; memset(szData, 0, lSize + 1); if (int err = recv(sc->csock.s, szData, lSize, 0); err <= 0) { if (FLHookConfig::c()->general.debugMode) { int wsaLastErr = WSAGetLastError(); Console::ConWarn(std::format("Socket Error - recv: {} - WSAGetLastError: {}", err, wsaLastErr)); } Console::ConWarn("socket: socket connection closed"); delete[] szData; lstDelete.push_back(sc); continue; } // enqueue commands (terminated by \n) std::wstring wscData; if (sc->csock.bEncrypted) { SwapBytes(szData, lSize); Blowfish_Decrypt(sc->csock.bfc, szData, lSize); SwapBytes(szData, lSize); } if (sc->csock.bUnicode) wscData = std::wstring((wchar_t*)szData, lSize / 2); else wscData = stows(szData); std::wstring wscTmp = sc->wscPending + wscData; wscData = wscTmp; // check for memory overflow ddos attack uint iMaxKB = 1; if ((sc->csock.bAuthed)) // not authenticated yet iMaxKB = 500; if (wscData.length() > (1024 * iMaxKB)) { Console::ConWarn("socket: socket connection closed (possible ddos attempt)"); AddLog(LogType::Normal, LogLevel::Info, std::format("socket: socket connection from {}:{} closed (possible ddos attempt)", sc->csock.sIP, sc->csock.iPort)); delete[] szData; lstDelete.push_back(sc); continue; } std::list<std::wstring> lstCmds; std::wstring wscCmd; for (uint i = 0; (i < wscData.length()); i++) { if (!wscData.substr(i, 2).compare(L"\r\n")) { lstCmds.push_back(wscCmd); wscCmd = L""; i++; } else if (wscData[i] == '\n') { lstCmds.push_back(wscCmd); wscCmd = L""; } else wscCmd.append(1, wscData[i]); } sc->wscPending = wscCmd; // process cmds for (auto& cmd : lstCmds) { if (ProcessSocketCmd(sc, cmd)) { lstDelete.push_back(sc); break; } } delete[] szData; } } // delete closed connections for (auto it = lstDelete.begin(); it != lstDelete.end(); ++it) { closesocket((*it)->csock.s); lstSockets.remove(*it); delete (*it); } lstDelete.clear(); } CATCH_HOOK({}) }
25,442
C++
.cpp
730
30.054795
151
0.594748
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,373
HkIEngineDamage.cpp
TheStarport_FLHook/source/HkIEngineDamage.cpp
#include "Global.hpp" EXPORT uint g_DmgTo = 0; EXPORT uint g_DmgToSpaceId = 0; DamageList g_LastDmgList; bool g_NonGunHitsBase = false; float g_LastHitPts; /************************************************************************************************************** Called when a torp/missile/mine/wasp hits a ship return 0 -> pass on to server.dll return 1 -> suppress **************************************************************************************************************/ FARPROC g_OldGuidedHit; int __stdcall GuidedHit(char* ecx, char* p1, DamageList* dmgList) { auto [rval, skip] = CallPluginsBefore<int>(HookedCall::IEngine__GuidedHit, ecx, p1, dmgList); if (skip) return rval; TRY_HOOK { char* p; memcpy(&p, ecx + 0x10, 4); uint client; memcpy(&client, p + 0xB4, 4); uint spaceId; memcpy(&spaceId, p + 0xB0, 4); g_DmgTo = client; g_DmgToSpaceId = spaceId; if (client) { // a player was hit uint inflictorShip; memcpy(&inflictorShip, p1 + 4, 4); const auto clientInflictor = Hk::Client::GetClientIdByShip(inflictorShip); if (clientInflictor.has_error()) return 0; // hit by npc if (!AllowPlayerDamage(clientInflictor.value(), client)) return 1; if (FLHookConfig::i()->general.changeCruiseDisruptorBehaviour && ((dmgList->get_cause() == DamageCause::CruiseDisrupter || dmgList->get_cause() == DamageCause::UnkDisrupter) && !ClientInfo[client].bCruiseActivated)) { dmgList->set_cause(DamageCause::DummyDisrupter); // change to sth else, so client won't recognize it as a disruptor } } } CATCH_HOOK({}) return 0; } __declspec(naked) void Naked__GuidedHit() { __asm { mov eax, [esp+4] mov edx, [esp+8] push ecx push edx push eax push ecx call GuidedHit pop ecx cmp eax, 1 jnz go_ahead mov edx, [esp] ; suppress add esp, 0Ch jmp edx go_ahead: jmp [g_OldGuidedHit] } } /************************************************************************************************************** Called when ship was damaged however you can't figure out here, which ship is being damaged, that's why i use the g_DmgTo variable... **************************************************************************************************************/ void __stdcall AddDamageEntry( DamageList* dmgList, unsigned short subObjId, float hitPts, enum DamageEntry::SubObjFate fate) { if (CallPluginsBefore(HookedCall::IEngine__AddDamageEntry, dmgList, subObjId, hitPts, fate)) return; // check if we got damaged by a cd with changed behaviour if (dmgList->get_cause() == DamageCause::DummyDisrupter) { // check if player should be protected (f.e. in a docking cut scene) bool unk1 = false; bool unk2 = false; float unk; pub::SpaceObj::GetInvincible(ClientInfo[g_DmgTo].ship, unk1, unk2, unk); // if so, suppress the damage if (unk1 && unk2) return; } if (g_NonGunHitsBase && (dmgList->get_cause() == DamageCause::CruiseDisrupter)) { const float damage = g_LastHitPts - hitPts; hitPts = g_LastHitPts - damage * FLHookConfig::i()->general.torpMissileBaseDamageMultiplier; if (hitPts < 0) hitPts = 0; } if (!dmgList->is_inflictor_a_player()) // npcs always do damage dmgList->add_damage_entry(subObjId, hitPts, fate); else if (g_DmgTo) { // lets see if player should do damage to other player const auto dmgFrom = Hk::Client::GetClientIdByShip(dmgList->get_inflictor_id()); if (dmgFrom.has_value() && AllowPlayerDamage(dmgFrom.value(), g_DmgTo)) dmgList->add_damage_entry(subObjId, hitPts, fate); } else dmgList->add_damage_entry(subObjId, hitPts, fate); TRY_HOOK { g_LastDmgList = *dmgList; // save // check for base kill (when hull health = 0) if (hitPts == 0 && subObjId == 1) { uint type; pub::SpaceObj::GetType(g_DmgToSpaceId, type); const auto clientKiller = Hk::Client::GetClientIdByShip(dmgList->get_inflictor_id()); if (clientKiller.has_value() && type & (OBJ_DOCKING_RING | OBJ_STATION | OBJ_WEAPONS_PLATFORM)) BaseDestroyed(g_DmgToSpaceId, clientKiller.value()); } if (g_DmgTo && subObjId == 1) // only save hits on the hull (subObjId=1) { ClientInfo[g_DmgTo].dmgLast = *dmgList; } } CATCH_HOOK({}) CallPluginsAfter(HookedCall::IEngine__AddDamageEntry, dmgList, subObjId, hitPts, fate); g_DmgTo = 0; g_DmgToSpaceId = 0; } __declspec(naked) void Naked__AddDamageEntry() { __asm { push [esp+0Ch] push [esp+0Ch] push [esp+0Ch] push ecx call AddDamageEntry mov eax, [esp] add esp, 10h jmp eax } } /************************************************************************************************************** Called when ship was damaged **************************************************************************************************************/ FARPROC g_OldDamageHit, g_OldDamageHit2; void __stdcall DamageHit(char* ecx) { CallPluginsBefore(HookedCall::IEngine__DamageHit, ecx); TRY_HOOK { char* p; memcpy(&p, ecx + 0x10, 4); uint client; memcpy(&client, p + 0xB4, 4); uint spaceId; memcpy(&spaceId, p + 0xB0, 4); g_DmgTo = client; g_DmgToSpaceId = spaceId; } CATCH_HOOK({}) } __declspec(naked) void Naked__DamageHit() { __asm { push ecx push ecx call DamageHit pop ecx jmp [g_OldDamageHit] } } __declspec(naked) void Naked__DamageHit2() { __asm { push ecx push ecx call DamageHit pop ecx jmp [g_OldDamageHit2] } } /************************************************************************************************************** Called when ship was damaged **************************************************************************************************************/ bool AllowPlayerDamage(ClientId client, ClientId clientTarget) { auto [rval, skip] = CallPluginsBefore<bool>(HookedCall::IEngine__AllowPlayerDamage, client, clientTarget); if (skip) return rval; const auto* config = FLHookConfig::c(); if (clientTarget) { // anti-dockkill check if (ClientInfo[clientTarget].bSpawnProtected) { if ((Hk::Time::GetUnixMiliseconds() - ClientInfo[clientTarget].tmSpawnTime) <= config->general.antiDockKill) return false; // target is protected else ClientInfo[clientTarget].bSpawnProtected = false; } if (ClientInfo[client].bSpawnProtected) { if ((Hk::Time::GetUnixMiliseconds() - ClientInfo[client].tmSpawnTime) <= config->general.antiDockKill) return false; // target may not shoot else ClientInfo[client].bSpawnProtected = false; } // no-pvp check uint systemId; pub::Player::GetSystem(client, systemId); if (std::ranges::find(config->general.noPVPSystemsHashed, systemId) != config->general.noPVPSystemsHashed.end()) return false; } return true; } /************************************************************************************************************** **************************************************************************************************************/ FARPROC g_OldNonGunWeaponHitsBase; void __stdcall NonGunWeaponHitsBaseBefore(const char* ECX, [[maybe_unused]] const char* p1, const DamageList* dmg) { CSimple* simple; memcpy(&simple, ECX + 0x10, 4); g_LastHitPts = simple->get_hit_pts(); g_NonGunHitsBase = true; } void NonGunWeaponHitsBaseAfter() { g_NonGunHitsBase = false; } ulong g_NonGunWeaponHitsBaseRetAddress; __declspec(naked) void Naked__NonGunWeaponHitsBase() { __asm { mov eax, [esp+4] mov edx, [esp+8] push ecx push edx push eax push ecx call NonGunWeaponHitsBaseBefore pop ecx mov eax, [esp] mov [g_NonGunWeaponHitsBaseRetAddress], eax lea eax, return_here mov [esp], eax jmp [g_OldNonGunWeaponHitsBase] return_here: pushad call NonGunWeaponHitsBaseAfter popad jmp [g_NonGunWeaponHitsBaseRetAddress] } } ///////////////////////////
8,067
C++
.cpp
254
27.972441
179
0.590265
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,374
HkClientServerInterface.cpp
TheStarport_FLHook/source/HkClientServerInterface.cpp
#include "Global.hpp" #include "Features/Mail.hpp" #include "Features/TempBan.hpp" #include <random> void IClientImpl__Startup__Inner(uint, uint) { // load the universe directly before the server becomes internet accessible CoreGlobals::i()->allBases.clear(); Universe::IBase* base = Universe::GetFirstBase(); while (base) { BaseInfo bi; bi.bDestroyed = false; bi.iObjectId = base->lSpaceObjId; char const* szBaseName = ""; __asm { pushad mov ecx, [base] mov eax, [base] mov eax, [eax] call [eax+4] mov [szBaseName], eax popad } bi.scBasename = szBaseName; bi.baseId = CreateID(szBaseName); CoreGlobals::i()->allBases.push_back(bi); pub::System::LoadSystem(base->systemId); base = Universe::GetNextBase(); } } // Doesn't call a Client method, so we need a custom hook bool IClientImpl::DispatchMsgs() { cdpServer->DispatchMsgs(); // calls IServerImpl functions, which also call // IClientImpl functions return true; } namespace IServerImplHook { Timer g_Timers[] = { {ProcessPendingCommands, 50}, {TimerCheckKick, 1000}, {TimerNPCAndF1Check, 50}, {TimerCheckResolveResults, 0}, {TimerTempBanCheck, 15000}, }; void Update__Inner() { static bool firstTime = true; if (firstTime) { FLHookInit(); firstTime = false; } const auto currentTime = Hk::Time::GetUnixMiliseconds(); for (auto& timer : g_Timers) { // This one isn't actually in seconds, but the plugins should be if ((currentTime - timer.lastTime) >= timer.intervalInSeconds) { timer.lastTime = currentTime; timer.func(); } } for (std::shared_ptr<PluginData> plugin : PluginManager::ir()) { if (plugin->timers) { for (auto& timer : *plugin->timers) { if ((currentTime - timer.lastTime) >= (timer.intervalInSeconds * 1000)) { timer.lastTime = currentTime; timer.func(); } } } } auto globals = CoreGlobals::i(); char* data; memcpy(&data, g_FLServerDataPtr + 0x40, 4); memcpy(&globals->serverLoadInMs, data + 0x204, 4); memcpy(&globals->playerCount, data + 0x208, 4); } CInGame g_Admin; const std::unique_ptr<SubmitData> chatData = std::make_unique<SubmitData>(); bool SubmitChat__Inner(CHAT_ID cidFrom, ulong size, void const* rdlReader, CHAT_ID& cidTo, int) { TRY_HOOK { const auto* config = FLHookConfig::i(); // Group join/leave commands are not parsed if (cidTo.iId == SpecialChatIds::GROUP_EVENT) return true; // Anything outside normal bounds is aborted to prevent crashes if (cidTo.iId > SpecialChatIds::GROUP_EVENT || cidTo.iId > SpecialChatIds::PLAYER_MAX && cidTo.iId < SpecialChatIds::SPECIAL_BASE) return false; if (cidFrom.iId == 0) { chatData->characterName = L"CONSOLE"; } else if (Hk::Client::IsValidClientID(cidFrom.iId)) { chatData->characterName = Hk::Client::GetCharacterNameByID(cidFrom.iId).value(); } else { chatData->characterName = L""; } // extract text from rdlReader BinaryRDLReader rdl; std::wstring buffer; buffer.resize(size); uint iRet1; rdl.extract_text_from_buffer((unsigned short*)buffer.data(), buffer.size(), iRet1, (const char*)rdlReader, size); std::erase(buffer, '\0'); // if this is a message in system chat then convert it to local unless // explicitly overriden by the player using /s. if (config->messages.defaultLocalChat && cidTo.iId == SpecialChatIds::SYSTEM) { cidTo.iId = SpecialChatIds::LOCAL; } // fix flserver commands and change chat to id so that event logging is accurate. bool foundCommand = false; if (buffer[0] == '/') { if (UserCmd_Process(cidFrom.iId, buffer)) { if (FLHookConfig::c()->messages.echoCommands) { const std::wstring xml = L"<TRA data=\"" + FLHookConfig::c()->messages.msgStyle.msgEchoStyle + L"\" mask=\"-1\"/><TEXT>" + XMLText(buffer) + L"</TEXT>"; Hk::Message::FMsg(cidFrom.iId, xml); } return false; } if (buffer.length() == 2 || buffer[2] == ' ') { if (buffer[1] == 'g') { foundCommand = true; cidTo.iId = SpecialChatIds::GROUP; } else if (buffer[1] == 's') { foundCommand = true; cidTo.iId = SpecialChatIds::SYSTEM; } else if (buffer[1] == 'l') { foundCommand = true; cidTo.iId = SpecialChatIds::LOCAL; } } } else if (buffer[0] == '.') { const CAccount* acc = Players.FindAccountFromClientID(cidFrom.iId); std::wstring accDirname = Hk::Client::GetAccountDirName(acc); std::string adminFile = CoreGlobals::c()->accPath + wstos(accDirname) + "\\flhookadmin.ini"; WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(adminFile.c_str(), &fd); if (hFind != INVALID_HANDLE_VALUE) { if (FLHookConfig::c()->messages.echoCommands) { const std::wstring XML = L"<TRA data=\"" + FLHookConfig::c()->messages.msgStyle.msgEchoStyle + L"\" mask=\"-1\"/><TEXT>" + XMLText(buffer) + L"</TEXT>"; Hk::Message::FMsg(cidFrom.iId, XML); } FindClose(hFind); g_Admin.ReadRights(adminFile); g_Admin.client = cidFrom.iId; g_Admin.wscAdminName = ToWChar(Players.GetActiveCharacterName(cidFrom.iId)); g_Admin.ExecuteCommandString(buffer.data() + 1); return false; } } std::wstring eventString; eventString.reserve(256); eventString = L"chat"; eventString += L" from="; if (cidFrom.iId == SpecialChatIds::CONSOLE) eventString += L"console"; else { const auto* fromName = ToWChar(Players.GetActiveCharacterName(cidFrom.iId)); if (!fromName) eventString += L"unknown"; else eventString += fromName; } eventString += L" id="; eventString += std::to_wstring(cidFrom.iId); eventString += L" type="; if (cidTo.iId == SpecialChatIds::UNIVERSE) eventString += L"universe"; else if (cidTo.iId == SpecialChatIds::GROUP) { eventString += L"group"; eventString += L" grpidto="; eventString += std::to_wstring(Players.GetGroupID(cidFrom.iId)); } else if (cidTo.iId == SpecialChatIds::SYSTEM) eventString += L"system"; else if (cidTo.iId == SpecialChatIds::LOCAL) eventString += L"local"; else { eventString += L"player"; eventString += L" to="; if (cidTo.iId == SpecialChatIds::CONSOLE) eventString += L"console"; else { const auto* toName = ToWChar(Players.GetActiveCharacterName(cidTo.iId)); if (!toName) eventString += L"unknown"; else eventString += toName; } eventString += L" idto="; eventString += std::to_wstring(cidTo.iId); } eventString += L" text="; eventString += buffer; ProcessEvent(L"{}", eventString.c_str()); // check if chat should be suppressed for in-built command prefixes if (buffer[0] == L'/' || buffer[0] == L'.') { if (FLHookConfig::c()->messages.echoCommands) { const std::wstring XML = L"<TRA data=\"" + FLHookConfig::c()->messages.msgStyle.msgEchoStyle + L"\" mask=\"-1\"/><TEXT>" + XMLText(buffer) + L"</TEXT>"; Hk::Message::FMsg(cidFrom.iId, XML); } if (config->messages.suppressInvalidCommands && !foundCommand) { return false; } } // Check if any other custom prefixes have been added if (!config->general.chatSuppressList.empty()) { auto lcBuffer = ToLower(buffer); for (const auto& chat : config->general.chatSuppressList) { if (lcBuffer.rfind(chat, 0) == 0) return false; } } } CATCH_HOOK({}) return true; } void PlayerLaunch__Inner(uint shipId, ClientId client) { TRY_HOOK { ClientInfo[client].ship = shipId; ClientInfo[client].bCruiseActivated = false; ClientInfo[client].bThrusterActivated = false; ClientInfo[client].bEngineKilled = false; ClientInfo[client].bTradelane = false; // adjust cash, this is necessary when cash was added while use was in // charmenu/had other char selected std::wstring charName = ToLower(ToWChar(Players.GetActiveCharacterName(client))); for (const auto& i : ClientInfo[client].lstMoneyFix) { if (i.character == charName) { Hk::Player::AddCash(charName, i.uAmount); ClientInfo[client].lstMoneyFix.remove(i); break; } } } CATCH_HOOK({}) } void PlayerLaunch__InnerAfter([[maybe_unused]] uint shipId, ClientId client) { TRY_HOOK { if (!ClientInfo[client].iLastExitedBaseId) { ClientInfo[client].iLastExitedBaseId = 1; // event ProcessEvent(L"spawn char={} id={} system={}", ToWChar(Players.GetActiveCharacterName(client)), client, Hk::Client::GetPlayerSystem(client).value().c_str()); } } CATCH_HOOK({}) } void SPMunitionCollision__Inner(const SSPMunitionCollisionInfo& mci, uint) { TRY_HOOK { const auto isClient = Hk::Client::GetClientIdByShip(mci.dwTargetShip); if (isClient.has_value()) CoreGlobals::i()->damageToClientId = isClient.value(); } CATCH_HOOK({}) } bool SPObjUpdate__Inner(const SSPObjUpdateInfo& ui, ClientId client) { // NAN check if (isnan(ui.vPos.x) || isnan(ui.vPos.y) || isnan(ui.vPos.z) || isnan(ui.vDir.w) || isnan(ui.vDir.x) || isnan(ui.vDir.y) || isnan(ui.vDir.z) || isnan(ui.fThrottle)) { AddLog(LogType::Normal, LogLevel::Err, std::format("NAN found in SPObjUpdate for id={}", client)); Hk::Player::Kick(client); return false; } // Denormalized check if (float n = ui.vDir.w * ui.vDir.w + ui.vDir.x * ui.vDir.x + ui.vDir.y * ui.vDir.y + ui.vDir.z * ui.vDir.z; n > 1.21f || n < 0.81f) { AddLog(LogType::Normal, LogLevel::Err, std::format("Non-normalized quaternion found in SPObjUpdate for id={}", client)); Hk::Player::Kick(client); return false; } // Far check if (abs(ui.vPos.x) > 1e7f || abs(ui.vPos.y) > 1e7f || abs(ui.vPos.z) > 1e7f) { AddLog(LogType::Normal, LogLevel::Err, std::format("Ship position out of bounds in SPObjUpdate for id={}", client)); Hk::Player::Kick(client); return false; } return true; } void LaunchComplete__Inner(uint, uint shipId) {TRY_HOOK {ClientId client = Hk::Client::GetClientIdByShip(shipId).value(); if (client) { ClientInfo[client].tmSpawnTime = Hk::Time::GetUnixMiliseconds(); // save for anti-dockkill // is there spawnprotection? if (FLHookConfig::i()->general.antiDockKill > 0) ClientInfo[client].bSpawnProtected = true; else ClientInfo[client].bSpawnProtected = false; } // event ProcessEvent(L"launch char={} id={} base={} system={}", ToWChar(Players.GetActiveCharacterName(client)), client, Hk::Client::GetBaseNickByID(ClientInfo[client].iLastExitedBaseId).value().c_str(), Hk::Client::GetPlayerSystem(client).value().c_str()); } // namespace IServerImplHook CATCH_HOOK({}) } std::wstring g_CharBefore; bool CharacterSelect__Inner(const CHARACTER_ID& cid, ClientId client) { try { const wchar_t* charName = ToWChar(Players.GetActiveCharacterName(client)); g_CharBefore = charName ? ToWChar(Players.GetActiveCharacterName(client)) : L""; ClientInfo[client].iLastExitedBaseId = 0; ClientInfo[client].iTradePartner = 0; } catch (...) { AddKickLog(client, "Corrupt character file?"); Hk::Player::Kick(client); return false; } Hk::Ini::CharacterSelect(cid, client); return true; } void CharacterSelect__InnerAfter(const CHARACTER_ID& cId, unsigned int client) { TRY_HOOK { std::wstring charName = ToWChar(Players.GetActiveCharacterName(client)); if (g_CharBefore.compare(charName) != 0) { LoadUserCharSettings(client); if (FLHookConfig::i()->userCommands.userCmdHelp) PrintUserCmdText(client, L"To get a list of available commands, type " L"\"/help\" in chat."); int iHold; auto lstCargo = Hk::Player::EnumCargo(client, iHold); if (lstCargo.has_error()) { Hk::Player::Kick(client); return; } for (const auto& cargo : lstCargo.value()) { if (cargo.iCount < 0) { AddCheaterLog(charName, "Negative good-count, likely to have cheated in the past"); Hk::Message::MsgU(std::format(L"Possible cheating detected ({})", charName.c_str())); Hk::Player::Ban(client, true); Hk::Player::Kick(client); return; } } // event CAccount* acc = Players.FindAccountFromClientID(client); std::wstring dir = Hk::Client::GetAccountDirName(acc); auto pi = Hk::Admin::GetPlayerInfo(client, false); ProcessEvent(L"login char={} accountdirname={} id={} ip={}", charName.c_str(), dir.c_str(), client, pi.value().wscIP.c_str()); MailManager::i()->SendMailNotification(client); // Assign their random formation id. // Numbers are between 0-20 (inclusive) // Formations are between 1-29 (inclusive) std::random_device dev; std::mt19937 rng(dev()); std::uniform_int_distribution<std::mt19937::result_type> distNum(1, 20); const auto* conf = FLHookConfig::c(); std::uniform_int_distribution<std::mt19937::result_type> distForm(0, conf->callsign.allowedFormations.size() - 1); auto& ci = ClientInfo[client]; ci.formationNumber1 = distNum(rng); ci.formationNumber2 = distNum(rng); ci.formationTag = conf->callsign.allowedFormations[distForm(rng)]; } } CATCH_HOOK({}) } void BaseEnter__Inner(uint baseId, ClientId client) { } void BaseEnter__InnerAfter(uint baseId, ClientId client) { TRY_HOOK { // adjust cash, this is necessary when cash was added while use was in // charmenu/had other char selected std::wstring charName = ToLower(ToWChar(Players.GetActiveCharacterName(client))); for (const auto& i : ClientInfo[client].lstMoneyFix) { if (i.character == charName) { Hk::Player::AddCash(charName, i.uAmount); ClientInfo[client].lstMoneyFix.remove(i); break; } } // anti base-idle ClientInfo[client].iBaseEnterTime = static_cast<uint>(time(0)); // event ProcessEvent(L"baseenter char={} id={} base={} system={}", ToWChar(Players.GetActiveCharacterName(client)), client, Hk::Client::GetBaseNickByID(baseId).value().c_str(), Hk::Client::GetPlayerSystem(client).value().c_str()); // print to log if the char has too much money if (const auto value = Hk::Player::GetShipValue((const wchar_t*)Players.GetActiveCharacterName(client)); value.has_value() && value.value() > 2100000000) { std::wstring charname = (const wchar_t*)Players.GetActiveCharacterName(client); AddLog(LogType::Normal, LogLevel::Err, std::format("Possible corrupt ship charname={} asset_value={}", wstos(charname), value.value())); } } CATCH_HOOK({}) } void BaseExit__Inner(uint baseId, ClientId client) { TRY_HOOK { ClientInfo[client].iBaseEnterTime = 0; ClientInfo[client].iLastExitedBaseId = baseId; } CATCH_HOOK({}) } void BaseExit__InnerAfter(uint baseId, ClientId client) { TRY_HOOK { ProcessEvent(L"baseexit char={} id={} base={} system={}", ToWChar(Players.GetActiveCharacterName(client)), client, Hk::Client::GetBaseNickByID(baseId).value().c_str(), Hk::Client::GetPlayerSystem(client).value().c_str()); } CATCH_HOOK({}) } void TerminateTrade__InnerAfter(ClientId client, int accepted) { TRY_HOOK { if (accepted) { // save both chars to prevent cheating in case of server crash Hk::Player::SaveChar(client); if (ClientInfo[client].iTradePartner) Hk::Player::SaveChar(ClientInfo[client].iTradePartner); } if (ClientInfo[client].iTradePartner) ClientInfo[ClientInfo[client].iTradePartner].iTradePartner = 0; ClientInfo[client].iTradePartner = 0; } CATCH_HOOK({}) } void InitiateTrade__Inner(ClientId client1, ClientId client2) { if (client1 <= MaxClientId && client2 <= MaxClientId) { ClientInfo[client1].iTradePartner = client2; ClientInfo[client2].iTradePartner = client1; } } void ActivateEquip__Inner(ClientId client, const XActivateEquip& aq) { TRY_HOOK { int _; const auto lstCargo = Hk::Player::EnumCargo(client, _); for (auto& cargo : lstCargo.value()) { if (cargo.iId == aq.sId) { Archetype::Equipment* eq = Archetype::GetEquipment(cargo.iArchId); EquipmentType eqType = Hk::Client::GetEqType(eq); if (eqType == ET_ENGINE) { ClientInfo[client].bEngineKilled = !aq.bActivate; if (!aq.bActivate) ClientInfo[client].bCruiseActivated = false; // enginekill enabled } } } } CATCH_HOOK({}) } void ActivateCruise__Inner(ClientId client, const XActivateCruise& ac) { TRY_HOOK { ClientInfo[client].bCruiseActivated = ac.bActivate; } CATCH_HOOK({}) } void ActivateThrusters__Inner(ClientId client, const XActivateThrusters& at) { TRY_HOOK { ClientInfo[client].bThrusterActivated = at.bActivate; } CATCH_HOOK({}) } bool GFGoodSell__Inner(const SGFGoodSellInfo& gsi, ClientId client) { TRY_HOOK { // anti-cheat check int _; const auto lstCargo = Hk::Player::EnumCargo(client, _); bool legalSell = false; for (const auto& cargo : lstCargo.value()) { if (cargo.iArchId == gsi.iArchId) { legalSell = true; if (abs(gsi.iCount) > cargo.iCount) { const auto* charName = ToWChar(Players.GetActiveCharacterName(client)); AddCheaterLog(charName, std::format("Sold more good than possible item={} count={}", gsi.iArchId, gsi.iCount)); Hk::Message::MsgU(std::format(L"Possible cheating detected ({})", charName)); Hk::Player::Ban(client, true); Hk::Player::Kick(client); return false; } break; } } if (!legalSell) { const auto* charName = ToWChar(Players.GetActiveCharacterName(client)); AddCheaterLog(charName, std::format("Sold good player does not have (buggy test), item={}", gsi.iArchId)); return false; } } CATCH_HOOK({ AddLog(LogType::Normal, LogLevel::Err, std::format("Exception in {} (client={} ({}))", __FUNCTION__, client, wstos(Hk::Client::GetCharacterNameByID(client).value()))); }) return true; } bool CharacterInfoReq__Inner(ClientId client, bool) { TRY_HOOK { if (!ClientInfo[client].bCharSelected) ClientInfo[client].bCharSelected = true; else { // pushed f1 uint shipId = 0; pub::Player::GetShip(client, shipId); if (shipId) { // in space ClientInfo[client].tmF1Time = Hk::Time::GetUnixMiliseconds() + FLHookConfig::i()->general.antiF1; return false; } } } CATCH_HOOK({}) return true; } bool CharacterInfoReq__Catch(ClientId client, bool) { AddKickLog(client, "Corrupt charfile?"); Hk::Player::Kick(client); return false; } bool OnConnect__Inner(ClientId client) { TRY_HOOK { // If Id is too high due to disconnect buffer time then manually drop // the connection. if (client > MaxClientId) { AddLog(LogType::Normal, LogLevel::Warn, std::format("INFO: Blocking connect in {} due to invalid id, id={}", __FUNCTION__, client)); CDPClientProxy* cdpClient = clientProxyArray[client - 1]; if (!cdpClient) return false; cdpClient->Disconnect(); return false; } // If this client is in the anti-F1 timeout then force the disconnect. if (ClientInfo[client].tmF1TimeDisconnect > Hk::Time::GetUnixMiliseconds()) { // manual disconnect CDPClientProxy* cdpClient = clientProxyArray[client - 1]; if (!cdpClient) return false; cdpClient->Disconnect(); return false; } ClientInfo[client].iConnects++; ClearClientInfo(client); } CATCH_HOOK({}) return true; } void OnConnect__InnerAfter(ClientId client) { TRY_HOOK { // event std::wstring ip = Hk::Admin::GetPlayerIP(client); ProcessEvent(L"connect id={} ip={}", client, ip.c_str()); } CATCH_HOOK({}) } void DisConnect__Inner(ClientId client, EFLConnection) { if (client <= MaxClientId && client > 0 && !ClientInfo[client].bDisconnected) { ClientInfo[client].bDisconnected = true; ClientInfo[client].lstMoneyFix.clear(); ClientInfo[client].iTradePartner = 0; const auto* charName = ToWChar(Players.GetActiveCharacterName(client)); ProcessEvent(L"disconnect char={} id={}", charName, client); } } void JumpInComplete__InnerAfter(uint systemId, uint shipId) { TRY_HOOK { const auto client = Hk::Client::GetClientIdByShip(shipId); if (client.has_error()) return; // event ProcessEvent(L"jumpin char={} id={} system={}", ToWChar(Players.GetActiveCharacterName(client.value())), client, Hk::Client::GetSystemNickByID(systemId).value().c_str()); } CATCH_HOOK({}) } void SystemSwitchOutComplete__InnerAfter(uint, ClientId client) { TRY_HOOK { const auto system = Hk::Client::GetPlayerSystem(client); ProcessEvent(L"switchout char={} id={} system={}", ToWChar(Players.GetActiveCharacterName(client)), client, system.value().c_str()); } CATCH_HOOK({}) } bool Login__InnerBefore(const SLoginInfo& li, ClientId client) { // The startup cache disables reading of the banned file. Check this manually on // login and boot the player if they are banned. CAccount* acc = Players.FindAccountFromClientID(client); if (acc) { std::wstring dir = Hk::Client::GetAccountDirName(acc); char szDataPath[MAX_PATH]; GetUserDataPath(szDataPath); std::string path = std::string(szDataPath) + "\\Accts\\MultiPlayer\\" + wstos(dir) + "\\banned"; FILE* file = fopen(path.c_str(), "r"); if (file) { fclose(file); // Ban the player st6::wstring flStr((ushort*)acc->wszAccId); Players.BanAccount(flStr, true); // Kick them acc->ForceLogout(); return false; } } return true; } bool Login__InnerAfter(const SLoginInfo& li, ClientId client) { TRY_HOOK { if (client > MaxClientId) return false; // DisconnectDelay bug if (!Hk::Client::IsValidClientID(client)) return false; // player was kicked // Kick the player if the account Id doesn't exist. This is caused // by a duplicate log on. CAccount* acc = Players.FindAccountFromClientID(client); if (acc && !acc->wszAccId) { acc->ForceLogout(); return false; } // check for ip ban auto ip = Hk::Admin::GetPlayerIP(client); for (const auto& ban : FLHookConfig::i()->bans.banWildcardsAndIPs) { if (Wildcard::Fit(wstos(ban).c_str(), wstos(ip).c_str())) { AddKickLog(client, wstos(std::format(L"IP/Hostname ban({} matches {})", ip.c_str(), ban.c_str()))); if (FLHookConfig::i()->bans.banAccountOnMatch) Hk::Player::Ban(client, true); Hk::Player::Kick(client); } } // resolve RESOLVE_IP rip = {client, ClientInfo[client].iConnects, ip}; EnterCriticalSection(&csIPResolve); g_lstResolveIPs.push_back(rip); LeaveCriticalSection(&csIPResolve); // count players PlayerData* playerData = nullptr; uint playerCount = 0; while ((playerData = Players.traverse_active(playerData))) playerCount++; if (playerCount > (Players.GetMaxPlayerCount() - FLHookConfig::i()->general.reservedSlots)) { // check if player has a reserved slot std::wstring dir = Hk::Client::GetAccountDirName(acc); std::string userFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; bool reserved = IniGetB(userFile, "Settings", "ReservedSlot", false); if (!reserved) { Hk::Player::Kick(client); return false; } } LoadUserSettings(client); AddConnectLog(client, wstos(ip)); } CATCH_HOOK({ CAccount* acc = Players.FindAccountFromClientID(client); if (acc) acc->ForceLogout(); return false; }) return true; } void GoTradelane__Inner(ClientId client, const XGoTradelane& gtl) { if (client <= MaxClientId && client > 0) ClientInfo[client].bTradelane = true; } bool GoTradelane__Catch(ClientId client, const XGoTradelane& gtl) { uint system; pub::Player::GetSystem(client, system); AddLog(LogType::Normal, LogLevel::Err, wstos(std::format(L"Exception in IServerImpl::GoTradelane charname={} sys=0x{:08X} arch=0x{:08X} arch2=0x{:08X}", Hk::Client::GetCharacterNameByID(client).value(), system, gtl.iTradelaneSpaceObj1, gtl.iTradelaneSpaceObj2))); return true; } void StopTradelane__Inner(ClientId client, uint, uint, uint) { if (client <= MaxClientId && client > 0) ClientInfo[client].bTradelane = false; } void Shutdown__InnerAfter() { FLHookShutdown(); } // The maximum number of players we can support is MaxClientId // Add one to the maximum number to allow renames const int g_MaxPlayers = MaxClientId + 1; void Startup__Inner(const SStartupInfo& si) { FLHookInit_Pre(); // Startup the server with this number of players. char* address = (reinterpret_cast<char*>(hModServer) + ADDR_SRV_PLAYERDBMAXPLAYERSPATCH); char nop[] = {'\x90'}; char movECX[] = {'\xB9'}; WriteProcMem(address, movECX, sizeof(movECX)); WriteProcMem(address + 1, &g_MaxPlayers, sizeof(g_MaxPlayers)); WriteProcMem(address + 5, nop, sizeof(nop)); StartupCache::Init(); } void Startup__InnerAfter(const SStartupInfo& si) { // Patch to set maximum number of players to connect. This is normally // less than MaxClientId char* address = (reinterpret_cast<char*>(hModServer) + ADDR_SRV_PLAYERDBMAXPLAYERS); WriteProcMem(address, reinterpret_cast<const void*>(&si.iMaxPlayers), sizeof(g_MaxPlayers)); // read base market data from ini LoadBaseMarket(); // Clean up any mail to chars that no longer exist MailManager::i()->CleanUpOldMail(); StartupCache::Done(); Console::ConInfo("FLHook Ready"); CoreGlobals::i()->flhookReady = true; } } bool IClientImpl::Send_FLPACKET_COMMON_FIREWEAPON(ClientId client, XFireWeaponInfo& fwi) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_FIREWEAPON(\n\tClientId client = {}\n\tXFireWeaponInfo& fwi = {}\n)", client, ToLogString(fwi)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_COMMON_FIREWEAPON, client, fwi); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_FIREWEAPON(client, fwi); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_COMMON_FIREWEAPON, client, fwi); return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_ACTIVATEEQUIP(ClientId client, XActivateEquip& aq) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_ACTIVATEEQUIP(\n\tClientId client = {}\n\tXActivateEquip& aq = {}\n)", client, ToLogString(aq)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATEEQUIP, client, aq); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_ACTIVATEEQUIP(client, aq); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATEEQUIP, client, aq); return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_ACTIVATECRUISE(ClientId client, XActivateCruise& aq) { AddLog(LogType::Normal, LogLevel::Debug, wstos( std::format(L"IClientImpl::Send_FLPACKET_COMMON_ACTIVATECRUISE(\n\tClientId client = {}\n\tXActivateCruise& aq = {}\n)", client, ToLogString(aq)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATECRUISE, client, aq); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_ACTIVATECRUISE(client, aq); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATECRUISE, client, aq); return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_ACTIVATETHRUSTERS(ClientId client, XActivateThrusters& aq) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_COMMON_ACTIVATETHRUSTERS(\n\tClientId client = {}\n\tXActivateThrusters& aq = {}\n)", client, ToLogString(aq)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATETHRUSTERS, client, aq); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_ACTIVATETHRUSTERS(client, aq); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATETHRUSTERS, client, aq); return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_SETTARGET(ClientId client, XSetTarget& st) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_SETTARGET(\n\tClientId client = {}\n\tXSetTarget& st = {}\n)", client, ToLogString(st)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_SETTARGET(client, st); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_6(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_6(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_6(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_COMMON_GOTRADELANE(ClientId client, XGoTradelane& tl) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_GOTRADELANE(\n\tClientId client = {}\n\tXGoTradelane& tl = {}\n)", client, ToLogString(tl)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_GOTRADELANE(client, tl); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_STOPTRADELANE(ClientId client, uint shipId, uint archTradelane1, uint archTradelane2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_STOPTRADELANE(\n\tClientId client = {}\n\tuint shipId = {}\n\tuint archTradelane1 = {}\n\tuint " L"archTradelane2 = {}\n)", client, shipId, archTradelane1, archTradelane2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_STOPTRADELANE(client, shipId, archTradelane1, archTradelane2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_JETTISONCARGO(ClientId client, XJettisonCargo& jc) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_JETTISONCARGO(\n\tClientId client = {}\n\tXJettisonCargo& jc = {}\n)", client, ToLogString(jc)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_JETTISONCARGO(client, jc); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::SendPacket(ClientId client, void* _genArg1) { bool retVal; CALL_CLIENT_PREAMBLE { retVal = SendPacket(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Startup(uint _genArg1, uint _genArg2) { IClientImpl__Startup__Inner(_genArg1, _genArg2); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Startup(_genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::nullsub(uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::nullsub(\n\tuint _genArg1 = {}\n)", _genArg1)); CALL_CLIENT_PREAMBLE { nullsub(_genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_LOGINRESPONSE(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_LOGINRESPONSE(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_LOGINRESPONSE(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CHARACTERINFO(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_CHARACTERINFO(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CHARACTERINFO(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CHARSELECTVERIFIED(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_CHARSELECTVERIFIED(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CHARSELECTVERIFIED(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::Shutdown() { CALL_CLIENT_PREAMBLE { Shutdown(); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::CDPClientProxy__Disconnect(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::CDPClientProxy__Disconnect(\n\tClientId client = {}\n)", client)); bool retVal; CALL_CLIENT_PREAMBLE { retVal = CDPClientProxy__Disconnect(client); } CALL_CLIENT_POSTAMBLE; return retVal; } uint IClientImpl::CDPClientProxy__GetSendQSize(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::CDPClientProxy__GetSendQSize(\n\tClientId client = {}\n)", client)); uint retVal; CALL_CLIENT_PREAMBLE { retVal = CDPClientProxy__GetSendQSize(client); } CALL_CLIENT_POSTAMBLE; return retVal; } uint IClientImpl::CDPClientProxy__GetSendQBytes(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::CDPClientProxy__GetSendQBytes(\n\tClientId client = {}\n)", client)); uint retVal; CALL_CLIENT_PREAMBLE { retVal = CDPClientProxy__GetSendQBytes(client); } CALL_CLIENT_POSTAMBLE; return retVal; } double IClientImpl::CDPClientProxy__GetLinkSaturation(ClientId client) { auto [retVal, skip] = CallPluginsBefore<double>(HookedCall::IClientImpl__CDPClientProxy__GetLinkSaturation, client); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = CDPClientProxy__GetLinkSaturation(client); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__CDPClientProxy__GetLinkSaturation, client); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SETSHIPARCH(ClientId client, uint shipArch) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SETSHIPARCH(\n\tClientId client = {}\n\tuint shipArch = {}\n)", client, shipArch))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETSHIPARCH, client, shipArch); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETSHIPARCH(client, shipArch); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETSHIPARCH, client, shipArch); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SETHULLSTATUS(ClientId client, float status) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SETHULLSTATUS(\n\tClientId client = {}\n\tfloat status = {}\n)", client, status))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETHULLSTATUS, client, status); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETHULLSTATUS(client, status); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETHULLSTATUS, client, status); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SETCOLLISIONGROUPS(ClientId client, st6::list<XCollision>& collisionGroupList) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SETCOLLISIONGROUPS(\n\tClientId client = {}\n\tst6::list<XCollisionGroup>& collisionGroupList = {}\n)", client, ToLogString(collisionGroupList)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETCOLLISIONGROUPS, client, collisionGroupList); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETCOLLISIONGROUPS(client, collisionGroupList); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETCOLLISIONGROUPS, client, collisionGroupList); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SETEQUIPMENT(ClientId client, st6::vector<EquipDesc>& equipmentVector) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SETEQUIPMENT(\n\tClientId client = {}\n\tst6::vector<EquipDesc>& equipmentVector = {}\n)", client, ToLogString(equipmentVector)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETEQUIPMENT, client, equipmentVector); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETEQUIPMENT(client, equipmentVector); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETEQUIPMENT, client, equipmentVector); return retVal; } void IClientImpl::unknown_26(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_26(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_26(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SETADDITEM(ClientId client, FLPACKET_UNKNOWN& _genArg1, FLPACKET_UNKNOWN& _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_SETADDITEM(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n\tFLPACKET_UNKNOWN& _genArg2 = {}\n)", client, ToLogString(_genArg1), ToLogString(_genArg2)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETADDITEM, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETADDITEM(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETADDITEM, client, _genArg1, _genArg2); return retVal; } void IClientImpl::unknown_28(ClientId client, uint _genArg1, uint _genArg2, uint _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_28(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n\tuint _genArg3 = {}\n)", client, _genArg1, _genArg2, _genArg3))); CALL_CLIENT_PREAMBLE { unknown_28(client, _genArg1, _genArg2, _genArg3); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SETSTARTROOM(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SETSTARTROOM(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETSTARTROOM, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETSTARTROOM(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETSTARTROOM, client, _genArg1, _genArg2); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFDESTROYCHARACTER(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFDESTROYCHARACTER(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFDESTROYCHARACTER(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFUPDATECHAR(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFUPDATECHAR(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFUPDATECHAR(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETECHARLIST(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETECHARLIST(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFCOMPLETECHARLIST(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFSCRIPTBEHAVIOR(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFSCRIPTBEHAVIOR(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFSCRIPTBEHAVIOR(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFDESTROYSCRIPTBEHAVIOR(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFDESTROYSCRIPTBEHAVIOR(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFDESTROYSCRIPTBEHAVIOR(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETESCRIPTBEHAVIORLIST(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETESCRIPTBEHAVIORLIST(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFCOMPLETESCRIPTBEHAVIORLIST(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_36(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_36(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_36(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_37(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_37(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_37(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETEAMBIENTSCRIPTLIST(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos( std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETEAMBIENTSCRIPTLIST(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFCOMPLETEAMBIENTSCRIPTLIST(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFDESTROYMISSIONCOMPUTER(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFDESTROYMISSIONCOMPUTER(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFDESTROYMISSIONCOMPUTER(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFUPDATEMISSIONCOMPUTER(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFUPDATEMISSIONCOMPUTER(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFUPDATEMISSIONCOMPUTER(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETEMISSIONCOMPUTERLIST(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETEMISSIONCOMPUTERLIST(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFCOMPLETEMISSIONCOMPUTERLIST(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFMISSIONVENDORACCEPTANCE(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFMISSIONVENDORACCEPTANCE(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFMISSIONVENDORACCEPTANCE(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFMISSIONVENDORWHYEMPTY(ClientId client, uint reason) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFMISSIONVENDORWHYEMPTY(\n\tClientId client = {}\n\tuint reason = {}\n)", client, reason))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFMISSIONVENDORWHYEMPTY(client, reason); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_44(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_44(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_44(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_GFUPDATENEWSBROADCAST(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFUPDATENEWSBROADCAST(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFUPDATENEWSBROADCAST(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETENEWSBROADCASTLIST(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_GFCOMPLETENEWSBROADCASTLIST(\n\tClientId client = {}\n\tuint _genArg1 = " L"{}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_GFCOMPLETENEWSBROADCASTLIST(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CREATESOLAR(ClientId client, FLPACKET_CREATESOLAR& solar) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_CREATESOLAR(\n\tClientId client = {}\n\tFLPACKET_CREATESOLAR& solar = " L"{}\n)", client, ToLogString(solar)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATESOLAR, client, solar); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CREATESOLAR(client, solar); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATESOLAR, client, solar); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CREATESHIP(ClientId client, FLPACKET_CREATESHIP& ship) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_CREATESHIP(\n\tClientId client = {}\n\tFLPACKET_CREATESHIP& ship = {}\n)", client, ToLogString(ship)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATESHIP, client, ship); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CREATESHIP(client, ship); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATESHIP, client, ship); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CREATELOOT(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_CREATELOOT(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATELOOT, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CREATELOOT(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATELOOT, client, _genArg1); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CREATEMINE(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_CREATEMINE(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATEMINE, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CREATEMINE(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATEMINE, client, _genArg1); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CREATEGUIDED(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_CREATEGUIDED(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATEGUIDED, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CREATEGUIDED(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATEGUIDED, client, _genArg1); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_CREATECOUNTER(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_CREATECOUNTER(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATECOUNTER, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_CREATECOUNTER(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATECOUNTER, client, _genArg1); return retVal; } void IClientImpl::unknown_53(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_53(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_53(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_54(ClientId client, uint _genArg1, uint _genArg2, uint _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_54(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n\tuint _genArg3 = {}\n)", client, _genArg1, _genArg2, _genArg3))); CALL_CLIENT_PREAMBLE { unknown_54(client, _genArg1, _genArg2, _genArg3); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_COMMON_UPDATEOBJECT(ClientId client, SSPObjUpdateInfo& update) { auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_COMMON_UPDATEOBJECT, client, update); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_UPDATEOBJECT(client, update); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_COMMON_UPDATEOBJECT, client, update); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_DESTROYOBJECT(ClientId client, FLPACKET_DESTROYOBJECT& destroy) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_DESTROYOBJECT(\n\tClientId client = {}\n\tFLPACKET_DESTROYOBJECT& destroy = {}\n)", client, ToLogString(destroy)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_DESTROYOBJECT, client, destroy); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_DESTROYOBJECT(client, destroy); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_DESTROYOBJECT, client, destroy); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_ACTIVATEOBJECT(ClientId client, XActivateEquip& aq) { AddLog(LogType::Normal, LogLevel::Debug, wstos( std::format(L"IClientImpl::Send_FLPACKET_SERVER_ACTIVATEOBJECT(\n\tClientId client = {}\n\tXActivateEquip& aq = {}\n)", client, ToLogString(aq)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_ACTIVATEOBJECT, client, aq); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_ACTIVATEOBJECT(client, aq); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_ACTIVATEOBJECT, client, aq); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SYSTEM_SWITCH_OUT(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SYSTEM_SWITCH_OUT(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SYSTEM_SWITCH_OUT(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SYSTEM_SWITCH_IN(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SYSTEM_SWITCH_IN(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SYSTEM_SWITCH_IN(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_LAND(ClientId client, FLPACKET_LAND& land) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_LAND(\n\tClientId client = {}\n\tFLPACKET_LAND& land = {}\n)", client, ToLogString(land)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_LAND(client, land); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_LAUNCH(ClientId client, FLPACKET_LAUNCH& launch) { AddLog(LogType::Normal, LogLevel::Debug, wstos( std::format(L"IClientImpl::Send_FLPACKET_SERVER_LAUNCH(\n\tClientId client = {}\n\tFLPACKET_LAUNCH& launch = {}\n)", client, ToLogString(launch)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_LAUNCH, client, launch); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_LAUNCH(client, launch); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_LAUNCH, client, launch); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP(ClientId client, bool response, uint shipId) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP(\n\tClientId client = {}\n\tbool response = {}\n\tuint shipId = {}\n)", client, response, shipId))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP, client, response, shipId); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP(client, response, shipId); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP, client, response, shipId); return retVal; } void IClientImpl::unknown_63(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_63(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_63(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_DAMAGEOBJECT(ClientId client, uint objId, DamageList& dmgList) { bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_DAMAGEOBJECT(client, objId, dmgList); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_ITEMTRACTORED(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_ITEMTRACTORED(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_ITEMTRACTORED(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_USE_ITEM(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::Send_FLPACKET_SERVER_USE_ITEM(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_USE_ITEM, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_USE_ITEM(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_USE_ITEM, client, _genArg1); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_SETREPUTATION(ClientId client, FLPACKET_SETREPUTATION& rep) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_SETREPUTATION(\n\tClientId client = {}\n\tFLPACKET_SETREPUTATION& rep = {}\n)", client, ToLogString(rep)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETREPUTATION, client, rep); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETREPUTATION(client, rep); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETREPUTATION, client, rep); return retVal; } void IClientImpl::unknown_68(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_68(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_68(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SENDCOMM(ClientId client, uint _genArg1, uint _genArg2, uint _genArg3, uint _genArg4, uint _genArg5, uint _genArg6, uint _genArg7, uint _genArg8, uint _genArg9, uint _genArg10, uint _genArg11, uint _genArg12, uint _genArg13, uint _genArg14, uint _genArg15, uint _genArg16, uint _genArg17, uint _genArg18, uint _genArg19, uint _genArg20, uint _genArg21, uint _genArg22) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SENDCOMM(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = " L"{}\n\tuint _genArg3 = {}\n\tuint _genArg4 = {}\n\tuint _genArg5 = {}\n\tuint _genArg6 = {}\n\tuint _genArg7 " L"= {}\n\tuint _genArg8 = {}\n\tuint _genArg9 = {}\n\tuint _genArg10 = {}\n\tuint _genArg11 = {}\n\tuint " L"_genArg12 = {}\n\tuint _genArg13 = {}\n\tuint _genArg14 = {}\n\tuint _genArg15 = {}\n\tuint _genArg16 = " L"{}\n\tuint _genArg17 = {}\n\tuint _genArg18 = {}\n\tuint _genArg19 = {}\n\tuint _genArg20 = {}\n\tuint " L"_genArg21 = {}\n\tuint _genArg22 = {}\n)", client, _genArg1, _genArg2, _genArg3, _genArg4, _genArg5, _genArg6, _genArg7, _genArg8, _genArg9, _genArg10, _genArg11, _genArg12, _genArg13, _genArg14, _genArg15, _genArg16, _genArg17, _genArg18, _genArg19, _genArg20, _genArg21, _genArg22))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SENDCOMM, client, _genArg1, _genArg2, _genArg3, _genArg4, _genArg5, _genArg6, _genArg7, _genArg8, _genArg9, _genArg10, _genArg11, _genArg12, _genArg13, _genArg14, _genArg15, _genArg16, _genArg17, _genArg18, _genArg19, _genArg20, _genArg21, _genArg22); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SENDCOMM(client, _genArg1, _genArg2, _genArg3, _genArg4, _genArg5, _genArg6, _genArg7, _genArg8, _genArg9, _genArg10, _genArg11, _genArg12, _genArg13, _genArg14, _genArg15, _genArg16, _genArg17, _genArg18, _genArg19, _genArg20, _genArg21, _genArg22); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SENDCOMM, client, _genArg1, _genArg2, _genArg3, _genArg4, _genArg5, _genArg6, _genArg7, _genArg8, _genArg9, _genArg10, _genArg11, _genArg12, _genArg13, _genArg14, _genArg15, _genArg16, _genArg17, _genArg18, _genArg19, _genArg20, _genArg21, _genArg22); return retVal; } void IClientImpl::unknown_70(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_70(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_70(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SET_MISSION_MESSAGE(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SET_MISSION_MESSAGE(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SET_MISSION_MESSAGE, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SET_MISSION_MESSAGE(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SET_MISSION_MESSAGE, client, _genArg1); return retVal; } void IClientImpl::unknown_72(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_72(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_72(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES, client, _genArg1); return retVal; } void IClientImpl::unknown_74(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_74(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_74(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_75(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_75(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_75(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_MARKOBJ(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_MARKOBJ(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MARKOBJ(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_77(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_77(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_77(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SETCASH(ClientId client, uint cash) { AddLog( LogType::Normal, LogLevel::Debug, std::format("IClientImpl::Send_FLPACKET_SERVER_SETCASH(\n\tClientId client = {}\n\tuint cash = {}\n)", client, cash)); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETCASH, client, cash); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SETCASH(client, cash); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETCASH, client, cash); return retVal; } void IClientImpl::unknown_79(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_79(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_79(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_80(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_80(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_80(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_81(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_81(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_81(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_82(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_82(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_82(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_83(ClientId client, char* _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_83(\n\tClientId client = {}\n\tchar* _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_83(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_REQUEST_RETURNED(ClientId client, uint shipId, uint flag, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_REQUEST_RETURNED(\n\tClientId client = {}\n\tuint shipId = {}\n\tuint flag = {}\n\tuint _genArg1 " L"= {}\n\tuint _genArg2 = {}\n)", client, shipId, flag, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_REQUEST_RETURNED(client, shipId, flag, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_85(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_85(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_85(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_86(ClientId client, uint _genArg1, uint _genArg2, uint _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_86(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n\tuint _genArg3 = {}\n)", client, _genArg1, _genArg2, _genArg3))); CALL_CLIENT_PREAMBLE { unknown_86(client, _genArg1, _genArg2, _genArg3); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_OBJECTCARGOUPDATE(SObjectCargoUpdate& cargoUpdate, uint iDunno1, uint iDunno2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_OBJECTCARGOUPDATE(\n\tSObjectCargoUpdate client = {}\n\tuint iDunno1 = {}\n\tuint iDunno2 = {}\n)", cargoUpdate.client, iDunno1, iDunno2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_OBJECTCARGOUPDATE(cargoUpdate, iDunno1, iDunno2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_BURNFUSE(ClientId client, FLPACKET_BURNFUSE& burnFuse) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_BURNFUSE(\n\tClientId client = {}\n\tFLPACKET_BURNFUSE& burnFuse = {}\n)", client, ToLogString(burnFuse)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_BURNFUSE, client, burnFuse); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_BURNFUSE(client, burnFuse); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_BURNFUSE, client, burnFuse); return retVal; } void IClientImpl::unknown_89(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_89(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_89(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_90(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_90(\n\tClientId client = {}\n)", client)); CALL_CLIENT_PREAMBLE { unknown_90(client); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_91(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_91(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_91(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_COMMON_SET_WEAPON_GROUP(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::Send_FLPACKET_COMMON_SET_WEAPON_GROUP(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2)); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_SET_WEAPON_GROUP(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_SET_VISITED_STATE(ClientId client, uint objHash, int state) { AddLog(LogType::Normal, LogLevel::Debug, std::format( "IClientImpl::Send_FLPACKET_COMMON_SET_VISITED_STATE(\n\tClientId client = {}\n\tuint objHash = {}\n\tint state = {}\n)", client, objHash, state)); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_SET_VISITED_STATE(client, objHash, state); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_REQUEST_BEST_PATH(ClientId client, uint objHash, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_REQUEST_BEST_PATH(\n\tClientId client = {}\n\tobjHash = {}\n\tint _genArg2 = {}\n)", client, objHash, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_REQUEST_BEST_PATH(client, objHash, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_REQUEST_PLAYER_STATS(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_REQUEST_PLAYER_STATS(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_REQUEST_PLAYER_STATS(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_96(ClientId client, uint _genArg1, uint _genArg2, uint _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_96(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n\tuint _genArg3 = {}\n)", client, _genArg1, _genArg2, _genArg3))); CALL_CLIENT_PREAMBLE { unknown_96(client, _genArg1, _genArg2, _genArg3); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_COMMON_REQUEST_GROUP_POSITIONS(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_REQUEST_GROUP_POSITIONS(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_REQUEST_GROUP_POSITIONS(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_SET_MISSION_LOG(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_SET_MISSION_LOG(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_SET_MISSION_LOG(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } bool IClientImpl::Send_FLPACKET_COMMON_SET_INTERFACE_STATE(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_SET_INTERFACE_STATE(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_SET_INTERFACE_STATE(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_100(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_100(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_100(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_101(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_101(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); CALL_CLIENT_PREAMBLE { unknown_101(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_102(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_102(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_102(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_103(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_103(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_103(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_104(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_104(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_104(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_105(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_105(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_105(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_106(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_106(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_106(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_107(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_107(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); CALL_CLIENT_PREAMBLE { unknown_107(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_COMMON_PLAYER_TRADE(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_COMMON_PLAYER_TRADE(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_COMMON_PLAYER_TRADE(client, _genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_109(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_109(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_109(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_SCANNOTIFY(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_SCANNOTIFY(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SCANNOTIFY, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_SCANNOTIFY(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SCANNOTIFY, client, _genArg1, _genArg2); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_PLAYERLIST(ClientId client, wchar_t* characterName, uint _genArg2, char _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_PLAYERLIST(\n\tClientId client = {}\n\twchar_t* characterName = {}\n\tuint _genArg2 = {}\n\tchar " L"_genArg3 = {}\n)", client, std::wstring(characterName), _genArg2, ToLogString(_genArg3)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST, client, characterName, _genArg2, _genArg3); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_PLAYERLIST(client, characterName, _genArg2, _genArg3); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST, client, characterName, _genArg2, _genArg3); return retVal; } void IClientImpl::unknown_112(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_112(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_112(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_PLAYERLIST_2(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::Send_FLPACKET_SERVER_PLAYERLIST_2(\n\tClientId client = {}\n)", client)); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST_2, client); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_PLAYERLIST_2(client); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST_2, client); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_6(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_6(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_6, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE_6(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_6, client, _genArg1, _genArg2); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_7(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_7(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_7, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE_7(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_7, client, _genArg1, _genArg2); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE(ClientId client, FLPACKET_UNKNOWN& _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE(\n\tClientId client = {}\n\tFLPACKET_UNKNOWN& _genArg1 = {}\n)", client, ToLogString(_genArg1)))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE, client, _genArg1); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE, client, _genArg1); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_2(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_2(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_2, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE_2(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_2, client, _genArg1, _genArg2); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_3(ClientId client, uint targetId, uint rank) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format( L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_3(\n\tClientId client = {}\n\tuint targetId = {}\n\tuint rank = {}\n)", client, targetId, rank))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_3, client, targetId, rank); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE_3(client, targetId, rank); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_3, client, targetId, rank); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_4(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_4(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint " L"_genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_4, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE_4(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_4, client, _genArg1, _genArg2); return retVal; } bool IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_5(ClientId client, uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_MISCOBJUPDATE_5(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", client, _genArg1, _genArg2))); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_5, client, _genArg1, _genArg2); if (!skip) { CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_MISCOBJUPDATE_5(client, _genArg1, _genArg2); } CALL_CLIENT_POSTAMBLE; } CallPluginsAfter(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_5, client, _genArg1, _genArg2); return retVal; } void IClientImpl::unknown_121(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_121(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_121(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } bool IClientImpl::Send_FLPACKET_SERVER_FORMATION_UPDATE(ClientId client, uint shipId, Vector& formationOffset) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::Send_FLPACKET_SERVER_FORMATION_UPDATE(\n\tClientId client = {}\n\tuint shipId = {}\n\tVector& formationOffset = {}\n)", client, shipId, ToLogString(formationOffset)))); bool retVal; CALL_CLIENT_PREAMBLE { retVal = Send_FLPACKET_SERVER_FORMATION_UPDATE(client, shipId, formationOffset); } CALL_CLIENT_POSTAMBLE; return retVal; } void IClientImpl::unknown_123(ClientId client, uint _genArg1, uint _genArg2, uint _genArg3, uint _genArg4, uint _genArg5, uint _genArg6) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"IClientImpl::unknown_123(\n\tClientId client = {}\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n\tuint " L"_genArg3 = {}\n\tuint _genArg4 = {}\n\tuint _genArg5 = {}\n\tuint _genArg6 = {}\n)", client, _genArg1, _genArg2, _genArg3, _genArg4, _genArg5, _genArg6))); CALL_CLIENT_PREAMBLE { unknown_123(client, _genArg1, _genArg2, _genArg3, _genArg4, _genArg5, _genArg6); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_124(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_124(\n\tClientId client = {}\n)", client)); CALL_CLIENT_PREAMBLE { unknown_124(client); } CALL_CLIENT_POSTAMBLE; } void IClientImpl::unknown_125(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_125(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); CALL_CLIENT_PREAMBLE { unknown_125(client, _genArg1); } CALL_CLIENT_POSTAMBLE; } int IClientImpl::unknown_126(char* _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("IClientImpl::unknown_126(\n\tchar* _genArg1 = {}\n)", _genArg1)); int retVal; CALL_CLIENT_PREAMBLE { retVal = unknown_126(_genArg1); } CALL_CLIENT_POSTAMBLE; return retVal; } namespace IServerImplHook { void __stdcall FireWeapon(ClientId client, XFireWeaponInfo const& fwi) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"FireWeapon(\n\tClientId client = {}\n\tXFireWeaponInfo const& fwi = {}\n)", client, ToLogString(fwi)))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__FireWeapon, client, fwi); CHECK_FOR_DISCONNECT; if (!skip) { CALL_SERVER_PREAMBLE { Server.FireWeapon(client, fwi); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__FireWeapon, client, fwi); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ActivateEquip(ClientId client, XActivateEquip const& aq) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ActivateEquip(\n\tClientId client = {}\n\tXActivateEquip const& aq = {}\n)", client, ToLogString(aq)))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ActivateEquip, client, aq); CHECK_FOR_DISCONNECT; ActivateEquip__Inner(client, aq); if (!skip) { CALL_SERVER_PREAMBLE { Server.ActivateEquip(client, aq); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ActivateEquip, client, aq); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ActivateCruise(ClientId client, XActivateCruise const& ac) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ActivateCruise(\n\tClientId client = {}\n\tXActivateCruise const& ac = {}\n)", client, ToLogString(ac)))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ActivateCruise, client, ac); CHECK_FOR_DISCONNECT; ActivateCruise__Inner(client, ac); if (!skip) { CALL_SERVER_PREAMBLE { Server.ActivateCruise(client, ac); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ActivateCruise, client, ac); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ActivateThrusters(ClientId client, XActivateThrusters const& at) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ActivateThrusters(\n\tClientId client = {}\n\tXActivateThrusters const& at = {}\n)", client, ToLogString(at)))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ActivateThrusters, client, at); CHECK_FOR_DISCONNECT; ActivateThrusters__Inner(client, at); if (!skip) { CALL_SERVER_PREAMBLE { Server.ActivateThrusters(client, at); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ActivateThrusters, client, at); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SetTarget(ClientId client, XSetTarget const& st) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SetTarget(\n\tClientId client = {}\n\tXSetTarget const& st = {}\n)", client, ToLogString(st)))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SetTarget, client, st); !skip) { CALL_SERVER_PREAMBLE { Server.SetTarget(client, st); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SetTarget, client, st); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall TractorObjects(ClientId client, XTractorObjects const& to) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"TractorObjects(\n\tClientId client = {}\n\tXTractorObjects const& to = {}\n)", client, ToLogString(to)))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__TractorObjects, client, to); !skip) { CALL_SERVER_PREAMBLE { Server.TractorObjects(client, to); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__TractorObjects, client, to); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall GoTradelane(ClientId client, XGoTradelane const& gt) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"GoTradelane(\n\tClientId client = {}\n\tXGoTradelane const& gt = {}\n)", client, ToLogString(gt)))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__GoTradelane, client, gt); GoTradelane__Inner(client, gt); if (!skip) { CALL_SERVER_PREAMBLE { Server.GoTradelane(client, gt); } CALL_SERVER_POSTAMBLE(GoTradelane__Catch(client, gt), ); } CallPluginsAfter(HookedCall::IServerImpl__GoTradelane, client, gt); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall StopTradelane(ClientId client, uint shipId, uint tradelaneRing1, uint tradelaneRing2) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"StopTradelane(\n\tClientId client = {}\n\tuint shipId = {}\n\tuint tradelaneRing1 = {}\n\tuint tradelaneRing2 = {}\n)", client, shipId, tradelaneRing1, tradelaneRing2))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__StopTradelane, client, shipId, tradelaneRing1, tradelaneRing2); StopTradelane__Inner(client, shipId, tradelaneRing1, tradelaneRing2); if (!skip) { CALL_SERVER_PREAMBLE { Server.StopTradelane(client, shipId, tradelaneRing1, tradelaneRing2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__StopTradelane, client, shipId, tradelaneRing1, tradelaneRing2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall JettisonCargo(ClientId client, XJettisonCargo const& jc) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"JettisonCargo(\n\tClientId client = {}\n\tXJettisonCargo const& jc = {}\n)", client, ToLogString(jc)))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__JettisonCargo, client, jc); !skip) { CALL_SERVER_PREAMBLE { Server.JettisonCargo(client, jc); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__JettisonCargo, client, jc); } } // namespace IServerImplHook namespace IServerImplHook { bool __stdcall Startup(SStartupInfo const& si) { Startup__Inner(si); auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IServerImpl__Startup, si); if (!skip) { CALL_SERVER_PREAMBLE { retVal = Server.Startup(si); } CALL_SERVER_POSTAMBLE(true, bool()); } Startup__InnerAfter(si); CallPluginsAfter(HookedCall::IServerImpl__Startup, si); return retVal; } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall Shutdown() { AddLog(LogType::Normal, LogLevel::Debug, "Shutdown()"); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__Shutdown); !skip) { CALL_SERVER_PREAMBLE { Server.Shutdown(); } CALL_SERVER_POSTAMBLE(true, ); } Shutdown__InnerAfter(); } } // namespace IServerImplHook namespace IServerImplHook { int __stdcall Update() { auto [retVal, skip] = CallPluginsBefore<int>(HookedCall::IServerImpl__Update); Update__Inner(); if (!skip) { CALL_SERVER_PREAMBLE { retVal = Server.Update(); } CALL_SERVER_POSTAMBLE(true, int()); } CallPluginsAfter(HookedCall::IServerImpl__Update); return retVal; } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall DisConnect(ClientId client, EFLConnection conn) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"DisConnect(\n\tClientId client = {}\n\tEFLConnection conn = {}\n)", client, ToLogString(conn)))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__DisConnect, client, conn); DisConnect__Inner(client, conn); if (!skip) { CALL_SERVER_PREAMBLE { Server.DisConnect(client, conn); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__DisConnect, client, conn); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall OnConnect(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"OnConnect(\n\tClientId client = {}\n)", client))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__OnConnect, client); if (bool innerCheck = OnConnect__Inner(client); !innerCheck) return; if (!skip) { CALL_SERVER_PREAMBLE { Server.OnConnect(client); } CALL_SERVER_POSTAMBLE(true, ); } OnConnect__InnerAfter(client); CallPluginsAfter(HookedCall::IServerImpl__OnConnect, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall Login(SLoginInfo const& li, ClientId client) { AddLog( LogType::Normal, LogLevel::Debug, wstos(std::format(L"Login(\n\tSLoginInfo const& li = {}\n\tClientId client = {}\n)", ToLogString(li), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__Login, li, client); !skip && Login__InnerBefore(li, client)) { CALL_SERVER_PREAMBLE { Server.Login(li, client); } CALL_SERVER_POSTAMBLE(true, ); } Login__InnerAfter(li, client); if (TempBanManager::i()->CheckIfTempBanned(client)) { Hk::Player::Kick(client); return; } CallPluginsAfter(HookedCall::IServerImpl__Login, li, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall CharacterInfoReq(ClientId client, bool _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"CharacterInfoReq(\n\tClientId client = {}\n\tbool _genArg1 = {}\n)", client, _genArg1))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__CharacterInfoReq, client, _genArg1); CHECK_FOR_DISCONNECT; if (bool innerCheck = CharacterInfoReq__Inner(client, _genArg1); !innerCheck) return; if (!skip) { CALL_SERVER_PREAMBLE { Server.CharacterInfoReq(client, _genArg1); } CALL_SERVER_POSTAMBLE(CharacterInfoReq__Catch(client, _genArg1), ); } CallPluginsAfter(HookedCall::IServerImpl__CharacterInfoReq, client, _genArg1); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall CharacterSelect(CHARACTER_ID const& cid, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"CharacterSelect(\n\tCHARACTER_ID const& cid = {}\n\tClientId client = {}\n)", ToLogString(cid), client))); std::string charName = cid.szCharFilename; auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__CharacterSelect, charName, client); CHECK_FOR_DISCONNECT; if (bool innerCheck = CharacterSelect__Inner(cid, client); !innerCheck) return; if (!skip) { CALL_SERVER_PREAMBLE { Server.CharacterSelect(cid, client); } CALL_SERVER_POSTAMBLE(true, ); } CharacterSelect__InnerAfter(cid, client); CallPluginsAfter(HookedCall::IServerImpl__CharacterSelect, charName, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall CreateNewCharacter(SCreateCharacterInfo const& _genArg1, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"CreateNewCharacter(\n\tSCreateCharacterInfo const& _genArg1 = {}\n\tClientId client = {}\n)", ToLogString(_genArg1), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__CreateNewCharacter, _genArg1, client); !skip) { CALL_SERVER_PREAMBLE { Server.CreateNewCharacter(_genArg1, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__CreateNewCharacter, _genArg1, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall DestroyCharacter(CHARACTER_ID const& _genArg1, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"DestroyCharacter(\n\tCHARACTER_ID const& _genArg1 = {}\n\tClientId client = {}\n)", ToLogString(_genArg1), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__DestroyCharacter, _genArg1, client); !skip) { CALL_SERVER_PREAMBLE { Server.DestroyCharacter(_genArg1, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__DestroyCharacter, _genArg1, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqShipArch(uint archId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ReqShipArch(\n\tuint archId = {}\n\tClientId client = {}\n)", archId, client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqShipArch, archId, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqShipArch(archId, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqShipArch, archId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqHullStatus(float status, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ReqHullStatus(\n\tfloat status = {}\n\tClientId client = {}\n)", status, client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqHullStatus, status, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqHullStatus(status, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqHullStatus, status, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqCollisionGroups(st6::list<CollisionGroupDesc> const& collisionGroups, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ReqCollisionGroups(\n\tst6::list<CollisionGroupDesc> const& CollisionGroups = {}\n\tClientId client = {}\n)", ToLogString(collisionGroups), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqCollisionGroups, collisionGroups, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqCollisionGroups(collisionGroups, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqCollisionGroups, collisionGroups, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqEquipment(EquipDescList const& edl, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ReqEquipment(\n\tEquipDescList const& edl = {}\n\tClientId client = {}\n)", ToLogString(edl), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqEquipment, edl, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqEquipment(edl, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqEquipment, edl, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqAddItem(uint goodId, char const* hardpoint, int count, float status, bool mounted, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"ReqAddItem(\n\tuint goodId = {}\n\tchar const* hardpoint = {}\n\tint count = {}\n\tfloat status = " L"{}\n\tbool mounted = {}\n\tClientId client = {}\n)", goodId, stows(std::string(hardpoint)), count, status, mounted, client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqAddItem, goodId, hardpoint, count, status, mounted, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqAddItem(goodId, hardpoint, count, status, mounted, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqAddItem, goodId, hardpoint, count, status, mounted, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqRemoveItem(ushort slotId, int count, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("ReqRemoveItem(\n\tushort slotId = {}\n\tint count = {}\n\tClientId client = {}\n)", slotId, count, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqRemoveItem, slotId, count, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqRemoveItem(slotId, count, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqRemoveItem, slotId, count, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqModifyItem(ushort slotId, char const* hardpoint, int count, float status, bool mounted, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("ReqModifyItem(\n\tushort slotId = {}\n\tchar const* hardpoint = {}\n\tint count = {}\n\tfloat status = " "{}\n\tbool mounted = {}\n\tClientId client = {}\n)", slotId, std::string(hardpoint), count, status, mounted, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqModifyItem, slotId, hardpoint, count, status, mounted, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqModifyItem(slotId, hardpoint, count, status, mounted, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqModifyItem, slotId, hardpoint, count, status, mounted, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqSetCash(int cash, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("ReqSetCash(\n\tint cash = {}\n\tClientId client = {}\n)", cash, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqSetCash, cash, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqSetCash(cash, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqSetCash, cash, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall ReqChangeCash(int cashAdd, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("ReqChangeCash(\n\tint cashAdd = {}\n\tClientId client = {}\n)", cashAdd, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__ReqChangeCash, cashAdd, client); !skip) { CALL_SERVER_PREAMBLE { Server.ReqChangeCash(cashAdd, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__ReqChangeCash, cashAdd, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall BaseEnter(uint baseId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("BaseEnter(\n\tuint baseId = {}\n\tClientId client = {}\n)", baseId, client)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__BaseEnter, baseId, client); CHECK_FOR_DISCONNECT; BaseEnter__Inner(baseId, client); if (!skip) { CALL_SERVER_PREAMBLE { Server.BaseEnter(baseId, client); } CALL_SERVER_POSTAMBLE(true, ); } BaseEnter__InnerAfter(baseId, client); CallPluginsAfter(HookedCall::IServerImpl__BaseEnter, baseId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall BaseExit(uint baseId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("BaseExit(\n\tuint baseId = {}\n\tClientId client = {}\n)", baseId, client)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__BaseExit, baseId, client); CHECK_FOR_DISCONNECT; BaseExit__Inner(baseId, client); if (!skip) { CALL_SERVER_PREAMBLE { Server.BaseExit(baseId, client); } CALL_SERVER_POSTAMBLE(true, ); } BaseExit__InnerAfter(baseId, client); CallPluginsAfter(HookedCall::IServerImpl__BaseExit, baseId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall LocationEnter(uint locationId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("LocationEnter(\n\tuint locationId = {}\n\tClientId client = {}\n)", locationId, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__LocationEnter, locationId, client); !skip) { CALL_SERVER_PREAMBLE { Server.LocationEnter(locationId, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__LocationEnter, locationId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall LocationExit(uint locationId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("LocationExit(\n\tuint locationId = {}\n\tClientId client = {}\n)", locationId, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__LocationExit, locationId, client); !skip) { CALL_SERVER_PREAMBLE { Server.LocationExit(locationId, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__LocationExit, locationId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall BaseInfoRequest(unsigned int _genArg1, unsigned int _genArg2, bool _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, std::format("BaseInfoRequest(\n\tunsigned int _genArg1 = {}\n\tunsigned int _genArg2 = {}\n\tbool _genArg3 = {}\n)", _genArg1, _genArg2, _genArg3)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__BaseInfoRequest, _genArg1, _genArg2, _genArg3); !skip) { CALL_SERVER_PREAMBLE { Server.BaseInfoRequest(_genArg1, _genArg2, _genArg3); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__BaseInfoRequest, _genArg1, _genArg2, _genArg3); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall LocationInfoRequest(unsigned int _genArg1, unsigned int _genArg2, bool _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, std::format( "LocationInfoRequest(\n\tunsigned int _genArg1 = {}\n\tunsigned int _genArg2 = {}\n\tbool _genArg3 = {}\n)", _genArg1, _genArg2, _genArg3)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__LocationInfoRequest, _genArg1, _genArg2, _genArg3); !skip) { CALL_SERVER_PREAMBLE { Server.LocationInfoRequest(_genArg1, _genArg2, _genArg3); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__LocationInfoRequest, _genArg1, _genArg2, _genArg3); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall GFObjSelect(unsigned int _genArg1, unsigned int _genArg2) { AddLog( LogType::Normal, LogLevel::Debug, std::format("GFObjSelect(\n\tunsigned int _genArg1 = {}\n\tunsigned int _genArg2 = {}\n)", _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__GFObjSelect, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.GFObjSelect(_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__GFObjSelect, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall GFGoodVaporized(SGFGoodVaporizedInfo const& gvi, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"GFGoodVaporized(\n\tSGFGoodVaporizedInfo const& gvi = {}\n\tClientId client = {}\n)", ToLogString(gvi), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__GFGoodVaporized, gvi, client); !skip) { CALL_SERVER_PREAMBLE { Server.GFGoodVaporized(gvi, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__GFGoodVaporized, gvi, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall MissionResponse(unsigned int _genArg1, unsigned long _genArg2, bool _genArg3, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("MissionResponse(\n\tunsigned int _genArg1 = {}\n\tunsigned long _genArg2 = {}\n\tbool _genArg3 = " "{}\n\tClientId client = {}\n)", _genArg1, _genArg2, _genArg3, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__MissionResponse, _genArg1, _genArg2, _genArg3, client); !skip) { CALL_SERVER_PREAMBLE { Server.MissionResponse(_genArg1, _genArg2, _genArg3, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__MissionResponse, _genArg1, _genArg2, _genArg3, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall TradeResponse(unsigned char const* _genArg1, int _genArg2, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("TradeResponse(\n\tunsigned char const* _genArg1 = {}\n\tint _genArg2 = {}\n\tClientId client = {}\n)", std::string(reinterpret_cast<char const*>(_genArg1)), _genArg2, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__TradeResponse, _genArg1, _genArg2, client); !skip) { CALL_SERVER_PREAMBLE { Server.TradeResponse(_genArg1, _genArg2, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__TradeResponse, _genArg1, _genArg2, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall GFGoodBuy(SGFGoodBuyInfo const& _genArg1, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"GFGoodBuy(\n\tSGFGoodBuyInfo const& _genArg1 = {}\n\tClientId client = {}\n)", ToLogString(_genArg1), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__GFGoodBuy, _genArg1, client); !skip) { CALL_SERVER_PREAMBLE { Server.GFGoodBuy(_genArg1, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__GFGoodBuy, _genArg1, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall GFGoodSell(SGFGoodSellInfo const& _genArg1, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"GFGoodSell(\n\tSGFGoodSellInfo const& _genArg1 = {}\n\tClientId client = {}\n)", ToLogString(_genArg1), client))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__GFGoodSell, _genArg1, client); CHECK_FOR_DISCONNECT; if (bool innerCheck = GFGoodSell__Inner(_genArg1, client); !innerCheck) return; if (!skip) { CALL_SERVER_PREAMBLE { Server.GFGoodSell(_genArg1, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__GFGoodSell, _genArg1, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SystemSwitchOutComplete(uint shipId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("SystemSwitchOutComplete(\n\tuint shipId = {}\n\tClientId client = {}\n)", shipId, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SystemSwitchOutComplete, shipId, client); !skip) { CALL_SERVER_PREAMBLE { Server.SystemSwitchOutComplete(shipId, client); } CALL_SERVER_POSTAMBLE(true, ); } SystemSwitchOutComplete__InnerAfter(shipId, client); CallPluginsAfter(HookedCall::IServerImpl__SystemSwitchOutComplete, shipId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall PlayerLaunch(uint shipId, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("PlayerLaunch(\n\tuint shipId = {}\n\tClientId client = {}\n)", shipId, client)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__PlayerLaunch, shipId, client); CHECK_FOR_DISCONNECT; PlayerLaunch__Inner(shipId, client); if (!skip) { CALL_SERVER_PREAMBLE { Server.PlayerLaunch(shipId, client); } CALL_SERVER_POSTAMBLE(true, ); } PlayerLaunch__InnerAfter(shipId, client); CallPluginsAfter(HookedCall::IServerImpl__PlayerLaunch, shipId, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall LaunchComplete(uint baseId, uint shipId) { AddLog(LogType::Normal, LogLevel::Debug, std::format("LaunchComplete(\n\tuint baseId = {}\n\tuint shipId = {}\n)", baseId, shipId)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__LaunchComplete, baseId, shipId); LaunchComplete__Inner(baseId, shipId); if (!skip) { CALL_SERVER_PREAMBLE { Server.LaunchComplete(baseId, shipId); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__LaunchComplete, baseId, shipId); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall JumpInComplete(uint systemId, uint shipId) { AddLog(LogType::Normal, LogLevel::Debug, std::format("JumpInComplete(\n\tuint systemId = {}\n\tuint shipId = {}\n)", systemId, shipId)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__JumpInComplete, systemId, shipId); !skip) { CALL_SERVER_PREAMBLE { Server.JumpInComplete(systemId, shipId); } CALL_SERVER_POSTAMBLE(true, ); } JumpInComplete__InnerAfter(systemId, shipId); CallPluginsAfter(HookedCall::IServerImpl__JumpInComplete, systemId, shipId); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall Hail(unsigned int _genArg1, unsigned int _genArg2, unsigned int _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, std::format("Hail(\n\tunsigned int _genArg1 = {}\n\tunsigned int _genArg2 = {}\n\tunsigned int _genArg3 = {}\n)", _genArg1, _genArg2, _genArg3)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__Hail, _genArg1, _genArg2, _genArg3); !skip) { CALL_SERVER_PREAMBLE { Server.Hail(_genArg1, _genArg2, _genArg3); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__Hail, _genArg1, _genArg2, _genArg3); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SPObjUpdate(SSPObjUpdateInfo const& ui, ClientId client) { auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SPObjUpdate, ui, client); CHECK_FOR_DISCONNECT; if (bool innerCheck = SPObjUpdate__Inner(ui, client); !innerCheck) return; if (!skip) { CALL_SERVER_PREAMBLE { Server.SPObjUpdate(ui, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SPObjUpdate, ui, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SPMunitionCollision(SSPMunitionCollisionInfo const& mci, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SPMunitionCollision(\n\tSSPMunitionCollisionInfo const& mci = {}\n\tClientId client = {}\n)", ToLogString(mci), client))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SPMunitionCollision, mci, client); CHECK_FOR_DISCONNECT; SPMunitionCollision__Inner(mci, client); if (!skip) { CALL_SERVER_PREAMBLE { Server.SPMunitionCollision(mci, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SPMunitionCollision, mci, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SPObjCollision(SSPObjCollisionInfo const& oci, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SPObjCollision(\n\tSSPObjCollisionInfo const& oci = {}\n\tClientId client = {}\n)", ToLogString(oci), client))); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SPObjCollision, oci, client); CHECK_FOR_DISCONNECT; if (!skip) { CALL_SERVER_PREAMBLE { Server.SPObjCollision(oci, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SPObjCollision, oci, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SPRequestUseItem(SSPUseItem const& ui, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SPRequestUseItem(\n\tSSPUseItem const& ui = {}\n\tClientId client = {}\n)", ToLogString(ui), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SPRequestUseItem, ui, client); !skip) { CALL_SERVER_PREAMBLE { Server.SPRequestUseItem(ui, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SPRequestUseItem, ui, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SPRequestInvincibility(uint shipId, bool enable, InvincibilityReason reason, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SPRequestInvincibility(\n\tuint shipId = {}\n\tbool enable = {}\n\tInvincibilityReason reason = " L"{}\n\tClientId client = {}\n)", shipId, enable, ToLogString(reason), client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SPRequestInvincibility, shipId, enable, reason, client); !skip) { CALL_SERVER_PREAMBLE { Server.SPRequestInvincibility(shipId, enable, reason, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SPRequestInvincibility, shipId, enable, reason, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestEvent(int eventType, uint shipId, uint dockTarget, uint _genArg1, ulong _genArg2, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestEvent(\n\tint eventType = {}\n\tuint shipId = {}\n\tuint dockTarget = {}\n\tuint _genArg1 = {}\n\tulong _genArg2 = " "{}\n\tClientId client = {}\n)", eventType, shipId, dockTarget, _genArg1, _genArg2, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestEvent, eventType, shipId, dockTarget, _genArg1, _genArg2, client); !skip) { CALL_SERVER_PREAMBLE { Server.RequestEvent(eventType, shipId, dockTarget, _genArg1, _genArg2, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestEvent, eventType, shipId, dockTarget, _genArg1, _genArg2, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestCancel(int eventType, uint shipId, uint _genArg1, ulong _genArg2, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestCancel(\n\tint eventType = {}\n\tuint shipId = {}\n\tuint _genArg1 = {}\n\tulong _genArg2 = {}\n\tClientId client = {}\n)", eventType, shipId, _genArg1, _genArg2, client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestCancel, eventType, shipId, _genArg1, _genArg2, client); !skip) { CALL_SERVER_PREAMBLE { Server.RequestCancel(eventType, shipId, _genArg1, _genArg2, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestCancel, eventType, shipId, _genArg1, _genArg2, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall MineAsteroid(uint systemId, Vector const& pos, uint crateId, uint lootId, uint count, ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"MineAsteroid(\n\tuint systemId = {}\n\tVector const& pos = {}\n\tuint crateId = {}\n\tuint lootId = {}\n\tuint count = " L"{}\n\tClientId client = {}\n)", systemId, ToLogString(pos), crateId, lootId, count, client))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__MineAsteroid, systemId, pos, crateId, lootId, count, client); !skip) { CALL_SERVER_PREAMBLE { Server.MineAsteroid(systemId, pos, crateId, lootId, count, client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__MineAsteroid, systemId, pos, crateId, lootId, count, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestCreateShip(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestCreateShip(\n\tClientId client = {}\n)", client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestCreateShip, client); !skip) { CALL_SERVER_PREAMBLE { Server.RequestCreateShip(client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestCreateShip, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SPScanCargo(uint const& _genArg1, uint const& _genArg2, uint _genArg3) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SPScanCargo(\n\tuint const& _genArg1 = {}\n\tuint const& _genArg2 = {}\n\tuint _genArg3 = {}\n)", ToLogString(_genArg1), ToLogString(_genArg2), _genArg3))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SPScanCargo, _genArg1, _genArg2, _genArg3); !skip) { CALL_SERVER_PREAMBLE { Server.SPScanCargo(_genArg1, _genArg2, _genArg3); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SPScanCargo, _genArg1, _genArg2, _genArg3); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SetManeuver(ClientId client, XSetManeuver const& sm) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"SetManeuver(\n\tClientId client = {}\n\tXSetManeuver const& sm = {}\n)", client, ToLogString(sm)))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SetManeuver, client, sm); !skip) { CALL_SERVER_PREAMBLE { Server.SetManeuver(client, sm); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SetManeuver, client, sm); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall InterfaceItemUsed(uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("InterfaceItemUsed(\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__InterfaceItemUsed, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.InterfaceItemUsed(_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__InterfaceItemUsed, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall AbortMission(ClientId client, uint _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("AbortMission(\n\tClientId client = {}\n\tuint _genArg1 = {}\n)", client, _genArg1)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__AbortMission, client, _genArg1); !skip) { CALL_SERVER_PREAMBLE { Server.AbortMission(client, _genArg1); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__AbortMission, client, _genArg1); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SetWeaponGroup(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("SetWeaponGroup(\n\tClientId client = {}\n\tuint _genArg1 = 0x{:08X}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SetWeaponGroup, client, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.SetWeaponGroup(client, (uchar*)_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SetWeaponGroup, client, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SetVisitedState(ClientId client, uint objHash, int state) { AddLog(LogType::Normal, LogLevel::Debug, std::format("SetVisitedState(\n\tClientId client = {}\n\tuint objHash = {}\n\tint state = {}\n)", client, objHash, state)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SetVisitedState, client, objHash, state); !skip) { CALL_SERVER_PREAMBLE { Server.SetVisitedState(client, (uchar*)objHash, state); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SetVisitedState, client, objHash, state); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestBestPath(ClientId client, BestPathInfo* bpi, int bestPathInfoStructSize) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestBestPath(\n\tClientId client = {}\n\tuint _genArg1 = 0x{:08X}\n\tint _genArg2 = {}\n)", client, (uint)bpi, bestPathInfoStructSize)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestBestPath, client, bpi, bestPathInfoStructSize); !skip) { CALL_SERVER_PREAMBLE { Server.RequestBestPath(client, (uchar*)bpi, bestPathInfoStructSize); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestBestPath, client, bpi, bestPathInfoStructSize); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestPlayerStats(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestPlayerStats(\n\tClientId client = {}\n\tuint _genArg1 = 0x{:08X}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestPlayerStats, client, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.RequestPlayerStats(client, (uchar*)_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestPlayerStats, client, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall PopupDialog(ClientId client, uint buttonClicked) { AddLog(LogType::Normal, LogLevel::Debug, std::format("PopupDialog(\n\tClientId client = {}\n\tuint buttonClicked = {}\n)", client, buttonClicked)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__PopupDialog, client, buttonClicked); !skip) { CALL_SERVER_PREAMBLE { Server.PopUpDialog(client, buttonClicked); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__PopupDialog, client, buttonClicked); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestGroupPositions(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestGroupPositions(\n\tClientId client = {}\n\tuint _genArg1 = 0x{:08X}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestGroupPositions, client, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.RequestGroupPositions(client, (uchar*)_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestGroupPositions, client, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SetInterfaceState(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("SetInterfaceState(\n\tClientId client = {}\n\tuint _genArg1 = 0x{:08X}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SetInterfaceState, client, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.SetInterfaceState(client, (uchar*)_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SetInterfaceState, client, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestRankLevel(ClientId client, uint _genArg1, int _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestRankLevel(\n\tClientId client = {}\n\tuint _genArg1 = 0x{:08X}\n\tint _genArg2 = {}\n)", client, _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestRankLevel, client, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.RequestRankLevel(client, (uchar*)_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestRankLevel, client, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall InitiateTrade(ClientId client1, ClientId client2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("InitiateTrade(\n\tClientId client1 = {}\n\tClientId client2 = {}\n)", client1, client2)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__InitiateTrade, client1, client2); InitiateTrade__Inner(client1, client2); if (!skip) { CALL_SERVER_PREAMBLE { Server.InitiateTrade(client1, client2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__InitiateTrade, client1, client2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall TerminateTrade(ClientId client, int accepted) { AddLog(LogType::Normal, LogLevel::Debug, std::format("TerminateTrade(\n\tClientId client = {}\n\tint accepted = {}\n)", client, accepted)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__TerminateTrade, client, accepted); CHECK_FOR_DISCONNECT; if (!skip) { CALL_SERVER_PREAMBLE { Server.TerminateTrade(client, accepted); } CALL_SERVER_POSTAMBLE(true, ); } TerminateTrade__InnerAfter(client, accepted); CallPluginsAfter(HookedCall::IServerImpl__TerminateTrade, client, accepted); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall AcceptTrade(ClientId client, bool _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("AcceptTrade(\n\tClientId client = {}\n\tbool _genArg1 = {}\n)", client, _genArg1)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__AcceptTrade, client, _genArg1); !skip) { CALL_SERVER_PREAMBLE { Server.AcceptTrade(client, _genArg1); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__AcceptTrade, client, _genArg1); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SetTradeMoney(ClientId client, ulong _genArg1) { AddLog(LogType::Normal, LogLevel::Debug, std::format("SetTradeMoney(\n\tClientId client = {}\n\tulong _genArg1 = {}\n)", client, _genArg1)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SetTradeMoney, client, _genArg1); !skip) { CALL_SERVER_PREAMBLE { Server.SetTradeMoney(client, _genArg1); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__SetTradeMoney, client, _genArg1); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall AddTradeEquip(ClientId client, EquipDesc const& ed) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"AddTradeEquip(\n\tClientId client = {}\n\tEquipDesc const& ed = {}\n)", client, ToLogString(ed)))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__AddTradeEquip, client, ed); !skip) { CALL_SERVER_PREAMBLE { Server.AddTradeEquip(client, ed); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__AddTradeEquip, client, ed); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall DelTradeEquip(ClientId client, EquipDesc const& ed) { AddLog(LogType::Normal, LogLevel::Debug, wstos(std::format(L"DelTradeEquip(\n\tClientId client = {}\n\tEquipDesc const& ed = {}\n)", client, ToLogString(ed)))); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__DelTradeEquip, client, ed); !skip) { CALL_SERVER_PREAMBLE { Server.DelTradeEquip(client, ed); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__DelTradeEquip, client, ed); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall RequestTrade(uint _genArg1, uint _genArg2) { AddLog(LogType::Normal, LogLevel::Debug, std::format("RequestTrade(\n\tuint _genArg1 = {}\n\tuint _genArg2 = {}\n)", _genArg1, _genArg2)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__RequestTrade, _genArg1, _genArg2); !skip) { CALL_SERVER_PREAMBLE { Server.RequestTrade(_genArg1, _genArg2); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__RequestTrade, _genArg1, _genArg2); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall StopTradeRequest(ClientId client) { AddLog(LogType::Normal, LogLevel::Debug, std::format("StopTradeRequest(\n\tClientId client = {}\n)", client)); if (auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__StopTradeRequest, client); !skip) { CALL_SERVER_PREAMBLE { Server.StopTradeRequest(client); } CALL_SERVER_POSTAMBLE(true, ); } CallPluginsAfter(HookedCall::IServerImpl__StopTradeRequest, client); } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall Dock([[maybe_unused]] uint const& _genArg1, [[maybe_unused]] uint const& _genArg2) { } } // namespace IServerImplHook namespace IServerImplHook { void __stdcall SubmitChat(CHAT_ID cidFrom, ulong size, void const* rdlReader, CHAT_ID cidTo, int _genArg1) { AddLog( LogType::Normal, LogLevel::Debug, std::format("SubmitChat(\n\tuint From = {}\n\tulong size = {}\n\tuint cidTo = {}", cidFrom.iId, size, cidTo.iId)); auto skip = CallPluginsBefore<void>(HookedCall::IServerImpl__SubmitChat, cidFrom.iId, size, rdlReader, cidTo.iId, _genArg1); bool innerCheck = SubmitChat__Inner(cidFrom, size, rdlReader, cidTo, _genArg1); if (!innerCheck) return; chatData->inSubmitChat = true; if (!skip) { CALL_SERVER_PREAMBLE { Server.SubmitChat(cidFrom, size, rdlReader, cidTo, _genArg1); } CALL_SERVER_POSTAMBLE(true, ); } chatData->inSubmitChat = false; CallPluginsAfter(HookedCall::IServerImpl__SubmitChat, cidFrom.iId, size, rdlReader, cidTo.iId, _genArg1); } } // namespace IServerImplHook HookEntry IServerImplEntries[] = { {FARPROC(IServerImplHook::SubmitChat), -0x008, nullptr}, {FARPROC(IServerImplHook::FireWeapon), 0x000, nullptr}, {FARPROC(IServerImplHook::ActivateEquip), 0x004, nullptr}, {FARPROC(IServerImplHook::ActivateCruise), 0x008, nullptr}, {FARPROC(IServerImplHook::ActivateThrusters), 0x00C, nullptr}, {FARPROC(IServerImplHook::SetTarget), 0x010, nullptr}, {FARPROC(IServerImplHook::TractorObjects), 0x014, nullptr}, {FARPROC(IServerImplHook::GoTradelane), 0x018, nullptr}, {FARPROC(IServerImplHook::StopTradelane), 0x01C, nullptr}, {FARPROC(IServerImplHook::JettisonCargo), 0x020, nullptr}, {FARPROC(IServerImplHook::DisConnect), 0x040, nullptr}, {FARPROC(IServerImplHook::OnConnect), 0x044, nullptr}, {FARPROC(IServerImplHook::Login), 0x048, nullptr}, {FARPROC(IServerImplHook::CharacterInfoReq), 0x04C, nullptr}, {FARPROC(IServerImplHook::CharacterSelect), 0x050, nullptr}, {FARPROC(IServerImplHook::CreateNewCharacter), 0x058, nullptr}, {FARPROC(IServerImplHook::DestroyCharacter), 0x05C, nullptr}, {FARPROC(IServerImplHook::ReqShipArch), 0x064, nullptr}, {FARPROC(IServerImplHook::ReqHullStatus), 0x068, nullptr}, {FARPROC(IServerImplHook::ReqCollisionGroups), 0x06C, nullptr}, {FARPROC(IServerImplHook::ReqEquipment), 0x070, nullptr}, {FARPROC(IServerImplHook::ReqAddItem), 0x078, nullptr}, {FARPROC(IServerImplHook::ReqRemoveItem), 0x07C, nullptr}, {FARPROC(IServerImplHook::ReqModifyItem), 0x080, nullptr}, {FARPROC(IServerImplHook::ReqSetCash), 0x084, nullptr}, {FARPROC(IServerImplHook::ReqChangeCash), 0x088, nullptr}, {FARPROC(IServerImplHook::BaseEnter), 0x08C, nullptr}, {FARPROC(IServerImplHook::BaseExit), 0x090, nullptr}, {FARPROC(IServerImplHook::LocationEnter), 0x094, nullptr}, {FARPROC(IServerImplHook::LocationExit), 0x098, nullptr}, {FARPROC(IServerImplHook::BaseInfoRequest), 0x09C, nullptr}, {FARPROC(IServerImplHook::LocationInfoRequest), 0x0A0, nullptr}, {FARPROC(IServerImplHook::GFObjSelect), 0x0A4, nullptr}, {FARPROC(IServerImplHook::GFGoodVaporized), 0x0A8, nullptr}, {FARPROC(IServerImplHook::MissionResponse), 0x0AC, nullptr}, {FARPROC(IServerImplHook::TradeResponse), 0x0B0, nullptr}, {FARPROC(IServerImplHook::GFGoodBuy), 0x0B4, nullptr}, {FARPROC(IServerImplHook::GFGoodSell), 0x0B8, nullptr}, {FARPROC(IServerImplHook::SystemSwitchOutComplete), 0x0BC, nullptr}, {FARPROC(IServerImplHook::PlayerLaunch), 0x0C0, nullptr}, {FARPROC(IServerImplHook::LaunchComplete), 0x0C4, nullptr}, {FARPROC(IServerImplHook::JumpInComplete), 0x0C8, nullptr}, {FARPROC(IServerImplHook::Hail), 0x0CC, nullptr}, {FARPROC(IServerImplHook::SPObjUpdate), 0x0D0, nullptr}, {FARPROC(IServerImplHook::SPMunitionCollision), 0x0D4, nullptr}, {FARPROC(IServerImplHook::SPObjCollision), 0x0DC, nullptr}, {FARPROC(IServerImplHook::SPRequestUseItem), 0x0E0, nullptr}, {FARPROC(IServerImplHook::SPRequestInvincibility), 0x0E4, nullptr}, {FARPROC(IServerImplHook::RequestEvent), 0x0F0, nullptr}, {FARPROC(IServerImplHook::RequestCancel), 0x0F4, nullptr}, {FARPROC(IServerImplHook::MineAsteroid), 0x0F8, nullptr}, {FARPROC(IServerImplHook::RequestCreateShip), 0x100, nullptr}, {FARPROC(IServerImplHook::SPScanCargo), 0x104, nullptr}, {FARPROC(IServerImplHook::SetManeuver), 0x108, nullptr}, {FARPROC(IServerImplHook::InterfaceItemUsed), 0x10C, nullptr}, {FARPROC(IServerImplHook::AbortMission), 0x110, nullptr}, {FARPROC(IServerImplHook::SetWeaponGroup), 0x118, nullptr}, {FARPROC(IServerImplHook::SetVisitedState), 0x11C, nullptr}, {FARPROC(IServerImplHook::RequestBestPath), 0x120, nullptr}, {FARPROC(IServerImplHook::RequestPlayerStats), 0x124, nullptr}, {FARPROC(IServerImplHook::PopupDialog), 0x128, nullptr}, {FARPROC(IServerImplHook::RequestGroupPositions), 0x12C, nullptr}, {FARPROC(IServerImplHook::SetInterfaceState), 0x134, nullptr}, {FARPROC(IServerImplHook::RequestRankLevel), 0x138, nullptr}, {FARPROC(IServerImplHook::InitiateTrade), 0x13C, nullptr}, {FARPROC(IServerImplHook::TerminateTrade), 0x140, nullptr}, {FARPROC(IServerImplHook::AcceptTrade), 0x144, nullptr}, {FARPROC(IServerImplHook::SetTradeMoney), 0x148, nullptr}, {FARPROC(IServerImplHook::AddTradeEquip), 0x14C, nullptr}, {FARPROC(IServerImplHook::DelTradeEquip), 0x150, nullptr}, {FARPROC(IServerImplHook::RequestTrade), 0x154, nullptr}, {FARPROC(IServerImplHook::StopTradeRequest), 0x158, nullptr}, {FARPROC(IServerImplHook::Dock), 0x16C, nullptr}, }; void PluginManager::setupProps() { setProps(HookedCall::IEngine__CShip__Init, true, false); setProps(HookedCall::IEngine__CShip__Destroy, true, false); setProps(HookedCall::IEngine__UpdateTime, true, true); setProps(HookedCall::IEngine__ElapseTime, true, true); setProps(HookedCall::IEngine__DockCall, true, false); setProps(HookedCall::IEngine__LaunchPosition, true, false); setProps(HookedCall::IEngine__ShipDestroyed, true, false); setProps(HookedCall::IEngine__BaseDestroyed, true, false); setProps(HookedCall::IEngine__GuidedHit, true, false); setProps(HookedCall::IEngine__AddDamageEntry, true, true); setProps(HookedCall::IEngine__DamageHit, true, false); setProps(HookedCall::IEngine__AllowPlayerDamage, true, false); setProps(HookedCall::IEngine__SendDeathMessage, true, false); setProps(HookedCall::FLHook__TimerCheckKick, true, false); setProps(HookedCall::FLHook__TimerNPCAndF1Check, true, false); setProps(HookedCall::FLHook__UserCommand__Process, true, false); setProps(HookedCall::FLHook__AdminCommand__Help, true, true); setProps(HookedCall::FLHook__AdminCommand__Process, true, false); setProps(HookedCall::FLHook__LoadSettings, true, true); setProps(HookedCall::FLHook__LoadCharacterSettings, true, true); setProps(HookedCall::FLHook__ClearClientInfo, true, true); setProps(HookedCall::FLHook__ProcessEvent, true, false); setProps(HookedCall::IChat__SendChat, true, false); setProps(HookedCall::IClientImpl__Send_FLPACKET_COMMON_FIREWEAPON, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATEEQUIP, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATECRUISE, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_COMMON_ACTIVATETHRUSTERS, true, true); setProps(HookedCall::IClientImpl__CDPClientProxy__GetLinkSaturation, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETSHIPARCH, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETHULLSTATUS, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETCOLLISIONGROUPS, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETEQUIPMENT, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETADDITEM, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETSTARTROOM, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATESOLAR, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATESHIP, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATELOOT, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATEMINE, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATEGUIDED, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_CREATECOUNTER, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_COMMON_UPDATEOBJECT, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_DESTROYOBJECT, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_ACTIVATEOBJECT, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_LAUNCH, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_REQUESTCREATESHIPRESP, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_USE_ITEM, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETREPUTATION, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SENDCOMM, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SET_MISSION_MESSAGE, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETMISSIONOBJECTIVES, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SETCASH, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_BURNFUSE, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_SCANNOTIFY, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_PLAYERLIST_2, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_6, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_7, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_2, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_3, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_4, true, true); setProps(HookedCall::IClientImpl__Send_FLPACKET_SERVER_MISCOBJUPDATE_5, true, true); setProps(HookedCall::IServerImpl__FireWeapon, true, true); setProps(HookedCall::IServerImpl__ActivateEquip, true, true); setProps(HookedCall::IServerImpl__ActivateCruise, true, true); setProps(HookedCall::IServerImpl__ActivateThrusters, true, true); setProps(HookedCall::IServerImpl__SetTarget, true, true); setProps(HookedCall::IServerImpl__TractorObjects, true, true); setProps(HookedCall::IServerImpl__GoTradelane, true, true); setProps(HookedCall::IServerImpl__StopTradelane, true, true); setProps(HookedCall::IServerImpl__JettisonCargo, true, true); setProps(HookedCall::IServerImpl__Startup, true, true); setProps(HookedCall::IServerImpl__Shutdown, true, false); setProps(HookedCall::IServerImpl__Update, true, true); setProps(HookedCall::IServerImpl__DisConnect, true, true); setProps(HookedCall::IServerImpl__OnConnect, true, true); setProps(HookedCall::IServerImpl__Login, true, true); setProps(HookedCall::IServerImpl__CharacterInfoReq, true, true); setProps(HookedCall::IServerImpl__CharacterSelect, true, true); setProps(HookedCall::IServerImpl__CreateNewCharacter, true, true); setProps(HookedCall::IServerImpl__DestroyCharacter, true, true); setProps(HookedCall::IServerImpl__ReqShipArch, true, true); setProps(HookedCall::IServerImpl__ReqHullStatus, true, true); setProps(HookedCall::IServerImpl__ReqCollisionGroups, true, true); setProps(HookedCall::IServerImpl__ReqEquipment, true, true); setProps(HookedCall::IServerImpl__ReqAddItem, true, true); setProps(HookedCall::IServerImpl__ReqRemoveItem, true, true); setProps(HookedCall::IServerImpl__ReqModifyItem, true, true); setProps(HookedCall::IServerImpl__ReqSetCash, true, true); setProps(HookedCall::IServerImpl__ReqChangeCash, true, true); setProps(HookedCall::IServerImpl__BaseEnter, true, true); setProps(HookedCall::IServerImpl__BaseExit, true, true); setProps(HookedCall::IServerImpl__LocationEnter, true, true); setProps(HookedCall::IServerImpl__LocationExit, true, true); setProps(HookedCall::IServerImpl__BaseInfoRequest, true, true); setProps(HookedCall::IServerImpl__LocationInfoRequest, true, true); setProps(HookedCall::IServerImpl__GFObjSelect, true, true); setProps(HookedCall::IServerImpl__GFGoodVaporized, true, true); setProps(HookedCall::IServerImpl__MissionResponse, true, true); setProps(HookedCall::IServerImpl__TradeResponse, true, true); setProps(HookedCall::IServerImpl__GFGoodBuy, true, true); setProps(HookedCall::IServerImpl__GFGoodSell, true, true); setProps(HookedCall::IServerImpl__SystemSwitchOutComplete, true, true); setProps(HookedCall::IServerImpl__PlayerLaunch, true, true); setProps(HookedCall::IServerImpl__LaunchComplete, true, true); setProps(HookedCall::IServerImpl__JumpInComplete, true, true); setProps(HookedCall::IServerImpl__Hail, true, true); setProps(HookedCall::IServerImpl__SPObjUpdate, true, true); setProps(HookedCall::IServerImpl__SPMunitionCollision, true, true); setProps(HookedCall::IServerImpl__SPObjCollision, true, true); setProps(HookedCall::IServerImpl__SPRequestUseItem, true, true); setProps(HookedCall::IServerImpl__SPRequestInvincibility, true, true); setProps(HookedCall::IServerImpl__RequestEvent, true, true); setProps(HookedCall::IServerImpl__RequestCancel, true, true); setProps(HookedCall::IServerImpl__MineAsteroid, true, true); setProps(HookedCall::IServerImpl__RequestCreateShip, true, true); setProps(HookedCall::IServerImpl__SPScanCargo, true, true); setProps(HookedCall::IServerImpl__SetManeuver, true, true); setProps(HookedCall::IServerImpl__InterfaceItemUsed, true, true); setProps(HookedCall::IServerImpl__AbortMission, true, true); setProps(HookedCall::IServerImpl__SetWeaponGroup, true, true); setProps(HookedCall::IServerImpl__SetVisitedState, true, true); setProps(HookedCall::IServerImpl__RequestBestPath, true, true); setProps(HookedCall::IServerImpl__RequestPlayerStats, true, true); setProps(HookedCall::IServerImpl__PopupDialog, true, true); setProps(HookedCall::IServerImpl__RequestGroupPositions, true, true); setProps(HookedCall::IServerImpl__SetInterfaceState, true, true); setProps(HookedCall::IServerImpl__RequestRankLevel, true, true); setProps(HookedCall::IServerImpl__InitiateTrade, true, true); setProps(HookedCall::IServerImpl__TerminateTrade, true, true); setProps(HookedCall::IServerImpl__AcceptTrade, true, true); setProps(HookedCall::IServerImpl__SetTradeMoney, true, true); setProps(HookedCall::IServerImpl__AddTradeEquip, true, true); setProps(HookedCall::IServerImpl__DelTradeEquip, true, true); setProps(HookedCall::IServerImpl__RequestTrade, true, true); setProps(HookedCall::IServerImpl__StopTradeRequest, true, true); setProps(HookedCall::IServerImpl__SubmitChat, true, true); }
155,746
C++
.cpp
4,423
31.517974
162
0.722431
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,376
HkInit.cpp
TheStarport_FLHook/source/HkInit.cpp
#include "Global.hpp" namespace IEngineHook { void __cdecl UpdateTime(double interval); void __stdcall ElapseTime(float interval); int __cdecl DockCall(const uint& shipId, const uint& spaceId, int flags, DOCK_HOST_RESPONSE response); int __cdecl FreeReputationVibe(int const& p1); void Naked__CShip__Init(); void Naked__CShip__Destroy(); void Naked__LaunchPosition(); void Naked__LoadReputationFromCharacterFile(); extern FARPROC g_OldInitCShip; extern FARPROC g_OldDestroyCShip; extern FARPROC g_OldLaunchPosition; extern FARPROC g_OldLoadReputationFromCharacterFile; } // namespace IEngine void __stdcall ShipDestroyed(DamageList* dmgList, DWORD* ecx, uint kill); void __stdcall NonGunWeaponHitsBaseBefore(char* ECX, char* p1, DamageList* dmg); void __stdcall SendChat(ClientId client, ClientId clientTo, uint size, void* rdl); extern FARPROC g_OldShipDestroyed; extern FARPROC g_OldNonGunWeaponHitsBase; extern FARPROC g_OldDamageHit, g_OldDamageHit2; extern FARPROC g_OldDisconnectPacketSent; extern FARPROC g_OldGuidedHit; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// PatchInfo piFLServerEXE = { "flserver.exe", 0x0400000, { { 0x041B094, &IEngineHook::UpdateTime, 4, 0, false }, { 0x041BAB0, &IEngineHook::ElapseTime, 4, 0, false }, { 0, 0, 0, 0 } // terminate } }; PatchInfo piContentDLL = { "content.dll", 0x6EA0000, { { 0x6FB358C, &IEngineHook::DockCall, 4, 0, false }, { 0, 0, 0, 0 } // terminate } }; PatchInfo piCommonDLL = { "common.dll", 0x6260000, { { 0x0639C138, &IEngineHook::Naked__CShip__Init, 4, &IEngineHook::g_OldInitCShip, false }, { 0x0639C064, &IEngineHook::Naked__CShip__Destroy, 4, &IEngineHook::g_OldDestroyCShip, false }, { 0, 0, 0, 0 } // terminate } }; PatchInfo piServerDLL = { "server.dll", 0x6CE0000, { { 0x6D67274, &Naked__ShipDestroyed, 4, &g_OldShipDestroyed, false }, { 0x6D641EC, &Naked__AddDamageEntry, 4, 0, false }, { 0x6D67320, &Naked__GuidedHit, 4, &g_OldGuidedHit, false }, { 0x6D65448, &Naked__GuidedHit, 4, 0, false }, { 0x6D67670, &Naked__GuidedHit, 4, 0, false }, { 0x6D653F4, &Naked__DamageHit, 4, &g_OldDamageHit, false }, { 0x6D672CC, &Naked__DamageHit, 4, 0, false }, { 0x6D6761C, &Naked__DamageHit, 4, 0, false }, { 0x6D65458, &Naked__DamageHit2, 4, &g_OldDamageHit2, false }, { 0x6D67330, &Naked__DamageHit2, 4, 0, false }, { 0x6D67680, &Naked__DamageHit2, 4, 0, false }, { 0x6D67668, &Naked__NonGunWeaponHitsBase, 4, &g_OldNonGunWeaponHitsBase, false }, { 0x6D6420C, &IEngineHook::Naked__LaunchPosition, 4, &IEngineHook::g_OldLaunchPosition, false }, { 0x6D648E0, &IEngineHook::FreeReputationVibe, 4, 0, false }, { 0, 0, 0, 0 } // terminate } }; PatchInfo piRemoteClientDLL = { "remoteclient.dll", 0x6B30000, { { 0x6B6BB80, &SendChat, 4, &RCSendChatMsg, false }, { 0, 0, 0, 0 } // terminate } }; PatchInfo piDaLibDLL = { "dalib.dll", 0x65C0000, { { 0x65C4BEC, &Naked__DisconnectPacketSent, 4, &g_OldDisconnectPacketSent, false }, { 0, 0, 0, 0 } // terminate } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool Patch(PatchInfo& pi) { HMODULE hMod = GetModuleHandle(pi.szBinName); if (!hMod) return false; for (uint i = 0; (i < sizeof(pi.piEntries) / sizeof(PatchInfoEntry)); i++) { if (!pi.piEntries[i].pAddress) break; char* pAddress = (char*)hMod + (pi.piEntries[i].pAddress - pi.pBaseAddress); if (!pi.piEntries[i].pOldValue) { pi.piEntries[i].pOldValue = new char[pi.piEntries[i].iSize]; pi.piEntries[i].bAlloced = true; } else pi.piEntries[i].bAlloced = false; ReadProcMem(pAddress, pi.piEntries[i].pOldValue, pi.piEntries[i].iSize); WriteProcMem(pAddress, &pi.piEntries[i].pNewValue, pi.piEntries[i].iSize); } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool RestorePatch(PatchInfo& pi) { HMODULE hMod = GetModuleHandle(pi.szBinName); if (!hMod) return false; for (uint i = 0; (i < sizeof(pi.piEntries) / sizeof(PatchInfoEntry)); i++) { if (!pi.piEntries[i].pAddress) break; char* pAddress = (char*)hMod + (pi.piEntries[i].pAddress - pi.pBaseAddress); WriteProcMem(pAddress, pi.piEntries[i].pOldValue, pi.piEntries[i].iSize); if (pi.piEntries[i].bAlloced) delete[] pi.piEntries[i].pOldValue; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// CDPClientProxy** clientProxyArray; CDPServer* cdpSrv; IClientImpl* FakeClient; IClientImpl* HookClient; char* OldClient; _CRCAntiCheat CRCAntiCheat; char* g_FLServerDataPtr; _GetShipInspect GetShipInspect; std::array<CLIENT_INFO, MaxClientId + 1> ClientInfo; char szRepFreeFixOld[5]; /************************************************************************************************************** clear the clientinfo **************************************************************************************************************/ void ClearClientInfo(ClientId client) { auto* info = &ClientInfo[client]; info->dieMsg = DIEMSG_ALL; info->ship = 0; info->shipOld = 0; info->tmSpawnTime = 0; info->lstMoneyFix.clear(); info->iTradePartner = 0; info->iBaseEnterTime = 0; info->iCharMenuEnterTime = 0; info->bCruiseActivated = false; info->tmKickTime = 0; info->iLastExitedBaseId = 0; info->bDisconnected = false; info->bCharSelected = false; info->tmF1Time = 0; info->tmF1TimeDisconnect = 0; DamageList dmg; info->dmgLast = dmg; info->dieMsgSize = CS_DEFAULT; info->chatSize = CS_DEFAULT; info->chatStyle = CST_DEFAULT; info->lstIgnore.clear(); info->wscHostname = L""; info->bEngineKilled = false; info->bThrusterActivated = false; info->bTradelane = false; info->iGroupId = 0; info->bSpawnProtected = false; // Reset the dmg list if this client was the inflictor for (auto& i : ClientInfo) { if (i.dmgLast.inflictorPlayerId == client) i.dmgLast = dmg; } Hk::Ini::CharacterClearClientInfo(client); CallPluginsAfter(HookedCall::FLHook__ClearClientInfo, client); } /************************************************************************************************************** load settings from flhookhuser.ini **************************************************************************************************************/ void LoadUserSettings(ClientId client) { auto* info = &ClientInfo[client]; CAccount const* acc = Players.FindAccountFromClientID(client); std::wstring dir = Hk::Client::GetAccountDirName(acc); std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; // read diemsg settings info->dieMsg = (DIEMSGTYPE)IniGetI(scUserFile, "settings", "DieMsg", DIEMSG_ALL); info->dieMsgSize = (CHATSIZE)IniGetI(scUserFile, "settings", "DieMsgSize", CS_DEFAULT); // read chatstyle settings info->chatSize = (CHATSIZE)IniGetI(scUserFile, "settings", "ChatSize", CS_DEFAULT); info->chatStyle = (CHATSTYLE)IniGetI(scUserFile, "settings", "ChatStyle", CST_DEFAULT); // read ignorelist info->lstIgnore.clear(); for (int i = 1;; i++) { std::wstring wscIgnore = IniGetWS(scUserFile, "IgnoreList", std::to_string(i), L""); if (!wscIgnore.length()) break; IGNORE_INFO ii; ii.character = GetParam(wscIgnore, ' ', 0); ii.wscFlags = GetParam(wscIgnore, ' ', 1); info->lstIgnore.push_back(ii); } } /************************************************************************************************************** load settings from flhookhuser.ini (specific to character) **************************************************************************************************************/ void LoadUserCharSettings(ClientId client) { CallPluginsAfter(HookedCall::FLHook__LoadCharacterSettings, client); } /************************************************************************************************************** install the callback hooks **************************************************************************************************************/ bool InitHookExports() { // init critial sections InitializeCriticalSection(&csIPResolve); DWORD dwId; DWORD dwParam[34]; // else release version crashes, dont ask me why... hThreadResolver = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadResolver, &dwParam, 0, &dwId); GetShipInspect = (_GetShipInspect)SRV_ADDR(ADDR_SRV_GETINSPECT); // install IServerImpl callbacks in remoteclient.dll auto* pServer = reinterpret_cast<char*>(&Server); memcpy(&pServer, pServer, 4); for (uint i = 0; i < std::size(IServerImplEntries); i++) { char* pAddress = pServer + IServerImplEntries[i].dwRemoteAddress; ReadProcMem(pAddress, &IServerImplEntries[i].fpOldProc, 4); WriteProcMem(pAddress, &IServerImplEntries[i].fpProc, 4); } // patch it Patch(piFLServerEXE); Patch(piContentDLL); Patch(piCommonDLL); Patch(piServerDLL); Patch(piRemoteClientDLL); Patch(piDaLibDLL); DetourSendComm(); // patch rep array free char szNOPs[] = { '\x90', '\x90', '\x90', '\x90', '\x90' }; char* pAddress = ((char*)hModServer + ADDR_SRV_REPARRAYFREE); ReadProcMem(pAddress, szRepFreeFixOld, 5); WriteProcMem(pAddress, szNOPs, 5); // patch flserver so it can better handle faulty house entries in char files // divert call to house load/save func pAddress = SRV_ADDR(0x679C6); char szDivertJump[] = { '\x6F' }; WriteProcMem(pAddress, szDivertJump, 1); // install hook at new address pAddress = SRV_ADDR(0x78B39); char szMovEAX[] = { '\xB8' }; char szJMPEAX[] = { '\xFF', '\xE0' }; FARPROC fpLoadRepFromCharFile = (FARPROC)IEngineHook::Naked__LoadReputationFromCharacterFile; WriteProcMem(pAddress, szMovEAX, 1); WriteProcMem(pAddress + 1, &fpLoadRepFromCharFile, 4); WriteProcMem(pAddress + 5, szJMPEAX, 2); IEngineHook::g_OldLoadReputationFromCharacterFile = (FARPROC)SRV_ADDR(0x78B40); // crc anti-cheat CRCAntiCheat = (_CRCAntiCheat)((char*)hModServer + ADDR_CRCANTICHEAT); // get CDPServer pAddress = DALIB_ADDR(ADDR_CDPSERVER); ReadProcMem(pAddress, &cdpSrv, 4); // read g_FLServerDataPtr(used for serverload calc) pAddress = FLSERVER_ADDR(ADDR_DATAPTR); ReadProcMem(pAddress, &g_FLServerDataPtr, 4); // some setting relate hooks HookRehashed(); // get client proxy array, used to retrieve player pings/ips pAddress = (char*)hModRemoteClient + ADDR_CPLIST; char* szTemp; ReadProcMem(pAddress, &szTemp, 4); szTemp += 0x10; memcpy(&clientProxyArray, &szTemp, 4); // init variables char szDataPath[MAX_PATH]; GetUserDataPath(szDataPath); CoreGlobals::i()->accPath = std::string(szDataPath) + "\\Accts\\MultiPlayer\\"; // Load DLLs for strings Hk::Message::LoadStringDLLs(); // clear ClientInfo for (uint i = 0; i < ClientInfo.size(); i++) { ClientInfo[i].iConnects = 0; // only set to 0 on start ClearClientInfo(i); } // Fix Refire bug std::array<byte, 22> refireBytes = {0x75, 0x0B, 0xC7, 0x84, 0x8C, 0x9C, 00, 00, 00, 00, 00, 00, 00, 0x41, 0x83, 0xC2, 0x04, 0x39, 0xC1, 0x7C, 0xE9, 0xEB }; WriteProcMem(SRV_ADDR(0x02C057), refireBytes.data(), 22); // Enable undocking announcer regardless of distance std::array<byte, 1> undockAnnouncerBytes = {0xEB}; WriteProcMem(SRV_ADDR(0x173da), undockAnnouncerBytes.data(), 1); return true; } void PatchClientImpl() { // install IClientImpl callback FakeClient = new IClientImpl; HookClient = &Client; memcpy(&OldClient, &Client, 4); WriteProcMem(&Client, FakeClient, 4); } /************************************************************************************************************** uninstall the callback hooks **************************************************************************************************************/ void UnloadHookExports() { char* pAddress; // uninstall IServerImpl callbacks in remoteclient.dll char* pServer = (char*)&Server; if (pServer) { memcpy(&pServer, pServer, 4); for (uint i = 0; i < std::size(IServerImplEntries); i++) { void* pAddress = (void*)((char*)pServer + IServerImplEntries[i].dwRemoteAddress); WriteProcMem(pAddress, &IServerImplEntries[i].fpOldProc, 4); } } // reset npc spawn setting Hk::Admin::ChangeNPCSpawn(false); // restore other hooks RestorePatch(piFLServerEXE); RestorePatch(piContentDLL); RestorePatch(piCommonDLL); RestorePatch(piServerDLL); RestorePatch(piRemoteClientDLL); RestorePatch(piDaLibDLL); UnDetourSendComm(); // unpatch rep array free pAddress = ((char*)GetModuleHandle("server.dll") + ADDR_SRV_REPARRAYFREE); WriteProcMem(pAddress, szRepFreeFixOld, 5); // unpatch flserver so it can better handle faulty house entries in char // files // undivert call to house load/save func pAddress = SRV_ADDR(0x679C6); char szDivertJump[] = { '\x76' }; // anti-death-msg char szOld[] = { '\x74' }; pAddress = SRV_ADDR(ADDR_ANTIdIEMSG); WriteProcMem(pAddress, szOld, 1); // plugins PluginManager::i()->unloadAll(); // Undo refire bug std::array<byte, 22> refireBytes = {0x74, 0x0A, 0x41, 0x83, 0xC2, 0x04, 0x3B, 0xC8, 0x7C, 0xF4, 0xEB, 0x0B, 0xC7, 0x84, 0x8C, 0x9C, 0, 0, 0, 0, 0, 0}; WriteProcMem(SRV_ADDR(0x02C057), refireBytes.data(), 22); // undocking announcer regardless of distance std::array<byte, 1> undockAnnouncerBytes = {0x74}; WriteProcMem(SRV_ADDR(0x173da), undockAnnouncerBytes.data(), 1); } /************************************************************************************************************** settings were rehashed sometimes adjustments need to be made after a rehash **************************************************************************************************************/ void HookRehashed() { char* pAddress; // anti-deathmsg if (FLHookConfig::i()->messages.dieMsg) { // disables the "old" "A Player has died: ..." messages char szJMP[] = { '\xEB' }; pAddress = SRV_ADDR(ADDR_ANTIdIEMSG); WriteProcMem(pAddress, szJMP, 1); } else { char szOld[] = { '\x74' }; pAddress = SRV_ADDR(ADDR_ANTIdIEMSG); WriteProcMem(pAddress, szOld, 1); } // charfile encyption(doesn't get disabled when unloading FLHook) if (FLHookConfig::i()->general.disableCharfileEncryption) { char szBuf[] = { '\x14', '\xB3' }; pAddress = SRV_ADDR(ADDR_DISCFENCR); WriteProcMem(pAddress, szBuf, 2); pAddress = SRV_ADDR(ADDR_DISCFENCR2); WriteProcMem(pAddress, szBuf, 2); } else { char szBuf[] = { '\xE4', '\xB4' }; pAddress = SRV_ADDR(ADDR_DISCFENCR); WriteProcMem(pAddress, szBuf, 2); pAddress = SRV_ADDR(ADDR_DISCFENCR2); WriteProcMem(pAddress, szBuf, 2); } // maximum group size if (FLHookConfig::i()->general.maxGroupSize > 0) { char cNewGroupSize = FLHookConfig::i()->general.maxGroupSize & 0xFF; pAddress = SRV_ADDR(ADDR_SRV_MAXGROUPSIZE); WriteProcMem(pAddress, &cNewGroupSize, 1); pAddress = SRV_ADDR(ADDR_SRV_MAXGROUPSIZE2); WriteProcMem(pAddress, &cNewGroupSize, 1); } else { // default char cNewGroupSize = 8; pAddress = SRV_ADDR(ADDR_SRV_MAXGROUPSIZE); WriteProcMem(pAddress, &cNewGroupSize, 1); pAddress = SRV_ADDR(ADDR_SRV_MAXGROUPSIZE2); WriteProcMem(pAddress, &cNewGroupSize, 1); } }
16,871
C++
.cpp
400
35.5875
157
0.579073
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,378
HkIEngine.cpp
TheStarport_FLHook/source/HkIEngine.cpp
#include "Global.hpp" /************************************************************************************************************** // misc flserver engine function hooks **************************************************************************************************************/ namespace IEngineHook { /************************************************************************************************************** // ship create & destroy **************************************************************************************************************/ FARPROC g_OldInitCShip; void __stdcall CShip__Init(CShip* ship) { CallPluginsAfter(HookedCall::IEngine__CShip__Init, ship); } __declspec(naked) void Naked__CShip__Init() { __asm { push ecx push [esp+8] call g_OldInitCShip call CShip__Init ret 4 } } FARPROC g_OldDestroyCShip; void __stdcall CShip__Destroy(CShip* ship) { CallPluginsBefore(HookedCall::IEngine__CShip__Destroy, ship); } __declspec(naked) void Naked__CShip__Destroy() { __asm { push ecx push ecx call CShip__Destroy pop ecx jmp g_OldDestroyCShip } } /************************************************************************************************************** // flserver memory leak bugfix **************************************************************************************************************/ int __cdecl FreeReputationVibe(int const& p1) { __asm { mov eax, p1 push eax mov eax, [hModServer] add eax, 0x65C20 call eax add esp, 4 } return Reputation::Vibe::Free(p1); } /************************************************************************************************************** **************************************************************************************************************/ void __cdecl UpdateTime(double interval) { CallPluginsBefore(HookedCall::IEngine__UpdateTime, interval); Timing::UpdateGlobalTime(interval); CallPluginsAfter(HookedCall::IEngine__UpdateTime, interval); } /************************************************************************************************************** **************************************************************************************************************/ uint g_LastTicks = 0; static void* dummy; void __stdcall ElapseTime(float interval) { CallPluginsBefore(HookedCall::IEngine__ElapseTime, interval); dummy = &Server; Server.ElapseTime(interval); CallPluginsAfter(HookedCall::IEngine__ElapseTime, interval); // low server load missile jitter bug fix uint curLoad = GetTickCount() - g_LastTicks; if (curLoad < 5) { uint fakeLoad = 5 - curLoad; Sleep(fakeLoad); } g_LastTicks = GetTickCount(); } /************************************************************************************************************** **************************************************************************************************************/ int __cdecl DockCall(const uint& shipId, const uint& spaceId, int dockPortIndex, DOCK_HOST_RESPONSE response) { // dockPortIndex == -1, response -> 2 --> Dock Denied! // dockPortIndex == -1, response -> 3 --> Dock in Use // dockPortIndex != -1, response -> 4 --> Dock ok, proceed (dockPortIndex starts from 0 for docking point 1) // dockPortIndex == -1, response -> 5 --> now DOCK! CallPluginsBefore(HookedCall::IEngine__DockCall, shipId, spaceId, dockPortIndex, response); int retVal = 0; TRY_HOOK { // Print out a message when a player ship docks. if (FLHookConfig::c()->messages.dockingMessages && response == PROCEED_DOCK) { const auto client = Hk::Client::GetClientIdByShip(shipId); if (client.has_value()) { std::wstring wscMsg = L"Traffic control alert: %player has requested to dock"; wscMsg = ReplaceStr(wscMsg, L"%player", (const wchar_t*)Players.GetActiveCharacterName(client.value())); PrintLocalUserCmdText(client.value(), wscMsg, 15000); } } // Actually dock retVal = pub::SpaceObj::Dock(shipId, spaceId, dockPortIndex, response); } CATCH_HOOK({}) CallPluginsAfter(HookedCall::IEngine__DockCall, shipId, spaceId, dockPortIndex, response); return retVal; } /************************************************************************************************************** **************************************************************************************************************/ FARPROC g_OldLaunchPosition; bool __stdcall LaunchPosition(uint spaceId, struct CEqObj& obj, Vector& position, Matrix& orientation, int dock) { auto [retVal, skip] = CallPluginsBefore<bool>(HookedCall::IEngine__LaunchPosition, spaceId, obj, position, orientation, dock); if (skip) return retVal; return obj.launch_pos(position, orientation, dock); } __declspec(naked) void Naked__LaunchPosition() { __asm { push ecx // 4 push [esp+8+8] // 8 push [esp+12+4] // 12 push [esp+16+0] // 16 push ecx push [ecx+176] call LaunchPosition pop ecx ret 0x0C } } /************************************************************************************************************** **************************************************************************************************************/ struct LOAD_REP_DATA { uint iRepId; float fAttitude; }; struct REP_DATA_LIST { uint iDunno; LOAD_REP_DATA* begin; LOAD_REP_DATA* end; }; bool __stdcall LoadReputationFromCharacterFile(REP_DATA_LIST* savedReps, LOAD_REP_DATA* repToSave) { // check of the rep id is valid if (repToSave->iRepId == 0xFFFFFFFF) return false; // rep id not valid! LOAD_REP_DATA* repIt = savedReps->begin; while (repIt != savedReps->end) { if (repIt->iRepId == repToSave->iRepId) return false; // we already saved this rep! repIt++; } // everything seems fine, add return true; } FARPROC g_OldLoadReputationFromCharacterFile; __declspec(naked) void Naked__LoadReputationFromCharacterFile() { __asm { push ecx // save ecx because thiscall push [esp+4+4+8] // rep data push ecx // rep data list call LoadReputationFromCharacterFile pop ecx // recover ecx test al, al jz abort_lbl jmp [g_OldLoadReputationFromCharacterFile] abort_lbl: ret 0x0C } } /************************************************************************************************************** **************************************************************************************************************/ } // namespace IEngine
6,729
C++
.cpp
183
32.639344
113
0.47076
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,379
Settings.cpp
TheStarport_FLHook/source/Settings.cpp
#include "Global.hpp" #include <refl.hpp> /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // setting variables /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::string FLHookConfig::File() { return "FLHook.json"; } void LoadSettings() { auto config = Serializer::JsonToObject<FLHookConfig>(); if (!config.socket.encryptionKey.empty()) { if (!config.socket.bfCTX) config.socket.bfCTX = static_cast<BLOWFISH_CTX*>(malloc(sizeof(BLOWFISH_CTX))); Blowfish_Init(static_cast<BLOWFISH_CTX*>(config.socket.bfCTX), reinterpret_cast<unsigned char*>(config.socket.encryptionKey.data()), static_cast<int>(config.socket.encryptionKey.length())); } // NoPVP config.general.noPVPSystemsHashed.clear(); for (const auto& system : config.general.noPVPSystems) { uint systemId; pub::GetSystemID(systemId, system.c_str()); config.general.noPVPSystemsHashed.emplace_back(systemId); } // No Beam Bases config.general.noBeamBasesHashed.clear(); for (const auto& base : config.general.noBeamBases) { config.general.noBeamBasesHashed.emplace_back(CreateID(base.c_str())); } auto ptr = std::make_unique<FLHookConfig>(config); FLHookConfig::i(&ptr); } #ifndef CORE_REFL #define CORE_REFL REFL_AUTO(type(FLHookConfig::General), field(antiDockKill), field(antiF1), field(changeCruiseDisruptorBehaviour), field(debugMode), field(disableCharfileEncryption), field(disconnectDelay), field(disableNPCSpawns), field(localTime), field(maxGroupSize), field(persistGroup), field(reservedSlots), field(torpMissileBaseDamageMultiplier), field(logPerformanceTimers), field(chatSuppressList), field(noPVPSystems), field(antiBaseIdle), field(antiCharMenuIdle), field(noBeamBases)); REFL_AUTO(type(FLHookConfig::Plugins), field(loadAllPlugins), field(plugins)); REFL_AUTO(type(FLHookConfig::Socket), field(activated), field(port), field(wPort), field(ePort), field(eWPort), field(encryptionKey), field(passRightsMap)); REFL_AUTO(type(FLHookConfig::Message), field(defaultLocalChat), field(echoCommands), field(suppressInvalidCommands), field(dieMsg), field(dockingMessages)); REFL_AUTO(type(FLHookConfig::MsgStyle), field(msgEchoStyle), field(deathMsgStyle), field(deathMsgStyleSys), field(kickMsgPeriod), field(kickMsg), field(userCmdStyle), field(adminCmdStyle), field(deathMsgTextAdminKill), field(deathMsgTextPlayerKill), field(deathMsgTextSelfKill), field(deathMsgTextNPC), field(deathMsgTextSuicide)); REFL_AUTO(type(FLHookConfig::UserCommands), field(userCmdSetDieMsg), field(userCmdSetDieMsgSize), field(userCmdSetChatFont), field(userCmdIgnore), field(userCmdHelp), field(userCmdMaxIgnoreList), field(defaultLocalChat)); REFL_AUTO(type(FLHookConfig::Bans), field(banAccountOnMatch), field(banWildcardsAndIPs)); REFL_AUTO(type(FLHookConfig::Callsign), field(allowedFormations), field(disableRandomisedFormations), field(disableUsingAffiliationForCallsign)); REFL_AUTO(type(FLHookConfig), field(general), field(plugins), field(socket), field(messages), field(userCommands), field(bans), field(callsign)); #endif
3,250
C++
.cpp
55
55.490909
161
0.72252
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,380
Exceptions.cpp
TheStarport_FLHook/source/Exceptions.cpp
#include "Global.hpp" #include "ExceptionInfo.h" #ifndef DISABLE_EXTENDED_EXCEPTION_LOGGING #include <psapi.h> HMODULE GetModuleAddr(uint iAddr) { HMODULE hModArr[1024]; DWORD iArrSizeNeeded; HANDLE hProcess = GetCurrentProcess(); if (EnumProcessModules(hProcess, hModArr, sizeof(hModArr), &iArrSizeNeeded)) { if (iArrSizeNeeded > sizeof(hModArr)) iArrSizeNeeded = sizeof(hModArr); iArrSizeNeeded /= sizeof(HMODULE); for (uint i = 0; i < iArrSizeNeeded; i++) { MODULEINFO mi; if (GetModuleInformation(hProcess, hModArr[i], &mi, sizeof(mi))) { if (((uint)mi.lpBaseOfDll) < iAddr && (uint)mi.lpBaseOfDll + (uint)mi.SizeOfImage > iAddr) { return hModArr[i]; } } } } return 0; } #include "dbghelp.h" #include <string.h> // based on dbghelp.h typedef BOOL(WINAPI* MINIdUMPWRITEDUMP)(HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); void WriteMiniDump(SEHException* ex) { AddLog(LogType::Normal, LogLevel::Err, "Attempting to write minidump..."); HMODULE hDll = ::LoadLibrary("DBGHELP.DLL"); if (hDll) { MINIdUMPWRITEDUMP pDump = (MINIdUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump"); if (pDump) { // put the dump file in the flhook logs/debug directory char szDumpPath[_MAX_PATH]; char szDumpPathFirst[_MAX_PATH]; time_t tNow = time(0); tm t; localtime_s(&t, &tNow); strftime(szDumpPathFirst, sizeof(szDumpPathFirst), "./logs/debug/flserver_%d.%m.%Y_%H.%M.%S", &t); int n = 1; do { sprintf_s(szDumpPath, "%s-%d.dmp", szDumpPathFirst, n); n++; } while (FileExists(szDumpPath)); // create the file HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { _MINIDUMP_EXCEPTION_INFORMATION ExInfo; if (ex) { ExInfo.ThreadId = ::GetCurrentThreadId(); EXCEPTION_POINTERS ep; ep.ContextRecord = &ex->context; ep.ExceptionRecord = &ex->record; ExInfo.ExceptionPointers = &ep; ExInfo.ClientPointers = NULL; pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL); } else { pDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, NULL, NULL, NULL); } ::CloseHandle(hFile); AddLog(LogType::Normal, LogLevel::Err, std::format("Minidump '{}' written.", szDumpPath)); } } } } #include "ExceptionInfo.h" #include "dbghelp.h" #include <Psapi.h> #include <io.h> #include <shlwapi.h> #include <string.h> void AddExceptionInfoLog(SEHException* ex) { if (!ex) { AddExceptionInfoLog(); return; } try { EXCEPTION_RECORD const* exception = &ex->record; _CONTEXT const* reg = &ex->context; if (exception) { DWORD iCode = exception->ExceptionCode; uint iAddr = (uint)exception->ExceptionAddress; uint iOffset = 0; HMODULE hModExc = GetModuleAddr(iAddr); char szModName[MAX_PATH] = ""; if (hModExc) { iOffset = iAddr - (uint)hModExc; GetModuleFileName(hModExc, szModName, sizeof(szModName)); } AddLog(LogType::Normal, LogLevel::Debug, std::format("Code={:X} Offset={:X} Module=\"{}\"", iCode, iOffset, szModName)); if (iCode == 0xE06D7363 && exception->NumberParameters == 3) // C++ exception { const auto* info = reinterpret_cast<const msvc__ThrowInfo*>(exception->ExceptionInformation[2]); const auto* typeArr = &info->pCatchableTypeArray->arrayOfCatchableTypes; const auto* obj = reinterpret_cast<const std::exception*>(exception->ExceptionInformation[1]); const char* szName = info && info->pCatchableTypeArray && info->pCatchableTypeArray->nCatchableTypes ? (*typeArr)[0]->pType->name : ""; int i = 0; for (; i < info->pCatchableTypeArray->nCatchableTypes; i++) { if (!strcmp(".?AVexception@@", (*typeArr)[i]->pType->name)) break; } const char* szMessage = i != info->pCatchableTypeArray->nCatchableTypes ? obj->what() : ""; // C++ exceptions are triggered by RaiseException in kernel32, // so use ebp to get the return address iOffset = 0; szModName[0] = 0; if (reg) { iAddr = *((*((uint**)reg->Ebp)) + 1); hModExc = GetModuleAddr(iAddr); if (hModExc) { iOffset = iAddr - (uint)hModExc; GetModuleFileName(hModExc, szModName, sizeof(szModName)); } } AddLog(LogType::Normal, LogLevel::Debug, std::format("Name=\"{}\" Message=\"{}\" Offset=0x{:08X} Module=\"{}\"", szName, szMessage, iOffset, strrchr(szModName, '\\') + 1)); } void* callers[62]; int count = CaptureStackBackTrace(0, 62, callers, NULL); for (int i = 0; i < count; i++) AddLog(LogType::Normal, LogLevel::Debug, std::vformat("{} called from {:#X}", std::make_format_args(i, callers[i]))); } else AddLog(LogType::Normal, LogLevel::Debug, "No exception information available"); if (reg) { AddLog(LogType::Normal, LogLevel::Debug, std::format("eax={:X} ebx={:X} ecx={:X} edx={:X} edi={:X} esi={:X} ebp={:X} eip={:X} esp={:X}", reg->Eax, reg->Ebx, reg->Ecx, reg->Edx, reg->Edi, reg->Esi, reg->Ebp, reg->Eip, reg->Esp)); } else { AddLog(LogType::Normal, LogLevel::Trace, "No register information available"); } } catch (...) { AddLog(LogType::Normal, LogLevel::Trace, "Exception in AddExceptionInfoLog!"); } } void AddExceptionInfoLog() { SEHException ex; ex.context = *GetCurrentExceptionContext(); ex.record = *GetCurrentExceptionRecord(); ex.code = ex.record.ExceptionCode; AddExceptionInfoLog(&ex); } #endif
5,882
C++
.cpp
183
27.923497
139
0.67019
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,381
HkIEngineDeath.cpp
TheStarport_FLHook/source/HkIEngineDeath.cpp
#include "Global.hpp" std::wstring SetSizeToSmall(const std::wstring& wscDataFormat) { return wscDataFormat.substr(0, 8) + L"90"; } /************************************************************************************************************** Send "Death: ..." chat-message **************************************************************************************************************/ void SendDeathMessage(const std::wstring& msg, uint systemId, ClientId clientVictim, ClientId clientKiller) { CallPluginsBefore(HookedCall::IEngine__SendDeathMessage, msg, systemId, clientVictim, clientKiller); // encode xml std::string(default and small) // non-sys std::wstring xmlMsg = L"<TRA data=\"" + FLHookConfig::i()->messages.msgStyle.deathMsgStyle + L"\" mask=\"-1\"/> <TEXT>"; xmlMsg += XMLText(msg); xmlMsg += L"</TEXT>"; char xmlBuf[0xFFFF]; uint ret; if(Hk::Message::FMsgEncodeXML(xmlMsg, xmlBuf, sizeof(xmlBuf), ret).has_error()) return; std::wstring styleSmall = SetSizeToSmall(FLHookConfig::i()->messages.msgStyle.deathMsgStyle); std::wstring xmlMsgSmall = std::wstring(L"<TRA data=\"") + styleSmall + L"\" mask=\"-1\"/> <TEXT>"; xmlMsgSmall += XMLText(msg); xmlMsgSmall += L"</TEXT>"; char bufSmall[0xFFFF]; uint retSmall; if (Hk::Message::FMsgEncodeXML(xmlMsgSmall, bufSmall, sizeof(bufSmall), retSmall).has_error()) return; // sys std::wstring xmlMsgSys = L"<TRA data=\"" + FLHookConfig::i()->messages.msgStyle.deathMsgStyleSys + L"\" mask=\"-1\"/> <TEXT>"; xmlMsgSys += XMLText(msg); xmlMsgSys += L"</TEXT>"; char bufSys[0xFFFF]; uint retSys; if (Hk::Message::FMsgEncodeXML(xmlMsgSys, bufSys, sizeof(bufSys), retSys).has_error()) return; std::wstring styleSmallSys = SetSizeToSmall(FLHookConfig::i()->messages.msgStyle.deathMsgStyleSys); std::wstring xmlMsgSmallSys = L"<TRA data=\"" + styleSmallSys + L"\" mask=\"-1\"/> <TEXT>"; xmlMsgSmallSys += XMLText(msg); xmlMsgSmallSys += L"</TEXT>"; char szBufSmallSys[0xFFFF]; uint retSmallSys; if (Hk::Message::FMsgEncodeXML(xmlMsgSmallSys, szBufSmallSys, sizeof(szBufSmallSys), retSmallSys).has_error()) return; // send // for all players PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { const auto client = playerData->iOnlineId; uint clientSystemId = 0; pub::Player::GetSystem(client, clientSystemId); char* sendXmlBuf; int sendXmlRet; char* sendXmlBufSys; int sendXmlSysRet; if (FLHookConfig::i()->userCommands.userCmdSetDieMsgSize && (ClientInfo[client].dieMsgSize == CS_SMALL)) { sendXmlBuf = bufSmall; sendXmlRet = retSmall; sendXmlBufSys = szBufSmallSys; sendXmlSysRet = retSmallSys; } else { sendXmlBuf = xmlBuf; sendXmlRet = ret; sendXmlBufSys = bufSys; sendXmlSysRet = retSys; } if (!FLHookConfig::i()->userCommands.userCmdSetDieMsg) { // /set diemsg disabled, thus send to all if (systemId == clientSystemId) Hk::Message::FMsgSendChat(client, sendXmlBufSys, sendXmlSysRet); else Hk::Message::FMsgSendChat(client, sendXmlBuf, sendXmlRet); continue; } if (ClientInfo[client].dieMsg == DIEMSG_NONE) continue; else if ((ClientInfo[client].dieMsg == DIEMSG_SYSTEM) && (systemId == clientSystemId)) Hk::Message::FMsgSendChat(client, sendXmlBufSys, sendXmlSysRet); else if ( (ClientInfo[client].dieMsg == DIEMSG_SELF) && ((client == clientVictim) || (client == clientKiller))) Hk::Message::FMsgSendChat(client, sendXmlBufSys, sendXmlSysRet); else if (ClientInfo[client].dieMsg == DIEMSG_ALL) { if (systemId == clientSystemId) Hk::Message::FMsgSendChat(client, sendXmlBufSys, sendXmlSysRet); else Hk::Message::FMsgSendChat(client, sendXmlBuf, sendXmlRet); } } } /************************************************************************************************************** Called when ship was destroyed **************************************************************************************************************/ void __stdcall ShipDestroyed(DamageList* dmgList, DWORD* ecx, uint kill) { CallPluginsBefore(HookedCall::IEngine__ShipDestroyed, dmgList, ecx, kill); TRY_HOOK { if (kill == 1) { CShip* cship = (CShip*)ecx[4]; ClientId client = cship->GetOwnerPlayer(); if (client) { // a player was killed DamageList dmg; try { dmg = *dmgList; } catch (...) { return; } std::wstring eventStr; eventStr.reserve(256); eventStr = L"kill"; uint systemId; pub::Player::GetSystem(client, systemId); wchar_t systemName[64]; swprintf_s(systemName, L"%u", systemId); if (!magic_enum::enum_integer(dmg.get_cause())) dmg = ClientInfo[client].dmgLast; DamageCause cause = dmg.get_cause(); const auto clientKiller = Hk::Client::GetClientIdByShip(dmg.get_inflictor_id()); std::wstring victimName = ToWChar(Players.GetActiveCharacterName(client)); eventStr += L" victim=" + victimName; if (clientKiller.has_value()) { std::wstring killType; switch (cause) { case DamageCause::Collision: killType = L"Collision"; break; case DamageCause::Gun: killType = L"Gun"; break; case DamageCause::MissileTorpedo: killType = L"Missile/Torpedo"; break; case DamageCause::CruiseDisrupter: case DamageCause::DummyDisrupter: case DamageCause::UnkDisrupter: killType = L"Cruise Disruptor"; break; case DamageCause::Mine: killType = L"Mine"; break; case DamageCause::Suicide: killType = L"Suicide"; break; default: killType = L"Somehow"; ; } std::wstring deathMessage; if (client == clientKiller.value() || cause == DamageCause::Suicide) { eventStr += L" type=selfkill"; deathMessage = ReplaceStr(FLHookConfig::i()->messages.msgStyle.deathMsgTextSelfKill, L"%victim", victimName); } else if (cause == DamageCause::Admin) { eventStr += L" type=admin"; deathMessage = ReplaceStr(FLHookConfig::i()->messages.msgStyle.deathMsgTextAdminKill, L"%victim", victimName); } else { eventStr += L" type=player"; std::wstring wscKiller = ToWChar(Players.GetActiveCharacterName(clientKiller.value())); eventStr += L" by=" + wscKiller; deathMessage = ReplaceStr(FLHookConfig::i()->messages.msgStyle.deathMsgTextPlayerKill, L"%victim", victimName); deathMessage = ReplaceStr(deathMessage, L"%killer", wscKiller); } deathMessage = ReplaceStr(deathMessage, L"%type", killType); if (FLHookConfig::i()->messages.dieMsg && deathMessage.length()) SendDeathMessage(deathMessage, systemId, client, clientKiller.value()); ProcessEvent(L"%s", eventStr.c_str()); } else if (dmg.get_inflictor_id()) { std::wstring killType; switch (cause) { case DamageCause::Collision: killType = L"Collision"; break; case DamageCause::Gun: break; case DamageCause::MissileTorpedo: killType = L"Missile/Torpedo"; break; case DamageCause::CruiseDisrupter: case DamageCause::DummyDisrupter: case DamageCause::UnkDisrupter: killType = L"Cruise Disruptor"; break; case DamageCause::Mine: killType = L"Mine"; break; default: killType = L"Gun"; } eventStr += L" type=npc"; std::wstring deathMessage = ReplaceStr(FLHookConfig::i()->messages.msgStyle.deathMsgTextNPC, L"%victim", victimName); deathMessage = ReplaceStr(deathMessage, L"%type", killType); if (FLHookConfig::i()->messages.dieMsg && deathMessage.length()) SendDeathMessage(deathMessage, systemId, client, 0); ProcessEvent(L"%s", eventStr.c_str()); } else if (cause == DamageCause::Suicide) { eventStr += L" type=suicide"; if (std::wstring deathMessage = ReplaceStr(FLHookConfig::i()->messages.msgStyle.deathMsgTextSuicide, L"%victim", victimName); FLHookConfig::i()->messages.dieMsg && !deathMessage.empty()) SendDeathMessage(deathMessage, systemId, client, 0); ProcessEvent(L"%s", eventStr.c_str()); } else if (cause == DamageCause::Admin) { if (std::wstring deathMessage = ReplaceStr(FLHookConfig::i()->messages.msgStyle.deathMsgTextAdminKill, L"%victim", victimName); FLHookConfig::i()->messages.dieMsg && deathMessage.length()) SendDeathMessage(deathMessage, systemId, client, 0); } else { std::wstring deathMessage = L"Death: " + victimName + L" has died"; if (FLHookConfig::i()->messages.dieMsg && deathMessage.length()) SendDeathMessage(deathMessage, systemId, client, 0); } } ClientInfo[client].shipOld = ClientInfo[client].ship; ClientInfo[client].ship = 0; } } CATCH_HOOK({}) } FARPROC g_OldShipDestroyed; __declspec(naked) void Naked__ShipDestroyed() { __asm { mov eax, [esp+0Ch] ; +4 mov edx, [esp+4] push ecx push edx push ecx push eax call ShipDestroyed pop ecx mov eax, [g_OldShipDestroyed] jmp eax } } /************************************************************************************************************** Called when base was destroyed **************************************************************************************************************/ void BaseDestroyed(uint objectId, ClientId clientBy) { CallPluginsBefore(HookedCall::IEngine__BaseDestroyed, objectId, clientBy); uint baseId; pub::SpaceObj::GetDockingTarget(objectId, baseId); Universe::IBase* base = Universe::get_base(baseId); const char* baseName = ""; if (base) { __asm { pushad mov ecx, [base] mov eax, [base] mov eax, [eax] call [eax+4] mov [baseName], eax popad } } ProcessEvent( L"basedestroy basename=%s basehash=%u solarhash=%u by=%s", stows(baseName).c_str(), objectId, baseId, ToWChar(Players.GetActiveCharacterName(clientBy))); }
10,129
C++
.cpp
284
30.735915
132
0.630914
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,382
CCmds.cpp
TheStarport_FLHook/source/CCmds.cpp
#include "Global.hpp" #define RIGHT_CHECK(a) \ if (!(this->rights & a)) \ { \ Print("ERR No permission"); \ return; \ } #define RIGHT_CHECK_SUPERADMIN() \ if (!(this->rights == RIGHT_SUPERADMIN)) \ { \ Print("ERR No permission"); \ return; \ } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetCash(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_CASH); const auto res = Hk::Player::GetCash(player); if (res.has_error()) { PrintError(res.error()); return; } Print(std::format("cash={}\nOK\n", res.value())); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdSetCash(const std::variant<uint, std::wstring>& player, uint iAmount) { RIGHT_CHECK(RIGHT_CASH); const auto res = Hk::Player::GetCash(player); if (res.has_error()) { PrintError(res.error()); return; } Hk::Player::AdjustCash(player, iAmount - res.value()); CmdGetCash(player); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdAddCash(const std::variant<uint, std::wstring>& player, uint amount) { RIGHT_CHECK(RIGHT_CASH); if (const auto res = Hk::Player::AddCash(player, amount); res.has_error()) { PrintError(res.error()); return; } CmdGetCash(player); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdKick(const std::variant<uint, std::wstring>& player, const std::wstring& reason) { RIGHT_CHECK(RIGHT_KICKBAN); if (const auto res = Hk::Player::KickReason(player, reason); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdBan(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_KICKBAN); if (const auto res = Hk::Player::Ban(player, true); res.has_error()) { PrintError(res.error()); return; } Print("Player banned"); CmdKick(player, L"Player banned"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdTempBan(const std::variant<uint, std::wstring>& player, uint duration) { if (!FLHookConfig::i()->general.tempBansEnabled) { Print("TempBan disabled"); return; } RIGHT_CHECK(RIGHT_KICKBAN); if (const auto res = Hk::Player::TempBan(player, duration); res.has_error()) { PrintError(res.error()); return; } Print("Player tempbanned"); CmdKick(player, L"Player tempbanned"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdUnban(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_KICKBAN); if (const auto res = Hk::Player::Ban(player, false); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetClientID(const std::wstring& player) { RIGHT_CHECK(RIGHT_OTHER); auto client = Hk::Client::GetClientIdFromCharName(player); if (client.has_error()) { PrintError(client.error()); return; } Print(std::format("clientid={}\nOK\n", client.value())); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdKill(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_BEAMKILL); if (const auto res = Hk::Player::Kill(player); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdResetRep(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_REPUTATION); if (const auto res = Hk::Player::ResetRep(player); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdSetRep(const std::variant<uint, std::wstring>& player, const std::wstring& repGroup, float value) { RIGHT_CHECK(RIGHT_REPUTATION); if (const auto res = Hk::Player::SetRep(player, repGroup, value); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetRep(const std::variant<uint, std::wstring>& player, const std::wstring& repGroup) { RIGHT_CHECK(RIGHT_REPUTATION); const auto res = Hk::Player::GetRep(player, repGroup); if ( res.has_error()) { PrintError(res.error()); return; } Print(std::format("feelings={}", res.value())); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdMsg(const std::variant<uint, std::wstring>& player, const std::wstring& text) { RIGHT_CHECK(RIGHT_MSG); if (const auto res = Hk::Message::Msg(player, text); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdMsgS(const std::wstring& system, const std::wstring& text) { RIGHT_CHECK(RIGHT_MSG); if (const auto res = Hk::Message::MsgS(system, text); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdMsgU(const std::wstring& text) { RIGHT_CHECK(RIGHT_MSG); if (const auto res = Hk::Message::MsgU(text); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdFMsg(const std::variant<uint, std::wstring>& player, const std::wstring& xml) { RIGHT_CHECK(RIGHT_MSG); if (const auto res = Hk::Message::FMsg(player, xml); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdFMsgS(const std::wstring& system, const std::wstring& xml) { RIGHT_CHECK(RIGHT_MSG); uint systemId; pub::GetSystemID(systemId, wstos(system).c_str()); if (!systemId) { Print("Invalid System"); return; } if (const auto res = Hk::Message::FMsgS(systemId, xml); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdFMsgU(const std::wstring& xml) { RIGHT_CHECK(RIGHT_MSG); if (const auto res = Hk::Message::FMsgU(xml); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdEnumCargo(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_CARGO); int holdSize = 0; auto cargo = Hk::Player::EnumCargo(player, holdSize); if (cargo.has_error()) { PrintError(cargo.error()); } Print(std::format("remainingholdsize={}", holdSize)); for (auto& item : cargo.value()) { if (!item.bMounted) Print(std::format("id={} archid={} count={} mission={}", item.iId, item.iArchId, item.iCount, item.bMission ? 1 : 0)); } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdRemoveCargo(const std::variant<uint, std::wstring>& player, ushort id, uint count) { RIGHT_CHECK(RIGHT_CARGO); if (const auto res = Hk::Player::RemoveCargo(player, id, count); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdAddCargo(const std::variant<uint, std::wstring>& player, const std::wstring& good, uint count, bool mission) { RIGHT_CHECK(RIGHT_CARGO); if (const auto res = Hk::Player::AddCargo(player, good, count, mission); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdRename(const std::variant<uint, std::wstring>& player, const std::wstring& newName) { RIGHT_CHECK(RIGHT_CHARACTERS); if (const auto res = Hk::Player::Rename(player, newName, false); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdDeleteChar(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_CHARACTERS); if (const auto res = Hk::Player::Rename(player, L"", true); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdReadCharFile(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_CHARACTERS); const auto res = Hk::Player::ReadCharFile(player); if (res.has_error()) { PrintError(res.error()); return; } for (const auto& line : res.value()) { Print(wstos(line)); } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdWriteCharFile(const std::variant<uint, std::wstring>& player, const std::wstring& data) { RIGHT_CHECK(RIGHT_CHARACTERS); if (const auto res = Hk::Player::WriteCharFile(player, data); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::PrintPlayerInfo(PlayerInfo& pi) { RIGHT_CHECK(RIGHT_OTHER); Print(wstos(std::format(L"charname={} clientid={} ip={} host={} ping={} base={} system={}", pi.character, pi.client, pi.wscIP, pi.wscHostname, pi.connectionInfo.dwRoundTripLatencyMS, pi.wscBase, pi.wscSystem))); } void CCmds::CmdGetPlayerInfo(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_OTHER); const auto res = Hk::Admin::GetPlayerInfo(player, false); if (res.has_error()) { PrintError(res.error()); return; } auto info = res.value(); PrintPlayerInfo(info); } void CCmds::CmdGetPlayers() { RIGHT_CHECK(RIGHT_OTHER); for (auto& p : Hk::Admin::GetPlayers()) PrintPlayerInfo(p); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::XPrintPlayerInfo(const PlayerInfo& pi) { RIGHT_CHECK(RIGHT_OTHER); Print(wstos(std::format(L"Name: {}, Id: {}, IP: {}, Host: {}, Ping: {}, Base: {}, System: {}\n", pi.character, pi.client, pi.wscIP, pi.wscHostname, pi.connectionInfo.dwRoundTripLatencyMS, pi.wscBase, pi.wscSystem))); } void CCmds::CmdXGetPlayerInfo(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_OTHER); const auto res = Hk::Admin::GetPlayerInfo(player, false); if (res.has_error()) { PrintError(res.error()); return; } XPrintPlayerInfo(res.value()); } void CCmds::CmdXGetPlayers() { RIGHT_CHECK(RIGHT_OTHER); for (const auto& p : Hk::Admin::GetPlayers()) XPrintPlayerInfo(p); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetPlayerIds() { RIGHT_CHECK(RIGHT_OTHER); for (auto& p : Hk::Admin::GetPlayers()) { Print(std::format("{} = {} | ", wstos(p.character), p.client)); } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetAccountDirName(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_OTHER); const auto acc = Hk::Client::GetAccountByCharName(std::get<std::wstring>(player)); if (acc.has_error()) { PrintError(acc.error()); return; } auto dir = Hk::Client::GetAccountDirName(acc.value()); Print(std::format("dirname={}\nOK", wstos(dir))); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetCharFileName(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_OTHER); const auto res = Hk::Client::GetCharFileName(player); if (res.has_error()) { PrintError(res.error()); return; } Print(std::format("filename={}", wstos(res.value()))); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdIsOnServer(const std::wstring& player) { RIGHT_CHECK(RIGHT_OTHER); const auto res = Hk::Client::GetAccountByCharName(player); if ( res.has_error()) { PrintError(res.error()); return; } const auto id = Hk::Client::GetClientIdFromAccount(res.value()); if (id.has_error()) Print("onserver=noOK\n"); else Print("onserver=yesOK\n"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdMoneyFixList() { RIGHT_CHECK(RIGHT_OTHER); PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { ClientId client = playerDb->iOnlineId; if (ClientInfo[client].lstMoneyFix.size()) Print(std::format("id={}", client)); } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdServerInfo() { RIGHT_CHECK(RIGHT_OTHER); // calculate uptime FILETIME ftCreation; FILETIME ft; GetProcessTimes(GetCurrentProcess(), &ftCreation, &ft, &ft, &ft); SYSTEMTIME st; GetSystemTime(&st); FILETIME ftNow; SystemTimeToFileTime(&st, &ftNow); int64 iTimeCreation = (((int64)ftCreation.dwHighDateTime) << 32) + ftCreation.dwLowDateTime; int64 iTimeNow = (((int64)ftNow.dwHighDateTime) << 32) + ftNow.dwLowDateTime; auto iUptime = static_cast<uint>((iTimeNow - iTimeCreation) / 10000000); uint iDays = (iUptime / (60 * 60 * 24)); iUptime %= (60 * 60 * 24); uint iHours = (iUptime / (60 * 60)); iUptime %= (60 * 60); uint iMinutes = (iUptime / 60); iUptime %= 60; uint iSeconds = iUptime; std::string time = std::format("{}:{}:{}:{}", iDays, iHours, iMinutes, iSeconds); // print Print(std::format( "serverload={} npcspawn={} uptime={}\nOK\n", CoreGlobals::c()->serverLoadInMs, CoreGlobals::c()->disableNpcs ? "disabled" : "enabled", time)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetGroupMembers(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_OTHER); const auto res = Hk::Player::GetGroupMembers(player); if (res.has_error()) { PrintError(res.error()); return; } Print(std::format("groupsize={}", res.value().size())); for (auto& m : res.value()) Print(std::format("id={} charname={}", m.client, wstos(m.character))); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdSaveChar(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_OTHER); if (const auto res = Hk::Player::SaveChar(player); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetReservedSlot(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK(RIGHT_SETTINGS); const auto res = Hk::Player::GetReservedSlot(player); if (res.has_error()) { PrintError(res.error()); return; } Print(std::format("reservedslot={}\nOK\n", res.value() ? "yes" : "no")); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdSetReservedSlot(const std::variant<uint, std::wstring>& player, int reservedSlot) { RIGHT_CHECK(RIGHT_SETTINGS); if (const auto res = Hk::Player::SetReservedSlot(player, reservedSlot ? true : false); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdSetAdmin(const std::variant<uint, std::wstring>& player, const std::wstring& playerRights) { RIGHT_CHECK_SUPERADMIN(); if (const auto res = Hk::Admin::SetAdmin(player, playerRights); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdGetAdmin(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK_SUPERADMIN(); const auto res = Hk::Admin::GetAdmin(player); if (res.has_error()) { PrintError(res.error()); return; } Print(std::format("rights={}\nOK\n", wstos(res.value()))); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdDelAdmin(const std::variant<uint, std::wstring>& player) { RIGHT_CHECK_SUPERADMIN(); if (const auto res = Hk::Admin::DelAdmin(player); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdLoadPlugins() { RIGHT_CHECK(RIGHT_PLUGINS); PluginManager::i()->loadAll(false, this); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdLoadPlugin(const std::wstring& wscPlugin) { RIGHT_CHECK(RIGHT_PLUGINS); PluginManager::i()->load(wscPlugin, this, false); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdReloadPlugin(const std::wstring& wscPlugin) { RIGHT_CHECK(RIGHT_PLUGINS); const auto unloadedPlugin = PluginManager::i()->unload(wstos(wscPlugin)); if (unloadedPlugin.has_error()) { PrintError(unloadedPlugin.error()); return; } PluginManager::i()->load(unloadedPlugin.value(), this, false); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdListPlugins() { RIGHT_CHECK(RIGHT_PLUGINS); for (const auto& data : PluginManager::ir()) Print(std::format("{} ({}) - {}", data->name, data->shortName, !data->paused ? "running" : "paused")); Print("OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdUnloadPlugin(const std::wstring& wscPlugin) { RIGHT_CHECK(RIGHT_PLUGINS); if (const auto res = PluginManager::i()->unload(wstos(wscPlugin)); res.has_error()) { PrintError(res.error()); return; } Print("OK"); } void CCmds::CmdShutdown() { RIGHT_CHECK(RIGHT_SUPERADMIN); Print("Shutting down Server"); // Kick everyone first and force a save PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { Hk::Player::SaveChar(playerDb->iOnlineId); Hk::Player::Kick(playerDb->iOnlineId); } PostMessageA(GetFLServerHwnd(), WM_CLOSE, 0, 0); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Chase a player. Only works in system as you'd need a client hook to do across system */ void CCmds::CmdChase(std::wstring adminName, const std::variant<uint, std::wstring>& player) { RIGHT_CHECK_SUPERADMIN(); const auto admin = Hk::Admin::GetPlayerInfo(adminName, false); if (admin.has_error()) { PrintError(admin.error()); return; } const auto target = Hk::Admin::GetPlayerInfo(player, false); if (target.has_error() || target.value().ship == 0) { Print("ERR Player not found or not in space."); return; } if (target.value().iSystem != admin.value().iSystem) { Print("ERR Player must be in the same system as you."); return; } Vector pos; Matrix ornt; pub::SpaceObj::GetLocation(target.value().ship, pos, ornt); pos.y += 100; Hk::Player::RelocateClient(admin.value().client, pos, ornt); return; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Beam admin to a base. Works across systems but needs improvement of the path * selection algorithm */ void CCmds::CmdBeam(const std::variant<uint, std::wstring>& player, const std::wstring& targetBaseName) { RIGHT_CHECK(RIGHT_BEAMKILL); try { if (Trim(targetBaseName).empty()) { PrintError(Error::InvalidBaseName); return; } const auto base = Hk::Solar::GetBaseByWildcard(targetBaseName); if (base.has_error()) { PrintError(base.error()); return; } const auto res = Hk::Player::Beam(player, base.value()->baseId); if (res.has_error()) { PrintError(res.error()); } } catch (...) { // exeption, kick player Hk::Player::Kick(player); Print("ERR exception occured, player kicked"); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Pull a player to you. Only works in system as you'd need a client hook to move their system **/ void CCmds::CmdPull(std::wstring adminName, const std::variant<uint, std::wstring>& player) { RIGHT_CHECK_SUPERADMIN(); if (const auto res = Hk::Admin::GetPlayerInfo(adminName, false); res.has_error()) { PrintError(res.error()); return; } const auto target = Hk::Admin::GetPlayerInfo(player, false); if (target.has_error() || target.value().ship == 0) { Print("ERR Player not found or not in space"); return; } Vector pos; Matrix ornt; pub::SpaceObj::GetLocation(target.value().ship, pos, ornt); pos.y += 400; Print(std::format("Jump to system={} x={:.2f} y={:.2f} z={:.2f}", wstos(target.value().wscSystem), pos.x, pos.y, pos.z)); return; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** Move to location */ void CCmds::CmdMove(std::wstring adminName, float x, float y, float z) { RIGHT_CHECK_SUPERADMIN(); const auto res = Hk::Admin::GetPlayerInfo(adminName, false); if (res.has_error()) { PrintError(res.error()); return; } Vector pos; Matrix rot; pub::SpaceObj::GetLocation(res.value().ship, pos, rot); pos.x = x; pos.y = y; pos.z = z; Print(std::format("Moving to {:.2f} {:.2f} {:.2f}", pos.x, pos.y, pos.z)); Hk::Player::RelocateClient(res.value().client, pos, rot); return; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::CmdHelp() { // TODO: Reimplement } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::wstring CCmds::ArgCharname(uint iArg) { std::wstring wscArg = GetParam(wscCurCmdString, ' ', iArg); if (iArg == 1) { if (bId) return wscArg.replace(0, 0, L"id "); else if (bShortCut) return wscArg.replace(0, 0, L"sc "); else if (bSelf) return this->GetAdminName(); else if (bTarget) { uint target = Hk::Player::GetTarget(this->GetAdminName()).value(); if (!target) return L""; auto targetId = Hk::Client::GetClientIdByShip(target); if (!targetId.has_error()) return L""; return L"id " + std::to_wstring(targetId.value()); } } { if (wscArg == L">s") return this->GetAdminName(); else if (wscArg.find(L">i") == 0) return L"id " + wscArg.substr(2); else if (wscArg == L">t") { uint target = Hk::Player::GetTarget(this->GetAdminName()).value(); if (!target) return L""; auto targetId = Hk::Client::GetClientIdByShip(target); if (!targetId.has_error()) return L""; return L"id " + std::to_wstring(targetId.value()); } else return wscArg; } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// int CCmds::ArgInt(uint iArg) { std::wstring wscArg = GetParam(wscCurCmdString, ' ', iArg); return ToInt(wscArg); } uint CCmds::ArgUInt(uint iArg) { std::wstring wscArg = GetParam(wscCurCmdString, ' ', iArg); return ToUInt(wscArg); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// float CCmds::ArgFloat(uint iArg) { std::wstring wscArg = GetParam(wscCurCmdString, ' ', iArg); return ToFloat(wscArg); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::wstring CCmds::ArgStr(uint iArg) { std::wstring wscArg = GetParam(wscCurCmdString, ' ', iArg); return wscArg; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::wstring CCmds::ArgStrToEnd(uint iArg) { for (uint i = 0, iCurArg = 0; (i < wscCurCmdString.length()); i++) { if (wscCurCmdString[i] == ' ') { iCurArg++; if (iCurArg == iArg) return wscCurCmdString.substr(i + 1); while (((i + 1) < wscCurCmdString.length()) && (wscCurCmdString[i + 1] == ' ')) i++; // skip "whitechar" } } return L""; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::ExecuteCommandString(const std::wstring& wscCmdStr) { // check if command was sent by a socket connection bool bSocket = false; std::wstring wscAdminName = GetAdminName(); if (wscAdminName.find(L"Socket connection") == 0) { bSocket = true; } try { if (bSocket) AddLog(LogType::SocketCmds, LogLevel::Info, std::format("{}: {}", wstos(wscAdminName).c_str(), wstos(wscCmdStr).c_str())); AddLog(LogType::AdminCmds, LogLevel::Info, std::format("{}: {}", wstos(wscAdminName).c_str(), wstos(wscCmdStr).c_str())); bId = false; bShortCut = false; bSelf = false; bTarget = false; wscCurCmdString = wscCmdStr; std::wstring wscCmd = ToLower(GetParam(wscCmdStr, ' ', 0)); if (wscCmd.length() == 0) { Print("ERR unknown command"); return; } size_t wscCmd_pos = wscCmdStr.find(wscCmd); if (wscCmd[wscCmd.length() - 1] == '$') { bId = true; wscCmd.erase(wscCmd.length() - 1, 1); } else if (wscCmd[wscCmd.length() - 1] == '&') { bShortCut = true; wscCmd.erase(wscCmd.length() - 1, 1); } else if (wscCmd[wscCmd.length() - 1] == '!') { bSelf = true; wscCurCmdString.insert(wscCmd_pos + wscCmd.length() - 1, L" "); wscCmd.erase(wscCmd.length() - 1, 1); } else if (wscCmd[wscCmd.length() - 1] == '?') { bTarget = true; wscCurCmdString.insert(wscCmd_pos + wscCmd.length() - 1, L" "); wscCmd.erase(wscCmd.length() - 1, 1); } if (const bool plugins = CallPluginsBefore(HookedCall::FLHook__AdminCommand__Process, this, wscCmd); !plugins) { if (wscCmd == L"getcash") { CmdGetCash(ArgCharname(1)); } else if (wscCmd == L"setcash") { CmdSetCash(ArgCharname(1), ArgUInt(2)); } else if (wscCmd == L"addcash") { CmdAddCash(ArgCharname(1), ArgUInt(2)); } else if (wscCmd == L"kick") { CmdKick(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"ban") { CmdBan(ArgCharname(1)); } else if (wscCmd == L"tempban") { CmdTempBan(ArgCharname(1), ArgUInt(2)); } else if (wscCmd == L"unban") { CmdUnban(ArgCharname(1)); } else if (wscCmd == L"getclientid") { CmdGetClientID(ArgCharname(1)); } else if (wscCmd == L"beam") { CmdBeam(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"kill") { CmdKill(ArgCharname(1)); } else if (wscCmd == L"resetrep") { CmdResetRep(ArgCharname(1)); } else if (wscCmd == L"setrep") { CmdSetRep(ArgCharname(1), ArgStr(2), ArgFloat(3)); } else if (wscCmd == L"getrep") { CmdGetRep(ArgCharname(1), ArgStr(2)); } else if (wscCmd == L"msg") { CmdMsg(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"msgs") { CmdMsgS(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"msgu") { CmdMsgU(ArgStrToEnd(1)); } else if (wscCmd == L"fmsg") { CmdFMsg(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"fmsgs") { CmdFMsgS(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"fmsgu") { CmdFMsgU(ArgStrToEnd(1)); } else if (wscCmd == L"enumcargo") { CmdEnumCargo(ArgCharname(1)); } else if (wscCmd == L"removecargo") { CmdRemoveCargo(ArgCharname(1), static_cast<ushort>(ArgInt(2)), ArgInt(3)); } else if (wscCmd == L"addcargo") { CmdAddCargo(ArgCharname(1), ArgStr(2), ArgInt(3), ArgInt(4)); } else if (wscCmd == L"rename") { CmdRename(ArgCharname(1), ArgStr(2)); } else if (wscCmd == L"deletechar") { CmdDeleteChar(ArgCharname(1)); } else if (wscCmd == L"readcharfile") { CmdReadCharFile(ArgCharname(1)); } else if (wscCmd == L"writecharfile") { CmdWriteCharFile(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"getplayerinfo") { CmdGetPlayerInfo(ArgCharname(1)); } else if (wscCmd == L"getplayers") { CmdGetPlayers(); } else if (wscCmd == L"xgetplayerinfo") { CmdXGetPlayerInfo(ArgCharname(1)); } else if (wscCmd == L"xgetplayers") { CmdXGetPlayers(); } else if (wscCmd == L"getplayerids") { CmdGetPlayerIds(); } else if (wscCmd == L"getaccountdirname") { CmdGetAccountDirName(ArgCharname(1)); } else if (wscCmd == L"getcharfilename") { CmdGetCharFileName(ArgCharname(1)); } else if (wscCmd == L"savechar") { CmdSaveChar(ArgCharname(1)); } else if (wscCmd == L"isonserver") { CmdIsOnServer(ArgCharname(1)); } else if (wscCmd == L"moneyfixlist") { CmdMoneyFixList(); } else if (wscCmd == L"serverinfo") { CmdServerInfo(); } else if (wscCmd == L"getgroupmembers") { CmdGetGroupMembers(ArgCharname(1)); } else if (wscCmd == L"getreservedslot") { CmdGetReservedSlot(ArgCharname(1)); } else if (wscCmd == L"setreservedslot") { CmdSetReservedSlot(ArgCharname(1), ArgInt(2)); } else if (wscCmd == L"setadmin") { CmdSetAdmin(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"getadmin") { CmdGetAdmin(ArgCharname(1)); } else if (wscCmd == L"deladmin") { CmdDelAdmin(ArgCharname(1)); } else if (wscCmd == L"unloadplugin") { CmdUnloadPlugin(ArgStrToEnd(1)); } else if (wscCmd == L"loadplugins") { CmdLoadPlugins(); } else if (wscCmd == L"reloadplugin") { CmdReloadPlugin(ArgStrToEnd(1)); } else if (wscCmd == L"loadplugin") { CmdLoadPlugin(ArgStrToEnd(1)); } else if (wscCmd == L"shutdown") { CmdShutdown(); } else if (wscCmd == L"listplugins") { CmdListPlugins(); } else if (wscCmd == L"help") { CmdHelp(); } else if (wscCmd == L"move") { CmdMove(wscAdminName, ArgFloat(1), ArgFloat(2), ArgFloat(3)); } else if (wscCmd == L"chase") { CmdChase(wscAdminName, ArgCharname(1)); } else if (wscCmd == L"beam") { CmdBeam(ArgCharname(1), ArgStrToEnd(2)); } else if (wscCmd == L"pull") { CmdPull(wscAdminName, ArgCharname(1)); } else { Print("ERR unknown command"); } } if (bSocket) { AddLog(LogType::SocketCmds, LogLevel::Info, "finished"); } else { AddLog(LogType::AdminCmds, LogLevel::Info, "finished"); } } catch (...) { if (bSocket) AddLog(LogType::SocketCmds, LogLevel::Info, "exception"); AddLog(LogType::AdminCmds, LogLevel::Info, "exception"); Print("ERR exception occured"); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::SetRightsByString(const std::string& scRights) { rights = RIGHT_NOTHING; std::string scRightStr = ToLower(scRights); if (scRightStr.find("superadmin") != -1) rights |= RIGHT_SUPERADMIN; if (scRightStr.find("cash") != -1) rights |= RIGHT_CASH; if (scRightStr.find("kickban") != -1) rights |= RIGHT_KICKBAN; if (scRightStr.find("beamkill") != -1) rights |= RIGHT_BEAMKILL; if (scRightStr.find("msg") != -1) rights |= RIGHT_MSG; if (scRightStr.find("other") != -1) rights |= RIGHT_OTHER; if (scRightStr.find("cargo") != -1) rights |= RIGHT_CARGO; if (scRightStr.find("characters") != -1) rights |= RIGHT_CHARACTERS; if (scRightStr.find("settings") != -1) rights |= RIGHT_SETTINGS; if (scRightStr.find("reputation") != -1) rights |= RIGHT_REPUTATION; if (scRightStr.find("plugins") != -1) rights |= RIGHT_PLUGINS; if (scRightStr.find("eventmode") != -1) rights |= RIGHT_EVENTMODE; if (scRightStr.find("special1") != -1) rights |= RIGHT_SPECIAL1; if (scRightStr.find("special2") != -1) rights |= RIGHT_SPECIAL2; if (scRightStr.find("special3") != -1) rights |= RIGHT_SPECIAL3; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::PrintError(Error err) { Print(std::format("ERR: {}", wstos(Hk::Err::ErrGetText(err)))); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCmds::Print(const std::string& text) { DoPrint(text); }
35,572
C++
.cpp
1,131
27.5084
148
0.51943
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,383
flcodec.cpp
TheStarport_FLHook/source/flcodec.cpp
/* Freelancer .FL Savegame encode/decoder Credits to Sherlog <sherlog@t-online.de> for finding out the algorithm (c) 2003 by Jor <flcodec@jors.net> This is free software. Permission to copy, store and use granted as long as this copyright note remains intact. Compilation in a POSIX environment: cc -O -o flcodec flcodec.c Or in Wintendo 32 (get the free lcc compiler): lcc -O flcodec.c lcclnk -o flcodec.exe flcodec.obj ******* EDITED by mc_horst for use in FLHook Updated 2022 to use proper C++ syntax and work in memory ~ Laz */ #include "Global.hpp" /* Very Secret Key - this is Microsoft Security In Action[tm] */ const char gene[] = "Gene"; std::string ReadFile(const char* input) { std::ifstream file(input, std::ios::binary); if (!file.is_open() || !file.good()) return {}; file.unsetf(std::ios::skipws); std::streampos fileSize; file.seekg(0, std::ios::end); fileSize = file.tellg(); file.seekg(0, std::ios::beg); std::string vec; vec.reserve(static_cast<uint>(fileSize)); vec.insert(vec.begin(), std::istream_iterator<BYTE>(file), std::istream_iterator<BYTE>()); return vec; } std::string FlcDecode(std::string& input) { if (!input.starts_with("FLS1")) { return {}; } std::string output; int i = 0; const int length = input.size() - 4; while (i < length) { auto c = static_cast<byte>(((&input[0]) + 4)[i]); auto k = static_cast<byte>((gene[i % 4] + i) % 256); byte r = c ^ (k | 0x80); output += r; i++; } return output; } std::string FlcEncode(std::string& input) { // Create our output vector, start with the magic string. std::string output = {'F', 'L', 'S', '1'}; const int length = input.size(); int i = 0; while (i < length) { byte c = (&input[0])[i]; auto k = static_cast<byte>((gene[i % 4] + i) % 256); byte r = c ^ (k | 0x80); output += r; i++; } return output; } bool EncodeDecode(const char* input, const char* output, bool encode) { auto undecodedBytes = ReadFile(input); const auto decodedBytes = encode ? FlcEncode(undecodedBytes) : FlcDecode(undecodedBytes); if (decodedBytes.empty()) { return false; } std::ofstream outputFile(output, std::ios::out | std::ios::binary); outputFile.write((char*)&decodedBytes[0], decodedBytes.size() * sizeof(byte)); outputFile.close(); return true; } bool FlcDecodeFile(const char* input, const char* outputFile) { return EncodeDecode(input, outputFile, false); } bool FlcEncodeFile(const char* input, const char* outputFile) { return EncodeDecode(input, outputFile, true); }
2,551
C++
.cpp
89
26.348315
91
0.698347
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,387
HkIEngineDisconnect.cpp
TheStarport_FLHook/source/HkIEngineDisconnect.cpp
#include "Global.hpp" /////////////////////////////////////////////////////////////////////////////////////////////////////////////// int __stdcall DisconnectPacketSent(ClientId client) { TRY_HOOK { uint ship = 0; pub::Player::GetShip(client, ship); if (FLHookConfig::i()->general.disconnectDelay && ship) { // in space ClientInfo[client].tmF1TimeDisconnect = Hk::Time::GetUnixMiliseconds() + FLHookConfig::i()->general.disconnectDelay; return 0; // don't pass on } } CATCH_HOOK({}) return 1; // pass on } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// FARPROC g_OldDisconnectPacketSent; __declspec(naked) void Naked__DisconnectPacketSent() { __asm { pushad mov eax, [esi+0x68] push eax call DisconnectPacketSent cmp eax, 0 jz suppress popad jmp [g_OldDisconnectPacketSent] suppress: popad mov eax, [hModDaLib] add eax, ADDR_DALIB_DISC_SUPPRESS jmp eax } }
1,051
C++
.cpp
37
23.918919
119
0.515423
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,388
Lights.cpp
TheStarport_FLHook/source/Data/Lights.cpp
#include "Global.hpp" void DataManager::LoadLights() { INI_Reader ini; if (!ini.open("freelancer.ini", false)) return; std::vector<std::string> equipmentFiles; ini.find_header("Data"); while (ini.read_value()) { if (ini.is_value("equipment")) { equipmentFiles.emplace_back(ini.get_value_string()); } } ini.close(); for (const auto& file : equipmentFiles) { if (!ini.open(std::format("{}\\{}", this->dataPath, file).c_str(), false)) continue; while (ini.read_header()) { if (!ini.is_header("Light")) continue; Light light; while (ini.read_value()) { if (ini.is_value("nickname")) { light.nickname = ini.get_value_string(); light.archId = CreateID(light.nickname.c_str()); } else if (ini.is_value("inherit")) { const auto inherited = lights.find(CreateID(ini.get_value_string())); if (inherited == lights.end()) continue; light.alwaysOn = inherited->second.alwaysOn; light.bulbSize = inherited->second.bulbSize; light.glowSize = inherited->second.glowSize; light.intensity = inherited->second.intensity; light.glowColor = inherited->second.glowColor; light.color = inherited->second.color; light.minColor = inherited->second.minColor; light.dockingLight = inherited->second.dockingLight; light.flareConeMin = inherited->second.flareConeMin; light.flareConeMax = inherited->second.flareConeMax; light.lightSourceCone = inherited->second.lightSourceCone; light.blinks = inherited->second.blinks; light.delay = inherited->second.delay; light.blinkDuration = inherited->second.blinkDuration; } else if (ini.is_value("bulb_size")) { light.bulbSize = ini.get_value_float(0); } else if (ini.is_value("glow_size")) { light.glowSize = ini.get_value_float(0); } else if (ini.is_value("flare_cone")) { light.flareConeMin = ini.get_value_float(0); light.flareConeMax = ini.get_value_float(1); } else if (ini.is_value("blink_duration")) { light.blinks = true; light.blinkDuration = ini.get_value_float(0); } else if (ini.is_value("avg_delay")) { light.delay = ini.get_value_float(0); } else if (ini.is_value("color")) { light.color = ini.get_vector(); } else if (ini.is_value("min_color")) { light.minColor = ini.get_vector(); } else if (ini.is_value("glow_color")) { light.glowColor = ini.get_vector(); } else if (ini.is_value("intensity")) { light.intensity = ini.get_value_float(0); } else if (ini.is_value("lightsource_cone")) { light.lightSourceCone = ini.get_value_int(0); } else if (ini.is_value("always_on")) { light.alwaysOn = ini.get_value_bool(0); } else if (ini.is_value("docking_light")) { light.dockingLight = ini.get_value_bool(0); } } if (!light.nickname.empty()) lights[light.archId] = std::move(light); } } Console::ConInfo(std::format("Loaded {} Lights.", lights.size())); } const std::map<EquipId, Light>& DataManager::GetLights() const { return lights; } cpp::result<const Light&, Error> DataManager::FindLightByHash(EquipId hash) const { const auto light = lights.find(hash); if (light == lights.end()) { return cpp::fail(Error::NicknameNotFound); } return light->second; }
3,397
C++
.cpp
122
23.434426
81
0.653174
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,389
SendComm.cpp
TheStarport_FLHook/source/Hooks/SendComm.cpp
#include <Global.hpp> #include <Tools/Detour.hpp> #include <Tools/Typedefs.hpp> using SendCommType = int(__cdecl*)(uint, uint, uint, const Costume*, uint, uint*, int, uint, float, bool); const std::unique_ptr<FunctionDetour<SendCommType>> func = std::make_unique<FunctionDetour<SendCommType>>(pub::SpaceObj::SendComm); int SendComm(uint fromShipId, uint toShipId, uint voiceId, const Costume* costume, uint infocardId, uint* a5, int a6, uint infocardId2, float a8, bool a9) { if (auto* ship = (CShip*)CObject::Find(toShipId, CObject::Class::CSHIP_OBJECT); ship) { if (ship->is_player()) { const auto client = ship->GetOwnerPlayer(); const auto& ci = ClientInfo[client]; const auto* conf = FLHookConfig::c(); static std::array<byte, 8> num1RewriteBytes = {0xBA, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90, 0x90}; const auto content = DWORD(GetModuleHandle("content.dll")); constexpr DWORD factionOffset = 0x6fb632c + 18 - 0x6ea0000; constexpr DWORD numberOffset1 = 0x6eeb49b - 0x6ea0000; constexpr DWORD numberOffset2 = 0x6eeb523 + 1 - 0x6ea0000; constexpr DWORD formationOffset = 0x6fb7524 + 25 - 0x6ea0000; const auto playerFactionAddr = PVOID(content + factionOffset); const auto playerNumber1 = PVOID(content + numberOffset1); const auto playerNumber2 = PVOID(content + numberOffset2); const auto playerFormation = PCHAR(content + formationOffset); if (!conf->callsign.disableRandomisedFormations) { *(int*)(num1RewriteBytes.data() + 1) = ci.formationNumber1; WriteProcMem(playerNumber1, num1RewriteBytes.data(), num1RewriteBytes.size()); WriteProcMem(playerNumber2, &ci.formationNumber2, 1); DWORD _; VirtualProtect(playerFormation, 2, PAGE_READWRITE, &_); std::sprintf(playerFormation, "%02d", ci.formationTag); } if (!conf->callsign.disableUsingAffiliationForCallsign) { if (auto repGroupNick = Hk::Ini::GetFromPlayerFile(client, L"rep_group"); repGroupNick.has_value() && repGroupNick.value().length() - 4 <= 6) { auto val = wstos(repGroupNick.value()); WriteProcMem(playerFactionAddr, val.erase(val.size() - 4).c_str(), val.size()); } else { WriteProcMem(playerFactionAddr, "player", 6); } } } ship->Release(); } func->UnDetour(); const int res = func->GetOriginalFunc()(fromShipId, toShipId, voiceId, costume, infocardId, a5, a6, infocardId2, a8, a9); func->Detour(SendComm); return res; } void DetourSendComm() { func->Detour(SendComm); } void UnDetourSendComm() { func->UnDetour(); }
2,535
C++
.cpp
61
38.131148
154
0.72229
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,390
GenerateCertificate.cpp
TheStarport_FLHook/source/Tools/GenerateCertificate.cpp
#include "Global.hpp" #include <openssl/pem.h> #include <openssl/x509.h> /* Generates a self-signed x509 certificate. */ X509* GenerateX509(EVP_PKEY* pkey) { /* Allocate memory for the X509 structure. */ X509* x509 = X509_new(); if (!x509) { Console::ConErr(L"Unable to create X509 structure."); return nullptr; } /* Set the serial number. */ ASN1_INTEGER_set(X509_get_serialNumber(x509), 1); /* This certificate is valid from now until exactly one year from now. */ X509_gmtime_adj(X509_get_notBefore(x509), 0); X509_gmtime_adj(X509_get_notAfter(x509), 31536000L); /* Set the public key for our certificate. */ X509_set_pubkey(x509, pkey); /* We want to copy the subject name to the issuer name. */ auto* name = X509_get_subject_name(x509); /* Set the country code and common name. */ X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, reinterpret_cast<unsigned char*>("CA"), -1, -1, 0); X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, reinterpret_cast<unsigned char*>("FLServer"), -1, -1, 0); X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, reinterpret_cast<unsigned char*>("localhost"), -1, -1, 0); /* Now set the issuer name. */ X509_set_issuer_name(x509, name); /* Actually sign the certificate with our key. */ if (!X509_sign(x509, pkey, EVP_sha1())) { Console::ConErr(L"Error signing certificate."); X509_free(x509); return nullptr; } return x509; } bool WriteToDisk(EVP_PKEY* pkey, X509* x509) { /* Open the PEM file for writing the key to disk. */ FILE* pkey_file = fopen("key.pem", "wb"); if (!pkey_file) { Console::ConErr(L"Unable to open \"key.pem\" for writing."); return false; } /* Write the key to disk. */ bool ret = PEM_write_PrivateKey(pkey_file, pkey, nullptr, nullptr, 0, nullptr, nullptr); fclose(pkey_file); if (!ret) { Console::ConErr(L"Unable to write private key to disk."); return false; } /* Open the PEM file for writing the certificate to disk. */ FILE* x509_file = fopen("cert.pem", "wb"); if (!x509_file) { Console::ConErr(L"Unable to open \"cert.pem\" for writing."); return false; } /* Write the certificate to disk. */ ret = PEM_write_X509(x509_file, x509); fclose(x509_file); if (!ret) { Console::ConErr(L"Unable to write certificate to disk."); return false; } return true; } void GenerateCertificate() { Console::ConInfo(L"Generating Certificate and PEM"); Console::ConInfo(L"Generating RSA key"); EVP_PKEY* key = EVP_RSA_gen(2048); if (!key) { Console::ConWarn(L"Unable to generate 2048-bit RSA key"); return; } /* Generate the certificate. */ Console::ConInfo(L"Generating X509 certificate"); X509* x509 = GenerateX509(key); if (!x509) { Console::ConWarn(L"Unable to generate X509 cert"); EVP_PKEY_free(key); return; } const bool ret = WriteToDisk(key, x509); EVP_PKEY_free(key); X509_free(x509); if (!ret) { Console::ConWarn(L"Unable to write certificate and key to disk."); } else { Console::ConInfo(L"Certificate and key written to disk."); } }
3,028
C++
.cpp
102
27.411765
112
0.698555
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,391
Mqtt.cpp
TheStarport_FLHook/source/Tools/Mqtt.cpp
#include "Global.hpp" #include <mqtt/async_client.h> std::tuple<mqtt::async_client_ptr, mqtt::connect_options_ptr, mqtt::callback_ptr> ConnectBroker() { const auto config = FLHookConfig::c(); auto connOpts = std::make_shared<mqtt::connect_options>(); connOpts->set_automatic_reconnect(5, 120); auto client = std::make_shared<mqtt::async_client>("tcp://localhost:1883", "FLServer"); auto cb = std::make_shared<callback>(); client->set_callback(*cb); try { ConPrint(L"MQTT: connecting...\n"); mqtt::token_ptr conntok = client->connect(*connOpts); // Wait for connection to be established TODO: This just waits if the // mqtt server is down and lags the server ConPrint(L"MQTT: Waiting for connection...\n"); conntok->wait(); ConPrint(L"MQTT: Connected\n"); // Subscribe to /allplayers const std::string TOPIC("allplayers"); client->subscribe(TOPIC, 0); } catch (const mqtt::exception& exc) { ConPrint(L"MQTT: error " + stows(exc.what()) + L"\n"); } return std::make_tuple(client, connOpts, cb); } void SetupMessageQueue() { }
1,065
C++
.cpp
32
31
97
0.711782
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,392
Console.cpp
TheStarport_FLHook/source/Tools/Console.cpp
#include "Global.hpp" #include <intrin.h> void Console::Log(const std::string& str, void* addr) { unsigned long iCharsWritten; std::string text = str + "\n"; // Get DLL Name if (HMODULE hmod; RtlPcToFileHeader(addr, (void**)&hmod)) { CHAR sz[MAX_PATH]; // If successful, prepend if (GetModuleFileName(hmod, sz, MAX_PATH)) { std::string path = sz; text = std::string("(") + wstos(GetTimeString(FLHookConfig::i()->general.localTime)) + path.substr(path.find_last_of("\\") + 1) + ") " + text; } } WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), text.c_str(), DWORD(text.length()), &iCharsWritten, nullptr); // Reset SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD(ConsoleColor::WHITE)); } void Console::ConPrint(const std::string& str) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD(ConsoleColor::STRONG_WHITE)); Log(str, _ReturnAddress()); } void Console::ConErr(const std::string& str) { const auto newStr = "ERR: " + str; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD(ConsoleColor::STRONG_RED)); Log(newStr, _ReturnAddress()); } void Console::ConWarn(const std::string& str) { const auto newStr = "WARN: " + str; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD(ConsoleColor::STRONG_YELLOW)); Log(newStr, _ReturnAddress()); } void Console::ConInfo(const std::string& str) { const auto newStr = "INFO: " + str; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD(ConsoleColor::STRONG_CYAN)); Log(newStr, _ReturnAddress()); } void Console::ConDebug(const std::string& str) { if (!FLHookConfig::i()->general.debugMode) return; const auto newStr = "DEBUG: " + str; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), WORD(ConsoleColor::STRONG_GREEN)); Log(newStr, _ReturnAddress()); }
1,810
C++
.cpp
52
32.730769
145
0.733945
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,393
MemoryManager.cpp
TheStarport_FLHook/source/Memory/MemoryManager.cpp
#include "MemoryManager.hpp" void MemoryManager::AddHooks() { SaveGameDetour::InitHook(); } void MemoryManager::RemoveHooks() { SaveGameDetour::DestroyHook(); }
164
C++
.cpp
9
16.888889
33
0.798701
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,394
SaveData.cpp
TheStarport_FLHook/source/Memory/SaveData.cpp
#include "MemoryManager.hpp" #include <Tools/Detour.hpp> using GetUserDataPathSig = bool (*)(char*); bool SaveGameDetour::GetUserDataPathDetour(char* retPtr) { const auto* i = dynamic_cast<SaveGameDetour*>(MemoryManager::i()); const auto len = i->path.size(); strncpy(retPtr, i->path.c_str(), len + 1); return true; } std::string SaveGameDetour::GetSaveDataPath() const { INI_Reader ini; ini.open("dacom.ini", false); ini.find_header("DACOM"); std::string saveDataPath = ExpandEnvironmentVariables(std::string(R"(%UserProfile%\My Documents\My Games\Freelancer)")); while (ini.read_value()) { if (ini.is_value("SavePath")) { saveDataPath = ExpandEnvironmentVariables(std::string(ini.get_value_string())); } } const std::filesystem::path trimmed = Trim(saveDataPath); try { if (trimmed.empty()) { throw std::runtime_error("SavePath was not defined, but INI key existed within dacom.ini"); } if (!std::filesystem::exists(trimmed)) { std::filesystem::create_directories(trimmed); } } catch (const std::exception& ex) { MessageBox(GetFLServerHwnd(), ex.what(), "Unable to handle SavePath", MB_ICONERROR); } return trimmed.string(); } const auto detour = std::make_unique<FunctionDetour<GetUserDataPathSig>>(GetUserDataPathSig(GetProcAddress(GetModuleHandle("common.dll"), "?GetUserDataPath@@YA_NQAD@Z"))); void SaveGameDetour::InitHook() { detour->Detour(GetUserDataPathDetour); path = std::format("{}\0", GetSaveDataPath()); char arr[255]; GetUserDataPath(arr); } void SaveGameDetour::DestroyHook() { detour->UnDetour(); }
1,593
C++
.cpp
54
27.12963
155
0.737188
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,396
Player.cpp
TheStarport_FLHook/source/Helpers/Player.cpp
#include "Global.hpp" #include "Features/TempBan.hpp" namespace Hk::Player { using _FLAntiCheat = void(__stdcall*)(); using _FLPossibleCheatingDetected = void(__stdcall*)(int iReason); constexpr auto AddrAntiCheat1 = 0x70120; constexpr auto AddrAntiCheat2 = 0x6FD20; constexpr auto AddrAntiCheat3 = 0x6FAF0; constexpr auto AddrAntiCheat4 = 0x6FAA0; constexpr auto PossibleCheatingDetectedAddr = 0x6F570; cpp::result<void, Error> AddToGroup(ClientId client, uint iGroupId) { if (!Client::IsValidClientID(client)) return cpp::fail(Error::InvalidClientId); if (const uint groupId = Players.GetGroupID(client); groupId == iGroupId) return cpp::fail(Error::InvalidGroupId); CPlayerGroup* group = CPlayerGroup::FromGroupID(iGroupId); if (!group) return cpp::fail(Error::InvalidGroupId); group->AddMember(client); return {}; } cpp::result<const uint, Error> GetGroupID(ClientId client) { if (!Client::IsValidClientID(client)) return cpp::fail(Error::InvalidClientId); return Players.GetGroupID(client); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const uint, Error> GetCash(const std::variant<uint, std::wstring>& player) { if (ClientId client = Hk::Client::ExtractClientID(player); client != UINT_MAX) { if (Client::IsInCharSelectMenu(client)) return cpp::fail(Error::CharacterNotSelected); int cash; pub::Player::InspectCash(client, cash); return static_cast<uint>(cash); } if (!player.index()) return cpp::fail(Error::InvalidClientId); const auto acc = Hk::Client::GetAccountByCharName(std::get<std::wstring>(player)); if (acc.has_error()) return cpp::fail(acc.error()); auto dir = Hk::Client::GetAccountDirName(acc.value()); auto file = Client::GetCharFileName(player); if (file.has_error()) return cpp::fail(file.error()); std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; FILE* fTest; fopen_s(&fTest, scCharFile.c_str(), "r"); if (!fTest) return cpp::fail(Error::CharacterDoesNotExist); else fclose(fTest); if (Client::IsEncoded(scCharFile)) { const std::string scCharFileNew = scCharFile + ".ini"; if (!FlcDecodeFile(scCharFile.c_str(), scCharFileNew.c_str())) return cpp::fail(Error::CouldNotDecodeCharFile); auto cash = static_cast<uint>(IniGetI(scCharFileNew, "Player", "money", -1)); DeleteFile(scCharFileNew.c_str()); return cash; } return static_cast<uint>(IniGetI(scCharFile, "Player", "money", -1)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> AdjustCash(const std::variant<uint, std::wstring>& player, int iAmount) { ClientId client = Hk::Client::ExtractClientID(player); if (client != UINT_MAX) { if (Client::IsInCharSelectMenu(client)) return cpp::fail(Error::CharacterNotSelected); pub::Player::AdjustCash(client, iAmount); return {}; } if (!player.index()) { return cpp::fail(Error::InvalidClientId); } const auto& character = std::get<std::wstring>(player); const auto acc = Hk::Client::GetAccountByCharName(std::get<std::wstring>(player)); if (acc.has_error()) return cpp::fail(acc.error()); auto dir = Hk::Client::GetAccountDirName(acc.value()); const auto file = Client::GetCharFileName(character); if (file.has_error()) return cpp::fail(file.error()); std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; int iRet; if (Client::IsEncoded(scCharFile)) { std::string scCharFileNew = scCharFile + ".ini"; if (!FlcDecodeFile(scCharFile.c_str(), scCharFileNew.c_str())) return cpp::fail(Error::CouldNotDecodeCharFile); iRet = IniGetI(scCharFileNew, "Player", "money", -1); // Add a space to the value so the ini file line looks like "<key> = // <value>" otherwise IFSO can't decode the file correctly IniWrite(scCharFileNew, "Player", "money", " " + std::to_string(iRet + iAmount)); if (!FLHookConfig::i()->general.disableCharfileEncryption && !FlcEncodeFile(scCharFileNew.c_str(), scCharFile.c_str())) return cpp::fail(Error::CouldNotEncodeCharFile); DeleteFile(scCharFileNew.c_str()); } else { iRet = IniGetI(scCharFile, "Player", "money", -1); // Add a space to the value so the ini file line looks like "<key> = // <value>" otherwise IFSO can't decode the file correctly IniWrite(scCharFile, "Player", "money", " " + std::to_string(iRet + iAmount)); } if (client != UINT_MAX) { // money fix in case player logs in with this account bool bFound = false; std::wstring characterLower = ToLower(character); for (auto& money : ClientInfo[client].lstMoneyFix) { if (money.character == characterLower) { money.uAmount += iAmount; bFound = true; break; } } if (!bFound) { MONEY_FIX mf; mf.character = characterLower; mf.uAmount = iAmount; ClientInfo[client].lstMoneyFix.push_back(mf); } } return {}; } cpp::result<void, Error> AddCash(const std::variant<uint, std::wstring>& player, uint uAmount) { return AdjustCash(player, static_cast<int>(uAmount)); } cpp::result<void, Error> RemoveCash(const std::variant<uint, std::wstring>& player, uint uAmount) { return AdjustCash(player, -static_cast<int>(uAmount)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> Kick(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); CAccount* acc = Players.FindAccountFromClientID(client); acc->ForceLogout(); return {}; } cpp::result<void, Error> KickReason(const std::variant<uint, std::wstring>& player, const std::wstring& wscReason) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); if (wscReason.length()) MsgAndKick(client, wscReason, FLHookConfig::i()->messages.msgStyle.kickMsgPeriod); else Players.FindAccountFromClientID(client)->ForceLogout(); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> Ban(const std::variant<uint, std::wstring>& player, bool bBan) { auto acc = Hk::Client::ExtractAccount(player); if (acc.has_error()) return cpp::fail(Error::CharacterDoesNotExist); auto id = Client::GetAccountID(acc.value()); if (id.has_error()) return cpp::fail(id.error()); st6::wstring flStr((ushort*)id.value().c_str()); Players.BanAccount(flStr, bBan); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> TempBan(const std::variant<uint, std::wstring>& player, uint duration) { uint clientId; if (player.index() != 0) { const auto& charName = std::get<std::wstring>(player); auto client = Hk::Client::GetClientIdFromCharName(charName); if (client.has_error()) { return cpp::fail(client.error()); } clientId = client.value(); } else { clientId = std::get<uint>(player); } if (!Hk::Client::IsValidClientID(clientId)) return cpp::fail(Error::InvalidClientId); TempBanManager::i()->AddTempBan(clientId, duration); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> Beam(const std::variant<uint, std::wstring>& player, const std::variant<uint, std::wstring>& baseVar) { ClientId client = Hk::Client::ExtractClientID(player); uint baseId; // check if logged in if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } // check if ship in space if (const auto ship = Hk::Player::GetShip(client); ship.has_error()) { return cpp::fail(ship.error()); } // if basename was passed as string if (baseVar.index() == 1) { const std::string baseName = wstos(std::get<std::wstring>(baseVar)); // get base id if (pub::GetBaseID(baseId, baseName.c_str()) == -4) { return cpp::fail(Error::InvalidBaseName); } } else { baseId = std::get<uint>(baseVar); } if (std::ranges::find(FLHookConfig::c()->general.noBeamBasesHashed, baseId) != FLHookConfig::c()->general.noBeamBasesHashed.end()) { return cpp::fail(Error::InvalidBaseName); } uint iSysId; pub::Player::GetSystem(client, iSysId); const Universe::IBase* base = Universe::get_base(baseId); if (!base) { return cpp::fail(Error::InvalidBase); } pub::Player::ForceLand(client, baseId); // beam // if not in the same system, emulate F1 charload if (base->systemId != iSysId) { Server.BaseEnter(baseId, client); Server.BaseExit(baseId, client); auto fileName = Client::GetCharFileName(client); if (fileName.has_error()) { return cpp::fail(fileName.error()); } const std::wstring newFile = fileName.value() + L".fl"; CHARACTER_ID cId; strcpy_s(cId.szCharFilename, wstos(newFile.substr(0, 14)).c_str()); Server.CharacterSelect(cId, client); } return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> SaveChar(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); void* pJmp = (char*)hModServer + 0x7EFA8; char szNop[2] = {'\x90', '\x90'}; char szTestAlAl[2] = {'\x74', '\x44'}; WriteProcMem(pJmp, szNop, sizeof(szNop)); // nop the SinglePlayer() check pub::Save(client, 1); WriteProcMem(pJmp, szTestAlAl, sizeof(szTestAlAl)); // restore return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct EQ_ITEM { EQ_ITEM* next; uint i2; ushort s1; ushort sId; uint iGoodId; CacheString hardpoint; bool bMounted; char sz[3]; float fStatus; uint iCount; bool bMission; }; cpp::result<const std::list<CARGO_INFO>, Error> EnumCargo(const std::variant<uint, std::wstring>& player, int& iRemainingHoldSize) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX || Client::IsInCharSelectMenu(client)) return cpp::fail(Error::PlayerNotLoggedIn); std::list<CARGO_INFO> cargo; char* szClassPtr; memcpy(&szClassPtr, &Players, 4); szClassPtr += 0x418 * (client - 1); EQ_ITEM* eqLst; memcpy(&eqLst, szClassPtr + 0x27C, 4); EQ_ITEM* eq; eq = eqLst->next; while (eq != eqLst) { CARGO_INFO ci = {eq->sId, (int)eq->iCount, eq->iGoodId, eq->fStatus, eq->bMission, eq->bMounted, eq->hardpoint}; cargo.push_back(ci); eq = eq->next; } float fRemHold; pub::Player::GetRemainingHoldSize(client, fRemHold); iRemainingHoldSize = (int)fRemHold; return cargo; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> RemoveCargo(const std::variant<uint, std::wstring>& player, ushort cargoId, int count) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX || Hk::Client::IsInCharSelectMenu(client)) return cpp::fail(Error::PlayerNotLoggedIn); int iHold; const auto cargo = EnumCargo(player, iHold); if (cargo.has_error()) { return cpp::fail(cargo.error()); } for (auto& item : cargo.value()) { if ((item.iId == cargoId) && (item.iCount < count)) count = item.iCount; // trying to remove more than actually there } pub::Player::RemoveCargo(client, cargoId, count); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> AddCargo(const std::variant<uint, std::wstring>& player, uint iGoodId, int iCount, bool bMission) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX || Hk::Client::IsInCharSelectMenu(client)) return cpp::fail(Error::PlayerNotLoggedIn); // add const GoodInfo* gi; if (!(gi = GoodList::find_by_id(iGoodId))) return cpp::fail(Error::InvalidGood); bool bMultiCount; memcpy(&bMultiCount, (char*)gi + 0x70, 1); uint iBase = 0; pub::Player::GetBase(client, iBase); uint iLocation = 0; pub::Player::GetLocation(client, iLocation); // trick cheat detection if (iBase) { if (iLocation) Server.LocationExit(iLocation, client); Server.BaseExit(iBase, client); if (!Hk::Client::IsValidClientID(client)) // got cheat kicked return cpp::fail(Error::PlayerNotLoggedIn); } if (bMultiCount) { // it's a good that can have multiple units(commodities missile ammo, etc) int ret; // we need to do this, else server or client may crash for (const auto cargo = EnumCargo(player, ret); auto& item : cargo.value()) { if ((item.iArchId == iGoodId) && (item.bMission != bMission)) { RemoveCargo(player, static_cast<ushort>(item.iId), item.iCount); iCount += item.iCount; } } pub::Player::AddCargo(client, iGoodId, iCount, 1, bMission); } else { for (int i = 0; (i < iCount); i++) pub::Player::AddCargo(client, iGoodId, 1, 1, bMission); } if (iBase) { // player docked on base /////////////////////////////////////////////////// // fix, else we get anti-cheat msg when undocking // this DOES NOT disable anti-cheat-detection, we're // just making some adjustments so that we dont get kicked Server.BaseEnter(iBase, client); if (iLocation) Server.LocationEnter(iLocation, client); } return {}; } cpp::result<void, Error> AddCargo(const std::variant<uint, std::wstring>& player, const std::wstring& wscGood, int iCount, bool bMission) { uint iGoodId = ToInt(wscGood.c_str()); if (!iGoodId) pub::GetGoodID(iGoodId, wstos(wscGood).c_str()); if (!iGoodId) return cpp::fail(Error::InvalidGood); return AddCargo(player, iGoodId, iCount, bMission); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> Rename(const std::variant<uint, std::wstring>& player, const std::wstring& wscNewCharname, bool bOnlyDelete) { ClientId client = Hk::Client::ExtractClientID(player); if ((client == UINT_MAX) && player.index() && !Hk::Client::GetAccountByClientID(client)) return cpp::fail(Error::CharacterDoesNotExist); if (!bOnlyDelete && Hk::Client::GetAccountByCharName(wscNewCharname)) return cpp::fail(Error::AlreadyExists); if (!bOnlyDelete && (wscNewCharname.length() > 23)) return cpp::fail(Error::CharacterNameTooLong); if (!bOnlyDelete && !wscNewCharname.length()) return cpp::fail(Error::CharacterNameTooShort); INI_Reader ini; if (!bOnlyDelete && !(ini.open("..\\DATA\\CHARACTERS\\newcharacter.ini", false))) return cpp::fail(Error::MpNewCharacterFileNotFoundOrInvalid); CAccount* acc; std::wstring oldCharName; if (client != UINT_MAX) { acc = Players.FindAccountFromClientID(client); oldCharName = (wchar_t*)Players.GetActiveCharacterName(client); } else { oldCharName = std::get<std::wstring>(player); acc = Hk::Client::GetAccountByCharName(std::get<std::wstring>(player)).value(); } const std::wstring wscAccountDirname = Hk::Client::GetAccountDirName(acc); const auto newFileName = Hk::Client::GetCharFileName(wscNewCharname); if (newFileName.has_error()) { return cpp::fail(newFileName.error()); } const auto oldFileName = Hk::Client::GetCharFileName(oldCharName); if (oldFileName.has_error()) { return cpp::fail(oldFileName.error()); } std::string scNewCharfilePath = CoreGlobals::c()->accPath + wstos(wscAccountDirname) + "\\" + wstos(newFileName.value()) + ".fl"; std::string scOldCharfilePath = CoreGlobals::c()->accPath + wstos(wscAccountDirname) + "\\" + wstos(oldFileName.value()) + ".fl"; if (bOnlyDelete) { // delete character st6::wstring str((ushort*)oldCharName.c_str()); Hk::Client::LockAccountAccess(acc, true); // also kicks player on this account Players.DeleteCharacterFromName(str); Hk::Client::UnlockAccountAccess(acc); return {}; } Hk::Client::LockAccountAccess(acc, true); // kick player if online Hk::Client::UnlockAccountAccess(acc); // Copy existing char file into tmp std::string scTmpPath = scOldCharfilePath + ".tmp"; DeleteFile(scTmpPath.c_str()); CopyFile(scOldCharfilePath.c_str(), scTmpPath.c_str(), FALSE); // Delete existing char otherwise a rename of the char in slot 5 fails. st6::wstring str((ushort*)oldCharName.c_str()); Players.DeleteCharacterFromName(str); // Emulate char create SLoginInfo logindata; wcsncpy_s(logindata.wszAccount, Hk::Client::GetAccountID(acc).value().c_str(), 36); Players.login(logindata, MaxClientId + 1); SCreateCharacterInfo newcharinfo; wcsncpy_s(newcharinfo.wszCharname, wscNewCharname.c_str(), 23); newcharinfo.wszCharname[23] = 0; newcharinfo.iNickName = 0; newcharinfo.iBase = 0; newcharinfo.iPackage = 0; newcharinfo.iPilot = 0; while (ini.read_header()) { if (ini.is_header("Faction")) { while (ini.read_value()) { if (ini.is_value("nickname")) newcharinfo.iNickName = CreateID(ini.get_value_string()); else if (ini.is_value("base")) newcharinfo.iBase = CreateID(ini.get_value_string()); else if (ini.is_value("Package")) newcharinfo.iPackage = CreateID(ini.get_value_string()); else if (ini.is_value("Pilot")) newcharinfo.iPilot = CreateID(ini.get_value_string()); } break; } } ini.close(); if (newcharinfo.iNickName == 0) newcharinfo.iNickName = CreateID("new_player"); if (newcharinfo.iBase == 0) newcharinfo.iBase = CreateID("Li01_01_Base"); if (newcharinfo.iPackage == 0) newcharinfo.iPackage = CreateID("ge_fighter"); if (newcharinfo.iPilot == 0) newcharinfo.iPilot = CreateID("trent"); // Fill struct with valid data (though it isnt used it is needed) newcharinfo.iDunno[4] = 65536; newcharinfo.iDunno[5] = 65538; newcharinfo.iDunno[6] = 0; newcharinfo.iDunno[7] = 1058642330; newcharinfo.iDunno[8] = 3206125978; newcharinfo.iDunno[9] = 65537; newcharinfo.iDunno[10] = 0; newcharinfo.iDunno[11] = 3206125978; newcharinfo.iDunno[12] = 65539; newcharinfo.iDunno[13] = 65540; newcharinfo.iDunno[14] = 65536; newcharinfo.iDunno[15] = 65538; Server.CreateNewCharacter(newcharinfo, MaxClientId + 1); SaveChar(wscNewCharname); Players.logout(MaxClientId + 1); // Decode the backup of the old char and overwrite the new char file if (!FlcDecodeFile(scTmpPath.c_str(), scNewCharfilePath.c_str())) { // file wasn't encoded, thus // simply rename it DeleteFile(scNewCharfilePath.c_str()); // just to get sure... CopyFile(scTmpPath.c_str(), scNewCharfilePath.c_str(), FALSE); } DeleteFile(scTmpPath.c_str()); // Update the char name in the new char file. // Add a space to the value so the ini file line looks like "<key> = // <value>" otherwise Ioncross Server Operator can't decode the file // correctly std::string scValue = " "; for (uint i = 0; (i < wscNewCharname.length()); i++) { char cHiByte = wscNewCharname[i] >> 8; char cLoByte = wscNewCharname[i] & 0xFF; char szBuf[8]; sprintf_s(szBuf, "%02X%02X", ((uint)cHiByte) & 0xFF, ((uint)cLoByte) & 0xFF); scValue += szBuf; } IniWrite(scNewCharfilePath, "Player", "Name", scValue); // Re-encode the char file if needed. if (!FLHookConfig::i()->general.disableCharfileEncryption && !FlcEncodeFile(scNewCharfilePath.c_str(), scNewCharfilePath.c_str())) return cpp::fail(Error::CouldNotEncodeCharFile); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> MsgAndKick(ClientId client, const std::wstring& wscReason, uint iIntervall) { if (!ClientInfo[client].tmKickTime) { std::wstring wscMsg = ReplaceStr(FLHookConfig::i()->messages.msgStyle.kickMsg, L"%reason", XMLText(wscReason)); Hk::Message::FMsg(client, wscMsg); ClientInfo[client].tmKickTime = Hk::Time::GetUnixMiliseconds() + iIntervall; } return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> Kill(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); // check if logged in if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); uint ship; pub::Player::GetShip(client, ship); if (!ship) return cpp::fail(Error::PlayerNotInSpace); pub::SpaceObj::SetRelativeHealth(ship, 0.0f); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<bool, Error> GetReservedSlot(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); const CAccount* acc; if (client != UINT_MAX) acc = Players.FindAccountFromClientID(client); else acc = player.index() ? Hk::Client::GetAccountByCharName(std::get<std::wstring>(player)).value() : nullptr; if (!acc) return cpp::fail(Error::CharacterDoesNotExist); const auto dir = Hk::Client::GetAccountDirName(acc); std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; return IniGetB(scUserFile, "Settings", "ReservedSlot", false); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> SetReservedSlot(const std::variant<uint, std::wstring>& player, bool bReservedSlot) { auto acc = Hk::Client::ExtractAccount(player); if (acc.has_error()) return cpp::fail(Error::CharacterDoesNotExist); const auto dir = Hk::Client::GetAccountDirName(acc.value()); std::string scUserFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; if (bReservedSlot) IniWrite(scUserFile, "Settings", "ReservedSlot", "yes"); else IniWrite(scUserFile, "Settings", "ReservedSlot", "no"); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> ResetRep(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); // check if logged in if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); INI_Reader ini; if (!ini.open("mpnewcharacter.fl", false)) return cpp::fail(Error::MpNewCharacterFileNotFoundOrInvalid); ini.read_header(); if (!ini.is_header("Player")) { ini.close(); return cpp::fail(Error::MpNewCharacterFileNotFoundOrInvalid); } int iPlayerRep; pub::Player::GetRep(client, iPlayerRep); while (ini.read_value()) { if (ini.is_value("house")) { float fRep = ini.get_value_float(0); const char* szRepGroupName = ini.get_value_string(1); uint iRepGroupId; pub::Reputation::GetReputationGroup(iRepGroupId, szRepGroupName); pub::Reputation::SetReputation(iPlayerRep, iRepGroupId, fRep); } } ini.close(); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> SetRep(const std::variant<uint, std::wstring>& player, const std::wstring& wscRepGroup, float fValue) { ClientId client = Hk::Client::ExtractClientID(player); // check if logged in if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); uint iRepGroupId; pub::Reputation::GetReputationGroup(iRepGroupId, wstos(wscRepGroup).c_str()); if (iRepGroupId == -1) return cpp::fail(Error::InvalidRepGroup); int iPlayerRep; pub::Player::GetRep(client, iPlayerRep); pub::Reputation::SetReputation(iPlayerRep, iRepGroupId, fValue); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<float, Error> GetRep(const std::variant<uint, std::wstring>& player, const std::variant<uint, std::wstring>& repGroup) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); uint repGroupId; if (repGroup.index() == 1) { pub::Reputation::GetReputationGroup(repGroupId, wstos(std::get<std::wstring>(repGroup)).c_str()); if (repGroupId == UINT_MAX) return cpp::fail(Error::InvalidRepGroup); } else { repGroupId = std::get<uint>(repGroup); } int playerRep; pub::Player::GetRep(client, playerRep); float playerFactionRep; pub::Reputation::GetGroupFeelingsTowards(playerRep, repGroupId, playerFactionRep); return playerFactionRep; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<std::vector<GroupMember>, Error> GetGroupMembers(const std::variant<uint, std::wstring>& player) { std::vector<GroupMember> members; ClientId client = Hk::Client::ExtractClientID(player); // check if logged in if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); // hey, at least it works! beware of the VC optimiser. st6::vector<uint> vMembers; pub::Player::GetGroupMembers(client, vMembers); for (uint i : vMembers) { GroupMember gm = {i, (wchar_t*)Players.GetActiveCharacterName(i)}; members.push_back(gm); } return members; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<std::list<std::wstring>, Error> ReadCharFile(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); std::wstring dir; cpp::result<CAccount*, Error> acc; if (client != UINT_MAX) { acc = Players.FindAccountFromClientID(client); if (const wchar_t* wszCharname = (wchar_t*)Players.GetActiveCharacterName(client); !wszCharname) return cpp::fail(Error::CharacterNotSelected); dir = Hk::Client::GetAccountDirName(acc.value()); } else { acc = Hk::Client::ExtractAccount(player); if (!acc) return cpp::fail(Error::CharacterDoesNotExist); } auto file = Hk::Client::GetCharFileName(player); if (file.has_error()) { return cpp::fail(file.error()); } std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; std::string scFileToRead; bool bDeleteAfter; if (Hk::Client::IsEncoded(scCharFile)) { std::string scCharFileNew = scCharFile + ".ini"; if (!FlcDecodeFile(scCharFile.c_str(), scCharFileNew.c_str())) return cpp::fail(Error::CouldNotDecodeCharFile); scFileToRead = scCharFileNew; bDeleteAfter = true; } else { scFileToRead = scCharFile; bDeleteAfter = false; } std::ifstream ifs; ifs.open(scFileToRead.c_str(), std::ios_base::in); if (!ifs.is_open()) return cpp::fail(Error::UnknownError); std::list<std::wstring> output; std::string scLine; while (getline(ifs, scLine)) output.emplace_back(stows(scLine)); ifs.close(); if (bDeleteAfter) DeleteFile(scFileToRead.c_str()); return output; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> WriteCharFile(const std::variant<uint, std::wstring>& player, std::wstring wscData) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::InvalidClientId); } const auto acc = Players.FindAccountFromClientID(client); if (const wchar_t* wszCharname = (wchar_t*)Players.GetActiveCharacterName(client); !wszCharname) return cpp::fail(Error::CharacterNotSelected); auto dir = Hk::Client::GetAccountDirName(acc); const auto file = Hk::Client::GetCharFileName(player); if (file.has_error()) { return cpp::fail(file.error()); } std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; std::string scFileToWrite; bool bEncode; if (Hk::Client::IsEncoded(scCharFile)) { scFileToWrite = scCharFile + ".ini"; bEncode = true; } else { scFileToWrite = scCharFile; bEncode = false; } std::ofstream ofs; ofs.open(scFileToWrite.c_str(), std::ios_base::out); if (!ofs.is_open()) return cpp::fail(Error::UnknownError); size_t iPos; while ((iPos = wscData.find(L"\\n")) != -1) { std::wstring wscLine = wscData.substr(0, iPos); ofs << wstos(wscLine) << std::endl; wscData.erase(0, iPos + 2); } if (wscData.length()) ofs << wstos(wscData); ofs.close(); if (bEncode) { FlcEncodeFile(scFileToWrite.c_str(), scCharFile.c_str()); DeleteFile(scFileToWrite.c_str()); } return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> PlayerRecalculateCRC(ClientId client) { try { const PlayerData* pd = &Players[client]; char* ACCalcCRC = (char*)hModServer + 0x6FAF0; __asm { pushad mov ecx, [pd] call[ACCalcCRC] mov ecx, [pd] mov[ecx + 320h], eax popad } } catch (...) { return cpp::fail(Error::InvalidClientId); } return {}; } /** Move the client to the specified location */ void RelocateClient(ClientId client, Vector vDestination, const Matrix& mOrientation) { Quaternion qRotation = Math::MatrixToQuaternion(mOrientation); FLPACKET_LAUNCH pLaunch; pLaunch.ship = ClientInfo[client].ship; pLaunch.iBase = 0; pLaunch.iState = 0xFFFFFFFF; pLaunch.fRotate[0] = qRotation.w; pLaunch.fRotate[1] = qRotation.x; pLaunch.fRotate[2] = qRotation.y; pLaunch.fRotate[3] = qRotation.z; pLaunch.fPos[0] = vDestination.x; pLaunch.fPos[1] = vDestination.y; pLaunch.fPos[2] = vDestination.z; HookClient->Send_FLPACKET_SERVER_LAUNCH(client, pLaunch); uint iSystem; pub::Player::GetSystem(client, iSystem); pub::SpaceObj::Relocate(ClientInfo[client].ship, iSystem, vDestination, mOrientation); } /** Dock the client immediately */ cpp::result<void, Error> InstantDock(ClientId client, uint iDockObj) { // check if logged in if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); uint ship; pub::Player::GetShip(client, ship); if (!ship) return cpp::fail(Error::PlayerNotInSpace); uint iSystem; uint iSystem2; pub::SpaceObj::GetSystem(ship, iSystem); pub::SpaceObj::GetSystem(iDockObj, iSystem2); if (iSystem != iSystem2) { return cpp::fail(Error::PlayerNotInSpace); } try { pub::SpaceObj::InstantDock(ship, iDockObj, 1); } catch (...) { return cpp::fail(Error::PlayerNotInSpace); } return {}; } cpp::result<int, Error> GetRank(const std::variant<uint, std::wstring>& player) { auto rank = Hk::Ini::GetFromPlayerFile(player, L"rank"); if (rank.has_error()) { return cpp::fail(rank.error()); } return rank.value().length() ? ToInt(rank.value()) : 0; } /// Get online time. cpp::result<int, Error> GetOnlineTime(const std::variant<uint, std::wstring>& player) { const auto client = Hk::Client::ExtractClientID(player); const auto acc = Hk::Client::GetAccountByClientID(client); auto dir = Hk::Client::GetAccountDirName(acc); const auto file = Hk::Client::GetCharFileName(player); if (file.has_error()) { return cpp::fail(file.error()); } std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; if (Hk::Client::IsEncoded(scCharFile)) { std::string scCharFileNew = scCharFile + ".ini"; if (!FlcDecodeFile(scCharFile.c_str(), scCharFileNew.c_str())) return cpp::fail(Error::CouldNotDecodeCharFile); int secs = IniGetI(scCharFileNew, "mPlayer", "total_time_played", 0); DeleteFile(scCharFileNew.c_str()); return secs; } else { return IniGetI(scCharFile, "mPlayer", "total_time_played", 0); } } cpp::result<const uint, Error> GetSystemByNickname(std::variant<std::string, std::wstring> nickname) { uint system = 0; const std::string nick = nickname.index() == 0 ? std::get<std::string>(nickname) : wstos(std::get<std::wstring>(nickname)); pub::GetSystemID(system, nick.c_str()); if (!system) return cpp::fail(Error::InvalidSystem); return system; } CShip* CShipFromShipDestroyed(const DWORD** ecx) { return reinterpret_cast<CShip*>((*ecx)[4]); // NOLINT(performance-no-int-to-ptr) } /// Return true if this player is within the specified distance of any other player. bool IsInRange(ClientId client, float fDistance) { const auto lstMembers = GetGroupMembers((const wchar_t*)Players.GetActiveCharacterName(client)); if (lstMembers.has_error()) { return false; } uint ship; pub::Player::GetShip(client, ship); Vector pos; Matrix rot; pub::SpaceObj::GetLocation(ship, pos, rot); uint iSystem; pub::Player::GetSystem(client, iSystem); // For all players in system... PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { // Get the this player's current system and location in the system. ClientId client2 = playerDb->iOnlineId; uint iSystem2 = 0; pub::Player::GetSystem(client2, iSystem2); if (iSystem != iSystem2) continue; uint ship2; pub::Player::GetShip(client2, ship2); Vector pos2; Matrix rot2; pub::SpaceObj::GetLocation(ship2, pos2, rot2); // Ignore players who are in your group. bool bGrouped = false; for (auto& gm : lstMembers.value()) { if (gm.client == client2) { bGrouped = true; break; } } if (bGrouped) continue; // Is player within the specified range of the sending char. if (Hk::Math::Distance3D(pos, pos2) < fDistance) return true; } return false; } /** Delete a character. */ void DeleteCharacter(CAccount* acc, const std::wstring& character) { Hk::Client::LockAccountAccess(acc, true); st6::wstring str((ushort*)character.c_str()); Players.DeleteCharacterFromName(str); Hk::Client::UnlockAccountAccess(acc); } /** Create a new character in the specified account by emulating a create character. */ cpp::result<void, Error> NewCharacter(CAccount* acc, std::wstring& character) { Hk::Client::LockAccountAccess(acc, true); Hk::Client::UnlockAccountAccess(acc); INI_Reader ini; if (!ini.open("..\\DATA\\CHARACTERS\\newcharacter.ini", false)) return cpp::fail(Error::MpNewCharacterFileNotFoundOrInvalid); // Emulate char create by logging in. SLoginInfo logindata; wcsncpy_s(logindata.wszAccount, Hk::Client::GetAccountID(acc).value().c_str(), 36); Players.login(logindata, Players.GetMaxPlayerCount() + 1); SCreateCharacterInfo newcharinfo; wcsncpy_s(newcharinfo.wszCharname, character.c_str(), 23); newcharinfo.wszCharname[23] = 0; newcharinfo.iNickName = 0; newcharinfo.iBase = 0; newcharinfo.iPackage = 0; newcharinfo.iPilot = 0; while (ini.read_header()) { if (ini.is_header("Faction")) { while (ini.read_value()) { if (ini.is_value("nickname")) newcharinfo.iNickName = CreateID(ini.get_value_string()); else if (ini.is_value("base")) newcharinfo.iBase = CreateID(ini.get_value_string()); else if (ini.is_value("package")) newcharinfo.iPackage = CreateID(ini.get_value_string()); else if (ini.is_value("pilot")) newcharinfo.iPilot = CreateID(ini.get_value_string()); } break; } } ini.close(); if (newcharinfo.iNickName == 0) newcharinfo.iNickName = CreateID("new_player"); if (newcharinfo.iBase == 0) newcharinfo.iBase = CreateID("Li01_01_Base"); if (newcharinfo.iPackage == 0) newcharinfo.iPackage = CreateID("ge_fighter"); if (newcharinfo.iPilot == 0) newcharinfo.iPilot = CreateID("trent"); // Fill struct with valid data (though it isnt used it is needed) newcharinfo.iDunno[4] = 65536; newcharinfo.iDunno[5] = 65538; newcharinfo.iDunno[6] = 0; newcharinfo.iDunno[7] = 1058642330; newcharinfo.iDunno[8] = 3206125978; newcharinfo.iDunno[9] = 65537; newcharinfo.iDunno[10] = 0; newcharinfo.iDunno[11] = 3206125978; newcharinfo.iDunno[12] = 65539; newcharinfo.iDunno[13] = 65540; newcharinfo.iDunno[14] = 65536; newcharinfo.iDunno[15] = 65538; Server.CreateNewCharacter(newcharinfo, Players.GetMaxPlayerCount() + 1); SaveChar(character); Players.logout(Players.GetMaxPlayerCount() + 1); return {}; } // Anti cheat checking code by mc_horst. Will always return okay if the user is in space. cpp::result<void, Error> AntiCheat(ClientId client) { const auto AntiCheat1 = (_FLAntiCheat)((char*)hModServer + AddrAntiCheat1); const auto AntiCheat2 = (_FLAntiCheat)((char*)hModServer + AddrAntiCheat2); const auto AntiCheat3 = (_FLAntiCheat)((char*)hModServer + AddrAntiCheat3); const auto AntiCheat4 = (_FLAntiCheat)((char*)hModServer + AddrAntiCheat4); // Hack to make the linter happy (void)AntiCheat1; (void)AntiCheat2; (void)AntiCheat3; (void)AntiCheat4; // Check if ship in space if (const auto ship = Hk::Player::GetShip(client); ship.has_value()) { return {}; } char* szObjPtr; memcpy(&szObjPtr, &Players, 4); szObjPtr += 0x418 * (client - 1); char cRes = 0; __asm { mov ecx, [szObjPtr] call [AntiCheat1] mov [cRes], al } if (cRes != 0) { // kick Kick(client); return cpp::fail(Error::UnknownError); } __asm { mov ecx, [szObjPtr] call [AntiCheat2] mov [cRes], al } if (cRes != 0) { Kick(client); return cpp::fail(Error::UnknownError); } ulong lRet = 0; ulong lCompare = 0; __asm { mov ecx, [szObjPtr] mov eax, [ecx+0x320] mov [lCompare], eax call [AntiCheat3] mov [lRet], eax } if (lRet > lCompare) { Kick(client); return cpp::fail(Error::UnknownError); } __asm { mov ecx, [szObjPtr] call [AntiCheat4] mov [cRes], al } if (cRes != 0) { Kick(client); return cpp::fail(Error::UnknownError); } return {}; } cpp::result<void, Error> SetEquip(const std::variant<uint, std::wstring>& player, const st6::list<EquipDesc>& equip) { ClientId client = Hk::Client::ExtractClientID(player); if ((client == UINT_MAX) || Hk::Client::IsInCharSelectMenu(client)) return cpp::fail(Error::CharacterNotSelected); // Update FLHook's lists to make anticheat pleased. if (&equip != &Players[client].lShadowEquipDescList.equip) Players[client].lShadowEquipDescList.equip = equip; if (&equip != &Players[client].equipDescList.equip) Players[client].equipDescList.equip = equip; // Calculate packet size. First two bytes reserved for items count. uint itemBufSize = 2; for (const auto& item : equip) { itemBufSize += sizeof(SetEquipmentItem) + strlen(item.szHardPoint.value) + 1; } FLPACKET* packet = FLPACKET::Create(itemBufSize, FLPACKET::FLPACKET_SERVER_SETEQUIPMENT); auto pSetEquipment = reinterpret_cast<FlPacketSetEquipment*>(packet->content); // Add items to packet as array of variable size. uint index = 0; for (const auto& item : equip) { SetEquipmentItem setEquipItem; setEquipItem.iCount = item.iCount; setEquipItem.fHealth = item.fHealth; setEquipItem.iArchId = item.iArchId; setEquipItem.sId = item.sId; setEquipItem.bMounted = item.bMounted; setEquipItem.bMission = item.bMission; if (uint len = strlen(item.szHardPoint.value); len && item.szHardPoint.value != "BAY") { setEquipItem.szHardPointLen = static_cast<ushort>(len + 1); // add 1 for the null - char* is a null-terminated string in C++ } else { setEquipItem.szHardPointLen = 0; } pSetEquipment->count++; const byte* buf = (byte*)&setEquipItem; for (int i = 0; i < sizeof(SetEquipmentItem); i++) pSetEquipment->items[index++] = buf[i]; const byte* szHardPoint = (byte*)item.szHardPoint.value; for (int i = 0; i < setEquipItem.szHardPointLen; i++) pSetEquipment->items[index++] = szHardPoint[i]; } if (packet->SendTo(client)) { return {}; } return cpp::fail(Error::UnknownError); } cpp::result<void, Error> AddEquip(const std::variant<uint, std::wstring>& player, uint iGoodId, const std::string& scHardpoint) { ClientId client = Hk::Client::ExtractClientID(player); if ((client == UINT_MAX) || Hk::Client::IsInCharSelectMenu(client)) return cpp::fail(Error::CharacterNotSelected); if (!Players[client].iEnteredBase) { Players[client].iEnteredBase = Players[client].baseId; Server.ReqAddItem(iGoodId, scHardpoint.c_str(), 1, 1.0f, true, client); Players[client].iEnteredBase = 0; } else { Server.ReqAddItem(iGoodId, scHardpoint.c_str(), 1, 1.0f, true, client); } // Add to check-list which is being compared to the users equip-list when // saving char to fix "Ship or Equipment not sold on base" kick EquipDesc ed; ed.sId = Players[client].sLastEquipId; ed.iCount = 1; ed.iArchId = iGoodId; Players[client].lShadowEquipDescList.add_equipment_item(ed, false); return {}; } cpp::result<void, Error> AddEquip(const std::variant<uint, std::wstring>& player, uint iGoodId, const std::string& scHardpoint, bool bMounted) { typedef bool(__stdcall * _AddCargoDocked)(uint iGoodId, CacheString * &hardpoint, int iNumItems, float fHealth, int bMounted, int bMission, uint iOne); static _AddCargoDocked AddCargoDocked = nullptr; if (!AddCargoDocked) AddCargoDocked = (_AddCargoDocked)((char*)hModServer + 0x6EFC0); ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX || Hk::Client::IsInCharSelectMenu(client)) return cpp::fail(Error::PlayerNotLoggedIn); uint iBase = 0; pub::Player::GetBase(client, iBase); uint iLocation = 0; pub::Player::GetLocation(client, iLocation); if (iLocation) Server.LocationExit(iLocation, client); if (iBase) Server.BaseExit(iBase, client); if (!Hk::Client::IsValidClientID(client)) return cpp::fail(Error::PlayerNotLoggedIn); PlayerData* pd = &Players[client]; const char* p = scHardpoint.c_str(); CacheString hardpoint; hardpoint.value = StringAlloc(p, false); int iOne = 1; int iMounted = bMounted; float fHealth = 1; CacheString* pHP = &hardpoint; __asm { push iOne push iMounted push iOne push fHealth push iOne push pHP push iGoodId mov ecx, pd call AddCargoDocked } if (iBase) Server.BaseEnter(iBase, client); if (iLocation) Server.LocationEnter(iLocation, client); return {}; } void DelayedKick(ClientId client, uint secs) { mstime kick_time = Hk::Time::GetUnixMiliseconds() + (secs * 1000); if (!ClientInfo[client].tmKickTime || ClientInfo[client].tmKickTime > kick_time) ClientInfo[client].tmKickTime = kick_time; } std::string GetPlayerSystemS(ClientId client) { uint iSystemId; pub::Player::GetSystem(client, iSystemId); char szSystemname[1024] = ""; pub::GetSystemNickname(szSystemname, sizeof(szSystemname), iSystemId); return szSystemname; } cpp::result<const uint, Error> GetShipValue(const std::variant<uint, std::wstring>& player) { if (ClientId client = Hk::Client::ExtractClientID(player); client != UINT_MAX && !Hk::Client::IsInCharSelectMenu(client)) { SaveChar(player); if (!Hk::Client::IsValidClientID(client)) { return cpp::fail(Error::UnknownError); } } float fValue = 0.0f; uint iBaseId = 0; const auto lstCharFile = ReadCharFile(player); if (lstCharFile.has_error()) { return cpp::fail(lstCharFile.error()); } for (const auto& line : lstCharFile.value()) { std::wstring wscKey = Trim(line.substr(0, line.find(L"="))); if (wscKey == L"base" || wscKey == L"last_base") { int iFindEqual = line.find(L"="); if (iFindEqual == -1) { continue; } if ((iFindEqual + 1) >= (int)line.size()) { continue; } iBaseId = CreateID(wstos(Trim(line.substr(iFindEqual + 1))).c_str()); break; } } for (const auto& line : lstCharFile.value()) { std::wstring wscKey = Trim(line.substr(0, line.find(L"="))); if (wscKey == L"cargo" || wscKey == L"equip") { int iFindEqual = line.find(L"="); if (iFindEqual == -1) { continue; } int iFindComma = line.find(L",", iFindEqual); if (iFindComma == -1) { continue; } uint iGoodId = ToUInt(Trim(line.substr(iFindEqual + 1, iFindComma))); uint iGoodCount = ToUInt(Trim(line.substr(iFindComma + 1, line.find(L",", iFindComma + 1)))); float fItemValue; if (pub::Market::GetPrice(iBaseId, Arch2Good(iGoodId), fItemValue) == 0) { if (arch_is_combinable(iGoodId)) { fValue += fItemValue * static_cast<float>(iGoodCount); } else { float const* fResaleFactor = (float*)((char*)hModServer + 0x8AE7C); fValue += fItemValue * (*fResaleFactor); } } } else if (wscKey == L"money") { int iFindEqual = line.find(L"="); if (iFindEqual == -1) { continue; } uint fItemValue = ToUInt(Trim(line.substr(iFindEqual + 1))); fValue += fItemValue; } else if (wscKey == L"ship_archetype") { uint shipArchId = ToUInt(Trim(line.substr(line.find(L"=") + 1, line.length()))); const GoodInfo* gi = GoodList_get()->find_by_ship_arch(shipArchId); if (gi) { gi = GoodList::find_by_id(gi->iArchId); if (gi) { auto fResaleFactor = (float*)((char*)hModServer + 0x8AE78); float fItemValue = gi->fPrice * (*fResaleFactor); fValue += fItemValue; } } } } return static_cast<uint>(fValue); } void SaveChar(ClientId client) { BYTE patch[] = {0x90, 0x90}; WriteProcMem((char*)hModServer + 0x7EFA8, patch, sizeof(patch)); pub::Save(client, 1); } cpp::result<const ShipId, Error> GetTarget(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); const auto ship = GetShip(client); if (ship.has_error()) return cpp::fail(ship.error()); uint target; pub::SpaceObj::GetTarget(ship.value(), target); if (!target) return cpp::fail(Error::NoTargetSelected); return target; } cpp::result<ClientId, Error> GetTargetClientID(const std::variant<uint, std::wstring>& player) { const auto target = GetTarget(player); if (target.has_error()) return cpp::fail(target.error()); auto targetClientId = Hk::Client::GetClientIdByShip(target.value()); if (targetClientId.has_error()) return cpp::fail(Error::TargetIsNotPlayer); return targetClientId; } cpp::result<const BaseId, Error> GetCurrentBase(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } uint base; pub::Player::GetBase(client, base); if (base) { return base; } return cpp::fail(Error::PlayerNotDocked); } cpp::result<const SystemId, Error> GetSystem(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } uint system; pub::Player::GetSystem(client, system); if (!system) return cpp::fail(Error::InvalidSystem); return system; } // returns ship instance ID cpp::result<const ShipId, Error> GetShip(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } uint ship; pub::Player::GetShip(client, ship); if (!ship) return cpp::fail(Error::PlayerNotInSpace); return ship; } // returns Ship Type cpp::result<const uint, Error> GetShipID(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } uint shipId; pub::Player::GetShipID(client, shipId); if (!shipId) return cpp::fail(Error::PlayerNotInSpace); return shipId; } cpp::result<void, Error> MarkObj(const std::variant<uint, std::wstring>& player, uint objId, int markStatus) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } pub::Player::MarkObj(client, objId, markStatus); return {}; } cpp::result<int, Error> GetPvpKills(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } int kills; pub::Player::GetNumKills(client, kills); return kills; } cpp::result<void, Error> SetPvpKills(const std::variant<uint, std::wstring>& player, int killAmount) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } pub::Player::SetNumKills(client, killAmount); return {}; } cpp::result<int, Error> IncrementPvpKills(const std::variant<uint, std::wstring>& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } int kills; pub::Player::GetNumKills(client, kills); kills++; pub::Player::SetNumKills(client, kills); return {}; } cpp::result<int, Error> SendBestPath(const std::variant<uint, std::wstring>& player, int iStartSysId, Vector vStartPos, int iTargetSysId, Vector vTargetPos) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) { return cpp::fail(Error::PlayerNotLoggedIn); } BestPathInfo bpi; bpi.iWaypointStartIndex = 1; //Use 1 as start index so the waypoints of the player get overwritten bpi.iStartSysId = iStartSysId; bpi.vStartPos = vStartPos; bpi.iTargetSysId = iTargetSysId; bpi.vTargetPos = vTargetPos; bpi.iDunno1 = 2; bpi.bDunno2 = 0; bpi.iDunno3 = 0; bpi.iDunno4 = 0; // The original asm code sets 52 as size for the struct. So better hard code it instead of sizeof in case someone messes up the struct in a commit. Server.RequestBestPath(client, (uchar*)&bpi, 52); return {}; } } // namespace Hk::Player
50,783
C++
.cpp
1,470
31.011565
157
0.662048
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,397
Client.cpp
TheStarport_FLHook/source/Helpers/Client.cpp
#include "Global.hpp" namespace Hk::Client { cpp::result<const uint, Error> GetClientID(const std::wstring& character) { if (character.find(L"id ") == std::string::npos) { return cpp::fail(Error::InvalidIdString); } auto resolvedId = ResolveID(character); if (resolvedId.has_error() || resolvedId.error() == Error::InvalidIdString) { resolvedId = ResolveShortCut(character); if (resolvedId.has_error()) { if ((resolvedId.error() == Error::AmbiguousShortcut) || (resolvedId.error() == Error::NoMatchingPlayer)) { return cpp::fail(resolvedId.error()); } if (resolvedId.error() == Error::InvalidShortcutString) { resolvedId = GetClientIdFromCharName(character); if (resolvedId.has_value()) return resolvedId.value(); else return cpp::fail(Error::PlayerNotLoggedIn); } return cpp::fail(resolvedId.error()); } } return resolvedId.value(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const uint, Error> GetClientIdFromAccount(const CAccount* acc) { PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { if (playerDb->Account == acc) { return playerDb->iOnlineId; } } return cpp::fail(Error::PlayerNotLoggedIn); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<CAccount*, Error> GetAccountByCharName(const std::wstring& character) { st6::wstring flStr((ushort*)character.c_str()); CAccount* acc = Players.FindAccountFromCharacterName(flStr); if (!acc) return cpp::fail(Error::CharacterDoesNotExist); return acc; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const uint, Error> GetClientIdFromCharName(const std::wstring& character) { const auto acc = GetAccountByCharName(character); if (acc.has_error()) return cpp::fail(acc.error()); const auto client = GetClientIdFromAccount(acc.value()); if (client.has_error()) return cpp::fail(client.error()); const auto newCharacter = GetCharacterNameByID(client.value()); if (newCharacter.has_error()) return cpp::fail(newCharacter.error()); if (ToLower(newCharacter.value()).compare(ToLower(character)) != 0) return cpp::fail(Error::CharacterDoesNotExist); return client; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const std::wstring, Error> GetAccountID(CAccount* acc) { if (acc && acc->wszAccId) return acc->wszAccId; return cpp::fail(Error::CannotGetAccount); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsEncoded(const std::string& scFilename) { bool bRet = false; FILE* f; fopen_s(&f, scFilename.c_str(), "r"); if (!f) return false; char szMagic[] = "FLS1"; char szFile[sizeof(szMagic)] = ""; fread(szFile, 1, sizeof(szMagic), f); if (!strncmp(szMagic, szFile, sizeof(szMagic) - 1)) bRet = true; fclose(f); return bRet; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsInCharSelectMenu(const uint& player) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return false; uint iBase = 0; uint iSystem = 0; pub::Player::GetBase(client, iBase); pub::Player::GetSystem(client, iSystem); if (!iBase && !iSystem) return true; else return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool IsValidClientID(ClientId client) { PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { if (playerDb->iOnlineId == client) return true; } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const std::wstring, Error> GetCharacterNameByID(ClientId& client) { if (!IsValidClientID(client)) return cpp::fail(Error::InvalidClientId); return reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const uint, Error> ResolveID(const std::wstring& character) { if (const std::wstring characterLower = ToLower(character); characterLower.find(L"id ") == 0) { uint iId = 0; swscanf_s(characterLower.c_str(), L"id %u", &iId); if (!IsValidClientID(iId)) return cpp::fail(Error::InvalidClientId); return iId; } return cpp::fail(Error::InvalidIdString); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<ClientId, Error> ResolveShortCut(const std::wstring& wscShortcut) { std::wstring wscShortcutLower = ToLower(wscShortcut); if (wscShortcutLower.find(L"sc ") != 0) return cpp::fail(Error::InvalidShortcutString); wscShortcutLower = wscShortcutLower.substr(3); uint clientFound = UINT_MAX; PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { const auto characterName = GetCharacterNameByID(playerDb->iOnlineId); if (characterName.has_error()) continue; if (ToLower(characterName.value()).find(wscShortcutLower) != -1) { if (clientFound == UINT_MAX) clientFound = playerDb->iOnlineId; else return cpp::fail(Error::AmbiguousShortcut); } } if (clientFound == UINT_MAX) return cpp::fail(Error::NoMatchingPlayer); return clientFound; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<ClientId, Error> GetClientIdByShip(const ShipId ship) { if (auto foundClient = std::ranges::find_if(ClientInfo, [ship](const CLIENT_INFO& ci) { return ci.ship == ship; }); foundClient != ClientInfo.end()) return std::ranges::distance(ClientInfo.begin(), foundClient); return cpp::fail(Error::InvalidShip); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::wstring GetAccountDirName(const CAccount* acc) { const auto GetFLName = reinterpret_cast<_GetFLName>(reinterpret_cast<char*>(hModServer) + 0x66370); char szDir[1024] = ""; GetFLName(szDir, acc->wszAccId); return stows(szDir); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const std::wstring, Error> GetCharFileName(const std::variant<uint, std::wstring>& player, bool returnValueIfNoFile) { static _GetFLName GetFLName = nullptr; if (!GetFLName) GetFLName = (_GetFLName)((char*)hModServer + 0x66370); std::string buffer; buffer.reserve(1024); if (ClientId client = Hk::Client::ExtractClientID(player); client != UINT_MAX) { if (const auto character = GetCharacterNameByID(client); character.has_error()) return cpp::fail(character.error()); GetFLName(buffer.data(), reinterpret_cast<const wchar_t*>(Players.GetActiveCharacterName(client))); } else if ((player.index() && GetAccountByCharName(std::get<std::wstring>(player))) || returnValueIfNoFile) { GetFLName(buffer.data(), std::get<std::wstring>(player).c_str()); } else { return cpp::fail(Error::InvalidClientId); } return stows(buffer); } cpp::result<const std::wstring, Error> GetCharFileName(const std::variant<uint, std::wstring>& player) { return GetCharFileName(player, false); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const std::wstring, Error> GetBaseNickByID(uint baseId) { std::string base; base.resize(1024); pub::GetBaseNickname(base.data(), base.capacity(), baseId); base.resize(1024); // Without calling another core function will result in length not being updated if (base.empty()) return cpp::fail(Error::InvalidBase); return stows(base); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const std::wstring, Error> GetSystemNickByID(uint systemId) { std::string system; system.resize(1024); pub::GetSystemNickname(system.data(), system.capacity(), systemId); system.resize(1024); // Without calling another core function will result in length not being updated if (system.empty()) return cpp::fail(Error::InvalidSystem); return stows(system); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<const std::wstring, Error> GetPlayerSystem(ClientId client) { if (!IsValidClientID(client)) return cpp::fail(Error::InvalidClientId); uint systemId; pub::Player::GetSystem(client, systemId); return GetSystemNickByID(systemId); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> LockAccountAccess(CAccount* acc, bool bKick) { const std::array<char, 1> jmp = {'\xEB'}; const std::array<char, 1> jbe = {'\x76'}; const auto accountId = GetAccountID(acc); if (accountId.has_error()) return cpp::fail(accountId.error()); st6::wstring flStr((ushort*)accountId.value().c_str()); if (!bKick) WriteProcMem((void*)0x06D52A6A, jmp.data(), 1); Players.LockAccountAccess(flStr); // also kicks player on this account if (!bKick) WriteProcMem((void*)0x06D52A6A, jbe.data(), 1); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> UnlockAccountAccess(CAccount* acc) { const auto accountId = GetAccountID(acc); if (accountId.has_error()) return cpp::fail(accountId.error()); st6::wstring flStr((ushort*)accountId.value().c_str()); Players.UnlockAccountAccess(flStr); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void GetItemsForSale(uint baseId, std::list<uint>& lstItems) { lstItems.clear(); const std::array<char, 2> nop = {'\x90', '\x90'}; const std::array<char, 2> jnz = {'\x75', '\x1D'}; WriteProcMem(SRV_ADDR(ADDR_SRV_GETCOMMODITIES), nop.data(), 2); // patch, else we only get commodities std::array<int, 1024> arr; int size = 256; pub::Market::GetCommoditiesForSale(baseId, reinterpret_cast<uint* const>(arr.data()), &size); WriteProcMem(SRV_ADDR(ADDR_SRV_GETCOMMODITIES), jnz.data(), 2); for (int i = 0; (i < size); i++) lstItems.push_back(arr[i]); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<IObjInspectImpl*, Error> GetInspect(ClientId client) { uint ship; pub::Player::GetShip(client, ship); uint iDunno; IObjInspectImpl* inspect; if (!GetShipInspect(ship, inspect, iDunno)) return cpp::fail(Error::InvalidShip); else return inspect; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// EngineState GetEngineState(ClientId client) { if (ClientInfo[client].bTradelane) return ES_TRADELANE; else if (ClientInfo[client].bCruiseActivated) return ES_CRUISE; else if (ClientInfo[client].bThrusterActivated) return ES_THRUSTER; else if (!ClientInfo[client].bEngineKilled) return ES_ENGINE; else return ES_KILLED; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// EquipmentType GetEqType(Archetype::Equipment* eq) { uint iVFTableMine = (uint)hModCommon + ADDR_COMMON_VFTABLE_MINE; uint iVFTableCM = (uint)hModCommon + ADDR_COMMON_VFTABLE_CM; uint iVFTableGun = (uint)hModCommon + ADDR_COMMON_VFTABLE_GUN; uint iVFTableShieldGen = (uint)hModCommon + ADDR_COMMON_VFTABLE_SHIELDGEN; uint iVFTableThruster = (uint)hModCommon + ADDR_COMMON_VFTABLE_THRUSTER; uint iVFTableShieldBat = (uint)hModCommon + ADDR_COMMON_VFTABLE_SHIELDBAT; uint iVFTableNanoBot = (uint)hModCommon + ADDR_COMMON_VFTABLE_NANOBOT; uint iVFTableMunition = (uint)hModCommon + ADDR_COMMON_VFTABLE_MUNITION; uint iVFTableEngine = (uint)hModCommon + ADDR_COMMON_VFTABLE_ENGINE; uint iVFTableScanner = (uint)hModCommon + ADDR_COMMON_VFTABLE_SCANNER; uint iVFTableTractor = (uint)hModCommon + ADDR_COMMON_VFTABLE_TRACTOR; uint iVFTableLight = (uint)hModCommon + ADDR_COMMON_VFTABLE_LIGHT; uint iVFTable = *((uint*)eq); if (iVFTable == iVFTableGun) { Archetype::Gun const* gun = (Archetype::Gun*)eq; Archetype::Equipment* eqAmmo = Archetype::GetEquipment(gun->iProjectileArchId); int iMissile; memcpy(&iMissile, (char*)eqAmmo + 0x90, 4); uint iGunType = gun->get_hp_type_by_index(0); if (iGunType == 36) return ET_TORPEDO; else if (iGunType == 35) return ET_CD; else if (iMissile) return ET_MISSILE; else return ET_GUN; } else if (iVFTable == iVFTableCM) return ET_CM; else if (iVFTable == iVFTableShieldGen) return ET_SHIELDGEN; else if (iVFTable == iVFTableThruster) return ET_THRUSTER; else if (iVFTable == iVFTableShieldBat) return ET_SHIELDBAT; else if (iVFTable == iVFTableNanoBot) return ET_NANOBOT; else if (iVFTable == iVFTableMunition) return ET_MUNITION; else if (iVFTable == iVFTableMine) return ET_MINE; else if (iVFTable == iVFTableEngine) return ET_ENGINE; else if (iVFTable == iVFTableLight) return ET_LIGHT; else if (iVFTable == iVFTableScanner) return ET_SCANNER; else if (iVFTable == iVFTableTractor) return ET_TRACTOR; else return ET_OTHER; } uint ExtractClientID(const std::variant<uint, std::wstring>& player) { // If index is 0, we just use the client Id we are given if (!player.index()) { const uint id = std::get<uint>(player); return IsValidClientID(id) ? id : -1; } // Otherwise we have a character name const std::wstring characterName = std::get<std::wstring>(player); // Check if its an id string if (characterName.rfind(L"id ", 0) != std::wstring::npos) { const auto val = ResolveID(characterName); if (val.has_error()) { return -1; } return val.value(); } const auto client = GetClientIdFromCharName(characterName); if (client.has_error()) { return -1; } return client.value(); } cpp::result<CAccount*, Error> ExtractAccount(const std::variant<uint, std::wstring>& player) { if (ClientId client = Hk::Client::ExtractClientID(player); client != UINT_MAX) return Players.FindAccountFromClientID(client); if (!player.index()) return nullptr; const auto acc = GetAccountByCharName(std::get<std::wstring>(player)); if (acc.has_error()) { return cpp::fail(acc.error()); } return acc.value(); } CAccount* GetAccountByClientID(ClientId client) { if (!Hk::Client::IsValidClientID(client)) return nullptr; return Players.FindAccountFromClientID(client); } std::wstring GetAccountIdByClientID(ClientId client) { if (Hk::Client::IsValidClientID(client)) { CAccount const* acc = GetAccountByClientID(client); if (acc && acc->wszAccId) { return acc->wszAccId; } } return L""; } cpp::result<void, Error> PlaySoundEffect(ClientId client, uint soundId) { if (Hk::Client::IsValidClientID(client)) { pub::Audio::PlaySoundEffect(client, soundId); return {}; } return cpp::fail(Error::PlayerNotLoggedIn); } std::vector<uint> getAllPlayersInSystem(SystemId system) { PlayerData* playerData = nullptr; std::vector<uint> playersInSystem; while ((playerData = Players.traverse_active(playerData))) { if (playerData->systemId == system) playersInSystem.push_back(playerData->iOnlineId); } return playersInSystem; } }
16,142
C++
.cpp
441
33.256236
129
0.604848
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,398
PilotPersonalities.cpp
TheStarport_FLHook/source/Helpers/PilotPersonalities.cpp
#include "Global.hpp" namespace Hk::Personalities { std::map<std::string, pub::AI::Personality> pilots; std::map<std::string, pub::AI::Personality::EvadeDodgeUseStruct> evadeDodge; std::map<std::string, pub::AI::Personality::EvadeBreakUseStruct> evadeBreak; std::map<std::string, pub::AI::Personality::BuzzHeadTowardUseStruct> buzzHead; std::map<std::string, pub::AI::Personality::BuzzPassByUseStruct> buzzPass; std::map<std::string, pub::AI::Personality::TrailUseStruct> trail; std::map<std::string, pub::AI::Personality::StrafeUseStruct> strafe; std::map<std::string, pub::AI::Personality::EngineKillUseStruct> engineKill; std::map<std::string, pub::AI::Personality::RepairUseStruct> repair; std::map<std::string, pub::AI::Personality::GunUseStruct> gun; std::map<std::string, pub::AI::Personality::MissileUseStruct> missile; std::map<std::string, pub::AI::Personality::MineUseStruct> mine; std::map<std::string, pub::AI::Personality::MissileReactionStruct> missileReaction; std::map<std::string, pub::AI::Personality::DamageReactionStruct> damageReaction; std::map<std::string, pub::AI::Personality::CountermeasureUseStruct> cm; std::map<std::string, pub::AI::Personality::FormationUseStruct> formation; std::map<std::string, pub::AI::Personality::JobStruct> job; cpp::result<pub::AI::Personality, Error> GetPersonality(const std::string& pilotNickname) { const auto& pilot = pilots.find(pilotNickname); if (pilot == pilots.end()) { return cpp::fail(Error::NicknameNotFound); } return pilot->second; } void SetDirection(INI_Reader& ini, float (&direction)[4]) { const auto str = std::string(ini.get_value_string(0)); if (str == "right") direction[0] = ini.get_value_float(1); else if (str == "left") direction[1] = ini.get_value_float(1); else if (str == "up") direction[2] = ini.get_value_float(1); else if (str == "down") direction[3] = ini.get_value_float(1); } void LoadEvadeDodge(INI_Reader& ini) { pub::AI::Personality::EvadeDodgeUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("evade_dodge_style_weight")) { const auto str = std::string(ini.get_value_string(0)); if (str == "waggle") data.evade_dodge_style_weight[0] = ini.get_value_float(1); else if (str == "waggle_random") data.evade_dodge_style_weight[1] = ini.get_value_float(1); else if (str == "slide") data.evade_dodge_style_weight[2] = ini.get_value_float(1); else if (str == "corkscrew") data.evade_dodge_style_weight[3] = ini.get_value_float(1); } else if (ini.is_value("evade_dodge_direction_weight")) { SetDirection(ini, data.evade_dodge_direction_weight); } else if (ini.is_value("evade_dodge_cone_angle")) data.evade_dodge_cone_angle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_interval_time")) data.evade_dodge_interval_time = ini.get_value_float(0); else if (ini.is_value("evade_dodge_time")) data.evade_dodge_time = ini.get_value_float(0); else if (ini.is_value("evade_dodge_distance")) data.evade_dodge_distance = ini.get_value_float(0); else if (ini.is_value("evade_activate_range")) data.evade_activate_range = ini.get_value_float(0); else if (ini.is_value("evade_dodge_roll_angle")) data.evade_dodge_roll_angle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_waggle_axis_cone_angle")) data.evade_dodge_waggle_axis_cone_angle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_slide_throttle")) data.evade_dodge_slide_throttle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_turn_throttle")) data.evade_dodge_turn_throttle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_corkscrew_turn_throttle")) data.evade_dodge_corkscrew_turn_throttle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_corkscrew_roll_throttle")) data.evade_dodge_corkscrew_roll_throttle = ini.get_value_float(0); else if (ini.is_value("evade_dodge_corkscrew_roll_flip_direction")) data.evade_dodge_corkscrew_roll_flip_direction = ini.get_value_bool(0); else if (ini.is_value("evade_dodge_interval_time_variance_percent")) data.evade_dodge_interval_time_variance_percent = ini.get_value_float(0); else if (ini.is_value("evade_dodge_cone_angle_variance_percent")) data.evade_dodge_cone_angle_variance_percent = ini.get_value_float(0); } if (!nick.empty()) evadeDodge[std::move(nick)] = data; } void LoadEvadeBreak(INI_Reader& ini) { pub::AI::Personality::EvadeBreakUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("evade_break_roll_throttle")) data.evade_break_roll_throttle = ini.get_value_float(0); else if (ini.is_value("evade_break_time")) data.evade_break_time = ini.get_value_float(0); else if (ini.is_value("evade_break_interval_time")) data.evade_break_interval_time = ini.get_value_float(0); else if (ini.is_value("evade_break_afterburner_delay")) data.evade_break_afterburner_delay = ini.get_value_float(0); else if (ini.is_value("evade_break_turn_throttle")) data.evade_break_turn_throttle = ini.get_value_float(0); else if (ini.is_value("evade_break_direction_weight")) { SetDirection(ini, data.evade_break_direction_weight); } else if (ini.is_value("evade_break_roll_throttle")) { const auto str = std::string(ini.get_value_string(0)); if (str == "sideways") data.evade_break_style_weight[0] = ini.get_value_float(1); else if (str == "outrun") data.evade_break_style_weight[1] = ini.get_value_float(1); else if (str == "reverse") data.evade_break_style_weight[2] = ini.get_value_float(1); } else if (ini.is_value("evade_break_attempt_reverse_time")) data.evade_break_attempt_reverse_time = ini.get_value_float(0); else if (ini.is_value("evade_break_reverse_distance")) data.evade_break_reverse_distance = ini.get_value_float(0); else if (ini.is_value("evade_break_afterburner_delay_variance_percent")) data.evade_break_afterburner_delay_variance_percent = ini.get_value_float(0); } if (!nick.empty()) evadeBreak[std::move(nick)] = data; } void LoadBuzzHead(INI_Reader& ini) { pub::AI::Personality::BuzzHeadTowardUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("buzz_dodge_cone_angle")) data.buzz_dodge_cone_angle = ini.get_value_float(0); else if (ini.is_value("buzz_dodge_cone_angle_variance_percent")) data.buzz_dodge_cone_angle_variance_percent = ini.get_value_float(0); else if (ini.is_value("buzz_dodge_interval_time")) data.buzz_dodge_interval_time = ini.get_value_float(0); else if (ini.is_value("buzz_dodge_interval_time_variance_percent")) data.buzz_dodge_interval_time_variance_percent = ini.get_value_float(0); else if (ini.is_value("buzz_dodge_roll_angle")) data.buzz_dodge_roll_angle = ini.get_value_float(0); else if (ini.is_value("buzz_dodge_direction_weight")) { SetDirection(ini, data.buzz_dodge_direction_weight); } else if (ini.is_value("buzz_head_toward_style_weight")) { const auto str = std::string(ini.get_value_string(0)); if (str == "straight_to") data.buzz_head_toward_style_weight[0] = ini.get_value_float(1); else if (str == "slide") data.buzz_head_toward_style_weight[1] = ini.get_value_float(1); else if (str == "waggle") data.buzz_head_toward_style_weight[2] = ini.get_value_float(1); } else if (ini.is_value("buzz_dodge_turn_throttle")) data.buzz_dodge_turn_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_dodge_waggle_axis_cone_angle")) data.buzz_dodge_waggle_axis_cone_angle = ini.get_value_float(0); else if (ini.is_value("buzz_head_toward_engine_throttle")) data.buzz_head_toward_engine_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_head_toward_roll_flip_direction")) data.buzz_head_toward_roll_flip_direction = ini.get_value_bool(0); else if (ini.is_value("buzz_head_toward_roll_throttle")) data.buzz_head_toward_roll_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_slide_throttle")) data.buzz_slide_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_slide_interval_time_variance_percent")) data.buzz_slide_interval_time_variance_percent = ini.get_value_float(0); else if (ini.is_value("buzz_slide_interval_time")) data.buzz_slide_interval_time = ini.get_value_float(0); else if (ini.is_value("buzz_min_distance_to_head_toward")) data.buzz_min_distance_to_head_toward = ini.get_value_float(0); else if (ini.is_value("buzz_min_distance_to_head_toward_variance_percent")) data.buzz_min_distance_to_head_toward_variance_percent = ini.get_value_float(0); else if (ini.is_value("buzz_max_time_to_head_away")) data.buzz_max_time_to_head_away = ini.get_value_float(0); else if (ini.is_value("buzz_head_toward_turn_throttle")) data.buzz_head_toward_turn_throttle = ini.get_value_float(0); } if (!nick.empty()) buzzHead[std::move(nick)] = data; } void LoadBuzzPass(INI_Reader& ini) { pub::AI::Personality::BuzzPassByUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("buzz_break_direction_cone_angle")) data.buzz_break_direction_cone_angle = ini.get_value_float(0); else if (ini.is_value("buzz_break_turn_throttle")) data.buzz_break_turn_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_distance_to_pass_by")) data.buzz_distance_to_pass_by = ini.get_value_float(0); else if (ini.is_value("buzz_drop_bomb_on_pass_by")) data.buzz_drop_bomb_on_pass_by = ini.get_value_bool(0); else if (ini.is_value("buzz_pass_by_roll_throttle")) data.buzz_pass_by_roll_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_break_direction_weight")) { SetDirection(ini, data.buzz_break_direction_weight); } else if (ini.is_value("evade_break_roll_throttle")) { const auto str = std::string(ini.get_value_string(0)); if (str == "straight_by") data.buzz_pass_by_style_weight[0] = ini.get_value_float(1); else if (str == "break_away") data.buzz_pass_by_style_weight[1] = ini.get_value_float(1); else if (str == "engine_kill") data.buzz_pass_by_style_weight[2] = ini.get_value_float(1); } else if (ini.is_value("buzz_pass_by_roll_throttle")) data.buzz_pass_by_roll_throttle = ini.get_value_float(0); else if (ini.is_value("buzz_pass_by_time")) data.buzz_pass_by_time = ini.get_value_float(0); } if (!nick.empty()) buzzPass[std::move(nick)] = data; } void LoadTrail(INI_Reader& ini) { pub::AI::Personality::TrailUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("trail_break_afterburner")) data.trail_break_afterburner = ini.get_value_bool(0); else if (ini.is_value("trail_break_roll_throttle")) data.trail_break_roll_throttle = ini.get_value_float(0); else if (ini.is_value("trail_break_time")) data.trail_break_time = ini.get_value_float(0); else if (ini.is_value("trail_distance")) data.trail_distance = ini.get_value_float(0); else if (ini.is_value("trail_lock_cone_angle")) data.trail_lock_cone_angle = ini.get_value_float(0); else if (ini.is_value("trail_max_turn_throttle")) data.trail_max_turn_throttle = ini.get_value_float(0); else if (ini.is_value("trail_min_no_lock_time")) data.trail_min_no_lock_time = ini.get_value_float(0); } if (!nick.empty()) trail[std::move(nick)] = data; } void LoadStrafe(INI_Reader& ini) { pub::AI::Personality::StrafeUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("strafe_attack_throttle")) data.strafe_attack_throttle = ini.get_value_bool(0); else if (ini.is_value("strafe_run_away_distance")) data.strafe_run_away_distance = ini.get_value_float(0); else if (ini.is_value("strafe_turn_throttle")) data.strafe_turn_throttle = ini.get_value_float(0); } if (!nick.empty()) strafe[std::move(nick)] = data; } void LoadEngineKill(INI_Reader& ini) { pub::AI::Personality::EngineKillUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("engine_kill_afterburner_time")) data.engine_kill_afterburner_time = ini.get_value_float(0); else if (ini.is_value("engine_kill_face_time")) data.engine_kill_face_time = ini.get_value_float(0); else if (ini.is_value("engine_kill_max_target_distance")) data.engine_kill_max_target_distance = ini.get_value_float(0); else if (ini.is_value("engine_kill_search_time")) data.engine_kill_search_time = ini.get_value_float(0); else if (ini.is_value("engine_kill_use_afterburner")) data.engine_kill_use_afterburner = ini.get_value_float(0); } if (!nick.empty()) engineKill[std::move(nick)] = data; } void LoadRepair(INI_Reader& ini) { pub::AI::Personality::RepairUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("use_hull_repair_at_damage_percent")) data.use_hull_repair_at_damage_percent = ini.get_value_float(0); else if (ini.is_value("use_hull_repair_post_delay")) data.use_hull_repair_post_delay = ini.get_value_float(0); else if (ini.is_value("use_hull_repair_pre_delay")) data.use_hull_repair_pre_delay = ini.get_value_float(0); else if (ini.is_value("use_shield_repair_at_damage_percent")) data.use_shield_repair_at_damage_percent = ini.get_value_float(0); else if (ini.is_value("use_shield_repair_post_delay")) data.use_shield_repair_post_delay = ini.get_value_float(0); else if (ini.is_value("use_shield_repair_pre_delay")) data.use_shield_repair_pre_delay = ini.get_value_float(0); } if (!nick.empty()) repair[std::move(nick)] = data; } void LoadGun(INI_Reader& ini) { pub::AI::Personality::GunUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("gun_fire_accuracy_cone_angle")) data.gun_fire_accuracy_cone_angle = ini.get_value_float(0); else if (ini.is_value("gun_fire_accuracy_power")) data.gun_fire_accuracy_power = ini.get_value_float(0); else if (ini.is_value("gun_fire_accuracy_power_npc")) data.gun_fire_accuracy_power_npc = ini.get_value_float(0); else if (ini.is_value("use_shield_repair_at_damage_percent")) data.gun_fire_burst_interval_time = ini.get_value_float(0); else if (ini.is_value("gun_fire_burst_interval_variance_percent")) data.gun_fire_burst_interval_variance_percent = ini.get_value_float(0); else if (ini.is_value("gun_fire_interval_time")) data.gun_fire_interval_time = ini.get_value_float(0); else if (ini.is_value("gun_fire_burst_interval_variance_percent")) data.gun_fire_burst_interval_variance_percent = ini.get_value_float(0); else if (ini.is_value("gun_fire_no_burst_interval_time")) data.gun_fire_no_burst_interval_time = ini.get_value_float(0); else if (ini.is_value("gun_fire_interval_variance_percent")) data.gun_fire_interval_variance_percent = ini.get_value_float(0); else if (ini.is_value("gun_range_threshold")) data.gun_range_threshold = ini.get_value_float(0); else if (ini.is_value("gun_range_threshold_variance_percent")) data.gun_range_threshold_variance_percent = ini.get_value_float(0); else if (ini.is_value("gun_target_point_switch_time")) data.gun_target_point_switch_time = ini.get_value_float(0); } if (!nick.empty()) gun[std::move(nick)] = data; } void LoadMine(INI_Reader& ini) { pub::AI::Personality::MineUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("mine_launch_cone_angle")) data.mine_launch_cone_angle = ini.get_value_float(0); else if (ini.is_value("mine_launch_interval")) data.mine_launch_interval = ini.get_value_float(0); else if (ini.is_value("mine_launch_range")) data.mine_launch_range = ini.get_value_float(0); } if (!nick.empty()) mine[std::move(nick)] = data; } void LoadMissileReaction(INI_Reader& ini) { pub::AI::Personality::MissileReactionStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("evade_afterburn_missile_reaction_time")) data.evade_afterburn_missile_reaction_time = ini.get_value_float(0); else if (ini.is_value("evade_break_missile_reaction_time")) data.evade_break_missile_reaction_time = ini.get_value_float(0); else if (ini.is_value("evade_missile_distance")) data.evade_missile_distance = ini.get_value_float(0); else if (ini.is_value("evade_slide_missile_reaction_time")) data.evade_slide_missile_reaction_time = ini.get_value_float(0); } if (!nick.empty()) missileReaction[std::move(nick)] = data; } void LoadDamageReaction(INI_Reader& ini) { pub::AI::Personality::DamageReactionStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("afterburner_damage_trigger_percent")) data.afterburner_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("afterburner_damage_trigger_time")) data.afterburner_damage_trigger_time = ini.get_value_float(0); else if (ini.is_value("brake_reverse_damage_trigger_percent")) data.brake_reverse_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("drop_mines_damage_trigger_percent")) data.drop_mines_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("drop_mines_damage_trigger_time")) data.drop_mines_damage_trigger_time = ini.get_value_float(0); else if (ini.is_value("engine_kill_face_damage_trigger_percent")) data.engine_kill_face_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("engine_kill_face_damage_trigger_time")) data.engine_kill_face_damage_trigger_time = ini.get_value_float(0); else if (ini.is_value("evade_break_damage_trigger_percent")) data.evade_break_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("evade_dodge_more_damage_trigger_percent")) data.evade_dodge_more_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("fire_guns_damage_trigger_percent")) data.fire_guns_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("fire_guns_damage_trigger_time")) data.fire_guns_damage_trigger_time = ini.get_value_float(0); else if (ini.is_value("fire_missiles_damage_trigger_percent")) data.fire_missiles_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("fire_missiles_damage_trigger_time")) data.fire_missiles_damage_trigger_time = ini.get_value_float(0); } if (!nick.empty()) damageReaction[std::move(nick)] = data; } void LoadCM(INI_Reader& ini) { pub::AI::Personality::CountermeasureUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("countermeasure_active_time")) data.countermeasure_active_time = ini.get_value_float(0); else if (ini.is_value("countermeasure_unactive_time")) data.countermeasure_unactive_time = ini.get_value_float(0); } if (!nick.empty()) cm[std::move(nick)] = data; } void LoadFormation(INI_Reader& ini) { pub::AI::Personality::FormationUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("break_apart_formation_damage_trigger_percent")) data.break_apart_formation_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("break_apart_formation_damage_trigger_time")) data.break_apart_formation_damage_trigger_time = ini.get_value_float(0); else if (ini.is_value("break_apart_formation_missile_reaction_time")) data.break_apart_formation_missile_reaction_time = ini.get_value_float(0); else if (ini.is_value("break_apart_formation_on_buzz_head_toward")) data.break_apart_formation_on_buzz_head_toward = ini.get_value_bool(0); else if (ini.is_value("break_apart_formation_on_buzz_head_toward")) data.break_apart_formation_on_buzz_head_toward = ini.get_value_bool(0); else if (ini.is_value("break_apart_formation_on_buzz_pass_by")) data.break_apart_formation_on_buzz_pass_by = ini.get_value_bool(0); else if (ini.is_value("break_apart_formation_on_evade_break")) data.break_apart_formation_on_evade_break = ini.get_value_bool(0); else if (ini.is_value("break_apart_formation_on_evade_dodge")) data.break_apart_formation_on_evade_dodge = ini.get_value_bool(0); else if (ini.is_value("break_formation_damage_trigger_percent")) data.break_formation_damage_trigger_percent = ini.get_value_float(0); else if (ini.is_value("break_formation_damage_trigger_time")) data.break_formation_damage_trigger_time = ini.get_value_float(0); else if (ini.is_value("break_formation_missile_reaction_time")) data.break_formation_missile_reaction_time = ini.get_value_float(0); else if (ini.is_value("break_formation_on_buzz_head_toward_time")) data.break_formation_on_buzz_head_toward_time = ini.get_value_float(0); else if (ini.is_value("formation_exit_top_turn_break_away_throttle")) data.formation_exit_top_turn_break_away_throttle = ini.get_value_float(0); else if (ini.is_value("regroup_formation_on_buzz_head_toward")) data.regroup_formation_on_buzz_head_toward = ini.get_value_bool(0); else if (ini.is_value("regroup_formation_on_buzz_pass_by")) data.regroup_formation_on_buzz_pass_by = ini.get_value_bool(0); else if (ini.is_value("regroup_formation_on_evade_break")) data.regroup_formation_on_evade_break = ini.get_value_bool(0); else if (ini.is_value("regroup_formation_on_evade_dodge")) data.regroup_formation_on_evade_dodge = ini.get_value_bool(0); else if (ini.is_value("force_attack_formation_active_time")) data.force_attack_formation_active_time = ini.get_value_float(0); else if (ini.is_value("force_attack_formation_unactive_time")) data.force_attack_formation_unactive_time = ini.get_value_float(0); else if (ini.is_value("leader_makes_me_tougher")) data.leader_makes_me_tougher = ini.get_value_bool(0); else if (ini.is_value("formation_exit_max_time")) data.formation_exit_max_time = ini.get_value_float(0); else if (ini.is_value("formation_exit_mode")) data.formation_exit_mode = ini.get_value_int(0); else if (ini.is_value("formation_exit_roll_outrun_throttle")) data.formation_exit_roll_outrun_throttle = ini.get_value_float(0); } if (!nick.empty()) formation[std::move(nick)] = data; } void GetDifficulty(INI_Reader& ini, int& difficulty) { const std::string str = ToLower(ini.get_value_string(0)); if (str == "easiest") difficulty = 0; else if (str == "easy") difficulty = 1; else if (str == "equal") difficulty = 2; else if (str == "hard") difficulty = 3; else { difficulty = 4; } } void LoadJob(INI_Reader& ini) { pub::AI::Personality::JobStruct data; std::string nick; // attack_preference = anything, 5000, GUNS | GUIDED | UNGUIDED // Missing Attack Order / Attack Sub target - more complex while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("allow_player_targeting")) data.allow_player_targeting = ToLower(ini.get_value_string()) == "true"; else if (ini.is_value("force_attack_formation")) data.force_attack_formation = ToLower(ini.get_value_string()) == "true"; else if (ini.is_value("force_attack_formation_used")) data.force_attack_formation_used = ToLower(ini.get_value_string()) == "true"; else if (ini.is_value("combat_drift_distance")) data.combat_drift_distance = ini.get_value_float(0); else if (ini.is_value("flee_scene_threat_style")) { GetDifficulty(ini, data.flee_scene_threat_style); } else if (ini.is_value("field_targeting")) { const std::string str = ToLower(ini.get_value_string(0)); if (str == "never") data.field_targeting = 0; else if (str == "low_density") data.field_targeting = 1; else if (str == "high_density") data.field_targeting = 2; else if (str == "always") data.field_targeting = 3; } else if (ini.is_value("flee_no_weapons_style")) data.flee_no_weapons_style = ToLower(ini.get_value_string()) == "true"; else if (ini.is_value("target_toughness_preference")) { GetDifficulty(ini, data.target_toughness_preference); } else if (ini.is_value("loot_flee_threshold")) { GetDifficulty(ini, data.loot_flee_threshold); } else if (ini.is_value("wait_for_leader_target")) data.wait_for_leader_target = ini.get_value_bool(0); else if (ini.is_value("flee_when_leader_flees_style")) data.flee_when_leader_flees_style = ini.get_value_bool(0); else if (ini.is_value("maximum_leader_target_distance")) data.maximum_leader_target_distance = ini.get_value_float(0); else if (ini.is_value("flee_when_hull_damaged_percent")) data.flee_when_hull_damaged_percent = ini.get_value_float(0); else if (ini.is_value("loot_preference")) { const std::string str = ini.get_value_string(0); if (str.find("LT_COMMODITIES")) data.loot_preference |= 1; if (str.find("LT_EQUIPMENT")) data.loot_preference |= 2; if (str.find("LT_POTIONS")) data.loot_preference |= 4; if (str.find("LT_ALL")) data.loot_preference = 7; if (str.find("LT_NONE")) data.loot_preference = 0; } else if (ini.is_value("scene_toughness_threshold")) { GetDifficulty(ini, data.scene_toughness_threshold); } } if (!nick.empty()) job[std::move(nick)] = data; } void LoadMissile(INI_Reader& ini) { pub::AI::Personality::MissileUseStruct data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); else if (ini.is_value("anti_cruise_missile_interval_time")) data.anti_cruise_missile_interval_time = ini.get_value_float(0); else if (ini.is_value("anti_cruise_missile_max_distance")) data.anti_cruise_missile_max_distance = ini.get_value_float(0); else if (ini.is_value("anti_cruise_missile_min_distance")) data.anti_cruise_missile_min_distance = ini.get_value_float(0); else if (ini.is_value("anti_cruise_missile_pre_fire_delay")) data.anti_cruise_missile_pre_fire_delay = ini.get_value_float(0); else if (ini.is_value("missile_launch_allow_out_of_range")) data.missile_launch_allow_out_of_range = ini.get_value_bool(0); else if (ini.is_value("missile_launch_cone_angle")) data.missile_launch_cone_angle = ini.get_value_float(0); else if (ini.is_value("missile_launch_interval_time")) data.missile_launch_interval_time = ini.get_value_float(0); else if (ini.is_value("missile_launch_interval_variance_percent")) data.missile_launch_interval_variance_percent = ini.get_value_float(0); else if (ini.is_value("missile_launch_range")) data.missile_launch_range = ini.get_value_float(0); } if (!nick.empty()) missile[std::move(nick)] = data; } void LoadPilot(INI_Reader& ini) { pub::AI::Personality data; std::string nick; while (ini.read_value()) { if (ini.is_value("nickname")) nick = ini.get_value_string(); if (ini.is_value("gun_id")) { if (const auto entity = gun.find(ini.get_value_string()); entity != gun.end()) data.GunUse = entity->second; } else if (ini.is_value("missile_id")) { if (const auto entity = missile.find(ini.get_value_string()); entity != missile.end()) data.MissileUse = entity->second; } else if (ini.is_value("evade_dodge_id")) { if (const auto entity = evadeDodge.find(ini.get_value_string()); entity != evadeDodge.end()) data.EvadeDodgeUse = entity->second; } else if (ini.is_value("evade_break_id")) { if (const auto entity = evadeBreak.find(ini.get_value_string()); entity != evadeBreak.end()) data.EvadeBreakUse = entity->second; } else if (ini.is_value("buzz_head_toward_id")) { if (const auto entity = buzzHead.find(ini.get_value_string()); entity != buzzHead.end()) data.BuzzHeadTowardUse = entity->second; } else if (ini.is_value("buzz_pass_by_id")) { if (const auto entity = buzzPass.find(ini.get_value_string()); entity != buzzPass.end()) data.BuzzPassByUse = entity->second; } else if (ini.is_value("trail_id")) { if (const auto entity = trail.find(ini.get_value_string()); entity != trail.end()) data.TrailUse = entity->second; } else if (ini.is_value("strafe_id")) { if (const auto entity = strafe.find(ini.get_value_string()); entity != strafe.end()) data.StrafeUse = entity->second; } else if (ini.is_value("engine_kill_id")) { if (const auto entity = engineKill.find(ini.get_value_string()); entity != engineKill.end()) data.EngineKillUse = entity->second; } else if (ini.is_value("mine_id")) { if (const auto entity = mine.find(ini.get_value_string()); entity != mine.end()) data.MineUse = entity->second; } else if (ini.is_value("countermeasure_id")) { if (const auto entity = cm.find(ini.get_value_string()); entity != cm.end()) data.CountermeasureUse = entity->second; } else if (ini.is_value("damage_reaction_id")) { if (const auto entity = damageReaction.find(ini.get_value_string()); entity != damageReaction.end()) data.DamageReaction = entity->second; } else if (ini.is_value("missile_reaction_id")) { if (const auto entity = missileReaction.find(ini.get_value_string()); entity != missileReaction.end()) data.MissileReaction = entity->second; } else if (ini.is_value("formation_id")) { if (const auto entity = formation.find(ini.get_value_string()); entity != formation.end()) data.FormationUse = entity->second; } else if (ini.is_value("repair_id")) { if (const auto entity = repair.find(ini.get_value_string()); entity != repair.end()) data.RepairUse = entity->second; } else if (ini.is_value("job_id")) { if (const auto entity = job.find(ini.get_value_string()); entity != job.end()) data.Job = entity->second; } } pilots[std::move(nick)] = data; } void LoadPersonalities() { pilots.clear(); evadeBreak.clear(); evadeDodge.clear(); buzzHead.clear(); buzzPass.clear(); trail.clear(); engineKill.clear(); repair.clear(); gun.clear(); mine.clear(); missileReaction.clear(); damageReaction.clear(); cm.clear(); formation.clear(); job.clear(); INI_Reader ini; if (!ini.open(R"(..\DATA\MISSIONS\pilots_population.ini)", false)) { Console::ConWarn("Unable to parse pilot_population"); return; } Console::ConInfo("Parsing Pilot Population"); while (ini.read_header()) { if (ini.is_header("EvadeDodgeBlock")) LoadEvadeDodge(ini); else if (ini.is_header("EvadeBreakBlock")) LoadEvadeBreak(ini); else if (ini.is_header("BuzzHeadTowardBlock")) LoadBuzzHead(ini); else if (ini.is_header("BuzzPassByBlock")) LoadBuzzPass(ini); else if (ini.is_header("TrailBlock")) LoadTrail(ini); else if (ini.is_header("StrafeBlock")) LoadStrafe(ini); else if (ini.is_header("EngineKillBlock")) LoadEngineKill(ini); else if (ini.is_header("RepairBlock")) LoadRepair(ini); else if (ini.is_header("GunBlock")) LoadGun(ini); else if (ini.is_header("MineBlock")) LoadMine(ini); else if (ini.is_header("MissileBlock")) LoadMissile(ini); else if (ini.is_header("DamageReactionBlock")) LoadDamageReaction(ini); else if (ini.is_header("MissileReactionBlock")) LoadMissileReaction(ini); else if (ini.is_header("CountermeasureBlock")) LoadCM(ini); else if (ini.is_header("FormationBlock")) LoadFormation(ini); else if (ini.is_header("JobBlock")) LoadJob(ini); else if (ini.is_header("Pilot")) LoadPilot(ini); } Console::ConInfo(std::format("Parsed Pilot Population: {} personalities", pilots.size())); } } // namespace Hk::Personalities
33,090
C++
.cpp
790
37.826582
106
0.69388
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,399
Ini.cpp
TheStarport_FLHook/source/Helpers/Ini.cpp
#include "Global.hpp" namespace Hk::Ini { struct FLHOOK_PLAYER_DATA { std::string charfilename; std::map<std::wstring, std::wstring> lines; }; std::map<uint, FLHOOK_PLAYER_DATA> clients; std::string GetAccountDir(ClientId client) { static _GetFLName GetFLName = (_GetFLName)((char*)hModServer + 0x66370); char dirname[1024]; GetFLName(dirname, Players[client].Account->wszAccId); return dirname; } std::string GetCharfilename(const std::wstring& charname) { static _GetFLName GetFLName = (_GetFLName)((char*)hModServer + 0x66370); char filename[1024]; GetFLName(filename, charname.c_str()); return filename; } static PlayerData* CurrPlayer; int __stdcall Cb_UpdateFile(char* filename, wchar_t* savetime, int b) { // Call the original save charfile function int retv = 0; __asm { pushad mov ecx, [CurrPlayer] push b push savetime push filename mov eax, 0x6d4ccd0 call eax mov retv, eax popad } // Readd the flhook section. if (retv) { ClientId client = CurrPlayer->iOnlineId; std::string path = CoreGlobals::c()->accPath + GetAccountDir(client) + "\\" + filename; const bool encryptFiles = !FLHookConfig::c()->general.disableCharfileEncryption; const auto writeFlhookSection = [client](std::string& str) { str += "\n[flhook]\n"; for (const auto& [key, value] : clients[client].lines) { str += wstos(std::format(L"{} = {}\n", key, value)); } }; std::fstream saveFile; std::string data; if (encryptFiles) { saveFile.open(path, std::ios::ate | std::ios::in | std::ios::out | std::ios::binary); // Copy old version that we plan to rewrite auto size = static_cast<size_t>(saveFile.tellg()); std::string buffer(size, ' '); saveFile.seekg(0); saveFile.read(&buffer[0], size); // Reset the file pointer so we can start overwriting saveFile.seekg(0); buffer = FlcDecode(buffer); writeFlhookSection(buffer); data = FlcEncode(buffer); } else { saveFile.open(path, std::ios::app | std::ios::binary); writeFlhookSection(data); } saveFile.write(data.c_str(), data.size()); saveFile.close(); } return retv; } __declspec(naked) void Cb_UpdateFileNaked() { __asm { mov CurrPlayer, ecx jmp Cb_UpdateFile } } void CharacterClearClientInfo(ClientId client) { clients.erase(client); } void CharacterSelect(CHARACTER_ID const charId, ClientId client) { std::string path = CoreGlobals::c()->accPath + GetAccountDir(client) + "\\" + charId.szCharFilename; clients[client].charfilename = charId.szCharFilename; clients[client].lines.clear(); // Read the flhook section so that we can rewrite after the save so that it isn't lost INI_Reader ini; if (ini.open(path.c_str(), false)) { while (ini.read_header()) { if (ini.is_header("flhook")) { std::wstring tag; while (ini.read_value()) { clients[client].lines[stows(ini.get_name_ptr())] = stows(ini.get_value_string()); } } } ini.close(); } } static bool patched = false; void CharacterInit() { clients.clear(); if (patched) return; PatchCallAddr((char*)hModServer, 0x6c547, (char*)Cb_UpdateFileNaked); PatchCallAddr((char*)hModServer, 0x6c9cd, (char*)Cb_UpdateFileNaked); patched = true; } void CharacterShutdown() { if (!patched) return; BYTE patch[] = {0xE8, 0x84, 0x07, 0x00, 0x00}; WriteProcMem((char*)hModServer + 0x6c547, patch, 5); BYTE patch2[] = {0xE8, 0xFE, 0x2, 0x00, 0x00}; WriteProcMem((char*)hModServer + 0x6c9cd, patch2, 5); patched = false; } cpp::result<std::wstring, Error> GetFromPlayerFile(const std::variant<uint, std::wstring>& player, const std::wstring& wscKey) { std::wstring ret; const auto client = Hk::Client::ExtractClientID(player); const auto acc = Hk::Client::GetAccountByClientID(client); auto dir = Hk::Client::GetAccountDirName(acc); auto file = Hk::Client::GetCharFileName(player); if (file.has_error()) { return cpp::fail(file.error()); } if (const std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; Hk::Client::IsEncoded(scCharFile)) { const std::string scCharFileNew = scCharFile + ".ini"; if (!FlcDecodeFile(scCharFile.c_str(), scCharFileNew.c_str())) return cpp::fail(Error::CouldNotDecodeCharFile); ret = stows(IniGetS(scCharFileNew, "Player", wstos(wscKey), "")); DeleteFile(scCharFileNew.c_str()); } else { ret = stows(IniGetS(scCharFile, "Player", wstos(wscKey), "")); } return ret; } cpp::result<void, Error> WriteToPlayerFile(const std::variant<uint, std::wstring>& player, const std::wstring& wscKey, const std::wstring& wscValue) { const auto client = Hk::Client::ExtractClientID(player); const auto acc = Hk::Client::GetAccountByClientID(client); auto dir = Hk::Client::GetAccountDirName(acc); auto file = Hk::Client::GetCharFileName(player); if (file.has_error()) { return cpp::fail(file.error()); } if (std::string scCharFile = CoreGlobals::c()->accPath + wstos(dir) + "\\" + wstos(file.value()) + ".fl"; Hk::Client::IsEncoded(scCharFile)) { std::string scCharFileNew = scCharFile + ".ini"; if (!FlcDecodeFile(scCharFile.c_str(), scCharFileNew.c_str())) return cpp::fail(Error::CouldNotDecodeCharFile); IniWrite(scCharFileNew, "Player", wstos(wscKey), wstos(wscValue)); // keep decoded DeleteFile(scCharFile.c_str()); MoveFile(scCharFileNew.c_str(), scCharFile.c_str()); } else { IniWrite(scCharFile, "Player", wstos(wscKey), wstos(wscValue)); } return {}; } std::wstring GetCharacterIniString(ClientId client, const std::wstring& name) { if (!clients.contains(client)) return L""; if (!clients[client].charfilename.length()) return L""; if (!clients[client].lines.contains(name)) return L""; auto line = clients[client].lines[name]; return line; } void SetCharacterIni(ClientId client, const std::wstring& name, std::wstring value) { clients[client].lines[name] = std::move(value); } bool GetCharacterIniBool(ClientId client, const std::wstring& name) { const auto val = GetCharacterIniString(client, name); return val == L"true" || val == L"1"; } int GetCharacterIniInt(ClientId client, const std::wstring& name) { const auto val = GetCharacterIniString(client, name); return wcstol(val.c_str(), nullptr, 10); } uint GetCharacterIniUint(ClientId client, const std::wstring& name) { const auto val = GetCharacterIniString(client, name); return wcstoul(val.c_str(), nullptr, 10); } float GetCharacterIniFloat(ClientId client, const std::wstring& name) { const auto val = GetCharacterIniString(client, name); return wcstof(val.c_str(), nullptr); } double GetCharacterIniDouble(ClientId client, const std::wstring& name) { const auto val = GetCharacterIniString(client, name); return wcstod(val.c_str(), nullptr); } int64 GetCharacterIniInt64(ClientId client, const std::wstring& name) { const auto val = GetCharacterIniString(client, name); return wcstoll(val.c_str(), nullptr, 10); } } // namespace Hk::Ini
7,195
C++
.cpp
227
28.220264
149
0.695275
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,400
Message.cpp
TheStarport_FLHook/source/Helpers/Message.cpp
#include <Global.hpp> // Very hacky way to call non-header function namespace IServerImplHook { void __stdcall SubmitChat(CHAT_ID cidFrom, ulong size, void const* rdlReader, CHAT_ID cidTo, int _genArg1); } bool g_bMsg; bool g_bMsgU; bool g_bMsgS; _RCSendChatMsg RCSendChatMsg; namespace Hk::Message { cpp::result<void, Error> Msg(const std::variant<uint, std::wstring>& player, const std::wstring& message) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); const CHAT_ID ci = {0}; const CHAT_ID ciClient = {client}; const std::wstring wscXML = L"<TRA data=\"0x19BD3A00\" mask=\"-1\"/><TEXT>" + XMLText(message) + L"</TEXT>"; uint iRet; char szBuf[1024]; if (const auto err = FMsgEncodeXML(wscXML, szBuf, sizeof(szBuf), iRet); err.has_error()) return cpp::fail(err.error()); IServerImplHook::SubmitChat(ci, iRet, szBuf, ciClient, -1); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> MsgS(const std::variant<std::wstring, uint>& system, const std::wstring& message) { uint systemId = 0; if (!system.index()) { std::wstring systemName = std::get<std::wstring>(system); pub::GetSystemID(systemId, wstos(systemName).c_str()); } else { systemId = std::get<uint>(system); } // prepare xml const std::wstring xml = L"<TRA data=\"0xE6C68400\" mask=\"-1\"/><TEXT>" + XMLText(message) + L"</TEXT>"; uint ret; char buffer[1024]; if (const auto err = FMsgEncodeXML(xml, buffer, sizeof(buffer), ret); err.has_error()) return cpp::fail(err.error()); const CHAT_ID ci = {0}; // for all players in system... for (auto player : Hk::Client::getAllPlayersInSystem(systemId)) { const CHAT_ID ciClient = {player}; IServerImplHook::SubmitChat(ci, ret, buffer, ciClient, -1); } return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> MsgU(const std::wstring& message) { const CHAT_ID ci = {0}; const CHAT_ID ciClient = {0x00010000}; const std::wstring xml = L"<TRA font=\"1\" color=\"#FFFFFF\"/><TEXT>" + XMLText(message) + L"</TEXT>"; uint iRet; char szBuf[1024]; if (const auto err = FMsgEncodeXML(xml, szBuf, sizeof(szBuf), iRet); err.has_error()) return cpp::fail(err.error()); IServerImplHook::SubmitChat(ci, iRet, szBuf, ciClient, -1); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> FMsgEncodeXML(const std::wstring& xmlString, char* buffer, uint size, uint& ret) { XMLReader rdr; RenderDisplayList rdl; std::wstring wscMsg = L"<?xml version=\"1.0\" encoding=\"UTF-16\"?><RDL><PUSH/>"; wscMsg += xmlString; wscMsg += L"<PARA/><POP/></RDL>\x000A\x000A"; if (!rdr.read_buffer(rdl, (const char*)wscMsg.c_str(), wscMsg.length() * 2)) return cpp::fail(Error::WrongXmlSyntax); BinaryRDLWriter rdlwrite; rdlwrite.write_buffer(rdl, buffer, size, ret); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void FMsgSendChat(ClientId client, char* buffer, uint size) { auto p4 = (uint)buffer; uint p3 = size; uint p2 = 0x00010000; uint p1 = client; __asm { push [p4] push [p3] push [p2] push [p1] mov ecx, [HookClient] add ecx, 4 call [RCSendChatMsg] } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> FMsg(ClientId client, const std::wstring& xmlString) { char szBuf[0xFFFF]; uint iRet; if (const auto err = FMsgEncodeXML(xmlString, szBuf, sizeof(szBuf), iRet); err.has_error()) return cpp::fail(err.error()); FMsgSendChat(client, szBuf, iRet); return {}; } cpp::result<void, Error> FMsg(const std::variant<uint, std::wstring>& player, const std::wstring& xmlString) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX) return cpp::fail(Error::PlayerNotLoggedIn); return FMsg(client, xmlString); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> FMsgS(const std::variant<std::wstring, uint>& system, const std::wstring& xmlString) { uint systemId = 0; if (!system.index()) { std::wstring systemName = std::get<std::wstring>(system); pub::GetSystemID(systemId, wstos(systemName).c_str()); } else { systemId = std::get<uint>(system); } // encode xml std::string char szBuf[0xFFFF]; uint iRet; if (const auto err = FMsgEncodeXML(xmlString, szBuf, sizeof(szBuf), iRet); err.has_error()) return cpp::fail(err.error()); // for all players in system... for (auto player : Hk::Client::getAllPlayersInSystem(systemId)) { FMsgSendChat(player, szBuf, iRet); } return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> FMsgU(const std::wstring& xmlString) { // encode xml std::string char szBuf[0xFFFF]; uint iRet; const auto err = FMsgEncodeXML(xmlString, szBuf, sizeof(szBuf), iRet); if (err.has_error()) return cpp::fail(err.error()); // for all players PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { ClientId client = playerDb->iOnlineId; FMsgSendChat(client, szBuf, iRet); } return {}; } /** Format a chat std::string in accordance with the receiver's preferences and send it. Will check that the receiver accepts messages from sender and refuses to send if necessary. */ cpp::result<void, Error> FormatSendChat(uint toClientId, const std::wstring& sender, const std::wstring& text, const std::wstring& textColor) { #define HAS_FLAG(a, b) ((a).wscFlags.find(b) != -1) if (FLHookConfig::i()->userCommands.userCmdIgnore) { for (const auto& ignore : ClientInfo[toClientId].lstIgnore) { if (!HAS_FLAG(ignore, L"i") && !(ToLower(sender).compare(ToLower(ignore.character)))) return {}; // ignored else if (HAS_FLAG(ignore, L"i") && (ToLower(sender).find(ToLower(ignore.character)) != -1)) return {}; // ignored } } uchar cFormat; // adjust chatsize switch (ClientInfo[toClientId].chatSize) { case CS_SMALL: cFormat = 0x90; break; case CS_BIG: cFormat = 0x10; break; default: cFormat = 0x00; break; } // adjust chatstyle switch (ClientInfo[toClientId].chatStyle) { case CST_BOLD: cFormat += 0x01; break; case CST_ITALIC: cFormat += 0x02; break; case CST_UNDERLINE: cFormat += 0x04; break; default: cFormat += 0x00; break; } wchar_t wszFormatBuf[8]; swprintf(wszFormatBuf, _countof(wszFormatBuf), L"%02X", (long)cFormat); const std::wstring wscTRADataFormat = wszFormatBuf; const std::wstring wscTRADataSenderColor = L"FFFFFF"; // white const std::wstring wscXML = L"<TRA data=\"0x" + wscTRADataSenderColor + wscTRADataFormat + L"\" mask=\"-1\"/><TEXT>" + XMLText(sender) + L": </TEXT>" + L"<TRA data=\"0x" + textColor + wscTRADataFormat + L"\" mask=\"-1\"/><TEXT>" + XMLText(text) + L"</TEXT>"; if (const auto err = FMsg(toClientId, wscXML); err.has_error()) return cpp::fail(err.error()); return {}; } /** Send a player to player message */ cpp::result<void, Error> SendPrivateChat(uint fromClientId, uint toClientId, const std::wstring& text) { const auto wscSender = Client::GetCharacterNameByID(fromClientId); if (wscSender.has_error()) { Console::ConErr(std::format("Unable to send private chat message from client {}", fromClientId)); return {}; } if (FLHookConfig::i()->userCommands.userCmdIgnore) { for (auto const& ignore : ClientInfo[toClientId].lstIgnore) { if (HAS_FLAG(ignore, L"p")) return {}; } } // Send the message to both the sender and receiver. auto err = FormatSendChat(toClientId, wscSender.value(), text, L"19BD3A"); if (err.has_error()) return cpp::fail(err.error()); err = FormatSendChat(fromClientId, wscSender.value(), text, L"19BD3A"); if (err.has_error()) return cpp::fail(err.error()); return {}; } /** Send a player to system message */ void SendSystemChat(uint fromClientId, const std::wstring& text) { const std::wstring wscSender = (const wchar_t*)Players.GetActiveCharacterName(fromClientId); // Get the player's current system. uint systemId; pub::Player::GetSystem(fromClientId, systemId); // For all players in system... for (auto player : Hk::Client::getAllPlayersInSystem(systemId)) { // Send the message a player in this system. FormatSendChat(player, wscSender, text, L"E6C684"); } } /** Send a player to local system message */ void SendLocalSystemChat(uint fromClientId, const std::wstring& text) { // Don't even try to send an empty message if (text.empty()) { return; } const auto wscSender = Client::GetCharacterNameByID(fromClientId); if (wscSender.has_error()) { Console::ConErr(std::format("Unable to send local system chat message from client {}", fromClientId)); return; } // Get the player's current system and location in the system. uint systemId; pub::Player::GetSystem(fromClientId, systemId); uint iFromShip; pub::Player::GetShip(fromClientId, iFromShip); Vector vFromShipLoc; Matrix mFromShipDir; pub::SpaceObj::GetLocation(iFromShip, vFromShipLoc, mFromShipDir); // For all players in system... for (auto player : Hk::Client::getAllPlayersInSystem(systemId)) { uint ship; pub::Player::GetShip(player, ship); Vector vShipLoc; Matrix mShipDir; pub::SpaceObj::GetLocation(ship, vShipLoc, mShipDir); // Cheat in the distance calculation. Ignore the y-axis // Is player within scanner range (15K) of the sending char. if (static_cast<float>(sqrt(pow(vShipLoc.x - vFromShipLoc.x, 2) + pow(vShipLoc.z - vFromShipLoc.z, 2))) > 14999.0f) continue; // Send the message a player in this system. FormatSendChat(player, wscSender.value(), text, L"FF8F40"); } } /** Send a player to group message */ void SendGroupChat(uint fromClientId, const std::wstring& text) { auto wscSender = (const wchar_t*)Players.GetActiveCharacterName(fromClientId); // Format and send the message a player in this group. auto lstMembers = Hk::Player::GetGroupMembers(wscSender); if (lstMembers.has_error()) { return; } for (const auto& gm : lstMembers.value()) { FormatSendChat(gm.client, wscSender, text, L"FF7BFF"); } } std::vector<HINSTANCE> vDLLs; void UnloadStringDLLs() { for (uint i = 0; i < vDLLs.size(); i++) FreeLibrary(vDLLs[i]); vDLLs.clear(); } void LoadStringDLLs() { UnloadStringDLLs(); HINSTANCE hDLL = LoadLibraryEx("resources.dll", nullptr, LOAD_LIBRARY_AS_DATAFILE); // typically resources.dll if (hDLL) vDLLs.push_back(hDLL); INI_Reader ini; if (ini.open("freelancer.ini", false)) { while (ini.read_header()) { if (ini.is_header("Resources")) { while (ini.read_value()) { if (ini.is_value("DLL")) { hDLL = LoadLibraryEx(ini.get_value_string(0), nullptr, LOAD_LIBRARY_AS_DATAFILE); if (hDLL) vDLLs.push_back(hDLL); } } } } ini.close(); } } std::wstring GetWStringFromIdS(uint iIdS) { if (wchar_t wszBuf[1024]; LoadStringW(vDLLs[iIdS >> 16], iIdS & 0xFFFF, wszBuf, 1024)) return wszBuf; return L""; } std::wstring FormatMsg(MessageColor color, MessageFormat format, const std::wstring& msg) { const uint bgrColor = Math::RgbToBgr(static_cast<uint>(color)); const std::wstring tra = Math::UintToHexString(bgrColor, 6, true) + Math::UintToHexString(static_cast<uint>(format), 2); return L"<TRA data=\"" + tra + L"\" mask=\"-1\"/><TEXT>" + XMLText(msg) + L"</TEXT>"; } } // namespace Hk::Message
12,171
C++
.cpp
356
30.691011
142
0.639244
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,401
Admin.cpp
TheStarport_FLHook/source/Helpers/Admin.cpp
#include "Global.hpp" bool g_bNPCDisabled; namespace Hk::Admin { std::wstring GetPlayerIP(ClientId client) { CDPClientProxy const* cdpClient = clientProxyArray[client - 1]; if (!cdpClient) return L""; // get ip char* szP1; char* szIdirectPlay8Address; wchar_t wszHostname[] = L"hostname"; memcpy(&szP1, (char*)cdpSrv + 4, 4); wchar_t wszIP[1024] = L""; long lSize = sizeof(wszIP); long lDataType = 1; __asm { push 0 ; dwFlags lea edx, szIdirectPlay8Address push edx ; pAddress mov edx, [cdpClient] mov edx, [edx+8] push edx ; dpnid mov eax, [szP1] push eax mov ecx, [eax] call dword ptr[ecx + 0x28] ; GetClientAddress cmp eax, 0 jnz some_error lea eax, lDataType push eax lea eax, lSize push eax lea eax, wszIP push eax lea eax, wszHostname push eax mov ecx, [szIdirectPlay8Address] push ecx mov ecx, [ecx] call dword ptr[ecx+0x40] ; GetComponentByName mov ecx, [szIdirectPlay8Address] push ecx mov ecx, [ecx] call dword ptr[ecx+0x08] ; Release some_error: } return wszIP; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<PlayerInfo, Error> GetPlayerInfo(const std::variant<uint, std::wstring>& player, bool bAlsoCharmenu) { ClientId client = Hk::Client::ExtractClientID(player); if (client == UINT_MAX || (Hk::Client::IsInCharSelectMenu(client) && !bAlsoCharmenu)) return cpp::fail(Error::PlayerNotLoggedIn); PlayerInfo pi; const wchar_t* wszActiveCharname = (wchar_t*)Players.GetActiveCharacterName(client); pi.client = client; pi.character = wszActiveCharname ? wszActiveCharname : L""; pi.wscBase = pi.wscSystem = L""; uint iBase = 0; uint iSystem = 0; pub::Player::GetBase(client, iBase); pub::Player::GetSystem(client, iSystem); pub::Player::GetShip(client, pi.ship); if (iBase) { char szBasename[1024] = ""; pub::GetBaseNickname(szBasename, sizeof(szBasename), iBase); pi.wscBase = stows(szBasename); } if (iSystem) { char szSystemname[1024] = ""; pub::GetSystemNickname(szSystemname, sizeof(szSystemname), iSystem); pi.wscSystem = stows(szSystemname); pi.iSystem = iSystem; } // get ping auto ci = GetConnectionStats(client); if (ci.has_error()) { AddLog(LogType::Normal, LogLevel::Warn, wstos(Hk::Err::ErrGetText(ci.error()))); return cpp::fail(Error::PlayerNotLoggedIn); } pi.connectionInfo = ci.value(); // get ip pi.wscIP = GetPlayerIP(client); pi.wscHostname = ClientInfo[client].wscHostname; return pi; } std::list<PlayerInfo> GetPlayers() { std::list<PlayerInfo> lstRet; std::wstring wscRet; PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { ClientId client = playerDb->iOnlineId; if (Hk::Client::IsInCharSelectMenu(client)) continue; auto pi = GetPlayerInfo(client, false); auto a = std::move(pi).value(); lstRet.emplace_back(a); } return lstRet; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<DPN_CONNECTION_INFO, Error> GetConnectionStats(ClientId client) { if (client < 1 || client > MaxClientId) return cpp::fail(Error::InvalidClientId); CDPClientProxy* cdpClient = clientProxyArray[client - 1]; DPN_CONNECTION_INFO ci; if (!cdpClient || !cdpClient->GetConnectionStats(&ci)) return cpp::fail(Error::InvalidClientId); return ci; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> SetAdmin(const std::variant<uint, std::wstring>& player, const std::wstring& wscRights) { auto acc = Hk::Client::ExtractAccount(player); if (acc.has_error()) { return cpp::fail(Error::CharacterDoesNotExist); } auto dir = Hk::Client::GetAccountDirName(acc.value()); std::string scAdminFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookadmin.ini"; IniWrite(scAdminFile, "admin", "rights", wstos(wscRights)); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<std::wstring, Error> GetAdmin(const std::variant<uint, std::wstring>& player) { auto acc = Hk::Client::ExtractAccount(player); if (acc.has_error()) { return cpp::fail(acc.error()); } std::wstring dir = Hk::Client::GetAccountDirName(acc.value()); std::string scAdminFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookadmin.ini"; WIN32_FIND_DATA fd; HANDLE hFind = FindFirstFile(scAdminFile.c_str(), &fd); if (hFind == INVALID_HANDLE_VALUE) { return cpp::fail(Error::NoAdmin); } FindClose(hFind); return stows(IniGetS(scAdminFile, "admin", "rights", "")); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> DelAdmin(const std::variant<uint, std::wstring>& player) { auto acc = Hk::Client::ExtractAccount(player); if (acc.has_error()) { return cpp::fail(acc.error()); } std::wstring dir = Hk::Client::GetAccountDirName(acc.value()); std::string scAdminFile = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookadmin.ini"; DeleteFile(scAdminFile.c_str()); return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<void, Error> ChangeNPCSpawn(bool bDisable) { if (CoreGlobals::c()->disableNpcs && bDisable) return {}; else if (!CoreGlobals::c()->disableNpcs && !bDisable) return {}; char szJump[1]; char szCmp[1]; if (bDisable) { szJump[0] = '\xEB'; szCmp[0] = '\xFF'; } else { szJump[0] = '\x75'; szCmp[0] = '\xF9'; } void* pAddress = CONTENT_ADDR(ADDR_DISABLENPCSPAWNS1); WriteProcMem(pAddress, &szJump, 1); pAddress = CONTENT_ADDR(ADDR_DISABLENPCSPAWNS2); WriteProcMem(pAddress, &szCmp, 1); g_bNPCDisabled = bDisable; return {}; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// cpp::result<BaseHealth, Error> GetBaseStatus(const std::wstring& wscBasename) { uint baseId = 0; pub::GetBaseID(baseId, wstos(wscBasename).c_str()); if (!baseId) { return cpp::fail(Error::InvalidBaseName); } float curHealth; float maxHealth; Universe::IBase const* base = Universe::get_base(baseId); pub::SpaceObj::GetHealth(base->lSpaceObjId, curHealth, maxHealth); BaseHealth bh = {curHealth, maxHealth}; return bh; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// Fuse* GetFuseFromID(uint iFuseId) { int iDunno = 0; Fuse* fuse = nullptr; __asm { mov edx, 0x6CFD390 call edx lea ecx, iFuseId push ecx lea ecx, iDunno push ecx mov ecx, eax mov edx, 0x6D15D10 call edx mov edx, [iDunno] mov edi, [edx+0x10] mov fuse, edi } return fuse; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Return the CEqObj from the IObjRW __declspec(naked) CEqObj* __stdcall GetEqObjFromObjRW_(struct IObjRW* objRW) { __asm { push ecx push edx mov ecx, [esp+12] mov edx, [ecx] call dword ptr[edx+0x150] pop edx pop ecx ret 4 } } CEqObj* GetEqObjFromObjRW(struct IObjRW* objRW) { return GetEqObjFromObjRW_(objRW); } __declspec(naked) bool __stdcall LightFuse_(IObjRW* ship, uint iFuseId, float fDelay, float fLifetime, float fSkip) { __asm { lea eax, [esp+8] // iFuseId push [esp+20] // fSkip push [esp+16] // fDelay push 0 // SUBOBJ_Id_NONE push eax push [esp+32] // fLifetime mov ecx, [esp+24] mov eax, [ecx] call [eax+0x1E4] ret 20 } } bool LightFuse(IObjRW* ship, uint iFuseId, float fDelay, float fLifetime, float fSkip) { return LightFuse_(ship, iFuseId, fDelay, fLifetime, fSkip); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Returns true if a fuse was unlit __declspec(naked) bool __stdcall UnLightFuse_(IObjRW* ship, uint iFuseId, float fDunno) { __asm { mov ecx, [esp+4] lea eax, [esp+8] // iFuseId push [esp+12] // fDunno push 0 // SUBOBJ_Id_NONE push eax // iFuseId mov eax, [ecx] call [eax+0x1E8] ret 12 } } bool UnLightFuse(IObjRW* ship, uint iFuseId) { return UnLightFuse_(ship, iFuseId, 0.f); } } // namespace Hk::Admin
9,039
C++
.cpp
285
27.266667
116
0.567667
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,402
Solar.cpp
TheStarport_FLHook/source/Helpers/Solar.cpp
#include "Global.hpp" namespace Hk::Solar { cpp::result<const SystemId, Error> GetSystemBySpaceId(uint spaceObjId) { uint system; pub::SpaceObj::GetSystem(spaceObjId, system); if (!system) return cpp::fail(Error::InvalidSystem); return system; } cpp::result<std::pair<Vector, Matrix>, Error> GetLocation(uint id, IdType type) { switch (type) { case IdType::Client: { uint ship = 0; pub::Player::GetShip(id, ship); if (!ship) return cpp::fail(Error::PlayerNotInSpace); id = ship; } [[fallthrough]]; case IdType::Solar: { Vector pos; Matrix rot; pub::SpaceObj::GetLocation(id, pos, rot); return std::make_pair(pos, rot); break; } default: return cpp::fail(Error::InvalidIdType); } } cpp::result<float, Error> GetMass(uint spaceObjId) { uint system; pub::SpaceObj::GetSystem(spaceObjId, system); if (!system) { return cpp::fail(Error::InvalidSpaceObjId); } float mass; pub::SpaceObj::GetMass(spaceObjId, mass); return mass; } cpp::result<std::pair<Vector, Vector>, Error> GetMotion(uint spaceObjId) { uint system; pub::SpaceObj::GetSystem(spaceObjId, system); if (!system) { return cpp::fail(Error::InvalidSpaceObjId); } Vector v1; Vector v2; pub::SpaceObj::GetMotion(spaceObjId, v1, v2); return std::make_pair(v1, v2); } cpp::result<uint, Error> GetType(uint spaceObjId) { uint system; pub::SpaceObj::GetSystem(spaceObjId, system); if (!system) { return cpp::fail(Error::InvalidSpaceObjId); } uint type; pub::SpaceObj::GetType(spaceObjId, type); return type; } cpp::result<Universe::IBase*, Error> GetBaseByWildcard(const std::wstring& targetBaseName) { // Search for an exact match at the start of the name Universe::IBase* baseinfo = Universe::GetFirstBase(); while (baseinfo) { char baseNickname[1024] = ""; pub::GetBaseNickname(baseNickname, sizeof(baseNickname), baseinfo->baseId); if (std::wstring basename = Hk::Message::GetWStringFromIdS(baseinfo->baseIdS); ToLower(stows(baseNickname)) == ToLower(targetBaseName) || ToLower(basename).find(ToLower(targetBaseName)) == 0) { return baseinfo; } baseinfo = Universe::GetNextBase(); } // Exact match failed, try a for an partial match baseinfo = Universe::GetFirstBase(); while (baseinfo) { if (std::wstring basename = Hk::Message::GetWStringFromIdS(baseinfo->baseIdS); ToLower(basename).find(ToLower(targetBaseName)) != -1) { return baseinfo; } baseinfo = Universe::GetNextBase(); } return cpp::fail(Error::InvalidBase); } cpp::result<uint, Error> GetAffiliation(BaseId solarId) { int solarRep; pub::SpaceObj::GetSolarRep(solarId, solarRep); if (solarRep == -1) { return cpp::fail(Error::InvalidBase); } uint baseAff; pub::Reputation::GetAffiliation(solarRep, baseAff); if (baseAff == UINT_MAX) { return cpp::fail(Error::InvalidRepGroup); } return baseAff; } cpp::result<float, Error> GetCommodityPrice(BaseId baseId, GoodId goodId) { float nomPrice; pub::Market::GetNominalPrice(goodId, nomPrice); if (nomPrice == 0.0f) { return cpp::fail(Error::InvalidGood); } float price; pub::Market::GetPrice(baseId, goodId, price); if (price == -1) { return cpp::fail(Error::InvalidBase); } return price; } } // namespace Hk::Solar
3,380
C++
.cpp
131
22.465649
136
0.698702
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,403
Math.cpp
TheStarport_FLHook/source/Helpers/Math.cpp
#include "Global.hpp" namespace Hk::Math { float Distance3D(Vector v1, Vector v2) { const float sq1 = v1.x - v2.x; const float sq2 = v1.y - v2.y; const float sq3 = v1.z - v2.z; return sqrt(sq1 * sq1 + sq2 * sq2 + sq3 * sq3); } cpp::result<float, Error> Distance3DByShip(uint ship1, uint ship2) { Vector v1; Matrix m1; pub::SpaceObj::GetLocation(ship1, v1, m1); if (v1.x == 0.f && v1.y == 0.f && v1.z == 0.f) return cpp::fail(Error::InvalidShip); Vector v2; Matrix m2; pub::SpaceObj::GetLocation(ship2, v2, m2); if (v2.x == 0.f && v2.y == 0.f && v2.z == 0.f) return cpp::fail(Error::InvalidShip); return Distance3D(v1, v2); } Quaternion MatrixToQuaternion(const Matrix& m) { Quaternion quaternion; quaternion.w = sqrt(std::max(0.0f, 1.0f + m.data[0][0] + m.data[1][1] + m.data[2][2])) / 2; quaternion.x = sqrt(std::max(0.0f, 1.0f + m.data[0][0] - m.data[1][1] - m.data[2][2])) / 2; quaternion.y = sqrt(std::max(0.0f, 1.0f - m.data[0][0] + m.data[1][1] - m.data[2][2])) / 2; quaternion.z = sqrt(std::max(0.0f, 1.0f - m.data[0][0] - m.data[1][1] + m.data[2][2])) / 2; quaternion.x = (float)_copysign(quaternion.x, m.data[2][1] - m.data[1][2]); quaternion.y = (float)_copysign(quaternion.y, m.data[0][2] - m.data[2][0]); quaternion.z = (float)_copysign(quaternion.z, m.data[1][0] - m.data[0][1]); return quaternion; } template<typename Str> Str VectorToSectorCoord(uint systemId, Vector vPos) { float scale = 1.0; if (const Universe::ISystem* iSystem = Universe::get_system(systemId)) scale = iSystem->NavMapScale; const float fGridSize = 34000.0f / scale; int gridRefX = (int)((vPos.x + (fGridSize * 5)) / fGridSize) - 1; int gridRefZ = (int)((vPos.z + (fGridSize * 5)) / fGridSize) - 1; gridRefX = std::min(std::max(gridRefX, 0), 7); char scXPos = 'A' + char(gridRefX); gridRefZ = std::min(std::max(gridRefZ, 0), 7); char scZPos = '1' + char(gridRefZ); typename Str::value_type szCurrentLocation[100]; if constexpr (std::is_same_v<Str, std::string>) _snprintf_s(szCurrentLocation, sizeof(szCurrentLocation), "%c-%c", scXPos, scZPos); else _snwprintf_s(szCurrentLocation, sizeof(szCurrentLocation), L"%C-%C", scXPos, scZPos); return szCurrentLocation; } constexpr float PI = std::numbers::pi_v<float>; // Convert radians to degrees. float Degrees(float rad) { rad *= 180 / PI; // Prevent displaying -0 and prefer 180 to -180. if (rad < 0) { if (rad > -0.005f) rad = 0; else if (rad <= -179.995f) rad = 180; } // Round to two decimal places here, so %g can display it without decimals. if (const float frac = modff(rad * 100, &rad); frac >= 0.5f) ++rad; else if (frac <= -0.5f) --rad; return rad / 100; } // Convert an orientation matrix to a pitch/yaw/roll vector. Based on what // Freelancer does for the save game. Vector MatrixToEuler(const Matrix& mat) { const Vector x = {mat.data[0][0], mat.data[1][0], mat.data[2][0]}; const Vector y = {mat.data[0][1], mat.data[1][1], mat.data[2][1]}; const Vector z = {mat.data[0][2], mat.data[1][2], mat.data[2][2]}; Vector vec; if (const auto h = static_cast<float>(_hypot(x.x, x.y)); h > 1 / 524288.0f) { vec.x = Degrees(atan2f(y.z, z.z)); vec.y = Degrees(atan2f(-x.z, h)); vec.z = Degrees(atan2f(x.y, x.x)); } else { vec.x = Degrees(atan2f(-z.y, y.y)); vec.y = Degrees(atan2f(-x.z, h)); vec.z = 0; } return vec; } uint RgbToBgr(uint color) { return (color & 0xFF000000) | ((color & 0xFF0000) >> 16) | (color & 0x00FF00) | ((color & 0x0000FF) << 16); }; std::wstring UintToHexString(uint number, uint width, bool addPrefix) { std::wstringstream stream; if (addPrefix) { stream << L"0x"; } stream << std::setfill(L'0') << std::setw(width) << std::hex << number; return stream.str(); } }
3,858
C++
.cpp
111
31.693694
139
0.633387
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,404
ZoneUtilities.cpp
TheStarport_FLHook/source/Helpers/ZoneUtilities.cpp
#include "Global.hpp" namespace Hk::ZoneUtilities { /** A map of system id to system info */ std::map<uint, SystemInfo> mapSystems; /** A map of system id to zones */ std::multimap<uint, Zone> allZones; /** A map of system id to JumpPoint info */ std::multimap<uint, JumpPoint> JumpPoints; /** Multiply mat1 by mat2 and return the result */ static TransformMatrix MultiplyMatrix(const TransformMatrix& mat1, const TransformMatrix& mat2) { TransformMatrix result = {0}; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 4; k++) result.d[i][j] += mat1.d[i][k] * mat2.d[k][j]; return result; } /** Setup of transformation matrix using the vector p and the rotation r */ static TransformMatrix SetupTransform(const Vector& p, const Vector& r) { // Convert degrees into radians float ax = r.x * (static_cast<float>(std::numbers::pi) / 180); float ay = r.y * (static_cast<float>(std::numbers::pi) / 180); float az = r.z * (static_cast<float>(std::numbers::pi) / 180); // Initial matrix TransformMatrix smat = {0}; smat.d[0][0] = smat.d[1][1] = smat.d[2][2] = smat.d[3][3] = 1; // Translation matrix TransformMatrix tmat; tmat.d[0][0] = 1; tmat.d[0][1] = 0; tmat.d[0][2] = 0; tmat.d[0][3] = 0; tmat.d[1][0] = 0; tmat.d[1][1] = 1; tmat.d[1][2] = 0; tmat.d[1][3] = 0; tmat.d[2][0] = 0; tmat.d[2][1] = 0; tmat.d[2][2] = 1; tmat.d[2][3] = 0; tmat.d[3][0] = -p.x; tmat.d[3][1] = -p.y; tmat.d[3][2] = -p.z; tmat.d[3][3] = 1; // X-axis rotation matrix TransformMatrix xmat; xmat.d[0][0] = 1; xmat.d[0][1] = 0; xmat.d[0][2] = 0; xmat.d[0][3] = 0; xmat.d[1][0] = 0; xmat.d[1][1] = std::cos(ax); xmat.d[1][2] = std::sin(ax); xmat.d[1][3] = 0; xmat.d[2][0] = 0; xmat.d[2][1] = -std::sin(ax); xmat.d[2][2] = std::cos(ax); xmat.d[2][3] = 0; xmat.d[3][0] = 0; xmat.d[3][1] = 0; xmat.d[3][2] = 0; xmat.d[3][3] = 1; // Y-axis rotation matrix TransformMatrix ymat; ymat.d[0][0] = std::cos(ay); ymat.d[0][1] = 0; ymat.d[0][2] = -std::sin(ay); ymat.d[0][3] = 0; ymat.d[1][0] = 0; ymat.d[1][1] = 1; ymat.d[1][2] = 0; ymat.d[1][3] = 0; ymat.d[2][0] = std::sin(ay); ymat.d[2][1] = 0; ymat.d[2][2] = std::cos(ay); ymat.d[2][3] = 0; ymat.d[3][0] = 0; ymat.d[3][1] = 0; ymat.d[3][2] = 0; ymat.d[3][3] = 1; // Z-axis rotation matrix TransformMatrix zmat; zmat.d[0][0] = std::cos(az); zmat.d[0][1] = std::sin(az); zmat.d[0][2] = 0; zmat.d[0][3] = 0; zmat.d[1][0] = -std::sin(az); zmat.d[1][1] = std::cos(az); zmat.d[1][2] = 0; zmat.d[1][3] = 0; zmat.d[2][0] = 0; zmat.d[2][1] = 0; zmat.d[2][2] = 1; zmat.d[2][3] = 0; zmat.d[3][0] = 0; zmat.d[3][1] = 0; zmat.d[3][2] = 0; zmat.d[3][3] = 1; TransformMatrix tm; tm = MultiplyMatrix(smat, tmat); tm = MultiplyMatrix(tm, xmat); tm = MultiplyMatrix(tm, ymat); tm = MultiplyMatrix(tm, zmat); return tm; } /** Parse the specified ini file (usually in the data/solar/asteriods) and retrieve the lootable zone details. */ void ZoneUtilities::ReadLootableZone(std::multimap<uint, LootableZone, std::less<>>& zones, const std::string& systemNick, const std::string& defaultZoneNick, const std::string& file) { std::string path = "..\\data\\"; path += file; INI_Reader ini; if (ini.open(path.c_str(), false)) { while (ini.read_header()) { if (ini.is_header("LootableZone")) { std::string zoneNick = defaultZoneNick; std::string crateNick = ""; std::string lootNick = ""; int iMinLoot = 0; int iMaxLoot = 0; uint iLootDifficulty = 0; while (ini.read_value()) { if (ini.is_value("zone")) { zoneNick = ToLower(ini.get_value_string()); } else if (ini.is_value("dynamic_loot_container")) { crateNick = ToLower(ini.get_value_string()); } else if (ini.is_value("dynamic_loot_commodity")) { lootNick = ToLower(ini.get_value_string()); } else if (ini.is_value("dynamic_loot_count")) { iMinLoot = ini.get_value_int(0); iMaxLoot = ini.get_value_int(1); } else if (ini.is_value("dynamic_loot_difficulty")) { iLootDifficulty = ini.get_value_int(0); } } LootableZone lz; lz.systemId = CreateID(systemNick.c_str()); lz.zoneNick = zoneNick; lz.lootNick = lootNick; lz.iLootId = CreateID(lootNick.c_str()); lz.iCrateId = CreateID(crateNick.c_str()); lz.iMinLoot = iMinLoot; lz.iMaxLoot = iMaxLoot; lz.iLootDifficulty = iLootDifficulty; lz.pos.x = lz.pos.y = lz.pos.z = 0; lz.size.x = lz.size.y = lz.size.z = 0; bool exists = false; for (const auto& [_, zone] : zones) { if (zone.zoneNick == zoneNick) { exists = true; break; } } if (!exists) zones.insert({lz.systemId, lz}); } } ini.close(); } } /** Read the asteroid sections out of the system ini */ void ZoneUtilities::ReadSystemLootableZones( std::multimap<uint, LootableZone, std::less<>>& zones, const std::string& systemNick, const std::string& file) { std::string path = "..\\data\\universe\\"; path += file; INI_Reader ini; if (ini.open(path.c_str(), false)) { while (ini.read_header()) { if (ini.is_header("Asteroids")) { std::string lootableZonefile = ""; std::string zoneNick = ""; while (ini.read_value()) { if (ini.is_value("zone")) zoneNick = ToLower(ini.get_value_string()); if (ini.is_value("file")) lootableZonefile = ini.get_value_string(); } ReadLootableZone(zones, systemNick, zoneNick, lootableZonefile); } } ini.close(); } } /** Read the zone size/rotation and position information out of the specified file and calcuate the lootable zone transformation matrix */ void ZoneUtilities::ReadSystemZones(std::multimap<uint, LootableZone, std::less<>>& zones, const std::string& systemNick, const std::string& file) { std::string path = "..\\data\\universe\\"; path += file; INI_Reader ini; if (ini.open(path.c_str(), false)) { while (ini.read_header()) { if (ini.is_header("zone")) { std::string zoneNick = ""; Vector size = {0, 0, 0}; Vector pos = {0, 0, 0}; Vector rotation = {0, 0, 0}; int damage = 0; bool encounter = false; while (ini.read_value()) { if (ini.is_value("nickname")) { zoneNick = ToLower(ini.get_value_string()); } else if (ini.is_value("pos")) { pos.x = ini.get_value_float(0); pos.y = ini.get_value_float(1); pos.z = ini.get_value_float(2); } else if (ini.is_value("rotate")) { rotation.x = 180 + ini.get_value_float(0); rotation.y = 180 + ini.get_value_float(1); rotation.z = 180 + ini.get_value_float(2); } else if (ini.is_value("size")) { size.x = ini.get_value_float(0); size.y = ini.get_value_float(1); size.z = ini.get_value_float(2); if (size.y == 0 || size.z == 0) { size.y = size.x; size.z = size.x; } } else if (ini.is_value("damage")) { damage = ini.get_value_int(0); } else if (ini.is_value("encounter")) { encounter = true; } } for (auto& [_, zone] : zones) { if (zone.zoneNick == zoneNick) { zone.pos = pos; zone.size = size; break; } } Zone lz; lz.sysNick = systemNick; lz.zoneNick = zoneNick; lz.systemId = CreateID(systemNick.c_str()); lz.size = size; lz.pos = pos; lz.damage = damage; lz.encounter = encounter; lz.transform = SetupTransform(pos, rotation); allZones.insert({lz.systemId, lz }); } else if (ini.is_header("Object")) { std::string nickname; std::string jumpDestSysNick; bool bIsJump = false; while (ini.read_value()) { if (ini.is_value("nickname")) { nickname = ToLower(ini.get_value_string()); } else if (ini.is_value("goto")) { bIsJump = true; jumpDestSysNick = ini.get_value_string(0); } } if (bIsJump) { JumpPoint jp; jp.sysNick = systemNick; jp.jumpNick = nickname; jp.jumpDestSysNick = jumpDestSysNick; jp.System = CreateID(systemNick.c_str()); jp.jumpId = CreateID(nickname.c_str()); jp.jumpDestSysId = CreateID(jumpDestSysNick.c_str()); JumpPoints.insert({jp.System, jp}); } } } ini.close(); } } /** Read all systems in the universe ini */ void ZoneUtilities::ReadUniverse(std::multimap<uint, LootableZone, std::less<>>* zones) { allZones.clear(); // Read all system ini files again this time extracting zone size/postion // information for the zone list. INI_Reader ini; if (ini.open("..\\data\\universe\\universe.ini", false)) { while (ini.read_header()) { if (ini.is_header("System")) { std::string systemNick = ""; std::string file = ""; float scale = 1.0f; while (ini.read_value()) { if (ini.is_value("nickname")) systemNick = ToLower(ini.get_value_string()); if (ini.is_value("file")) file = ini.get_value_string(); if (ini.is_value("NavMapScale")) scale = ini.get_value_float(0); } if (zones) ReadSystemLootableZones(*zones, systemNick, file); SystemInfo sysInfo; sysInfo.sysNick = systemNick; sysInfo.systemId = CreateID(systemNick.c_str()); sysInfo.scale = scale; mapSystems[sysInfo.systemId] = sysInfo; } } ini.close(); } // Read all system ini files again this time extracting zone size/postion // information for the lootable zone list. if (ini.open("..\\data\\universe\\universe.ini", false)) { while (ini.read_header()) { if (ini.is_header("System")) { std::string systemNick = ""; std::string file = ""; while (ini.read_value()) { if (ini.is_value("nickname")) systemNick = ini.get_value_string(); if (ini.is_value("file")) file = ini.get_value_string(); } if (zones) ReadSystemZones(*zones, systemNick, file); } } ini.close(); } } /** Return true if the ship location as specified by the position parameter is in a lootable zone. */ bool ZoneUtilities::InZone(uint system, const Vector& pos, Zone& rlz) { // For each zone in the system test that pos is inside the // zone. auto start = allZones.lower_bound(system); auto end = allZones.upper_bound(system); for (auto i = start; i != end; ++i) { const Zone& lz = i->second; /** Transform the point pos onto coordinate system defined by matrix m */ float x = pos.x * lz.transform.d[0][0] + pos.y * lz.transform.d[1][0] + pos.z * lz.transform.d[2][0] + lz.transform.d[3][0]; float y = pos.x * lz.transform.d[0][1] + pos.y * lz.transform.d[1][1] + pos.z * lz.transform.d[2][1] + lz.transform.d[3][1]; float z = pos.x * lz.transform.d[0][2] + pos.y * lz.transform.d[1][2] + pos.z * lz.transform.d[2][2] + lz.transform.d[3][2]; // If r is less than/equal to 1 then the point is inside the ellipsoid. float result = sqrt(powf(x / lz.size.x, 2) + powf(y / lz.size.y, 2) + powf(z / lz.size.z, 2)); if (result <= 1) { rlz = lz; return true; } } // Return the iterator. If the iter is allZones.end() then the point // is not in a lootable zone. return false; } /** Return true if the ship location as specified by the position parameter is in a death zone */ bool ZoneUtilities::InDeathZone(uint system, const Vector& pos, Zone& rlz) { // For each zone in the system test that pos is inside the // zone. auto start = allZones.lower_bound(system); auto end = allZones.upper_bound(system); for (auto i = start; i != end; ++i) { const Zone& lz = i->second; /** Transform the point pos onto coordinate system defined by matrix m */ float x = pos.x * lz.transform.d[0][0] + pos.y * lz.transform.d[1][0] + pos.z * lz.transform.d[2][0] + lz.transform.d[3][0]; float y = pos.x * lz.transform.d[0][1] + pos.y * lz.transform.d[1][1] + pos.z * lz.transform.d[2][1] + lz.transform.d[3][1]; float z = pos.x * lz.transform.d[0][2] + pos.y * lz.transform.d[1][2] + pos.z * lz.transform.d[2][2] + lz.transform.d[3][2]; // If r is less than/equal to 1 then the point is inside the ellipsoid. float result = sqrt(powf(x / lz.size.x, 2) + powf(y / lz.size.y, 2) + powf(z / lz.size.z, 2)); if (result <= 1 && lz.damage > 250) { rlz = lz; return true; } } // Return the iterator. If the iter is allZones.end() then the point // is not in a death zone. return false; } /** Return a pointer to the system info object for the specified system Id. Return 0 if the system Id does not exist. */ SystemInfo* ZoneUtilities::GetSystemInfo(uint systemId) { if (mapSystems.contains(systemId)) return &mapSystems[systemId]; return nullptr; } void ZoneUtilities::PrintZones() { std::multimap<uint, LootableZone, std::less<>> zones; ReadUniverse(&zones); Console::ConInfo("Zone, Commodity, MinLoot, MaxLoot, Difficultly, PosX, PosY, PosZ, SizeX, SizeY, SizeZ, IdsName, IdsInfo, Bonus\n"); for (const auto& [_, zone] : zones) { Console::ConInfo(std::format("{}, {}, {}, {}, {}, {:.0f}, {:.0f}, {:.0f}, {:.0f}, {:.0f}, {:.0f}\n", zone.zoneNick, zone.lootNick, zone.iMinLoot, zone.iMaxLoot, zone.iLootDifficulty, zone.pos.x, zone.pos.y, zone.pos.z, zone.size.x, zone.size.y, zone.size.z)); } Console::ConInfo(std::format("Zones={}", zones.size())); } } // namespace Hk::ZoneUtilities
13,925
C++
.cpp
472
24.724576
147
0.5956
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,405
TempBan.cpp
TheStarport_FLHook/source/Features/TempBan.cpp
#include "Features/TempBan.hpp" #include "Tools/Hk.hpp" void TempBanManager::ClearFinishedTempBans() { auto timeNow = Hk::Time::GetUnixMiliseconds(); auto it = tempBanList.begin(); while (it != tempBanList.end()) { if ((*it).banEnd < timeNow) { it = tempBanList.erase(it); } else { it++; } } } void TempBanManager::AddTempBan(ClientId client, uint durationInMin, const std::wstring& banReason) { if (!FLHookConfig::i()->general.tempBansEnabled) return; auto account = Hk::Client::GetAccountByClientID(client); const auto accId = Hk::Client::GetAccountID(account); TempBanInfo banInfo; banInfo.banStart = Hk::Time::GetUnixMiliseconds(); banInfo.banEnd = banInfo.banStart + (durationInMin * 1000 * 60); banInfo.accountId = accId.value(); if (!banReason.empty()) { Hk::Player::KickReason(client, banReason); } else { Hk::Player::Kick(client); } tempBanList.push_back(banInfo); } void TempBanManager::AddTempBan(ClientId client, uint durationInMin) { AddTempBan(client, durationInMin, L""); } bool TempBanManager::CheckIfTempBanned(ClientId client) { if (!FLHookConfig::i()->general.tempBansEnabled) return false; CAccount* acc = Players.FindAccountFromClientID(client); const auto id = Hk::Client::GetAccountID(acc); return std::ranges::any_of(tempBanList, [&id](TempBanInfo const& ban) { return ban.accountId == id.value(); }); }
1,391
C++
.cpp
50
25.56
112
0.740045
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,406
PluginManager.cpp
TheStarport_FLHook/source/Features/PluginManager.cpp
#include "Global.hpp" // Map of plugins to their relative communicators, if they have any. static std::map<std::string, PluginCommunicator*> pluginCommunicators; void PluginCommunicator::ExportPluginCommunicator(PluginCommunicator* communicator) { pluginCommunicators[communicator->plugin] = communicator; } void PluginCommunicator::Dispatch(int id, void* dataPack) const { for (const auto& i : listeners) { i.second(id, dataPack); } } void PluginCommunicator::AddListener(const std::string plugin, EventSubscription event) { this->listeners[plugin] = event; } PluginCommunicator* PluginCommunicator::ImportPluginCommunicator(const std::string plugin, PluginCommunicator::EventSubscription subscription) { const auto el = pluginCommunicators.find(plugin); if (el == pluginCommunicators.end()) return nullptr; if (subscription != nullptr) { el->second->AddListener(plugin, subscription); } return el->second; } void PluginManager::clearData(bool free) { if (free) { for (const auto& p : plugins_) if (p->mayUnload) FreeLibrary(p->dll); } plugins_.clear(); for (auto& p : pluginHooks_) p.clear(); } PluginManager::PluginManager() { clearData(false); setupProps(); } PluginManager::~PluginManager() { clearData(false); } cpp::result<std::wstring, Error> PluginManager::unload(const std::string& name) { const auto pluginIterator = std::ranges::find_if(plugins_, [&name](const std::shared_ptr<PluginData> data) { return name == data->shortName; }); if (pluginIterator == end()) return cpp::fail(Error::PluginNotFound); const auto plugin = *pluginIterator; if (!plugin->mayUnload) { Console::ConWarn("Plugin may not be unloaded."); return {}; } HMODULE dllAddr = plugin->dll; std::wstring unloadedPluginDll = plugin->dllName; Console::ConPrint(std::format("Unloading {} ({})", plugin->name, wstos(plugin->dllName))); for (const auto& hook : plugin->pInfo->hooks_) { const uint hookId = uint(hook.targetFunction_) * uint(magic_enum::enum_count<HookStep>()) + uint(hook.step_); auto& list = pluginHooks_[hookId]; std::erase_if(list, [dllAddr](const PluginHookData& x) { return x.plugin->dll == dllAddr; }); } plugins_.erase(pluginIterator); FreeLibrary(dllAddr); return unloadedPluginDll; } void PluginManager::unloadAll() { clearData(true); } void PluginManager::load(const std::wstring& fileName, CCmds* adminInterface, bool startup) { std::wstring dllName = fileName; if (dllName.find(L".dll") == std::string::npos) dllName.append(L".dll"); for (const auto& plugin : plugins_) { if (plugin->dllName == dllName) return adminInterface->Print(std::format("Plugin {} already loaded, skipping\n", wstos(plugin->dllName))); } std::wstring pathToDLL = L"./plugins/" + dllName; FILE* fp; _wfopen_s(&fp, pathToDLL.c_str(), L"r"); if (!fp) return adminInterface->Print(std::format("ERR plugin {} not found", wstos(dllName))); fclose(fp); auto plugin = std::make_shared<PluginData>(); plugin->dllName = dllName; plugin->dll = LoadLibraryW(pathToDLL.c_str()); if (!plugin->dll) return adminInterface->Print(std::format("ERR can't load plugin DLL {}", wstos(plugin->dllName))); auto getPluginInfo = reinterpret_cast<ExportPluginInfoT>(GetProcAddress(plugin->dll, "ExportPluginInfo")); if (!getPluginInfo) { adminInterface->Print(std::format("ERR could not read plugin info (ExportPluginInfo not exported?) for {}", wstos(plugin->dllName))); FreeLibrary(plugin->dll); return; } auto pi = std::make_shared<PluginInfo>(); getPluginInfo(pi.get()); if (pi->versionMinor_ == PluginMinorVersion::UNDEFINED || pi->versionMajor_ == PluginMajorVersion::UNDEFINED) { adminInterface->Print(std::format("ERR plugin {} does not have defined API version. Unloading.", wstos(plugin->dllName))); FreeLibrary(plugin->dll); return; } if (pi->versionMajor_ != CurrentMajorVersion) { adminInterface->Print(std::format("ERR incompatible plugin API (major) version for {}: expected {}, got {}", wstos(plugin->dllName), (int)CurrentMajorVersion, (int)pi->versionMajor_)); FreeLibrary(plugin->dll); return; } if ((int)pi->versionMinor_ > (int)CurrentMinorVersion) { adminInterface->Print(std::format("ERR incompatible plugin API (minor) version for {}: expected {} or lower, got {}", wstos(plugin->dllName), (int)CurrentMinorVersion, (int)pi->versionMinor_)); FreeLibrary(plugin->dll); return; } if (int(pi->versionMinor_) != (int)CurrentMinorVersion) { adminInterface->Print(std::format( "Warning, incompatible plugin API version for {}: expected {}, got {}", wstos(plugin->dllName), (int)CurrentMinorVersion, (int)pi->versionMinor_)); adminInterface->Print("Processing will continue, but plugin should be considered unstable."); } if (pi->shortName_.empty() || pi->name_.empty()) { adminInterface->Print(std::format("ERR missing name/short name for {}", wstos(plugin->dllName))); FreeLibrary(plugin->dll); return; } if (pi->returnCode_ == nullptr) { adminInterface->Print(std::format("ERR missing return code pointer {}", wstos(plugin->dllName))); FreeLibrary(plugin->dll); return; } plugin->mayUnload = pi->mayUnload_; plugin->name = pi->name_; plugin->shortName = pi->shortName_; plugin->resetCode = pi->resetCode_; plugin->returnCode = pi->returnCode_; // plugins that may not unload are interpreted as crucial plugins that can // also not be loaded after FLServer startup if (!plugin->mayUnload && !startup) { adminInterface->Print(std::format("ERR could not load plugin {}: plugin cannot be unloaded, need server restart to load", wstos(plugin->dllName))); FreeLibrary(plugin->dll); return; } for (const auto& hook : pi->hooks_) { if (!hook.hookFunction_) { adminInterface->Print( std::format("ERR could not load function. has step {} of plugin {}", magic_enum::enum_name(hook.step_), wstos(plugin->dllName))); continue; } if (const auto& targetHookProps = hookProps_[hook.targetFunction_]; !targetHookProps.matches(hook.step_)) { adminInterface->Print(std::format("ERR could not bind function. plugin: {}, step not available", wstos(plugin->dllName))); continue; } uint hookId = uint(hook.targetFunction_) * uint(magic_enum::enum_count<HookStep>()) + uint(hook.step_); auto& list = pluginHooks_[hookId]; PluginHookData data = {hook.targetFunction_, hook.hookFunction_, hook.step_, hook.priority_, plugin}; list.emplace_back(std::move(data)); } plugin->timers = pi->timers_; plugin->commands = pi->commands_; plugin->pInfo = std::move(pi); plugins_.emplace_back(plugin); std::ranges::sort(plugins_, [](const std::shared_ptr<PluginData> a, std::shared_ptr<PluginData> b) { return a->name < b->name; }); adminInterface->Print(std::format("Plugin {} loaded ({})", plugin->shortName, wstos(plugin->dllName))); } void PluginManager::loadAll(bool startup, CCmds* adminInterface) { WIN32_FIND_DATAW findData; HANDLE findPluginsHandle = FindFirstFileW(L"./plugins/*.dll", &findData); do { if (findPluginsHandle == INVALID_HANDLE_VALUE) break; load(findData.cFileName, adminInterface, startup); } while (FindNextFileW(findPluginsHandle, &findData)); } void PluginManager::setProps(HookedCall c, bool before, bool after) { hookProps_[c] = {before, after}; } void PluginInfo::versionMajor(PluginMajorVersion version) { versionMajor_ = version; } void PluginInfo::versionMinor(PluginMinorVersion version) { versionMinor_ = version; } void PluginInfo::name(const char* name) { name_ = name; } void PluginInfo::shortName(const char* shortName) { shortName_ = shortName; } void PluginInfo::mayUnload(bool unload) { mayUnload_ = unload; } void PluginInfo::autoResetCode(bool reset) { resetCode_ = reset; } void PluginInfo::returnCode(ReturnCode* returnCode) { returnCode_ = returnCode; } void PluginInfo::addHook(const PluginHook& hook) { hooks_.push_back(hook); } void PluginInfo::commands(const std::vector<UserCommand>* cmds) { commands_ = const_cast<std::vector<UserCommand>*>(cmds); } void PluginInfo::timers(const std::vector<Timer>* timers) { timers_ = const_cast<std::vector<Timer>*>(timers); }
8,195
C++
.cpp
243
31.312757
153
0.730833
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,407
Logging.cpp
TheStarport_FLHook/source/Features/Logging.cpp
#include "Global.hpp" #define SPDLOG_USE_STD_FORMAT #include "spdlog/async.h" #include "spdlog/sinks/basic_file_sink.h" #include "spdlog/sinks/msvc_sink.h" #include "spdlog/spdlog.h" std::shared_ptr<spdlog::logger> FLHookLog = nullptr; std::shared_ptr<spdlog::logger> CheaterLog = nullptr; std::shared_ptr<spdlog::logger> KickLog = nullptr; std::shared_ptr<spdlog::logger> ConnectsLog = nullptr; std::shared_ptr<spdlog::logger> AdminCmdsLog = nullptr; std::shared_ptr<spdlog::logger> SocketCmdsLog = nullptr; std::shared_ptr<spdlog::logger> UserCmdsLog = nullptr; std::shared_ptr<spdlog::logger> PerfTimersLog = nullptr; std::shared_ptr<spdlog::logger> FLHookDebugLog = nullptr; std::shared_ptr<spdlog::logger> WinDebugLog = nullptr; bool InitLogs() { try { FLHookLog = spdlog::basic_logger_mt<spdlog::async_factory>("FLHook", "logs/FLHook.log"); CheaterLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_cheaters", "logs/flhook_cheaters.log"); KickLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_kicks", "logs/flhook_kicks.log"); ConnectsLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_connects", "logs/flhook_connects.log"); AdminCmdsLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_admincmds", "logs/flhook_admincmds.log"); SocketCmdsLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_socketcmds", "logs/flhook_socketcmds.log"); UserCmdsLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_usercmds", "logs/flhook_usercmds.log"); PerfTimersLog = spdlog::basic_logger_mt<spdlog::async_factory>("flhook_perftimers", "logs/flhook_perftimers.log"); spdlog::flush_on(spdlog::level::err); spdlog::flush_every(std::chrono::seconds(3)); if (IsDebuggerPresent()) { WinDebugLog = spdlog::create_async<spdlog::sinks::msvc_sink_mt>("windows_debug"); WinDebugLog->set_level(spdlog::level::debug); } if (FLHookConfig::c()->general.debugMode) { char szDate[64]; time_t tNow = time(nullptr); tm t; localtime_s(&t, &tNow); strftime(szDate, sizeof szDate, "%d.%m.%Y_%H.%M", &t); std::string sDebugLog = "./logs/debug/FLHookDebug_" + (std::string)szDate; sDebugLog += ".log"; FLHookDebugLog = spdlog::basic_logger_mt<spdlog::async_factory>("async_file_logger", sDebugLog); FLHookDebugLog->set_level(spdlog::level::debug); } } catch (const spdlog::spdlog_ex& ex) { Console::ConErr(std::format("Log initialization failed: {}", ex.what())); return false; } return true; } void AddLog(LogType LogType, LogLevel lvl, const std::string& str) { auto level = static_cast<spdlog::level::level_enum>(lvl); switch (LogType) { case LogType::Cheater: CheaterLog->log(level, str); break; case LogType::Kick: KickLog->log(level, str); break; case LogType::Connects: ConnectsLog->log(level, str); break; case LogType::AdminCmds: AdminCmdsLog->log(level, str); break; case LogType::UserLogCmds: UserCmdsLog->log(level, str); break; case LogType::SocketCmds: SocketCmdsLog->log(level, str); break; case LogType::PerfTimers: PerfTimersLog->log(level, str); break; case LogType::Normal: switch (level) { case spdlog::level::debug: Console::ConDebug(str); break; case spdlog::level::info: Console::ConInfo(str); break; case spdlog::level::warn: Console::ConWarn(str); break; case spdlog::level::critical: case spdlog::level::err: Console::ConErr(str); break; default: ; } FLHookLog->log(level, str); break; default: break; } if (lvl == LogLevel::Debug && FLHookDebugLog) { FLHookDebugLog->debug(str); } if (IsDebuggerPresent() && WinDebugLog) { WinDebugLog->debug(str); } if (lvl == LogLevel::Critical) { // Ensure all is flushed! spdlog::shutdown(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void HandleCheater(ClientId client, bool bBan, std::string reason) { AddCheaterLog(client, reason); if (reason[0] != '#' && Players.GetActiveCharacterName(client)) { std::wstring character = (wchar_t*)Players.GetActiveCharacterName(client); Hk::Message::MsgU(std::format(L"Possible cheating detected: {}", character.c_str())); } if (bBan) Hk::Player::Ban(client, true); if (reason[0] != '#') Hk::Player::Kick(client); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AddCheaterLog(const std::variant<uint, std::wstring>& player, const std::string& wscReason) { ClientId client = Hk::Client::ExtractClientID(player); CAccount* acc = Players.FindAccountFromClientID(client); std::wstring wscAccountDir = L"???"; std::wstring wscAccountId = L"???"; if (acc) { wscAccountDir = Hk::Client::GetAccountDirName(acc); wscAccountId = Hk::Client::GetAccountID(acc).value(); } std::wstring wscHostName = L"???"; std::wstring wscIp = L"???"; wscHostName = ClientInfo[client].wscHostname; wscIp = Hk::Admin::GetPlayerIP(client); const std::wstring wscCharacterName = Hk::Client::GetCharacterNameByID(client).value(); AddLog(LogType::Cheater, LogLevel::Info, wstos(std::format(L"Possible cheating detected ({}) by {}({})({}) [{} {}]", stows(wscReason), wscCharacterName, wscAccountDir.c_str(), wscAccountId.c_str(), wscHostName.c_str(), wscIp.c_str()))); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AddKickLog(ClientId client, const std::string& wscReason) { const wchar_t* wszCharname = (wchar_t*)Players.GetActiveCharacterName(client); if (!wszCharname) wszCharname = L""; CAccount* acc = Players.FindAccountFromClientID(client); std::wstring wscAccountDir = Hk::Client::GetAccountDirName(acc); AddLog(LogType::Kick, LogLevel::Info, wstos(std::format(L"Kick ({}): {}({})({})\n", stows(wscReason), wszCharname, wscAccountDir.c_str(), Hk::Client::GetAccountID(acc).value().c_str()))); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool AddConnectLog(ClientId client, const std::string& wscReason) { const wchar_t* wszCharname = (wchar_t*)Players.GetActiveCharacterName(client); if (!wszCharname) wszCharname = L""; CAccount* acc = Players.FindAccountFromClientID(client); std::wstring wscAccountDir = Hk::Client::GetAccountDirName(acc); AddLog(LogType::Connects, LogLevel::Info, wstos(std::format(L"Connect ({}): {}({})({})\n", stows(wscReason), wszCharname, wscAccountDir.c_str(), Hk::Client::GetAccountID(acc).value().c_str()))); return true; }
6,694
C++
.cpp
175
35.382857
195
0.667232
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,408
UserCommands.cpp
TheStarport_FLHook/source/Features/UserCommands.cpp
#include "Global.hpp" #include "Features/Mail.hpp" #define PRINT_ERROR() \ { \ for (uint i = 0; (i < sizeof(error) / sizeof(std::wstring)); i++) \ PrintUserCmdText(client, std::format(L"{}", error[i])); \ return; \ } #define PRINT_OK() PrintUserCmdText(client, L"OK"); #define PRINT_DISABLED() PrintUserCmdText(client, L"Command disabled"); #define GET_USERFILE(a) \ std::string a; \ { \ CAccount* acc = Players.FindAccountFromClientID(client); \ std::wstring dir = Hk::Client::GetAccountDirName(acc); \ a = CoreGlobals::c()->accPath + wstos(dir) + "\\flhookuser.ini"; \ } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void PrintUserCmdText(ClientId client, const std::wstring& text) { auto newLineChar = text.find(L"\n"); if (newLineChar == std::wstring::npos) { std::wstring xml = std::format(L"<TRA data=\"{}\" mask=\"-1\"/><TEXT>{}</TEXT>", FLHookConfig::i()->messages.msgStyle.userCmdStyle, XMLText(text)); Hk::Message::FMsg(client, xml); } else { // Split text into two strings, one from the beginning to the character before newLineChar, and one after newLineChar till the end. // It will then recursively call itself for each new line char until the original text is all displayed. PrintUserCmdText(client, text.substr(0, newLineChar)); PrintUserCmdText(client, text.substr(newLineChar + 1, std::wstring::npos)); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Print message to all ships within the specific number of meters of the /// player. void PrintLocalUserCmdText(ClientId client, const std::wstring& msg, float distance) { uint ship; pub::Player::GetShip(client, ship); Vector pos; Matrix rot; pub::SpaceObj::GetLocation(ship, pos, rot); uint iSystem; pub::Player::GetSystem(client, iSystem); // For all players in system... PlayerData* playerDb = nullptr; while ((playerDb = Players.traverse_active(playerDb))) { // Get the this player's current system and location in the system. ClientId client2 = playerDb->iOnlineId; uint iSystem2 = 0; pub::Player::GetSystem(client2, iSystem2); if (iSystem != iSystem2) continue; uint ship2; pub::Player::GetShip(client2, ship2); Vector pos2; Matrix rot2; pub::SpaceObj::GetLocation(ship2, pos2, rot2); // Is player within the specified range of the sending char. if (Hk::Math::Distance3D(pos, pos2) > distance) continue; PrintUserCmdText(client2, msg); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_SetDieMsg(ClientId& client, const std::wstring& param) { if (!FLHookConfig::i()->messages.dieMsg) { PRINT_DISABLED() return; } static const std::wstring errorMsg = L"Error: Invalid parameters\n" L"Usage: /set diemsg <param>\n" L"<param>: all,system,self or none"; std::wstring dieMsgParam = ToLower(GetParam(param, ' ', 0)); DIEMSGTYPE dieMsg; if (dieMsgParam == L"all") dieMsg = DIEMSG_ALL; else if (dieMsgParam == L"system") dieMsg = DIEMSG_SYSTEM; else if (dieMsgParam == L"none") dieMsg = DIEMSG_NONE; else if (dieMsgParam == L"self") dieMsg = DIEMSG_SELF; else { PrintUserCmdText(client, errorMsg); return; } // save to ini GET_USERFILE(scUserFile) IniWrite(scUserFile, "settings", "DieMsg", std::to_string(dieMsg)); // save in ClientInfo ClientInfo[client].dieMsg = dieMsg; // send confirmation msg PRINT_OK() } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_SetDieMsgSize(ClientId& client, const std::wstring& param) { if (!FLHookConfig::i()->userCommands.userCmdSetDieMsgSize) { PRINT_DISABLED() return; } static const std::wstring errorMsg = L"Error: Invalid parameters\n" L"Usage: /set diemsgsize <size>\n" L"<size>: small, default"; std::wstring dieMsgSizeParam = ToLower(GetParam(param, ' ', 0)); CHATSIZE dieMsgSize; if (!dieMsgSizeParam.compare(L"small")) dieMsgSize = CS_SMALL; else if (!dieMsgSizeParam.compare(L"default")) dieMsgSize = CS_DEFAULT; else { PrintUserCmdText(client, errorMsg); return; } // save to ini GET_USERFILE(scUserFile) IniWrite(scUserFile, "Settings", "DieMsgSize", std::to_string(dieMsgSize)); // save in ClientInfo ClientInfo[client].dieMsgSize = dieMsgSize; // send confirmation msg PRINT_OK() } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_SetChatFont(ClientId& client, const std::wstring& param) { if (!FLHookConfig::i()->userCommands.userCmdSetChatFont) { PRINT_DISABLED() return; } static const std::wstring errorMsg = L"Error: Invalid parameters\n" L"Usage: /set chatfont <size> <style>\n" L"<size>: small, default or big\n" L"<style>: default, bold, italic or underline"; std::wstring chatSizeParam = ToLower(GetParam(param, ' ', 0)); std::wstring chatStyleParam = ToLower(GetParam(param, ' ', 1)); CHATSIZE chatSize; if (!chatSizeParam.compare(L"small")) chatSize = CS_SMALL; else if (!chatSizeParam.compare(L"default")) chatSize = CS_DEFAULT; else if (!chatSizeParam.compare(L"big")) chatSize = CS_BIG; else { PrintUserCmdText(client, errorMsg); return; } CHATSTYLE chatStyle; if (!chatStyleParam.compare(L"default")) chatStyle = CST_DEFAULT; else if (!chatStyleParam.compare(L"bold")) chatStyle = CST_BOLD; else if (!chatStyleParam.compare(L"italic")) chatStyle = CST_ITALIC; else if (!chatStyleParam.compare(L"underline")) chatStyle = CST_UNDERLINE; else { PrintUserCmdText(client, errorMsg); return; } // save to ini GET_USERFILE(scUserFile) IniWrite(scUserFile, "settings", "ChatSize", std::to_string(chatSize)); IniWrite(scUserFile, "settings", "ChatStyle", std::to_string(chatStyle)); // save in ClientInfo ClientInfo[client].chatSize = chatSize; ClientInfo[client].chatStyle = chatStyle; // send confirmation msg PRINT_OK() } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_Ignore(ClientId& client, const std::wstring& param) { if (!FLHookConfig::i()->userCommands.userCmdIgnore) { PRINT_DISABLED() return; } static const std::wstring errorMsg = L"Error: Invalid parameters\n" L"Usage: /ignore <charname> [<flags>]\n" L"<charname>: character name which should be ignored(case insensitive)\n" L"<flags>: combination of the following flags:\n" L" p - only affect private chat\n" L" i - <charname> may match partially\n" L"Examples:\n" L"\"/ignore SomeDude\" ignores all chatmessages from SomeDude\n" L"\"/ignore PlayerX p\" ignores all private-chatmessages from PlayerX\n" L"\"/ignore idiot i\" ignores all chatmessages from players whose \n" L"charname contain \"idiot\" (e.g. \"[XYZ]IdIOT\", \"MrIdiot\", etc)\n" L"\"/ignore Fool pi\" ignores all private-chatmessages from players \n" L"whose charname contain \"fool\""; std::wstring allowedFlags = L"pi"; std::wstring character = GetParam(param, ' ', 0); std::wstring flags = ToLower(GetParam(param, ' ', 1)); if (character.empty()) { PrintUserCmdText(client, errorMsg); return; } // check if flags are valid for (auto flag : flags) { if (allowedFlags.find_first_of(flag) == -1) { PrintUserCmdText(client, errorMsg); return; } } if (ClientInfo[client].lstIgnore.size() > FLHookConfig::i()->userCommands.userCmdMaxIgnoreList) { PrintUserCmdText(client, L"Error: Too many entries in the ignore list, please delete an entry first!"); return; } // save to ini GET_USERFILE(scUserFile) IniWriteW(scUserFile, "IgnoreList", std::to_string((int)ClientInfo[client].lstIgnore.size() + 1), character + L" " + flags); // save in ClientInfo IGNORE_INFO ii; ii.character = character; ii.wscFlags = flags; ClientInfo[client].lstIgnore.push_back(ii); // send confirmation msg PRINT_OK() } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_IgnoreID(ClientId& client, const std::wstring& param) { if (!FLHookConfig::i()->userCommands.userCmdIgnore) { PRINT_DISABLED() return; } static const std::wstring errorMsg = L"Error: Invalid parameters\n" L"Usage: /ignoreid <client-id> [<flags>]\n" L"<client-id>: client-id of character which should be ignored\n" L"<flags>: if \"p\"(without quotation marks) then only affect private\n" L"chat"; std::wstring clientId = GetParam(param, ' ', 0); std::wstring flags = ToLower(GetParam(param, ' ', 1)); if (!clientId.length() || !flags.empty() && flags.compare(L"p") != 0) { PrintUserCmdText(client, errorMsg); return; } if (ClientInfo[client].lstIgnore.size() > FLHookConfig::i()->userCommands.userCmdMaxIgnoreList) { PrintUserCmdText(client, L"Error: Too many entries in the ignore list, please delete an entry first!"); return; } ClientId clientTarget = ToInt(clientId); if (!Hk::Client::IsValidClientID(clientTarget) || Hk::Client::IsInCharSelectMenu(clientTarget)) { PrintUserCmdText(client, L"Error: Invalid client-id"); return; } std::wstring character = Hk::Client::GetCharacterNameByID(clientTarget).value(); // save to ini GET_USERFILE(scUserFile) IniWriteW(scUserFile, "IgnoreList", std::to_string((int)ClientInfo[client].lstIgnore.size() + 1), character + L" " + flags); // save in ClientInfo IGNORE_INFO ii; ii.character = character; ii.wscFlags = flags; ClientInfo[client].lstIgnore.push_back(ii); // send confirmation msg PrintUserCmdText(client, std::format(L"OK, \"{}\" added to ignore list", character)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_IgnoreList(ClientId& client, [[maybe_unused]] const std::wstring& param) { if (!FLHookConfig::i()->userCommands.userCmdIgnore) { PRINT_DISABLED() return; } PrintUserCmdText(client, L"Id | Charactername | Flags"); int i = 1; for (auto& ignore : ClientInfo[client].lstIgnore) { PrintUserCmdText(client, std::format(L"{} | %s | %s", i, ignore.character.c_str(), ignore.wscFlags)); i++; } // send confirmation msg PRINT_OK() } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_DelIgnore(ClientId& client, const std::wstring& param) { if (!FLHookConfig::i()->userCommands.userCmdIgnore) { PRINT_DISABLED() return; } static const std::wstring errorMsg = L"Error: Invalid parameters\n" L"Usage: /delignore <id> [<id2> <id3> ...]\n" L"<id>: id of ignore-entry(see /ignorelist) or *(delete all)"; std::wstring idToDelete = GetParam(param, ' ', 0); if (idToDelete.empty()) { PrintUserCmdText(client, errorMsg); return; } GET_USERFILE(scUserFile) if (!idToDelete.compare(L"*")) { // delete all IniDelSection(scUserFile, "IgnoreList"); ClientInfo[client].lstIgnore.clear(); PRINT_OK() return; } std::list<uint> lstDelete; for (uint j = 1; !idToDelete.empty(); j++) { uint iId = ToInt(idToDelete.c_str()); if (!iId || iId > ClientInfo[client].lstIgnore.size()) { PrintUserCmdText(client, L"Error: Invalid Id"); return; } lstDelete.push_back(iId); idToDelete = GetParam(param, ' ', j); } lstDelete.sort(std::greater<uint>()); ClientInfo[client].lstIgnore.reverse(); for (const auto& del : lstDelete) { uint iCurId = ClientInfo[client].lstIgnore.size(); for (auto ignoreIt = ClientInfo[client].lstIgnore.begin(); ignoreIt != ClientInfo[client].lstIgnore.end(); ++ignoreIt) { if (iCurId == del) { ClientInfo[client].lstIgnore.erase(ignoreIt); break; } iCurId--; } } ClientInfo[client].lstIgnore.reverse(); // send confirmation msg IniDelSection(scUserFile, "IgnoreList"); int i = 1; for (const auto& ignore : ClientInfo[client].lstIgnore) { IniWriteW(scUserFile, "IgnoreList", std::to_string(i), ignore.character + L" " + ignore.wscFlags); i++; } PRINT_OK() } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_Ids(ClientId& client, [[maybe_unused]] const std::wstring& param) { for (auto& player : Hk::Admin::GetPlayers()) { PrintUserCmdText(client, std::format(L"{} = {} | ", player.character, player.client)); } PrintUserCmdText(client, L"OK"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_ID(ClientId& client, [[maybe_unused]] const std::wstring& param) { PrintUserCmdText(client, std::format(L"Your client-id: {}", client)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Invite_Player(ClientId& client, const std::wstring& characterName) { std::wstring XML = L"<TEXT>/i " + XMLText(characterName) + L"</TEXT>"; char szBuf[0xFFFF]; uint iRet; if (Hk::Message::FMsgEncodeXML(XML, szBuf, sizeof szBuf, iRet).has_error()) { PrintUserCmdText(client, L"Error: Could not encode XML"); return; } CHAT_ID cId; cId.iId = client; CHAT_ID cIdTo; cIdTo.iId = 0x00010001; Server.SubmitChat(cId, iRet, szBuf, cIdTo, -1); } void UserCmd_Invite(ClientId& client, const std::wstring& param) { if (!param.empty()) { const auto characterName = GetParam(param, ' ', 0); auto inviteeId = Hk::Client::GetClientIdFromCharName(characterName); if (inviteeId.has_value() && !Hk::Client::IsInCharSelectMenu(inviteeId.value())) { Invite_Player(client, characterName); } } else { auto targetClientId = Hk::Player::GetTargetClientID(client); if (targetClientId.has_value()) { Invite_Player(client, Hk::Client::GetCharacterNameByID(targetClientId.value()).value()); } } } void UserCmd_InviteID(ClientId& client, const std::wstring& param) { std::wstring invitedClientId = GetParam(param, ' ', 0); if (invitedClientId.empty()) { PrintUserCmdText(client, L"Error: Invalid parameters\nUsage: /i$ <client-id>"); return; } ClientId clientTarget = ToInt(invitedClientId); if (!Hk::Client::IsValidClientID(clientTarget) || Hk::Client::IsInCharSelectMenu(clientTarget)) { PrintUserCmdText(client, L"Error: Invalid client-id"); return; } Invite_Player(client, Hk::Client::GetCharacterNameByID(clientTarget).value()); } void UserCmd_FactionInvite(ClientId& client, const std::wstring& param) { const std::wstring& charnamePrefix = ToLower(GetParam(param, ' ', 0)); bool msgSent = false; if (charnamePrefix.size() < 3) { PrintUserCmdText(client, L"ERR Invalid parameters"); PrintUserCmdText(client, L"Usage: /factioninvite <tag> or /fi ..."); return; } for (const auto& player : Hk::Admin::GetPlayers()) { if (ToLower(player.character).find(charnamePrefix) == std::string::npos) continue; if (player.client == client) continue; Invite_Player(client, player.character); msgSent = true; } if (msgSent == false) PrintUserCmdText(client, L"ERR No chars found"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_FLHookInfo(ClientId& client, [[maybe_unused]] const std::wstring& param) { PrintUserCmdText(client, L"This server is running FLHook v" + VersionInformation); PrintUserCmdText(client, L"Running plugins:"); bool bRunning = false; for (const auto& plugin : PluginManager::ir()) { if (plugin->paused) continue; bRunning = true; PrintUserCmdText(client, std::format(L"- {}", stows(plugin->name))); } if (!bRunning) PrintUserCmdText(client, L"- none -"); } void UserCmdDelMail(ClientId& client, const std::wstring& param) { // /maildel <id/all> [readonly] const auto str = GetParam(param, ' ', 0); if (str == L"all") { const auto count = MailManager::i()->PurgeAllMail(client, GetParam(param, ' ', 1) == L"readonly"); if (count.has_error()) { PrintUserCmdText(client, std::format(L"Error deleting mail: {}", stows(count.error()))); return; } PrintUserCmdText(client, std::format(L"Deleted {} mail", count.value())); } else { const auto index = ToInt64(str); if (const auto err = MailManager::i()->DeleteMail(client, index); err.has_error()) { PrintUserCmdText(client, std::format(L"Error deleting mail: {}", stows(err.error()))); return; } PrintUserCmdText(client, L"Mail deleted"); } } void UserCmdReadMail(ClientId& client, const std::wstring& param) { const auto index = ToInt64(GetParam(param, ' ', 0)); if (index <= 0) { PrintUserCmdText(client, L"Id was not provided or was invalid."); return; } const auto mail = MailManager::i()->GetMailById(client, index); if (mail.has_error()) { PrintUserCmdText(client, std::format(L"Error retreiving mail: {}", stows(mail.error()))); return; } const auto& item = mail.value(); PrintUserCmdText(client, std::format(L"From: {}", stows(item.author))); PrintUserCmdText(client, std::format(L"Subject: {}", stows(item.subject))); PrintUserCmdText(client, std::format(L"Date: {:%F %T}", UnixToSysTime(item.timestamp))); PrintUserCmdText(client, stows(item.body)); } void UserCmdListMail(ClientId& client, const std::wstring& param) { const auto page = ToInt(GetParam(param, ' ', 0)); if (page <= 0) { PrintUserCmdText(client, L"Page was not provided or was invalid."); return; } const bool unreadOnly = GetParam(param, ' ', 1) == L"unread"; const auto mail = MailManager::i()->GetMail(client, unreadOnly, page); if (mail.has_error()) { PrintUserCmdText(client, std::format(L"Error retreiving mail: {}", stows(mail.error()))); return; } const auto& mailList = mail.value(); if (mailList.empty()) { PrintUserCmdText(client, L"You have no mail."); return; } PrintUserCmdText(client, std::format(L"Printing mail of page {}", mailList.size())); for (const auto& item : mailList) { // | Id.) Subject (unread) - Author - Time PrintUserCmdText(client, stows(std::format( "| {}.) {} {}- {} - {:%F %T}", item.id, item.subject, item.unread ? "(unread) " : "", item.author, UnixToSysTime(item.timestamp)))); } } void UserCmdGiveCash(ClientId& client, const std::wstring& param) { const auto targetPlayer = Hk::Client::GetClientIdFromCharName(GetParam(param, ' ', 0)); const auto cash = MultiplyUIntBySuffix(GetParam(param, ' ', 1)); const auto clientCash = Hk::Player::GetCash(client); if (targetPlayer.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(targetPlayer.error())); return; } if (client == targetPlayer.value()) { PrintUserCmdText(client, L"Not sure this really accomplishes much, (Don't give cash to yourself.)"); return; } if (clientCash.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(clientCash.error())); return; } if (cash == 0) { PrintUserCmdText(client, std::format(L"Err: Invalid cash amount.")); return; } if (clientCash.value() < cash) { PrintUserCmdText(client, std::format(L"Err: You do not have enough cash, you only have {}, and are trying to give {}.", clientCash.value(), cash)); return; } const auto removal = Hk::Player::RemoveCash(client, cash); if (removal.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(removal.error())); return; } const auto addition = Hk::Player::AddCash(targetPlayer.value(), cash); if (addition.has_error()) { PrintUserCmdText(client, Hk::Err::ErrGetText(addition.error())); return; } Hk::Player::SaveChar(client); Hk::Player::SaveChar(targetPlayer.value()); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void UserCmd_Help(ClientId& client, const std::wstring& paramView); UserCommand CreateUserCommand(const std::variant<std::wstring, std::vector<std::wstring>>& command, const std::wstring& usage, const std::variant<UserCmdProc, UserCmdProcWithParam>& proc, const std::wstring& description) { return {command, usage, proc, description}; } std::vector<std::wstring> CmdArr(std::initializer_list<std::wstring> cmds) { return cmds; } const std::wstring helpUsage = L"/help [module] [command]"; const std::wstring helpDescription = L"/help, /h, or /? will list all command modules, commands within a specific module, or information on a specific command."; const std::vector UserCmds = {{CreateUserCommand(L"/set diemsg", L"<all/system/self/none>", UserCmd_SetDieMsg, L""), CreateUserCommand(L"/set diemsgsize", L"<small/default>", UserCmd_SetDieMsgSize, L"Sets the text size of death messages."), CreateUserCommand(L"/set chatfont", L"<small/default/big> <default/bold/italic/underline>", UserCmd_SetChatFont, L"Sets the font of chat."), CreateUserCommand(L"/ignorelist", L"", UserCmd_IgnoreList, L"Lists currently ignored players."), CreateUserCommand(L"/delignore", L"<id/*> [<id2> <id3...]", UserCmd_DelIgnore, L"Removes specified entries form ignore list, '*' clears the whole list."), CreateUserCommand(L"/ignore", L"<name> [flags]", UserCmd_Ignore, L"Suppresses chat messages from the specified player. Flag 'p' only suppresses private chat, 'i' allows for partial match."), CreateUserCommand( L"/ignoreid", L"<client-id> [flags]", UserCmd_IgnoreID, L"Suppresses chat messages from the specified player. Flag 'p' only suppresses private chat."), CreateUserCommand(L"/ids", L"", UserCmd_Ids, L"List all player IDs."), CreateUserCommand(L"/id", L"", UserCmd_ID, L"Lists your player ID."), CreateUserCommand(L"/invite", L"[name]", UserCmd_Invite, L"Sends a group invite to a player with the specified name, or target, if no name is provided."), CreateUserCommand(L"/invite$", L"<id>", UserCmd_InviteID, L"Sends a group invite to a player with the specified ID."), CreateUserCommand(L"/i", L"[name]", UserCmd_Invite, L"Shortcut for /invite"), CreateUserCommand(L"/i$", L"<id>", UserCmd_InviteID, L"Shortcut for /invite$"), CreateUserCommand(L"/factioninvite", L"<name>", UserCmd_FactionInvite, L"Send a group invite to online members of the specified tag."), CreateUserCommand(L"/fi", L"<name>", UserCmd_FactionInvite, L"Shortcut for /factioninvite."), CreateUserCommand(L"/flhookinfo", L"", UserCmd_FLHookInfo, L""), CreateUserCommand(L"/maildel", L"/maildel <id/all> [readonly]", UserCmdDelMail, L"Delete the specified mail, or if all is provided delete all mail. If all is specified with the param of readonly, unread mail will be preserved."), CreateUserCommand(L"/mailread", L"/mailread <id>", UserCmdReadMail, L"Read the specified mail."), CreateUserCommand(L"/maillist", L"/maillist <page> [unread]", UserCmdListMail, L"List the mail items on the specified page. If unread is specified, only mail that hasn't been read will be listed."), CreateUserCommand(CmdArr({L"/help", L"/h", L"/?"}), helpUsage, UserCmd_Help, helpDescription), CreateUserCommand(L"/givecash", L"<player> <amount>", UserCmdGiveCash, L"Gives specified amount of cash to a target player, target must be online.")}}; bool GetCommand(const std::wstring& cmd, const UserCommand& userCmd) { const auto isMatch = [&cmd](const std::wstring& subCmd) { if (cmd.rfind(L'/') == 0) { return subCmd == cmd; } auto trimmed = subCmd; trimmed.erase(0, 1); return trimmed == cmd; }; if (userCmd.command.index() == 0) { return isMatch(std::get<std::wstring>(userCmd.command)); } else { const auto& arr = std::get<std::vector<std::wstring>>(userCmd.command); return std::ranges::any_of(arr, isMatch); } } void UserCmd_Help(ClientId& client, const std::wstring& paramView) { if (const auto* config = FLHookConfig::c(); !config->userCommands.userCmdHelp) { PRINT_DISABLED() return; } const auto& plugins = PluginManager::ir(); if (paramView.find(L' ') == std::string::npos) { PrintUserCmdText(client, L"The following command modules are available to you. Use /help <module> [command] for detailed information."); PrintUserCmdText(client, L"core"); for (const auto& plugin : plugins) { if (!plugin->commands || plugin->commands->empty()) continue; PrintUserCmdText(client, ToLower(stows(plugin->shortName))); } return; } const auto mod = GetParam(paramView, L' ', 1); const auto cmd = ToLower(Trim(GetParam(paramView, L' ', 2))); if (mod == L"core") { if (cmd.empty()) { for (const auto& i : UserCmds) { if (i.command.index() == 0) PrintUserCmdText(client, std::get<std::wstring>(i.command)); else PrintUserCmdText(client, i.usage); } } else if (const auto& userCommand = std::ranges::find_if(UserCmds, [&cmd](const UserCommand& userCmd) { return GetCommand(cmd, userCmd); }); userCommand != UserCmds.end()) { PrintUserCmdText(client, userCommand->usage); PrintUserCmdText(client, userCommand->description); } else { PrintUserCmdText(client, std::format(L"Command '{}' not found within module 'Core'", cmd.c_str())); } return; } const auto& pluginIterator = std::ranges::find_if(plugins, [&mod](const std::shared_ptr<PluginData> plug) { return ToLower(stows(plug->shortName)) == ToLower(mod); }); if (pluginIterator == plugins.end()) { PrintUserCmdText(client, L"Command module not found."); return; } const auto plugin = *pluginIterator; if (plugin->commands) { if (cmd.empty()) { for (const auto& command : *plugin->commands) { if (command.command.index() == 0) PrintUserCmdText(client, std::get<std::wstring>(command.command)); else PrintUserCmdText(client, command.usage); } } else if (const auto& userCommand = std::ranges::find_if(*plugin->commands, [&cmd](const UserCommand& userCmd) { return GetCommand(cmd, userCmd); }); userCommand != plugin->commands->end()) { PrintUserCmdText(client, userCommand->usage); PrintUserCmdText(client, userCommand->description); } else { PrintUserCmdText(client, std::format(L"Command '{}' not found within module '{}'", cmd, stows(plugin->shortName))); } } else { PrintUserCmdText(client, std::format(L"Module '{}' does not have commands.", stows(plugin->shortName))); } } bool ProcessPluginCommand(ClientId& client, const std::wstring& originalCmdString, const std::vector<UserCommand>& commands) { const std::wstring inputLower = ToLower(originalCmdString); for (const auto& cmdObj : commands) { std::optional<std::wstring> param; if (cmdObj.command.index() == 0) { const auto& subCmd = std::get<std::wstring>(cmdObj.command); // No command match if (inputLower.rfind(subCmd, 0) != 0) { continue; } // If the length of the input is greater than the command, check the last character and assert its not a space if (originalCmdString.length() > subCmd.length()) { if (originalCmdString[subCmd.length()] != ' ') { continue; } param = originalCmdString.substr(subCmd.length() + 1); } else { param = L""; } } else { for (const auto& subCmd : std::get<std::vector<std::wstring>>(cmdObj.command)) { if (inputLower.rfind(subCmd, 0) != 0 || (originalCmdString.length() > subCmd.length() && originalCmdString[subCmd.length()] != ' ')) { continue; } param = originalCmdString; } } if (param.has_value()) { std::wstring character = (wchar_t*)Players.GetActiveCharacterName(client); AddLog(LogType::UserLogCmds, LogLevel::Info, wstos(std::format(L"{}: {}", character.c_str(), originalCmdString.c_str()))); try { if (cmdObj.proc.index() == 0) { std::get<UserCmdProc>(cmdObj.proc)(client); } else { std::get<UserCmdProcWithParam>(cmdObj.proc)(client, param.value()); } AddLog(LogType::UserLogCmds, LogLevel::Info, "finished"); } catch (std::exception const& ex) { AddLog(LogType::UserLogCmds, LogLevel::Err, std::format("exception {}", ex.what())); } return true; } } return false; }; bool UserCmd_Process(ClientId client, const std::wstring& cmd) { auto [pluginRet, pluginSkip] = CallPluginsBefore<bool>(HookedCall::FLHook__UserCommand__Process, client, cmd); if (pluginSkip) return pluginRet; for (const auto& plugins = PluginManager::ir(); const std::shared_ptr<PluginData> i : plugins) { if (i->commands && ProcessPluginCommand(client, cmd, *i->commands)) { return true; } } // In-built commands return ProcessPluginCommand(client, cmd, UserCmds); }
29,839
C++
.cpp
805
33.156522
159
0.638844
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,409
Error.cpp
TheStarport_FLHook/source/Features/Error.cpp
#include "Global.hpp" namespace Hk::Err { struct ErrorInfo { Error Err; std::wstring text; }; const std::array<ErrorInfo, 30> Errors = {{ {Error::PlayerNotLoggedIn, L"Player not logged in"}, {Error::CharacterDoesNotExist, L"Char does not exist"}, {Error::CouldNotDecodeCharFile, L"Could not decode charfile"}, {Error::CouldNotEncodeCharFile, L"Coult not encode charfile"}, {Error::NoTargetSelected, L"No target selected"}, {Error::TargetIsNotPlayer, L"Target is not a player"}, {Error::PlayerNotDocked, L"Player in space"}, {Error::UnknownError, L"Unknown error"}, {Error::InvalidClientId, L"Invalid client id"}, {Error::InvalidIdString, L"Invalid id std::string"}, {Error::InvalidSystem, L"Invalid system"}, {Error::PlayerNotInSpace, L"Player not in space"}, {Error::NoAdmin, L"Player is no admin"}, {Error::WrongXmlSyntax, L"Wrong XML syntax"}, {Error::InvalidGood, L"Invalid good"}, {Error::CharacterNotSelected, L"Player has no char selected"}, {Error::AlreadyExists, L"Charname already exists"}, {Error::CharacterNameTooLong, L"Charname is too long"}, {Error::CharacterNameTooShort, L"Charname is too short"}, {Error::AmbiguousShortcut, L"Ambiguous shortcut"}, {Error::NoMatchingPlayer, L"No matching player"}, {Error::InvalidShortcutString, L"Invalid shortcut std::string"}, {Error::MpNewCharacterFileNotFoundOrInvalid, L"mpnewcharacter.fl not found or invalid"}, {Error::InvalidRepGroup, L"Invalid reputation group"}, {Error::PluginCannotBeLoaded, L"Plugin cannot be unloaded"}, {Error::PluginNotFound, L"Plugin not found"}, {Error::InvalidIdType, L"Invalid Id Type provided"}, {Error::InvalidSpaceObjId, L"Invalid SpaceObj Id provided"}, {Error::InvalidBase, L"Invalid base provided"}, {Error::InvalidBaseName, L"Invalid Base name"}, }}; std::wstring ErrGetText(Error Err) { if (const auto err = std::ranges::find_if(Errors, [Err](const ErrorInfo& e) { return e.Err == Err; }); err != Errors.end()) { return err->text; } return L"No error text available"; } } // namespace Hk::Err
2,168
C++
.cpp
49
39.591837
125
0.701846
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,410
Timers.cpp
TheStarport_FLHook/source/Features/Timers.cpp
#include "Global.hpp" #include <WS2tcpip.h> #include "Features/TempBan.hpp" CTimer::CTimer(const std::string& sFunc, uint iWarn) : sFunction(sFunc), iWarning(iWarn) { } void CTimer::start() { tmStart = Hk::Time::GetUnixMiliseconds(); } uint CTimer::stop() { auto timeDelta = static_cast<uint>(Hk::Time::GetUnixMiliseconds() - tmStart); if (FLHookConfig::i()->general.logPerformanceTimers) { if (timeDelta > iMax && timeDelta > iWarning) { AddLog(LogType::PerfTimers, LogLevel::Info, std::format("Spent {} ms in {}, longest so far.", timeDelta, sFunction)); iMax = timeDelta; } else if (timeDelta > 100) { AddLog(LogType::PerfTimers, LogLevel::Info, std::format("Spent {} ms in {}", timeDelta, sFunction)); } } return timeDelta; } /************************************************************************************************************* check if temporary ban has expired **************************************************************************************************************/ void TimerTempBanCheck() { const auto* config = FLHookConfig::c(); if (config->general.tempBansEnabled) { TempBanManager::i()->ClearFinishedTempBans(); } } /************************************************************************************************************** check if players should be kicked **************************************************************************************************************/ void TimerCheckKick() { CallPluginsBefore(HookedCall::FLHook__TimerCheckKick); TRY_HOOK { // for all players PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; if (client < 1 || client > MaxClientId) continue; if (ClientInfo[client].tmKickTime) { if (Hk::Time::GetUnixMiliseconds() >= ClientInfo[client].tmKickTime) { Hk::Player::Kick(client); // kick time expired ClientInfo[client].tmKickTime = 0; } continue; // player will be kicked anyway } const auto* config = FLHookConfig::c(); if (config->general.antiBaseIdle) { // anti base-idle check uint baseId; pub::Player::GetBase(client, baseId); if (baseId && ClientInfo[client].iBaseEnterTime && (time(0) - ClientInfo[client].iBaseEnterTime) >= config->general.antiBaseIdle) { AddKickLog(client, "Base idling"); Hk::Player::MsgAndKick(client, L"Base idling", 10); ClientInfo[client].iBaseEnterTime = 0; } } if (config->general.antiCharMenuIdle) { // anti charmenu-idle check if (Hk::Client::IsInCharSelectMenu(client)) { if (!ClientInfo[client].iCharMenuEnterTime) ClientInfo[client].iCharMenuEnterTime = static_cast<uint>(time(nullptr)); else if ((time(0) - ClientInfo[client].iCharMenuEnterTime) >= config->general.antiCharMenuIdle) { AddKickLog(client, "Charmenu idling"); Hk::Player::Kick(client); ClientInfo[client].iCharMenuEnterTime = 0; continue; } } else ClientInfo[client].iCharMenuEnterTime = 0; } } } CATCH_HOOK({}) } /************************************************************************************************************** Check if NPC spawns should be disabled **************************************************************************************************************/ void TimerNPCAndF1Check() { CallPluginsBefore(HookedCall::FLHook__TimerNPCAndF1Check); TRY_HOOK { PlayerData* playerData = nullptr; while ((playerData = Players.traverse_active(playerData))) { ClientId client = playerData->iOnlineId; if (client < 1 || client > MaxClientId) continue; if (ClientInfo[client].tmF1Time && (Hk::Time::GetUnixMiliseconds() >= ClientInfo[client].tmF1Time)) { // f1 Server.CharacterInfoReq(client, false); ClientInfo[client].tmF1Time = 0; } else if (ClientInfo[client].tmF1TimeDisconnect && (Hk::Time::GetUnixMiliseconds() >= ClientInfo[client].tmF1TimeDisconnect)) { ulong dataArray[64] = { 0 }; dataArray[26] = client; __asm { pushad lea ecx, dataArray mov eax, [hModRemoteClient] add eax, ADDR_RC_DISCONNECT call eax ; disconncet popad } ClientInfo[client].tmF1TimeDisconnect = 0; continue; } } const auto* config = FLHookConfig::c(); if (config->general.disableNPCSpawns && (CoreGlobals::c()->serverLoadInMs >= config->general.disableNPCSpawns)) Hk::Admin::ChangeNPCSpawn(true); // serverload too high, disable npcs else Hk::Admin::ChangeNPCSpawn(false); } CATCH_HOOK({}) } /************************************************************************************************************** **************************************************************************************************************/ CRITICAL_SECTION csIPResolve; std::list<RESOLVE_IP> g_lstResolveIPs; std::list<RESOLVE_IP> g_lstResolveIPsResult; HANDLE hThreadResolver; void ThreadResolver() { TRY_HOOK { while (true) { EnterCriticalSection(&csIPResolve); std::list<RESOLVE_IP> lstMyResolveIPs = g_lstResolveIPs; g_lstResolveIPs.clear(); LeaveCriticalSection(&csIPResolve); for (auto& ip : lstMyResolveIPs) { SOCKADDR_IN addr { AF_INET, 2302, {}, { 0 } }; InetPtonW(AF_INET, ip.wscIP.c_str(), &addr.sin_addr); wchar_t hostbuf[255]; GetNameInfoW( reinterpret_cast<const SOCKADDR*>(&addr), sizeof(addr), hostbuf, std::size(hostbuf), nullptr, 0, 0); ip.wscHostname = hostbuf; } EnterCriticalSection(&csIPResolve); for (auto& ip : lstMyResolveIPs) { if (ip.wscHostname.length()) g_lstResolveIPsResult.push_back(ip); } LeaveCriticalSection(&csIPResolve); Sleep(50); } } CATCH_HOOK({}) } /************************************************************************************************************** **************************************************************************************************************/ void TimerCheckResolveResults() { TRY_HOOK { EnterCriticalSection(&csIPResolve); for (const auto& ip : g_lstResolveIPsResult) { if (ip.iConnects != ClientInfo[ip.client].iConnects) continue; // outdated // check if banned for (const auto* config = FLHookConfig::c(); const auto& ban : config->bans.banWildcardsAndIPs) { if (Wildcard::Fit(wstos(ban).c_str(), wstos(ip.wscHostname).c_str())) { AddKickLog(ip.client, wstos(std::format(L"IP/Hostname ban({} matches {})", ip.wscHostname.c_str(), ban.c_str()))); if (config->bans.banAccountOnMatch) Hk::Player::Ban(ip.client, true); Hk::Player::Kick(ip.client); } } ClientInfo[ip.client].wscHostname = ip.wscHostname; } g_lstResolveIPsResult.clear(); LeaveCriticalSection(&csIPResolve); } CATCH_HOOK({}) } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
7,022
C++
.cpp
207
29.898551
127
0.562389
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,411
StartupCache.cpp
TheStarport_FLHook/source/Features/StartupCache.cpp
#include "Global.hpp" namespace StartupCache { // The number of characters loaded. static int chars_loaded = 0; // The original function read charname function typedef int(__stdcall* _ReadCharacterName)(const char* filename, st6::wstring* str); _ReadCharacterName ReadCharName; // map of acc_char_path to char name static std::map<std::string, std::wstring> cache; static std::string scBaseAcctPath; // length of the user data path + accts\multiplayer to remove so that // we can search only for the acc_char_path static int acc_path_prefix_length = 0; // A fast alternative to the built in read character name function in server.dll static int __stdcall Cb_ReadCharacterName(const char* filename, st6::wstring* str) { Console::ConDebug("Read character - " + std::string(filename)); // If this account/charfile can be found in the character return // then name immediately. std::string acc_path(&filename[acc_path_prefix_length]); if (auto i = cache.find(acc_path); i != cache.end()) { *str = st6::wstring((ushort*)i->second.c_str()); return 1; } // Otherwise use the original FL function to load the char name // and cache the result and report that this is an uncached file ReadCharName(filename, str); cache[acc_path] = std::wstring((wchar_t*)str->c_str()); return 1; } struct NameInfo { char acc_path[27]; // accdir(11)/charfile(11).fl + terminator wchar_t name[25]; // max name is 24 chars + terminator }; static void LoadCache() { // Open the name cache file and load it into memory. std::string scPath = scBaseAcctPath + "namecache.bin"; Console::ConInfo("Loading character name cache"); FILE* file; fopen_s(&file, scPath.c_str(), "rb"); if (file) { NameInfo ni {}; while (fread(&ni, sizeof(NameInfo), 1, file)) { std::string acc_path(ni.acc_path); std::wstring name(ni.name); cache[acc_path] = name; } fclose(file); } Console::ConInfo(std::format("Loaded {} names", cache.size())); } static void SaveCache() { // Save the name cache file std::string scPath = scBaseAcctPath + "namecache.bin"; FILE* file; fopen_s(&file, scPath.c_str(), "wb"); if (file) { Console::ConInfo("Saving character name cache"); for (const auto& [charPath, charName] : cache) { NameInfo ni {}; memset(&ni, 0, sizeof(ni)); strncpy_s(ni.acc_path, 27, charPath.c_str(), charPath.size()); wcsncpy_s(ni.name, 25, charName.c_str(), charName.size()); if (!fwrite(&ni, sizeof(NameInfo), 1, file)) { Console::ConErr("Saving character name cache failed"); break; } } fclose(file); Console::ConInfo(std::format("Saved {} names", cache.size())); } cache.clear(); } // Call from Startup void Init() { // Disable the admin and banned file checks. { const BYTE patch[] = { 0x5f, 0x5e, 0x5d, 0x5b, 0x81, 0xC4, 0x08, 0x11, 0x00, 0x00, 0xC2, 0x04, 0x00 }; // pop regs, restore esp, ret 4 WriteProcMem((char*)hModServer + 0x76b3e, patch, 13); } // Hook the read character name and replace it with the caching version PatchCallAddr((char*)hModServer, 0x717be, (char*)Cb_ReadCharacterName); // Keep a reference to the old read character name function. ReadCharName = reinterpret_cast<_ReadCharacterName>(reinterpret_cast<char*>(hModServer) + 0x72fe0); // Calculate our base path char szDataPath[MAX_PATH]; GetUserDataPath(szDataPath); scBaseAcctPath = std::string(szDataPath) + "\\Accts\\MultiPlayer\\"; acc_path_prefix_length = scBaseAcctPath.length(); // Load the cache LoadCache(); } // Call from Startup_AFTER void Done() { SaveCache(); // Restore admin and banned file checks { BYTE patch[] = { 0x8b, 0x35, 0xc0, 0x4b, 0xd6, 0x06, 0x6a, 0x00, 0x68, 0xB0, 0xB8, 0xD6, 0x06 }; WriteProcMem((char*)hModServer + 0x76b3e, patch, 13); } // Unhook the read character name function. { BYTE patch[] = { 0xe8, 0x1d, 0x18, 0x00, 0x00 }; WriteProcMem((char*)hModServer + 0x717be, patch, 5); } } } // namespace StartupCache
4,050
C++
.cpp
121
30.231405
101
0.689611
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,412
Mail.cpp
TheStarport_FLHook/source/Features/Mail.cpp
#include "Features/Mail.hpp" #include "Global.hpp" std::string MailManager::GetCharacterName(const std::variant<uint, std::wstring>& character) const { // If character is uint if (!character.index()) { const auto name = Hk::Client::GetCharacterNameByID(std::get<uint>(character)); if (name.has_error()) return ""; return wstos(name.value()); } // Validate that the name is correct if (const auto acc = Hk::Client::GetAccountByCharName(std::get<std::wstring>(character)); acc.has_error()) return ""; return wstos(std::get<std::wstring>(character)); } MailManager::MailManager() { if (db.tableExists("items")) { return; } db.exec("CREATE TABLE items (" "id INTEGER NOT NULL UNIQUE PRIMARY KEY AUTOINCREMENT," "unread INTEGER(1, 1) NOT NULL CHECK(unread IN(0, 1))," "subject TEXT(36, 36) NOT NULL," "author TEXT(36, 36) NOT NULL," "body TEXT(255, 255) NOT NULL," "timestamp INTEGER NOT NULL," "characterName TEXT(36, 36) NOT NULL);"); db.exec("CREATE INDEX IDX_characterName ON items (characterName DESC);"); } cpp::result<void, std::string> MailManager::SendNewMail(const std::variant<uint, std::wstring>& character, const MailItem& item) const { const auto characterName = GetCharacterName(character); if (characterName.empty()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } if (item.subject.length() > 32) { return cpp::fail(GetErrorCode(ErrorTypes::SubjectTooLong)); } if (item.author.length() > 36) { return cpp::fail(GetErrorCode(ErrorTypes::AuthorTooLong)); } if (item.body.length() > 255) { return cpp::fail(GetErrorCode(ErrorTypes::BodyTooLong)); } SQLite::Statement newMailQuery(db, "INSERT INTO items (unread, subject, author, body, characterName, timestamp) VALUES(?, ?, ?, ?, ?, ?)"); newMailQuery.bind(1, item.unread); newMailQuery.bind(2, item.subject); newMailQuery.bind(3, item.author); newMailQuery.bind(4, item.body); newMailQuery.bind(5, characterName); newMailQuery.bind(6, item.timestamp); try { newMailQuery.exec(); } catch (SQLite::Exception& ex) { return cpp::fail(ex.getErrorStr()); } return {}; } using namespace std::string_literals; cpp::result<std::vector<MailManager::MailItem>, std::string> MailManager::GetMail( const std::variant<uint, std::wstring>& character, const bool& ignoreRead, const int& page) { const auto characterName = GetCharacterName(character); if (characterName.empty()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } if (ignoreRead) { SQLite::Statement getUnreadMail( db, "SELECT id, subject, author, body, timestamp FROM items WHERE unread = TRUE AND characterName = ? ORDER BY timestamp DESC LIMIT 15 OFFSET ?;"); getUnreadMail.bind(1, characterName); getUnreadMail.bind(2, (page - 1) * 15); std::vector<MailItem> mail; while (getUnreadMail.executeStep()) { mail.emplace_back(getUnreadMail.getColumn(0).getInt64(), true, getUnreadMail.getColumn(1).getString(), getUnreadMail.getColumn(2).getString(), getUnreadMail.getColumn(3).getString(), getUnreadMail.getColumn(4).getInt64()); } return mail; } SQLite::Statement getMail(db, "SELECT id, unread, subject, author, body, timestamp FROM items WHERE characterName = ? ORDER BY timestamp DESC LIMIT 15 OFFSET ?;"); getMail.bind(1, characterName); getMail.bind(2, (page - 1) * 15); std::vector<MailItem> mail; while (getMail.executeStep()) { mail.emplace_back(getMail.getColumn(0).getInt64(), static_cast<bool>(getMail.getColumn(1).getInt()), getMail.getColumn(2).getString(), getMail.getColumn(3).getString(), getMail.getColumn(4).getString(), getMail.getColumn(5).getInt64()); } return mail; } cpp::result<MailManager::MailItem, std::string> MailManager::GetMailById(const std::variant<uint, std::wstring>& character, const int64& index) { const auto characterName = GetCharacterName(character); if (characterName.empty()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } SQLite::Statement getMail(db, "SELECT unread, subject, author, body, timestamp FROM items WHERE characterName = ? AND id = ?;"); getMail.bind(1, characterName); getMail.bind(2, index); MailItem mail; try { if (!getMail.executeStep()) { return cpp::fail(GetErrorCode(ErrorTypes::MailIdNotFound)); } mail = MailItem(index, static_cast<bool>(getMail.getColumn(0).getInt()), getMail.getColumn(1).getString(), getMail.getColumn(2).getString(), getMail.getColumn(3).getString(), getMail.getColumn(4).getInt64()); SQLite::Statement markRead(db, "UPDATE items SET unread = FALSE WHERE id = ?;"); markRead.bind(1, index); markRead.exec(); return mail; } catch (SQLite::Exception& ex) { return cpp::fail(ex.getErrorStr()); } } cpp::result<void, std::string> MailManager::DeleteMail(const std::variant<uint, std::wstring>& character, const int64& index) const { const auto characterName = GetCharacterName(character); if (characterName.empty()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } SQLite::Statement deleteMail(db, "DELETE FROM items WHERE id = ? AND characterName = ?;"); deleteMail.bind(1, index); deleteMail.bind(2, characterName); try { if (!deleteMail.exec()) { return cpp::fail(GetErrorCode(ErrorTypes::MailIdNotFound)); } } catch (SQLite::Exception& ex) { return cpp::fail(ex.getErrorStr()); } return {}; } cpp::result<int64, std::string> MailManager::PurgeAllMail(const std::variant<uint, std::wstring>& character, const bool& readMailOnly) { const auto characterName = GetCharacterName(character); if (characterName.empty()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } SQLite::Statement deleteMail = readMailOnly ? SQLite::Statement(db, "DELETE FROM items WHERE unread = FALSE AND characterName = ?;") : SQLite::Statement(db, "DELETE FROM items WHERE characterName = ?;"); deleteMail.bind(1, characterName); try { int count = deleteMail.exec(); if (!count) { return cpp::fail("No mail to delete."); } return count; } catch (SQLite::Exception& ex) { return cpp::fail(ex.getErrorStr()); } } cpp::result<int64, std::string> MailManager::UpdateCharacterName(const std::string& oldCharacterName, const std::string& newCharacterName) { if (const auto acc = Hk::Client::GetAccountByCharName(stows(newCharacterName)); acc.has_error()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } SQLite::Statement updateName(db, "UPDATE items SET characterName = ? WHERE characterName = ?;"); updateName.bind(1, newCharacterName); updateName.bind(2, oldCharacterName); try { int count = updateName.exec(); if (!count) { return cpp::fail(GetErrorCode(ErrorTypes::MailIdNotFound)); } return count; } catch (SQLite::Exception& ex) { return cpp::fail(ex.getErrorStr()); } } cpp::result<int64, std::string> MailManager::GetUnreadMail(const std::variant<uint, std::wstring>& character) { const auto characterName = GetCharacterName(character); if (characterName.empty()) { return cpp::fail(GetErrorCode(ErrorTypes::InvalidCharacter)); } SQLite::Statement count(db, "SELECT COUNT(*) FROM items WHERE characterName = ?;"); count.bind(1, characterName); if (count.executeStep()) { return count.getColumn(0).getInt64(); } return 0; } void MailManager::SendMailNotification(const std::variant<uint, std::wstring>& character) { const auto client = Hk::Client::ExtractClientID(character); if (client == UINT_MAX) { return; } const auto mailCount = GetUnreadMail(client); if (mailCount.has_error()) { Console::ConErr(mailCount.error()); } else if (mailCount.value() > 0) { PrintUserCmdText(client, std::format(L"You have {} unread mail! Read it via /mailread.", mailCount.value())); } } void MailManager::CleanUpOldMail() { try { SQLite::Statement getAllUniqueCharacterNames(db, "SELECT characterName FROM items GROUP BY characterName;"); while (getAllUniqueCharacterNames.executeStep()) { const auto name = stows(getAllUniqueCharacterNames.getColumn(0)); const auto acc = Hk::Client::GetAccountByCharName(name); if (acc.has_error()) { PurgeAllMail(name, false); } } } catch (SQLite::Exception& ex) { AddLog(LogType::Normal, LogLevel::Err, std::format("Unable to perform mail cleanup. Err: {}", ex.getErrorStr())); } }
8,492
C++
.cpp
267
28.88015
164
0.722793
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,413
AntiJumpDisconnect.h
TheStarport_FLHook/plugins/anti_jump_disconnect/AntiJumpDisconnect.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::AntiJumpDisconnect { //! Global data for this plugin struct Global final { ReturnCode returncode = ReturnCode::Default; struct INFO { bool bInWrapGate; }; //! Map of client ids and whether they are in a gate or not std::map<uint, INFO> mapInfo; }; } // namespace Plugins::AntiJumpDisconnect
387
C++
.h
17
20.470588
61
0.746594
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,414
LightControl.h
TheStarport_FLHook/plugins/light_control/LightControl.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::LightControl { //! A hardpoint for a single client. struct EquipmentHardpoint { EquipmentHardpoint() = default; uint id = 0; uint archId = 0; uint originalArchId = 0; std::wstring hardPoint; }; //! Config data for this plugin struct Config final : Reflectable { std::string File() override { return "config/light_control.json"; } //! Vector of Available equipment std::vector<uint> lightsHashed; std::vector<std::wstring> lights; //! cost per changed item. uint cost = 0; //! For options command, how many items to display. uint itemsPerPage = 24; //! Map of bases who offer LightControl std::vector<std::string> bases; std::vector<uint> baseIdHashes; //! Intro messages when entering the base. std::wstring introMessage1 = L"Light customization facilities are available here."; std::wstring introMessage2 = L"Type /lights on your console to see options."; bool notifyAvailabilityOnEnter = false; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; jpWide::Regex regex = jpWide::Regex(L"(?<=.{2})([A-Z])", "g"); }; } // namespace Plugins::LightControl
1,287
C++
.h
41
28.707317
85
0.726316
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,415
Restarts.h
TheStarport_FLHook/plugins/restarts/Restarts.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Restart { //! A struct containing a pending restart struct Restart final { //! Name of the character std::wstring characterName; //! The name of the restart .fl file they wish to be applied to them std::string restartFile; //! The directory of the character file std::wstring directory; //! The name of the character file std::wstring characterFile; //! The amount of cash to be saved to the character file uint cash; }; //! Config data for this plugin struct Config final : Reflectable { //! Players with a cash above this value cannot use the restart command. uint maxCash = 1000000; //! Players with a rank above this value cannot use the restart command. int maxRank = 5; //! Where to enable the restarts costing money or being free bool enableRestartCost; //! File path of the json config file std::string File() override { return "config/restarts.json"; } //! A map of restart names and their cost std::map<std::wstring, uint> availableRestarts; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; //! A vector of currently pending restarts std::vector<Restart> pendingRestarts; }; } // namespace Plugins::Restart
1,354
C++
.h
42
29.619048
74
0.740031
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,416
DailyTasks.hpp
TheStarport_FLHook/plugins/daily_tasks/DailyTasks.hpp
#pragma once #include <FLHook.hpp> #include <plugin.h> #include <ranges> #include <random> namespace Plugins::DailyTasks { // Loadable json configuration struct Config : Reflectable { std::string File() override { return "config/daily_tasks.json"; } //! The number of randomly generated tasks a player will receive each day. int taskQuantity = 3; //! The minimum possible amount of credits that can be awarded for completing a daily task. int minCreditsReward = 5000; //! The maximum possible amount of credits that can be awarded for completing a daily task. int maxCreditsReward = 10000; //! A pool of possible item rewards for completing a daily task. std::map<std::string, std::vector<int>> itemRewardPool { {{"commodity_luxury_consumer_goods"}, {{5}, {10}}}, {{"commodity_diamonds"}, {{25}, {40}}}, {{"commodity_alien_artifacts"}, {{10}, {25}}}}; //! Possible target bases for trade tasks. std::vector<std::string> taskTradeBaseTargets {{"li03_01_base"}, {"li03_02_base"}, {"li03_03_base"}}; //! Possible target items and their minimum and maximum quantity for trade tasks. std::map<std::string, std::vector<int>> taskTradeItemTargets { {{"commodity_cardamine"}, {{5}, {10}}}, {{"commodity_scrap_metal"}, {{25}, {40}}}, {{"commodity_construction_machinery"}, {{10}, {25}}}}; //! Possible options for item acquisition tasks. Parameters are item and quantity. std::map<std::string, std::vector<int>> taskItemAcquisitionTargets { {{"commodity_optronics"}, {{3}, {5}}}, {{"commodity_super_alloys"}, {{10}, {15}}}, {{"commodity_mox_fuel"}, {{8}, {16}}}}; //! Possible options for NPC kill tasks. Parameters are target faction and quantity. std::map<std::string, std::vector<int>> taskNpcKillTargets = {{{"fc_x_grp"}, {{3}, {5}}}, {{"li_n_grp"}, {{10}, {15}}}}; //! Possible options for player kill tasks. Parameters are minimum and maximum quantity of kills needed. std::vector<int> taskPlayerKillTargets = {{1}, {3}}; //! The server hour at which players will be able to use the reset tasks command again. int resetTime = 12; //! The amount of time in seconds a player has to complete a set of assigned tasks before they get cleaned up during the hourly check or at login. int taskDuration = 86400; //! Whether or not to display a message with daily task data when a player logs in. bool displayMessage = true; }; enum class TaskType { GetItem, KillNpc, KillPlayer, SellItem }; struct Task : Reflectable { TaskType taskType = TaskType::GetItem; int quantity = 0; int quantityCompleted = 0; uint itemTarget = 0; uint baseTarget = 0; uint npcFactionTarget = 0; std::string taskDescription; bool isCompleted = false; uint setTime = 0; }; struct Tasks : Reflectable { std::vector<Task> tasks; }; struct Global { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; std::map<uint, bool> playerTaskAllocationStatus; std::map<uint, std::vector<int>> itemRewardPool; std::map<uint, std::vector<int>> taskTradeItemTargets; std::map<uint, std::vector<int>> taskItemAcquisitionTargets; std::map<uint, std::vector<int>> taskNpcKillTargets; std::vector<uint> taskTradeBaseTargets; std::vector<TaskType> taskTypePool; std::map<CAccount*, Tasks> accountTasks; std::map<CAccount*, bool> tasksReset; bool dailyReset; std::map<uint, float> goodList; }; } // namespace Plugins::DailyTasks
3,451
C++
.h
79
40.835443
148
0.711356
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,417
NPCControl.h
TheStarport_FLHook/plugins/npc_control/NPCControl.h
#pragma once #include <FLHook.hpp> #include <plugin.h> #include <spdlog/logger.h> #include <spdlog/async.h> #include <spdlog/sinks/basic_file_sink.h> #include <random> namespace Plugins::Npc { //! A struct that represents an npc that can be spawned struct Npc final : Reflectable { std::string shipArch = "ge_fighter"; std::string loadout = "MP_ge_fighter"; std::string iff = "fc_fl_grp"; uint iffId = 0; uint infocardId = 197808; uint infocard2Id = 197809; std::string pilot = "pilot_pirate_ace"; std::string graph = "FIGHTER"; // NOTHING, FIGHTER, TRANSPORT, GUNBOAT, CRUISER. Possibly (unconfirmed) MINER, CAPITAL, FREIGHTER uint shipArchId = 0; uint loadoutId = 0; }; // A struct that represents a fleet that can be spawned struct Fleet final : Reflectable { std::wstring name = L"example"; std::map<std::wstring, int> member = {{L"example", 5}}; }; // A struct that represents an NPC that is spawned on startup struct StartupNpc final : Reflectable { std::wstring name = L"example"; std::string system = "li01"; float spawnChance = 1; std::vector<float> position = {-33367, 120, -28810}; std::vector<float> rotation = {0, 0, 0}; uint systemId = 0; Matrix rotationMatrix = {0, 0, 0}; Vector positionVector = {0, 0, 0}; }; //! Config data for this plugin struct Config final : Reflectable { //! Map of npcs that can be spawned std::map<std::wstring, Npc> npcInfo = {{L"example", Npc()}}; //! Map of fleets that can be spawned std::map<std::wstring, Fleet> fleetInfo = {{L"example", Fleet()}}; //! Vector of npcs that are spawned on startup std::vector<StartupNpc> startupNpcs = {StartupNpc()}; //! Vector containing Infocard Ids used for naming npcs std::vector<uint> npcInfocardIds {197808}; //! The config file we load out of std::string File() override { return "config/npc.json"; } }; //! Communicator class for this plugin. This is used by other plugins class NpcCommunicator : public PluginCommunicator { public: inline static const char* pluginName = "NPC Control"; explicit NpcCommunicator(const std::string& plug); uint PluginCall(CreateNpc, const std::wstring& name, Vector position, const Matrix& rotation, SystemId systemId, bool varyPosition); }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; std::vector<const char*> listGraphs {}; std::vector<uint> spawnedNpcs {}; std::shared_ptr<spdlog::logger> log = nullptr; uint dockNpc = 0; NpcCommunicator* communicator = nullptr; }; } // namespace Plugins::Npc
2,631
C++
.h
75
32.533333
134
0.715351
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,418
NPCSpinProtection.h
TheStarport_FLHook/plugins/npc_spin_protection/NPCSpinProtection.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::NPCSpinProtection { //! Config data for this plugin struct Config : Reflectable { //! The minimum amount of mass a ship must have for spin protection to kick in float spinProtectionMass = 180.0f; //! The higher this value is the more aggressive the spin protection is float spinImpulseMultiplier = -1.0f; //! File location of the json config file std::string File() override { return "config/npc_spin_protection.json"; } }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; }; } // namespace Plugins::NPCSpinProtection
713
C++
.h
22
30.090909
80
0.755102
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,419
Message.h
TheStarport_FLHook/plugins/message/Message.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Message { //! Number of auto message slots constexpr int NumberOfSlots = 10; //! A struct to represent each client class ClientInfo { public: ClientInfo() = default; //! Slots that contain prewritten messages std::array<std::wstring, NumberOfSlots> slots; //! Client Id of last PM. uint lastPmClientId = -1; //! Client Id of selected target uint targetClientId = -1; //! Current chat time settings bool showChatTime = false; //! True if the login banner has been displayed. bool greetingShown = true; //! Swear word warn level int swearWordWarnings = 0; }; //! Config data for this plugin struct Config : Reflectable { //! The json file we load out of std::string File() override { return "config/message.json"; } //! Greetings text for when user logins in std::vector<std::wstring> greetingBannerLines; //! special banner text, on timer std::vector<std::wstring> specialBannerLines; //! standard banner text, on timer std::vector<std::wstring> standardBannerLines; //! Time in second to repeat display of special banner int specialBannerTimeout = 5; //! Time in second to repeat display of standard banner int standardBannerTimeout = 60; //! true if we override flhook built in help bool customHelp = false; //! true if we don't echo mistyped user and admin commands to other players. bool suppressMistypedCommands = true; //! if true support the /showmsg and /setmsg commands. This needs a client hook bool enableSetMessage = false; //! Enable /me command bool enableMe = true; //! Enable /do command bool enableDo = true; //! String that stores the disconnect message for swearing in space std::wstring disconnectSwearingInSpaceMsg = L"%player has been kicked for swearing"; //! Amount of time in minutes for which to tempban a player in case of swearing uint swearingTempBanDuration = 10; //! What radius around the player the message should be broadcasted to float disconnectSwearingInSpaceRange = 5000.0f; //! Vector of swear words std::vector<std::wstring> swearWords; }; //! Global data for this plugin struct Global final { ReturnCode returncode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; //! Cache of preset messages for the online players (by client Id) std::map<uint, ClientInfo> info; //! This parameter is sent when we send a chat time line so that we don't print a time chat line recursively. bool sendingTime = false; }; //! A random macro to make things easier #define HAS_FLAG(a, b) ((a).wscFlags.find(b) != -1) void UserCmd_ReplyToLastPMSender(ClientId& client, const std::wstring& wscParam); void UserCmd_SendToLastTarget(ClientId& client, const std::wstring& wscParam); } // namespace Plugins::Message
2,865
C++
.h
74
35.743243
111
0.743664
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,420
CargoDrop.h
TheStarport_FLHook/plugins/cargo_drop/CargoDrop.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::CargoDrop { //! Used to store info about each client class Info { public: Info() : f1DisconnectProcessed(false), lastTimestamp(0) {} bool f1DisconnectProcessed; double lastTimestamp; Vector lastPosition; Quaternion lastDirection; }; //! Config data for this plugin struct Config final : Reflectable { std::string File() override { return "config/cargo_drop.json"; } // Reflectable fields //! If true, inform all players within range specified in disconnectingPlayersRange about the player disconnecting. bool reportDisconnectingPlayers = false; //! If true, kills the player should they disconnect while another player is within range specified in disconnectingPlayersRange. bool killDisconnectingPlayers = false; //! If true, drops the players cargo into space if there were players within range specified in disconnectingPlayersRange. bool lootDisconnectingPlayers = false; //! If true, causes players to drop all non-mounted equipment and commodities on death. bool enablePlayerCargoDropOnDeath = false; //! Caps the amount of any individual cargo type(weapon, commodity) being left behind on death. //! Sum of various cargos can exceed this number. int maxPlayerCargoDropCount = 3000; //! Distance used to decide if report/player death should occur based on proximity to other players. float disconnectingPlayersRange = 5000.0f; //! Ratio of ship's mass space to 'ship parts' commodities left behind on death, specified in playerOnDeathCargo. The number of items dropped of each type is equal to ship mass multiplied by hullDropFactor. float hullDropFactor = 0.1f; //! Message broadcasted to nearby players upon disconnect if reportDisconnectingPlayers is true. std::string disconnectMsg = "%player is attempting to engage cloaking device"; //! Nickname of loot container model containing cargo/ship parts left behind upon death/disconnection. std::string cargoDropContainer = "lootcrate_ast_loot_metal"; //! Contains a list of nicknames of items that will always be dropped into space when a player is destroyed if hullDropFactor is above zero. std::vector<std::string> playerOnDeathCargo = {"commodity_super_alloys", "commodity_engine_components"}; //! Contains a list of nicknames of items that will not be dropped into space under any circumstances. std::vector<std::string> noLootItems = {}; }; //! Global data for this plugin struct Global final { //! Contains config data defined above std::unique_ptr<Config> config = nullptr; //! Default return code of the plugin ReturnCode returnCode = ReturnCode::Default; //! Map of ClientIds and the Info Struct defined above std::map<uint, Info> info; //! The id of the container to drop uint cargoDropContainerId; //! This id is for commodities to represent the ship after destruction std::vector<uint> playerOnDeathCargo; //! Items we don't want to be looted std::vector<uint> noLootItemsIds; }; } // namespace Plugins::CargoDrop
3,063
C++
.h
61
47.491803
208
0.775108
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,421
Event.h
TheStarport_FLHook/plugins/event/Event.h
#pragma once #include <FLHook.hpp> #include <plugin.h> #include <nlohmann/json.hpp> namespace Plugins::Event { struct CARGO_MISSION { std::string nickname; uint base; uint item; int required_amount; int current_amount; }; struct NPC_MISSION { std::string nickname; uint system; std::string sector; uint reputation; int required_amount; int current_amount; }; //! Configurable fields for this plugin struct Config final : Reflectable { std::string File() override { return "config/event.json"; } struct NPC_MISSION_REFLECTABLE : Reflectable { std::string nickname = "Example"; std::string system = "li01"; std::string sector = "D-6"; std::string reputation = "fc_lr_grp"; int required_amount = 99; int current_amount = 0; }; struct CARGO_MISSION_REFLECTABLE : Reflectable { std::string nickname = "Example"; std::string base = "li01_01_base"; std::string item = "commodity_gold"; int required_amount = 99; int current_amount = 0; }; CARGO_MISSION_REFLECTABLE example; NPC_MISSION_REFLECTABLE example2; // Reflectable fields std::map<std::string, CARGO_MISSION_REFLECTABLE> CargoMissions = {{example.nickname, example}}; std::map<std::string, NPC_MISSION_REFLECTABLE> NpcMissions = {{example2.nickname, example2}}; }; struct Global final { // Map of base Id to mission structure std::vector<CARGO_MISSION> CargoMissions; // Map of repgroup Id to mission structure std::vector<NPC_MISSION> NpcMissions; std::map<uint, std::string> nicknameToNameMap; // A return code to indicate to FLHook if we want the hook processing to // continue. ReturnCode returncode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; }; }
1,746
C++
.h
63
24.793651
97
0.725478
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,422
IPBan.h
TheStarport_FLHook/plugins/ip_ban/IPBan.h
#pragma once #include <FLHook.hpp> #include <plugin.h> struct Config : Reflectable { std::string File() override { return "config/ip_ban.json"; } std::wstring BanMessage = L"You are banned, please contact an administrator"; }; struct IPBans : Reflectable { std::string File() override { char path[MAX_PATH]; GetUserDataPath(path); return std::string(path) + "\\IPBans.json"; } std::vector<std::string> Bans; }; struct LoginIdBans : Reflectable { std::string File() override { char path[MAX_PATH]; GetUserDataPath(path); return std::string(path) + "\\LoginIdBans.json"; } std::vector<std::string> Bans; }; struct AuthenticatedAccounts : Reflectable { std::string File() override { char path[MAX_PATH]; GetUserDataPath(path); return std::string(path) + "\\AuthenticatedAccounts.json"; } std::vector<std::wstring> Accounts; }; struct Global final { ReturnCode returncode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; /// list of bans IPBans ipBans; LoginIdBans loginIdBans; // Authenticated accounts even if they are banned somehow AuthenticatedAccounts authenticatedAccounts; std::map<uint, bool> IPChecked; };
1,179
C++
.h
49
22.020408
78
0.749777
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,423
Arena.h
TheStarport_FLHook/plugins/arena/Arena.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Arena { enum class ClientState { None, Transfer, Return }; const std::wstring StrInfo1 = L"Please dock at nearest base"; const std::wstring StrInfo2 = L"Cargo hold is not empty"; //! Config data for this plugin struct Config final : Reflectable { std::string File() override { return "config/arena.json"; } // Reflectable fields //! The command to be used to beam to the arena system. Defaults to "arena". std::string command = "arena"; //! The base in the pvp system they should be beamed to. std::string targetBase; //! The pvp system they should be beamed to. std::string targetSystem; //! The system the commands should not work for. std::string restrictedSystem; // Non-reflectable fields uint targetBaseId; uint targetSystemId; uint restrictedSystemId; std::wstring wscCommand; }; //! Global data for this plugin struct Global { std::array<ClientState, MaxClientId + 1> transferFlags; //! This plugin can communicate with the base plugin if loaded. // BaseCommunicator* baseCommunicator = nullptr; //! Return code for the plugin ReturnCode returnCode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; }; } // namespace Plugins::Arena
1,296
C++
.h
43
27.581395
78
0.740176
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,424
Afk.h
TheStarport_FLHook/plugins/afk/Afk.h
#pragma once // Includes #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Afk { //! Global data for this plugin struct Global final { // Other fields ReturnCode returnCode = ReturnCode::Default; std::vector<uint> awayClients; }; } // namespace Plugins::Afk
281
C++
.h
14
18.214286
46
0.74717
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,425
Main.hpp
TheStarport_FLHook/plugins/_plugin_template/Main.hpp
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Template { // Loadable json configuration struct Config : Reflectable { std::string File() override { return "config/template.json"; } bool overrideUserNumber = false; }; struct Global { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; }; } // namespace Plugins::Template
404
C++
.h
17
21.588235
64
0.753927
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,426
Stats.h
TheStarport_FLHook/plugins/stats/Stats.h
#pragma once #include <FLHook.hpp> #include <fstream> #include <iostream> #include <nlohmann/json.hpp> #include <plugin.h> namespace Plugins::Stats { //! Reflectable struct that contains the file path of the config file as well as the file to export stats to struct FileName : Reflectable { std::string File() override { return "config/stats.json"; } std::string StatsFile = "stats.json"; std::string FilePath = "EXPORTS"; }; //! Global data for this plugin struct Global final { ReturnCode returncode = ReturnCode::Default; FileName jsonFileName; //! A map containing a shipId and the user friendly name std::map<ShipId, std::wstring> Ships; }; } // namespace Plugins::Stats
701
C++
.h
24
27.166667
109
0.746291
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,427
MiscCommands.h
TheStarport_FLHook/plugins/misc_commands/MiscCommands.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::MiscCommands { //! The struct that holds client info for this plugin struct MiscClientInfo { bool lightsOn = false; bool shieldsDown = false; }; //! Config data for this plugin struct Config final : Reflectable { std::string File() override { return "config/misc_commands.json"; } //! The amount it costs to use the /droprep command. uint repDropCost = 0; bool enableDropRep = true; //! The message that will be displayed when the /stuck command is used. std::wstring stuckMessage = L"Attention! Stand Clear. Towing %player"; //! The message that will be displayed when the /dice command is used. std::wstring diceMessage = L"%player rolled %number of %max"; //! The message that will be displayed when the /coin command is used. std::wstring coinMessage = L"%player tosses %result"; //! The music that will be played when an admin activates .smiteall std::string smiteMusicId = "music_danger"; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; // Other fields ReturnCode returncode = ReturnCode::Default; //! The hash smite music. uint smiteMusicHash = 0; //! A map of client id to client data std::map<uint, MiscClientInfo> mapInfo; }; } // namespace Plugins::MiscCommands
1,359
C++
.h
39
32.282051
73
0.734196
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,428
KillTracker.h
TheStarport_FLHook/plugins/kill_tracker/KillTracker.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::KillTracker { //! Struct to hold the Kill Streaks struct KillMessage final : Reflectable { uint number = 0; std::wstring message; KillMessage(int numberParam, std::wstring const& messageParam) : number(numberParam), message(messageParam) {} KillMessage() = default; }; //! Configurable fields for this plugin struct Config final : Reflectable { std::string File() override { return "config/killtracker.json"; } // Reflectable fields //! If enabled, lists all NPC ship types killed, along with kill counts. bool enableNPCKillOutput = false; //! If enabled, broadcasts a system message announcing the player with the biggest contribution to the kill. bool enableDamageTracking = false; //! If enabled, broadcasts //! Message broadcasted systemwide upon ship's death if enableDamageTracking is true. //! {0} is replaced with victim's name, {1} with player who dealt the most damage to them, //! {2} with percentage of hull damage taken byt that player. std::wstring deathDamageTemplate = L"{0} took most hull damage from {1}, {2}%"; //! Message broadcasted systemwide upon ship's death if template isn't empty. //! {0} corresponds to the killers name, {1} corresponds to the victims name, //! {2} corresponds to the kill count std::vector<KillMessage> killStreakTemplates = { KillMessage(5, L"{0} is on a killing spree!"), KillMessage(10, L"{0} has claimed {2} kills!"), KillMessage(15, L"{0} has slain {1} for kill {2}") }; //! Message broadcasted systemwide when player reaches certain kill counts, //! if template isn't empty. {0} corresponds to said players name std::vector<KillMessage> milestoneTemplates = { KillMessage(100, L"{0} has killed their 100th enemy!"), KillMessage(1000, L"{0} has killed their 1,000th enemy!"), KillMessage(10000, L"{0} has killed their 10,000th enemy!") }; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; std::array<std::array<float, MaxClientId + 1>, MaxClientId + 1> damageArray; std::array<float, MaxClientId + 1> lastPlayerHealth; ReturnCode returncode = ReturnCode::Default; std::map<ClientId, uint> killStreaks; std::map<int, std::wstring> killStreakTemplates; std::map<int, std::wstring> milestoneTemplates; }; } // namespace Plugins::KillTracker
2,426
C++
.h
57
39.561404
112
0.728003
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,429
Warehouse.h
TheStarport_FLHook/plugins/warehouse/Warehouse.h
#pragma once #include <FLHook.hpp> namespace Plugins::Warehouse { struct Config final : Reflectable { std::string File() override { return "config/warehouse.json"; } //! Vector of base nicknames where warehouse functionality is not available. std::vector<std::string> restrictedBases; std::vector<uint> restrictedBasesHashed; //! Vector of item nicknames which cannot be stored using the warehouse functionality. std::vector<std::string> restrictedItems; std::vector<uint> restrictedItemsHashed; //! Credit cost of withdrawing an item from the warehouse. uint costPerStackWithdraw = 0; //! Credit cost of depositing an item into the warehouse. uint costPerStackStore = 0; }; struct WareHouseItem { int64 id; uint equipArchId; int64 quantity; }; //! Global data for this plugin struct Global final { // Other fields ReturnCode returnCode = ReturnCode::Default; SQLite::Database sql = SqlHelpers::Create("warehouse.sqlite"); Config config; }; extern const std::unique_ptr<Global> global; void CreateSqlTables(); int64 GetOrAddBase(BaseId& base); int64 GetOrAddPlayer(int64 baseId, const CAccount* acc); WareHouseItem GetOrAddItem(EquipId& item, int64 playerId, int64 quantity = 0); int64 RemoveItem(const int64& sqlId, int64 playerId, int64 quantity); std::vector<WareHouseItem> GetAllItemsOnBase(int64 playerId, int64 baseId); std::map<int64, std::vector<WareHouseItem>> GetAllBases(int64 playerId); } // namespace Plugins::Warehouse
1,497
C++
.h
41
33.95122
88
0.77455
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,430
LootTables.hpp
TheStarport_FLHook/plugins/loot_tables/LootTables.hpp
#pragma once #include <FLHook.hpp> #include <plugin.h> #include <random> namespace Plugins::LootTables { struct DropWeight final : Reflectable { uint weighting = 2; // Weights are relative, meaning to compute drop likelihood, do w_i / sum(w_1, w_2, ...) uint itemHashed = 0; std::string item = "missile01_mark02_ammo"; uint dropCount = 3; }; struct LootTable final : Reflectable { uint rollCount = 5; bool applyToPlayers = false; bool applyToNpcs = false; std::string triggerItem = "missile01_mark02"; uint triggerItemHashed = 0; std::vector<DropWeight> dropWeights = { DropWeight() }; }; // Loadable json configuration struct Config final : Reflectable { // What json file to use / write to std::string File() override { return "config/loottables.json"; } // Crate to use for loot std::string lootDropContainer = "lootcrate_ast_loot_metal"; uint lootDropContainerHashed = 0; // Loot Tables std::vector<LootTable> lootTables = { LootTable() }; }; struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returncode = ReturnCode::Default; }; } // namespace Plugins::Template
1,152
C++
.h
39
27
110
0.726449
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,431
Tax.h
TheStarport_FLHook/plugins/tax/Tax.h
#pragma once // Included #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Tax { //! Structs struct Tax { uint targetId; uint initiatorId; std::wstring target; std::wstring initiator; uint cash; bool f1; }; //! Configurable fields for this plugin struct Config final : Reflectable { std::string File() override { return "config/tax.json"; } // Reflectable fields //! Minimal playtime in seconds required for a character to be a valid demand target. int minplaytimeSec = 0; //! Maximum amount of credits a player can demand from another. uint maxTax = 300; //! Color of messages that will be broadcasted by this plugin. MessageColor customColor = MessageColor::LightGreen; //! Formatting of the messages broadcasted by this plugin. MessageFormat customFormat = MessageFormat::Small; //! Message letting the target know about the size of the demand, as well as informing them on how to comply. std::wstring taxRequestReceived = L"You have received a tax request: Pay {} credits to {}! Type \"/pay\" to pay the tax."; //! Message letting the target know they're being attacked. std::wstring huntingMessage = L"You are being hunted by {}. Run for cover, they want to kill you!"; //! Confirmation message to the aggressor that the victim has been informed. std::wstring huntingMessageOriginator = L"Good luck hunting {} !"; //! Message received if payment attempt is made on std::wstring cannotPay = L"This rogue isn't interested in money. Run for cover, they want to kill you!"; //! If true, kills the players who disconnect while having a demand levied against them. bool killDisconnectingPlayers = true; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; std::list<Tax> lsttax; std::vector<uint> excludedsystemsIds; }; } // namespace Plugins::Tax
1,926
C++
.h
49
36.734694
124
0.744658
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,432
MiningControl.h
TheStarport_FLHook/plugins/minecontrol/MiningControl.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::MiningControl { //! A struct that defines a mining bonus to a player if they meet certain criteria struct PlayerBonus : Reflectable { PlayerBonus() = default; //! The loot commodity id this configuration applies to. std::string Loot = "commodity_gold"; uint LootId = 0; //! The loot bonus multiplier. float Bonus = 0.0f; //! The affiliation/reputation of the player std::string Rep = "li_n_grp"; uint RepId = UINT_MAX; //! The list of ships that this bonus applies to std::vector<std::string> Ships = {"ge_fighter"}; std::vector<uint> ShipIds; //! The list of equipment items that the ship must carry std::vector<std::string> Items = {"ge_s_battery_01"}; std::vector<uint> ItemIds; //! The list of ammo arch ids for mining guns std::vector<std::string> Ammo = {"missile01_mark01"}; std::vector<uint> AmmoIds; }; //! A struct that defines a mining bonus for a certain zone in space struct ZoneBonus : Reflectable { ZoneBonus() = default; std::string Zone = "ExampleZone"; //! The loot bonus multiplier. float Bonus = 0.0f; //! The hash of the item to replace the dropped std::string ReplacementLoot = "commodity_gold"; uint ReplacementLootId = 0; //! The recharge rate of the zone. This is the number of units of ore added to the reserve per minute. float RechargeRate = 0; //! The current amount of ore in the zone. When this gets low, ore gets harder to mine. When it gets to 0, ore is impossible to mine. float CurrentReserve = 100000; //! The maximum limit for the amount of ore in the field float MaxReserve = 50000; //! The amount of ore that has been mined. float Mined = 0; }; //! A struct to represent each client struct ClientData { ClientData() = default; bool Setup = false; std::map<uint, float> LootBonus; std::map<uint, std::vector<uint>> LootAmmo; std::map<uint, std::vector<uint>> LootShip; int Debug = 0; int MineAsteroidEvents = 0; time_t MineAsteroidSampleStart = 0; }; //! A struct to hold the current status of a zone so their progress persists across restarts struct ZoneStats : Reflectable { std::string Zone; float CurrentReserve = 0.0f; float Mined = 0.0f; }; //! A struct to load in the stats config file across restarts struct MiningStats : Reflectable { std::string File() override { char path[MAX_PATH]; GetUserDataPath(path); return std::string(path) + "\\MiningStats.json"; } std::vector<ZoneStats> Stats; }; //! Config data for this plugin struct Config : Reflectable { //! The json file we load out of std::string File() override { return "config/mine_control.json"; } PlayerBonus playerBonusExample; ZoneBonus zoneBonusExample; std::vector<PlayerBonus> PlayerBonus = {playerBonusExample}; std::vector<ZoneBonus> ZoneBonus = {zoneBonusExample}; float GenericFactor = 1.0f; int PluginDebug = 0; }; //! Global data for this plugin struct Global final { ReturnCode returnCode = ReturnCode::Default; std::map<uint, ClientData> Clients; std::multimap<uint, PlayerBonus> PlayerBonus; std::map<uint, ZoneBonus> ZoneBonus; std::unique_ptr<Config> config = nullptr; }; } // namespace Plugins::MiningControl
3,289
C++
.h
98
30.683673
135
0.72331
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,433
SoundManager.h
TheStarport_FLHook/plugins/sound_manager/SoundManager.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::SoundManager { //! Config data for this plugin struct Config final : Reflectable { //! This json file should contain a "sounds" array containing a list of sounds for e.g. dx_s032a_01a01_hvis_xtr_1 std::string File() override { return "config/sound_manager.json"; } //! A vector of sounds in their Freelancer name format std::vector<std::string> sounds; //! A vector of sounds converted to their ids std::vector<uint> sound_ids; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returncode = ReturnCode::Default; }; } // namespace Plugins::SoundManager
715
C++
.h
22
30.181818
115
0.741279
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,434
CrashCatcher.h
TheStarport_FLHook/plugins/crash_catcher/CrashCatcher.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::CrashCatcher { //! Config data for this plugin struct Config final : Reflectable { std::string File() override { return "config/crashcatcher.json"; } //! Sets the maximum distance at which NPCs become visible as per scanner settings, a value of 0 will disable this override. float npcVisibilityDistance = 6500.f; //! Sets the distnace at which NPCs will despawn, a value of 0 will disable this override. float npcPersistDistance = 6500.f; //! Sets the distance at which NPCs will spawn, a value of 0 will disable this override. float npcSpawnDistance = 6500.f; }; //! Global data for this plugin struct Global final { ReturnCode returncode = ReturnCode::Default; bool bPatchInstalled = false; FARPROC fpOldTimingSeconds = 0; HMODULE hModServerAC; HMODULE hEngBase; HMODULE hModContentAC; std::map<uint, mstime> mapSaveTimes; }; #define LOG_EXCEPTION_INTERNAL() \ { \ AddLogInternal("ERROR Exception in %s", __FUNCTION__); \ AddExceptionInfoLog(); \ }; } // namespace Plugins::CrashCatcher IMPORT struct CObject* __cdecl GetRoot(struct CObject const*);
1,296
C++
.h
34
35.617647
126
0.683958
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,435
Betting.h
TheStarport_FLHook/plugins/betting/Betting.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Betting { //! A struct to hold a duel between two players. This holds the amount of cash they're betting on, and whether it's been accepted or not struct Duel { uint client; uint client2; uint amount; bool accepted; }; //! A struct to hold a contestant for a Free-For-All struct Contestant { bool accepted; bool loser; }; //! A struct to hold a Free-For-All competition. This holds the contestants, how much it costs to enter, and the total pot to be won by the eventual winner struct FreeForAll { std::map<uint, Contestant> contestants; uint entryAmount; uint pot; }; //! Global data for this plugin struct Global final { ReturnCode returnCode = ReturnCode::Default; std::list<Duel> duels; std::map<uint, FreeForAll> freeForAlls; // uint is iSystemId }; } // namespace Plugins::Betting
905
C++
.h
34
24.323529
156
0.743945
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,436
Rename.h
TheStarport_FLHook/plugins/rename/Rename.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Rename { //! Struct to hold a clan/group tag. This contains the passwords used to manage and rename a character to use this tag struct TagData : Reflectable { std::wstring tag; std::wstring masterPassword; std::wstring renamePassword; long long lastAccess; std::wstring description; }; //! Struct to hold a pending rename of a character struct Rename { std::wstring charName; std::wstring newCharName; std::string sourceFile; std::string destFile; }; //! Struct to hold a pending move of a character to a new account struct Move { std::wstring destinationCharName; std::wstring movingCharName; std::string sourceFile; std::string destFile; }; //! A struct to hold all the tags struct TagList : Reflectable { std::string File() override { char szDataPath[MAX_PATH]; GetUserDataPath(szDataPath); return std::string(szDataPath) + R"(\Accts\MultiPlayer\tags.json)"; } std::vector<TagData> tags; std::vector<TagData>::iterator FindTag(const std::wstring& tag); std::vector<TagData>::iterator FindTagPartial(const std::wstring& tag); }; //! Config data for this plugin struct Config : Reflectable { //! Json file the config is stored at std::string File() override { return "config/rename.json"; } //! Enable Rename bool enableRename = false; //! Enable Moving of Characters bool enableMoveChar = false; //! Cost of the rename in credits uint moveCost = 0; //! Cost of the rename in credits uint renameCost = 0; //! Rename is not allowed if attempted within the rename time limit (in seconds) int renameTimeLimit = 0; //! True if charname tags are supported bool enableTagProtection = false; //! True if ascii only tags are supported bool asciiCharNameOnly = false; //! The tag making cost uint makeTagCost = 2'500'000; }; //! Minimum character name length constant constexpr int MinCharacterNameLength = 3; //! Global data for this plugin struct Global { ReturnCode returnCode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; std::vector<Move> pendingMoves; std::vector<Rename> pendingRenames; TagList tagList; }; } // namespace Plugins::Rename
2,268
C++
.h
77
26.662338
119
0.740331
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,437
Autobuy.h
TheStarport_FLHook/plugins/autobuy/Autobuy.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Autobuy { //! A struct to represent each client class AutobuyInfo { public: AutobuyInfo() = default; bool missiles; bool mines; bool torps; bool cd; bool cm; bool bb; bool repairs; bool shells; }; struct AutobuyCartItem { uint archId = 0; uint count = 0; std::wstring description; }; //! Configurable fields for this plugin struct Config final : Reflectable { std::string File() override { return "config/autobuy.json"; } // Reflectable fields //! Nickname of the nanobot item being used when performing the automatic purchase std::string nanobot_nickname = "ge_s_repair_01"; //! Nickname of the shield battery item being used when performing the automatic purchase std::string shield_battery_nickname = "ge_s_battery_01"; // paths to inis which should be read for ammo limits std::vector<std::string> ammoIniPaths { R"(..\data\equipment\light_equip.ini)", R"(..\data\equipment\select_equip.ini)", R"(..\data\equipment\misc_equip.ini)", R"(..\data\equipment\engine_equip.ini)", R"(..\data\equipment\ST_equip.ini)", R"(..\data\equipment\weapon_equip.ini)", R"(..\data\equipment\prop_equip.ini)" }; }; struct Global final { std::unique_ptr<Config> config = nullptr; std::map<uint, AutobuyInfo> autobuyInfo; ReturnCode returnCode = ReturnCode::Default; std::unordered_map<uint, int> ammoLimits; }; } // namespace Plugins::Autobuy
1,503
C++
.h
54
24.944444
91
0.716273
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,438
Wardrobe.h
TheStarport_FLHook/plugins/wardrobe/Wardrobe.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Wardrobe { //! Struct that holds a pending wardrobe change struct Wardrobe final { std::wstring characterName; std::wstring directory; std::wstring characterFile; std::string costume; bool head; // 1 Head, 0 Body }; //! Config data for this plugin struct Config final : Reflectable { std::string File() override { return "config/wardrobe.json"; } //! A map containing the user friendly name of a head and it's actual name in the FL files std::map<std::string, std::string> heads = {{"ExampleHead", "ku_edo_head"}}; //! A map containing the user friendly name of a body and it's actual name in the FL files std::map<std::string, std::string> bodies = {{"ExampleBody", "ku_edo_body"}}; }; //! Global data for this plugin struct Global final { ReturnCode returncode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; //! A vector containing the restarts (wardrobe changes) that are currently pending std::vector<Wardrobe> pendingRestarts; }; } // namespace Plugins::Wardrobe
1,103
C++
.h
32
32.125
92
0.730337
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,439
Mark.h
TheStarport_FLHook/plugins/mark/Mark.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::Mark { typedef void (*_TimerFunc)(); //! Structs struct MARK_INFO { bool MarkEverything; bool IgnoreGroupMark; float AutoMarkRadius; std::vector<uint> MarkedObjects; std::vector<uint> DelayedSystemMarkedObjects; std::vector<uint> AutoMarkedObjects; std::vector<uint> DelayedAutoMarkedObjects; }; struct DELAY_MARK { uint iObj; mstime time; }; struct TIMER { _TimerFunc proc; mstime IntervalMS; mstime LastCall; }; // Reflectable config struct Config final : Reflectable { std::string File() override { return "config/mark.json"; } //! Radius within which all targets get marked, if autoMark is enabled. float AutoMarkRadiusInM = 2000; }; // Functions char MarkObject(ClientId client, uint iObject); void UnMarkAllObjects(ClientId client); char UnMarkObject(ClientId client, uint iObject); void UserCmd_AutoMark(ClientId& client, const std::wstring& wscParam); void UserCmd_MarkObj(ClientId& client, const std::wstring& wscParam); void UserCmd_MarkObjGroup(ClientId& client, const std::wstring& wscParam); void UserCmd_SetIgnoreGroupMark(ClientId& client, const std::wstring& wscParam); void UserCmd_UnMarkObj(ClientId& client, const std::wstring& wscParam); void UserCmd_UnMarkObjGroup(ClientId& client, const std::wstring& wscParam); void UserCmd_UnMarkAllObj(ClientId& client, const std::wstring& wscParam); void TimerMarkDelay(); void TimerSpaceObjMark(); //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; // Other fields ReturnCode returncode = ReturnCode::Default; MARK_INFO Mark[250]; std::list<DELAY_MARK> DelayedMarks; std::list<TIMER> Timers; }; extern std::unique_ptr<Global> global; //! Macros #define PRINT_ERROR() \ { \ for (uint i = 0; (i < sizeof(wscError) / sizeof(std::wstring)); i++) \ PrintUserCmdText(client, wscError[i]); \ return; \ } } // namespace Plugins::Mark
2,220
C++
.h
67
30.626866
81
0.679307
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,440
BountyHunt.h
TheStarport_FLHook/plugins/bountyhunt/BountyHunt.h
#pragma once // Included #include <FLHook.hpp> #include <plugin.h> namespace Plugins::BountyHunt { //! Structs struct BountyHunt { uint targetId; uint initiatorId; std::wstring target; std::wstring initiator; int cash; mstime end; }; //! Configurable fields for this plugin struct Config final : Reflectable { std::string File() override { return "config/bountyhunt.json"; } // Reflectable fields bool enableBountyHunt = true; int levelProtect = 0; //! Minimal time a hunt can be set to, in minutes. uint minimalHuntTime = 1; //! Maximum time a hunt can be set to, in minutes. uint maximumHuntTime = 240; //! Hunt time in minutes, if not explicitly specified. uint defaultHuntTime = 30; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; std::vector<BountyHunt> bountyHunt; }; } // namespace Plugins::BountyHunt
960
C++
.h
38
22.815789
66
0.736096
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,441
CashManager.h
TheStarport_FLHook/plugins/cash_manager/CashManager.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::CashManager { enum class BankCode { InternalServerError, NotEnoughMoney, AboveMaximumTransferThreshold, BelowMinimumTransferThreshold, CannotWithdrawNegativeNumber, BankCouldNotAffordTransfer, Success }; class CashManagerCommunicator final : public PluginCommunicator { public: inline static const char* pluginName = "Cash Manager"; explicit CashManagerCommunicator(const std::string& plugin); /** @ingroup CashManager * @brief Withdraw money from the specified accountId. */ BankCode PluginCall(ConsumeBankCash, const CAccount* account, uint cashAmount, const std::string& transactionSource); }; struct Config final : Reflectable { std::string File() override { return "config/cash_manager.json"; } //! The minimum transfer amount. uint minimumTransfer = 0; //! It is best to set this to a low enough value as to prevent players from //! accidentally corrupting their accounts via their value (approximately 2 billion credits). uint maximumTransfer = 0; //! If someone's cash goes above a threshold, deposit surplus money. bool depositSurplusOnDock = false; //! When safety above kicks in, how much cash should be taken to prevent the mechanism from activating immediately on next transaction. uint safetyMargin = 0; //! Message displayed when they hit the threshold. std::wstring preventTransactionMessage = L"Transaction barred. Your ship value is too high. Deposit some cash into your bank using the /bank command."; //! If the above is true, any amount above this value will cause the character to lock. uint cashThreshold = 1'800'000'000; //! Transfers are not allowed to/from chars in this system.. std::vector<std::string> blockedSystems; std::vector<uint> blockedSystemsHashed; //! Enable in dock cash cheat detection. bool cheatDetection = false; //! Prohibit transfers if the character has not been online for at least this time. uint minimumTime = 0; //! Remove transaction logs older than the amount of days indicated. uint eraseTransactionsAfterDaysPassed = 365; //! Cost in credits per transfer. uint transferFee = 0; }; struct Transaction { // When did this happen? uint64 timestamp; // Who accessed the bank? std::wstring accessor; // How much was taken/removed? int64 amount; // What bank did this involve? std::string bankId; }; struct Bank { std::string accountId; std::wstring bankPassword; std::wstring identifier; uint64 cash = 0; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; // Other fields ReturnCode returnCode = ReturnCode::Default; SQLite::Database sql = SqlHelpers::Create("banks.sqlite"); }; extern const std::unique_ptr<Global> global; namespace Sql { void CreateSqlTables(); std::optional<Bank> GetBankByIdentifier(std::wstring identifier); Bank GetOrCreateBank(const CAccount* account); bool WithdrawCash(const Bank& bank, int64 withdrawalAmount); bool DepositCash(const Bank& bank, uint depositAmount); bool TransferCash(const Bank& source, const Bank& target, int amount, int fee); std::vector<Transaction> ListTransactions(const Bank& bank, int amount = 20, int skip = 0); int CountTransactions(const Bank& bank); std::wstring SetNewPassword(const Bank& bank); void AddTransaction(const Bank& receiver, const std::string& sender, const int64& amount); int RemoveTransactionsOverSpecifiedDays(uint days); void SetOrClearIdentifier(const Bank& bank, const std::string& identifier); } // namespace Sql } // namespace Plugins::CashManager
3,678
C++
.h
96
35.447917
153
0.765928
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,442
SolarControl.h
TheStarport_FLHook/plugins/solar_control/SolarControl.h
#pragma once #include <FLHook.hpp> #include <plugin.h> #include <spdlog/logger.h> #include <spdlog/async.h> #include <spdlog/sinks/basic_file_sink.h> namespace Plugins::SolarControl { struct StartupSolar final : Reflectable { std::wstring name = L"largestation1"; std::string system = "li01"; std::vector<float> position = {-30367, 120, -25810}; std::vector<float> rotation = {0, 0, 0}; uint systemId {}; Vector pos {}; Matrix rot {}; }; struct SolarArch final : Reflectable { std::string solarArch = "largestation1"; std::string loadout; std::string iff; uint infocard = 197808; std::string base; std::string pilot; uint solarArchId {}; uint loadoutId {}; uint baseId {}; }; struct SolarArchFormationComponent final : Reflectable { std::string solarArchName; std::vector<float> relativePosition; std::vector<float> rotation; }; struct SolarArchFormation final : Reflectable { std::vector<SolarArchFormationComponent> components; }; struct Config final : Reflectable { std::vector<StartupSolar> startupSolars = {StartupSolar()}; std::map<std::wstring, SolarArch> solarArches = {{L"largestation1", SolarArch()}}; std::map<std::string, std::string> baseRedirects = {{"li01_01_base", "li01_02_base"}}; std::map<uint, uint> hashedBaseRedirects; //! The config file we load out of std::string File() override { return "config/solar.json"; } std::map<std::wstring, SolarArchFormation> solarArchFormations; }; //! Communicator class for this plugin. This is used by other plugins class SolarCommunicator : public PluginCommunicator { public: inline static const char* pluginName = "Solar Control"; explicit SolarCommunicator(const std::string& plug); uint PluginCall(CreateSolar, const std::wstring& name, Vector position, const Matrix& rotation, SystemId system, bool varyPosition, bool mission); std::vector<uint> PluginCall(CreateSolarFormation, const std::wstring& formation, const Vector& position, uint system); }; //! Global data for this plugin struct Global final { std::vector<uint> pendingDockingRequests; std::map<uint, pub::SpaceObj::SolarInfo> spawnedSolars; bool firstRun = true; ReturnCode returnCode = ReturnCode::Default; std::unique_ptr<Config> config = nullptr; std::shared_ptr<spdlog::logger> log = nullptr; SolarCommunicator* communicator = nullptr; std::map<uint, uint> pendingRedirects; }; } // namespace Plugins::SolarControl
2,457
C++
.h
72
31.555556
148
0.744949
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,443
PurchaseRestrictions.h
TheStarport_FLHook/plugins/purchase_restrictions/PurchaseRestrictions.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::PurchaseRestrictions { //! Config data for this plugin struct Config : Reflectable { std::string File() override { return "config/purchaseRestrictions.json"; } //! Check whether a player is trying to buy items without the correct id bool checkItemRestrictions = false; //! Block them for buying said item without the correct id bool enforceItemRestrictions = false; //! Messages when they are blocked from buying something std::wstring shipPurchaseDenied = L"You are not authorized to buy this ship."; std::wstring goodPurchaseDenied = L"You are not authorized to buy this item."; //! Items that we log transfers for std::vector<std::string> itemsOfInterest = {"li_gun01_mark01"}; //! Items that cannot be bought at all. std::vector<std::string> unbuyableItems = {"li_gun01_mark01"}; //! Items that can only be bought with a certain item equipped (item, [ equippedItemsThatAllowPurchase ]) std::map<std::string, std::vector<std::string>> goodItemRestrictions = {{"li_gun01_mark02", {"li_gun01_mark03"}}}; //! Ships that can only be bought with a certain item equipped (ship, [ equippedItemsThatAllowPurchase ]) std::map<std::string, std::vector<std::string>> shipItemRestrictions = {{"li_fighter", {"li_gun01_mark03"}}}; }; //! Global data for this plugin struct Global { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; std::map<ClientId, bool> clientSuppressBuy; std::vector<uint> unbuyableItemsHashed; std::map<uint, std::string> itemsOfInterestHashed; std::map<uint, std::vector<uint>> goodItemRestrictionsHashed; std::map<uint, std::vector<uint>> shipItemRestrictionsHashed; }; } // namespace Plugins::PurchaseRestrictions
1,804
C++
.h
37
46.027027
116
0.749573
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,444
Condata.h
TheStarport_FLHook/plugins/condata/Condata.h
#pragma once #include <FLHook.hpp> #include "plugin.h" constexpr int LossInterval = 4; namespace Plugins::ConData { struct ConnectionData { // connection data std::list<uint> lossList; uint lastLoss; uint averageLoss; std::list<uint> pingList; uint averagePing; //! Variation in minimal and maximum ping between client and server. uint pingFluctuation; uint lastPacketsSent; uint lastPacketsReceived; uint lastPacketsDropped; uint lags; std::list<uint> objUpdateIntervalsList; mstime lastObjUpdate; mstime lastObjTimestamp; // exception bool exception; std::string exceptionReason; // Client Id (for when receiving data) uint client; }; struct ConnectionDataException final { ClientId client; bool isException; std::string reason; }; // Inter plugin comms class ConDataCommunicator : public PluginCommunicator { public: inline static const char* pluginName = "Advanced Connection Data"; explicit ConDataCommunicator(const std::string& plug); void PluginCall(ReceiveException, const ConnectionDataException&); void PluginCall(ReceiveData, ConnectionData&); }; //! The struct that holds client info for this plugin struct MiscClientInfo final { bool lightsOn = false; bool shieldsDown = false; }; struct Config final : Reflectable { std::string File() override { return "config/condata.json"; } uint pingKick = 0; uint pingKickFrame = 120; uint fluctKick = 0; uint lossKick = 0; uint lossKickFrame = 120; uint lagKick = 0; uint lagDetectionFrame = 50; uint lagDetectionMin = 50; uint kickThreshold = 0; bool allowPing = true; }; //! Global data for this plugin struct Global final { std::unique_ptr<Config> config = nullptr; // Other fields ReturnCode returncode = ReturnCode::Default; ConnectionData connections[MaxClientId + 1]; ConDataCommunicator* communicator = nullptr; }; }; // namespace Plugins::ConData REFL_AUTO(type(Plugins::ConData::Config), field(pingKick), field(pingKickFrame), field(fluctKick), field(lossKick), field(lossKickFrame), field(lagKick), field(lagDetectionFrame), field(lagDetectionMin), field(kickThreshold), field(allowPing))
2,190
C++
.h
76
26.026316
153
0.765744
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,445
SystemSensor.h
TheStarport_FLHook/plugins/system_sensor/SystemSensor.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::SystemSensor { using NetworkId = uint; enum class Mode { Off = 0x00, JumpGate = 0x01, TradeLane = 0x02, Both = 0x1 | 0x2 }; struct Sensor final { Sensor() = delete; Sensor(const std::string& systemId, const std::string& equipId, const NetworkId networkId) : systemId(CreateID(systemId.c_str())), equipId(CreateID(equipId.c_str())), networkId(networkId) { } const SystemId systemId; const EquipId equipId; const NetworkId networkId; }; //! Map of equipment and systems that have sensor networks struct ActiveNetwork { std::list<CARGO_INFO> lastScanList; NetworkId availableNetworkId = 0; NetworkId lastScanNetworkId = 0; bool inJumpGate = false; Mode mode = Mode::Off; }; struct ReflectableSensor final : Reflectable { std::string systemId; std::string equipId; NetworkId networkId; }; struct Config final : Reflectable { std::string File() override { return "config/systemSensor.json"; } std::vector<ReflectableSensor> sensors; }; struct Global { ReturnCode returnCode = ReturnCode::Default; std::map<ClientId, ActiveNetwork> networks; std::multimap<EquipId, Sensor> sensorEquip; std::multimap<SystemId, Sensor> sensorSystem; }; } // namespace Plugins::SystemSensor
1,324
C++
.h
52
22.846154
102
0.746044
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,446
AdvancedStartupSolars.hpp
TheStarport_FLHook/plugins/advanced_startup_solars/AdvancedStartupSolars.hpp
#pragma once #include <FLHook.hpp> #include <plugin.h> #include <ranges> #include "../npc_control/NPCControl.h" #include "../solar_control/SolarControl.h" namespace Plugins::AdvancedStartupSolars { //! Additional data for formations to spawn from solarFamilies struct SolarFormation final : Reflectable { //! The formation name from solar.json to use std::wstring formation; //! NPCs from npc.json and the number to spawn std::map<std::wstring, int> npcs; //! The weight for this formation to spawn within the SolarFamily int spawnWeight = 0; }; //! Positional data for SolarFamily struct Position final : Reflectable { std::vector<float> location; std::string system; }; //! A SolarFamily struct that contains grouped formations and potential spawn locations struct SolarFamily final : Reflectable { //! The name of the SolarFamily. Principally used for debug messages std::string name; //! A vector containing possible solarFormations to spawn std::vector<SolarFormation> solarFormations; //! A vector containing possible positions to spawn solarFormations at std::vector<Position> spawnLocations; //! The overall spawn chance for the whole SolarFamily int spawnChance = 0; //! The number of formations to spawn within the family int spawnQuantity = 0; }; struct Config final : Reflectable { std::string File() override { return "config/advanced_startup_solars.json"; } //! A vector containing overal SolarFamily groups std::vector<SolarFamily> solarFamilies; }; //! Global data for this plugin struct Global { std::unique_ptr<Config> config = nullptr; ReturnCode returnCode = ReturnCode::Default; Plugins::Npc::NpcCommunicator* npcCommunicator = nullptr; Plugins::SolarControl::SolarCommunicator* solarCommunicator = nullptr; bool pluginActive = true; bool firstRun = true; }; } // namespace Plugins::AdvancedStartupSolars
1,908
C++
.h
55
32.2
88
0.767896
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,447
DeathPenalty.h
TheStarport_FLHook/plugins/death_penalty/DeathPenalty.h
#pragma once #include <FLHook.hpp> #include <plugin.h> namespace Plugins::DeathPenalty { struct CLIENT_DATA { bool bDisplayDPOnLaunch = true; uint DeathPenaltyCredits = 0; }; //! Configurable fields for this plugin struct Config final : Reflectable { std::string File() override { return "config/deathpenalty.json"; } // Reflectable fields //! Percentage of player's worth deducted upon death, where 1.0f stands for all of his worth. float DeathPenaltyFraction = 0.0f; //! Percentage of death penalty transferred to the killer, where 1.0f means the killer gets as much as the victim lost. float DeathPenaltyFractionKiller = 0.0f; //! List of system where death penalty/kill reward is disabled in. std::vector<std::string> ExcludedSystems = {}; //! Map of ship archetypes to a penalty multiplier. //! For example, {li_elite, 2} causes Defenders to lose twice the amount compared to unlisted ships on death. std::map<std::string, float> FractionOverridesByShip = {}; }; struct Global final { std::vector<uint> ExcludedSystemsIds; std::map<uint, float> FractionOverridesByShipIds; std::map<uint, CLIENT_DATA> MapClients; std::unique_ptr<Config> config = nullptr; ReturnCode returncode = ReturnCode::Default; }; } // namespace Plugins::DeathPenalty
1,299
C++
.h
34
35.617647
121
0.754972
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,448
plugin.h
TheStarport_FLHook/include/plugin.h
#pragma once #include <functional> #ifndef DLL #ifndef FLHOOK #define DLL __declspec(dllimport) #else #define DLL __declspec(dllexport) #endif #endif struct UserCommand { std::variant<std::wstring, std::vector<std::wstring>> command; std::wstring usage; std::variant<UserCmdProc, UserCmdProcWithParam> proc; std::wstring description; }; template<typename... Ts> std::string cat(Ts&&... args) { std::ostringstream oss; (oss << ... << std::forward<Ts>(args)); return oss.str(); } DLL std::vector<std::wstring> CmdArr(std::initializer_list<std::wstring> cmds); DLL UserCommand CreateUserCommand(const std::variant<std::wstring, std::vector<std::wstring>>& command, const std::wstring& usage, const std::variant<UserCmdProc, UserCmdProcWithParam>& proc, const std::wstring& description); struct Timer { std::function<void()> func; mstime intervalInSeconds; mstime lastTime = 0; }; constexpr PluginMajorVersion CurrentMajorVersion = PluginMajorVersion::VERSION_04; constexpr PluginMinorVersion CurrentMinorVersion = PluginMinorVersion::VERSION_00; const std::wstring VersionInformation = std::to_wstring(static_cast<int>(CurrentMajorVersion)) + L"." + std::to_wstring(static_cast<int>(CurrentMinorVersion)); class PluginHook { public: using FunctionType = void(); private: HookedCall targetFunction_; FunctionType* hookFunction_; HookStep step_; int priority_; public: template<typename Func> PluginHook(HookedCall targetFunction, Func* hookFunction, HookStep step = HookStep::Before, int priority = 0) : targetFunction_(targetFunction), hookFunction_(reinterpret_cast<FunctionType*>(hookFunction)), step_(step), priority_(priority) { switch (step) { case HookStep::Before: if (targetFunction == HookedCall::FLHook__LoadSettings) throw std::invalid_argument("Load settings can only be called HookStep::After."); break; case HookStep::After: break; default:; } } friend class PluginManager; }; #define PluginCall(name, ...) (* (name))(__VA_ARGS__) // Inherit from this to define a IPC (Inter-Plugin Communication) class. class DLL PluginCommunicator { public: using EventSubscription = void(*)(int id, void* dataPack); void Dispatch(int id, void* dataPack) const; void AddListener(std::string plugin, EventSubscription event); std::string plugin; explicit PluginCommunicator(std::string plugin) : plugin(std::move(plugin)) {} static void ExportPluginCommunicator(PluginCommunicator* communicator); static PluginCommunicator* ImportPluginCommunicator(std::string plugin, PluginCommunicator::EventSubscription subscription = nullptr); private: std::map<std::string, EventSubscription> listeners; }; struct PluginInfo { DLL void versionMajor(PluginMajorVersion version); DLL void versionMinor(PluginMinorVersion version); DLL void name(const char* name); DLL void shortName(const char* shortName); DLL void mayUnload(bool unload); DLL void autoResetCode(bool reset); DLL void returnCode(ReturnCode* returnCode); DLL void addHook(const PluginHook& hook); DLL void commands(const std::vector<UserCommand>*); DLL void timers(const std::vector<Timer>*); #ifdef FLHOOK template<typename... Args> void addHook(Args&&... args) { addHook(PluginHook(std::forward<Args>(args)...)); } PluginMajorVersion versionMajor_ = PluginMajorVersion::UNDEFINED; PluginMinorVersion versionMinor_ = PluginMinorVersion::UNDEFINED; std::string name_, shortName_; bool mayUnload_ = false, resetCode_ = true; ReturnCode* returnCode_ = nullptr; std::list<PluginHook> hooks_; std::vector<UserCommand>* commands_; std::vector<Timer>* timers_; #else template<typename... Args> void emplaceHook(Args&&... args) { PluginHook ph(std::forward<Args>(args)...); addHook(ph); } #endif };
3,776
C++
.h
112
31.5
159
0.767416
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,449
FLHook.hpp
TheStarport_FLHook/include/FLHook.hpp
#pragma once #define _CRT_SECURE_NO_WARNINGS #define _WINSOCKAPI_ #include <Windows.h> #include <string> #include <set> #include <list> #include <map> #include <filesystem> #include <variant> #include <numbers> #define _WINSOCK_DEPRECATED_NO_WARNINGS #include "WinSock2.h" #include "Tools/Hk.hpp" #include "Tools/Utils.hpp" // Magic Enum Extensions using namespace magic_enum::bitwise_operators; // NOLINT using namespace magic_enum::ostream_operators; // NOLINT DLL void ProcessEvent(std::wstring text, ...); // Tools class DLL Console { static void Log(const std::string& str, void* addr); // Might use more later? enum class ConsoleColor { BLUE = 0x0001, GREEN = 0x0002, CYAN = BLUE | GREEN, RED = 0x0004, PURPLE = RED | BLUE, YELLOW = RED | GREEN, WHITE = RED | BLUE | GREEN, STRONG_BLUE = 0x0008 | BLUE, STRONG_GREEN = 0x0008 | GREEN, STRONG_CYAN = 0x0008 | CYAN, STRONG_RED = 0x0008 | RED, STRONG_PURPLE = 0x0008 | PURPLE, STRONG_YELLOW = 0x0008 | YELLOW, STRONG_WHITE = 0x0008 | WHITE, }; public: // String static void ConPrint(const std::string& str); static void ConErr(const std::string& str); static void ConWarn(const std::string& str); static void ConInfo(const std::string& str); static void ConDebug(const std::string& str); }; class DLL DataManager : public Singleton<DataManager> { private: std::string dataPath; std::map<EquipId, Light> lights; public: DataManager() { INI_Reader ini; ini.open("freelancer.ini", false); ini.find_header("Freelancer"); while (ini.read_value()) { if (ini.is_value("data path")) { dataPath = ini.get_value_string(); break; } } ini.close(); }; DataManager(const DataManager&) = delete; #ifdef FLHOOK void LoadLights(); #endif // Lights const std::map<EquipId, Light>& GetLights() const; cpp::result<const Light&, Error> FindLightByHash(EquipId hash) const; }; DLL std::string IniGetS(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::string& scDefault); DLL int IniGetI(const std::string& scFile, const std::string& scApp, const std::string& scKey, int iDefault); DLL bool IniGetB(const std::string& scFile, const std::string& scApp, const std::string& scKey, bool bDefault); DLL void IniWrite(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::string& scValue); DLL void IniDelSection(const std::string& scFile, const std::string& scApp); DLL void IniDelete(const std::string& scFile, const std::string& scApp, const std::string& scKey); DLL void IniWriteW(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::wstring& wscValue); DLL std::wstring IniGetWS(const std::string& scFile, const std::string& scApp, const std::string& scKey, const std::wstring& wscDefault); DLL float IniGetF(const std::string& scFile, const std::string& scApp, const std::string& scKey, float fDefault); DLL BOOL FileExists(LPCTSTR szPath); DLL void ini_write_wstring(FILE* file, const std::string& parmname, const std::wstring& in); DLL void ini_get_wstring(INI_Reader& ini, std::wstring& wscValue); DLL std::wstring GetTimeString(bool bLocalTime); DLL std::string GetUserFilePath(const std::variant<uint, std::wstring>& player, const std::string& scExtension); DLL void AddLog(LogType LogType, LogLevel lvl, const std::string& str); // variables extern DLL HANDLE hProcFL; extern DLL HMODULE hModServer; extern DLL HMODULE hModCommon; extern DLL HMODULE hModRemoteClient; extern DLL HMODULE hModDPNet; extern DLL HMODULE hModDaLib; extern DLL HMODULE hModContent; extern DLL FARPROC fpOldUpdate; // A base class/struct used for denoting that a class can be scanned. // Reflectable values are int, uint, bool, float, string, Reflectable, and std::vectors of the previous types. // Reflectables are interepreted as headers of the provided name. // Circular references are not handled and will crash. // Marking a field as reflectable without properly initalizing it will crash upon attempted deserialization. // Ensure that the default CTOR initalizes all fields. struct DLL Reflectable { virtual ~Reflectable() = default; virtual std::string File() { return {}; } }; #include <Tools/Serialization/Serializer.hpp> struct DLL FLHookConfig final : Reflectable, Singleton<FLHookConfig> { std::string File() override; struct General final : Reflectable { //! Time of invulnerability upon undock in miliseconds. //! Protected player can also not inflict any damage. uint antiDockKill = 4000; //! Number of miliseconds the player character remains in space after disconnecting. uint antiF1 = 0; //! Disable the cruise disrupting effects. bool changeCruiseDisruptorBehaviour = false; //! If true, enables FLHook debug mode. bool debugMode = false; //! If true, it encodes player characters to bini (binary ini) bool disableCharfileEncryption = false; //! If a player disconnects in space, their ship will remain in game world for the time specified, in miliseconds. uint disconnectDelay = 0; //! If above zero, disables NPC spawns if "server load in ms" goes above the specified value. uint disableNPCSpawns = 0; //! If true, it uses local time when rendering current time instead of server time, //! in for example, "/time" function. bool localTime = false; //! Maximum amount of players in a group. uint maxGroupSize = 8; //! NOT IMPLEMENTED YET: if true, keeps the player in the group if they switch characters within one account. bool persistGroup = false; //! Number of slots reserved to specified accounts. uint reservedSlots = 0; //! Global damage multiplier to missile and torpedo type weapons. float torpMissileBaseDamageMultiplier = 1.0f; //! If true, it logs performance of functions if they take too long to execute. bool logPerformanceTimers = false; bool tempBansEnabled = true; //! A vector of forbidden words/phrases, which will not be processed and sent to other players std::vector<std::wstring> chatSuppressList; //! Vector of systems where players can't deal damage to one another. std::vector<std::string> noPVPSystems; std::vector<uint> noPVPSystemsHashed; //! Amount of time spent idly on a base resulting in a server kick, in seconds. uint antiBaseIdle = 600; //! Amount of time spent idly on character select screen resulting in a server kick, in seconds. uint antiCharMenuIdle = 600; //! Bases that beam commands will not work for std::vector<std::string> noBeamBases = {"br_m_beryllium_miner", "[br_m_hydrocarbon_miner]", "[br_m_niobium_miner]", "[co_khc_copper_miner]", "[co_khc_cobalt_miner]", "[co_kt_hydrocarbon_miner]", "[co_shi_h-fuel_miner]", "[co_shi_water_miner]", "[co_ti_water_miner]", "[gd_gm_h-fuel_miner]", "[gd_im_oxygen_miner]", "[gd_im_copper_miner]", "[gd_im_silver_miner]", "[gd_im_water_miner]", "[rh_m_diamond_miner]", "intro3_base", "intro2_base", "intro1_base", "st03b_01_base", "st02_01_base", "st01_02_base", "iw02_03_base", "rh02_07_base", "li04_06_base", "li01_15_base"}; std::vector<uint> noBeamBasesHashed = {}; }; struct Plugins final : Reflectable { //! If true, loads all plugins on FLHook startup. bool loadAllPlugins = true; //! Contains a list of plugins to be enabled on startup if loadAllPlugins is false, //! or plugins to be excluded from being loaded on startup if loadAllPlugins is true. std::vector<std::string> plugins = {}; }; struct MsgStyle final : Reflectable { std::wstring msgEchoStyle = L"0x00AA0090"; std::wstring deathMsgStyle = L"0x19198C01"; std::wstring deathMsgStyleSys = L"0x1919BD01"; //! Time in ms between kick message rendering and actual server kick occuring. uint kickMsgPeriod = 5000; //! Kick message content. std::wstring kickMsg = LR"(<TRA data=" 0x0000FF10 " mask=" - 1 "/><TEXT>You will be kicked. Reason: %reason</TEXT>)"; std::wstring userCmdStyle = L"0x00FF0090"; std::wstring adminCmdStyle = L"0x00FF0090"; //! Death message for admin kills. std::wstring deathMsgTextAdminKill = L"Death: %victim was killed by an admin"; //! Default player to player kill message. std::wstring deathMsgTextPlayerKill = L"Death: %victim was killed by %killer (%type)"; //! Death message for weapon self-kills. std::wstring deathMsgTextSelfKill = L"Death: %victim killed himself (%type)"; //! Death message for player deaths to NPCs. std::wstring deathMsgTextNPC = L"Death: %victim was killed by an NPC"; //! Death message for environmental deaths. std::wstring deathMsgTextSuicide = L"Death: %victim committed suicide"; }; struct Message final : Reflectable { MsgStyle msgStyle; //! If true, messages will sent only to local ships bool defaultLocalChat = false; //! If true, sends a copy of submitted commands to the player's chatlog. bool echoCommands = true; //! If true, invalid commands are not echo'ed bool suppressInvalidCommands = true; //! If true, player's death renders the default message. bool dieMsg = true; //! Broadcasts a message that the player is attempting docking to all players in range //! currently hardcoded to 15K bool dockingMessages = true; }; struct Socket final : Reflectable { bool activated = false; int port = 1919; int wPort = 1920; int ePort = 1921; int eWPort = 1922; std::string encryptionKey = "SomeRandomKey000"; void* bfCTX = nullptr; std::map<std::wstring, std::string> passRightsMap = {{L"SuperSecret", "superadmin"}}; }; struct UserCommands final : Reflectable { //! Can users use SetDieMsgSize command bool userCmdSetDieMsgSize = true; //! Can users use SetDieMsg command bool userCmdSetDieMsg = true; //! Can users use SetChatFont command bool userCmdSetChatFont = true; //! Can users use Ignore command bool userCmdIgnore = true; //! Can users use Help command bool userCmdHelp = true; //! Maximum size of users added via /ignore command uint userCmdMaxIgnoreList = 0; //! If true, the default player chat will be local, not system. bool defaultLocalChat = false; }; struct Bans final : Reflectable { //! If true, apply a vanilla FLServer ban in case of a wildcard/IP match on top of kicking them. bool banAccountOnMatch = false; //! Instantly kicks any player with a matching IP or matching IP range. std::vector<std::wstring> banWildcardsAndIPs; }; struct Callsign final : Reflectable { //! The mapping of numbers to formations. 1, min = Alpha. 29, max = Yanagi std::vector<int> allowedFormations = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29}; //! If true, formations and numbers will not be assigned to ships. All ships will be alpha 1-1. bool disableRandomisedFormations = false; //! If true, NPCs will refer to all players as freelancer bool disableUsingAffiliationForCallsign = false; }; General general; Plugins plugins; Socket socket; UserCommands userCommands; Bans bans; Message messages; Callsign callsign; }; // Use the class to create and send packets of inconstant size. #pragma pack(push, 1) class FLPACKET { private: uint Size; byte kind; byte type; public: // This is content of your packet. You may want to reinterpretate it as pointer to packet data struct for convenience. byte content[1]; enum CommonPacket { FLPACKET_COMMON_00, FLPACKET_COMMON_UPDATEOBJECT, FLPACKET_COMMON_FIREWEAPON, FLPACKET_COMMON_03, FLPACKET_COMMON_SETTARGET, FLPACKET_COMMON_CHATMSG, FLPACKET_COMMON_06, FLPACKET_COMMON_07, FLPACKET_COMMON_ACTIVATEEQUIP, FLPACKET_COMMON_09, FLPACKET_COMMON_0A, FLPACKET_COMMON_0B, FLPACKET_COMMON_0C, FLPACKET_COMMON_0D, FLPACKET_COMMON_ACTIVATECRUISE, FLPACKET_COMMON_GOTRADELANE, FLPACKET_COMMON_STOPTRADELANE, FLPACKET_COMMON_SET_WEAPON_GROUP, FLPACKET_COMMON_PLAYER_TRADE, FLPACKET_COMMON_SET_VISITED_STATE, FLPACKET_COMMON_JETTISONCARGO, FLPACKET_COMMON_ACTIVATETHRUSTERS, FLPACKET_COMMON_REQUEST_BEST_PATH, FLPACKET_COMMON_REQUEST_GROUP_POSITIONS, FLPACKET_COMMON_REQUEST_PLAYER_STATS, FLPACKET_COMMON_SET_MISSION_LOG, FLPACKET_COMMON_REQUEST_RANK_LEVEL, FLPACKET_COMMON_POP_UP_DIALOG, FLPACKET_COMMON_SET_INTERFACE_STATE, FLPACKET_COMMON_TRACTOROBJECTS }; enum ServerPacket { FLPACKET_SERVER_00, FLPACKET_SERVER_CONNECTRESPONSE, FLPACKET_SERVER_LOGINRESPONSE, FLPACKET_SERVER_CHARACTERINFO, FLPACKET_SERVER_CREATESHIP, FLPACKET_SERVER_DAMAGEOBJECT, FLPACKET_SERVER_DESTROYOBJECT, FLPACKET_SERVER_LAUNCH, FLPACKET_SERVER_CHARSELECTVERIFIED, FLPACKET_SERVER_09, FLPACKET_SERVER_ACTIVATEOBJECT, FLPACKET_SERVER_LAND, FLPACKET_SERVER_0C, FLPACKET_SERVER_SETSTARTROOM, FLPACKET_SERVER_GFCOMPLETENEWSBROADCASTLIST, FLPACKET_SERVER_GFCOMPLETECHARLIST, FLPACKET_SERVER_GFCOMPLETEMISSIONCOMPUTERLIST, FLPACKET_SERVER_GFCOMPLETESCRIPTBEHAVIORLIST, FLPACKET_SERVER_12, FLPACKET_SERVER_GFCOMPLETEAMBIENTSCRIPTLIST, FLPACKET_SERVER_GFDESTROYNEWSBROADCAST, FLPACKET_SERVER_GFDESTROYCHARACTER, FLPACKET_SERVER_GFDESTROYMISSIONCOMPUTER, FLPACKET_SERVER_GFDESTROYSCRIPTBEHAVIOR, FLPACKET_SERVER_18, FLPACKET_SERVER_GFDESTROYAMBIENTSCRIPT, FLPACKET_SERVER_GFSCRIPTBEHAVIOR, FLPACKET_SERVER_1B, FLPACKET_SERVER_1C, FLPACKET_SERVER_GFUPDATEMISSIONCOMPUTER, FLPACKET_SERVER_GFUPDATENEWSBROADCAST, FLPACKET_SERVER_GFUPDATEAMBIENTSCRIPT, FLPACKET_SERVER_GFMISSIONVENDORACCEPTANCE, FLPACKET_SERVER_SYSTEM_SWITCH_OUT, FLPACKET_SERVER_SYSTEM_SWITCH_IN, FLPACKET_SERVER_SETSHIPARCH, FLPACKET_SERVER_SETEQUIPMENT, FLPACKET_SERVER_SETCARGO, FLPACKET_SERVER_GFUPDATECHAR, FLPACKET_SERVER_REQUESTCREATESHIPRESP, FLPACKET_SERVER_CREATELOOT, FLPACKET_SERVER_SETREPUTATION, FLPACKET_SERVER_ADJUSTATTITUDE, FLPACKET_SERVER_SETGROUPFEELINGS, FLPACKET_SERVER_CREATEMINE, FLPACKET_SERVER_CREATECOUNTER, FLPACKET_SERVER_SETADDITEM, FLPACKET_SERVER_SETREMOVEITEM, FLPACKET_SERVER_SETCASH, FLPACKET_SERVER_EXPLODEASTEROIdMINE, FLPACKET_SERVER_REQUESTSPACESCRIPT, FLPACKET_SERVER_SETMISSIONOBJECTIVESTATE, FLPACKET_SERVER_REPLACEMISSIONOBJECTIVE, FLPACKET_SERVER_SETMISSIONOBJECTIVES, FLPACKET_SERVER_36, FLPACKET_SERVER_CREATEGUIDED, FLPACKET_SERVER_ITEMTRACTORED, FLPACKET_SERVER_SCANNOTIFY, FLPACKET_SERVER_3A, FLPACKET_SERVER_3B, FLPACKET_SERVER_REPAIROBJECT, FLPACKET_SERVER_REMOTEOBJECTCARGOUPDATE, FLPACKET_SERVER_SETNUMKILLS, FLPACKET_SERVER_SETMISSIONSUCCESSES, FLPACKET_SERVER_SETMISSIONFAILURES, FLPACKET_SERVER_BURNFUSE, FLPACKET_SERVER_CREATESOLAR, FLPACKET_SERVER_SET_STORY_CUE, FLPACKET_SERVER_REQUEST_RETURNED, FLPACKET_SERVER_SET_MISSION_MESSAGE, FLPACKET_SERVER_MARKOBJ, FLPACKET_SERVER_CFGINTERFACENOTIFICATION, FLPACKET_SERVER_SETCOLLISIONGROUPS, FLPACKET_SERVER_SETHULLSTATUS, FLPACKET_SERVER_SETGUIDEDTARGET, FLPACKET_SERVER_SET_CAMERA, FLPACKET_SERVER_REVERT_CAMERA, FLPACKET_SERVER_LOADHINT, FLPACKET_SERVER_SETDIRECTIVE, FLPACKET_SERVER_SENDCOMM, FLPACKET_SERVER_50, FLPACKET_SERVER_USE_ITEM, FLPACKET_SERVER_PLAYERLIST, FLPACKET_SERVER_FORMATION_UPDATE, FLPACKET_SERVER_MISCOBJUPDATE, FLPACKET_SERVER_OBJECTCARGOUPDATE, FLPACKET_SERVER_SENDNNMESSAGE, FLPACKET_SERVER_SET_MUSIC, FLPACKET_SERVER_CANCEL_MUSIC, FLPACKET_SERVER_PLAY_SOUND_EFFECT, FLPACKET_SERVER_GFMISSIONVENDORWHYEMPTY, FLPACKET_SERVER_MISSIONSAVEA }; enum ClientPacket { FLPACKET_CLIENT_00, FLPACKET_CLIENT_LOGIN, FLPACKET_CLIENT_02, FLPACKET_CLIENT_MUNCOLLISION, FLPACKET_CLIENT_REQUESTLAUNCH, FLPACKET_CLIENT_REQUESTCHARINFO, FLPACKET_CLIENT_SELECTCHARACTER, FLPACKET_CLIENT_ENTERBASE, FLPACKET_CLIENT_REQUESTBASEINFO, FLPACKET_CLIENT_REQUESTLOCATIONINFO, FLPACKET_CLIENT_GFREQUESTSHIPINFO, FLPACKET_CLIENT_SYSTEM_SWITCH_OUT_COMPLETE, FLPACKET_CLIENT_OBJCOLLISION, FLPACKET_CLIENT_EXITBASE, FLPACKET_CLIENT_ENTERLOCATION, FLPACKET_CLIENT_EXITLOCATION, FLPACKET_CLIENT_REQUESTCREATESHIP, FLPACKET_CLIENT_GFGOODSELL, FLPACKET_CLIENT_GFGOODBUY, FLPACKET_CLIENT_GFSELECTOBJECT, FLPACKET_CLIENT_MISSIONRESPONSE, FLPACKET_CLIENT_REQSHIPARCH, FLPACKET_CLIENT_REQEQUIPMENT, FLPACKET_CLIENT_REQCARGO, FLPACKET_CLIENT_REQADDITEM, FLPACKET_CLIENT_REQREMOVEITEM, FLPACKET_CLIENT_REQMODIFYITEM, FLPACKET_CLIENT_REQSETCASH, FLPACKET_CLIENT_REQCHANGECASH, FLPACKET_CLIENT_1D, FLPACKET_CLIENT_SAVEGAME, FLPACKET_CLIENT_1F, FLPACKET_CLIENT_MINEASTEROId, FLPACKET_CLIENT_21, FLPACKET_CLIENT_DBGCREATESHIP, FLPACKET_CLIENT_DBGLOADSYSTEM, FLPACKET_CLIENT_DOCK, FLPACKET_CLIENT_DBGDESTROYOBJECT, FLPACKET_CLIENT_26, FLPACKET_CLIENT_TRADERESPONSE, FLPACKET_CLIENT_28, FLPACKET_CLIENT_29, FLPACKET_CLIENT_2A, FLPACKET_CLIENT_CARGOSCAN, FLPACKET_CLIENT_2C, FLPACKET_CLIENT_DBGCONSOLE, FLPACKET_CLIENT_DBGFREESYSTEM, FLPACKET_CLIENT_SETMANEUVER, FLPACKET_CLIENT_DBGRELOCATE_SHIP, FLPACKET_CLIENT_REQUEST_EVENT, FLPACKET_CLIENT_REQUEST_CANCEL, FLPACKET_CLIENT_33, FLPACKET_CLIENT_34, FLPACKET_CLIENT_INTERFACEITEMUSED, FLPACKET_CLIENT_REQCOLLISIONGROUPS, FLPACKET_CLIENT_COMMCOMPLETE, FLPACKET_CLIENT_REQUESTNEWCHARINFO, FLPACKET_CLIENT_CREATENEWCHAR, FLPACKET_CLIENT_DESTROYCHAR, FLPACKET_CLIENT_REQHULLSTATUS, FLPACKET_CLIENT_GFGOODVAPORIZED, FLPACKET_CLIENT_BADLANDSOBJCOLLISION, FLPACKET_CLIENT_LAUNCHCOMPLETE, FLPACKET_CLIENT_HAIL, FLPACKET_CLIENT_REQUEST_USE_ITEM, FLPACKET_CLIENT_ABORT_MISSION, FLPACKET_CLIENT_SKIP_AUTOSAVE, FLPACKET_CLIENT_JUMPINCOMPLETE, FLPACKET_CLIENT_REQINVINCIBILITY, FLPACKET_CLIENT_MISSIONSAVEB, FLPACKET_CLIENT_REQDIFFICULTYSCALE, FLPACKET_CLIENT_RTCDONE }; // Common packets are being sent from server to client and from client to server. DLL static FLPACKET* Create(uint size, CommonPacket kind); // Server packets are being sent only from server to client. DLL static FLPACKET* Create(uint size, ServerPacket kind); // Client packets are being sent only from client to server. Can't imagine why you ever need to create such a packet at side of server. DLL static FLPACKET* Create(uint size, ClientPacket kind); // Returns true if sent succesfully, false if not. Frees memory allocated for packet. DLL bool SendTo(ClientId client); }; #pragma pack(pop) class CCmds { protected: ~CCmds() = default; private: bool bId; bool bShortCut; bool bSelf; bool bTarget; public: DWORD rights; #ifdef FLHOOK // commands void CmdGetCash(const std::variant<uint, std::wstring>& player); void CmdSetCash(const std::variant<uint, std::wstring>& player, uint iAmount); void CmdAddCash(const std::variant<uint, std::wstring>& player, uint iAmount); void CmdKick(const std::variant<uint, std::wstring>& player, const std::wstring& wscReason); void CmdBan(const std::variant<uint, std::wstring>& player); void CmdTempBan(const std::variant<uint, std::wstring>& player, uint duration); void CmdUnban(const std::variant<uint, std::wstring>& player); void CmdBeam(const std::variant<uint, std::wstring>& player, const std::wstring& wscBasename); void CmdChase(std::wstring wscAdminName, const std::variant<uint, std::wstring>& player); void CmdPull(std::wstring wscAdminName, const std::variant<uint, std::wstring>& player); void CmdMove(std::wstring wscAdminName, float x, float y, float z); void CmdKill(const std::variant<uint, std::wstring>& player); void CmdResetRep(const std::variant<uint, std::wstring>& player); void CmdSetRep(const std::variant<uint, std::wstring>& player, const std::wstring& wscRepGroup, float fValue); void CmdGetRep(const std::variant<uint, std::wstring>& player, const std::wstring& wscRepGroup); void CmdMsg(const std::variant<uint, std::wstring>& player, const std::wstring& text); void CmdMsgS(const std::wstring& wscSystemname, const std::wstring& text); void CmdMsgU(const std::wstring& text); void CmdFMsg(const std::variant<uint, std::wstring>& player, const std::wstring& wscXML); void CmdFMsgS(const std::wstring& wscSystemname, const std::wstring& wscXML); void CmdFMsgU(const std::wstring& wscXML); void CmdEnumCargo(const std::variant<uint, std::wstring>& player); void CmdRemoveCargo(const std::variant<uint, std::wstring>& player, ushort cargoId, uint count); void CmdAddCargo(const std::variant<uint, std::wstring>& player, const std::wstring& wscGood, uint iCount, bool iMission); void CmdRename(const std::variant<uint, std::wstring>& player, const std::wstring& wscNewCharname); void CmdDeleteChar(const std::variant<uint, std::wstring>& player); void CmdReadCharFile(const std::variant<uint, std::wstring>& player); void CmdWriteCharFile(const std::variant<uint, std::wstring>& player, const std::wstring& wscData); void CmdGetClientID(const std::wstring& player); void PrintPlayerInfo(PlayerInfo& pi); void CmdGetPlayerInfo(const std::variant<uint, std::wstring>& player); void CmdGetPlayers(); void XPrintPlayerInfo(const PlayerInfo& pi); void CmdXGetPlayerInfo(const std::variant<uint, std::wstring>& player); void CmdXGetPlayers(); void CmdGetPlayerIds(); void CmdHelp(); void CmdGetAccountDirName(const std::variant<uint, std::wstring>& player); void CmdGetCharFileName(const std::variant<uint, std::wstring>& player); void CmdIsOnServer(const std::wstring& player); void CmdMoneyFixList(); void CmdServerInfo(); void CmdGetGroupMembers(const std::variant<uint, std::wstring>& player); void CmdSaveChar(const std::variant<uint, std::wstring>& player); void CmdGetReservedSlot(const std::variant<uint, std::wstring>& player); void CmdSetReservedSlot(const std::variant<uint, std::wstring>& player, int iReservedSlot); void CmdSetAdmin(const std::variant<uint, std::wstring>& player, const std::wstring& wscRights); void CmdGetAdmin(const std::variant<uint, std::wstring>& player); void CmdDelAdmin(const std::variant<uint, std::wstring>& player); void CmdLoadPlugins(); void CmdLoadPlugin(const std::wstring& wscPlugin); void CmdListPlugins(); void CmdUnloadPlugin(const std::wstring& wscPlugin); void CmdReloadPlugin(const std::wstring& wscPlugin); void CmdShutdown(); void ExecuteCommandString(const std::wstring& wscCmd); void SetRightsByString(const std::string& scRightStr); std::wstring wscCurCmdString; #endif public: virtual void DoPrint(const std::string& text) = 0; DLL void PrintError(Error err); DLL std::wstring ArgCharname(uint iArg); DLL int ArgInt(uint iArg); DLL uint ArgUInt(uint iArg); DLL float ArgFloat(uint iArg); DLL std::wstring ArgStr(uint iArg); DLL std::wstring ArgStrToEnd(uint iArg); DLL void Print(const std::string& text); DLL virtual std::wstring GetAdminName() { return L""; }; DLL virtual bool IsPlayer() { return false; } }; class CInGame final : public CCmds { public: uint client; std::wstring wscAdminName; DLL void DoPrint(const std::string& text) override; DLL void ReadRights(const std::string& scIniFile); DLL std::wstring GetAdminName() override; DLL bool IsPlayer() override { return true; } }; class CSocket final : public CCmds { public: SOCKET s; BLOWFISH_CTX* bfc; bool bAuthed; bool bEventMode; bool bUnicode; bool bEncrypted; std::string sIP; ushort iPort; CSocket() { bAuthed = false; bEventMode = false; bUnicode = false; } DLL void DoPrint(const std::string& text) override; DLL std::wstring GetAdminName() override; }; // FuncLog DLL bool InitLogs(); DLL void HandleCheater(ClientId client, bool bBan, const std::string& reason); DLL bool AddCheaterLog(const std::variant<uint, std::wstring>& player, const std::string& reason); DLL bool AddKickLog(ClientId client, const std::string& reason); DLL bool AddConnectLog(ClientId client, const std::string& reason); DLL void UserCmd_SetDieMsg(ClientId& client, const std::wstring& wscParam); DLL void UserCmd_SetChatFont(ClientId& client, const std::wstring& wscParam); DLL void PrintUserCmdText(ClientId client, const std::wstring& text); DLL void PrintLocalUserCmdText(ClientId client, const std::wstring& wscMsg, float fDistance); DLL extern bool g_NonGunHitsBase; DLL extern float g_LastHitPts; // namespaces namespace IServerImplHook { struct SubmitData { bool inSubmitChat; std::wstring characterName; }; const DLL extern std::unique_ptr<SubmitData> chatData; } // namespace IServerImplHook struct DLL CoreGlobals : Singleton<CoreGlobals> { uint damageToClientId; uint damageToSpaceId; bool messagePrivate; bool messageSystem; bool messageUniverse; std::string accPath; uint serverLoadInMs; uint playerCount; bool disableNpcs; std::list<BaseInfo> allBases; bool flhookReady; }; extern DLL CDPServer* cdpSrv; extern DLL _GetShipInspect GetShipInspect; extern DLL char* g_FLServerDataPtr; extern DLL CDPClientProxy** clientProxyArray; extern DLL void* pClient; extern DLL _RCSendChatMsg RCSendChatMsg; extern DLL _CRCAntiCheat CRCAntiCheat; extern DLL IClientImpl* FakeClient; extern DLL IClientImpl* HookClient; extern DLL char* OldClient; extern DLL std::array<CLIENT_INFO, MaxClientId + 1> ClientInfo; DLL std::string FlcDecode(std::string& input); DLL std::string FlcEncode(std::string& input); DLL bool EncodeDecode(const char* input, const char* output, bool encode); DLL bool FlcDecodeFile(const char* input, const char* outputFile); DLL bool FlcEncodeFile(const char* input, const char* outputFile); DLL void Blowfish_Init(BLOWFISH_CTX* ctx, unsigned char* key, int keyLen); DLL char Blowfish_Encrypt(BLOWFISH_CTX* ctx, void* ptr, unsigned long dataLen); DLL char Blowfish_Decrypt(BLOWFISH_CTX* ctx, void* ptr, unsigned long dataLen);
25,719
C++
.h
676
35.39497
148
0.770837
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,537,450
SQLiteCpp.h
TheStarport_FLHook/include/SQLiteCpp/SQLiteCpp.h
/** * @file SQLiteCpp.h * @ingroup SQLiteCpp * @brief SQLiteC++ is a smart and simple C++ SQLite3 wrapper. This file is only "easy include" for other files. * * Include this main header file in your project to gain access to all functionality provided by the wrapper. * * Copyright (c) 2012-2022 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ /** * @defgroup SQLiteCpp SQLiteC++ * @brief SQLiteC++ is a smart and simple C++ SQLite3 wrapper. This file is only "easy include" for other files. */ #pragma once // Include useful headers of SQLiteC++ #include <SQLiteCpp/Assertion.h> #include <SQLiteCpp/Exception.h> #include <SQLiteCpp/Database.h> #include <SQLiteCpp/Statement.h> #include <SQLiteCpp/Column.h> #include <SQLiteCpp/Transaction.h> /** * @brief Version numbers for SQLiteC++ are provided in the same way as sqlite3.h * * The [SQLITECPP_VERSION] C preprocessor macro in the SQLiteC++.h header * evaluates to a string literal that is the SQLite version in the * format "X.Y.Z" where X is the major version number * and Y is the minor version number and Z is the release number. * * The [SQLITECPP_VERSION_NUMBER] C preprocessor macro resolves to an integer * with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same * numbers used in [SQLITECPP_VERSION]. * * WARNING: shall always be updated in sync with PROJECT_VERSION in CMakeLists.txt */ #define SQLITECPP_VERSION "3.02.01" // 3.2.1 #define SQLITECPP_VERSION_NUMBER 3002001 // 3.2.1
1,651
C++
.h
40
39.5
115
0.737399
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,537,455
Utils.h
TheStarport_FLHook/include/SQLiteCpp/Utils.h
/** * @file Utils.h * @ingroup SQLiteCpp * @brief Definition of the SQLITECPP_PURE_FUNC macro. * * Copyright (c) 2012-2022 Sebastien Rombauts (sebastien.rombauts@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #pragma once // macro taken from https://github.com/nemequ/hedley/blob/master/hedley.h that was in public domain at this time #if defined(__GNUC__) || defined(__GNUG__) || defined(__clang__) ||\ (defined(__INTEL_COMPILER) && __INTEL_COMPILER > 1600) ||\ (defined(__ARMCC_VERSION) && __ARMCC_VERSION > 4010000) ||\ (\ defined(__TI_COMPILER_VERSION__) && (\ __TI_COMPILER_VERSION__ > 8003000 ||\ (__TI_COMPILER_VERSION__ > 7003000 && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))\ )\ ) #if defined(__has_attribute) #if !defined(SQLITECPP_PURE_FUNC) && __has_attribute(pure) #define SQLITECPP_PURE_FUNC __attribute__((pure)) #endif #endif #endif #if !defined(SQLITECPP_PURE_FUNC) #define SQLITECPP_PURE_FUNC #endif
1,048
C++
.h
30
32.8
112
0.690265
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
1,537,462
Sql.hpp
TheStarport_FLHook/include/ext/Sql.hpp
#pragma once #pragma warning(push) #pragma warning(disable : 4067) #include <SQLiteCpp/SQLiteCpp.h> #pragma warning(pop) #pragma comment(lib, "sqlite3.lib") #pragma comment(lib, "SQLiteCpp.lib") namespace SqlHelpers { inline SQLite::Database Create(const std::string_view& path) { char dataPath[MAX_PATH]; GetUserDataPath(dataPath); const auto dir = std::format("{}\\{}", dataPath, path); return {dir, SQLite::OPEN_CREATE | SQLite::OPEN_READWRITE}; }; }; // namespace SqlHelpers
494
C++
.h
17
27.176471
61
0.744186
TheStarport/FLHook
30
15
67
GPL-3.0
9/20/2024, 10:44:43 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false