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,541,914
settings.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/settings.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "settings.h" #include "log.h" #include "scripts.h" #include "utils.h" #include <algorithm> #include <fmt/format.h> #include <limits> #include <string> namespace hooks { template <typename T> static T readSetting(const sol::table& table, const char* name, T def, T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max()) { return std::clamp<T>(table.get_or(name, def), min, max); } static std::string readSetting(const sol::table& table, const char* name, const std::string& def) { return table.get_or(name, def); } static void readAiAttackPowerSettings(const sol::table& table, Settings::AiAttackPowerBonus& value) { const auto& def = defaultSettings().aiAttackPowerBonus; auto bonuses = table.get<sol::optional<sol::table>>("aiAccuracyBonus"); if (!bonuses.has_value()) { value = def; return; } value.absolute = readSetting(bonuses.value(), "absolute", def.absolute); value.easy = readSetting(bonuses.value(), "easy", def.easy); value.average = readSetting(bonuses.value(), "average", def.average); value.hard = readSetting(bonuses.value(), "hard", def.hard); value.veryHard = readSetting(bonuses.value(), "veryHard", def.veryHard); } static void readAllowBattleItemsSettings(const sol::table& table, Settings::AllowBattleItems& value) { const auto& def = defaultSettings().allowBattleItems; auto category = table.get<sol::optional<sol::table>>("allowBattleItems"); if (!category.has_value()) { value = def; return; } value.onTransformOther = readSetting(category.value(), "onTransformOther", def.onTransformOther); value.onTransformSelf = readSetting(category.value(), "onTransformSelf", def.onTransformSelf); value.onDrainLevel = readSetting(category.value(), "onDrainLevel", def.onDrainLevel); value.onDoppelganger = readSetting(category.value(), "onDoppelganger", def.onDoppelganger); } static void readUnitEncyclopediaSettings(const sol::table& table, Settings::UnitEncyclopedia& value) { const auto& def = defaultSettings().unitEncyclopedia; auto category = table.get<sol::optional<sol::table>>("unitEncyclopedia"); if (!category.has_value()) { value = def; // For backward compatibility value.detailedAttackDescription = readSetting(table, "detailedAttackDescription", def.detailedAttackDescription); return; } value.detailedUnitDescription = readSetting(category.value(), "detailedUnitDescription", def.detailedUnitDescription); value.detailedAttackDescription = readSetting(category.value(), "detailedAttackDescription", def.detailedAttackDescription); value.displayDynamicUpgradeValues = readSetting(category.value(), "displayDynamicUpgradeValues", def.displayDynamicUpgradeValues); value.displayBonusHp = readSetting(category.value(), "displayBonusHp", def.displayBonusHp); value.displayBonusXp = readSetting(category.value(), "displayBonusXp", def.displayBonusXp); value.displayInfiniteAttackIndicator = readSetting(category.value(), "displayInfiniteAttackIndicator", def.displayInfiniteAttackIndicator); value.displayCriticalHitTextInAttackName = readSetting(category.value(), "displayCriticalHitTextInAttackName", def.displayCriticalHitTextInAttackName); } static void readModifierSettings(const sol::table& table, Settings::Modifiers& value) { const auto& def = defaultSettings().modifiers; auto category = table.get<sol::optional<sol::table>>("modifiers"); if (!category.has_value()) { value = def; return; } value.cumulativeUnitRegeneration = readSetting(category.value(), "cumulativeUnitRegeneration", def.cumulativeUnitRegeneration); value.notifyModifiersChanged = readSetting(category.value(), "notifyModifiersChanged", def.notifyModifiersChanged); value.validateUnitsOnGroupChanged = readSetting(category.value(), "validateUnitsOnGroupChanged", def.validateUnitsOnGroupChanged); } static Color readColor(const sol::table& table, const Color& def) { Color color{}; color.r = readSetting(table, "red", def.r); color.g = readSetting(table, "green", def.g); color.b = readSetting(table, "blue", def.b); return color; } static void readWaterMoveCostSettings(const sol::table& table, Settings::MovementCost::Water& water) { const auto& def = defaultSettings().movementCost.water; water.dflt = readSetting(table, "default", def.dflt, 1); water.deadLeader = readSetting(table, "withDeadLeader", def.deadLeader, 1); water.withBonus = readSetting(table, "withBonus", def.withBonus, 1); water.waterOnly = readSetting(table, "waterOnly", def.waterOnly, 1); } static void readForestMoveCostSettings(const sol::table& table, Settings::MovementCost::Forest& forest) { const auto& def = defaultSettings().movementCost.forest; forest.dflt = readSetting(table, "default", def.dflt, 1); forest.deadLeader = readSetting(table, "withDeadLeader", def.deadLeader, 1); forest.withBonus = readSetting(table, "withBonus", def.withBonus, 1); } static void readPlainMoveCostSettings(const sol::table& table, Settings::MovementCost::Plain& plain) { const auto& def = defaultSettings().movementCost.plain; plain.dflt = readSetting(table, "default", def.dflt, 1); plain.deadLeader = readSetting(table, "withDeadLeader", def.deadLeader, 1); plain.onRoad = readSetting(table, "onRoad", def.onRoad, 1); } static void readMovementCostSettings(const sol::table& table, Settings::MovementCost& value) { const auto& defTextColor = defaultSettings().movementCost.textColor; const auto& defOutlineColor = defaultSettings().movementCost.outlineColor; value.show = defaultSettings().movementCost.show; value.textColor = defTextColor; value.outlineColor = defOutlineColor; auto moveCost = table.get<sol::optional<sol::table>>("movementCost"); if (!moveCost.has_value()) { return; } auto water = moveCost.value().get<sol::optional<sol::table>>("water"); if (water.has_value()) { readWaterMoveCostSettings(water.value(), value.water); } auto forest = moveCost.value().get<sol::optional<sol::table>>("forest"); if (forest.has_value()) { readForestMoveCostSettings(forest.value(), value.forest); } auto plain = moveCost.value().get<sol::optional<sol::table>>("plain"); if (plain.has_value()) { readPlainMoveCostSettings(plain.value(), value.plain); } value.show = readSetting(moveCost.value(), "show", defaultSettings().movementCost.show); auto textColor = moveCost.value().get<sol::optional<sol::table>>("textColor"); if (textColor.has_value()) { value.textColor = readColor(textColor.value(), defTextColor); } auto outlineColor = moveCost.value().get<sol::optional<sol::table>>("outlineColor"); if (outlineColor.has_value()) { value.outlineColor = readColor(outlineColor.value(), defOutlineColor); } } static void readLobbySettings(const sol::table& table, Settings::Lobby& value) { const auto& settings = defaultSettings().lobby; value.server.ip = settings.server.ip; value.server.port = settings.server.port; value.client.port = settings.client.port; auto lobby = table.get<sol::optional<sol::table>>("lobby"); if (!lobby.has_value()) { return; } auto server = lobby.value().get<sol::optional<sol::table>>("server"); if (server.has_value()) { value.server.ip = readSetting(server.value(), "ip", settings.server.ip); value.server.port = readSetting(server.value(), "port", settings.server.port); } auto client = lobby.value().get<sol::optional<sol::table>>("client"); if (client.has_value()) { value.client.port = readSetting(client.value(), "port", settings.client.port); } } static void readDebugSettings(const sol::table& table, Settings::Debug& value) { const auto& def = defaultSettings().debug; // 'debug' is reserved to Lua standard debug library auto category = table.get<sol::optional<sol::table>>("debugging"); if (!category.has_value()) { value = def; return; } value.sendObjectsChangesTreshold = readSetting(category.value(), "sendObjectsChangesTreshold", def.sendObjectsChangesTreshold); value.logSinglePlayerMessages = readSetting(category.value(), "logSinglePlayerMessages", def.logSinglePlayerMessages); } static void readEngineSettings(const sol::table& table, Settings::Engine& value) { const auto& def = defaultSettings().engine; auto category = table.get<sol::optional<sol::table>>("engine"); if (!category.has_value()) { value = def; return; } value.sendRefreshInfoObjectCountLimit = readSetting(category.value(), "sendRefreshInfoObjectCountLimit", def.sendRefreshInfoObjectCountLimit); } static void readBattleSettings(const sol::table& table, Settings::Battle& value) { const auto& def = defaultSettings().battle; auto category = table.get<sol::optional<sol::table>>("battle"); if (!category.has_value()) { value = def; return; } value.allowRetreatedUnitsToUpgrade = readSetting(category.value(), "allowRetreatedUnitsToUpgrade", def.allowRetreatedUnitsToUpgrade); value.carryXpOverUpgrade = readSetting(category.value(), "carryXpOverUpgrade", def.carryXpOverUpgrade); value.allowMultiUpgrade = readSetting(category.value(), "allowMultiUpgrade", def.allowMultiUpgrade); } static void readAdditionalLordIncomeSettings(const sol::table& table, Settings::AdditionalLordIncome& value) { const auto& def = defaultSettings().additionalLordIncome; auto income = table.get<sol::optional<sol::table>>("additionalLordIncome"); if (!income.has_value()) { value = def; return; } value.warrior = readSetting(income.value(), "warrior", def.warrior); value.mage = readSetting(income.value(), "mage", def.mage); value.guildmaster = readSetting(income.value(), "guildmaster", def.guildmaster); } static void readSettings(const sol::table& table, Settings& settings) { // clang-format off settings.unitMaxDamage = readSetting(table, "unitMaxDamage", defaultSettings().unitMaxDamage); settings.unitMaxArmor = readSetting(table, "unitMaxArmor", defaultSettings().unitMaxArmor); settings.stackScoutRangeMax = readSetting(table, "stackMaxScoutRange", defaultSettings().stackScoutRangeMax); settings.shatteredArmorMax = readSetting(table, "shatteredArmorMax", defaultSettings().shatteredArmorMax, 0, baseSettings().shatteredArmorMax); settings.shatterDamageMax = readSetting(table, "shatterDamageMax", defaultSettings().shatterDamageMax, 0, baseSettings().shatterDamageMax); settings.drainAttackHeal = readSetting(table, "drainAttackHeal", defaultSettings().drainAttackHeal); settings.drainOverflowHeal = readSetting(table, "drainOverflowHeal", defaultSettings().drainOverflowHeal); settings.carryOverItemsMax = readSetting(table, "carryOverItemsMax", defaultSettings().carryOverItemsMax, 0); settings.criticalHitDamage = readSetting(table, "criticalHitDamage", defaultSettings().criticalHitDamage); settings.criticalHitChance = readSetting(table, "criticalHitChance", defaultSettings().criticalHitChance, (uint8_t)0, (uint8_t)100); settings.mageLeaderAttackPowerReduction = readSetting(table, "mageLeaderAccuracyReduction", defaultSettings().mageLeaderAttackPowerReduction); settings.disableAllowedRoundMax = readSetting(table, "disableAllowedRoundMax", defaultSettings().disableAllowedRoundMax, (uint8_t)1); settings.shatterDamageUpgradeRatio = readSetting(table, "shatterDamageUpgradeRatio", defaultSettings().shatterDamageUpgradeRatio); settings.splitDamageMultiplier = readSetting(table, "splitDamageMultiplier", defaultSettings().splitDamageMultiplier, (uint8_t)1, (uint8_t)6); settings.showBanners = readSetting(table, "showBanners", defaultSettings().showBanners); settings.showResources = readSetting(table, "showResources", defaultSettings().showResources); settings.showLandConverted = readSetting(table, "showLandConverted", defaultSettings().showLandConverted); settings.preserveCapitalBuildings = readSetting(table, "preserveCapitalBuildings", defaultSettings().preserveCapitalBuildings); settings.buildTempleForWarriorLord = readSetting(table, "buildTempleForWarriorLord", defaultSettings().buildTempleForWarriorLord); settings.allowShatterAttackToMiss = readSetting(table, "allowShatterAttackToMiss", defaultSettings().allowShatterAttackToMiss); settings.doppelgangerRespectsEnemyImmunity = readSetting(table, "doppelgangerRespectsEnemyImmunity", defaultSettings().doppelgangerRespectsEnemyImmunity); settings.doppelgangerRespectsAllyImmunity = readSetting(table, "doppelgangerRespectsAllyImmunity", defaultSettings().doppelgangerRespectsAllyImmunity); settings.leveledDoppelgangerAttack = readSetting(table, "leveledDoppelgangerAttack", defaultSettings().leveledDoppelgangerAttack); settings.leveledTransformSelfAttack = readSetting(table, "leveledTransformSelfAttack", defaultSettings().leveledTransformSelfAttack); settings.leveledTransformOtherAttack = readSetting(table, "leveledTransformOtherAttack", defaultSettings().leveledTransformOtherAttack); settings.leveledDrainLevelAttack = readSetting(table, "leveledDrainLevelAttack", defaultSettings().leveledDrainLevelAttack); settings.leveledSummonAttack = readSetting(table, "leveledSummonAttack", defaultSettings().leveledSummonAttack); settings.missChanceSingleRoll = readSetting(table, "missChanceSingleRoll", defaultSettings().missChanceSingleRoll); settings.unrestrictedBestowWards = readSetting(table, "unrestrictedBestowWards", defaultSettings().unrestrictedBestowWards); settings.freeTransformSelfAttack = readSetting(table, "freeTransformSelfAttack", defaultSettings().freeTransformSelfAttack); settings.freeTransformSelfAttackInfinite = readSetting(table, "freeTransformSelfAttackInfinite", defaultSettings().freeTransformSelfAttackInfinite); settings.fixEffectiveHpFormula = readSetting(table, "fixEffectiveHpFormula", defaultSettings().fixEffectiveHpFormula); settings.debugMode = readSetting(table, "debugHooks", defaultSettings().debugMode); // clang-format on readAiAttackPowerSettings(table, settings.aiAttackPowerBonus); readAllowBattleItemsSettings(table, settings.allowBattleItems); readUnitEncyclopediaSettings(table, settings.unitEncyclopedia); readModifierSettings(table, settings.modifiers); readMovementCostSettings(table, settings.movementCost); readLobbySettings(table, settings.lobby); readDebugSettings(table, settings.debug); readEngineSettings(table, settings.engine); readBattleSettings(table, settings.battle); readAdditionalLordIncomeSettings(table, settings.additionalLordIncome); } const Settings& baseSettings() { static Settings settings; static bool initialized = false; if (!initialized) { settings.unitMaxDamage = 300; settings.unitMaxArmor = 90; settings.stackScoutRangeMax = 8; settings.shatteredArmorMax = 100; settings.shatterDamageMax = 100; settings.drainAttackHeal = 50; settings.drainOverflowHeal = 50; settings.carryOverItemsMax = 5; settings.criticalHitDamage = 5; settings.criticalHitChance = 100; settings.mageLeaderAttackPowerReduction = 10; settings.aiAttackPowerBonus.absolute = true; settings.aiAttackPowerBonus.easy = -15; settings.aiAttackPowerBonus.average = 0; settings.aiAttackPowerBonus.hard = 5; settings.aiAttackPowerBonus.veryHard = 10; settings.disableAllowedRoundMax = 40; settings.shatterDamageUpgradeRatio = 100; settings.splitDamageMultiplier = 1; settings.showBanners = false; settings.showResources = false; settings.showLandConverted = false; settings.preserveCapitalBuildings = false; settings.buildTempleForWarriorLord = false; settings.allowShatterAttackToMiss = false; settings.doppelgangerRespectsEnemyImmunity = false; settings.doppelgangerRespectsAllyImmunity = false; settings.leveledDoppelgangerAttack = false; settings.leveledTransformSelfAttack = false; settings.leveledTransformOtherAttack = false; settings.leveledDrainLevelAttack = false; settings.leveledSummonAttack = false; settings.missChanceSingleRoll = false; settings.unrestrictedBestowWards = false; settings.freeTransformSelfAttack = false; settings.freeTransformSelfAttackInfinite = false; settings.unitEncyclopedia.detailedUnitDescription = false; settings.unitEncyclopedia.detailedAttackDescription = false; settings.unitEncyclopedia.displayDynamicUpgradeValues = false; settings.unitEncyclopedia.displayBonusHp = false; settings.unitEncyclopedia.displayBonusXp = false; settings.unitEncyclopedia.displayInfiniteAttackIndicator = false; settings.fixEffectiveHpFormula = false; settings.modifiers.cumulativeUnitRegeneration = false; settings.modifiers.notifyModifiersChanged = false; settings.modifiers.validateUnitsOnGroupChanged = false; settings.allowBattleItems.onTransformOther = false; settings.allowBattleItems.onTransformSelf = false; settings.allowBattleItems.onDrainLevel = false; settings.allowBattleItems.onDoppelganger = false; settings.movementCost.water.dflt = 6; settings.movementCost.water.deadLeader = 12; settings.movementCost.water.withBonus = 2; settings.movementCost.water.waterOnly = 2; settings.movementCost.forest.dflt = 4; settings.movementCost.forest.deadLeader = 8; settings.movementCost.forest.withBonus = 2; settings.movementCost.plain.dflt = 2; settings.movementCost.plain.deadLeader = 4; settings.movementCost.plain.onRoad = 1; settings.movementCost.textColor = Color{200, 200, 200}; settings.movementCost.show = false; settings.debugMode = false; initialized = true; } return settings; } const Settings& defaultSettings() { static Settings settings; static bool initialized = false; if (!initialized) { settings = baseSettings(); settings.showBanners = true; settings.showResources = true; settings.movementCost.show = true; settings.unrestrictedBestowWards = true; settings.unitEncyclopedia.detailedUnitDescription = true; settings.unitEncyclopedia.detailedAttackDescription = true; settings.fixEffectiveHpFormula = true; // The default value of 1024 objects provides room for average object size of 512 bytes. settings.engine.sendRefreshInfoObjectCountLimit = 1024; initialized = true; } return settings; } void initializeUserSettings(Settings& value) { value = defaultSettings(); const auto path{scriptsFolder() / "settings.lua"}; try { const auto env{executeScriptFile(path)}; if (!env) return; const sol::table& table = (*env)["settings"]; readSettings(table, value); } catch (const std::exception& e) { showErrorMessageBox(fmt::format("Failed to read script '{:s}'.\n" "Reason: '{:s}'", path.string(), e.what())); } } const Settings& userSettings() { static Settings settings; static bool initialized = false; if (!initialized) { initializeUserSettings(settings); initialized = true; } return settings; } } // namespace hooks
21,822
C++
.cpp
413
44.726392
158
0.705871
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,915
attackdescriptor.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/attackdescriptor.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "attackdescriptor.h" #include "attack.h" #include "attackutils.h" #include "customattacks.h" #include "customattackutils.h" #include "game.h" #include "interfaceutils.h" #include "midunit.h" #include "midunitdescriptor.h" #include "restrictions.h" #include "settings.h" #include "ummodifier.h" #include "unitutils.h" #include "usunitimpl.h" namespace utils { game::IAttack* getAttack(game::IUsUnit* unitImpl, AttackType type) { using namespace game; switch (type) { case AttackType::Primary: return hooks::getAttack(unitImpl, true, true); case AttackType::Secondary: return hooks::getAttack(unitImpl, false, false); case AttackType::Alternative: { auto attack = hooks::getAttack(unitImpl, true, false); if (hooks::attackHasAltAttack(attack)) return attack; } } return nullptr; } game::IAttack* getGlobalAttack(game::IEncUnitDescriptor* descriptor, AttackType type) { using namespace game; CMidgardID attackId{}; switch (type) { case AttackType::Primary: descriptor->vftable->getAttackId(descriptor, &attackId); break; case AttackType::Secondary: descriptor->vftable->getAttack2Id(descriptor, &attackId); break; case AttackType::Alternative: descriptor->vftable->getAltAttackId(descriptor, &attackId); break; } if (attackId == emptyId) return nullptr; auto attack = hooks::getGlobalAttack(&attackId); if (attack == nullptr && type == AttackType::Primary) { hooks::generateUnitImplByAttackId(&attackId); attack = hooks::getGlobalAttack(&attackId); } return attack; } game::IAttack* getAttack(game::IEncUnitDescriptor* descriptor, AttackType type, bool global, bool* useDescriptor) { *useDescriptor = false; if (global) { return getGlobalAttack(descriptor, type); } auto midUnitDescriptor = hooks::castToMidUnitDescriptor(descriptor); if (midUnitDescriptor) { return getAttack(midUnitDescriptor->unit->unitImpl, type); } else { *useDescriptor = true; return getGlobalAttack(descriptor, type); } } int computeValue(int base, int min, int max, int boost, const game::IdList* modifiers, game::ModifierElementTypeFlag modifierType) { using namespace game; int result = base; if (modifiers) { result = gameFunctions().applyPercentModifiers(result, modifiers, modifierType); } if (boost) { result += result * boost / 100; } return std::clamp(result, min, max); } int computeDamage(int base, int boostDamageLevel, int lowerDamageLevel, const game::IdList* modifiers, int damageMax, game::AttackClassId classId, bool damageSplit) { using namespace game; const auto& restrictions = gameRestrictions(); int result = base; if (hooks::isNormalDamageAttack(classId)) { int boost = hooks::getBoostDamage(boostDamageLevel) - hooks::getLowerDamage(lowerDamageLevel); result = computeValue(base, restrictions.attackDamage->min, damageMax, boost, modifiers, ModifierElementTypeFlag::QtyDamage); if (damageSplit) { result *= hooks::userSettings().splitDamageMultiplier; } } else if (hooks::isModifiableDamageAttack(classId)) { result = computeValue(base, restrictions.attackDamage->min, damageMax, 0, modifiers, ModifierElementTypeFlag::QtyDamage); } if (classId == AttackClassId::Shatter) { if (result > hooks::userSettings().shatterDamageMax) { result = hooks::userSettings().shatterDamageMax; } } return result; } int computePower(int base, const game::IdList* modifiers, game::AttackClassId classId) { using namespace game; const auto& restrictions = gameRestrictions(); if (!hooks::attackHasPower(classId)) return 100; return computeValue(base, restrictions.attackPower->min, restrictions.attackPower->max, 0, modifiers, ModifierElementTypeFlag::Power); } int computeInitiative(int base, int lowerInitiativeLevel, const game::IdList* modifiers) { using namespace game; const auto& restrictions = gameRestrictions(); return computeValue(base, restrictions.attackInitiative->min, restrictions.attackInitiative->max, -hooks::getLowerInitiative(lowerInitiativeLevel), modifiers, ModifierElementTypeFlag::Initiative); } AttackDescriptor::AttackDescriptor(game::IEncUnitDescriptor* descriptor, AttackType type, bool global, int boostDamageLevel, int lowerDamageLevel, int lowerInitiativeLevel, const game::IdList* modifiers, int damageMax) : data() { using namespace hooks; bool useDescriptor; auto attack = getAttack(descriptor, type, global, &useDescriptor); if (attack == nullptr) { data.empty = true; data.classId = (game::AttackClassId)game::emptyCategoryId; data.sourceId = (game::AttackSourceId)game::emptyCategoryId; data.reachId = (game::AttackReachId)game::emptyCategoryId; return; } if (useDescriptor && type == AttackType::Primary) { data.name = descriptor->vftable->getAttackName(descriptor); data.classId = descriptor->vftable->getAttackClass(descriptor)->id; data.sourceId = descriptor->vftable->getAttackSource(descriptor)->id; data.reachId = descriptor->vftable->getAttackReach(descriptor)->id; data.initiative = descriptor->vftable->getAttackInitiative(descriptor); data.level = descriptor->vftable->getAttackLevel(descriptor); if (attackHasDamage(data.classId)) { data.damage = descriptor->vftable->getAttackDamageOrHeal(descriptor); } else if (attackHasHeal(data.classId)) { data.heal = descriptor->vftable->getAttackDamageOrHeal(descriptor); } if (attackHasPower(data.classId)) { data.power = descriptor->vftable->getAttackPower(descriptor); } } else { data.classId = attack->vftable->getAttackClass(attack)->id; data.sourceId = attack->vftable->getAttackSource(attack)->id; data.reachId = attack->vftable->getAttackReach(attack)->id; data.initiative = attack->vftable->getInitiative(attack); data.level = attack->vftable->getLevel(attack); if (attackHasDamage(data.classId)) { data.damage = attack->vftable->getQtyDamage(attack); } else if (attackHasHeal(data.classId)) { data.heal = attack->vftable->getQtyHeal(attack); } if (useDescriptor && type == AttackType::Secondary) { data.name = descriptor->vftable->getAttack2Name(descriptor); if (attackHasPower(data.classId)) { data.power = descriptor->vftable->getAttack2Power(descriptor); } } else if (useDescriptor && type == AttackType::Alternative) { data.name = descriptor->vftable->getAltAttackName(descriptor); if (attackHasPower(data.classId)) { data.power = descriptor->vftable->getAltAttackPower(descriptor); } } else { data.name = attack->vftable->getName(attack); if (attackHasPower(data.classId)) { int tmp; data.power = *attack->vftable->getPower(attack, &tmp); } } } data.custom = getCustomAttackData(attack); data.initiative = computeInitiative(data.initiative, lowerInitiativeLevel, modifiers); data.damage = computeDamage(data.damage, boostDamageLevel, lowerDamageLevel, modifiers, damageMax, data.classId, data.custom.damageSplit); data.drain = attackHasDrain(data.classId) ? attack->vftable->getDrain(attack, data.damage) : 0; data.power = computePower(data.power, modifiers, data.classId); data.infinite = attackHasInfinite(data.classId) ? attack->vftable->getInfinite(attack) : 0; data.critHit = false; if (attackHasCritHit(data.classId)) { data.critHit = attack->vftable->getCritHit(attack); if (!data.critHit) { if (global) { auto unitImpl = getUnitImpl(descriptor); data.critHit = hasCriticalHitLeaderAbility(unitImpl); } else { data.critHit = hasCriticalHitLeaderAbility(descriptor); } } } switch (data.classId) { case game::AttackClassId::Drain: data.drain += data.damage * userSettings().drainAttackHeal / 100; break; case game::AttackClassId::DrainOverflow: data.drain += data.damage * userSettings().drainOverflowHeal / 100; break; } } bool AttackDescriptor::empty() const { return data.empty; } std::string AttackDescriptor::name() const { return data.name; } game::AttackClassId AttackDescriptor::classId() const { return data.classId; } game::AttackSourceId AttackDescriptor::sourceId() const { return data.sourceId; } game::AttackReachId AttackDescriptor::reachId() const { return data.reachId; } int AttackDescriptor::damage() const { return data.damage; } int AttackDescriptor::drain() const { return data.drain; } int AttackDescriptor::heal() const { return data.heal; } bool AttackDescriptor::hasPower() const { return hooks::attackHasPower(data.classId); } int AttackDescriptor::power() const { return data.power; } int AttackDescriptor::initiative() const { return data.initiative; } int AttackDescriptor::level() const { return data.level; } int AttackDescriptor::boost() const { return hooks::getBoostDamage(data.level); } int AttackDescriptor::lower() const { return hooks::getLowerDamage(data.level); } int AttackDescriptor::lowerIni() const { return hooks::getLowerInitiative(data.level); } bool AttackDescriptor::hasInfinite() const { return hooks::attackHasInfinite(data.classId); } bool AttackDescriptor::infinite() const { return data.infinite; } bool AttackDescriptor::critHit() const { return data.critHit; } std::uint8_t AttackDescriptor::critDamage() const { return critHit() ? custom().critDamage : 0; } std::uint8_t AttackDescriptor::critPower() const { return critHit() ? custom().critPower : 0; } std::uint8_t AttackDescriptor::damageRatio() const { return custom().damageRatio; } bool AttackDescriptor::damageRatioPerTarget() const { return custom().damageRatioPerTarget; } bool AttackDescriptor::damageSplit() const { return custom().damageSplit; } const hooks::CustomAttackData& AttackDescriptor::custom() const { return data.custom; } } // namespace utils
12,104
C++
.cpp
344
28.267442
99
0.665726
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,916
terraincountmap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/terraincountmap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "terraincountmap.h" #include "version.h" #include <array> namespace game::TerrainCountMapApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Access)0x4462f7, }, // Russobit Api{ (Api::Access)0x4462f7, }, // Gog Api{ (Api::Access)0x445efb, }, // Scenario Editor Api{ (Api::Access)0x4c90db, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::TerrainCountMapApi
1,375
C++
.cpp
47
25.978723
72
0.704236
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,917
customattacks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/customattacks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "customattacks.h" #include "dbffile.h" #include "log.h" #include "utils.h" #include <fmt/format.h> namespace hooks { void initializeCustomAttacks() { utils::DbfFile dbf; const std::filesystem::path dbfFilePath{globalsFolder() / "Gattacks.dbf"}; if (!dbf.open(dbfFilePath)) { logError("mssProxyError.log", fmt::format("Could not open {:s}", dbfFilePath.filename().string())); return; } getCustomAttacks().damageRatiosEnabled = dbf.column(damageRatioColumnName) && dbf.column(damageRatioPerTargetColumnName) && dbf.column(damageSplitColumnName); getCustomAttacks().critSettingsEnabled = dbf.column(critDamageColumnName) && dbf.column(critPowerColumnName); } CustomAttacks& getCustomAttacks() { static CustomAttacks value{}; return value; } } // namespace hooks
1,789
C++
.cpp
45
33.755556
90
0.68894
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,918
rendererimpl.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/rendererimpl.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rendererimpl.h" #include "version.h" #include <array> namespace game::CRendererImplApi { // clang-format off static std::array<IMqRenderer2Vftable*, 4> vftables = {{ // Akella (IMqRenderer2Vftable*)0x6e2564, // Russobit (IMqRenderer2Vftable*)0x6e2564, // Gog (IMqRenderer2Vftable*)0x6e050c, // Scenario Editor (IMqRenderer2Vftable*)0x5d6ad4, }}; // clang-format on IMqRenderer2Vftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CRendererImplApi
1,358
C++
.cpp
39
32.333333
72
0.750381
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,919
displayhandlerhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/displayhandlerhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "displayhandlershooks.h" #include "game.h" #include "gameimages.h" #include "gameutils.h" #include "isolayers.h" #include "midgardobjectmap.h" #include "midplayer.h" #include "midvillage.h" #include "racetype.h" #include "stringintlist.h" #include <fmt/format.h> namespace hooks { static std::string getVillageImageName(game::RaceId raceId, int villageTier, bool shadow) { using game::RaceId; const char tierLetter = '0' + static_cast<char>(villageTier); auto imageName{fmt::format("G000FT0000NE{:c}", tierLetter)}; switch (raceId) { case RaceId::Dwarf: imageName += "DW"; break; case RaceId::Elf: imageName += "EL"; break; case RaceId::Heretic: imageName += "HE"; break; case RaceId::Human: imageName += "HU"; break; case RaceId::Undead: imageName += "UN"; break; default: break; } if (shadow) { imageName += 'S'; } return imageName; } static game::IMqImage2* getVillageImageForRace(game::RaceId raceId, int villageTier, bool animatedIso, bool shadow) { using namespace game; const auto& listApi{StringIntListApi::get()}; StringIntList list{}; listApi.constructor(&list); const auto& imagesApi{GameImagesApi::get()}; GameImagesPtr imagesPtr; imagesApi.getGameImages(&imagesPtr); auto images{*imagesPtr.data}; auto isoCmon{images->isoCmon}; auto isoImg{animatedIso ? images->isoAnim : images->isoStill}; const auto imageName{getVillageImageName(raceId, villageTier, shadow)}; const auto length{imageName.length()}; imagesApi.getCityImageNames(&list, isoCmon, isoImg, imageName.c_str(), length, length); IMqImage2* villageImage{}; if (list.length == 1) { auto node{list.head->next}; const auto& name{node->data.first}; const auto animated{node->data.second}; villageImage = imagesApi.getImage(animated ? isoImg : isoCmon, name.string, 0, true, images->log); } imagesApi.createOrFreeGameImages(&imagesPtr, nullptr); listApi.destructor(&list); return villageImage; } static game::IMqImage2* getVillageImage(game::RaceId raceId, int villageTier, bool animatedIso, bool shadow) { auto imageForRace{getVillageImageForRace(raceId, villageTier, animatedIso, shadow)}; return imageForRace ? imageForRace : game::GameImagesApi::get().getVillageImage(villageTier, animatedIso, shadow); } static const game::LRaceCategory* getVillageOwnerRace(const game::IMidgardObjectMap* objectMap, const game::CMidgardID& ownerId) { using namespace game; const LRaceCategory* ownerRace{RaceCategories::get().neutral}; if (ownerId != emptyId) { auto player{getPlayer(objectMap, &ownerId)}; if (player) { ownerRace = &player->raceType->data->raceType; } } return ownerRace; } static bool villageIsObjective(const game::IdSet* objectives, const game::CMidgardID& villageId) { using namespace game; IdSetIterator iterator{}; IdSetApi::get().find(objectives, &iterator, &villageId); return iterator != objectives->end(); } void __stdcall displayHandlerVillageHooked(game::ImageLayerList* list, const game::CMidVillage* village, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::IdSet* objectives, int a6, bool animatedIso) { using namespace game; const auto& listApi{ImageLayerListApi::get()}; listApi.clear(list); if (!village) { return; } auto ownerRace{getVillageOwnerRace(objectMap, village->ownerId)}; ImageLayerPair imagePair{getVillageImage(ownerRace->id, village->tierLevel, animatedIso, false), isoLayers().villages}; listApi.pushBack(list, &imagePair); ImageLayerPair shadowPair{getVillageImage(ownerRace->id, village->tierLevel, animatedIso, true), isoLayers().stacksShadow}; listApi.pushBack(list, &shadowPair); const auto& fn{gameFunctions()}; if (!fn.isRaceCategoryUnplayable(ownerRace)) { ImageLayerPair flagPair{GameImagesApi::get().getFlagImage(ownerRace), isoLayers().flags}; listApi.pushBack(list, &flagPair); } if (playerId && villageIsObjective(objectives, village->id)) { ImageLayerPair objectivePair{GameImagesApi::get().getObjectiveImage( village->mapElement.sizeX), isoLayers().symObjective}; listApi.pushBack(list, &objectivePair); } if (village->stackId != emptyId) { listApi.addShieldImageLayer(list, village, 0, objectMap, playerId); } if (village->riotTurn) { ImageLayerPair riotPair{GameImagesApi::get().getRiotImage(), isoLayers().riots}; listApi.pushBack(list, &riotPair); } } } // namespace hooks
6,360
C++
.cpp
160
30.51875
100
0.628854
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,920
customattack.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/customattack.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "customattack.h" #include "attackclasscat.h" #include "battlemsgdata.h" #include "customattackhooks.h" #include "game.h" #include "log.h" #include "mempool.h" namespace hooks { void __fastcall customAttackDtor(CustomAttack* attack, int /*%edx*/, bool freeMemory) { logDebug("newAttackType.log", "CustomAttack d-tor"); if (freeMemory) { game::Memory::get().freeNonZero(attack); } } bool __fastcall customAttackCanPerform(CustomAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId) { logDebug("newAttackType.log", "CustomAttack canPerform"); return true; } game::CMidgardID* __fastcall customAttackGetTargetGroupId(CustomAttack* thisptr, int /*%edx*/, game::CMidgardID* targetGroupId, game::BattleMsgData* battleMsgData) { logDebug("newAttackType.log", "CustomAttack getTargetGroupId"); game::gameFunctions().getAllyOrEnemyGroupId(targetGroupId, battleMsgData, &thisptr->id1, false); return targetGroupId; } void __fastcall customAttackFillTargetsList(CustomAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::TargetSet* targetsList) { logDebug("newAttackType.log", "CustomAttack fillTargetsList"); game::BattleMsgDataApi::get().fillTargetsList(objectMap, battleMsgData, thisptr, &thisptr->id1, &thisptr->id2, false, targetsList, true); } void __fastcall customAttackFillAltTargetsList(CustomAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::TargetSet* targetsList) { logDebug("newAttackType.log", "CustomAttack fillAltTargetsList"); // do nothing } bool __fastcall customAttackMethod5(CustomAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId) { logDebug("newAttackType.log", "CustomAttack method 5"); return thisptr->vftable->canPerform(thisptr, objectMap, battleMsgData, unitId); } bool __fastcall customAttackCanMiss(CustomAttack* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData, game::CMidgardID* id) { logDebug("newAttackType.log", "CustomAttack canMiss"); return true; } bool __fastcall customAttackMethod7(CustomAttack* thisptr, int /*%edx*/, int a2, int a3, int a4) { logDebug("newAttackType.log", "CustomAttack method 7"); return false; } bool __fastcall customAttackIsImmune(CustomAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId) { logDebug("newAttackType.log", "CustomAttack isImmune"); return game::gameFunctions().isUnitImmuneToAttack(objectMap, battleMsgData, unitId, thisptr->attack, false); } void __fastcall customAttackOnMiss(CustomAttack* thisptr, int /*%edx*/, int a2, int a3, int a4, int a5) { logDebug("newAttackType.log", "CustomAttack onMiss"); // do nothing } bool __fastcall customAttackGetAttackClass(CustomAttack* thisptr, int /*%edx*/, const game::CMidgardID* targetUnitId, const game::BattleMsgData* battleMsgData, game::LAttackClass* attackClass) { logDebug("newAttackType.log", "CustomAttack getAttackClass"); attackClass->id = customAttackClass.id; attackClass->table = customAttackClass.table; return true; } bool __fastcall customAttackGetUnderlyingAttackClass(CustomAttack* thisptr, int /*%edx*/, const game::CMidgardID* targetUnitId, const game::BattleMsgData* battleMsgData, game::LAttackClass* attackClass) { logDebug("newAttackType.log", "CustomAttack getUnderlyingAttackClass"); return thisptr->vftable->getAttackClass(thisptr, targetUnitId, battleMsgData, attackClass); } void __fastcall customAttackDoAttack(CustomAttack* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId, void* a5) { logDebug("newAttackType.log", "CustomAttack doAttack"); } bool __fastcall customAttackMethod13(CustomAttack* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData, game::IMidgardObjectMap* objectMap) { logDebug("newAttackType.log", "CustomAttack method 13"); return false; } bool __fastcall customAttackMethod14(CustomAttack* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData) { logDebug("newAttackType.log", "CustomAttack method 14"); return false; } bool __fastcall customAttackMethod15(CustomAttack* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData) { logDebug("newAttackType.log", "CustomAttack method 15"); return false; } bool __fastcall customAttackMethod16(CustomAttack* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData) { logDebug("newAttackType.log", "CustomAttack method 16"); return false; } bool __fastcall customAttackMethod17(CustomAttack* thisptr, int /*%edx*/, game::BattleMsgData* battleMsgData) { logDebug("newAttackType.log", "CustomAttack method 17"); return false; } // clang-format off static const game::IBatAttackVftable customAttackVftable{ (game::IBatAttackVftable::Destructor)customAttackDtor, (game::IBatAttackVftable::CanPerform)customAttackCanPerform, (game::IBatAttackVftable::GetTargetGroupId)customAttackGetTargetGroupId, (game::IBatAttackVftable::FillTargetsList)customAttackFillTargetsList, (game::IBatAttackVftable::FillTargetsList)customAttackFillAltTargetsList, (game::IBatAttackVftable::Method5)customAttackMethod5, (game::IBatAttackVftable::CanMiss)customAttackCanMiss, (game::IBatAttackVftable::Method7)customAttackMethod7, (game::IBatAttackVftable::IsImmune)customAttackIsImmune, (game::IBatAttackVftable::OnAttack)customAttackOnMiss, (game::IBatAttackVftable::GetAttackClass)customAttackGetAttackClass, (game::IBatAttackVftable::GetAttackClass)customAttackGetUnderlyingAttackClass, (game::IBatAttackVftable::OnAttack)customAttackDoAttack, (game::IBatAttackVftable::Method13)customAttackMethod13, (game::IBatAttackVftable::UnknownMethod)customAttackMethod14, (game::IBatAttackVftable::UnknownMethod)customAttackMethod15, (game::IBatAttackVftable::UnknownMethod)customAttackMethod16, (game::IBatAttackVftable::UnknownMethod)customAttackMethod17, }; // clang-format on game::IBatAttack* customAttackCtor(CustomAttack* attack, game::IMidgardObjectMap* objectMap, const game::CMidgardID* id1, const game::CMidgardID* id2, int attackNumber) { logDebug("newAttackType.log", "CustomAttack c-tor"); attack->id1 = *id1; attack->id2 = *id2; attack->attackNumber = attackNumber; attack->attack = game::gameFunctions().getAttackById(objectMap, id1, attackNumber, true); attack->vftable = &customAttackVftable; return attack; } } // namespace hooks
10,060
C++
.cpp
214
32.957944
100
0.584241
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,921
cmdbattlechooseactionmsg.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/cmdbattlechooseactionmsg.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmdbattlechooseactionmsg.h" #include "version.h" #include <array> namespace game::CCmdBattleChooseActionMsgApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Destructor)0x415ce5, }, // Russobit Api{ (Api::Destructor)0x415ce5, }, // Gog Api{ (Api::Destructor)0x4159cb, }, // Scenario Editor Api{ (Api::Destructor)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } // clang-format off static std::array<CCommandMsgVftable*, 4> vftables = {{ // Akella (CCommandMsgVftable*)0x6d49dc, // Russobit (CCommandMsgVftable*)0x6d49dc, // Gog (CCommandMsgVftable*)0x6d297c, // Scenario Editor (CCommandMsgVftable*)nullptr, }}; // clang-format on CCommandMsgVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CCmdBattleChooseActionMsgApi
1,818
C++
.cpp
63
25.571429
72
0.712815
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,922
displayhandlers.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/displayhandlers.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "displayhandlers.h" #include "version.h" #include <array> namespace game::DisplayHandlersApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::DisplayHandler<CMidVillage>)0x5bcb73, }, // Russobit Api{ (Api::DisplayHandler<CMidVillage>)0x5bcb73, }, // Gog Api{ (Api::DisplayHandler<CMidVillage>)0x5bbc37, }, // Scenario Editor Api{ (Api::DisplayHandler<CMidVillage>)0x55d9eb, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::DisplayHandlersApi
1,458
C++
.cpp
47
27.765957
72
0.716216
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,923
pictureinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/pictureinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pictureinterf.h" #include "version.h" #include <array> namespace game::CPictureInterfApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetImage)0x5318a0, (Api::AssignFunctor)0x531843, }, // Russobit Api{ (Api::SetImage)0x5318a0, (Api::AssignFunctor)0x531843, }, // Gog Api{ (Api::SetImage)0x530db8, (Api::AssignFunctor)0x530d5b, }, // Scenario Editor Api{ (Api::SetImage)0x494988, (Api::AssignFunctor)0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CPictureInterfApi
1,523
C++
.cpp
51
26.156863
72
0.698023
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,924
scripts.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/scripts.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "scripts.h" #include "attackview.h" #include "battlemsgdata.h" #include "battlemsgdataview.h" #include "categoryids.h" #include "currencyview.h" #include "diplomacyview.h" #include "dynupgradeview.h" #include "fogview.h" #include "fortview.h" #include "gameutils.h" #include "groupview.h" #include "idview.h" #include "itembaseview.h" #include "itemview.h" #include "locationview.h" #include "log.h" #include "midstack.h" #include "modifierview.h" #include "playerview.h" #include "point.h" #include "ruinview.h" #include "scenariovariableview.h" #include "scenarioview.h" #include "scenvariablesview.h" #include "stackview.h" #include "tileview.h" #include "unitimplview.h" #include "unitslotview.h" #include "unitview.h" #include "unitviewdummy.h" #include "utils.h" #include <fmt/format.h> #include <mutex> #include <thread> extern std::thread::id mainThreadId; namespace hooks { struct PathHash { std::size_t operator()(std::filesystem::path const& p) const noexcept { return std::filesystem::hash_value(p); } }; static void bindApi(sol::state& lua) { using namespace game; // clang-format off lua.new_enum("Race", "Human", RaceId::Human, "Undead", RaceId::Undead, "Heretic", RaceId::Heretic, "Dwarf", RaceId::Dwarf, "Neutral", RaceId::Neutral, "Elf", RaceId::Elf ); lua.new_enum("Lord", "Mage", LordId::Mage, "Warrior", LordId::Warrior, "Diplomat", LordId::Diplomat ); lua.new_enum("Subrace", "Custom", SubRaceId::Custom, "Human", SubRaceId::Human, "Undead", SubRaceId::Undead, "Heretic", SubRaceId::Heretic, "Dwarf", SubRaceId::Dwarf, "Neutral", SubRaceId::Neutral, "NeutralHuman", SubRaceId::NeutralHuman, "NeutralElf", SubRaceId::NeutralElf, "NeutralGreenSkin", SubRaceId::NeutralGreenSkin, "NeutralDragon", SubRaceId::NeutralDragon, "NeutralMarsh", SubRaceId::NeutralMarsh, "NeutralWater", SubRaceId::NeutralWater, "NeutralBarbarian", SubRaceId::NeutralBarbarian, "NeutralWolf", SubRaceId::NeutralWolf, "Elf", SubRaceId::Elf ); lua.new_enum("Terrain", "Human", TerrainId::Human, "Dwarf", TerrainId::Dwarf, "Heretic", TerrainId::Heretic, "Undead", TerrainId::Undead, "Neutral", TerrainId::Neutral, "Elf", TerrainId::Elf ); lua.new_enum("Ground", "Plain", GroundId::Plain, "Forest", GroundId::Forest, "Water", GroundId::Water, "Mountain", GroundId::Mountain ); lua.new_enum("Unit", "Soldier", UnitId::Soldier, "Noble", UnitId::Noble, "Leader", UnitId::Leader, "Summon", UnitId::Summon, "Illusion", UnitId::Illusion, "Guardian", UnitId::Guardian ); lua.new_enum("Leader", "Fighter", LeaderId::Fighter, "Explorer", LeaderId::Explorer, "Mage", LeaderId::Mage, "Rod", LeaderId::Rod, "Noble", LeaderId::Noble ); lua.new_enum("Ability", "Incorruptible", LeaderAbilityId::Incorruptible, "WeaponMaster", LeaderAbilityId::WeaponMaster, "WandScrollUse", LeaderAbilityId::WandScrollUse, "WeaponArmorUse", LeaderAbilityId::WeaponArmorUse, "BannerUse", LeaderAbilityId::BannerUse, "JewelryUse", LeaderAbilityId::JewelryUse, "Rod", LeaderAbilityId::Rod, "OrbUse", LeaderAbilityId::OrbUse, "TalismanUse", LeaderAbilityId::TalismanUse, "TravelItemUse", LeaderAbilityId::TravelItemUse, "CriticalHit", LeaderAbilityId::CriticalHit ); lua.new_enum("Attack", "Damage", AttackClassId::Damage, "Drain", AttackClassId::Drain, "Paralyze", AttackClassId::Paralyze, "Heal", AttackClassId::Heal, "Fear", AttackClassId::Fear, "BoostDamage", AttackClassId::BoostDamage, "Petrify", AttackClassId::Petrify, "LowerDamage", AttackClassId::LowerDamage, "LowerInitiative", AttackClassId::LowerInitiative, "Poison", AttackClassId::Poison, "Frostbite", AttackClassId::Frostbite, "Revive", AttackClassId::Revive, "DrainOverflow", AttackClassId::DrainOverflow, "Cure", AttackClassId::Cure, "Summon", AttackClassId::Summon, "DrainLevel", AttackClassId::DrainLevel, "GiveAttack", AttackClassId::GiveAttack, "Doppelganger", AttackClassId::Doppelganger, "TransformSelf", AttackClassId::TransformSelf, "TransformOther", AttackClassId::TransformOther, "Blister", AttackClassId::Blister, "BestowWards", AttackClassId::BestowWards, "Shatter", AttackClassId::Shatter ); lua.new_enum("Source", "Weapon", AttackSourceId::Weapon, "Mind", AttackSourceId::Mind, "Life", AttackSourceId::Life, "Death", AttackSourceId::Death, "Fire", AttackSourceId::Fire, "Water", AttackSourceId::Water, "Earth", AttackSourceId::Earth, "Air", AttackSourceId::Air ); lua.new_enum("Reach", "All", AttackReachId::All, "Any", AttackReachId::Any, "Adjacent", AttackReachId::Adjacent ); lua.new_enum("Item", "Armor", ItemId::Armor, "Jewel", ItemId::Jewel, "Weapon", ItemId::Weapon, "Banner", ItemId::Banner, "PotionBoost", ItemId::PotionBoost, "PotionHeal", ItemId::PotionHeal, "PotionRevive", ItemId::PotionRevive, "PotionPermanent", ItemId::PotionPermanent, "Scroll", ItemId::Scroll, "Wand", ItemId::Wand, "Valuable", ItemId::Valuable, "Orb", ItemId::Orb, "Talisman", ItemId::Talisman, "TravelItem", ItemId::TravelItem, "Special", ItemId::Special ); lua.new_enum("Equipment", "Banner", EquippedItemIdx::Banner, "Tome", EquippedItemIdx::Tome, "Battle1", EquippedItemIdx::Battle1, "Battle2", EquippedItemIdx::Battle2, "Artifact1", EquippedItemIdx::Artifact1, "Artifact2", EquippedItemIdx::Artifact2, "Boots", EquippedItemIdx::Boots ); lua.new_enum("Immune", "NotImmune", ImmuneId::Notimmune, "Once", ImmuneId::Once, "Always", ImmuneId::Always ); lua.new_enum("DeathAnimation", "Human", DeathAnimationId::Human, "Heretic", DeathAnimationId::Heretic, "Dwarf", DeathAnimationId::Dwarf, "Undead", DeathAnimationId::Undead, "Neutral", DeathAnimationId::Neutral, "Dragon", DeathAnimationId::Dragon, "Ghost", DeathAnimationId::Ghost, "Elf", DeathAnimationId::Elf ); lua.new_enum("BattleStatus", "XpCounted", BattleStatus::XpCounted, "Dead", BattleStatus::Dead, "Paralyze", BattleStatus::Paralyze, "Petrify", BattleStatus::Petrify, "DisableLong", BattleStatus::DisableLong, "BoostDamageLvl1", BattleStatus::BoostDamageLvl1, "BoostDamageLvl2", BattleStatus::BoostDamageLvl2, "BoostDamageLvl3", BattleStatus::BoostDamageLvl3, "BoostDamageLvl4", BattleStatus::BoostDamageLvl4, "BoostDamageLong", BattleStatus::BoostDamageLong, "LowerDamageLvl1", BattleStatus::LowerDamageLvl1, "LowerDamageLvl2", BattleStatus::LowerDamageLvl2, "LowerDamageLong", BattleStatus::LowerDamageLong, "LowerInitiative", BattleStatus::LowerInitiative, "LowerInitiativeLong", BattleStatus::LowerInitiativeLong, "Poison", BattleStatus::Poison, "PoisonLong", BattleStatus::PoisonLong, "Frostbite", BattleStatus::Frostbite, "FrostbiteLong", BattleStatus::FrostbiteLong, "Blister", BattleStatus::Blister, "BlisterLong", BattleStatus::BlisterLong, "Cured", BattleStatus::Cured, "Transform", BattleStatus::Transform, "TransformLong", BattleStatus::TransformLong, "TransformSelf", BattleStatus::TransformSelf, "TransformDoppelganger", BattleStatus::TransformDoppelganger, "TransformDrainLevel", BattleStatus::TransformDrainLevel, "Summon", BattleStatus::Summon, "Retreated", BattleStatus::Retreated, "Retreat", BattleStatus::Retreat, "Hidden", BattleStatus::Hidden, "Defend", BattleStatus::Defend, "Unsummoned", BattleStatus::Unsummoned ); // clang-format on bindings::UnitView::bind(lua); bindings::UnitViewDummy::bind(lua); bindings::UnitImplView::bind(lua); bindings::UnitSlotView::bind(lua); bindings::DynUpgradeView::bind(lua); bindings::ScenarioView::bind(lua); bindings::LocationView::bind(lua); bindings::Point::bind(lua); bindings::IdView::bind(lua); bindings::ScenVariablesView::bind(lua); bindings::ScenarioVariableView::bind(lua); bindings::TileView::bind(lua); bindings::StackView::bind(lua); bindings::FortView::bind(lua); bindings::RuinView::bind(lua); bindings::GroupView::bind(lua); bindings::AttackView::bind(lua); bindings::CurrencyView::bind(lua); bindings::ItemBaseView::bind(lua); bindings::ItemView::bind(lua); bindings::PlayerView::bind(lua); bindings::ModifierView::bind(lua); bindings::BattleMsgDataView::bind(lua); bindings::DiplomacyView::bind(lua); bindings::FogView::bind(lua); lua.set_function("log", [](const std::string& message) { logDebug("luaDebug.log", message); }); } // https://sol2.readthedocs.io/en/latest/threading.html // Lua has no thread safety. sol does not force thread safety bottlenecks anywhere. // Treat access and object handling like you were dealing with a raw int reference (int&). sol::state& getLua() { static std::unique_ptr<sol::state> mainThreadLua; static std::unique_ptr<sol::state> workerThreadLua; auto& lua = std::this_thread::get_id() == mainThreadId ? mainThreadLua : workerThreadLua; if (lua == nullptr) { lua = std::make_unique<sol::state>(); lua->open_libraries(sol::lib::base, sol::lib::package, sol::lib::math, sol::lib::table, sol::lib::os, sol::lib::string); bindApi(*lua); } return *lua; } const std::string& getSource(const std::filesystem::path& path) { static std::unordered_map<std::filesystem::path, std::string, PathHash> sources; static std::mutex sourcesMutex; const std::lock_guard<std::mutex> lock(sourcesMutex); auto it = sources.find(path); if (it != sources.end()) return it->second; auto& source = sources[path]; source = readFile(path); return source; } bindings::ScenarioView getScenario() { return {getObjectMap()}; } sol::environment executeScript(const std::string& source, sol::protected_function_result& result, bool bindScenario) { auto& lua = getLua(); // Environment prevents cluttering of global namespace by scripts // making each script run isolated from others. sol::environment env{lua, sol::create, lua.globals()}; result = lua.safe_script(source, env, [](lua_State*, sol::protected_function_result pfr) { return pfr; }); if (bindScenario) { env["getScenario"] = &getScenario; } return env; } std::optional<sol::environment> executeScriptFile(const std::filesystem::path& path, bool alwaysExists, bool bindScenario) { if (!alwaysExists && !std::filesystem::exists(path)) return std::nullopt; const auto& source = getSource(path); if (source.empty()) { showErrorMessageBox(fmt::format("Failed to read '{:s}' script file.", path.string())); return std::nullopt; } sol::protected_function_result result; auto env = executeScript(source, result, bindScenario); if (!result.valid()) { const sol::error err = result; showErrorMessageBox(fmt::format("Failed to execute script '{:s}'.\n" "Reason: '{:s}'", path.string(), err.what())); return std::nullopt; } return {std::move(env)}; } std::optional<sol::function> getScriptFunction(const sol::environment& environment, const char* name, bool alwaysExists) { const sol::object object = environment[name]; const sol::type objectType = object.get_type(); if (objectType != sol::type::function) { if (alwaysExists) { showErrorMessageBox( fmt::format("'{:s}' is not a function, type: {:d}.", name, (int)objectType)); } return std::nullopt; } return object.as<sol::function>(); } std::optional<sol::function> getScriptFunction(const std::filesystem::path& path, const char* name, std::optional<sol::environment>& environment, bool alwaysExists, bool bindScenario) { environment = executeScriptFile(path, alwaysExists, bindScenario); if (!environment) return std::nullopt; auto function = getScriptFunction(*environment, name, false); if (!function && alwaysExists) { showErrorMessageBox( fmt::format("Could not find function '{:s}' in script '{:s}'.", name, path.string())); } return function; } std::optional<sol::protected_function> getProtectedScriptFunction( const sol::environment& environment, const char* name, bool alwaysExists) { const sol::object object = environment[name]; const sol::type objectType = object.get_type(); if (objectType != sol::type::function) { if (alwaysExists) { showErrorMessageBox( fmt::format("'{:s}' is not a function, type: {:d}.", name, (int)objectType)); } return std::nullopt; } return object.as<sol::protected_function>(); } } // namespace hooks
15,100
C++
.cpp
399
30.370927
99
0.641551
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,925
modifgroup.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/modifgroup.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "modifgroup.h" #include "version.h" #include <array> namespace game::LModifGroupApi { // clang-format off static std::array<Categories, 4> cats = {{ // Akella Categories{ (LModifGroup*)0x83a388, (LModifGroup*)0x83a398, (LModifGroup*)0x83a3a8, }, // Russobit Categories{ (LModifGroup*)0x83a388, (LModifGroup*)0x83a398, (LModifGroup*)0x83a3a8, }, // Gog Categories{ (LModifGroup*)0x838338, (LModifGroup*)0x838348, (LModifGroup*)0x838358, }, // Scenario Editor Categories{ (LModifGroup*)0x665e70, (LModifGroup*)0x665e80, (LModifGroup*)0x665e90, }, }}; static std::array<void*, 4> vftables = {{ // Akella (void*)0x6ea68c, // Russobit (void*)0x6ea68c, // Gog (void*)0x6e862c, // Scenario Editor (void*)0x5defa4, }}; // clang-format on Categories& categories() { return cats[static_cast<int>(hooks::gameVersion())]; } void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::LModifGroupApi namespace game::LModifGroupTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x59786a, (Api::Init)0x5979ba, (Api::ReadCategory)0x597a32, (Api::InitDone)0x597975, (Api::FindCategoryById)0x58af3b, }, // Russobit Api{ (Api::Constructor)0x59786a, (Api::Init)0x5979ba, (Api::ReadCategory)0x597a32, (Api::InitDone)0x597975, (Api::FindCategoryById)0x58af3b, }, // Gog Api{ (Api::Constructor)0x59698f, (Api::Init)0x596adf, (Api::ReadCategory)0x596b57, (Api::InitDone)0x596a9a, (Api::FindCategoryById)0x58a0a7, }, // Scenario Editor Api{ (Api::Constructor)0x541029, (Api::Init)0x541179, (Api::ReadCategory)0x5411f1, (Api::InitDone)0x541134, (Api::FindCategoryById)0x535ccb, }, }}; static std::array<void*, 4> vftables = {{ // Akella (void*)0x6eba5c, // Russobit (void*)0x6eba5c, // Gog (void*)0x6e99fc, // Scenario Editor (void*)0x5dfe8c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::LModifGroupTableApi
3,291
C++
.cpp
125
21.632
72
0.657469
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,926
custommodifierfunctions.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/custommodifierfunctions.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "custommodifierfunctions.h" #include "currencyview.h" #include "idview.h" #include "scripts.h" #include "unitimplview.h" #include "unitview.h" #include "utils.h" namespace hooks { CustomModifierFunctions::CustomModifierFunctions(const std::string& scriptFileName) { environment = executeScriptFile(modifiersFolder() / scriptFileName, false, true); if (!environment) return; #define FUNCTION(_NAME_) this->##_NAME_ = getScriptFunction(env, #_NAME_); const auto& env = *environment; FUNCTION(onModifiersChanged) FUNCTION(canApplyToUnit) FUNCTION(canApplyToUnitType) FUNCTION(canApplyAsLowerSpell) FUNCTION(canApplyAsBoostSpell) FUNCTION(getModifierDisplay) FUNCTION(getModifierDescTxt) FUNCTION(getModifierIconName) FUNCTION(getNameTxt) FUNCTION(getDescTxt) FUNCTION(getHitPoint) FUNCTION(getArmor) FUNCTION(getDeathAnim) FUNCTION(getRegen) FUNCTION(getXpNext) FUNCTION(getXpKilled) FUNCTION(getImmuneToAttack) FUNCTION(getImmuneToSource) FUNCTION(getAtckTwice) FUNCTION(getEnrollCost) FUNCTION(getReviveCost) FUNCTION(getHealCost) FUNCTION(getTrainingCost) FUNCTION(getMovement) FUNCTION(hasMovementBonus) FUNCTION(getScout) FUNCTION(getLeadership) FUNCTION(getNegotiate) FUNCTION(hasAbility) FUNCTION(getFastRetreat) FUNCTION(getLowerCost) FUNCTION(getAttackId) FUNCTION(getAttack2Id) FUNCTION(getAltAttackId) FUNCTION(getAttackReach) FUNCTION(getAttackInitiative) FUNCTION(getAttackNameTxt) FUNCTION(getAttack2NameTxt) FUNCTION(getAttackDescTxt) FUNCTION(getAttack2DescTxt) FUNCTION(getAttackDamRatio) FUNCTION(getAttack2DamRatio) FUNCTION(getAttackDrRepeat) FUNCTION(getAttack2DrRepeat) FUNCTION(getAttackDrSplit) FUNCTION(getAttack2DrSplit) FUNCTION(getAttackCritDamage) FUNCTION(getAttack2CritDamage) FUNCTION(getAttackCritPower) FUNCTION(getAttack2CritPower) FUNCTION(getAttackClass) FUNCTION(getAttack2Class) FUNCTION(getAttackSource) FUNCTION(getAttack2Source) FUNCTION(getAttackPower) FUNCTION(getAttack2Power) FUNCTION(getAttackDamage) FUNCTION(getAttack2Damage) FUNCTION(getAttackHeal) FUNCTION(getAttack2Heal) FUNCTION(getAttackDrain) FUNCTION(getAttack2Drain) FUNCTION(getAttackLevel) FUNCTION(getAttack2Level) FUNCTION(getAttackInfinite) FUNCTION(getAttack2Infinite) FUNCTION(getAttackCritHit) FUNCTION(getAttack2CritHit) FUNCTION(getAttackWards) FUNCTION(getAttack2Wards) } } // namespace hooks
3,437
C++
.cpp
105
28.657143
85
0.778413
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,927
sitemerchantinterfhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/sitemerchantinterfhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "sitemerchantinterfhooks.h" #include "middragdropinterfhooks.h" #include "originalfunctions.h" #include "sitemerchantinterf.h" namespace hooks { void __fastcall siteMerchantInterfOnObjectChangedHooked(game::CSiteMerchantInterf* thisptr, int /*%edx*/, game::IMidScenarioObject* obj) { getOriginalFunctions().siteMerchantInterfOnObjectChanged(thisptr, obj); midDragDropInterfResetCurrentSource(&thisptr->dragDropInterf); } } // namespace hooks
1,389
C++
.cpp
31
39.225806
91
0.72136
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,928
netmsgmapentry.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netmsgmapentry.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netmsgmapentry.h" #include "version.h" #include <array> namespace game::CNetMsgMapEntryApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::AllocateEntry<Api::MenusAnsInfoCallback>)0x4f1053, (Api::AllocateEntry<Api::GameVersionCallback>)0x4f107a, }, // Russobit Api{ (Api::AllocateEntry<Api::MenusAnsInfoCallback>)0x4f1053, (Api::AllocateEntry<Api::GameVersionCallback>)0x4f107a, }, // Gog Api{ (Api::AllocateEntry<Api::MenusAnsInfoCallback>)0x4f049f, (Api::AllocateEntry<Api::GameVersionCallback>)0x4F04C6, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CNetMsgMapEntryApi
1,597
C++
.cpp
46
31.326087
72
0.727038
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,929
musicfader.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/musicfader.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "musicfader.h" #include "version.h" #include <array> namespace game::CMusicFaderApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Get)0x5b065e, (Api::HasEventId)0x5b0c33, (Api::Callback)0x5b0b6d, }, // Russobit Api{ (Api::Get)0x5b065e, (Api::HasEventId)0x5b0c33, (Api::Callback)0x5b0b6d, }, // Gog Api{ (Api::Get)0x5af952, (Api::HasEventId)0x5aff27, (Api::Callback)0x5afe61, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMusicFaderApi
1,486
C++
.cpp
49
26.591837
72
0.695531
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,930
commandmsg.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/commandmsg.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "commandmsg.h" #include "version.h" #include <array> namespace game::CCommandMsgApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Destructor)0x47b64d, }, // Russobit Api{ (Api::Destructor)0x47b64d, }, // Gog Api{ (Api::Destructor)0x47b184, }, // Scenario Editor Api{ (Api::Destructor)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CCommandMsgApi
1,377
C++
.cpp
47
26.042553
72
0.704906
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,931
midmusic.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midmusic.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midmusic.h" #include "version.h" #include <array> namespace game::CMidMusicApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::FreeStrings)0x5ab139, (Api::PlayFile)0x5aa9d6, (Api::PlayBattleTrack)0x5aab4f, (Api::PlayCapitalTrack)0x5aaf31 }, // Russobit Api{ (Api::FreeStrings)0x5ab139, (Api::PlayFile)0x5aa9d6, (Api::PlayBattleTrack)0x5aab4f, (Api::PlayCapitalTrack)0x5aaf31 }, // Gog Api{ (Api::FreeStrings)0x5aa3c1, (Api::PlayFile)0x5a9c5e, (Api::PlayBattleTrack)0x5a9dd7, (Api::PlayCapitalTrack)0x5aa1b9 } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidMusicApi
1,638
C++
.cpp
52
27.461538
72
0.701455
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,932
midunitdescriptor.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midunitdescriptor.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midunitdescriptor.h" #include "version.h" #include <array> namespace game::CMidUnitDescriptorApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x57e871, (Api::GetSoldier)0x57eda2, (Api::GetAttack)0x57edb8, (Api::GetAltAttack)0x57ee00, }, // Russobit Api{ (Api::Constructor)0x57e871, (Api::GetSoldier)0x57eda2, (Api::GetAttack)0x57edb8, (Api::GetAltAttack)0x57ee00, }, // Gog Api{ (Api::Constructor)0x57df2c, (Api::GetSoldier)0x57e45d, (Api::GetAttack)0x57e473, (Api::GetAltAttack)0x57e4bb, }, // Scenario Editor Api{ (Api::Constructor)0x4cfcb5, (Api::GetSoldier)0x4d01e6, (Api::GetAttack)0x4d01fc, (Api::GetAltAttack)0x4d0244, }, }}; static std::array<IEncUnitDescriptorVftable*, 4> vftables = {{ // Akella (IEncUnitDescriptorVftable*)0x6e919c, // Russobit (IEncUnitDescriptorVftable*)0x6e919c, // Gog (IEncUnitDescriptorVftable*)0x6e713c, // Scenario Editor (IEncUnitDescriptorVftable*)0x5d869c, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const IEncUnitDescriptorVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidUnitDescriptorApi
2,236
C++
.cpp
73
26.342466
72
0.69898
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,933
umattack.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/umattack.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "umattack.h" #include "version.h" #include <array> namespace game::CUmAttackApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5a56b9, (Api::CopyConstructor)0x5a5939, (Api::DataConstructor)0x5a58a7, (Api::DataCopyConstructor)0x5a59ce, (Api::ReadData)0x5a57cf, }, // Russobit Api{ (Api::Constructor)0x5a56b9, (Api::CopyConstructor)0x5a5939, (Api::DataConstructor)0x5a58a7, (Api::DataCopyConstructor)0x5a59ce, (Api::ReadData)0x5a57cf, }, // Gog Api{ (Api::Constructor)0x5a4949, (Api::CopyConstructor)0x5a4bc9, (Api::DataConstructor)0x5a4b37, (Api::DataCopyConstructor)0x5a4c5e, (Api::ReadData)0x5a4a5f, }, // Scenario Editor Api{ (Api::Constructor)0x54d852, (Api::CopyConstructor)0x54dad2, (Api::DataConstructor)0x54da40, (Api::DataCopyConstructor)0x54db67, (Api::ReadData)0x54d968, } }}; static std::array<Vftable, 4> vftables = {{ // Akella Vftable{ (IUsUnitVftable*)0x6ecfa4, (IUsSoldierVftable*)0x6ecf2c, (CUmModifierVftable*)0x6ecefc, }, // Russobit Vftable{ (IUsUnitVftable*)0x6ecfa4, (IUsSoldierVftable*)0x6ecf2c, (CUmModifierVftable*)0x6ecefc, }, // Gog Vftable{ (IUsUnitVftable*)0x6eaf44, (IUsSoldierVftable*)0x6eaecc, (CUmModifierVftable*)0x6eae9c, }, // Scenario Editor Vftable{ (IUsUnitVftable*)0x5e1164, (IUsSoldierVftable*)0x5e10ec, (CUmModifierVftable*)0x5e10bc, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } Vftable& vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CUmAttackApi
2,729
C++
.cpp
93
24.215054
72
0.675162
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,934
imagelayerlist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/imagelayerlist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "imagelayerlist.h" #include "version.h" #include <array> namespace game::ImageLayerListApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::PushBack)0x522151, (Api::Clear)0x522289, (Api::AddShieldImageLayer)0x5bca73, }, // Russobit Api{ (Api::PushBack)0x522151, (Api::Clear)0x522289, (Api::AddShieldImageLayer)0x5bca73, }, // Gog Api{ (Api::PushBack)0x524c10, (Api::Clear)0x407a04, (Api::AddShieldImageLayer)0x5bbb37, }, // Scenario Editor Api{ (Api::PushBack)0x55e5b7, (Api::Clear)0x5541ca, (Api::AddShieldImageLayer)0x55d8eb, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::ImageLayerListApi
1,675
C++
.cpp
55
26.363636
72
0.693498
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,935
streamutils.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/streamutils.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "streamutils.h" #include "game.h" #include "midgardstream.h" #include <fmt/format.h> namespace hooks { void streamTurn(game::IMidgardStream* stream, const char* fieldName, int* fieldValue) { using namespace game; const auto& fn = gameFunctions(); if (!fieldValue) { fn.throwScenarioException(fieldName, "StreamTurn: param"); return; // Mutes compiler warnings about possible deref of nullptr } int turn = 0; if (stream->vftable->writeMode(stream)) { turn = *fieldValue; } stream->vftable->streamInt(stream, fieldName, &turn); if (!fn.isTurnValid(turn)) { fn.throwScenarioException(fieldName, fmt::format("Scenario: Error invalid value {:d}", turn).c_str()); } *fieldValue = turn; } } // namespace hooks
1,644
C++
.cpp
43
34.069767
99
0.709171
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,936
playerincomehooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/playerincomehooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "playerincomehooks.h" #include "currency.h" #include "fortcategory.h" #include "fortification.h" #include "game.h" #include "gameutils.h" #include "log.h" #include "lordtype.h" #include "midgardid.h" #include "midgardobjectmap.h" #include "midplayer.h" #include "midscenvariables.h" #include "midvillage.h" #include "originalfunctions.h" #include "racecategory.h" #include "racetype.h" #include "settings.h" #include "utils.h" #include <algorithm> #include <array> #include <fmt/format.h> namespace hooks { game::Bank* __stdcall computePlayerDailyIncomeHooked(game::Bank* income, game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId) { using namespace game; getOriginalFunctions().computePlayerDailyIncome(income, objectMap, playerId); auto playerObj = objectMap->vftable->findScenarioObjectById(objectMap, playerId); if (!playerObj) { logError("mssProxyError.log", fmt::format("Could not find player {:s}", idToString(playerId))); return income; } const auto& races = RaceCategories::get(); auto player = static_cast<const CMidPlayer*>(playerObj); if (player->raceType->data->raceType.id == races.neutral->id) { // Skip neutrals return income; } //additional income for lord type const auto& globalApi = GlobalDataApi::get(); const auto lords = (*globalApi.getGlobalData())->lords; const auto lordType = (TLordType*)globalApi.findById(lords, &player->lordId); const auto lordId = lordType->data->lordCategory.id; int additionalLordIncome {}; switch (lordId) { case LordId::Warrior: additionalLordIncome = userSettings().additionalLordIncome.warrior; break; case LordId::Mage: additionalLordIncome = userSettings().additionalLordIncome.mage; break; case LordId::Diplomat: additionalLordIncome = userSettings().additionalLordIncome.guildmaster; break; } const int goldLordIncome{income->gold + additionalLordIncome}; BankApi::get().set(income, CurrencyType::Gold, std::clamp(goldLordIncome, 0, 9999)); auto variables{getScenarioVariables(objectMap)}; if (!variables || !variables->variables.length) { // No variables defined, skip return income; } const auto raceId = player->raceType->data->raceType.id; const char* racePrefix{}; if (raceId == races.human->id) { racePrefix = "EMPIRE_"; } else if (raceId == races.heretic->id) { racePrefix = "LEGIONS_"; } else if (raceId == races.dwarf->id) { racePrefix = "CLANS_"; } else if (raceId == races.undead->id) { racePrefix = "HORDES_"; } else if (raceId == races.elf->id) { racePrefix = "ELVES_"; } if (!racePrefix) { logError("mssProxyError.log", fmt::format("Trying to compute daily income for unknown race. " "LRace.dbf id: {:d}", raceId)); return income; } std::array<int, 6> cityIncome = {0, 0, 0, 0, 0, 0}; logDebug("cityIncome.log", fmt::format("Loop through {:d} scenario variables", variables->variables.length)); std::uint32_t listIndex{}; for (const auto& variable : variables->variables) { const auto& name = variable.second.name; // Additional income for specific race if (!strncmp(name, racePrefix, std::strlen(racePrefix))) { for (int i = 0; i < 6; ++i) { const auto expectedName{fmt::format("{:s}TIER_{:d}_CITY_INCOME", racePrefix, i)}; if (!strncmp(name, expectedName.c_str(), sizeof(name))) { cityIncome[i] += variable.second.value; break; } } } // Additional income for all races if (!strncmp(name, "TIER", 4)) { for (int i = 0; i < 6; ++i) { const auto expectedName{fmt::format("TIER_{:d}_CITY_INCOME", i)}; if (!strncmp(name, expectedName.c_str(), sizeof(name))) { cityIncome[i] += variable.second.value; break; } } } listIndex++; } logDebug("cityIncome.log", fmt::format("Loop done in {:d} iterations", listIndex)); if (std::all_of(std::begin(cityIncome), std::end(cityIncome), [](int value) { return value == 0; })) { return income; } auto getVillageIncome = [playerId, income, &cityIncome](const IMidScenarioObject* obj) { auto fortification = static_cast<const CFortification*>(obj); if (fortification->ownerId == *playerId) { auto vftable = static_cast<const CFortificationVftable*>(fortification->vftable); auto category = vftable->getCategory(fortification); if (category->id == FortCategories::get().village->id) { auto village = static_cast<const CMidVillage*>(fortification); const int gold{income->gold + cityIncome[village->tierLevel]}; BankApi::get().set(income, CurrencyType::Gold, std::clamp(gold, 0, 9999)); } } }; forEachScenarioObject(objectMap, IdType::Fortification, getVillageIncome); // Custom capital city income const int gold{income->gold + cityIncome[0]}; BankApi::get().set(income, CurrencyType::Gold, std::clamp(gold, 0, 9999)); return income; } } // namespace hooks
6,472
C++
.cpp
155
33.722581
97
0.629217
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,937
battleviewerinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/battleviewerinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "battleviewerinterf.h" #include "version.h" #include <array> namespace game::BattleViewerInterfApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::MarkAttackTargets)0x6340f5, (Api::IsUnitOnTheLeft)0x63e7f9, (Api::IsFlipped)0x63af35, (Api::GetBigFace)0x63b3c8, (Api::GetBigFace)0x63b349, (Api::GetUnitRect)0x630b54, (Api::GetUnitRect)0x633c79, (Api::GetBoolById)0x63fad0, (Api::GetBoolById)0x63faf0, (Api::GetBoolById)0x63f980, (Api::GetSelectedUnitId)0x64e04c, (Api::HighlightGroupFrame)0x64e289, (Api::UnknownMethod)0x64e17e, (Api::UnknownMethod2)0x64e204, (Api::UnknownMethod3)0x64e4dc, (Api::GetUnitAnimation)0x63b447, (Api::UpdateUnknown)0x639743, (Api::UpdateBattleItems)0x639990, (Api::CBattleViewerTargetDataSetConstructor)0x63f800, (Api::CBattleViewerTargetDataSetSetAttacker)0x63f890, (Api::Callback)0x6355ef, (Api::Callback)0x635664, (Api::CreateButtonFunctor)0x643370, (Api::UnknownMethod4)0x643040, (Api::FillTargetPositions)0x631f08, (Api::AddTargetUnitData)0x6388a7, (Api::SetCheckedForRightUnitsToggleButton)0x631ee1, (Api::UnknownMethod6)0x639858, (Api::UnknownMethod7)0x638f65, (Api::UpdateCursor)0x634fdf, (Api::UnknownMethod9)0x63adda, (Api::UnknownMethod10)0x639be9, (Api::UnknownMethod11)0x639e1e, (Api::UnknownMethod12)0x63a6df, }, // Russobit Api{ (Api::MarkAttackTargets)0x6340f5, (Api::IsUnitOnTheLeft)0x63e7f9, (Api::IsFlipped)0x63af35, (Api::GetBigFace)0x63b3c8, (Api::GetBigFace)0x63b349, (Api::GetUnitRect)0x630b54, (Api::GetUnitRect)0x633c79, (Api::GetBoolById)0x63fad0, (Api::GetBoolById)0x63faf0, (Api::GetBoolById)0x63f980, (Api::GetSelectedUnitId)0x64e04c, (Api::HighlightGroupFrame)0x64e289, (Api::UnknownMethod)0x64e17e, (Api::UnknownMethod2)0x64e204, (Api::UnknownMethod3)0x64e4dc, (Api::GetUnitAnimation)0x63b447, (Api::UpdateUnknown)0x639743, (Api::UpdateBattleItems)0x639990, (Api::CBattleViewerTargetDataSetConstructor)0x63f800, (Api::CBattleViewerTargetDataSetSetAttacker)0x63f890, (Api::Callback)0x6355ef, (Api::Callback)0x635664, (Api::CreateButtonFunctor)0x643370, (Api::UnknownMethod4)0x643040, (Api::FillTargetPositions)0x631f08, (Api::AddTargetUnitData)0x6388a7, (Api::SetCheckedForRightUnitsToggleButton)0x631ee1, (Api::UnknownMethod6)0x639858, (Api::UnknownMethod7)0x638f65, (Api::UpdateCursor)0x634fdf, (Api::UnknownMethod9)0x63adda, (Api::UnknownMethod10)0x639be9, (Api::UnknownMethod11)0x639e1e, (Api::UnknownMethod12)0x63a6df, }, // Gog Api{ (Api::MarkAttackTargets)0x632b35, (Api::IsUnitOnTheLeft)0x63d239, (Api::IsFlipped)0x639975, (Api::GetBigFace)0x639e08, (Api::GetBigFace)0x639d89, (Api::GetUnitRect)0x62f594, (Api::GetUnitRect)0x6326b9, (Api::GetBoolById)0x63e4c0, (Api::GetBoolById)0x63e4e0, (Api::GetBoolById)0x63e370, (Api::GetSelectedUnitId)0x64c98c, (Api::HighlightGroupFrame)0x64cbc9, (Api::UnknownMethod)0x64cabe, (Api::UnknownMethod2)0x64cb44, (Api::UnknownMethod3)0x64ce1c, (Api::GetUnitAnimation)0x639e87, (Api::UpdateUnknown)0x638183, (Api::UpdateBattleItems)0x6383d0, (Api::CBattleViewerTargetDataSetConstructor)0x63e1f0, (Api::CBattleViewerTargetDataSetSetAttacker)0x63e280, (Api::Callback)0x63402f, (Api::Callback)0x6340a4, (Api::CreateButtonFunctor)0x641bd0, (Api::UnknownMethod4)0x641890, (Api::FillTargetPositions)0x630948, (Api::AddTargetUnitData)0x6372e7, (Api::SetCheckedForRightUnitsToggleButton)0x630921, (Api::UnknownMethod6)0x638298, (Api::UnknownMethod7)0x6379a5, (Api::UpdateCursor)0x633a1f, (Api::UnknownMethod9)0x63981a, (Api::UnknownMethod10)0x638629, (Api::UnknownMethod11)0x63885e, (Api::UnknownMethod12)0x63911f, }, }}; static std::array<IBatViewerVftable*, 4> vftables = {{ // Akella (IBatViewerVftable*)0x6f4294, // Russobit (IBatViewerVftable*)0x6f4294, // Gog (IBatViewerVftable*)0x6f2244, // Scenario Editor (IBatViewerVftable*)nullptr, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const IBatViewerVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BattleViewerInterfApi
5,727
C++
.cpp
156
29.839744
72
0.685838
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,938
aigiveitemsaction.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/aigiveitemsaction.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "aigiveitemsaction.h" #include "version.h" #include <array> namespace game::CAiGiveItemsActionApi { // clang-format off static std::array<Vftable, 4> vftables = {{ // Akella Vftable{ (IAiTacticActionVftable*)0x6d2a24, (IAiReactionVftable*)0x6d29b4, }, // Russobit Vftable{ (IAiTacticActionVftable*)0x6d2a24, (IAiReactionVftable*)0x6d29b4, }, // Gog Vftable{ (IAiTacticActionVftable*)0x6d09c4, (IAiReactionVftable*)0x6d0954, }, // Scenario Editor Vftable{ (IAiTacticActionVftable*)nullptr, (IAiReactionVftable*)nullptr, }, }}; // clang-format on const Vftable& vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CAiGiveItemsActionApi
1,617
C++
.cpp
51
28
72
0.720692
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,939
stringpairarrayptr.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/stringpairarrayptr.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stringpairarrayptr.h" #include "version.h" #include <array> namespace game::StringPairArrayPtrApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x6092ac, (Api::SetData)0x5e475a, }, // Russobit Api{ (Api::Constructor)0x6092ac, (Api::SetData)0x5e475a, }, // Gog Api{ (Api::Constructor)0x607d76, (Api::SetData)0x5e34a4, }, // Scenario Editor Api{ (Api::Constructor)0x503f4b, (Api::SetData)0x4dcd74, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::StringPairArrayPtrApi
1,532
C++
.cpp
51
26.313725
72
0.699661
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,940
mqimage2surface16.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/mqimage2surface16.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mqimage2surface16.h" #include "version.h" #include <array> namespace game::CMqImage2Surface16Api { // clang-format off std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x6704f0, }, // Russobit Api{ (Api::Constructor)0x6704f0, }, // Gog Api{ (Api::Constructor)0x66ed90, }, // Scenario Editor Api{ (Api::Constructor)0x4af530, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMqImage2Surface16Api
1,395
C++
.cpp
47
26.425532
72
0.709605
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,941
mainview2hooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/mainview2hooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mainview2hooks.h" #include "dialoginterf.h" #include "gameimages.h" #include "gameutils.h" #include "isolayers.h" #include "log.h" #include "mainview2.h" #include "mapgraphics.h" #include "phasegame.h" #include "scenarioinfo.h" #include "togglebutton.h" #include <fmt/format.h> namespace hooks { static bool gridVisible{false}; static void showGrid(int mapSize) { using namespace game; const auto& imagesApi = GameImagesApi::get(); GameImagesPtr imagesPtr; imagesApi.getGameImages(&imagesPtr); auto images = *imagesPtr.data; const auto& mapGraphics{MapGraphicsApi::get()}; for (int x = 0; x < mapSize; ++x) { for (int y = 0; y < mapSize; ++y) { auto gridImage{imagesApi.getImage(images->isoCmon, "GRID", 0, true, images->log)}; if (!gridImage) { continue; } const CMqPoint mapPosition{x, y}; mapGraphics.showImageOnMap(&mapPosition, isoLayers().grid, gridImage, 0, 0); } } imagesApi.createOrFreeGameImages(&imagesPtr, nullptr); } static void hideGrid() { using namespace game; MapGraphicsApi::get().hideLayerImages(isoLayers().grid); } static void __fastcall mainView2OnToggleGrid(game::CMainView2* thisptr, int /*%edx*/, bool toggleOn, game::CToggleButton*) { gridVisible = toggleOn; if (gridVisible) { auto objectMap{game::CPhaseApi::get().getObjectMap(&thisptr->phaseGame->phase)}; auto scenarioInfo{getScenarioInfo(objectMap)}; showGrid(scenarioInfo->mapSize); return; } hideGrid(); } void __fastcall mainView2ShowIsoDialogHooked(game::CMainView2* thisptr, int /*%edx*/) { using namespace game; const auto& mainViewApi{CMainView2Api::get()}; mainViewApi.showDialog(thisptr, nullptr); static const char buttonName[]{"TOG_GRID"}; const auto& dialogApi{CDialogInterfApi::get()}; auto dialog{thisptr->dialogInterf}; if (!dialogApi.findControl(dialog, buttonName)) { // Grid button was not added to Interf.dlg, skip return; } auto toggleButton{dialogApi.findToggleButton(dialog, buttonName)}; if (!toggleButton) { // Control was found, but it is not CToggleButton logError("mssProxyError.log", fmt::format("{:s} in {:s} must be a toggle button", buttonName, dialog->data->dialogName)); return; } using ButtonCallback = CMainView2Api::Api::ToggleButtonCallback; ButtonCallback callback{}; callback.callback = (ButtonCallback::Callback)&mainView2OnToggleGrid; SmartPointer functor; mainViewApi.createToggleButtonFunctor(&functor, 0, thisptr, &callback); const auto& buttonApi{CToggleButtonApi::get()}; buttonApi.assignFunctor(dialog, buttonName, dialog->data->dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); buttonApi.setChecked(toggleButton, gridVisible); } } // namespace hooks
3,957
C++
.cpp
101
32.881188
94
0.681474
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,942
stringandid.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/stringandid.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stringandid.h" #include "version.h" #include <array> namespace game::StringAndIdApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetString)0x60778a, }, // Russobit Api{ (Api::SetString)0x60778a, }, // Gog Api{ (Api::SetString)0x60627b, }, // Scenario Editor Api{ (Api::SetString)0x4fc04b, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::StringAndIdApi
1,375
C++
.cpp
47
26
72
0.70446
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,943
midevent.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midevent.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midevent.h" #include "version.h" #include <array> namespace game::CMidEventApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::AddCondition)nullptr, (Api::AddEffect)nullptr, (Api::CheckValid)nullptr, (Api::AffectsPlayer)0x444f2f, }, // Russobit Api{ (Api::AddCondition)nullptr, (Api::AddEffect)nullptr, (Api::CheckValid)nullptr, (Api::AffectsPlayer)0x444f2f, }, // Gog Api{ (Api::AddCondition)nullptr, (Api::AddEffect)nullptr, (Api::CheckValid)nullptr, (Api::AffectsPlayer)0x444b33, }, // Scenario Editor Api{ (Api::AddCondition)0x4f8ed0, (Api::AddEffect)0x4f8f22, (Api::CheckValid)0x45b324, (Api::AffectsPlayer)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidEventApi
1,797
C++
.cpp
59
26.033898
72
0.684362
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,944
pathinfolist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/pathinfolist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pathinfolist.h" #include "version.h" #include <array> namespace game::PathInfoListApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x4cdc3b, (Api::PopulateFromPath)0x4cd9df, (Api::FreeNodes)0x4cdca8, (Api::FreeNode)0x4c8755, }, // Russobit Api{ (Api::Constructor)0x4cdc3b, (Api::PopulateFromPath)0x4cd9df, (Api::FreeNodes)0x4cdca8, (Api::FreeNode)0x4c8755, }, // Gog Api{ (Api::Constructor)0x4cd334, (Api::PopulateFromPath)0x4cd0d8, (Api::FreeNodes)0x44df27, (Api::FreeNode)0x5215fc, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::PathInfoListApi
1,633
C++
.cpp
52
27.365385
72
0.698604
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,945
draganddropinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/draganddropinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "draganddropinterf.h" #include "version.h" #include <array> namespace game::CDragAndDropInterfApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::GetDialog)0x56cea4 }, // Russobit Api{ (Api::GetDialog)0x56cea4 }, // Gog Api{ (Api::GetDialog)0x56c54e } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CDragAndDropInterfApi
1,317
C++
.cpp
43
27.627907
72
0.720252
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,946
exchangeinterfhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/exchangeinterfhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "exchangeinterfhooks.h" #include "exchangeinterf.h" #include "middragdropinterfhooks.h" #include "originalfunctions.h" namespace hooks { void __fastcall exchangeInterfOnObjectChangedHooked(game::CExchangeInterf* thisptr, int /*%edx*/, game::IMidScenarioObject* obj) { getOriginalFunctions().exchangeInterfOnObjectChanged(thisptr, obj); midDragDropInterfResetCurrentSource(&thisptr->dragDropInterf); } } // namespace hooks
1,361
C++
.cpp
31
38.580645
83
0.721509
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,947
ummodifier.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/ummodifier.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ummodifier.h" #include "version.h" #include <array> namespace game::CUmModifierApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5a9dd4, (Api::CopyConstructor)0x5a9e37, (Api::Destructor)0x5a9e70, (Api::SetPrev)0x5a9ea9, }, // Russobit Api{ (Api::Constructor)0x5a9dd4, (Api::CopyConstructor)0x5a9e37, (Api::Destructor)0x5a9e70, (Api::SetPrev)0x5a9ea9, }, // Gog Api{ (Api::Constructor)0x5a906a, (Api::CopyConstructor)0x5a90cd, (Api::Destructor)0x5a9106, (Api::SetPrev)0x5a9138, }, // Scenario Editor Api{ (Api::Constructor)0x53ec7e, (Api::CopyConstructor)0x53ece1, (Api::Destructor)0x53ed1a, (Api::SetPrev)0x53ed4c, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CUmModifierApi
1,809
C++
.cpp
59
26.237288
72
0.687106
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,948
roomservercreation.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/roomservercreation.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "roomservercreation.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "lobbyclient.h" #include "log.h" #include "mempool.h" #include "menubase.h" #include "menuflashwait.h" #include "netcustomplayerclient.h" #include "netcustomplayerserver.h" #include "netcustomservice.h" #include "netcustomsession.h" #include "originalfunctions.h" #include "roomscallback.h" #include "settings.h" #include "utils.h" #include <fmt/format.h> namespace hooks { game::CMenuFlashWait* menuWaitServer{nullptr}; game::CMenuBase* menuBase{nullptr}; static bool loadingScenario{false}; static std::string roomPassword{}; static void hideWaitMenu() { if (menuWaitServer) { hideInterface(menuWaitServer); menuWaitServer->vftable->destructor(menuWaitServer, 1); menuWaitServer = nullptr; } } static void serverCreationError(const std::string& message) { hideWaitMenu(); showMessageBox(message); } /** * Handles host player client connection to player server. * Sets up host player net ids and executes original game logic from CMenuNewSkirmish BTN_LOAD. */ class HostClientConnectCallbacks : public NetworkPeerCallbacks { public: HostClientConnectCallbacks() = default; ~HostClientConnectCallbacks() override = default; void onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) override { auto service = getNetService(); auto hostPlayer = service->session->players.front(); if (type == ID_CONNECTION_ATTEMPT_FAILED) { serverCreationError("Host player failed to connect to player server"); // Unsubscribe from callbacks hostPlayer->player.netPeer.removeCallback(this); return; } if (type != ID_CONNECTION_REQUEST_ACCEPTED) { return; } // Unsubscribe from callbacks hostPlayer->player.netPeer.removeCallback(this); hideWaitMenu(); // Setup host player netId and remember serverId auto& player = hostPlayer->player; player.netId = SLNet::RakNetGUID::ToUint32(peer->GetMyGUID()); auto serverGuid = peer->GetGuidFromSystemAddress(packet->systemAddress); hostPlayer->serverId = SLNet::RakNetGUID::ToUint32(serverGuid); hostPlayer->setupPacketCallbacks(); logDebug("lobby.log", fmt::format("Host player netId 0x{:x} connected to player server netId 0x{:x}", player.netId, hostPlayer->serverId)); if (menuBase) { const auto& fn = getOriginalFunctions(); if (loadingScenario) { logDebug("lobby.log", "Proceed to next screen as CMenuLoadSkirmishMulti"); fn.menuLoadSkirmishMultiLoadScenario((game::CMenuLoad*)menuBase); } else { logDebug("lobby.log", "Proceed to next screen as CMenuNewSkirmishMulti"); fn.menuNewSkirmishLoadScenario(menuBase); } } else { logDebug("lobby.log", "MenuBase is null somehow!"); } } }; static HostClientConnectCallbacks hostClientConnectCallbacks; static void createHostPlayer() { auto service = getNetService(); logDebug("lobby.log", "Creating host player client"); // Connect player client to local player server, wait response. // Use dummy name, it will be set properly later in session::CreateClient method auto hostPlayer = createCustomHostPlayerClient(service->session, "Host player"); service->session->players.push_back(hostPlayer); logDebug("lobby.log", "Host player client waits for player server connection response"); hostPlayer->player.netPeer.addCallback(&hostClientConnectCallbacks); } /** * Handles response to room creation request. * Creates host player. */ class RoomsCreateServerCallback : public SLNet::RoomsCallback { public: RoomsCreateServerCallback() = default; ~RoomsCreateServerCallback() override = default; void CreateRoom_Callback(const SLNet::SystemAddress& senderAddress, SLNet::CreateRoom_Func* callResult) override { logDebug("lobby.log", "Room creation response received"); // Unsubscribe from callbacks removeRoomsCallback(this); if (callResult->resultCode != SLNet::REC_SUCCESS) { auto result{SLNet::RoomsErrorCodeDescription::ToEnglish(callResult->resultCode)}; const auto msg{fmt::format("Could not create a room.\nReason: {:s}", result)}; logDebug("lobby.log", msg); serverCreationError(msg); return; } logDebug("lobby.log", "Player server connected to lobby server, nat client attached"); createHostPlayer(); } }; static RoomsCreateServerCallback roomServerCallback; /** * Handles player server connection to lobby server. * Attaches NAT client and requests lobby server to create a room on successfull connection. */ class ServerConnectCallbacks : public NetworkPeerCallbacks { public: ServerConnectCallbacks() = default; ~ServerConnectCallbacks() override = default; void onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) override { auto service = getNetService(); auto playerServer{service->session->server}; if (type == ID_CONNECTION_ATTEMPT_FAILED) { // Unsubscribe from callbacks playerServer->player.netPeer.removeCallback(this); serverCreationError("Failed to connect player server to NAT server"); return; } if (type != ID_CONNECTION_REQUEST_ACCEPTED) { return; } // Unsubscribe from callbacks playerServer->player.netPeer.removeCallback(this); addRoomsCallback(&roomServerCallback); const char* password{roomPassword.empty() ? nullptr : roomPassword.c_str()}; // Request room creation and wait for lobby server response if (!tryCreateRoom(service->session->name.c_str(), peer->GetMyGUID().ToString(), password)) { serverCreationError("Failed to request room creation"); return; } logDebug("lobby.log", "Waiting for room creation response"); peer->AttachPlugin(&playerServer->natClient); playerServer->natClient.FindRouterPortStride(packet->systemAddress); } }; static ServerConnectCallbacks serverConnectCallbacks; static void createSessionAndServer(const char* sessionName) { logDebug("lobby.log", "Create session"); auto service = getNetService(); service->session = (CNetCustomSession*)createCustomNetSession(service, sessionName, true); logDebug("lobby.log", "Create player server"); // NetSession and NetSystem will be set later by the game in CMidServerStart() auto playerServer = (CNetCustomPlayerServer*)createCustomPlayerServer(service->session, nullptr, nullptr); service->session->server = playerServer; const auto& lobbySettings = userSettings().lobby; const auto& serverIp = lobbySettings.server.ip; const auto& serverPort = lobbySettings.server.port; auto peer = playerServer->getPeer(); // Connect player server to lobby server, wait response. // We need this connection for NAT punchthrough if (peer->Connect(serverIp.c_str(), serverPort, nullptr, 0) != SLNet::CONNECTION_ATTEMPT_STARTED) { const std::string msg{"Failed to connect server player to lobby server"}; logError("lobby.log", msg); serverCreationError(msg); return; } logDebug("lobby.log", "Player server waits for response from lobby server"); playerServer->player.netPeer.addCallback(&serverConnectCallbacks); } void startRoomAndServerCreation(game::CMenuBase* menu, bool loadScenario) { using namespace game; menuWaitServer = (CMenuFlashWait*)Memory::get().allocate(sizeof(CMenuFlashWait)); CMenuFlashWaitApi::get().constructor(menuWaitServer); showInterface(menuWaitServer); logDebug("lobby.log", "Create session and player server"); menuBase = menu; loadingScenario = loadScenario; auto& menuApi = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuApi.getDialogInterface(menu); auto password = dialogApi.findEditBox(dialog, "EDIT_PASSWORD"); const auto& passwordString{password->data->editBoxData.inputString}; if (!passwordString.length) { roomPassword.clear(); } else { roomPassword = passwordString.string; } auto editGame = dialogApi.findEditBox(dialog, "EDIT_GAME"); createSessionAndServer(editGame->data->editBoxData.inputString.string); } } // namespace hooks
9,802
C++
.cpp
231
35.588745
100
0.695849
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,949
netmsghooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netmsghooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netmsghooks.h" #include "dynamiccast.h" #include "mqstream.h" #include "netmsgutils.h" #include "originalfunctions.h" #include "stackbattleactionmsg.h" namespace hooks { void __fastcall stackBattleActionMsgSerializeHooked(game::CStackBattleActionMsg* thisptr, int /*%edx*/, game::CMqStream* stream) { serializeMsgWithBattleMsgData(thisptr, &thisptr->battleMsgData, getOriginalFunctions().stackBattleActionMsgSerialize, stream); } void __fastcall netMsgDtorHooked(game::CNetMsg* thisptr, int /*%edx*/) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; CStackBattleActionMsg* stackBattleActionMsg = (CStackBattleActionMsg*) dynamicCast(thisptr, 0, rtti.CNetMsgType, rtti.CStackBattleActionMsgType, 0); if (stackBattleActionMsg != nullptr) { BattleMsgDataApi::get().destructor(&stackBattleActionMsg->battleMsgData); } getOriginalFunctions().netMsgDtor(thisptr); } } // namespace hooks
1,962
C++
.cpp
45
37.911111
96
0.713986
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,950
batattackbestowwards.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batattackbestowwards.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batattackbestowwards.h" #include "version.h" #include <array> namespace game::CBatAttackBestowWardsApi { // clang-format off static std::array<IBatAttackVftable*, 4> vftables = {{ // Akella (IBatAttackVftable*)0x6f4ffc, // Russobit (IBatAttackVftable*)0x6f4ffc, // Gog (IBatAttackVftable*)0x6f2fac, // Scenario Editor (IBatAttackVftable*)nullptr, }}; // clang-format on IBatAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CBatAttackBestowWardsApi
1,369
C++
.cpp
39
32.615385
72
0.752453
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,951
unitstovalidate.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitstovalidate.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitstovalidate.h" namespace hooks { static UnitsToValidate units; UnitsToValidate& getUnitsToValidate() { return units; } } // namespace hooks
976
C++
.cpp
26
35.538462
72
0.768254
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,952
customattackhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/customattackhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "customattackhooks.h" #include "attackclasscat.h" #include "attackimpl.h" #include "attackutils.h" #include "batattacktransformself.h" #include "batattackutils.h" #include "customattack.h" #include "customattacks.h" #include "customattackutils.h" #include "dbfaccess.h" #include "dbtable.h" #include "dynamiccast.h" #include "game.h" #include "gameutils.h" #include "globaldata.h" #include "idlistutils.h" #include "immunecat.h" #include "itembattle.h" #include "log.h" #include "mempool.h" #include "midstack.h" #include "midunitgroup.h" #include "originalfunctions.h" #include "scripts.h" #include "settings.h" #include "targetslistutils.h" #include "unitutils.h" #include "ussoldier.h" #include "usstackleader.h" #include "usunitimpl.h" #include "utils.h" #include <fmt/format.h> #include <limits> namespace hooks { game::LAttackClass customAttackClass{}; game::LAttackClassTable* __fastcall attackClassTableCtorHooked(game::LAttackClassTable* thisptr, int /*%edx*/, const char* globalsFolderPath, void* codeBaseEnvProxy) { static const char dbfFileName[] = "LAttC.dbf"; static const char customCategoryName[] = "L_CUSTOM"; logDebug("newAttackType.log", "LAttackClassTable c-tor hook started"); const auto dbfFilePath{std::filesystem::path(globalsFolderPath) / dbfFileName}; bool customAttackExists = utils::dbValueExists(dbfFilePath, "TEXT", customCategoryName); if (customAttackExists) logDebug("newAttackType.log", "Found custom attack category"); using namespace game; thisptr->bgn = nullptr; thisptr->end = nullptr; thisptr->allocatedMemEnd = nullptr; thisptr->allocator = nullptr; thisptr->vftable = LAttackClassTableApi::vftable(); const auto& table = LAttackClassTableApi::get(); table.init(thisptr, codeBaseEnvProxy, globalsFolderPath, dbfFileName); auto& categories = AttackClassCategories::get(); table.readCategory(categories.paralyze, thisptr, "L_PARALYZE", dbfFileName); table.readCategory(categories.petrify, thisptr, "L_PETRIFY", dbfFileName); table.readCategory(categories.damage, thisptr, "L_DAMAGE", dbfFileName); table.readCategory(categories.drain, thisptr, "L_DRAIN", dbfFileName); table.readCategory(categories.heal, thisptr, "L_HEAL", dbfFileName); table.readCategory(categories.fear, thisptr, "L_FEAR", dbfFileName); table.readCategory(categories.boostDamage, thisptr, "L_BOOST_DAMAGE", dbfFileName); table.readCategory(categories.lowerDamage, thisptr, "L_LOWER_DAMAGE", dbfFileName); table.readCategory(categories.lowerInitiative, thisptr, "L_LOWER_INITIATIVE", dbfFileName); table.readCategory(categories.poison, thisptr, "L_POISON", dbfFileName); table.readCategory(categories.frostbite, thisptr, "L_FROSTBITE", dbfFileName); table.readCategory(categories.revive, thisptr, "L_REVIVE", dbfFileName); table.readCategory(categories.drainOverflow, thisptr, "L_DRAIN_OVERFLOW", dbfFileName); table.readCategory(categories.cure, thisptr, "L_CURE", dbfFileName); table.readCategory(categories.summon, thisptr, "L_SUMMON", dbfFileName); table.readCategory(categories.drainLevel, thisptr, "L_DRAIN_LEVEL", dbfFileName); table.readCategory(categories.giveAttack, thisptr, "L_GIVE_ATTACK", dbfFileName); table.readCategory(categories.doppelganger, thisptr, "L_DOPPELGANGER", dbfFileName); table.readCategory(categories.transformSelf, thisptr, "L_TRANSFORM_SELF", dbfFileName); table.readCategory(categories.transformOther, thisptr, "L_TRANSFORM_OTHER", dbfFileName); table.readCategory(categories.blister, thisptr, "L_BLISTER", dbfFileName); table.readCategory(categories.bestowWards, thisptr, "L_BESTOW_WARDS", dbfFileName); table.readCategory(categories.shatter, thisptr, "L_SHATTER", dbfFileName); if (customAttackExists) { table.readCategory(&customAttackClass, thisptr, customCategoryName, dbfFileName); } table.initDone(thisptr); logDebug("newAttackType.log", "LAttackClassTable c-tor hook finished"); return thisptr; } game::LAttackSourceTable* __fastcall attackSourceTableCtorHooked(game::LAttackSourceTable* thisptr, int /*%edx*/, const char* globalsFolderPath, void* codeBaseEnvProxy) { using namespace game; logDebug("customAttacks.log", "LAttackSourceTable c-tor hook started"); static const char dbfFileName[] = "LAttS.dbf"; fillCustomAttackSources(std::filesystem::path(globalsFolderPath) / dbfFileName); thisptr->bgn = nullptr; thisptr->end = nullptr; thisptr->allocatedMemEnd = nullptr; thisptr->allocator = nullptr; thisptr->vftable = LAttackSourceTableApi::vftable(); const auto& table = LAttackSourceTableApi::get(); auto& sources = AttackSourceCategories::get(); table.init(thisptr, codeBaseEnvProxy, globalsFolderPath, dbfFileName); table.readCategory(sources.weapon, thisptr, "L_WEAPON", dbfFileName); table.readCategory(sources.mind, thisptr, "L_MIND", dbfFileName); table.readCategory(sources.life, thisptr, "L_LIFE", dbfFileName); table.readCategory(sources.death, thisptr, "L_DEATH", dbfFileName); table.readCategory(sources.fire, thisptr, "L_FIRE", dbfFileName); table.readCategory(sources.water, thisptr, "L_WATER", dbfFileName); table.readCategory(sources.air, thisptr, "L_AIR", dbfFileName); table.readCategory(sources.earth, thisptr, "L_EARTH", dbfFileName); for (auto& custom : getCustomAttacks().sources) { logDebug("customAttacks.log", fmt::format("Reading custom attack source {:s}", custom.text)); table.readCategory(&custom.source, thisptr, custom.text.c_str(), dbfFileName); } table.initDone(thisptr); logDebug("customAttacks.log", "LAttackSourceTable c-tor hook finished"); return thisptr; } game::LAttackReachTable* __fastcall attackReachTableCtorHooked(game::LAttackReachTable* thisptr, int /*%edx*/, const char* globalsFolderPath, void* codeBaseEnvProxy) { using namespace game; logDebug("customAttacks.log", "LAttackReachTable c-tor hook started"); static const char dbfFileName[] = "LAttR.dbf"; fillCustomAttackReaches(std::filesystem::path(globalsFolderPath) / dbfFileName); thisptr->bgn = nullptr; thisptr->end = nullptr; thisptr->allocatedMemEnd = nullptr; thisptr->allocator = nullptr; thisptr->vftable = LAttackReachTableApi::vftable(); const auto& table = LAttackReachTableApi::get(); const auto& reaches = AttackReachCategories::get(); table.init(thisptr, codeBaseEnvProxy, globalsFolderPath, dbfFileName); table.readCategory(reaches.all, thisptr, "L_ALL", dbfFileName); table.readCategory(reaches.any, thisptr, "L_ANY", dbfFileName); table.readCategory(reaches.adjacent, thisptr, "L_ADJACENT", dbfFileName); for (auto& custom : getCustomAttacks().reaches) { logDebug("customAttacks.log", fmt::format("Reading custom attack reach {:s}", custom.text)); table.readCategory(&custom.reach, thisptr, custom.text.c_str(), dbfFileName); } table.initDone(thisptr); logDebug("customAttacks.log", "LAttackReachTable c-tor hook finished"); return thisptr; } game::CAttackImpl* __fastcall attackImplCtorHooked(game::CAttackImpl* thisptr, int /*%edx*/, const game::CDBTable* dbTable, const game::GlobalData** globalData) { using namespace game; const auto& attackImpl = CAttackImplApi::get(); thisptr->data = (CAttackImplData*)Memory::get().allocate(sizeof(CAttackImplData)); attackImpl.initData(thisptr->data); thisptr->vftable = CAttackImplApi::vftable(); const auto& db = CDBTableApi::get(); db.readId(&thisptr->id, dbTable, "ATT_ID"); auto gData = *globalData; auto data = thisptr->data; db.readText(&data->name, dbTable, "NAME_TXT", gData->texts); db.readText(&data->description, dbTable, "DESC_TXT", gData->texts); db.findAttackClass(&data->attackClass, dbTable, "CLASS", gData->attackClasses); db.findAttackSource(&data->attackSource, dbTable, "SOURCE", gData->attackSources); db.findAttackReach(&data->attackReach, dbTable, "REACH", gData->attackReaches); db.readInitiative(&data->initiative, dbTable, "INITIATIVE", &thisptr->id); const auto& categories = AttackClassCategories::get(); const auto id = thisptr->data->attackClass.id; if (attackHasPower(thisptr->data->attackClass.id)) { db.readPower(&data->power, &data->power, dbTable, "POWER", &thisptr->id); } if (attackHasDamage(thisptr->data->attackClass.id)) { db.readDamage(&data->qtyDamage, dbTable, "QTY_DAM", &thisptr->id); } else { data->qtyDamage = 0; } if (id == categories.heal->id || id == categories.revive->id) { db.readHeal(&data->qtyHeal, dbTable, "QTY_HEAL", &thisptr->id); } else if (id == categories.bestowWards->id) { data->qtyHeal = 0; db.readIntWithBoundsCheck(&data->qtyHeal, dbTable, "QTY_HEAL", 0, std::numeric_limits<int>::max()); } else { data->qtyHeal = 0; } if (id == categories.boostDamage->id || id == categories.lowerDamage->id || id == categories.lowerInitiative->id) { db.readAttackLevel(&data->level, dbTable, "LEVEL", &thisptr->id, &data->attackClass); } else { data->level = -1; } if (attackHasInfinite(thisptr->data->attackClass.id)) { db.readInfinite(&data->infinite, dbTable, "INFINITE"); } else { data->infinite = false; } if (attackHasAltAttack(thisptr->data->attackClass.id)) { db.readId(&data->altAttack, dbTable, "ALT_ATTACK"); } else { data->altAttack = emptyId; } if (id == categories.bestowWards->id) { int count{0}; db.readIntWithBoundsCheck(&count, dbTable, "QTY_WARDS", std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); for (int i = 0; i < count; ++i) { CMidgardID wardId = invalidId; db.readId(&wardId, dbTable, fmt::format("WARD{:d}", i + 1).c_str()); IdVectorApi::get().pushBack(&data->wards, &wardId); } } if (attackHasCritHit(thisptr->data->attackClass.id)) { db.readBool(&data->critHit, dbTable, "CRIT_HIT"); } else { data->critHit = false; } data->critDamage = userSettings().criticalHitDamage; data->critPower = userSettings().criticalHitChance; if (getCustomAttacks().critSettingsEnabled) { int critDamage; db.readIntWithBoundsCheck(&critDamage, dbTable, critDamageColumnName, 0, 255); if (critDamage != 0) data->critDamage = (std::uint8_t)critDamage; int critPower; db.readIntWithBoundsCheck(&critPower, dbTable, critPowerColumnName, 0, 100); if (critPower != 0) data->critPower = (std::uint8_t)critPower; } data->damageRatio = 100; data->damageRatioPerTarget = false; data->damageSplit = false; if (getCustomAttacks().damageRatiosEnabled) { int damageRatio; db.readIntWithBoundsCheck(&damageRatio, dbTable, damageRatioColumnName, 0, 255); if (damageRatio != 0) data->damageRatio = (std::uint8_t)damageRatio; data->damageRatioPerTarget = false; db.readBool(&data->damageRatioPerTarget, dbTable, damageRatioPerTargetColumnName); data->damageSplit = false; db.readBool(&data->damageSplit, dbTable, damageSplitColumnName); } return thisptr; } game::CAttackImpl* __fastcall attackImplCtor2Hooked(game::CAttackImpl* thisptr, int /*%edx*/, const game::CAttackData* data) { auto result = getOriginalFunctions().attackImplCtor2(thisptr, data); thisptr->data->critDamage = data->critDamage; thisptr->data->critPower = data->critPower; thisptr->data->damageRatio = data->damageRatio; thisptr->data->damageRatioPerTarget = data->damageRatioPerTarget; thisptr->data->damageSplit = data->damageSplit; return result; } void __fastcall attackImplGetDataHooked(game::CAttackImpl* thisptr, int /*%edx*/, game::CAttackData* value) { getOriginalFunctions().attackImplGetData(thisptr, value); value->critDamage = thisptr->data->critDamage; value->critPower = thisptr->data->critPower; value->damageRatio = thisptr->data->damageRatio; value->damageRatioPerTarget = thisptr->data->damageRatioPerTarget; value->damageSplit = thisptr->data->damageSplit; } game::IBatAttack* __stdcall createBatAttackHooked(game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, const game::CMidgardID* id1, const game::CMidgardID* id2, int attackNumber, const game::LAttackClass* attackClass, bool a7) { using namespace game; if (attackClass->id == customAttackClass.id) { CustomAttack* customAttack = (CustomAttack*)Memory::get().allocate(sizeof(CustomAttack)); customAttackCtor(customAttack, objectMap, id1, id2, attackNumber); return customAttack; } return getOriginalFunctions().createBatAttack(objectMap, battleMsgData, id1, id2, attackNumber, attackClass, a7); } std::uint32_t __stdcall getAttackClassWardFlagPositionHooked(const game::LAttackClass* attackClass) { if (attackClass->id == customAttackClass.id) { return 23; } return getOriginalFunctions().getAttackClassWardFlagPosition(attackClass); } const char* __stdcall attackClassToStringHooked(const game::LAttackClass* attackClass) { if (attackClass->id == customAttackClass.id) { return "DAMA"; } return getOriginalFunctions().attackClassToString(attackClass); } void __stdcall getUnitAttackSourceImmunitiesHooked(const game::LImmuneCat* immuneCat, const game::CMidUnit* unit, game::List<game::LAttackSource>* value) { using namespace game; const auto soldier = gameFunctions().castUnitImplToSoldier(unit->unitImpl); getSoldierAttackSourceImmunities(immuneCat, soldier, value); } void __stdcall getSoldierAttackSourceImmunitiesHooked(const game::IUsSoldier* soldier, bool alwaysImmune, game::List<game::LAttackSource>* value) { using namespace game; const auto& immunities = ImmuneCategories::get(); getSoldierAttackSourceImmunities(alwaysImmune ? immunities.always : immunities.once, soldier, value); } double __stdcall getSoldierImmunityAiRatingHooked(const game::IUsSoldier* soldier) { using namespace game; double result = getOriginalFunctions().getSoldierImmunityAiRating(soldier); const auto& immunities = ImmuneCategories::get(); for (const auto& custom : getCustomAttacks().sources) { auto immuneCat = soldier->vftable->getImmuneByAttackSource(soldier, &custom.source); if (immuneCat->id != immunities.notimmune->id) result += custom.immunityAiRating; } return result; } double __stdcall getAttackClassAiRatingHooked(const game::IUsSoldier* soldier, bool a2) { using namespace game; const auto& classes = AttackClassCategories::get(); const auto& reaches = AttackReachCategories::get(); auto attack = soldier->vftable->getAttackById(soldier); auto attackClass = attack->vftable->getAttackClass(attack); if (attackClass->id == classes.paralyze->id || attackClass->id == classes.petrify->id) { return 30.0; } else if (attackClass->id == classes.damage->id || attackClass->id == classes.heal->id) { return 1.0; } else if (attackClass->id == classes.drain->id) { return 1.5; } else if (attackClass->id == classes.fear->id) { return 30.0; } else if (attackClass->id == classes.boostDamage->id || attackClass->id == classes.bestowWards->id) { return 40.0; } else if (attackClass->id == classes.shatter->id) { return 30.0; } else if (attackClass->id == classes.lowerDamage->id || attackClass->id == classes.lowerInitiative->id) { return 40.0; } else if (attackClass->id == classes.drainOverflow->id) { return 2.0; } else if (attackClass->id == classes.summon->id) { return 200.0; } else if (attackClass->id == classes.drainLevel->id) { return 100.0; } else if (attackClass->id == classes.giveAttack->id) { return 50.0; } else if (attackClass->id == classes.doppelganger->id) { return a2 ? 100.0 : 200.0; } else if (attackClass->id == classes.transformSelf->id) { return 100.0; } else if (attackClass->id == classes.transformOther->id) { auto attackReach = attack->vftable->getAttackReach(attack); for (const auto& custom : getCustomAttacks().reaches) { if (attackReach->id == custom.reach.id) { return 60.0 + 8.0 * (custom.maxTargets - 1); } } return attackReach->id == reaches.all->id ? 100.0 : 60.0; } return 1.0; } double __stdcall getAttackReachAiRatingHooked(const game::IUsSoldier* soldier, int targetCount) { using namespace game; const auto& reaches = AttackReachCategories::get(); auto attack = soldier->vftable->getAttackById(soldier); auto attackReach = attack->vftable->getAttackReach(attack); if (attackReach->id == reaches.all->id) { int targetFactor = targetCount - 1; return 1.0 + 0.4 * targetFactor; } else if (attackReach->id == reaches.any->id) { return 1.5; } else if (attackReach->id != reaches.adjacent->id) { for (const auto& custom : getCustomAttacks().reaches) { if (attackReach->id == custom.reach.id) { int count = std::min(targetCount, (int)custom.maxTargets); if (count == 1 && !custom.melee) return 1.5; else return 1.0 + 0.4 * (computeTotalDamageRatio(attack, count) - 1); } } } return 1.0; } std::uint32_t __stdcall getAttackSourceWardFlagPositionHooked( const game::LAttackSource* attackSource) { for (const auto& custom : getCustomAttacks().sources) { if (custom.source.id == attackSource->id) return custom.wardFlagPosition; } return getOriginalFunctions().getAttackSourceWardFlagPosition(attackSource); } bool __fastcall isUnitAttackSourceWardRemovedHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::CMidgardID* unitId, const game::LAttackSource* attackSource) { using namespace game; auto unitInfo = BattleMsgDataApi::get().getUnitInfoById(thisptr, unitId); if (unitInfo == nullptr) return false; std::uint32_t flag = 1 << gameFunctions().getAttackSourceWardFlagPosition(attackSource); return (unitInfo->attackSourceImmunityStatuses.patched & flag) != 0; } void __fastcall removeUnitAttackSourceWardHooked(game::BattleMsgData* thisptr, int /*%edx*/, const game::CMidgardID* unitId, const game::LAttackSource* attackSource) { using namespace game; auto unitInfo = BattleMsgDataApi::get().getUnitInfoById(thisptr, unitId); if (unitInfo == nullptr) return; std::uint32_t flag = 1 << gameFunctions().getAttackSourceWardFlagPosition(attackSource); unitInfo->attackSourceImmunityStatuses.patched |= flag; } void __stdcall addUnitToBattleMsgDataHooked(const game::IMidgardObjectMap* objectMap, const game::CMidUnitGroup* group, const game::CMidgardID* unitId, char attackerFlags, game::BattleMsgData* battleMsgData) { using namespace game; for (auto& unitsInfo : battleMsgData->unitsInfo) { if (unitsInfo.unitId1 == invalidId) { unitsInfo.attackClassImmunityStatuses = 0; unitsInfo.attackSourceImmunityStatuses.patched = 0; getOriginalFunctions().addUnitToBattleMsgData(objectMap, group, unitId, attackerFlags, battleMsgData); return; } } logError("mssProxyError.log", fmt::format("Could not find a free slot for a new unit {:s} in battle msg data", hooks::idToString(unitId))); } bool __stdcall getTargetsToAttackForAllOrCustomReach(game::IdList* value, const game::IMidgardObjectMap* objectMap, const game::IAttack* attack, const game::IBatAttack* batAttack, const game::LAttackReach* attackReach, const game::BattleMsgData* battleMsgData, game::BattleAction action, const game::CMidgardID* targetUnitId) { using namespace game; const auto& fn = gameFunctions(); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; const auto& reaches = AttackReachCategories::get(); if (action != BattleAction::Attack && action != BattleAction::UseItem) return false; auto transformSelfAttack = (CBatAttackTransformSelf*) dynamicCast(batAttack, 0, rtti.IBatAttackType, rtti.CBatAttackTransformSelfType, 0); if (transformSelfAttack && transformSelfAttack->unitId == *targetUnitId) return false; CMidgardID targetGroupId{}; batAttack->vftable->getTargetGroupId(batAttack, &targetGroupId, battleMsgData); if (attackReach->id == reaches.all->id) { getTargetsToAttackForAllAttackReach(objectMap, battleMsgData, attack, batAttack, &targetGroupId, targetUnitId, value); return true; } else if (attackReach->id != reaches.any->id && attackReach->id != reaches.adjacent->id) { for (const auto& custom : getCustomAttacks().reaches) { if (attackReach->id == custom.reach.id) { const CMidgardID* unitId = getUnitId(batAttack); CMidgardID unitGroupId{}; fn.getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, unitId, true); getTargetsToAttackForCustomAttackReach(objectMap, battleMsgData, batAttack, &targetGroupId, targetUnitId, &unitGroupId, unitId, custom, value); return true; } } } return false; } void __stdcall getTargetsToAttackHooked(game::IdList* value, const game::IMidgardObjectMap* objectMap, const game::IAttack* attack, const game::IBatAttack* batAttack, const game::LAttackReach* attackReach, const game::BattleMsgData* battleMsgData, game::BattleAction action, const game::CMidgardID* targetUnitId) { using namespace game; const auto& listApi = IdListApi::get(); if (!getTargetsToAttackForAllOrCustomReach(value, objectMap, attack, batAttack, attackReach, battleMsgData, action, targetUnitId)) { listApi.pushBack(value, targetUnitId); } if (getCustomAttacks().damageRatiosEnabled) { fillCustomAttackTargets(value); } } void __stdcall fillTargetsListHooked(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::IBatAttack* batAttack, const game::CMidgardID* unitId, const game::CMidgardID* attackUnitOrItemId, bool targetAllies, game::TargetSet* value, bool checkAltAttack) { using namespace game; const auto& fn = gameFunctions(); const auto& battle = BattleMsgDataApi::get(); const auto& reaches = AttackReachCategories::get(); CMidgardID unitGroupId{}; fn.getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, unitId, true); CMidgardID targetGroupId{}; fn.getAllyOrEnemyGroupId(&targetGroupId, battleMsgData, unitId, targetAllies); IAttack* attack = fn.getAttackById(objectMap, attackUnitOrItemId, 1, checkAltAttack); LAttackReach* attackReach = attack->vftable->getAttackReach(attack); if (attackReach->id == reaches.all->id) { battle.fillTargetsListForAllAttackReach(objectMap, battleMsgData, batAttack, &targetGroupId, value); } else if (attackReach->id == reaches.any->id) { battle.fillTargetsListForAnyAttackReach(objectMap, battleMsgData, batAttack, &targetGroupId, value); } else if (attackReach->id == reaches.adjacent->id) { battle.fillTargetsListForAdjacentAttackReach(objectMap, battleMsgData, batAttack, &targetGroupId, &unitGroupId, unitId, value); } else { for (const auto& custom : getCustomAttacks().reaches) { if (attackReach->id == custom.reach.id) { fillTargetsListForCustomAttackReach(objectMap, battleMsgData, batAttack, &targetGroupId, &unitGroupId, unitId, attackUnitOrItemId, custom, value); break; } } } if (shouldExcludeImmuneTargets(objectMap, battleMsgData, unitId)) { excludeImmuneTargets(objectMap, battleMsgData, attack, &unitGroupId, &targetGroupId, value); } } void __stdcall fillEmptyTargetsListHooked(const game::IMidgardObjectMap* objectMap, const game::BattleMsgData* battleMsgData, const game::IBatAttack* batAttack, const game::CMidgardID* unitId, const game::CMidgardID* attackUnitOrItemId, bool targetAllies, game::TargetSet* value) { using namespace game; const auto& fn = gameFunctions(); const auto& battle = BattleMsgDataApi::get(); const auto& reaches = AttackReachCategories::get(); CMidgardID unitGroupId{}; fn.getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, unitId, true); CMidgardID targetGroupId{}; fn.getAllyOrEnemyGroupId(&targetGroupId, battleMsgData, unitId, targetAllies); IAttack* attack = fn.getAttackById(objectMap, attackUnitOrItemId, 1, true); LAttackReach* attackReach = attack->vftable->getAttackReach(attack); if (attackReach->id == reaches.all->id) { battle.fillEmptyTargetsListForAllAttackReach(objectMap, &targetGroupId, value); } else if (attackReach->id == reaches.any->id) { battle.fillEmptyTargetsListForAnyAttackReach(objectMap, &targetGroupId, value); } else if (attackReach->id == reaches.adjacent->id) { battle.fillEmptyTargetsListForAdjacentAttackReach(objectMap, battleMsgData, batAttack, &targetGroupId, &unitGroupId, unitId, value); } else { // Do nothing - custom attack reaches process empty targets in fillTargetsListHooked } } bool __stdcall isGroupSuitableForAiNobleMisfitHooked(const game::IMidgardObjectMap* objectMap, const game::CMidUnitGroup* group) { using namespace game; const auto& fn = gameFunctions(); const auto& unitIds = group->units; if (unitIds.end - unitIds.bgn < 2) return false; for (const CMidgardID* unitId = unitIds.bgn; unitId != unitIds.end; ++unitId) { auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); if (!soldier->vftable->getSizeSmall(soldier)) continue; auto attack = soldier->vftable->getAttackById(soldier); if (!isMeleeAttack(attack)) return true; } return false; } bool __stdcall isUnitSuitableForAiNobleDuelHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId) { using namespace game; const auto& fn = gameFunctions(); const auto& attackClasses = AttackClassCategories::get(); const auto& attackReaches = AttackReachCategories::get(); auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); if (unit->currentHp >= 100) return false; auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); auto attack = soldier->vftable->getAttackById(soldier); auto attackClassId = attack->vftable->getAttackClass(attack)->id; if (attackClassId == attackClasses.damage->id) { auto attackDamage = attack->vftable->getQtyDamage(attack); auto attackReach = attack->vftable->getAttackReach(attack); if (attackReach->id == attackReaches.all->id) { return attackDamage < 40; } else { for (auto& custom : getCustomAttacks().reaches) { if (attackReach->id == custom.reach.id) { auto attackInitiative = attack->vftable->getInitiative(attack); return attackDamage < 40 && attackInitiative <= 50; } } } } else if (attackClassId == attackClasses.heal->id || attackClassId == attackClasses.boostDamage->id || attackClassId == attackClasses.lowerDamage->id || attackClassId == attackClasses.lowerInitiative->id || attackClassId == attackClasses.revive->id || attackClassId == attackClasses.cure->id || attackClassId == attackClasses.bestowWards->id || attackClassId == attackClasses.shatter->id || attackClassId == attackClasses.giveAttack->id) { return true; } return false; } bool __stdcall findDamageAndShatterAttackTargetWithMeleeReach( const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::IAttack* attack, const game::IAttack* damageAttack, int attackDamage, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, const game::BattleMsgData* battleMsgData, game::CMidgardID* value) { using namespace game; const auto& fn = gameFunctions(); const auto& battle = BattleMsgDataApi::get(); const auto& groupApi = CMidUnitGroupApi::get(); const auto& immunities = ImmuneCategories::get(); int primaryEffectiveHp = std::numeric_limits<int>::max(); int secondaryEffectiveHp = std::numeric_limits<int>::max(); CMidUnit* primaryTarget = nullptr; CMidUnit* secondaryTarget = nullptr; for (const auto& targetPosition : *targets) { auto targetUnitId = *groupApi.getUnitIdByPosition(targetGroup, targetPosition); bool isSecondary = battle.getUnitStatus(battleMsgData, &targetUnitId, BattleStatus::Summon); if (primaryTarget && isSecondary) continue; auto targetUnit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, &targetUnitId)); auto targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); int targetArmorShattered; fn.computeArmor(&targetArmorShattered, objectMap, battleMsgData, &targetUnitId); targetArmorShattered -= computeShatterDamage(&targetUnitId, targetSoldier, battleMsgData, attack); // Assume effective hp as if target's armor is already shattered - thus adding shatter // damage to priority evaluation. int targetEffectiveHp = computeUnitEffectiveHpForAi(targetUnit->currentHp, targetArmorShattered); if (!isGreaterPickRandomIfEqual(primaryEffectiveHp, targetEffectiveHp)) continue; if (isSecondary && !isGreaterPickRandomIfEqual(secondaryEffectiveHp, targetEffectiveHp)) continue; auto attackSource = damageAttack->vftable->getAttackSource(damageAttack); if (targetSoldier->vftable->getImmuneByAttackSource(targetSoldier, attackSource)->id == immunities.always->id) continue; auto attackClass = damageAttack->vftable->getAttackClass(damageAttack); if (targetSoldier->vftable->getImmuneByAttackClass(targetSoldier, attackClass)->id == immunities.always->id) continue; if (isSecondary) { secondaryEffectiveHp = targetEffectiveHp; secondaryTarget = targetUnit; } else { primaryEffectiveHp = targetEffectiveHp; primaryTarget = targetUnit; } } if (primaryTarget) { *value = primaryTarget->id; return true; } else if (secondaryTarget) { *value = secondaryTarget->id; return true; } return false; } bool __stdcall findDamageAndShatterAttackTargetWithNonMeleeReach( const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::IAttack* attack, const game::IAttack* damageAttack, int attackDamage, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, const game::BattleMsgData* battleMsgData, game::CMidgardID* value) { using namespace game; const auto& fn = gameFunctions(); const auto& battle = BattleMsgDataApi::get(); const auto& groupApi = CMidUnitGroupApi::get(); const auto& immunities = ImmuneCategories::get(); int resultPriority = 0; CMidUnit* result = nullptr; for (const auto& targetPosition : *targets) { auto targetUnitId = *groupApi.getUnitIdByPosition(targetGroup, targetPosition); auto targetUnit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, &targetUnitId)); auto targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); // Include shatter damage into target priority evaluation. int targetPriority = fn.computeTargetUnitAiPriority(objectMap, &targetUnitId, battleMsgData, attackDamage); int shatterDamage = computeShatterDamage(&targetUnitId, targetSoldier, battleMsgData, attack); targetPriority += shatterDamage * 10; auto attackSource = damageAttack->vftable->getAttackSource(damageAttack); auto attackSourceImmunity = targetSoldier->vftable->getImmuneByAttackSource(targetSoldier, attackSource); if (attackSourceImmunity->id == immunities.always->id) continue; auto attackClass = damageAttack->vftable->getAttackClass(damageAttack); auto attackClassImmunity = targetSoldier->vftable->getImmuneByAttackClass(targetSoldier, attackClass); if (attackClassImmunity->id == immunities.always->id) continue; bool hasSourceWard = attackSourceImmunity->id == immunities.once->id && !battle.isUnitAttackSourceWardRemoved((BattleMsgData*)battleMsgData, &targetUnitId, attackSource); bool hasClassWard = attackClassImmunity->id == immunities.once->id && !battle.isUnitAttackClassWardRemoved((BattleMsgData*)battleMsgData, &targetUnitId, attackClass); if (hasSourceWard || hasClassWard) { targetPriority = lround(0.7 * targetPriority); } if (isGreaterPickRandomIfEqual(targetPriority, resultPriority)) { resultPriority = targetPriority; result = targetUnit; } } if (result) { *value = result->id; return true; } return false; } bool __stdcall findShatterOnlyAttackTarget(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::IAttack* attack, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, const game::BattleMsgData* battleMsgData, game::CMidgardID* value) { using namespace game; const auto& fn = gameFunctions(); const auto& battle = BattleMsgDataApi::get(); const auto& groupApi = CMidUnitGroupApi::get(); int resultPriority = 0; CMidUnit* result = nullptr; for (const auto& targetPosition : *targets) { auto targetUnitId = *groupApi.getUnitIdByPosition(targetGroup, targetPosition); if (battle.getUnitStatus(battleMsgData, &targetUnitId, BattleStatus::Retreat)) continue; auto targetUnit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, &targetUnitId)); auto targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); int shatterDamage = computeShatterDamage(&targetUnitId, targetSoldier, battleMsgData, attack); if (shatterDamage == 0) continue; // Include shatter damage into target priority evaluation. int targetPriority = fn.computeTargetUnitAiPriority(objectMap, &targetUnitId, battleMsgData, 0); targetPriority += shatterDamage * 10; if (isGreaterPickRandomIfEqual(targetPriority, resultPriority)) { resultPriority = targetPriority; result = targetUnit; } } if (result) { *value = result->id; return true; } return false; } bool __stdcall findShatterAttackTarget(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::IAttack* attack, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, const game::BattleMsgData* battleMsgData, game::CMidgardID* value) { using namespace game; const auto& fn = gameFunctions(); const auto& idApi = CMidgardIDApi::get(); const auto& battle = BattleMsgDataApi::get(); const auto& attackReaches = AttackReachCategories::get(); int attackDamage = 0; if (idApi.getType(unitOrItemId) == IdType::Unit) { auto unit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitOrItemId)); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); attackDamage = fn.computeAttackDamageCheckAltAttack(soldier, &unit->unitImpl->id, battleMsgData, unitOrItemId); } if (attackDamage > 0) { IAttack* primaryAttack = fn.getAttackById(objectMap, unitOrItemId, 1, true); LAttackReach* attackReach = primaryAttack->vftable->getAttackReach(primaryAttack); if (attackReach->id == attackReaches.all->id) { return battle.findAttackTargetWithAllReach(value, targetGroup, targets); } else if (isMeleeAttack(primaryAttack)) { return findDamageAndShatterAttackTargetWithMeleeReach(objectMap, unitOrItemId, attack, primaryAttack, attackDamage, targetGroup, targets, battleMsgData, value); } else { return findDamageAndShatterAttackTargetWithNonMeleeReach(objectMap, unitOrItemId, attack, primaryAttack, attackDamage, targetGroup, targets, battleMsgData, value); } } return findShatterOnlyAttackTarget(objectMap, unitOrItemId, attack, targetGroup, targets, battleMsgData, value); } bool __stdcall findAttackTargetHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::IAttack* attack, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, const game::BattleMsgData* battleMsgData, game::CMidgardID* value) { using namespace game; const auto& battle = BattleMsgDataApi::get(); const auto& attackCategories = AttackClassCategories::get(); auto attackClass = attack->vftable->getAttackClass(attack); if (attackClass->id == attackCategories.shatter->id) { if (findShatterAttackTarget(objectMap, unitOrItemId, attack, targetGroup, targets, battleMsgData, value)) return true; } if (getOriginalFunctions().findAttackTarget(objectMap, unitOrItemId, attack, targetGroup, targets, battleMsgData, value)) { return true; } if (attackClass->id == attackCategories.lowerDamage->id) { return battle.findBoostAttackTarget(objectMap, battleMsgData, targetGroup, targets, value); } else if (attackClass->id == attackCategories.lowerInitiative->id) { return battle.findFearAttackTarget(objectMap, battleMsgData, targetGroup, targets, value); } return false; } bool __stdcall findDoppelgangerAttackTargetHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId, const game::BattleMsgData* battleMsgData, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, game::CMidgardID* value) { using namespace game; const auto& fn = gameFunctions(); const auto& groupApi = CMidUnitGroupApi::get(); auto enemyGroup = getAllyOrEnemyGroup(objectMap, battleMsgData, unitId, false); int unitPosition = groupApi.getUnitPosition(targetGroup, unitId); int primaryXpKilled = 0; int secondaryXpKilled = 0; CMidUnit* primaryTarget = nullptr; CMidUnit* secondaryTarget = nullptr; for (const auto& targetPosition : *targets) { auto targetUnitId = getTargetUnitId(targetPosition, targetGroup, enemyGroup); auto targetUnit = static_cast<CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, &targetUnitId)); auto soldier = fn.castUnitImplToSoldier(getGlobalUnitImpl(&targetUnit->unitImpl->id)); auto attack = soldier->vftable->getAttackById(soldier); if (!fn.isAttackEffectiveAgainstGroup(objectMap, attack, enemyGroup)) continue; auto xpKilled = soldier->vftable->getXpKilled(soldier); if (isMeleeAttack(attack) == (unitPosition % 2 == 0)) { if (isGreaterPickRandomIfEqual(xpKilled, primaryXpKilled)) { primaryXpKilled = xpKilled; primaryTarget = targetUnit; } } else if (primaryTarget == nullptr) { if (isGreaterPickRandomIfEqual(xpKilled, secondaryXpKilled)) { secondaryXpKilled = xpKilled; secondaryTarget = targetUnit; } } } if (primaryTarget) { *value = primaryTarget->id; return true; } else if (secondaryTarget) { *value = secondaryTarget->id; return true; } return false; } bool __stdcall findDamageAttackTargetWithNonAllReachHooked(const game::IMidgardObjectMap* objectMap, const game::IAttack* attack, int damage, const game::CMidUnitGroup* targetGroup, const game::TargetSet* targets, const game::BattleMsgData* battleMsgData, game::CMidgardID* value) { using namespace game; const auto& battle = BattleMsgDataApi::get(); auto attackSource = attack->vftable->getAttackSource(attack); auto attackClass = attack->vftable->getAttackClass(attack); if (isMeleeAttack(attack)) { auto id = battle.findDamageAttackTargetWithAdjacentReach(value, objectMap, targetGroup, targets, battleMsgData, attackSource, attackClass); return *id != emptyId; } else { return battle.findDamageAttackTargetWithAnyReach(objectMap, targetGroup, targets, damage, battleMsgData, attackClass, attackSource, 0, value); } } bool __stdcall isAttackBetterThanItemUsageHooked(const game::IItem* item, const game::IUsSoldier* soldier, const game::CMidgardID* unitImplId) { using namespace game; const auto& fn = gameFunctions(); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; const auto& attackClasses = AttackClassCategories::get(); auto itemBattle = (CItemBattle*)dynamicCast(item, 0, rtti.IItemType, rtti.CItemBattleType, 0); auto itemAttack = getGlobalAttack(&itemBattle->attackId); if (itemAttack->vftable->getQtyDamage(itemAttack) == 0) return false; auto attackClass = itemAttack->vftable->getAttackClass(itemAttack); if (attackClass->id == attackClasses.shatter->id) return false; auto itemDamage = computeAverageTotalDamage(itemAttack, itemAttack->vftable->getQtyDamage(itemAttack)); auto soldierDamage = fn.computeAttackDamageCheckAltAttack(soldier, unitImplId, nullptr, &emptyId); soldierDamage = computeAverageTotalDamage(soldier->vftable->getAttackById(soldier), soldierDamage); return soldierDamage >= itemDamage; } game::CMidgardID* __stdcall getSummonUnitImplIdByAttackHooked(game::CMidgardID* summonImplId, const game::CMidgardID* attackId, int position, bool smallUnit) { using namespace game; const auto& fn = gameFunctions(); const auto& listApi = IdListApi::get(); const auto& global = GlobalDataApi::get(); IdList summonImplIds{}; listApi.constructor(&summonImplIds); auto globalData = *global.getGlobalData(); const auto transf = globalData->transf; fn.fillAttackTransformIdList(transf, &summonImplIds, attackId, smallUnit); if (summonImplIds.length == 0) { *summonImplId = emptyId; } else { IdListIterator startIt = summonImplIds.begin(); int start = fn.generateRandomNumberStd(summonImplIds.length); for (int i = 0; i < start; i++) { ++startIt; } if (position % 2 == 0) { *summonImplId = *startIt; } else { IdListIterator it = startIt; do { *summonImplId = *it; auto unitImpl = static_cast<TUsUnitImpl*>( global.findById(globalData->units, summonImplId)); const auto soldier = fn.castUnitImplToSoldier(unitImpl); const auto attack = soldier->vftable->getAttackById(soldier); if (!isMeleeAttack(attack)) break; if (++it == summonImplIds.end()) it = summonImplIds.begin(); } while (it != startIt); } } listApi.destructor(&summonImplIds); return summonImplId; } bool __stdcall isSmallMeleeFighterHooked(const game::IUsSoldier* soldier) { using namespace game; if (!soldier->vftable->getSizeSmall(soldier)) return false; const auto attack = soldier->vftable->getAttackById(soldier); if (attack->vftable->getQtyDamage(attack) == 0) return false; return isMeleeAttack(attack); } bool __stdcall cAiHireUnitEvalHooked(const game::IMidgardObjectMap* objectMap, const game::CMidUnitGroup* group) { using namespace game; const auto& fn = gameFunctions(); const auto& unitIds = group->units; for (const CMidgardID* unitId = unitIds.bgn; unitId != unitIds.end; ++unitId) { auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); auto attack = soldier->vftable->getAttackById(soldier); if (isMeleeAttack(attack)) return true; } return false; } double __stdcall getMeleeUnitToHireAiRatingHooked(const game::CMidgardID* unitImplId, bool a2, bool a3) { using namespace game; if (!a2 || a3) return 0.0; const auto& fn = gameFunctions(); const auto& global = GlobalDataApi::get(); auto globalData = *global.getGlobalData(); auto unitImpl = static_cast<TUsUnitImpl*>(global.findById(globalData->units, unitImplId)); auto soldier = fn.castUnitImplToSoldier(unitImpl); auto attack = soldier->vftable->getAttackById(soldier); return isMeleeAttack(attack) ? 100.0 : 0.0; } int __stdcall computeTargetUnitAiPriorityHooked(const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitId, const game::BattleMsgData* battleMsgData, int attackerDamage) { using namespace game; const auto& fn = gameFunctions(); const auto& attackClasses = AttackClassCategories::get(); auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, unitId)); auto soldier = fn.castUnitImplToSoldier(unit->unitImpl); auto attack = soldier->vftable->getAttackById(soldier); auto attackClassId = attack->vftable->getAttackClass(attack)->id; AttackClassId attack2ClassId = (AttackClassId)emptyCategoryId; auto attack2 = soldier->vftable->getSecondAttackById(soldier); if (attack2) attack2ClassId = attack2->vftable->getAttackClass(attack2)->id; int modifier = 0; if (!soldier->vftable->getSizeSmall(soldier) || isMeleeAttack(attack) || attackClassId == attackClasses.boostDamage->id) { int effectiveHp = fn.computeUnitEffectiveHpForAi(objectMap, unit, battleMsgData); modifier = effectiveHp > attackerDamage ? -effectiveHp : effectiveHp; } else { modifier = soldier->vftable->getXpKilled(soldier); if (attackClassId == attackClasses.heal->id || attack2ClassId == attackClasses.heal->id) { modifier *= 2; } else if (attackClassId == attackClasses.paralyze->id || attack2ClassId == attackClasses.paralyze->id) { modifier *= 8; } else if (attackClassId == attackClasses.petrify->id || attack2ClassId == attackClasses.petrify->id) { modifier *= 8; } else if (attackClassId == attackClasses.summon->id || attack2ClassId == attackClasses.summon->id) { modifier *= 10; } else if (attackClassId == attackClasses.transformOther->id || attack2ClassId == attackClasses.transformOther->id) { modifier *= 9; } else if (attackClassId == attackClasses.giveAttack->id || attack2ClassId == attackClasses.giveAttack->id) { modifier *= 3; } } return 10000 + modifier; } bool __fastcall midStackInitializeHooked(game::CMidStack* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* leaderId, const game::CMidgardID* ownerId, const game::CMidgardID* subraceId, const game::CMqPoint* position) { using namespace game; const auto& fn = gameFunctions(); const auto& stackApi = CMidStackApi::get(); auto leader = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, leaderId)); auto stackLeader = fn.castUnitImplToStackLeader(leader->unitImpl); if (!stackLeader) return false; int unitPosition = 2; auto soldier = fn.castUnitImplToSoldier(leader->unitImpl); if (soldier->vftable->getSizeSmall(soldier)) { auto attack = soldier->vftable->getAttackById(soldier); if (!isMeleeAttack(attack)) unitPosition = 3; } if (!thisptr->group.vftable->addLeader(&thisptr->group, leaderId, unitPosition, objectMap)) return false; thisptr->leaderId = *leaderId; thisptr->leaderAlive = leader->currentHp > 0; if (!thisptr->inventory.vftable->method1(&thisptr->inventory, &thisptr->id, objectMap)) return false; if (!stackApi.setPosition(thisptr, objectMap, position, false)) return false; if (!stackApi.setOwner(thisptr, objectMap, ownerId, subraceId)) return false; thisptr->facing = 0; thisptr->upgCount = 0; thisptr->invisible = 0; thisptr->aiIgnore = 0; thisptr->movement = stackLeader->vftable->getMovement(stackLeader); if (fn.isPlayerRaceUnplayable(ownerId, objectMap)) { thisptr->order = *OrderCategories::get().stand; } else { thisptr->order = *OrderCategories::get().normal; } thisptr->orderTargetId = emptyId; thisptr->aiOrder = *OrderCategories::get().normal; thisptr->aiOrderTargetId = emptyId; thisptr->creatLvl = soldier->vftable->getLevel(soldier); return true; } } // namespace hooks
58,698
C++
.cpp
1,165
37.765665
105
0.613337
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,953
custommodifier.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/custommodifier.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "custommodifier.h" #include "attackimpl.h" #include "attackutils.h" #include "currencyview.h" #include "customattacks.h" #include "customattackutils.h" #include "custommodifierfunctions.h" #include "deathanimcat.h" #include "dynamiccast.h" #include "game.h" #include "groundcat.h" #include "immunecat.h" #include "leaderabilitycat.h" #include "mempool.h" #include "midunit.h" #include "restrictions.h" #include "scriptutils.h" #include "unitcat.h" #include "unitimplview.h" #include "unitmodifier.h" #include "unitmodifierhooks.h" #include "unitutils.h" #include "ussoldierimpl.h" #include "utils.h" #include <fmt/format.h> #include <mutex> #include <set> namespace hooks { #define GET_VALUE(_FUNC_, _PREV_) \ getValue(getCustomModifierFunctions(unitModifier).##_FUNC_, #_FUNC_, _PREV_) #define THIZ_GET_VALUE(_FUNC_, _PREV_) \ thiz->getValue(getCustomModifierFunctions(thiz->unitModifier).##_FUNC_, #_FUNC_, _PREV_) #define THIZ_GET_VALUE_AS(_FUNC_, _PREV_) \ thiz->getValueAs(getCustomModifierFunctions(thiz->unitModifier).##_FUNC_, #_FUNC_, _PREV_) #define THIZ_GET_VALUE_PARAM(_FUNC_, _PARAM_, _PREV_) \ thiz->getValueParam(getCustomModifierFunctions(thiz->unitModifier).##_FUNC_, #_FUNC_, _PARAM_, \ _PREV_) #define THIZ_GET_VALUE_NO_PARAM(_FUNC_, _DEF_) \ thiz->getValueNoParam(getCustomModifierFunctions(thiz->unitModifier).##_FUNC_, #_FUNC_, _DEF_) static struct { game::RttiInfo<game::IUsUnitVftable> usUnit; game::RttiInfo<game::IUsSoldierVftable> usSoldier; game::RttiInfo<game::CUmModifierVftable> umModifier; game::RttiInfo<game::IUsStackLeaderVftable> usStackLeader; game::RttiInfo<game::IAttackVftable> attack; game::RttiInfo<game::IAttackVftable> attack2; game::RttiInfo<game::IAttackVftable> altAttack; } rttiInfo; void initRttiInfo(); void initVftable(CCustomModifier* thisptr); static inline CCustomModifier* castUnitToCustomModifier(const game::IUsUnit* unit) { return (CCustomModifier*)unit; } static inline CCustomModifier* castSoldierToCustomModifier(const game::IUsSoldier* soldier) { if (soldier == nullptr) return nullptr; return reinterpret_cast<CCustomModifier*>((uintptr_t)soldier - offsetof(CCustomModifier, usSoldier)); } CCustomModifier* castModifierToCustomModifier(const game::CUmModifier* modifier) { if (!modifier || modifier->vftable != &rttiInfo.umModifier.vftable) return nullptr; return reinterpret_cast<CCustomModifier*>((uintptr_t)modifier - offsetof(CCustomModifier, umModifier)); } static inline CCustomModifier* castStackLeaderToCustomModifier( const game::IUsStackLeader* stackLeader) { if (stackLeader == nullptr) return nullptr; return reinterpret_cast<CCustomModifier*>((uintptr_t)stackLeader - offsetof(CCustomModifier, usStackLeader)); } CCustomModifier* castAttackToCustomModifier(const game::IAttack* attack) { if (attack == nullptr) return nullptr; if (attack->vftable == &rttiInfo.attack.vftable) { return reinterpret_cast<CCustomModifier*>((uintptr_t)attack - offsetof(CCustomModifier, attack)); } else if (attack->vftable == &rttiInfo.attack2.vftable) { return reinterpret_cast<CCustomModifier*>((uintptr_t)attack - offsetof(CCustomModifier, attack2)); } else if (attack->vftable == &rttiInfo.altAttack.vftable) { return reinterpret_cast<CCustomModifier*>((uintptr_t)attack - offsetof(CCustomModifier, altAttack)); } return nullptr; } const game::IUsUnit* CCustomModifier::getPrev() const { return umModifier.data->prev; } const game::IUsSoldier* CCustomModifier::getPrevSoldier() const { return game::gameFunctions().castUnitImplToSoldier(getPrev()); } const game::IUsStackLeader* CCustomModifier::getPrevStackLeader() const { return game::gameFunctions().castUnitImplToStackLeader(getPrev()); } const game::IAttack* CCustomModifier::getPrevAttack(const game::IAttack* thisptr) const { if (thisptr == &attack) { return attack.prev; } else if (thisptr == &attack2) { return attack2.prev; } else if (thisptr == &altAttack) { return altAttack.prev; } return nullptr; } const CCustomModifier* CCustomModifier::getPrevCustomModifier() const { using namespace game; const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto current = getPrev(); while (current) { auto modifier = (CUmModifier*)dynamicCast(current, 0, rtti.IUsUnitType, rtti.CUmModifierType, 0); auto customModifier = castModifierToCustomModifier(modifier); if (customModifier) return customModifier; current = modifier ? modifier->data->prev : nullptr; } return nullptr; } CustomAttackData CCustomModifier::getCustomAttackData(const game::IAttack* thisptr) const { const auto& restrictions = game::gameRestrictions(); auto prev = getPrevAttack(thisptr); auto value = hooks::getCustomAttackData(prev); if (thisptr != &attack2) { value.damageRatio = GET_VALUE(getAttackDamRatio, value.damageRatio); value.damageRatioPerTarget = GET_VALUE(getAttackDrRepeat, value.damageRatioPerTarget); value.damageSplit = GET_VALUE(getAttackDrSplit, value.damageSplit); value.critDamage = GET_VALUE(getAttackCritDamage, value.critDamage); value.critPower = std::clamp(GET_VALUE(getAttackCritPower, value.critPower), (uint8_t)restrictions.attackPower->min, (uint8_t)restrictions.attackPower->max); } else { value.damageRatio = GET_VALUE(getAttack2DamRatio, value.damageRatio); value.damageRatioPerTarget = GET_VALUE(getAttack2DrRepeat, value.damageRatioPerTarget); value.damageSplit = GET_VALUE(getAttack2DrSplit, value.damageSplit); value.critDamage = GET_VALUE(getAttack2CritDamage, value.critDamage); value.critPower = std::clamp(GET_VALUE(getAttack2CritPower, value.critPower), (uint8_t)restrictions.attackPower->min, (uint8_t)restrictions.attackPower->max); } return value; } CustomModifierData& CCustomModifier::getData() { const std::lock_guard<std::mutex> lock(dataMutex); auto result = data.emplace(std::this_thread::get_id(), CustomModifierData{}); if (result.second) { auto& wards = result.first->second.wards; game::IdVectorApi::get().reserve(&wards, 1); } return result.first->second; } void CCustomModifier::setUnit(const game::CMidUnit* value) { unit = value; } game::IAttack* CCustomModifier::getAttack(bool primary) { auto prev = getPrev(); auto prevValue = hooks::getAttack(prev, primary, false); bindings::IdView prevId{prevValue ? prevValue->id : game::emptyId}; auto value = primary ? GET_VALUE(getAttackId, prevId) : GET_VALUE(getAttack2Id, prevId); if (value != prevId) { if (value.id == game::emptyId) { if (!primary) // Allow to remove secondary attack prevValue = nullptr; } else { auto global = getGlobalAttack(&value.id); if (global) prevValue = global; } } if (prevValue == nullptr) return nullptr; auto result = primary ? &attack : &attack2; result->id = prevValue->id; result->prev = prevValue; return result; } game::IAttack* CCustomModifier::wrapAltAttack(const game::IAttack* value) { if (!value) return nullptr; altAttack.id = value->id; altAttack.prev = value; return &altAttack; } bool CCustomModifier::getDisplay() const { auto prevValue = display; if (!unit) { return prevValue; } return GET_VALUE(getModifierDisplay, prevValue); } game::CMidgardID CCustomModifier::getDescTxt() const { auto prevValue = descTxt; if (!unit) { return prevValue; } bindings::IdView prevId{prevValue}; return GET_VALUE(getModifierDescTxt, prevId); } std::string CCustomModifier::getIconName() const { auto prevValue = idToString(&umModifier.data->modifierId); if (!unit) { return prevValue; } return GET_VALUE(getModifierIconName, prevValue); } const char* CCustomModifier::getFormattedGlobalText(const game::CMidgardID& formatId, const game::CMidgardID& baseId) const { static std::set<std::string> globals; static std::mutex globalsMutex; auto format = getGlobalText(formatId); auto base = getGlobalText(baseId); std::string formatted = format; if (!replace(formatted, "%BASE%", base)) return format; // No iterators or references are invalidated on insert // so it is safe to return raw char pointer. const std::lock_guard<std::mutex> lock(globalsMutex); return globals.insert(formatted).first->c_str(); } void CCustomModifier::showScriptErrorMessage(const char* functionName, const char* reason) const { showErrorMessageBox(fmt::format("Failed to run '{:s}' script.\n" "Function: '{:s}'\n" "Reason: '{:s}'", scriptFileName, functionName, reason)); } void CCustomModifier::showInvalidRetvalMessage(const char* functionName, const char* reason) const { showErrorMessageBox(fmt::format("Invalid return value in '{:s}' script.\n" "Function: '{:s}'\n" "Reason: '{:s}'", scriptFileName, functionName, reason)); } void CCustomModifier::notifyModifiersChanged() const { auto f = getCustomModifierFunctions(unitModifier).onModifiersChanged; try { if (f) { bindings::UnitView unitView{unit}; (*f)(unitView); } } catch (const std::exception& e) { showScriptErrorMessage("onModifiersChanged", e.what()); } } game::CMidgardID CCustomModifier::getUnitNameTxt() const { auto prev = getPrevCustomModifier(); bindings::IdView prevValue{prev ? prev->getUnitNameTxt() : getUnitBaseNameTxt()}; return GET_VALUE(getNameTxt, prevValue); } game::CMidgardID CCustomModifier::getUnitBaseNameTxt() const { auto soldierImpl = getSoldierImpl(getPrev()); return soldierImpl ? soldierImpl->data->name.id : game::emptyId; } game::CMidgardID CCustomModifier::getUnitDescTxt() const { auto prev = getPrevCustomModifier(); bindings::IdView prevValue{prev ? prev->getUnitDescTxt() : getUnitBaseDescTxt()}; return GET_VALUE(getDescTxt, prevValue); } game::CMidgardID CCustomModifier::getUnitBaseDescTxt() const { auto soldierImpl = getSoldierImpl(getPrev()); return soldierImpl ? soldierImpl->data->description.id : game::emptyId; } game::CMidgardID CCustomModifier::getAttackNameTxt(bool primary, const game::CMidgardID& baseId) const { auto prev = getPrevCustomModifier(); bindings::IdView prevId{prev ? prev->getAttackNameTxt(primary, baseId) : baseId}; return primary ? GET_VALUE(getAttackNameTxt, prevId) : GET_VALUE(getAttack2NameTxt, prevId); } game::CMidgardID CCustomModifier::getAttackBaseNameTxt(const game::IAttack* attack) const { auto attackImpl = getAttackImpl(attack); return attackImpl ? attackImpl->data->name.id : game::emptyId; } game::CMidgardID CCustomModifier::getAttackDescTxt(bool primary, const game::CMidgardID& baseId) const { auto prev = getPrevCustomModifier(); bindings::IdView prevId{prev ? prev->getAttackDescTxt(primary, baseId) : baseId}; return primary ? GET_VALUE(getAttackDescTxt, prevId) : GET_VALUE(getAttack2DescTxt, prevId); } game::CMidgardID CCustomModifier::getAttackBaseDescTxt(const game::IAttack* attack) const { auto attackImpl = getAttackImpl(attack); return attackImpl ? attackImpl->data->description.id : game::emptyId; } CCustomModifier* customModifierCtor(CCustomModifier* thisptr, const game::TUnitModifier* unitModifier, const char* scriptFileName, const game::CMidgardID* descTxt, bool display, const game::GlobalData** globalData) { using namespace game; // Lazy init makes sure that vftable hooks (if any) are already applied initRttiInfo(); thisptr->usUnit.id = emptyId; CUmModifierApi::get().constructor(&thisptr->umModifier, &unitModifier->id, globalData); thisptr->attack.prev = nullptr; thisptr->attack2.prev = nullptr; thisptr->altAttack.prev = nullptr; thisptr->unit = nullptr; thisptr->unitModifier = unitModifier; const_cast<CMidgardID&>(thisptr->descTxt) = *descTxt; const_cast<bool&>(thisptr->display) = display; new (const_cast<std::string*>(&thisptr->scriptFileName)) std::string(scriptFileName); new (&thisptr->data) CustomModifierDataMap(); new (&thisptr->dataMutex) std::mutex(); initVftable(thisptr); return thisptr; } CCustomModifier* customModifierCopyCtor(CCustomModifier* thisptr, const CCustomModifier* src) { using namespace game; thisptr->usUnit.id = src->usUnit.id; CUmModifierApi::get().copyConstructor(&thisptr->umModifier, &src->umModifier); thisptr->attack.prev = src->attack.prev; thisptr->attack2.prev = src->attack2.prev; thisptr->altAttack.prev = src->altAttack.prev; thisptr->unit = src->unit; thisptr->unitModifier = src->unitModifier; const_cast<CMidgardID&>(thisptr->descTxt) = src->descTxt; const_cast<bool&>(thisptr->display) = src->display; new (const_cast<std::string*>(&thisptr->scriptFileName)) std::string(src->scriptFileName); new (&thisptr->data) CustomModifierDataMap(); // No copy required new (&thisptr->dataMutex) std::mutex(); initVftable(thisptr); return thisptr; } void customModifierDtor(CCustomModifier* thisptr, char flags) { using namespace game; thisptr->scriptFileName.~basic_string(); for (auto& data : thisptr->data) { IdVectorApi::get().destructor(&data.second.wards); } thisptr->data.~map(); thisptr->dataMutex.~mutex(); CUmModifierApi::get().destructor(&thisptr->umModifier); if (flags & 1) { Memory::get().freeNonZero(thisptr); } } void __fastcall unitDtor(game::IUsUnit* thisptr, int /*%edx*/, char flags) { auto thiz = castUnitToCustomModifier(thisptr); customModifierDtor(thiz, flags); } game::IUsUnitExtension* __fastcall unitCast(const game::IUsUnit* thisptr, int /*%edx*/, const char* rawTypeName) { using namespace game; const auto& rtti = RttiApi::rtti(); const auto& rttiApi = RttiApi::get(); auto& typeInfoRawName = *rttiApi.typeInfoRawName; auto thiz = castUnitToCustomModifier(thisptr); auto prev = thiz->getPrev(); if (!strcmp(rawTypeName, typeInfoRawName(rtti.IUsSoldierType))) { return (IUsUnitExtension*)&thiz->usSoldier; } else if (!strcmp(rawTypeName, typeInfoRawName(rtti.IUsStackLeaderType))) { auto prevStackLeader = prev->vftable->cast(prev, rawTypeName); return prevStackLeader ? (IUsUnitExtension*)&thiz->usStackLeader : nullptr; } return prev->vftable->cast(prev, rawTypeName); } const game::LUnitCategory* __fastcall unitGetCategory(const game::IUsUnit* thisptr, int /*%edx*/) { auto prev = castUnitToCustomModifier(thisptr)->getPrev(); return prev->vftable->getCategory(prev); } void __fastcall soldierDtor(game::IUsSoldier* thisptr, int /*%edx*/, char flags) { auto thiz = castSoldierToCustomModifier(thisptr); customModifierDtor(thiz, flags); } const char* __fastcall soldierGetName(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); return thiz->getFormattedGlobalText(thiz->getUnitNameTxt(), thiz->getUnitBaseNameTxt()); } const char* __fastcall soldierGetDescription(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); return thiz->getFormattedGlobalText(thiz->getUnitDescTxt(), thiz->getUnitBaseDescTxt()); } const game::CMidgardID* __fastcall soldierGetRaceId(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getRaceId(prev); } const game::LSubRaceCategory* __fastcall soldierGetSubrace(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getSubrace(prev); } const game::LUnitBranch* __fastcall soldierGetBranch(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getBranch(prev); } bool __fastcall soldierGetSizeSmall(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getSizeSmall(prev); } bool __fastcall soldierGetSexM(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getSexM(prev); } int __fastcall soldierGetLevel(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getLevel(prev); } int __fastcall soldierGetHitPoints(const game::IUsSoldier* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); auto value = THIZ_GET_VALUE(getHitPoint, prev->vftable->getHitPoints(prev)); return std::clamp(value, restrictions.unitHp->min, restrictions.unitHp->max); } int* __fastcall soldierGetArmor(const game::IUsSoldier* thisptr, int /*%edx*/, int* armor) { const auto& restrictions = game::gameRestrictions(); auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); auto value = THIZ_GET_VALUE(getArmor, *prev->vftable->getArmor(prev, armor)); *armor = std::clamp(value, restrictions.unitArmor->min, restrictions.unitArmor->max); return armor; } const game::CMidgardID* __fastcall soldierGetBaseUnitImplId(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getBaseUnitImplId(prev); } const game::LDeathAnimCategory* __fastcall soldierGetDeathAnim(const game::IUsSoldier* thisptr, int /*%edx*/) { using namespace game; const auto& annimations = DeathAnimCategories::get(); auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); auto prevValue = prev->vftable->getDeathAnim(prev); auto value = THIZ_GET_VALUE(getDeathAnim, (int)prevValue->id); switch ((DeathAnimationId)value) { case DeathAnimationId::Human: return annimations.human; case DeathAnimationId::Heretic: return annimations.heretic; case DeathAnimationId::Dwarf: return annimations.dwarf; case DeathAnimationId::Undead: return annimations.undead; case DeathAnimationId::Neutral: return annimations.neutral; case DeathAnimationId::Dragon: return annimations.dragon; case DeathAnimationId::Ghost: return annimations.ghost; case DeathAnimationId::Elf: return annimations.elf; default: return prevValue; } } int* __fastcall soldierGetRegen(const game::IUsSoldier* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); auto value = THIZ_GET_VALUE(getRegen, *prev->vftable->getRegen(prev)); auto& regen = thiz->getData().regen; regen = std::clamp(value, restrictions.unitRegen.min, restrictions.unitRegen.max); return &regen; } int __fastcall soldierGetXpNext(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); return THIZ_GET_VALUE(getXpNext, prev->vftable->getXpNext(prev)); } int __fastcall soldierGetXpKilled(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); return THIZ_GET_VALUE(getXpKilled, prev->vftable->getXpKilled(prev)); } const game::LImmuneCat* getImmuneCatById(int categoryId, const game::LImmuneCat* default) { using namespace game; const auto& immunities = ImmuneCategories::get(); switch ((ImmuneId)categoryId) { case ImmuneId::Notimmune: return immunities.notimmune; case ImmuneId::Once: return immunities.once; case ImmuneId::Always: return immunities.always; default: return default; } } const game::LImmuneCat* __fastcall soldierGetImmuneByAttackClass( const game::IUsSoldier* thisptr, int /*%edx*/, const game::LAttackClass* attackClass) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); auto prevValue = prev->vftable->getImmuneByAttackClass(prev, attackClass); auto value = THIZ_GET_VALUE_PARAM(getImmuneToAttack, (int)attackClass->id, (int)prevValue->id); return getImmuneCatById(value, prevValue); } const game::LImmuneCat* __fastcall soldierGetImmuneByAttackSource( const game::IUsSoldier* thisptr, int /*%edx*/, const game::LAttackSource* attackSource) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); auto prevValue = prev->vftable->getImmuneByAttackSource(prev, attackSource); auto value = THIZ_GET_VALUE_PARAM(getImmuneToSource, (int)attackSource->id, (int)prevValue->id); return getImmuneCatById(value, prevValue); } const game::IAttack* __fastcall soldierGetAttackById(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); return thiz->getAttack(true); } const game::IAttack* __fastcall soldierGetSecondAttackById(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); return thiz->getAttack(false); } bool __fastcall soldierGetAttackTwice(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); return THIZ_GET_VALUE(getAtckTwice, prev->vftable->getAttackTwice(prev)); } const game::Bank* __fastcall soldierGetEnrollCost(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); bindings::CurrencyView prevValue{*prev->vftable->getEnrollCost(prev)}; auto value = THIZ_GET_VALUE(getEnrollCost, prevValue); auto& enrollCost = thiz->getData().enrollCost; enrollCost = value.bank; return &enrollCost; } const game::Bank* __fastcall soldierGetReviveCost(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); bindings::CurrencyView prevValue{*prev->vftable->getReviveCost(prev)}; auto value = THIZ_GET_VALUE(getReviveCost, prevValue); auto& reviveCost = thiz->getData().reviveCost; reviveCost = value.bank; return &reviveCost; } const game::Bank* __fastcall soldierGetHealCost(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); bindings::CurrencyView prevValue{*prev->vftable->getHealCost(prev)}; auto value = THIZ_GET_VALUE(getHealCost, prevValue); auto& healCost = thiz->getData().healCost; healCost = value.bank; return &healCost; } const game::Bank* __fastcall soldierGetTrainingCost(const game::IUsSoldier* thisptr, int /*%edx*/) { auto thiz = castSoldierToCustomModifier(thisptr); auto prev = thiz->getPrevSoldier(); bindings::CurrencyView prevValue{*prev->vftable->getTrainingCost(prev)}; auto value = THIZ_GET_VALUE(getTrainingCost, prevValue); auto& trainingCost = thiz->getData().trainingCost; trainingCost = value.bank; return &trainingCost; } const game::CMidgardID* __fastcall soldierGetDynUpg1(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getDynUpg1(prev); } int __fastcall soldierGetDynUpgLvl(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getDynUpgLvl(prev); } const game::CMidgardID* __fastcall soldierGetDynUpg2(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getDynUpg2(prev); } bool __fastcall soldierGetWaterOnly(const game::IUsSoldier* thisptr, int /*%edx*/) { auto prev = castSoldierToCustomModifier(thisptr)->getPrevSoldier(); return prev->vftable->getWaterOnly(prev); } void __fastcall modifierDtor(game::CUmModifier* thisptr, int /*%edx*/, char flags) { auto thiz = castModifierToCustomModifier(thisptr); customModifierDtor(thiz, flags); } game::CUmModifier* __fastcall modifierCopy(const game::CUmModifier* thisptr, int /*%edx*/) { using namespace game; auto thiz = castModifierToCustomModifier(thisptr); auto copy = (CCustomModifier*)Memory::get().allocate(sizeof(CCustomModifier)); customModifierCopyCtor(copy, thiz); return &copy->umModifier; } bool __fastcall modifierCanApplyWithLeadership(const game::CUmModifier* thisptr, int /*%edx*/, const int* leadership) { return true; } bool __fastcall modifierCanApplyToUnit(const game::CUmModifier* thisptr, int /*%edx*/, const game::IUsUnit* unit) { auto thiz = castModifierToCustomModifier(thisptr); auto f = getCustomModifierFunctions(thiz->unitModifier).canApplyToUnit; try { if (f) { bindings::UnitImplView unitImplView{unit}; return (*f)(unitImplView); } } catch (const std::exception& e) { thiz->showScriptErrorMessage("canApplyToUnit", e.what()); } return true; } bool __fastcall modifierCanApplyToUnitCategory(const game::CUmModifier* thisptr, int /*%edx*/, const game::LUnitCategory* unitCategory) { auto thiz = castModifierToCustomModifier(thisptr); auto f = getCustomModifierFunctions(thiz->unitModifier).canApplyToUnitType; try { if (f) { return (*f)((int)unitCategory->id); } } catch (const std::exception& e) { thiz->showScriptErrorMessage("canApplyToUnitType", e.what()); } return true; } bool __fastcall modifierIsLower(const game::CUmModifier* thisptr, int /*%edx*/) { auto thiz = castModifierToCustomModifier(thisptr); return THIZ_GET_VALUE_NO_PARAM(canApplyAsLowerSpell, true); } bool __fastcall modifierIsBoost(const game::CUmModifier* thisptr, int /*%edx*/) { auto thiz = castModifierToCustomModifier(thisptr); return THIZ_GET_VALUE_NO_PARAM(canApplyAsBoostSpell, true); } bool __fastcall modifierHasElement(const game::CUmModifier* thisptr, int /*%edx*/, game::ModifierElementTypeFlag type) { return false; // should cause modifierGetFirstElementValue to not be called at all } int __fastcall modifierGetFirstElementValue(const game::CUmModifier* thisptr, int /*%edx*/) { using namespace game; auto thiz = castModifierToCustomModifier(thisptr); // The values are used to check if this modifier can be applied, to apply spell effects, etc. // Custom modifiers do not have defined element values. // The goal here is to provide universal static values to pass most of the checks, // while having neutral effect if the values are applied directly. switch (thiz->getData().lastElementQuery) { case ModifierElementTypeFlag::Leadership: // Used by GetCombinedLeadership (Akella 0x4a7d6d) to check if Leadership leader upgrade can // be offered. return 0; case ModifierElementTypeFlag::MoveAbility: // Used by CanUseItem (Akella 0x5ed7cf) to check if leader already has this movement bonus. return emptyCategoryId; // game::GroundId case ModifierElementTypeFlag::LeaderAbility: // Used by CanUseItem (Akella 0x5ed7cf) to check if leader already has this ability. return emptyCategoryId; // game::LeaderAbilityId case ModifierElementTypeFlag::QtyDamage: case ModifierElementTypeFlag::Power: case ModifierElementTypeFlag::Initiative: // Used by ApplyPercentModifiers (Akella 0x577515) to exclude editor modifiers when // calculating bonus damage/power/ini in GenerateAttackDescription (Akella 0x57652b). return 0; case ModifierElementTypeFlag::Hp: // Used by CEffectModifierApply (Akella 0x439cd1) to apply Gallean's Boon G000UM7545. return 0; case ModifierElementTypeFlag::Armor: // Used by ApplyFortificationArmor (Akella 0x4212a2). // Used by ApplyAbsoluteModifiers (Akella 0x57646e) to exclude editor modifiers when // calculating bonus armor in GenerateUnitDescription (Akella 0x5757eb). return 0; case ModifierElementTypeFlag::ImmunityAlways: case ModifierElementTypeFlag::ImmunityOnce: // Used by CanUseItem (Akella 0x5ed7cf) to check if unit already immune to attack source. return emptyCategoryId; // game::AttackSourceId case ModifierElementTypeFlag::ImmunityclassAlways: case ModifierElementTypeFlag::ImmunityclassOnce: // Used by CanUseItem (Akella 0x5ed7cf) to check if unit already immune to attack class. return emptyCategoryId; // game::AttackClassId case ModifierElementTypeFlag::MoveAllowance: case ModifierElementTypeFlag::ScoutingRange: case ModifierElementTypeFlag::Regeneration: case ModifierElementTypeFlag::AttackDrain: default: return 0; } } const char* __fastcall modifierGetDescription(const game::CUmModifier* thisptr, int /*%edx*/) { using namespace game; auto thiz = castModifierToCustomModifier(thisptr); return getGlobalText(thiz->descTxt); } void __fastcall modifierUpdateUnitImplId(game::CUmModifier* thisptr, int /*%edx*/) { auto thiz = castModifierToCustomModifier(thisptr); thiz->usUnit.id = thiz->getPrev()->id; } void __fastcall stackLeaderDtor(game::IUsStackLeader* thisptr, int /*%edx*/, char flags) { auto thiz = castStackLeaderToCustomModifier(thisptr); customModifierDtor(thiz, flags); } int __fastcall stackLeaderGetMovement(const game::IUsStackLeader* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); auto value = THIZ_GET_VALUE(getMovement, prev->vftable->getMovement(prev)); return std::clamp(value, restrictions.stackMovement->min, restrictions.stackMovement->max); } const char* __fastcall stackLeaderGetAbilityName(const game::IUsStackLeader* thisptr, int /*%edx*/) { auto prev = castStackLeaderToCustomModifier(thisptr)->getPrevStackLeader(); return prev->vftable->getAbilityName(prev); } bool __fastcall stackLeaderHasMovementBonus(const game::IUsStackLeader* thisptr, int /*%edx*/, const game::LGroundCategory* ground) { auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); return THIZ_GET_VALUE_PARAM(hasMovementBonus, (int)ground->id, prev->vftable->hasMovementBonus(prev, ground)); } int __fastcall stackLeaderGetScout(const game::IUsStackLeader* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); auto value = THIZ_GET_VALUE(getScout, prev->vftable->getScout(prev)); return std::clamp(value, restrictions.stackScoutRange->min, restrictions.stackScoutRange->max); } int __fastcall stackLeaderGetLeadership(const game::IUsStackLeader* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); auto value = THIZ_GET_VALUE(getLeadership, prev->vftable->getLeadership(prev)); return std::clamp(value, restrictions.stackLeadership->min, restrictions.stackLeadership->max); } int __fastcall stackLeaderGetNegotiate(const game::IUsStackLeader* thisptr, int /*%edx*/) { auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); return THIZ_GET_VALUE(getNegotiate, prev->vftable->getNegotiate(prev)); } bool __fastcall stackLeaderHasAbility(const game::IUsStackLeader* thisptr, int /*%edx*/, const game::LLeaderAbility* ability) { auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); return THIZ_GET_VALUE_PARAM(hasAbility, (int)ability->id, prev->vftable->hasAbility(prev, ability)); } bool __fastcall stackLeaderGetFastRetreat(const game::IUsStackLeader* thisptr, int /*%edx*/) { auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); return THIZ_GET_VALUE(getFastRetreat, prev->vftable->getFastRetreat(prev)); } int __fastcall stackLeaderGetLowerCost(const game::IUsStackLeader* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castStackLeaderToCustomModifier(thisptr); auto prev = thiz->getPrevStackLeader(); // Treated as percentValue, see implementation of DBReadCUmStackData (Akella 0x5A3F36) auto value = THIZ_GET_VALUE(getLowerCost, prev->vftable->getLowerCost(prev)); return std::clamp(value, restrictions.percentValue.min, restrictions.percentValue.max); } void __fastcall attackDtor(game::IAttack* thisptr, int /*%edx*/, char flags) { auto thiz = castAttackToCustomModifier(thisptr); customModifierDtor(thiz, flags); } const char* __fastcall attackGetName(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); if (attackHasAltAttack(prev)) { return prev->vftable->getName(prev); } auto baseId = thiz->getAttackBaseNameTxt(thisptr); bool primary = thisptr != &thiz->attack2; return thiz->getFormattedGlobalText(thiz->getAttackNameTxt(primary, baseId), baseId); } const char* __fastcall attackGetDescription(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); if (attackHasAltAttack(prev)) { return prev->vftable->getDescription(prev); } auto baseId = thiz->getAttackBaseDescTxt(thisptr); bool primary = thisptr != &thiz->attack2; return thiz->getFormattedGlobalText(thiz->getAttackDescTxt(primary, baseId), baseId); } const game::LAttackClass* __fastcall attackGetAttackClass(const game::IAttack* thisptr, int /*%edx*/) { using namespace game; const auto& classes = AttackClassCategories::get(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getAttackClass(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; auto value = primary ? THIZ_GET_VALUE(getAttackClass, (int)prevValue->id) : THIZ_GET_VALUE(getAttack2Class, (int)prevValue->id); // Prevents infinite recursion since alt attack is wrapped instead of the primary if (primary && prevValue->id != (AttackClassId)value && attackHasAltAttack((AttackClassId)value)) { thiz->showInvalidRetvalMessage( "getAttackClass", "Cannot change attack class to one with alt attack (Doppelganger, TransformSelf). Use 'getAttackId' for this purpose."); return prevValue; } switch ((AttackClassId)value) { case AttackClassId::Damage: return classes.damage; case AttackClassId::Drain: return classes.drain; case AttackClassId::Paralyze: return classes.paralyze; case AttackClassId::Heal: return classes.heal; case AttackClassId::Fear: return classes.fear; case AttackClassId::BoostDamage: return classes.boostDamage; case AttackClassId::Petrify: return classes.petrify; case AttackClassId::LowerDamage: return classes.lowerDamage; case AttackClassId::LowerInitiative: return classes.lowerInitiative; case AttackClassId::Poison: return classes.poison; case AttackClassId::Frostbite: return classes.frostbite; case AttackClassId::Revive: return classes.revive; case AttackClassId::DrainOverflow: return classes.drainOverflow; case AttackClassId::Cure: return classes.cure; case AttackClassId::Summon: return classes.summon; case AttackClassId::DrainLevel: return classes.drainLevel; case AttackClassId::GiveAttack: return classes.giveAttack; case AttackClassId::Doppelganger: return classes.doppelganger; case AttackClassId::TransformSelf: return classes.transformSelf; case AttackClassId::TransformOther: return classes.transformOther; case AttackClassId::Blister: return classes.blister; case AttackClassId::BestowWards: return classes.bestowWards; case AttackClassId::Shatter: return classes.shatter; default: return prevValue; } } const game::LAttackSource* __fastcall attackGetAttackSource(const game::IAttack* thisptr, int /*%edx*/) { using namespace game; const auto& sources = AttackSourceCategories::get(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getAttackSource(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; auto value = primary ? THIZ_GET_VALUE(getAttackSource, (int)prevValue->id) : THIZ_GET_VALUE(getAttack2Source, (int)prevValue->id); switch ((AttackSourceId)value) { case AttackSourceId::Weapon: return sources.weapon; case AttackSourceId::Mind: return sources.mind; case AttackSourceId::Life: return sources.life; case AttackSourceId::Death: return sources.death; case AttackSourceId::Fire: return sources.fire; case AttackSourceId::Water: return sources.water; case AttackSourceId::Earth: return sources.earth; case AttackSourceId::Air: return sources.air; default: for (const auto& custom : getCustomAttacks().sources) { if (custom.source.id == (AttackSourceId)value) return &custom.source; } return prevValue; } } int __fastcall attackGetInitiative(const game::IAttack* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getInitiative(prev); if (thisptr == &thiz->attack2 || attackHasAltAttack(prev)) { return prevValue; } auto value = THIZ_GET_VALUE(getAttackInitiative, prevValue); return std::clamp(value, restrictions.attackInitiative->min, restrictions.attackInitiative->max); } int* __fastcall attackGetPower(const game::IAttack* thisptr, int /*%edx*/, int* power) { const auto& restrictions = game::gameRestrictions(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getPower(prev, power); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; auto value = primary ? THIZ_GET_VALUE(getAttackPower, *prevValue) : THIZ_GET_VALUE(getAttack2Power, *prevValue); *power = std::clamp(value, restrictions.attackPower->min, restrictions.attackPower->max); return power; } const game::LAttackReach* __fastcall attackGetAttackReach(const game::IAttack* thisptr, int /*%edx*/) { using namespace game; const auto& reaches = AttackReachCategories::get(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getAttackReach(prev); if (thisptr == &thiz->attack2 || attackHasAltAttack(prev)) { return prevValue; } auto value = THIZ_GET_VALUE(getAttackReach, (int)prevValue->id); switch ((AttackReachId)value) { case AttackReachId::All: return reaches.all; case AttackReachId::Any: return reaches.any; case AttackReachId::Adjacent: return reaches.adjacent; default: for (const auto& custom : getCustomAttacks().reaches) { if (custom.reach.id == (AttackReachId)value) return &custom.reach; } return prevValue; } } int __fastcall attackGetQtyDamage(const game::IAttack* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); const auto& fn = game::gameFunctions(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getQtyDamage(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; auto value = primary ? THIZ_GET_VALUE(getAttackDamage, prevValue) : THIZ_GET_VALUE(getAttack2Damage, prevValue); return std::clamp(value, restrictions.attackDamage->min, fn.getUnitImplDamageMax(&thiz->unit->unitImpl->id)); } int __fastcall attackGetQtyHeal(const game::IAttack* thisptr, int /*%edx*/) { const auto& restrictions = game::gameRestrictions(); auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getQtyHeal(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; auto value = primary ? THIZ_GET_VALUE(getAttackHeal, prevValue) : THIZ_GET_VALUE(getAttack2Heal, prevValue); return std::clamp(value, restrictions.attackHeal.min, restrictions.attackHeal.max); } int __fastcall attackGetDrain(const game::IAttack* thisptr, int /*%edx*/, int damage) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getDrain(prev, damage); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; return primary ? THIZ_GET_VALUE_PARAM(getAttackDrain, damage, prevValue) : THIZ_GET_VALUE_PARAM(getAttack2Drain, damage, prevValue); } int __fastcall attackGetLevel(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getLevel(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; return primary ? THIZ_GET_VALUE(getAttackLevel, prevValue) : THIZ_GET_VALUE(getAttack2Level, prevValue); } const game::CMidgardID* __fastcall attackGetAltAttackId(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getAltAttackId(prev); if (*prevValue == game::emptyId) { return prevValue; } bindings::IdView prevId{prevValue}; auto value = THIZ_GET_VALUE(getAltAttackId, prevId); if (value != prevId) { auto global = getGlobalAttack(&value.id); if (global) { return &global->id; } } return prevValue; } bool __fastcall attackGetInfinite(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getInfinite(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; return primary ? THIZ_GET_VALUE(getAttackInfinite, prevValue) : THIZ_GET_VALUE(getAttack2Infinite, prevValue); } game::IdVector* __fastcall attackGetWards(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getWards(prev); if (attackHasAltAttack(prev)) { return prevValue; } auto prevIds = IdVectorToIds(prevValue); bool primary = thisptr != &thiz->attack2; auto value = primary ? THIZ_GET_VALUE_AS(getAttackWards, prevIds) : THIZ_GET_VALUE_AS(getAttack2Wards, prevIds); if (value == prevIds) { return prevValue; } else { auto& wards = thiz->getData().wards; IdsToIdVector(value, &wards); return &wards; } } bool __fastcall attackGetCritHit(const game::IAttack* thisptr, int /*%edx*/) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); auto prevValue = prev->vftable->getCritHit(prev); if (attackHasAltAttack(prev)) { return prevValue; } bool primary = thisptr != &thiz->attack2; return primary ? THIZ_GET_VALUE(getAttackCritHit, prevValue) : THIZ_GET_VALUE(getAttack2CritHit, prevValue); } void __fastcall attackGetData(const game::IAttack* thisptr, int /*%edx*/, game::CAttackData* value) { auto thiz = castAttackToCustomModifier(thisptr); auto prev = thiz->getPrevAttack(thisptr); prev->vftable->getData(prev, value); } void initUnitRttiInfo() { using namespace game; auto& info = rttiInfo.usUnit; replaceRttiInfo(info, CUmUnitApi::vftable().usUnit, false); auto& vftable = info.vftable; vftable.destructor = (IMidObjectVftable::Destructor)&unitDtor; vftable.cast = (IUsUnitVftable::Cast)&unitCast; vftable.getCategory = (IUsUnitVftable::GetCategory)&unitGetCategory; } void initSoldierRttiInfo() { using namespace game; auto& info = rttiInfo.usSoldier; replaceRttiInfo(info, CUmUnitApi::vftable().usSoldier, false); auto& vftable = info.vftable; vftable.destructor = (IUsUnitExtensionVftable::Destructor)&soldierDtor; vftable.getName = (IUsSoldierVftable::GetCStr)&soldierGetName; vftable.getDescription = (IUsSoldierVftable::GetCStr)&soldierGetDescription; vftable.getRaceId = (IUsSoldierVftable::GetId)&soldierGetRaceId; vftable.getSubrace = (IUsSoldierVftable::GetSubrace)&soldierGetSubrace; vftable.getBranch = (IUsSoldierVftable::GetBranch)&soldierGetBranch; vftable.getSizeSmall = (IUsSoldierVftable::GetBool)&soldierGetSizeSmall; vftable.getSexM = (IUsSoldierVftable::GetBool)&soldierGetSexM; vftable.getLevel = (IUsSoldierVftable::GetInt)&soldierGetLevel; vftable.getHitPoints = (IUsSoldierVftable::GetInt)&soldierGetHitPoints; vftable.getArmor = (IUsSoldierVftable::GetArmor)&soldierGetArmor; vftable.getBaseUnitImplId = (IUsSoldierVftable::GetId)&soldierGetBaseUnitImplId; vftable.getDeathAnim = (IUsSoldierVftable::GetDeathAnim)&soldierGetDeathAnim; vftable.getRegen = (IUsSoldierVftable::GetRegen)&soldierGetRegen; vftable.getXpNext = (IUsSoldierVftable::GetInt)&soldierGetXpNext; vftable.getXpKilled = (IUsSoldierVftable::GetInt)&soldierGetXpKilled; vftable.getImmuneByAttackClass = (IUsSoldierVftable:: GetImmuneByAttackClass)&soldierGetImmuneByAttackClass; vftable.getImmuneByAttackSource = (IUsSoldierVftable:: GetImmuneByAttackSource)&soldierGetImmuneByAttackSource; vftable.getAttackById = (IUsSoldierVftable::GetAttackById)&soldierGetAttackById; vftable.getSecondAttackById = (IUsSoldierVftable::GetAttackById)&soldierGetSecondAttackById; vftable.getAttackTwice = (IUsSoldierVftable::GetBool)&soldierGetAttackTwice; vftable.getEnrollCost = (IUsSoldierVftable::GetBank)&soldierGetEnrollCost; vftable.getReviveCost = (IUsSoldierVftable::GetBank)&soldierGetReviveCost; vftable.getHealCost = (IUsSoldierVftable::GetBank)&soldierGetHealCost; vftable.getTrainingCost = (IUsSoldierVftable::GetBank)&soldierGetTrainingCost; vftable.getDynUpg1 = (IUsSoldierVftable::GetId)&soldierGetDynUpg1; vftable.getDynUpgLvl = (IUsSoldierVftable::GetDynUpgLvl)&soldierGetDynUpgLvl; vftable.getDynUpg2 = (IUsSoldierVftable::GetId)&soldierGetDynUpg2; vftable.getWaterOnly = (IUsSoldierVftable::GetBool)&soldierGetWaterOnly; } void initModifierRttiInfo() { using namespace game; auto& info = rttiInfo.umModifier; replaceRttiInfo(info, CUmUnitApi::vftable().umModifier, false); auto& vftable = info.vftable; vftable.destructor = (CUmModifierVftable::Destructor)&modifierDtor; vftable.copy = (CUmModifierVftable::Copy)&modifierCopy; vftable.canApplyWithLeadership = (CUmModifierVftable:: CanApplyWithLeadership)&modifierCanApplyWithLeadership; vftable.canApplyToUnit = (CUmModifierVftable::CanApplyToUnit)&modifierCanApplyToUnit; vftable.canApplyToUnitCategory = (CUmModifierVftable:: CanApplyToUnitCategory)&modifierCanApplyToUnitCategory; vftable.isLower = (CUmModifierVftable::GetBool)&modifierIsLower; vftable.isBoost = (CUmModifierVftable::GetBool)&modifierIsBoost; vftable.hasElement = (CUmModifierVftable::HasElement)&modifierHasElement; vftable.getFirstElementValue = (CUmModifierVftable:: GetFirstElementValue)&modifierGetFirstElementValue; vftable.getDescription = (CUmModifierVftable::GetDescription)&modifierGetDescription; vftable.updateUnitImplId = (CUmModifierVftable::UpdateUnitImplId)&modifierUpdateUnitImplId; } void initStackLeaderRttiInfo() { using namespace game; // None of the existing RTTI can be reused as this class has unique offset. // Lucky for us, the game is not using IUsStackLeader for dynamic casts so we should be fine // with base RTTI. Otherwise, we would need to either patch dynamicCast or create our own RTTI. auto& info = rttiInfo.usStackLeader; replaceRttiInfo(info, IUsStackLeaderApi::vftable(), false); auto& vftable = info.vftable; vftable.destructor = (IUsUnitExtensionVftable::Destructor)&stackLeaderDtor; vftable.getMovement = (IUsStackLeaderVftable::GetInt)&stackLeaderGetMovement; vftable.getAbilityName = (IUsStackLeaderVftable::GetAbilityName)&stackLeaderGetAbilityName; vftable .hasMovementBonus = (IUsStackLeaderVftable::HasMovementBonus)&stackLeaderHasMovementBonus; vftable.getScout = (IUsStackLeaderVftable::GetInt)&stackLeaderGetScout; vftable.getLeadership = (IUsStackLeaderVftable::GetInt)&stackLeaderGetLeadership; vftable.getNegotiate = (IUsStackLeaderVftable::GetInt)&stackLeaderGetNegotiate; vftable.hasAbility = (IUsStackLeaderVftable::HasAbility)&stackLeaderHasAbility; vftable.getFastRetreat = (IUsStackLeaderVftable::GetFastRetreat)&stackLeaderGetFastRetreat; vftable.getLowerCost = (IUsStackLeaderVftable::GetInt)&stackLeaderGetLowerCost; } void initAttackRttiInfo(game::RttiInfo<game::IAttackVftable>& info) { using namespace game; // None of the existing RTTI can be reused as this class has unique offset. // Lucky for us, the game is not using IAttack for dynamic casts so we should be fine // with base RTTI. Otherwise, we would need to either patch dynamicCast or create our own RTTI. replaceRttiInfo(info, IAttackApi::vftable(), false); auto& vftable = info.vftable; vftable.destructor = (IMidObjectVftable::Destructor)&attackDtor; vftable.getName = (IAttackVftable::GetCStr)&attackGetName; vftable.getDescription = (IAttackVftable::GetCStr)&attackGetDescription; vftable.getAttackClass = (IAttackVftable::GetAttackClass)&attackGetAttackClass; vftable.getAttackSource = (IAttackVftable::GetAttackSource)&attackGetAttackSource; vftable.getInitiative = (IAttackVftable::GetInitiative)&attackGetInitiative; vftable.getPower = (IAttackVftable::GetPower)&attackGetPower; vftable.getAttackReach = (IAttackVftable::GetAttackReach)&attackGetAttackReach; vftable.getQtyDamage = (IAttackVftable::GetInt)&attackGetQtyDamage; vftable.getQtyHeal = (IAttackVftable::GetInt)&attackGetQtyHeal; vftable.getDrain = (IAttackVftable::GetDrain)&attackGetDrain; vftable.getLevel = (IAttackVftable::GetInt)&attackGetLevel; vftable.getAltAttackId = (IAttackVftable::GetId)&attackGetAltAttackId; vftable.getInfinite = (IAttackVftable::GetBool)&attackGetInfinite; vftable.getWards = (IAttackVftable::GetWards)&attackGetWards; vftable.getCritHit = (IAttackVftable::GetBool)&attackGetCritHit; vftable.getData = (IAttackVftable::GetData)&attackGetData; } void initRttiInfo() { static bool initialized = false; if (!initialized) { initUnitRttiInfo(); initSoldierRttiInfo(); initModifierRttiInfo(); initStackLeaderRttiInfo(); initAttackRttiInfo(rttiInfo.attack); initAttackRttiInfo(rttiInfo.attack2); initAttackRttiInfo(rttiInfo.altAttack); initialized = true; } } void initVftable(CCustomModifier* thisptr) { thisptr->usUnit.vftable = &rttiInfo.usUnit.vftable; thisptr->usSoldier.vftable = &rttiInfo.usSoldier.vftable; thisptr->umModifier.vftable = &rttiInfo.umModifier.vftable; thisptr->usStackLeader.vftable = &rttiInfo.usStackLeader.vftable; thisptr->attack.vftable = &rttiInfo.attack.vftable; thisptr->attack2.vftable = &rttiInfo.attack2.vftable; thisptr->altAttack.vftable = &rttiInfo.altAttack.vftable; } game::CUmModifier* createCustomModifier(const game::TUnitModifier* unitModifier, const char* scriptFileName, const game::CMidgardID* descTxt, bool display, const game::GlobalData** globalData) { using namespace game; auto customModifier = (CCustomModifier*)Memory::get().allocate(sizeof(CCustomModifier)); customModifierCtor(customModifier, unitModifier, scriptFileName, descTxt, display, globalData); return &customModifier->umModifier; } } // namespace hooks
57,840
C++
.cpp
1,318
37.372534
132
0.69979
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,954
networkpeer.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/networkpeer.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "networkpeer.h" #include "utils.h" #include <algorithm> namespace hooks { void __fastcall packetEventCallback(NetworkPeer* netPeer, int /*%edx*/) { auto peer{netPeer->peer.get()}; for (auto packet = peer->Receive(); packet != nullptr; peer->DeallocatePacket(packet), packet = peer->Receive()) { auto type = static_cast<DefaultMessageIDTypes>(packet->data[0]); for (auto& callback : netPeer->callbacks) { callback->onPacketReceived(type, peer, packet); } } auto& toRemove{netPeer->removeCallbacks}; if (!toRemove.empty()) { auto& callbacks{netPeer->callbacks}; for (auto& callback : toRemove) { callbacks.erase(std::remove(callbacks.begin(), callbacks.end(), callback), callbacks.end()); } toRemove.clear(); } } NetworkPeer::NetworkPeer(PeerPtr&& peer) : peer{std::move(peer)} { createTimerEvent(&packetEvent, this, packetEventCallback, 100); } NetworkPeer::~NetworkPeer() { game::UiEventApi::get().destructor(&packetEvent); } void NetworkPeer::addCallback(NetworkPeerCallbacks* callback) { if (std::find(callbacks.begin(), callbacks.end(), callback) == callbacks.end()) { callbacks.push_back(callback); } } void NetworkPeer::removeCallback(NetworkPeerCallbacks* callback) { if (std::find(removeCallbacks.begin(), removeCallbacks.end(), callback) == removeCallbacks.end()) { removeCallbacks.push_back(callback); } } } // namespace hooks
2,364
C++
.cpp
65
31.923077
86
0.698031
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,955
terrainnamemap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/terrainnamemap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "terrainnamemap.h" #include "version.h" #include <array> namespace game::TerrainNameMapApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Get)0x5a6d29, (Api::Add)0x5a728e, }, // Russobit Api{ (Api::Get)0x5a6d29, (Api::Add)0x5a728e, }, // Gog Api{ (Api::Get)0x5a5f8a, (Api::Add)0x5a64ef, }, // Scenario Editor Api{ (Api::Get)0x53a351, (Api::Add)0x53a8b6, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::TerrainNameMapApi
1,471
C++
.cpp
51
25.137255
72
0.686926
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,956
unitinfolist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitinfolist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitinfolist.h" #include "version.h" #include <array> namespace game::UnitInfoListApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x41bf2a, (Api::Destructor)0x41bf63, (Api::Sort)0x640600, }, // Russobit Api{ (Api::Constructor)0x41bf2a, (Api::Destructor)0x41bf63, (Api::Sort)0x640600, }, // Gog Api{ (Api::Constructor)0x41b9f7, (Api::Destructor)0x41ba30, (Api::Sort)0x63eed0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::UnitInfoListApi
1,503
C++
.cpp
49
26.938776
72
0.698413
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,957
netcustomplayerserver.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netcustomplayerserver.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netcustomplayerserver.h" #include "log.h" #include "mempool.h" #include "mqnetreception.h" #include "mqnetsystem.h" #include "netcustomplayer.h" #include "netcustomsession.h" #include "netmsg.h" #include "utils.h" #include <BitStream.h> #include <MessageIdentifiers.h> #include <algorithm> #include <fmt/format.h> #include <mutex> namespace hooks { static std::mutex netMessagesMutex; void PlayerServerCallbacks::onPacketReceived(DefaultMessageIDTypes type, SLNet::RakPeerInterface* peer, const SLNet::Packet* packet) { auto netSystem{playerServer->player.netSystem}; switch (type) { case ID_REMOTE_DISCONNECTION_NOTIFICATION: { logDebug("lobby.log", "PlayerServer: Client disconnected"); if (netSystem) { auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); netSystem->vftable->onPlayerDisconnected(netSystem, (int)guidInt); } break; } case ID_REMOTE_CONNECTION_LOST: { logDebug("lobby.log", "PlayerServer: Client lost connection"); auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto& ids = playerServer->connectedIds; ids.erase(std::remove(ids.begin(), ids.end(), guid), ids.end()); if (netSystem) { auto guidInt = SLNet::RakNetGUID::ToUint32(guid); netSystem->vftable->onPlayerDisconnected(netSystem, (int)guidInt); } break; } case ID_REMOTE_NEW_INCOMING_CONNECTION: logDebug("lobby.log", "PlayerServer: Client connected"); break; case ID_CONNECTION_REQUEST_ACCEPTED: // This should never happen on server ? logDebug("lobby.log", "PlayerServer: Connection request to the server was accepted"); break; case ID_NEW_INCOMING_CONNECTION: { auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); logDebug("lobby.log", fmt::format("PlayerServer: Incoming connection, id 0x{:x}", guidInt)); playerServer->connectedIds.push_back(guid); if (netSystem) { logDebug("lobby.log", "PlayerServer: Call netSystem onPlayerConnected"); netSystem->vftable->onPlayerConnected(netSystem, (int)guidInt); } else { logDebug("lobby.log", "PlayerServer: no netSystem is set, skip onPlayerConnected notification"); } break; } case ID_NO_FREE_INCOMING_CONNECTIONS: // This should never happen on server ? logDebug("lobby.log", "PlayerServer: Server is full"); break; case ID_DISCONNECTION_NOTIFICATION: { logDebug("lobby.log", "PlayerServer: Client has disconnected from server"); if (netSystem) { auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); netSystem->vftable->onPlayerDisconnected(netSystem, (int)guidInt); } break; } case ID_CONNECTION_LOST: { logDebug("lobby.log", "PlayerServer: Client has lost connection"); if (netSystem) { auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); netSystem->vftable->onPlayerDisconnected(netSystem, (int)guidInt); } break; } case 0xff: { // Game message received auto message = reinterpret_cast<const game::NetMessageHeader*>(packet->data); auto guid = peer->GetGuidFromSystemAddress(packet->systemAddress); auto guidInt = SLNet::RakNetGUID::ToUint32(guid); /*logDebug("playerServer.log", fmt::format("Game message '{:s}' from {:x}", message->messageClassName, guidInt));*/ // logDebug("playerServer.log", "Allocate net message"); auto msg = std::make_unique<unsigned char[]>(message->length); // logDebug("playerServer.log", "Copy net message"); std::memcpy(msg.get(), message, message->length); { std::lock_guard<std::mutex> messageGuard(netMessagesMutex); playerServer->messages.push_back( CNetCustomPlayerServer::IdMessagePair{std::uint32_t{guidInt}, std::move(msg)}); } auto reception = playerServer->player.netReception; if (reception) { reception->vftable->notify(reception); } break; } default: logDebug("lobby.log", fmt::format("PlayerServer: Packet type {:d}", static_cast<int>(packet->data[0]))); break; } } static void __fastcall playerServerDtor(CNetCustomPlayerServer* thisptr, int /*%edx*/, char flags) { playerLog("CNetCustomPlayerServer d-tor"); thisptr->~CNetCustomPlayerServer(); if (flags & 1) { playerLog("CNetCustomPlayerServer d-tor frees memory"); game::Memory::get().freeNonZero(thisptr); } } static game::String* __fastcall playerServerGetName(CNetCustomPlayerServer* thisptr, int /*%edx*/, game::String* string) { playerLog("CNetCustomPlayerServer getName"); thisptr->player.vftable->getName(&thisptr->player, string); return string; } static int __fastcall playerServerGetNetId(CNetCustomPlayerServer* thisptr, int /*%edx*/) { playerLog("CNetCustomPlayerServer getNetId"); return thisptr->player.vftable->getNetId(&thisptr->player); } static game::IMqNetSession* __fastcall playerServerGetSession(CNetCustomPlayerServer* thisptr, int /*%edx*/) { playerLog("CNetCustomPlayerServer getSession"); return thisptr->player.vftable->getSession(&thisptr->player); } static int __fastcall playerServerGetMessageCount(CNetCustomPlayerServer* thisptr, int /*%edx*/) { playerLog("CNetCustomPlayerServer getMessageCount"); std::lock_guard<std::mutex> messageGuard(netMessagesMutex); return static_cast<int>(thisptr->messages.size()); } static bool __fastcall playerServerSendMessage(CNetCustomPlayerServer* thisptr, int /*%edx*/, int idTo, const game::NetMessageHeader* message) { auto peer{thisptr->getPeer()}; if (!peer) { playerLog("CNetCustomPlayerServer could not send message, peer is nullptr"); return false; } const auto& connectedIds{thisptr->connectedIds}; SLNet::BitStream stream((unsigned char*)message, message->length, false); if (idTo == game::broadcastNetPlayerId) { playerLog("CNetCustomPlayerServer sendMessage broadcast"); // Do not use broadcast Send() because player server is also connected to lobby server // and we do not want to send him game messages for (const auto& guid : connectedIds) { peer->Send(&stream, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED, 0, guid, false); } return true; } auto it = std::find_if(connectedIds.begin(), connectedIds.end(), [idTo](const auto& guid) { return static_cast<int>(SLNet::RakNetGUID::ToUint32(guid)) == idTo; }); if (it != connectedIds.end()) { const auto& guid = *it; playerLog(fmt::format("CNetCustomPlayerServer sendMessage to 0x{:x}", std::uint32_t{SLNet::RakNetGUID::ToUint32(guid)})); peer->Send(&stream, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED, 0, guid, false); return true; } playerLog(fmt::format("CNetCustomPlayerServer could not send message. No client with id 0x{:x}", uint32_t(idTo))); return false; } static int __fastcall playerServerReceiveMessage(CNetCustomPlayerServer* thisptr, int /*%edx*/, int* idFrom, game::NetMessageHeader* buffer) { if (!idFrom || !buffer) { // This should never happen return 3; } playerLog("CNetCustomPlayerServer receiveMessage"); std::lock_guard<std::mutex> messageGuard(netMessagesMutex); if (thisptr->messages.empty()) { return 0; } const auto& pair = thisptr->messages.front(); auto message = reinterpret_cast<const game::NetMessageHeader*>(pair.second.get()); if (message->messageType != game::netMessageNormalType) { playerLog("CNetCustomPlayerServer received message with invalid type"); return 3; } if (message->length >= game::netMessageMaxLength) { playerLog("CNetCustomPlayerServer received message with invalid length"); return 3; } playerLog(fmt::format("CNetCustomPlayerServer receiveMessage '{:s}' length {:d} from 0x{:x}", message->messageClassName, message->length, pair.first)); *idFrom = static_cast<int>(pair.first); std::memcpy(buffer, message, message->length); thisptr->messages.pop_front(); return 2; } static void __fastcall playerServerSetNetSystem(CNetCustomPlayerServer* thisptr, int /*%edx*/, game::IMqNetSystem* netSystem) { playerLog("CNetCustomPlayerServer setNetSystem"); thisptr->player.vftable->setNetSystem(&thisptr->player, netSystem); } static int __fastcall playerServerMethod8(CNetCustomPlayerServer* thisptr, int /*%edx*/, int a2) { playerLog("CNetCustomPlayerServer method8"); return thisptr->player.vftable->method8(&thisptr->player, a2); } static bool __fastcall playerServerDestroyPlayer(CNetCustomPlayerServer* thisptr, int /*%edx*/, int playerId) { playerLog("CNetCustomPlayerServer destroyPlayer"); return false; } static bool __fastcall playerServerSetMaxPlayers(CNetCustomPlayerServer* thisptr, int /*%edx*/, int maxPlayers) { playerLog(fmt::format("CNetCustomPlayerServer setMaxPlayers {:d}", maxPlayers)); return thisptr->player.session->setMaxPlayers(maxPlayers); } static bool __fastcall playerServerSetAllowJoin(CNetCustomPlayerServer* thisptr, int /*%edx*/, bool allowJoin) { // Ignore this since its only called during server creation and eventually being allowed playerLog(fmt::format("CNetCustomPlayerServer setAllowJoin {:d}", (int)allowJoin)); return true; } static game::IMqNetPlayerServerVftable playerServerVftable{ (game::IMqNetPlayerServerVftable::Destructor)playerServerDtor, (game::IMqNetPlayerServerVftable::GetName)playerServerGetName, (game::IMqNetPlayerServerVftable::GetNetId)playerServerGetNetId, (game::IMqNetPlayerServerVftable::GetSession)playerServerGetSession, (game::IMqNetPlayerServerVftable::GetMessageCount)playerServerGetMessageCount, (game::IMqNetPlayerServerVftable::SendNetMessage)playerServerSendMessage, (game::IMqNetPlayerServerVftable::ReceiveMessage)playerServerReceiveMessage, (game::IMqNetPlayerServerVftable::SetNetSystem)playerServerSetNetSystem, (game::IMqNetPlayerServerVftable::Method8)playerServerMethod8, (game::IMqNetPlayerServerVftable::DestroyPlayer)playerServerDestroyPlayer, (game::IMqNetPlayerServerVftable::SetMaxPlayers)playerServerSetMaxPlayers, (game::IMqNetPlayerServerVftable::SetAllowJoin)playerServerSetAllowJoin, }; CNetCustomPlayerServer::CNetCustomPlayerServer(CNetCustomSession* session, game::IMqNetSystem* netSystem, game::IMqNetReception* netReception, NetworkPeer::PeerPtr&& peer) // 1 is a server netId hardcoded in game and was also used in DirectPlay. : player{session, netSystem, netReception, "SERVER", std::move(peer), 1} , callbacks{this} { vftable = &playerServerVftable; player.netPeer.addCallback(&callbacks); } bool CNetCustomPlayerServer::notifyHostClientConnected() { if (!player.netSystem) { playerLog("PlayerServer: no netSystem in notifyHostClientConnected()"); return false; } if (connectedIds.empty()) { playerLog("PlayerServer: host client is not connected"); return false; } const std::uint32_t hostClientNetId{SLNet::RakNetGUID::ToUint32(connectedIds[0])}; playerLog(fmt::format("PlayerServer: onPlayerConnected 0x{:x}", hostClientNetId)); player.netSystem->vftable->onPlayerConnected(player.netSystem, (int)hostClientNetId); return true; } game::IMqNetPlayerServer* createCustomPlayerServer(CNetCustomSession* session, game::IMqNetSystem* netSystem, game::IMqNetReception* netReception) { using namespace game; playerLog("Creating player server peer"); SLNet::SocketDescriptor descriptor{CNetCustomPlayer::serverPort, nullptr}; auto peer{NetworkPeer::PeerPtr(SLNet::RakPeerInterface::GetInstance())}; constexpr std::uint16_t maxConnections{4}; peer->SetMaximumIncomingConnections(maxConnections); const auto result{peer->Startup(maxConnections, &descriptor, 1)}; if (result != SLNet::StartupResult::RAKNET_STARTED) { playerLog("Failed to start peer for CNetCustomPlayerServer"); return nullptr; } playerLog("Creating CNetCustomPlayerServer"); auto server = (CNetCustomPlayerServer*)Memory::get().allocate(sizeof(CNetCustomPlayerServer)); new (server) CNetCustomPlayerServer(session, netSystem, netReception, std::move(peer)); playerLog("Player server created"); auto netId = SLNet::RakNetGUID::ToUint32(server->getPeer()->GetMyGUID()); playerLog(fmt::format("CNetCustomPlayerServer has netId 0x{:x}, ", netId)); return server; } } // namespace hooks
15,386
C++
.cpp
331
36.984894
100
0.654136
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,958
attacksourcelist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/attacksourcelist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "attacksourcelist.h" #include "version.h" #include <array> namespace game::AttackSourceListApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Add)0x40a271, }, // Russobit Api{ (Api::Add)0x40a271, }, // Gog Api{ (Api::Add)0x409ef4, }, // Scenario Editor Api{ (Api::Add)0x5237c8, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::AttackSourceListApi
1,365
C++
.cpp
47
25.787234
72
0.70297
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,959
menunewmap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menunewmap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menunewmap.h" namespace game::editor::CMenuNewMapApi { Api& get() { static Api api{ (Api::GetCreationSettings)0x418977, (Api::CheckCreationSettings)0x418ac7, }; return api; } } // namespace game::editor::CMenuNewMapApi
1,074
C++
.cpp
29
34.310345
72
0.747115
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,960
unitbranchcat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitbranchcat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitbranchcat.h" #include "version.h" #include <array> namespace game::UnitBranchCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LUnitBranch*)0x839fc8, (LUnitBranch*)0x839fa8, (LUnitBranch*)0x839fd8, (LUnitBranch*)0x839f98, (LUnitBranch*)0x839f78 }, // Russobit Categories{ (LUnitBranch*)0x839fc8, (LUnitBranch*)0x839fa8, (LUnitBranch*)0x839fd8, (LUnitBranch*)0x839f98, (LUnitBranch*)0x839f78 }, // Gog Categories{ (LUnitBranch*)0x837f78, (LUnitBranch*)0x837f58, (LUnitBranch*)0x837f88, (LUnitBranch*)0x837f48, (LUnitBranch*)0x837f28 }, // Scenario Editor Categories{ (LUnitBranch*)0x665a58, (LUnitBranch*)0x665a38, (LUnitBranch*)0x665a68, (LUnitBranch*)0x665a28, (LUnitBranch*)0x665a08 } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6d8e5c, // Russobit (const void*)0x6d8e5c, // Gog (const void*)0x6d6dfc, // Scenario Editor (const void*)0x5df604 }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::UnitBranchCategories
2,243
C++
.cpp
77
24.597403
72
0.685039
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,961
textids.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/textids.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "textids.h" #include "log.h" #include "scripts.h" #include "utils.h" #include <fmt/format.h> namespace hooks { void readOwnResourceTextIds(const sol::table& table, TextIds::Events::Conditions::OwnResource& value) { value.tooMany = table.get_or("tooMany", std::string()); value.mutuallyExclusive = table.get_or("mutuallyExclusive", std::string()); } void readGameModeTextIds(const sol::table& table, TextIds::Events::Conditions::GameMode& value) { value.tooMany = table.get_or("tooMany", std::string()); value.single = table.get_or("single", std::string()); value.hotseat = table.get_or("hotseat", std::string()); value.online = table.get_or("online", std::string()); } void readPlayerTypeTextIds(const sol::table& table, TextIds::Events::Conditions::PlayerType& value) { value.tooMany = table.get_or("tooMany", std::string()); value.human = table.get_or("human", std::string()); value.ai = table.get_or("ai", std::string()); } void readVariableCmpTextIds(const sol::table& table, TextIds::Events::Conditions::VariableCmp& value) { value.equal = table.get_or("equal", std::string()); value.notEqual = table.get_or("notEqual", std::string()); value.greater = table.get_or("greater", std::string()); value.greaterEqual = table.get_or("greaterEqual", std::string()); value.less = table.get_or("less", std::string()); value.lessEqual = table.get_or("lessEqual", std::string()); } void readConditionsTextIds(const sol::table& table, TextIds::Events::Conditions& value) { auto conditions = table.get<sol::optional<sol::table>>("conditions"); if (!conditions.has_value()) return; auto ownResource = conditions.value().get<sol::optional<sol::table>>("ownResource"); if (ownResource.has_value()) { readOwnResourceTextIds(ownResource.value(), value.ownResource); } auto gameMode = conditions.value().get<sol::optional<sol::table>>("gameMode"); if (gameMode.has_value()) { readGameModeTextIds(gameMode.value(), value.gameMode); } auto playerType = conditions.value().get<sol::optional<sol::table>>("playerType"); if (playerType.has_value()) { readPlayerTypeTextIds(playerType.value(), value.playerType); } auto variableCmp = conditions.value().get<sol::optional<sol::table>>("variableCmp"); if (variableCmp.has_value()) { readVariableCmpTextIds(variableCmp.value(), value.variableCmp); } } void readEventsTextIds(const sol::table& table, TextIds::Events& value) { auto events = table.get<sol::optional<sol::table>>("events"); if (!events.has_value()) return; readConditionsTextIds(events.value(), value.conditions); } void readLobbyTextIds(const sol::table& table, TextIds::Lobby& value) { auto lobbyTable = table.get<sol::optional<sol::table>>("lobby"); if (!lobbyTable.has_value()) return; auto& lobby = lobbyTable.value(); value.serverName = lobby.get_or("serverName", std::string()); value.serverNotResponding = lobby.get_or("serverNotResponding", std::string()); value.connectAttemptFailed = lobby.get_or("connectAttemptFailed", std::string()); value.serverIsFull = lobby.get_or("serverIsFull", std::string()); value.computeHashFailed = lobby.get_or("computeHashFailed", std::string()); value.requestHashCheckFailed = lobby.get_or("requestHashCheckFailed", std::string()); value.wrongHash = lobby.get_or("wrongHash", std::string()); value.wrongRoomPassword = lobby.get_or("wrongRoomPassword", std::string()); } void readGeneratorTextIds(const sol::table& table, TextIds::ScenarioGenerator& value) { auto rsgTable = table.get<sol::optional<sol::table>>("generator"); if (!rsgTable.has_value()) return; auto& rsg = rsgTable.value(); value.description = rsg.get_or("description", std::string()); value.wrongGameData = rsg.get_or("wrongGameData", std::string()); value.generationError = rsg.get_or("generationError", std::string()); value.limitExceeded = rsg.get_or("limitExceeded", std::string()); } void readInterfTextIds(const sol::table& table, TextIds::Interf& value) { auto interf = table.get<sol::optional<sol::table>>("interf"); if (!interf.has_value()) return; value.sellAllValuables = interf.value().get_or("sellAllValuables", std::string()); value.sellAllItems = interf.value().get_or("sellAllItems", std::string()); value.critHitAttack = interf.value().get_or("critHitAttack", std::string()); value.critHitDamage = interf.value().get_or("critHitDamage", std::string()); value.ratedDamage = interf.value().get_or("ratedDamage", std::string()); value.ratedDamageEqual = interf.value().get_or("ratedDamageEqual", std::string()); value.ratedDamageSeparator = interf.value().get_or("ratedDamageSeparator", std::string()); value.splitDamage = interf.value().get_or("splitDamage", std::string()); value.modifiedValue = interf.value().get_or("modifiedValue", std::string()); value.modifiedNumber = interf.value().get_or("modifiedNumber", std::string()); value.modifiedNumberTotal = interf.value().get_or("modifiedNumberTotal", std::string()); value.positiveBonusNumber = interf.value().get_or("positiveBonusNumber", std::string()); value.negativeBonusNumber = interf.value().get_or("negativeBonusNumber", std::string()); value.modifiersCaption = interf.value().get_or("modifiersCaption", std::string()); value.modifiersEmpty = interf.value().get_or("modifiersEmpty", std::string()); value.modifierDescription = interf.value().get_or("modifierDescription", std::string()); value.nativeModifierDescription = interf.value().get_or("nativeModifierDescription", std::string()); value.drainDescription = interf.value().get_or("drainDescription", std::string()); value.drainEffect = interf.value().get_or("drainEffect", std::string()); value.overflowAttack = interf.value().get_or("overflowAttack", std::string()); value.overflowText = interf.value().get_or("overflowText", std::string()); value.dynamicUpgradeLevel = interf.value().get_or("dynamicUpgradeLevel", std::string()); value.dynamicUpgradeValues = interf.value().get_or("dynamicUpgradeValues", std::string()); value.durationDescription = interf.value().get_or("durationDescription", std::string()); value.durationText = interf.value().get_or("durationText", std::string()); value.instantDurationText = interf.value().get_or("instantDurationText", std::string()); value.randomDurationText = interf.value().get_or("randomDurationText", std::string()); value.singleTurnDurationText = interf.value().get_or("singleTurnDurationText", std::string()); value.wholeBattleDurationText = interf.value().get_or("wholeBattleDurationText", std::string()); value.infiniteAttack = interf.value().get_or("infiniteAttack", std::string()); value.infiniteText = interf.value().get_or("infiniteText", std::string()); value.removedAttackWard = interf.value().get_or("removedAttackWard", std::string()); } void initialize(TextIds& value) { const auto path{hooks::scriptsFolder() / "textids.lua"}; try { const auto env{executeScriptFile(path)}; if (!env) return; const sol::table& table = (*env)["textids"]; readInterfTextIds(table, value.interf); readEventsTextIds(table, value.events); readLobbyTextIds(table, value.lobby); readGeneratorTextIds(table, value.rsg); } catch (const std::exception& e) { showErrorMessageBox(fmt::format("Failed to read script '{:s}'.\n" "Reason: '{:s}'", path.string(), e.what())); } } const TextIds& textIds() { static TextIds value; static bool initialized = false; if (!initialized) { initialize(value); initialized = true; } return value; } } // namespace hooks
8,898
C++
.cpp
176
45.159091
100
0.690008
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,962
midgardscenariomap.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midgardscenariomap.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midgardscenariomap.h" #include "version.h" #include <array> namespace game::CMidgardScenarioMapApi { // clang-format off std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetIterator)0x5ef64a, (Api::GetIterator)0x5ef664, (Api::Advance)0x5f0222, (Api::CheckObjects)0x5efcd1, (Api::Stream)0x5efd6c, }, // Russobit Api{ (Api::GetIterator)0x5ef64a, (Api::GetIterator)0x5ef664, (Api::Advance)0x5f0222, (Api::CheckObjects)0x5efcd1, (Api::Stream)0x5efd6c, }, // Gog Api{ (Api::GetIterator)0x5ee30f, (Api::GetIterator)0x5ee329, (Api::Advance)0x410884, (Api::CheckObjects)0x5ee996, (Api::Stream)0x5eea31, }, // Scenario Editor Api{ (Api::GetIterator)0x4dbde5, (Api::GetIterator)0x4dbdff, (Api::Advance)0x4dc693, (Api::CheckObjects)0x4dc157, (Api::Stream)0x4dc1f2, }, }}; static std::array<IMidgardObjectMapVftable*, 4> vftables = {{ // Akella (IMidgardObjectMapVftable*)0x6f0c14, // Russobit (IMidgardObjectMapVftable*)0x6f0c14, // Gog (IMidgardObjectMapVftable*)0x6eebb4, // Scenario Editor (IMidgardObjectMapVftable*)0x5d9354, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } IMidgardObjectMapVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidgardScenarioMapApi
2,339
C++
.cpp
77
25.844156
72
0.690022
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,963
enclayout.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayout.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayout.h" #include "version.h" #include <array> namespace game::IEncLayoutApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5746a7, (Api::Destructor)0x5746e3, }, // Russobit Api{ (Api::Constructor)0x5746a7, (Api::Destructor)0x5746e3, }, // Gog Api{ (Api::Constructor)0x573cfc, (Api::Destructor)0x573d38, }, // Scenario Editor Api{ (Api::Constructor)0x4c5127, (Api::Destructor)0x4c5163, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IEncLayoutApi
1,519
C++
.cpp
51
26.078431
72
0.697198
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,964
scenarioheader.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/scenarioheader.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "scenarioheader.h" #include "version.h" #include <array> namespace game::ScenarioFileHeaderApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::ReadAndCheckHeader)0x5e3db7 }, // Russobit Api{ (Api::ReadAndCheckHeader)0x5e3db7 }, // Gog Api{ (Api::ReadAndCheckHeader)0x5e2ae4 } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::ScenarioFileHeaderApi
1,341
C++
.cpp
43
28.186047
72
0.725445
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,965
midstack.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midstack.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midstack.h" #include "version.h" #include <array> namespace game::CMidStackApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetPosition)0x5edc57, (Api::SetOwner)0x5ee191, }, // Russobit Api{ (Api::SetPosition)0x5edc57, (Api::SetOwner)0x5ee191, }, // Gog Api{ (Api::SetPosition)0x5ec917, (Api::SetOwner)0x5ece51, }, // Scenario Editor Api{ (Api::SetPosition)0x4f14d0, (Api::SetOwner)0x4f1907, }, }}; static std::array<const IMapElementVftable*, 4> vftables = {{ // Akella (const IMapElementVftable*)0x6f0a94, // Russobit (const IMapElementVftable*)0x6f0a94, // Gog (const IMapElementVftable*)0x6eea34, // Scenario Editor (const IMapElementVftable*)0x5da744, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const IMapElementVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidStackApi
1,905
C++
.cpp
65
25.6
72
0.699945
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,966
buildingcat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/buildingcat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "buildingcat.h" #include "version.h" #include <array> namespace game { namespace BuildingCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LBuildingCategory*)0x839a30, (LBuildingCategory*)0x839a40, (LBuildingCategory*)0x839a50, (LBuildingCategory*)0x839a20 }, // Russobit Categories{ (LBuildingCategory*)0x839a30, (LBuildingCategory*)0x839a40, (LBuildingCategory*)0x839a50, (LBuildingCategory*)0x839a20 }, // Gog Categories{ (LBuildingCategory*)0x8379e0, (LBuildingCategory*)0x8379f0, (LBuildingCategory*)0x837a00, (LBuildingCategory*)0x8379d0 }, // Scenario Editor Categories{ (LBuildingCategory*)0x665af8, (LBuildingCategory*)0x665b08, (LBuildingCategory*)0x665b18, (LBuildingCategory*)0x665ae8 } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6d153c, // Russobit (const void*)0x6d153c, // Gog (const void*)0x6cf4dc, // Scenario Editor (const void*)0x5df5dc }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace BuildingCategories namespace LBuildingCategoryTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x58b4a0, (Api::Init)0x58b607, (Api::ReadCategory)0x58b67f, (Api::InitDone)0x58b5c2, (Api::FindCategoryById)0x58c13d, }, // Russobit Api{ (Api::Constructor)0x58b4a0, (Api::Init)0x58b607, (Api::ReadCategory)0x58b67f, (Api::InitDone)0x58b5c2, (Api::FindCategoryById)0x58c13d, }, // Gog Api{ (Api::Constructor)0x58a60c, (Api::Init)0x58a773, (Api::ReadCategory)0x58a7eb, (Api::InitDone)0x58a72e, (Api::FindCategoryById)0x58b2cb, }, // Scenario Editor Api{ (Api::Constructor)0x53b0a8, (Api::Init)0x53b20f, (Api::ReadCategory)0x53b287, (Api::InitDone)0x53b1ca, (Api::FindCategoryById)0x538d2d, } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6ea71c, // Russobit (const void*)0x6ea71c, // Gog (const void*)0x6e86bc, // Scenario Editor (const void*)0x5df714 }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace LBuildingCategoryTableApi } // namespace game
3,618
C++
.cpp
131
22.839695
72
0.673769
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,967
attack.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/attack.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "attack.h" #include "version.h" #include <array> namespace game::IAttackApi { // clang-format off static std::array<IAttackVftable*, 4> vftables = {{ // Akella (IAttackVftable*)0x6eb52c, // Russobit (IAttackVftable*)0x6eb52c, // Gog (IAttackVftable*)0x6e94cc, // Scenario Editor (IAttackVftable*)0x5df4b4, }}; // clang-format on const IAttackVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IAttackApi
1,317
C++
.cpp
39
31.282051
72
0.741555
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,968
cursorhandle.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/cursorhandle.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cursorhandle.h" #include "version.h" #include <array> namespace game::CursorHandleApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Create)0x5b3528, }, // Russobit Api{ (Api::Create)0x5b3528, }, // Gog Api{ (Api::Create)0x5b27ee, }, // Scenario Editor Api{ (Api::Create)0x5548e5, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CursorHandleApi
1,365
C++
.cpp
47
25.787234
72
0.702209
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,969
stringarray.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/stringarray.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stringarray.h" #include "version.h" #include <array> namespace game::StringArrayApi { // clang-format off static std::array<Api, 4> functions = { { // Akella Api{ (Api::Destructor)0x40a63e, (Api::Reserve)0x4173e8, (Api::PushBack)0x4173ba, }, // Russobit Api{ (Api::Destructor)0x40a63e, (Api::Reserve)0x4173e8, (Api::PushBack)0x4173ba, }, // Gog Api{ (Api::Destructor)0x40a27d, (Api::Reserve)0x416fdc, (Api::PushBack)0x416fae, }, // Scenario Editor Api{ (Api::Destructor)0x414f16, (Api::Reserve)0x4370a3, (Api::PushBack)0x414ea3, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::StringArrayApi
1,639
C++
.cpp
55
25.709091
72
0.685877
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,970
cmdbattlestartmsg.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/cmdbattlestartmsg.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cmdbattlestartmsg.h" #include "version.h" #include <array> namespace game::CCmdBattleStartMsgApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Destructor)0x40f257, }, // Russobit Api{ (Api::Destructor)0x40f257, }, // Gog Api{ (Api::Destructor)0x40ee7d, }, // Scenario Editor Api{ (Api::Destructor)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } // clang-format off static std::array<CCommandMsgVftable*, 4> vftables = {{ // Akella (CCommandMsgVftable*)0x6d49c4, // Russobit (CCommandMsgVftable*)0x6d49c4, // Gog (CCommandMsgVftable*)0x6d2964, // Scenario Editor (CCommandMsgVftable*)nullptr, }}; // clang-format on CCommandMsgVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CCmdBattleStartMsgApi
1,797
C++
.cpp
63
25.238095
72
0.709323
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,971
scenariodataarray.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/scenariodataarray.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "scenariodataarray.h" #include "version.h" #include <array> namespace game::ScenarioDataArrayApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::PushBack)0x60613f, (Api::GetElement)0x606051 }, // Russobit Api{ (Api::PushBack)0x60613f, (Api::GetElement)0x606051 }, // Gog Api{ (Api::PushBack)0x604c4c, (Api::GetElement)0x604b5e } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::ScenarioDataArrayApi
1,417
C++
.cpp
46
27.413043
72
0.711567
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,972
midgardmsgbox.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midgardmsgbox.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midgardmsgbox.h" #include "version.h" #include <array> namespace game::CMidgardMsgBoxApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x5c87a3, }, // Russobit Api{ (Api::Constructor)0x5c87a3, }, // Gog Api{ (Api::Constructor)0x5c7771, }, // Scenario Editor Api{ (Api::Constructor)0x4d1bc4, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidgardMsgBoxApi
1,390
C++
.cpp
47
26.319149
72
0.707773
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,973
midevconditionhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midevconditionhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midevconditionhooks.h" #include "d2string.h" #include "eventconditioncathooks.h" #include "game.h" #include "midcondgamemode.h" #include "midcondownresource.h" #include "midcondplayertype.h" #include "midcondscript.h" #include "midcondvarcmp.h" #include "originalfunctions.h" #include <fmt/format.h> namespace hooks { game::CMidEvCondition* __stdcall createEventConditionFromCategoryHooked( const game::LEventCondCategory* category) { const auto& conditions = customEventConditions(); const auto id = category->id; if (id == conditions.ownResource.category.id) { return createMidCondOwnResource(); } if (id == conditions.gameMode.category.id) { return createMidCondGameMode(); } if (id == conditions.playerType.category.id) { return createMidCondPlayerType(); } if (id == conditions.variableCmp.category.id) { return createMidCondVarCmp(); } if (id == conditions.script.category.id) { return createMidCondScript(); } return getOriginalFunctions().createEventConditionFromCategory(category); } void __stdcall eventConditionGetInfoStringHooked(game::String* info, const game::IMidgardObjectMap* objectMap, const game::CMidEvCondition* eventCondition) { const auto& conditions = customEventConditions(); const auto id = eventCondition->category.id; if (id == conditions.ownResource.category.id) { midCondOwnResourceGetInfoString(info, objectMap, eventCondition); return; } if (id == conditions.gameMode.category.id) { midCondGameModeGetInfoString(info, objectMap, eventCondition); return; } if (id == conditions.playerType.category.id) { midCondPlayerTypeGetInfoString(info, objectMap, eventCondition); return; } if (id == conditions.variableCmp.category.id) { midCondVarCmpGetInfoString(info, objectMap, eventCondition); return; } if (id == conditions.script.category.id) { midCondScriptGetInfoString(info, objectMap, eventCondition); return; } getOriginalFunctions().eventConditionGetInfoString(info, objectMap, eventCondition); } void __stdcall eventConditionGetDescriptionHooked(game::String* description, const game::LEventCondCategory* category) { using namespace game; const auto& conditions = customEventConditions(); const auto id = category->id; const CMidgardID* descriptionId{nullptr}; if (id == conditions.ownResource.category.id) { descriptionId = &conditions.ownResource.description; } else if (id == conditions.gameMode.category.id) { descriptionId = &conditions.gameMode.description; } else if (id == conditions.playerType.category.id) { descriptionId = &conditions.playerType.description; } else if (id == conditions.variableCmp.category.id) { descriptionId = &conditions.variableCmp.description; } else if (id == conditions.script.category.id) { descriptionId = &conditions.script.description; } if (descriptionId) { auto text = gameFunctions().getInterfaceText(descriptionId); StringApi::get().initFromStringN(description, text, std::strlen(text)); return; } getOriginalFunctions().eventConditionGetDescription(description, category); } void __stdcall eventConditionGetBriefHooked(game::String* brief, const game::LEventCondCategory* category) { using namespace game; const auto& conditions = customEventConditions(); const auto id = category->id; const CMidgardID* briefId{nullptr}; if (id == conditions.ownResource.category.id) { briefId = &conditions.ownResource.brief; } else if (id == conditions.gameMode.category.id) { briefId = &conditions.gameMode.brief; } else if (id == conditions.playerType.category.id) { briefId = &conditions.playerType.brief; } else if (id == conditions.variableCmp.category.id) { briefId = &conditions.variableCmp.brief; } else if (id == conditions.script.category.id) { briefId = &conditions.script.brief; } if (briefId) { auto text = gameFunctions().getInterfaceText(briefId); StringApi::get().initFromStringN(brief, text, std::strlen(text)); return; } getOriginalFunctions().eventConditionGetBrief(brief, category); } } // namespace hooks
5,394
C++
.cpp
131
34.847328
93
0.699083
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,974
stackbattleactionmsg.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/stackbattleactionmsg.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "stackbattleactionmsg.h" #include "version.h" #include <array> namespace game::CStackBattleActionMsgApi { // clang-format off static std::array<CNetMsgVftable*, 4> vftables = {{ // Akella (CNetMsgVftable*)0x6d50cc, // Russobit (CNetMsgVftable*)0x6d50cc, // Gog (CNetMsgVftable*)0x6d306c, // Scenario Editor (CNetMsgVftable*)nullptr, }}; // clang-format on CNetMsgVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CStackBattleActionMsgApi
1,352
C++
.cpp
39
32.179487
72
0.749235
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,975
menunewskirmishmulti.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menunewskirmishmulti.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menunewskirmishmulti.h" #include "version.h" #include <array> namespace game::CMenuNewSkirmishMultiApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::CreateServer)0x4ea31b, (Api::Constructor)0x4ea0d6, }, // Russobit Api{ (Api::CreateServer)0x4ea31b, (Api::Constructor)0x4ea0d6, }, // Gog Api{ (Api::CreateServer)0x4e97b6, (Api::Constructor)0x4e9571, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMenuNewSkirmishMultiApi
1,447
C++
.cpp
46
28.065217
72
0.7149
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,976
togglebutton.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/togglebutton.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "togglebutton.h" #include "version.h" #include <array> namespace game::CToggleButtonApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::SetChecked)0x5355b3, (Api::AssignFunctor)0x5c947c, }, // Russobit Api{ (Api::SetChecked)0x5355b3, (Api::AssignFunctor)0x5c947c, }, // Gog Api{ (Api::SetChecked)0x534b91, (Api::AssignFunctor)0x5c844a, }, // Scenario Editor Api{ (Api::SetChecked)0x4945d1, (Api::AssignFunctor)nullptr, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CToggleButtonApi
1,535
C++
.cpp
51
26.392157
72
0.700473
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,977
battleattackinfo.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/battleattackinfo.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "battleattackinfo.h" #include "version.h" #include <array> namespace game::BattleAttackInfoApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::AddUnitInfo)0x47ec6a }, // Russobit Api{ (Api::AddUnitInfo)0x47ec6a }, // Gog Api{ (Api::AddUnitInfo)0x47e834 } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BattleAttackInfoApi
1,318
C++
.cpp
43
27.651163
72
0.720472
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,978
batunitanim.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batunitanim.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batunitanim.h" #include "version.h" #include <array> namespace game::BatUnitAnimApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Update)0x652de8, }, // Russobit Api{ (Api::Update)0x652de8, }, // Gog Api{ (Api::Update)0x6515d8, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BatUnitAnimApi
1,293
C++
.cpp
43
27.069767
72
0.711647
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,979
menunewskirmishmultihooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menunewskirmishmultihooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menunewskirmishmultihooks.h" #include "button.h" #include "dialoginterf.h" #include "log.h" #include "netcustomplayerserver.h" #include "netcustomservice.h" #include "netcustomsession.h" #include "originalfunctions.h" namespace hooks { static void __fastcall showMenuRandomScenarioMulti(game::CMenuNewSkirmishMulti* thisptr, int /*%edx*/) { using namespace game; // Transfer to a new random scenario generation menu, from state 6 to 41 CMenuPhase* menuPhase{thisptr->menuBaseData->menuPhase}; CMenuPhaseApi::get().setTransition(menuPhase, 2); } bool __fastcall menuNewSkirmishMultiCreateServerHooked(game::CMenuNewSkirmishMulti* thisptr, int /*%edx*/) { logDebug("lobby.log", "CMenuNewSkirmishMulti::CreateServer"); const auto result{getOriginalFunctions().menuNewSkirmishMultiCreateServer(thisptr)}; if (!result) { // Game failed to initialize session, server or host client logDebug("lobby.log", "Failed to create server"); return false; } auto service{getNetService()}; if (!service) { // Current net service is not custom lobby, use default game logic return result; } auto session{service->session}; if (!session) { logDebug("lobby.log", "Session is null"); return false; } auto playerServer{session->server}; if (!playerServer) { logDebug("lobby.log", "Player server is null"); return false; } logDebug("lobby.log", "Notify player server about host client connection"); // Notify server about host player client connection. // The other clients that connect later will be handled in a usual way using net peer callbacks return playerServer->notifyHostClientConnected(); } game::CMenuNewSkirmishMulti* __fastcall menuNewSkirmishMultiCtorHooked( game::CMenuNewSkirmishMulti* thisptr, int /*%edx*/, game::CMenuPhase* menuPhase) { getOriginalFunctions().menuNewSkirmishMultiCtor(thisptr, menuPhase); using namespace game; static const char buttonName[] = "BTN_RANDOM_MAP"; const auto& menuBase{CMenuBaseApi::get()}; const auto& dialogApi{CDialogInterfApi::get()}; CDialogInterf* dialog{menuBase.getDialogInterface(thisptr)}; // Check if we have new button for random scenario generator menu and setup its callback if (dialogApi.findControl(dialog, buttonName)) { const auto& button{CButtonInterfApi::get()}; SmartPointer functor; auto callback = (CMenuBaseApi::Api::ButtonCallback)showMenuRandomScenarioMulti; menuBase.createButtonFunctor(&functor, 0, thisptr, &callback); button.assignFunctor(dialog, buttonName, "DLG_HOST", &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } return thisptr; } } // namespace hooks
3,748
C++
.cpp
88
37.068182
99
0.714364
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,980
midcondplayertype.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midcondplayertype.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midcondplayertype.h" #include "button.h" #include "condinterf.h" #include "condinterfhandler.h" #include "d2string.h" #include "dialoginterf.h" #include "eventconditioncathooks.h" #include "game.h" #include "interfmanager.h" #include "mempool.h" #include "midevcondition.h" #include "midevent.h" #include "mideventhooks.h" #include "midgardobjectmap.h" #include "midgardstream.h" #include "midplayer.h" #include "testcondition.h" #include "textids.h" #include "togglebutton.h" #include "utils.h" namespace hooks { /** Custom event condition that checks whether affected player is controlled by AI or not. */ struct CMidCondPlayerType : public game::CMidEvCondition { bool playerTypeAi; }; void __fastcall condPlayerTypeDestructor(CMidCondPlayerType* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall condPlayerTypeIsIdsEqual(const CMidCondPlayerType*, int /*%edx*/, const game::CMidgardID*) { return false; } void __fastcall condPlayerTypeAddToList(const CMidCondPlayerType*, int /*%edx*/, game::Set<game::CMidgardID>*) { } bool __fastcall condPlayerTypeIsValid(const CMidCondPlayerType* thisptr, int /*%edx*/, const game::IMidgardObjectMap*) { return true; } bool __fastcall condPlayerTypeMethod4(const CMidCondPlayerType*, int /*%edx*/, int) { return false; } void __fastcall condPlayerTypeStream(CMidCondPlayerType* thisptr, int /*%edx*/, game::IMidgardStream** stream) { auto streamPtr = *stream; auto vftable = streamPtr->vftable; vftable->streamBool(streamPtr, "AI", &thisptr->playerTypeAi); } // clang-format off static game::CMidEvConditionVftable condPlayerTypeVftable{ (game::CMidEvConditionVftable::Destructor)condPlayerTypeDestructor, (game::CMidEvConditionVftable::IsIdsEqual)condPlayerTypeIsIdsEqual, (game::CMidEvConditionVftable::AddToList)condPlayerTypeAddToList, (game::CMidEvConditionVftable::IsValid)condPlayerTypeIsValid, (game::CMidEvConditionVftable::Method4)condPlayerTypeMethod4, (game::CMidEvConditionVftable::Stream)condPlayerTypeStream, }; // clang-format on game::CMidEvCondition* createMidCondPlayerType() { using namespace game; auto playerType = (CMidCondPlayerType*)Memory::get().allocate(sizeof(CMidCondPlayerType)); playerType->category.vftable = EventCondCategories::vftable(); playerType->category.id = customEventConditions().playerType.category.id; playerType->category.table = customEventConditions().playerType.category.table; playerType->playerTypeAi = false; playerType->vftable = &condPlayerTypeVftable; return playerType; } void __stdcall midCondPlayerTypeGetInfoString(game::String* info, const game::IMidgardObjectMap* objectMap, const game::CMidEvCondition* eventCondition) { const auto textInfoId = &customEventConditions().playerType.infoText; std::string str{game::gameFunctions().getInterfaceText(textInfoId)}; const auto ai = static_cast<const CMidCondPlayerType*>(eventCondition)->playerTypeAi; std::string type; const auto& playerTypeTextIds = textIds().events.conditions.playerType; if (ai) { type = getInterfaceText(playerTypeTextIds.ai.c_str()); if (type.empty()) { type = "AI"; } } else { type = getInterfaceText(playerTypeTextIds.human.c_str()); if (type.empty()) { type = "human"; } } replace(str, "%TYPE%", type); game::StringApi::get().initFromStringN(info, str.c_str(), str.length()); } struct CCondPlayerTypeInterf : public game::editor::CCondInterf { void* unknown; CMidCondPlayerType* condition; game::CMidgardID eventId; }; void __fastcall condPlayerTypeInterfDestructor(CCondPlayerTypeInterf* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } static game::CInterfaceVftable::OnVisibilityChanged onVisibilityChanged{}; void __fastcall condPlayerTypeInterfOnVisibilityChanged(CCondPlayerTypeInterf* thisptr, int /*%edx*/, int a2, int a3) { using namespace game; if (onVisibilityChanged) { onVisibilityChanged(thisptr, a2, a3); } if (!a2) { return; } if (!thisptr->condition) { return; } auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); auto toggleButton = dialogApi.findToggleButton(dialog, "TOG_AI"); if (toggleButton) { CToggleButtonApi::get().setChecked(toggleButton, thisptr->condition->playerTypeAi); } } bool __fastcall condPlayerTypeInterfSetEventCondition(CCondPlayerTypeInterf* thisptr, int /*%edx*/, game::CMidEvCondition* eventCondition) { if (eventCondition->category.id == customEventConditions().playerType.category.id) { thisptr->condition = static_cast<CMidCondPlayerType*>(eventCondition); return true; } return false; } static game::editor::CCondInterfVftable condPlayerTypeInterfVftable{}; void __fastcall condPlayerTypeInterfCancelButtonHandler(CCondPlayerTypeInterf* thisptr, int /*%edx*/) { using namespace game; auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, false); } InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } void __fastcall condPlayerTypeInterfOkButtonHandler(CCondPlayerTypeInterf* thisptr, int /*%edx*/) { using namespace game; using namespace editor; auto handler = thisptr->condData->interfHandler; if (handler) { handler->vftable->runCallback(handler, true); } auto objectMap = CCondInterfApi::get().getObjectMap(thisptr->unknown); { auto midEvent = (const CMidEvent*)objectMap->vftable ->findScenarioObjectById(objectMap, &thisptr->eventId); const int conditionsTotal = midEvent->conditions.end - midEvent->conditions.bgn; if (conditionsTotal >= 10) { // Could not create new condition showMessageBox(getInterfaceText("X100TA0631")); return; } } auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); auto condition = static_cast<CMidCondPlayerType*>(createMidCondPlayerType()); auto toggleButton = dialogApi.findToggleButton(dialog, "TOG_AI"); if (toggleButton) { condition->playerTypeAi = toggleButton->data->checked; } auto midEvent = (CMidEvent*)objectMap->vftable ->findScenarioObjectByIdForChange(objectMap, &thisptr->eventId); CMidEventApi::get().addCondition(midEvent, nullptr, condition); InterfManagerImplPtr ptr; CInterfManagerImplApi::get().get(&ptr); ptr.data->CInterfManagerImpl::CInterfManager::vftable->hideInterface(ptr.data, thisptr); SmartPointerApi::get().createOrFree((SmartPointer*)&ptr, nullptr); if (thisptr) { thisptr->CInterface::vftable->destructor(thisptr, 1); } } game::editor::CCondInterf* createCondPlayerTypeInterf(game::ITask* task, void* a2, const game::CMidgardID* eventId) { using namespace game; using namespace editor; auto thisptr = (CCondPlayerTypeInterf*)Memory::get().allocate(sizeof(CCondPlayerTypeInterf)); static const char dialogName[]{"DLG_COND_PLAYER_TYPE"}; CCondInterfApi::get().constructor(thisptr, dialogName, task); static bool initialized{false}; if (!initialized) { initialized = true; onVisibilityChanged = thisptr->CInterface::vftable->onVisibilityChanged; std::memcpy(&condPlayerTypeInterfVftable, thisptr->CInterface::vftable, sizeof(CInterfaceVftable)); // Change methods that are specific for our custom class condPlayerTypeInterfVftable .destructor = (CInterfaceVftable::Destructor)&condPlayerTypeInterfDestructor; condPlayerTypeInterfVftable.onVisibilityChanged = (CInterfaceVftable::OnVisibilityChanged)&condPlayerTypeInterfOnVisibilityChanged; condPlayerTypeInterfVftable .setEventCondition = (CCondInterfVftable:: SetEventCondition)&condPlayerTypeInterfSetEventCondition; } thisptr->CInterface::vftable = &condPlayerTypeInterfVftable; thisptr->eventId = *eventId; thisptr->unknown = a2; thisptr->condition = nullptr; auto dialog = thisptr->popupData->dialog; const auto& dialogApi = CDialogInterfApi::get(); if (dialogApi.findButton(dialog, "BTN_OK")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condPlayerTypeInterfOkButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } if (dialogApi.findButton(dialog, "BTN_CANCEL")) { using ButtonCallback = CCondInterfApi::Api::ButtonCallback; ButtonCallback callback{}; SmartPointer functor{}; callback.callback = (ButtonCallback::Callback)condPlayerTypeInterfCancelButtonHandler; CCondInterfApi::get().createButtonFunctor(&functor, 0, thisptr, &callback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); SmartPointerApi::get().createOrFreeNoDtor(&functor, nullptr); } return thisptr; } struct CTestPlayerType : public game::ITestCondition { CMidCondPlayerType* condition; }; void __fastcall testPlayerTypeDestructor(CTestPlayerType* thisptr, int /*%edx*/, char flags) { if (flags & 1) { game::Memory::get().freeNonZero(thisptr); } } bool __fastcall testPlayerTypeDoTest(const CTestPlayerType* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* playerId, const game::CMidgardID* eventId) { using namespace game; if (!CMidEventApi::get().affectsPlayer(objectMap, playerId, eventId)) { return false; } auto obj = objectMap->vftable->findScenarioObjectById(objectMap, playerId); if (!obj) { return false; } auto player = static_cast<const CMidPlayer*>(obj); return thisptr->condition->playerTypeAi == !player->isHuman; } static game::ITestConditionVftable testPlayerTypeVftable{ (game::ITestConditionVftable::Destructor)testPlayerTypeDestructor, (game::ITestConditionVftable::Test)testPlayerTypeDoTest, }; game::ITestCondition* createTestPlayerType(game::CMidEvCondition* eventCondition) { auto thisptr = (CTestPlayerType*)game::Memory::get().allocate(sizeof(CTestPlayerType)); thisptr->condition = static_cast<CMidCondPlayerType*>(eventCondition); thisptr->vftable = &testPlayerTypeVftable; return thisptr; } bool checkPlayerTypeConditionValid(game::CDialogInterf* dialog, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* eventId) { using namespace game; auto obj = objectMap->vftable->findScenarioObjectById(objectMap, eventId); if (!obj) { return false; } const auto& category = customEventConditions().playerType.category; auto event = static_cast<const CMidEvent*>(obj); std::vector<const CMidEvCondition*> conditions{}; getConditionsOfType(event, &category, conditions); if (conditions.size() > 1) { auto message = getInterfaceText(textIds().events.conditions.playerType.tooMany.c_str()); if (message.empty()) { message = "Only one condition of type \"Player type\" is allowed per event."; } showMessageBox(message); return false; } return true; } } // namespace hooks
14,176
C++
.cpp
337
33.816024
97
0.668266
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,981
registeraccountinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/registeraccountinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "registeraccountinterf.h" #include "button.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "lobbyclient.h" #include "log.h" #include "mempool.h" #include "menubase.h" #include "popupdialoginterf.h" #include "utils.h" #include <fmt/format.h> namespace hooks { struct CRegisterAccountInterf : public game::CPopupDialogInterf { }; static void closeRegisterAccountInterf(CRegisterAccountInterf* interf) { hideInterface(interf); interf->vftable->destructor(interf, 1); } static void __fastcall tryRegisterAccount(CRegisterAccountInterf* thisptr, int /*%edx*/) { logDebug("lobby.log", "User tries to create account"); using namespace game; auto& dialogApi = CDialogInterfApi::get(); auto dialog = *thisptr->dialog; auto accNameEdit = dialogApi.findEditBox(dialog, "EDIT_ACCOUNT_NAME"); if (!accNameEdit) { closeRegisterAccountInterf(thisptr); return; } auto nicknameEdit = dialogApi.findEditBox(dialog, "EDIT_NICKNAME"); if (!nicknameEdit) { closeRegisterAccountInterf(thisptr); return; } auto pwdEdit = dialogApi.findEditBox(dialog, "EDIT_PASSWORD"); if (!pwdEdit) { closeRegisterAccountInterf(thisptr); return; } auto pwdQuestionEdit = dialogApi.findEditBox(dialog, "EDIT_PWD_QUESTION"); if (!pwdQuestionEdit) { closeRegisterAccountInterf(thisptr); return; } auto pwdAnswerEdit = dialogApi.findEditBox(dialog, "EDIT_PWD_ANSWER"); if (!pwdAnswerEdit) { closeRegisterAccountInterf(thisptr); return; } // TODO: better check each input separately and show meaningful info to the player const char* accountName = accNameEdit->data->editBoxData.inputString.string; const char* nickname = nicknameEdit->data->editBoxData.inputString.string; const char* password = pwdEdit->data->editBoxData.inputString.string; const char* pwdQuestion = pwdQuestionEdit->data->editBoxData.inputString.string; const char* pwdAnswer = pwdAnswerEdit->data->editBoxData.inputString.string; if (!tryCreateAccount(accountName, nickname, password, pwdQuestion, pwdAnswer)) { showMessageBox("Wrong account data"); return; } closeRegisterAccountInterf(thisptr); } static void __fastcall cancelRegisterAccount(CRegisterAccountInterf* thisptr, int /*%edx*/) { logDebug("lobby.log", "User canceled account creation"); closeRegisterAccountInterf(thisptr); } CRegisterAccountInterf* createRegisterAccountInterf() { using namespace game; static const char dialogName[]{"DLG_REGISTER_ACCOUNT"}; auto interf = (CRegisterAccountInterf*)Memory::get().allocate(sizeof(CRegisterAccountInterf)); CPopupDialogInterfApi::get().constructor(interf, dialogName, nullptr); auto& dialogApi = CDialogInterfApi::get(); auto dialog = *interf->dialog; SmartPointer functor; auto callback = (CMenuBaseApi::Api::ButtonCallback)cancelRegisterAccount; CMenuBaseApi::get().createButtonFunctor(&functor, 0, (CMenuBase*)interf, &callback); CButtonInterfApi::get().assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)tryRegisterAccount; CMenuBaseApi::get().createButtonFunctor(&functor, 0, (CMenuBase*)interf, &callback); CButtonInterfApi::get().assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); freeFunctor(&functor, nullptr); return interf; } void showRegisterAccountDialog() { showInterface(createRegisterAccountInterf()); } } // namespace hooks
4,505
C++
.cpp
110
36.863636
98
0.746566
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,982
unitmodifierhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/unitmodifierhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "unitmodifierhooks.h" #include "custommodifier.h" #include "custommodifierfunctions.h" #include "custommodifiers.h" #include "d2string.h" #include "dbtable.h" #include "globaldata.h" #include "mempool.h" #include "modifgroup.h" #include "unitmodifier.h" #include <thread> extern std::thread::id mainThreadId; namespace hooks { struct TUnitModifierDataPatched : game::TUnitModifierData { std::string scriptFileName; CustomModifierFunctions* mainThreadFunctions; CustomModifierFunctions* workerThreadFunctions; }; const CustomModifierFunctions& getCustomModifierFunctions(const game::TUnitModifier* unitModifier) { auto data = static_cast<TUnitModifierDataPatched*>(unitModifier->data); auto& functions = std::this_thread::get_id() == mainThreadId ? data->mainThreadFunctions : data->workerThreadFunctions; if (functions == nullptr) { // Functions need to be initialized in a corresponding thread to use its own Lua instance functions = new CustomModifierFunctions(data->scriptFileName); } return *functions; } game::TUnitModifier* __fastcall unitModifierCtorHooked(game::TUnitModifier* thisptr, int /*%edx*/, const game::CDBTable* dbTable, const char* globalsFolderPath, void* codeBaseEnvProxy, const game::GlobalData** globalData) { using namespace game; const auto& memAlloc = Memory::get().allocate; const auto& dbApi = CDBTableApi::get(); const auto& stringApi = StringApi::get(); const auto& idApi = CMidgardIDApi::get(); thisptr->vftable = TUnitModifierApi::vftable(); thisptr->id = emptyId; auto data = (TUnitModifierDataPatched*)memAlloc(sizeof(TUnitModifierDataPatched)); if (data) { data->group.id = (ModifierSourceId)emptyCategoryId; data->group.table = nullptr; data->group.vftable = LModifGroupApi::vftable(); data->modifier = nullptr; new (&data->scriptFileName) std::string(); data->mainThreadFunctions = nullptr; data->workerThreadFunctions = nullptr; } thisptr->data = data; dbApi.readId(&thisptr->id, dbTable, "MODIF_ID"); dbApi.findModifGroupCategory(&data->group, dbTable, "SOURCE", (*globalData)->modifGroups); if (data->group.id == getCustomModifiers().group.id) { String script{}; dbApi.readString(&script, dbTable, "SCRIPT"); if (script.string) data->scriptFileName = script.string; stringApi.free(&script); String descTxtString{}; dbApi.readString(&descTxtString, dbTable, "DESC_TXT"); CMidgardID descTxt; idApi.fromString(&descTxt, descTxtString.string); stringApi.free(&descTxtString); if (descTxt == invalidId) idApi.fromString(&descTxt, "x000tg6000"); // "!! Missing modifier name !!" bool display; dbApi.readBool(&display, dbTable, "DISPLAY"); data->modifier = createCustomModifier(thisptr, data->scriptFileName.c_str(), &descTxt, display, globalData); } else { dbApi.readModifier(&data->modifier, &thisptr->id, &data->group, globalsFolderPath, codeBaseEnvProxy, globalData); } return thisptr; } void __fastcall unitModifierDtorHooked(game::TUnitModifier* thisptr, int /*%edx*/, char flags) { using namespace game; const auto& memFree = Memory::get().freeNonZero; auto data = (TUnitModifierDataPatched*)thisptr->data; if (data) { auto modifier = data->modifier; if (modifier) modifier->vftable->destructor(modifier, true); data->scriptFileName.~basic_string(); if (data->mainThreadFunctions) { delete data->mainThreadFunctions; } if (data->workerThreadFunctions) { delete data->workerThreadFunctions; } memFree(data); } if (flags & 1) { memFree(thisptr); } } } // namespace hooks
5,113
C++
.cpp
121
33.826446
98
0.649688
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,983
batbigface.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/batbigface.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "batbigface.h" #include "version.h" #include <array> namespace game::BatBigFaceApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::SetUnitId)0x650809, (Api::SetUnknown)0x651124, (Api::Update)0x650884, (Api::UnitDataMapErase)0x651520, (Api::UnitDataMapAccess)0x6513e0, (Api::UnitImplDataMapAccess)0x651680, (Api::ItemDataMapAccess)0x4ae89b, }, // Russobit Api{ (Api::SetUnitId)0x650809, (Api::SetUnknown)0x651124, (Api::Update)0x650884, (Api::UnitDataMapErase)0x651520, (Api::UnitDataMapAccess)0x6513e0, (Api::UnitImplDataMapAccess)0x651680, (Api::ItemDataMapAccess)0x4ae89b, }, // Gog Api{ (Api::SetUnitId)0x64f149, (Api::SetUnknown)0x64fa64, (Api::Update)0x64f1c4, (Api::UnitDataMapErase)0x64fe60, (Api::UnitDataMapAccess)0x64fd20, (Api::UnitImplDataMapAccess)0x64ff50, (Api::ItemDataMapAccess)0x4adf16, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::BatBigFaceApi
2,010
C++
.cpp
61
28.180328
72
0.694959
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,984
interfmanager.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/interfmanager.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "interfmanager.h" #include "version.h" #include <array> namespace game::CInterfManagerImplApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Get)0x530ae7, }, // Russobit Api{ (Api::Get)0x530ae7, }, // Gog Api{ (Api::Get)0x530014, }, // Scenario Editor Api{ (Api::Get)0x48bce2, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CInterfManagerImplApi
1,366
C++
.cpp
47
25.808511
72
0.702435
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,985
menucustomlobby.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menucustomlobby.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menucustomlobby.h" #include "autodialog.h" #include "button.h" #include "dialoginterf.h" #include "dynamiccast.h" #include "globaldata.h" #include "image2fill.h" #include "image2outline.h" #include "image2text.h" #include "listbox.h" #include "lobbyclient.h" #include "log.h" #include "loginaccountinterf.h" #include "mempool.h" #include "menuflashwait.h" #include "menuphase.h" #include "midgard.h" #include "netcustomplayerclient.h" #include "netcustomservice.h" #include "netcustomsession.h" #include "netmessages.h" #include "netmsgcallbacks.h" #include "netmsgmapentry.h" #include "racelist.h" #include "registeraccountinterf.h" #include "roompasswordinterf.h" #include "textboxinterf.h" #include "uimanager.h" #include "utils.h" #include <chrono> #include <fmt/chrono.h> #include <thread> namespace hooks { static void menuDeleteWaitMenu(CMenuCustomLobby* menu) { if (menu->waitMenu) { hideInterface(menu->waitMenu); menu->waitMenu->vftable->destructor(menu->waitMenu, 1); menu->waitMenu = nullptr; } } static void menuUpdateAccountText(CMenuCustomLobby* menu, const char* accountName = nullptr) { using namespace game; auto& menuBase = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuBase.getDialogInterface(menu); auto textBox = dialogApi.findTextBox(dialog, "TXT_NICKNAME"); if (accountName) { auto text{fmt::format("\\fLarge;\\vC;\\hC;{:s}", accountName)}; CTextBoxInterfApi::get().setString(textBox, text.c_str()); return; } CTextBoxInterfApi::get().setString(textBox, ""); } static void menuUpdateButtons(CMenuCustomLobby* menu) { using namespace game; const auto loggedIn{menu->loggedIn}; auto& menuBase = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuBase.getDialogInterface(menu); // Disable login button if player has already logged in. auto loginButton = dialogApi.findButton(dialog, "BTN_LOGIN"); loginButton->vftable->setEnabled(loginButton, !loggedIn); // Disable logout and create, load, join buttons if player is not logged in. auto logoutButton = dialogApi.findButton(dialog, "BTN_LOGOUT"); logoutButton->vftable->setEnabled(logoutButton, loggedIn); auto createButton = dialogApi.findButton(dialog, "BTN_CREATE"); createButton->vftable->setEnabled(createButton, loggedIn); auto loadButton = dialogApi.findButton(dialog, "BTN_LOAD"); loadButton->vftable->setEnabled(loadButton, loggedIn); auto joinButton = dialogApi.findButton(dialog, "BTN_JOIN"); joinButton->vftable->setEnabled(joinButton, loggedIn); } void __fastcall menuDestructor(CMenuCustomLobby* thisptr, int /*%edx*/, char flags) { using namespace game; menuDeleteWaitMenu(thisptr); if (thisptr->netMsgEntryData) { logDebug("transitions.log", "Delete custom lobby menu netMsgEntryData"); NetMsgApi::get().freeEntryData(thisptr->netMsgEntryData); } logDebug("transitions.log", "Delete rooms list event"); UiEventApi::get().destructor(&thisptr->roomsListEvent); removeLobbyCallbacks(thisptr->uiCallbacks.get()); removeRoomsCallback(thisptr->roomsCallbacks.get()); thisptr->uiCallbacks.reset(nullptr); thisptr->roomsCallbacks.reset(nullptr); thisptr->rooms.~vector(); CMenuBaseApi::get().destructor(thisptr); if (flags & 1) { logDebug("transitions.log", "Free custom menu memory"); Memory::get().freeNonZero(thisptr); } } static void __fastcall menuRegisterAccountBtnHandler(CMenuCustomLobby*, int /*%edx*/) { showRegisterAccountDialog(); } static void __fastcall menuLoginAccountBtnHandler(CMenuCustomLobby*, int /*%edx*/) { showLoginAccountDialog(); } static void __fastcall menuLogoutAccountBtnHandler(CMenuCustomLobby*, int /*%edx*/) { logDebug("lobby.log", "User logging out"); logoutAccount(); } static void __fastcall menuRoomsListSearchHandler(CMenuCustomLobby*, int /*%edx*/) { logDebug("lobby.log", "Request fresh rooms list"); trySearchRooms(); } static void __fastcall menuCreateRoomBtnHandler(CMenuCustomLobby* thisptr, int /*%edx*/) { auto menuPhase = thisptr->menuBaseData->menuPhase; // Pretend we are in CMenuMulti, transition to CMenuMultyHost menuPhase->data->transitionNumber = 4; logDebug("transitions.log", "Create room, pretend we are in CMenuMulti, transition to CMenuNewSkirmishMulti"); game::CMenuPhaseApi::get().setTransition(menuPhase, 0); } static void __fastcall menuLoadBtnHandler(CMenuCustomLobby* thisptr, int /*%edx*/) { // Pretend we are in CMenuMulti, transition to CMenuLoadSkirmishMulti auto menuPhase = thisptr->menuBaseData->menuPhase; menuPhase->data->transitionNumber = 4; menuPhase->data->networkGame = true; logDebug("transitions.log", "Create room, pretend we are in CMenuMulti, transition to CMenuLoadSkirmishMulti"); game::CMenuPhaseApi::get().setTransition(menuPhase, 2); } static int menuGetCurrentRoomIndex(CMenuCustomLobby* menuLobby) { using namespace game; auto dialog = CMenuBaseApi::get().getDialogInterface(menuLobby); auto listBox = CDialogInterfApi::get().findListBox(dialog, "LBOX_ROOMS"); return CListBoxInterfApi::get().selectedIndex(listBox); } static void menuTryJoinRoom(CMenuCustomLobby* menuLobby, const char* roomName) { using namespace game; if (!tryJoinRoom(roomName)) { logDebug("transitions.log", "Failed to request room join"); } // Rooms callback will notify us when its time to send game messages to server, // requesting version and info. auto& menuBase = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuBase.getDialogInterface(menuLobby); // For now, disable join button auto buttonJoin = dialogApi.findButton(dialog, "BTN_JOIN"); if (buttonJoin) { buttonJoin->vftable->setEnabled(buttonJoin, false); } menuDeleteWaitMenu(menuLobby); auto flashWait = (CMenuFlashWait*)Memory::get().allocate(sizeof(CMenuFlashWait)); CMenuFlashWaitApi::get().constructor(flashWait); showInterface(flashWait); menuLobby->waitMenu = flashWait; } static void menuOnRoomPasswordCorrect(CMenuCustomLobby* menuLobby) { logDebug("transitions.log", "Room password correct, trying to join a room"); // Get current room name, try to join using namespace game; auto index = menuGetCurrentRoomIndex(menuLobby); if (index < 0 || index >= (int)menuLobby->rooms.size()) { return; } const auto& room = menuLobby->rooms[index]; menuTryJoinRoom(menuLobby, room.name.c_str()); } static void menuOnRoomPasswordCancel(CMenuCustomLobby* menuLobby) { // Create rooms list event once again createTimerEvent(&menuLobby->roomsListEvent, menuLobby, menuRoomsListSearchHandler, 5000); } static void __fastcall menuJoinRoomBtnHandler(CMenuCustomLobby* thisptr, int /*%edx*/) { using namespace game; logDebug("transitions.log", "Join room button pressed"); auto index = menuGetCurrentRoomIndex(thisptr); if (index < 0 || index >= (int)thisptr->rooms.size()) { return; } const auto& room = thisptr->rooms[index]; // Do fast check if room can be joined if (room.usedSlots >= room.totalSlots) { // Could not join game. Host did not report any available race. showMessageBox(getInterfaceText("X005TA0886")); return; } // Check if room protected with password, ask user to input if (!room.password.empty()) { // Remove rooms list callback so we don't mess with the list UiEventApi::get().destructor(&thisptr->roomsListEvent); showRoomPasswordDialog(thisptr, menuOnRoomPasswordCorrect, menuOnRoomPasswordCancel); return; } menuTryJoinRoom(thisptr, room.name.c_str()); } static void __fastcall menuListBoxDisplayHandler(CMenuCustomLobby* thisptr, int /*%edx*/, game::ImagePointList* contents, const game::CMqRect* lineArea, int index, bool selected) { if (thisptr->rooms.empty()) { return; } using namespace game; auto& createFreePtr = SmartPointerApi::get().createOrFree; auto& imageApi = CImage2TextApi::get(); const auto width = lineArea->right - lineArea->left; const auto height = lineArea->bottom - lineArea->top; const auto& room = thisptr->rooms[(size_t)index % thisptr->rooms.size()]; // Width of table column border image in pixels const int columnBorderWidth{9}; // 'Host' column with in pixels const int hostTextWidth{122}; int offset = 0; // Host name { auto hostText = (CImage2Text*)Memory::get().allocate(sizeof(CImage2Text)); imageApi.constructor(hostText, hostTextWidth, height); imageApi.setText(hostText, fmt::format("\\vC;{:s}", room.hostName).c_str()); ImagePtrPointPair pair{}; createFreePtr((SmartPointer*)&pair.first, hostText); pair.second.x = offset + 5; pair.second.y = 0; ImagePointListApi::get().add(contents, &pair); createFreePtr((SmartPointer*)&pair.first, nullptr); offset += hostTextWidth + columnBorderWidth; } // 'Description' column width in pixels const int descriptionWidth{452}; // Room description { auto description = (CImage2Text*)Memory::get().allocate(sizeof(CImage2Text)); imageApi.constructor(description, descriptionWidth, height); imageApi.setText(description, fmt::format("\\vC;{:s}", room.name).c_str()); ImagePtrPointPair pair{}; createFreePtr((SmartPointer*)&pair.first, description); pair.second.x = offset + 5; pair.second.y = 0; ImagePointListApi::get().add(contents, &pair); createFreePtr((SmartPointer*)&pair.first, nullptr); offset += descriptionWidth + columnBorderWidth; } // '#' column width const int playerCountWidth{44}; // Number of players in room { auto playerCount = (CImage2Text*)Memory::get().allocate(sizeof(CImage2Text)); imageApi.constructor(playerCount, playerCountWidth, height); imageApi .setText(playerCount, fmt::format("\\vC;\\hC;{:d}/{:d}", room.usedSlots, room.totalSlots).c_str()); ImagePtrPointPair pair{}; createFreePtr((SmartPointer*)&pair.first, playerCount); pair.second.x = offset; pair.second.y = 0; ImagePointListApi::get().add(contents, &pair); createFreePtr((SmartPointer*)&pair.first, nullptr); offset += playerCountWidth + columnBorderWidth; } // Password protection status if (!room.password.empty()) { auto lockImage{AutoDialogApi::get().loadImage("ROOM_PROTECTED")}; ImagePtrPointPair pair{}; createFreePtr((SmartPointer*)&pair.first, lockImage); // Adjust lock image position to match with lock image in column header pair.second.x = offset + 3; pair.second.y = 1; ImagePointListApi::get().add(contents, &pair); createFreePtr((SmartPointer*)&pair.first, nullptr); } // Outline for selected element if (selected) { auto outline = (CImage2Outline*)Memory::get().allocate(sizeof(CImage2Outline)); CMqPoint size{}; size.x = width; size.y = height; game::Color color{}; // 0x0 - transparent, 0xff - opaque std::uint32_t opacity{0xff}; CImage2OutlineApi::get().constructor(outline, &size, &color, opacity); ImagePtrPointPair pair{}; createFreePtr((SmartPointer*)&pair.first, outline); pair.second.x = 0; pair.second.y = 0; ImagePointListApi::get().add(contents, &pair); createFreePtr((SmartPointer*)&pair.first, nullptr); } } static void copyString(char** dest, const char* src) { auto& memory = game::Memory::get(); if (*dest) { memory.freeNonZero(*dest); *dest = nullptr; } if (src && *src) { const auto length = std::strlen(src); *dest = (char*)memory.allocate(length + 1); std::strncpy(*dest, src, length); (*dest)[length] = 0; } } static bool __fastcall menuAnsInfoMsgHandler(CMenuCustomLobby* menu, int /*%edx*/, const game::CMenusAnsInfoMsg* message, std::uint32_t idFrom) { logDebug("netCallbacks.log", fmt::format("CMenusAnsInfoMsg received from 0x{:x}", idFrom)); if (message->raceIds.length == 0) { customLobbyProcessJoinError(menu, "No available races"); return true; } using namespace game; auto menuPhase = menu->menuBaseData->menuPhase; auto globalData = *GlobalDataApi::get().getGlobalData(); auto racesTable = globalData->raceCategories; auto& findRaceById = LRaceCategoryTableApi::get().findCategoryById; auto& listApi = RaceCategoryListApi::get(); auto raceList = &menuPhase->data->races; listApi.freeNodes(raceList); for (auto node = message->raceIds.head->next; node != message->raceIds.head; node = node->next) { const int raceId = static_cast<const int>(node->data); LRaceCategory category{}; findRaceById(racesTable, &category, &raceId); listApi.add(raceList, &category); } menuPhase->data->unknown8 = false; menuPhase->data->suggestedLevel = message->suggestedLevel; copyString(&menuPhase->data->scenarioName, message->scenarioName); copyString(&menuPhase->data->scenarioDescription, message->scenarioDescription); logDebug("netCallbacks.log", "Switch to CMenuLobbyJoin (I hope)"); // Here we can set next menu transition, there is no need to hide wait message, // it will be hidden from the destructor // Pretend we are in transition 15, after CMenuSession, transition to CMenuLobbyJoin menuPhase->data->transitionNumber = 15; menuPhase->data->host = false; logDebug("transitions.log", "Joining room, pretend we are in phase 15, transition to CMenuLobbyJoin"); game::CMenuPhaseApi::get().setTransition(menuPhase, 0); return true; } static bool __fastcall menuGameVersionMsgHandler(CMenuCustomLobby* menu, int /*%edx*/, const game::CGameVersionMsg* message, std::uint32_t idFrom) { // Check server version if (message->gameVersion != 40) { // "You are trying to join a game with a newer or an older version of the game." customLobbyProcessJoinError(menu, getInterfaceText("X006ta0008").c_str()); return true; } using namespace game; CMenusReqInfoMsg requestInfo; requestInfo.vftable = NetMessagesApi::getMenusReqInfoVftable(); auto& midgardApi = CMidgardApi::get(); auto midgard = midgardApi.instance(); midgardApi.sendNetMsgToServer(midgard, &requestInfo); auto msg{fmt::format("CGameVersionMsg received from 0x{:x}", idFrom)}; logDebug("netCallbacks.log", msg); return true; } static game::RttiInfo<game::CInterfaceVftable> menuLobbyRttiInfo; void menuCustomLobbyCtor(CMenuCustomLobby* menu, game::CMenuPhase* menuPhase) { using namespace game; const char dialogName[] = "DLG_CUSTOM_LOBBY"; auto& menuBase = CMenuBaseApi::get(); logDebug("transitions.log", "Call CMenuBase c-tor for CMenuCustomLobby"); menuBase.constructor(menu, menuPhase); auto vftable = &menuLobbyRttiInfo.vftable; static bool firstTime{true}; if (firstTime) { firstTime = false; // Reuse object locator for our custom menu. // We only need it for dynamic_cast<CAnimInterf>() to work properly without exceptions // when the game exits main loop and checks for current CInterface. // See DestroyAnimInterface() in IDA. replaceRttiInfo(menuLobbyRttiInfo, menu->vftable); vftable->destructor = (game::CInterfaceVftable::Destructor)&menuDestructor; } menu->vftable = vftable; logDebug("transitions.log", "Call createMenu for CMenuCustomLobby"); menuBase.createMenu(menu, dialogName); std::vector<RoomInfo>().swap(menu->rooms); menu->loggedIn = false; const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; // Setup button handlers { auto dialog = menuBase.getDialogInterface(menu); SmartPointer functor; menuBase.createButtonFunctor(&functor, 0, menu, &menuBase.buttonBackCallback); const auto& button = CButtonInterfApi::get(); button.assignFunctor(dialog, "BTN_BACK", dialogName, &functor, 0); freeFunctor(&functor, nullptr); auto callback = (CMenuBaseApi::Api::ButtonCallback)menuRegisterAccountBtnHandler; menuBase.createButtonFunctor(&functor, 0, menu, &callback); button.assignFunctor(dialog, "BTN_REGISTER", dialogName, &functor, 0); freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)menuLoginAccountBtnHandler; menuBase.createButtonFunctor(&functor, 0, menu, &callback); button.assignFunctor(dialog, "BTN_LOGIN", dialogName, &functor, 0); freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)menuLogoutAccountBtnHandler; menuBase.createButtonFunctor(&functor, 0, menu, &callback); button.assignFunctor(dialog, "BTN_LOGOUT", dialogName, &functor, 0); freeFunctor(&functor, nullptr); auto& dialogApi = CDialogInterfApi::get(); auto logoutButton = dialogApi.findButton(dialog, "BTN_LOGOUT"); if (logoutButton) { logoutButton->vftable->setEnabled(logoutButton, false); } callback = (CMenuBaseApi::Api::ButtonCallback)menuCreateRoomBtnHandler; menuBase.createButtonFunctor(&functor, 0, menu, &callback); button.assignFunctor(dialog, "BTN_CREATE", dialogName, &functor, 0); freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)menuLoadBtnHandler; menuBase.createButtonFunctor(&functor, 0, menu, &callback); button.assignFunctor(dialog, "BTN_LOAD", dialogName, &functor, 0); freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)menuJoinRoomBtnHandler; menuBase.createButtonFunctor(&functor, 0, menu, &callback); button.assignFunctor(dialog, "BTN_JOIN", dialogName, &functor, 0); freeFunctor(&functor, nullptr); auto buttonCreate = dialogApi.findButton(dialog, "BTN_CREATE"); if (buttonCreate) { buttonCreate->vftable->setEnabled(buttonCreate, false); } auto buttonLoad = dialogApi.findButton(dialog, "BTN_LOAD"); if (buttonLoad) { buttonLoad->vftable->setEnabled(buttonLoad, false); } auto buttonJoin = dialogApi.findButton(dialog, "BTN_JOIN"); if (buttonJoin) { buttonJoin->vftable->setEnabled(buttonJoin, false); } auto displayCallback = (CMenuBaseApi::Api::ListBoxDisplayCallback)menuListBoxDisplayHandler; menuBase.createListBoxDisplayFunctor(&functor, 0, menu, &displayCallback); auto listBox = dialogApi.findListBox(dialog, "LBOX_ROOMS"); if (listBox) { CListBoxInterfApi::get().assignDisplaySurfaceFunctor(dialog, "LBOX_ROOMS", dialogName, &functor); CListBoxInterfApi::get().setElementsTotal(listBox, 0); } freeFunctor(&functor, nullptr); } // Setup lobby callbacks { menu->uiCallbacks = std::make_unique<UiUpdateCallbacks>(menu); addLobbyCallbacks(menu->uiCallbacks.get()); } // Setup ingame net message callbacks { logDebug("netCallbacks.log", "Allocate entry data"); auto& netApi = NetMsgApi::get(); netApi.allocateEntryData(menu->menuBaseData->menuPhase, &menu->netMsgEntryData); auto& entryApi = CNetMsgMapEntryApi::get(); logDebug("netCallbacks.log", "Allocate CMenusAnsInfoMsg entry"); auto infoCallback = (CNetMsgMapEntryApi::Api::MenusAnsInfoCallback)menuAnsInfoMsgHandler; auto entry = entryApi.allocateMenusAnsInfoEntry(menu, infoCallback); logDebug("netCallbacks.log", "Add CMenusAnsInfoMsg entry"); netApi.addEntry(menu->netMsgEntryData, entry); logDebug("netCallbacks.log", "Allocate CGameVersionMsg entry"); auto versionCallback = (CNetMsgMapEntryApi::Api::GameVersionCallback) menuGameVersionMsgHandler; entry = entryApi.allocateGameVersionEntry(menu, versionCallback); logDebug("netCallbacks.log", "Add CGameVersionMsg entry"); netApi.addEntry(menu->netMsgEntryData, entry); } } game::CMenuBase* __stdcall createCustomLobbyMenu(game::CMenuPhase* menuPhase) { auto menu = (CMenuCustomLobby*)game::Memory::get().allocate(sizeof(CMenuCustomLobby)); std::memset(menu, 0, sizeof(CMenuCustomLobby)); menuCustomLobbyCtor(menu, menuPhase); return menu; } void customLobbyShowError(const char* message) { showMessageBox(fmt::format("\\fLarge;\\hC;Error\\fSmall;\n\n{:s}", message)); } void customLobbyProcessLogin(CMenuCustomLobby* menu, const char* accountName) { using namespace game; // Remember account that successfully logged in setCurrentLobbyPlayer(accountName); menuUpdateAccountText(menu, accountName); menu->loggedIn = true; menuUpdateButtons(menu); // Connect ui-related rooms callbacks menu->roomsCallbacks = std::make_unique<RoomsListCallbacks>(menu); addRoomsCallback(menu->roomsCallbacks.get()); // Request rooms list as soon as possible, no need to wait for event trySearchRooms(); // Add timer event that will send rooms list requests every 5 seconds createTimerEvent(&menu->roomsListEvent, menu, menuRoomsListSearchHandler, 5000); } void customLobbyProcessLogout(CMenuCustomLobby* menu) { using namespace game; // Forget about logged account setCurrentLobbyPlayer(nullptr); menuUpdateAccountText(menu); menu->loggedIn = false; menuUpdateButtons(menu); // Remove timer event game::UiEventApi::get().destructor(&menu->roomsListEvent); // Disconnect ui-related rooms callbacks removeRoomsCallback(menu->roomsCallbacks.get()); menu->roomsCallbacks.reset(nullptr); auto& menuBase = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuBase.getDialogInterface(menu); auto listBox = dialogApi.findListBox(dialog, "LBOX_ROOMS"); auto& listBoxApi = CListBoxInterfApi::get(); // Clean up any rooms information to be safe listBoxApi.setElementsTotal(listBox, 0); menu->rooms.clear(); } void customLobbySetRoomsInfo(CMenuCustomLobby* menu, std::vector<RoomInfo>&& rooms) { using namespace game; auto& menuBase = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuBase.getDialogInterface(menu); auto listBox = dialogApi.findListBox(dialog, "LBOX_ROOMS"); auto& listBoxApi = CListBoxInterfApi::get(); if (!menu->loggedIn) { listBoxApi.setElementsTotal(listBox, 0); menu->rooms.clear(); return; } listBoxApi.setElementsTotal(listBox, (int)rooms.size()); menu->rooms = std::move(rooms); } void customLobbyProcessJoinError(CMenuCustomLobby* menu, const char* message) { using namespace game; menuDeleteWaitMenu(menu); auto& menuBase = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuBase.getDialogInterface(menu); // TODO: check player entered a room in lobby server, // if so, leave it and enable join button in rooms callback auto buttonJoin = dialogApi.findButton(dialog, "BTN_JOIN"); if (buttonJoin) { buttonJoin->vftable->setEnabled(buttonJoin, true); } customLobbyShowError(message); } bool customLobbyCheckRoomPassword(CMenuCustomLobby* menu, const char* password) { using namespace game; auto index = menuGetCurrentRoomIndex(menu); if (index < 0 || index >= (int)menu->rooms.size()) { return false; } const auto& room = menu->rooms[index]; return room.password == password; } } // namespace hooks
25,664
C++
.cpp
590
36.845763
100
0.690374
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,986
image2outline.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/image2outline.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "image2outline.h" #include "version.h" #include <array> namespace game::CImage2OutlineApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x53abbe, }, // Russobit Api{ (Api::Constructor)0x53abbe, }, // Gog Api{ (Api::Constructor)0x53a25f, }, // Scenario Editor Api{ (Api::Constructor)0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CImage2OutlineApi
1,383
C++
.cpp
47
26.170213
72
0.706236
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,987
idset.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/idset.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "idset.h" #include "version.h" #include <array> namespace game::IdSetApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x407b06, (Api::Destructor)0x407ce9, (Api::Insert)0x525755, (Api::Find)0x59f52d, }, // Russobit Api{ (Api::Constructor)0x407b06, (Api::Destructor)0x407ce9, (Api::Insert)0x525755, (Api::Find)0x59f52d, }, // Gog Api{ (Api::Constructor)0x40778d, (Api::Destructor)0x407995, (Api::Insert)0x524c35, (Api::Find)0x53207e, }, // Scenario Editor Api{ (Api::Constructor)0x408512, (Api::Destructor)0x408635, (Api::Insert)0x408551, (Api::Find)0x54770d, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::IdSetApi
1,744
C++
.cpp
59
25.135593
72
0.674405
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,988
tilevariation.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/tilevariation.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tilevariation.h" #include "version.h" #include <array> namespace game::CTileVariationApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::CheckData)0x59b07e, (Api::CheckRecordsCorrect)0x59b8f2, }, // Russobit Api{ (Api::CheckData)0x59b07e, (Api::CheckRecordsCorrect)0x59b8f2, }, // Gog Api{ (Api::CheckData)0x59a1d0, (Api::CheckRecordsCorrect)0x59aa44, }, // Scenario Editor Api{ (Api::CheckData)0x53dd3a, (Api::CheckRecordsCorrect)0x53e5ae, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CTileVariationApi
1,558
C++
.cpp
51
26.843137
72
0.70506
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,989
isoengineground.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/isoengineground.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "isoengineground.h" #include "version.h" #include <array> namespace game::CGroundTextureApi { // clang-format off static std::array<IMqTextureVftable*, 4> vftables = {{ // Akella (IMqTextureVftable*)0x6e40c4, // Russobit (IMqTextureVftable*)0x6e40c4, // Gog (IMqTextureVftable*)0x6e2064, // Scenario Editor (IMqTextureVftable*)0x5d54b4, }}; static std::array<CIsoEngineGroundVftable*, 4> isoEngineVftables = {{ // Akella (CIsoEngineGroundVftable*)0x6e40b4, // Russobit (CIsoEngineGroundVftable*)0x6e40b4, // Gog (CIsoEngineGroundVftable*)0x6e2054, // Scenario Editor (CIsoEngineGroundVftable*)0x5d54a4, }}; static std::array<void*, 4> borderMaskBuffers = {{ // Akella (void*)0x837df0, // Russobit (void*)0x837df0, // Gog (void*)0x835da0, // Scenario Editor (void*)0x663a60, }}; // clang-format on IMqTextureVftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } CIsoEngineGroundVftable* isoEngineVftable() { return isoEngineVftables[static_cast<int>(hooks::gameVersion())]; } void* borderMaskBuffer() { return borderMaskBuffers[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CGroundTextureApi
2,073
C++
.cpp
67
27.940299
72
0.734602
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,990
lobbyclient.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/lobbyclient.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "lobbyclient.h" #include "log.h" #include "netcustomservice.h" #include <fmt/format.h> namespace hooks { // Hardcoded in client and server #if 0 static const char titleName[]{"Test Title Name"}; static const char titleSecretKey[]{"Test secret key"}; #else static const char titleName[]{"Disciples2 Motlin"}; static const char titleSecretKey[]{"Disciples2 Key"}; #endif const char* serverGuidColumnName{"ServerGuid"}; const char* passwordColumnName{"Password"}; bool tryCreateAccount(const char* accountName, const char* nickname, const char* password, const char* pwdRecoveryQuestion, const char* pwdRecoveryAnswer) { if (!accountName) { logDebug("lobby.log", "Empty account name"); return false; } if (!nickname) { logDebug("lobby.log", "Empty nick name"); return false; } if (!password) { logDebug("lobby.log", "Empty password"); return false; } if (!pwdRecoveryQuestion) { logDebug("lobby.log", "Empty pwd recv question"); return false; } if (!pwdRecoveryAnswer) { logDebug("lobby.log", "Empty pwd recv answer"); return false; } auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } auto msg{netService->lobbyMsgFactory.Alloc(SLNet::L2MID_Client_RegisterAccount)}; auto account{static_cast<SLNet::Client_RegisterAccount*>(msg)}; if (!account) { logDebug("lobby.log", "Can not allocate account message"); return false; } account->userName = accountName; account->titleName = titleName; auto& params = account->createAccountParameters; params.firstName = nickname; params.lastName = params.firstName; params.password = password; params.passwordRecoveryQuestion = pwdRecoveryQuestion; params.passwordRecoveryAnswer = pwdRecoveryAnswer; const auto result{account->PrevalidateInput()}; if (!result) { logDebug("lobby.log", "Wrong account registration data"); } else { netService->lobbyClient.SendMsg(account); logDebug("lobby.log", "Account registration sent"); } netService->lobbyMsgFactory.Dealloc(account); return result; } bool tryLoginAccount(const char* accountName, const char* password) { if (!accountName) { return false; } if (!password) { return false; } auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } auto msg{netService->lobbyMsgFactory.Alloc(SLNet::L2MID_Client_Login)}; auto login{static_cast<SLNet::Client_Login*>(msg)}; if (!login) { logDebug("lobby.log", "Can not allocate login message"); return false; } login->userName = accountName; login->userPassword = password; login->titleName = titleName; login->titleSecretKey = titleSecretKey; const auto result{login->PrevalidateInput()}; if (!result) { logDebug("lobby.log", "Wrong account data"); } else { netService->lobbyClient.SendMsg(login); logDebug("lobby.log", "Trying to login"); } netService->lobbyMsgFactory.Dealloc(login); return result; } void logoutAccount() { auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return; } auto msg{netService->lobbyMsgFactory.Alloc(SLNet::L2MID_Client_Logoff)}; auto logoff{static_cast<SLNet::Client_Logoff*>(msg)}; if (!logoff) { logDebug("lobby.log", "Can not allocate logoff message"); return; } netService->lobbyClient.SendMsg(logoff); netService->lobbyMsgFactory.Dealloc(logoff); } void setCurrentLobbyPlayer(const char* accountName) { auto netService{getNetService()}; if (!netService) { return; } if (accountName) { logDebug("lobby.log", fmt::format("Set current logged accout to {:s}", accountName)); netService->loggedAccount = accountName; } else { logDebug("lobby.log", "Forget current logged accout"); netService->loggedAccount.clear(); } } bool tryCreateRoom(const char* roomName, const char* serverGuid, const char* password) { if (!roomName) { logDebug("lobby.log", "Could not create a room: no room name provided"); return false; } if (!serverGuid) { logDebug("lobby.log", "Could not create a room: empty server guid"); return false; } auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } SLNet::CreateRoom_Func room{}; room.gameIdentifier = titleName; room.userName = netService->loggedAccount.c_str(); room.resultCode = SLNet::REC_SUCCESS; auto& params = room.networkedRoomCreationParameters; params.roomName = roomName; params.slots.publicSlots = 1; params.slots.reservedSlots = 0; params.slots.spectatorSlots = 0; logDebug("lobby.log", fmt::format("Account {:s} is trying to create and enter a room " "with serverGuid {:s}, password {:s}", room.userName.C_String(), serverGuid, (password ? password : ""))); auto& properties = room.initialRoomProperties; const auto guidColumn{ properties.AddColumn(serverGuidColumnName, DataStructures::Table::STRING)}; constexpr auto invalidColumn{std::numeric_limits<unsigned int>::max()}; if (guidColumn == invalidColumn) { logDebug("lobby.log", fmt::format("Could not add server guid column to room properties table")); return false; } unsigned int passwordColumn{invalidColumn}; if (password) { passwordColumn = properties.AddColumn(passwordColumnName, DataStructures::Table::STRING); if (passwordColumn == invalidColumn) { logDebug("lobby.log", fmt::format("Could not add password column to room properties table")); return false; } } auto row = properties.AddRow(0); if (!row) { logDebug("lobby.log", "Could not add row to room properties table"); return false; } row->UpdateCell(guidColumn, serverGuid); if (password) { row->UpdateCell(passwordColumn, password); } logDebug("lobby.log", fmt::format("Account {:s} is trying to create and enter a room {:s}", room.userName.C_String(), params.roomName.C_String())); netService->roomsClient.ExecuteFunc(&room); return true; } bool trySearchRooms(const char* accountName) { auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } SLNet::SearchByFilter_Func search; search.gameIdentifier = titleName; search.userName = accountName ? accountName : netService->loggedAccount.c_str(); logDebug("lobby.log", fmt::format("Account {:s} is trying to search rooms", search.userName.C_String())); netService->roomsClient.ExecuteFunc(&search); return true; } bool tryJoinRoom(const char* roomName) { if (!roomName) { logDebug("lobby.log", "Could not join room without a name"); return false; } auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } SLNet::JoinByFilter_Func join; join.gameIdentifier = titleName; join.userName = netService->loggedAccount.c_str(); join.query.AddQuery_STRING(DefaultRoomColumns::GetColumnName(DefaultRoomColumns::TC_ROOM_NAME), roomName); join.roomMemberMode = RMM_PUBLIC; logDebug("lobby.log", fmt::format("Account {:s} is trying to join room {:s}", join.userName.C_String(), roomName)); netService->roomsClient.ExecuteFunc(&join); return true; } bool tryChangeRoomPublicSlots(unsigned int publicSlots) { if (publicSlots < 1) { logDebug("lobby.log", "Could not set number of room public slots lesser than 1"); return false; } auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } SLNet::ChangeSlotCounts_Func slotCounts; slotCounts.userName = netService->loggedAccount.c_str(); slotCounts.slots.publicSlots = publicSlots; logDebug("lobby.log", fmt::format("Account {:s} is trying to change room public slots to {:d}", slotCounts.userName.C_String(), publicSlots)); netService->roomsClient.ExecuteFunc(&slotCounts); return true; } bool tryCheckFilesIntegrity(const char* hash) { if (!hash || !std::strlen(hash)) { logDebug("lobby.log", "Could not check client integrity with empty hash"); return false; } auto netService{getNetService()}; if (!netService) { logDebug("lobby.log", "No net service in midgard"); return false; } SLNet::BitStream stream; stream.Write(static_cast<SLNet::MessageID>(ID_CHECK_FILES_INTEGRITY)); stream.Write(hash); const auto serverAddress{netService->lobbyClient.GetServerAddress()}; const auto result{netService->lobbyPeer.peer->Send(&stream, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED, 0, serverAddress, false)}; return result != 0; } } // namespace hooks
10,664
C++
.cpp
288
30.295139
99
0.658556
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,991
categorylist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/categorylist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "categorylist.h" #include "version.h" #include <array> namespace game::CategoryListApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x424628, (Api::Clear)0x40a549, (Api::FreeNode)0x4c8755, }, // Russobit Api{ (Api::Constructor)0x424628, (Api::Clear)0x40a549, (Api::FreeNode)0x4c8755, }, // Gog Api{ (Api::Constructor)0x42413b, (Api::Clear)0x40a22b, (Api::FreeNode)0x5215fc, }, // Scenario Editor Api{ (Api::Constructor)0x402fed, (Api::Clear)0x43ee56, (Api::FreeNode)0x4fd186, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CategoryListApi
1,638
C++
.cpp
55
25.690909
72
0.686312
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,992
midgardid.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midgardid.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midgardid.h" #include "version.h" #include <array> namespace game { const CMidgardID invalidId{0x3f0000}; const CMidgardID emptyId{0}; namespace CMidgardIDApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::GetCategory)0x57fcc5, (Api::GetCategoryIndex)0x57fcde, (Api::GetType)0x57fcfe, (Api::GetTypeIndex)0x57fd1a, (Api::ToString)0x57fd37, (Api::FromString)0x57f897, (Api::FromParts)0x57fbfa, (Api::IsIdStringValid)0x57fb49, (Api::IsSummonUnitId)0x64599f, (Api::SummonUnitIdFromPosition)0x645abe, (Api::SummonUnitIdToPosition)0x645b37, (Api::ChangeType)0x599e59, (Api::ValidateId)0x57fb6f, (Api::IdTypeToString)0x57fc80, }, // Russobit Api{ (Api::GetCategory)0x57fcc5, (Api::GetCategoryIndex)0x57fcde, (Api::GetType)0x57fcfe, (Api::GetTypeIndex)0x57fd1a, (Api::ToString)0x57fd37, (Api::FromString)0x57f897, (Api::FromParts)0x57fbfa, (Api::IsIdStringValid)0x57fb49, (Api::IsSummonUnitId)0x64599f, (Api::SummonUnitIdFromPosition)0x645abe, (Api::SummonUnitIdToPosition)0x645b37, (Api::ChangeType)0x599e59, (Api::ValidateId)0x57fb6f, (Api::IdTypeToString)0x57fc80, }, // Gog Api{ (Api::GetCategory)0x57f37d, (Api::GetCategoryIndex)0x57f396, (Api::GetType)0x57f3b6, (Api::GetTypeIndex)0x57f3d2, (Api::ToString)0x57f3ef, (Api::FromString)0x57ef4f, (Api::FromParts)0x57f2b2, (Api::IsIdStringValid)0x57f201, (Api::IsSummonUnitId)0x6441cf, (Api::SummonUnitIdFromPosition)0x6442ee, (Api::SummonUnitIdToPosition)0x644367, (Api::ChangeType)0x598fe3, (Api::ValidateId)0x57f227, (Api::IdTypeToString)0x57f338, }, // Scenario Editor Api{ (Api::GetCategory)0x5275d3, (Api::GetCategoryIndex)0x5275ec, (Api::GetType)0x52760c, (Api::GetTypeIndex)0x527628, (Api::ToString)0x527645, (Api::FromString)0x5271a5, (Api::FromParts)0x527508, (Api::IsIdStringValid)nullptr, (Api::IsSummonUnitId)nullptr, (Api::SummonUnitIdFromPosition)nullptr, (Api::SummonUnitIdToPosition)nullptr, (Api::ChangeType)0x544a43, (Api::ValidateId)0x52747d, (Api::IdTypeToString)0x52758e, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace CMidgardIDApi } // namespace game
3,453
C++
.cpp
103
27.427184
72
0.676242
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,993
encyclopediapopup.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/encyclopediapopup.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "encyclopediapopup.h" #include "version.h" #include <array> namespace game::CEncyclopediaPopupApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x4c6937, }, // Russobit Api{ (Api::Constructor)0x4c6937, }, // Gog Api{ (Api::Constructor)0x4c5fca, }, // Scenario Editor Api{ }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CEncyclopediaPopupApi namespace game::editor::CEncyclopediaPopupApi { // clang-format off static Api functions = { (Api::Constructor)0x45765c, }; // clang-format on Api& get() { return functions; } } // namespace game::editor::CEncyclopediaPopupApi
1,606
C++
.cpp
57
25.245614
72
0.718182
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,994
loginaccountinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/loginaccountinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "loginaccountinterf.h" #include "button.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "lobbyclient.h" #include "log.h" #include "mempool.h" #include "menubase.h" #include "popupdialoginterf.h" #include "utils.h" #include <fmt/format.h> namespace hooks { struct CLoginAccountInterf : public game::CPopupDialogInterf { }; static void closeLoginAccountInterf(CLoginAccountInterf* interf) { hideInterface(interf); interf->vftable->destructor(interf, 1); } static void __fastcall loginAccount(CLoginAccountInterf* thisptr, int /*%edx*/) { logDebug("lobby.log", "User tries to log in"); using namespace game; auto& dialogApi = CDialogInterfApi::get(); auto dialog = *thisptr->dialog; auto accNameEdit = dialogApi.findEditBox(dialog, "EDIT_ACCOUNT_NAME"); if (!accNameEdit) { logDebug("lobby.log", "Edit account ui element not found"); closeLoginAccountInterf(thisptr); return; } auto pwdEdit = dialogApi.findEditBox(dialog, "EDIT_PASSWORD"); if (!pwdEdit) { logDebug("lobby.log", "Edit password ui element not found"); closeLoginAccountInterf(thisptr); return; } const char* accountName = accNameEdit->data->editBoxData.inputString.string; const char* password = pwdEdit->data->editBoxData.inputString.string; if (!tryLoginAccount(accountName, password)) { showMessageBox("Wrong user input"); return; } closeLoginAccountInterf(thisptr); } static void __fastcall cancelLoginAccount(CLoginAccountInterf* thisptr, int /*%edx*/) { logDebug("lobby.log", "User canceled logging in"); closeLoginAccountInterf(thisptr); } static CLoginAccountInterf* createLoginAccountInterf() { using namespace game; static const char dialogName[]{"DLG_LOGIN_ACCOUNT"}; auto interf = (CLoginAccountInterf*)Memory::get().allocate(sizeof(CLoginAccountInterf)); CPopupDialogInterfApi::get().constructor(interf, dialogName, nullptr); const auto createFunctor = CMenuBaseApi::get().createButtonFunctor; const auto assignFunctor = CButtonInterfApi::get().assignFunctor; const auto freeFunctor = SmartPointerApi::get().createOrFreeNoDtor; auto& dialogApi = CDialogInterfApi::get(); auto dialog = *interf->dialog; SmartPointer functor; auto callback = (CMenuBaseApi::Api::ButtonCallback)cancelLoginAccount; createFunctor(&functor, 0, (CMenuBase*)interf, &callback); assignFunctor(dialog, "BTN_CANCEL", dialogName, &functor, 0); freeFunctor(&functor, nullptr); callback = (CMenuBaseApi::Api::ButtonCallback)loginAccount; createFunctor(&functor, 0, (CMenuBase*)interf, &callback); assignFunctor(dialog, "BTN_OK", dialogName, &functor, 0); freeFunctor(&functor, nullptr); return interf; } void showLoginAccountDialog() { showInterface(createLoginAccountInterf()); } } // namespace hooks
3,729
C++
.cpp
95
35.515789
92
0.742731
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,995
dialoginterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/dialoginterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dialoginterf.h" #include "version.h" #include <array> namespace game::CDialogInterfApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::FindControl)0x50c206, (Api::FindUiElement<CButtonInterf>)0x50baaf, (Api::FindUiElement<CListBoxInterf>)0x50bacf, (Api::FindUiElement<CTextBoxInterf>)0x50bb0f, (Api::FindUiElement<CPictureInterf>)0x50badf, (Api::FindUiElement<CRadioButtonInterf>)0x50baef, (Api::FindUiElement<CToggleButton>)0x50bb1f, (Api::FindUiElement<CSpinButtonInterf>)0x50baff, (Api::FindUiElement<CEditBoxInterf>)0x50babf, (Api::FindUiElement<CScrollBarInterf>)nullptr, (Api::ShowControl)0x5c9d95, (Api::HideControl)0x50c291, }, // Russobit Api{ (Api::FindControl)0x50c206, (Api::FindUiElement<CButtonInterf>)0x50baaf, (Api::FindUiElement<CListBoxInterf>)0x50bacf, (Api::FindUiElement<CTextBoxInterf>)0x50bb0f, (Api::FindUiElement<CPictureInterf>)0x50badf, (Api::FindUiElement<CRadioButtonInterf>)0x50baef, (Api::FindUiElement<CToggleButton>)0x50bb1f, (Api::FindUiElement<CSpinButtonInterf>)0x50baff, (Api::FindUiElement<CEditBoxInterf>)0x50babf, (Api::FindUiElement<CScrollBarInterf>)nullptr, (Api::ShowControl)0x5c9d95, (Api::HideControl)0x50c291, }, // Gog Api{ (Api::FindControl)0x50b70a, (Api::FindUiElement<CButtonInterf>)0x50afb3, (Api::FindUiElement<CListBoxInterf>)0x50afd3, (Api::FindUiElement<CTextBoxInterf>)0x50b013, (Api::FindUiElement<CPictureInterf>)0x50afe3, (Api::FindUiElement<CRadioButtonInterf>)0x50aff3, (Api::FindUiElement<CToggleButton>)0x50b023, (Api::FindUiElement<CSpinButtonInterf>)0x50b003, (Api::FindUiElement<CEditBoxInterf>)0x50afc3, (Api::FindUiElement<CScrollBarInterf>)nullptr, (Api::ShowControl)0x5c8d63, (Api::HideControl)0x50b795, }, // Scenario Editor Api{ (Api::FindControl)0x4a3d15, (Api::FindUiElement<CButtonInterf>)0x4a3501, (Api::FindUiElement<CListBoxInterf>)0x4a3521, (Api::FindUiElement<CTextBoxInterf>)0x4a3571, (Api::FindUiElement<CPictureInterf>)0x4a3531, (Api::FindUiElement<CRadioButtonInterf>)0x4a3541, (Api::FindUiElement<CToggleButton>)0x4a3581, (Api::FindUiElement<CSpinButtonInterf>)0x4a3561, (Api::FindUiElement<CEditBoxInterf>)0x4a3511, (Api::FindUiElement<CScrollBarInterf>)0x4a3551, (Api::ShowControl)0x4d19c7, (Api::HideControl)0x4a3da0, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CDialogInterfApi
3,644
C++
.cpp
91
34.010989
72
0.708286
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,996
terraincat.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/terraincat.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "terraincat.h" #include "version.h" #include <array> namespace game { namespace TerrainCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LTerrainCategory*)0x8399c8, (LTerrainCategory*)0x8399b0, (LTerrainCategory*)0x839990, (LTerrainCategory*)0x8399a0, (LTerrainCategory*)0x839980, (LTerrainCategory*)0x839970, }, // Russobit Categories{ (LTerrainCategory*)0x8399c8, (LTerrainCategory*)0x8399b0, (LTerrainCategory*)0x839990, (LTerrainCategory*)0x8399a0, (LTerrainCategory*)0x839980, (LTerrainCategory*)0x839970, }, // Gog Categories{ (LTerrainCategory*)0x837978, (LTerrainCategory*)0x837960, (LTerrainCategory*)0x837940, (LTerrainCategory*)0x837950, (LTerrainCategory*)0x837930, (LTerrainCategory*)0x837920, }, // Scenario Editor Categories{ (LTerrainCategory*)0x664f30, (LTerrainCategory*)0x664f18, (LTerrainCategory*)0x664ef8, (LTerrainCategory*)0x664f08, (LTerrainCategory*)0x664ee8, (LTerrainCategory*)0x664ed8, }, }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6cf9d4, // Russobit (const void*)0x6cf9d4, // Gog (const void*)0x6cd974, // Scenario Editor (const void*)0x5ca8e4 }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace TerrainCategories namespace LTerrainCategoryTableApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x58a72a, (Api::Init)0x58a8bf, (Api::ReadCategory)0x58a937, (Api::InitDone)0x58a87a, (Api::FindCategoryById)0x4791c3, }, // Russobit Api{ (Api::Constructor)0x58a72a, (Api::Init)0x58a8bf, (Api::ReadCategory)0x58a937, (Api::InitDone)0x58a87a, (Api::FindCategoryById)0x4791c3, }, // Gog Api{ (Api::Constructor)0x589899, (Api::Init)0x589a2e, (Api::ReadCategory)0x589aa6, (Api::InitDone)0x5899e9, (Api::FindCategoryById)0x478d8f, }, // Scenario Editor Api{ (Api::Constructor)0x52aaa4, (Api::Init)0x52ac39, (Api::ReadCategory)0x52acb1, (Api::InitDone)0x52abf4, (Api::FindCategoryById)0x4e443a, } }}; static std::array<const void*, 4> vftables = {{ // Akella (const void*)0x6ea63c, // Russobit (const void*)0x6ea63c, // Gog (const void*)0x6e85dc, // Scenario Editor (const void*)0x5ddb9c }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace LTerrainCategoryTableApi } // namespace game
3,899
C++
.cpp
139
23.021583
72
0.670494
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,997
condinterfhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/condinterfhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "condinterfhooks.h" #include "eventconditioncathooks.h" #include "midcondgamemode.h" #include "midcondownresource.h" #include "midcondplayertype.h" #include "midcondscript.h" #include "midcondvarcmp.h" #include "originalfunctions.h" namespace hooks { game::editor::CCondInterf* __stdcall createCondInterfFromCategoryHooked( game::ITask* task, void* a2, const game::CMidgardID* eventId, const game::LEventCondCategory* category) { const auto& conditions = customEventConditions(); const auto id = category->id; if (id == conditions.ownResource.category.id) { return createCondOwnResourceInterf(task, a2, eventId); } if (id == conditions.gameMode.category.id) { return createCondGameModeInterf(task, a2, eventId); } if (id == conditions.playerType.category.id) { return createCondPlayerTypeInterf(task, a2, eventId); } if (id == conditions.variableCmp.category.id) { return createCondVarCmpInterf(task, a2, eventId); } if (id == conditions.script.category.id) { return createCondScriptInterf(task, a2, eventId); } return getOriginalFunctions().createCondInterfFromCategory(task, a2, eventId, category); } } // namespace hooks
2,063
C++
.cpp
53
35.377358
92
0.743
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,998
capitalraceset.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/capitalraceset.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "capitalraceset.h" #include "version.h" #include <array> namespace game::CapitalRaceSetApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x56b1ca, (Api::Add)0x56b228, }, // Russobit Api{ (Api::Constructor)0x56b1ca, (Api::Add)0x56b228, }, // Gog Api{ (Api::Constructor)0x56a87a, (Api::Add)0x56a8d8, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CapitalRaceSetApi
1,399
C++
.cpp
46
27.021739
72
0.70549
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541,999
menuloadskirmishmultihooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menuloadskirmishmultihooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menuloadskirmishmultihooks.h" #include "dialoginterf.h" #include "editboxinterf.h" #include "log.h" #include "netcustomplayerserver.h" #include "netcustomservice.h" #include "netcustomsession.h" #include "originalfunctions.h" #include "roomservercreation.h" #include "utils.h" namespace hooks { static bool isRoomAndPlayerNamesValid(game::CMenuBase* menu) { using namespace game; auto& menuApi = CMenuBaseApi::get(); auto& dialogApi = CDialogInterfApi::get(); auto dialog = menuApi.getDialogInterface(menu); auto editGame = dialogApi.findEditBox(dialog, "EDIT_GAME"); if (!editGame || !std::strlen(editGame->data->editBoxData.inputString.string)) { return false; } auto editName = dialogApi.findEditBox(dialog, "EDIT_NAME"); if (!editName || !std::strlen(editName->data->editBoxData.inputString.string)) { return false; } return true; } void __fastcall menuLoadSkirmishMultiLoadScenarioHooked(game::CMenuLoad* thisptr, int /*%edx*/) { auto service = getNetService(); if (!service) { // Current net service is not custom lobby, use default game logic getOriginalFunctions().menuLoadSkirmishMultiLoadScenario(thisptr); return; } if (!isRoomAndPlayerNamesValid(thisptr)) { // Please enter valid game and player names showMessageBox(getInterfaceText("X005TA0867")); return; } logDebug("lobby.log", "Custom lobby net service in CMenuLoad!"); startRoomAndServerCreation(thisptr, true); } void __fastcall menuLoadSkirmishMultiCreateHostPlayerHooked(game::CMenuLoad* thisptr, int /*%edx*/) { auto service = getNetService(); if (service) { auto session{service->session}; if (!session) { logDebug("lobby.log", "Session is null"); return; } auto playerServer{session->server}; if (!playerServer) { logDebug("lobby.log", "Player server is null"); return; } logDebug("lobby.log", "Notify player server about host client connection in CMenuLoad"); // Notify server about host player client connection. // The other clients that connect later will be handled in a usual way using net peer // callbacks playerServer->notifyHostClientConnected(); } getOriginalFunctions().menuLoadSkirmishMultiCreateHostPlayer(thisptr); } } // namespace hooks
3,253
C++
.cpp
84
33.904762
99
0.713923
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,000
midserver.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midserver.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midserver.h" #include "version.h" #include <array> namespace game::CMidServerApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::SendNetMsg)0x4336dc, }, // Russobit Api{ (Api::SendNetMsg)0x4336dc, }, // Gog Api{ (Api::SendNetMsg)0x4331a1, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMidServerApi
1,301
C++
.cpp
43
27.255814
72
0.713488
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,001
midunithooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/midunithooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "midunithooks.h" #include "campaignstream.h" #include "custommodifier.h" #include "custommodifiers.h" #include "dynamiccast.h" #include "log.h" #include "midgardstream.h" #include "midgardstreamenv.h" #include "modifierutils.h" #include "originalfunctions.h" #include "settings.h" #include "streamutils.h" #include "stringandid.h" #include "stringpairarrayptr.h" #include "ummodifier.h" #include "unitgenerator.h" #include "unitmodifier.h" #include "unitutils.h" #include "ussoldier.h" #include "usunit.h" #include "usunitimpl.h" #include <fmt/format.h> namespace hooks { bool __fastcall addModifierHooked(game::CMidUnit* thisptr, int /*%edx*/, const game::CMidgardID* modifierId) { return addModifier(thisptr, modifierId, true); } bool __fastcall removeModifierHooked(game::CMidUnit* thisptr, int /*%edx*/, const game::CMidgardID* modifierId) { using namespace game; const auto& umModifierApi = CUmModifierApi::get(); if (!thisptr) { return false; } CUmModifier* modifier = nullptr; for (auto curr = thisptr->unitImpl; curr; curr = modifier->data->prev) { modifier = castUnitToUmModifier(curr); if (!modifier) { break; } if (modifier->data->modifierId == *modifierId) { auto prev = modifier->data->prev; auto next = modifier->data->next; if (next) { umModifierApi.setPrev(next, prev); } else { thisptr->unitImpl = prev; } auto prevModifier = castUnitToUmModifier(prev); if (prevModifier) { prevModifier->data->next = next; } if (userSettings().modifiers.notifyModifiersChanged) { notifyModifiersChanged(thisptr->unitImpl); } modifier->vftable->destructor(modifier, true); return true; } } return false; } bool __fastcall transformHooked(game::CMidUnit* thisptr, int /*%edx*/, const game::CScenarioVisitor* visitor, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* transformImplId, bool keepHp) { using namespace game; const auto& fn = gameFunctions(); const auto& unitApi = CMidUnitApi::get(); const auto& global = GlobalDataApi::get(); if (thisptr->transformed && !unitApi.untransform(thisptr, visitor)) return false; if (thisptr->origTypeId == emptyId) { auto soldier = fn.castUnitImplToSoldier(thisptr->unitImpl); thisptr->transformed = true; thisptr->origTypeId = thisptr->unitImpl->id; thisptr->keepHp = keepHp; thisptr->hpBefore = thisptr->currentHp; thisptr->hpBefMax = soldier->vftable->getHitPoints(soldier); thisptr->origXp = thisptr->currentXp; unitApi.getModifiers(&thisptr->origModifiers, thisptr); } auto globalData = *global.getGlobalData(); auto globalUnitImpl = static_cast<TUsUnitImpl*>( global.findById(globalData->units, &thisptr->unitImpl->id)); auto globalTransformImpl = static_cast<TUsUnitImpl*>( global.findById(globalData->units, transformImplId)); if (!fn.castUnitImplToStackLeader(globalUnitImpl) && fn.castUnitImplToStackLeader(globalTransformImpl)) { auto globalTransformSoldier = fn.castUnitImplToSoldier(globalTransformImpl); auto transformName = globalTransformSoldier->vftable->getName(globalTransformSoldier); StringAndIdApi::get().setString(&thisptr->name, transformName); } thisptr->currentXp = 0; if (!unitApi.removeModifiers(&thisptr->unitImpl) || !unitApi.replaceImpl(&thisptr->unitImpl, globalTransformImpl) || !unitApi.addModifiers(&thisptr->origModifiers, thisptr, nullptr, true)) { return false; } if (!keepHp) { // Fix unit transformation to include hp mods into current hp recalculation auto transformedSoldier = fn.castUnitImplToSoldier(thisptr->unitImpl); int transformedHp = transformedSoldier->vftable->getHitPoints(transformedSoldier); thisptr->currentHp = transformedHp * thisptr->hpBefore / thisptr->hpBefMax; if (thisptr->currentHp == 0) thisptr->currentHp = 1; } return true; } bool __fastcall upgradeHooked(game::CMidUnit* thisptr, int /*%edx*/, const game::CScenarioVisitor* visitor, const game::CMidgardID* upgradeImplId) { using namespace game; const auto& fn = gameFunctions(); const auto& unitApi = CMidUnitApi::get(); const auto& listApi = IdListApi::get(); const auto& rttiApi = RttiApi::get(); const auto& typeIdOperator = *rttiApi.typeIdOperator; const auto& typeInfoInequalityOperator = *rttiApi.typeInfoInequalityOperator; auto upgradeUnitImpl = getUnitImpl(upgradeImplId); if (!upgradeUnitImpl) return false; auto unitImpl = getUnitImpl(thisptr->unitImpl); if (typeInfoInequalityOperator(typeIdOperator(unitImpl), typeIdOperator(upgradeUnitImpl))) return false; IdList modifierIds{}; listApi.constructor(&modifierIds); if (!unitApi.getModifiers(&modifierIds, thisptr) || !unitApi.removeModifiers(&thisptr->unitImpl) || !unitApi.replaceImpl(&thisptr->unitImpl, upgradeUnitImpl) || !unitApi.addModifiers(&modifierIds, thisptr, nullptr, true)) { listApi.destructor(&modifierIds); return false; } listApi.destructor(&modifierIds); // Reset XP first, because getHitPoints can return different values depending on current XP in // case of custom modifiers (has real examples in MNS) auto soldier = fn.castUnitImplToSoldier(thisptr->unitImpl); thisptr->currentXp = 0; thisptr->currentHp = soldier->vftable->getHitPoints(soldier); return true; } bool __fastcall initWithSoldierImplHooked(game::CMidUnit* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitImplId, const int* turn) { using namespace game; if (!getOriginalFunctions().initWithSoldierImpl(thisptr, objectMap, unitImplId, turn)) { return false; } for (const auto& modifierId : getNativeModifiers(thisptr->unitImpl->id)) { CMidUnitApi::get().addModifier(thisptr, &modifierId); } return true; } void __fastcall midUnitStreamHooked(game::CMidUnit* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, game::IMidgardStreamEnv* streamEnv) { using namespace game; const auto& fn = gameFunctions(); const auto& stringPairArrayPtrApi = StringPairArrayPtrApi::get(); const auto& campaignStreamApi = CampaignStreamApi::get(); const auto& midUnitApi = CMidUnitApi::get(); StringPairArrayPtr arrayPtr; stringPairArrayPtrApi.constructor(&arrayPtr); CampaignStream campaignStream; static const char* dbfFileName = "SUnit.dbf"; campaignStreamApi.constructor(&campaignStream, streamEnv, &dbfFileName, &arrayPtr); stringPairArrayPtrApi.setData(&arrayPtr, nullptr); if (campaignStreamApi.hasErrors(&campaignStream)) { fn.throwScenarioException("", "Invalid Stream"); } // Fixes issues with current hp/xp being higher than maximum values when corresponding modifiers // are added/removed. Only validates in write mode (game server or editor) to have actual // scenario map available to custom mod scripts. // TODO: implement efficient scheme of keeping current hp, xp and move points aligned with // its max values, given that custom modifiers scripts can alter it freely (not only upon // modifier addition or removal). if (streamEnv->vftable->writeMode(streamEnv)) { validateUnit(thisptr); } auto& stream = campaignStream.stream; auto& streamVPtr = stream->vftable; streamVPtr->enterRecord(stream); streamVPtr->streamId(stream, "UNIT_ID", &thisptr->id); midUnitApi.streamImpl(&stream, &thisptr->unitImpl); midUnitApi.streamModifiers(&stream, &thisptr->id, thisptr); streamTurn(stream, "CREATION", &thisptr->creation); streamVPtr->streamText(stream, "NAME_TXT", &thisptr->name, 0); streamVPtr->streamBool(stream, "TRANSF", &thisptr->transformed); if (thisptr->transformed) { streamVPtr->streamId(stream, "ORIGTYPEID", &thisptr->origTypeId); streamVPtr->streamBool(stream, "KEEP_HP", &thisptr->keepHp); streamVPtr->streamInt(stream, "ORIG_XP", &thisptr->origXp); streamVPtr->streamInt(stream, "HP_BEFORE", &thisptr->hpBefore); streamVPtr->streamInt(stream, "HP_BEF_MAX", &thisptr->hpBefMax); } if (streamVPtr->hasValue(stream, "DYNLEVEL")) { streamVPtr->streamBool(stream, "DYNLEVEL", &thisptr->dynLevel); } else { thisptr->dynLevel = false; } streamVPtr->streamInt(stream, "HP", &thisptr->currentHp); if (thisptr->currentHp < 0) { thisptr->currentHp = 0; } streamVPtr->streamInt(stream, "XP", &thisptr->currentXp); if (thisptr->currentXp < 0) { thisptr->currentXp = 0; } // Moved calls of soldier->getHitPoints / getXpNext to later phase of scenario load // (see loadScenarioMapHooked and scenarioMapStreamHooked), because of an issue with custom // modifiers where corresponding scripts are trying to access unit stack or other scenario // objects while the scenario is being loaded and expected objects are not accessible yet. streamVPtr->leaveRecord(stream); campaignStreamApi.destructor(&campaignStream); } bool __stdcall getModifiersHooked(game::IdList* value, const game::CMidUnit* unit) { using namespace game; const auto& listApi = IdListApi::get(); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; listApi.clear(value); NativeModifiers nativeModifiers = getNativeModifiers(unit->unitImpl->id); CUmModifier* modifier = nullptr; for (auto curr = unit->unitImpl; curr; curr = modifier->data->prev) { modifier = (CUmModifier*)dynamicCast(curr, 0, rtti.IUsUnitType, rtti.CUmModifierType, 0); if (!modifier) break; auto modifierId = modifier->data->modifierId; auto it = std::find(nativeModifiers.begin(), nativeModifiers.end(), modifierId); if (it != nativeModifiers.end()) { // Count skipped in case if native mod is duplicated by normal one nativeModifiers.erase(it); continue; } listApi.pushFront(value, &modifierId); } return true; } bool canReapplyModifier(const game::CMidUnit* unit, const game::TUnitModifier* unitModifier) { using namespace game; const auto& fn = gameFunctions(); // Fix exception while streaming, copying or untransforming unit when previously applied // modifier suddenly becomes inapplicable ("sudden death of leader" issue). The cause is // custom modifier that can grant different bonuses at different times, causing standard // modifiers to become inapplicable (CUmStack granting leader abilities), or the custom // modifier itself suddenly returning false on 'canApplyToUnit' check when it is already // applied. auto modifier = unitModifier->data->modifier; if (castModifierToCustomModifier(modifier)) { return true; } else if (castUmModifierToUmStack(modifier)) { // Do only minimal check for CUmStack - skip checking of IUsStackLeader::hasAbility. // Cannot patch CUmStack::canApplyToUnit directly - otherwise leaders can be offered // duplicated upgrades on level-up. return fn.castUnitImplToStackLeader(unit->unitImpl) != nullptr; } return false; } bool addModifier(game::CMidUnit* unit, const game::CMidgardID* modifierId, char* errorBuffer, bool skipInapplicable) { using namespace game; const auto unitModifier = getUnitModifier(modifierId); if (!unitModifier) { auto message = fmt::format("MidUnit: Missing modifier '{:s}', unit '{:s}'", idToString(modifierId), idToString(&unit->id)); errorBuffer[message.copy(errorBuffer, 128)] = 0; return false; } if (!unitModifier->vftable->canApplyToUnit(unitModifier, unit->unitImpl)) { if (skipInapplicable) { return true; } if (!canReapplyModifier(unit, unitModifier)) { auto message = fmt::format("MidUnit: Invalid modifier '{:s}', unit '{:s}'", idToString(modifierId), idToString(&unit->id)); errorBuffer[message.copy(errorBuffer, 128)] = 0; return false; } } return addModifier(unit, modifierId, false); } bool __stdcall addModifiersHooked(const game::IdList* value, game::CMidUnit* unit, char* errorBuffer, bool skipInapplicable) { for (const auto& modifierId : getNativeModifiers(unit->unitImpl->id)) { if (!addModifier(unit, &modifierId, errorBuffer, skipInapplicable)) { return false; } } for (const auto& modifierId : *value) { if (!addModifier(unit, &modifierId, errorBuffer, skipInapplicable)) { return false; } } return true; } bool __stdcall removeModifiersHooked(game::IUsUnit** unitImpl) { using namespace game; for (auto curr = *unitImpl; curr; curr = *unitImpl) { auto modifier = castUnitToUmModifier(curr); if (!modifier) { break; } *unitImpl = modifier->data->prev; auto prevModifier = castUnitToUmModifier(*unitImpl); if (prevModifier) { prevModifier->data->next = nullptr; } modifier->vftable->destructor(modifier, true); } return true; } void __stdcall midUnitStreamImplIdAndLevelHooked(game::IMidgardStream** stream, game::CMidgardID* unitImplId, const char* idName, const char* levelName) { using namespace game; const auto& fn = gameFunctions(); const auto& globalApi = GlobalDataApi::get(); auto streamPtr = *stream; const GlobalUnits* units = (*globalApi.getGlobalData())->units; auto unitGenerator = (*globalApi.getGlobalData())->unitGenerator; int unitLevel = 0; CMidgardID globalUnitImplId = emptyId; if (streamPtr->vftable->writeMode(streamPtr) && *unitImplId != emptyId) { unitGenerator->vftable->getGlobalUnitImplId(unitGenerator, &globalUnitImplId, unitImplId); auto unitImpl = static_cast<TUsUnitImpl*>(globalApi.findById(units, unitImplId)); auto soldier = fn.castUnitImplToSoldier(unitImpl); unitLevel = soldier->vftable->getLevel(soldier); } streamPtr->vftable->streamId(streamPtr, idName, &globalUnitImplId); streamPtr->vftable->streamInt(streamPtr, levelName, &unitLevel); if (streamPtr->vftable->readMode(streamPtr)) { if (globalUnitImplId == emptyId) { *unitImplId = emptyId; } else { unitGenerator->vftable->generateUnitImplId(unitGenerator, unitImplId, &globalUnitImplId, unitLevel); if (*unitImplId == emptyId) { // Clamp only on failed generation for better performance int levelMin = fn.getUnitLevelByImplId(&globalUnitImplId); int levelMax = unitGenerator->vftable->getGeneratedUnitImplLevelMax(unitGenerator); unitLevel = std::clamp(unitLevel, levelMin, levelMax); logDebug("scenario.log", fmt::format("Adjusted level of unit impl '{:s}' to {:d}", idToString(&globalUnitImplId), unitLevel)); unitGenerator->vftable->generateUnitImplId(unitGenerator, unitImplId, &globalUnitImplId, unitLevel); } if (!unitGenerator->vftable->generateUnitImpl(unitGenerator, unitImplId)) { auto message = fmt::format( "Unable to generate unit impl with id '{:s}' and level {:d}", idToString(&globalUnitImplId), unitLevel); fn.throwScenarioException("MidUnit", message.c_str()); } } } } } // namespace hooks
17,975
C++
.cpp
398
36.045226
100
0.648091
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,002
doppelgangerhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/doppelgangerhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "doppelgangerhooks.h" #include "attack.h" #include "batattackdoppelganger.h" #include "battleattackinfo.h" #include "battlemsgdata.h" #include "battlemsgdataview.h" #include "game.h" #include "globaldata.h" #include "immunecat.h" #include "itemview.h" #include "log.h" #include "midgardobjectmap.h" #include "midunit.h" #include "scripts.h" #include "settings.h" #include "unitgenerator.h" #include "unitview.h" #include "ussoldier.h" #include "usunitimpl.h" #include "utils.h" #include "visitors.h" #include <fmt/format.h> namespace hooks { static int getDoppelgangerTransformLevel(const game::CMidUnit* doppelganger, const game::CMidUnit* targetUnit, const game::IMidgardObjectMap* objectMap, const game::CMidgardID* unitOrItemId, const game::BattleMsgData* battleMsgData) { using namespace game; // The function is only accessed by the server thread - the single instance is enough. static std::optional<sol::environment> env; static std::optional<sol::function> getLevel; const auto path{scriptsFolder() / "doppelganger.lua"}; if (!env && !getLevel) { getLevel = getScriptFunction(path, "getLevel", env, true, true); } if (!getLevel) { return 0; } try { const bindings::UnitView attacker{doppelganger}; const bindings::UnitView target{targetUnit}; const bindings::BattleMsgDataView battleView{battleMsgData, objectMap}; if (CMidgardIDApi::get().getType(unitOrItemId) == IdType::Item) { const bindings::ItemView itemView{unitOrItemId, objectMap}; return (*getLevel)(attacker, target, &itemView, battleView); } else return (*getLevel)(attacker, target, nullptr, battleView); } catch (const std::exception& e) { showErrorMessageBox(fmt::format("Failed to run '{:s}' script.\n" "Reason: '{:s}'", path.string(), e.what())); return 0; } } bool isAllyTarget(game::CBatAttackDoppelganger* thisptr, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; CMidgardID unitGroupId{}; gameFunctions().getAllyOrEnemyGroupId(&unitGroupId, battleMsgData, &thisptr->unitId, true); CMidgardID targetUnitGroupId{}; gameFunctions().getAllyOrEnemyGroupId(&targetUnitGroupId, battleMsgData, targetUnitId, true); return unitGroupId == targetUnitGroupId; } bool __fastcall doppelgangerAttackCanPerformHooked(game::CBatAttackDoppelganger* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); if (battle.cannotUseDoppelgangerAttack(&thisptr->unitId, battleMsgData) || !thisptr->hasTargetsToTransformInto) { return thisptr->altAttack->vftable->canPerform(thisptr->altAttack, objectMap, battleMsgData, targetUnitId); } if (battle.getUnitStatus(battleMsgData, targetUnitId, BattleStatus::Dead)) return false; const auto& fn = gameFunctions(); const CMidUnit* targetUnit = fn.findUnitById(objectMap, targetUnitId); const IUsUnit* targetUnitImpl = targetUnit->unitImpl; const LUnitCategory* unitCategory = targetUnitImpl->vftable->getCategory(targetUnitImpl); if (unitCategory->id == UnitId::Illusion || unitCategory->id == UnitId::Guardian) return false; const IUsSoldier* targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); if (!targetSoldier->vftable->getSizeSmall(targetSoldier)) return false; const IAttack* targetAttack = targetSoldier->vftable->getAttackById(targetSoldier); const LAttackClass* targetAttackClass = targetAttack->vftable->getAttackClass(targetAttack); if (targetAttackClass->id == AttackClassId::Doppelganger) return false; bool ally = isAllyTarget(thisptr, battleMsgData, targetUnitId); if (ally && !userSettings().doppelgangerRespectsAllyImmunity) return true; if (!ally && !userSettings().doppelgangerRespectsEnemyImmunity) return true; IAttack* attack = fn.getAttackById(objectMap, &thisptr->attackImplUnitId, thisptr->attackNumber, false); return !fn.isUnitImmuneToAttack(objectMap, battleMsgData, targetUnitId, attack, true); } /* * CBatLogic::battleTurn incorrectly handles immunities to doppelganger and transform self * attacks. Had to call removeUnitAttackSourceWard and removeUnitAttackClassWard here as a * backdoor. CBatLogic::battleTurn needs to be rewritten someday. */ bool __fastcall doppelgangerAttackIsImmuneHooked(game::CBatAttackDoppelganger* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* unitId) { using namespace game; const auto& battle = BattleMsgDataApi::get(); if (battle.cannotUseDoppelgangerAttack(&thisptr->unitId, battleMsgData) || !thisptr->hasTargetsToTransformInto) { return thisptr->altAttack->vftable->isImmune(thisptr->altAttack, objectMap, battleMsgData, unitId); } bool ally = isAllyTarget(thisptr, battleMsgData, unitId); if (ally && !userSettings().doppelgangerRespectsAllyImmunity) return false; if (!ally && !userSettings().doppelgangerRespectsEnemyImmunity) return false; const auto& fn = gameFunctions(); IAttack* attack = fn.getAttackById(objectMap, &thisptr->attackImplUnitId, thisptr->attackNumber, false); const CMidUnit* targetUnit = fn.findUnitById(objectMap, unitId); const IUsSoldier* targetSoldier = fn.castUnitImplToSoldier(targetUnit->unitImpl); const LAttackSource* attackSource = attack->vftable->getAttackSource(attack); const LImmuneCat* immuneCat = targetSoldier->vftable->getImmuneByAttackSource(targetSoldier, attackSource); const LAttackClass* attackClass = attack->vftable->getAttackClass(attack); const LImmuneCat* immuneCatC = targetSoldier->vftable->getImmuneByAttackClass(targetSoldier, attackClass); bool result = false; if (immuneCat->id == ImmuneCategories::get().once->id) { result = !battle.isUnitAttackSourceWardRemoved(battleMsgData, unitId, attackSource); if (result) battle.removeUnitAttackSourceWard(battleMsgData, unitId, attackSource); } else if (immuneCat->id == ImmuneCategories::get().always->id) { result = true; } if (immuneCatC->id == ImmuneCategories::get().once->id) { result = !battle.isUnitAttackClassWardRemoved(battleMsgData, unitId, attackClass); if (result) battle.removeUnitAttackClassWard(battleMsgData, unitId, attackClass); } else if (immuneCatC->id == ImmuneCategories::get().always->id) { result = true; } return result; } void __fastcall doppelgangerAttackOnHitHooked(game::CBatAttackDoppelganger* thisptr, int /*%edx*/, game::IMidgardObjectMap* objectMap, game::BattleMsgData* battleMsgData, game::CMidgardID* targetUnitId, game::BattleAttackInfo** attackInfo) { using namespace game; const auto& battle = BattleMsgDataApi::get(); if (battle.cannotUseDoppelgangerAttack(&thisptr->unitId, battleMsgData) || !thisptr->hasTargetsToTransformInto) { thisptr->altAttack->vftable->onHit(thisptr->altAttack, objectMap, battleMsgData, targetUnitId, attackInfo); return; } const auto& fn = gameFunctions(); CMidUnit* targetUnit = fn.findUnitById(objectMap, targetUnitId); CMidgardID targetUnitImplId = targetUnit->unitImpl->id; const CMidUnit* unit = fn.findUnitById(objectMap, &thisptr->unitId); const auto transformLevel = getDoppelgangerTransformLevel(unit, targetUnit, objectMap, &thisptr->attackImplUnitId, battleMsgData); CMidgardID transformUnitImplId{targetUnit->unitImpl->id}; CUnitGenerator* unitGenerator = (*(GlobalDataApi::get().getGlobalData()))->unitGenerator; unitGenerator->vftable->generateUnitImplId(unitGenerator, &transformUnitImplId, &targetUnit->unitImpl->id, transformLevel); unitGenerator->vftable->generateUnitImpl(unitGenerator, &transformUnitImplId); const auto& visitors = VisitorApi::get(); visitors.transformUnit(&thisptr->unitId, &transformUnitImplId, false, objectMap, 1); BattleAttackUnitInfo info{}; info.unitId = thisptr->unitId; info.unitImplId = unit->unitImpl->id; BattleAttackInfoApi::get().addUnitInfo(&(*attackInfo)->unitsInfo, &info); battle.removeTransformStatuses(&thisptr->unitId, battleMsgData); battle.setUnitStatus(battleMsgData, &thisptr->unitId, BattleStatus::TransformDoppelganger, true); battle.setUnitHp(battleMsgData, &thisptr->unitId, unit->currentHp); } bool __stdcall cannotUseDoppelgangerAttackHooked(const game::CMidgardID* unitId, const game::BattleMsgData* battleMsgData) { // The attack should always be available except when there are no targets to transform into, // which is controlled by separate flag CBatAttackDoppelganger::hasTargetsToTransformInto return false; } } // namespace hooks
11,365
C++
.cpp
219
40.589041
100
0.648622
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,003
effectinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/effectinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "effectinterf.h" namespace game::editor::CEffectInterfApi { Api& get() { // clang-format off static Api api{ (Api::Constructor)0x433831, (Api::CreateFromCategory)0x45c3c4, (Api::GetObjectMap)0x403c23, (Api::CreateButtonFunctor)0x435161, (Api::CreateListBoxDisplayFunctor)0x4351b3, }; // clang-format on return api; } } // namespace game::editor::CEffectInterfApi
1,249
C++
.cpp
34
33.323529
72
0.735537
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,004
menunewskirmish.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/menunewskirmish.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "menunewskirmish.h" #include "version.h" #include <array> namespace game::CMenuNewSkirmishApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x4e9697, (CMenuBaseApi::Api::ButtonCallback)0x4e9d2a, (Api::UpdateScenarioUi)0x4e987c, }, // Russobit Api{ (Api::Constructor)0x4e9697, (CMenuBaseApi::Api::ButtonCallback)0x4e9d2a, (Api::UpdateScenarioUi)0x4e987c, }, // Gog Api{ (Api::Constructor)0x4e8b32, (CMenuBaseApi::Api::ButtonCallback)0x4e91c5, (Api::UpdateScenarioUi)0x4e8d17, }, }}; static std::array<Vftable*, 3> vftables = {{ // Akella (Vftable*)0x6dec9c, // Russobit (Vftable*)0x6dec9c, // Gog (Vftable*)0x6dcc44, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } Vftable* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CMenuNewSkirmishApi
1,851
C++
.cpp
61
26.655738
72
0.70387
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,005
mapinterf.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/mapinterf.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mapinterf.h" namespace game::editor::CMapInterfApi { Api& get() { // clang-format off static Api api{ (Api::CreateMapChangeTask)0x4628aa, (Api::CreateTask)0x462ad3, (Api::CreateTask)0x462918, (Api::CreateTask)0x462b42, (Api::CreateTask)0x462997, }; // clang-format on return api; } } // namespace game::editor::CMapInterfApi
1,212
C++
.cpp
34
32.235294
72
0.727195
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,006
itemcategory.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/itemcategory.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "itemcategory.h" #include "version.h" #include <array> namespace game::ItemCategories { // clang-format off static std::array<Categories, 4> categories = {{ // Akella Categories{ (LItemCategory*)0x8396e0, (LItemCategory*)0x8396d0, (LItemCategory*)0x8396f0, (LItemCategory*)0x8396c0, (LItemCategory*)0x839778, (LItemCategory*)0x839740, (LItemCategory*)0x8396b0, (LItemCategory*)0x839750, (LItemCategory*)0x839710, (LItemCategory*)0x839720, (LItemCategory*)0x839760, (LItemCategory*)0x839788, (LItemCategory*)0x839700, (LItemCategory*)0x839730, (LItemCategory*)0x8396a0 }, // Russobit Categories{ (LItemCategory*)0x8396e0, (LItemCategory*)0x8396d0, (LItemCategory*)0x8396f0, (LItemCategory*)0x8396c0, (LItemCategory*)0x839778, (LItemCategory*)0x839740, (LItemCategory*)0x8396b0, (LItemCategory*)0x839750, (LItemCategory*)0x839710, (LItemCategory*)0x839720, (LItemCategory*)0x839760, (LItemCategory*)0x839788, (LItemCategory*)0x839700, (LItemCategory*)0x839730, (LItemCategory*)0x8396a0 }, // Gog Categories{ (LItemCategory*)0x837690, (LItemCategory*)0x837680, (LItemCategory*)0x8376a0, (LItemCategory*)0x837670, (LItemCategory*)0x837728, (LItemCategory*)0x8376f0, (LItemCategory*)0x837660, (LItemCategory*)0x837700, (LItemCategory*)0x8376c0, (LItemCategory*)0x8376d0, (LItemCategory*)0x837710, (LItemCategory*)0x837738, (LItemCategory*)0x8376b0, (LItemCategory*)0x8376e0, (LItemCategory*)0x837650 }, // Scenario Editor Categories{ (LItemCategory*)0x665088, (LItemCategory*)0x665078, (LItemCategory*)0x665098, (LItemCategory*)0x665068, (LItemCategory*)0x665120, (LItemCategory*)0x6650e8, (LItemCategory*)0x665058, (LItemCategory*)0x6650f8, (LItemCategory*)0x6650b8, (LItemCategory*)0x6650c8, (LItemCategory*)0x665108, (LItemCategory*)0x665130, (LItemCategory*)0x6650a8, (LItemCategory*)0x6650d8, (LItemCategory*)0x665048 } }}; // clang-format on Categories& get() { return categories[static_cast<int>(hooks::gameVersion())]; } } // namespace game::ItemCategories
3,318
C++
.cpp
103
25.834951
72
0.671651
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,007
buildingbranch.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/buildingbranch.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2020 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "buildingbranch.h" #include "version.h" #include <array> namespace game::CBuildingBranchApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x4aaa69, (Api::InitData)0x4aaee5, (Api::InitBranchMap)0x4ab326, (Api::AddSideshowUnitBuilding)0x4aae31, (Api::AddUnitBuilding)0x4aad34, (Api::AddBuilding)0x4aadbf, (Api::CreateDialogName)0x4ab172, }, // Russobit Api{ (Api::Constructor)0x4aaa69, (Api::InitData)0x4aaee5, (Api::InitBranchMap)0x4ab326, (Api::AddSideshowUnitBuilding)0x4aae31, (Api::AddUnitBuilding)0x4aad34, (Api::AddBuilding)0x4aadbf, (Api::CreateDialogName)0x4ab172, }, // Gog Api{ (Api::Constructor)0x4aa283, (Api::InitData)0x4aa6ff, (Api::InitBranchMap)0x4aab40, (Api::AddSideshowUnitBuilding)0x4aa64b, (Api::AddUnitBuilding)0x4aa54e, (Api::AddBuilding)0x4aa5d9, (Api::CreateDialogName)0x4aa98c, } }}; static std::array<const void*, 3> vftables = {{ // Akella (const void*)0x6d8e64, // Russobit (const void*)0x6d8e64, // Gog (const void*)0x6d6e04 }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } const void* vftable() { return vftables[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CBuildingBranchApi
2,287
C++
.cpp
73
26.767123
72
0.691436
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,008
capitaldatlist.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/capitaldatlist.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "capitaldatlist.h" #include "version.h" #include <array> namespace game::CapitalDatListApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Constructor)0x56aaea, }, // Russobit Api{ (Api::Constructor)0x56aaea, }, // Gog Api{ (Api::Constructor)0x56a1f9, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CapitalDatListApi
1,315
C++
.cpp
43
27.581395
72
0.717443
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,009
netsingleplayerhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/netsingleplayerhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2023 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "netsingleplayerhooks.h" #include "commandmsg.h" #include "log.h" #include "logutils.h" #include "netsingleplayer.h" #include "originalfunctions.h" #include <fmt/format.h> #include <process.h> namespace hooks { bool __fastcall netSinglePlayerSendMessageHooked(game::CNetSinglePlayer* thisptr, int /*%edx*/, int idTo, const game::NetMessageHeader* message) { auto logFileName = fmt::format("netMessages{:d}.log", _getpid()); logDebug(logFileName, fmt::format("{:08x} ({:s})\t-> {:08x} ({:s})\t{:s}\tsender name: {:s}", thisptr->netId, getNetPlayerIdDesc(thisptr->netId), idTo, getNetPlayerIdDesc(idTo), message->messageClassName, thisptr->playerName.string)); return getOriginalFunctions().netSinglePlayerSendMessage(thisptr, idTo, message); } } // namespace hooks
1,813
C++
.cpp
40
38.225
100
0.668552
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,010
campaignstream.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/campaignstream.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "campaignstream.h" #include "version.h" #include <array> namespace game::CampaignStreamApi { // clang-format off static std::array<Api, 4> functions = {{ // Akella Api{ (Api::Constructor)0x609619, (Api::HasErrors)0x5e5099, (Api::Destructor)0x609695, }, // Russobit Api{ (Api::Constructor)0x609619, (Api::HasErrors)0x5e5099, (Api::Destructor)0x609695, }, // Gog Api{ (Api::Constructor)0x6080e3, (Api::HasErrors)0x5e3db6, (Api::Destructor)0x60815f, }, // Scenario Editor Api{ (Api::Constructor)0x5042b8, (Api::HasErrors)0x4dc307, (Api::Destructor)0x504334, }, }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CampaignStreamApi
1,668
C++
.cpp
55
26.218182
72
0.691973
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,011
enclayoutcityhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutcityhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutcityhooks.h" #include "borderedimg.h" #include "dialoginterf.h" #include "dynamiccast.h" #include "faceimg.h" #include "fortification.h" #include "gameutils.h" #include "interfaceutils.h" #include "midstack.h" #include "mqimage2.h" #include "originalfunctions.h" #include "pictureinterf.h" #include "textboxinterf.h" #include "unitutils.h" #include "usunit.h" #include "utils.h" #include <fmt/format.h> #include <string> namespace hooks { static std::string getXpKilledField(const game::IMidgardObjectMap* objectMap, const game::CFortification* fort) { return getNumberText(getGroupXpKilled(objectMap, &fort->group), false); } static std::string getXpKilledStackField(const game::IMidgardObjectMap* objectMap, const game::CFortification* fort) { using namespace game; if (fort->stackId == emptyId) { return getNumberText(0, false); } auto stack = getStack(objectMap, &fort->stackId); return getNumberText(getGroupXpKilled(objectMap, &stack->group), false); } static void setTxtXpKilled(game::CDialogInterf* dialog, const game::IMidgardObjectMap* objectMap, const game::CFortification* fort) { if (!fort) { return; } using namespace game; static const char controlName[]{"TXT_XP_KILLED"}; const auto& dialogApi{CDialogInterfApi::get()}; if (!dialogApi.findControl(dialog, controlName)) { return; } auto textBox{dialogApi.findTextBox(dialog, controlName)}; if (!textBox) { return; } std::string text{textBox->data->text.string}; if (replace(text, "%XPKILL%", getXpKilledField(objectMap, fort))) { CTextBoxInterfApi::get().setString(textBox, text.c_str()); } } static void setTxtXpKilledStack(game::CDialogInterf* dialog, const game::IMidgardObjectMap* objectMap, const game::CFortification* fort) { if (!fort) { return; } using namespace game; static const char controlName[]{"TXT_XP_KILLED_STACK"}; const auto& dialogApi{CDialogInterfApi::get()}; if (!dialogApi.findControl(dialog, controlName)) { return; } auto textBox{dialogApi.findTextBox(dialog, controlName)}; if (!textBox) { return; } std::string text{textBox->data->text.string}; if (replace(text, "%XPKILL%", getXpKilledStackField(objectMap, fort))) { CTextBoxInterfApi::get().setString(textBox, text.c_str()); } } void __fastcall encLayoutCityUpdateHooked(game::CEncLayoutCity* thisptr, int /*%edx*/, const game::IMidgardObjectMap* objectMap, const game::CFortification* fort, game::CDialogInterf* dialog) { getOriginalFunctions().encLayoutCityUpdate(thisptr, objectMap, fort, dialog); setTxtXpKilled(dialog, objectMap, fort); setTxtXpKilledStack(dialog, objectMap, fort); } void __fastcall encLayoutCityOnObjectChangedHooked(game::CEncLayoutCity* thisptr, int /*%edx*/, const game::IMidObject* obj) { using namespace game; if (!obj) { return; } const auto& api = CEncLayoutCityApi::get(); const auto& idApi = CMidgardIDApi::get(); const auto& rtti = RttiApi::rtti(); const auto dynamicCast = RttiApi::get().dynamicCast; auto idType = idApi.getType(&obj->id); if (idType == IdType::Fortification) { auto fort = static_cast<const CFortification*>( dynamicCast(obj, 0, rtti.IMidObjectType, rtti.CFortificationType, 0)); if (fort && fort->id == thisptr->data->fortificationId) { api.update(thisptr, thisptr->data->objectMap, fort, thisptr->dialog); } } else if (idType == IdType::Stack) { auto stack = static_cast<const CMidStack*>( dynamicCast(obj, 0, rtti.IMidObjectType, rtti.CMidStackType, 0)); if (stack && stack->insideId == thisptr->data->fortificationId) { auto objectMap = thisptr->data->objectMap; auto fort = static_cast<const CFortification*>( objectMap->vftable->findScenarioObjectById(objectMap, &thisptr->data->fortificationId)); api.update(thisptr, objectMap, fort, thisptr->dialog); } } } std::string getUnitUiControlName(int unitPosition, const char* nameFormat) { std::string result = nameFormat; replace(result, "%d", fmt::format("{:d}", unitPosition)); return result; } void resizeUnitUiControl(game::CInterface* control, const game::CInterface* relative, bool isUnitSmall) { using namespace game; auto relativeArea = relative->vftable->getArea(relative); CMqRect area = *control->vftable->getArea(control); if (isUnitSmall) { if (relativeArea->left > area.left) { area.right = area.left + (relativeArea->right - relativeArea->left); } else { area.left = area.right - (relativeArea->right - relativeArea->left); } } else { if (relativeArea->left > area.left) { area.right = relativeArea->right; } else { area.left = relativeArea->left; } } control->vftable->setArea(control, &area); } void alignUnitUiControls(game::CDialogInterf* dialog, game::CInterface* control, int unitPosition, const char* controlNameFormat, bool isUnitSmall) { using namespace game; const auto& dialogApi = CDialogInterfApi::get(); if (unitPosition % 2 == 0) { auto control2Name = getUnitUiControlName(unitPosition + 1, controlNameFormat); dialogApi.showControl(dialog, dialog->data->dialogName, control2Name.c_str()); auto control2 = dialogApi.findControl(dialog, control2Name.c_str()); resizeUnitUiControl(control, control2, isUnitSmall); if (!isUnitSmall) { dialogApi.hideControl(dialog, control2Name.c_str()); } } } game::IMqImage2* createUnitFaceImage(const game::CMidUnit* unit, bool isStackGroup) { using namespace game; const auto& fn = gameFunctions(); auto faceImage = fn.createUnitFaceImage(&unit->unitImpl->id, false); if (unit->currentHp > 0) { auto percentHp = 100 * unit->currentHp / getUnitHpMax(unit); faceImage->vftable->setPercentHp(faceImage, percentHp); faceImage->vftable->setUnknown68(faceImage, 0); } else { faceImage->vftable->setUnknown68(faceImage, 10); } faceImage->vftable->setLeftSide(faceImage, isStackGroup); return (IMqImage2*)faceImage; } void updateTxtStack(game::CDialogInterf* dialog, const game::CMidUnit* unit, int unitPosition, const char* txtStackNameFormat, bool isUnitSmall) { using namespace game; const auto& fn = gameFunctions(); const auto& dialogApi = CDialogInterfApi::get(); auto txtStackName = getUnitUiControlName(unitPosition, txtStackNameFormat); auto txtStack = dialogApi.findTextBox(dialog, txtStackName.c_str()); alignUnitUiControls(dialog, txtStack, unitPosition, txtStackNameFormat, isUnitSmall); std::string unitName; if (unit) { if (fn.castUnitImplToStackLeader(unit->unitImpl)) { unitName = getInterfaceText("X005TA0784"); } else { unitName = getInterfaceText("X005TA0783"); } replace(unitName, "%NAME%", getUnitName(unit)); } CTextBoxInterfApi::get().setString(txtStack, unitName.c_str()); } void updateImgStack(game::CDialogInterf* dialog, const game::CMidUnit* unit, int unitPosition, const char* imgStackNameFormat, bool isUnitSmall, bool isStackGroup) { using namespace game; const auto& dialogApi = CDialogInterfApi::get(); auto imgStackName = getUnitUiControlName(unitPosition, imgStackNameFormat); auto imgStack = dialogApi.findPicture(dialog, imgStackName.c_str()); alignUnitUiControls(dialog, imgStack, unitPosition, imgStackNameFormat, isUnitSmall); auto faceImage = unit ? createUnitFaceImage(unit, isStackGroup) : nullptr; auto borderedFaceImage = createBorderedImage(faceImage, isUnitSmall ? BorderType::UnitSmall : BorderType::UnitLarge); setCenteredImage(imgStack, borderedFaceImage); } void __stdcall encLayoutCityUpdateGroupUiHooked(const game::IMidgardObjectMap* objectMap, const game::CMidUnitGroup* group, game::CDialogInterf* dialog, const char* txtStackNameFormat, const char* imgStackNameFormat, bool isStackGroup) { using namespace game; const auto& groupApi = CMidUnitGroupApi::get(); for (int unitPosition = 0; unitPosition < 6; ++unitPosition) { auto unitId = group ? *groupApi.getUnitIdByPosition(group, unitPosition) : emptyId; if (unitId != emptyId) { auto unit = static_cast<const CMidUnit*>( objectMap->vftable->findScenarioObjectById(objectMap, &unitId)); bool isUnitSmall = hooks::isUnitSmall(unit); updateTxtStack(dialog, unit, unitPosition, txtStackNameFormat, isUnitSmall); updateImgStack(dialog, unit, unitPosition, imgStackNameFormat, isUnitSmall, isStackGroup); if (!isUnitSmall) { ++unitPosition; } } else { updateTxtStack(dialog, nullptr, unitPosition, txtStackNameFormat, true); updateImgStack(dialog, nullptr, unitPosition, imgStackNameFormat, true, isStackGroup); } } } } // namespace hooks
11,211
C++
.cpp
266
32.703008
98
0.63183
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,012
capitaldata.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/capitaldata.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2021 Vladimir Makeev. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "capitaldata.h" #include "version.h" #include <array> namespace game::CapitalDataApi { // clang-format off static std::array<Api, 3> functions = {{ // Akella Api{ (Api::Allocate)0x56ad71, (Api::GetCapitalData)0x56aea4, (Api::CapitalDataPtrSetData)0x40813a, (Api::Read)0x61d17b, (Api::ReadEntry)0x683318, }, // Russobit Api{ (Api::Allocate)0x56ad71, (Api::GetCapitalData)0x56aea4, (Api::CapitalDataPtrSetData)0x40813a, (Api::Read)0x61d17b, (Api::ReadEntry)0x683318, }, // Gog Api{ (Api::Allocate)0x56a421, (Api::GetCapitalData)0x56a554, (Api::CapitalDataPtrSetData)0x407dc5, (Api::Read)0x61bc90, (Api::ReadEntry)0x681ca2, } }}; // clang-format on Api& get() { return functions[static_cast<int>(hooks::gameVersion())]; } } // namespace game::CapitalDataApi
1,741
C++
.cpp
55
27.345455
72
0.69423
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,542,013
enclayoutruinhooks.cpp
VladimirMakeev_D2ModdingToolset/mss32/src/enclayoutruinhooks.cpp
/* * This file is part of the modding toolset for Disciples 2. * (https://github.com/VladimirMakeev/D2ModdingToolset) * Copyright (C) 2022 Stanislav Egorov. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "enclayoutruinhooks.h" #include "dialoginterf.h" #include "enclayoutruin.h" #include "gameutils.h" #include "interfaceutils.h" #include "midruin.h" #include "originalfunctions.h" #include "textboxinterf.h" #include "utils.h" #include <string> namespace hooks { static std::string getXpKilledField(const game::IMidgardObjectMap* objectMap, const game::CMidRuin* ruin) { return getNumberText(getGroupXpKilled(objectMap, &ruin->group), false); } static void setTxtXpKilled(game::CDialogInterf* dialog, const game::IMidgardObjectMap* objectMap, const game::CMidRuin* ruin) { if (!ruin) { return; } using namespace game; static const char controlName[]{"TXT_XP_KILLED"}; const auto& dialogApi{CDialogInterfApi::get()}; if (!dialogApi.findControl(dialog, controlName)) { return; } auto textBox{dialogApi.findTextBox(dialog, controlName)}; if (!textBox) { return; } std::string text{textBox->data->text.string}; if (replace(text, "%XPKILL%", getXpKilledField(objectMap, ruin))) { CTextBoxInterfApi::get().setString(textBox, text.c_str()); } } void __stdcall encLayoutRuinUpdateHooked(const game::CEncLayoutRuinData* data, const game::CMidRuin* ruin, game::CDialogInterf* dialog) { getOriginalFunctions().encLayoutRuinUpdate(data, ruin, dialog); setTxtXpKilled(dialog, data->objectMap, ruin); } } // namespace hooks
2,411
C++
.cpp
64
32.015625
78
0.691088
VladimirMakeev/D2ModdingToolset
32
13
15
GPL-3.0
9/20/2024, 10:45:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false