diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..4989fc4237a --- /dev/null +++ b/.clang-format @@ -0,0 +1,142 @@ +--- +Language: Cpp +#BasedOnStyle: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: BlockIndent +AlignConsecutiveMacros: false +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: false +AlignTrailingComments: false +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: Empty +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: All +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 0 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 3 + SortPriority: 0 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 2 + SortPriority: 0 + - Regex: '.*' + Priority: 1 + SortPriority: 0 +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: true +IndentGotoLabels: true +IndentPPDirectives: BeforeHash +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +ReflowComments: true +SortIncludes: false +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +Standard: Latest +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseCRLF: false +UseTab: true +IndentAccessModifiers: true +RemoveBracesLLVM: false +#InsertNewlineAtEOF: true +LambdaBodyIndentation: Signature +NamespaceIndentation: All +QualifierAlignment: Left +ReferenceAlignment: Right +MaxEmptyLinesToKeep: 1 diff --git a/.github/workflows/clang-lint.yml b/.github/workflows/clang-lint.yml new file mode 100644 index 00000000000..5eba8e1e18a --- /dev/null +++ b/.github/workflows/clang-lint.yml @@ -0,0 +1,42 @@ +--- +name: Clang-format +on: + pull_request: + push: +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Set up Git + if: ${{ github.ref != 'refs/heads/main' }} + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "GitHub Actions" + + - name: Actions checkout + if: ${{ github.ref != 'refs/heads/main' }} + uses: actions/checkout@v3 + with: + repository: ${{ github.event.pull_request.head.repo.full_name }} + ref: ${{ github.event.pull_request.head.ref }} + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Run clang format lint + if: ${{ github.ref != 'refs/heads/main' }} + uses: DoozyX/clang-format-lint-action@v0.15 + with: + source: "src" + exclude: "src/protobuf" + extensions: "cpp,hpp,h" + clangFormatVersion: 15 + inplace: true + + - name: Run add and commit + if: ${{ github.ref != 'refs/heads/main' }} + uses: EndBug/add-and-commit@v9 + with: + author_name: GitHub Actions + author_email: github-actions[bot]@users.noreply.github.com + message: "Code format - (Clang-format)" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/src/config/config_definitions.hpp b/src/config/config_definitions.hpp index 6a07271980d..4c54073eba2 100644 --- a/src/config/config_definitions.hpp +++ b/src/config/config_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CONFIG_CONFIG_DEFINITIONS_HPP_ #define SRC_CONFIG_CONFIG_DEFINITIONS_HPP_ @@ -69,7 +69,7 @@ enum booleanConfig_t { ALLOW_RELOAD, LAST_BOOLEAN_CONFIG - }; +}; enum stringConfig_t { MAP_NAME, @@ -102,7 +102,7 @@ enum stringConfig_t { FORGE_FIENDISH_INTERVAL_TIME, LAST_STRING_CONFIG - }; +}; enum integerConfig_t { SQL_PORT, @@ -216,4 +216,4 @@ enum floatingConfig_t { LAST_FLOATING_CONFIG }; -#endif // SRC_CONFIG_CONFIG_DEFINITIONS_HPP_ +#endif // SRC_CONFIG_CONFIG_DEFINITIONS_HPP_ diff --git a/src/config/configmanager.cpp b/src/config/configmanager.cpp index c7e9e36a027..10f0441f883 100644 --- a/src/config/configmanager.cpp +++ b/src/config/configmanager.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -15,41 +15,14 @@ #include "lua/scripts/luajit_sync.hpp" #if LUA_VERSION_NUM >= 502 -#undef lua_strlen -#define lua_strlen lua_rawlen + #undef lua_strlen + #define lua_strlen lua_rawlen #endif namespace { -std::string getGlobalString(lua_State* L, const char* identifier, const char* defaultValue) -{ - lua_getglobal(L, identifier); - if (!lua_isstring(L, -1)) { - return defaultValue; - } - - size_t len = lua_strlen(L, -1); - std::string ret(lua_tostring(L, -1), len); - lua_pop(L, 1); - return ret; -} - -int32_t getGlobalNumber(lua_State* L, const char* identifier, const int32_t defaultValue = 0) -{ - lua_getglobal(L, identifier); - if (!lua_isnumber(L, -1)) { - return defaultValue; - } - - int32_t val = lua_tonumber(L, -1); - lua_pop(L, 1); - return val; -} - -bool getGlobalBoolean(lua_State* L, const char* identifier, const bool defaultValue) -{ - lua_getglobal(L, identifier); - if (!lua_isboolean(L, -1)) { + std::string getGlobalString(lua_State* L, const char* identifier, const char* defaultValue) { + lua_getglobal(L, identifier); if (!lua_isstring(L, -1)) { return defaultValue; } @@ -57,30 +30,52 @@ bool getGlobalBoolean(lua_State* L, const char* identifier, const bool defaultVa size_t len = lua_strlen(L, -1); std::string ret(lua_tostring(L, -1), len); lua_pop(L, 1); - return booleanString(ret); + return ret; } - int val = lua_toboolean(L, -1); - lua_pop(L, 1); - return val != 0; -} + int32_t getGlobalNumber(lua_State* L, const char* identifier, const int32_t defaultValue = 0) { + lua_getglobal(L, identifier); + if (!lua_isnumber(L, -1)) { + return defaultValue; + } -float getGlobalFloat(lua_State* L, const char* identifier, const float defaultValue = 0.0) -{ - lua_getglobal(L, identifier); - if (!lua_isnumber(L, -1)) { - return defaultValue; + int32_t val = lua_tonumber(L, -1); + lua_pop(L, 1); + return val; } - float val = lua_tonumber(L, -1); - lua_pop(L, 1); - return val; -} + bool getGlobalBoolean(lua_State* L, const char* identifier, const bool defaultValue) { + lua_getglobal(L, identifier); + if (!lua_isboolean(L, -1)) { + if (!lua_isstring(L, -1)) { + return defaultValue; + } + + size_t len = lua_strlen(L, -1); + std::string ret(lua_tostring(L, -1), len); + lua_pop(L, 1); + return booleanString(ret); + } + + int val = lua_toboolean(L, -1); + lua_pop(L, 1); + return val != 0; + } + + float getGlobalFloat(lua_State* L, const char* identifier, const float defaultValue = 0.0) { + lua_getglobal(L, identifier); + if (!lua_isnumber(L, -1)) { + return defaultValue; + } + + float val = lua_tonumber(L, -1); + lua_pop(L, 1); + return val; + } } -bool ConfigManager::load() -{ +bool ConfigManager::load() { lua_State* L = luaL_newstate(); if (!L) { throw std::runtime_error("Failed to allocate memory"); @@ -307,8 +302,7 @@ bool ConfigManager::load() return true; } -bool ConfigManager::reload() -{ +bool ConfigManager::reload() { bool result = load(); if (transformToSHA1(getString(MOTD)) != g_game().getMotdHash()) { g_game().incrementMotdNum(); @@ -318,8 +312,7 @@ bool ConfigManager::reload() static std::string dummyStr; -const std::string& ConfigManager::getString(stringConfig_t what) const -{ +const std::string &ConfigManager::getString(stringConfig_t what) const { if (what >= LAST_STRING_CONFIG) { SPDLOG_WARN("[ConfigManager::getString] - Accessing invalid index: {}", what); return dummyStr; @@ -327,8 +320,7 @@ const std::string& ConfigManager::getString(stringConfig_t what) const return string[what]; } -int32_t ConfigManager::getNumber(integerConfig_t what) const -{ +int32_t ConfigManager::getNumber(integerConfig_t what) const { if (what >= LAST_INTEGER_CONFIG) { SPDLOG_WARN("[ConfigManager::getNumber] - Accessing invalid index: {}", what); return 0; @@ -336,8 +328,7 @@ int32_t ConfigManager::getNumber(integerConfig_t what) const return integer[what]; } -int16_t ConfigManager::getShortNumber(integerConfig_t what) const -{ +int16_t ConfigManager::getShortNumber(integerConfig_t what) const { if (what >= LAST_INTEGER_CONFIG) { SPDLOG_WARN("[ConfigManager::getShortNumber] - Accessing invalid index: {}", what); return 0; @@ -345,8 +336,7 @@ int16_t ConfigManager::getShortNumber(integerConfig_t what) const return integer[what]; } -bool ConfigManager::getBoolean(booleanConfig_t what) const -{ +bool ConfigManager::getBoolean(booleanConfig_t what) const { if (what >= LAST_BOOLEAN_CONFIG) { SPDLOG_WARN("[ConfigManager::getBoolean] - Accessing invalid index: {}", what); return false; @@ -354,8 +344,7 @@ bool ConfigManager::getBoolean(booleanConfig_t what) const return boolean[what]; } -float ConfigManager::getFloat(floatingConfig_t what) const -{ +float ConfigManager::getFloat(floatingConfig_t what) const { if (what >= LAST_FLOATING_CONFIG) { SPDLOG_WARN("[ConfigManager::getFLoat] - Accessing invalid index: {}", what); return 0; diff --git a/src/config/configmanager.h b/src/config/configmanager.h index f8c5ad88caa..f497b4ba3be 100644 --- a/src/config/configmanager.h +++ b/src/config/configmanager.h @@ -5,43 +5,42 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CONFIG_CONFIGMANAGER_H_ #define SRC_CONFIG_CONFIGMANAGER_H_ #include "declarations.hpp" -class ConfigManager -{ +class ConfigManager { public: ConfigManager() = default; // Singleton - ensures we don't accidentally copy it - ConfigManager(ConfigManager const&) = delete; - void operator=(ConfigManager const&) = delete; + ConfigManager(const ConfigManager &) = delete; + void operator=(const ConfigManager &) = delete; - static ConfigManager& getInstance() { + static ConfigManager &getInstance() { // Guaranteed to be destroyed static ConfigManager instance; // Instantiated on first use return instance; } - + bool load(); bool reload(); - const std::string& getString(stringConfig_t what) const; + const std::string &getString(stringConfig_t what) const; int32_t getNumber(integerConfig_t what) const; int16_t getShortNumber(integerConfig_t what) const; bool getBoolean(booleanConfig_t what) const; float getFloat(floatingConfig_t what) const; - std::string const& setConfigFileLua(const std::string& what) { + const std::string &setConfigFileLua(const std::string &what) { configFileLua = { what }; return configFileLua; }; - std::string const& getConfigFileLua() const { + const std::string &getConfigFileLua() const { return configFileLua; }; @@ -58,4 +57,4 @@ class ConfigManager constexpr auto g_configManager = &ConfigManager::getInstance; -#endif // SRC_CONFIG_CONFIGMANAGER_H_ +#endif // SRC_CONFIG_CONFIGMANAGER_H_ diff --git a/src/core.hpp b/src/core.hpp index 5fbb4a2b853..2878c1512ae 100644 --- a/src/core.hpp +++ b/src/core.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CORE_HPP_ #define SRC_CORE_HPP_ @@ -22,4 +22,4 @@ static constexpr auto CLIENT_VERSION = 1291; #define CLIENT_VERSION_UPPER (CLIENT_VERSION / 100) #define CLIENT_VERSION_LOWER (CLIENT_VERSION % 100) -#endif // SRC_CORE_HPP_ +#endif // SRC_CORE_HPP_ diff --git a/src/creatures/appearance/mounts/mounts.cpp b/src/creatures/appearance/mounts/mounts.cpp index 738c3a4b0e0..f8b0610d83c 100644 --- a/src/creatures/appearance/mounts/mounts.cpp +++ b/src/creatures/appearance/mounts/mounts.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,14 +14,12 @@ #include "utils/pugicast.h" #include "utils/tools.h" -bool Mounts::reload() -{ +bool Mounts::reload() { mounts.clear(); return loadFromXml(); } -bool Mounts::loadFromXml() -{ +bool Mounts::loadFromXml() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/mounts.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); @@ -50,18 +48,17 @@ bool Mounts::loadFromXml() return true; } -Mount* Mounts::getMountByID(uint8_t id) -{ - auto it = std::find_if(mounts.begin(), mounts.end(), [id](const Mount& mount) { +Mount* Mounts::getMountByID(uint8_t id) { + auto it = std::find_if(mounts.begin(), mounts.end(), [id](const Mount &mount) { return mount.id == id; }); return it != mounts.end() ? &*it : nullptr; } -Mount* Mounts::getMountByName(const std::string& name) { +Mount* Mounts::getMountByName(const std::string &name) { auto mountName = name.c_str(); - for (auto& it : mounts) { + for (auto &it : mounts) { if (strcasecmp(mountName, it.name.c_str()) == 0) { return ⁢ } @@ -70,9 +67,8 @@ Mount* Mounts::getMountByName(const std::string& name) { return nullptr; } -Mount* Mounts::getMountByClientID(uint16_t clientId) -{ - auto it = std::find_if(mounts.begin(), mounts.end(), [clientId](const Mount& mount) { +Mount* Mounts::getMountByClientID(uint16_t clientId) { + auto it = std::find_if(mounts.begin(), mounts.end(), [clientId](const Mount &mount) { return mount.clientId == clientId; }); diff --git a/src/creatures/appearance/mounts/mounts.h b/src/creatures/appearance/mounts/mounts.h index 7c217a72027..834fbbc515a 100644 --- a/src/creatures/appearance/mounts/mounts.h +++ b/src/creatures/appearance/mounts/mounts.h @@ -5,37 +5,33 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_APPEARANCE_MOUNTS_MOUNTS_H_ #define SRC_CREATURES_APPEARANCE_MOUNTS_MOUNTS_H_ - -struct Mount -{ - Mount(uint8_t initId, uint16_t initClientId, std::string initName, int32_t initSpeed, bool initPremium, - std::string initType) : - name(initName), speed(initSpeed), clientId(initClientId), id(initId), premium(initPremium), - type(initType) {} - - std::string name; - int32_t speed; - uint16_t clientId; - uint8_t id; - bool premium; - std::string type; +struct Mount { + Mount(uint8_t initId, uint16_t initClientId, std::string initName, int32_t initSpeed, bool initPremium, std::string initType) : + name(initName), speed(initSpeed), clientId(initClientId), id(initId), premium(initPremium), + type(initType) { } + + std::string name; + int32_t speed; + uint16_t clientId; + uint8_t id; + bool premium; + std::string type; }; -class Mounts -{ +class Mounts { public: bool reload(); bool loadFromXml(); Mount* getMountByID(uint8_t id); - Mount* getMountByName(const std::string& name); + Mount* getMountByName(const std::string &name); Mount* getMountByClientID(uint16_t clientId); - const std::vector& getMounts() const { + const std::vector &getMounts() const { return mounts; } @@ -43,4 +39,4 @@ class Mounts std::vector mounts; }; -#endif // SRC_CREATURES_APPEARANCE_MOUNTS_MOUNTS_H_ +#endif // SRC_CREATURES_APPEARANCE_MOUNTS_MOUNTS_H_ diff --git a/src/creatures/appearance/outfit/outfit.cpp b/src/creatures/appearance/outfit/outfit.cpp index ac6ad90b256..87cf4e02af1 100644 --- a/src/creatures/appearance/outfit/outfit.cpp +++ b/src/creatures/appearance/outfit/outfit.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,8 +14,7 @@ #include "utils/tools.h" #include "game/game.h" -bool Outfits::loadFromXml() -{ +bool Outfits::loadFromXml() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/outfits.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); @@ -48,10 +47,8 @@ bool Outfits::loadFromXml() } if (uint16_t lookType = pugi::cast(lookTypeAttribute.value()); - g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 - && !g_game().isLookTypeRegistered(lookType) - ) - { + g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 + && !g_game().isLookTypeRegistered(lookType)) { SPDLOG_WARN("[Outfits::loadFromXml] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", lookType); return false; } @@ -70,9 +67,8 @@ bool Outfits::loadFromXml() return true; } -const Outfit* Outfits::getOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const -{ - for (const Outfit& outfit : outfits[sex]) { +const Outfit* Outfits::getOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const { + for (const Outfit &outfit : outfits[sex]) { if (outfit.lookType == lookType) { return &outfit; } @@ -87,15 +83,14 @@ const Outfit* Outfits::getOutfitByLookType(PlayerSex_t sex, uint16_t lookType) c * @return const pointer to the outfit or nullptr if it could not be found. */ -const Outfit *Outfits::getOpositeSexOutfitByLookType(PlayerSex_t sex, uint16_t lookType) -{ - PlayerSex_t searchSex = (sex == PLAYERSEX_MALE)?PLAYERSEX_FEMALE:PLAYERSEX_MALE; +const Outfit* Outfits::getOpositeSexOutfitByLookType(PlayerSex_t sex, uint16_t lookType) { + PlayerSex_t searchSex = (sex == PLAYERSEX_MALE) ? PLAYERSEX_FEMALE : PLAYERSEX_MALE; - for(uint16_t i=0; i< outfits[sex].size(); i++) { + for (uint16_t i = 0; i < outfits[sex].size(); i++) { if (outfits[sex].at(i).lookType == lookType) { - if (outfits[searchSex].size()>i) { + if (outfits[searchSex].size() > i) { return &outfits[searchSex].at(i); - } else { //looktype found but the oposite sex array doesn't have this index. + } else { // looktype found but the oposite sex array doesn't have this index. return nullptr; } } diff --git a/src/creatures/appearance/outfit/outfit.h b/src/creatures/appearance/outfit/outfit.h index 782614111a4..13dab444e1c 100644 --- a/src/creatures/appearance/outfit/outfit.h +++ b/src/creatures/appearance/outfit/outfit.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_APPEARANCE_OUTFIT_OUTFIT_H_ #define SRC_CREATURES_APPEARANCE_OUTFIT_OUTFIT_H_ @@ -13,29 +13,28 @@ #include "declarations.hpp" struct Outfit { - Outfit(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initFrom) : - name(initName), lookType(initLookType), premium(initPremium), unlocked(initUnlocked), from(initFrom) {} - - std::string name; - uint16_t lookType; - bool premium; - bool unlocked; - std::string from; + Outfit(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initFrom) : + name(initName), lookType(initLookType), premium(initPremium), unlocked(initUnlocked), from(initFrom) { } + + std::string name; + uint16_t lookType; + bool premium; + bool unlocked; + std::string from; }; struct ProtocolOutfit { - ProtocolOutfit(const std::string& initName, uint16_t initLookType, uint8_t initAddons) : - name(initName), lookType(initLookType), addons(initAddons) {} + ProtocolOutfit(const std::string &initName, uint16_t initLookType, uint8_t initAddons) : + name(initName), lookType(initLookType), addons(initAddons) { } - const std::string& name; - uint16_t lookType; - uint8_t addons; + const std::string &name; + uint16_t lookType; + uint8_t addons; }; -class Outfits -{ +class Outfits { public: - static Outfits& getInstance() { + static Outfits &getInstance() { static Outfits instance; return instance; } @@ -45,7 +44,7 @@ class Outfits bool loadFromXml(); const Outfit* getOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const; - const std::vector& getOutfits(PlayerSex_t sex) const { + const std::vector &getOutfits(PlayerSex_t sex) const { return outfits[sex]; } @@ -53,4 +52,4 @@ class Outfits std::vector outfits[PLAYERSEX_LAST + 1]; }; -#endif // SRC_CREATURES_APPEARANCE_OUTFIT_OUTFIT_H_ +#endif // SRC_CREATURES_APPEARANCE_OUTFIT_OUTFIT_H_ diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 9aa0245fa67..29ccdfa63e3 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,8 +18,7 @@ #include "creatures/monsters/monsters.h" #include "items/weapons/weapons.h" -CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const -{ +CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const { CombatDamage damage; damage.origin = params.origin; damage.primary.type = params.combatType; @@ -70,8 +69,7 @@ CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const return damage; } -void Combat::getCombatArea(const Position& centerPos, const Position& targetPos, const AreaCombat* area, std::forward_list& list) -{ +void Combat::getCombatArea(const Position ¢erPos, const Position &targetPos, const AreaCombat* area, std::forward_list &list) { if (targetPos.z >= MAP_MAX_LAYERS) { return; } @@ -88,8 +86,7 @@ void Combat::getCombatArea(const Position& centerPos, const Position& targetPos, } } -CombatType_t Combat::ConditionToDamageType(ConditionType_t type) -{ +CombatType_t Combat::ConditionToDamageType(ConditionType_t type) { switch (type) { case CONDITION_FIRE: return COMBAT_FIREDAMAGE; @@ -122,8 +119,7 @@ CombatType_t Combat::ConditionToDamageType(ConditionType_t type) return COMBAT_NONE; } -ConditionType_t Combat::DamageToConditionType(CombatType_t type) -{ +ConditionType_t Combat::DamageToConditionType(CombatType_t type) { switch (type) { case COMBAT_FIREDAMAGE: return CONDITION_FIRE; @@ -154,8 +150,7 @@ ConditionType_t Combat::DamageToConditionType(CombatType_t type) } } -bool Combat::isPlayerCombat(const Creature* target) -{ +bool Combat::isPlayerCombat(const Creature* target) { if (target->getPlayer()) { return true; } @@ -167,14 +162,13 @@ bool Combat::isPlayerCombat(const Creature* target) return false; } -ReturnValue Combat::canTargetCreature(Player* player, Creature* target) -{ +ReturnValue Combat::canTargetCreature(Player* player, Creature* target) { if (player == target) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } if (!player->hasFlag(PlayerFlags_t::IgnoreProtectionZone)) { - //pz-zone + // pz-zone if (player->getZone() == ZONE_PROTECTION) { return RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE; } @@ -183,7 +177,7 @@ ReturnValue Combat::canTargetCreature(Player* player, Creature* target) return RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE; } - //nopvp-zone + // nopvp-zone if (isPlayerCombat(target)) { if (player->getZone() == ZONE_NOPVP) { return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; @@ -216,8 +210,7 @@ ReturnValue Combat::canTargetCreature(Player* player, Creature* target) return Combat::canDoCombat(player, target); } -ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) -{ +ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) { if (tile->hasProperty(CONST_PROP_BLOCKPROJECTILE)) { return RETURNVALUE_NOTENOUGHROOM; } @@ -231,8 +224,8 @@ ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) } if (caster) { - const Position& casterPosition = caster->getPosition(); - const Position& tilePosition = tile->getPosition(); + const Position &casterPosition = caster->getPosition(); + const Position &tilePosition = tile->getPosition(); if (casterPosition.z < tilePosition.z) { return RETURNVALUE_FIRSTGODOWNSTAIRS; } else if (casterPosition.z > tilePosition.z) { @@ -246,7 +239,7 @@ ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) } } - //pz-zone + // pz-zone if (aggressive && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { return RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE; } @@ -254,13 +247,11 @@ ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) return g_events().eventCreatureOnAreaCombat(caster, tile, aggressive); } -bool Combat::isInPvpZone(const Creature* attacker, const Creature* target) -{ +bool Combat::isInPvpZone(const Creature* attacker, const Creature* target) { return attacker->getZone() == ZONE_PVP && target->getZone() == ZONE_PVP; } -bool Combat::isProtected(const Player* attacker, const Player* target) -{ +bool Combat::isProtected(const Player* attacker, const Player* target) { uint32_t protectionLevel = g_configManager().getNumber(PROTECTION_LEVEL); if (target->getLevel() < protectionLevel || attacker->getLevel() < protectionLevel) { return true; @@ -277,8 +268,7 @@ bool Combat::isProtected(const Player* attacker, const Player* target) return false; } -ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) -{ +ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) { if (attacker) { const Creature* attackerMaster = attacker->getMaster(); if (const Player* targetPlayer = target->getPlayer()) { @@ -295,10 +285,9 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } - //nopvp-zone + // nopvp-zone if (const Tile* targetPlayerTile = targetPlayer->getTile(); - targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE)) - { + targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE)) { return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; } else if (attackerPlayer->getTile()->hasFlag(TILESTATE_NOPVPZONE) && !targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE | TILESTATE_PROTECTIONZONE)) { return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; @@ -324,7 +313,7 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) } } } - + if (attacker->getMonster() && (!attackerMaster || attackerMaster->getMonster())) { if (attacker->getFaction() != FACTION_DEFAULT && !attacker->getMonster()->isEnemyFaction(targetPlayer->getFaction())) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; @@ -375,8 +364,7 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) return g_events().eventCreatureOnTargetCombat(attacker, target); } -void Combat::setPlayerCombatValues(formulaType_t newFormulaType, double newMina, double newMinb, double newMaxa, double newMaxb) -{ +void Combat::setPlayerCombatValues(formulaType_t newFormulaType, double newMina, double newMinb, double newMaxa, double newMaxb) { this->formulaType = newFormulaType; this->mina = newMina; this->minb = newMinb; @@ -384,8 +372,7 @@ void Combat::setPlayerCombatValues(formulaType_t newFormulaType, double newMina, this->maxb = newMaxb; } -bool Combat::setParam(CombatParam_t param, uint32_t value) -{ +bool Combat::setParam(CombatParam_t param, uint32_t value) { switch (param) { case COMBAT_PARAM_TYPE: { params.combatType = static_cast(value); @@ -440,8 +427,7 @@ bool Combat::setParam(CombatParam_t param, uint32_t value) return false; } -bool Combat::setCallback(CallBackParam_t key) -{ +bool Combat::setCallback(CallBackParam_t key) { switch (key) { case CALLBACK_PARAM_LEVELMAGICVALUE: { params.valueCallback.reset(new ValueCallback(COMBAT_FORMULA_LEVELMAGIC)); @@ -466,8 +452,7 @@ bool Combat::setCallback(CallBackParam_t key) return false; } -CallBack* Combat::getCallback(CallBackParam_t key) -{ +CallBack* Combat::getCallback(CallBackParam_t key) { switch (key) { case CALLBACK_PARAM_LEVELMAGICVALUE: case CALLBACK_PARAM_SKILLVALUE: { @@ -485,33 +470,32 @@ CallBack* Combat::getCallback(CallBackParam_t key) return nullptr; } -void Combat::CombatHealthFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data) -{ +void Combat::CombatHealthFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data) { assert(data); CombatDamage damage = *data; - Player *attackerPlayer = nullptr; + Player* attackerPlayer = nullptr; if (caster) { attackerPlayer = caster->getPlayer(); } - Monster *targetMonster = nullptr; + Monster* targetMonster = nullptr; if (target) { targetMonster = target->getMonster(); } - Monster *attackerMonster = nullptr; + Monster* attackerMonster = nullptr; if (caster) { attackerMonster = caster->getMonster(); } - Player *targetPlayer = nullptr; + Player* targetPlayer = nullptr; if (target) { targetPlayer = target->getPlayer(); } if (caster && attackerPlayer) { - Item *item = attackerPlayer->getWeapon(); + Item* item = attackerPlayer->getWeapon(); damage = applyImbuementElementalDamage(item, damage); g_events().eventPlayerOnCombat(attackerPlayer, target, item, damage); @@ -537,7 +521,7 @@ void Combat::CombatHealthFunc(Creature* caster, Creature* target, const CombatPa damage.secondary.value += static_cast(std::ceil((damage.secondary.value * slot->bonusPercentage) / 100)); } } - + // Monster attacking player if (attackerMonster && targetPlayer) { const PreySlot* slot = targetPlayer->getPreyWithMonster(attackerMonster->getRaceId()); @@ -565,9 +549,8 @@ CombatDamage Combat::applyImbuementElementalDamage(Item* item, CombatDamage dama } if (imbuementInfo.imbuement->combatType == COMBAT_NONE - || damage.primary.type == COMBAT_HEALING - || damage.secondary.type == COMBAT_HEALING) - { + || damage.primary.type == COMBAT_HEALING + || damage.secondary.type == COMBAT_HEALING) { continue; } @@ -580,12 +563,11 @@ CombatDamage Combat::applyImbuementElementalDamage(Item* item, CombatDamage dama /* If damage imbuement is set, we can return without checking other slots */ break; } - + return damage; } -void Combat::CombatManaFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data) -{ +void Combat::CombatManaFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data) { assert(data); CombatDamage damage = *data; if (damage.primary.value < 0) { @@ -599,18 +581,17 @@ void Combat::CombatManaFunc(Creature* caster, Creature* target, const CombatPara } } -void Combat::CombatConditionFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data) -{ +void Combat::CombatConditionFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data) { if (params.origin == ORIGIN_MELEE && data && data->primary.value == 0 && data->secondary.value == 0) { return; } - for (const auto& condition : params.conditionList) { + for (const auto &condition : params.conditionList) { Player* player = nullptr; if (target) { player = target->getPlayer(); } - //Cleanse charm rune (target as player) + // Cleanse charm rune (target as player) if (player) { if (player->isImmuneCleanse(condition->getType())) { player->sendCancelMessage("You are still immune against this spell."); @@ -640,7 +621,7 @@ void Combat::CombatConditionFunc(Creature* caster, Creature* target, const Comba conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID()); } - //TODO: infight condition until all aggressive conditions has ended + // TODO: infight condition until all aggressive conditions has ended if (target) { target->addCombatCondition(conditionCopy); } @@ -648,21 +629,18 @@ void Combat::CombatConditionFunc(Creature* caster, Creature* target, const Comba } } -void Combat::CombatDispelFunc(Creature*, Creature* target, const CombatParams& params, CombatDamage*) -{ +void Combat::CombatDispelFunc(Creature*, Creature* target, const CombatParams ¶ms, CombatDamage*) { if (target) { target->removeCombatCondition(params.dispelType); } } -void Combat::CombatNullFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage*) -{ +void Combat::CombatNullFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage*) { CombatConditionFunc(caster, target, params, nullptr); CombatDispelFunc(caster, target, params, nullptr); } -void Combat::combatTileEffects(const SpectatorHashSet& spectators, Creature* caster, Tile* tile, const CombatParams& params) -{ +void Combat::combatTileEffects(const SpectatorHashSet &spectators, Creature* caster, Tile* tile, const CombatParams ¶ms) { if (params.itemId != 0) { uint16_t itemId = params.itemId; switch (itemId) { @@ -747,15 +725,13 @@ void Combat::combatTileEffects(const SpectatorHashSet& spectators, Creature* cas } } -void Combat::postCombatEffects(Creature* caster, const Position& pos, const CombatParams& params) -{ +void Combat::postCombatEffects(Creature* caster, const Position &pos, const CombatParams ¶ms) { if (caster && params.distanceEffect != CONST_ANI_NONE) { addDistanceEffect(caster, caster->getPosition(), pos, params.distanceEffect); } } -void Combat::addDistanceEffect(Creature* caster, const Position& fromPos, const Position& toPos, uint8_t effect) -{ +void Combat::addDistanceEffect(Creature* caster, const Position &fromPos, const Position &toPos, uint8_t effect) { if (effect == CONST_ANI_WEAPONTYPE) { if (!caster) { return; @@ -787,9 +763,8 @@ void Combat::addDistanceEffect(Creature* caster, const Position& fromPos, const } } -void Combat::doCombat(Creature* caster, Creature* target) const -{ - //target combat callback function +void Combat::doCombat(Creature* caster, Creature* target) const { + // target combat callback function if (params.combatType != COMBAT_NONE) { CombatDamage damage = getCombatDamage(caster, target); if (damage.primary.type != COMBAT_MANADRAIN) { @@ -802,9 +777,8 @@ void Combat::doCombat(Creature* caster, Creature* target) const } } -void Combat::doCombat(Creature* caster, const Position& position) const -{ - //area combat callback function +void Combat::doCombat(Creature* caster, const Position &position) const { + // area combat callback function if (params.combatType != COMBAT_NONE) { CombatDamage damage = getCombatDamage(caster, nullptr); if (damage.primary.type != COMBAT_MANADRAIN) { @@ -817,8 +791,7 @@ void Combat::doCombat(Creature* caster, const Position& position) const } } -void Combat::CombatFunc(Creature* caster, const Position& pos, const AreaCombat* area, const CombatParams& params, CombatFunction func, CombatDamage* data) -{ +void Combat::CombatFunc(Creature* caster, const Position &pos, const AreaCombat* area, const CombatParams ¶ms, CombatFunction func, CombatDamage* data) { std::forward_list tileList; if (caster) { @@ -831,9 +804,9 @@ void Combat::CombatFunc(Creature* caster, const Position& pos, const AreaCombat* uint32_t maxX = 0; uint32_t maxY = 0; - //calculate the max viewable range + // calculate the max viewable range for (Tile* tile : tileList) { - const Position& tilePos = tile->getPosition(); + const Position &tilePos = tile->getPosition(); uint32_t diff = Position::getDistanceX(tilePos, pos); if (diff > maxX) { @@ -924,16 +897,15 @@ void Combat::CombatFunc(Creature* caster, const Position& pos, const AreaCombat* postCombatEffects(caster, pos, params); } -void Combat::doCombatHealth(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params) -{ +void Combat::doCombatHealth(Creature* caster, Creature* target, CombatDamage &damage, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR); - if ( (caster && target) - && (caster == target || canCombat) - && (params.impactEffect != CONST_ME_NONE)) { + if ((caster && target) + && (caster == target || canCombat) + && (params.impactEffect != CONST_ME_NONE)) { g_game().addMagicEffect(target->getPosition(), params.impactEffect); } - if (target && params.combatType == COMBAT_HEALING && target->getMonster()){ + if (target && params.combatType == COMBAT_HEALING && target->getMonster()) { if (target != caster) { return; } @@ -957,8 +929,8 @@ void Combat::doCombatHealth(Creature* caster, Creature* target, CombatDamage& da } if (chance != 0 && uniform_random(1, 100) <= chance) { damage.critical = true; - damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; - damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; + damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; + damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; } // Fatal hit (onslaught) @@ -985,23 +957,19 @@ void Combat::doCombatHealth(Creature* caster, Creature* target, CombatDamage& da } } -void Combat::doCombatHealth(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params) -{ - if (caster && caster->getPlayer()) - { +void Combat::doCombatHealth(Creature* caster, const Position &position, const AreaCombat* area, CombatDamage &damage, const CombatParams ¶ms) { + if (caster && caster->getPlayer()) { // Critical damage if (uint16_t chance = caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_CHANCE); - damage.primary.type != COMBAT_HEALING && chance != 0 && uniform_random(1, 100) <= chance) - { + damage.primary.type != COMBAT_HEALING && chance != 0 && uniform_random(1, 100) <= chance) { damage.critical = true; - damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; - damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; + damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; + damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; } // Fatal hit (onslaught) if (auto playerWeapon = caster->getPlayer()->getInventoryItem(CONST_SLOT_LEFT); - playerWeapon != nullptr && playerWeapon->getTier() > 0) - { + playerWeapon != nullptr && playerWeapon->getTier() > 0) { double_t fatalChance = playerWeapon->getFatalChance(); double_t randomChance = uniform_random(0, 10000) / 100; if (damage.primary.type != COMBAT_HEALING && fatalChance > 0 && randomChance < fatalChance) { @@ -1014,24 +982,21 @@ void Combat::doCombatHealth(Creature* caster, const Position& position, const Ar CombatFunc(caster, position, area, params, CombatHealthFunc, &damage); } -void Combat::doCombatMana(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params) -{ +void Combat::doCombatMana(Creature* caster, Creature* target, CombatDamage &damage, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR); if ((caster && target) - && (caster == target || canCombat) - && (params.impactEffect != CONST_ME_NONE)) - { + && (caster == target || canCombat) + && (params.impactEffect != CONST_ME_NONE)) { g_game().addMagicEffect(target->getPosition(), params.impactEffect); } - if (caster && caster->getPlayer()) - { + if (caster && caster->getPlayer()) { // Critical damage uint16_t chance = caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_CHANCE); if (chance != 0 && uniform_random(1, 100) <= chance) { damage.critical = true; - damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; - damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; + damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; + damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; } } @@ -1047,29 +1012,24 @@ void Combat::doCombatMana(Creature* caster, Creature* target, CombatDamage& dama } } -void Combat::doCombatMana(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params) -{ - if (caster && caster->getPlayer()) - { +void Combat::doCombatMana(Creature* caster, const Position &position, const AreaCombat* area, CombatDamage &damage, const CombatParams ¶ms) { + if (caster && caster->getPlayer()) { // Critical damage uint16_t chance = caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_CHANCE); - if (chance != 0 && uniform_random(1, 100) <= chance) - { + if (chance != 0 && uniform_random(1, 100) <= chance) { damage.critical = true; - damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; - damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE ))/100; + damage.primary.value += (damage.primary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; + damage.secondary.value += (damage.secondary.value * caster->getPlayer()->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE)) / 100; } } CombatFunc(caster, position, area, params, CombatManaFunc, &damage); } -void Combat::doCombatCondition(Creature* caster, const Position& position, const AreaCombat* area, const CombatParams& params) -{ +void Combat::doCombatCondition(Creature* caster, const Position &position, const AreaCombat* area, const CombatParams ¶ms) { CombatFunc(caster, position, area, params, CombatConditionFunc, nullptr); } -void Combat::doCombatCondition(Creature* caster, Creature* target, const CombatParams& params) -{ +void Combat::doCombatCondition(Creature* caster, Creature* target, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR); if ((caster == target || canCombat) && params.impactEffect != CONST_ME_NONE) { g_game().addMagicEffect(target->getPosition(), params.impactEffect); @@ -1087,17 +1047,15 @@ void Combat::doCombatCondition(Creature* caster, Creature* target, const CombatP } } -void Combat::doCombatDispel(Creature* caster, const Position& position, const AreaCombat* area, const CombatParams& params) -{ +void Combat::doCombatDispel(Creature* caster, const Position &position, const AreaCombat* area, const CombatParams ¶ms) { CombatFunc(caster, position, area, params, CombatDispelFunc, nullptr); } -void Combat::doCombatDispel(Creature* caster, Creature* target, const CombatParams& params) -{ +void Combat::doCombatDispel(Creature* caster, Creature* target, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR); - if ( (caster && target) - && (caster == target || canCombat) - && (params.impactEffect != CONST_ME_NONE)) { + if ((caster && target) + && (caster == target || canCombat) + && (params.impactEffect != CONST_ME_NONE)) { g_game().addMagicEffect(target->getPosition(), params.impactEffect); } @@ -1113,8 +1071,7 @@ void Combat::doCombatDispel(Creature* caster, Creature* target, const CombatPara } } -void Combat::doCombatDefault(Creature* caster, Creature* target, const CombatParams& params) -{ +void Combat::doCombatDefault(Creature* caster, Creature* target, const CombatParams ¶ms) { if (!params.aggressive || (caster != target && Combat::canDoCombat(caster, target) == RETURNVALUE_NOERROR)) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, target->getPosition(), true, true); @@ -1140,13 +1097,12 @@ void Combat::doCombatDefault(Creature* caster, Creature* target, const CombatPar //**********************************************************// -void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool useCharges) const -{ - //onGetPlayerMinMaxValues(...) +void ValueCallback::getMinMaxValues(Player* player, CombatDamage &damage, bool useCharges) const { + // onGetPlayerMinMaxValues(...) if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[ValueCallback::getMinMaxValues - Player {} formula {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), type); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), type); return; } @@ -1170,7 +1126,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool u switch (type) { case COMBAT_FORMULA_LEVELMAGIC: { - //onGetPlayerMinMaxValues(player, level, maglevel) + // onGetPlayerMinMaxValues(player, level, maglevel) lua_pushnumber(L, player->getLevel()); lua_pushnumber(L, player->getMagicLevel()); parameters += 2; @@ -1178,7 +1134,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool u } case COMBAT_FORMULA_SKILL: { - //onGetPlayerMinMaxValues(player, attackSkill, attackValue, attackFactor) + // onGetPlayerMinMaxValues(player, attackSkill, attackValue, attackFactor) Item* tool = player->getWeapon(); const Weapon* weapon = g_weapons().getWeapon(tool); Item* item = nullptr; @@ -1201,8 +1157,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool u shouldCalculateSecondaryDamage = true; attackValue += elementAttack; } - } - else { + } else { shouldCalculateSecondaryDamage = false; } @@ -1231,8 +1186,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool u int size0 = lua_gettop(L); if (lua_pcall(L, parameters, 2, 0) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); - } - else { + } else { int32_t defaultDmg = normal_random( LuaScriptInterface::getNumber(L, -2), @@ -1240,7 +1194,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool u ); if (shouldCalculateSecondaryDamage) { - double factor = (double)elementAttack / (double)attackValue; //attack value here is phys dmg + element dmg + double factor = (double)elementAttack / (double)attackValue; // attack value here is phys dmg + element dmg int32_t elementDamage = std::round(defaultDmg * factor); int32_t physDmg = std::round(defaultDmg * (1.0 - factor)); damage.primary.value = physDmg; @@ -1264,16 +1218,12 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage, bool u //**********************************************************// -void TileCallback::onTileCombat(Creature* creature, Tile* tile) const -{ - //onTileCombat(creature, pos) +void TileCallback::onTileCombat(Creature* creature, Tile* tile) const { + // onTileCombat(creature, pos) if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[TileCallback::onTileCombat - Creature {} type {} on tile x: {} y: {} z: {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), type, - (tile->getPosition()).getX(), - (tile->getPosition()).getY(), - (tile->getPosition()).getZ()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), type, (tile->getPosition()).getX(), (tile->getPosition()).getY(), (tile->getPosition()).getZ()); return; } @@ -1299,13 +1249,12 @@ void TileCallback::onTileCombat(Creature* creature, Tile* tile) const //**********************************************************// -void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const -{ - //onTargetCombat(creature, target) +void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const { + // onTargetCombat(creature, target) if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[TargetCallback::onTargetCombat - Creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName()); return; } @@ -1348,24 +1297,21 @@ void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const //**********************************************************// -void AreaCombat::clear() -{ - for (const auto& it : areas) { +void AreaCombat::clear() { + for (const auto &it : areas) { delete it.second; } areas.clear(); } -AreaCombat::AreaCombat(const AreaCombat& rhs) -{ +AreaCombat::AreaCombat(const AreaCombat &rhs) { hasExtArea = rhs.hasExtArea; - for (const auto& it : rhs.areas) { + for (const auto &it : rhs.areas) { areas[it.first] = new MatrixArea(*it.second); } } -void AreaCombat::getList(const Position& centerPos, const Position& targetPos, std::forward_list& list) const -{ +void AreaCombat::getList(const Position ¢erPos, const Position &targetPos, std::forward_list &list) const { const MatrixArea* area = getArea(centerPos, targetPos); if (!area) { return; @@ -1393,8 +1339,7 @@ void AreaCombat::getList(const Position& centerPos, const Position& targetPos, s } } -void AreaCombat::copyArea(const MatrixArea* input, MatrixArea* output, MatrixOperation_t op) const -{ +void AreaCombat::copyArea(const MatrixArea* input, MatrixArea* output, MatrixOperation_t op) const { uint32_t centerY, centerX; input->getCenter(centerY, centerX); @@ -1458,15 +1403,15 @@ void AreaCombat::copyArea(const MatrixArea* input, MatrixArea* output, MatrixOpe const uint32_t rows = input->getRows(); for (uint32_t x = 0, cols = input->getCols(); x < cols; ++x) { for (uint32_t y = 0; y < rows; ++y) { - //calculate new coordinates using rotation center + // calculate new coordinates using rotation center int32_t newX = x - centerX; int32_t newY = y - centerY; - //perform rotation + // perform rotation int32_t rotatedX = static_cast(round(newX * a + newY * b)); int32_t rotatedY = static_cast(round(newX * c + newY * d)); - //write in the output matrix using rotated coordinates + // write in the output matrix using rotated coordinates (*output)[rotatedY + rotateCenterY][rotatedX + rotateCenterX] = (*input)[y][x]; } } @@ -1475,8 +1420,7 @@ void AreaCombat::copyArea(const MatrixArea* input, MatrixArea* output, MatrixOpe } } -MatrixArea* AreaCombat::createArea(const std::list& list, uint32_t rows) -{ +MatrixArea* AreaCombat::createArea(const std::list &list, uint32_t rows) { uint32_t cols; if (rows == 0) { cols = 0; @@ -1508,33 +1452,31 @@ MatrixArea* AreaCombat::createArea(const std::list& list, uint32_t row return area; } -void AreaCombat::setupArea(const std::list& list, uint32_t rows) -{ +void AreaCombat::setupArea(const std::list &list, uint32_t rows) { MatrixArea* area = createArea(list, rows); - //NORTH + // NORTH areas[DIRECTION_NORTH] = area; uint32_t maxOutput = std::max(area->getCols(), area->getRows()) * 2; - //SOUTH + // SOUTH MatrixArea* southArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, southArea, MATRIXOPERATION_ROTATE180); areas[DIRECTION_SOUTH] = southArea; - //EAST + // EAST MatrixArea* eastArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, eastArea, MATRIXOPERATION_ROTATE90); areas[DIRECTION_EAST] = eastArea; - //WEST + // WEST MatrixArea* westArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, westArea, MATRIXOPERATION_ROTATE270); areas[DIRECTION_WEST] = westArea; } -void AreaCombat::setupArea(int32_t length, int32_t spread) -{ +void AreaCombat::setupArea(int32_t length, int32_t spread) { std::list list; uint32_t rows = length; @@ -1568,27 +1510,26 @@ void AreaCombat::setupArea(int32_t length, int32_t spread) setupArea(list, rows); } -void AreaCombat::setupArea(int32_t radius) -{ +void AreaCombat::setupArea(int32_t radius) { int32_t area[13][13] = { - {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0}, - {0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0}, - {0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0}, - {0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0}, - {0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0}, - {8, 7, 6, 5, 4, 2, 1, 2, 4, 5, 6, 7, 8}, - {0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0}, - {0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0}, - {0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0}, - {0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0}, - {0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0} + { 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0 }, + { 0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0 }, + { 0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0 }, + { 0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0 }, + { 0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0 }, + { 8, 7, 6, 5, 4, 2, 1, 2, 4, 5, 6, 7, 8 }, + { 0, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6, 8, 0 }, + { 0, 8, 7, 6, 5, 4, 4, 4, 5, 6, 7, 8, 0 }, + { 0, 0, 8, 7, 6, 5, 5, 5, 6, 7, 8, 0, 0 }, + { 0, 0, 0, 8, 7, 6, 6, 6, 7, 8, 0, 0, 0 }, + { 0, 0, 0, 0, 8, 8, 7, 8, 8, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0 } }; std::list list; - for (auto& row : area) { + for (auto &row : area) { for (int cell : row) { if (cell == 1) { list.push_back(3); @@ -1603,8 +1544,7 @@ void AreaCombat::setupArea(int32_t radius) setupArea(list, 13); } -void AreaCombat::setupExtArea(const std::list& list, uint32_t rows) -{ +void AreaCombat::setupExtArea(const std::list &list, uint32_t rows) { if (list.empty()) { return; } @@ -1612,22 +1552,22 @@ void AreaCombat::setupExtArea(const std::list& list, uint32_t rows) hasExtArea = true; MatrixArea* area = createArea(list, rows); - //NORTH-WEST + // NORTH-WEST areas[DIRECTION_NORTHWEST] = area; uint32_t maxOutput = std::max(area->getCols(), area->getRows()) * 2; - //NORTH-EAST + // NORTH-EAST MatrixArea* neArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, neArea, MATRIXOPERATION_MIRROR); areas[DIRECTION_NORTHEAST] = neArea; - //SOUTH-WEST + // SOUTH-WEST MatrixArea* swArea = new MatrixArea(maxOutput, maxOutput); copyArea(area, swArea, MATRIXOPERATION_FLIP); areas[DIRECTION_SOUTHWEST] = swArea; - //SOUTH-EAST + // SOUTH-EAST MatrixArea* seArea = new MatrixArea(maxOutput, maxOutput); copyArea(swArea, seArea, MATRIXOPERATION_MIRROR); areas[DIRECTION_SOUTHEAST] = seArea; @@ -1635,9 +1575,8 @@ void AreaCombat::setupExtArea(const std::list& list, uint32_t rows) //**********************************************************// -void MagicField::onStepInField(Creature& creature) -{ - //remove magic walls/wild growth +void MagicField::onStepInField(Creature &creature) { + // remove magic walls/wild growth if (!isBlocking() && g_game().getWorldType() == WORLD_TYPE_NO_PVP && id == ITEM_MAGICWALL_SAFE || id == ITEM_WILDGROWTH_SAFE) { if (!creature.isInGhostMode()) { g_game().internalRemoveItem(this, 1); @@ -1646,7 +1585,7 @@ void MagicField::onStepInField(Creature& creature) return; } - const ItemType& it = items[getID()]; + const ItemType &it = items[getID()]; if (it.conditionDamage) { Condition* conditionCopy = it.conditionDamage->clone(); auto ownerId = getAttribute(ItemAttribute_t::OWNER); diff --git a/src/creatures/combat/combat.h b/src/creatures/combat/combat.h index df30a4cb2a6..2b6ff379d5b 100644 --- a/src/creatures/combat/combat.h +++ b/src/creatures/combat/combat.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_COMBAT_COMBAT_H_ #define SRC_CREATURES_COMBAT_COMBAT_H_ @@ -19,19 +19,18 @@ class Condition; class Creature; class Item; -//for luascript callback -class ValueCallback final : public CallBack -{ +// for luascript callback +class ValueCallback final : public CallBack { public: - explicit ValueCallback(formulaType_t initType): type(initType) {} - void getMinMaxValues(Player* player, CombatDamage& damage, bool useCharges) const; + explicit ValueCallback(formulaType_t initType) : + type(initType) { } + void getMinMaxValues(Player* player, CombatDamage &damage, bool useCharges) const; private: formulaType_t type; }; -class TileCallback final : public CallBack -{ +class TileCallback final : public CallBack { public: void onTileCombat(Creature* creature, Tile* tile) const; @@ -39,8 +38,7 @@ class TileCallback final : public CallBack formulaType_t type; }; -class TargetCallback final : public CallBack -{ +class TargetCallback final : public CallBack { public: void onTargetCombat(Creature* creature, Creature* target) const; @@ -49,34 +47,34 @@ class TargetCallback final : public CallBack }; struct CombatParams { - std::forward_list> conditionList; + std::forward_list> conditionList; - std::unique_ptr valueCallback; - std::unique_ptr tileCallback; - std::unique_ptr targetCallback; + std::unique_ptr valueCallback; + std::unique_ptr tileCallback; + std::unique_ptr targetCallback; - uint16_t itemId = 0; + uint16_t itemId = 0; - ConditionType_t dispelType = CONDITION_NONE; - CombatType_t combatType = COMBAT_NONE; - CombatOrigin origin = ORIGIN_SPELL; + ConditionType_t dispelType = CONDITION_NONE; + CombatType_t combatType = COMBAT_NONE; + CombatOrigin origin = ORIGIN_SPELL; - uint8_t impactEffect = CONST_ME_NONE; - uint8_t distanceEffect = CONST_ANI_NONE; + uint8_t impactEffect = CONST_ME_NONE; + uint8_t distanceEffect = CONST_ANI_NONE; - bool blockedByArmor = false; - bool blockedByShield = false; - bool targetCasterOrTopMost = false; - bool aggressive = true; - bool useCharges = false; + bool blockedByArmor = false; + bool blockedByShield = false; + bool targetCasterOrTopMost = false; + bool aggressive = true; + bool useCharges = false; }; -using CombatFunction = std::function; +using CombatFunction = std::function; -class MatrixArea -{ +class MatrixArea { public: - MatrixArea(uint32_t initRows, uint32_t initCols): centerX(0), centerY(0), rows(initRows), cols(initCols) { + MatrixArea(uint32_t initRows, uint32_t initCols) : + centerX(0), centerY(0), rows(initRows), cols(initCols) { data_ = new bool*[rows]; for (uint32_t row = 0; row < rows; ++row) { @@ -88,7 +86,7 @@ class MatrixArea } } - MatrixArea(const MatrixArea& rhs) { + MatrixArea(const MatrixArea &rhs) { centerX = rhs.centerX; centerY = rhs.centerY; rows = rhs.rows; @@ -114,11 +112,10 @@ class MatrixArea } // non-assignable - MatrixArea& operator=(const MatrixArea&) = delete; + MatrixArea &operator=(const MatrixArea &) = delete; void setValue(uint32_t row, uint32_t col, bool value) { - if (row < rows && col < cols) - { + if (row < rows && col < cols) { data_[row][col] = value; } else { SPDLOG_ERROR("[{}] Access exceeds the upper limit of memory block"); @@ -133,7 +130,7 @@ class MatrixArea centerX = x; centerY = y; } - void getCenter(uint32_t& y, uint32_t& x) const { + void getCenter(uint32_t &y, uint32_t &x) const { x = centerX; y = centerY; } @@ -161,32 +158,31 @@ class MatrixArea bool** data_; }; -class AreaCombat -{ +class AreaCombat { public: AreaCombat() = default; - AreaCombat(const AreaCombat& rhs); + AreaCombat(const AreaCombat &rhs); ~AreaCombat() { clear(); } // non-assignable - AreaCombat& operator=(const AreaCombat&) = delete; + AreaCombat &operator=(const AreaCombat &) = delete; - void getList(const Position& centerPos, const Position& targetPos, std::forward_list& list) const; + void getList(const Position ¢erPos, const Position &targetPos, std::forward_list &list) const; - void setupArea(const std::list& list, uint32_t rows); + void setupArea(const std::list &list, uint32_t rows); void setupArea(int32_t length, int32_t spread); void setupArea(int32_t radius); - void setupExtArea(const std::list& list, uint32_t rows); + void setupExtArea(const std::list &list, uint32_t rows); void clear(); private: - MatrixArea* createArea(const std::list& list, uint32_t rows); + MatrixArea* createArea(const std::list &list, uint32_t rows); void copyArea(const MatrixArea* input, MatrixArea* output, MatrixOperation_t op) const; - MatrixArea* getArea(const Position& centerPos, const Position& targetPos) const { + MatrixArea* getArea(const Position ¢erPos, const Position &targetPos) const { int32_t dx = Position::getOffsetX(targetPos, centerPos); int32_t dy = Position::getOffsetY(targetPos, centerPos); @@ -224,28 +220,27 @@ class AreaCombat bool hasExtArea = false; }; -class Combat -{ +class Combat { public: Combat() = default; // non-copyable - Combat(const Combat&) = delete; - Combat& operator=(const Combat&) = delete; + Combat(const Combat &) = delete; + Combat &operator=(const Combat &) = delete; - static void doCombatHealth(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params); - static void doCombatHealth(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params); + static void doCombatHealth(Creature* caster, Creature* target, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatHealth(Creature* caster, const Position &position, const AreaCombat* area, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatMana(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params); - static void doCombatMana(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params); + static void doCombatMana(Creature* caster, Creature* target, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatMana(Creature* caster, const Position &position, const AreaCombat* area, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatCondition(Creature* caster, Creature* target, const CombatParams& params); - static void doCombatCondition(Creature* caster, const Position& position, const AreaCombat* area, const CombatParams& params); + static void doCombatCondition(Creature* caster, Creature* target, const CombatParams ¶ms); + static void doCombatCondition(Creature* caster, const Position &position, const AreaCombat* area, const CombatParams ¶ms); - static void doCombatDispel(Creature* caster, Creature* target, const CombatParams& params); - static void doCombatDispel(Creature* caster, const Position& position, const AreaCombat* area, const CombatParams& params); + static void doCombatDispel(Creature* caster, Creature* target, const CombatParams ¶ms); + static void doCombatDispel(Creature* caster, const Position &position, const AreaCombat* area, const CombatParams ¶ms); - static void getCombatArea(const Position& centerPos, const Position& targetPos, const AreaCombat* area, std::forward_list& list); + static void getCombatArea(const Position ¢erPos, const Position &targetPos, const AreaCombat* area, std::forward_list &list); static bool isInPvpZone(const Creature* attacker, const Creature* target); static bool isProtected(const Player* attacker, const Player* target); @@ -255,12 +250,12 @@ class Combat static ReturnValue canTargetCreature(Player* attacker, Creature* target); static ReturnValue canDoCombat(Creature* caster, Tile* tile, bool aggressive); static ReturnValue canDoCombat(Creature* attacker, Creature* target); - static void postCombatEffects(Creature* caster, const Position& pos, const CombatParams& params); + static void postCombatEffects(Creature* caster, const Position &pos, const CombatParams ¶ms); - static void addDistanceEffect(Creature* caster, const Position& fromPos, const Position& toPos, uint8_t effect); + static void addDistanceEffect(Creature* caster, const Position &fromPos, const Position &toPos, uint8_t effect); void doCombat(Creature* caster, Creature* target) const; - void doCombat(Creature* caster, const Position& pos) const; + void doCombat(Creature* caster, const Position &pos) const; bool setCallback(CallBackParam_t key); CallBack* getCallback(CallBackParam_t key); @@ -276,7 +271,7 @@ class Combat params.conditionList.emplace_front(condition); } void setPlayerCombatValues(formulaType_t formulaType, double mina, double minb, double maxa, double maxb); - void postCombatEffects(Creature* caster, const Position& pos) const { + void postCombatEffects(Creature* caster, const Position &pos) const { postCombatEffects(caster, pos, params); } @@ -285,24 +280,24 @@ class Combat } private: - static void doCombatDefault(Creature* caster, Creature* target, const CombatParams& params); + static void doCombatDefault(Creature* caster, Creature* target, const CombatParams ¶ms); - static void CombatFunc(Creature* caster, const Position& pos, const AreaCombat* area, const CombatParams& params, CombatFunction func, CombatDamage* data); + static void CombatFunc(Creature* caster, const Position &pos, const AreaCombat* area, const CombatParams ¶ms, CombatFunction func, CombatDamage* data); - static void CombatHealthFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data); + static void CombatHealthFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data); static CombatDamage applyImbuementElementalDamage(Item* item, CombatDamage damage); - static void CombatManaFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* damage); - static void CombatConditionFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data); - static void CombatDispelFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data); - static void CombatNullFunc(Creature* caster, Creature* target, const CombatParams& params, CombatDamage* data); + static void CombatManaFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* damage); + static void CombatConditionFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data); + static void CombatDispelFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data); + static void CombatNullFunc(Creature* caster, Creature* target, const CombatParams ¶ms, CombatDamage* data); - static void combatTileEffects(const SpectatorHashSet& spectators, Creature* caster, Tile* tile, const CombatParams& params); + static void combatTileEffects(const SpectatorHashSet &spectators, Creature* caster, Tile* tile, const CombatParams ¶ms); CombatDamage getCombatDamage(Creature* creature, Creature* target) const; - //configureable + // configureable CombatParams params; - //formula variables + // formula variables formulaType_t formulaType = COMBAT_FORMULA_UNDEFINED; double mina = 0.0; double minb = 0.0; @@ -312,10 +307,10 @@ class Combat std::unique_ptr area; }; -class MagicField final : public Item -{ +class MagicField final : public Item { public: - explicit MagicField(uint16_t type) : Item(type), createTime(OTSYS_TIME()) {} + explicit MagicField(uint16_t type) : + Item(type), createTime(OTSYS_TIME()) { } MagicField* getMagicField() override { return this; @@ -328,20 +323,20 @@ class MagicField final : public Item return Item::items[getID()].replaceable; } CombatType_t getCombatType() const { - const ItemType& it = items[getID()]; + const ItemType &it = items[getID()]; return it.combatType; } int32_t getDamage() const { - const ItemType& it = items[getID()]; + const ItemType &it = items[getID()]; if (it.conditionDamage) { return it.conditionDamage->getTotalDamage(); } return 0; } - void onStepInField(Creature& creature); + void onStepInField(Creature &creature); private: int64_t createTime; }; -#endif // SRC_CREATURES_COMBAT_COMBAT_H_ +#endif // SRC_CREATURES_COMBAT_COMBAT_H_ diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index bcc8f14a354..031d557f863 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "creatures/combat/condition.h" #include "game/game.h" -bool Condition::setParam(ConditionParam_t param, int32_t value) -{ +bool Condition::setParam(ConditionParam_t param, int32_t value) { switch (param) { case CONDITION_PARAM_TICKS: { ticks = value; @@ -36,8 +35,7 @@ bool Condition::setParam(ConditionParam_t param, int32_t value) } } -bool Condition::unserialize(PropStream& propStream) -{ +bool Condition::unserialize(PropStream &propStream) { uint8_t attr_type; while (propStream.read(attr_type) && attr_type != CONDITIONATTR_END) { if (!unserializeProp(static_cast(attr_type), propStream)) { @@ -47,8 +45,7 @@ bool Condition::unserialize(PropStream& propStream) return true; } -bool Condition::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool Condition::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { switch (attr) { case CONDITIONATTR_TYPE: { int32_t value; @@ -96,8 +93,7 @@ bool Condition::unserializeProp(ConditionAttr_t attr, PropStream& propStream) } } -void Condition::serialize(PropWriteStream& propWriteStream) -{ +void Condition::serialize(PropWriteStream &propWriteStream) { propWriteStream.write(CONDITIONATTR_TYPE); propWriteStream.write(conditionType); @@ -114,25 +110,22 @@ void Condition::serialize(PropWriteStream& propWriteStream) propWriteStream.write(subId); } -void Condition::setTicks(int32_t newTicks) -{ +void Condition::setTicks(int32_t newTicks) { ticks = newTicks; endTime = ticks + OTSYS_TIME(); } -bool Condition::executeCondition(Creature*, int32_t interval) -{ +bool Condition::executeCondition(Creature*, int32_t interval) { if (ticks == -1) { return true; } - //Not using set ticks here since it would reset endTime + // Not using set ticks here since it would reset endTime ticks = std::max(0, ticks - interval); return getEndTime() >= OTSYS_TIME(); } -Condition* Condition::createCondition(ConditionId_t id, ConditionType_t type, int32_t ticks, int32_t param/* = 0*/, bool buff/* = false*/, uint32_t subId/* = 0*/) -{ +Condition* Condition::createCondition(ConditionId_t id, ConditionType_t type, int32_t ticks, int32_t param /* = 0*/, bool buff /* = false*/, uint32_t subId /* = 0*/) { switch (type) { case CONDITION_POISON: case CONDITION_FIRE: @@ -172,10 +165,10 @@ Condition* Condition::createCondition(ConditionId_t id, ConditionType_t type, in case CONDITION_SPELLGROUPCOOLDOWN: return new ConditionSpellGroupCooldown(id, type, ticks, buff, subId); - case CONDITION_MANASHIELD: - return new ConditionManaShield(id, type, ticks, buff, subId); + case CONDITION_MANASHIELD: + return new ConditionManaShield(id, type, ticks, buff, subId); - case CONDITION_ROOTED: + case CONDITION_ROOTED: case CONDITION_INFIGHT: case CONDITION_DRUNK: case CONDITION_EXHAUST: @@ -192,8 +185,7 @@ Condition* Condition::createCondition(ConditionId_t id, ConditionType_t type, in } } -Condition* Condition::createCondition(PropStream& propStream) -{ +Condition* Condition::createCondition(PropStream &propStream) { uint8_t attr; if (!propStream.read(attr) || attr != CONDITIONATTR_TYPE) { return nullptr; @@ -243,16 +235,14 @@ Condition* Condition::createCondition(PropStream& propStream) return createCondition(static_cast(id), static_cast(type), ticks, 0, buff != 0, subId); } -bool Condition::startCondition(Creature*) -{ +bool Condition::startCondition(Creature*) { if (ticks > 0) { endTime = ticks + OTSYS_TIME(); } return true; } -bool Condition::isPersistent() const -{ +bool Condition::isPersistent() const { if (ticks == -1) { return false; } @@ -264,13 +254,11 @@ bool Condition::isPersistent() const return true; } -uint32_t Condition::getIcons() const -{ +uint32_t Condition::getIcons() const { return isBuff ? ICON_PARTY_BUFF : 0; } -bool Condition::updateCondition(const Condition* addCondition) -{ +bool Condition::updateCondition(const Condition* addCondition) { if (conditionType != addCondition->getType()) { return false; } @@ -286,30 +274,25 @@ bool Condition::updateCondition(const Condition* addCondition) return true; } -bool ConditionGeneric::startCondition(Creature* creature) -{ +bool ConditionGeneric::startCondition(Creature* creature) { return Condition::startCondition(creature); } -bool ConditionGeneric::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionGeneric::executeCondition(Creature* creature, int32_t interval) { return Condition::executeCondition(creature, interval); } -void ConditionGeneric::endCondition(Creature*) -{ +void ConditionGeneric::endCondition(Creature*) { // } -void ConditionGeneric::addCondition(Creature*, const Condition* addCondition) -{ +void ConditionGeneric::addCondition(Creature*, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); } } -uint32_t ConditionGeneric::getIcons() const -{ +uint32_t ConditionGeneric::getIcons() const { uint32_t icons = Condition::getIcons(); switch (conditionType) { @@ -321,8 +304,8 @@ uint32_t ConditionGeneric::getIcons() const icons |= ICON_DRUNK; break; - case CONDITION_ROOTED: - icons |= ICON_ROOTED; + case CONDITION_ROOTED: + icons |= ICON_ROOTED; break; default: @@ -332,408 +315,392 @@ uint32_t ConditionGeneric::getIcons() const return icons; } -void ConditionAttributes::addCondition(Creature* creature, const Condition* addCondition) -{ - if (updateCondition(addCondition)) { - setTicks(addCondition->getTicks()); - - const ConditionAttributes& conditionAttrs = static_cast(*addCondition); - //Remove the old condition - endCondition(creature); - - //Apply the new one - memcpy(skills, conditionAttrs.skills, sizeof(skills)); - memcpy(skillsPercent, conditionAttrs.skillsPercent, sizeof(skillsPercent)); - memcpy(stats, conditionAttrs.stats, sizeof(stats)); - memcpy(statsPercent, conditionAttrs.statsPercent, sizeof(statsPercent)); - memcpy(buffs, conditionAttrs.buffs, sizeof(buffs)); - memcpy(buffsPercent, conditionAttrs.buffsPercent, sizeof(buffsPercent)); - updatePercentBuffs(creature); - updateBuffs(creature); - disableDefense = conditionAttrs.disableDefense; - - if (Player* player = creature->getPlayer()) { - updatePercentSkills(player); - updateSkills(player); - updatePercentStats(player); - updateStats(player); - } - } -} - -bool ConditionAttributes::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ - if (attr == CONDITIONATTR_SKILLS) { - return propStream.read(skills[currentSkill++]); - } - else if (attr == CONDITIONATTR_STATS) { - return propStream.read(stats[currentStat++]); - } - else if (attr == CONDITIONATTR_BUFFS) { - return propStream.read(buffs[currentBuff++]); - } - return Condition::unserializeProp(attr, propStream); -} - -void ConditionAttributes::serialize(PropWriteStream& propWriteStream) -{ - Condition::serialize(propWriteStream); - - for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { - propWriteStream.write(CONDITIONATTR_SKILLS); - propWriteStream.write(skills[i]); - } - - for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { - propWriteStream.write(CONDITIONATTR_STATS); - propWriteStream.write(stats[i]); - } - - for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { - propWriteStream.write(CONDITIONATTR_BUFFS); - propWriteStream.write(buffs[i]); - } -} - -bool ConditionAttributes::startCondition(Creature* creature) -{ - if (!Condition::startCondition(creature)) { - return false; - } - - creature->setUseDefense(!disableDefense); - updatePercentBuffs(creature); - updateBuffs(creature); - if (Player* player = creature->getPlayer()) { - updatePercentSkills(player); - updateSkills(player); - updatePercentStats(player); - updateStats(player); - } - - return true; -} - -void ConditionAttributes::updatePercentStats(Player* player) -{ - for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { - if (statsPercent[i] == 0) { - continue; - } - - switch (i) { - case STAT_MAXHITPOINTS: - stats[i] = static_cast(player->getMaxHealth() * ((statsPercent[i] - 100) / 100.f)); - break; - - case STAT_MAXMANAPOINTS: - stats[i] = static_cast(player->getMaxMana() * ((statsPercent[i] - 100) / 100.f)); - break; - - case STAT_MAGICPOINTS: - stats[i] = static_cast(player->getBaseMagicLevel() * ((statsPercent[i] - 100) / 100.f)); - break; - - case STAT_CAPACITY: - stats[i] = static_cast(player->getCapacity() * (statsPercent[i] / 100.f)); - break; - } - } -} - -void ConditionAttributes::updateStats(Player* player) -{ - bool needUpdate = false; - - for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { - if (stats[i]) { - needUpdate = true; - player->setVarStats(static_cast(i), stats[i]); - } - } - - if (needUpdate) { - player->sendStats(); - player->sendSkills(); - } -} - -void ConditionAttributes::updatePercentSkills(Player* player) -{ - for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { - if (skillsPercent[i] == 0) { - continue; - } - - int32_t unmodifiedSkill = player->getBaseSkill(i); - skills[i] = static_cast(unmodifiedSkill * ((skillsPercent[i] - 100) / 100.f)); - } -} - -void ConditionAttributes::updateSkills(Player* player) -{ - bool needUpdateSkills = false; - - for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { - if (skills[i]) { - needUpdateSkills = true; - player->setVarSkill(static_cast(i), skills[i]); - } - } - - if (needUpdateSkills) { - player->sendSkills(); - } -} - -void ConditionAttributes::updatePercentBuffs(Creature* creature) -{ - for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { - if (buffsPercent[i] == 0) { - continue; - } - - int32_t actualBuff = creature->getBuff(i); - buffs[i] = static_cast(actualBuff * ((buffsPercent[i] - 100) / 100.f)); - } -} - -void ConditionAttributes::updateBuffs(Creature* creature) -{ - bool needUpdate = false; - for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { - if (buffs[i]) { - needUpdate = true; - creature->setBuff(static_cast(i), buffs[i]); - } - } - if (creature->getMonster() && needUpdate) { - g_game().updateCreatureIcon(creature); - } -} - -bool ConditionAttributes::executeCondition(Creature* creature, int32_t interval) -{ - return ConditionGeneric::executeCondition(creature, interval); -} - -void ConditionAttributes::endCondition(Creature* creature) -{ - Player* player = creature->getPlayer(); - if (player) { - bool needUpdate = false; - - for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { - if (skills[i] || skillsPercent[i]) { - needUpdate = true; - player->setVarSkill(static_cast(i), -skills[i]); - } - } - - for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { - if (stats[i]) { - needUpdate = true; - player->setVarStats(static_cast(i), -stats[i]); - } - } - - if (needUpdate) { - player->sendStats(); - player->sendSkills(); - } - } - bool needUpdateIcons = false; - for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { - if (buffs[i]) { - needUpdateIcons = true; - creature->setBuff(static_cast(i), -buffs[i]); - } - } - if (creature->getMonster() && needUpdateIcons) { - g_game().updateCreatureIcon(creature); - } - - if (disableDefense) { - creature->setUseDefense(true); - } -} - -bool ConditionAttributes::setParam(ConditionParam_t param, int32_t value) -{ - bool ret = ConditionGeneric::setParam(param, value); - - switch (param) { - case CONDITION_PARAM_SKILL_MELEE: { - skills[SKILL_CLUB] = value; - skills[SKILL_AXE] = value; - skills[SKILL_SWORD] = value; - return true; - } - - case CONDITION_PARAM_SKILL_MELEEPERCENT: { - skillsPercent[SKILL_CLUB] = value; - skillsPercent[SKILL_AXE] = value; - skillsPercent[SKILL_SWORD] = value; - return true; - } - - case CONDITION_PARAM_SKILL_FIST: { - skills[SKILL_FIST] = value; - return true; - } - - case CONDITION_PARAM_SKILL_FISTPERCENT: { - skillsPercent[SKILL_FIST] = value; - return true; - } - - case CONDITION_PARAM_SKILL_CLUB: { - skills[SKILL_CLUB] = value; - return true; - } - - case CONDITION_PARAM_SKILL_CLUBPERCENT: { - skillsPercent[SKILL_CLUB] = value; - return true; - } - - case CONDITION_PARAM_SKILL_SWORD: { - skills[SKILL_SWORD] = value; - return true; - } - - case CONDITION_PARAM_SKILL_SWORDPERCENT: { - skillsPercent[SKILL_SWORD] = value; - return true; - } - - case CONDITION_PARAM_SKILL_AXE: { - skills[SKILL_AXE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_AXEPERCENT: { - skillsPercent[SKILL_AXE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_DISTANCE: { - skills[SKILL_DISTANCE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_DISTANCEPERCENT: { - skillsPercent[SKILL_DISTANCE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_SHIELD: { - skills[SKILL_SHIELD] = value; - return true; - } - - case CONDITION_PARAM_SKILL_SHIELDPERCENT: { - skillsPercent[SKILL_SHIELD] = value; - return true; - } - - case CONDITION_PARAM_SKILL_FISHING: { - skills[SKILL_FISHING] = value; - return true; - } - - case CONDITION_PARAM_SKILL_FISHINGPERCENT: { - skillsPercent[SKILL_FISHING] = value; - return true; - } - - case CONDITION_PARAM_SKILL_CRITICAL_HIT_CHANCE: { - skills[SKILL_CRITICAL_HIT_CHANCE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_CRITICAL_HIT_DAMAGE: { - skills[SKILL_CRITICAL_HIT_DAMAGE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_LIFE_LEECH_CHANCE: { - skills[SKILL_LIFE_LEECH_CHANCE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_LIFE_LEECH_AMOUNT: { - skills[SKILL_LIFE_LEECH_AMOUNT] = value; - return true; - } - - case CONDITION_PARAM_SKILL_MANA_LEECH_CHANCE: { - skills[SKILL_MANA_LEECH_CHANCE] = value; - return true; - } - - case CONDITION_PARAM_SKILL_MANA_LEECH_AMOUNT: { - skills[SKILL_MANA_LEECH_AMOUNT] = value; - return true; - } - - case CONDITION_PARAM_STAT_MAXHITPOINTS: { - stats[STAT_MAXHITPOINTS] = value; - return true; - } - - case CONDITION_PARAM_STAT_MAXMANAPOINTS: { - stats[STAT_MAXMANAPOINTS] = value; - return true; - } - - case CONDITION_PARAM_STAT_MAGICPOINTS: { - stats[STAT_MAGICPOINTS] = value; - return true; - } - - case CONDITION_PARAM_STAT_MAXHITPOINTSPERCENT: { - statsPercent[STAT_MAXHITPOINTS] = std::max(0, value); - return true; - } - - case CONDITION_PARAM_STAT_MAXMANAPOINTSPERCENT: { - statsPercent[STAT_MAXMANAPOINTS] = std::max(0, value); - return true; - } - - case CONDITION_PARAM_STAT_MAGICPOINTSPERCENT: { - statsPercent[STAT_MAGICPOINTS] = std::max(0, value); - return true; - } - - case CONDITION_PARAM_DISABLE_DEFENSE: { - disableDefense = (value != 0); - return true; - } - - case CONDITION_PARAM_STAT_CAPACITYPERCENT: { - statsPercent[STAT_CAPACITY] = std::max(0, value); - return true; - } - - case CONDITION_PARAM_BUFF_DAMAGEDEALT: { - buffsPercent[BUFF_DAMAGEDEALT] = std::max(0, value); - return true; - } - - case CONDITION_PARAM_BUFF_DAMAGERECEIVED: { - buffsPercent[BUFF_DAMAGERECEIVED] = std::max(0, value); - return true; - } - - default: - return ret; - } -} - -bool ConditionRegeneration::startCondition(Creature* creature) -{ +void ConditionAttributes::addCondition(Creature* creature, const Condition* addCondition) { + if (updateCondition(addCondition)) { + setTicks(addCondition->getTicks()); + + const ConditionAttributes &conditionAttrs = static_cast(*addCondition); + // Remove the old condition + endCondition(creature); + + // Apply the new one + memcpy(skills, conditionAttrs.skills, sizeof(skills)); + memcpy(skillsPercent, conditionAttrs.skillsPercent, sizeof(skillsPercent)); + memcpy(stats, conditionAttrs.stats, sizeof(stats)); + memcpy(statsPercent, conditionAttrs.statsPercent, sizeof(statsPercent)); + memcpy(buffs, conditionAttrs.buffs, sizeof(buffs)); + memcpy(buffsPercent, conditionAttrs.buffsPercent, sizeof(buffsPercent)); + updatePercentBuffs(creature); + updateBuffs(creature); + disableDefense = conditionAttrs.disableDefense; + + if (Player* player = creature->getPlayer()) { + updatePercentSkills(player); + updateSkills(player); + updatePercentStats(player); + updateStats(player); + } + } +} + +bool ConditionAttributes::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { + if (attr == CONDITIONATTR_SKILLS) { + return propStream.read(skills[currentSkill++]); + } else if (attr == CONDITIONATTR_STATS) { + return propStream.read(stats[currentStat++]); + } else if (attr == CONDITIONATTR_BUFFS) { + return propStream.read(buffs[currentBuff++]); + } + return Condition::unserializeProp(attr, propStream); +} + +void ConditionAttributes::serialize(PropWriteStream &propWriteStream) { + Condition::serialize(propWriteStream); + + for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { + propWriteStream.write(CONDITIONATTR_SKILLS); + propWriteStream.write(skills[i]); + } + + for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { + propWriteStream.write(CONDITIONATTR_STATS); + propWriteStream.write(stats[i]); + } + + for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { + propWriteStream.write(CONDITIONATTR_BUFFS); + propWriteStream.write(buffs[i]); + } +} + +bool ConditionAttributes::startCondition(Creature* creature) { + if (!Condition::startCondition(creature)) { + return false; + } + + creature->setUseDefense(!disableDefense); + updatePercentBuffs(creature); + updateBuffs(creature); + if (Player* player = creature->getPlayer()) { + updatePercentSkills(player); + updateSkills(player); + updatePercentStats(player); + updateStats(player); + } + + return true; +} + +void ConditionAttributes::updatePercentStats(Player* player) { + for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { + if (statsPercent[i] == 0) { + continue; + } + + switch (i) { + case STAT_MAXHITPOINTS: + stats[i] = static_cast(player->getMaxHealth() * ((statsPercent[i] - 100) / 100.f)); + break; + + case STAT_MAXMANAPOINTS: + stats[i] = static_cast(player->getMaxMana() * ((statsPercent[i] - 100) / 100.f)); + break; + + case STAT_MAGICPOINTS: + stats[i] = static_cast(player->getBaseMagicLevel() * ((statsPercent[i] - 100) / 100.f)); + break; + + case STAT_CAPACITY: + stats[i] = static_cast(player->getCapacity() * (statsPercent[i] / 100.f)); + break; + } + } +} + +void ConditionAttributes::updateStats(Player* player) { + bool needUpdate = false; + + for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { + if (stats[i]) { + needUpdate = true; + player->setVarStats(static_cast(i), stats[i]); + } + } + + if (needUpdate) { + player->sendStats(); + player->sendSkills(); + } +} + +void ConditionAttributes::updatePercentSkills(Player* player) { + for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { + if (skillsPercent[i] == 0) { + continue; + } + + int32_t unmodifiedSkill = player->getBaseSkill(i); + skills[i] = static_cast(unmodifiedSkill * ((skillsPercent[i] - 100) / 100.f)); + } +} + +void ConditionAttributes::updateSkills(Player* player) { + bool needUpdateSkills = false; + + for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { + if (skills[i]) { + needUpdateSkills = true; + player->setVarSkill(static_cast(i), skills[i]); + } + } + + if (needUpdateSkills) { + player->sendSkills(); + } +} + +void ConditionAttributes::updatePercentBuffs(Creature* creature) { + for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { + if (buffsPercent[i] == 0) { + continue; + } + + int32_t actualBuff = creature->getBuff(i); + buffs[i] = static_cast(actualBuff * ((buffsPercent[i] - 100) / 100.f)); + } +} + +void ConditionAttributes::updateBuffs(Creature* creature) { + bool needUpdate = false; + for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { + if (buffs[i]) { + needUpdate = true; + creature->setBuff(static_cast(i), buffs[i]); + } + } + if (creature->getMonster() && needUpdate) { + g_game().updateCreatureIcon(creature); + } +} + +bool ConditionAttributes::executeCondition(Creature* creature, int32_t interval) { + return ConditionGeneric::executeCondition(creature, interval); +} + +void ConditionAttributes::endCondition(Creature* creature) { + Player* player = creature->getPlayer(); + if (player) { + bool needUpdate = false; + + for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { + if (skills[i] || skillsPercent[i]) { + needUpdate = true; + player->setVarSkill(static_cast(i), -skills[i]); + } + } + + for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { + if (stats[i]) { + needUpdate = true; + player->setVarStats(static_cast(i), -stats[i]); + } + } + + if (needUpdate) { + player->sendStats(); + player->sendSkills(); + } + } + bool needUpdateIcons = false; + for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { + if (buffs[i]) { + needUpdateIcons = true; + creature->setBuff(static_cast(i), -buffs[i]); + } + } + if (creature->getMonster() && needUpdateIcons) { + g_game().updateCreatureIcon(creature); + } + + if (disableDefense) { + creature->setUseDefense(true); + } +} + +bool ConditionAttributes::setParam(ConditionParam_t param, int32_t value) { + bool ret = ConditionGeneric::setParam(param, value); + + switch (param) { + case CONDITION_PARAM_SKILL_MELEE: { + skills[SKILL_CLUB] = value; + skills[SKILL_AXE] = value; + skills[SKILL_SWORD] = value; + return true; + } + + case CONDITION_PARAM_SKILL_MELEEPERCENT: { + skillsPercent[SKILL_CLUB] = value; + skillsPercent[SKILL_AXE] = value; + skillsPercent[SKILL_SWORD] = value; + return true; + } + + case CONDITION_PARAM_SKILL_FIST: { + skills[SKILL_FIST] = value; + return true; + } + + case CONDITION_PARAM_SKILL_FISTPERCENT: { + skillsPercent[SKILL_FIST] = value; + return true; + } + + case CONDITION_PARAM_SKILL_CLUB: { + skills[SKILL_CLUB] = value; + return true; + } + + case CONDITION_PARAM_SKILL_CLUBPERCENT: { + skillsPercent[SKILL_CLUB] = value; + return true; + } + + case CONDITION_PARAM_SKILL_SWORD: { + skills[SKILL_SWORD] = value; + return true; + } + + case CONDITION_PARAM_SKILL_SWORDPERCENT: { + skillsPercent[SKILL_SWORD] = value; + return true; + } + + case CONDITION_PARAM_SKILL_AXE: { + skills[SKILL_AXE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_AXEPERCENT: { + skillsPercent[SKILL_AXE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_DISTANCE: { + skills[SKILL_DISTANCE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_DISTANCEPERCENT: { + skillsPercent[SKILL_DISTANCE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_SHIELD: { + skills[SKILL_SHIELD] = value; + return true; + } + + case CONDITION_PARAM_SKILL_SHIELDPERCENT: { + skillsPercent[SKILL_SHIELD] = value; + return true; + } + + case CONDITION_PARAM_SKILL_FISHING: { + skills[SKILL_FISHING] = value; + return true; + } + + case CONDITION_PARAM_SKILL_FISHINGPERCENT: { + skillsPercent[SKILL_FISHING] = value; + return true; + } + + case CONDITION_PARAM_SKILL_CRITICAL_HIT_CHANCE: { + skills[SKILL_CRITICAL_HIT_CHANCE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_CRITICAL_HIT_DAMAGE: { + skills[SKILL_CRITICAL_HIT_DAMAGE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_LIFE_LEECH_CHANCE: { + skills[SKILL_LIFE_LEECH_CHANCE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_LIFE_LEECH_AMOUNT: { + skills[SKILL_LIFE_LEECH_AMOUNT] = value; + return true; + } + + case CONDITION_PARAM_SKILL_MANA_LEECH_CHANCE: { + skills[SKILL_MANA_LEECH_CHANCE] = value; + return true; + } + + case CONDITION_PARAM_SKILL_MANA_LEECH_AMOUNT: { + skills[SKILL_MANA_LEECH_AMOUNT] = value; + return true; + } + + case CONDITION_PARAM_STAT_MAXHITPOINTS: { + stats[STAT_MAXHITPOINTS] = value; + return true; + } + + case CONDITION_PARAM_STAT_MAXMANAPOINTS: { + stats[STAT_MAXMANAPOINTS] = value; + return true; + } + + case CONDITION_PARAM_STAT_MAGICPOINTS: { + stats[STAT_MAGICPOINTS] = value; + return true; + } + + case CONDITION_PARAM_STAT_MAXHITPOINTSPERCENT: { + statsPercent[STAT_MAXHITPOINTS] = std::max(0, value); + return true; + } + + case CONDITION_PARAM_STAT_MAXMANAPOINTSPERCENT: { + statsPercent[STAT_MAXMANAPOINTS] = std::max(0, value); + return true; + } + + case CONDITION_PARAM_STAT_MAGICPOINTSPERCENT: { + statsPercent[STAT_MAGICPOINTS] = std::max(0, value); + return true; + } + + case CONDITION_PARAM_DISABLE_DEFENSE: { + disableDefense = (value != 0); + return true; + } + + case CONDITION_PARAM_STAT_CAPACITYPERCENT: { + statsPercent[STAT_CAPACITY] = std::max(0, value); + return true; + } + + case CONDITION_PARAM_BUFF_DAMAGEDEALT: { + buffsPercent[BUFF_DAMAGEDEALT] = std::max(0, value); + return true; + } + + case CONDITION_PARAM_BUFF_DAMAGERECEIVED: { + buffsPercent[BUFF_DAMAGERECEIVED] = std::max(0, value); + return true; + } + + default: + return ret; + } +} + +bool ConditionRegeneration::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } @@ -744,19 +711,17 @@ bool ConditionRegeneration::startCondition(Creature* creature) return true; } -void ConditionRegeneration::endCondition(Creature* creature) -{ +void ConditionRegeneration::endCondition(Creature* creature) { if (Player* player = creature->getPlayer()) { player->sendStats(); } } -void ConditionRegeneration::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionRegeneration::addCondition(Creature* creature, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); - const ConditionRegeneration& conditionRegen = static_cast(*addCondition); + const ConditionRegeneration &conditionRegen = static_cast(*addCondition); healthTicks = conditionRegen.healthTicks; manaTicks = conditionRegen.manaTicks; @@ -770,8 +735,7 @@ void ConditionRegeneration::addCondition(Creature* creature, const Condition* ad } } -bool ConditionRegeneration::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool ConditionRegeneration::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { if (attr == CONDITIONATTR_HEALTHTICKS) { return propStream.read(healthTicks); } else if (attr == CONDITIONATTR_HEALTHGAIN) { @@ -784,8 +748,7 @@ bool ConditionRegeneration::unserializeProp(ConditionAttr_t attr, PropStream& pr return Condition::unserializeProp(attr, propStream); } -void ConditionRegeneration::serialize(PropWriteStream& propWriteStream) -{ +void ConditionRegeneration::serialize(PropWriteStream &propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write(CONDITIONATTR_HEALTHTICKS); @@ -801,8 +764,7 @@ void ConditionRegeneration::serialize(PropWriteStream& propWriteStream) propWriteStream.write(manaGain); } -bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interval) { internalHealthTicks += interval; internalManaTicks += interval; Player* player = creature->getPlayer(); @@ -845,7 +807,6 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva } } } - } if (creature->getZone() != ZONE_PROTECTION || PlayerdailyStreak >= DAILY_REWARD_MP_REGENERATION) { @@ -862,8 +823,7 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva return ConditionGeneric::executeCondition(creature, interval); } -bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) -{ +bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) { bool ret = ConditionGeneric::setParam(param, value); switch (param) { @@ -888,8 +848,7 @@ bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) } } -uint32_t ConditionRegeneration::getHealthTicks(Creature* creature) const -{ +uint32_t ConditionRegeneration::getHealthTicks(Creature* creature) const { const Player* player = creature->getPlayer(); if (player != nullptr && isBuff) { @@ -899,8 +858,7 @@ uint32_t ConditionRegeneration::getHealthTicks(Creature* creature) const return healthTicks; } -uint32_t ConditionRegeneration::getManaTicks(Creature* creature) const -{ +uint32_t ConditionRegeneration::getManaTicks(Creature* creature) const { const Player* player = creature->getPlayer(); if (player != nullptr && isBuff) { @@ -910,34 +868,31 @@ uint32_t ConditionRegeneration::getManaTicks(Creature* creature) const return manaTicks; } -bool ConditionManaShield::startCondition(Creature* creature) -{ - if (!Condition::startCondition(creature)) { - return false; - } - creature->setManaShield(manaShield); - creature->setMaxManaShield(manaShield); - if (Player* player = creature->getPlayer()) { - player->sendStats(); - } - return true; +bool ConditionManaShield::startCondition(Creature* creature) { + if (!Condition::startCondition(creature)) { + return false; + } + creature->setManaShield(manaShield); + creature->setMaxManaShield(manaShield); + if (Player* player = creature->getPlayer()) { + player->sendStats(); + } + return true; } -void ConditionManaShield::endCondition(Creature* creature) -{ - creature->setManaShield(0); - creature->setMaxManaShield(0); - if (Player* player = creature->getPlayer()) { - player->sendStats(); - } +void ConditionManaShield::endCondition(Creature* creature) { + creature->setManaShield(0); + creature->setMaxManaShield(0); + if (Player* player = creature->getPlayer()) { + player->sendStats(); + } } -void ConditionManaShield::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionManaShield::addCondition(Creature* creature, const Condition* addCondition) { endCondition(creature); setTicks(addCondition->getTicks()); - const ConditionManaShield& conditionManaShield = static_cast(*addCondition); + const ConditionManaShield &conditionManaShield = static_cast(*addCondition); manaShield = conditionManaShield.manaShield; creature->setManaShield(manaShield); @@ -948,59 +903,53 @@ void ConditionManaShield::addCondition(Creature* creature, const Condition* addC } } -bool ConditionManaShield::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ - if (attr == CONDITIONATTR_MANASHIELD) { - return propStream.read(manaShield); - } - return Condition::unserializeProp(attr, propStream); +bool ConditionManaShield::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { + if (attr == CONDITIONATTR_MANASHIELD) { + return propStream.read(manaShield); + } + return Condition::unserializeProp(attr, propStream); } -void ConditionManaShield::serialize(PropWriteStream& propWriteStream) -{ - Condition::serialize(propWriteStream); +void ConditionManaShield::serialize(PropWriteStream &propWriteStream) { + Condition::serialize(propWriteStream); - propWriteStream.write(CONDITIONATTR_MANASHIELD); - propWriteStream.write(manaShield); + propWriteStream.write(CONDITIONATTR_MANASHIELD); + propWriteStream.write(manaShield); } -bool ConditionManaShield::setParam(ConditionParam_t param, int32_t value) -{ - bool ret = Condition::setParam(param, value); +bool ConditionManaShield::setParam(ConditionParam_t param, int32_t value) { + bool ret = Condition::setParam(param, value); - switch (param) { - case CONDITION_PARAM_MANASHIELD: - manaShield = value; - return true; - default: - return ret; - } + switch (param) { + case CONDITION_PARAM_MANASHIELD: + manaShield = value; + return true; + default: + return ret; + } } -uint32_t ConditionManaShield::getIcons() const -{ +uint32_t ConditionManaShield::getIcons() const { uint32_t icons = Condition::getIcons(); - if(manaShield != 0) + if (manaShield != 0) icons |= ICON_NEWMANASHIELD; else icons |= ICON_MANASHIELD; return icons; } -void ConditionSoul::addCondition(Creature*, const Condition* addCondition) -{ +void ConditionSoul::addCondition(Creature*, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); - const ConditionSoul& conditionSoul = static_cast(*addCondition); + const ConditionSoul &conditionSoul = static_cast(*addCondition); soulTicks = conditionSoul.soulTicks; soulGain = conditionSoul.soulGain; } } -bool ConditionSoul::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool ConditionSoul::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { if (attr == CONDITIONATTR_SOULGAIN) { return propStream.read(soulGain); } else if (attr == CONDITIONATTR_SOULTICKS) { @@ -1009,8 +958,7 @@ bool ConditionSoul::unserializeProp(ConditionAttr_t attr, PropStream& propStream return Condition::unserializeProp(attr, propStream); } -void ConditionSoul::serialize(PropWriteStream& propWriteStream) -{ +void ConditionSoul::serialize(PropWriteStream &propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write(CONDITIONATTR_SOULGAIN); @@ -1020,8 +968,7 @@ void ConditionSoul::serialize(PropWriteStream& propWriteStream) propWriteStream.write(soulTicks); } -bool ConditionSoul::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionSoul::executeCondition(Creature* creature, int32_t interval) { internalSoulTicks += interval; if (Player* player = creature->getPlayer()) { @@ -1036,8 +983,7 @@ bool ConditionSoul::executeCondition(Creature* creature, int32_t interval) return ConditionGeneric::executeCondition(creature, interval); } -bool ConditionSoul::setParam(ConditionParam_t param, int32_t value) -{ +bool ConditionSoul::setParam(ConditionParam_t param, int32_t value) { bool ret = ConditionGeneric::setParam(param, value); switch (param) { case CONDITION_PARAM_SOULGAIN: @@ -1053,8 +999,7 @@ bool ConditionSoul::setParam(ConditionParam_t param, int32_t value) } } -bool ConditionDamage::setParam(ConditionParam_t param, int32_t value) -{ +bool ConditionDamage::setParam(ConditionParam_t param, int32_t value) { bool ret = Condition::setParam(param, value); switch (param) { @@ -1101,8 +1046,7 @@ bool ConditionDamage::setParam(ConditionParam_t param, int32_t value) return ret; } -bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { if (attr == CONDITIONATTR_DELAYED) { uint8_t value; if (!propStream.read(value)) { @@ -1130,8 +1074,7 @@ bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream& propStre return Condition::unserializeProp(attr, propStream); } -void ConditionDamage::serialize(PropWriteStream& propWriteStream) -{ +void ConditionDamage::serialize(PropWriteStream &propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write(CONDITIONATTR_DELAYED); @@ -1140,15 +1083,14 @@ void ConditionDamage::serialize(PropWriteStream& propWriteStream) propWriteStream.write(CONDITIONATTR_PERIODDAMAGE); propWriteStream.write(periodDamage); - for (const IntervalInfo& intervalInfo : damageList) { + for (const IntervalInfo &intervalInfo : damageList) { propWriteStream.write(CONDITIONATTR_INTERVALDATA); propWriteStream.write(intervalInfo); } } -bool ConditionDamage::updateCondition(const Condition* addCondition) -{ - const ConditionDamage& conditionDamage = static_cast(*addCondition); +bool ConditionDamage::updateCondition(const Condition* addCondition) { + const ConditionDamage &conditionDamage = static_cast(*addCondition); if (conditionDamage.doForceUpdate()) { return true; } @@ -1160,11 +1102,10 @@ bool ConditionDamage::updateCondition(const Condition* addCondition) return conditionDamage.getTotalDamage() > getTotalDamage(); } -bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) -{ +bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) { time = std::max(time, EVENT_CREATURE_THINK_INTERVAL); if (rounds == -1) { - //periodic damage + // periodic damage periodDamage = value; setParam(CONDITION_PARAM_TICKINTERVAL, time); setParam(CONDITION_PARAM_TICKS, -1); @@ -1175,7 +1116,7 @@ bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) return false; } - //rounds, time, damage + // rounds, time, damage for (int32_t i = 0; i < rounds; ++i) { IntervalInfo damageInfo; damageInfo.interval = time; @@ -1192,8 +1133,7 @@ bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) return true; } -bool ConditionDamage::init() -{ +bool ConditionDamage::init() { if (periodDamage != 0) { return true; } @@ -1219,8 +1159,7 @@ bool ConditionDamage::init() return !damageList.empty(); } -bool ConditionDamage::startCondition(Creature* creature) -{ +bool ConditionDamage::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } @@ -1238,8 +1177,7 @@ bool ConditionDamage::startCondition(Creature* creature) return true; } -bool ConditionDamage::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionDamage::executeCondition(Creature* creature, int32_t interval) { if (periodDamage != 0) { periodDamageTick += interval; @@ -1248,7 +1186,7 @@ bool ConditionDamage::executeCondition(Creature* creature, int32_t interval) doDamage(creature, periodDamage); } } else if (!damageList.empty()) { - IntervalInfo& damageInfo = damageList.front(); + IntervalInfo &damageInfo = damageList.front(); bool bRemove = (ticks != -1); creature->onTickCondition(getType(), bRemove); @@ -1278,13 +1216,12 @@ bool ConditionDamage::executeCondition(Creature* creature, int32_t interval) return Condition::executeCondition(creature, interval); } -bool ConditionDamage::getNextDamage(int32_t& damage) -{ +bool ConditionDamage::getNextDamage(int32_t &damage) { if (periodDamage != 0) { damage = periodDamage; return true; } else if (!damageList.empty()) { - IntervalInfo& damageInfo = damageList.front(); + IntervalInfo &damageInfo = damageList.front(); damage = damageInfo.value; if (ticks != -1) { damageList.pop_front(); @@ -1294,8 +1231,7 @@ bool ConditionDamage::getNextDamage(int32_t& damage) return false; } -bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) -{ +bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) { if (creature->isSuppress(getType())) { return true; } @@ -1323,13 +1259,11 @@ bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) return g_game().combatChangeHealth(attacker, creature, damage); } -void ConditionDamage::endCondition(Creature*) -{ +void ConditionDamage::endCondition(Creature*) { // } -void ConditionDamage::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionDamage::addCondition(Creature* creature, const Condition* addCondition) { if (addCondition->getType() != conditionType) { return; } @@ -1338,7 +1272,7 @@ void ConditionDamage::addCondition(Creature* creature, const Condition* addCondi return; } - const ConditionDamage& conditionDamage = static_cast(*addCondition); + const ConditionDamage &conditionDamage = static_cast(*addCondition); setTicks(addCondition->getTicks()); owner = conditionDamage.owner; @@ -1350,8 +1284,8 @@ void ConditionDamage::addCondition(Creature* creature, const Condition* addCondi int32_t nextTimeLeft = tickInterval; if (!damageList.empty()) { - //save previous timeLeft - IntervalInfo& damageInfo = damageList.front(); + // save previous timeLeft + IntervalInfo &damageInfo = damageList.front(); nextTimeLeft = damageInfo.timeLeft; damageList.clear(); } @@ -1360,8 +1294,8 @@ void ConditionDamage::addCondition(Creature* creature, const Condition* addCondi if (init()) { if (!damageList.empty()) { - //restore last timeLeft - IntervalInfo& damageInfo = damageList.front(); + // restore last timeLeft + IntervalInfo &damageInfo = damageList.front(); damageInfo.timeLeft = nextTimeLeft; } @@ -1374,12 +1308,11 @@ void ConditionDamage::addCondition(Creature* creature, const Condition* addCondi } } -int32_t ConditionDamage::getTotalDamage() const -{ +int32_t ConditionDamage::getTotalDamage() const { int32_t result; if (!damageList.empty()) { result = 0; - for (const IntervalInfo& intervalInfo : damageList) { + for (const IntervalInfo &intervalInfo : damageList) { result += intervalInfo.value; } } else { @@ -1388,8 +1321,7 @@ int32_t ConditionDamage::getTotalDamage() const return std::abs(result); } -uint32_t ConditionDamage::getIcons() const -{ +uint32_t ConditionDamage::getIcons() const { uint32_t icons = Condition::getIcons(); switch (conditionType) { case CONDITION_FIRE: @@ -1430,8 +1362,7 @@ uint32_t ConditionDamage::getIcons() const return icons; } -void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::list& list) -{ +void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::list &list) { amount = std::abs(amount); int32_t sum = 0; double x1, x2; @@ -1450,22 +1381,19 @@ void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::lis } } -void ConditionSpeed::setFormulaVars(float NewMina, float NewMinb, float NewMaxa, float NewMaxb) -{ +void ConditionSpeed::setFormulaVars(float NewMina, float NewMinb, float NewMaxa, float NewMaxb) { this->mina = NewMina; this->minb = NewMinb; this->maxa = NewMaxa; this->maxb = NewMaxb; } -void ConditionSpeed::getFormulaValues(int32_t var, int32_t& min, int32_t& max) const -{ +void ConditionSpeed::getFormulaValues(int32_t var, int32_t &min, int32_t &max) const { min = (var * mina) + minb; max = (var * maxa) + maxb; } -bool ConditionSpeed::setParam(ConditionParam_t param, int32_t value) -{ +bool ConditionSpeed::setParam(ConditionParam_t param, int32_t value) { Condition::setParam(param, value); if (param != CONDITION_PARAM_SPEED) { return false; @@ -1481,8 +1409,7 @@ bool ConditionSpeed::setParam(ConditionParam_t param, int32_t value) return true; } -bool ConditionSpeed::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool ConditionSpeed::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { if (attr == CONDITIONATTR_SPEEDDELTA) { return propStream.read(speedDelta); } else if (attr == CONDITIONATTR_FORMULA_MINA) { @@ -1497,8 +1424,7 @@ bool ConditionSpeed::unserializeProp(ConditionAttr_t attr, PropStream& propStrea return Condition::unserializeProp(attr, propStream); } -void ConditionSpeed::serialize(PropWriteStream& propWriteStream) -{ +void ConditionSpeed::serialize(PropWriteStream &propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write(CONDITIONATTR_SPEEDDELTA); @@ -1517,8 +1443,7 @@ void ConditionSpeed::serialize(PropWriteStream& propWriteStream) propWriteStream.write(maxb); } -bool ConditionSpeed::startCondition(Creature* creature) -{ +bool ConditionSpeed::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } @@ -1533,18 +1458,15 @@ bool ConditionSpeed::startCondition(Creature* creature) return true; } -bool ConditionSpeed::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionSpeed::executeCondition(Creature* creature, int32_t interval) { return Condition::executeCondition(creature, interval); } -void ConditionSpeed::endCondition(Creature* creature) -{ +void ConditionSpeed::endCondition(Creature* creature) { g_game().changeSpeed(creature, -speedDelta); } -void ConditionSpeed::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionSpeed::addCondition(Creature* creature, const Condition* addCondition) { if (conditionType != addCondition->getType()) { return; } @@ -1555,7 +1477,7 @@ void ConditionSpeed::addCondition(Creature* creature, const Condition* addCondit setTicks(addCondition->getTicks()); - const ConditionSpeed& conditionSpeed = static_cast(*addCondition); + const ConditionSpeed &conditionSpeed = static_cast(*addCondition); int32_t oldSpeedDelta = speedDelta; speedDelta = conditionSpeed.speedDelta; mina = conditionSpeed.mina; @@ -1576,8 +1498,7 @@ void ConditionSpeed::addCondition(Creature* creature, const Condition* addCondit } } -uint32_t ConditionSpeed::getIcons() const -{ +uint32_t ConditionSpeed::getIcons() const { uint32_t icons = Condition::getIcons(); switch (conditionType) { case CONDITION_HASTE: @@ -1594,8 +1515,7 @@ uint32_t ConditionSpeed::getIcons() const return icons; } -bool ConditionInvisible::startCondition(Creature* creature) -{ +bool ConditionInvisible::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } @@ -1604,8 +1524,7 @@ bool ConditionInvisible::startCondition(Creature* creature) return true; } -void ConditionInvisible::endCondition(Creature* creature) -{ +void ConditionInvisible::endCondition(Creature* creature) { if (!creature->isInvisible()) { g_game().internalCreatureChangeVisible(creature, true); } @@ -1615,33 +1534,29 @@ void ConditionInvisible::endCondition(Creature* creature) * ConditionOutfit */ -void ConditionOutfit::setOutfit(const Outfit_t& newOutfit) -{ +void ConditionOutfit::setOutfit(const Outfit_t &newOutfit) { this->outfit = newOutfit; } -void ConditionOutfit::setLazyMonsterOutfit(const std::string& monsterName) { +void ConditionOutfit::setLazyMonsterOutfit(const std::string &monsterName) { this->monsterName = monsterName; } -bool ConditionOutfit::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool ConditionOutfit::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { if (attr == CONDITIONATTR_OUTFIT) { return propStream.read(outfit); } return Condition::unserializeProp(attr, propStream); } -void ConditionOutfit::serialize(PropWriteStream& propWriteStream) -{ +void ConditionOutfit::serialize(PropWriteStream &propWriteStream) { Condition::serialize(propWriteStream); propWriteStream.write(CONDITIONATTR_OUTFIT); propWriteStream.write(outfit); } -bool ConditionOutfit::startCondition(Creature* creature) -{ +bool ConditionOutfit::startCondition(Creature* creature) { if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { SPDLOG_WARN("[ConditionOutfit::startCondition] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); return false; @@ -1665,18 +1580,15 @@ bool ConditionOutfit::startCondition(Creature* creature) return true; } -bool ConditionOutfit::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionOutfit::executeCondition(Creature* creature, int32_t interval) { return Condition::executeCondition(creature, interval); } -void ConditionOutfit::endCondition(Creature* creature) -{ +void ConditionOutfit::endCondition(Creature* creature) { g_game().internalCreatureChangeOutfit(creature, creature->getDefaultOutfit()); } -void ConditionOutfit::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionOutfit::addCondition(Creature* creature, const Condition* addCondition) { if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { SPDLOG_WARN("[ConditionOutfit::addCondition] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); return; @@ -1685,7 +1597,7 @@ void ConditionOutfit::addCondition(Creature* creature, const Condition* addCondi if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); - const ConditionOutfit& conditionOutfit = static_cast(*addCondition); + const ConditionOutfit &conditionOutfit = static_cast(*addCondition); if (!conditionOutfit.monsterName.empty() && conditionOutfit.monsterName.compare(monsterName) != 0) { const MonsterType* monsterType = g_monsters().getMonsterType(conditionOutfit.monsterName); if (monsterType) { @@ -1694,8 +1606,7 @@ void ConditionOutfit::addCondition(Creature* creature, const Condition* addCondi SPDLOG_ERROR("[ConditionOutfit::addCondition] - Monster {} does not exist", monsterName); return; } - } - else if (conditionOutfit.outfit.lookType != 0 || conditionOutfit.outfit.lookTypeEx != 0) { + } else if (conditionOutfit.outfit.lookType != 0 || conditionOutfit.outfit.lookTypeEx != 0) { setOutfit(conditionOutfit.outfit); } @@ -1707,8 +1618,7 @@ void ConditionOutfit::addCondition(Creature* creature, const Condition* addCondi * ConditionLight */ -bool ConditionLight::startCondition(Creature* creature) -{ +bool ConditionLight::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } @@ -1720,8 +1630,7 @@ bool ConditionLight::startCondition(Creature* creature) return true; } -bool ConditionLight::executeCondition(Creature* creature, int32_t interval) -{ +bool ConditionLight::executeCondition(Creature* creature, int32_t interval) { internalLightTicks += interval; if (internalLightTicks >= lightChangeInterval) { @@ -1738,18 +1647,16 @@ bool ConditionLight::executeCondition(Creature* creature, int32_t interval) return Condition::executeCondition(creature, interval); } -void ConditionLight::endCondition(Creature* creature) -{ +void ConditionLight::endCondition(Creature* creature) { creature->setNormalCreatureLight(); g_game().changeLight(creature); } -void ConditionLight::addCondition(Creature* creature, const Condition* condition) -{ +void ConditionLight::addCondition(Creature* creature, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); - const ConditionLight& conditionLight = static_cast(*condition); + const ConditionLight &conditionLight = static_cast(*condition); lightInfo.level = conditionLight.lightInfo.level; lightInfo.color = conditionLight.lightInfo.color; lightChangeInterval = ticks / lightInfo.level; @@ -1759,8 +1666,7 @@ void ConditionLight::addCondition(Creature* creature, const Condition* condition } } -bool ConditionLight::setParam(ConditionParam_t param, int32_t value) -{ +bool ConditionLight::setParam(ConditionParam_t param, int32_t value) { bool ret = Condition::setParam(param, value); if (ret) { return false; @@ -1780,8 +1686,7 @@ bool ConditionLight::setParam(ConditionParam_t param, int32_t value) } } -bool ConditionLight::unserializeProp(ConditionAttr_t attr, PropStream& propStream) -{ +bool ConditionLight::unserializeProp(ConditionAttr_t attr, PropStream &propStream) { if (attr == CONDITIONATTR_LIGHTCOLOR) { uint32_t value; if (!propStream.read(value)) { @@ -1806,8 +1711,7 @@ bool ConditionLight::unserializeProp(ConditionAttr_t attr, PropStream& propStrea return Condition::unserializeProp(attr, propStream); } -void ConditionLight::serialize(PropWriteStream& propWriteStream) -{ +void ConditionLight::serialize(PropWriteStream &propWriteStream) { Condition::serialize(propWriteStream); // TODO: color and level could be serialized as 8-bit if we can retain backwards @@ -1826,8 +1730,7 @@ void ConditionLight::serialize(PropWriteStream& propWriteStream) propWriteStream.write(lightChangeInterval); } -void ConditionSpellCooldown::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionSpellCooldown::addCondition(Creature* creature, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); @@ -1840,8 +1743,7 @@ void ConditionSpellCooldown::addCondition(Creature* creature, const Condition* a } } -bool ConditionSpellCooldown::startCondition(Creature* creature) -{ +bool ConditionSpellCooldown::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } @@ -1855,8 +1757,7 @@ bool ConditionSpellCooldown::startCondition(Creature* creature) return true; } -void ConditionSpellGroupCooldown::addCondition(Creature* creature, const Condition* addCondition) -{ +void ConditionSpellGroupCooldown::addCondition(Creature* creature, const Condition* addCondition) { if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); @@ -1869,8 +1770,7 @@ void ConditionSpellGroupCooldown::addCondition(Creature* creature, const Conditi } } -bool ConditionSpellGroupCooldown::startCondition(Creature* creature) -{ +bool ConditionSpellGroupCooldown::startCondition(Creature* creature) { if (!Condition::startCondition(creature)) { return false; } diff --git a/src/creatures/combat/condition.h b/src/creatures/combat/condition.h index e2ebe4a6753..0037bdbac87 100644 --- a/src/creatures/combat/condition.h +++ b/src/creatures/combat/condition.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_COMBAT_CONDITION_H_ #define SRC_CREATURES_COMBAT_CONDITION_H_ @@ -17,13 +17,12 @@ class Creature; class Player; class PropStream; -class Condition -{ +class Condition { public: Condition() = default; Condition(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : endTime(initTicks == -1 ? std::numeric_limits::max() : 0), - subId(initSubId), ticks(initTicks), conditionType(initType), id(initId), isBuff(initBuff) {} + subId(initSubId), ticks(initTicks), conditionType(initType), id(initId), isBuff(initBuff) { } virtual ~Condition() = default; virtual bool startCondition(Creature* creature); @@ -52,14 +51,14 @@ class Condition void setTicks(int32_t newTicks); static Condition* createCondition(ConditionId_t id, ConditionType_t type, int32_t ticks, int32_t param = 0, bool buff = false, uint32_t subId = 0); - static Condition* createCondition(PropStream& propStream); + static Condition* createCondition(PropStream &propStream); virtual bool setParam(ConditionParam_t param, int32_t value); - //serialization - bool unserialize(PropStream& propStream); - virtual void serialize(PropWriteStream& propWriteStream); - virtual bool unserializeProp(ConditionAttr_t attr, PropStream& propStream); + // serialization + bool unserialize(PropStream &propStream); + virtual void serialize(PropWriteStream &propWriteStream); + virtual bool unserializeProp(ConditionAttr_t attr, PropStream &propStream); bool isPersistent() const; @@ -74,11 +73,10 @@ class Condition virtual bool updateCondition(const Condition* addCondition); }; -class ConditionGeneric : public Condition -{ +class ConditionGeneric : public Condition { public: - ConditionGeneric(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0): - Condition(initId, initType, initTicks, initBuff, initSubId) {} + ConditionGeneric(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : + Condition(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) override; bool executeCondition(Creature* creature, int32_t interval) override; @@ -91,11 +89,10 @@ class ConditionGeneric : public Condition } }; -class ConditionAttributes final : public ConditionGeneric -{ +class ConditionAttributes final : public ConditionGeneric { public: ConditionAttributes(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : - ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) {} + ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) final; bool executeCondition(Creature* creature, int32_t interval) final; @@ -108,20 +105,20 @@ class ConditionAttributes final : public ConditionGeneric return new ConditionAttributes(*this); } - //serialization - void serialize(PropWriteStream& propWriteStream) final; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) final; + // serialization + void serialize(PropWriteStream &propWriteStream) final; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) final; private: int32_t skills[SKILL_LAST + 1] = {}; int32_t skillsPercent[SKILL_LAST + 1] = {}; int32_t stats[STAT_LAST + 1] = {}; int32_t statsPercent[STAT_LAST + 1] = {}; - int32_t buffsPercent[BUFF_LAST + 1] = {}; - int32_t buffs[BUFF_LAST + 1] = {}; + int32_t buffsPercent[BUFF_LAST + 1] = {}; + int32_t buffs[BUFF_LAST + 1] = {}; int32_t currentSkill = 0; int32_t currentStat = 0; - int32_t currentBuff = 0; + int32_t currentBuff = 0; bool disableDefense = false; @@ -129,15 +126,14 @@ class ConditionAttributes final : public ConditionGeneric void updateStats(Player* player); void updatePercentSkills(Player* player); void updateSkills(Player* player); - void updatePercentBuffs(Creature* creature); - void updateBuffs(Creature* creature); + void updatePercentBuffs(Creature* creature); + void updateBuffs(Creature* creature); }; -class ConditionRegeneration final : public ConditionGeneric -{ +class ConditionRegeneration final : public ConditionGeneric { public: - ConditionRegeneration(ConditionId_t initId, ConditionType_t initType, int32_t iniTicks, bool initBuff = false, uint32_t initSubId = 0): - ConditionGeneric(initId, initType, iniTicks, initBuff, initSubId) {} + ConditionRegeneration(ConditionId_t initId, ConditionType_t initType, int32_t iniTicks, bool initBuff = false, uint32_t initSubId = 0) : + ConditionGeneric(initId, initType, iniTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) override; void endCondition(Creature* creature) override; @@ -153,9 +149,9 @@ class ConditionRegeneration final : public ConditionGeneric return new ConditionRegeneration(*this); } - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: uint32_t internalHealthTicks = 0; @@ -167,36 +163,34 @@ class ConditionRegeneration final : public ConditionGeneric uint32_t manaGain = 0; }; -class ConditionManaShield final : public Condition -{ -public: - ConditionManaShield(ConditionId_t initId, ConditionType_t initType, int32_t iniTicks, bool initBuff = false, uint32_t initSubId = 0) : - Condition(initId, initType, iniTicks, initBuff, initSubId) {} +class ConditionManaShield final : public Condition { + public: + ConditionManaShield(ConditionId_t initId, ConditionType_t initType, int32_t iniTicks, bool initBuff = false, uint32_t initSubId = 0) : + Condition(initId, initType, iniTicks, initBuff, initSubId) { } - bool startCondition(Creature* creature) override; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* addCondition) override; - uint32_t getIcons() const override; + bool startCondition(Creature* creature) override; + void endCondition(Creature* creature) override; + void addCondition(Creature* creature, const Condition* addCondition) override; + uint32_t getIcons() const override; - bool setParam(ConditionParam_t param, int32_t value) override; + bool setParam(ConditionParam_t param, int32_t value) override; - ConditionManaShield* clone() const override { - return new ConditionManaShield(*this); - } + ConditionManaShield* clone() const override { + return new ConditionManaShield(*this); + } - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; -private: - uint16_t manaShield = 0; + private: + uint16_t manaShield = 0; }; -class ConditionSoul final : public ConditionGeneric -{ +class ConditionSoul final : public ConditionGeneric { public: ConditionSoul(ConditionId_t initId, ConditionType_t initType, int32_t iniTicks, bool initBuff = false, uint32_t initSubId = 0) : - ConditionGeneric(initId, initType, iniTicks, initBuff, initSubId) {} + ConditionGeneric(initId, initType, iniTicks, initBuff, initSubId) { } void addCondition(Creature* creature, const Condition* addCondition) override; bool executeCondition(Creature* creature, int32_t interval) override; @@ -207,9 +201,9 @@ class ConditionSoul final : public ConditionGeneric return new ConditionSoul(*this); } - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: uint32_t internalSoulTicks = 0; @@ -217,11 +211,10 @@ class ConditionSoul final : public ConditionGeneric uint32_t soulGain = 0; }; -class ConditionInvisible final : public ConditionGeneric -{ +class ConditionInvisible final : public ConditionGeneric { public: ConditionInvisible(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : - ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) {} + ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) override; void endCondition(Creature* creature) override; @@ -231,14 +224,13 @@ class ConditionInvisible final : public ConditionGeneric } }; -class ConditionDamage final : public Condition -{ +class ConditionDamage final : public Condition { public: ConditionDamage() = default; ConditionDamage(ConditionId_t intiId, ConditionType_t initType, bool initBuff = false, uint32_t initSubId = 0) : - Condition(intiId, initType, 0, initBuff, initSubId) {} + Condition(intiId, initType, 0, initBuff, initSubId) { } - static void generateDamageList(int32_t amount, int32_t start, std::list& list); + static void generateDamageList(int32_t amount, int32_t start, std::list &list); bool startCondition(Creature* creature) override; bool executeCondition(Creature* creature, int32_t interval) override; @@ -258,9 +250,9 @@ class ConditionDamage final : public Condition } int32_t getTotalDamage() const; - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: int32_t maxDamage = 0; @@ -279,17 +271,16 @@ class ConditionDamage final : public Condition std::list damageList; - bool getNextDamage(int32_t& damage); + bool getNextDamage(int32_t &damage); bool doDamage(Creature* creature, int32_t healthChange); bool updateCondition(const Condition* addCondition) override; }; -class ConditionSpeed final : public Condition -{ +class ConditionSpeed final : public Condition { public: ConditionSpeed(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff, uint32_t initSubId, int32_t initChangeSpeed) : - Condition(initId, initType, initTicks, initBuff, initSubId), speedDelta(initChangeSpeed) {} + Condition(initId, initType, initTicks, initBuff, initSubId), speedDelta(initChangeSpeed) { } bool startCondition(Creature* creature) override; bool executeCondition(Creature* creature, int32_t interval) override; @@ -305,27 +296,26 @@ class ConditionSpeed final : public Condition void setFormulaVars(float mina, float minb, float maxa, float maxb); - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: - void getFormulaValues(int32_t var, int32_t& min, int32_t& max) const; + void getFormulaValues(int32_t var, int32_t &min, int32_t &max) const; int32_t speedDelta; - //formula variables + // formula variables float mina = 0.0f; float minb = 0.0f; float maxa = 0.0f; float maxb = 0.0f; }; -class ConditionOutfit final : public Condition -{ +class ConditionOutfit final : public Condition { public: ConditionOutfit(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : - Condition(initId, initType, initTicks, initBuff, initSubId) {} + Condition(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) override; bool executeCondition(Creature* creature, int32_t interval) override; @@ -336,23 +326,22 @@ class ConditionOutfit final : public Condition return new ConditionOutfit(*this); } - void setOutfit(const Outfit_t& outfit); - void setLazyMonsterOutfit(const std::string& monsterName); + void setOutfit(const Outfit_t &outfit); + void setLazyMonsterOutfit(const std::string &monsterName); - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: Outfit_t outfit; std::string monsterName; }; -class ConditionLight final : public Condition -{ +class ConditionLight final : public Condition { public: ConditionLight(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff, uint32_t initSubId, uint8_t initLightlevel, uint8_t initLightcolor) : - Condition(initId, initType, initTicks, initBuff, initSubId), lightInfo(initLightlevel, initLightcolor) {} + Condition(initId, initType, initTicks, initBuff, initSubId), lightInfo(initLightlevel, initLightcolor) { } bool startCondition(Creature* creature) override; bool executeCondition(Creature* creature, int32_t interval) override; @@ -365,9 +354,9 @@ class ConditionLight final : public Condition bool setParam(ConditionParam_t param, int32_t value) override; - //serialization - void serialize(PropWriteStream& propWriteStream) override; - bool unserializeProp(ConditionAttr_t attr, PropStream& propStream) override; + // serialization + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: LightInfo lightInfo; @@ -375,11 +364,10 @@ class ConditionLight final : public Condition uint32_t lightChangeInterval = 0; }; -class ConditionSpellCooldown final : public ConditionGeneric -{ +class ConditionSpellCooldown final : public ConditionGeneric { public: ConditionSpellCooldown(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : - ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) {} + ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) override; void addCondition(Creature* creature, const Condition* condition) override; @@ -389,11 +377,10 @@ class ConditionSpellCooldown final : public ConditionGeneric } }; -class ConditionSpellGroupCooldown final : public ConditionGeneric -{ +class ConditionSpellGroupCooldown final : public ConditionGeneric { public: ConditionSpellGroupCooldown(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : - ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) {} + ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(Creature* creature) override; void addCondition(Creature* creature, const Condition* condition) override; @@ -403,4 +390,4 @@ class ConditionSpellGroupCooldown final : public ConditionGeneric } }; -#endif // SRC_CREATURES_COMBAT_CONDITION_H_ +#endif // SRC_CREATURES_COMBAT_CONDITION_H_ diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index 83fd5aeef1e..ce2d803cd59 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,11 +18,10 @@ Spells::Spells() = default; Spells::~Spells() = default; -TalkActionResult_t Spells::playerSaySpell(Player* player, std::string& words) -{ +TalkActionResult_t Spells::playerSaySpell(Player* player, std::string &words) { std::string str_words = words; - //strip trailing spaces + // strip trailing spaces trimString(str_words); InstantSpell* instantSpell = getInstantSpell(str_words); @@ -72,38 +71,35 @@ TalkActionResult_t Spells::playerSaySpell(Player* player, std::string& words) return TALKACTION_FAILED; } -void Spells::clear() -{ +void Spells::clear() { instants.clear(); runes.clear(); } -bool Spells::hasInstantSpell(const std::string& word) const -{ +bool Spells::hasInstantSpell(const std::string &word) const { if (auto iterate = instants.find(word); - iterate != instants.end()) - { + iterate != instants.end()) { return true; } return false; } -bool Spells::registerInstantLuaEvent(InstantSpell* event) -{ +bool Spells::registerInstantLuaEvent(InstantSpell* event) { InstantSpell_ptr instant { event }; if (instant) { // If the spell not have the "spell:words()" return a error message - const std::string& instantName = instant->getName(); + const std::string &instantName = instant->getName(); if (instant->getWordsMap().empty()) { SPDLOG_ERROR("[Spells::registerInstantLuaEvent] - Missing register words for spell with name {}", instantName); return false; } - const std::string& words = instant->getWords(); + const std::string &words = instant->getWords(); // Checks if there is any spell registered with the same name if (hasInstantSpell(words)) { SPDLOG_WARN("[Spells::registerInstantLuaEvent] - " - "Duplicate registered instant spell with words: {}, on spell with name: {}", words, instantName); + "Duplicate registered instant spell with words: {}, on spell with name: {}", + words, instantName); return false; } // Register spell word in the map @@ -113,8 +109,7 @@ bool Spells::registerInstantLuaEvent(InstantSpell* event) return false; } -bool Spells::registerRuneLuaEvent(RuneSpell* event) -{ +bool Spells::registerRuneLuaEvent(RuneSpell* event) { RuneSpell_ptr rune { event }; if (rune) { uint16_t id = rune->getRuneItemId(); @@ -133,19 +128,17 @@ bool Spells::registerRuneLuaEvent(RuneSpell* event) return false; } -std::list Spells::getSpellsByVocation(uint16_t vocationId) -{ +std::list Spells::getSpellsByVocation(uint16_t vocationId) { std::list spellsList; VocSpellMap vocSpells; std::map::const_iterator vocSpellsIt; - for (const auto& it : instants) { + for (const auto &it : instants) { vocSpells = it.second.getVocMap(); vocSpellsIt = vocSpells.find(vocationId); if (vocSpellsIt != vocSpells.end() - && vocSpellsIt->second) - { + && vocSpellsIt->second) { spellsList.push_back(it.second.getId()); } } @@ -153,8 +146,7 @@ std::list Spells::getSpellsByVocation(uint16_t vocationId) return spellsList; } -Spell* Spells::getSpellByName(const std::string& name) -{ +Spell* Spells::getSpellByName(const std::string &name) { Spell* spell = getRuneSpellByName(name); if (!spell) { spell = getInstantSpellByName(name); @@ -162,11 +154,10 @@ Spell* Spells::getSpellByName(const std::string& name) return spell; } -RuneSpell* Spells::getRuneSpell(uint32_t id) -{ +RuneSpell* Spells::getRuneSpell(uint32_t id) { auto it = runes.find(id); if (it == runes.end()) { - for (auto& rune : runes) { + for (auto &rune : runes) { if (rune.second.getId() == id) { return &rune.second; } @@ -176,9 +167,8 @@ RuneSpell* Spells::getRuneSpell(uint32_t id) return &it->second; } -RuneSpell* Spells::getRuneSpellByName(const std::string& name) -{ - for (auto& it : runes) { +RuneSpell* Spells::getRuneSpellByName(const std::string &name) { + for (auto &it : runes) { if (strcasecmp(it.second.getName().c_str(), name.c_str()) == 0) { return &it.second; } @@ -186,12 +176,11 @@ RuneSpell* Spells::getRuneSpellByName(const std::string& name) return nullptr; } -InstantSpell* Spells::getInstantSpell(const std::string& words) -{ +InstantSpell* Spells::getInstantSpell(const std::string &words) { InstantSpell* result = nullptr; - for (auto& it : instants) { - const std::string& instantSpellWords = it.second.getWords(); + for (auto &it : instants) { + const std::string &instantSpellWords = it.second.getWords(); size_t spellLen = instantSpellWords.length(); if (strncasecmp(instantSpellWords.c_str(), words.c_str(), spellLen) == 0) { if (!result || spellLen > result->getWords().length()) { @@ -204,7 +193,7 @@ InstantSpell* Spells::getInstantSpell(const std::string& words) } if (result) { - const std::string& resultWords = result->getWords(); + const std::string &resultWords = result->getWords(); if (words.length() > resultWords.length()) { if (!result->getHasParam()) { return nullptr; @@ -221,9 +210,8 @@ InstantSpell* Spells::getInstantSpell(const std::string& words) return nullptr; } -InstantSpell* Spells::getInstantSpellById(uint32_t spellId) -{ - for (auto& it : instants) { +InstantSpell* Spells::getInstantSpellById(uint32_t spellId) { + for (auto &it : instants) { if (it.second.getId() == spellId) { return &it.second; } @@ -231,9 +219,8 @@ InstantSpell* Spells::getInstantSpellById(uint32_t spellId) return nullptr; } -InstantSpell* Spells::getInstantSpellByName(const std::string& name) -{ - for (auto& it : instants) { +InstantSpell* Spells::getInstantSpellByName(const std::string &name) { + for (auto &it : instants) { if (strcasecmp(it.second.getName().c_str(), name.c_str()) == 0) { return &it.second; } @@ -241,8 +228,7 @@ InstantSpell* Spells::getInstantSpellByName(const std::string& name) return nullptr; } -Position Spells::getCasterPosition(Creature* creature, Direction dir) -{ +Position Spells::getCasterPosition(Creature* creature, Direction dir) { return getNextPosition(dir, creature->getPosition()); } @@ -250,19 +236,16 @@ CombatSpell::CombatSpell(Combat* newCombat, bool newNeedTarget, bool newNeedDire Script(&g_spells().getScriptInterface()), combat(newCombat), needDirection(newNeedDirection), - needTarget(newNeedTarget) -{ -// Empty + needTarget(newNeedTarget) { + // Empty } -bool CombatSpell::loadScriptCombat() -{ +bool CombatSpell::loadScriptCombat() { combat = g_luaEnvironment.getCombatObject(g_luaEnvironment.lastCombatId).get(); return combat != nullptr; } -bool CombatSpell::castSpell(Creature* creature) -{ +bool CombatSpell::castSpell(Creature* creature) { if (isLoadedCallback()) { LuaVariant var; var.type = VARIANT_POSITION; @@ -287,8 +270,7 @@ bool CombatSpell::castSpell(Creature* creature) return true; } -bool CombatSpell::castSpell(Creature* creature, Creature* target) -{ +bool CombatSpell::castSpell(Creature* creature, Creature* target) { if (isLoadedCallback()) { LuaVariant var; @@ -322,13 +304,12 @@ bool CombatSpell::castSpell(Creature* creature, Creature* target) return true; } -bool CombatSpell::executeCastSpell(Creature* creature, const LuaVariant& var) const -{ - //onCastSpell(creature, var) +bool CombatSpell::executeCastSpell(Creature* creature, const LuaVariant &var) const { + // onCastSpell(creature, var) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CombatSpell::executeCastSpell - Creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName()); return false; } @@ -347,8 +328,7 @@ bool CombatSpell::executeCastSpell(Creature* creature, const LuaVariant& var) co return getScriptInterface()->callFunction(2); } -bool Spell::playerSpellCheck(Player* player) const -{ +bool Spell::playerSpellCheck(Player* player) const { if (player->hasFlag(PlayerFlags_t::CannotUseSpells)) { return false; } @@ -447,13 +427,12 @@ bool Spell::playerSpellCheck(Player* player) const return true; } -bool Spell::playerInstantSpellCheck(Player* player, const Position& toPos) -{ +bool Spell::playerInstantSpellCheck(Player* player, const Position &toPos) { if (toPos.x == 0xFFFF) { return true; } - const Position& playerPos = player->getPosition(); + const Position &playerPos = player->getPosition(); if (playerPos.z > toPos.z) { player->sendCancelMessage(RETURNVALUE_FIRSTGOUPSTAIRS); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -492,8 +471,7 @@ bool Spell::playerInstantSpellCheck(Player* player, const Position& toPos) return true; } -bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) -{ +bool Spell::playerRuneSpellCheck(Player* player, const Position &toPos) { if (!playerSpellCheck(player)) { return false; } @@ -502,7 +480,7 @@ bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) return true; } - const Position& playerPos = player->getPosition(); + const Position &playerPos = player->getPosition(); if (playerPos.z > toPos.z) { player->sendCancelMessage(RETURNVALUE_FIRSTGOUPSTAIRS); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -561,8 +539,7 @@ bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) return true; } -void Spell::applyCooldownConditions(Player* player) const -{ +void Spell::applyCooldownConditions(Player* player) const { if (cooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, cooldown / g_configManager().getFloat(RATE_SPELL_COOLDOWN), 0, false, spellId); player->addCondition(condition); @@ -579,8 +556,7 @@ void Spell::applyCooldownConditions(Player* player) const } } -void Spell::postCastSpell(Player* player, bool finishedCast /*= true*/, bool payCost /*= true*/) const -{ +void Spell::postCastSpell(Player* player, bool finishedCast /*= true*/, bool payCost /*= true*/) const { if (finishedCast) { if (!player->hasFlag(PlayerFlags_t::HasNoExhaustion)) { applyCooldownConditions(player); @@ -596,8 +572,7 @@ void Spell::postCastSpell(Player* player, bool finishedCast /*= true*/, bool pay } } -void Spell::postCastSpell(Player* player, uint32_t manaCost, uint32_t soulCost) -{ +void Spell::postCastSpell(Player* player, uint32_t manaCost, uint32_t soulCost) { if (manaCost > 0) { player->addManaSpent(manaCost); player->changeMana(-static_cast(manaCost)); @@ -610,8 +585,7 @@ void Spell::postCastSpell(Player* player, uint32_t manaCost, uint32_t soulCost) } } -uint32_t Spell::getManaCost(const Player* player) const -{ +uint32_t Spell::getManaCost(const Player* player) const { if (mana != 0) { return mana; } @@ -625,8 +599,7 @@ uint32_t Spell::getManaCost(const Player* player) const return 0; } -bool InstantSpell::playerCastInstant(Player* player, std::string& param) -{ +bool InstantSpell::playerCastInstant(Player* player, std::string ¶m) { if (!playerSpellCheck(player)) { return false; } @@ -746,20 +719,16 @@ bool InstantSpell::playerCastInstant(Player* player, std::string& param) return result; } -bool InstantSpell::canThrowSpell(const Creature* creature, const Creature* target) const -{ - const Position& fromPos = creature->getPosition(); - const Position& toPos = target->getPosition(); - if (fromPos.z != toPos.z || - (range == -1 && !g_game().canThrowObjectTo(fromPos, toPos, checkLineOfSight)) || - (range != -1 && !g_game().canThrowObjectTo(fromPos, toPos, checkLineOfSight, range, range))) { +bool InstantSpell::canThrowSpell(const Creature* creature, const Creature* target) const { + const Position &fromPos = creature->getPosition(); + const Position &toPos = target->getPosition(); + if (fromPos.z != toPos.z || (range == -1 && !g_game().canThrowObjectTo(fromPos, toPos, checkLineOfSight)) || (range != -1 && !g_game().canThrowObjectTo(fromPos, toPos, checkLineOfSight, range, range))) { return false; } return true; } -bool InstantSpell::castSpell(Creature* creature) -{ +bool InstantSpell::castSpell(Creature* creature) { LuaVariant var; if (casterTargetOrDirection) { @@ -786,8 +755,7 @@ bool InstantSpell::castSpell(Creature* creature) return executeCastSpell(creature, var); } -bool InstantSpell::castSpell(Creature* creature, Creature* target) -{ +bool InstantSpell::castSpell(Creature* creature, Creature* target) { if (needTarget) { LuaVariant var; var.type = VARIANT_NUMBER; @@ -798,13 +766,12 @@ bool InstantSpell::castSpell(Creature* creature, Creature* target) } } -bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant& var) const -{ - //onCastSpell(creature, var) +bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant &var) const { + // onCastSpell(creature, var) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[InstantSpell::executeCastSpell - Creature {} words {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), getWords()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), getWords()); return false; } @@ -823,8 +790,7 @@ bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant& var) c return getScriptInterface()->callFunction(2); } -bool InstantSpell::canCast(const Player* player) const -{ +bool InstantSpell::canCast(const Player* player) const { if (player->hasFlag(PlayerFlags_t::CannotUseSpells)) { return false; } @@ -846,8 +812,7 @@ bool InstantSpell::canCast(const Player* player) const return false; } -ReturnValue RuneSpell::canExecuteAction(const Player* player, const Position& toPos) -{ +ReturnValue RuneSpell::canExecuteAction(const Player* player, const Position &toPos) { if (player->hasFlag(PlayerFlags_t::CannotUseSpells)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } @@ -868,8 +833,7 @@ ReturnValue RuneSpell::canExecuteAction(const Player* player, const Position& to return RETURNVALUE_NOERROR; } -bool RuneSpell::executeUse(Player* player, Item* item, const Position&, Thing* target, const Position& toPosition, bool isHotkey) -{ +bool RuneSpell::executeUse(Player* player, Item* item, const Position &, Thing* target, const Position &toPosition, bool isHotkey) { if (!playerRuneSpellCheck(player, toPosition)) { return false; } @@ -919,24 +883,21 @@ bool RuneSpell::executeUse(Player* player, Item* item, const Position&, Thing* t return true; } -bool RuneSpell::castSpell(Creature* creature) -{ +bool RuneSpell::castSpell(Creature* creature) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = creature->getID(); return internalCastSpell(creature, var, false); } -bool RuneSpell::castSpell(Creature* creature, Creature* target) -{ +bool RuneSpell::castSpell(Creature* creature, Creature* target) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = target->getID(); return internalCastSpell(creature, var, false); } -bool RuneSpell::internalCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) -{ +bool RuneSpell::internalCastSpell(Creature* creature, const LuaVariant &var, bool isHotkey) { bool result; if (isLoadedCallback()) { result = executeCastSpell(creature, var, isHotkey); @@ -946,13 +907,12 @@ bool RuneSpell::internalCastSpell(Creature* creature, const LuaVariant& var, boo return result; } -bool RuneSpell::executeCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) const -{ - //onCastSpell(creature, var, isHotkey) +bool RuneSpell::executeCastSpell(Creature* creature, const LuaVariant &var, bool isHotkey) const { + // onCastSpell(creature, var, isHotkey) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[RuneSpell::executeCastSpell - Creature {} runeId {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), getRuneItemId()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), getRuneItemId()); return false; } diff --git a/src/creatures/combat/spells.h b/src/creatures/combat/spells.h index de3df6bb0af..2fbf924b2fb 100644 --- a/src/creatures/combat/spells.h +++ b/src/creatures/combat/spells.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_COMBAT_SPELLS_H_ #define SRC_CREATURES_COMBAT_SPELLS_H_ @@ -24,45 +24,44 @@ using VocSpellMap = std::map; using InstantSpell_ptr = std::unique_ptr; using RuneSpell_ptr = std::unique_ptr; -class Spells final : public Scripts -{ +class Spells final : public Scripts { public: Spells(); ~Spells(); // non-copyable - Spells(const Spells&) = delete; - Spells& operator=(const Spells&) = delete; + Spells(const Spells &) = delete; + Spells &operator=(const Spells &) = delete; - static Spells& getInstance() { + static Spells &getInstance() { // Guaranteed to be destroyed static Spells instance; // Instantiated on first use return instance; } - Spell* getSpellByName(const std::string& name); + Spell* getSpellByName(const std::string &name); RuneSpell* getRuneSpell(uint32_t id); - RuneSpell* getRuneSpellByName(const std::string& name); + RuneSpell* getRuneSpellByName(const std::string &name); - InstantSpell* getInstantSpell(const std::string& words); - InstantSpell* getInstantSpellByName(const std::string& name); + InstantSpell* getInstantSpell(const std::string &words); + InstantSpell* getInstantSpellByName(const std::string &name); InstantSpell* getInstantSpellById(uint32_t spellId); - TalkActionResult_t playerSaySpell(Player* player, std::string& words); + TalkActionResult_t playerSaySpell(Player* player, std::string &words); static Position getCasterPosition(Creature* creature, Direction dir); std::list getSpellsByVocation(uint16_t vocationId); - const std::map& getInstantSpells() const { + const std::map &getInstantSpells() const { return instants; }; - bool hasInstantSpell(const std::string& word) const; + bool hasInstantSpell(const std::string &word) const; - void setInstantSpell(const std::string &word, InstantSpell& instant) { + void setInstantSpell(const std::string &word, InstantSpell &instant) { instants.try_emplace(word, instant); } @@ -79,10 +78,9 @@ class Spells final : public Scripts constexpr auto g_spells = &Spells::getInstance; -using RuneSpellFunction = std::function; +using RuneSpellFunction = std::function; -class BaseSpell -{ +class BaseSpell { public: constexpr BaseSpell() = default; virtual ~BaseSpell() = default; @@ -91,21 +89,20 @@ class BaseSpell virtual bool castSpell(Creature* creature, Creature* target) = 0; }; -class CombatSpell final : public Script, public BaseSpell -{ +class CombatSpell final : public Script, public BaseSpell { public: // Constructor CombatSpell(Combat* newCombat, bool newNeedTarget, bool newNeedDirection); // The copy constructor and the assignment operator have been deleted to prevent accidental copying. - CombatSpell(const CombatSpell&) = delete; - CombatSpell& operator=(const CombatSpell&) = delete; + CombatSpell(const CombatSpell &) = delete; + CombatSpell &operator=(const CombatSpell &) = delete; bool castSpell(Creature* creature) override; bool castSpell(Creature* creature, Creature* target) override; // Scripting spell - bool executeCastSpell(Creature* creature, const LuaVariant& var) const; + bool executeCastSpell(Creature* creature, const LuaVariant &var) const; bool loadScriptCombat(); Combat* getCombat() { @@ -123,12 +120,11 @@ class CombatSpell final : public Script, public BaseSpell bool needTarget; }; -class Spell : public BaseSpell -{ +class Spell : public BaseSpell { public: Spell() = default; - const std::string& getName() const { + const std::string &getName() const { return name; } void setName(std::string n) { @@ -189,7 +185,7 @@ class Spell : public BaseSpell enabled = e; } - const VocSpellMap& getVocMap() const { + const VocSpellMap &getVocMap() const { return vocSpellMap; } void addVocMap(uint16_t n, bool b) { @@ -280,13 +276,13 @@ class Spell : public BaseSpell bool getAllowOnSelf() const { return allowOnSelf; } - void setAllowOnSelf(bool s) { + void setAllowOnSelf(bool s) { allowOnSelf = s; } bool getLockedPZ() const { return pzLocked; } - void setLockedPZ(bool b){ + void setLockedPZ(bool b) { pzLocked = b; } @@ -295,8 +291,8 @@ class Spell : public BaseSpell protected: void applyCooldownConditions(Player* player) const; bool playerSpellCheck(Player* player) const; - bool playerInstantSpellCheck(Player* player, const Position& toPos); - bool playerRuneSpellCheck(Player* player, const Position& toPos); + bool playerInstantSpellCheck(Player* player, const Position &toPos); + bool playerRuneSpellCheck(Player* player, const Position &toPos); VocSpellMap vocSpellMap; @@ -318,7 +314,6 @@ class Spell : public BaseSpell bool pzLocked = false; private: - uint32_t mana = 0; uint32_t manaPercent = 0; uint32_t soul = 0; @@ -331,23 +326,21 @@ class Spell : public BaseSpell bool enabled = true; bool premium = false; - private: std::string name; }; -class InstantSpell final : public TalkAction, public Spell -{ +class InstantSpell final : public TalkAction, public Spell { public: using TalkAction::TalkAction; - virtual bool playerCastInstant(Player* player, std::string& param); + virtual bool playerCastInstant(Player* player, std::string ¶m); bool castSpell(Creature* creature) override; bool castSpell(Creature* creature, Creature* target) override; // Scripting spell - bool executeCastSpell(Creature* creature, const LuaVariant& var) const; + bool executeCastSpell(Creature* creature, const LuaVariant &var) const; bool isInstant() const override { return true; @@ -397,26 +390,25 @@ class InstantSpell final : public TalkAction, public Spell bool casterTargetOrDirection = false; }; -class RuneSpell final : public Action, public Spell -{ +class RuneSpell final : public Action, public Spell { public: using Action::Action; - ReturnValue canExecuteAction(const Player* player, const Position& toPos) override; + ReturnValue canExecuteAction(const Player* player, const Position &toPos) override; bool hasOwnErrorHandler() override { return true; } - Thing* getTarget(Player*, Creature* targetCreature, const Position&, uint8_t) const override { + Thing* getTarget(Player*, Creature* targetCreature, const Position &, uint8_t) const override { return targetCreature; } - bool executeUse(Player* player, Item* item, const Position& fromPosition, Thing* target, const Position& toPosition, bool isHotkey) override; + bool executeUse(Player* player, Item* item, const Position &fromPosition, Thing* target, const Position &toPosition, bool isHotkey) override; bool castSpell(Creature* creature) override; bool castSpell(Creature* creature, Creature* target) override; // Scripting spell - bool executeCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) const; + bool executeCastSpell(Creature* creature, const LuaVariant &var, bool isHotkey) const; bool isInstant() const override { return false; @@ -442,11 +434,11 @@ class RuneSpell final : public Action, public Spell return "onCastSpell"; } - bool internalCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey); + bool internalCastSpell(Creature* creature, const LuaVariant &var, bool isHotkey); uint16_t runeId = 0; uint32_t charges = 0; bool hasCharges = false; }; -#endif // SRC_CREATURES_COMBAT_SPELLS_H_ +#endif // SRC_CREATURES_COMBAT_SPELLS_H_ diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index ac9ceb6f889..be0cfe2064a 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -19,13 +19,11 @@ double Creature::speedA = 857.36; double Creature::speedB = 261.29; double Creature::speedC = -4795.01; -Creature::Creature() -{ +Creature::Creature() { onIdleStatus(); } -Creature::~Creature() -{ +Creature::~Creature() { for (Creature* summon : summons) { summon->setAttackedCreature(nullptr); summon->removeMaster(); @@ -37,17 +35,16 @@ Creature::~Creature() } } -bool Creature::canSee(const Position& myPos, const Position& pos, int32_t viewRangeX, int32_t viewRangeY) -{ +bool Creature::canSee(const Position &myPos, const Position &pos, int32_t viewRangeX, int32_t viewRangeY) { if (myPos.z <= MAP_INIT_SURFACE_LAYER) { - //we are on ground level or above (7 -> 0) - //view is from 7 -> 0 + // we are on ground level or above (7 -> 0) + // view is from 7 -> 0 if (pos.z > MAP_INIT_SURFACE_LAYER) { return false; } } else if (myPos.z >= MAP_INIT_SURFACE_LAYER + 1) { - //we are underground (8 -> 15) - //view is +/- 2 from the floor we stand on + // we are underground (8 -> 15) + // view is +/- 2 from the floor we stand on if (Position::getDistanceZ(myPos, pos) > MAP_LAYER_VIEW_LIMIT) { return false; } @@ -58,35 +55,30 @@ bool Creature::canSee(const Position& myPos, const Position& pos, int32_t viewRa && (pos.getY() >= myPos.getY() - viewRangeY + offsetz) && (pos.getY() <= myPos.getY() + viewRangeY + offsetz); } -bool Creature::canSee(const Position& pos) const -{ +bool Creature::canSee(const Position &pos) const { return canSee(getPosition(), pos, Map::maxViewportX, Map::maxViewportY); } -bool Creature::canSeeCreature(const Creature* creature) const -{ +bool Creature::canSeeCreature(const Creature* creature) const { if (!canSeeInvisibility() && creature->isInvisible()) { return false; } return true; } -void Creature::setSkull(Skulls_t newSkull) -{ +void Creature::setSkull(Skulls_t newSkull) { skull = newSkull; g_game().updateCreatureSkull(this); } -int64_t Creature::getTimeSinceLastMove() const -{ +int64_t Creature::getTimeSinceLastMove() const { if (lastStep) { return OTSYS_TIME() - lastStep; } return std::numeric_limits::max(); } -int32_t Creature::getWalkDelay(Direction dir) const -{ +int32_t Creature::getWalkDelay(Direction dir) const { if (lastStep == 0) { return 0; } @@ -96,9 +88,8 @@ int32_t Creature::getWalkDelay(Direction dir) const return stepDuration - (ct - lastStep); } -int32_t Creature::getWalkDelay() const -{ - //Used for auto-walking +int32_t Creature::getWalkDelay() const { + // Used for auto-walking if (lastStep == 0) { return 0; } @@ -108,8 +99,7 @@ int32_t Creature::getWalkDelay() const return stepDuration - (ct - lastStep); } -void Creature::onThink(uint32_t interval) -{ +void Creature::onThink(uint32_t interval) { if (!isMapLoaded && useCacheMap()) { isMapLoaded = true; updateMapCache(); @@ -143,15 +133,14 @@ void Creature::onThink(uint32_t interval) goToFollowCreature(); } - //scripting event - onThink - const CreatureEventList& thinkEvents = getCreatureEvents(CREATURE_EVENT_THINK); + // scripting event - onThink + const CreatureEventList &thinkEvents = getCreatureEvents(CREATURE_EVENT_THINK); for (CreatureEvent* thinkEvent : thinkEvents) { thinkEvent->executeOnThink(this, interval); } } -void Creature::onAttacking(uint32_t interval) -{ +void Creature::onAttacking(uint32_t interval) { if (!attackedCreature) { return; } @@ -164,16 +153,14 @@ void Creature::onAttacking(uint32_t interval) } } -void Creature::onIdleStatus() -{ +void Creature::onIdleStatus() { if (getHealth() > 0) { damageMap.clear(); lastHitCreatureId = 0; } } -void Creature::onCreatureWalk() -{ +void Creature::onCreatureWalk() { if (getWalkDelay() <= 0) { Direction dir; uint32_t flags = FLAG_IGNOREFIELDDAMAGE; @@ -208,8 +195,7 @@ void Creature::onCreatureWalk() } } -void Creature::onWalk(Direction& dir) -{ +void Creature::onWalk(Direction &dir) { if (hasCondition(CONDITION_DRUNK)) { uint32_t r = uniform_random(0, 20); if (r <= DIRECTION_DIAGONAL_MASK) { @@ -221,8 +207,7 @@ void Creature::onWalk(Direction& dir) } } -bool Creature::getNextStep(Direction& dir, uint32_t&) -{ +bool Creature::getNextStep(Direction &dir, uint32_t &) { if (listWalkDir.empty()) { return false; } @@ -233,8 +218,7 @@ bool Creature::getNextStep(Direction& dir, uint32_t&) return true; } -void Creature::startAutoWalk(const std::forward_list& listDir) -{ +void Creature::startAutoWalk(const std::forward_list &listDir) { if (hasCondition(CONDITION_ROOTED)) { return; } @@ -248,8 +232,7 @@ void Creature::startAutoWalk(const std::forward_list& listDir) addEventWalk(size == 1); } -void Creature::addEventWalk(bool firstStep) -{ +void Creature::addEventWalk(bool firstStep) { cancelNextWalk = false; if (getStepSpeed() <= 0) { @@ -273,18 +256,16 @@ void Creature::addEventWalk(bool firstStep) eventWalk = g_scheduler().addEvent(createSchedulerTask(static_cast(ticks), std::bind(&Game::checkCreatureWalk, &g_game(), getID()))); } -void Creature::stopEventWalk() -{ +void Creature::stopEventWalk() { if (eventWalk != 0) { g_scheduler().stopEvent(eventWalk); eventWalk = 0; } } -void Creature::updateMapCache() -{ +void Creature::updateMapCache() { Tile* newTile; - const Position& myPos = getPosition(); + const Position &myPos = getPosition(); Position pos(0, 0, myPos.z); for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) { @@ -297,16 +278,14 @@ void Creature::updateMapCache() } } -void Creature::updateTileCache(const Tile* newTile, int32_t dx, int32_t dy) -{ +void Creature::updateTileCache(const Tile* newTile, int32_t dx, int32_t dy) { if (std::abs(dx) <= maxWalkCacheWidth && std::abs(dy) <= maxWalkCacheHeight) { localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx] = newTile && newTile->queryAdd(0, *this, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR; } } -void Creature::updateTileCache(const Tile* upTile, const Position& pos) -{ - const Position& myPos = getPosition(); +void Creature::updateTileCache(const Tile* upTile, const Position &pos) { + const Position &myPos = getPosition(); if (pos.z == myPos.z) { int32_t dx = Position::getOffsetX(pos, myPos); int32_t dy = Position::getOffsetY(pos, myPos); @@ -314,13 +293,12 @@ void Creature::updateTileCache(const Tile* upTile, const Position& pos) } } -int32_t Creature::getWalkCache(const Position& pos) const -{ +int32_t Creature::getWalkCache(const Position &pos) const { if (!useCacheMap()) { return 2; } - const Position& myPos = getPosition(); + const Position &myPos = getPosition(); if (myPos.z != pos.z) { return 0; } @@ -341,20 +319,17 @@ int32_t Creature::getWalkCache(const Position& pos) const } } - //out of range + // out of range return 2; } -void Creature::onAddTileItem(const Tile* tileItem, const Position& pos) -{ +void Creature::onAddTileItem(const Tile* tileItem, const Position &pos) { if (isMapLoaded && pos.z == getPosition().z) { updateTileCache(tileItem, pos); } } -void Creature::onUpdateTileItem(const Tile* updateTile, const Position& pos, const Item*, - const ItemType& oldType, const Item*, const ItemType& newType) -{ +void Creature::onUpdateTileItem(const Tile* updateTile, const Position &pos, const Item*, const ItemType &oldType, const Item*, const ItemType &newType) { if (!isMapLoaded) { return; } @@ -366,8 +341,7 @@ void Creature::onUpdateTileItem(const Tile* updateTile, const Position& pos, con } } -void Creature::onRemoveTileItem(const Tile* updateTile, const Position& pos, const ItemType& iType, const Item*) -{ +void Creature::onRemoveTileItem(const Tile* updateTile, const Position &pos, const ItemType &iType, const Item*) { if (!isMapLoaded) { return; } @@ -379,8 +353,7 @@ void Creature::onRemoveTileItem(const Tile* updateTile, const Position& pos, con } } -void Creature::onCreatureAppear(Creature* creature, bool isLogin) -{ +void Creature::onCreatureAppear(Creature* creature, bool isLogin) { if (creature == this) { if (useCacheMap()) { isMapLoaded = true; @@ -397,12 +370,11 @@ void Creature::onCreatureAppear(Creature* creature, bool isLogin) } } -void Creature::onRemoveCreature(Creature* creature, bool) -{ +void Creature::onRemoveCreature(Creature* creature, bool) { onCreatureDisappear(creature, true); if (creature != this && isMapLoaded) { if (creature->getPosition().z == getPosition().z) { - updateTileCache(creature->getTile(), creature->getPosition()); + updateTileCache(creature->getTile(), creature->getPosition()); } } @@ -413,8 +385,7 @@ void Creature::onRemoveCreature(Creature* creature, bool) } } -void Creature::onCreatureDisappear(const Creature* creature, bool isLogout) -{ +void Creature::onCreatureDisappear(const Creature* creature, bool isLogout) { if (attackedCreature == creature) { setAttackedCreature(nullptr); onAttackedCreatureDisappear(isLogout); @@ -426,22 +397,19 @@ void Creature::onCreatureDisappear(const Creature* creature, bool isLogout) } } -void Creature::onChangeZone(ZoneType_t zone) -{ +void Creature::onChangeZone(ZoneType_t zone) { if (attackedCreature && zone == ZONE_PROTECTION) { onCreatureDisappear(attackedCreature, false); } } -void Creature::onAttackedCreatureChangeZone(ZoneType_t zone) -{ +void Creature::onAttackedCreatureChangeZone(ZoneType_t zone) { if (zone == ZONE_PROTECTION) { onCreatureDisappear(attackedCreature, false); } } -void Creature::checkSummonMove(const Position& newPos, bool teleportSummon) const -{ +void Creature::checkSummonMove(const Position &newPos, bool teleportSummon) const { if (hasSummons()) { std::vector despawnMonsterList; for (Creature* creature : getSummons()) { @@ -449,17 +417,13 @@ void Creature::checkSummonMove(const Position& newPos, bool teleportSummon) cons continue; } - const Position& pos = creature->getPosition(); + const Position &pos = creature->getPosition(); const Monster* monster = creature->getMonster(); bool protectionZoneCheck = this->getTile()->hasFlag(TILESTATE_PROTECTIONZONE); // Check if any of our summons is out of range (+/- 0 floors or 15 tiles away) - bool checkSummonDist = Position::getDistanceZ(newPos, pos) > 0 || - (std::max(Position::getDistanceX(newPos, pos), - Position::getDistanceY(newPos, pos)) > 15); + bool checkSummonDist = Position::getDistanceZ(newPos, pos) > 0 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 15); // Check if any of our summons is out of range (+/- 2 floors or 30 tiles away) - bool checkRemoveDist = Position::getDistanceZ(newPos, pos) > 2 || - (std::max(Position::getDistanceX(newPos, pos), - Position::getDistanceY(newPos, pos)) > 30); + bool checkRemoveDist = Position::getDistanceZ(newPos, pos) > 2 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 30); if (monster->isFamiliar() && checkSummonDist || teleportSummon && !protectionZoneCheck && checkSummonDist) { g_game().internalTeleport(creature, creature->getMaster()->getPosition(), true); @@ -479,19 +443,17 @@ void Creature::checkSummonMove(const Position& newPos, bool teleportSummon) cons } } -void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport) -{ +void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) { if (creature == this) { lastStep = OTSYS_TIME(); lastStepCost = 1; if (!teleport) { if (oldPos.z != newPos.z) { - //floor change extra cost + // floor change extra cost lastStepCost = 2; } else if (Position::getDistanceX(newPos, oldPos) >= 1 && Position::getDistanceY(newPos, oldPos) >= 1) { - //diagonal extra cost + // diagonal extra cost lastStepCost = 3; } } else { @@ -500,12 +462,12 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS); checkSummonMove(newPos, configTeleportSummons); - if(isLostSummon()) { + if (isLostSummon()) { handleLostSummon(configTeleportSummons); } if (Player* player = creature->getPlayer()) { - if (player->isExerciseTraining()){ + if (player->isExerciseTraining()) { player->setTraining(false); } } @@ -514,31 +476,31 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos onChangeZone(getZone()); } - //update map cache + // update map cache if (isMapLoaded) { if (teleport || oldPos.z != newPos.z) { updateMapCache(); } else { - const Position& myPos = getPosition(); + const Position &myPos = getPosition(); - if (oldPos.y > newPos.y) { //north - //shift y south + if (oldPos.y > newPos.y) { // north + // shift y south for (int32_t y = mapWalkHeight - 1; --y >= 0;) { memcpy(localMapCache[y + 1], localMapCache[y], sizeof(localMapCache[y])); } - //update 0 + // update 0 for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) { const Tile* cacheTile = g_game().map.getTile(static_cast(myPos.getX() + x), static_cast(myPos.getY() - maxWalkCacheHeight), myPos.z); updateTileCache(cacheTile, x, -maxWalkCacheHeight); } } else if (oldPos.y < newPos.y) { // south - //shift y north + // shift y north for (int32_t y = 0; y <= mapWalkHeight - 2; ++y) { memcpy(localMapCache[y], localMapCache[y + 1], sizeof(localMapCache[y])); } - //update mapWalkHeight - 1 + // update mapWalkHeight - 1 for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) { const Tile* cacheTile = g_game().map.getTile(static_cast(myPos.getX() + x), static_cast(myPos.getY() + maxWalkCacheHeight), myPos.z); updateTileCache(cacheTile, x, maxWalkCacheHeight); @@ -546,7 +508,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } if (oldPos.x < newPos.x) { // east - //shift y west + // shift y west int32_t starty = 0; int32_t endy = mapWalkHeight - 1; int32_t dy = Position::getDistanceY(oldPos, newPos); @@ -563,13 +525,13 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } - //update mapWalkWidth - 1 + // update mapWalkWidth - 1 for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) { const Tile* cacheTile = g_game().map.getTile(myPos.x + maxWalkCacheWidth, static_cast(myPos.y + y), myPos.z); updateTileCache(cacheTile, maxWalkCacheWidth, y); } } else if (oldPos.x > newPos.x) { // west - //shift y east + // shift y east int32_t starty = 0; int32_t endy = mapWalkHeight - 1; int32_t dy = Position::getDistanceY(oldPos, newPos); @@ -586,7 +548,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } - //update 0 + // update 0 for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) { const Tile* cacheTile = g_game().map.getTile(myPos.x - maxWalkCacheWidth, static_cast(myPos.y + y), myPos.z); updateTileCache(cacheTile, -maxWalkCacheWidth, y); @@ -598,7 +560,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } else { if (isMapLoaded) { - const Position& myPos = getPosition(); + const Position &myPos = getPosition(); if (newPos.z == myPos.z) { updateTileCache(newTile, newPos); @@ -626,7 +588,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos onCreatureDisappear(attackedCreature, false); } else { if (hasExtraSwing()) { - //our target is moving lets see if we can get in hit + // our target is moving lets see if we can get in hit g_dispatcher().addTask(createTask(std::bind(&Game::checkCreatureAttack, &g_game(), getID()))); } @@ -637,8 +599,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } -void Creature::onDeath() -{ +void Creature::onDeath() { bool lastHitUnjustified = false; bool mostDamageUnjustified = false; Creature* lastHitCreature = g_game().getCreatureByID(lastHitCreatureId); @@ -656,7 +617,7 @@ void Creature::onDeath() const uint32_t inFightTicks = g_configManager().getNumber(PZ_LOCKED); int32_t mostDamage = 0; std::map experienceMap; - for (const auto& it : damageMap) { + for (const auto &it : damageMap) { if (Creature* attacker = g_game().getCreatureByID(it.first)) { CountBlock_t cb = it.second; if ((cb.total > mostDamage && (timeNow - cb.ticks <= inFightTicks))) { @@ -686,7 +647,7 @@ void Creature::onDeath() } } - for (const auto& it : experienceMap) { + for (const auto &it : experienceMap) { it.first->onGainExperience(it.second, this); } @@ -711,12 +672,11 @@ void Creature::onDeath() } } -bool Creature::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) -{ +bool Creature::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { if (!lootDrop && getMonster()) { if (master) { // Scripting event onDeath - const CreatureEventList& deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH); + const CreatureEventList &deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH); for (CreatureEvent* deathEvent : deathEvents) { deathEvent->executeOnDeath(this, nullptr, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } @@ -796,8 +756,7 @@ bool Creature::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreatur return true; } -bool Creature::hasBeenAttacked(uint32_t attackerId) -{ +bool Creature::hasBeenAttacked(uint32_t attackerId) { auto it = damageMap.find(attackerId); if (it == damageMap.end()) { return false; @@ -805,13 +764,11 @@ bool Creature::hasBeenAttacked(uint32_t attackerId) return (OTSYS_TIME() - it->second.ticks) <= g_configManager().getNumber(PZ_LOCKED); } -Item* Creature::getCorpse(Creature*, Creature*) -{ +Item* Creature::getCorpse(Creature*, Creature*) { return Item::CreateItem(getLookCorpse()); } -void Creature::changeHealth(int32_t healthChange, bool sendHealthChange/* = true*/) -{ +void Creature::changeHealth(int32_t healthChange, bool sendHealthChange /* = true*/) { int32_t oldHealth = health; if (healthChange > 0) { @@ -828,8 +785,7 @@ void Creature::changeHealth(int32_t healthChange, bool sendHealthChange/* = true } } -void Creature::changeMana(int32_t manaChange) -{ +void Creature::changeMana(int32_t manaChange) { if (manaChange > 0) { mana += std::min(manaChange, getMaxMana() - mana); } else { @@ -837,16 +793,14 @@ void Creature::changeMana(int32_t manaChange) } } -void Creature::gainHealth(Creature* healer, int32_t healthGain) -{ +void Creature::gainHealth(Creature* healer, int32_t healthGain) { changeHealth(healthGain); if (healer) { healer->onTargetCreatureGainHealth(this, healthGain); } } -void Creature::drainHealth(Creature* attacker, int32_t damage) -{ +void Creature::drainHealth(Creature* attacker, int32_t damage) { changeHealth(-damage, false); if (attacker) { @@ -854,8 +808,7 @@ void Creature::drainHealth(Creature* attacker, int32_t damage) } } -void Creature::drainMana(Creature* attacker, int32_t manaLoss) -{ +void Creature::drainMana(Creature* attacker, int32_t manaLoss) { onAttacked(); changeMana(-manaLoss); @@ -864,9 +817,7 @@ void Creature::drainMana(Creature* attacker, int32_t manaLoss) } } -BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, - bool checkDefense /* = false */, bool checkArmor /* = false */, bool /* field = false */) -{ +BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int32_t &damage, bool checkDefense /* = false */, bool checkArmor /* = false */, bool /* field = false */) { BlockType_t blockType = BLOCK_NONE; if (isImmune(combatType)) { @@ -918,14 +869,13 @@ BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int3 return blockType; } -bool Creature::setAttackedCreature(Creature* creature) -{ +bool Creature::setAttackedCreature(Creature* creature) { if (creature) { if (this->getMonster() && this->getMonster()->isFamiliar() && this->getTile() && this->getTile()->hasFlag(TILESTATE_PROTECTIONZONE)) { return false; } - const Position& creaturePos = creature->getPosition(); + const Position &creaturePos = creature->getPosition(); if (creaturePos.z != getPosition().z || !canSee(creaturePos)) { attackedCreature = nullptr; return false; @@ -944,8 +894,7 @@ bool Creature::setAttackedCreature(Creature* creature) return true; } -void Creature::getPathSearchParams(const Creature*, FindPathParams& fpp) const -{ +void Creature::getPathSearchParams(const Creature*, FindPathParams &fpp) const { fpp.fullPathSearch = !hasFollowPath; fpp.clearSight = true; fpp.maxSearchDist = 12; @@ -953,10 +902,9 @@ void Creature::getPathSearchParams(const Creature*, FindPathParams& fpp) const fpp.maxTargetDist = 1; } -void Creature::goToFollowCreature() -{ +void Creature::goToFollowCreature() { if (followCreature) { - if(isSummon() && !getMonster()->isFamiliar() && !canFollowMaster()){ + if (isSummon() && !getMonster()->isFamiliar() && !canFollowMaster()) { hasFollowPath = false; return; } @@ -969,7 +917,7 @@ void Creature::goToFollowCreature() if (monster->isFleeing()) { monster->getDistanceStep(followCreature->getPosition(), dir, true); - } else { //maxTargetDist > 1 + } else { // maxTargetDist > 1 if (!monster->getDistanceStep(followCreature->getPosition(), dir)) { // if we can't get anything then let the A* calculate listWalkDir.clear(); @@ -1008,14 +956,13 @@ bool Creature::canFollowMaster() const { return !master->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) && (canSeeInvisibility() || !master->isInvisible()); } -bool Creature::setFollowCreature(Creature* creature) -{ +bool Creature::setFollowCreature(Creature* creature) { if (creature) { if (followCreature == creature) { return true; } - const Position& creaturePos = creature->getPosition(); + const Position &creaturePos = creature->getPosition(); if (creaturePos.z != getPosition().z || !canSee(creaturePos)) { followCreature = nullptr; return false; @@ -1039,13 +986,12 @@ bool Creature::setFollowCreature(Creature* creature) return true; } -double Creature::getDamageRatio(Creature* attacker) const -{ +double Creature::getDamageRatio(Creature* attacker) const { uint32_t totalDamage = 0; uint32_t attackerDamage = 0; - for (const auto& it : damageMap) { - const CountBlock_t& cb = it.second; + for (const auto &it : damageMap) { + const CountBlock_t &cb = it.second; totalDamage += cb.total; if (it.first == attacker->getID()) { attackerDamage += cb.total; @@ -1059,13 +1005,11 @@ double Creature::getDamageRatio(Creature* attacker) const return (static_cast(attackerDamage) / totalDamage); } -uint64_t Creature::getGainedExperience(Creature* attacker) const -{ +uint64_t Creature::getGainedExperience(Creature* attacker) const { return std::floor(getDamageRatio(attacker) * getLostExperience()); } -void Creature::addDamagePoints(Creature* attacker, int32_t damagePoints) -{ +void Creature::addDamagePoints(Creature* attacker, int32_t damagePoints) { if (damagePoints <= 0) { return; } @@ -1086,8 +1030,7 @@ void Creature::addDamagePoints(Creature* attacker, int32_t damagePoints) lastHitCreatureId = attackerId; } -void Creature::onAddCondition(ConditionType_t type) -{ +void Creature::onAddCondition(ConditionType_t type) { if (type == CONDITION_PARALYZE && hasCondition(CONDITION_HASTE)) { removeCondition(CONDITION_HASTE); } else if (type == CONDITION_HASTE && hasCondition(CONDITION_PARALYZE)) { @@ -1095,18 +1038,15 @@ void Creature::onAddCondition(ConditionType_t type) } } -void Creature::onAddCombatCondition(ConditionType_t) -{ +void Creature::onAddCombatCondition(ConditionType_t) { // } -void Creature::onEndCondition(ConditionType_t) -{ +void Creature::onEndCondition(ConditionType_t) { // } -void Creature::onTickCondition(ConditionType_t type, bool& bRemove) -{ +void Creature::onTickCondition(ConditionType_t type, bool &bRemove) { const MagicField* field = getTile()->getFieldItem(); if (!field) { return; @@ -1142,45 +1082,39 @@ void Creature::onTickCondition(ConditionType_t type, bool& bRemove) } } -void Creature::onCombatRemoveCondition(Condition* condition) -{ +void Creature::onCombatRemoveCondition(Condition* condition) { removeCondition(condition); } -void Creature::onAttacked() -{ +void Creature::onAttacked() { // } -void Creature::onAttackedCreatureDrainHealth(Creature* target, int32_t points) -{ +void Creature::onAttackedCreatureDrainHealth(Creature* target, int32_t points) { target->addDamagePoints(this, points); } -void Creature::onAttackedCreatureKilled(Creature* target) -{ +void Creature::onAttackedCreatureKilled(Creature* target) { if (target != this) { uint64_t gainExp = target->getGainedExperience(this); onGainExperience(gainExp, target); } } -bool Creature::onKilledCreature(Creature* target, bool lastHit) -{ +bool Creature::onKilledCreature(Creature* target, bool lastHit) { if (master) { master->onKilledCreature(target, lastHit); } - //scripting event - onKill - const CreatureEventList& killEvents = getCreatureEvents(CREATURE_EVENT_KILL); + // scripting event - onKill + const CreatureEventList &killEvents = getCreatureEvents(CREATURE_EVENT_KILL); for (CreatureEvent* killEvent : killEvents) { killEvent->executeOnKill(this, target, lastHit); } return false; } -void Creature::onGainExperience(uint64_t gainExp, Creature* target) -{ +void Creature::onGainExperience(uint64_t gainExp, Creature* target) { if (gainExp == 0 || !master) { return; } @@ -1210,7 +1144,7 @@ void Creature::onGainExperience(uint64_t gainExp, Creature* target) } } -bool Creature::setMaster(Creature* newMaster, bool reloadCreature/* = false*/) { +bool Creature::setMaster(Creature* newMaster, bool reloadCreature /* = false*/) { // Persists if this creature has ever been a summon this->summoned = true; @@ -1243,8 +1177,7 @@ bool Creature::setMaster(Creature* newMaster, bool reloadCreature/* = false*/) { return true; } -bool Creature::addCondition(Condition* condition) -{ +bool Creature::addCondition(Condition* condition) { if (condition == nullptr) { return false; } @@ -1266,9 +1199,8 @@ bool Creature::addCondition(Condition* condition) return false; } -bool Creature::addCombatCondition(Condition* condition) -{ - //Caution: condition variable could be deleted after the call to addCondition +bool Creature::addCombatCondition(Condition* condition) { + // Caution: condition variable could be deleted after the call to addCondition ConditionType_t type = condition->getType(); if (!addCondition(condition)) { @@ -1279,8 +1211,7 @@ bool Creature::addCombatCondition(Condition* condition) return true; } -void Creature::removeCondition(ConditionType_t type) -{ +void Creature::removeCondition(ConditionType_t type) { auto it = conditions.begin(), end = conditions.end(); while (it != end) { Condition* condition = *it; @@ -1298,8 +1229,7 @@ void Creature::removeCondition(ConditionType_t type) } } -void Creature::removeCondition(ConditionType_t conditionType, ConditionId_t conditionId, bool force/* = false*/) -{ +void Creature::removeCondition(ConditionType_t conditionType, ConditionId_t conditionId, bool force /* = false*/) { auto it = conditions.begin(), end = conditions.end(); while (it != end) { Condition* condition = *it; @@ -1325,8 +1255,7 @@ void Creature::removeCondition(ConditionType_t conditionType, ConditionId_t cond } } -void Creature::removeCombatCondition(ConditionType_t type) -{ +void Creature::removeCombatCondition(ConditionType_t type) { std::vector removeConditions; for (Condition* condition : conditions) { if (condition->getType() == type) { @@ -1339,8 +1268,7 @@ void Creature::removeCombatCondition(ConditionType_t type) } } -void Creature::removeCondition(Condition* condition) -{ +void Creature::removeCondition(Condition* condition) { auto it = std::find(conditions.begin(), conditions.end(), condition); if (it == conditions.end()) { return; @@ -1353,8 +1281,7 @@ void Creature::removeCondition(Condition* condition) delete condition; } -Condition* Creature::getCondition(ConditionType_t type) const -{ +Condition* Creature::getCondition(ConditionType_t type) const { for (Condition* condition : conditions) { if (condition->getType() == type) { return condition; @@ -1363,8 +1290,7 @@ Condition* Creature::getCondition(ConditionType_t type) const return nullptr; } -Condition* Creature::getCondition(ConditionType_t type, ConditionId_t conditionId, uint32_t subId/* = 0*/) const -{ +Condition* Creature::getCondition(ConditionType_t type, ConditionId_t conditionId, uint32_t subId /* = 0*/) const { for (Condition* condition : conditions) { if (condition->getType() == type && condition->getId() == conditionId && condition->getSubId() == subId) { return condition; @@ -1373,8 +1299,7 @@ Condition* Creature::getCondition(ConditionType_t type, ConditionId_t conditionI return nullptr; } -void Creature::executeConditions(uint32_t interval) -{ +void Creature::executeConditions(uint32_t interval) { auto it = conditions.begin(), end = conditions.end(); while (it != end) { Condition* condition = *it; @@ -1393,8 +1318,7 @@ void Creature::executeConditions(uint32_t interval) } } -bool Creature::hasCondition(ConditionType_t type, uint32_t subId/* = 0*/) const -{ +bool Creature::hasCondition(ConditionType_t type, uint32_t subId /* = 0*/) const { if (isSuppress(type)) { return false; } @@ -1412,23 +1336,19 @@ bool Creature::hasCondition(ConditionType_t type, uint32_t subId/* = 0*/) const return false; } -bool Creature::isImmune(CombatType_t type) const -{ +bool Creature::isImmune(CombatType_t type) const { return hasBitSet(static_cast(type), getDamageImmunities()); } -bool Creature::isImmune(ConditionType_t type) const -{ +bool Creature::isImmune(ConditionType_t type) const { return hasBitSet(static_cast(type), getConditionImmunities()); } -bool Creature::isSuppress(ConditionType_t type) const -{ +bool Creature::isSuppress(ConditionType_t type) const { return hasBitSet(static_cast(type), getConditionSuppressions()); } -int64_t Creature::getStepDuration(Direction dir) const -{ +int64_t Creature::getStepDuration(Direction dir) const { int64_t stepDuration = getStepDuration(); if ((dir & DIRECTION_DIAGONAL_MASK) != 0) { stepDuration *= 3; @@ -1436,8 +1356,7 @@ int64_t Creature::getStepDuration(Direction dir) const return stepDuration; } -int64_t Creature::getStepDuration() const -{ +int64_t Creature::getStepDuration() const { if (isRemoved()) { return 0; } @@ -1449,7 +1368,7 @@ int64_t Creature::getStepDuration() const uint32_t groundSpeed = 150; if (tile && tile->getGround()) { Item* ground = tile->getGround(); - const ItemType& it = Item::items[ground->getID()]; + const ItemType &it = Item::items[ground->getID()]; groundSpeed = it.speed > 0 ? it.speed : groundSpeed; } @@ -1464,8 +1383,7 @@ int64_t Creature::getStepDuration() const return stepDuration; } -int64_t Creature::getEventStepTicks(bool onlyDelay) const -{ +int64_t Creature::getEventStepTicks(bool onlyDelay) const { int64_t ret = getWalkDelay(); if (ret <= 0) { int64_t stepDuration = getStepDuration(); @@ -1478,15 +1396,13 @@ int64_t Creature::getEventStepTicks(bool onlyDelay) const return ret; } -LightInfo Creature::getCreatureLight() const -{ +LightInfo Creature::getCreatureLight() const { return internalLight; } void Creature::setSpeed(int32_t varSpeedDelta) { // Prevents creatures from not exceeding the maximum allowed speed - if (getSpeed() >= PLAYER_MAX_SPEED) - { + if (getSpeed() >= PLAYER_MAX_SPEED) { return; } @@ -1505,13 +1421,11 @@ void Creature::setCreatureLight(LightInfo lightInfo) { internalLight = std::move(lightInfo); } -void Creature::setNormalCreatureLight() -{ +void Creature::setNormalCreatureLight() { internalLight = {}; } -bool Creature::registerCreatureEvent(const std::string& name) -{ +bool Creature::registerCreatureEvent(const std::string &name) { CreatureEvent* event = g_creatureEvents().getEventByName(name); if (!event) { return false; @@ -1532,8 +1446,7 @@ bool Creature::registerCreatureEvent(const std::string& name) return true; } -bool Creature::unregisterCreatureEvent(const std::string& name) -{ +bool Creature::unregisterCreatureEvent(const std::string &name) { const CreatureEvent* event = g_creatureEvents().getEventByName(name); if (!event) { return false; @@ -1566,8 +1479,7 @@ bool Creature::unregisterCreatureEvent(const std::string& name) return true; } -CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) -{ +CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) { CreatureEventList tmpEventList; if (!hasEventRegistered(type)) { @@ -1583,9 +1495,7 @@ CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) return tmpEventList; } -bool FrozenPathingConditionCall::isInRange(const Position& startPos, const Position& testPos, - const FindPathParams& fpp) const -{ +bool FrozenPathingConditionCall::isInRange(const Position &startPos, const Position &testPos, const FindPathParams &fpp) const { if (fpp.fullPathSearch) { if (testPos.x > targetPos.x + fpp.maxTargetDist) { return false; @@ -1629,9 +1539,7 @@ bool FrozenPathingConditionCall::isInRange(const Position& startPos, const Posit } return true; } -bool FrozenPathingConditionCall::operator()(const Position& startPos, const Position& testPos, - const FindPathParams& fpp, int32_t& bestMatchDist) const -{ +bool FrozenPathingConditionCall::operator()(const Position &startPos, const Position &testPos, const FindPathParams &fpp, int32_t &bestMatchDist) const { if (!isInRange(startPos, testPos, fpp)) { return false; } @@ -1654,7 +1562,7 @@ bool FrozenPathingConditionCall::operator()(const Position& startPos, const Posi bestMatchDist = 0; return true; } else if (testDist > bestMatchDist) { - //not quite what we want, but the best so far + // not quite what we want, but the best so far bestMatchDist = testDist; return true; } @@ -1662,20 +1570,18 @@ bool FrozenPathingConditionCall::operator()(const Position& startPos, const Posi return false; } -bool Creature::isInvisible() const -{ - return std::find_if(conditions.begin(), conditions.end(), [] (const Condition* condition) { - return condition->getType() == CONDITION_INVISIBLE; - }) != conditions.end(); +bool Creature::isInvisible() const { + return std::find_if(conditions.begin(), conditions.end(), [](const Condition* condition) { + return condition->getType() == CONDITION_INVISIBLE; + }) + != conditions.end(); } -bool Creature::getPathTo(const Position& targetPos, std::forward_list& dirList, const FindPathParams& fpp) const -{ +bool Creature::getPathTo(const Position &targetPos, std::forward_list &dirList, const FindPathParams &fpp) const { return g_game().map.getPathMatching(*this, dirList, FrozenPathingConditionCall(targetPos), fpp); } -bool Creature::getPathTo(const Position& targetPos, std::forward_list& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch /*= true*/, bool clearSight /*= true*/, int32_t maxSearchDist /*= 0*/) const -{ +bool Creature::getPathTo(const Position &targetPos, std::forward_list &dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch /*= true*/, bool clearSight /*= true*/, int32_t maxSearchDist /*= 0*/) const { FindPathParams fpp; fpp.fullPathSearch = fullPathSearch; fpp.maxSearchDist = maxSearchDist; @@ -1685,9 +1591,8 @@ bool Creature::getPathTo(const Position& targetPos, std::forward_list return getPathTo(targetPos, dirList, fpp); } -void Creature::turnToCreature(Creature* creature) -{ - const Position& creaturePos = creature->getPosition(); +void Creature::turnToCreature(Creature* creature) { + const Position &creaturePos = creature->getPosition(); const auto dx = Position::getOffsetX(position, creaturePos); const auto dy = Position::getOffsetY(position, creaturePos); @@ -1720,8 +1625,7 @@ bool Creature::isLostSummon() const { return false; } const Position &masterPosition = getMaster()->getPosition(); - return std::max(Position::getDistanceX(getPosition(), masterPosition), - Position::getDistanceY(getPosition(), masterPosition)) > 30; + return std::max(Position::getDistanceX(getPosition(), masterPosition), Position::getDistanceY(getPosition(), masterPosition)) > 30; } void Creature::handleLostSummon(bool teleportSummons) { diff --git a/src/creatures/creature.h b/src/creatures/creature.h index 63efd2d26de..e8891616815 100644 --- a/src/creatures/creature.h +++ b/src/creatures/creature.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_CREATURE_H_ #define SRC_CREATURES_CREATURE_H_ @@ -34,16 +34,14 @@ static constexpr int32_t EVENT_CREATURECOUNT = 10; static constexpr int32_t EVENT_CREATURE_THINK_INTERVAL = 1000; static constexpr int32_t EVENT_CHECK_CREATURE_INTERVAL = (EVENT_CREATURE_THINK_INTERVAL / EVENT_CREATURECOUNT); -class FrozenPathingConditionCall -{ +class FrozenPathingConditionCall { public: - explicit FrozenPathingConditionCall(Position newTargetPos) : targetPos(std::move(newTargetPos)) {} + explicit FrozenPathingConditionCall(Position newTargetPos) : + targetPos(std::move(newTargetPos)) { } - bool operator()(const Position& startPos, const Position& testPos, - const FindPathParams& fpp, int32_t& bestMatchDist) const; + bool operator()(const Position &startPos, const Position &testPos, const FindPathParams &fpp, int32_t &bestMatchDist) const; - bool isInRange(const Position& startPos, const Position& testPos, - const FindPathParams& fpp) const; + bool isInRange(const Position &startPos, const Position &testPos, const FindPathParams &fpp) const; private: Position targetPos; @@ -53,8 +51,7 @@ class FrozenPathingConditionCall // Defines the Base class for all creatures and base functions which // every creature has -class Creature : virtual public Thing -{ +class Creature : virtual public Thing { protected: Creature(); @@ -64,8 +61,8 @@ class Creature : virtual public Thing virtual ~Creature(); // non-copyable - Creature(const Creature&) = delete; - Creature& operator=(const Creature&) = delete; + Creature(const Creature &) = delete; + Creature &operator=(const Creature &) = delete; Creature* getCreature() override final { return this; @@ -92,10 +89,10 @@ class Creature : virtual public Thing return nullptr; } - virtual const std::string& getName() const = 0; + virtual const std::string &getName() const = 0; // Real creature name, set on creature creation "createNpcType(typeName) and createMonsterType(typeName)" - virtual const std::string& getTypeName() const = 0; - virtual const std::string& getNameDescription() const = 0; + virtual const std::string &getTypeName() const = 0; + virtual const std::string &getNameDescription() const = 0; virtual CreatureType_t getType() const = 0; @@ -110,7 +107,7 @@ class Creature : virtual public Thing virtual void removeList() = 0; virtual void addList() = 0; - virtual bool canSee(const Position& pos) const; + virtual bool canSee(const Position &pos) const; virtual bool canSeeCreature(const Creature* creature) const; virtual RaceType_t getRace() const { @@ -195,29 +192,29 @@ class Creature : virtual public Thing return mana; } - uint16_t getManaShield() const { - return manaShield; - } + uint16_t getManaShield() const { + return manaShield; + } - void setManaShield(uint16_t value) { - manaShield = value; - } + void setManaShield(uint16_t value) { + manaShield = value; + } - uint16_t getMaxManaShield() const { - return maxManaShield; - } + uint16_t getMaxManaShield() const { + return maxManaShield; + } - void setMaxManaShield(uint16_t value) { - maxManaShield = value; - } + void setMaxManaShield(uint16_t value) { + maxManaShield = value; + } - int32_t getBuff(int32_t buff) { - return varBuffs[buff]; - } + int32_t getBuff(int32_t buff) { + return varBuffs[buff]; + } - void setBuff(buffs_t buff, int32_t modifier) { - varBuffs[buff] += modifier; - } + void setBuff(buffs_t buff, int32_t modifier) { + varBuffs[buff] += modifier; + } virtual CreatureIcon_t getIcon() const { return CREATUREICON_NONE; @@ -237,34 +234,33 @@ class Creature : virtual public Thing return getTile()->getZone(); } - //walk functions - void startAutoWalk(const std::forward_list& listDir); + // walk functions + void startAutoWalk(const std::forward_list &listDir); void addEventWalk(bool firstStep = false); void stopEventWalk(); virtual void goToFollowCreature(); - //walk events - virtual void onWalk(Direction& dir); - virtual void onWalkAborted() {} - virtual void onWalkComplete() {} + // walk events + virtual void onWalk(Direction &dir); + virtual void onWalkAborted() { } + virtual void onWalkComplete() { } - //follow functions + // follow functions Creature* getFollowCreature() const { return followCreature; } virtual bool setFollowCreature(Creature* creature); - //follow events - virtual void onFollowCreature(const Creature*) {} - virtual void onFollowCreatureComplete(const Creature*) {} + // follow events + virtual void onFollowCreature(const Creature*) { } + virtual void onFollowCreatureComplete(const Creature*) { } - //combat functions + // combat functions Creature* getAttackedCreature() { return attackedCreature; } virtual bool setAttackedCreature(Creature* creature); - virtual BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, - bool checkDefense = false, bool checkArmor = false, bool field = false); + virtual BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false); bool setMaster(Creature* newMaster, bool reloadCreature = false); @@ -280,8 +276,8 @@ class Creature : virtual public Thing } /** - * hasBeenSummoned doesn't guarantee master still exists - */ + * hasBeenSummoned doesn't guarantee master still exists + */ bool hasBeenSummoned() const { return summoned; } @@ -289,7 +285,7 @@ class Creature : virtual public Thing return master; } - const std::list& getSummons() const { + const std::list &getSummons() const { return summons; } @@ -355,21 +351,21 @@ class Creature : virtual public Thing void addDamagePoints(Creature* attacker, int32_t damagePoints); bool hasBeenAttacked(uint32_t attackerId); - //combat event functions + // combat event functions virtual void onAddCondition(ConditionType_t type); virtual void onAddCombatCondition(ConditionType_t type); virtual void onEndCondition(ConditionType_t type); - void onTickCondition(ConditionType_t type, bool& bRemove); + void onTickCondition(ConditionType_t type, bool &bRemove); virtual void onCombatRemoveCondition(Condition* condition); - virtual void onAttackedCreature(Creature*) {} + virtual void onAttackedCreature(Creature*) { } virtual void onAttacked(); virtual void onAttackedCreatureDrainHealth(Creature* target, int32_t points); - virtual void onTargetCreatureGainHealth(Creature*, int32_t) {} + virtual void onTargetCreatureGainHealth(Creature*, int32_t) { } void onAttackedCreatureKilled(Creature* target); virtual bool onKilledCreature(Creature* target, bool lastHit = true); virtual void onGainExperience(uint64_t gainExp, Creature* target); - virtual void onAttackedCreatureBlockHit(BlockType_t) {} - virtual void onBlockHit() {} + virtual void onAttackedCreatureBlockHit(BlockType_t) { } + virtual void onBlockHit() { } virtual void onChangeZone(ZoneType_t zone); virtual void onAttackedCreatureChangeZone(ZoneType_t zone); virtual void onIdleStatus(); @@ -381,15 +377,13 @@ class Creature : virtual public Thing virtual void onThink(uint32_t interval); void onAttacking(uint32_t interval); virtual void onCreatureWalk(); - virtual bool getNextStep(Direction& dir, uint32_t& flags); + virtual bool getNextStep(Direction &dir, uint32_t &flags); virtual void turnToCreature(Creature* creature); - void onAddTileItem(const Tile* tile, const Position& pos); - virtual void onUpdateTileItem(const Tile* tile, const Position& pos, const Item* oldItem, - const ItemType& oldType, const Item* newItem, const ItemType& newType); - virtual void onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, - const Item* item); + void onAddTileItem(const Tile* tile, const Position &pos); + virtual void onUpdateTileItem(const Tile* tile, const Position &pos, const Item* oldItem, const ItemType &oldType, const Item* newItem, const ItemType &newType); + virtual void onRemoveTileItem(const Tile* tile, const Position &pos, const ItemType &iType, const Item* item); virtual void onCreatureAppear(Creature* creature, bool isLogin); virtual void onRemoveCreature(Creature* creature, bool isLogout); @@ -402,18 +396,17 @@ class Creature : virtual public Thing * @return true * @return false */ - void checkSummonMove(const Position& newPos, bool teleportSummon = false) const; - virtual void onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport); + void checkSummonMove(const Position &newPos, bool teleportSummon = false) const; + virtual void onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport); - virtual void onAttackedCreatureDisappear(bool) {} - virtual void onFollowCreatureDisappear(bool) {} + virtual void onAttackedCreatureDisappear(bool) { } + virtual void onFollowCreatureDisappear(bool) { } - virtual void onCreatureSay(Creature*, SpeakClasses, const std::string&) {} + virtual void onCreatureSay(Creature*, SpeakClasses, const std::string &) { } - virtual void onPlacedCreature() {} + virtual void onPlacedCreature() { } - virtual bool getCombatValues(int32_t&, int32_t&) { + virtual bool getCombatValues(int32_t &, int32_t &) { return false; } @@ -444,9 +437,9 @@ class Creature : virtual public Thing canUseDefense = useDefense; } - //creature script events - bool registerCreatureEvent(const std::string& name); - bool unregisterCreatureEvent(const std::string& name); + // creature script events + bool registerCreatureEvent(const std::string &name); + bool unregisterCreatureEvent(const std::string &name); Cylinder* getParent() const override final { return tile; @@ -456,7 +449,7 @@ class Creature : virtual public Thing position = tile->getPosition(); } - const Position& getPosition() const override final { + const Position &getPosition() const override final { return position; } @@ -467,21 +460,21 @@ class Creature : virtual public Thing return tile; } - int32_t getWalkCache(const Position& pos) const; + int32_t getWalkCache(const Position &pos) const; - const Position& getLastPosition() const { + const Position &getLastPosition() const { return lastPosition; } void setLastPosition(Position newLastPos) { lastPosition = newLastPos; } - static bool canSee(const Position& myPos, const Position& pos, int32_t viewRangeX, int32_t viewRangeY); + static bool canSee(const Position &myPos, const Position &pos, int32_t viewRangeX, int32_t viewRangeY); double getDamageRatio(Creature* attacker) const; - bool getPathTo(const Position& targetPos, std::forward_list& dirList, const FindPathParams& fpp) const; - bool getPathTo(const Position& targetPos, std::forward_list& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 0) const; + bool getPathTo(const Position &targetPos, std::forward_list &dirList, const FindPathParams &fpp) const; + bool getPathTo(const Position &targetPos, std::forward_list &dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 0) const; void incrementReferenceCounter() { ++referenceCounter; @@ -492,12 +485,12 @@ class Creature : virtual public Thing } } struct CountBlock_t { - int32_t total; - int64_t ticks; + int32_t total; + int64_t ticks; }; using CountMap = std::map; CountMap getDamageMap() const { - return damageMap; + return damageMap; } protected: @@ -526,13 +519,13 @@ class Creature : virtual public Thing Creature* followCreature = nullptr; /** - * We need to persist if this creature is summon or not because when we - * increment the bestiary count, the master might be gone before we can - * check if this summon has a master and mistakenly count it kill. - * - * @see BestiaryOnKill - * @see Monster::death() - */ + * We need to persist if this creature is summon or not because when we + * increment the bestiary count, the master might be gone before we can + * check if this summon has a master and mistakenly count it kill. + * + * @see BestiaryOnKill + * @see Monster::death() + */ bool summoned = false; uint64_t lastStep = 0; @@ -564,7 +557,7 @@ class Creature : virtual public Thing Direction direction = DIRECTION_SOUTH; Skulls_t skull = SKULL_NONE; - bool localMapCache[mapWalkHeight][mapWalkWidth] = {{ false }}; + bool localMapCache[mapWalkHeight][mapWalkWidth] = { { false } }; bool isInternalRemoved = false; bool isMapLoaded = false; bool isUpdatingPath = false; @@ -580,7 +573,7 @@ class Creature : virtual public Thing bool canUseDefense = true; bool moveLocked = false; - //creature script events + // creature script events bool hasEventRegistered(CreatureEventType_t event) const { return (0 != (scriptEventsBitField & (static_cast(1) << event))); } @@ -588,9 +581,9 @@ class Creature : virtual public Thing void updateMapCache(); void updateTileCache(const Tile* tile, int32_t dx, int32_t dy); - void updateTileCache(const Tile* tile, const Position& pos); + void updateTileCache(const Tile* tile, const Position &pos); void onCreatureDisappear(const Creature* creature, bool isLogout); - virtual void doAttacking(uint32_t) {} + virtual void doAttacking(uint32_t) { } virtual bool hasExtraSwing() { return false; } @@ -598,12 +591,12 @@ class Creature : virtual public Thing virtual uint64_t getLostExperience() const { return 0; } - virtual void dropLoot(Container*, Creature*) {} + virtual void dropLoot(Container*, Creature*) { } virtual uint16_t getLookCorpse() const { return 0; } - virtual void getPathSearchParams(const Creature* creature, FindPathParams& fpp) const; - virtual void death(Creature*) {} + virtual void getPathSearchParams(const Creature* creature, FindPathParams &fpp) const; + virtual void death(Creature*) { } virtual bool dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); virtual Item* getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature); @@ -617,4 +610,4 @@ class Creature : virtual public Thing void handleLostSummon(bool teleportSummons); }; -#endif // SRC_CREATURES_CREATURE_H_ +#endif // SRC_CREATURES_CREATURE_H_ diff --git a/src/creatures/creatures_definitions.hpp b/src/creatures/creatures_definitions.hpp index f67c4ab6519..6b4185970fc 100644 --- a/src/creatures/creatures_definitions.hpp +++ b/src/creatures/creatures_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_CREATURES_DEFINITIONS_HPP_ #define SRC_CREATURES_CREATURES_DEFINITIONS_HPP_ @@ -58,7 +58,7 @@ enum ConditionAttr_t { CONDITIONATTR_SUBID, CONDITIONATTR_MANASHIELD, - //reserved for serialization + // reserved for serialization CONDITIONATTR_END = 254, }; @@ -99,7 +99,7 @@ enum ConditionType_t { enum ConditionParam_t { CONDITION_PARAM_OWNER = 1, CONDITION_PARAM_TICKS = 2, - //CONDITION_PARAM_OUTFIT = 3, + // CONDITION_PARAM_OUTFIT = 3, CONDITION_PARAM_HEALTHGAIN = 4, CONDITION_PARAM_HEALTHTICKS = 5, CONDITION_PARAM_MANAGAIN = 6, @@ -590,128 +590,128 @@ enum PartyAnalyzer_t : uint8_t { struct Position; struct VIPEntry { - VIPEntry(uint32_t initGuid, std::string initName, std::string initDescription, - uint32_t initIcon, bool initNotify) : - guid(initGuid), - name(std::move(initName)), - description(std::move(initDescription)), - icon(initIcon), - notify(initNotify) {} + VIPEntry(uint32_t initGuid, std::string initName, std::string initDescription, uint32_t initIcon, bool initNotify) : + guid(initGuid), + name(std::move(initName)), + description(std::move(initDescription)), + icon(initIcon), + notify(initNotify) { } - uint32_t guid; - std::string name; - std::string description; - uint32_t icon; - bool notify; + uint32_t guid; + std::string name; + std::string description; + uint32_t icon; + bool notify; }; struct OutfitEntry { - constexpr OutfitEntry(uint16_t initLookType, uint8_t initAddons) : - lookType(initLookType), addons(initAddons) {} + constexpr OutfitEntry(uint16_t initLookType, uint8_t initAddons) : + lookType(initLookType), addons(initAddons) { } - uint16_t lookType; - uint8_t addons; + uint16_t lookType; + uint8_t addons; }; struct FamiliarEntry { - constexpr explicit FamiliarEntry(uint16_t initLookType) : lookType(initLookType) {} - uint16_t lookType; + constexpr explicit FamiliarEntry(uint16_t initLookType) : + lookType(initLookType) { } + uint16_t lookType; }; struct Skill { - uint64_t tries = 0; - uint16_t level = 10; - double_t percent = 0; + uint64_t tries = 0; + uint16_t level = 10; + double_t percent = 0; }; struct Kill { - uint32_t target; - time_t time; - bool unavenged; + uint32_t target; + time_t time; + bool unavenged; - Kill(uint32_t _target, time_t _time, bool _unavenged) : - target(_target), time(_time), unavenged(_unavenged) {} + Kill(uint32_t _target, time_t _time, bool _unavenged) : + target(_target), time(_time), unavenged(_unavenged) { } }; struct IntervalInfo { - int32_t timeLeft; - int32_t value; - int32_t interval; + int32_t timeLeft; + int32_t value; + int32_t interval; }; struct FindPathParams { - bool fullPathSearch = true; - bool clearSight = true; - bool allowDiagonal = true; - bool keepDistance = false; - int32_t maxSearchDist = 0; - int32_t minTargetDist = -1; - int32_t maxTargetDist = -1; + bool fullPathSearch = true; + bool clearSight = true; + bool allowDiagonal = true; + bool keepDistance = false; + int32_t maxSearchDist = 0; + int32_t minTargetDist = -1; + int32_t maxTargetDist = -1; }; struct RecentDeathEntry { - RecentDeathEntry(std::string cause, uint32_t timestamp) : - cause(std::move(cause)), - timestamp(timestamp) {} + RecentDeathEntry(std::string cause, uint32_t timestamp) : + cause(std::move(cause)), + timestamp(timestamp) { } - std::string cause; - uint32_t timestamp; + std::string cause; + uint32_t timestamp; }; struct RecentPvPKillEntry { - RecentPvPKillEntry(std::string description, uint32_t timestamp, uint8_t status) : - description(std::move(description)), - timestamp(timestamp), - status(status) {} + RecentPvPKillEntry(std::string description, uint32_t timestamp, uint8_t status) : + description(std::move(description)), + timestamp(timestamp), + status(status) { } - std::string description; - uint32_t timestamp; - uint8_t status; + std::string description; + uint32_t timestamp; + uint8_t status; }; struct MarketOffer { - uint64_t price; - uint32_t timestamp; - uint16_t amount; - uint16_t counter; - uint16_t itemId; - uint8_t tier; - std::string playerName; + uint64_t price; + uint32_t timestamp; + uint16_t amount; + uint16_t counter; + uint16_t itemId; + uint8_t tier; + std::string playerName; }; struct MarketOfferEx { - MarketOfferEx() = default; - MarketOfferEx(MarketOfferEx&& other) : - id(other.id), - playerId(other.playerId), - timestamp(other.timestamp), - price(other.price), - amount(other.amount), - counter(other.counter), - itemId(other.itemId), - type(other.type), - tier(other.tier), - playerName(std::move(other.playerName)) {} - - uint32_t id; - uint32_t playerId; - uint32_t timestamp; - uint64_t price; - uint16_t amount; - uint16_t counter; - uint16_t itemId; - MarketAction_t type; - uint8_t tier; - std::string playerName; + MarketOfferEx() = default; + MarketOfferEx(MarketOfferEx &&other) : + id(other.id), + playerId(other.playerId), + timestamp(other.timestamp), + price(other.price), + amount(other.amount), + counter(other.counter), + itemId(other.itemId), + type(other.type), + tier(other.tier), + playerName(std::move(other.playerName)) { } + + uint32_t id; + uint32_t playerId; + uint32_t timestamp; + uint64_t price; + uint16_t amount; + uint16_t counter; + uint16_t itemId; + MarketAction_t type; + uint8_t tier; + std::string playerName; }; struct HistoryMarketOffer { - uint32_t timestamp; - uint64_t price; - uint16_t itemId; - uint16_t amount; - uint8_t tier; - MarketOfferState_t state; + uint32_t timestamp; + uint64_t price; + uint16_t itemId; + uint16_t amount; + uint8_t tier; + MarketOfferState_t state; }; using MarketOfferList = std::list; @@ -729,174 +729,174 @@ using ItemsTierCountList = std::map>; */ struct Familiar { - Familiar(std::string initName, uint16_t initLookType, - bool initPremium, bool initUnlocked, std::string initType) : - name(initName), lookType(initLookType), - premium(initPremium), unlocked(initUnlocked), - type(initType) {} + Familiar(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initType) : + name(initName), lookType(initLookType), + premium(initPremium), unlocked(initUnlocked), + type(initType) { } - std::string name; - uint16_t lookType; - bool premium; - bool unlocked; - std::string type; + std::string name; + uint16_t lookType; + bool premium; + bool unlocked; + std::string type; }; struct ProtocolFamiliars { - ProtocolFamiliars(const std::string& initName, uint16_t initLookType) : - name(initName), lookType(initLookType) {} + ProtocolFamiliars(const std::string &initName, uint16_t initLookType) : + name(initName), lookType(initLookType) { } - const std::string& name; - uint16_t lookType; + const std::string &name; + uint16_t lookType; }; struct LightInfo { - uint8_t level = 0; - uint8_t color = 0; - constexpr LightInfo() = default; - constexpr LightInfo(uint8_t newLevel, uint8_t newColor) : level(newLevel), color(newColor) {} + uint8_t level = 0; + uint8_t color = 0; + constexpr LightInfo() = default; + constexpr LightInfo(uint8_t newLevel, uint8_t newColor) : + level(newLevel), color(newColor) { } }; struct CombatDamage { - struct { - CombatType_t type; - int32_t value; - } primary, secondary; - - CombatOrigin origin; - bool critical; - int affected; - bool extension; - std::string exString; - bool fatal; - - CombatDamage() { - origin = ORIGIN_NONE; - primary.type = secondary.type = COMBAT_NONE; - primary.value = secondary.value = 0; - critical = false; - affected = 1; - extension = false; - exString = ""; - fatal = false; - } + struct { + CombatType_t type; + int32_t value; + } primary, secondary; + + CombatOrigin origin; + bool critical; + int affected; + bool extension; + std::string exString; + bool fatal; + + CombatDamage() { + origin = ORIGIN_NONE; + primary.type = secondary.type = COMBAT_NONE; + primary.value = secondary.value = 0; + critical = false; + affected = 1; + extension = false; + exString = ""; + fatal = false; + } }; struct RespawnType { - RespawnPeriod_t period; - bool underground; + RespawnPeriod_t period; + bool underground; }; struct LootBlock; struct LootBlock { - uint16_t id; - uint32_t countmax; - uint32_t countmin; - uint32_t chance; - - //optional - int32_t subType; - int32_t actionId; - std::string text; - std::string name; - std::string article; - int32_t attack; - int32_t defense; - int32_t extraDefense; - int32_t armor; - int32_t shootRange; - int32_t hitChance; - bool unique; - - std::vector childLoot; - LootBlock() { - id = 0; - countmax = 1; - countmin = 1; - chance = 0; - - subType = -1; - actionId = -1; - attack = -1; - defense = -1; - extraDefense = -1; - armor = -1; - shootRange = -1; - hitChance = -1; - unique = false; - } + uint16_t id; + uint32_t countmax; + uint32_t countmin; + uint32_t chance; + + // optional + int32_t subType; + int32_t actionId; + std::string text; + std::string name; + std::string article; + int32_t attack; + int32_t defense; + int32_t extraDefense; + int32_t armor; + int32_t shootRange; + int32_t hitChance; + bool unique; + + std::vector childLoot; + LootBlock() { + id = 0; + countmax = 1; + countmin = 1; + chance = 0; + + subType = -1; + actionId = -1; + attack = -1; + defense = -1; + extraDefense = -1; + armor = -1; + shootRange = -1; + hitChance = -1; + unique = false; + } }; struct ShopBlock { - uint16_t itemId; - std::string itemName; - int32_t itemSubType; - uint32_t itemBuyPrice; - uint32_t itemSellPrice; - int32_t itemStorageKey; - int32_t itemStorageValue; - - std::vector childShop; - ShopBlock() { - itemId = 0; - itemName = ""; - itemSubType = 0; - itemBuyPrice = 0; - itemSellPrice = 0; - itemStorageKey = 0; - itemStorageValue = 0; - } - - explicit ShopBlock(uint16_t newItemId, int32_t newSubType = 0, uint32_t newBuyPrice = 0, uint32_t newSellPrice = 0, int32_t newStorageKey = 0, int32_t newStorageValue = 0, std::string newName = "") - : itemId(newItemId), itemSubType(newSubType), itemBuyPrice(newBuyPrice), itemSellPrice(newSellPrice), itemStorageKey(newStorageKey), itemStorageValue(newStorageValue), itemName(std::move(newName)) {} + uint16_t itemId; + std::string itemName; + int32_t itemSubType; + uint32_t itemBuyPrice; + uint32_t itemSellPrice; + int32_t itemStorageKey; + int32_t itemStorageValue; + + std::vector childShop; + ShopBlock() { + itemId = 0; + itemName = ""; + itemSubType = 0; + itemBuyPrice = 0; + itemSellPrice = 0; + itemStorageKey = 0; + itemStorageValue = 0; + } + + explicit ShopBlock(uint16_t newItemId, int32_t newSubType = 0, uint32_t newBuyPrice = 0, uint32_t newSellPrice = 0, int32_t newStorageKey = 0, int32_t newStorageValue = 0, std::string newName = "") : + itemId(newItemId), itemSubType(newSubType), itemBuyPrice(newBuyPrice), itemSellPrice(newSellPrice), itemStorageKey(newStorageKey), itemStorageValue(newStorageValue), itemName(std::move(newName)) { } }; struct summonBlock_t { - std::string name; - uint32_t chance; - uint32_t speed; - uint32_t count; - bool force = false; + std::string name; + uint32_t chance; + uint32_t speed; + uint32_t count; + bool force = false; }; struct Outfit_t { - uint16_t lookType = 0; - uint16_t lookTypeEx = 0; - uint16_t lookMount = 0; - uint8_t lookHead = 0; - uint8_t lookBody = 0; - uint8_t lookLegs = 0; - uint8_t lookFeet = 0; - uint8_t lookAddons = 0; - uint8_t lookMountHead = 0; - uint8_t lookMountBody = 0; - uint8_t lookMountLegs = 0; - uint8_t lookMountFeet = 0; - uint16_t lookFamiliarsType = 0; + uint16_t lookType = 0; + uint16_t lookTypeEx = 0; + uint16_t lookMount = 0; + uint8_t lookHead = 0; + uint8_t lookBody = 0; + uint8_t lookLegs = 0; + uint8_t lookFeet = 0; + uint8_t lookAddons = 0; + uint8_t lookMountHead = 0; + uint8_t lookMountBody = 0; + uint8_t lookMountLegs = 0; + uint8_t lookMountFeet = 0; + uint16_t lookFamiliarsType = 0; }; struct voiceBlock_t { - std::string text; - bool yellText; + std::string text; + bool yellText; }; struct PartyAnalyzer { - PartyAnalyzer(uint32_t playerId, std::string playerName) : - id(playerId), - name(std::move(playerName)) {} + PartyAnalyzer(uint32_t playerId, std::string playerName) : + id(playerId), + name(std::move(playerName)) { } - uint32_t id; + uint32_t id; - std::string name; + std::string name; - uint64_t damage = 0; - uint64_t healing = 0; - uint64_t lootPrice = 0; - uint64_t supplyPrice = 0; + uint64_t damage = 0; + uint64_t healing = 0; + uint64_t lootPrice = 0; + uint64_t supplyPrice = 0; - std::map lootMap; // [itemID] = amount - std::map supplyMap; // [itemID] = amount + std::map lootMap; // [itemID] = amount + std::map supplyMap; // [itemID] = amount }; -#endif // SRC_CREATURES_CREATURES_DEFINITIONS_HPP_ +#endif // SRC_CREATURES_CREATURES_DEFINITIONS_HPP_ diff --git a/src/creatures/interactions/chat.cpp b/src/creatures/interactions/chat.cpp index 3ff14adf5b1..a834354de3c 100644 --- a/src/creatures/interactions/chat.cpp +++ b/src/creatures/interactions/chat.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,21 +14,18 @@ #include "utils/pugicast.h" #include "game/scheduling/scheduler.h" -bool PrivateChatChannel::isInvited(uint32_t guid) const -{ +bool PrivateChatChannel::isInvited(uint32_t guid) const { if (guid == getOwner()) { return true; } return invites.find(guid) != invites.end(); } -bool PrivateChatChannel::removeInvite(uint32_t guid) -{ +bool PrivateChatChannel::removeInvite(uint32_t guid) { return invites.erase(guid) != 0; } -void PrivateChatChannel::invitePlayer(const Player& player, Player& invitePlayer) -{ +void PrivateChatChannel::invitePlayer(const Player &player, Player &invitePlayer) { auto result = invites.emplace(invitePlayer.getGUID(), &invitePlayer); if (!result.second) { return; @@ -42,13 +39,12 @@ void PrivateChatChannel::invitePlayer(const Player& player, Player& invitePlayer ss << invitePlayer.getName() << " has been invited."; player.sendTextMessage(MESSAGE_PARTY_MANAGEMENT, ss.str()); - for (const auto& it : users) { + for (const auto &it : users) { it.second->sendChannelEvent(id, invitePlayer.getName(), CHANNELEVENT_INVITE); } } -void PrivateChatChannel::excludePlayer(const Player& player, Player& excludePlayer) -{ +void PrivateChatChannel::excludePlayer(const Player &player, Player &excludePlayer) { if (!removeInvite(excludePlayer.getGUID())) { return; } @@ -61,20 +57,18 @@ void PrivateChatChannel::excludePlayer(const Player& player, Player& excludePlay excludePlayer.sendClosePrivate(id); - for (const auto& it : users) { + for (const auto &it : users) { it.second->sendChannelEvent(id, excludePlayer.getName(), CHANNELEVENT_EXCLUDE); } } -void PrivateChatChannel::closeChannel() const -{ - for (const auto& it : users) { +void PrivateChatChannel::closeChannel() const { + for (const auto &it : users) { it.second->sendClosePrivate(id); } } -bool ChatChannel::addUser(Player& player) -{ +bool ChatChannel::addUser(Player &player) { if (users.find(player.getID()) != users.end()) { return false; } @@ -92,7 +86,7 @@ bool ChatChannel::addUser(Player& player) } if (!publicChannel) { - for (const auto& it : users) { + for (const auto &it : users) { it.second->sendChannelEvent(id, player.getName(), CHANNELEVENT_JOIN); } } @@ -101,8 +95,7 @@ bool ChatChannel::addUser(Player& player) return true; } -bool ChatChannel::removeUser(const Player& player) -{ +bool ChatChannel::removeUser(const Player &player) { auto iter = users.find(player.getID()); if (iter == users.end()) { return false; @@ -111,7 +104,7 @@ bool ChatChannel::removeUser(const Player& player) users.erase(iter); if (!publicChannel) { - for (const auto& it : users) { + for (const auto &it : users) { it.second->sendChannelEvent(id, player.getName(), CHANNELEVENT_LEAVE); } } @@ -120,41 +113,38 @@ bool ChatChannel::removeUser(const Player& player) return true; } -bool ChatChannel::hasUser(const Player& player) { +bool ChatChannel::hasUser(const Player &player) { return users.find(player.getID()) != users.end(); } -void ChatChannel::sendToAll(const std::string& message, SpeakClasses type) const -{ - for (const auto& it : users) { +void ChatChannel::sendToAll(const std::string &message, SpeakClasses type) const { + for (const auto &it : users) { it.second->sendChannelMessage("", message, type, id); } } -bool ChatChannel::talk(const Player& fromPlayer, SpeakClasses type, const std::string& text) -{ +bool ChatChannel::talk(const Player &fromPlayer, SpeakClasses type, const std::string &text) { if (users.find(fromPlayer.getID()) == users.end()) { return false; } - for (const auto& it : users) { + for (const auto &it : users) { it.second->sendToChannel(&fromPlayer, type, text, id); } return true; } -bool ChatChannel::executeCanJoinEvent(const Player& player) -{ +bool ChatChannel::executeCanJoinEvent(const Player &player) { if (canJoinEvent == -1) { return true; } - //canJoin(player) + // canJoin(player) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[CanJoinChannelEvent::execute - Player {}, on channel {}] " - "Call stack overflow. Too many lua script calls being nested.", - player.getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + player.getName(), getName()); return false; } @@ -170,18 +160,17 @@ bool ChatChannel::executeCanJoinEvent(const Player& player) return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnJoinEvent(const Player& player) -{ +bool ChatChannel::executeOnJoinEvent(const Player &player) { if (onJoinEvent == -1) { return true; } - //onJoin(player) + // onJoin(player) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[OnJoinChannelEvent::execute - Player {}, on channel {}] " - "Call stack overflow. Too many lua script calls being nested", - player.getName(), getName()); + "Call stack overflow. Too many lua script calls being nested", + player.getName(), getName()); return false; } @@ -197,18 +186,17 @@ bool ChatChannel::executeOnJoinEvent(const Player& player) return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnLeaveEvent(const Player& player) -{ +bool ChatChannel::executeOnLeaveEvent(const Player &player) { if (onLeaveEvent == -1) { return true; } - //onLeave(player) + // onLeave(player) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[OnLeaveChannelEvent::execute - Player {}, on channel {}] " - "Call stack overflow. Too many lua script calls being nested.", - player.getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + player.getName(), getName()); return false; } @@ -224,18 +212,17 @@ bool ChatChannel::executeOnLeaveEvent(const Player& player) return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnSpeakEvent(const Player& player, SpeakClasses& type, const std::string& message) -{ +bool ChatChannel::executeOnSpeakEvent(const Player &player, SpeakClasses &type, const std::string &message) { if (onSpeakEvent == -1) { return true; } - //onSpeak(player, type, message) + // onSpeak(player, type, message) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[OnSpeakChannelEvent::execute - Player {}, type {}] " - "Call stack overflow. Too many lua script calls being nested.", - player.getName(), type); + "Call stack overflow. Too many lua script calls being nested.", + player.getName(), type); return false; } @@ -273,15 +260,13 @@ bool ChatChannel::executeOnSpeakEvent(const Player& player, SpeakClasses& type, return result; } -Chat::Chat(): +Chat::Chat() : scriptInterface("Chat Interface"), - dummyPrivate(CHANNEL_PRIVATE, "Private Chat Channel") -{ + dummyPrivate(CHANNEL_PRIVATE, "Private Chat Channel") { scriptInterface.initState(); } -bool Chat::load() -{ +bool Chat::load() { pugi::xml_document doc; auto coreFolder = g_configManager().getString(CORE_DIRECTORY); auto folder = coreFolder + "/chatchannels/chatchannels.xml"; @@ -299,7 +284,7 @@ bool Chat::load() auto it = normalChannels.find(channelId); if (it != normalChannels.end()) { - ChatChannel& channel = it->second; + ChatChannel &channel = it->second; channel.publicChannel = isPublic; channel.name = channelName; @@ -310,13 +295,12 @@ bool Chat::load() channel.onJoinEvent = scriptInterface.getEvent("onJoin"); channel.onLeaveEvent = scriptInterface.getEvent("onLeave"); } else { - SPDLOG_WARN("[Chat::load] - Can not load script: {}", - scriptAttribute.as_string()); + SPDLOG_WARN("[Chat::load] - Can not load script: {}", scriptAttribute.as_string()); } } UsersMap tempUserMap = std::move(channel.users); - for (const auto& pair : tempUserMap) { + for (const auto &pair : tempUserMap) { channel.addUser(*pair.second); } continue; @@ -332,8 +316,7 @@ bool Chat::load() channel.onJoinEvent = scriptInterface.getEvent("onJoin"); channel.onLeaveEvent = scriptInterface.getEvent("onLeave"); } else { - SPDLOG_WARN("[Chat::load] Can not load script: {}", - scriptAttribute.as_string()); + SPDLOG_WARN("[Chat::load] Can not load script: {}", scriptAttribute.as_string()); } } @@ -342,8 +325,7 @@ bool Chat::load() return true; } -ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) -{ +ChatChannel* Chat::createChannel(const Player &player, uint16_t channelId) { if (getChannel(player, channelId) != nullptr) { return nullptr; } @@ -368,16 +350,16 @@ ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) } case CHANNEL_PRIVATE: { - //only 1 private channel for each premium player + // only 1 private channel for each premium player if (!player.isPremium() || (getPrivateChannel(player) != nullptr)) { return nullptr; } - //find a free private channel slot + // find a free private channel slot for (uint16_t i = 100; i < 10000; ++i) { auto ret = privateChannels.emplace(std::make_pair(i, PrivateChatChannel(i, player.getName() + "'s Channel"))); - if (ret.second) { //second is a bool that indicates that a new channel has been placed in the map - auto& newChannel = (*ret.first).second; + if (ret.second) { // second is a bool that indicates that a new channel has been placed in the map + auto &newChannel = (*ret.first).second; newChannel.setOwner(player.getGUID()); return &newChannel; } @@ -391,8 +373,7 @@ ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) return nullptr; } -bool Chat::deleteChannel(const Player& player, uint16_t channelId) -{ +bool Chat::deleteChannel(const Player &player, uint16_t channelId) { switch (channelId) { case CHANNEL_GUILD: { Guild* guild = player.getGuild(); @@ -439,8 +420,7 @@ bool Chat::deleteChannel(const Player& player, uint16_t channelId) return true; } -ChatChannel* Chat::addUserToChannel(Player& player, uint16_t channelId) -{ +ChatChannel* Chat::addUserToChannel(Player &player, uint16_t channelId) { ChatChannel* channel = getChannel(player, channelId); if ((channel != nullptr) && channel->addUser(player)) { return channel; @@ -448,8 +428,7 @@ ChatChannel* Chat::addUserToChannel(Player& player, uint16_t channelId) return nullptr; } -bool Chat::removeUserFromChannel(const Player& player, uint16_t channelId) -{ +bool Chat::removeUserFromChannel(const Player &player, uint16_t channelId) { ChatChannel* channel = getChannel(player, channelId); if ((channel == nullptr) || !channel->removeUser(player)) { return false; @@ -461,17 +440,16 @@ bool Chat::removeUserFromChannel(const Player& player, uint16_t channelId) return true; } -void Chat::removeUserFromAllChannels(const Player& player) -{ - for (auto& it : normalChannels) { +void Chat::removeUserFromAllChannels(const Player &player) { + for (auto &it : normalChannels) { it.second.removeUser(player); } - for (auto& it : partyChannels) { + for (auto &it : partyChannels) { it.second.removeUser(player); } - for (auto& it : guildChannels) { + for (auto &it : guildChannels) { it.second.removeUser(player); } @@ -489,8 +467,7 @@ void Chat::removeUserFromAllChannels(const Player& player) } } -bool Chat::talkToChannel(const Player& player, SpeakClasses type, const std::string& text, uint16_t channelId) -{ +bool Chat::talkToChannel(const Player &player, SpeakClasses type, const std::string &text, uint16_t channelId) { ChatChannel* channel = getChannel(player, channelId); if (channel == nullptr) { return false; @@ -514,8 +491,7 @@ bool Chat::talkToChannel(const Player& player, SpeakClasses type, const std::str return channel->talk(player, type, text); } -ChannelList Chat::getChannelList(const Player& player) -{ +ChannelList Chat::getChannelList(const Player &player) { ChannelList list; if (player.getGuild()) { ChatChannel* channel = getChannel(player, CHANNEL_GUILD); @@ -541,7 +517,7 @@ ChannelList Chat::getChannelList(const Player& player) } } - for (const auto& it : normalChannels) { + for (const auto &it : normalChannels) { ChatChannel* channel = getChannel(player, it.first); if (channel) { list.push_back(channel); @@ -549,7 +525,7 @@ ChannelList Chat::getChannelList(const Player& player) } bool hasPrivate = false; - for (auto& it : privateChannels) { + for (auto &it : privateChannels) { if (PrivateChatChannel* channel = &it.second) { uint32_t guid = player.getGUID(); if (channel->isInvited(guid)) { @@ -568,8 +544,7 @@ ChannelList Chat::getChannelList(const Player& player) return list; } -ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) -{ +ChatChannel* Chat::getChannel(const Player &player, uint16_t channelId) { switch (channelId) { case CHANNEL_GUILD: { Guild* guild = player.getGuild(); @@ -596,7 +571,7 @@ ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) default: { auto it = normalChannels.find(channelId); if (it != normalChannels.end()) { - ChatChannel& channel = it->second; + ChatChannel &channel = it->second; if (!channel.executeCanJoinEvent(player)) { return nullptr; } @@ -613,8 +588,7 @@ ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) return nullptr; } -ChatChannel* Chat::getGuildChannelById(uint32_t guildId) -{ +ChatChannel* Chat::getGuildChannelById(uint32_t guildId) { auto it = guildChannels.find(guildId); if (it == guildChannels.end()) { return nullptr; @@ -622,8 +596,7 @@ ChatChannel* Chat::getGuildChannelById(uint32_t guildId) return &it->second; } -ChatChannel* Chat::getChannelById(uint16_t channelId) -{ +ChatChannel* Chat::getChannelById(uint16_t channelId) { auto it = normalChannels.find(channelId); if (it == normalChannels.end()) { return nullptr; @@ -631,9 +604,8 @@ ChatChannel* Chat::getChannelById(uint16_t channelId) return &it->second; } -PrivateChatChannel* Chat::getPrivateChannel(const Player& player) -{ - for (auto& it : privateChannels) { +PrivateChatChannel* Chat::getPrivateChannel(const Player &player) { + for (auto &it : privateChannels) { if (it.second.getOwner() == player.getGUID()) { return &it.second; } diff --git a/src/creatures/interactions/chat.h b/src/creatures/interactions/chat.h index 935861a943d..acb714b5696 100644 --- a/src/creatures/interactions/chat.h +++ b/src/creatures/interactions/chat.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_INTERACTIONS_CHAT_H_ #define SRC_CREATURES_INTERACTIONS_CHAT_H_ @@ -19,30 +19,29 @@ class Player; using UsersMap = std::map; using InvitedMap = std::map; -class ChatChannel -{ +class ChatChannel { public: ChatChannel() = default; - ChatChannel(uint16_t channelId, std::string channelName): + ChatChannel(uint16_t channelId, std::string channelName) : name(std::move(channelName)), - id(channelId) {} + id(channelId) { } virtual ~ChatChannel() = default; - bool addUser(Player& player); - bool removeUser(const Player& player); - bool hasUser(const Player& player); + bool addUser(Player &player); + bool removeUser(const Player &player); + bool hasUser(const Player &player); - bool talk(const Player& fromPlayer, SpeakClasses type, const std::string& text); - void sendToAll(const std::string& message, SpeakClasses type) const; + bool talk(const Player &fromPlayer, SpeakClasses type, const std::string &text); + void sendToAll(const std::string &message, SpeakClasses type) const; - const std::string& getName() const { + const std::string &getName() const { return name; } uint16_t getId() const { return id; } - const UsersMap& getUsers() const { + const UsersMap &getUsers() const { return users; } virtual const InvitedMap* getInvitedUsers() const { @@ -53,12 +52,14 @@ class ChatChannel return 0; } - bool isPublicChannel() const { return publicChannel; } + bool isPublicChannel() const { + return publicChannel; + } - bool executeOnJoinEvent(const Player& player); - bool executeCanJoinEvent(const Player& player); - bool executeOnLeaveEvent(const Player& player); - bool executeOnSpeakEvent(const Player& player, SpeakClasses& type, const std::string& message); + bool executeOnJoinEvent(const Player &player); + bool executeCanJoinEvent(const Player &player); + bool executeOnLeaveEvent(const Player &player); + bool executeOnSpeakEvent(const Player &player, SpeakClasses &type, const std::string &message); protected: UsersMap users; @@ -73,13 +74,13 @@ class ChatChannel uint16_t id; bool publicChannel = false; - friend class Chat; + friend class Chat; }; -class PrivateChatChannel final : public ChatChannel -{ +class PrivateChatChannel final : public ChatChannel { public: - PrivateChatChannel(uint16_t channelId, std::string channelName) : ChatChannel(channelId, channelName) {} + PrivateChatChannel(uint16_t channelId, std::string channelName) : + ChatChannel(channelId, channelName) { } uint32_t getOwner() const override { return owner; @@ -90,8 +91,8 @@ class PrivateChatChannel final : public ChatChannel bool isInvited(uint32_t guid) const; - void invitePlayer(const Player& player, Player& invitePlayer); - void excludePlayer(const Player& player, Player& excludePlayer); + void invitePlayer(const Player &player, Player &invitePlayer); + void excludePlayer(const Player &player, Player &excludePlayer); bool removeInvite(uint32_t guid); @@ -108,16 +109,15 @@ class PrivateChatChannel final : public ChatChannel using ChannelList = std::list; -class Chat -{ +class Chat { public: Chat(); // non-copyable - Chat(const Chat&) = delete; - Chat& operator=(const Chat&) = delete; + Chat(const Chat &) = delete; + Chat &operator=(const Chat &) = delete; - static Chat& getInstance() { + static Chat &getInstance() { // Guaranteed to be destroyed static Chat instance; // Instantiated on first use @@ -126,21 +126,21 @@ class Chat bool load(); - ChatChannel* createChannel(const Player& player, uint16_t channelId); - bool deleteChannel(const Player& player, uint16_t channelId); + ChatChannel* createChannel(const Player &player, uint16_t channelId); + bool deleteChannel(const Player &player, uint16_t channelId); - ChatChannel* addUserToChannel(Player& player, uint16_t channelId); - bool removeUserFromChannel(const Player& player, uint16_t channelId); - void removeUserFromAllChannels(const Player& player); + ChatChannel* addUserToChannel(Player &player, uint16_t channelId); + bool removeUserFromChannel(const Player &player, uint16_t channelId); + void removeUserFromAllChannels(const Player &player); - bool talkToChannel(const Player& player, SpeakClasses type, const std::string& text, uint16_t channelId); + bool talkToChannel(const Player &player, SpeakClasses type, const std::string &text, uint16_t channelId); - ChannelList getChannelList(const Player& player); + ChannelList getChannelList(const Player &player); - ChatChannel* getChannel(const Player& player, uint16_t channelId); + ChatChannel* getChannel(const Player &player, uint16_t channelId); ChatChannel* getChannelById(uint16_t channelId); ChatChannel* getGuildChannelById(uint32_t guildId); - PrivateChatChannel* getPrivateChannel(const Player& player); + PrivateChatChannel* getPrivateChannel(const Player &player); LuaScriptInterface* getScriptInterface() { return &scriptInterface; @@ -159,4 +159,4 @@ class Chat constexpr auto g_chat = &Chat::getInstance; -#endif // SRC_CREATURES_INTERACTIONS_CHAT_H_ +#endif // SRC_CREATURES_INTERACTIONS_CHAT_H_ diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index 094d7e249d6..e363344daa1 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -20,8 +20,7 @@ int32_t Monster::despawnRadius; uint32_t Monster::monsterAutoID = 0x40000000; -Monster* Monster::createMonster(const std::string& name) -{ +Monster* Monster::createMonster(const std::string &name) { MonsterType* mType = g_monsters().getMonsterType(name); if (!mType) { return nullptr; @@ -32,60 +31,55 @@ Monster* Monster::createMonster(const std::string& name) Monster::Monster(MonsterType* mType) : Creature(), strDescription(asLowerCaseString(mType->nameDescription)), - mType(mType) -{ + mType(mType) { defaultOutfit = mType->info.outfit; currentOutfit = mType->info.outfit; skull = mType->info.skull; float multiplier = g_configManager().getFloat(RATE_MONSTER_HEALTH); - health = mType->info.health*multiplier; - healthMax = mType->info.healthMax*multiplier; + health = mType->info.health * multiplier; + healthMax = mType->info.healthMax * multiplier; baseSpeed = mType->getBaseSpeed(); internalLight = mType->info.light; hiddenHealth = mType->info.hiddenHealth; targetDistance = mType->info.targetDistance; // Register creature events - for (const std::string& scriptName : mType->info.scripts) { + for (const std::string &scriptName : mType->info.scripts) { if (!registerCreatureEvent(scriptName)) { SPDLOG_WARN("[Monster::Monster] - " - "Unknown event name: {}", scriptName); + "Unknown event name: {}", + scriptName); } } } -Monster::~Monster() -{ +Monster::~Monster() { clearTargetList(); clearFriendList(); } -void Monster::addList() -{ +void Monster::addList() { g_game().addMonster(this); } -void Monster::removeList() -{ +void Monster::removeList() { g_game().removeMonster(this); } -bool Monster::canSee(const Position& pos) const -{ - return Creature::canSee(getPosition(), pos, 10, 10); //jlcvp FIX - range 10 Avoids killing monster without reaction +bool Monster::canSee(const Position &pos) const { + return Creature::canSee(getPosition(), pos, 10, 10); // jlcvp FIX - range 10 Avoids killing monster without reaction } -bool Monster::canWalkOnFieldType(CombatType_t combatType) const -{ +bool Monster::canWalkOnFieldType(CombatType_t combatType) const { switch (combatType) { case COMBAT_ENERGYDAMAGE: return mType->info.canWalkOnEnergy; case COMBAT_FIREDAMAGE: return mType->info.canWalkOnFire; case COMBAT_EARTHDAMAGE: - return mType->info.canWalkOnPoison; - default: - return true; + return mType->info.canWalkOnPoison; + default: + return true; } } @@ -105,14 +99,12 @@ uint32_t Monster::getHealingCombatValue(CombatType_t healingType) const { return 0; } -void Monster::onAttackedCreatureDisappear(bool) -{ +void Monster::onAttackedCreatureDisappear(bool) { attackTicks = 0; extraMeleeAttack = true; } -void Monster::onCreatureAppear(Creature* creature, bool isLogin) -{ +void Monster::onCreatureAppear(Creature* creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); if (mType->info.creatureAppearEvent != -1) { @@ -120,8 +112,8 @@ void Monster::onCreatureAppear(Creature* creature, bool isLogin) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[Monster::onCreatureAppear - Monster {} creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - getName(), creature->getName()); + "Call stack overflow. Too many lua script calls being nested.", + getName(), creature->getName()); return; } @@ -143,7 +135,7 @@ void Monster::onCreatureAppear(Creature* creature, bool isLogin) } if (creature == this) { - //We just spawned lets look around to see who is there. + // We just spawned lets look around to see who is there. if (isSummon()) { isMasterInRange = canSee(getMaster()->getPosition()); } @@ -155,8 +147,7 @@ void Monster::onCreatureAppear(Creature* creature, bool isLogin) } } -void Monster::onRemoveCreature(Creature* creature, bool isLogout) -{ +void Monster::onRemoveCreature(Creature* creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); if (mType->info.creatureDisappearEvent != -1) { @@ -164,8 +155,8 @@ void Monster::onRemoveCreature(Creature* creature, bool isLogout) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[Monster::onCreatureDisappear - Monster {} creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - getName(), creature->getName()); + "Call stack overflow. Too many lua script calls being nested.", + getName(), creature->getName()); return; } @@ -197,9 +188,7 @@ void Monster::onRemoveCreature(Creature* creature, bool isLogout) } } -void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport) -{ +void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) { Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); if (mType->info.creatureMoveEvent != -1) { @@ -207,8 +196,8 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi LuaScriptInterface* scriptInterface = mType->info.scriptInterface; if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("[Monster::onCreatureMove - Monster {} creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - getName(), creature->getName()); + "Call stack overflow. Too many lua script calls being nested.", + getName(), creature->getName()); return; } @@ -250,21 +239,21 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi } if (canSeeNewPos && isSummon() && getMaster() == creature) { - isMasterInRange = true; //Follow master again + isMasterInRange = true; // Follow master again } updateIdleStatus(); if (!isSummon()) { if (followCreature) { - const Position& followPosition = followCreature->getPosition(); - const Position& pos = getPosition(); + const Position &followPosition = followCreature->getPosition(); + const Position &pos = getPosition(); int32_t offset_x = Position::getDistanceX(followPosition, pos); int32_t offset_y = Position::getDistanceY(followPosition, pos); if ((offset_x > 1 || offset_y > 1) && mType->info.changeTargetChance > 0) { Direction dir = getDirectionTo(pos, followPosition); - const Position& checkPosition = getNextPosition(dir, pos); + const Position &checkPosition = getNextPosition(dir, pos); const Tile* nextTile = g_game().map.getTile(checkPosition); if (nextTile) { @@ -275,15 +264,14 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi } } } else if (isOpponent(creature)) { - //we have no target lets try pick this one + // we have no target lets try pick this one selectTarget(creature); } } } } -void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) -{ +void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::string &text) { Creature::onCreatureSay(creature, type, text); if (mType->info.creatureSayEvent != -1) { @@ -291,7 +279,8 @@ void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::st LuaScriptInterface* scriptInterface = mType->info.scriptInterface; if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("Monster {} creature {}] Call stack overflow. Too many lua " - "script calls being nested.", getName(), creature->getName()); + "script calls being nested.", + getName(), creature->getName()); return; } @@ -314,8 +303,7 @@ void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::st } } -void Monster::addFriend(Creature* creature) -{ +void Monster::addFriend(Creature* creature) { assert(creature != this); auto result = friendList.insert(creature); if (result.second) { @@ -323,8 +311,7 @@ void Monster::addFriend(Creature* creature) } } -void Monster::removeFriend(Creature* creature) -{ +void Monster::removeFriend(Creature* creature) { auto it = friendList.find(creature); if (it != friendList.end()) { creature->decrementReferenceCounter(); @@ -332,8 +319,7 @@ void Monster::removeFriend(Creature* creature) } } -void Monster::addTarget(Creature* creature, bool pushFront/* = false*/) -{ +void Monster::addTarget(Creature* creature, bool pushFront /* = false*/) { assert(creature != this); if (std::find(targetList.begin(), targetList.end(), creature) == targetList.end()) { creature->incrementReferenceCounter(); @@ -342,13 +328,12 @@ void Monster::addTarget(Creature* creature, bool pushFront/* = false*/) } else { targetList.push_back(creature); } - if(!master && getFaction() != FACTION_DEFAULT && creature->getPlayer()) + if (!master && getFaction() != FACTION_DEFAULT && creature->getPlayer()) totalPlayersOnScreen++; } } -void Monster::removeTarget(Creature* creature) -{ +void Monster::removeTarget(Creature* creature) { if (!creature) { return; } @@ -364,8 +349,7 @@ void Monster::removeTarget(Creature* creature) } } -void Monster::updateTargetList() -{ +void Monster::updateTargetList() { auto friendIterator = friendList.begin(); while (friendIterator != friendList.end()) { Creature* creature = *friendIterator; @@ -398,24 +382,21 @@ void Monster::updateTargetList() } } -void Monster::clearTargetList() -{ +void Monster::clearTargetList() { for (Creature* creature : targetList) { creature->decrementReferenceCounter(); } targetList.clear(); } -void Monster::clearFriendList() -{ +void Monster::clearFriendList() { for (Creature* creature : friendList) { creature->decrementReferenceCounter(); } friendList.clear(); } -void Monster::onCreatureFound(Creature* creature, bool pushFront/* = false*/) -{ +void Monster::onCreatureFound(Creature* creature, bool pushFront /* = false*/) { if (isFriend(creature)) { addFriend(creature); } @@ -427,18 +408,16 @@ void Monster::onCreatureFound(Creature* creature, bool pushFront/* = false*/) updateIdleStatus(); } -void Monster::onCreatureEnter(Creature* creature) -{ +void Monster::onCreatureEnter(Creature* creature) { if (getMaster() == creature) { - //Follow master again + // Follow master again isMasterInRange = true; } onCreatureFound(creature, true); } -bool Monster::isFriend(const Creature* creature) const -{ +bool Monster::isFriend(const Creature* creature) const { if (isSummon() && getMaster()->getPlayer()) { const Player* masterPlayer = getMaster()->getPlayer(); const Player* tmpPlayer = nullptr; @@ -463,8 +442,7 @@ bool Monster::isFriend(const Creature* creature) const return false; } -bool Monster::isOpponent(const Creature* creature) const -{ +bool Monster::isOpponent(const Creature* creature) const { if (isSummon() && getMaster()->getPlayer()) { if (creature != getMaster()) { return true; @@ -483,19 +461,18 @@ bool Monster::isOpponent(const Creature* creature) const return false; } -void Monster::onCreatureLeave(Creature* creature) -{ +void Monster::onCreatureLeave(Creature* creature) { if (getMaster() == creature) { - //Take random steps and only use defense abilities (e.g. heal) until its master comes back + // Take random steps and only use defense abilities (e.g. heal) until its master comes back isMasterInRange = false; } - //update friendList + // update friendList if (isFriend(creature)) { removeFriend(creature); } - //update targetList + // update targetList if (isOpponent(creature)) { removeTarget(creature); if (targetList.empty()) { @@ -504,8 +481,7 @@ void Monster::onCreatureLeave(Creature* creature) } } -bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAULT*/) -{ +bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAULT*/) { if (searchType == TARGETSEARCH_DEFAULT) { int32_t rnd = uniform_random(1, 100); @@ -527,7 +503,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL } std::list resultList; - const Position& myPos = getPosition(); + const Position &myPos = getPosition(); for (Creature* creature : targetList) { if (isTarget(creature)) { @@ -551,10 +527,10 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL getTarget = *it; if (++it != resultList.end()) { - const Position& targetPosition = getTarget->getPosition(); + const Position &targetPosition = getTarget->getPosition(); int32_t minRange = std::max(Position::getDistanceX(myPos, targetPosition), Position::getDistanceY(myPos, targetPosition)); do { - const Position& pos = (*it)->getPosition(); + const Position &pos = (*it)->getPosition(); int32_t distance = std::max(Position::getDistanceX(myPos, pos), Position::getDistanceY(myPos, pos)); if (distance < minRange) { @@ -570,7 +546,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL continue; } - const Position& pos = creature->getPosition(); + const Position &pos = creature->getPosition(); int32_t distance = std::max(Position::getDistanceX(myPos, pos), Position::getDistanceY(myPos, pos)); if (distance < minRange) { getTarget = creature; @@ -613,7 +589,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL if (++it != resultList.end()) { int32_t mostDamage = 0; do { - const auto& dmg = damageMap.find((*it)->getID()); + const auto &dmg = damageMap.find((*it)->getID()); if (dmg != damageMap.end()) { if (dmg->second.total > mostDamage) { mostDamage = dmg->second.total; @@ -639,7 +615,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL } } - //lets just pick the first target in the list + // lets just pick the first target in the list for (Creature* target : targetList) { if (selectTarget(target)) { return true; @@ -648,8 +624,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL return false; } -void Monster::onFollowCreatureComplete(const Creature* creature) -{ +void Monster::onFollowCreatureComplete(const Creature* creature) { if (creature) { auto it = std::find(targetList.begin(), targetList.end(), creature); if (it != targetList.end()) { @@ -667,9 +642,7 @@ void Monster::onFollowCreatureComplete(const Creature* creature) } } -BlockType_t Monster::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, - bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool /* field = false */) -{ +BlockType_t Monster::blockHit(Creature* attacker, CombatType_t combatType, int32_t &damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool /* field = false */) { BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor); if (damage != 0) { @@ -691,11 +664,8 @@ BlockType_t Monster::blockHit(Creature* attacker, CombatType_t combatType, int32 return blockType; } - -bool Monster::isTarget(const Creature* creature) const -{ - if (creature->isRemoved() || !creature->isAttackable() || - creature->getZone() == ZONE_PROTECTION || !canSeeCreature(creature)) { +bool Monster::isTarget(const Creature* creature) const { + if (creature->isRemoved() || !creature->isAttackable() || creature->getZone() == ZONE_PROTECTION || !canSeeCreature(creature)) { return false; } @@ -709,15 +679,14 @@ bool Monster::isTarget(const Creature* creature) const return true; } -bool Monster::selectTarget(Creature* creature) -{ +bool Monster::selectTarget(Creature* creature) { if (!isTarget(creature)) { return false; } auto it = std::find(targetList.begin(), targetList.end(), creature); if (it == targetList.end()) { - //Target not found in our target list. + // Target not found in our target list. return false; } @@ -729,8 +698,7 @@ bool Monster::selectTarget(Creature* creature) return setFollowCreature(creature); } -void Monster::setIdle(bool idle) -{ +void Monster::setIdle(bool idle) { if (isRemoved() || getHealth() <= 0) { return; } @@ -747,15 +715,13 @@ void Monster::setIdle(bool idle) } } -void Monster::updateIdleStatus() -{ +void Monster::updateIdleStatus() { bool idle = false; if (conditions.empty()) { if (!isSummon() && targetList.empty()) { idle = true; - } - else if ((!master || master->getMonster()) && getFaction() != FACTION_DEFAULT && (totalPlayersOnScreen == 0 && (!master || master->getMonster()->totalPlayersOnScreen == 0))) { + } else if ((!master || master->getMonster()) && getFaction() != FACTION_DEFAULT && (totalPlayersOnScreen == 0 && (!master || master->getMonster()->totalPlayersOnScreen == 0))) { idle = true; } } @@ -763,18 +729,16 @@ void Monster::updateIdleStatus() setIdle(idle); } -void Monster::onAddCondition(ConditionType_t type) -{ +void Monster::onAddCondition(ConditionType_t type) { if (type == CONDITION_FIRE || type == CONDITION_ENERGY || type == CONDITION_POISON) { - ignoreFieldDamage = true; + ignoreFieldDamage = true; updateMapCache(); } updateIdleStatus(); } -void Monster::onEndCondition(ConditionType_t type) -{ +void Monster::onEndCondition(ConditionType_t type) { if (type == CONDITION_FIRE || type == CONDITION_ENERGY || type == CONDITION_POISON) { ignoreFieldDamage = false; updateMapCache(); @@ -783,8 +747,7 @@ void Monster::onEndCondition(ConditionType_t type) updateIdleStatus(); } -void Monster::onThink(uint32_t interval) -{ +void Monster::onThink(uint32_t interval) { Creature::onThink(interval); if (mType->info.thinkEvent != -1) { @@ -792,7 +755,8 @@ void Monster::onThink(uint32_t interval) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("Monster {} Call stack overflow. Too many lua script calls " - "being nested.", getName()); + "being nested.", + getName()); return; } @@ -837,16 +801,16 @@ void Monster::onThink(uint32_t interval) if (isSummon()) { if (!attackedCreature) { if (getMaster() && getMaster()->getAttackedCreature()) { - //This happens if the monster is summoned during combat + // This happens if the monster is summoned during combat selectTarget(getMaster()->getAttackedCreature()); } else if (getMaster() != followCreature) { - //Our master has not ordered us to attack anything, lets follow him around instead. + // Our master has not ordered us to attack anything, lets follow him around instead. setFollowCreature(getMaster()); } } else if (attackedCreature == this) { setFollowCreature(nullptr); } else if (followCreature != attackedCreature) { - //This happens just after a master orders an attack, so lets follow it aswell. + // This happens just after a master orders an attack, so lets follow it aswell. setFollowCreature(attackedCreature); } } else if (!targetList.empty()) { @@ -866,8 +830,7 @@ void Monster::onThink(uint32_t interval) } } -void Monster::doAttacking(uint32_t interval) -{ +void Monster::doAttacking(uint32_t interval) { if (!attackedCreature || (isSummon() && attackedCreature == this)) { return; } @@ -877,23 +840,22 @@ void Monster::doAttacking(uint32_t interval) attackTicks += interval; float forgeAttackBonus = 0; - if (monsterForgeClassification > ForgeClassifications_t::FORGE_NORMAL_MONSTER) - { + if (monsterForgeClassification > ForgeClassifications_t::FORGE_NORMAL_MONSTER) { uint16_t damageBase = 3; forgeAttackBonus = static_cast(damageBase + 100) / 100.f; } - const Position& myPos = getPosition(); - const Position& targetPos = attackedCreature->getPosition(); + const Position &myPos = getPosition(); + const Position &targetPos = attackedCreature->getPosition(); - for (const spellBlock_t& spellBlock : mType->info.attackSpells) { + for (const spellBlock_t &spellBlock : mType->info.attackSpells) { bool inRange = false; if (attackedCreature == nullptr) { break; } - if(spellBlock.isMelee && isFleeing()){ + if (spellBlock.isMelee && isFleeing()) { continue; } @@ -932,7 +894,7 @@ void Monster::doAttacking(uint32_t interval) } if (!inRange && spellBlock.isMelee) { - //melee swing out of reach + // melee swing out of reach extraMeleeAttack = true; } } @@ -946,12 +908,11 @@ void Monster::doAttacking(uint32_t interval) } } -bool Monster::canUseAttack(const Position& pos, const Creature* target) const -{ +bool Monster::canUseAttack(const Position &pos, const Creature* target) const { if (isHostile()) { - const Position& targetPos = target->getPosition(); + const Position &targetPos = target->getPosition(); uint32_t distance = std::max(Position::getDistanceX(pos, targetPos), Position::getDistanceY(pos, targetPos)); - for (const spellBlock_t& spellBlock : mType->info.attackSpells) { + for (const spellBlock_t &spellBlock : mType->info.attackSpells) { if (spellBlock.range != 0 && distance <= spellBlock.range) { return g_game().isSightClear(pos, targetPos, true); } @@ -961,9 +922,7 @@ bool Monster::canUseAttack(const Position& pos, const Creature* target) const return true; } -bool Monster::canUseSpell(const Position& pos, const Position& targetPos, - const spellBlock_t& sb, uint32_t interval, bool& inRange, bool& resetTicks) -{ +bool Monster::canUseSpell(const Position &pos, const Position &targetPos, const spellBlock_t &sb, uint32_t interval, bool &inRange, bool &resetTicks) { inRange = true; if (sb.isMelee && isFleeing()) { @@ -983,7 +942,7 @@ bool Monster::canUseSpell(const Position& pos, const Position& targetPos, } if (attackTicks % sb.speed >= interval) { - //already used this spell for this round + // already used this spell for this round return false; } } @@ -995,8 +954,7 @@ bool Monster::canUseSpell(const Position& pos, const Position& targetPos, return true; } -void Monster::onThinkTarget(uint32_t interval) -{ +void Monster::onThinkTarget(uint32_t interval) { if (!isSummon()) { if (mType->info.changeTargetSpeed != 0) { bool canChangeTarget = true; @@ -1040,19 +998,18 @@ void Monster::onThinkTarget(uint32_t interval) } } -void Monster::onThinkDefense(uint32_t interval) -{ +void Monster::onThinkDefense(uint32_t interval) { bool resetTicks = true; defenseTicks += interval; - for (const spellBlock_t& spellBlock : mType->info.defenseSpells) { + for (const spellBlock_t &spellBlock : mType->info.defenseSpells) { if (spellBlock.speed > defenseTicks) { resetTicks = false; continue; } if (defenseTicks % spellBlock.speed >= interval) { - //already used this spell for this round + // already used this spell for this round continue; } @@ -1064,7 +1021,7 @@ void Monster::onThinkDefense(uint32_t interval) } if (!isSummon() && summons.size() < mType->info.maxSummons && hasFollowPath) { - for (const summonBlock_t& summonBlock : mType->info.summons) { + for (const summonBlock_t &summonBlock : mType->info.summons) { if (summonBlock.speed > defenseTicks) { resetTicks = false; continue; @@ -1075,7 +1032,7 @@ void Monster::onThinkDefense(uint32_t interval) } if (defenseTicks % summonBlock.speed >= interval) { - //already used this spell for this round + // already used this spell for this round continue; } @@ -1112,8 +1069,7 @@ void Monster::onThinkDefense(uint32_t interval) } } -void Monster::onThinkYell(uint32_t interval) -{ +void Monster::onThinkYell(uint32_t interval) { if (mType->info.yellSpeedTicks == 0) { return; } @@ -1124,7 +1080,7 @@ void Monster::onThinkYell(uint32_t interval) if (!mType->info.voiceVector.empty() && (mType->info.yellChance >= static_cast(uniform_random(1, 100)))) { uint32_t index = uniform_random(0, mType->info.voiceVector.size() - 1); - const voiceBlock_t& vb = mType->info.voiceVector[index]; + const voiceBlock_t &vb = mType->info.voiceVector[index]; if (vb.yellText) { g_game().internalCreatureSay(this, TALKTYPE_MONSTER_YELL, vb.text, false); @@ -1135,10 +1091,9 @@ void Monster::onThinkYell(uint32_t interval) } } -bool Monster::pushItem(Item *item, const Direction& nextDirection) -{ - const Position& centerPos = item->getPosition(); - for (const auto& [x, y] : getPushItemLocationOptions(nextDirection)) { +bool Monster::pushItem(Item* item, const Direction &nextDirection) { + const Position ¢erPos = item->getPosition(); + for (const auto &[x, y] : getPushItemLocationOptions(nextDirection)) { Position tryPos(centerPos.x + x, centerPos.y + y, centerPos.z); Tile* tile = g_game().map.getTile(tryPos); if (tile && g_game().canThrowObjectTo(centerPos, tryPos) && g_game().internalMoveItem(item->getParent(), tile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr) == RETURNVALUE_NOERROR) { @@ -1148,8 +1103,7 @@ bool Monster::pushItem(Item *item, const Direction& nextDirection) return false; } -void Monster::pushItems(Tile *tile, const Direction& nextDirection) -{ +void Monster::pushItems(Tile* tile, const Direction &nextDirection) { // We can not use iterators here since we can push the item to another tile // which will invalidate the iterator. // start from the end to minimize the amount of traffic @@ -1162,8 +1116,7 @@ void Monster::pushItems(Tile *tile, const Direction& nextDirection) auto it = items->begin(); while (it != items->end()) { Item* item = *it; - if (item && item->hasProperty(CONST_PROP_MOVEABLE) && (item->hasProperty(CONST_PROP_BLOCKPATH) - || item->hasProperty(CONST_PROP_BLOCKSOLID)) && item->getAttribute(ItemAttribute_t::ACTIONID) != 100 /* non-moveable action*/) { + if (item && item->hasProperty(CONST_PROP_MOVEABLE) && (item->hasProperty(CONST_PROP_BLOCKPATH) || item->hasProperty(CONST_PROP_BLOCKSOLID)) && item->getAttribute(ItemAttribute_t::ACTIONID) != 100 /* non-moveable action*/) { if (moveCount < 20 && pushItem(item, nextDirection)) { ++moveCount; } else if (!item->isCorpse() && g_game().internalRemoveItem(item) == RETURNVALUE_NOERROR) { @@ -1173,22 +1126,21 @@ void Monster::pushItems(Tile *tile, const Direction& nextDirection) it++; } } - if(removeCount > 0){ + if (removeCount > 0) { g_game().addMagicEffect(tile->getPosition(), CONST_ME_POFF); } } -bool Monster::pushCreature(Creature* creature) -{ +bool Monster::pushCreature(Creature* creature) { static std::vector dirList { - DIRECTION_NORTH, + DIRECTION_NORTH, DIRECTION_WEST, DIRECTION_EAST, - DIRECTION_SOUTH + DIRECTION_SOUTH }; std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); for (Direction dir : dirList) { - const Position& tryPos = Spells::getCasterPosition(creature, dir); + const Position &tryPos = Spells::getCasterPosition(creature, dir); const Tile* toTile = g_game().map.getTile(tryPos); if (toTile && !toTile->hasFlag(TILESTATE_BLOCKPATH) && g_game().internalMoveCreature(creature, dir) == RETURNVALUE_NOERROR) { return true; @@ -1197,10 +1149,9 @@ bool Monster::pushCreature(Creature* creature) return false; } -void Monster::pushCreatures(Tile* tile) -{ - //We can not use iterators here since we can push a creature to another tile - //which will invalidate the iterator. +void Monster::pushCreatures(Tile* tile) { + // We can not use iterators here since we can push a creature to another tile + // which will invalidate the iterator. if (CreatureVector* creatures = tile->getCreatures()) { uint32_t removeCount = 0; Monster* lastPushedMonster = nullptr; @@ -1227,10 +1178,9 @@ void Monster::pushCreatures(Tile* tile) } } -bool Monster::getNextStep(Direction& nextDirection, uint32_t& flags) -{ +bool Monster::getNextStep(Direction &nextDirection, uint32_t &flags) { if (isIdle || getHealth() <= 0) { - //we dont have anyone watching might aswell stop walking + // we dont have anyone watching might aswell stop walking eventWalk = 0; return false; } @@ -1244,7 +1194,7 @@ bool Monster::getNextStep(Direction& nextDirection, uint32_t& flags) } if (result && (canPushItems() || canPushCreatures())) { - const Position& pos = getNextPosition(nextDirection, getPosition()); + const Position &pos = getNextPosition(nextDirection, getPosition()); Tile* posTile = g_game().map.getTile(pos); if (posTile) { if (canPushItems()) { @@ -1276,7 +1226,7 @@ void Monster::doFollowCreature(uint32_t &flags, Direction &nextDirection, bool & if (ignoreFieldDamage) { updateMapCache(); } - //target dancing + // target dancing if (attackedCreature && attackedCreature == followCreature) { if (isFleeing()) { result = getDanceStep(getPosition(), nextDirection, false, false); @@ -1287,12 +1237,11 @@ void Monster::doFollowCreature(uint32_t &flags, Direction &nextDirection, bool & } } -bool Monster::getRandomStep(const Position& creaturePos, Direction& moveDirection) const -{ - static std::vector dirList{ - DIRECTION_NORTH, +bool Monster::getRandomStep(const Position &creaturePos, Direction &moveDirection) const { + static std::vector dirList { + DIRECTION_NORTH, DIRECTION_WEST, DIRECTION_EAST, - DIRECTION_SOUTH + DIRECTION_SOUTH }; std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); @@ -1305,13 +1254,11 @@ bool Monster::getRandomStep(const Position& creaturePos, Direction& moveDirectio return false; } -bool Monster::getDanceStep(const Position& creaturePos, Direction& moveDirection, - bool keepAttack /*= true*/, bool keepDistance /*= true*/) -{ +bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection, bool keepAttack /*= true*/, bool keepDistance /*= true*/) { bool canDoAttackNow = canUseAttack(creaturePos, attackedCreature); assert(attackedCreature != nullptr); - const Position& centerPos = attackedCreature->getPosition(); + const Position ¢erPos = attackedCreature->getPosition(); int_fast32_t offset_x = Position::getOffsetX(creaturePos, centerPos); int_fast32_t offset_y = Position::getOffsetY(creaturePos, centerPos); @@ -1321,8 +1268,8 @@ bool Monster::getDanceStep(const Position& creaturePos, Direction& moveDirection uint32_t centerToDist = std::max(distance_x, distance_y); - //monsters not at targetDistance shouldn't dancestep - if (centerToDist < (uint32_t) targetDistance) { + // monsters not at targetDistance shouldn't dancestep + if (centerToDist < (uint32_t)targetDistance) { return false; } @@ -1396,9 +1343,8 @@ bool Monster::getDanceStep(const Position& creaturePos, Direction& moveDirection return false; } -bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirection, bool flee /* = false */) -{ - const Position& creaturePos = getPosition(); +bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirection, bool flee /* = false */) { + const Position &creaturePos = getPosition(); int_fast32_t dx = Position::getDistanceX(creaturePos, targetPos); int_fast32_t dy = Position::getDistanceY(creaturePos, targetPos); @@ -1413,7 +1359,7 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio int_fast32_t offsety = Position::getOffsetY(creaturePos, targetPos); if (dx <= 1 && dy <= 1) { - //seems like a target is near, it this case we need to slow down our movements (as a monster) + // seems like a target is near, it this case we need to slow down our movements (as a monster) if (stepDuration < 2) { stepDuration++; } @@ -1426,10 +1372,10 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio } if (dx == dy) { - //player is diagonal to the monster + // player is diagonal to the monster if (offsetx >= 1 && offsety >= 1) { // player is NW - //escape to SE, S or E [and some extra] + // escape to SE, S or E [and some extra] bool s = canWalkTo(creaturePos, DIRECTION_SOUTH); bool e = canWalkTo(creaturePos, DIRECTION_EAST); @@ -1474,8 +1420,8 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio return true; } else if (offsetx <= -1 && offsety <= -1) { - //player is SE - //escape to NW , W or N [and some extra] + // player is SE + // escape to NW , W or N [and some extra] bool w = canWalkTo(creaturePos, DIRECTION_WEST); bool n = canWalkTo(creaturePos, DIRECTION_NORTH); @@ -1522,8 +1468,8 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio return true; } else if (offsetx >= 1 && offsety <= -1) { - //player is SW - //escape to NE, N, E [and some extra] + // player is SW + // escape to NE, N, E [and some extra] bool n = canWalkTo(creaturePos, DIRECTION_NORTH); bool e = canWalkTo(creaturePos, DIRECTION_EAST); if (n && e) { @@ -1570,7 +1516,7 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio return true; } else if (offsetx <= -1 && offsety >= 1) { // player is NE - //escape to SW, S, W [and some extra] + // escape to SW, S, W [and some extra] bool w = canWalkTo(creaturePos, DIRECTION_WEST); bool s = canWalkTo(creaturePos, DIRECTION_SOUTH); if (w && s) { @@ -1616,7 +1562,7 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio } } - //Now let's decide where the player is located to the monster (what direction) so we can decide where to escape. + // Now let's decide where the player is located to the monster (what direction) so we can decide where to escape. if (dy > dx) { Direction playerDir = offsety < 0 ? DIRECTION_SOUTH : DIRECTION_NORTH; switch (playerDir) { @@ -1889,8 +1835,7 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& moveDirectio return true; } -bool Monster::canWalkTo(Position pos, Direction moveDirection) const -{ +bool Monster::canWalkTo(Position pos, Direction moveDirection) const { pos = getNextPosition(moveDirection, pos); if (isInSpawnRange(pos)) { if (getWalkCache(pos) == 0) { @@ -1898,16 +1843,14 @@ bool Monster::canWalkTo(Position pos, Direction moveDirection) const } const Tile* tile = g_game().map.getTile(pos); - if (tile && tile->getTopVisibleCreature(this) == nullptr && - tile->queryAdd(0, *this, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR) { + if (tile && tile->getTopVisibleCreature(this) == nullptr && tile->queryAdd(0, *this, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR) { return true; } } return false; } -void Monster::death(Creature*) -{ +void Monster::death(Creature*) { if (monsterForgeClassification > ForgeClassifications_t::FORGE_NORMAL_MONSTER) { g_game().removeForgeMonster(getID(), monsterForgeClassification, true); } @@ -1924,8 +1867,7 @@ void Monster::death(Creature*) onIdleStatus(); } -Item* Monster::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) -{ +Item* Monster::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) { Item* corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse) { if (mostDamageCreature) { @@ -1942,8 +1884,7 @@ Item* Monster::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature return corpse; } -bool Monster::isInSpawnRange(const Position& pos) const -{ +bool Monster::isInSpawnRange(const Position &pos) const { if (!spawnMonster) { return true; } @@ -1967,8 +1908,7 @@ bool Monster::isInSpawnRange(const Position& pos) const return true; } -bool Monster::getCombatValues(int32_t& min, int32_t& max) -{ +bool Monster::getCombatValues(int32_t &min, int32_t &max) { if (minCombatValue == 0 && maxCombatValue == 0) { return false; } @@ -1985,27 +1925,26 @@ bool Monster::getCombatValues(int32_t& min, int32_t& max) return true; } -void Monster::updateLookDirection() -{ +void Monster::updateLookDirection() { Direction newDir = getDirection(); if (attackedCreature) { - const Position& pos = getPosition(); - const Position& attackedCreaturePos = attackedCreature->getPosition(); + const Position &pos = getPosition(); + const Position &attackedCreaturePos = attackedCreature->getPosition(); int_fast32_t offsetx = Position::getOffsetX(attackedCreaturePos, pos); int_fast32_t offsety = Position::getOffsetY(attackedCreaturePos, pos); int32_t dx = std::abs(offsetx); int32_t dy = std::abs(offsety); if (dx > dy) { - //look EAST/WEST + // look EAST/WEST if (offsetx < 0) { newDir = DIRECTION_WEST; } else { newDir = DIRECTION_EAST; } } else if (dx < dy) { - //look NORTH/SOUTH + // look NORTH/SOUTH if (offsety < 0) { newDir = DIRECTION_NORTH; } else { @@ -2043,20 +1982,18 @@ void Monster::updateLookDirection() g_game().internalCreatureTurn(this, newDir); } -void Monster::dropLoot(Container* corpse, Creature*) -{ +void Monster::dropLoot(Container* corpse, Creature*) { if (corpse && lootDrop) { // Only fiendish drops sliver if (ForgeClassifications_t classification = getMonsterForgeClassification(); // Condition - classification == ForgeClassifications_t::FORGE_FIENDISH_MONSTER) - { + classification == ForgeClassifications_t::FORGE_FIENDISH_MONSTER) { auto minSlivers = g_configManager().getNumber(FORGE_MIN_SLIVERS); auto maxSlivers = g_configManager().getNumber(FORGE_MAX_SLIVERS); auto sliverCount = static_cast(uniform_random(minSlivers, maxSlivers)); - Item *sliver = Item::CreateItem(ITEM_FORGE_SLIVER, sliverCount); + Item* sliver = Item::CreateItem(ITEM_FORGE_SLIVER, sliverCount); if (g_game().internalAddItem(corpse, sliver) != RETURNVALUE_NOERROR) { corpse->internalAddThing(sliver); } @@ -2065,13 +2002,11 @@ void Monster::dropLoot(Container* corpse, Creature*) } } -void Monster::setNormalCreatureLight() -{ +void Monster::setNormalCreatureLight() { internalLight = mType->info.light; } -void Monster::drainHealth(Creature* attacker, int32_t damage) -{ +void Monster::drainHealth(Creature* attacker, int32_t damage) { Creature::drainHealth(attacker, damage); if (damage > 0 && randomStepping) { @@ -2084,15 +2019,13 @@ void Monster::drainHealth(Creature* attacker, int32_t damage) } } -void Monster::changeHealth(int32_t healthChange, bool sendHealthChange/* = true*/) -{ +void Monster::changeHealth(int32_t healthChange, bool sendHealthChange /* = true*/) { // In case a player with ignore flag set attacks the monster setIdle(false); Creature::changeHealth(healthChange, sendHealthChange); } -bool Monster::challengeCreature(Creature* creature) -{ +bool Monster::challengeCreature(Creature* creature) { if (isSummon()) { return false; } @@ -2106,8 +2039,7 @@ bool Monster::challengeCreature(Creature* creature) return result; } -bool Monster::changeTargetDistance(int32_t distance) -{ +bool Monster::changeTargetDistance(int32_t distance) { if (isSummon()) { return false; } @@ -2126,8 +2058,7 @@ bool Monster::changeTargetDistance(int32_t distance) return true; } -void Monster::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const -{ +void Monster::getPathSearchParams(const Creature* creature, FindPathParams &fpp) const { Creature::getPathSearchParams(creature, fpp); fpp.minTargetDist = 1; @@ -2155,24 +2086,20 @@ void Monster::getPathSearchParams(const Creature* creature, FindPathParams& fpp) } } -void Monster::configureForgeSystem() -{ +void Monster::configureForgeSystem() { if (!canBeForgeMonster()) { return; } // Avoid double forge - if (monsterForgeClassification == ForgeClassifications_t::FORGE_FIENDISH_MONSTER) - { + if (monsterForgeClassification == ForgeClassifications_t::FORGE_FIENDISH_MONSTER) { // Set stack setForgeStack(15); // Set icon setMonsterIcon(15, 5); // Update g_game().updateCreatureIcon(this); - } - else if (monsterForgeClassification == ForgeClassifications_t::FORGE_INFLUENCED_MONSTER) - { + } else if (monsterForgeClassification == ForgeClassifications_t::FORGE_INFLUENCED_MONSTER) { // Set stack auto stack = static_cast(normal_random(1, 5)); setForgeStack(stack); @@ -2196,8 +2123,7 @@ void Monster::configureForgeSystem() g_game().sendUpdateCreature(this); } -void Monster::clearFiendishStatus() -{ +void Monster::clearFiendishStatus() { timeToChangeFiendish = 0; forgeStack = 0; monsterForgeClassification = ForgeClassifications_t::FORGE_NORMAL_MONSTER; @@ -2213,8 +2139,7 @@ void Monster::clearFiendishStatus() g_game().sendUpdateCreature(this); } -void Monster::setMonsterIcon(uint16_t iconcount, uint16_t iconnumber) -{ +void Monster::setMonsterIcon(uint16_t iconcount, uint16_t iconnumber) { iconCount = iconcount; iconNumber = iconnumber; } @@ -2225,22 +2150,22 @@ bool Monster::canDropLoot() const { std::vector> Monster::getPushItemLocationOptions(const Direction &direction) { if (direction == DIRECTION_WEST || direction == DIRECTION_EAST) { - return {{0, -1}, {0, 1}}; + return { { 0, -1 }, { 0, 1 } }; } if (direction == DIRECTION_NORTH || direction == DIRECTION_SOUTH) { - return {{-1, 0}, {1, 0}}; + return { { -1, 0 }, { 1, 0 } }; } if (direction == DIRECTION_NORTHWEST) { - return {{0, -1}, {-1, 0}}; + return { { 0, -1 }, { -1, 0 } }; } if (direction == DIRECTION_NORTHEAST) { - return {{0, -1}, {1, 0}}; + return { { 0, -1 }, { 1, 0 } }; } if (direction == DIRECTION_SOUTHWEST) { - return {{0, 1}, {-1, 0}}; + return { { 0, 1 }, { -1, 0 } }; } if (direction == DIRECTION_SOUTHEAST) { - return {{0, 1}, {1, 0}}; + return { { 0, 1 }, { 1, 0 } }; } return {}; diff --git a/src/creatures/monsters/monster.h b/src/creatures/monsters/monster.h index 9c0c3c9fff5..42e9c9c7a88 100644 --- a/src/creatures/monsters/monster.h +++ b/src/creatures/monsters/monster.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_MONSTERS_MONSTER_H_ #define SRC_CREATURES_MONSTERS_MONSTER_H_ @@ -21,10 +21,9 @@ class Spawn; using CreatureHashSet = phmap::flat_hash_set; using CreatureList = std::list; -class Monster final : public Creature -{ +class Monster final : public Creature { public: - static Monster* createMonster(const std::string& name); + static Monster* createMonster(const std::string &name); static int32_t despawnRange; static int32_t despawnRadius; @@ -32,8 +31,8 @@ class Monster final : public Creature ~Monster(); // non-copyable - Monster(const Monster&) = delete; - Monster& operator=(const Monster&) = delete; + Monster(const Monster &) = delete; + Monster &operator=(const Monster &) = delete; Monster* getMonster() override { return this; @@ -51,14 +50,14 @@ class Monster final : public Creature void removeList() override; void addList() override; - const std::string& getName() const override { + const std::string &getName() const override { return mType->name; } // Real monster name, set on monster creation "createMonsterType(typeName)" - const std::string& getTypeName() const override { + const std::string &getTypeName() const override { return mType->typeName; } - const std::string& getNameDescription() const override { + const std::string &getNameDescription() const override { return mType->nameDescription; } std::string getDescription(int32_t) const override { @@ -69,7 +68,7 @@ class Monster final : public Creature return CREATURETYPE_MONSTER; } - const Position& getMasterPos() const { + const Position &getMasterPos() const { return masterPos; } void setMasterPos(Position pos) { @@ -119,7 +118,7 @@ class Monster final : public Creature bool isFamiliar() const { return mType->info.isFamiliar; } - bool canSee(const Position& pos) const override; + bool canSee(const Position &pos) const override; bool canSeeInvisibility() const override { return isImmune(CONDITION_INVISIBLE); } @@ -141,12 +140,12 @@ class Monster final : public Creature void onCreatureAppear(Creature* creature, bool isLogin) override; void onRemoveCreature(Creature* creature, bool isLogout) override; - void onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, const Tile* oldTile, const Position& oldPos, bool teleport) override; - void onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) override; + void onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) override; + void onCreatureSay(Creature* creature, SpeakClasses type, const std::string &text) override; void drainHealth(Creature* attacker, int32_t damage) override; void changeHealth(int32_t healthChange, bool sendHealthChange = true) override; - bool getNextStep(Direction& direction, uint32_t& flags) override; + bool getNextStep(Direction &direction, uint32_t &flags) override; void onFollowCreatureComplete(const Creature* creature) override; void onThink(uint32_t interval) override; @@ -216,7 +215,7 @@ class Monster final : public Creature void setMonsterIcon(uint16_t iconcount, uint16_t iconnumber); void setNormalCreatureLight() override; - bool getCombatValues(int32_t& min, int32_t& max) override; + bool getCombatValues(int32_t &min, int32_t &max) override; void doAttacking(uint32_t interval) override; bool hasExtraSwing() override { @@ -226,10 +225,10 @@ class Monster final : public Creature bool searchTarget(TargetSearchType_t searchType = TARGETSEARCH_DEFAULT); bool selectTarget(Creature* creature); - const CreatureList& getTargetList() const { + const CreatureList &getTargetList() const { return targetList; } - const CreatureHashSet& getFriendList() const { + const CreatureHashSet &getFriendList() const { return friendList; } @@ -238,7 +237,7 @@ class Monster final : public Creature return !isSummon() && getHealth() <= mType->info.runAwayHealth && challengeFocusDuration <= 0; } - bool getDistanceStep(const Position& targetPos, Direction& direction, bool flee = false); + bool getDistanceStep(const Position &targetPos, Direction &direction, bool flee = false); bool isTargetNearby() const { return stepDuration >= 1; } @@ -262,8 +261,7 @@ class Monster final : public Creature void clearTargetList(); void clearFriendList(); - BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, - bool checkDefense = false, bool checkArmor = false, bool field = false) override; + BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false) override; static uint32_t monsterAutoID; @@ -273,7 +271,6 @@ class Monster final : public Creature return getForgeStack() == 0 && !isSummon() && !isRewardBoss() && canDropLoot() && isForgeCreature() && getRaceId() > 0; } - bool isForgeCreature() const { return mType->info.isForgeCreature; } @@ -374,17 +371,15 @@ class Monster final : public Creature void onAddCondition(ConditionType_t type) override; void onEndCondition(ConditionType_t type) override; - bool canUseAttack(const Position& pos, const Creature* target) const; - bool canUseSpell(const Position& pos, const Position& targetPos, - const spellBlock_t& sb, uint32_t interval, bool& inRange, bool& resetTicks); - bool getRandomStep(const Position& creaturePos, Direction& direction) const; - bool getDanceStep(const Position& creaturePos, Direction& direction, - bool keepAttack = true, bool keepDistance = true); - bool isInSpawnRange(const Position& pos) const; + bool canUseAttack(const Position &pos, const Creature* target) const; + bool canUseSpell(const Position &pos, const Position &targetPos, const spellBlock_t &sb, uint32_t interval, bool &inRange, bool &resetTicks); + bool getRandomStep(const Position &creaturePos, Direction &direction) const; + bool getDanceStep(const Position &creaturePos, Direction &direction, bool keepAttack = true, bool keepDistance = true); + bool isInSpawnRange(const Position &pos) const; bool canWalkTo(Position pos, Direction direction) const; - static bool pushItem(Item *item, const Direction& nextDirection); - static void pushItems(Tile *tile, const Direction& nextDirection); + static bool pushItem(Item* item, const Direction &nextDirection); + static void pushItems(Tile* tile, const Direction &nextDirection); static bool pushCreature(Creature* creature); static void pushCreatures(Tile* tile); @@ -408,7 +403,7 @@ class Monster final : public Creature uint32_t getConditionImmunities() const override { return mType->info.conditionImmunities; } - void getPathSearchParams(const Creature* creature, FindPathParams& fpp) const override; + void getPathSearchParams(const Creature* creature, FindPathParams &fpp) const override; bool useCacheMap() const override { return !randomStepping; } @@ -422,4 +417,4 @@ class Monster final : public Creature void doRandomStep(Direction &nextDirection, bool &result); }; -#endif // SRC_CREATURES_MONSTERS_MONSTER_H_ +#endif // SRC_CREATURES_MONSTERS_MONSTER_H_ diff --git a/src/creatures/monsters/monsters.cpp b/src/creatures/monsters/monsters.cpp index b4a3d7f3b36..3abdfdee2c7 100644 --- a/src/creatures/monsters/monsters.cpp +++ b/src/creatures/monsters/monsters.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,15 +16,13 @@ #include "game/game.h" #include "items/weapons/weapons.h" -spellBlock_t::~spellBlock_t() -{ +spellBlock_t::~spellBlock_t() { if (combatSpell) { delete spell; } } -void MonsterType::loadLoot(MonsterType* monsterType, LootBlock lootBlock) -{ +void MonsterType::loadLoot(MonsterType* monsterType, LootBlock lootBlock) { if (lootBlock.childLoot.empty()) { bool isContainer = Item::items[lootBlock.id].isContainer(); if (isContainer) { @@ -38,13 +36,11 @@ void MonsterType::loadLoot(MonsterType* monsterType, LootBlock lootBlock) } } -bool MonsterType::canSpawn(const Position& pos) -{ +bool MonsterType::canSpawn(const Position &pos) { bool canSpawn = true; bool isDay = g_game().gameIsDay(); - if ((isDay && info.respawnType.period == RESPAWNPERIOD_NIGHT) || - (!isDay && info.respawnType.period == RESPAWNPERIOD_DAY)) { + if ((isDay && info.respawnType.period == RESPAWNPERIOD_NIGHT) || (!isDay && info.respawnType.period == RESPAWNPERIOD_DAY)) { // It will ignore day and night if underground canSpawn = (pos.z > MAP_INIT_SURFACE_LAYER && info.respawnType.underground); } @@ -52,9 +48,7 @@ bool MonsterType::canSpawn(const Position& pos) return canSpawn; } -ConditionDamage* Monsters::getDamageCondition(ConditionType_t conditionType, - int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval) -{ +ConditionDamage* Monsters::getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval) { ConditionDamage* condition = static_cast(Condition::createCondition(CONDITIONID_COMBAT, conditionType, 0, 0)); condition->setParam(CONDITION_PARAM_TICKINTERVAL, tickInterval); condition->setParam(CONDITION_PARAM_MINVALUE, minDamage); @@ -64,65 +58,53 @@ ConditionDamage* Monsters::getDamageCondition(ConditionType_t conditionType, return condition; } -bool Monsters::deserializeSpell(MonsterSpell *spell, spellBlock_t &sb, const std::string &description) -{ - if (!spell->scriptName.empty()) - { +bool Monsters::deserializeSpell(MonsterSpell* spell, spellBlock_t &sb, const std::string &description) { + if (!spell->scriptName.empty()) { spell->isScripted = true; - } - else if (!spell->name.empty()) - { + } else if (!spell->name.empty()) { spell->isScripted = false; - } - else - { + } else { return false; } sb.speed = spell->interval; - sb.chance = std::min((int) spell->chance, 100); - sb.range = std::min((int) spell->range, Map::maxViewportX *2); + sb.chance = std::min((int)spell->chance, 100); + sb.range = std::min((int)spell->range, Map::maxViewportX * 2); sb.minCombatValue = std::min(spell->minCombatValue, spell->maxCombatValue); sb.maxCombatValue = std::max(spell->minCombatValue, spell->maxCombatValue); sb.spell = g_spells().getSpellByName(spell->name); - if (sb.spell) - { + if (sb.spell) { return true; } - CombatSpell *combatSpell = nullptr; + CombatSpell* combatSpell = nullptr; auto combatPtr = std::make_unique(); sb.combatSpell = true; - if (spell->length > 0) - { - spell->spread = std::max (0, spell->spread); + if (spell->length > 0) { + spell->spread = std::max(0, spell->spread); - AreaCombat *area = new AreaCombat(); + AreaCombat* area = new AreaCombat(); area->setupArea(spell->length, spell->spread); combatPtr->setArea(area); spell->needDirection = true; } - if (spell->radius > 0) - { - AreaCombat *area = new AreaCombat(); + if (spell->radius > 0) { + AreaCombat* area = new AreaCombat(); area->setupArea(spell->radius); combatPtr->setArea(area); } - if (std::string spellName = asLowerCaseString(spell->name); - spellName == "melee") - { + spellName == "melee") { sb.isMelee = true; - if (spell->attack > 0 && spell->skill > 0) - { + if (spell->attack > 0 && spell->skill > 0) { sb.minCombatValue = 0; sb.maxCombatValue = -Weapons::getMaxMeleeDamage(spell->skill, spell->attack); } @@ -132,181 +114,135 @@ bool Monsters::deserializeSpell(MonsterSpell *spell, spellBlock_t &sb, const std combatPtr->setParam(COMBAT_PARAM_BLOCKARMOR, 1); combatPtr->setParam(COMBAT_PARAM_BLOCKSHIELD, 1); combatPtr->setOrigin(ORIGIN_MELEE); - } - else if (spellName == "combat") - { - if (spell->combatType == COMBAT_PHYSICALDAMAGE) - { + } else if (spellName == "combat") { + if (spell->combatType == COMBAT_PHYSICALDAMAGE) { combatPtr->setParam(COMBAT_PARAM_BLOCKARMOR, 1); combatPtr->setOrigin(ORIGIN_RANGED); - } - else if (spell->combatType == COMBAT_HEALING) - { + } else if (spell->combatType == COMBAT_HEALING) { combatPtr->setParam(COMBAT_PARAM_AGGRESSIVE, 0); } combatPtr->setParam(COMBAT_PARAM_TYPE, spell->combatType); - } - else if (spellName == "speed") - { + } else if (spellName == "speed") { int32_t speedChange = 0; int32_t duration = 10000; - if (spell->duration != 0) - { + if (spell->duration != 0) { duration = spell->duration; } - if (spell->speedChange != 0) - { + if (spell->speedChange != 0) { speedChange = spell->speedChange; - if (speedChange < -1000) - { - //cant be slower than 100% + if (speedChange < -1000) { + // cant be slower than 100% speedChange = -1000; } } ConditionType_t conditionType; - if (speedChange > 0) - { + if (speedChange > 0) { conditionType = CONDITION_HASTE; combatPtr->setParam(COMBAT_PARAM_AGGRESSIVE, 0); - } - else - { + } else { conditionType = CONDITION_PARALYZE; } - ConditionSpeed *condition = static_cast (Condition::createCondition(CONDITIONID_COMBAT, conditionType, duration, 0)); + ConditionSpeed* condition = static_cast(Condition::createCondition(CONDITIONID_COMBAT, conditionType, duration, 0)); condition->setFormulaVars(speedChange / 1000.0, 0, speedChange / 1000.0, 0); combatPtr->addCondition(condition); - } - else if (spellName == "outfit") - { + } else if (spellName == "outfit") { int32_t duration = 10000; - if (spell->duration != 0) - { + if (spell->duration != 0) { duration = spell->duration; } - ConditionOutfit *condition = static_cast (Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)); + ConditionOutfit* condition = static_cast(Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)); - if (spell->outfitMonster != "") - { + if (spell->outfitMonster != "") { condition->setLazyMonsterOutfit(spell->outfitMonster); - } - else if (spell->outfitItem > 0) - { + } else if (spell->outfitItem > 0) { Outfit_t outfit; outfit.lookTypeEx = spell->outfitItem; condition->setOutfit(outfit); - } - else - { + } else { SPDLOG_ERROR("[Monsters::deserializeSpell] - " - "Missing outfit monster or item in outfit spell for: {}", - description); + "Missing outfit monster or item in outfit spell for: {}", + description); return false; } combatPtr->setParam(COMBAT_PARAM_AGGRESSIVE, 0); combatPtr->addCondition(condition); - } - else if (spellName == "invisible") - { + } else if (spellName == "invisible") { int32_t duration = 10000; - if (spell->duration != 0) - { + if (spell->duration != 0) { duration = spell->duration; } - Condition *condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_INVISIBLE, duration, 0); + Condition* condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_INVISIBLE, duration, 0); combatPtr->setParam(COMBAT_PARAM_AGGRESSIVE, 0); combatPtr->addCondition(condition); - } - else if (spellName == "drunk") - { + } else if (spellName == "drunk") { int32_t duration = 10000; - if (spell->duration != 0) - { + if (spell->duration != 0) { duration = spell->duration; } - Condition *condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_DRUNK, duration, 0); + Condition* condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_DRUNK, duration, 0); combatPtr->addCondition(condition); - } - else if (spellName == "firefield") - { + } else if (spellName == "firefield") { combatPtr->setParam(COMBAT_PARAM_CREATEITEM, ITEM_FIREFIELD_PVP_FULL); - } - else if (spellName == "poisonfield") - { + } else if (spellName == "poisonfield") { combatPtr->setParam(COMBAT_PARAM_CREATEITEM, ITEM_POISONFIELD_PVP); - } - else if (spellName == "energyfield") - { + } else if (spellName == "energyfield") { combatPtr->setParam(COMBAT_PARAM_CREATEITEM, ITEM_ENERGYFIELD_PVP); - } - else if (spellName == "condition") - { - if (spell->conditionType == CONDITION_NONE) - { + } else if (spellName == "condition") { + if (spell->conditionType == CONDITION_NONE) { SPDLOG_ERROR("[Monsters::deserializeSpell] - " - "{} condition is not set for: {}", description, spell->name); + "{} condition is not set for: {}", + description, spell->name); } - } - else if (spellName == "strength") - { + } else if (spellName == "strength") { // - } - else if (spellName == "effect") - { + } else if (spellName == "effect") { // - } - else - { + } else { SPDLOG_ERROR("[Monsters::deserializeSpell] - " - "{} unknown or missing parameter on spell with name: {}", description, spell->name); + "{} unknown or missing parameter on spell with name: {}", + description, spell->name); } - if (spell->shoot != CONST_ANI_NONE) - { + if (spell->shoot != CONST_ANI_NONE) { combatPtr->setParam(COMBAT_PARAM_DISTANCEEFFECT, spell->shoot); } - if (spell->effect != CONST_ME_NONE) - { + if (spell->effect != CONST_ME_NONE) { combatPtr->setParam(COMBAT_PARAM_EFFECT, spell->effect); } // If a spell has a condition, it always applies, no matter what kind of spell it is - if (spell->conditionType != CONDITION_NONE) - { + if (spell->conditionType != CONDITION_NONE) { int32_t minDamage = std::abs(spell->conditionMinDamage); int32_t maxDamage = std::abs(spell->conditionMaxDamage); int32_t startDamage = std::abs(spell->conditionStartDamage); uint32_t tickInterval = 2000; - if (spell->tickInterval > 0) - { + if (spell->tickInterval > 0) { tickInterval = spell->tickInterval; } - if (startDamage > minDamage) - { + if (startDamage > minDamage) { startDamage = 0; } - if (maxDamage == 0) - { + if (maxDamage == 0) { maxDamage = minDamage; } - Condition *condition = getDamageCondition(spell->conditionType, maxDamage, minDamage, startDamage, tickInterval); + Condition* condition = getDamageCondition(spell->conditionType, maxDamage, minDamage, startDamage, tickInterval); combatPtr->addCondition(condition); } @@ -314,16 +250,14 @@ bool Monsters::deserializeSpell(MonsterSpell *spell, spellBlock_t &sb, const std combatSpell = new CombatSpell(combatPtr.release(), spell->needTarget, spell->needDirection); sb.spell = combatSpell; - if (combatSpell) - { + if (combatSpell) { sb.combatSpell = true; } return true; } -bool MonsterType::loadCallback(LuaScriptInterface* scriptInterface) -{ +bool MonsterType::loadCallback(LuaScriptInterface* scriptInterface) { int32_t id = scriptInterface->getEvent(); if (id == -1) { SPDLOG_WARN("[MonsterType::loadCallback] - Event not found"); @@ -345,14 +279,12 @@ bool MonsterType::loadCallback(LuaScriptInterface* scriptInterface) return true; } -MonsterType* Monsters::getMonsterType(const std::string& name) -{ +MonsterType* Monsters::getMonsterType(const std::string &name) { std::string lowerCaseName = asLowerCaseString(name); if (auto it = monsters.find(lowerCaseName); - it != monsters.end() - // We will only return the MonsterType if it match the exact name of the monster - && it->first.find(lowerCaseName) != it->first.npos) - { + it != monsters.end() + // We will only return the MonsterType if it match the exact name of the monster + && it->first.find(lowerCaseName) != it->first.npos) { return it->second; } SPDLOG_ERROR("[Monsters::getMonsterType] - Monster with name {} not exist", lowerCaseName); @@ -369,8 +301,7 @@ MonsterType* Monsters::getMonsterTypeByRaceId(uint16_t thisrace) { return (mtype ? mtype : nullptr); } -void Monsters::addMonsterType(const std::string& name, MonsterType* mType) -{ +void Monsters::addMonsterType(const std::string &name, MonsterType* mType) { std::string lowerName = asLowerCaseString(name); monsters[lowerName] = mType; } diff --git a/src/creatures/monsters/monsters.h b/src/creatures/monsters/monsters.h index 675a94b3ac7..3b3ea65ae54 100644 --- a/src/creatures/monsters/monsters.h +++ b/src/creatures/monsters/monsters.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_MONSTERS_MONSTERS_H_ #define SRC_CREATURES_MONSTERS_MONSTERS_H_ @@ -18,138 +18,138 @@ class Loot { Loot() = default; // non-copyable - Loot(const Loot&) = delete; - Loot& operator=(const Loot&) = delete; + Loot(const Loot &) = delete; + Loot &operator=(const Loot &) = delete; LootBlock lootBlock; }; class BaseSpell; struct spellBlock_t { - constexpr spellBlock_t() = default; - ~spellBlock_t(); - spellBlock_t(const spellBlock_t& other) = delete; - spellBlock_t& operator=(const spellBlock_t& other) = delete; - spellBlock_t(spellBlock_t&& other) : - spell(other.spell), - chance(other.chance), - speed(other.speed), - range(other.range), - minCombatValue(other.minCombatValue), - maxCombatValue(other.maxCombatValue), - combatSpell(other.combatSpell), - isMelee(other.isMelee) { - other.spell = nullptr; - } - - BaseSpell* spell = nullptr; - uint32_t chance = 100; - uint32_t speed = 2000; - uint32_t range = 0; - int32_t minCombatValue = 0; - int32_t maxCombatValue = 0; - bool combatSpell = false; - bool isMelee = false; -}; - -class MonsterType -{ - struct MonsterInfo { - LuaScriptInterface* scriptInterface; - - std::map elementMap; - std::map reflectMap; - std::map healingMap; - - std::vector voiceVector; + constexpr spellBlock_t() = default; + ~spellBlock_t(); + spellBlock_t(const spellBlock_t &other) = delete; + spellBlock_t &operator=(const spellBlock_t &other) = delete; + spellBlock_t(spellBlock_t &&other) : + spell(other.spell), + chance(other.chance), + speed(other.speed), + range(other.range), + minCombatValue(other.minCombatValue), + maxCombatValue(other.maxCombatValue), + combatSpell(other.combatSpell), + isMelee(other.isMelee) { + other.spell = nullptr; + } - std::vector lootItems; - std::vector scripts; - std::vector attackSpells; - std::vector defenseSpells; - std::vector summons; + BaseSpell* spell = nullptr; + uint32_t chance = 100; + uint32_t speed = 2000; + uint32_t range = 0; + int32_t minCombatValue = 0; + int32_t maxCombatValue = 0; + bool combatSpell = false; + bool isMelee = false; +}; - Skulls_t skull = SKULL_NONE; - Outfit_t outfit = {}; - RaceType_t race = RACE_BLOOD; - RespawnType respawnType = {}; - - LightInfo light = {}; - uint16_t lookcorpse = 0; - uint16_t baseSpeed = 110; - - uint64_t experience = 0; - - uint32_t manaCost = 0; - uint32_t yellChance = 0; - uint32_t yellSpeedTicks = 0; - uint32_t staticAttackChance = 95; - uint32_t maxSummons = 0; - uint32_t changeTargetSpeed = 0; - uint32_t conditionImmunities = 0; - uint32_t damageImmunities = 0; - - // Bestiary - uint8_t bestiaryOccurrence = 0; - uint8_t bestiaryStars = 0; - uint16_t bestiaryToUnlock = 0; - uint16_t bestiaryFirstUnlock = 0; - uint16_t bestiarySecondUnlock = 0; - uint16_t bestiaryCharmsPoints = 0; - uint16_t raceid = 0; - std::string bestiaryLocations; - std::string bestiaryClass; // String (addString) - BestiaryType_t bestiaryRace = BESTY_RACE_NONE; // Number (addByte) - - int32_t creatureAppearEvent = -1; - int32_t creatureDisappearEvent = -1; - int32_t creatureMoveEvent = -1; - int32_t creatureSayEvent = -1; - int32_t thinkEvent = -1; - int32_t targetDistance = 1; - int32_t runAwayHealth = 0; - int32_t health = 100; - int32_t healthMax = 100; - int32_t changeTargetChance = 0; - int32_t defense = 0; - int32_t armor = 0; - int32_t strategiesTargetNearest = 0; - int32_t strategiesTargetHealth = 0; - int32_t strategiesTargetDamage = 0; - int32_t strategiesTargetRandom = 0; - bool targetPreferPlayer = false; - bool targetPreferMaster = false; - - Faction_t faction = FACTION_DEFAULT; - phmap::flat_hash_set enemyFactions; - - bool canPushItems = false; - bool canPushCreatures = false; - bool pushable = true; - bool isSummonable = false; - bool isIllusionable = false; - bool isConvinceable = false; - bool isAttackable = true; - bool isHostile = true; - bool hiddenHealth = false; - bool isBlockable = false; - bool isFamiliar = false; - bool isRewardBoss = false; - bool canWalkOnEnergy = true; - bool canWalkOnFire = true; - bool canWalkOnPoison = true; - bool isForgeCreature = true; - - MonstersEvent_t eventType = MONSTERS_EVENT_NONE; - }; +class MonsterType { + struct MonsterInfo { + LuaScriptInterface* scriptInterface; + + std::map elementMap; + std::map reflectMap; + std::map healingMap; + + std::vector voiceVector; + + std::vector lootItems; + std::vector scripts; + std::vector attackSpells; + std::vector defenseSpells; + std::vector summons; + + Skulls_t skull = SKULL_NONE; + Outfit_t outfit = {}; + RaceType_t race = RACE_BLOOD; + RespawnType respawnType = {}; + + LightInfo light = {}; + uint16_t lookcorpse = 0; + uint16_t baseSpeed = 110; + + uint64_t experience = 0; + + uint32_t manaCost = 0; + uint32_t yellChance = 0; + uint32_t yellSpeedTicks = 0; + uint32_t staticAttackChance = 95; + uint32_t maxSummons = 0; + uint32_t changeTargetSpeed = 0; + uint32_t conditionImmunities = 0; + uint32_t damageImmunities = 0; + + // Bestiary + uint8_t bestiaryOccurrence = 0; + uint8_t bestiaryStars = 0; + uint16_t bestiaryToUnlock = 0; + uint16_t bestiaryFirstUnlock = 0; + uint16_t bestiarySecondUnlock = 0; + uint16_t bestiaryCharmsPoints = 0; + uint16_t raceid = 0; + std::string bestiaryLocations; + std::string bestiaryClass; // String (addString) + BestiaryType_t bestiaryRace = BESTY_RACE_NONE; // Number (addByte) + + int32_t creatureAppearEvent = -1; + int32_t creatureDisappearEvent = -1; + int32_t creatureMoveEvent = -1; + int32_t creatureSayEvent = -1; + int32_t thinkEvent = -1; + int32_t targetDistance = 1; + int32_t runAwayHealth = 0; + int32_t health = 100; + int32_t healthMax = 100; + int32_t changeTargetChance = 0; + int32_t defense = 0; + int32_t armor = 0; + int32_t strategiesTargetNearest = 0; + int32_t strategiesTargetHealth = 0; + int32_t strategiesTargetDamage = 0; + int32_t strategiesTargetRandom = 0; + bool targetPreferPlayer = false; + bool targetPreferMaster = false; + + Faction_t faction = FACTION_DEFAULT; + phmap::flat_hash_set enemyFactions; + + bool canPushItems = false; + bool canPushCreatures = false; + bool pushable = true; + bool isSummonable = false; + bool isIllusionable = false; + bool isConvinceable = false; + bool isAttackable = true; + bool isHostile = true; + bool hiddenHealth = false; + bool isBlockable = false; + bool isFamiliar = false; + bool isRewardBoss = false; + bool canWalkOnEnergy = true; + bool canWalkOnFire = true; + bool canWalkOnPoison = true; + bool isForgeCreature = true; + + MonstersEvent_t eventType = MONSTERS_EVENT_NONE; + }; public: MonsterType() = default; - explicit MonsterType(const std::string &initName) : name(initName), typeName(initName), nameDescription(initName) {}; + explicit MonsterType(const std::string &initName) : + name(initName), typeName(initName), nameDescription(initName) {}; // non-copyable - MonsterType(const MonsterType&) = delete; - MonsterType& operator=(const MonsterType&) = delete; + MonsterType(const MonsterType &) = delete; + MonsterType &operator=(const MonsterType &) = delete; bool loadCallback(LuaScriptInterface* scriptInterface); @@ -169,16 +169,15 @@ class MonsterType void loadLoot(MonsterType* monsterType, LootBlock lootblock); - bool canSpawn(const Position& pos); + bool canSpawn(const Position &pos); }; -class MonsterSpell -{ +class MonsterSpell { public: MonsterSpell() = default; - MonsterSpell(const MonsterSpell&) = delete; - MonsterSpell& operator=(const MonsterSpell&) = delete; + MonsterSpell(const MonsterSpell &) = delete; + MonsterSpell &operator=(const MonsterSpell &) = delete; std::string name = ""; std::string scriptName = ""; @@ -218,36 +217,34 @@ class MonsterSpell CombatType_t combatType = COMBAT_UNDEFINEDDAMAGE; }; -class Monsters -{ +class Monsters { public: Monsters() = default; // non-copyable - Monsters(const Monsters&) = delete; - Monsters& operator=(const Monsters&) = delete; + Monsters(const Monsters &) = delete; + Monsters &operator=(const Monsters &) = delete; - static Monsters& getInstance() { + static Monsters &getInstance() { // Guaranteed to be destroyed static Monsters instance; // Instantiated on first use return instance; } - MonsterType* getMonsterType(const std::string& name); + MonsterType* getMonsterType(const std::string &name); MonsterType* getMonsterTypeByRaceId(uint16_t thisrace); - void addMonsterType(const std::string& name, MonsterType* mType); - bool deserializeSpell(MonsterSpell* spell, spellBlock_t& sb, const std::string& description = ""); + void addMonsterType(const std::string &name, MonsterType* mType); + bool deserializeSpell(MonsterSpell* spell, spellBlock_t &sb, const std::string &description = ""); std::unique_ptr scriptInterface; std::map monsters; private: - ConditionDamage* getDamageCondition(ConditionType_t conditionType, - int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval); + ConditionDamage* getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval); - MonsterType* loadMonster(const std::string& file, const std::string& monsterName, bool reloading = false); + MonsterType* loadMonster(const std::string &file, const std::string &monsterName, bool reloading = false); }; constexpr auto g_monsters = &Monsters::getInstance; -#endif // SRC_CREATURES_MONSTERS_MONSTERS_H_ +#endif // SRC_CREATURES_MONSTERS_MONSTERS_H_ diff --git a/src/creatures/monsters/spawns/spawn_monster.cpp b/src/creatures/monsters/spawns/spawn_monster.cpp index 00b8210b56c..b45e3ac4f77 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -20,8 +20,7 @@ static constexpr int32_t MONSTER_MINSPAWN_INTERVAL = 1000; // 1 second static constexpr int32_t MONSTER_MAXSPAWN_INTERVAL = 86400000; // 1 day -bool SpawnsMonster::loadFromXML(const std::string& filemonstername) -{ +bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { if (isLoaded()) { return true; } @@ -60,7 +59,7 @@ bool SpawnsMonster::loadFromXML(const std::string& filemonstername) } spawnMonsterList.emplace_front(centerPos, radius); - SpawnMonster& spawnMonster = spawnMonsterList.front(); + SpawnMonster &spawnMonster = spawnMonsterList.front(); for (auto childMonsterNode : spawnMonsterNode.children()) { if (strcasecmp(childMonsterNode.name(), "monster") == 0) { @@ -87,7 +86,7 @@ bool SpawnsMonster::loadFromXML(const std::string& filemonstername) ); int32_t boostedrate = 1; - + if (nameAttribute.value() == boostedNameGet) { boostedrate = 2; } @@ -97,7 +96,8 @@ bool SpawnsMonster::loadFromXML(const std::string& filemonstername) spawnMonster.addMonster(nameAttribute.as_string(), pos, dir, static_cast(interval)); } else { if (interval <= MONSTER_MINSPAWN_INTERVAL) { - SPDLOG_WARN("[SpawnsMonster::loadFromXml] - {} {} spawntime cannot be less than {} seconds, set to {} by default.", nameAttribute.as_string(), pos.toString(), MONSTER_MINSPAWN_INTERVAL / 1000, MONSTER_MINSPAWN_INTERVAL / 1000); spawnMonster.addMonster(nameAttribute.as_string(), pos, dir, MONSTER_MINSPAWN_INTERVAL); + SPDLOG_WARN("[SpawnsMonster::loadFromXml] - {} {} spawntime cannot be less than {} seconds, set to {} by default.", nameAttribute.as_string(), pos.toString(), MONSTER_MINSPAWN_INTERVAL / 1000, MONSTER_MINSPAWN_INTERVAL / 1000); + spawnMonster.addMonster(nameAttribute.as_string(), pos, dir, MONSTER_MINSPAWN_INTERVAL); } else { SPDLOG_WARN("[SpawnsMonster::loadFromXml] - {} {} spawntime can not be more than {} seconds", nameAttribute.as_string(), pos.toString(), MONSTER_MAXSPAWN_INTERVAL / 1000); } @@ -108,22 +108,20 @@ bool SpawnsMonster::loadFromXML(const std::string& filemonstername) return true; } -void SpawnsMonster::startup() -{ +void SpawnsMonster::startup() { if (!isLoaded() || isStarted()) { return; } - for (SpawnMonster& spawnMonster : spawnMonsterList) { + for (SpawnMonster &spawnMonster : spawnMonsterList) { spawnMonster.startup(); } started = true; } -void SpawnsMonster::clear() -{ - for (SpawnMonster& spawnMonster : spawnMonsterList) { +void SpawnsMonster::clear() { + for (SpawnMonster &spawnMonster : spawnMonsterList) { spawnMonster.stopEvent(); } spawnMonsterList.clear(); @@ -133,34 +131,29 @@ void SpawnsMonster::clear() filemonstername.clear(); } -bool SpawnsMonster::isInZone(const Position& centerPos, int32_t radius, const Position& pos) -{ +bool SpawnsMonster::isInZone(const Position ¢erPos, int32_t radius, const Position &pos) { if (radius == -1) { return true; } - return ((pos.getX() >= centerPos.getX() - radius) && (pos.getX() <= centerPos.getX() + radius) && - (pos.getY() >= centerPos.getY() - radius) && (pos.getY() <= centerPos.getY() + radius)); + return ((pos.getX() >= centerPos.getX() - radius) && (pos.getX() <= centerPos.getX() + radius) && (pos.getY() >= centerPos.getY() - radius) && (pos.getY() <= centerPos.getY() + radius)); } -void SpawnMonster::startSpawnMonsterCheck() -{ +void SpawnMonster::startSpawnMonsterCheck() { if (checkSpawnMonsterEvent == 0) { checkSpawnMonsterEvent = g_scheduler().addEvent(createSchedulerTask(getInterval(), std::bind(&SpawnMonster::checkSpawnMonster, this))); } } -SpawnMonster::~SpawnMonster() -{ - for (const auto& it : spawnedMonsterMap) { +SpawnMonster::~SpawnMonster() { + for (const auto &it : spawnedMonsterMap) { Monster* monster = it.second; monster->setSpawnMonster(nullptr); monster->decrementReferenceCounter(); } } -bool SpawnMonster::findPlayer(const Position& pos) -{ +bool SpawnMonster::findPlayer(const Position &pos) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, pos, false, true); for (Creature* spectator : spectators) { @@ -171,16 +164,14 @@ bool SpawnMonster::findPlayer(const Position& pos) return false; } -bool SpawnMonster::isInSpawnMonsterZone(const Position& pos) -{ +bool SpawnMonster::isInSpawnMonsterZone(const Position &pos) { return SpawnsMonster::isInZone(centerPos, radius, pos); } -bool SpawnMonster::spawnMonster(uint32_t spawnMonsterId, MonsterType* monsterType, const Position& pos, Direction dir, bool startup /*= false*/) -{ +bool SpawnMonster::spawnMonster(uint32_t spawnMonsterId, MonsterType* monsterType, const Position &pos, Direction dir, bool startup /*= false*/) { std::unique_ptr monster_ptr(new Monster(monsterType)); if (startup) { - //No need to send out events to the surrounding since there is no one out there to listen! + // No need to send out events to the surrounding since there is no one out there to listen! if (!g_game().internalPlaceCreature(monster_ptr.get(), pos, true)) { return false; } @@ -202,30 +193,28 @@ bool SpawnMonster::spawnMonster(uint32_t spawnMonsterId, MonsterType* monsterTyp return true; } -void SpawnMonster::startup() -{ - for (const auto& it : spawnMonsterMap) { +void SpawnMonster::startup() { + for (const auto &it : spawnMonsterMap) { uint32_t spawnMonsterId = it.first; - const spawnBlock_t& sb = it.second; + const spawnBlock_t &sb = it.second; spawnMonster(spawnMonsterId, sb.monsterType, sb.pos, sb.direction, true); } } -void SpawnMonster::checkSpawnMonster() -{ +void SpawnMonster::checkSpawnMonster() { checkSpawnMonsterEvent = 0; cleanup(); uint32_t spawnMonsterCount = 0; - for (auto& it : spawnMonsterMap) { + for (auto &it : spawnMonsterMap) { uint32_t spawnMonsterId = it.first; if (spawnedMonsterMap.find(spawnMonsterId) != spawnedMonsterMap.end()) { continue; } - spawnBlock_t& sb = it.second; + spawnBlock_t &sb = it.second; if (!sb.monsterType->canSpawn(sb.pos)) { sb.lastSpawn = OTSYS_TIME(); continue; @@ -254,8 +243,7 @@ void SpawnMonster::checkSpawnMonster() } } -void SpawnMonster::scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t& sb, uint16_t interval) -{ +void SpawnMonster::scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, uint16_t interval) { if (interval <= 0) { spawnMonster(spawnMonsterId, sb.monsterType, sb.pos, sb.direction); } else { @@ -264,14 +252,13 @@ void SpawnMonster::scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t& sb, uint } } -void SpawnMonster::cleanup() -{ +void SpawnMonster::cleanup() { auto it = spawnedMonsterMap.begin(); while (it != spawnedMonsterMap.end()) { - uint32_t spawnMonsterId = it->first; + uint32_t spawnMonsterId = it->first; Monster* monster = it->second; - if (monster->isRemoved()) { - spawnMonsterMap[spawnMonsterId].lastSpawn = OTSYS_TIME(); + if (monster->isRemoved()) { + spawnMonsterMap[spawnMonsterId].lastSpawn = OTSYS_TIME(); monster->decrementReferenceCounter(); it = spawnedMonsterMap.erase(it); } else { @@ -280,8 +267,7 @@ void SpawnMonster::cleanup() } } -bool SpawnMonster::addMonster(const std::string& name, const Position& pos, Direction dir, uint32_t scheduleInterval) -{ +bool SpawnMonster::addMonster(const std::string &name, const Position &pos, Direction dir, uint32_t scheduleInterval) { MonsterType* monsterType = g_monsters().getMonsterType(name); if (!monsterType) { SPDLOG_ERROR("Can not find {}", name); @@ -302,8 +288,7 @@ bool SpawnMonster::addMonster(const std::string& name, const Position& pos, Dire return true; } -void SpawnMonster::removeMonster(Monster* monster) -{ +void SpawnMonster::removeMonster(Monster* monster) { for (auto it = spawnedMonsterMap.begin(), end = spawnedMonsterMap.end(); it != end; ++it) { if (it->second == monster) { monster->decrementReferenceCounter(); @@ -313,8 +298,7 @@ void SpawnMonster::removeMonster(Monster* monster) } } -void SpawnMonster::stopEvent() -{ +void SpawnMonster::stopEvent() { if (checkSpawnMonsterEvent != 0) { g_scheduler().stopEvent(checkSpawnMonsterEvent); checkSpawnMonsterEvent = 0; diff --git a/src/creatures/monsters/spawns/spawn_monster.h b/src/creatures/monsters/spawns/spawn_monster.h index afc529817c7..ef87cbe74a2 100644 --- a/src/creatures/monsters/spawns/spawn_monster.h +++ b/src/creatures/monsters/spawns/spawn_monster.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_MONSTERS_SPAWNS_SPAWN_MONSTER_H_ #define SRC_CREATURES_MONSTERS_SPAWNS_SPAWN_MONSTER_H_ @@ -17,24 +17,24 @@ class Monster; class MonsterType; struct spawnBlock_t { - Position pos; - MonsterType* monsterType; - int64_t lastSpawn; - uint32_t interval; - Direction direction; + Position pos; + MonsterType* monsterType; + int64_t lastSpawn; + uint32_t interval; + Direction direction; }; -class SpawnMonster -{ +class SpawnMonster { public: - SpawnMonster(Position initPos, int32_t initRadius) : centerPos(std::move(initPos)), radius(initRadius) {} + SpawnMonster(Position initPos, int32_t initRadius) : + centerPos(std::move(initPos)), radius(initRadius) { } ~SpawnMonster(); // non-copyable - SpawnMonster(const SpawnMonster&) = delete; - SpawnMonster& operator=(const SpawnMonster&) = delete; + SpawnMonster(const SpawnMonster &) = delete; + SpawnMonster &operator=(const SpawnMonster &) = delete; - bool addMonster(const std::string& name, const Position& pos, Direction dir, uint32_t interval); + bool addMonster(const std::string &name, const Position &pos, Direction dir, uint32_t interval); void removeMonster(Monster* monster); uint32_t getInterval() const { @@ -45,16 +45,16 @@ class SpawnMonster void startSpawnMonsterCheck(); void stopEvent(); - bool isInSpawnMonsterZone(const Position& pos); + bool isInSpawnMonsterZone(const Position &pos); void cleanup(); private: - //map of the spawned creatures + // map of the spawned creatures using SpawnedMap = std::multimap; using spawned_pair = SpawnedMap::value_type; SpawnedMap spawnedMonsterMap; - //map of creatures in the spawn + // map of creatures in the spawn std::map spawnMonsterMap; Position centerPos; @@ -63,18 +63,17 @@ class SpawnMonster uint32_t interval = 30000; uint32_t checkSpawnMonsterEvent = 0; - static bool findPlayer(const Position& pos); - bool spawnMonster(uint32_t spawnMonsterId, MonsterType* monsterType, const Position& pos, Direction dir, bool startup = false); + static bool findPlayer(const Position &pos); + bool spawnMonster(uint32_t spawnMonsterId, MonsterType* monsterType, const Position &pos, Direction dir, bool startup = false); void checkSpawnMonster(); - void scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t& sb, uint16_t interval); + void scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, uint16_t interval); }; -class SpawnsMonster -{ +class SpawnsMonster { public: - static bool isInZone(const Position& centerPos, int32_t radius, const Position& pos); + static bool isInZone(const Position ¢erPos, int32_t radius, const Position &pos); - bool loadFromXML(const std::string& filemonstername); + bool loadFromXML(const std::string &filemonstername); void startup(); void clear(); @@ -84,7 +83,7 @@ class SpawnsMonster bool isLoaded() const { return loaded; } - std::forward_list& getspawnMonsterList() { + std::forward_list &getspawnMonsterList() { return spawnMonsterList; } @@ -97,4 +96,4 @@ class SpawnsMonster static constexpr int32_t NONBLOCKABLE_SPAWN_MONSTER_INTERVAL = 1400; -#endif // SRC_CREATURES_MONSTERS_SPAWNS_SPAWN_MONSTER_H_ +#endif // SRC_CREATURES_MONSTERS_SPAWNS_SPAWN_MONSTER_H_ diff --git a/src/creatures/npcs/npc.cpp b/src/creatures/npcs/npc.cpp index 4440e8b7ad5..a0664b663e7 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -20,8 +20,7 @@ int32_t Npc::despawnRadius; uint32_t Npc::npcAutoID = 0x80000000; -Npc* Npc::createNpc(const std::string& name) -{ +Npc* Npc::createNpc(const std::string &name) { NpcType* npcType = g_npcs().getNpcType(name); if (!npcType) { return nullptr; @@ -32,19 +31,18 @@ Npc* Npc::createNpc(const std::string& name) Npc::Npc(NpcType* npcType) : Creature(), strDescription(npcType->nameDescription), - npcType(npcType) -{ + npcType(npcType) { defaultOutfit = npcType->info.outfit; currentOutfit = npcType->info.outfit; float multiplier = g_configManager().getFloat(RATE_NPC_HEALTH); - health = npcType->info.health*multiplier; - healthMax = npcType->info.healthMax*multiplier; + health = npcType->info.health * multiplier; + healthMax = npcType->info.healthMax * multiplier; baseSpeed = npcType->info.baseSpeed; internalLight = npcType->info.light; floorChange = npcType->info.floorChange; // register creature events - for (const std::string& scriptName : npcType->info.scripts) { + for (const std::string &scriptName : npcType->info.scripts) { if (!registerCreatureEvent(scriptName)) { SPDLOG_WARN("Unknown event name: {}", scriptName); } @@ -54,34 +52,29 @@ Npc::Npc(NpcType* npcType) : Npc::~Npc() { } -void Npc::addList() -{ +void Npc::addList() { g_game().addNpc(this); } -void Npc::removeList() -{ +void Npc::removeList() { g_game().removeNpc(this); } -bool Npc::canSee(const Position& pos) const -{ +bool Npc::canSee(const Position &pos) const { if (pos.z != getPosition().z) { return false; } return Creature::canSee(getPosition(), pos, 4, 4); } -bool Npc::canSeeRange(const Position& pos, int32_t viewRangeX/* = 4*/, int32_t viewRangeY/* = 4*/) const -{ +bool Npc::canSeeRange(const Position &pos, int32_t viewRangeX /* = 4*/, int32_t viewRangeY /* = 4*/) const { if (pos.z != getPosition().z) { return false; } return Creature::canSee(getPosition(), pos, viewRangeX, viewRangeY); } -void Npc::onCreatureAppear(Creature* creature, bool isLogin) -{ +void Npc::onCreatureAppear(Creature* creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); // onCreatureAppear(self, creature) @@ -96,8 +89,7 @@ void Npc::onCreatureAppear(Creature* creature, bool isLogin) } } -void Npc::onRemoveCreature(Creature* creature, bool isLogout) -{ +void Npc::onRemoveCreature(Creature* creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); // onCreatureDisappear(self, creature) @@ -123,9 +115,7 @@ void Npc::onRemoveCreature(Creature* creature, bool isLogout) shopPlayerSet.clear(); } -void Npc::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport) -{ +void Npc::onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) { Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); // onCreatureMove(self, creature, oldPosition, newPosition) @@ -147,15 +137,14 @@ void Npc::onCreatureMove(Creature* creature, const Tile* newTile, const Position return; } - Player *player = creature->getPlayer(); + Player* player = creature->getPlayer(); if (player && !canSee(newPos) && canSee(oldPos)) { updatePlayerInteractions(player); player->closeShopWindow(true); } } -void Npc::onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) -{ +void Npc::onCreatureSay(Creature* creature, SpeakClasses type, const std::string &text) { Creature::onCreatureSay(creature, type, text); if (!creature->getPlayer()) { @@ -176,8 +165,7 @@ void Npc::onCreatureSay(Creature* creature, SpeakClasses type, const std::string } } -void Npc::onThink(uint32_t interval) -{ +void Npc::onThink(uint32_t interval) { Creature::onThink(interval); // onThink(self, interval) @@ -206,19 +194,17 @@ void Npc::onThink(uint32_t interval) g_game().map.getSpectators(spectators, position, false, false); // Check if there is at least one player in the set of spectators that does not have the "IgnoredByNpcs" flag if (std::ranges::any_of(spectators, [](Creature* spectator) { - auto player = spectator->getPlayer(); - // If there are no players or all players have the "IgnoredByNpcs" flag, then the NPC will not walk or yell. - return player && !player->hasFlag(PlayerFlags_t::IgnoredByNpcs); - })) { + auto player = spectator->getPlayer(); + // If there are no players or all players have the "IgnoredByNpcs" flag, then the NPC will not walk or yell. + return player && !player->hasFlag(PlayerFlags_t::IgnoredByNpcs); + })) { // There is at least one normal player on the screen, so the NPC should continue walking and yelling onThinkYell(interval); onThinkWalk(interval); } } -void Npc::onPlayerBuyItem(Player* player, uint16_t itemId, - uint8_t subType, uint16_t amount, bool ignore, bool inBackpacks) -{ +void Npc::onPlayerBuyItem(Player* player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore, bool inBackpacks) { if (player == nullptr) { SPDLOG_ERROR("[Npc::onPlayerBuyItem] - Player is nullptr"); return; @@ -232,7 +218,7 @@ void Npc::onPlayerBuyItem(Player* player, uint16_t itemId, uint32_t shoppingBagPrice = 20; uint32_t shoppingBagSlots = 20; - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; if (const Tile* tile = ignore ? player->getTile() : nullptr; tile) { double slotsNedeed = 0; if (itemType.stackable) { @@ -291,20 +277,16 @@ void Npc::onPlayerBuyItem(Player* player, uint16_t itemId, } } -void Npc::onPlayerSellItem(Player* player, uint16_t itemId, - uint8_t subType, uint16_t amount, bool ignore) -{ +void Npc::onPlayerSellItem(Player* player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore) { if (!player) { return; } uint32_t sellPrice = 0; - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; const std::vector &shopVector = getShopItemVector(); - for (ShopBlock shopBlock : shopVector) - { - if (itemType.id == shopBlock.itemId && shopBlock.itemSellPrice != 0) - { + for (ShopBlock shopBlock : shopVector) { + if (itemType.id == shopBlock.itemId && shopBlock.itemSellPrice != 0) { sellPrice = shopBlock.itemSellPrice; } } @@ -324,8 +306,7 @@ void Npc::onPlayerSellItem(Player* player, uint16_t itemId, removeAmount -= removeCount; if (auto ret = g_game().internalRemoveItem(item, removeCount); - ret != RETURNVALUE_NOERROR) - { + ret != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Npc::onPlayerSellItem] - Player {} have a problem for sell item {} on shop for npc {}", player->getName(), item->getID(), getName()); continue; } @@ -366,14 +347,12 @@ void Npc::onPlayerSellItem(Player* player, uint16_t itemId, } } -void Npc::onPlayerCheckItem(Player* player, uint16_t itemId, - uint8_t subType) -{ +void Npc::onPlayerCheckItem(Player* player, uint16_t itemId, uint8_t subType) { if (!player) { return; } - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; // onPlayerCheckItem(self, player, itemId, subType) CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, this); if (callback.startScriptInterface(npcType->info.playerLookEvent)) { @@ -388,8 +367,7 @@ void Npc::onPlayerCheckItem(Player* player, uint16_t itemId, } } -void Npc::onPlayerCloseChannel(Creature* creature) -{ +void Npc::onPlayerCloseChannel(Creature* creature) { Player* player = creature->getPlayer(); if (!player) { return; @@ -410,8 +388,7 @@ void Npc::onPlayerCloseChannel(Creature* creature) this->removePlayerInteraction(player->getID()); } -void Npc::onThinkYell(uint32_t interval) -{ +void Npc::onThinkYell(uint32_t interval) { if (npcType->info.yellSpeedTicks == 0) { return; } @@ -422,7 +399,7 @@ void Npc::onThinkYell(uint32_t interval) if (!npcType->info.voiceVector.empty() && (npcType->info.yellChance >= static_cast(uniform_random(1, 100)))) { uint32_t index = uniform_random(0, npcType->info.voiceVector.size() - 1); - const voiceBlock_t& vb = npcType->info.voiceVector[index]; + const voiceBlock_t &vb = npcType->info.voiceVector[index]; if (vb.yellText) { g_game().internalCreatureSay(this, TALKTYPE_YELL, vb.text, false); @@ -433,8 +410,7 @@ void Npc::onThinkYell(uint32_t interval) } } -void Npc::onThinkWalk(uint32_t interval) -{ +void Npc::onThinkWalk(uint32_t interval) { if (npcType->info.walkInterval == 0 || baseSpeed == 0) { return; } @@ -452,8 +428,7 @@ void Npc::onThinkWalk(uint32_t interval) } if (Direction newDirection; - getRandomStep(newDirection)) - { + getRandomStep(newDirection)) { listWalkDir.push_front(newDirection); addEventWalk(); } @@ -461,13 +436,11 @@ void Npc::onThinkWalk(uint32_t interval) walkTicks = 0; } -void Npc::onPlacedCreature() -{ +void Npc::onPlacedCreature() { addEventWalk(); } -bool Npc::isInSpawnRange(const Position& pos) const -{ +bool Npc::isInSpawnRange(const Position &pos) const { if (!spawnNpc) { return true; } @@ -518,8 +491,7 @@ void Npc::resetPlayerInteractions() { playerInteractions.clear(); } -bool Npc::canWalkTo(const Position& fromPos, Direction dir) const -{ +bool Npc::canWalkTo(const Position &fromPos, Direction dir) const { if (npcType->info.walkRadius == 0) { return false; } @@ -545,12 +517,11 @@ bool Npc::canWalkTo(const Position& fromPos, Direction dir) const return true; } -bool Npc::getNextStep(Direction& nextDirection, uint32_t& flags) { +bool Npc::getNextStep(Direction &nextDirection, uint32_t &flags) { return Creature::getNextStep(nextDirection, flags); } -bool Npc::getRandomStep(Direction& moveDirection) const -{ +bool Npc::getRandomStep(Direction &moveDirection) const { static std::vector directionvector { Direction::DIRECTION_NORTH, Direction::DIRECTION_WEST, @@ -559,9 +530,8 @@ bool Npc::getRandomStep(Direction& moveDirection) const }; std::ranges::shuffle(directionvector, getRandomGenerator()); - for (const Position& creaturePos = getPosition(); - Direction direction : directionvector) - { + for (const Position &creaturePos = getPosition(); + Direction direction : directionvector) { if (canWalkTo(creaturePos, direction)) { moveDirection = direction; return true; @@ -570,20 +540,17 @@ bool Npc::getRandomStep(Direction& moveDirection) const return false; } -void Npc::addShopPlayer(Player* player) -{ +void Npc::addShopPlayer(Player* player) { shopPlayerSet.insert(player); } -void Npc::removeShopPlayer(Player* player) -{ +void Npc::removeShopPlayer(Player* player) { if (player) { shopPlayerSet.erase(player); } } -void Npc::closeAllShopWindows() -{ +void Npc::closeAllShopWindows() { for (auto shopPlayer : shopPlayerSet) { if (shopPlayer) { shopPlayer->closeShopWindow(); diff --git a/src/creatures/npcs/npc.h b/src/creatures/npcs/npc.h index 32b82a608fe..4f7c2f6ff93 100644 --- a/src/creatures/npcs/npc.h +++ b/src/creatures/npcs/npc.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_NPCS_NPC_H_ #define SRC_CREATURES_NPCS_NPC_H_ @@ -18,10 +18,9 @@ class Creature; class Game; class SpawnNpc; -class Npc final : public Creature -{ +class Npc final : public Creature { public: - static Npc* createNpc(const std::string& name); + static Npc* createNpc(const std::string &name); static int32_t despawnRange; static int32_t despawnRadius; @@ -30,10 +29,10 @@ class Npc final : public Creature ~Npc(); // Singleton - ensures we don't accidentally copy it - Npc(Npc const&) = delete; - void operator=(Npc const&) = delete; + Npc(const Npc &) = delete; + void operator=(const Npc &) = delete; - static Npc& getInstance() { + static Npc &getInstance() { // Guaranteed to be destroyed static Npc instance; // Instantiated on first use @@ -56,14 +55,14 @@ class Npc final : public Creature void removeList() override; void addList() override; - const std::string& getName() const override { + const std::string &getName() const override { return npcType->name; } // Real npc name, set on npc creation "createNpcType(typeName)" - const std::string& getTypeName() const override { + const std::string &getTypeName() const override { return npcType->typeName; } - const std::string& getNameDescription() const override { + const std::string &getNameDescription() const override { return npcType->nameDescription; } std::string getDescription(int32_t) const override { @@ -78,7 +77,7 @@ class Npc final : public Creature return CREATURETYPE_NPC; } - const Position& getMasterPos() const { + const Position &getMasterPos() const { return masterPos; } void setMasterPos(Position pos) { @@ -111,8 +110,8 @@ class Npc final : public Creature return false; } - bool canSee(const Position& pos) const override; - bool canSeeRange(const Position& pos, int32_t viewRangeX = 4, int32_t viewRangeY = 4) const; + bool canSee(const Position &pos) const override; + bool canSeeRange(const Position &pos, int32_t viewRangeX = 4, int32_t viewRangeY = 4) const; bool canSeeInvisibility() const override { return true; } @@ -129,9 +128,9 @@ class Npc final : public Creature void resetPlayerInteractions(); bool isInteractingWithPlayer(uint32_t playerId) { - if (playerInteractions.find(playerId) == playerInteractions.end()) { - return false; - } + if (playerInteractions.find(playerId) == playerInteractions.end()) { + return false; + } return true; } @@ -145,21 +144,18 @@ class Npc final : public Creature void onCreatureAppear(Creature* creature, bool isLogin) override; void onRemoveCreature(Creature* creature, bool isLogout) override; - void onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, const Tile* oldTile, const Position& oldPos, bool teleport) override; - void onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) override; + void onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) override; + void onCreatureSay(Creature* creature, SpeakClasses type, const std::string &text) override; void onThink(uint32_t interval) override; - void onPlayerBuyItem(Player* player, uint16_t itemid, uint8_t count, - uint16_t amount, bool ignore, bool inBackpacks); - void onPlayerSellItem(Player* player, uint16_t itemid, uint8_t count, - uint16_t amount, bool ignore); - void onPlayerCheckItem(Player* player, uint16_t itemid, - uint8_t count); + void onPlayerBuyItem(Player* player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore, bool inBackpacks); + void onPlayerSellItem(Player* player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore); + void onPlayerCheckItem(Player* player, uint16_t itemid, uint8_t count); void onPlayerCloseChannel(Creature* creature); void onPlacedCreature() override; - bool canWalkTo(const Position& fromPos, Direction dir) const; - bool getNextStep(Direction& nextDirection, uint32_t& flags) override; - bool getRandomStep(Direction& moveDirection) const; + bool canWalkTo(const Position &fromPos, Direction dir) const; + bool getNextStep(Direction &nextDirection, uint32_t &flags) override; + bool getRandomStep(Direction &moveDirection) const; void setNormalCreatureLight() override { internalLight = npcType->info.light; @@ -175,7 +171,7 @@ class Npc final : public Creature void onThinkYell(uint32_t interval); void onThinkWalk(uint32_t interval); - bool isInSpawnRange(const Position& pos) const; + bool isInSpawnRange(const Position &pos) const; std::string strDescription; @@ -201,4 +197,4 @@ class Npc final : public Creature constexpr auto g_npc = &Npc::getInstance; -#endif // SRC_CREATURES_NPCS_NPC_H_ +#endif // SRC_CREATURES_NPCS_NPC_H_ diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index 7f1f9c42b69..649ba6cd166 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,13 +18,11 @@ #include "lua/scripts/scripts.h" #include "game/game.h" -bool NpcType::canSpawn(const Position& pos) -{ +bool NpcType::canSpawn(const Position &pos) { bool canSpawn = true; bool isDay = g_game().gameIsDay(); - if ((isDay && info.respawnType.period == RESPAWNPERIOD_NIGHT) || - (!isDay && info.respawnType.period == RESPAWNPERIOD_DAY)) { + if ((isDay && info.respawnType.period == RESPAWNPERIOD_NIGHT) || (!isDay && info.respawnType.period == RESPAWNPERIOD_DAY)) { // It will ignore day and night if underground canSpawn = (pos.z > MAP_INIT_SURFACE_LAYER && info.respawnType.underground); } @@ -32,8 +30,7 @@ bool NpcType::canSpawn(const Position& pos) return canSpawn; } -bool NpcType::loadCallback(LuaScriptInterface* scriptInterface) -{ +bool NpcType::loadCallback(LuaScriptInterface* scriptInterface) { int32_t id = scriptInterface->getEvent(); if (id == -1) { SPDLOG_WARN("[NpcType::loadCallback] - Event not found"); @@ -76,9 +73,8 @@ bool NpcType::loadCallback(LuaScriptInterface* scriptInterface) return true; } -void NpcType::loadShop(NpcType* npcType, ShopBlock shopBlock) -{ - ItemType & iType = Item::items.getItemType(shopBlock.itemId); +void NpcType::loadShop(NpcType* npcType, ShopBlock shopBlock) { + ItemType &iType = Item::items.getItemType(shopBlock.itemId); // Registering item prices globaly. if (shopBlock.itemSellPrice > iType.sellPrice) { @@ -87,7 +83,7 @@ void NpcType::loadShop(NpcType* npcType, ShopBlock shopBlock) if (shopBlock.itemBuyPrice > iType.buyPrice) { iType.buyPrice = shopBlock.itemBuyPrice; } - + if (shopBlock.childShop.empty()) { bool isContainer = iType.isContainer(); if (isContainer) { @@ -101,7 +97,7 @@ void NpcType::loadShop(NpcType* npcType, ShopBlock shopBlock) } } -bool Npcs::load(bool loadLibs/* = true*/, bool loadNpcs/* = true*/, bool reloading/* = false*/) const { +bool Npcs::load(bool loadLibs /* = true*/, bool loadNpcs /* = true*/, bool reloading /* = false*/) const { if (loadLibs) { auto coreFolder = g_configManager().getString(CORE_DIRECTORY); return g_luaEnvironment.loadFile(coreFolder + "/npclib/load.lua", "load.lua") == 0; @@ -112,8 +108,7 @@ bool Npcs::load(bool loadLibs/* = true*/, bool loadNpcs/* = true*/, bool reloadi return false; } -bool Npcs::reload() -{ +bool Npcs::reload() { // Load the "npclib" folder if (load(true, false, true)) { // Load the npcs scripts folder @@ -129,8 +124,7 @@ bool Npcs::reload() return false; } -NpcType* Npcs::getNpcType(const std::string& name, bool create /* = false*/) -{ +NpcType* Npcs::getNpcType(const std::string &name, bool create /* = false*/) { std::string key = asLowerCaseString(name); auto it = npcs.find(key); diff --git a/src/creatures/npcs/npcs.h b/src/creatures/npcs/npcs.h index 4e5f22e683a..e30cb4b23cc 100644 --- a/src/creatures/npcs/npcs.h +++ b/src/creatures/npcs/npcs.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_NPCS_NPCS_H_ #define SRC_CREATURES_NPCS_NPCS_H_ @@ -17,65 +17,65 @@ class Shop { Shop() = default; // non-copyable - Shop(const Shop&) = delete; - Shop& operator=(const Shop&) = delete; + Shop(const Shop &) = delete; + Shop &operator=(const Shop &) = delete; ShopBlock shopBlock; }; -class NpcType -{ - struct NpcInfo { - LuaScriptInterface* scriptInterface; +class NpcType { + struct NpcInfo { + LuaScriptInterface* scriptInterface; - Outfit_t outfit = {}; - RespawnType respawnType = {}; + Outfit_t outfit = {}; + RespawnType respawnType = {}; - LightInfo light = {}; + LightInfo light = {}; - uint8_t speechBubble; + uint8_t speechBubble; - uint16_t currencyId = ITEM_GOLD_COIN; + uint16_t currencyId = ITEM_GOLD_COIN; - uint32_t yellChance = 0; - uint32_t yellSpeedTicks = 0; - uint32_t baseSpeed = 55; - uint32_t walkInterval = 2000; + uint32_t yellChance = 0; + uint32_t yellSpeedTicks = 0; + uint32_t baseSpeed = 55; + uint32_t walkInterval = 2000; - int32_t creatureAppearEvent = -1; - int32_t creatureDisappearEvent = -1; - int32_t creatureMoveEvent = -1; - int32_t creatureSayEvent = -1; - int32_t thinkEvent = -1; - int32_t playerCloseChannel = -1; - int32_t playerBuyEvent = -1; - int32_t playerSellEvent = -1; - int32_t playerLookEvent = -1; + int32_t creatureAppearEvent = -1; + int32_t creatureDisappearEvent = -1; + int32_t creatureMoveEvent = -1; + int32_t creatureSayEvent = -1; + int32_t thinkEvent = -1; + int32_t playerCloseChannel = -1; + int32_t playerBuyEvent = -1; + int32_t playerSellEvent = -1; + int32_t playerLookEvent = -1; - int32_t health = 100; - int32_t healthMax = 100; + int32_t health = 100; + int32_t healthMax = 100; - int32_t walkRadius = 10; + int32_t walkRadius = 10; - bool canPushItems = false; - bool canPushCreatures = false; - bool pushable = false; - bool floorChange = false; + bool canPushItems = false; + bool canPushCreatures = false; + bool pushable = false; + bool floorChange = false; - std::vector voiceVector; - std::vector scripts; - std::vector shopItemVector; + std::vector voiceVector; + std::vector scripts; + std::vector shopItemVector; - NpcsEvent_t eventType = NPCS_EVENT_NONE; - }; + NpcsEvent_t eventType = NPCS_EVENT_NONE; + }; public: NpcType() = default; - explicit NpcType(const std::string &initName) : name(initName), typeName(initName), nameDescription(initName) {}; + explicit NpcType(const std::string &initName) : + name(initName), typeName(initName), nameDescription(initName) {}; // non-copyable - NpcType(const NpcType&) = delete; - NpcType& operator=(const NpcType&) = delete; + NpcType(const NpcType &) = delete; + NpcType &operator=(const NpcType &) = delete; std::string name; std::string typeName; @@ -85,25 +85,24 @@ class NpcType void loadShop(NpcType* npcType, ShopBlock shopBlock); bool loadCallback(LuaScriptInterface* scriptInterface); - bool canSpawn(const Position& pos); + bool canSpawn(const Position &pos); }; -class Npcs -{ +class Npcs { public: Npcs() = default; // non-copyable - Npcs(const Npcs&) = delete; - Npcs& operator=(const Npcs&) = delete; + Npcs(const Npcs &) = delete; + Npcs &operator=(const Npcs &) = delete; - static Npcs& getInstance() { + static Npcs &getInstance() { // Guaranteed to be destroyed static Npcs instance; // Instantiated on first use return instance; } - NpcType* getNpcType(const std::string& name, bool create = false); + NpcType* getNpcType(const std::string &name, bool create = false); // Reset npcs informations on reload bool load(bool loadLibs = true, bool loadNpcs = true, bool reloading = false) const; @@ -116,4 +115,4 @@ class Npcs constexpr auto g_npcs = &Npcs::getInstance; -#endif // SRC_CREATURES_NPCS_NPCS_H_ +#endif // SRC_CREATURES_NPCS_NPCS_H_ diff --git a/src/creatures/npcs/spawns/spawn_npc.cpp b/src/creatures/npcs/spawns/spawn_npc.cpp index 74402d1c9da..cfb9b7cc7e5 100644 --- a/src/creatures/npcs/spawns/spawn_npc.cpp +++ b/src/creatures/npcs/spawns/spawn_npc.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -19,8 +19,7 @@ static constexpr int32_t MINSPAWN_INTERVAL = 1000; // 1 second static constexpr int32_t MAXSPAWN_INTERVAL = 86400000; // 1 day -bool SpawnsNpc::loadFromXml(const std::string& fileNpcName) -{ +bool SpawnsNpc::loadFromXml(const std::string &fileNpcName) { if (isLoaded()) { return true; } @@ -56,7 +55,7 @@ bool SpawnsNpc::loadFromXml(const std::string& fileNpcName) } spawnNpcList.emplace_front(centerPos, radius); - SpawnNpc& spawnNpc = spawnNpcList.front(); + SpawnNpc &spawnNpc = spawnNpcList.front(); for (auto childNode : spawnNode.children()) { if (strcasecmp(childNode.name(), "npc") == 0) { @@ -97,22 +96,20 @@ bool SpawnsNpc::loadFromXml(const std::string& fileNpcName) return true; } -void SpawnsNpc::startup() -{ +void SpawnsNpc::startup() { if (!isLoaded() || isStarted()) { return; } - for (SpawnNpc& spawnNpc : spawnNpcList) { + for (SpawnNpc &spawnNpc : spawnNpcList) { spawnNpc.startup(); } setStarted(true); } -void SpawnsNpc::clear() -{ - for (SpawnNpc& spawnNpc : spawnNpcList) { +void SpawnsNpc::clear() { + for (SpawnNpc &spawnNpc : spawnNpcList) { spawnNpc.stopEvent(); } spawnNpcList.clear(); @@ -122,34 +119,29 @@ void SpawnsNpc::clear() fileName.clear(); } -bool SpawnsNpc::isInZone(const Position& centerPos, int32_t radius, const Position& pos) -{ +bool SpawnsNpc::isInZone(const Position ¢erPos, int32_t radius, const Position &pos) { if (radius == -1) { return true; } - return ((pos.getX() >= centerPos.getX() - radius) && (pos.getX() <= centerPos.getX() + radius) && - (pos.getY() >= centerPos.getY() - radius) && (pos.getY() <= centerPos.getY() + radius)); + return ((pos.getX() >= centerPos.getX() - radius) && (pos.getX() <= centerPos.getX() + radius) && (pos.getY() >= centerPos.getY() - radius) && (pos.getY() <= centerPos.getY() + radius)); } -void SpawnNpc::startSpawnNpcCheck() -{ +void SpawnNpc::startSpawnNpcCheck() { if (checkSpawnNpcEvent == 0) { checkSpawnNpcEvent = g_scheduler().addEvent(createSchedulerTask(getInterval(), std::bind(&SpawnNpc::checkSpawnNpc, this))); } } -SpawnNpc::~SpawnNpc() -{ - for (const auto& it : spawnedNpcMap) { +SpawnNpc::~SpawnNpc() { + for (const auto &it : spawnedNpcMap) { Npc* npc = it.second; npc->setSpawnNpc(nullptr); npc->decrementReferenceCounter(); } } -bool SpawnNpc::findPlayer(const Position& pos) -{ +bool SpawnNpc::findPlayer(const Position &pos) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, pos, false, true); for (Creature* spectator : spectators) { @@ -160,13 +152,11 @@ bool SpawnNpc::findPlayer(const Position& pos) return false; } -bool SpawnNpc::isInSpawnNpcZone(const Position& pos) -{ +bool SpawnNpc::isInSpawnNpcZone(const Position &pos) { return SpawnsNpc::isInZone(centerPos, radius, pos); } -bool SpawnNpc::spawnNpc(uint32_t spawnId, NpcType* npcType, const Position& pos, Direction dir, bool startup /*= false*/) -{ +bool SpawnNpc::spawnNpc(uint32_t spawnId, NpcType* npcType, const Position &pos, Direction dir, bool startup /*= false*/) { std::unique_ptr npc_ptr(new Npc(npcType)); if (startup) { // No need to send out events to the surrounding since there is no one out there to listen! @@ -191,28 +181,26 @@ bool SpawnNpc::spawnNpc(uint32_t spawnId, NpcType* npcType, const Position& pos, return true; } -void SpawnNpc::startup() -{ - for (const auto& it : spawnNpcMap) { +void SpawnNpc::startup() { + for (const auto &it : spawnNpcMap) { uint32_t spawnId = it.first; - const spawnBlockNpc_t& sb = it.second; + const spawnBlockNpc_t &sb = it.second; spawnNpc(spawnId, sb.npcType, sb.pos, sb.direction, true); } } -void SpawnNpc::checkSpawnNpc() -{ +void SpawnNpc::checkSpawnNpc() { checkSpawnNpcEvent = 0; cleanup(); - for (auto& it : spawnNpcMap) { + for (auto &it : spawnNpcMap) { uint32_t spawnId = it.first; if (spawnedNpcMap.find(spawnId) != spawnedNpcMap.end()) { continue; } - spawnBlockNpc_t& sb = it.second; + spawnBlockNpc_t &sb = it.second; if (!sb.npcType->canSpawn(sb.pos)) { sb.lastSpawnNpc = OTSYS_TIME(); continue; @@ -233,8 +221,7 @@ void SpawnNpc::checkSpawnNpc() } } -void SpawnNpc::scheduleSpawnNpc(uint32_t spawnId, spawnBlockNpc_t& sb, uint16_t interval) -{ +void SpawnNpc::scheduleSpawnNpc(uint32_t spawnId, spawnBlockNpc_t &sb, uint16_t interval) { if (interval <= 0) { spawnNpc(spawnId, sb.npcType, sb.pos, sb.direction); } else { @@ -243,14 +230,13 @@ void SpawnNpc::scheduleSpawnNpc(uint32_t spawnId, spawnBlockNpc_t& sb, uint16_t } } -void SpawnNpc::cleanup() -{ +void SpawnNpc::cleanup() { auto it = spawnedNpcMap.begin(); while (it != spawnedNpcMap.end()) { - uint32_t spawnId = it->first; + uint32_t spawnId = it->first; Npc* npc = it->second; - if (npc->isRemoved()) { - spawnNpcMap[spawnId].lastSpawnNpc = OTSYS_TIME(); + if (npc->isRemoved()) { + spawnNpcMap[spawnId].lastSpawnNpc = OTSYS_TIME(); npc->decrementReferenceCounter(); it = spawnedNpcMap.erase(it); } else { @@ -259,8 +245,7 @@ void SpawnNpc::cleanup() } } -bool SpawnNpc::addNpc(const std::string& name, const Position& pos, Direction dir, uint32_t scheduleInterval) -{ +bool SpawnNpc::addNpc(const std::string &name, const Position &pos, Direction dir, uint32_t scheduleInterval) { NpcType* npcType = g_npcs().getNpcType(name); if (!npcType) { SPDLOG_ERROR("Can not find {}", name); @@ -281,8 +266,7 @@ bool SpawnNpc::addNpc(const std::string& name, const Position& pos, Direction di return true; } -void SpawnNpc::removeNpc(Npc* npc) -{ +void SpawnNpc::removeNpc(Npc* npc) { for (auto it = spawnedNpcMap.begin(), end = spawnedNpcMap.end(); it != end; ++it) { if (it->second == npc) { npc->decrementReferenceCounter(); @@ -292,8 +276,7 @@ void SpawnNpc::removeNpc(Npc* npc) } } -void SpawnNpc::stopEvent() -{ +void SpawnNpc::stopEvent() { if (checkSpawnNpcEvent != 0) { g_scheduler().stopEvent(checkSpawnNpcEvent); checkSpawnNpcEvent = 0; diff --git a/src/creatures/npcs/spawns/spawn_npc.h b/src/creatures/npcs/spawns/spawn_npc.h index 681337af641..4339b366764 100644 --- a/src/creatures/npcs/spawns/spawn_npc.h +++ b/src/creatures/npcs/spawns/spawn_npc.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_NPCS_SPAWNS_SPAWN_NPC_H_ #define SRC_CREATURES_NPCS_SPAWNS_SPAWN_NPC_H_ @@ -17,24 +17,24 @@ class Npc; class NpcType; struct spawnBlockNpc_t { - Position pos; - NpcType* npcType; - int64_t lastSpawnNpc; - uint32_t interval; - Direction direction; + Position pos; + NpcType* npcType; + int64_t lastSpawnNpc; + uint32_t interval; + Direction direction; }; -class SpawnNpc -{ +class SpawnNpc { public: - SpawnNpc(Position initPos, int32_t initRadius) : centerPos(std::move(initPos)), radius(initRadius) {} + SpawnNpc(Position initPos, int32_t initRadius) : + centerPos(std::move(initPos)), radius(initRadius) { } ~SpawnNpc(); // non-copyable - SpawnNpc(const SpawnNpc&) = delete; - SpawnNpc& operator=(const SpawnNpc&) = delete; + SpawnNpc(const SpawnNpc &) = delete; + SpawnNpc &operator=(const SpawnNpc &) = delete; - bool addNpc(const std::string& name, const Position& pos, Direction dir, uint32_t interval); + bool addNpc(const std::string &name, const Position &pos, Direction dir, uint32_t interval); void removeNpc(Npc* npc); uint32_t getInterval() const { @@ -45,16 +45,16 @@ class SpawnNpc void startSpawnNpcCheck(); void stopEvent(); - bool isInSpawnNpcZone(const Position& pos); + bool isInSpawnNpcZone(const Position &pos); void cleanup(); private: - //map of the spawned npcs + // map of the spawned npcs using SpawnedNpcMap = std::multimap; using spawned_pair = SpawnedNpcMap::value_type; SpawnedNpcMap spawnedNpcMap; - //map of npcs in the spawn + // map of npcs in the spawn std::map spawnNpcMap; Position centerPos; @@ -63,18 +63,17 @@ class SpawnNpc uint32_t interval = 60000; uint32_t checkSpawnNpcEvent = 0; - static bool findPlayer(const Position& pos); - bool spawnNpc(uint32_t spawnId, NpcType* npcType, const Position& pos, Direction dir, bool startup = false); + static bool findPlayer(const Position &pos); + bool spawnNpc(uint32_t spawnId, NpcType* npcType, const Position &pos, Direction dir, bool startup = false); void checkSpawnNpc(); - void scheduleSpawnNpc(uint32_t spawnId, spawnBlockNpc_t& sb, uint16_t interval); + void scheduleSpawnNpc(uint32_t spawnId, spawnBlockNpc_t &sb, uint16_t interval); }; -class SpawnsNpc -{ +class SpawnsNpc { public: - static bool isInZone(const Position& centerPos, int32_t radius, const Position& pos); + static bool isInZone(const Position ¢erPos, int32_t radius, const Position &pos); - bool loadFromXml(const std::string& filenpcname); + bool loadFromXml(const std::string &filenpcname); void startup(); void clear(); @@ -84,7 +83,7 @@ class SpawnsNpc bool setStarted(bool setStarted) { return started = setStarted; } - + bool isLoaded() const { return loaded; } @@ -96,7 +95,7 @@ class SpawnsNpc return fileName = setName; } - std::forward_list& getSpawnNpcList() { + std::forward_list &getSpawnNpcList() { return spawnNpcList; } @@ -109,4 +108,4 @@ class SpawnsNpc static constexpr int32_t NONBLOCKABLE_SPAWN_NPC_INTERVAL = 1400; -#endif // SRC_CREATURES_NPCS_SPAWNS_SPAWN_NPC_H_ +#endif // SRC_CREATURES_NPCS_SPAWNS_SPAWN_NPC_H_ diff --git a/src/creatures/players/account/account.cpp b/src/creatures/players/account/account.cpp index a3ac08d98b3..67c8a98da43 100644 --- a/src/creatures/players/account/account.cpp +++ b/src/creatures/players/account/account.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,385 +14,382 @@ namespace account { -Account::Account() { - id_ = 0; - email_.clear(); - password_.clear(); - premium_remaining_days_ = 0; - premium_last_day_ = 0; - account_type_ = ACCOUNT_TYPE_NORMAL; - db_ = &Database::getInstance(); - db_tasks_ = &g_databaseTasks(); -} - -Account::Account(uint32_t id) { - id_ = id; - email_.clear(); - password_.clear(); - premium_remaining_days_ = 0; - premium_last_day_ = 0; - account_type_ = ACCOUNT_TYPE_NORMAL; - db_ = &Database::getInstance(); - db_tasks_ = &g_databaseTasks(); -} - -Account::Account(const std::string &email) : email_(email) { - id_ = 0; - password_.clear(); - premium_remaining_days_ = 0; - premium_last_day_ = 0; - account_type_ = ACCOUNT_TYPE_NORMAL; - db_ = &Database::getInstance(); - db_tasks_ = &g_databaseTasks(); -} - - -/******************************************************************************* - * Interfaces - ******************************************************************************/ - -error_t Account::SetDatabaseInterface(Database *database) { - if (database == nullptr) { - return ERROR_NULLPTR; - } - - db_ = database; - return ERROR_NO; -} - -error_t Account::SetDatabaseTasksInterface(DatabaseTasks *database_tasks) { - if (database_tasks == nullptr) { - return ERROR_NULLPTR; - } - - db_tasks_ = database_tasks; - return ERROR_NO; -} - - -/******************************************************************************* - * Coins Methods - ******************************************************************************/ - -error_t Account::GetCoins(uint32_t *coins) { - - if (db_ == nullptr || coins == nullptr || id_ == 0) { - return ERROR_NOT_INITIALIZED; - } - - std::ostringstream query; - query << "SELECT `coins` FROM `accounts` WHERE `id` = " << id_; - - DBResult_ptr result = db_->storeQuery(query.str()); - if (!result) { - return ERROR_DB; - } - - *coins = result->getNumber("coins"); - return ERROR_NO; -} - -error_t Account::AddCoins(uint32_t amount) { - - if (db_tasks_ == nullptr) { - return ERROR_NULLPTR; - } - if (amount == 0) { - return ERROR_NO; - } - - uint32_t current_coins = 0; - this->GetCoins(¤t_coins); - if ((current_coins + amount) < current_coins) { - return ERROR_VALUE_OVERFLOW; - } - - std::ostringstream query; - query << "UPDATE `accounts` SET `coins` = " << (current_coins + amount) - << " WHERE `id` = " << id_; - - db_tasks_->addTask(query.str()); - return ERROR_NO; -} - -error_t Account::RemoveCoins(uint32_t amount) { - - if (db_tasks_ == nullptr) { - return ERROR_NULLPTR; - } - - if (amount == 0) { - return ERROR_NO; - } - - uint32_t current_coins = 0; - this->GetCoins(¤t_coins); - - if ((current_coins - amount) > current_coins) { - return ERROR_VALUE_NOT_ENOUGH_COINS; - } - - std::ostringstream query; - query << "UPDATE `accounts` SET `coins` = "<< (current_coins - amount) - << " WHERE `id` = " << id_; - - db_tasks_->addTask(query.str()); - - return ERROR_NO; -} + Account::Account() { + id_ = 0; + email_.clear(); + password_.clear(); + premium_remaining_days_ = 0; + premium_last_day_ = 0; + account_type_ = ACCOUNT_TYPE_NORMAL; + db_ = &Database::getInstance(); + db_tasks_ = &g_databaseTasks(); + } + + Account::Account(uint32_t id) { + id_ = id; + email_.clear(); + password_.clear(); + premium_remaining_days_ = 0; + premium_last_day_ = 0; + account_type_ = ACCOUNT_TYPE_NORMAL; + db_ = &Database::getInstance(); + db_tasks_ = &g_databaseTasks(); + } + + Account::Account(const std::string &email) : + email_(email) { + id_ = 0; + password_.clear(); + premium_remaining_days_ = 0; + premium_last_day_ = 0; + account_type_ = ACCOUNT_TYPE_NORMAL; + db_ = &Database::getInstance(); + db_tasks_ = &g_databaseTasks(); + } + + /******************************************************************************* + * Interfaces + ******************************************************************************/ + + error_t Account::SetDatabaseInterface(Database* database) { + if (database == nullptr) { + return ERROR_NULLPTR; + } + + db_ = database; + return ERROR_NO; + } + + error_t Account::SetDatabaseTasksInterface(DatabaseTasks* database_tasks) { + if (database_tasks == nullptr) { + return ERROR_NULLPTR; + } + + db_tasks_ = database_tasks; + return ERROR_NO; + } + + /******************************************************************************* + * Coins Methods + ******************************************************************************/ + + error_t Account::GetCoins(uint32_t* coins) { + + if (db_ == nullptr || coins == nullptr || id_ == 0) { + return ERROR_NOT_INITIALIZED; + } + + std::ostringstream query; + query << "SELECT `coins` FROM `accounts` WHERE `id` = " << id_; + + DBResult_ptr result = db_->storeQuery(query.str()); + if (!result) { + return ERROR_DB; + } + + *coins = result->getNumber("coins"); + return ERROR_NO; + } + + error_t Account::AddCoins(uint32_t amount) { + + if (db_tasks_ == nullptr) { + return ERROR_NULLPTR; + } + if (amount == 0) { + return ERROR_NO; + } -error_t Account::RegisterCoinsTransaction(CoinTransactionType type, - uint32_t coins, - const std::string& description) { + uint32_t current_coins = 0; + this->GetCoins(¤t_coins); + if ((current_coins + amount) < current_coins) { + return ERROR_VALUE_OVERFLOW; + } - if (db_ == nullptr) { - return ERROR_NULLPTR; - } + std::ostringstream query; + query << "UPDATE `accounts` SET `coins` = " << (current_coins + amount) + << " WHERE `id` = " << id_; - std::ostringstream query; - query << "INSERT INTO `coins_transactions` (`account_id`, `type`, `amount`," - " `description`) VALUES (" << id_ << ", " << static_cast(type) << ", "<< coins - << ", " << db_->escapeString(description) << ")"; + db_tasks_->addTask(query.str()); + return ERROR_NO; + } + + error_t Account::RemoveCoins(uint32_t amount) { + + if (db_tasks_ == nullptr) { + return ERROR_NULLPTR; + } - if (!db_->executeQuery(query.str())) { - return ERROR_DB; - } + if (amount == 0) { + return ERROR_NO; + } - return ERROR_NO; -} + uint32_t current_coins = 0; + this->GetCoins(¤t_coins); + if ((current_coins - amount) > current_coins) { + return ERROR_VALUE_NOT_ENOUGH_COINS; + } -/******************************************************************************* - * Database - ******************************************************************************/ + std::ostringstream query; + query << "UPDATE `accounts` SET `coins` = " << (current_coins - amount) + << " WHERE `id` = " << id_; + + db_tasks_->addTask(query.str()); + + return ERROR_NO; + } -error_t Account::LoadAccountDB() { - if (id_ != 0) { - return this->LoadAccountDB(id_); - } else if (!email_.empty()) { - return this->LoadAccountDB(email_); - } + error_t Account::RegisterCoinsTransaction(CoinTransactionType type, uint32_t coins, const std::string &description) { + + if (db_ == nullptr) { + return ERROR_NULLPTR; + } + + std::ostringstream query; + query << "INSERT INTO `coins_transactions` (`account_id`, `type`, `amount`," + " `description`) VALUES (" + << id_ << ", " << static_cast(type) << ", " << coins + << ", " << db_->escapeString(description) << ")"; + + if (!db_->executeQuery(query.str())) { + return ERROR_DB; + } + + return ERROR_NO; + } - return ERROR_NOT_INITIALIZED; -} - -error_t Account::LoadAccountDB(std::string email) { - std::ostringstream query; - query << "SELECT * FROM `accounts` WHERE `email` = " - << db_->escapeString(email); - return this->LoadAccountDB(query); -} - -error_t Account::LoadAccountDB(uint32_t id) { - std::ostringstream query; - query << "SELECT * FROM `accounts` WHERE `id` = " << id; - return this->LoadAccountDB(query); -} - -error_t Account::LoadAccountDB(std::ostringstream &query) { - if (db_ == nullptr) { - return ERROR_NULLPTR; - } - - DBResult_ptr result = db_->storeQuery(query.str()); - if (!result) { - return false; - } - - this->SetID(result->getNumber("id")); - this->SetEmail(result->getString("email")); - this->SetAccountType(static_cast(result->getNumber("type"))); - this->SetPassword(result->getString("password")); - this->SetPremiumRemaningDays(result->getNumber("premdays")); - this->SetPremiumLastDay(result->getNumber("lastday")); + /******************************************************************************* + * Database + ******************************************************************************/ - return ERROR_NO; -} + error_t Account::LoadAccountDB() { + if (id_ != 0) { + return this->LoadAccountDB(id_); + } else if (!email_.empty()) { + return this->LoadAccountDB(email_); + } -error_t Account::LoadAccountPlayerDB(Player *player, std::string& characterName) { - if (id_ == 0) { return ERROR_NOT_INITIALIZED; } - std::ostringstream query; - query << "SELECT `name`, `deletion` FROM `players` WHERE `account_id` = " - << id_ << " AND `name` = " << db_->escapeString(characterName) << " ORDER BY `name` ASC"; + error_t Account::LoadAccountDB(std::string email) { + std::ostringstream query; + query << "SELECT * FROM `accounts` WHERE `email` = " + << db_->escapeString(email); + return this->LoadAccountDB(query); + } + + error_t Account::LoadAccountDB(uint32_t id) { + std::ostringstream query; + query << "SELECT * FROM `accounts` WHERE `id` = " << id; + return this->LoadAccountDB(query); + } + + error_t Account::LoadAccountDB(std::ostringstream &query) { + if (db_ == nullptr) { + return ERROR_NULLPTR; + } + + DBResult_ptr result = db_->storeQuery(query.str()); + if (!result) { + return false; + } + + this->SetID(result->getNumber("id")); + this->SetEmail(result->getString("email")); + this->SetAccountType(static_cast(result->getNumber("type"))); + this->SetPassword(result->getString("password")); + this->SetPremiumRemaningDays(result->getNumber("premdays")); + this->SetPremiumLastDay(result->getNumber("lastday")); + + return ERROR_NO; + } + + error_t Account::LoadAccountPlayerDB(Player* player, std::string &characterName) { + if (id_ == 0) { + return ERROR_NOT_INITIALIZED; + } + + std::ostringstream query; + query << "SELECT `name`, `deletion` FROM `players` WHERE `account_id` = " + << id_ << " AND `name` = " << db_->escapeString(characterName) << " ORDER BY `name` ASC"; + + DBResult_ptr result = db_->storeQuery(query.str()); + if (!result || result->getNumber("deletion") != 0) { + return ERROR_PLAYER_NOT_FOUND; + } + + player->name = result->getString("name"); + player->deletion = result->getNumber("deletion"); + + return ERROR_NO; + } + + error_t Account::LoadAccountPlayersDB(std::vector* players) { + if (id_ == 0) { + return ERROR_NOT_INITIALIZED; + } + + std::ostringstream query; + query << "SELECT `name`, `deletion` FROM `players` WHERE `account_id` = " + << id_ << " ORDER BY `name` ASC"; + DBResult_ptr result = db_->storeQuery(query.str()); + if (!result) { + return ERROR_DB; + } + + do { + if (result->getNumber("deletion") == 0) { + Player new_player; + new_player.name = result->getString("name"); + new_player.deletion = result->getNumber("deletion"); + players->push_back(new_player); + } + } while (result->next()); + return ERROR_NO; + } + + error_t Account::SaveAccountDB() { + std::ostringstream query; + + query << "UPDATE `accounts` SET " + << "`email` = " << db_->escapeString(email_) << " , " + << "`type` = " << account_type_ << " , " + << "`password` = " << db_->escapeString(password_) << " , " + << "`premdays` = " << premium_remaining_days_ << " , " + << "`lastday` = " << premium_last_day_; + + if (id_ != 0) { + query << " WHERE `id` = " << id_; + } else if (!email_.empty()) { + query << " WHERE `email` = " << email_; + } + + if (!db_->executeQuery(query.str())) { + return ERROR_DB; + } + + return ERROR_NO; + } + + /******************************************************************************* + * Setters and Getters + ******************************************************************************/ + + error_t Account::SetID(uint32_t id) { + if (id == 0) { + return ERROR_INVALID_ID; + } + id_ = id; + return ERROR_NO; + } + + error_t Account::GetID(uint32_t* id) { + if (id == nullptr) { + return ERROR_NULLPTR; + } + + *id = id_; + return ERROR_NO; + } + + error_t Account::SetEmail(std::string email) { + if (email.empty()) { + return ERROR_INVALID_ACCOUNT_EMAIL; + } + email_ = email; + return ERROR_NO; + } + + error_t Account::GetEmail(std::string* email) { + if (email == nullptr) { + return ERROR_NULLPTR; + } - DBResult_ptr result = db_->storeQuery(query.str()); - if (!result || result->getNumber("deletion") != 0) { - return ERROR_PLAYER_NOT_FOUND; + *email = email_; + return ERROR_NO; } - player->name = result->getString("name"); - player->deletion = result->getNumber("deletion"); - - return ERROR_NO; -} - -error_t Account::LoadAccountPlayersDB(std::vector *players) { - if (id_ == 0) { - return ERROR_NOT_INITIALIZED; - } - - std::ostringstream query; - query << "SELECT `name`, `deletion` FROM `players` WHERE `account_id` = " - << id_ << " ORDER BY `name` ASC"; - DBResult_ptr result = db_->storeQuery(query.str()); - if (!result) { - return ERROR_DB; - } - - do { - if (result->getNumber("deletion") == 0) { - Player new_player; - new_player.name = result->getString("name"); - new_player.deletion = result->getNumber("deletion"); - players->push_back(new_player); - } - } while (result->next()); - return ERROR_NO; -} - -error_t Account::SaveAccountDB() { - std::ostringstream query; - - query << "UPDATE `accounts` SET " - << "`email` = " << db_->escapeString(email_) << " , " - << "`type` = " << account_type_ << " , " - << "`password` = " << db_->escapeString(password_) << " , " - << "`premdays` = " << premium_remaining_days_ << " , " - << "`lastday` = " << premium_last_day_; - - if (id_ != 0) { - query << " WHERE `id` = " << id_; - } else if (!email_.empty()) { - query << " WHERE `email` = " << email_; - } - - if (!db_->executeQuery(query.str())) { - return ERROR_DB; - } - - return ERROR_NO; -} - -/******************************************************************************* - * Setters and Getters - ******************************************************************************/ - -error_t Account::SetID(uint32_t id) { - if (id == 0) { - return ERROR_INVALID_ID; - } - id_ = id; - return ERROR_NO; -} - -error_t Account::GetID(uint32_t *id) { - if (id == nullptr) { - return ERROR_NULLPTR; - } - - *id = id_; - return ERROR_NO; -} - -error_t Account::SetEmail(std::string email) { - if (email.empty()) { - return ERROR_INVALID_ACCOUNT_EMAIL; - } - email_ = email; - return ERROR_NO; -} - -error_t Account::GetEmail(std::string *email) { - if (email == nullptr) { - return ERROR_NULLPTR; - } - - *email = email_; - return ERROR_NO; -} - -error_t Account::SetPassword(std::string password) { - if (password.empty()) { - return ERROR_INVALID_ACC_PASSWORD; - } - password_ = password; - return ERROR_NO; -} - -error_t Account::GetPassword(std::string *password) { - if (password == nullptr) { - return ERROR_NULLPTR; - } - - *password = password_; - return ERROR_NO; -} - -error_t Account::SetPremiumRemaningDays(uint32_t days) { - premium_remaining_days_ = days; - return ERROR_NO; -} - -error_t Account::GetPremiumRemaningDays(uint32_t *days) { - if (days == nullptr) { - return ERROR_NULLPTR; - } - - *days = premium_remaining_days_; - return ERROR_NO; -} - -error_t Account::SetPremiumLastDay(time_t last_day) { - if (last_day < 0) { - return ERROR_INVALID_LAST_DAY; - } - premium_last_day_ = last_day; - return ERROR_NO; -} - -error_t Account::GetPremiumLastDay(time_t *last_day) { - if (last_day == nullptr) { - return ERROR_NULLPTR; - } - - *last_day = premium_last_day_; - return ERROR_NO; -} - -error_t Account::SetAccountType(AccountType account_type) { - if (account_type > 5) { - return ERROR_INVALID_ACC_TYPE; - } - account_type_ = account_type; - return ERROR_NO; -} - -error_t Account::GetAccountType(AccountType *account_type) { - if (account_type == nullptr) { - return ERROR_NULLPTR; - } - - *account_type = account_type_; - return ERROR_NO; -} - -error_t Account::GetAccountPlayer(Player *player, std::string& characterName) { - if (player == nullptr) { - return ERROR_NULLPTR; + error_t Account::SetPassword(std::string password) { + if (password.empty()) { + return ERROR_INVALID_ACC_PASSWORD; + } + password_ = password; + return ERROR_NO; } - return this->LoadAccountPlayerDB(player, characterName); -} + error_t Account::GetPassword(std::string* password) { + if (password == nullptr) { + return ERROR_NULLPTR; + } -error_t Account::GetAccountPlayers(std::vector *players) { - if (players == nullptr) { - return ERROR_NULLPTR; - } + *password = password_; + return ERROR_NO; + } + + error_t Account::SetPremiumRemaningDays(uint32_t days) { + premium_remaining_days_ = days; + return ERROR_NO; + } + + error_t Account::GetPremiumRemaningDays(uint32_t* days) { + if (days == nullptr) { + return ERROR_NULLPTR; + } + + *days = premium_remaining_days_; + return ERROR_NO; + } + + error_t Account::SetPremiumLastDay(time_t last_day) { + if (last_day < 0) { + return ERROR_INVALID_LAST_DAY; + } + premium_last_day_ = last_day; + return ERROR_NO; + } + + error_t Account::GetPremiumLastDay(time_t* last_day) { + if (last_day == nullptr) { + return ERROR_NULLPTR; + } + + *last_day = premium_last_day_; + return ERROR_NO; + } - return this->LoadAccountPlayersDB(players); -} + error_t Account::SetAccountType(AccountType account_type) { + if (account_type > 5) { + return ERROR_INVALID_ACC_TYPE; + } + account_type_ = account_type; + return ERROR_NO; + } + + error_t Account::GetAccountType(AccountType* account_type) { + if (account_type == nullptr) { + return ERROR_NULLPTR; + } + + *account_type = account_type_; + return ERROR_NO; + } + + error_t Account::GetAccountPlayer(Player* player, std::string &characterName) { + if (player == nullptr) { + return ERROR_NULLPTR; + } + + return this->LoadAccountPlayerDB(player, characterName); + } + + error_t Account::GetAccountPlayers(std::vector* players) { + if (players == nullptr) { + return ERROR_NULLPTR; + } + + return this->LoadAccountPlayersDB(players); + } -} // namespace account +} // namespace account diff --git a/src/creatures/players/account/account.hpp b/src/creatures/players/account/account.hpp index ec66dbf62a0..453c35e1057 100644 --- a/src/creatures/players/account/account.hpp +++ b/src/creatures/players/account/account.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_ACCOUNT_ACCOUNT_HPP_ #define SRC_CREATURES_PLAYERS_ACCOUNT_ACCOUNT_HPP_ @@ -16,215 +16,211 @@ namespace account { -enum Errors : uint8_t { - ERROR_NO = 0, - ERROR_DB, - ERROR_INVALID_ACCOUNT_EMAIL, - ERROR_INVALID_ACC_PASSWORD, - ERROR_INVALID_ACC_TYPE, - ERROR_INVALID_ID, - ERROR_INVALID_LAST_DAY, - ERROR_LOADING_ACCOUNT_PLAYERS, - ERROR_NOT_INITIALIZED, - ERROR_NULLPTR, - ERROR_VALUE_NOT_ENOUGH_COINS, - ERROR_VALUE_OVERFLOW, - ERROR_PLAYER_NOT_FOUND -}; - -enum AccountType : uint8_t { - ACCOUNT_TYPE_NORMAL = 1, - ACCOUNT_TYPE_TUTOR = 2, - ACCOUNT_TYPE_SENIORTUTOR = 3, - ACCOUNT_TYPE_GAMEMASTER = 4, - ACCOUNT_TYPE_GOD = 5 -}; - -enum GroupType : uint8_t { - GROUP_TYPE_NORMAL = 1, - GROUP_TYPE_TUTOR = 2, - GROUP_TYPE_SENIORTUTOR = 3, - GROUP_TYPE_GAMEMASTER = 4, - GROUP_TYPE_COMMUNITYMANAGER = 5, - GROUP_TYPE_GOD = 6 -}; - -enum CoinTransactionType : uint8_t { - COIN_ADD = 1, - COIN_REMOVE = 2 -}; - -typedef struct { - std::string name; - uint64_t deletion; -} Player; - -/** - * @brief Account class to handle account information - * - */ -class Account { - public: - /** - * @brief Construct a new Account object - * - */ - Account(); - - /** - * @brief Construct a new Account object - * - * @param id Set Account ID to be used by LoadAccountDB - */ - explicit Account(uint32_t id); - - /** - * @brief Construct a new Account object - * - * @param name Set Account Name to be used by LoadAccountDB - */ - explicit Account(const std::string &name); - - /*************************************************************************** - * Interfaces - **************************************************************************/ - - /** - * @brief Set the Database Interface used to get and set information from - * the database - * - * @param database Database Interface pointer to be used - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t SetDatabaseInterface(Database *database); - - /** - * @brief Set the Database Tasks Interface used to schedule db update - * - * @param database Database Interface pointer to be used - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t SetDatabaseTasksInterface(DatabaseTasks *db_tasks); - - - /*************************************************************************** - * Coins Methods - **************************************************************************/ - - /** - * @brief Get the amount of coins that the account has from database. - * - * @param accountId Account ID to get the coins. - * @param coins Pointer to return the number of coins - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t GetCoins(uint32_t *coins); - - /** - * @brief Add coins to the account and update database. - * - * @param amount Amount of coins to be added - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t AddCoins(uint32_t amount); - - /** - * @brief Removes coins from the account and update database. - * - * @param amount Amount of coins to be removed - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t RemoveCoins(uint32_t amount); - - /** - * @brief Register account coins transactions in database. - * - * @param type Type of the transaction(Add/Remove). - * @param coins Amount of coins - * @param description Description of the transaction - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t RegisterCoinsTransaction(CoinTransactionType type, uint32_t coins, - const std::string &description); - - - /*************************************************************************** - * Database - **************************************************************************/ - - /** - * @brief Try to load account from DB using Account ID or Name if they were - * initialized. - * - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t LoadAccountDB(); - - /** - * @brief Try to - * - * @param name - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t LoadAccountDB(std::string name); - - /** - * @brief - * - * @param id - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t LoadAccountDB(uint32_t id); - - /** - * @brief - * - * @return error_t ERROR_NO(0) Success, otherwise Fail. - */ - error_t SaveAccountDB(); - - - /*************************************************************************** - * Setters and Getters - **************************************************************************/ - - error_t GetID(uint32_t *id); - - error_t SetEmail(std::string name); - error_t GetEmail(std::string *name); - - error_t SetPassword(std::string password); - error_t GetPassword(std::string *password); - - error_t SetPremiumRemaningDays(uint32_t days); - error_t GetPremiumRemaningDays(uint32_t *days); - - error_t SetPremiumLastDay(time_t last_day); - error_t GetPremiumLastDay(time_t *last_day); - - error_t SetAccountType(AccountType account_type); - error_t GetAccountType(AccountType *account_type); - - error_t GetAccountPlayer(Player *player, std::string& characterName); - error_t GetAccountPlayers(std::vector *players); - - private: - error_t SetID(uint32_t id); - error_t LoadAccountDB(std::ostringstream &query); - error_t LoadAccountPlayersDB(std::vector *players); - error_t LoadAccountPlayerDB(Player *player, std::string& characterName); - - Database *db_; - DatabaseTasks *db_tasks_; - - uint32_t id_; - std::string email_; - std::string password_; - uint32_t premium_remaining_days_; - time_t premium_last_day_; - AccountType account_type_; -}; - -} // namespace account - -#endif // SRC_CREATURES_PLAYERS_ACCOUNT_ACCOUNT_HPP_ + enum Errors : uint8_t { + ERROR_NO = 0, + ERROR_DB, + ERROR_INVALID_ACCOUNT_EMAIL, + ERROR_INVALID_ACC_PASSWORD, + ERROR_INVALID_ACC_TYPE, + ERROR_INVALID_ID, + ERROR_INVALID_LAST_DAY, + ERROR_LOADING_ACCOUNT_PLAYERS, + ERROR_NOT_INITIALIZED, + ERROR_NULLPTR, + ERROR_VALUE_NOT_ENOUGH_COINS, + ERROR_VALUE_OVERFLOW, + ERROR_PLAYER_NOT_FOUND + }; + + enum AccountType : uint8_t { + ACCOUNT_TYPE_NORMAL = 1, + ACCOUNT_TYPE_TUTOR = 2, + ACCOUNT_TYPE_SENIORTUTOR = 3, + ACCOUNT_TYPE_GAMEMASTER = 4, + ACCOUNT_TYPE_GOD = 5 + }; + + enum GroupType : uint8_t { + GROUP_TYPE_NORMAL = 1, + GROUP_TYPE_TUTOR = 2, + GROUP_TYPE_SENIORTUTOR = 3, + GROUP_TYPE_GAMEMASTER = 4, + GROUP_TYPE_COMMUNITYMANAGER = 5, + GROUP_TYPE_GOD = 6 + }; + + enum CoinTransactionType : uint8_t { + COIN_ADD = 1, + COIN_REMOVE = 2 + }; + + typedef struct { + std::string name; + uint64_t deletion; + } Player; + + /** + * @brief Account class to handle account information + * + */ + class Account { + public: + /** + * @brief Construct a new Account object + * + */ + Account(); + + /** + * @brief Construct a new Account object + * + * @param id Set Account ID to be used by LoadAccountDB + */ + explicit Account(uint32_t id); + + /** + * @brief Construct a new Account object + * + * @param name Set Account Name to be used by LoadAccountDB + */ + explicit Account(const std::string &name); + + /*************************************************************************** + * Interfaces + **************************************************************************/ + + /** + * @brief Set the Database Interface used to get and set information from + * the database + * + * @param database Database Interface pointer to be used + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t SetDatabaseInterface(Database* database); + + /** + * @brief Set the Database Tasks Interface used to schedule db update + * + * @param database Database Interface pointer to be used + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t SetDatabaseTasksInterface(DatabaseTasks* db_tasks); + + /*************************************************************************** + * Coins Methods + **************************************************************************/ + + /** + * @brief Get the amount of coins that the account has from database. + * + * @param accountId Account ID to get the coins. + * @param coins Pointer to return the number of coins + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t GetCoins(uint32_t* coins); + + /** + * @brief Add coins to the account and update database. + * + * @param amount Amount of coins to be added + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t AddCoins(uint32_t amount); + + /** + * @brief Removes coins from the account and update database. + * + * @param amount Amount of coins to be removed + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t RemoveCoins(uint32_t amount); + + /** + * @brief Register account coins transactions in database. + * + * @param type Type of the transaction(Add/Remove). + * @param coins Amount of coins + * @param description Description of the transaction + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t RegisterCoinsTransaction(CoinTransactionType type, uint32_t coins, const std::string &description); + + /*************************************************************************** + * Database + **************************************************************************/ + + /** + * @brief Try to load account from DB using Account ID or Name if they were + * initialized. + * + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t LoadAccountDB(); + + /** + * @brief Try to + * + * @param name + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t LoadAccountDB(std::string name); + + /** + * @brief + * + * @param id + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t LoadAccountDB(uint32_t id); + + /** + * @brief + * + * @return error_t ERROR_NO(0) Success, otherwise Fail. + */ + error_t SaveAccountDB(); + + /*************************************************************************** + * Setters and Getters + **************************************************************************/ + + error_t GetID(uint32_t* id); + + error_t SetEmail(std::string name); + error_t GetEmail(std::string* name); + + error_t SetPassword(std::string password); + error_t GetPassword(std::string* password); + + error_t SetPremiumRemaningDays(uint32_t days); + error_t GetPremiumRemaningDays(uint32_t* days); + + error_t SetPremiumLastDay(time_t last_day); + error_t GetPremiumLastDay(time_t* last_day); + + error_t SetAccountType(AccountType account_type); + error_t GetAccountType(AccountType* account_type); + + error_t GetAccountPlayer(Player* player, std::string &characterName); + error_t GetAccountPlayers(std::vector* players); + + private: + error_t SetID(uint32_t id); + error_t LoadAccountDB(std::ostringstream &query); + error_t LoadAccountPlayersDB(std::vector* players); + error_t LoadAccountPlayerDB(Player* player, std::string &characterName); + + Database* db_; + DatabaseTasks* db_tasks_; + + uint32_t id_; + std::string email_; + std::string password_; + uint32_t premium_remaining_days_; + time_t premium_last_day_; + AccountType account_type_; + }; + +} // namespace account + +#endif // SRC_CREATURES_PLAYERS_ACCOUNT_ACCOUNT_HPP_ diff --git a/src/creatures/players/grouping/familiars.cpp b/src/creatures/players/grouping/familiars.cpp index 245c6ee4a32..9230185120a 100644 --- a/src/creatures/players/grouping/familiars.cpp +++ b/src/creatures/players/grouping/familiars.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -52,7 +52,8 @@ bool Familiars::loadFromXml() { pugi::cast(lookTypeAttribute.value()), familiarsNode.attribute("premium").as_bool(), familiarsNode.attribute("unlocked").as_bool(true), - familiarsNode.attribute("type").as_string()); + familiarsNode.attribute("type").as_string() + ); } for (uint16_t vocation = VOCATION_NONE; vocation <= VOCATION_LAST; ++vocation) { familiars[vocation].shrink_to_fit(); @@ -61,7 +62,7 @@ bool Familiars::loadFromXml() { } const Familiar* Familiars::getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const { - for (const Familiar& familiar : familiars[vocation]) { + for (const Familiar &familiar : familiars[vocation]) { if (familiar.lookType == lookType) { return &familiar; } diff --git a/src/creatures/players/grouping/familiars.h b/src/creatures/players/grouping/familiars.h index 9da64074c4d..2d2e55cb3cd 100644 --- a/src/creatures/players/grouping/familiars.h +++ b/src/creatures/players/grouping/familiars.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_GROUPING_FAMILIARS_H_ #define SRC_CREATURES_PLAYERS_GROUPING_FAMILIARS_H_ @@ -14,17 +14,18 @@ class Familiars { public: - static Familiars& getInstance() { + static Familiars &getInstance() { static Familiars instance; return instance; } bool loadFromXml(); - const std::vector& getFamiliars(uint16_t vocation) const { + const std::vector &getFamiliars(uint16_t vocation) const { return familiars[vocation]; } const Familiar* getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const; + private: std::vector familiars[VOCATION_LAST + 1]; }; -#endif // SRC_CREATURES_PLAYERS_GROUPING_FAMILIARS_H_ +#endif // SRC_CREATURES_PLAYERS_GROUPING_FAMILIARS_H_ diff --git a/src/creatures/players/grouping/groups.cpp b/src/creatures/players/grouping/groups.cpp index ddd2ba154a3..d79ee5dd151 100644 --- a/src/creatures/players/grouping/groups.cpp +++ b/src/creatures/players/grouping/groups.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,43 +16,40 @@ #include "utils/tools.h" namespace ParsePlayerFlagMap { -// Initialize the map with all the values from the PlayerFlags_t enumeration -phmap::flat_hash_map initParsePlayerFlagMap() { - phmap::flat_hash_map map; - // Iterate through all values of the PlayerFlags_t enumeration - for (auto value : magic_enum::enum_values()) { - // Get the string representation of the current enumeration value - std::string name(magic_enum::enum_name(value).data()); - // Convert the string to lowercase - std::ranges::transform(name.begin(), name.end(), name.begin(), ::tolower); - // Add the current value to the map with its lowercase string representation as the key - map[name] = value; - } + // Initialize the map with all the values from the PlayerFlags_t enumeration + phmap::flat_hash_map initParsePlayerFlagMap() { + phmap::flat_hash_map map; + // Iterate through all values of the PlayerFlags_t enumeration + for (auto value : magic_enum::enum_values()) { + // Get the string representation of the current enumeration value + std::string name(magic_enum::enum_name(value).data()); + // Convert the string to lowercase + std::ranges::transform(name.begin(), name.end(), name.begin(), ::tolower); + // Add the current value to the map with its lowercase string representation as the key + map[name] = value; + } - return map; -} + return map; + } -const phmap::flat_hash_map parsePlayerFlagMap = initParsePlayerFlagMap(); + const phmap::flat_hash_map parsePlayerFlagMap = initParsePlayerFlagMap(); } -uint8_t Groups::getFlagNumber(PlayerFlags_t playerFlags) -{ +uint8_t Groups::getFlagNumber(PlayerFlags_t playerFlags) { return magic_enum::enum_integer(playerFlags); } -PlayerFlags_t Groups::getFlagFromNumber(uint8_t value) -{ +PlayerFlags_t Groups::getFlagFromNumber(uint8_t value) { return magic_enum::enum_value(value); } -bool Groups::reload() const -{ +bool Groups::reload() const { // Clear groups g_game().groups.getGroups().clear(); return g_game().groups.load(); } -void parseGroupFlags(Group& group, const pugi::xml_node& groupNode) { +void parseGroupFlags(Group &group, const pugi::xml_node &groupNode) { if (pugi::xml_node node = groupNode.child("flags")) { for (auto flagNode : node.children()) { pugi::xml_attribute attr = flagNode.first_attribute(); @@ -70,8 +67,7 @@ void parseGroupFlags(Group& group, const pugi::xml_node& groupNode) { } } -bool Groups::load() -{ +bool Groups::load() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/groups.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); @@ -103,9 +99,8 @@ bool Groups::load() return true; } -Group* Groups::getGroup(uint16_t id) -{ - for (Group& group : groups_vector) { +Group* Groups::getGroup(uint16_t id) { + for (Group &group : groups_vector) { if (group.id == id) { return &group; } diff --git a/src/creatures/players/grouping/groups.h b/src/creatures/players/grouping/groups.h index af15cc034a1..2a7463c1166 100644 --- a/src/creatures/players/grouping/groups.h +++ b/src/creatures/players/grouping/groups.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_GROUPING_GROUPS_H_ #define SRC_CREATURES_PLAYERS_GROUPING_GROUPS_H_ @@ -13,12 +13,12 @@ #include "declarations.hpp" struct Group { - std::string name; - std::array flags{false}; - uint32_t maxDepotItems; - uint32_t maxVipEntries; - uint16_t id; - bool access; + std::string name; + std::array flags { false }; + uint32_t maxDepotItems; + uint32_t maxVipEntries; + uint16_t id; + bool access; }; class Groups { @@ -28,7 +28,7 @@ class Groups { bool reload() const; bool load(); Group* getGroup(uint16_t id); - std::vector& getGroups() { + std::vector &getGroups() { return groups_vector; } @@ -36,4 +36,4 @@ class Groups { std::vector groups_vector; }; -#endif // SRC_CREATURES_PLAYERS_GROUPING_GROUPS_H_ +#endif // SRC_CREATURES_PLAYERS_GROUPING_GROUPS_H_ diff --git a/src/creatures/players/grouping/guild.cpp b/src/creatures/players/grouping/guild.cpp index 4e8e2288562..6773dc4c822 100644 --- a/src/creatures/players/grouping/guild.cpp +++ b/src/creatures/players/grouping/guild.cpp @@ -5,20 +5,18 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "creatures/players/grouping/guild.h" #include "game/game.h" -void Guild::addMember(Player* player) -{ +void Guild::addMember(Player* player) { membersOnline.push_back(player); } -void Guild::removeMember(Player* player) -{ +void Guild::removeMember(Player* player) { membersOnline.remove(player); if (membersOnline.empty()) { g_game().removeGuild(id); @@ -26,8 +24,7 @@ void Guild::removeMember(Player* player) } } -GuildRank_ptr Guild::getRankById(uint32_t rankId) -{ +GuildRank_ptr Guild::getRankById(uint32_t rankId) { for (auto rank : ranks) { if (rank->id == rankId) { return rank; @@ -36,8 +33,7 @@ GuildRank_ptr Guild::getRankById(uint32_t rankId) return nullptr; } -GuildRank_ptr Guild::getRankByName(const std::string& guildName) const -{ +GuildRank_ptr Guild::getRankByName(const std::string &guildName) const { for (auto rank : ranks) { if (rank->name == guildName) { return rank; @@ -46,8 +42,7 @@ GuildRank_ptr Guild::getRankByName(const std::string& guildName) const return nullptr; } -GuildRank_ptr Guild::getRankByLevel(uint8_t level) const -{ +GuildRank_ptr Guild::getRankByLevel(uint8_t level) const { for (auto rank : ranks) { if (rank->level == level) { return rank; @@ -56,7 +51,6 @@ GuildRank_ptr Guild::getRankByLevel(uint8_t level) const return nullptr; } -void Guild::addRank(uint32_t rankId, const std::string& rankName, uint8_t level) -{ - ranks.emplace_back(std::make_shared(rankId,rankName,level)); +void Guild::addRank(uint32_t rankId, const std::string &rankName, uint8_t level) { + ranks.emplace_back(std::make_shared(rankId, rankName, level)); } diff --git a/src/creatures/players/grouping/guild.h b/src/creatures/players/grouping/guild.h index 6fc0802277b..2841868837c 100644 --- a/src/creatures/players/grouping/guild.h +++ b/src/creatures/players/grouping/guild.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_GROUPING_GUILD_H_ #define SRC_CREATURES_PLAYERS_GROUPING_GUILD_H_ @@ -13,19 +13,19 @@ class Player; struct GuildRank { - uint32_t id; - std::string name; - uint8_t level; + uint32_t id; + std::string name; + uint8_t level; - GuildRank(uint32_t initId, std::string initName, uint8_t initLevel) : - id(initId), name(std::move(initName)), level(initLevel) {} + GuildRank(uint32_t initId, std::string initName, uint8_t initLevel) : + id(initId), name(std::move(initName)), level(initLevel) { } }; using GuildRank_ptr = std::shared_ptr; -class Guild -{ +class Guild { public: - Guild(uint32_t initId, std::string initName) : name(std::move(initName)), id(initId) {} + Guild(uint32_t initId, std::string initName) : + name(std::move(initName)), id(initId) { } void addMember(Player* player); void removeMember(Player* player); @@ -33,10 +33,10 @@ class Guild uint32_t getId() const { return id; } - const std::string& getName() const { + const std::string &getName() const { return name; } - const std::list& getMembersOnline() const { + const std::list &getMembersOnline() const { return membersOnline; } uint32_t getMemberCount() const { @@ -45,26 +45,26 @@ class Guild void setMemberCount(uint32_t count) { memberCount = count; } - uint64_t getBankBalance() const { - return bankBalance; - } - void setBankBalance(uint64_t balance) { - bankBalance = balance; - } + uint64_t getBankBalance() const { + return bankBalance; + } + void setBankBalance(uint64_t balance) { + bankBalance = balance; + } - const std::vector& getRanks() const { + const std::vector &getRanks() const { return ranks; } GuildRank_ptr getRankById(uint32_t id); - GuildRank_ptr getRankByName(const std::string& name) const; + GuildRank_ptr getRankByName(const std::string &name) const; GuildRank_ptr getRankByLevel(uint8_t level) const; - void addRank(uint32_t id, const std::string& name, uint8_t level); + void addRank(uint32_t id, const std::string &name, uint8_t level); - const std::string& getMotd() const { + const std::string &getMotd() const { return motd; } - void setMotd(const std::string& newMotd) { + void setMotd(const std::string &newMotd) { this->motd = newMotd; } @@ -78,4 +78,4 @@ class Guild uint32_t memberCount = 0; }; -#endif // SRC_CREATURES_PLAYERS_GROUPING_GUILD_H_ +#endif // SRC_CREATURES_PLAYERS_GROUPING_GUILD_H_ diff --git a/src/creatures/players/grouping/party.cpp b/src/creatures/players/grouping/party.cpp index 549ace4685e..2139e9e9a53 100644 --- a/src/creatures/players/grouping/party.cpp +++ b/src/creatures/players/grouping/party.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,13 +13,12 @@ #include "game/game.h" #include "lua/creature/events.h" -Party::Party(Player* initLeader) : leader(initLeader) -{ +Party::Party(Player* initLeader) : + leader(initLeader) { leader->setParty(this); } -void Party::disband() -{ +void Party::disband() { if (!g_events().eventPartyOnDisband(this)) { return; } @@ -64,8 +63,7 @@ void Party::disband() delete this; } -bool Party::leaveParty(Player* player) -{ +bool Party::leaveParty(Player* player) { if (!player) { return false; } @@ -91,7 +89,7 @@ bool Party::leaveParty(Player* player) } } - //since we already passed the leadership, we remove the player from the list + // since we already passed the leadership, we remove the player from the list auto it = std::find(memberList.begin(), memberList.end(), player); if (it != memberList.end()) { memberList.erase(it); @@ -129,13 +127,12 @@ bool Party::leaveParty(Player* player) return true; } -bool Party::passPartyLeadership(Player* player) -{ +bool Party::passPartyLeadership(Player* player) { if (!player || leader == player || player->getParty() != this) { return false; } - //Remove it before to broadcast the message correctly + // Remove it before to broadcast the message correctly auto it = std::find(memberList.begin(), memberList.end(), player); if (it != memberList.end()) { memberList.erase(it); @@ -170,8 +167,7 @@ bool Party::passPartyLeadership(Player* player) return true; } -bool Party::joinParty(Player& player) -{ +bool Party::joinParty(Player &player) { if (!g_events().eventPartyOnJoin(this, &player)) { return false; } @@ -207,17 +203,15 @@ bool Party::joinParty(Player& player) player.removePartyInvitation(this); updateSharedExperience(); - const std::string& leaderName = leader->getName(); + const std::string &leaderName = leader->getName(); ss.str(std::string()); - ss << "You have joined " << leaderName << "'" << (leaderName.back() == 's' ? "" : "s") << - " party. Open the party channel to communicate with your companions."; + ss << "You have joined " << leaderName << "'" << (leaderName.back() == 's' ? "" : "s") << " party. Open the party channel to communicate with your companions."; player.sendTextMessage(MESSAGE_PARTY_MANAGEMENT, ss.str()); updateTrackerAnalyzer(); return true; } -bool Party::removeInvite(Player& player, bool removeFromPlayer/* = true*/) -{ +bool Party::removeInvite(Player &player, bool removeFromPlayer /* = true*/) { auto it = std::find(inviteList.begin(), inviteList.end(), &player); if (it == inviteList.end()) { return false; @@ -239,8 +233,7 @@ bool Party::removeInvite(Player& player, bool removeFromPlayer/* = true*/) return true; } -void Party::revokeInvitation(Player& player) -{ +void Party::revokeInvitation(Player &player) { std::ostringstream ss; ss << leader->getName() << " has revoked " << (leader->getSex() == PLAYERSEX_FEMALE ? "her" : "his") << " invitation."; player.sendTextMessage(MESSAGE_PARTY_MANAGEMENT, ss.str()); @@ -252,8 +245,7 @@ void Party::revokeInvitation(Player& player) removeInvite(player); } -bool Party::invitePlayer(Player& player) -{ +bool Party::invitePlayer(Player &player) { if (isPlayerInvited(&player)) { return false; } @@ -282,13 +274,11 @@ bool Party::invitePlayer(Player& player) return true; } -bool Party::isPlayerInvited(const Player* player) const -{ +bool Party::isPlayerInvited(const Player* player) const { return std::find(inviteList.begin(), inviteList.end(), player) != inviteList.end(); } -void Party::updateAllPartyIcons() -{ +void Party::updateAllPartyIcons() { for (Player* member : memberList) { for (Player* otherMember : memberList) { member->sendPartyCreatureShield(otherMember); @@ -301,8 +291,7 @@ void Party::updateAllPartyIcons() updateTrackerAnalyzer(); } -void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string& msg, bool sendToInvitations /*= false*/) -{ +void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string &msg, bool sendToInvitations /*= false*/) { for (Player* member : memberList) { member->sendTextMessage(msgClass, msg); } @@ -316,8 +305,7 @@ void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string& ms } } -void Party::updateSharedExperience() -{ +void Party::updateSharedExperience() { if (sharedExpActive) { bool result = getSharedExperienceStatus() == SHAREDEXP_OK; if (result != sharedExpEnabled) { @@ -327,8 +315,7 @@ void Party::updateSharedExperience() } } -const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) -{ +const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) { switch (value) { case SHAREDEXP_OK: return "Shared Experience is now active."; @@ -345,8 +332,7 @@ const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) } } -bool Party::setSharedExperience(Player* player, bool newSharedExpActive) -{ +bool Party::setSharedExperience(Player* player, bool newSharedExpActive) { if (!player || leader != player) { return false; } @@ -369,8 +355,7 @@ bool Party::setSharedExperience(Player* player, bool newSharedExpActive) return true; } -void Party::shareExperience(uint64_t experience, Creature* target/* = nullptr*/) -{ +void Party::shareExperience(uint64_t experience, Creature* target /* = nullptr*/) { uint64_t shareExperience = experience; g_events().eventPartyOnShareExperience(this, shareExperience); for (Player* member : memberList) { @@ -379,13 +364,11 @@ void Party::shareExperience(uint64_t experience, Creature* target/* = nullptr*/) leader->onGainSharedExperience(shareExperience, target); } -bool Party::canUseSharedExperience(const Player* player) const -{ +bool Party::canUseSharedExperience(const Player* player) const { return getMemberSharedExperienceStatus(player) == SHAREDEXP_OK; } -SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) const -{ +SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) const { if (memberList.empty()) { return SHAREDEXP_EMPTYPARTY; } @@ -407,7 +390,7 @@ SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) c } if (!player->hasFlag(PlayerFlags_t::NotGainInFight)) { - //check if the player has healed/attacked anything recently + // check if the player has healed/attacked anything recently auto it = ticksMap.find(player->getID()); if (it == ticksMap.end()) { return SHAREDEXP_MEMBERINACTIVE; @@ -421,8 +404,7 @@ SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) c return SHAREDEXP_OK; } -SharedExpStatus_t Party::getSharedExperienceStatus() -{ +SharedExpStatus_t Party::getSharedExperienceStatus() { SharedExpStatus_t leaderStatus = getMemberSharedExperienceStatus(leader); if (leaderStatus != SHAREDEXP_OK) { return leaderStatus; @@ -437,16 +419,14 @@ SharedExpStatus_t Party::getSharedExperienceStatus() return SHAREDEXP_OK; } -void Party::updatePlayerTicks(Player* player, uint32_t points) -{ +void Party::updatePlayerTicks(Player* player, uint32_t points) { if (points != 0 && !player->hasFlag(PlayerFlags_t::NotGainInFight)) { ticksMap[player->getID()] = OTSYS_TIME(); updateSharedExperience(); } } -void Party::clearPlayerPoints(Player* player) -{ +void Party::clearPlayerPoints(Player* player) { auto it = ticksMap.find(player->getID()); if (it != ticksMap.end()) { ticksMap.erase(it); @@ -454,16 +434,14 @@ void Party::clearPlayerPoints(Player* player) } } -bool Party::canOpenCorpse(uint32_t ownerId) const -{ +bool Party::canOpenCorpse(uint32_t ownerId) const { if (const Player* player = g_game().getPlayerByID(ownerId)) { return leader->getID() == ownerId || player->getParty() == this; } return false; } -void Party::showPlayerStatus(Player* player, Player* member, bool showStatus) -{ +void Party::showPlayerStatus(Player* player, Player* member, bool showStatus) { player->sendPartyCreatureShowStatus(member, showStatus); member->sendPartyCreatureShowStatus(player, showStatus); if (showStatus) { @@ -489,8 +467,7 @@ void Party::showPlayerStatus(Player* player, Player* member, bool showStatus) } } -void Party::updatePlayerStatus(Player* player) -{ +void Party::updatePlayerStatus(Player* player) { int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); for (Player* member : memberList) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); @@ -508,8 +485,7 @@ void Party::updatePlayerStatus(Player* player) } } -void Party::updatePlayerStatus(Player* player, const Position& oldPos, const Position& newPos) -{ +void Party::updatePlayerStatus(Player* player, const Position &oldPos, const Position &newPos) { int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); if (maxDistance != 0) { for (Player* member : memberList) { @@ -532,8 +508,7 @@ void Party::updatePlayerStatus(Player* player, const Position& oldPos, const Pos } } -void Party::updatePlayerHealth(const Player* player, const Creature* target, uint8_t healthPercent) -{ +void Party::updatePlayerHealth(const Player* player, const Creature* target, uint8_t healthPercent) { int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); for (Player* member : memberList) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); @@ -547,8 +522,7 @@ void Party::updatePlayerHealth(const Player* player, const Creature* target, uin } } -void Party::updatePlayerMana(const Player* player, uint8_t manaPercent) -{ +void Party::updatePlayerMana(const Player* player, uint8_t manaPercent) { int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); for (Player* member : memberList) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); @@ -562,8 +536,7 @@ void Party::updatePlayerMana(const Player* player, uint8_t manaPercent) } } -void Party::updatePlayerVocation(const Player* player) -{ +void Party::updatePlayerVocation(const Player* player) { int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); for (Player* member : memberList) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); @@ -577,8 +550,7 @@ void Party::updatePlayerVocation(const Player* player) } } -void Party::updateTrackerAnalyzer() const -{ +void Party::updateTrackerAnalyzer() const { for (const Player* member : memberList) { member->updatePartyTrackerAnalyzer(); } @@ -588,8 +560,7 @@ void Party::updateTrackerAnalyzer() const } } -void Party::addPlayerLoot(const Player* player, const Item* item) -{ +void Party::addPlayerLoot(const Player* player, const Item* item) { PartyAnalyzer* playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = new PartyAnalyzer(player->getID(), player->getName()); @@ -600,43 +571,41 @@ void Party::addPlayerLoot(const Player* player, const Item* item) if (auto it = playerAnalyzer->lootMap.find(item->getID()); it != playerAnalyzer->lootMap.end()) { (*it).second += count; } else { - playerAnalyzer->lootMap.insert({item->getID(), count}); + playerAnalyzer->lootMap.insert({ item->getID(), count }); } if (priceType == LEADER_PRICE) { playerAnalyzer->lootPrice += leader->getItemCustomPrice(item->getID()) * count; } else { - std::map itemMap {{item->getID(), count}}; + std::map itemMap { { item->getID(), count } }; playerAnalyzer->lootPrice += g_game().getItemMarketPrice(itemMap, false); } updateTrackerAnalyzer(); } -void Party::addPlayerSupply(const Player* player, const Item* item) -{ +void Party::addPlayerSupply(const Player* player, const Item* item) { PartyAnalyzer* playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = new PartyAnalyzer(player->getID(), player->getName()); membersData.push_back(playerAnalyzer); } - if(auto it = playerAnalyzer->supplyMap.find(item->getID()); it != playerAnalyzer->supplyMap.end()) { + if (auto it = playerAnalyzer->supplyMap.find(item->getID()); it != playerAnalyzer->supplyMap.end()) { (*it).second += 1; } else { - playerAnalyzer->supplyMap.insert({item->getID(), 1}); + playerAnalyzer->supplyMap.insert({ item->getID(), 1 }); } if (priceType == LEADER_PRICE) { playerAnalyzer->supplyPrice += leader->getItemCustomPrice(item->getID(), true); } else { - std::map itemMap {{item->getID(), 1}}; + std::map itemMap { { item->getID(), 1 } }; playerAnalyzer->supplyPrice += g_game().getItemMarketPrice(itemMap, true); } updateTrackerAnalyzer(); } -void Party::addPlayerDamage(const Player* player, uint64_t amount) -{ +void Party::addPlayerDamage(const Player* player, uint64_t amount) { PartyAnalyzer* playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = new PartyAnalyzer(player->getID(), player->getName()); @@ -647,8 +616,7 @@ void Party::addPlayerDamage(const Player* player, uint64_t amount) updateTrackerAnalyzer(); } -void Party::addPlayerHealing(const Player* player, uint64_t amount) -{ +void Party::addPlayerHealing(const Player* player, uint64_t amount) { PartyAnalyzer* playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = new PartyAnalyzer(player->getID(), player->getName()); @@ -659,8 +627,7 @@ void Party::addPlayerHealing(const Player* player, uint64_t amount) updateTrackerAnalyzer(); } -void Party::switchAnalyzerPriceType() -{ +void Party::switchAnalyzerPriceType() { if (leader == nullptr) { return; } @@ -670,8 +637,7 @@ void Party::switchAnalyzerPriceType() updateTrackerAnalyzer(); } -void Party::resetAnalyzer() -{ +void Party::resetAnalyzer() { trackerTime = time(nullptr); for (PartyAnalyzer* analyzer : membersData) { delete analyzer; @@ -681,8 +647,7 @@ void Party::resetAnalyzer() updateTrackerAnalyzer(); } -void Party::reloadPrices() -{ +void Party::reloadPrices() { for (PartyAnalyzer* analyzer : membersData) { if (priceType == MARKET_PRICE) { analyzer->lootPrice = g_game().getItemMarketPrice(analyzer->lootMap, false); diff --git a/src/creatures/players/grouping/party.h b/src/creatures/players/grouping/party.h index 354e1505477..b1407f3e603 100644 --- a/src/creatures/players/grouping/party.h +++ b/src/creatures/players/grouping/party.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_GROUPING_PARTY_H_ #define SRC_CREATURES_PLAYERS_GROUPING_PARTY_H_ @@ -26,18 +26,17 @@ class Party; using PlayerVector = std::vector; -class Party -{ +class Party { public: explicit Party(Player* leader); Player* getLeader() const { return leader; } - PlayerVector& getMembers() { + PlayerVector &getMembers() { return memberList; } - const PlayerVector& getInvitees() const { + const PlayerVector &getInvitees() const { return inviteList; } size_t getMemberCount() const { @@ -48,17 +47,17 @@ class Party } void disband(); - bool invitePlayer(Player& player); - bool joinParty(Player& player); - void revokeInvitation(Player& player); + bool invitePlayer(Player &player); + bool joinParty(Player &player); + void revokeInvitation(Player &player); bool passPartyLeadership(Player* player); bool leaveParty(Player* player); - bool removeInvite(Player& player, bool removeFromPlayer = true); + bool removeInvite(Player &player, bool removeFromPlayer = true); bool isPlayerInvited(const Player* player) const; void updateAllPartyIcons(); - void broadcastPartyMessage(MessageClasses msgClass, const std::string& msg, bool sendToInvitations = false); + void broadcastPartyMessage(MessageClasses msgClass, const std::string &msg, bool sendToInvitations = false); bool empty() const { return memberList.empty() && inviteList.empty(); } @@ -73,7 +72,7 @@ class Party return sharedExpEnabled; } bool canUseSharedExperience(const Player* player) const; - SharedExpStatus_t getMemberSharedExperienceStatus(const Player* player) const; + SharedExpStatus_t getMemberSharedExperienceStatus(const Player* player) const; void updateSharedExperience(); void updatePlayerTicks(Player* player, uint32_t points); @@ -81,7 +80,7 @@ class Party void showPlayerStatus(Player* player, Player* member, bool showStatus); void updatePlayerStatus(Player* player); - void updatePlayerStatus(Player* player, const Position& oldPos, const Position& newPos); + void updatePlayerStatus(Player* player, const Position &oldPos, const Position &newPos); void updatePlayerHealth(const Player* player, const Creature* target, uint8_t healthPercent); void updatePlayerMana(const Player* player, uint8_t manaPercent); void updatePlayerVocation(const Player* player); @@ -95,19 +94,18 @@ class Party void resetAnalyzer(); void reloadPrices(); - PartyAnalyzer* getPlayerPartyAnalyzerStruct(uint32_t playerId) const - { + PartyAnalyzer* getPlayerPartyAnalyzerStruct(uint32_t playerId) const { if (auto it = std::find_if(membersData.begin(), membersData.end(), [playerId](const PartyAnalyzer* preyIt) { return preyIt->id == playerId; - }); it != membersData.end()) { + }); + it != membersData.end()) { return *it; } return nullptr; } - uint32_t getAnalyzerTimeNow() const - { + uint32_t getAnalyzerTimeNow() const { return static_cast(time(nullptr) - trackerTime); } @@ -132,4 +130,4 @@ class Party bool sharedExpEnabled = false; }; -#endif // SRC_CREATURES_PLAYERS_GROUPING_PARTY_H_ +#endif // SRC_CREATURES_PLAYERS_GROUPING_PARTY_H_ diff --git a/src/creatures/players/grouping/team_finder.hpp b/src/creatures/players/grouping/team_finder.hpp index fc2a0d7d375..998fad6cb99 100644 --- a/src/creatures/players/grouping/team_finder.hpp +++ b/src/creatures/players/grouping/team_finder.hpp @@ -5,56 +5,52 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_GROUPING_TEAM_FINDER_HPP_ #define SRC_CREATURES_PLAYERS_GROUPING_TEAM_FINDER_HPP_ /** - * Team assemble finder. - * This class is responsible control and manage the team finder feature. -**/ + * Team assemble finder. + * This class is responsible control and manage the team finder feature. + **/ class TeamFinder { - public: - TeamFinder() = default; - TeamFinder(uint16_t initMinLevel, uint16_t initMaxLevel, uint8_t initVocationIDs, - uint16_t initTeamSlots, uint16_t initFreeSlots, bool initPartyBool, - uint32_t initTimestamp, uint8_t initTeamType, uint16_t initBossID, - uint16_t initHunt_type, uint16_t initHunt_area, uint16_t initQuestID, - uint32_t initLeaderGuid, std::map initMembersMap) : - minLevel(initMinLevel), - maxLevel(initMaxLevel), - vocationIDs(initVocationIDs), - teamSlots(initTeamSlots), - freeSlots(initFreeSlots), - partyBool(initPartyBool), - timestamp(initTimestamp), - teamType(initTeamType), - bossID(initBossID), - hunt_type(initHunt_type), - hunt_area(initHunt_area), - questID(initQuestID), - leaderGuid(initLeaderGuid), - membersMap(initMembersMap) {} - virtual ~TeamFinder() = default; + public: + TeamFinder() = default; + TeamFinder(uint16_t initMinLevel, uint16_t initMaxLevel, uint8_t initVocationIDs, uint16_t initTeamSlots, uint16_t initFreeSlots, bool initPartyBool, uint32_t initTimestamp, uint8_t initTeamType, uint16_t initBossID, uint16_t initHunt_type, uint16_t initHunt_area, uint16_t initQuestID, uint32_t initLeaderGuid, std::map initMembersMap) : + minLevel(initMinLevel), + maxLevel(initMaxLevel), + vocationIDs(initVocationIDs), + teamSlots(initTeamSlots), + freeSlots(initFreeSlots), + partyBool(initPartyBool), + timestamp(initTimestamp), + teamType(initTeamType), + bossID(initBossID), + hunt_type(initHunt_type), + hunt_area(initHunt_area), + questID(initQuestID), + leaderGuid(initLeaderGuid), + membersMap(initMembersMap) { } + virtual ~TeamFinder() = default; - uint16_t minLevel = 0; - uint16_t maxLevel = 0; - uint8_t vocationIDs = 0; - uint16_t teamSlots = 0; - uint16_t freeSlots = 0; - bool partyBool = false; - uint32_t timestamp = 0; - uint8_t teamType = 0; - uint16_t bossID = 0; - uint16_t hunt_type = 0; - uint16_t hunt_area = 0; - uint16_t questID = 0; - uint32_t leaderGuid = 0; + uint16_t minLevel = 0; + uint16_t maxLevel = 0; + uint8_t vocationIDs = 0; + uint16_t teamSlots = 0; + uint16_t freeSlots = 0; + bool partyBool = false; + uint32_t timestamp = 0; + uint8_t teamType = 0; + uint16_t bossID = 0; + uint16_t hunt_type = 0; + uint16_t hunt_area = 0; + uint16_t questID = 0; + uint32_t leaderGuid = 0; - // list: player:getGuid(), player status - std::map membersMap = {}; + // list: player:getGuid(), player status + std::map membersMap = {}; }; -#endif // SRC_CREATURES_PLAYERS_GROUPING_TEAM_FINDER_HPP_ +#endif // SRC_CREATURES_PLAYERS_GROUPING_TEAM_FINDER_HPP_ diff --git a/src/creatures/players/imbuements/imbuements.cpp b/src/creatures/players/imbuements/imbuements.cpp index 689881aa490..6385293ad10 100644 --- a/src/creatures/players/imbuements/imbuements.cpp +++ b/src/creatures/players/imbuements/imbuements.cpp @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "creatures/players/imbuements/imbuements.h" #include "lua/creature/events.h" #include "utils/pugicast.h" -Imbuement* Imbuements::getImbuement(uint16_t id) -{ +Imbuement* Imbuements::getImbuement(uint16_t id) { if (id == 0) { return nullptr; } @@ -32,7 +31,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); - return false; + return false; } loaded = true; @@ -56,7 +55,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { ); - // Category/Group + // Category/Group } else if (strcasecmp(baseNode.name(), "category") == 0) { pugi::xml_attribute id = baseNode.attribute("id"); if (!id) { @@ -69,7 +68,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { baseNode.attribute("agressive").as_bool(true) ); - // Imbuements + // Imbuements } else if (strcasecmp(baseNode.name(), "imbuement") == 0) { ++runningid; pugi::xml_attribute base = baseNode.attribute("base"); @@ -85,16 +84,14 @@ bool Imbuements::loadFromXml(bool /* reloading */) { continue; } - auto imbuements = imbuementMap.emplace(std::piecewise_construct, - std::forward_as_tuple(runningid), - std::forward_as_tuple(runningid, baseid)); + auto imbuements = imbuementMap.emplace(std::piecewise_construct, std::forward_as_tuple(runningid), std::forward_as_tuple(runningid, baseid)); if (!imbuements.second) { SPDLOG_WARN("Duplicate imbuement of Base ID: '{}' ignored", baseid); continue; } - Imbuement& imbuement = imbuements.first->second; + Imbuement &imbuement = imbuements.first->second; pugi::xml_attribute iconBase = baseNode.attribute("iconid"); if (!iconBase) { @@ -158,26 +155,25 @@ bool Imbuements::loadFromXml(bool /* reloading */) { count = pugi::cast(childNode.attribute("count").value()); } - auto it2 = std::find_if(imbuement.items.begin(), imbuement.items.end(), [sourceId](const std::pair& source) -> bool { + auto it2 = std::find_if(imbuement.items.begin(), imbuement.items.end(), [sourceId](const std::pair &source) -> bool { return source.first == sourceId; }); if (it2 != imbuement.items.end()) { - SPDLOG_WARN("Duplicate item: {}, imbument name: {} ignored", - childNode.attribute("value").value(), imbuement.name); + SPDLOG_WARN("Duplicate item: {}, imbument name: {} ignored", childNode.attribute("value").value(), imbuement.name); continue; } imbuement.items.emplace_back(sourceId, count); - } else if (strcasecmp(type.c_str(), "description") == 0) { + } else if (strcasecmp(type.c_str(), "description") == 0) { std::string description = imbuement.name; if ((attr = childNode.attribute("value"))) { description = attr.as_string(); } imbuement.description = description; - } else if (strcasecmp(type.c_str(), "effect") == 0) { + } else if (strcasecmp(type.c_str(), "effect") == 0) { // Effects if (!(attr = childNode.attribute("type"))) { SPDLOG_WARN("Missing effect type for imbuement name: {}", imbuement.name); @@ -223,14 +219,12 @@ bool Imbuements::loadFromXml(bool /* reloading */) { usenormalskill = 3; skillId = SKILL_MANA_LEECH_AMOUNT; } else { - SPDLOG_WARN("Unknow skill name {} in imbuement name {}", - tmpStrValue, imbuement.name); + SPDLOG_WARN("Unknow skill name {} in imbuement name {}", tmpStrValue, imbuement.name); continue; } if (!(attr = childNode.attribute("bonus"))) { - SPDLOG_WARN("Missing skill bonus for imbuement name {}", - imbuement.name); + SPDLOG_WARN("Missing skill bonus for imbuement name {}", imbuement.name); continue; } int32_t bonus = pugi::cast(attr.value()); @@ -260,8 +254,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { } if (!(attr = childNode.attribute("value"))) { - SPDLOG_WARN("Missing damage reduction percentage for imbuement name {}", - imbuement.name); + SPDLOG_WARN("Missing damage reduction percentage for imbuement name {}", imbuement.name); continue; } @@ -282,8 +275,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { } if (!(attr = childNode.attribute("value"))) { - SPDLOG_WARN("Missing damage reduction percentage for imbuement name {}", - imbuement.name); + SPDLOG_WARN("Missing damage reduction percentage for imbuement name {}", imbuement.name); continue; } @@ -324,30 +316,26 @@ bool Imbuements::reload() { return loadFromXml(true); } -BaseImbuement* Imbuements::getBaseByID(uint16_t id) -{ - auto baseImbuements = std::find_if(basesImbuement.begin(), basesImbuement.end(), [id](const BaseImbuement& groupImbuement) { - return groupImbuement.id == id; - }); +BaseImbuement* Imbuements::getBaseByID(uint16_t id) { + auto baseImbuements = std::find_if(basesImbuement.begin(), basesImbuement.end(), [id](const BaseImbuement &groupImbuement) { + return groupImbuement.id == id; + }); return baseImbuements != basesImbuement.end() ? &*baseImbuements : nullptr; } -CategoryImbuement* Imbuements::getCategoryByID(uint16_t id) -{ - auto categoryImbuements = std::find_if(categoriesImbuement.begin(), categoriesImbuement.end(), [id](const CategoryImbuement& categoryImbuement) { - return categoryImbuement.id == id; - }); +CategoryImbuement* Imbuements::getCategoryByID(uint16_t id) { + auto categoryImbuements = std::find_if(categoriesImbuement.begin(), categoriesImbuement.end(), [id](const CategoryImbuement &categoryImbuement) { + return categoryImbuement.id == id; + }); return categoryImbuements != categoriesImbuement.end() ? &*categoryImbuements : nullptr; } -std::vector Imbuements::getImbuements(const Player* player, Item* item) -{ +std::vector Imbuements::getImbuements(const Player* player, Item* item) { std::vector imbuements; - for (auto& [key, value] : imbuementMap) - { + for (auto &[key, value] : imbuementMap) { Imbuement* imbuement = &value; if (!imbuement) { continue; @@ -355,9 +343,9 @@ std::vector Imbuements::getImbuements(const Player* player, Item* it // Parse the storages for each imbuement in imbuements.xml and config.lua (enable/disable storage) if (g_configManager().getBoolean(TOGGLE_IMBUEMENT_SHRINE_STORAGE) - && imbuement->getStorage() != 0 - && player->getStorageValue(imbuement->getStorage() == -1) - && imbuement->getBaseID() >= 1 && imbuement->getBaseID() <= 3) { + && imbuement->getStorage() != 0 + && player->getStorageValue(imbuement->getStorage() == -1) + && imbuement->getBaseID() >= 1 && imbuement->getBaseID() <= 3) { continue; } diff --git a/src/creatures/players/imbuements/imbuements.h b/src/creatures/players/imbuements/imbuements.h index 27270f94fd3..71912a02cbf 100644 --- a/src/creatures/players/imbuements/imbuements.h +++ b/src/creatures/players/imbuements/imbuements.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_IMBUEMENTS_IMBUEMENTS_H_ #define SRC_CREATURES_PLAYERS_IMBUEMENTS_IMBUEMENTS_H_ @@ -20,25 +20,25 @@ class Item; class Imbuement; struct BaseImbuement { - BaseImbuement(uint16_t initId, std::string initName, uint32_t initProtectionPrice, uint32_t initPrice, uint32_t initRemoveCost, uint32_t initDuration, uint8_t initPercent) : - id(initId), name(std::move(initName)), protectionPrice(initProtectionPrice), price(initPrice), removeCost(initRemoveCost), duration(initDuration), percent(initPercent) {} - - uint16_t id; - std::string name; - uint32_t protectionPrice; - uint32_t price; - uint32_t removeCost; - uint32_t duration; - uint8_t percent; + BaseImbuement(uint16_t initId, std::string initName, uint32_t initProtectionPrice, uint32_t initPrice, uint32_t initRemoveCost, uint32_t initDuration, uint8_t initPercent) : + id(initId), name(std::move(initName)), protectionPrice(initProtectionPrice), price(initPrice), removeCost(initRemoveCost), duration(initDuration), percent(initPercent) { } + + uint16_t id; + std::string name; + uint32_t protectionPrice; + uint32_t price; + uint32_t removeCost; + uint32_t duration; + uint8_t percent; }; struct CategoryImbuement { - CategoryImbuement(uint16_t initId, std::string initName, bool initAgressive) : - id(initId), name(std::move(initName)), agressive(initAgressive) {} + CategoryImbuement(uint16_t initId, std::string initName, bool initAgressive) : + id(initId), name(std::move(initName)), agressive(initAgressive) { } - uint16_t id; - std::string name; - bool agressive; + uint16_t id; + std::string name; + bool agressive; }; class Imbuements { @@ -49,10 +49,10 @@ class Imbuements { bool reload(); // non-copyable - Imbuements(const Imbuements&) = delete; - Imbuements& operator=(const Imbuements&) = delete; + Imbuements(const Imbuements &) = delete; + Imbuements &operator=(const Imbuements &) = delete; - static Imbuements& getInstance() { + static Imbuements &getInstance() { // Guaranteed to be destroyed static Imbuements instance; // Instantiated on first use @@ -80,11 +80,10 @@ class Imbuements { constexpr auto g_imbuements = &Imbuements::getInstance; -class Imbuement -{ +class Imbuement { public: Imbuement(uint16_t initId, uint16_t initBaseId) : - id(initId), baseid(initBaseId) {} + id(initId), baseid(initBaseId) { } uint16_t getID() const { return id; @@ -94,8 +93,7 @@ class Imbuement return baseid; } - uint32_t getStorage() const - { + uint32_t getStorage() const { return storage; } @@ -117,7 +115,7 @@ class Imbuement return category; } - const std::vector>& getItems() const { + const std::vector> &getItems() const { return items; } @@ -148,4 +146,4 @@ class Imbuement std::vector> items; }; -#endif // SRC_CREATURES_PLAYERS_IMBUEMENTS_IMBUEMENTS_H_ +#endif // SRC_CREATURES_PLAYERS_IMBUEMENTS_IMBUEMENTS_H_ diff --git a/src/creatures/players/management/ban.cpp b/src/creatures/players/management/ban.cpp index 95bee594087..5fd3ae0e438 100644 --- a/src/creatures/players/management/ban.cpp +++ b/src/creatures/players/management/ban.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,8 +14,7 @@ #include "database/databasetasks.h" #include "utils/tools.h" -bool Ban::acceptConnection(uint32_t clientIP) -{ +bool Ban::acceptConnection(uint32_t clientIP) { std::lock_guard lockClass(lock); uint64_t currentTime = OTSYS_TIME(); @@ -26,7 +25,7 @@ bool Ban::acceptConnection(uint32_t clientIP) return true; } - ConnectBlock& connectBlock = it->second; + ConnectBlock &connectBlock = it->second; if (connectBlock.blockTime > currentTime) { connectBlock.blockTime += 250; return false; @@ -48,9 +47,8 @@ bool Ban::acceptConnection(uint32_t clientIP) return true; } -bool IOBan::isAccountBanned(uint32_t accountId, BanInfo& banInfo) -{ - Database& db = Database::getInstance(); +bool IOBan::isAccountBanned(uint32_t accountId, BanInfo &banInfo) { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `reason`, `expires_at`, `banned_at`, `banned_by`, (SELECT `name` FROM `players` WHERE `id` = `banned_by`) AS `name` FROM `account_bans` WHERE `account_id` = " << accountId; @@ -79,13 +77,12 @@ bool IOBan::isAccountBanned(uint32_t accountId, BanInfo& banInfo) return true; } -bool IOBan::isIpBanned(uint32_t clientIP, BanInfo& banInfo) -{ +bool IOBan::isIpBanned(uint32_t clientIP, BanInfo &banInfo) { if (clientIP == 0) { return false; } - Database& db = Database::getInstance(); + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `reason`, `expires_at`, (SELECT `name` FROM `players` WHERE `id` = `banned_by`) AS `name` FROM `ip_bans` WHERE `ip` = " << clientIP; @@ -109,8 +106,7 @@ bool IOBan::isIpBanned(uint32_t clientIP, BanInfo& banInfo) return true; } -bool IOBan::isPlayerNamelocked(uint32_t playerId) -{ +bool IOBan::isPlayerNamelocked(uint32_t playerId) { std::ostringstream query; query << "SELECT 1 FROM `player_namelocks` WHERE `player_id` = " << playerId; return Database::getInstance().storeQuery(query.str()).get() != nullptr; diff --git a/src/creatures/players/management/ban.h b/src/creatures/players/management/ban.h index a290fb17c1c..f9bc9cf1573 100644 --- a/src/creatures/players/management/ban.h +++ b/src/creatures/players/management/ban.h @@ -5,30 +5,29 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_MANAGEMENT_BAN_H_ #define SRC_CREATURES_PLAYERS_MANAGEMENT_BAN_H_ struct BanInfo { - std::string bannedBy; - std::string reason; - time_t expiresAt; + std::string bannedBy; + std::string reason; + time_t expiresAt; }; struct ConnectBlock { - constexpr ConnectBlock(uint64_t lastAttempt, uint64_t blockTime, uint32_t count) : - lastAttempt(lastAttempt), blockTime(blockTime), count(count) {} + constexpr ConnectBlock(uint64_t lastAttempt, uint64_t blockTime, uint32_t count) : + lastAttempt(lastAttempt), blockTime(blockTime), count(count) { } - uint64_t lastAttempt; - uint64_t blockTime; - uint32_t count; + uint64_t lastAttempt; + uint64_t blockTime; + uint32_t count; }; using IpConnectMap = std::map; -class Ban -{ +class Ban { public: bool acceptConnection(uint32_t clientIP); @@ -37,12 +36,11 @@ class Ban std::recursive_mutex lock; }; -class IOBan -{ +class IOBan { public: - static bool isAccountBanned(uint32_t accountId, BanInfo& banInfo); - static bool isIpBanned(uint32_t clientIP, BanInfo& banInfo); + static bool isAccountBanned(uint32_t accountId, BanInfo &banInfo); + static bool isIpBanned(uint32_t clientIP, BanInfo &banInfo); static bool isPlayerNamelocked(uint32_t playerId); }; -#endif // SRC_CREATURES_PLAYERS_MANAGEMENT_BAN_H_ +#endif // SRC_CREATURES_PLAYERS_MANAGEMENT_BAN_H_ diff --git a/src/creatures/players/management/waitlist.cpp b/src/creatures/players/management/waitlist.cpp index f5cde9e2d3d..9866bb1d6c3 100644 --- a/src/creatures/players/management/waitlist.cpp +++ b/src/creatures/players/management/waitlist.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,69 +14,63 @@ namespace { -struct Wait -{ - constexpr Wait(std::size_t initTimeout, uint32_t initPlayerGUID) : - timeout(initTimeout), playerGUID(initPlayerGUID) {} + struct Wait { + constexpr Wait(std::size_t initTimeout, uint32_t initPlayerGUID) : + timeout(initTimeout), playerGUID(initPlayerGUID) { } - std::size_t timeout; - uint32_t playerGUID; -}; + std::size_t timeout; + uint32_t playerGUID; + }; -using WaitList = std::list; + using WaitList = std::list; -void cleanupList(WaitList& list) -{ - int64_t time = OTSYS_TIME(); + void cleanupList(WaitList &list) { + int64_t time = OTSYS_TIME(); - auto it = list.begin(), end = list.end(); - while (it != end) { - if ((it->timeout - time) <= 0) { - it = list.erase(it); - } else { - ++it; + auto it = list.begin(), end = list.end(); + while (it != end) { + if ((it->timeout - time) <= 0) { + it = list.erase(it); + } else { + ++it; + } } } -} -std::size_t getTimeout(std::size_t slot) -{ - //timeout is set to 15 seconds longer than expected retry attempt - return WaitingList::getTime(slot) + 15; -} + std::size_t getTimeout(std::size_t slot) { + // timeout is set to 15 seconds longer than expected retry attempt + return WaitingList::getTime(slot) + 15; + } } // namespace -struct WaitListInfo -{ - WaitList priorityWaitList; - WaitList waitList; +struct WaitListInfo { + WaitList priorityWaitList; + WaitList waitList; - std::pair findClient(const Player *player) { - std::size_t slot = 1; - for (auto it = priorityWaitList.begin(), end = priorityWaitList.end(); it != end; ++it, ++slot) { - if (it->playerGUID == player->getGUID()) { - return {it, slot}; + std::pair findClient(const Player* player) { + std::size_t slot = 1; + for (auto it = priorityWaitList.begin(), end = priorityWaitList.end(); it != end; ++it, ++slot) { + if (it->playerGUID == player->getGUID()) { + return { it, slot }; + } } - } - for (auto it = waitList.begin(), end = waitList.end(); it != end; ++it, ++slot) { - if (it->playerGUID == player->getGUID()) { - return {it, slot}; + for (auto it = waitList.begin(), end = waitList.end(); it != end; ++it, ++slot) { + if (it->playerGUID == player->getGUID()) { + return { it, slot }; + } } + return { waitList.end(), slot }; } - return {waitList.end(), slot}; - } }; -WaitingList& WaitingList::getInstance() -{ +WaitingList &WaitingList::getInstance() { static WaitingList waitingList; return waitingList; } -std::size_t WaitingList::getTime(std::size_t slot) -{ +std::size_t WaitingList::getTime(std::size_t slot) { if (slot < 5) { return 5; } else if (slot < 10) { @@ -90,10 +84,8 @@ std::size_t WaitingList::getTime(std::size_t slot) } } -bool WaitingList::clientLogin(const Player* player) -{ - if (player->hasFlag(PlayerFlags_t::CanAlwaysLogin) || - player->getAccountType() >= account::ACCOUNT_TYPE_GAMEMASTER) { +bool WaitingList::clientLogin(const Player* player) { + if (player->hasFlag(PlayerFlags_t::CanAlwaysLogin) || player->getAccountType() >= account::ACCOUNT_TYPE_GAMEMASTER) { return true; } @@ -110,12 +102,12 @@ bool WaitingList::clientLogin(const Player* player) std::tie(it, slot) = info->findClient(player); if (it != info->waitList.end()) { if ((g_game().getPlayersOnline() + slot) <= maxPlayers) { - //should be able to login now + // should be able to login now info->waitList.erase(it); return true; } - //let them wait a bit longer + // let them wait a bit longer it->timeout = OTSYS_TIME() + (getTimeout(slot) * 1000); return false; } @@ -130,8 +122,7 @@ bool WaitingList::clientLogin(const Player* player) return false; } -std::size_t WaitingList::getClientSlot(const Player* player) -{ +std::size_t WaitingList::getClientSlot(const Player* player) { WaitList::iterator it; WaitList::size_type slot; std::tie(it, slot) = info->findClient(player); @@ -141,4 +132,5 @@ std::size_t WaitingList::getClientSlot(const Player* player) return slot; } -WaitingList::WaitingList() : info(new WaitListInfo) {} +WaitingList::WaitingList() : + info(new WaitListInfo) { } diff --git a/src/creatures/players/management/waitlist.h b/src/creatures/players/management/waitlist.h index dfe5283d884..5f9f2282441 100644 --- a/src/creatures/players/management/waitlist.h +++ b/src/creatures/players/management/waitlist.h @@ -5,17 +5,16 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_MANAGEMENT_WAITLIST_H_ #define SRC_CREATURES_PLAYERS_MANAGEMENT_WAITLIST_H_ struct WaitListInfo; -class WaitingList -{ +class WaitingList { public: - static WaitingList& getInstance(); + static WaitingList &getInstance(); bool clientLogin(const Player* player); std::size_t getClientSlot(const Player* player); @@ -27,4 +26,4 @@ class WaitingList std::unique_ptr info; }; -#endif // SRC_CREATURES_PLAYERS_MANAGEMENT_WAITLIST_H_ +#endif // SRC_CREATURES_PLAYERS_MANAGEMENT_WAITLIST_H_ diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 2933f2591c1..822fb78cc7c 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -30,16 +30,15 @@ MuteCountMap Player::muteCountMap; uint32_t Player::playerAutoID = 0x10010000; Player::Player(ProtocolGame_ptr p) : - Creature(), - lastPing(OTSYS_TIME()), - lastPong(lastPing), - inbox(new Inbox(ITEM_INBOX)), - client(std::move(p)) { - inbox->incrementReferenceCounter(); + Creature(), + lastPing(OTSYS_TIME()), + lastPong(lastPing), + inbox(new Inbox(ITEM_INBOX)), + client(std::move(p)) { + inbox->incrementReferenceCounter(); } -Player::~Player() -{ +Player::~Player() { for (Item* item : inventory) { if (item) { item->setParent(nullptr); @@ -48,17 +47,17 @@ Player::~Player() } } - for (const auto& it : depotLockerMap) { + for (const auto &it : depotLockerMap) { it.second->removeInbox(inbox); it.second->stopDecaying(); it.second->decrementReferenceCounter(); } - for (const auto& it : rewardMap) { + for (const auto &it : rewardMap) { it.second->decrementReferenceCounter(); } - for (const auto& it : quickLootContainers) { + for (const auto &it : quickLootContainers) { it.second->decrementReferenceCounter(); } @@ -82,8 +81,7 @@ Player::~Player() logged = false; } -bool Player::setVocation(uint16_t vocId) -{ +bool Player::setVocation(uint16_t vocId) { Vocation* voc = g_vocations().getVocation(vocId); if (!voc) { return false; @@ -95,16 +93,14 @@ bool Player::setVocation(uint16_t vocId) return true; } -bool Player::isPushable() const -{ +bool Player::isPushable() const { if (hasFlag(PlayerFlags_t::CannotBePushed)) { return false; } return Creature::isPushable(); } -std::string Player::getDescription(int32_t lookDistance) const -{ +std::string Player::getDescription(int32_t lookDistance) const { std::ostringstream s; if (lookDistance == -1) { @@ -192,26 +188,22 @@ std::string Player::getDescription(int32_t lookDistance) const return s.str(); } -Item* Player::getInventoryItem(Slots_t slot) const -{ +Item* Player::getInventoryItem(Slots_t slot) const { if (slot < CONST_SLOT_FIRST || slot > CONST_SLOT_LAST) { return nullptr; } return inventory[slot]; } -void Player::addConditionSuppressions(uint32_t addConditions) -{ +void Player::addConditionSuppressions(uint32_t addConditions) { conditionSuppressions |= addConditions; } -void Player::removeConditionSuppressions(uint32_t removeConditions) -{ +void Player::removeConditionSuppressions(uint32_t removeConditions) { conditionSuppressions &= ~removeConditions; } -Item* Player::getWeapon(Slots_t slot, bool ignoreAmmo) const -{ +Item* Player::getWeapon(Slots_t slot, bool ignoreAmmo) const { Item* item = inventory[slot]; if (!item) { return nullptr; @@ -223,7 +215,7 @@ Item* Player::getWeapon(Slots_t slot, bool ignoreAmmo) const } if (!ignoreAmmo && weaponType == WEAPON_DISTANCE) { - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.ammoType != AMMO_NONE) { item = getQuiverAmmoOfType(it); } @@ -237,7 +229,7 @@ bool Player::hasQuiverEquipped() const { return quiver && quiver->isQuiver() && quiver->getContainer(); } -bool Player::hasWeaponDistanceEquipped() const{ +bool Player::hasWeaponDistanceEquipped() const { const Item* item = inventory[CONST_SLOT_LEFT]; return item && item->getWeaponType() == WEAPON_DISTANCE; } @@ -248,9 +240,8 @@ Item* Player::getQuiverAmmoOfType(const ItemType &it) const { } Item* quiver = inventory[CONST_SLOT_RIGHT]; - for (const Container *container = quiver->getContainer(); - Item* ammoItem : container->getItemList()) - { + for (const Container* container = quiver->getContainer(); + Item * ammoItem : container->getItemList()) { if (ammoItem->getAmmoType() == it.ammoType) { if (level >= Item::items[ammoItem->getID()].minReqLevel) { return ammoItem; @@ -260,8 +251,7 @@ Item* Player::getQuiverAmmoOfType(const ItemType &it) const { return nullptr; } -Item* Player::getWeapon(bool ignoreAmmo/* = false*/) const -{ +Item* Player::getWeapon(bool ignoreAmmo /* = false*/) const { Item* item = getWeapon(CONST_SLOT_LEFT, ignoreAmmo); if (item) { return item; @@ -274,8 +264,7 @@ Item* Player::getWeapon(bool ignoreAmmo/* = false*/) const return nullptr; } -WeaponType_t Player::getWeaponType() const -{ +WeaponType_t Player::getWeaponType() const { Item* item = getWeapon(); if (!item) { return WEAPON_NONE; @@ -283,8 +272,7 @@ WeaponType_t Player::getWeaponType() const return item->getWeaponType(); } -int32_t Player::getWeaponSkill(const Item* item) const -{ +int32_t Player::getWeaponSkill(const Item* item) const { if (!item) { return getSkillLevel(SKILL_FIST); } @@ -321,11 +309,10 @@ int32_t Player::getWeaponSkill(const Item* item) const return attackSkill; } -int32_t Player::getArmor() const -{ +int32_t Player::getArmor() const { int32_t armor = 0; - static const Slots_t armorSlots[] = {CONST_SLOT_HEAD, CONST_SLOT_NECKLACE, CONST_SLOT_ARMOR, CONST_SLOT_LEGS, CONST_SLOT_FEET, CONST_SLOT_RING}; + static const Slots_t armorSlots[] = { CONST_SLOT_HEAD, CONST_SLOT_NECKLACE, CONST_SLOT_ARMOR, CONST_SLOT_LEGS, CONST_SLOT_FEET, CONST_SLOT_RING }; for (Slots_t slot : armorSlots) { Item* inventoryItem = inventory[slot]; if (inventoryItem) { @@ -335,8 +322,7 @@ int32_t Player::getArmor() const return static_cast(armor * vocation->armorMultiplier); } -void Player::getShieldAndWeapon(const Item*& shield, const Item*& weapon) const -{ +void Player::getShieldAndWeapon(const Item*&shield, const Item*&weapon) const { shield = nullptr; weapon = nullptr; @@ -365,16 +351,14 @@ void Player::getShieldAndWeapon(const Item*& shield, const Item*& weapon) const } } -int32_t Player::getDefense() const -{ +int32_t Player::getDefense() const { int32_t defenseSkill = getSkillLevel(SKILL_FIST); int32_t defenseValue = 7; const Item* weapon; const Item* shield; try { getShieldAndWeapon(shield, weapon); - } - catch (const std::exception &e) { + } catch (const std::exception &e) { SPDLOG_ERROR("{} got exception {}", getName(), e.what()); } @@ -402,28 +386,33 @@ int32_t Player::getDefense() const return (defenseSkill / 4. + 2.23) * defenseValue * 0.15 * getDefenseFactor() * vocation->defenseMultiplier; } -float Player::getAttackFactor() const -{ +float Player::getAttackFactor() const { switch (fightMode) { - case FIGHTMODE_ATTACK: return 1.0f; - case FIGHTMODE_BALANCED: return 0.75f; - case FIGHTMODE_DEFENSE: return 0.5f; - default: return 1.0f; + case FIGHTMODE_ATTACK: + return 1.0f; + case FIGHTMODE_BALANCED: + return 0.75f; + case FIGHTMODE_DEFENSE: + return 0.5f; + default: + return 1.0f; } } -float Player::getDefenseFactor() const -{ +float Player::getDefenseFactor() const { switch (fightMode) { - case FIGHTMODE_ATTACK: return (OTSYS_TIME() - lastAttack) < getAttackSpeed() ? 0.5f : 1.0f; - case FIGHTMODE_BALANCED: return (OTSYS_TIME() - lastAttack) < getAttackSpeed() ? 0.75f : 1.0f; - case FIGHTMODE_DEFENSE: return 1.0f; - default: return 1.0f; + case FIGHTMODE_ATTACK: + return (OTSYS_TIME() - lastAttack) < getAttackSpeed() ? 0.5f : 1.0f; + case FIGHTMODE_BALANCED: + return (OTSYS_TIME() - lastAttack) < getAttackSpeed() ? 0.75f : 1.0f; + case FIGHTMODE_DEFENSE: + return 1.0f; + default: + return 1.0f; } } -uint32_t Player::getClientIcons() const -{ +uint32_t Player::getClientIcons() const { uint32_t icons = 0; for (Condition* condition : conditions) { if (!isSuppress(condition->getType())) { @@ -459,8 +448,7 @@ uint32_t Player::getClientIcons() const return icon_bitset.to_ulong(); } -void Player::updateInventoryWeight() -{ +void Player::updateInventoryWeight() { if (hasFlag(PlayerFlags_t::HasInfiniteCapacity)) { return; } @@ -474,8 +462,7 @@ void Player::updateInventoryWeight() } } -void Player::updateInventoryImbuement() -{ +void Player::updateInventoryImbuement() { // Get the tile the player is currently on const Tile* playerTile = getTile(); // Check if the player is in a protection zone @@ -483,16 +470,13 @@ void Player::updateInventoryImbuement() // Check if the player is in fight mode bool isInFightMode = hasCondition(CONDITION_INFIGHT); // Iterate through all items in the player's inventory - for (auto item : getAllInventoryItems()) - { + for (auto item : getAllInventoryItems()) { // Iterate through all imbuement slots on the item - for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) - { + for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) { ImbuementInfo imbuementInfo; // Get the imbuement information for the current slot - if (!item->getImbuementInfo(slotid, &imbuementInfo)) - { + if (!item->getImbuementInfo(slotid, &imbuementInfo)) { // If no imbuement is found, continue to the next slot break; } @@ -515,8 +499,7 @@ void Player::updateInventoryImbuement() } // If the imbuement's duration is 0, remove its stats and continue to the next slot - if (imbuementInfo.duration == 0) - { + if (imbuementInfo.duration == 0) { removeItemImbuementStats(imbuement); continue; } @@ -531,7 +514,7 @@ void Player::updateInventoryImbuement() } void Player::setTraining(bool value) { - for (const auto& [key, player] : g_game().getPlayers()) { + for (const auto &[key, player] : g_game().getPlayers()) { if (!this->isInGhostMode() || player->isAccessPlayer()) { player->notifyStatusChange(this, value ? VIPSTATUS_TRAINING : VIPSTATUS_ONLINE, false); } @@ -540,12 +523,11 @@ void Player::setTraining(bool value) { setExerciseTraining(value); } -void Player::addSkillAdvance(skills_t skill, uint64_t count) -{ +void Player::addSkillAdvance(skills_t skill, uint64_t count) { uint64_t currReqTries = vocation->getReqSkillTries(skill, skills[skill].level); uint64_t nextReqTries = vocation->getReqSkillTries(skill, skills[skill].level + 1); if (currReqTries >= nextReqTries) { - //player has reached max skill + // player has reached max skill return; } @@ -596,8 +578,7 @@ void Player::addSkillAdvance(skills_t skill, uint64_t count) } } -void Player::setVarStats(stats_t stat, int32_t modifier) -{ +void Player::setVarStats(stats_t stat, int32_t modifier) { varStats[stat] += modifier; switch (stat) { @@ -613,8 +594,7 @@ void Player::setVarStats(stats_t stat, int32_t modifier) case STAT_MAXMANAPOINTS: { if (getMana() > getMaxMana()) { Creature::changeMana(getMaxMana() - getMana()); - } - else { + } else { g_game().addPlayerMana(this); } break; @@ -626,18 +606,20 @@ void Player::setVarStats(stats_t stat, int32_t modifier) } } -int32_t Player::getDefaultStats(stats_t stat) const -{ +int32_t Player::getDefaultStats(stats_t stat) const { switch (stat) { - case STAT_MAXHITPOINTS: return healthMax; - case STAT_MAXMANAPOINTS: return manaMax; - case STAT_MAGICPOINTS: return getBaseMagicLevel(); - default: return 0; + case STAT_MAXHITPOINTS: + return healthMax; + case STAT_MAXMANAPOINTS: + return manaMax; + case STAT_MAGICPOINTS: + return getBaseMagicLevel(); + default: + return 0; } } -void Player::addContainer(uint8_t cid, Container* container) -{ +void Player::addContainer(uint8_t cid, Container* container) { if (cid > 0xF) { return; } @@ -652,7 +634,7 @@ void Player::addContainer(uint8_t cid, Container* container) auto it = openContainers.find(cid); if (it != openContainers.end()) { - OpenContainer& openContainer = it->second; + OpenContainer &openContainer = it->second; Container* oldContainer = openContainer.container; if (oldContainer->getID() == ITEM_BROWSEFIELD) { oldContainer->decrementReferenceCounter(); @@ -668,8 +650,7 @@ void Player::addContainer(uint8_t cid, Container* container) } } -void Player::closeContainer(uint8_t cid) -{ +void Player::closeContainer(uint8_t cid) { auto it = openContainers.find(cid); if (it == openContainers.end()) { return; @@ -684,8 +665,7 @@ void Player::closeContainer(uint8_t cid) } } -void Player::setContainerIndex(uint8_t cid, uint16_t index) -{ +void Player::setContainerIndex(uint8_t cid, uint16_t index) { auto it = openContainers.find(cid); if (it == openContainers.end()) { return; @@ -693,8 +673,7 @@ void Player::setContainerIndex(uint8_t cid, uint16_t index) it->second.index = index; } -Container* Player::getContainerByID(uint8_t cid) -{ +Container* Player::getContainerByID(uint8_t cid) { auto it = openContainers.find(cid); if (it == openContainers.end()) { return nullptr; @@ -702,9 +681,8 @@ Container* Player::getContainerByID(uint8_t cid) return it->second.container; } -int8_t Player::getContainerID(const Container* container) const -{ - for (const auto& it : openContainers) { +int8_t Player::getContainerID(const Container* container) const { + for (const auto &it : openContainers) { if (it.second.container == container) { return it.first; } @@ -712,8 +690,7 @@ int8_t Player::getContainerID(const Container* container) const return -1; } -uint16_t Player::getContainerIndex(uint8_t cid) const -{ +uint16_t Player::getContainerIndex(uint8_t cid) const { auto it = openContainers.find(cid); if (it == openContainers.end()) { return 0; @@ -721,13 +698,11 @@ uint16_t Player::getContainerIndex(uint8_t cid) const return it->second.index; } -bool Player::canOpenCorpse(uint32_t ownerId) const -{ +bool Player::canOpenCorpse(uint32_t ownerId) const { return getID() == ownerId || (party && party->canOpenCorpse(ownerId)); } -uint16_t Player::getLookCorpse() const -{ +uint16_t Player::getLookCorpse() const { if (sex == PLAYERSEX_FEMALE) { return ITEM_FEMALE_CORPSE; } else { @@ -735,8 +710,7 @@ uint16_t Player::getLookCorpse() const } } -void Player::addStorageValue(const uint32_t key, const int32_t value, const bool isLogin/* = false*/) -{ +void Player::addStorageValue(const uint32_t key, const int32_t value, const bool isLogin /* = false*/) { if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) { if (IS_IN_KEYRANGE(key, OUTFITS_RANGE)) { outfits.emplace_back( @@ -748,7 +722,8 @@ void Player::addStorageValue(const uint32_t key, const int32_t value, const bool // do nothing } else if (IS_IN_KEYRANGE(key, FAMILIARS_RANGE)) { familiars.emplace_back( - value >> 16); + value >> 16 + ); return; } else { SPDLOG_WARN("Unknown reserved key: {} for player: {}", key, getName()); @@ -768,8 +743,7 @@ void Player::addStorageValue(const uint32_t key, const int32_t value, const bool } } -int32_t Player::getStorageValue(const uint32_t key) const -{ +int32_t Player::getStorageValue(const uint32_t key) const { int32_t value = -1; auto it = storageMap.find(key); if (it == storageMap.end()) { @@ -780,16 +754,14 @@ int32_t Player::getStorageValue(const uint32_t key) const return value; } -bool Player::canSee(const Position& pos) const -{ +bool Player::canSee(const Position &pos) const { if (!client) { return false; } return client->canSee(pos); } -bool Player::canSeeCreature(const Creature* creature) const -{ +bool Player::canSeeCreature(const Creature* creature) const { if (creature == this) { return true; } @@ -804,8 +776,7 @@ bool Player::canSeeCreature(const Creature* creature) const return true; } -bool Player::canWalkthrough(const Creature* creature) const -{ +bool Player::canWalkthrough(const Creature* creature) const { if (group->access || creature->isInGhostMode()) { return true; } @@ -853,8 +824,7 @@ bool Player::canWalkthrough(const Creature* creature) const return false; } -bool Player::canWalkthroughEx(const Creature* creature) const -{ +bool Player::canWalkthroughEx(const Creature* creature) const { if (group->access) { return true; } @@ -879,18 +849,15 @@ bool Player::canWalkthroughEx(const Creature* creature) const } else { return false; } - } -void Player::onReceiveMail() const -{ +void Player::onReceiveMail() const { if (isNearDepotBox()) { sendTextMessage(MESSAGE_EVENT_ADVANCE, "New mail has arrived."); } } -Container* Player::setLootContainer(ObjectCategory_t category, Container* container, bool loading /* = false*/) -{ +Container* Player::setLootContainer(ObjectCategory_t category, Container* container, bool loading /* = false*/) { Container* previousContainer = nullptr; if (container) { previousContainer = container; @@ -905,8 +872,7 @@ Container* Player::setLootContainer(ObjectCategory_t category, Container* contai return previousContainer; } else { if (auto it = quickLootContainers.find(category); - it != quickLootContainers.end() && !loading) - { + it != quickLootContainers.end() && !loading) { previousContainer = (*it).second; auto flags = previousContainer->getAttribute(ItemAttribute_t::QUICKLOOTCONTAINER); flags &= ~(1 << category); @@ -924,8 +890,7 @@ Container* Player::setLootContainer(ObjectCategory_t category, Container* contai return nullptr; } -Container* Player::getLootContainer(ObjectCategory_t category) const -{ +Container* Player::getLootContainer(ObjectCategory_t category) const { if (category != OBJECTCATEGORY_DEFAULT && !isPremium()) { category = OBJECTCATEGORY_DEFAULT; } @@ -943,8 +908,7 @@ Container* Player::getLootContainer(ObjectCategory_t category) const return nullptr; } -void Player::checkLootContainers(const Item* item) -{ +void Player::checkLootContainers(const Item* item) { if (!item) { return; } @@ -980,8 +944,7 @@ void Player::checkLootContainers(const Item* item) } } -void Player::sendLootStats(Item* item, uint8_t count) const -{ +void Player::sendLootStats(Item* item, uint8_t count) const { if (client) { client->sendLootStats(item, count); } @@ -991,9 +954,8 @@ void Player::sendLootStats(Item* item, uint8_t count) const } } -bool Player::isNearDepotBox() const -{ - const Position& pos = getPosition(); +bool Player::isNearDepotBox() const { + const Position &pos = getPosition(); for (int32_t cx = -1; cx <= 1; ++cx) { for (int32_t cy = -1; cy <= 1; ++cy) { const Tile* posTile = g_game().map.getTile(static_cast(pos.x + cx), static_cast(pos.y + cy), pos.z); @@ -1009,8 +971,7 @@ bool Player::isNearDepotBox() const return false; } -DepotChest* Player::getDepotChest(uint32_t depotId, bool autoCreate) -{ +DepotChest* Player::getDepotChest(uint32_t depotId, bool autoCreate) { auto it = depotChests.find(depotId); if (it != depotChests.end()) { return it->second; @@ -1023,9 +984,9 @@ DepotChest* Player::getDepotChest(uint32_t depotId, bool autoCreate) DepotChest* depotChest; if (depotId > 0 && depotId < 18) { depotChest = new DepotChest(ITEM_DEPOT_NULL + depotId); - } else if (depotId == 18) { + } else if (depotId == 18) { depotChest = new DepotChest(ITEM_DEPOT_XVIII); - } else if (depotId == 19) { + } else if (depotId == 19) { depotChest = new DepotChest(ITEM_DEPOT_XIX); } else { depotChest = new DepotChest(ITEM_DEPOT_XX); @@ -1036,15 +997,14 @@ DepotChest* Player::getDepotChest(uint32_t depotId, bool autoCreate) return depotChest; } -DepotLocker* Player::getDepotLocker(uint32_t depotId) -{ +DepotLocker* Player::getDepotLocker(uint32_t depotId) { auto it = depotLockerMap.find(depotId); if (it != depotLockerMap.end()) { inbox->setParent(it->second); for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES); i > 0; i--) { if (DepotChest* depotBox = getDepotChest(i, false)) { depotBox->setParent(it->second->getItemByIndex(0)->getContainer()); - } + } } return it->second; } @@ -1065,8 +1025,7 @@ DepotLocker* Player::getDepotLocker(uint32_t depotId) return depotLocker; } -RewardChest* Player::getRewardChest() -{ +RewardChest* Player::getRewardChest() { if (rewardChest != nullptr) { return rewardChest; } @@ -1075,8 +1034,7 @@ RewardChest* Player::getRewardChest() return rewardChest; } -Reward* Player::getReward(uint32_t rewardId, bool autoCreate) -{ +Reward* Player::getReward(uint32_t rewardId, bool autoCreate) { auto it = rewardMap.find(rewardId); if (it != rewardMap.end()) { return it->second; @@ -1100,28 +1058,25 @@ void Player::removeReward(uint32_t rewardId) { rewardMap.erase(rewardId); } -void Player::getRewardList(std::vector& rewards) { +void Player::getRewardList(std::vector &rewards) { rewards.reserve(rewardMap.size()); - for (auto& it : rewardMap) { + for (auto &it : rewardMap) { rewards.push_back(it.first); } } -void Player::sendCancelMessage(ReturnValue message) const -{ +void Player::sendCancelMessage(ReturnValue message) const { sendCancelMessage(getReturnMessage(message)); } -void Player::sendStats() -{ +void Player::sendStats() { if (client) { client->sendStats(); lastStatsTrainingTime = getOfflineTrainingTime() / 60 / 1000; } } -void Player::updateSupplyTracker(const Item* item) const -{ +void Player::updateSupplyTracker(const Item* item) const { if (client) { client->sendUpdateSupplyTracker(item); } @@ -1131,15 +1086,13 @@ void Player::updateSupplyTracker(const Item* item) const } } -void Player::updateImpactTracker(CombatType_t type, int32_t amount) const -{ +void Player::updateImpactTracker(CombatType_t type, int32_t amount) const { if (client) { client->sendUpdateImpactTracker(type, amount); } } -void Player::sendPing() -{ +void Player::sendPing() { int64_t timeNow = OTSYS_TIME(); bool hasLostConnection = false; @@ -1166,15 +1119,13 @@ void Player::sendPing() } } -Item* Player::getWriteItem(uint32_t& retWindowTextId, uint16_t& retMaxWriteLen) -{ +Item* Player::getWriteItem(uint32_t &retWindowTextId, uint16_t &retMaxWriteLen) { retWindowTextId = this->windowTextId; retMaxWriteLen = this->maxWriteLen; return writeItem; } -void Player::setImbuingItem(Item* item) -{ +void Player::setImbuingItem(Item* item) { if (imbuingItem) { imbuingItem->decrementReferenceCounter(); } @@ -1186,8 +1137,7 @@ void Player::setImbuingItem(Item* item) imbuingItem = item; } -void Player::setWriteItem(Item* item, uint16_t maxWriteLength /*= 0*/) -{ +void Player::setWriteItem(Item* item, uint16_t maxWriteLength /*= 0*/) { windowTextId++; if (writeItem) { @@ -1204,22 +1154,19 @@ void Player::setWriteItem(Item* item, uint16_t maxWriteLength /*= 0*/) } } -House* Player::getEditHouse(uint32_t& retWindowTextId, uint32_t& retListId) -{ +House* Player::getEditHouse(uint32_t &retWindowTextId, uint32_t &retListId) { retWindowTextId = this->windowTextId; retListId = this->editListId; return editHouse; } -void Player::setEditHouse(House* house, uint32_t listId /*= 0*/) -{ +void Player::setEditHouse(House* house, uint32_t listId /*= 0*/) { windowTextId++; editHouse = house; editListId = listId; } -void Player::sendHouseWindow(House* house, uint32_t listId) const -{ +void Player::sendHouseWindow(House* house, uint32_t listId) const { if (!client) { return; } @@ -1230,42 +1177,36 @@ void Player::sendHouseWindow(House* house, uint32_t listId) const } } -void Player::onApplyImbuement(Imbuement *imbuement, Item *item, uint8_t slot, bool protectionCharm) -{ +void Player::onApplyImbuement(Imbuement* imbuement, Item* item, uint8_t slot, bool protectionCharm) { if (!imbuement || !item) { return; } ImbuementInfo imbuementInfo; - if (item->getImbuementInfo(slot, &imbuementInfo)) - { + if (item->getImbuementInfo(slot, &imbuementInfo)) { SPDLOG_ERROR("[Player::onApplyImbuement] - An error occurred while player with name {} try to apply imbuement, item already contains imbuement", this->getName()); this->sendImbuementResult("An error ocurred, please reopen imbuement window."); return; } - const auto& items = imbuement->getItems(); - for (auto& [key, value] : items) - { - const ItemType& itemType = Item::items[key]; - if (this->getItemTypeCount(key) + this->getStashItemCount(itemType.id) < value) - { + const auto &items = imbuement->getItems(); + for (auto &[key, value] : items) { + const ItemType &itemType = Item::items[key]; + if (this->getItemTypeCount(key) + this->getStashItemCount(itemType.id) < value) { this->sendImbuementResult("You don't have all necessary items."); return; } } - const BaseImbuement *baseImbuement = g_imbuements().getBaseByID(imbuement->getBaseID()); - if (!baseImbuement) - { + const BaseImbuement* baseImbuement = g_imbuements().getBaseByID(imbuement->getBaseID()); + if (!baseImbuement) { return; } uint32_t price = baseImbuement->price; price += protectionCharm ? baseImbuement->protectionPrice : 0; - if (!g_game().removeMoney(this, price, 0, true)) - { + if (!g_game().removeMoney(this, price, 0, true)) { std::string message = fmt::format("You don't have {} gold coins.", price); SPDLOG_ERROR("[Player::onApplyImbuement] - An error occurred while player with name {} try to apply imbuement, player do not have money", this->getName()); @@ -1274,31 +1215,27 @@ void Player::onApplyImbuement(Imbuement *imbuement, Item *item, uint8_t slot, bo } std::stringstream withdrawItemMessage; - for (auto& [key, value] : items) - { + for (auto &[key, value] : items) { uint32_t inventoryItemCount = getItemTypeCount(key); - if (inventoryItemCount >= value) - { + if (inventoryItemCount >= value) { removeItemOfType(key, value, -1, true); continue; } uint32_t mathItemCount = value; - if (inventoryItemCount > 0 && removeItemOfType(key, inventoryItemCount, -1, false)) - { + if (inventoryItemCount > 0 && removeItemOfType(key, inventoryItemCount, -1, false)) { mathItemCount = mathItemCount - inventoryItemCount; } - const ItemType& itemType = Item::items[key]; + const ItemType &itemType = Item::items[key]; - withdrawItemMessage << "Using " << mathItemCount << "x "<< itemType.name <<" from your supply stash. "; + withdrawItemMessage << "Using " << mathItemCount << "x " << itemType.name << " from your supply stash. "; withdrawItem(itemType.id, mathItemCount); } sendTextMessage(MESSAGE_STATUS, withdrawItemMessage.str()); - if (!protectionCharm && uniform_random(1, 100) > baseImbuement->percent) - { + if (!protectionCharm && uniform_random(1, 100) > baseImbuement->percent) { openImbuementWindow(item); sendImbuementResult("Oh no!\n\nThe imbuement has failed. You have lost the astral sources and gold you needed for the imbuement.\n\nNext time use a protection charm to better your chances."); openImbuementWindow(item); @@ -1314,27 +1251,24 @@ void Player::onApplyImbuement(Imbuement *imbuement, Item *item, uint8_t slot, bo openImbuementWindow(item); } -void Player::onClearImbuement(Item* item, uint8_t slot) -{ +void Player::onClearImbuement(Item* item, uint8_t slot) { if (!item) { return; } ImbuementInfo imbuementInfo; - if (!item->getImbuementInfo(slot, &imbuementInfo)) - { + if (!item->getImbuementInfo(slot, &imbuementInfo)) { SPDLOG_ERROR("[Player::onClearImbuement] - An error occurred while player with name {} try to apply imbuement, item not contains imbuement", this->getName()); this->sendImbuementResult("An error ocurred, please reopen imbuement window."); return; } - const BaseImbuement *baseImbuement = g_imbuements().getBaseByID(imbuementInfo.imbuement->getBaseID()); + const BaseImbuement* baseImbuement = g_imbuements().getBaseByID(imbuementInfo.imbuement->getBaseID()); if (!baseImbuement) { return; } - if (!g_game().removeMoney(this, baseImbuement->removeCost, 0, true)) - { + if (!g_game().removeMoney(this, baseImbuement->removeCost, 0, true)) { std::string message = fmt::format("You don't have {} gold coins.", baseImbuement->removeCost); SPDLOG_ERROR("[Player::onClearImbuement] - An error occurred while player with name {} try to apply imbuement, player do not have money", this->getName()); @@ -1351,15 +1285,13 @@ void Player::onClearImbuement(Item* item, uint8_t slot) this->openImbuementWindow(item); } -void Player::openImbuementWindow(Item* item) -{ +void Player::openImbuementWindow(Item* item) { if (!client || !item) { return; } if (item->getTopParent() != this) { - this->sendTextMessage(MESSAGE_FAILURE, - "You have to pick up the item to imbue it."); + this->sendTextMessage(MESSAGE_FAILURE, "You have to pick up the item to imbue it."); return; } @@ -1371,8 +1303,7 @@ void Player::openImbuementWindow(Item* item) client->openImbuementWindow(item); } -void Player::sendMarketEnter(uint32_t depotId) -{ +void Player::sendMarketEnter(uint32_t depotId) { if (!client || this->getLastDepotId() == -1 || !depotId) { return; } @@ -1380,9 +1311,8 @@ void Player::sendMarketEnter(uint32_t depotId) client->sendMarketEnter(depotId); } -//container -void Player::sendAddContainerItem(const Container* container, const Item* item) -{ +// container +void Player::sendAddContainerItem(const Container* container, const Item* item) { if (!client) { return; } @@ -1391,8 +1321,8 @@ void Player::sendAddContainerItem(const Container* container, const Item* item) return; } - for (const auto& it : openContainers) { - const OpenContainer& openContainer = it.second; + for (const auto &it : openContainers) { + const OpenContainer &openContainer = it.second; if (openContainer.container != container) { continue; } @@ -1414,14 +1344,13 @@ void Player::sendAddContainerItem(const Container* container, const Item* item) } } -void Player::sendUpdateContainerItem(const Container* container, uint16_t slot, const Item* newItem) -{ +void Player::sendUpdateContainerItem(const Container* container, uint16_t slot, const Item* newItem) { if (!client) { return; } - for (const auto& it : openContainers) { - const OpenContainer& openContainer = it.second; + for (const auto &it : openContainers) { + const OpenContainer &openContainer = it.second; if (openContainer.container != container) { continue; } @@ -1439,8 +1368,7 @@ void Player::sendUpdateContainerItem(const Container* container, uint16_t slot, } } -void Player::sendRemoveContainerItem(const Container* container, uint16_t slot) -{ +void Player::sendRemoveContainerItem(const Container* container, uint16_t slot) { if (!client) { return; } @@ -1449,13 +1377,13 @@ void Player::sendRemoveContainerItem(const Container* container, uint16_t slot) return; } - for (auto& it : openContainers) { - OpenContainer& openContainer = it.second; + for (auto &it : openContainers) { + OpenContainer &openContainer = it.second; if (openContainer.container != container) { continue; } - uint16_t& firstIndex = openContainer.index; + uint16_t &firstIndex = openContainer.index; if (firstIndex > 0 && firstIndex >= container->size() - 1) { firstIndex -= container->capacity(); sendContainer(it.first, container, false, firstIndex); @@ -1465,9 +1393,7 @@ void Player::sendRemoveContainerItem(const Container* container, uint16_t slot) } } -void Player::onUpdateTileItem(const Tile* updateTile, const Position& pos, const Item* oldItem, - const ItemType& oldType, const Item* newItem, const ItemType& newType) -{ +void Player::onUpdateTileItem(const Tile* updateTile, const Position &pos, const Item* oldItem, const ItemType &oldType, const Item* newItem, const ItemType &newType) { Creature::onUpdateTileItem(updateTile, pos, oldItem, oldType, newItem, newType); if (oldItem != newItem) { @@ -1481,9 +1407,7 @@ void Player::onUpdateTileItem(const Tile* updateTile, const Position& pos, const } } -void Player::onRemoveTileItem(const Tile* fromTile, const Position& pos, const ItemType& iType, - const Item* item) -{ +void Player::onRemoveTileItem(const Tile* fromTile, const Position &pos, const ItemType &iType, const Item* item) { Creature::onRemoveTileItem(fromTile, pos, iType, item); if (tradeState != TRADE_TRANSFER) { @@ -1497,11 +1421,10 @@ void Player::onRemoveTileItem(const Tile* fromTile, const Position& pos, const I } } - checkLootContainers(item); + checkLootContainers(item); } -void Player::onCreatureAppear(Creature* creature, bool isLogin) -{ +void Player::onCreatureAppear(Creature* creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); if (isLogin && creature == this) { @@ -1562,8 +1485,7 @@ void Player::onCreatureAppear(Creature* creature, bool isLogin) } } -void Player::onAttackedCreatureDisappear(bool isLogout) -{ +void Player::onAttackedCreatureDisappear(bool isLogout) { sendCancelTarget(); if (!isLogout) { @@ -1571,8 +1493,7 @@ void Player::onAttackedCreatureDisappear(bool isLogout) } } -void Player::onFollowCreatureDisappear(bool isLogout) -{ +void Player::onFollowCreatureDisappear(bool isLogout) { sendCancelTarget(); if (!isLogout) { @@ -1580,8 +1501,7 @@ void Player::onFollowCreatureDisappear(bool isLogout) } } -void Player::onChangeZone(ZoneType_t zone) -{ +void Player::onChangeZone(ZoneType_t zone) { if (zone == ZONE_PROTECTION) { if (attackedCreature && !hasFlag(PlayerFlags_t::IgnoreProtectionZone)) { setAttackedCreature(nullptr); @@ -1605,8 +1525,7 @@ void Player::onChangeZone(ZoneType_t zone) g_events().eventPlayerOnChangeZone(this, zone); } -void Player::onAttackedCreatureChangeZone(ZoneType_t zone) -{ +void Player::onAttackedCreatureChangeZone(ZoneType_t zone) { if (zone == ZONE_PROTECTION) { if (!hasFlag(PlayerFlags_t::IgnoreProtectionZone)) { setAttackedCreature(nullptr); @@ -1620,7 +1539,7 @@ void Player::onAttackedCreatureChangeZone(ZoneType_t zone) } } } else if (zone == ZONE_NORMAL && g_game().getWorldType() == WORLD_TYPE_NO_PVP) { - //attackedCreature can leave a pvp zone if not pzlocked + // attackedCreature can leave a pvp zone if not pzlocked if (attackedCreature->getPlayer()) { setAttackedCreature(nullptr); onAttackedCreatureDisappear(false); @@ -1628,8 +1547,7 @@ void Player::onAttackedCreatureChangeZone(ZoneType_t zone) } } -void Player::onRemoveCreature(Creature* creature, bool isLogout) -{ +void Player::onRemoveCreature(Creature* creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); if (creature == this) { @@ -1678,8 +1596,7 @@ void Player::onRemoveCreature(Creature* creature, bool isLogout) } } -bool Player::openShopWindow(Npc* npc) -{ +bool Player::openShopWindow(Npc* npc) { if (!npc) { SPDLOG_ERROR("[Player::openShopWindow] - Npc is wrong or nullptr"); return false; @@ -1694,8 +1611,7 @@ bool Player::openShopWindow(Npc* npc) return true; } -bool Player::closeShopWindow(bool sendCloseShopWindow /*= true*/) -{ +bool Player::closeShopWindow(bool sendCloseShopWindow /*= true*/) { if (!shopOwner) { return false; } @@ -1710,16 +1626,13 @@ bool Player::closeShopWindow(bool sendCloseShopWindow /*= true*/) return true; } -void Player::onWalk(Direction& dir) -{ +void Player::onWalk(Direction &dir) { Creature::onWalk(dir); setNextActionTask(nullptr); setNextAction(OTSYS_TIME() + getStepDuration(dir)); } -void Player::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport) -{ +void Player::onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) { Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); if (hasFollowPath && (creature == followCreature || (creature == this && followCreature))) { @@ -1732,7 +1645,7 @@ void Player::onCreatureMove(Creature* creature, const Tile* newTile, const Posit } if (tradeState != TRADE_TRANSFER) { - //check if we should close trade + // check if we should close trade if (tradeItem && !Position::areInRange<1, 1, 0>(tradeItem->getPosition(), getPosition())) { g_game().internalCloseTrade(this); } @@ -1774,14 +1687,12 @@ void Player::onCreatureMove(Creature* creature, const Tile* newTile, const Posit } } -//container -void Player::onAddContainerItem(const Item* item) -{ +// container +void Player::onAddContainerItem(const Item* item) { checkTradeState(item); } -void Player::onUpdateContainerItem(const Container* container, const Item* oldItem, const Item* newItem) -{ +void Player::onUpdateContainerItem(const Container* container, const Item* oldItem, const Item* newItem) { if (oldItem != newItem) { onRemoveContainerItem(container, oldItem); } @@ -1791,8 +1702,7 @@ void Player::onUpdateContainerItem(const Container* container, const Item* oldIt } } -void Player::onRemoveContainerItem(const Container* container, const Item* item) -{ +void Player::onRemoveContainerItem(const Container* container, const Item* item) { if (tradeState != TRADE_TRANSFER) { checkTradeState(item); @@ -1803,40 +1713,37 @@ void Player::onRemoveContainerItem(const Container* container, const Item* item) } } - checkLootContainers(item); + checkLootContainers(item); } -void Player::onCloseContainer(const Container* container) -{ +void Player::onCloseContainer(const Container* container) { if (!client) { return; } - for (const auto& it : openContainers) { + for (const auto &it : openContainers) { if (it.second.container == container) { client->sendCloseContainer(it.first); } } } -void Player::onSendContainer(const Container* container) -{ +void Player::onSendContainer(const Container* container) { if (!client) { return; } bool hasParent = container->hasParent(); - for (const auto& it : openContainers) { - const OpenContainer& openContainer = it.second; + for (const auto &it : openContainers) { + const OpenContainer &openContainer = it.second; if (openContainer.container == container) { client->sendContainer(it.first, container, hasParent, openContainer.index); } } } -//inventory -void Player::onUpdateInventoryItem(Item* oldItem, Item* newItem) -{ +// inventory +void Player::onUpdateInventoryItem(Item* oldItem, Item* newItem) { if (oldItem != newItem) { onRemoveInventoryItem(oldItem); } @@ -1846,8 +1753,7 @@ void Player::onUpdateInventoryItem(Item* oldItem, Item* newItem) } } -void Player::onRemoveInventoryItem(Item* item) -{ +void Player::onRemoveInventoryItem(Item* item) { if (tradeState != TRADE_TRANSFER) { checkTradeState(item); @@ -1859,11 +1765,10 @@ void Player::onRemoveInventoryItem(Item* item) } } - checkLootContainers(item); + checkLootContainers(item); } -void Player::checkTradeState(const Item* item) -{ +void Player::checkTradeState(const Item* item) { if (!tradeItem || tradeState == TRADE_TRANSFER) { return; } @@ -1883,8 +1788,7 @@ void Player::checkTradeState(const Item* item) } } -void Player::setNextWalkActionTask(SchedulerTask* task) -{ +void Player::setNextWalkActionTask(SchedulerTask* task) { if (walkTaskEvent != 0) { g_scheduler().stopEvent(walkTaskEvent); walkTaskEvent = 0; @@ -1894,8 +1798,7 @@ void Player::setNextWalkActionTask(SchedulerTask* task) walkTask = task; } -void Player::setNextWalkTask(SchedulerTask* task) -{ +void Player::setNextWalkTask(SchedulerTask* task) { if (nextStepEvent != 0) { g_scheduler().stopEvent(nextStepEvent); nextStepEvent = 0; @@ -1907,8 +1810,7 @@ void Player::setNextWalkTask(SchedulerTask* task) } } -void Player::setNextActionTask(SchedulerTask* task, bool resetIdleTime /*= true */) -{ +void Player::setNextActionTask(SchedulerTask* task, bool resetIdleTime /*= true */) { if (actionTaskEvent != 0) { g_scheduler().stopEvent(actionTaskEvent); actionTaskEvent = 0; @@ -1926,8 +1828,7 @@ void Player::setNextActionTask(SchedulerTask* task, bool resetIdleTime /*= true } } -void Player::setNextActionPushTask(SchedulerTask* task) -{ +void Player::setNextActionPushTask(SchedulerTask* task) { if (actionTaskEventPush != 0) { g_scheduler().stopEvent(actionTaskEventPush); actionTaskEventPush = 0; @@ -1938,8 +1839,7 @@ void Player::setNextActionPushTask(SchedulerTask* task) } } -void Player::setNextPotionActionTask(SchedulerTask* task) -{ +void Player::setNextPotionActionTask(SchedulerTask* task) { if (actionPotionTaskEvent != 0) { g_scheduler().stopEvent(actionPotionTaskEvent); actionPotionTaskEvent = 0; @@ -1949,31 +1849,27 @@ void Player::setNextPotionActionTask(SchedulerTask* task) if (task) { actionPotionTaskEvent = g_scheduler().addEvent(task); - //resetIdleTime(); + // resetIdleTime(); } } -uint32_t Player::getNextActionTime() const -{ +uint32_t Player::getNextActionTime() const { return std::max(SCHEDULER_MINTICKS, nextAction - OTSYS_TIME()); } -uint32_t Player::getNextPotionActionTime() const -{ +uint32_t Player::getNextPotionActionTime() const { return std::max(SCHEDULER_MINTICKS, nextPotionAction - OTSYS_TIME()); } -void Player::cancelPush() -{ - if (actionTaskEventPush != 0) { +void Player::cancelPush() { + if (actionTaskEventPush != 0) { g_scheduler().stopEvent(actionTaskEventPush); actionTaskEventPush = 0; inEventMovePush = false; } } -void Player::onThink(uint32_t interval) -{ +void Player::onThink(uint32_t interval) { Creature::onThink(interval); sendPing(); @@ -2009,8 +1905,7 @@ void Player::onThink(uint32_t interval) } } -uint32_t Player::isMuted() const -{ +uint32_t Player::isMuted() const { if (hasFlag(PlayerFlags_t::CannotBeMuted)) { return 0; } @@ -2024,15 +1919,13 @@ uint32_t Player::isMuted() const return static_cast(muteTicks) / 1000; } -void Player::addMessageBuffer() -{ +void Player::addMessageBuffer() { if (MessageBufferCount > 0 && g_configManager().getNumber(MAX_MESSAGEBUFFER) != 0 && !hasFlag(PlayerFlags_t::CannotBeMuted)) { --MessageBufferCount; } } -void Player::removeMessageBuffer() -{ +void Player::removeMessageBuffer() { if (hasFlag(PlayerFlags_t::CannotBeMuted)) { return; } @@ -2058,20 +1951,17 @@ void Player::removeMessageBuffer() } } -void Player::drainHealth(Creature* attacker, int32_t damage) -{ +void Player::drainHealth(Creature* attacker, int32_t damage) { Creature::drainHealth(attacker, damage); sendStats(); } -void Player::drainMana(Creature* attacker, int32_t manaLoss) -{ +void Player::drainMana(Creature* attacker, int32_t manaLoss) { Creature::drainMana(attacker, manaLoss); sendStats(); } -void Player::addManaSpent(uint64_t amount) -{ +void Player::addManaSpent(uint64_t amount) { if (hasFlag(PlayerFlags_t::NotGainMana)) { return; } @@ -2079,7 +1969,7 @@ void Player::addManaSpent(uint64_t amount) uint64_t currReqMana = vocation->getReqMana(magLevel); uint64_t nextReqMana = vocation->getReqMana(magLevel + 1); if (currReqMana >= nextReqMana) { - //player has reached max magic level + // player has reached max magic level return; } @@ -2128,13 +2018,12 @@ void Player::addManaSpent(uint64_t amount) } } -void Player::addExperience(Creature* target, uint64_t exp, bool sendText/* = false*/) -{ +void Player::addExperience(Creature* target, uint64_t exp, bool sendText /* = false*/) { uint64_t currLevelExp = Player::getExpForLevel(level); uint64_t nextLevelExp = Player::getExpForLevel(level + 1); uint64_t rawExp = exp; if (currLevelExp >= nextLevelExp) { - //player has reached max level + // player has reached max level levelPercent = 0; sendStats(); return; @@ -2190,7 +2079,7 @@ void Player::addExperience(Creature* target, uint64_t exp, bool sendText/* = fal currLevelExp = nextLevelExp; nextLevelExp = Player::getExpForLevel(level + 1); if (currLevelExp >= nextLevelExp) { - //player has reached max level + // player has reached max level break; } } @@ -2225,8 +2114,7 @@ void Player::addExperience(Creature* target, uint64_t exp, bool sendText/* = fal sendExperienceTracker(rawExp, exp); } -void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) -{ +void Player::removeExperience(uint64_t exp, bool sendText /* = false*/) { if (experience == 0 || exp == 0) { return; } @@ -2311,21 +2199,19 @@ void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) sendExperienceTracker(0, -static_cast(exp)); } -double_t Player::getPercentLevel(uint64_t count, uint64_t nextLevelCount) -{ +double_t Player::getPercentLevel(uint64_t count, uint64_t nextLevelCount) { if (nextLevelCount == 0) { return 0; } - double_t result = round( ((count * 100.) / nextLevelCount) * 100.) / 100.; + double_t result = round(((count * 100.) / nextLevelCount) * 100.) / 100.; if (result > 100) { return 0; } return result; } -void Player::onBlockHit() -{ +void Player::onBlockHit() { if (shieldBlockCount > 0) { --shieldBlockCount; @@ -2335,8 +2221,7 @@ void Player::onBlockHit() } } -void Player::onAttackedCreatureBlockHit(BlockType_t blockType) -{ +void Player::onAttackedCreatureBlockHit(BlockType_t blockType) { lastAttackBlockType = blockType; switch (blockType) { @@ -2349,7 +2234,7 @@ void Player::onAttackedCreatureBlockHit(BlockType_t blockType) case BLOCK_DEFENSE: case BLOCK_ARMOR: { - //need to draw blood every 30 hits + // need to draw blood every 30 hits if (bloodHitCount > 0) { addAttackSkillPoint = true; --bloodHitCount; @@ -2366,8 +2251,7 @@ void Player::onAttackedCreatureBlockHit(BlockType_t blockType) } } -bool Player::hasShield() const -{ +bool Player::hasShield() const { Item* item = inventory[CONST_SLOT_LEFT]; if (item && item->getWeaponType() == WEAPON_SHIELD) { return true; @@ -2380,9 +2264,7 @@ bool Player::hasShield() const return false; } -BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, - bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool field /* = false*/) -{ +BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_t &damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool field /* = false*/) { BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor, field); if (attacker) { @@ -2404,9 +2286,9 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ continue; } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.abilities) { - const int16_t& absorbPercent = it.abilities->absorbPercent[combatTypeToIndex(combatType)]; + const int16_t &absorbPercent = it.abilities->absorbPercent[combatTypeToIndex(combatType)]; auto charges = item->getAttribute(ItemAttribute_t::CHARGES); if (absorbPercent != 0) { damage -= std::round(damage * (absorbPercent / 100.)); @@ -2416,7 +2298,7 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ } if (field) { - const int16_t& fieldAbsorbPercent = it.abilities->fieldAbsorbPercent[combatTypeToIndex(combatType)]; + const int16_t &fieldAbsorbPercent = it.abilities->fieldAbsorbPercent[combatTypeToIndex(combatType)]; if (fieldAbsorbPercent != 0) { damage -= std::round(damage * (fieldAbsorbPercent / 100.)); if (charges != 0) { @@ -2425,7 +2307,7 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ } } if (attacker) { - const int16_t& reflectPercent = it.abilities->reflectPercent[combatTypeToIndex(combatType)]; + const int16_t &reflectPercent = it.abilities->reflectPercent[combatTypeToIndex(combatType)]; if (reflectPercent != 0) { CombatParams params; params.combatType = combatType; @@ -2441,21 +2323,18 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ } } - for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) - { + for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) { ImbuementInfo imbuementInfo; - if (!item->getImbuementInfo(slotid, &imbuementInfo)) - { + if (!item->getImbuementInfo(slotid, &imbuementInfo)) { continue; } - const int16_t& imbuementAbsorbPercent = imbuementInfo.imbuement->absorbPercent[combatTypeToIndex(combatType)]; + const int16_t &imbuementAbsorbPercent = imbuementInfo.imbuement->absorbPercent[combatTypeToIndex(combatType)]; if (imbuementAbsorbPercent != 0) { damage -= std::ceil(damage * (imbuementAbsorbPercent / 100.)); } } - } if (damage <= 0) { @@ -2466,8 +2345,7 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ return blockType; } -uint32_t Player::getIP() const -{ +uint32_t Player::getIP() const { if (client) { return client->getIP(); } @@ -2475,8 +2353,7 @@ uint32_t Player::getIP() const return 0; } -void Player::death(Creature* lastHitCreature) -{ +void Player::death(Creature* lastHitCreature) { loginPosition = town->getTemplePosition(); if (skillLoss) { @@ -2485,21 +2362,20 @@ void Player::death(Creature* lastHitCreature) int othersDmg = 0; uint32_t sumLevels = 0; uint32_t inFightTicks = 5 * 60 * 1000; - for (const auto& it : damageMap) { + for (const auto &it : damageMap) { CountBlock_t cb = it.second; if ((OTSYS_TIME() - cb.ticks) <= inFightTicks) { const Player* damageDealer = g_game().getPlayerByID(it.first); if (damageDealer) { playerDmg += cb.total; sumLevels += damageDealer->getLevel(); - } - else{ + } else { othersDmg += cb.total; } } } bool pvpDeath = false; - if (playerDmg > 0 || othersDmg > 0){ + if (playerDmg > 0 || othersDmg > 0) { pvpDeath = (Player::lastHitIsPlayer(lastHitCreature) || playerDmg / (playerDmg + static_cast(othersDmg)) >= 0.05); } if (pvpDeath && sumLevels > level) { @@ -2507,11 +2383,11 @@ void Player::death(Creature* lastHitCreature) unfairFightReduction = std::max(20, std::floor((reduce * 100) + 0.5)); } - //Magic level loss + // Magic level loss uint64_t sumMana = 0; uint64_t lostMana = 0; - //sum up all the mana + // sum up all the mana for (uint32_t i = 1; i <= magLevel; ++i) { sumMana += vocation->getReqMana(i); } @@ -2547,7 +2423,7 @@ void Player::death(Creature* lastHitCreature) magLevelPercent = 0; } - //Level loss + // Level loss uint64_t expLoss = static_cast(experience * deathLossPercent); g_events().eventPlayerOnLoseExperience(this, expLoss); @@ -2555,10 +2431,10 @@ void Player::death(Creature* lastHitCreature) std::ostringstream lostExp; lostExp << "You lost " << expLoss << " experience."; - //Skill loss - for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { //for each skill + // Skill loss + for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { // for each skill uint64_t sumSkillTries = 0; - for (uint16_t c = 11; c <= skills[i].level; ++c) { //sum up all required tries for all skill levels + for (uint16_t c = 11; c <= skills[i].level; ++c) { // sum up all required tries for all skill levels sumSkillTries += vocation->getReqSkillTries(i, c); } @@ -2632,10 +2508,10 @@ void Player::death(Creature* lastHitCreature) } sendTextMessage(MESSAGE_EVENT_ADVANCE, blesses.str()); - //Make player lose bless + // Make player lose bless uint8_t maxBlessing = 8; if (pvpDeath && hasBlessing(1)) { - removeBlessing(1, 1); //Remove TOF only + removeBlessing(1, 1); // Remove TOF only } else { for (int i = 2; i <= maxBlessing; i++) { removeBlessing(i, 1); @@ -2695,11 +2571,10 @@ void Player::death(Creature* lastHitCreature) despawn(); } -bool Player::spawn() -{ +bool Player::spawn() { setDead(false); - const Position& pos = getLoginPosition(); + const Position &pos = getLoginPosition(); if (!g_game().map.placeCreature(pos, this, false, true)) { return false; @@ -2725,8 +2600,7 @@ bool Player::spawn() return true; } -void Player::despawn() -{ +void Player::despawn() { if (isDead()) { return; } @@ -2773,15 +2647,14 @@ void Player::despawn() g_game().removePlayer(this); // show player as pending - for (const auto& [key, player] : g_game().getPlayers()) { + for (const auto &[key, player] : g_game().getPlayers()) { player->notifyStatusChange(this, VIPSTATUS_PENDING, false); } setDead(true); } -bool Player::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) -{ +bool Player::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { if (getZone() != ZONE_PVP || !Player::lastHitIsPlayer(lastHitCreature)) { return Creature::dropCorpse(lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } @@ -2790,8 +2663,7 @@ bool Player::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, return false; } -Item* Player::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) -{ +Item* Player::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) { Item* corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse && corpse->getContainer()) { std::ostringstream ss; @@ -2806,8 +2678,7 @@ Item* Player::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) return corpse; } -void Player::addInFightTicks(bool pzlock /*= false*/) -{ +void Player::addInFightTicks(bool pzlock /*= false*/) { if (hasFlag(PlayerFlags_t::NotGainInFight)) { return; } @@ -2821,26 +2692,23 @@ void Player::addInFightTicks(bool pzlock /*= false*/) addCondition(condition); } -void Player::removeList() -{ +void Player::removeList() { g_game().removePlayer(this); - for (const auto& [key, player] : g_game().getPlayers()) { + for (const auto &[key, player] : g_game().getPlayers()) { player->notifyStatusChange(this, VIPSTATUS_OFFLINE); } } -void Player::addList() -{ - for (const auto& [key, player] : g_game().getPlayers()) { +void Player::addList() { + for (const auto &[key, player] : g_game().getPlayers()) { player->notifyStatusChange(this, this->statusVipList); } g_game().addPlayer(this); } -void Player::removePlayer(bool displayEffect, bool forced /*= true*/) -{ +void Player::removePlayer(bool displayEffect, bool forced /*= true*/) { g_creatureEvents().playerLogout(this); if (client) { client->logout(displayEffect, forced); @@ -2849,8 +2717,7 @@ void Player::removePlayer(bool displayEffect, bool forced /*= true*/) } } -void Player::notifyStatusChange(Player* loginPlayer, VipStatus_t status, bool message) -{ +void Player::notifyStatusChange(Player* loginPlayer, VipStatus_t status, bool message) { if (!client) { return; } @@ -2871,8 +2738,7 @@ void Player::notifyStatusChange(Player* loginPlayer, VipStatus_t status, bool me } } -bool Player::removeVIP(uint32_t vipGuid) -{ +bool Player::removeVIP(uint32_t vipGuid) { if (VIPList.erase(vipGuid) == 0) { return false; } @@ -2881,8 +2747,7 @@ bool Player::removeVIP(uint32_t vipGuid) return true; } -bool Player::addVIP(uint32_t vipGuid, const std::string& vipName, VipStatus_t status) -{ +bool Player::addVIP(uint32_t vipGuid, const std::string &vipName, VipStatus_t status) { if (VIPList.size() >= getMaxVIPEntries() || VIPList.size() == 200) { // max number of buddies is 200 in 9.53 sendTextMessage(MESSAGE_FAILURE, "You cannot add more buddies."); return false; @@ -2901,8 +2766,7 @@ bool Player::addVIP(uint32_t vipGuid, const std::string& vipName, VipStatus_t st return true; } -bool Player::addVIPInternal(uint32_t vipGuid) -{ +bool Player::addVIPInternal(uint32_t vipGuid) { if (VIPList.size() >= getMaxVIPEntries() || VIPList.size() == 200) { // max number of buddies is 200 in 9.53 return false; } @@ -2910,8 +2774,7 @@ bool Player::addVIPInternal(uint32_t vipGuid) return VIPList.insert(vipGuid).second; } -bool Player::editVIP(uint32_t vipGuid, const std::string& description, uint32_t icon, bool notify) -{ +bool Player::editVIP(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify) { auto it = VIPList.find(vipGuid); if (it == VIPList.end()) { return false; // player is not in VIP @@ -2921,11 +2784,10 @@ bool Player::editVIP(uint32_t vipGuid, const std::string& description, uint32_t return true; } -//close container and its child containers -void Player::autoCloseContainers(const Container* container) -{ +// close container and its child containers +void Player::autoCloseContainers(const Container* container) { std::vector closeList; - for (const auto& it : openContainers) { + for (const auto &it : openContainers) { Container* tmpContainer = it.second.container; while (tmpContainer) { if (tmpContainer->isRemoved() || tmpContainer == container) { @@ -2945,8 +2807,7 @@ void Player::autoCloseContainers(const Container* container) } } -bool Player::hasCapacity(const Item* item, uint32_t count) const -{ +bool Player::hasCapacity(const Item* item, uint32_t count) const { if (hasFlag(PlayerFlags_t::CannotPickupItem)) { return false; } @@ -2962,8 +2823,7 @@ bool Player::hasCapacity(const Item* item, uint32_t count) const return itemWeight <= getFreeCapacity(); } -ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, uint32_t flags, Creature*) const -{ +ReturnValue Player::queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature*) const { const Item* item = thing.getItem(); if (item == nullptr) { SPDLOG_ERROR("[Player::queryAdd] - Item is nullptr"); @@ -2972,7 +2832,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); if (childIsOwner) { - //a child container is querying the player, just check if enough capacity + // a child container is querying the player, just check if enough capacity bool skipLimit = hasBitSet(FLAG_NOLIMIT, flags); if (skipLimit || hasCapacity(item, count)) { return RETURNVALUE_NOERROR; @@ -2986,11 +2846,8 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, ReturnValue ret = RETURNVALUE_NOERROR; - const int32_t& slotPosition = item->getSlotPosition(); - if ((slotPosition & SLOTP_HEAD) || (slotPosition & SLOTP_NECKLACE) || - (slotPosition & SLOTP_BACKPACK) || (slotPosition & SLOTP_ARMOR) || - (slotPosition & SLOTP_LEGS) || (slotPosition & SLOTP_FEET) || - (slotPosition & SLOTP_RING)) { + const int32_t &slotPosition = item->getSlotPosition(); + if ((slotPosition & SLOTP_HEAD) || (slotPosition & SLOTP_NECKLACE) || (slotPosition & SLOTP_BACKPACK) || (slotPosition & SLOTP_ARMOR) || (slotPosition & SLOTP_LEGS) || (slotPosition & SLOTP_FEET) || (slotPosition & SLOTP_RING)) { ret = RETURNVALUE_CANNOTBEDRESSED; } else if (slotPosition & SLOTP_TWO_HAND) { ret = RETURNVALUE_PUTTHISOBJECTINBOTHHANDS; @@ -3032,7 +2889,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, if (item->getWeaponType() != WEAPON_SHIELD && !item->isQuiver()) { ret = RETURNVALUE_CANNOTBEDRESSED; } else { - const Item *leftItem = inventory[CONST_SLOT_LEFT]; + const Item* leftItem = inventory[CONST_SLOT_LEFT]; if (leftItem) { if ((leftItem->getSlotPosition() | slotPosition) & SLOTP_TWO_HAND) { if (item->isQuiver() && leftItem->getWeaponType() == WEAPON_DISTANCE) @@ -3053,28 +2910,18 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, ret = RETURNVALUE_NOERROR; } } else if (inventory[CONST_SLOT_LEFT]) { - const Item *leftItem = inventory[CONST_SLOT_LEFT]; + const Item* leftItem = inventory[CONST_SLOT_LEFT]; WeaponType_t type = item->getWeaponType(), leftType = leftItem->getWeaponType(); - if (leftItem->getSlotPosition() & SLOTP_TWO_HAND) - { + if (leftItem->getSlotPosition() & SLOTP_TWO_HAND) { ret = RETURNVALUE_DROPTWOHANDEDITEM; - } - else if (item == leftItem && count == item->getItemCount()) - { + } else if (item == leftItem && count == item->getItemCount()) { ret = RETURNVALUE_NOERROR; - } - else if (leftType == WEAPON_SHIELD && type == WEAPON_SHIELD) - { + } else if (leftType == WEAPON_SHIELD && type == WEAPON_SHIELD) { ret = RETURNVALUE_CANONLYUSEONESHIELD; - } - else if (leftType == WEAPON_NONE || type == WEAPON_NONE || - leftType == WEAPON_SHIELD || leftType == WEAPON_AMMO || type == WEAPON_SHIELD || type == WEAPON_AMMO) - { + } else if (leftType == WEAPON_NONE || type == WEAPON_NONE || leftType == WEAPON_SHIELD || leftType == WEAPON_AMMO || type == WEAPON_SHIELD || type == WEAPON_AMMO) { ret = RETURNVALUE_NOERROR; - } - else - { + } else { ret = RETURNVALUE_CANONLYUSEONEWEAPON; } } else { @@ -3113,8 +2960,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, ret = RETURNVALUE_NOERROR; } else if (rightType == WEAPON_SHIELD && type == WEAPON_SHIELD) { ret = RETURNVALUE_CANONLYUSEONESHIELD; - } else if (rightType == WEAPON_NONE || type == WEAPON_NONE || - rightType == WEAPON_SHIELD || rightType == WEAPON_AMMO || type == WEAPON_SHIELD || type == WEAPON_AMMO) { + } else if (rightType == WEAPON_NONE || type == WEAPON_NONE || rightType == WEAPON_SHIELD || rightType == WEAPON_AMMO || type == WEAPON_SHIELD || type == WEAPON_AMMO) { ret = RETURNVALUE_NOERROR; } else { ret = RETURNVALUE_CANONLYUSEONEWEAPON; @@ -3164,18 +3010,18 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, } if (ret == RETURNVALUE_NOERROR || ret == RETURNVALUE_NOTENOUGHROOM) { - //need an exchange with source? + // need an exchange with source? const Item* inventoryItem = getInventoryItem(static_cast(index)); if (inventoryItem && (!inventoryItem->isStackable() || inventoryItem->getID() != item->getID())) { return RETURNVALUE_NEEDEXCHANGE; } - //check if enough capacity + // check if enough capacity if (!hasCapacity(item, count)) { return RETURNVALUE_NOTENOUGHCAPACITY; } - if (!g_moveEvents().onPlayerEquip(const_cast(*this), const_cast(*item), static_cast(index), true)) { + if (!g_moveEvents().onPlayerEquip(const_cast(*this), const_cast(*item), static_cast(index), true)) { return RETURNVALUE_CANNOTBEDRESSED; } } @@ -3183,9 +3029,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, return ret; } -ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t count, uint32_t& maxQueryCount, - uint32_t flags) const -{ +ReturnValue Player::queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const { const Item* item = thing.getItem(); if (item == nullptr) { maxQueryCount = 0; @@ -3202,7 +3046,7 @@ ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t co subContainer->queryMaxCount(INDEX_WHEREEVER, *item, item->getItemCount(), queryCount, flags); n += queryCount; - //iterate through all items, including sub-containers (deep search) + // iterate through all items, including sub-containers (deep search) for (ContainerIterator it = subContainer->iterator(); it.hasNext(); it.advance()) { if (Container* tmpContainer = (*it)->getContainer()) { queryCount = 0; @@ -3217,7 +3061,7 @@ ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t co n += remainder; } } - } else if (queryAdd(slotIndex, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { //empty slot + } else if (queryAdd(slotIndex, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { // empty slot if (item->isStackable()) { n += 100; } else { @@ -3241,7 +3085,7 @@ ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t co } else { maxQueryCount = 0; } - } else if (queryAdd(index, *item, count, flags) == RETURNVALUE_NOERROR) { //empty slot + } else if (queryAdd(index, *item, count, flags) == RETURNVALUE_NOERROR) { // empty slot if (item->isStackable()) { maxQueryCount = 100; } else { @@ -3259,8 +3103,7 @@ ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t co } } -ReturnValue Player::queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* /*= nullptr*/) const -{ +ReturnValue Player::queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* /*= nullptr*/) const { int32_t index = getThingIndex(&thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; @@ -3282,9 +3125,7 @@ ReturnValue Player::queryRemove(const Thing& thing, uint32_t count, uint32_t fla return RETURNVALUE_NOERROR; } -Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) -{ +Cylinder* Player::queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) { if (index == 0 /*drop to capacity window*/ || index == INDEX_WHEREEVER) { *destItem = nullptr; @@ -3310,7 +3151,7 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de } if (autoStack && isStackable) { - //try find an already existing item to stack with + // try find an already existing item to stack with if (queryAdd(slotIndex, *item, item->getItemCount(), 0) == RETURNVALUE_NOERROR) { if (inventoryItem->equals(item) && inventoryItem->getItemCount() < 100) { index = slotIndex; @@ -3325,7 +3166,7 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de } else if (Container* subContainer = inventoryItem->getContainer()) { containers.push_back(subContainer); } - } else if (queryAdd(slotIndex, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { //empty slot + } else if (queryAdd(slotIndex, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { // empty slot index = slotIndex; *destItem = nullptr; return this; @@ -3336,7 +3177,7 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de while (i < containers.size()) { Container* tmpContainer = containers[i++]; if (!autoStack || !isStackable) { - //we need to find first empty container as fast as we can for non-stackable items + // we need to find first empty container as fast as we can for non-stackable items uint32_t n = tmpContainer->capacity() - tmpContainer->size(); while (n) { if (tmpContainer->queryAdd(tmpContainer->capacity() - n, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { @@ -3368,7 +3209,7 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de continue; } - //try find an already existing item to stack with + // try find an already existing item to stack with if (tmpItem->equals(item) && tmpItem->getItemCount() < 100) { index = n; *destItem = tmpItem; @@ -3407,8 +3248,7 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de } } -void Player::addThing(int32_t index, Thing* thing) -{ +void Player::addThing(int32_t index, Thing* thing) { if (index < CONST_SLOT_FIRST || index > CONST_SLOT_LAST) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3421,12 +3261,11 @@ void Player::addThing(int32_t index, Thing* thing) item->setParent(this); inventory[index] = item; - //send to client + // send to client sendInventoryItem(static_cast(index), item); } -void Player::updateThing(Thing* thing, uint16_t itemId, uint32_t count) -{ +void Player::updateThing(Thing* thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -3440,15 +3279,14 @@ void Player::updateThing(Thing* thing, uint16_t itemId, uint32_t count) item->setID(itemId); item->setSubType(count); - //send to client + // send to client sendInventoryItem(static_cast(index), item); - //event methods + // event methods onUpdateInventoryItem(item, item); } -void Player::replaceThing(uint32_t index, Thing* thing) -{ +void Player::replaceThing(uint32_t index, Thing* thing) { if (index > CONST_SLOT_LAST) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3463,10 +3301,10 @@ void Player::replaceThing(uint32_t index, Thing* thing) return /*RETURNVALUE_NOTPOSSIBLE*/; } - //send to client + // send to client sendInventoryItem(static_cast(index), item); - //event methods + // event methods onUpdateInventoryItem(oldItem, item); item->setParent(this); @@ -3474,8 +3312,7 @@ void Player::replaceThing(uint32_t index, Thing* thing) inventory[index] = item; } -void Player::removeThing(Thing* thing, uint32_t count) -{ +void Player::removeThing(Thing* thing, uint32_t count) { Item* item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -3488,10 +3325,10 @@ void Player::removeThing(Thing* thing, uint32_t count) if (item->isStackable()) { if (count == item->getItemCount()) { - //send change to client + // send change to client sendInventoryItem(static_cast(index), nullptr); - //event methods + // event methods onRemoveInventoryItem(item); item->setParent(nullptr); @@ -3500,17 +3337,17 @@ void Player::removeThing(Thing* thing, uint32_t count) uint8_t newCount = static_cast(std::max(0, item->getItemCount() - count)); item->setItemCount(newCount); - //send change to client + // send change to client sendInventoryItem(static_cast(index), item); - //event methods + // event methods onUpdateInventoryItem(item, item); } } else { - //send change to client + // send change to client sendInventoryItem(static_cast(index), nullptr); - //event methods + // event methods onRemoveInventoryItem(item); item->setParent(nullptr); @@ -3518,8 +3355,7 @@ void Player::removeThing(Thing* thing, uint32_t count) } } -int32_t Player::getThingIndex(const Thing* thing) const -{ +int32_t Player::getThingIndex(const Thing* thing) const { for (uint8_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { if (inventory[i] == thing) { return i; @@ -3528,18 +3364,15 @@ int32_t Player::getThingIndex(const Thing* thing) const return -1; } -size_t Player::getFirstIndex() const -{ +size_t Player::getFirstIndex() const { return CONST_SLOT_FIRST; } -size_t Player::getLastIndex() const -{ +size_t Player::getLastIndex() const { return CONST_SLOT_LAST + 1; } -uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const -{ +uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const { uint32_t count = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { Item* item = inventory[i]; @@ -3562,8 +3395,7 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con return count; } -void Player::stashContainer(StashContainerList itemDict) -{ +void Player::stashContainer(StashContainerList itemDict) { StashItemList stashItemDict; // ItemID - Count for (auto it_dict : itemDict) { stashItemDict[(it_dict.first)->getID()] = it_dict.second; @@ -3614,8 +3446,7 @@ void Player::stashContainer(StashContainerList itemDict) } } -bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, bool ignoreEquipped/* = false*/, bool removeFromStash/* = false*/) -{ +bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, bool ignoreEquipped /* = false*/, bool removeFromStash /* = false*/) { if (amount == 0) { return true; } @@ -3661,7 +3492,7 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, if (count >= amount) { g_game().internalRemoveItems(std::move(itemList), amount, stackable); return true; - // If not, we will remove the amount the player have and save the rest to remove from the stash + // If not, we will remove the amount the player have and save the rest to remove from the stash } else if (removeFromStash && stackable) { g_game().internalRemoveItems(itemList, amount, stackable); // Save remaining items to remove @@ -3679,8 +3510,7 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, return false; } -ItemsTierCountList Player::getInventoryItemsId() const -{ +ItemsTierCountList Player::getInventoryItemsId() const { ItemsTierCountList itemMap; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { Item* item = inventory[i]; @@ -3699,8 +3529,7 @@ ItemsTierCountList Player::getInventoryItemsId() const return itemMap; } -std::vector Player::getInventoryItemsFromId(uint16_t itemId, bool ignore /*= true*/) const -{ +std::vector Player::getInventoryItemsFromId(uint16_t itemId, bool ignore /*= true*/) const { std::vector itemVector; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { Item* item = inventory[i]; @@ -3712,8 +3541,7 @@ std::vector Player::getInventoryItemsFromId(uint16_t itemId, bool ignore itemVector.push_back(item); } - if (Container* container = item->getContainer()) - { + if (Container* container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { auto containerItem = *it; if (containerItem->getID() == itemId) { @@ -3726,8 +3554,7 @@ std::vector Player::getInventoryItemsFromId(uint16_t itemId, bool ignore return itemVector; } -std::array Player::getFinalDamageReduction() const -{ +std::array Player::getFinalDamageReduction() const { std::array combatReductionArray; combatReductionArray.fill(0); calculateDamageReductionFromEquipedItems(combatReductionArray); @@ -3741,18 +3568,16 @@ std::array Player::getFinalDamageReduction() const return combatReductionArray; } -void Player::calculateDamageReductionFromEquipedItems(std::array &combatReductionArray) const -{ +void Player::calculateDamageReductionFromEquipedItems(std::array &combatReductionArray) const { for (uint8_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item *item = inventory[slot]; + Item* item = inventory[slot]; if (item) { calculateDamageReductionFromItem(combatReductionArray, item); } } } -void Player::calculateDamageReductionFromItem(std::array &combatReductionArray, Item *item) const -{ +void Player::calculateDamageReductionFromItem(std::array &combatReductionArray, Item* item) const { for (uint16_t combatTypeIndex = 0; combatTypeIndex < COMBAT_COUNT; combatTypeIndex++) { updateDamageReductionFromItemImbuement(combatReductionArray, item, combatTypeIndex); updateDamageReductionFromItemAbility(combatReductionArray, item, combatTypeIndex); @@ -3760,9 +3585,8 @@ void Player::calculateDamageReductionFromItem(std::array } void Player::updateDamageReductionFromItemImbuement( - std::array &combatReductionArray, Item *item, uint16_t combatTypeIndex -) const -{ + std::array &combatReductionArray, Item* item, uint16_t combatTypeIndex +) const { for (uint8_t imbueSlotId = 0; imbueSlotId < item->getImbuementSlot(); imbueSlotId++) { ImbuementInfo imbuementInfo; if (item->getImbuementInfo(imbueSlotId, &imbuementInfo) && imbuementInfo.imbuement) { @@ -3775,9 +3599,8 @@ void Player::updateDamageReductionFromItemImbuement( } void Player::updateDamageReductionFromItemAbility( - std::array &combatReductionArray, const Item *item, uint16_t combatTypeIndex -) const -{ + std::array &combatReductionArray, const Item* item, uint16_t combatTypeIndex +) const { if (!item) { return; } @@ -3791,13 +3614,11 @@ void Player::updateDamageReductionFromItemAbility( } } -double_t Player::calculateDamageReduction(double_t currentTotal, int16_t resistance) const -{ +double_t Player::calculateDamageReduction(double_t currentTotal, int16_t resistance) const { return (100 - currentTotal) / 100.0 * resistance + currentTotal; } -std::vector Player::getAllInventoryItems(bool ignoreEquiped /*= false*/) const -{ +std::vector Player::getAllInventoryItems(bool ignoreEquiped /*= false*/) const { std::vector itemVector; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { Item* item = inventory[i]; @@ -3809,8 +3630,7 @@ std::vector Player::getAllInventoryItems(bool ignoreEquiped /*= false*/) if (!ignoreEquiped) { itemVector.push_back(item); } - if (Container* container = item->getContainer()) - { + if (Container* container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { itemVector.push_back(*it); } @@ -3820,16 +3640,14 @@ std::vector Player::getAllInventoryItems(bool ignoreEquiped /*= false*/) return itemVector; } -std::map& Player::getAllItemTypeCount(std::map& countMap) const -{ +std::map &Player::getAllItemTypeCount(std::map &countMap) const { for (const auto item : getAllInventoryItems()) { countMap[static_cast(item->getID())] += Item::countByType(item, -1); } return countMap; } -std::map& Player::getAllSaleItemIdAndCount(std::map &countMap) const -{ +std::map &Player::getAllSaleItemIdAndCount(std::map &countMap) const { for (const auto item : getAllInventoryItems()) { if (item->getTier() > 0) { continue; @@ -3843,8 +3661,7 @@ std::map& Player::getAllSaleItemIdAndCount(std::map& countMap) const -{ +void Player::getAllItemTypeCountAndSubtype(std::map &countMap) const { for (const auto item : getAllInventoryItems()) { uint16_t itemId = item->getID(); if (Item::items[itemId].isFluidContainer()) { @@ -3855,8 +3672,7 @@ void Player::getAllItemTypeCountAndSubtype(std::map& countMa } } -Item* Player::getForgeItemFromId(uint16_t itemId, uint8_t tier) -{ +Item* Player::getForgeItemFromId(uint16_t itemId, uint8_t tier) { for (auto item : getAllInventoryItems(true)) { if (item->hasImbuements()) { continue; @@ -3870,18 +3686,16 @@ Item* Player::getForgeItemFromId(uint16_t itemId, uint8_t tier) return nullptr; } -Thing* Player::getThing(size_t index) const -{ +Thing* Player::getThing(size_t index) const { if (index >= CONST_SLOT_FIRST && index <= CONST_SLOT_LAST) { return inventory[index]; } return nullptr; } -void Player::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) -{ +void Player::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { if (link == LINK_OWNER) { - //calling movement scripts + // calling movement scripts g_moveEvents().onPlayerEquip(*this, *thing->getItem(), static_cast(index), false); } @@ -3916,10 +3730,10 @@ void Player::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_ } } else if (const Creature* creature = thing->getCreature()) { if (creature == this) { - //check containers + // check containers std::vector containers; - for (const auto& it : openContainers) { + for (const auto &it : openContainers) { Container* container = it.second.container; if (container == nullptr) { continue; @@ -3937,10 +3751,9 @@ void Player::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_ } } -void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) -{ +void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { if (link == LINK_OWNER) { - //calling movement scripts + // calling movement scripts g_moveEvents().onPlayerDeEquip(*this, *thing->getItem(), static_cast(index)); } @@ -3977,7 +3790,7 @@ void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int if (const DepotChest* depotChest = dynamic_cast(topContainer)) { bool isOwner = false; - for (const auto& it : depotChests) { + for (const auto &it : depotChests) { if (it.second == depotChest) { isOwner = true; it.second->stopDecaying(); @@ -4003,8 +3816,7 @@ void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int } // i will keep this function so it can be reviewed -bool Player::updateSaleShopList(const Item* item) -{ +bool Player::updateSaleShopList(const Item* item) { uint16_t itemId = item->getID(); if (!itemId || !item) return true; @@ -4014,32 +3826,29 @@ bool Player::updateSaleShopList(const Item* item) return true; } -bool Player::hasShopItemForSale(uint16_t itemId, uint8_t subType) const -{ +bool Player::hasShopItemForSale(uint16_t itemId, uint8_t subType) const { if (!shopOwner) { return false; } - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; std::vector shoplist = shopOwner->getShopItemVector(); - return std::any_of(shoplist.begin(), shoplist.end(), [&](const ShopBlock& shopBlock) { + return std::any_of(shoplist.begin(), shoplist.end(), [&](const ShopBlock &shopBlock) { return shopBlock.itemId == itemId && shopBlock.itemBuyPrice != 0 && (!itemType.isFluidContainer() || shopBlock.itemSubType == subType); }); } -void Player::internalAddThing(Thing* thing) -{ +void Player::internalAddThing(Thing* thing) { internalAddThing(0, thing); } -void Player::internalAddThing(uint32_t index, Thing* thing) -{ +void Player::internalAddThing(uint32_t index, Thing* thing) { Item* item = thing->getItem(); if (!item) { return; } - //index == 0 means we should equip this item at the most appropiate slot (no action required here) + // index == 0 means we should equip this item at the most appropiate slot (no action required here) if (index >= CONST_SLOT_FIRST && index <= CONST_SLOT_LAST) { if (inventory[index]) { return; @@ -4050,8 +3859,7 @@ void Player::internalAddThing(uint32_t index, Thing* thing) } } -bool Player::setFollowCreature(Creature* creature) -{ +bool Player::setFollowCreature(Creature* creature) { if (!Creature::setFollowCreature(creature)) { setFollowCreature(nullptr); setAttackedCreature(nullptr); @@ -4064,8 +3872,7 @@ bool Player::setFollowCreature(Creature* creature) return true; } -bool Player::setAttackedCreature(Creature* creature) -{ +bool Player::setAttackedCreature(Creature* creature) { if (!Creature::setAttackedCreature(creature)) { sendCancelTarget(); return false; @@ -4073,7 +3880,7 @@ bool Player::setAttackedCreature(Creature* creature) if (chaseMode && creature) { if (followCreature != creature) { - //chase opponent + // chase opponent setFollowCreature(creature); } } else if (followCreature) { @@ -4086,8 +3893,7 @@ bool Player::setAttackedCreature(Creature* creature) return true; } -void Player::goToFollowCreature() -{ +void Player::goToFollowCreature() { if (!walkTask) { if ((OTSYS_TIME() - lastFailedFollow) < 2000) { return; @@ -4101,14 +3907,12 @@ void Player::goToFollowCreature() } } -void Player::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const -{ +void Player::getPathSearchParams(const Creature* creature, FindPathParams &fpp) const { Creature::getPathSearchParams(creature, fpp); fpp.fullPathSearch = true; } -void Player::doAttacking(uint32_t) -{ +void Player::doAttacking(uint32_t) { if (lastAttack == 0) { lastAttack = OTSYS_TIME() - getAttackSpeed() - 1; } @@ -4152,8 +3956,7 @@ void Player::doAttacking(uint32_t) } } -uint64_t Player::getGainedExperience(Creature* attacker) const -{ +uint64_t Player::getGainedExperience(Creature* attacker) const { if (g_configManager().getBoolean(EXPERIENCE_FROM_PLAYERS)) { Player* attackerPlayer = attacker->getPlayer(); if (attackerPlayer && attackerPlayer != this && skillLoss && std::abs(static_cast(attackerPlayer->getLevel() - level)) <= g_configManager().getNumber(EXP_FROM_PLAYERS_LEVEL_RANGE)) { @@ -4163,22 +3966,20 @@ uint64_t Player::getGainedExperience(Creature* attacker) const return 0; } -void Player::onFollowCreature(const Creature* creature) -{ +void Player::onFollowCreature(const Creature* creature) { if (!creature) { stopWalk(); } } -void Player::setChaseMode(bool mode) -{ +void Player::setChaseMode(bool mode) { bool prevChaseMode = chaseMode; chaseMode = mode; if (prevChaseMode != chaseMode) { if (chaseMode) { if (!followCreature && attackedCreature) { - //chase opponent + // chase opponent setFollowCreature(attackedCreature); } } else if (attackedCreature) { @@ -4188,35 +3989,30 @@ void Player::setChaseMode(bool mode) } } -void Player::onWalkAborted() -{ +void Player::onWalkAborted() { setNextWalkActionTask(nullptr); sendCancelWalk(); } -void Player::onWalkComplete() -{ +void Player::onWalkComplete() { if (walkTask) { walkTaskEvent = g_scheduler().addEvent(walkTask); walkTask = nullptr; } } -void Player::stopWalk() -{ +void Player::stopWalk() { cancelNextWalk = true; } -LightInfo Player::getCreatureLight() const -{ +LightInfo Player::getCreatureLight() const { if (internalLight.level > itemsLight.level) { return internalLight; } return itemsLight; } -void Player::updateItemsLight(bool internal /*=false*/) -{ +void Player::updateItemsLight(bool internal /*=false*/) { LightInfo maxLight; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { @@ -4239,8 +4035,7 @@ void Player::updateItemsLight(bool internal /*=false*/) } } -void Player::onAddCondition(ConditionType_t type) -{ +void Player::onAddCondition(ConditionType_t type) { Creature::onAddCondition(type); if (type == CONDITION_OUTFIT && isMounted()) { @@ -4250,8 +4045,7 @@ void Player::onAddCondition(ConditionType_t type) sendIcons(); } -void Player::onAddCombatCondition(ConditionType_t type) -{ +void Player::onAddCombatCondition(ConditionType_t type) { switch (type) { case CONDITION_POISON: sendTextMessage(MESSAGE_FAILURE, "You are poisoned."); @@ -4294,8 +4088,7 @@ void Player::onAddCombatCondition(ConditionType_t type) } } -void Player::onEndCondition(ConditionType_t type) -{ +void Player::onEndCondition(ConditionType_t type) { Creature::onEndCondition(type); if (type == CONDITION_INFIGHT) { @@ -4311,15 +4104,14 @@ void Player::onEndCondition(ConditionType_t type) sendIcons(); } -void Player::onCombatRemoveCondition(Condition* condition) -{ - //Creature::onCombatRemoveCondition(condition); +void Player::onCombatRemoveCondition(Condition* condition) { + // Creature::onCombatRemoveCondition(condition); if (condition->getId() > 0) { - //Means the condition is from an item, id == slot + // Means the condition is from an item, id == slot if (g_game().getWorldType() == WORLD_TYPE_PVP_ENFORCED) { Item* item = getInventoryItem(static_cast(condition->getId())); if (item) { - //25% chance to destroy the item + // 25% chance to destroy the item if (25 >= uniform_random(1, 100)) { g_game().internalRemoveItem(item); } @@ -4340,8 +4132,7 @@ void Player::onCombatRemoveCondition(Condition* condition) } } -void Player::onAttackedCreature(Creature* target) -{ +void Player::onAttackedCreature(Creature* target) { Creature::onAttackedCreature(target); if (target->getZone() == ZONE_PVP) { @@ -4390,15 +4181,13 @@ void Player::onAttackedCreature(Creature* target) addInFightTicks(); } -void Player::onAttacked() -{ +void Player::onAttacked() { Creature::onAttacked(); addInFightTicks(); } -void Player::onIdleStatus() -{ +void Player::onIdleStatus() { Creature::onIdleStatus(); if (party) { @@ -4406,9 +4195,8 @@ void Player::onIdleStatus() } } -void Player::onPlacedCreature() -{ - //scripting event - onLogin +void Player::onPlacedCreature() { + // scripting event - onLogin if (!g_creatureEvents().playerLogin(this)) { removePlayer(true); } @@ -4416,23 +4204,21 @@ void Player::onPlacedCreature() sendUnjustifiedPoints(); } -void Player::onAttackedCreatureDrainHealth(Creature* target, int32_t points) -{ +void Player::onAttackedCreatureDrainHealth(Creature* target, int32_t points) { Creature::onAttackedCreatureDrainHealth(target, points); if (target) { if (party && !Combat::isPlayerCombat(target)) { Monster* tmpMonster = target->getMonster(); if (tmpMonster && tmpMonster->isHostile()) { - //We have fulfilled a requirement for shared experience + // We have fulfilled a requirement for shared experience party->updatePlayerTicks(this, points); } } } } -void Player::onTargetCreatureGainHealth(Creature* target, int32_t points) -{ +void Player::onTargetCreatureGainHealth(Creature* target, int32_t points) { if (target && party) { Player* tmpPlayer = nullptr; @@ -4450,8 +4236,7 @@ void Player::onTargetCreatureGainHealth(Creature* target, int32_t points) } } -bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) -{ +bool Player::onKilledCreature(Creature* target, bool lastHit /* = true*/) { bool unjustified = false; if (hasFlag(PlayerFlags_t::NotGenerateLoot)) { @@ -4467,7 +4252,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) } else if (!hasFlag(PlayerFlags_t::NotGainInFight) && !isPartner(targetPlayer)) { if (!Combat::isInPvpZone(this, targetPlayer) && hasAttacked(targetPlayer) && !targetPlayer->hasAttacked(this) && !isGuildMate(targetPlayer) && targetPlayer != this) { if (targetPlayer->hasKilled(this)) { - for (auto& kill : targetPlayer->unjustifiedKills) { + for (auto &kill : targetPlayer->unjustifiedKills) { if (kill.target == getGUID() && kill.unavenged) { kill.unavenged = false; auto it = attackedSet.find(targetPlayer->guid); @@ -4498,9 +4283,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) // If the player is not in a party and sharing exp active and enabled // And it's not the player killing the creature, then we ignore everything else auto damageParty = damagePlayer->getParty(); - if (this->getID() != damagePlayer->getID() && - (!damageParty || !damageParty->isSharedExperienceActive() || !damageParty->isSharedExperienceEnabled())) - { + if (this->getID() != damagePlayer->getID() && (!damageParty || !damageParty->isSharedExperienceActive() || !damageParty->isSharedExperienceEnabled())) { continue; } @@ -4511,8 +4294,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) if (const TaskHuntingOption* option = g_ioprey().GetTaskRewardOption(taskSlot)) { taskSlot->currentKills += 1; - if ((taskSlot->upgrade && taskSlot->currentKills >= option->secondKills) || - (!taskSlot->upgrade && taskSlot->currentKills >= option->firstKills)) { + if ((taskSlot->upgrade && taskSlot->currentKills >= option->secondKills) || (!taskSlot->upgrade && taskSlot->currentKills >= option->firstKills)) { taskSlot->state = PreyTaskDataState_Completed; std::string message = "You succesfully finished your hunting task. Your reward is ready to be claimed!"; damagePlayer->sendTextMessage(MESSAGE_STATUS, message); @@ -4525,8 +4307,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) return unjustified; } -void Player::gainExperience(uint64_t gainExp, Creature* target) -{ +void Player::gainExperience(uint64_t gainExp, Creature* target) { if (hasFlag(PlayerFlags_t::NotGainExperience) || gainExp == 0 || staminaMinutes == 0) { return; } @@ -4534,15 +4315,14 @@ void Player::gainExperience(uint64_t gainExp, Creature* target) addExperience(target, gainExp, true); } -void Player::onGainExperience(uint64_t gainExp, Creature* target) -{ +void Player::onGainExperience(uint64_t gainExp, Creature* target) { if (hasFlag(PlayerFlags_t::NotGainExperience)) { return; } if (target && !target->getPlayer() && party && party->isSharedExperienceActive() && party->isSharedExperienceEnabled()) { party->shareExperience(gainExp, target); - //We will get a share of the experience through the sharing mechanism + // We will get a share of the experience through the sharing mechanism return; } @@ -4550,34 +4330,29 @@ void Player::onGainExperience(uint64_t gainExp, Creature* target) gainExperience(gainExp, target); } -void Player::onGainSharedExperience(uint64_t gainExp, Creature* target) -{ +void Player::onGainSharedExperience(uint64_t gainExp, Creature* target) { gainExperience(gainExp, target); } -bool Player::isImmune(CombatType_t type) const -{ +bool Player::isImmune(CombatType_t type) const { if (hasFlag(PlayerFlags_t::CannotBeAttacked)) { return true; } return Creature::isImmune(type); } -bool Player::isImmune(ConditionType_t type) const -{ +bool Player::isImmune(ConditionType_t type) const { if (hasFlag(PlayerFlags_t::CannotBeAttacked)) { return true; } return Creature::isImmune(type); } -bool Player::isAttackable() const -{ +bool Player::isAttackable() const { return !hasFlag(PlayerFlags_t::CannotBeAttacked); } -bool Player::lastHitIsPlayer(Creature* lastHitCreature) -{ +bool Player::lastHitIsPlayer(Creature* lastHitCreature) { if (!lastHitCreature) { return false; } @@ -4590,14 +4365,12 @@ bool Player::lastHitIsPlayer(Creature* lastHitCreature) return lastHitMaster && lastHitMaster->getPlayer(); } -void Player::changeHealth(int32_t healthChange, bool sendHealthChange/* = true*/) -{ +void Player::changeHealth(int32_t healthChange, bool sendHealthChange /* = true*/) { Creature::changeHealth(healthChange, sendHealthChange); sendStats(); } -void Player::changeMana(int32_t manaChange) -{ +void Player::changeMana(int32_t manaChange) { if (!hasFlag(PlayerFlags_t::HasInfiniteMana)) { Creature::changeMana(manaChange); } @@ -4605,8 +4378,7 @@ void Player::changeMana(int32_t manaChange) sendStats(); } -void Player::changeSoul(int32_t soulChange) -{ +void Player::changeSoul(int32_t soulChange) { if (soulChange > 0) { soul += std::min(soulChange * g_configManager().getFloat(RATE_SOUL_REGEN), vocation->getSoulMax() - soul); } else { @@ -4616,8 +4388,7 @@ void Player::changeSoul(int32_t soulChange) sendStats(); } -bool Player::canWear(uint16_t lookType, uint8_t addons) const -{ +bool Player::canWear(uint16_t lookType, uint8_t addons) const { if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { SPDLOG_WARN("[Player::canWear] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", lookType); return false; @@ -4640,7 +4411,7 @@ bool Player::canWear(uint16_t lookType, uint8_t addons) const return true; } - for (const OutfitEntry& outfitEntry : outfits) { + for (const OutfitEntry &outfitEntry : outfits) { if (outfitEntry.lookType != lookType) { continue; } @@ -4649,8 +4420,7 @@ bool Player::canWear(uint16_t lookType, uint8_t addons) const return false; } -bool Player::canLogout() -{ +bool Player::canLogout() { if (isConnecting) { return false; } @@ -4666,23 +4436,21 @@ bool Player::canLogout() return !isPzLocked() && !hasCondition(CONDITION_INFIGHT); } -void Player::genReservedStorageRange() -{ +void Player::genReservedStorageRange() { // generate outfits range uint32_t outfits_key = PSTRG_OUTFITS_RANGE_START; - for (const OutfitEntry& entry : outfits) { + for (const OutfitEntry &entry : outfits) { storageMap[++outfits_key] = (entry.lookType << 16) | entry.addons; } // generate familiars range uint32_t familiar_key = PSTRG_FAMILIARS_RANGE_START; - for (const FamiliarEntry& entry : familiars) { + for (const FamiliarEntry &entry : familiars) { storageMap[++familiar_key] = (entry.lookType << 16); } } -void Player::addOutfit(uint16_t lookType, uint8_t addons) -{ - for (OutfitEntry& outfitEntry : outfits) { +void Player::addOutfit(uint16_t lookType, uint8_t addons) { + for (OutfitEntry &outfitEntry : outfits) { if (outfitEntry.lookType == lookType) { outfitEntry.addons |= addons; return; @@ -4691,10 +4459,9 @@ void Player::addOutfit(uint16_t lookType, uint8_t addons) outfits.emplace_back(lookType, addons); } -bool Player::removeOutfit(uint16_t lookType) -{ +bool Player::removeOutfit(uint16_t lookType) { for (auto it = outfits.begin(), end = outfits.end(); it != end; ++it) { - OutfitEntry& entry = *it; + OutfitEntry &entry = *it; if (entry.lookType == lookType) { outfits.erase(it); return true; @@ -4703,9 +4470,8 @@ bool Player::removeOutfit(uint16_t lookType) return false; } -bool Player::removeOutfitAddon(uint16_t lookType, uint8_t addons) -{ - for (OutfitEntry& outfitEntry : outfits) { +bool Player::removeOutfitAddon(uint16_t lookType, uint8_t addons) { + for (OutfitEntry &outfitEntry : outfits) { if (outfitEntry.lookType == lookType) { outfitEntry.addons &= ~addons; return true; @@ -4714,8 +4480,7 @@ bool Player::removeOutfitAddon(uint16_t lookType, uint8_t addons) return false; } -bool Player::getOutfitAddons(const Outfit& outfit, uint8_t& addons) const -{ +bool Player::getOutfitAddons(const Outfit &outfit, uint8_t &addons) const { if (group->access) { addons = 3; return true; @@ -4725,7 +4490,7 @@ bool Player::getOutfitAddons(const Outfit& outfit, uint8_t& addons) const return false; } - for (const OutfitEntry& outfitEntry : outfits) { + for (const OutfitEntry &outfitEntry : outfits) { if (outfitEntry.lookType != outfit.lookType) { continue; } @@ -4760,7 +4525,7 @@ bool Player::canFamiliar(uint16_t lookType) const { return true; } - for (const FamiliarEntry& familiarEntry : familiars) { + for (const FamiliarEntry &familiarEntry : familiars) { if (familiarEntry.lookType != lookType) { continue; } @@ -4769,7 +4534,7 @@ bool Player::canFamiliar(uint16_t lookType) const { } void Player::addFamiliar(uint16_t lookType) { - for (FamiliarEntry& familiarEntry : familiars) { + for (FamiliarEntry &familiarEntry : familiars) { if (familiarEntry.lookType == lookType) { return; } @@ -4779,7 +4544,7 @@ void Player::addFamiliar(uint16_t lookType) { bool Player::removeFamiliar(uint16_t lookType) { for (auto it = familiars.begin(), end = familiars.end(); it != end; ++it) { - FamiliarEntry& entry = *it; + FamiliarEntry &entry = *it; if (entry.lookType == lookType) { familiars.erase(it); return true; @@ -4788,7 +4553,7 @@ bool Player::removeFamiliar(uint16_t lookType) { return false; } -bool Player::getFamiliar(const Familiar& familiar) const { +bool Player::getFamiliar(const Familiar &familiar) const { if (group->access) { return true; } @@ -4797,7 +4562,7 @@ bool Player::getFamiliar(const Familiar& familiar) const { return false; } - for (const FamiliarEntry& familiarEntry : familiars) { + for (const FamiliarEntry &familiarEntry : familiars) { if (familiarEntry.lookType != familiar.lookType) { continue; } @@ -4812,21 +4577,18 @@ bool Player::getFamiliar(const Familiar& familiar) const { return true; } -void Player::setSex(PlayerSex_t newSex) -{ +void Player::setSex(PlayerSex_t newSex) { sex = newSex; } -Skulls_t Player::getSkull() const -{ +Skulls_t Player::getSkull() const { if (hasFlag(PlayerFlags_t::NotGainInFight)) { return SKULL_NONE; } return skull; } -Skulls_t Player::getSkullClient(const Creature* creature) const -{ +Skulls_t Player::getSkullClient(const Creature* creature) const { if (!creature || g_game().getWorldType() != WORLD_TYPE_PVP) { return SKULL_NONE; } @@ -4834,7 +4596,7 @@ Skulls_t Player::getSkullClient(const Creature* creature) const const Player* player = creature->getPlayer(); if (player && player->getSkull() == SKULL_NONE) { if (player == this) { - for (const auto& kill : unjustifiedKills) { + for (const auto &kill : unjustifiedKills) { if (kill.unavenged && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION) * 24 * 60 * 60) { return SKULL_ORANGE; } @@ -4856,9 +4618,8 @@ Skulls_t Player::getSkullClient(const Creature* creature) const return Creature::getSkullClient(creature); } -bool Player::hasKilled(const Player* player) const -{ - for (const auto& kill : unjustifiedKills) { +bool Player::hasKilled(const Player* player) const { + for (const auto &kill : unjustifiedKills) { if (kill.target == player->getGUID() && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION) * 24 * 60 * 60 && kill.unavenged) { return true; } @@ -4867,8 +4628,7 @@ bool Player::hasKilled(const Player* player) const return false; } -bool Player::hasAttacked(const Player* attacked) const -{ +bool Player::hasAttacked(const Player* attacked) const { if (hasFlag(PlayerFlags_t::NotGainInFight) || !attacked) { return false; } @@ -4876,8 +4636,7 @@ bool Player::hasAttacked(const Player* attacked) const return attackedSet.find(attacked->guid) != attackedSet.end(); } -void Player::addAttacked(const Player* attacked) -{ +void Player::addAttacked(const Player* attacked) { if (hasFlag(PlayerFlags_t::NotGainInFight) || !attacked || attacked == this) { return; } @@ -4885,8 +4644,7 @@ void Player::addAttacked(const Player* attacked) attackedSet.insert(attacked->guid); } -void Player::removeAttacked(const Player* attacked) -{ +void Player::removeAttacked(const Player* attacked) { if (!attacked || attacked == this) { return; } @@ -4897,13 +4655,11 @@ void Player::removeAttacked(const Player* attacked) } } -void Player::clearAttacked() -{ +void Player::clearAttacked() { attackedSet.clear(); } -void Player::addUnjustifiedDead(const Player* attacked) -{ +void Player::addUnjustifiedDead(const Player* attacked) { if (hasFlag(PlayerFlags_t::NotGainInFight) || attacked == this || g_game().getWorldType() == WORLD_TYPE_PVP_ENFORCED) { return; } @@ -4916,7 +4672,7 @@ void Player::addUnjustifiedDead(const Player* attacked) uint8_t weekKills = 0; uint8_t monthKills = 0; - for (const auto& kill : unjustifiedKills) { + for (const auto &kill : unjustifiedKills) { const auto diff = time(nullptr) - kill.time; if (diff <= 4 * 60 * 60) { dayKills += 1; @@ -4932,11 +4688,11 @@ void Player::addUnjustifiedDead(const Player* attacked) if (getSkull() != SKULL_BLACK) { if (dayKills >= 2 * g_configManager().getNumber(DAY_KILLS_TO_RED) || weekKills >= 2 * g_configManager().getNumber(WEEK_KILLS_TO_RED) || monthKills >= 2 * g_configManager().getNumber(MONTH_KILLS_TO_RED)) { setSkull(SKULL_BLACK); - //start black skull time + // start black skull time skullTicks = static_cast(g_configManager().getNumber(BLACK_SKULL_DURATION)) * 24 * 60 * 60; } else if (dayKills >= g_configManager().getNumber(DAY_KILLS_TO_RED) || weekKills >= g_configManager().getNumber(WEEK_KILLS_TO_RED) || monthKills >= g_configManager().getNumber(MONTH_KILLS_TO_RED)) { setSkull(SKULL_RED); - //reset red skull time + // reset red skull time skullTicks = static_cast(g_configManager().getNumber(RED_SKULL_DURATION)) * 24 * 60 * 60; } } @@ -4944,8 +4700,7 @@ void Player::addUnjustifiedDead(const Player* attacked) sendUnjustifiedPoints(); } -void Player::checkSkullTicks(int64_t ticks) -{ +void Player::checkSkullTicks(int64_t ticks) { int64_t newTicks = skullTicks - ticks; if (newTicks < 0) { skullTicks = 0; @@ -4958,14 +4713,12 @@ void Player::checkSkullTicks(int64_t ticks) } } -bool Player::isPromoted() const -{ +bool Player::isPromoted() const { uint16_t promotedVocation = g_vocations().getPromotedVocation(vocation->getId()); return promotedVocation == VOCATION_NONE && vocation->getId() != promotedVocation; } -double Player::getLostPercent() const -{ +double Player::getLostPercent() const { int32_t blessingCount = 0; uint8_t maxBlessing = (operatingSystem == CLIENTOS_NEW_WINDOWS || operatingSystem == CLIENTOS_NEW_MAC) ? 8 : 6; for (int i = 2; i <= maxBlessing; i++) { @@ -5001,20 +4754,17 @@ double Player::getLostPercent() const return lossPercent * (1 - (percentReduction / 100.)) / 100.; } -void Player::learnInstantSpell(const std::string& spellName) -{ +void Player::learnInstantSpell(const std::string &spellName) { if (!hasLearnedInstantSpell(spellName)) { learnedInstantSpellList.push_front(spellName); } } -void Player::forgetInstantSpell(const std::string& spellName) -{ +void Player::forgetInstantSpell(const std::string &spellName) { learnedInstantSpellList.remove(spellName); } -bool Player::hasLearnedInstantSpell(const std::string& spellName) const -{ +bool Player::hasLearnedInstantSpell(const std::string &spellName) const { if (hasFlag(PlayerFlags_t::CannotUseSpells)) { return false; } @@ -5023,7 +4773,7 @@ bool Player::hasLearnedInstantSpell(const std::string& spellName) const return true; } - for (const auto& learnedSpellName : learnedInstantSpellList) { + for (const auto &learnedSpellName : learnedInstantSpellList) { if (strcasecmp(learnedSpellName.c_str(), spellName.c_str()) == 0) { return true; } @@ -5031,8 +4781,7 @@ bool Player::hasLearnedInstantSpell(const std::string& spellName) const return false; } -bool Player::isInWar(const Player* player) const -{ +bool Player::isInWar(const Player* player) const { if (!player || !guild) { return false; } @@ -5045,13 +4794,11 @@ bool Player::isInWar(const Player* player) const return isInWarList(playerGuild->getId()) && player->isInWarList(guild->getId()); } -bool Player::isInWarList(uint32_t guildId) const -{ +bool Player::isInWarList(uint32_t guildId) const { return std::find(guildWarVector.begin(), guildWarVector.end(), guildId) != guildWarVector.end(); } -bool Player::isPremium() const -{ +bool Player::isPremium() const { if (g_configManager().getBoolean(FREE_PREMIUM) || hasFlag(PlayerFlags_t::IsAlwaysPremium)) { return true; } @@ -5059,19 +4806,16 @@ bool Player::isPremium() const return premiumDays > 0; } -void Player::setPremiumDays(int32_t v) -{ +void Player::setPremiumDays(int32_t v) { premiumDays = v; sendBasicData(); } -void Player::setTibiaCoins(int32_t v) -{ +void Player::setTibiaCoins(int32_t v) { coinBalance = v; } -PartyShields_t Player::getPartyShield(const Player* player) const -{ +PartyShields_t Player::getPartyShield(const Player* player) const { if (!player) { return SHIELD_NONE; } @@ -5125,38 +4869,33 @@ PartyShields_t Player::getPartyShield(const Player* player) const return SHIELD_NONE; } -bool Player::isInviting(const Player* player) const -{ +bool Player::isInviting(const Player* player) const { if (!player || !party || party->getLeader() != this) { return false; } return party->isPlayerInvited(player); } -bool Player::isPartner(const Player* player) const -{ +bool Player::isPartner(const Player* player) const { if (!player || !party || player == this) { return false; } return party == player->party; } -bool Player::isGuildMate(const Player* player) const -{ +bool Player::isGuildMate(const Player* player) const { if (!player || !guild) { return false; } return guild == player->guild; } -void Player::sendPlayerPartyIcons(Player* player) -{ +void Player::sendPlayerPartyIcons(Player* player) { sendPartyCreatureShield(player); sendPartyCreatureSkull(player); } -bool Player::addPartyInvitation(Party* newParty) -{ +bool Player::addPartyInvitation(Party* newParty) { auto it = std::find(invitePartyList.begin(), invitePartyList.end(), newParty); if (it != invitePartyList.end()) { return false; @@ -5166,21 +4905,18 @@ bool Player::addPartyInvitation(Party* newParty) return true; } -void Player::removePartyInvitation(Party* remParty) -{ +void Player::removePartyInvitation(Party* remParty) { invitePartyList.remove(remParty); } -void Player::clearPartyInvitations() -{ +void Player::clearPartyInvitations() { for (Party* invitingParty : invitePartyList) { invitingParty->removeInvite(*this, false); } invitePartyList.clear(); } -GuildEmblems_t Player::getGuildEmblem(const Player* player) const -{ +GuildEmblems_t Player::getGuildEmblem(const Player* player) const { if (!player) { return GUILDEMBLEM_NONE; } @@ -5205,14 +4941,13 @@ GuildEmblems_t Player::getGuildEmblem(const Player* player) const return GUILDEMBLEM_NEUTRAL; } -void Player::sendUnjustifiedPoints() -{ +void Player::sendUnjustifiedPoints() { if (client) { double dayKills = 0; double weekKills = 0; double monthKills = 0; - for (const auto& kill : unjustifiedKills) { + for (const auto &kill : unjustifiedKills) { const auto diff = time(nullptr) - kill.time; if (diff <= 24 * 60 * 60) { dayKills += 1; @@ -5242,8 +4977,7 @@ void Player::sendUnjustifiedPoints() } } -uint8_t Player::getCurrentMount() const -{ +uint8_t Player::getCurrentMount() const { int32_t value = getStorageValue(PSTRG_MOUNTS_CURRENTMOUNT); if (value > 0) { return value; @@ -5251,15 +4985,13 @@ uint8_t Player::getCurrentMount() const return 0; } -void Player::setCurrentMount(uint8_t mount) -{ +void Player::setCurrentMount(uint8_t mount) { addStorageValue(PSTRG_MOUNTS_CURRENTMOUNT, mount); } -bool Player::hasAnyMount() const -{ - for (const auto& mounts = g_game().mounts.getMounts(); - const Mount& mount : mounts) { +bool Player::hasAnyMount() const { + for (const auto &mounts = g_game().mounts.getMounts(); + const Mount &mount : mounts) { if (hasMount(&mount)) { return true; } @@ -5267,12 +4999,11 @@ bool Player::hasAnyMount() const return false; } -uint8_t Player::getRandomMountId() const -{ +uint8_t Player::getRandomMountId() const { std::vector playerMounts; - for (const auto& mounts = g_game().mounts.getMounts(); - const Mount& mount : mounts) { + for (const auto &mounts = g_game().mounts.getMounts(); + const Mount &mount : mounts) { if (hasMount(&mount)) { playerMounts.push_back(mount.id); } @@ -5283,8 +5014,7 @@ uint8_t Player::getRandomMountId() const return playerMounts.at(randomIndex); } -bool Player::toggleMount(bool mount) -{ +bool Player::toggleMount(bool mount) { if ((OTSYS_TIME() - lastToggleMount) < 3000 && !wasMounted) { sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); return false; @@ -5355,8 +5085,7 @@ bool Player::toggleMount(bool mount) return true; } -bool Player::tameMount(uint8_t mountId) -{ +bool Player::tameMount(uint8_t mountId) { if (!g_game().mounts.getMountByID(mountId)) { return false; } @@ -5375,8 +5104,7 @@ bool Player::tameMount(uint8_t mountId) return true; } -bool Player::untameMount(uint8_t mountId) -{ +bool Player::untameMount(uint8_t mountId) { if (!g_game().mounts.getMountByID(mountId)) { return false; } @@ -5404,8 +5132,7 @@ bool Player::untameMount(uint8_t mountId) return true; } -bool Player::hasMount(const Mount* mount) const -{ +bool Player::hasMount(const Mount* mount) const { if (isAccessPlayer()) { return true; } @@ -5424,8 +5151,7 @@ bool Player::hasMount(const Mount* mount) const return ((1 << (tmpMountId % 31)) & value) != 0; } -void Player::dismount() -{ +void Player::dismount() { const Mount* mount = g_game().mounts.getMountByID(getCurrentMount()); if (mount && mount->speed > 0) { g_game().changeSpeed(this, -mount->speed); @@ -5434,8 +5160,7 @@ void Player::dismount() defaultOutfit.lookMount = 0; } -bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) -{ +bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) { if (tries == 0 || skill == SKILL_LEVEL) { return false; } @@ -5576,18 +5301,15 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) return sendUpdate; } -bool Player::hasModalWindowOpen(uint32_t modalWindowId) const -{ +bool Player::hasModalWindowOpen(uint32_t modalWindowId) const { return find(modalWindows.begin(), modalWindows.end(), modalWindowId) != modalWindows.end(); } -void Player::onModalWindowHandled(uint32_t modalWindowId) -{ +void Player::onModalWindowHandled(uint32_t modalWindowId) { modalWindows.remove(modalWindowId); } -void Player::sendModalWindow(const ModalWindow& modalWindow) -{ +void Player::sendModalWindow(const ModalWindow &modalWindow) { if (!client) { return; } @@ -5596,25 +5318,23 @@ void Player::sendModalWindow(const ModalWindow& modalWindow) client->sendModalWindow(modalWindow); } -void Player::clearModalWindows() -{ +void Player::clearModalWindows() { modalWindows.clear(); } -uint16_t Player::getHelpers() const -{ +uint16_t Player::getHelpers() const { uint16_t helpers; if (guild && party) { phmap::flat_hash_set helperSet; - const auto& guildMembers = guild->getMembersOnline(); + const auto &guildMembers = guild->getMembersOnline(); helperSet.insert(guildMembers.begin(), guildMembers.end()); - const auto& partyMembers = party->getMembers(); + const auto &partyMembers = party->getMembers(); helperSet.insert(partyMembers.begin(), partyMembers.end()); - const auto& partyInvitees = party->getInvitees(); + const auto &partyInvitees = party->getInvitees(); helperSet.insert(partyInvitees.begin(), partyInvitees.end()); helperSet.insert(party->getLeader()); @@ -5631,8 +5351,7 @@ uint16_t Player::getHelpers() const return helpers; } -void Player::sendClosePrivate(uint16_t channelId) -{ +void Player::sendClosePrivate(uint16_t channelId) { if (channelId == CHANNEL_GUILD || channelId == CHANNEL_PARTY) { g_chat().removeUserFromChannel(*this, channelId); } @@ -5642,8 +5361,7 @@ void Player::sendClosePrivate(uint16_t channelId) } } -uint64_t Player::getMoney() const -{ +uint64_t Player::getMoney() const { std::vector containers; uint64_t moneyCount = 0; @@ -5676,13 +5394,12 @@ uint64_t Player::getMoney() const return moneyCount; } -std::pair Player::getForgeSliversAndCores() const -{ +std::pair Player::getForgeSliversAndCores() const { uint64_t sliverCount = 0; uint64_t coreCount = 0; // Check items from inventory - for (const auto *item : getAllInventoryItems()) { + for (const auto* item : getAllInventoryItems()) { if (!item) { continue; } @@ -5693,8 +5410,7 @@ std::pair Player::getForgeSliversAndCores() const // Check items from stash for (StashItemList stashToSend = getStashItems(); - auto [itemId, itemCount] : stashToSend) - { + auto [itemId, itemCount] : stashToSend) { if (itemId == ITEM_FORGE_SLIVER) { sliverCount += itemCount; } @@ -5706,8 +5422,7 @@ std::pair Player::getForgeSliversAndCores() const return std::make_pair(sliverCount, coreCount); } -size_t Player::getMaxVIPEntries() const -{ +size_t Player::getMaxVIPEntries() const { if (group->maxVipEntries != 0) { return group->maxVipEntries; } else if (isPremium()) { @@ -5716,8 +5431,7 @@ size_t Player::getMaxVIPEntries() const return 20; } -size_t Player::getMaxDepotItems() const -{ +size_t Player::getMaxDepotItems() const { if (group->maxDepotItems != 0) { return group->maxDepotItems; } else if (isPremium()) { @@ -5726,8 +5440,7 @@ size_t Player::getMaxDepotItems() const return g_configManager().getNumber(FREE_DEPOT_LIMIT); } -std::forward_list Player::getMuteConditions() const -{ +std::forward_list Player::getMuteConditions() const { std::forward_list muteConditions; for (Condition* condition : conditions) { if (condition->getTicks() <= 0) { @@ -5744,8 +5457,7 @@ std::forward_list Player::getMuteConditions() const return muteConditions; } -void Player::setGuild(Guild* newGuild) -{ +void Player::setGuild(Guild* newGuild) { if (newGuild == this->guild) { return; } @@ -5772,8 +5484,7 @@ void Player::setGuild(Guild* newGuild) } } -void Player::updateRegeneration() -{ +void Player::updateRegeneration() { if (!vocation) { return; } @@ -5796,19 +5507,17 @@ void Player::updateUIExhausted() { lastUIInteraction = OTSYS_TIME(); } -uint64_t Player::getItemCustomPrice(uint16_t itemId, bool buyPrice/* = false*/) const -{ +uint64_t Player::getItemCustomPrice(uint16_t itemId, bool buyPrice /* = false*/) const { auto it = itemPriceMap.find(itemId); if (it != itemPriceMap.end()) { return it->second; } - std::map itemMap {{itemId, 1}}; + std::map itemMap { { itemId, 1 } }; return g_game().getItemMarketPrice(itemMap, buyPrice); } -uint16_t Player::getFreeBackpackSlots() const -{ +uint16_t Player::getFreeBackpackSlots() const { Thing* thing = getThing(CONST_SLOT_BACKPACK); if (!thing) { return 0; @@ -5824,8 +5533,7 @@ uint16_t Player::getFreeBackpackSlots() const return counter; } -void Player::addItemImbuementStats(const Imbuement* imbuement) -{ +void Player::addItemImbuementStats(const Imbuement* imbuement) { bool requestUpdate = false; // Check imbuement skills for (int32_t skill = SKILL_FIRST; skill <= SKILL_LAST; ++skill) { @@ -5851,7 +5559,7 @@ void Player::addItemImbuementStats(const Imbuement* imbuement) // Add imbuement capacity if (imbuement->capacity != 0) { requestUpdate = true; - bonusCapacity = (capacity * imbuement->capacity)/100; + bonusCapacity = (capacity * imbuement->capacity) / 100; } if (requestUpdate) { @@ -5860,8 +5568,7 @@ void Player::addItemImbuementStats(const Imbuement* imbuement) } } -void Player::removeItemImbuementStats(const Imbuement* imbuement) -{ +void Player::removeItemImbuementStats(const Imbuement* imbuement) { bool requestUpdate = false; for (int32_t skill = SKILL_FIRST; skill <= SKILL_LAST; ++skill) { @@ -5941,23 +5648,19 @@ void Player::stowItem(Item* item, uint32_t count, bool allItems) { if (allItems) { // Stow player backpack if (auto inventoryItem = getInventoryItem(CONST_SLOT_BACKPACK); - !item->isInsideDepot(true)) - { + !item->isInsideDepot(true)) { sendStowItems(*item, *inventoryItem, itemDict); } // Stow locker items - DepotLocker *depotLocker = getDepotLocker(getLastDepotId()); + DepotLocker* depotLocker = getDepotLocker(getLastDepotId()); auto [itemVector, itemMap] = requestLockerItems(depotLocker); - for (auto lockerItem : itemVector) - { - if (lockerItem == nullptr) - { + for (auto lockerItem : itemVector) { + if (lockerItem == nullptr) { break; } - if (item->isInsideDepot(true)) - { + if (item->isInsideDepot(true)) { sendStowItems(*item, *lockerItem, itemDict); } } @@ -5984,8 +5687,7 @@ void Player::stowItem(Item* item, uint32_t count, bool allItems) { stashContainer(itemDict); } -void Player::openPlayerContainers() -{ +void Player::openPlayerContainers() { std::vector> openContainersList; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { @@ -6012,18 +5714,17 @@ void Player::openPlayerContainers() } } - std::sort(openContainersList.begin(), openContainersList.end(), [](const std::pair& left, const std::pair& right) { + std::sort(openContainersList.begin(), openContainersList.end(), [](const std::pair &left, const std::pair &right) { return left.first < right.first; }); - for (auto& it : openContainersList) { + for (auto &it : openContainersList) { addContainer(it.first - 1, it.second); onSendContainer(it.second); } } -void Player::initializePrey() -{ +void Player::initializePrey() { if (preys.empty()) { for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { auto slot = new PreySlot(static_cast(slotId)); @@ -6045,8 +5746,7 @@ void Player::initializePrey() } } -void Player::initializeTaskHunting() -{ +void Player::initializeTaskHunting() { if (taskHunting.empty()) { for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { auto slot = new TaskHuntingSlot(static_cast(slotId)); @@ -6072,8 +5772,7 @@ void Player::initializeTaskHunting() } } -std::string Player::getBlessingsName() const -{ +std::string Player::getBlessingsName() const { uint8_t count = 0; std::for_each(blessings.begin(), blessings.end(), [&count](uint8_t amount) { if (amount != 0) { @@ -6085,7 +5784,7 @@ std::string Player::getBlessingsName() const for (uint8_t i = 1; i <= 8; i++) { if (hasBlessing(i)) { if (auto blessName = BlessingNames.find(static_cast(i)); - blessName != BlessingNames.end()) { + blessName != BlessingNames.end()) { os << (*blessName).second; } else { continue; @@ -6147,8 +5846,7 @@ void Player::triggerMomentum() { /******************************************************************************* * Depot search system ******************************************************************************/ -void Player::requestDepotItems() -{ +void Player::requestDepotItems() { ItemsTierCountList itemMap; uint16_t count = 0; const DepotLocker* depotLocker = getDepotLocker(getLastDepotId()); @@ -6180,7 +5878,7 @@ void Player::requestDepotItems() } } - for (const auto& [itemId, itemCount] : getStashItems()) { + for (const auto &[itemId, itemCount] : getStashItems()) { auto itemMap_it = itemMap.find(itemId); // Stackable items not have upgrade classification if (Item::items[itemId].upgradeClassification > 0) { @@ -6205,16 +5903,15 @@ void Player::requestDepotItems() sendDepotItems(itemMap, count); } -void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) -{ +void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) { ItemVector depotItems; ItemVector inboxItems; uint32_t depotCount = 0; uint32_t inboxCount = 0; uint32_t stashCount = 0; - if (const ItemType& iType = Item::items[itemId]; - iType.stackable && iType.wareId > 0) { + if (const ItemType &iType = Item::items[itemId]; + iType.stackable && iType.wareId > 0) { stashCount = getStashItemCount(itemId); } @@ -6253,8 +5950,7 @@ void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) sendDepotSearchResultDetail(itemId, tier, depotCount, depotItems, inboxCount, inboxItems, stashCount); } -void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool isDepot) -{ +void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool isDepot) { const DepotLocker* depotLocker = getDepotLocker(getLastDepotId()); if (!depotLocker) { return; @@ -6267,9 +5963,7 @@ void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool // Retrieve from inbox. (c->isInbox() && isDepot) || // Retrieve from depot. - (!c->isInbox() && !isDepot) - ) - { + (!c->isInbox() && !isDepot)) { continue; } @@ -6304,8 +5998,7 @@ void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool requestDepotSearchItem(itemId, tier); } -void Player::openContainerFromDepotSearch(const Position& pos) -{ +void Player::openContainerFromDepotSearch(const Position &pos) { if (!isDepotSearchOpen()) { sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -6326,8 +6019,7 @@ void Player::openContainerFromDepotSearch(const Position& pos) g_actions().useItem(this, pos, 0, container, false); } -Item* Player::getItemFromDepotSearch(uint16_t itemId, const Position& pos) -{ +Item* Player::getItemFromDepotSearch(uint16_t itemId, const Position &pos) { const DepotLocker* depotLocker = getDepotLocker(getLastDepotId()); if (!depotLocker) { return nullptr; @@ -6336,9 +6028,8 @@ Item* Player::getItemFromDepotSearch(uint16_t itemId, const Position& pos) uint8_t index = 0; for (Item* locker : depotLocker->getItemList()) { const Container* c = locker->getContainer(); - if (!c || c->empty() || - (c->isInbox() && pos.y != 0x21) || // From inbox. - (!c->isInbox() && pos.y != 0x20)) { // From depot. + if (!c || c->empty() || (c->isInbox() && pos.y != 0x21) || // From inbox. + (!c->isInbox() && pos.y != 0x20)) { // From depot. continue; } @@ -6358,8 +6049,7 @@ Item* Player::getItemFromDepotSearch(uint16_t itemId, const Position& pos) return nullptr; } -std::pair, std::map>> Player::requestLockerItems(DepotLocker *depotLocker, bool sendToClient /*= false*/, uint8_t tier /*= 0*/) const -{ +std::pair, std::map>> Player::requestLockerItems(DepotLocker* depotLocker, bool sendToClient /*= false*/, uint8_t tier /*= 0*/) const { if (depotLocker == nullptr) { SPDLOG_ERROR("{} - Depot locker is nullptr", __FUNCTION__); return {}; @@ -6367,7 +6057,7 @@ std::pair, std::map>> P std::map> lockerItems; std::vector itemVector; - std::vector containers {depotLocker}; + std::vector containers { depotLocker }; size_t size = 0; do { @@ -6381,7 +6071,7 @@ std::pair, std::map>> P continue; } - const ItemType& itemType = Item::items[item->getID()]; + const ItemType &itemType = Item::items[item->getID()]; if (itemType.wareId == 0) { continue; } @@ -6404,18 +6094,14 @@ std::pair, std::map>> P } while (size < containers.size()); StashItemList stashToSend = getStashItems(); uint32_t countSize = 0; - for (auto [itemId, itemCount] : stashToSend) - { + for (auto [itemId, itemCount] : stashToSend) { countSize += itemCount; } - do - { - for (auto [itemId, itemCount] : stashToSend) - { + do { + for (auto [itemId, itemCount] : stashToSend) { const ItemType &itemType = Item::items[itemId]; - if (itemType.wareId == 0) - { + if (itemType.wareId == 0) { continue; } @@ -6427,8 +6113,7 @@ std::pair, std::map>> P return std::make_pair(itemVector, lockerItems); } -std::pair, uint16_t> Player::getLockerItemsAndCountById(DepotLocker &depotLocker, uint8_t tier, uint16_t itemId) -{ +std::pair, uint16_t> Player::getLockerItemsAndCountById(DepotLocker &depotLocker, uint8_t tier, uint16_t itemId) { std::vector lockerItems; auto [itemVector, itemMap] = requestLockerItems(&depotLocker, false, tier); uint16_t totalCount = 0; @@ -6446,11 +6131,11 @@ std::pair, uint16_t> Player::getLockerItemsAndCountById(Depot bool Player::saySpell( SpeakClasses type, - const std::string& text, + const std::string &text, bool ghostMode, - SpectatorHashSet* spectatorsPtr/* = nullptr*/, - const Position* pos/* = nullptr*/) -{ + SpectatorHashSet* spectatorsPtr /* = nullptr*/, + const Position* pos /* = nullptr*/ +) { if (text.empty()) { SPDLOG_DEBUG("{} - Spell text is empty for player {}", __FUNCTION__, getName()); return false; @@ -6468,13 +6153,9 @@ bool Player::saySpell( // used (hopefully the compiler will optimize away the construction of // the temporary when it's not used). if (type != TALKTYPE_YELL && type != TALKTYPE_MONSTER_YELL) { - g_game().map.getSpectators(spectators, *pos, false, false, - Map::maxClientViewportX, Map::maxClientViewportX, - Map::maxClientViewportY, Map::maxClientViewportY); + g_game().map.getSpectators(spectators, *pos, false, false, Map::maxClientViewportX, Map::maxClientViewportX, Map::maxClientViewportY, Map::maxClientViewportY); } else { - g_game().map.getSpectators(spectators, *pos, true, false, - (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportX + 1) * 2, - (Map::maxClientViewportY + 1) * 2, (Map::maxClientViewportY + 1) * 2); + g_game().map.getSpectators(spectators, *pos, true, false, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, (Map::maxClientViewportY + 1) * 2); } } else { spectators = (*spectatorsPtr); @@ -6511,8 +6192,7 @@ bool Player::saySpell( } // Forge system -void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool reduceTierLoss, uint8_t bonus, uint8_t coreCount) -{ +void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool reduceTierLoss, uint8_t bonus, uint8_t coreCount) { ForgeHistory history; history.actionType = ForgeConversion_t::FORGE_ACTION_FUSION; history.tier = tier; @@ -6526,8 +6206,7 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re return; } auto returnValue = g_game().internalRemoveItem(firstForgingItem, 1); - if (returnValue != RETURNVALUE_NOERROR) - { + if (returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Log 1] Failed to remove forge item {} from player with name {}", itemId, getName()); sendCancelMessage(getReturnMessage(returnValue)); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6540,8 +6219,7 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re return; } if (returnValue = g_game().internalRemoveItem(secondForgingItem, 1); - returnValue != RETURNVALUE_NOERROR) - { + returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Log 2] Failed to remove forge item {} from player with name {}", itemId, getName()); sendCancelMessage(getReturnMessage(returnValue)); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6593,17 +6271,14 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re } auto dustCost = static_cast(g_configManager().getNumber(FORGE_FUSION_DUST_COST)); - if (success) - { + if (success) { firstForgedItem->setTier(tier + 1); - if (bonus != 1) - { + if (bonus != 1) { history.dustCost = dustCost; setForgeDusts(getForgeDusts() - dustCost); } - if (bonus != 2) - { + if (bonus != 2) { if (!removeItemOfType(ITEM_FORGE_CORE, coreCount, -1, true, true)) { SPDLOG_ERROR("[{}][Log 1] Failed to remove item 'id :{} count: {}' from player {}", __FUNCTION__, ITEM_FORGE_CORE, coreCount, getName()); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6611,20 +6286,15 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re } history.coresCost = coreCount; } - if (bonus != 3) - { + if (bonus != 3) { uint64_t cost = 0; - for (const auto *itemClassification : g_game().getItemsClassifications()) - { - if (itemClassification->id != firstForgingItem->getClassification()) - { + for (const auto* itemClassification : g_game().getItemsClassifications()) { + if (itemClassification->id != firstForgingItem->getClassification()) { continue; } - for (const auto &[mapTier, mapPrice] : itemClassification->tiers) - { - if (mapTier == firstForgingItem->getTier()) - { + for (const auto &[mapTier, mapPrice] : itemClassification->tiers) { + if (mapTier == firstForgingItem->getTier()) { cost = mapPrice; break; } @@ -6639,24 +6309,17 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re history.cost = cost; } - if (bonus == 4) - { - if (tier > 0) - { + if (bonus == 4) { + if (tier > 0) { secondForgedItem->setTier(tier - 1); } - } - else if (bonus == 6) - { + } else if (bonus == 6) { secondForgedItem->setTier(tier + 1); - } - else if (bonus == 7 && tier + 2 <= firstForgedItem->getClassification()) - { + } else if (bonus == 7 && tier + 2 <= firstForgedItem->getClassification()) { firstForgedItem->setTier(tier + 2); } - if (bonus != 4 && bonus != 5 && bonus != 6 && bonus != 8) - { + if (bonus != 4 && bonus != 5 && bonus != 6 && bonus != 8) { returnValue = g_game().internalRemoveItem(secondForgedItem, 1); if (returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Log 6] Failed to remove forge item {} from player with name {}", itemId, getName()); @@ -6667,14 +6330,10 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re } } else { auto isTierLost = uniform_random(1, 100) <= (reduceTierLoss ? g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION) : 100); - if (isTierLost) - { - if (secondForgedItem->getTier() >= 1) - { + if (isTierLost) { + if (secondForgedItem->getTier() >= 1) { secondForgedItem->setTier(tier - 1); - } - else - { + } else { returnValue = g_game().internalRemoveItem(secondForgedItem, 1); if (returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Log 7] Failed to remove forge item {} from player with name {}", itemId, getName()); @@ -6702,17 +6361,13 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re } uint64_t cost = 0; - for (const auto *itemClassification : g_game().getItemsClassifications()) - { - if (itemClassification->id != firstForgingItem->getClassification()) - { + for (const auto* itemClassification : g_game().getItemsClassifications()) { + if (itemClassification->id != firstForgingItem->getClassification()) { continue; } - for (const auto &[mapTier, mapPrice] : itemClassification->tiers) - { - if (mapTier == firstForgingItem->getTier()) - { + for (const auto &[mapTier, mapPrice] : itemClassification->tiers) { + if (mapTier == firstForgingItem->getTier()) { cost = mapPrice; break; } @@ -6743,8 +6398,7 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re sendForgeFusionItem(itemId, tier, success, bonus, coreCount); } -void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t receiveItemId) -{ +void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t receiveItemId) { ForgeHistory history; history.actionType = ForgeConversion_t::FORGE_ACTION_TRANSFER; history.tier = tier; @@ -6757,8 +6411,7 @@ void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t return; } auto returnValue = g_game().internalRemoveItem(donorItem, 1); - if (returnValue != RETURNVALUE_NOERROR) - { + if (returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Log 1] Failed to remove transfer item {} from player with name {}", donorItemId, getName()); sendCancelMessage(getReturnMessage(returnValue)); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6772,8 +6425,7 @@ void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t return; } if (returnValue = g_game().internalRemoveItem(receiveItem, 1); - returnValue != RETURNVALUE_NOERROR) - { + returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Log 2] Failed to remove transfer item {} from player with name {}", receiveItemId, getName()); sendCancelMessage(getReturnMessage(returnValue)); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6836,17 +6488,13 @@ void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t return; } uint64_t cost = 0; - for (const auto &itemClassification : g_game().getItemsClassifications()) - { - if (itemClassification->id != donorItem->getClassification()) - { + for (const auto &itemClassification : g_game().getItemsClassifications()) { + if (itemClassification->id != donorItem->getClassification()) { continue; } - for (const auto &[mapTier, mapPrice] : itemClassification->tiers) - { - if (mapTier == donorItem->getTier() - 1) - { + for (const auto &[mapTier, mapPrice] : itemClassification->tiers) { + if (mapTier == donorItem->getTier() - 1) { cost = mapPrice; break; } @@ -6876,8 +6524,7 @@ void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t sendTransferItemTier(donorItemId, tier, receiveItemId); } -void Player::forgeResourceConversion(uint8_t action) -{ +void Player::forgeResourceConversion(uint8_t action) { auto actionEnum = magic_enum::enum_value(action); ForgeHistory history; history.actionType = actionEnum; @@ -6896,8 +6543,7 @@ void Player::forgeResourceConversion(uint8_t action) auto itemCount = static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT)); Item* item = Item::CreateItem(ITEM_FORGE_SLIVER, itemCount); returnValue = g_game().internalPlayerAddItem(this, item); - if (returnValue != RETURNVALUE_NOERROR) - { + if (returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("Failed to add {} slivers to player with name {}", itemCount, getName()); sendCancelMessage(getReturnMessage(returnValue)); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6925,8 +6571,7 @@ void Player::forgeResourceConversion(uint8_t action) item) { returnValue = g_game().internalPlayerAddItem(this, item); } - if (returnValue != RETURNVALUE_NOERROR) - { + if (returnValue != RETURNVALUE_NOERROR) { SPDLOG_ERROR("Failed to add one core to player with name {}", getName()); sendCancelMessage(getReturnMessage(returnValue)); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -6937,8 +6582,7 @@ void Player::forgeResourceConversion(uint8_t action) history.gained = 1; } else { auto dustLevel = getForgeDustLevel(); - if (dustLevel >= g_configManager().getNumber(FORGE_MAX_DUST)) - { + if (dustLevel >= g_configManager().getNumber(FORGE_MAX_DUST)) { SPDLOG_ERROR("[{}] Maximum level reached", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; @@ -6946,8 +6590,7 @@ void Player::forgeResourceConversion(uint8_t action) auto upgradeCost = dustLevel - 75; if (auto dusts = getForgeDusts(); - upgradeCost > dusts) - { + upgradeCost > dusts) { SPDLOG_ERROR("[{}] Not enough dust", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; @@ -6964,13 +6607,11 @@ void Player::forgeResourceConversion(uint8_t action) sendForgingData(); } -void Player::forgeHistory(uint8_t page) const -{ +void Player::forgeHistory(uint8_t page) const { sendForgeHistory(page); } -void Player::registerForgeHistoryDescription(ForgeHistory history) -{ +void Player::registerForgeHistoryDescription(ForgeHistory history) { std::string successfulString = history.success ? "Successful" : "Unsuccessful"; std::string historyTierString = history.tier > 0 ? "tier - 1" : "consumed"; std::string price = history.bonus != 3 ? formatPrice(std::to_string(history.cost), true) : "0"; @@ -6983,35 +6624,35 @@ void Player::registerForgeHistoryDescription(ForgeHistory history) "{:s}

" "Fusion partners:" "
    " - "
  • " - "First item: {:s} {:s}, tier {:s}" - "
  • " - "
  • " - "Second item: {:s} {:s}, tier {:s}" - "
  • " + "
  • " + "First item: {:s} {:s}, tier {:s}" + "
  • " + "
  • " + "Second item: {:s} {:s}, tier {:s}" + "
  • " "
" "
" "Result:" "
    " - "
  • " - "First item: tier + 1" - "
  • " - "
  • " - "Second item: {:s}" - "
  • " + "
  • " + "First item: tier + 1" + "
  • " + "
  • " + "Second item: {:s}" + "
  • " "
" "
" "Invested:" "
    " - "
  • " - "{:d} cores" - "
  • " - "
  • " - "{:d} dust" - "
  • " - "
  • " - "{:s} gold" - "
  • " + "
  • " + "{:d} cores" + "
  • " + "
  • " + "{:d} dust" + "
  • " + "
  • " + "{:s} gold" + "
  • " "
", successfulString, itemType.article, itemType.name, std::to_string(history.tier), @@ -7024,35 +6665,35 @@ void Player::registerForgeHistoryDescription(ForgeHistory history) "{:s}

" "Fusion partners:" "
    " - "
  • " - "First item: {:s} {:s}, tier {:s}" - "
  • " - "
  • " - "Second item: {:s} {:s}, tier {:s}" - "
  • " + "
  • " + "First item: {:s} {:s}, tier {:s}" + "
  • " + "
  • " + "Second item: {:s} {:s}, tier {:s}" + "
  • " "
" "
" "Result:" "
    " - "
  • " - "First item: unchanged" - "
  • " - "
  • " - "Second item: {:s}" - "
  • " + "
  • " + "First item: unchanged" + "
  • " + "
  • " + "Second item: {:s}" + "
  • " "
" "
" "Invested:" "
    " - "
  • " - "{:d} cores" - "
  • " - "
  • " - "100 dust" - "
  • " - "
  • " - "{:s} gold" - "
  • " + "
  • " + "{:d} cores" + "
  • " + "
  • " + "100 dust" + "
  • " + "
  • " + "{:s} gold" + "
  • " "
", successfulString, itemType.article, itemType.name, std::to_string(history.tier), @@ -7063,46 +6704,46 @@ void Player::registerForgeHistoryDescription(ForgeHistory history) } } else if (history.actionType == ForgeConversion_t::FORGE_ACTION_TRANSFER) { detailsResponse << fmt::format( - "{:s}

" - "Transfer partners:" - "
    " - "
  • " - "First item: {:s} {:s}, tier {:s}" - "
  • " - "
  • " - "Second item: {:s} {:s}, tier {:s}" - "
  • " - "
" - "
" - "Result:" - "
    " - "
  • " - "First item: {:s} {:s}, tier {:s}" - "
  • " - "
  • " - "Second item: {:s} {:s}, {:s}" - "
  • " - "
" - "
" - "Invested:" - "
    " - "
  • " - "1 cores" - "
  • " - "
  • " - "100 dust" - "
  • " - "
  • " - "{:s} gold" - "
  • " - "
", - successfulString, - itemType.article, itemType.name, std::to_string(history.tier), - itemType.article, itemType.name, std::to_string(history.tier), - itemType.article, itemType.name, std::to_string(history.tier), - itemType.article, itemType.name, std::to_string(history.tier), - price - ); + "{:s}

" + "Transfer partners:" + "
    " + "
  • " + "First item: {:s} {:s}, tier {:s}" + "
  • " + "
  • " + "Second item: {:s} {:s}, tier {:s}" + "
  • " + "
" + "
" + "Result:" + "
    " + "
  • " + "First item: {:s} {:s}, tier {:s}" + "
  • " + "
  • " + "Second item: {:s} {:s}, {:s}" + "
  • " + "
" + "
" + "Invested:" + "
    " + "
  • " + "1 cores" + "
  • " + "
  • " + "100 dust" + "
  • " + "
  • " + "{:s} gold" + "
  • " + "
", + successfulString, + itemType.article, itemType.name, std::to_string(history.tier), + itemType.article, itemType.name, std::to_string(history.tier), + itemType.article, itemType.name, std::to_string(history.tier), + itemType.article, itemType.name, std::to_string(history.tier), + price + ); } else if (history.actionType == ForgeConversion_t::FORGE_ACTION_DUSTTOSLIVERS) { detailsResponse << fmt::format("Converted {:d} dust to {:d} slivers.", history.cost, history.gained); diff --git a/src/creatures/players/player.h b/src/creatures/players/player.h index 595ebf97295..4280b77f59e 100644 --- a/src/creatures/players/player.h +++ b/src/creatures/players/player.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_PLAYER_H_ #define SRC_CREATURES_PLAYERS_PLAYER_H_ @@ -54,32 +54,32 @@ enum class ForgeConversion_t : uint8_t { }; struct ForgeHistory { - ForgeConversion_t actionType = ForgeConversion_t::FORGE_ACTION_FUSION; - uint8_t tier = 0; - uint8_t bonus = 0; + ForgeConversion_t actionType = ForgeConversion_t::FORGE_ACTION_FUSION; + uint8_t tier = 0; + uint8_t bonus = 0; - time_t createdAt; + time_t createdAt; - uint16_t historyId = 0; + uint16_t historyId = 0; - uint64_t cost = 0; - uint64_t dustCost = 0; - uint64_t coresCost = 0; - uint64_t gained = 0; + uint64_t cost = 0; + uint64_t dustCost = 0; + uint64_t coresCost = 0; + uint64_t gained = 0; - bool success = false; - bool tierLoss = false; - bool successCore = false; - bool tierCore = false; + bool success = false; + bool tierLoss = false; + bool successCore = false; + bool tierCore = false; - std::string description; - std::string firstItemName; - std::string secondItemName; + std::string description; + std::string firstItemName; + std::string secondItemName; }; struct OpenContainer { - Container* container; - uint16_t index; + Container* container; + uint16_t index; }; using MuteCountMap = std::map; @@ -87,15 +87,14 @@ using MuteCountMap = std::map; static constexpr int32_t PLAYER_MAX_SPEED = 65535; static constexpr int32_t PLAYER_MIN_SPEED = 10; -class Player final : public Creature, public Cylinder -{ +class Player final : public Creature, public Cylinder { public: explicit Player(ProtocolGame_ptr p); ~Player(); // non-copyable - Player(const Player&) = delete; - Player& operator=(const Player&) = delete; + Player(const Player &) = delete; + Player &operator=(const Player &) = delete; Player* getPlayer() override { return this; @@ -114,16 +113,16 @@ class Player final : public Creature, public Cylinder static MuteCountMap muteCountMap; - const std::string& getName() const override { + const std::string &getName() const override { return name; } void setName(std::string newName) { this->name = std::move(newName); } - const std::string& getTypeName() const override { + const std::string &getTypeName() const override { return name; } - const std::string& getNameDescription() const override { + const std::string &getNameDescription() const override { return name; } std::string getDescription(int32_t lookDistance) const override; @@ -152,7 +151,7 @@ class Player final : public Creature, public Cylinder randomMount = isMountRandomized; } - void sendFYIBox(const std::string& message) { + void sendFYIBox(const std::string &message) { if (client) { client->sendFYIBox(message); } @@ -163,14 +162,12 @@ class Player final : public Creature, public Cylinder client->BestiarysendCharms(); } } - void addBestiaryKillCount(uint16_t raceid, uint32_t amount) - { + void addBestiaryKillCount(uint16_t raceid, uint32_t amount) { uint32_t oldCount = getBestiaryKillCount(raceid); uint32_t key = STORAGEVALUE_BESTIARYKILLCOUNT + raceid; addStorageValue(key, static_cast(oldCount + amount), true); } - uint32_t getBestiaryKillCount(uint16_t raceid) const - { + uint32_t getBestiaryKillCount(uint16_t raceid) const { uint32_t key = STORAGEVALUE_BESTIARYKILLCOUNT + raceid; auto value = getStorageValue(key); return value > 0 ? static_cast(value) : 0; @@ -246,7 +243,7 @@ class Player final : public Creature, public Cylinder } void setGuild(Guild* guild); - GuildRank_ptr getGuildRank() const { + GuildRank_ptr getGuildRank() const { return guildRank; } void setGuildRank(GuildRank_ptr newGuildRank) { @@ -255,7 +252,7 @@ class Player final : public Creature, public Cylinder bool isGuildMate(const Player* player) const; - const std::string& getGuildNick() const { + const std::string &getGuildNick() const { return guildNick; } void setGuildNick(std::string nick) { @@ -278,8 +275,8 @@ class Player final : public Creature, public Cylinder uint32_t getClientIcons() const; - const GuildWarVector& getGuildWarVector() const { - return guildWarVector; + const GuildWarVector &getGuildWarVector() const { + return guildWarVector; } std::list getBestiaryTrackerList() const { @@ -376,14 +373,14 @@ class Player final : public Creature, public Cylinder return; } - blessings[index-1] += count; + blessings[index - 1] += count; } void removeBlessing(uint8_t index, uint8_t count) { if (blessings[index - 1] == 0) { return; } - blessings[index-1] -= count; + blessings[index - 1] -= count; } bool hasBlessing(uint8_t index) const { return blessings[index - 1] != 0; @@ -434,7 +431,7 @@ class Player final : public Creature, public Cylinder // Closing depot search when player have special container disabled and it's still open. if (isDepotSearchOpen() && !depotSearchBool && depotSearch) { - depotSearchOnItem = {0, 0}; + depotSearchOnItem = { 0, 0 }; sendCloseDepotSearch(); } @@ -455,7 +452,7 @@ class Player final : public Creature, public Cylinder return depotSearchOnItem.first == itemId; } void setDepotSearchIsOpen(uint16_t itemId, uint8_t tier) { - depotSearchOnItem = {itemId, tier}; + depotSearchOnItem = { itemId, tier }; } bool isDepotSearchAvailable() const { return depotSearch; @@ -545,10 +542,10 @@ class Player final : public Creature, public Cylinder return lastLogout; } - const Position& getLoginPosition() const { + const Position &getLoginPosition() const { return loginPosition; } - const Position& getTemplePosition() const { + const Position &getTemplePosition() const { return town->getTemplePosition(); } Town* getTown() const { @@ -659,7 +656,7 @@ class Player final : public Creature, public Cylinder Reward* getReward(uint32_t rewardId, bool autoCreate); void removeReward(uint32_t rewardId); - void getRewardList(std::vector& rewards); + void getRewardList(std::vector &rewards); RewardChest* getRewardChest(); DepotChest* getDepotChest(uint32_t depotId, bool autoCreate); @@ -670,7 +667,7 @@ class Player final : public Creature, public Cylinder Container* setLootContainer(ObjectCategory_t category, Container* container, bool loading = false); Container* getLootContainer(ObjectCategory_t category) const; - bool canSee(const Position& pos) const override; + bool canSee(const Position &pos) const override; bool canSeeCreature(const Creature* creature) const override; bool canWalkthrough(const Creature* creature) const; @@ -683,7 +680,7 @@ class Player final : public Creature, public Cylinder uint64_t getMoney() const; std::pair getForgeSliversAndCores() const; - //safe-trade functions + // safe-trade functions void setTradeState(TradeState_t state) { tradeState = state; } @@ -694,7 +691,7 @@ class Player final : public Creature, public Cylinder return tradeItem; } - //shop functions + // shop functions void setShopOwner(Npc* owner) { shopOwner = owner; } @@ -703,22 +700,22 @@ class Player final : public Creature, public Cylinder return shopOwner; } - //V.I.P. functions + // V.I.P. functions void notifyStatusChange(Player* player, VipStatus_t status, bool message = true); bool removeVIP(uint32_t vipGuid); - bool addVIP(uint32_t vipGuid, const std::string& vipName, VipStatus_t status); + bool addVIP(uint32_t vipGuid, const std::string &vipName, VipStatus_t status); bool addVIPInternal(uint32_t vipGuid); - bool editVIP(uint32_t vipGuid, const std::string& description, uint32_t icon, bool notify); + bool editVIP(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify); - //follow functions + // follow functions bool setFollowCreature(Creature* creature) override; void goToFollowCreature() override; - //follow events + // follow events void onFollowCreature(const Creature* creature) override; - //walk events - void onWalk(Direction& dir) override; + // walk events + void onWalk(Direction &dir) override; void onWalkAborted() override; void onWalkComplete() override; @@ -743,7 +740,7 @@ class Player final : public Creature, public Cylinder void setFaction(Faction_t factionId) { faction = factionId; } - //combat functions + // combat functions bool setAttackedCreature(Creature* creature) override; bool isImmune(CombatType_t type) const override; bool isImmune(ConditionType_t type) const override; @@ -751,7 +748,7 @@ class Player final : public Creature, public Cylinder bool isAttackable() const override; static bool lastHitIsPlayer(Creature* lastHitCreature); - //stash functions + // stash functions bool addItemFromStash(uint16_t itemId, uint32_t itemCount); void stowItem(Item* item, uint32_t count, bool allItems); @@ -762,8 +759,7 @@ class Player final : public Creature, public Cylinder bool isPzLocked() const { return pzLocked; } - BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, - bool checkDefense = false, bool checkArmor = false, bool field = false) override; + BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false) override; void doAttacking(uint32_t interval) override; bool hasExtraSwing() override { return lastAttack > 0 && ((OTSYS_TIME() - lastAttack) >= getAttackSpeed()); @@ -797,7 +793,7 @@ class Player final : public Creature, public Cylinder Item* getWeapon(bool ignoreAmmo = false) const; WeaponType_t getWeaponType() const; int32_t getWeaponSkill(const Item* item) const; - void getShieldAndWeapon(const Item*& shield, const Item*& weapon) const; + void getShieldAndWeapon(const Item*&shield, const Item*&weapon) const; void drainHealth(Creature* attacker, int32_t damage) override; void drainMana(Creature* attacker, int32_t manaLoss) override; @@ -813,7 +809,7 @@ class Player final : public Creature, public Cylinder uint64_t getGainedExperience(Creature* attacker) const override; - //combat event functions + // combat event functions void onAddCondition(ConditionType_t type) override; void onAddCombatCondition(ConditionType_t type) override; void onEndCondition(ConditionType_t type) override; @@ -836,8 +832,12 @@ class Player final : public Creature, public Cylinder Skulls_t getSkull() const override; Skulls_t getSkullClient(const Creature* creature) const override; - int64_t getSkullTicks() const { return skullTicks; } - void setSkullTicks(int64_t ticks) { skullTicks = ticks; } + int64_t getSkullTicks() const { + return skullTicks; + } + void setSkullTicks(int64_t ticks) { + skullTicks = ticks; + } bool hasAttacked(const Player* attacked) const; void addAttacked(const Player* attacked); @@ -860,12 +860,12 @@ class Player final : public Creature, public Cylinder void addOutfit(uint16_t lookType, uint8_t addons); bool removeOutfit(uint16_t lookType); bool removeOutfitAddon(uint16_t lookType, uint8_t addons); - bool getOutfitAddons(const Outfit& outfit, uint8_t& addons) const; + bool getOutfitAddons(const Outfit &outfit, uint8_t &addons) const; bool canFamiliar(uint16_t lookType) const; void addFamiliar(uint16_t lookType); bool removeFamiliar(uint16_t lookType); - bool getFamiliar(const Familiar& familiar) const; + bool getFamiliar(const Familiar &familiar) const; void setFamiliarLooktype(uint16_t familiarLooktype) { this->defaultOutfit.lookFamiliarsType = familiarLooktype; } @@ -877,9 +877,9 @@ class Player final : public Creature, public Cylinder size_t getMaxVIPEntries() const; size_t getMaxDepotItems() const; - //tile - //send methods - void sendAddTileItem(const Tile* itemTile, const Position& pos, const Item* item) { + // tile + // send methods + void sendAddTileItem(const Tile* itemTile, const Position &pos, const Item* item) { if (client) { int32_t stackpos = itemTile->getStackposOfItem(this, item); if (stackpos != -1) { @@ -887,7 +887,7 @@ class Player final : public Creature, public Cylinder } } } - void sendUpdateTileItem(const Tile* updateTile, const Position& pos, const Item* item) { + void sendUpdateTileItem(const Tile* updateTile, const Position &pos, const Item* item) { if (client) { int32_t stackpos = updateTile->getStackposOfItem(this, item); if (stackpos != -1) { @@ -895,33 +895,33 @@ class Player final : public Creature, public Cylinder } } } - void sendRemoveTileThing(const Position& pos, int32_t stackpos) { + void sendRemoveTileThing(const Position &pos, int32_t stackpos) { if (stackpos != -1 && client) { client->sendRemoveTileThing(pos, stackpos); } } - void sendUpdateTile(const Tile* updateTile, const Position& pos) { + void sendUpdateTile(const Tile* updateTile, const Position &pos) { if (client) { client->sendUpdateTile(updateTile, pos); } } - void sendChannelMessage(const std::string& author, const std::string& text, SpeakClasses type, uint16_t channel) { + void sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel) { if (client) { client->sendChannelMessage(author, text, type, channel); } } - void sendChannelEvent(uint16_t channelId, const std::string& playerName, ChannelEvent_t channelEvent) { + void sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent) { if (client) { client->sendChannelEvent(channelId, playerName, channelEvent); } } - void sendCreatureAppear(const Creature* creature, const Position& pos, bool isLogin) { + void sendCreatureAppear(const Creature* creature, const Position &pos, bool isLogin) { if (client) { client->sendAddCreature(creature, pos, creature->getTile()->getStackposOfCreature(this, creature), isLogin); } } - void sendCreatureMove(const Creature* creature, const Position& newPos, int32_t newStackPos, const Position& oldPos, int32_t oldStackPos, bool teleport) { + void sendCreatureMove(const Creature* creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { if (client) { client->sendMoveCreature(creature, newPos, newStackPos, oldPos, oldStackPos, teleport); } @@ -934,7 +934,7 @@ class Player final : public Creature, public Cylinder } } } - void sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string& text, const Position* pos = nullptr) { + void sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr) { if (client) { client->sendCreatureSay(creature, type, text, pos); } @@ -944,7 +944,7 @@ class Player final : public Creature, public Cylinder client->reloadCreature(creature); } } - void sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string& text) { + void sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string &text) { if (client) { client->sendPrivateMessage(speaker, type, text); } @@ -954,7 +954,7 @@ class Player final : public Creature, public Cylinder client->sendCreatureSquare(creature, color); } } - void sendCreatureChangeOutfit(const Creature* creature, const Outfit_t& outfit) { + void sendCreatureChangeOutfit(const Creature* creature, const Outfit_t &outfit) { if (client) { client->sendCreatureOutfit(creature, outfit); } @@ -996,7 +996,7 @@ class Player final : public Creature, public Cylinder client->sendCreatureIcon(creature); } } - void sendUpdateCreature(const Creature *creature) const { + void sendUpdateCreature(const Creature* creature) const { if (client) { client->sendUpdateCreature(creature); } @@ -1036,9 +1036,9 @@ class Player final : public Creature, public Cylinder client->reloadCreature(creature); } } - void sendModalWindow(const ModalWindow& modalWindow); + void sendModalWindow(const ModalWindow &modalWindow); - //container + // container void sendAddContainerItem(const Container* container, const Item* item); void sendUpdateContainerItem(const Container* container, uint16_t slot, const Item* newItem); void sendRemoveContainerItem(const Container* container, uint16_t slot); @@ -1048,7 +1048,7 @@ class Player final : public Creature, public Cylinder } } - //inventory + // inventory void sendDepotItems(const ItemsTierCountList &itemMap, uint16_t count) const { if (client) { client->sendDepotItems(itemMap, count); @@ -1059,13 +1059,7 @@ class Player final : public Creature, public Cylinder client->sendCloseDepotSearch(); } } - void sendDepotSearchResultDetail(uint16_t itemId, - uint8_t tier, - uint32_t depotCount, - const ItemVector &depotItems, - uint32_t inboxCount, - const ItemVector &inboxItems, - uint32_t stashCount) const { + void sendDepotSearchResultDetail(uint16_t itemId, uint8_t tier, uint32_t depotCount, const ItemVector &depotItems, uint32_t inboxCount, const ItemVector &inboxItems, uint32_t stashCount) const { if (client) { client->sendDepotSearchResultDetail(itemId, tier, depotCount, depotItems, inboxCount, inboxItems, stashCount); } @@ -1095,37 +1089,31 @@ class Player final : public Creature, public Cylinder } } - //event methods - void onUpdateTileItem(const Tile* tile, const Position& pos, const Item* oldItem, - const ItemType& oldType, const Item* newItem, - const ItemType& newType) override; - void onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, - const Item* item) override; + // event methods + void onUpdateTileItem(const Tile* tile, const Position &pos, const Item* oldItem, const ItemType &oldType, const Item* newItem, const ItemType &newType) override; + void onRemoveTileItem(const Tile* tile, const Position &pos, const ItemType &iType, const Item* item) override; void onCreatureAppear(Creature* creature, bool isLogin) override; void onRemoveCreature(Creature* creature, bool isLogout) override; - void onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, - bool teleport) override; + void onCreatureMove(Creature* creature, const Tile* newTile, const Position &newPos, const Tile* oldTile, const Position &oldPos, bool teleport) override; void onAttackedCreatureDisappear(bool isLogout) override; void onFollowCreatureDisappear(bool isLogout) override; - //container + // container void onAddContainerItem(const Item* item); - void onUpdateContainerItem(const Container* container, - const Item* oldItem, const Item* newItem); + void onUpdateContainerItem(const Container* container, const Item* oldItem, const Item* newItem); void onRemoveContainerItem(const Container* container, const Item* item); void onCloseContainer(const Container* container); void onSendContainer(const Container* container); void autoCloseContainers(const Container* container); - //inventory + // inventory void onUpdateInventoryItem(Item* oldItem, Item* newItem); void onRemoveInventoryItem(Item* item); - void sendCancelMessage(const std::string& msg) const { + void sendCancelMessage(const std::string &msg) const { if (client) { client->sendTextMessage(TextMessage(MESSAGE_FAILURE, msg)); } @@ -1191,14 +1179,13 @@ class Player final : public Creature, public Cylinder client->sendPlayerVocation(player); } } - void sendDistanceShoot(const Position& from, const Position& to, - uint8_t type) const { + void sendDistanceShoot(const Position &from, const Position &to, uint8_t type) const { if (client) { client->sendDistanceShoot(from, to, type); } } void sendHouseWindow(House* house, uint32_t listId) const; - void sendCreatePrivateChannel(uint16_t channelId, const std::string& channelName) { + void sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName) { if (client) { client->sendCreatePrivateChannel(channelId, channelName); } @@ -1219,7 +1206,7 @@ class Player final : public Creature, public Cylinder client->sendGameNews(); } } - void sendMagicEffect(const Position& pos, uint8_t type) const { + void sendMagicEffect(const Position &pos, uint8_t type) const { if (client) { client->sendMagicEffect(pos, type); } @@ -1246,12 +1233,12 @@ class Player final : public Creature, public Cylinder client->sendSkills(); } } - void sendTextMessage(MessageClasses mclass, const std::string& message) const { + void sendTextMessage(MessageClasses mclass, const std::string &message) const { if (client) { client->sendTextMessage(TextMessage(mclass, message)); } } - void sendTextMessage(const TextMessage& message) const { + void sendTextMessage(const TextMessage &message) const { if (client) { client->sendTextMessage(message); } @@ -1266,8 +1253,7 @@ class Player final : public Creature, public Cylinder client->sendTextWindow(windowTextId, item, maxlen, canWrite); } } - void sendToChannel(const Creature* creature, SpeakClasses type, - const std::string& text, uint16_t channelId) const { + void sendToChannel(const Creature* creature, SpeakClasses type, const std::string &text, uint16_t channelId) const { if (client) { client->sendToChannel(creature, type, text, channelId); } @@ -1277,7 +1263,7 @@ class Player final : public Creature, public Cylinder client->sendShop(npc); } } - void sendSaleItemList(const std::map& inventoryMap) const { + void sendSaleItemList(const std::map &inventoryMap) const { if (client && shopOwner) { client->sendSaleItemList(shopOwner->getShopItemVector(), inventoryMap); } @@ -1294,19 +1280,17 @@ class Player final : public Creature, public Cylinder client->sendMarketLeave(); } } - void sendMarketBrowseItem(uint16_t itemId, const MarketOfferList& buyOffers, const MarketOfferList& sellOffers, uint8_t tier) const { + void sendMarketBrowseItem(uint16_t itemId, const MarketOfferList &buyOffers, const MarketOfferList &sellOffers, uint8_t tier) const { if (client) { client->sendMarketBrowseItem(itemId, buyOffers, sellOffers, tier); } } - void sendMarketBrowseOwnOffers(const MarketOfferList& buyOffers, - const MarketOfferList& sellOffers) const { + void sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, const MarketOfferList &sellOffers) const { if (client) { client->sendMarketBrowseOwnOffers(buyOffers, sellOffers); } } - void sendMarketBrowseOwnHistory(const HistoryMarketOfferList& buyOffers, - const HistoryMarketOfferList& sellOffers) const { + void sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyOffers, const HistoryMarketOfferList &sellOffers) const { if (client) { client->sendMarketBrowseOwnHistory(buyOffers, sellOffers); } @@ -1316,18 +1300,17 @@ class Player final : public Creature, public Cylinder client->sendMarketDetail(itemId, tier); } } - void sendMarketAcceptOffer(const MarketOfferEx& offer) const { + void sendMarketAcceptOffer(const MarketOfferEx &offer) const { if (client) { client->sendMarketAcceptOffer(offer); } } - void sendMarketCancelOffer(const MarketOfferEx& offer) const { + void sendMarketCancelOffer(const MarketOfferEx &offer) const { if (client) { client->sendMarketCancelOffer(offer); } } - void sendTradeItemRequest(const std::string& traderName, - const Item* item, bool ack) const { + void sendTradeItemRequest(const std::string &traderName, const Item* item, bool ack) const { if (client) { client->sendTradeItemRequest(traderName, item, ack); } @@ -1352,7 +1335,7 @@ class Player final : public Creature, public Cylinder client->sendChannelsDialog(); } } - void sendOpenPrivateChannel(const std::string& receiver) { + void sendOpenPrivateChannel(const std::string &receiver) { if (client) { client->sendOpenPrivateChannel(receiver); } @@ -1368,25 +1351,20 @@ class Player final : public Creature, public Cylinder } } // Imbuements - void onApplyImbuement(Imbuement *imbuement, Item *item, uint8_t slot, bool protectionCharm); + void onApplyImbuement(Imbuement* imbuement, Item* item, uint8_t slot, bool protectionCharm); void onClearImbuement(Item* item, uint8_t slot); void openImbuementWindow(Item* item); - void sendImbuementResult(const std::string message) - { - if (client) - { + void sendImbuementResult(const std::string message) { + if (client) { client->sendImbuementResult(message); } } - void closeImbuementWindow() const - { - if(client) - { + void closeImbuementWindow() const { + if (client) { client->closeImbuementWindow(); } } - void sendPodiumWindow(const Item* podium, const Position& position, - uint16_t itemId, uint8_t stackpos) { + void sendPodiumWindow(const Item* podium, const Position &position, uint16_t itemId, uint8_t stackpos) { if (client) { client->sendPodiumWindow(podium, position, itemId, stackpos); } @@ -1397,8 +1375,7 @@ class Player final : public Creature, public Cylinder } } - void sendChannel(uint16_t channelId, const std::string& channelName, - const UsersMap* channelUsers, const InvitedMap* invitedUsers) { + void sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers) { if (client) { client->sendChannel(channelId, channelName, channelUsers, invitedUsers); } @@ -1408,13 +1385,12 @@ class Player final : public Creature, public Cylinder client->sendTutorial(tutorialId); } } - void sendAddMarker(const Position& pos, uint8_t markType, const std::string& desc) { + void sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc) { if (client) { client->sendAddMarker(pos, markType, desc); } } - void sendItemInspection(uint16_t itemId, uint8_t itemCount, - const Item* item, bool cyclopedia) { + void sendItemInspection(uint16_t itemId, uint8_t itemCount, const Item* item, bool cyclopedia) { if (client) { client->sendItemInspection(itemId, itemCount, item, cyclopedia); } @@ -1439,15 +1415,16 @@ class Player final : public Creature, public Cylinder client->sendCyclopediaCharacterCombatStats(); } } - void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector& entries) { + void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries) { if (client) { client->sendCyclopediaCharacterRecentDeaths(page, pages, entries); } } void sendCyclopediaCharacterRecentPvPKills( - uint16_t page, uint16_t pages, - const std::vector< - RecentPvPKillEntry>& entries) { + uint16_t page, uint16_t pages, + const std::vector< + RecentPvPKillEntry> &entries + ) { if (client) { client->sendCyclopediaCharacterRecentPvPKills(page, pages, entries); } @@ -1492,9 +1469,7 @@ class Player final : public Creature, public Cylinder client->sendHighscoresNoData(); } } - void sendHighscores(const std::vector& characters, - uint8_t categoryId, uint32_t vocationId, - uint16_t page, uint16_t pages) { + void sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages) { if (client) { client->sendHighscores(characters, categoryId, vocationId, page, pages); } @@ -1509,7 +1484,7 @@ class Player final : public Creature, public Cylinder asyncOngoingTasks &= ~(flags); } void sendTournamentLeaderboard() { - if (client) { + if (client) { client->sendTournamentLeaderboard(); } } @@ -1523,7 +1498,7 @@ class Player final : public Creature, public Cylinder client->sendFightModes(); } } - void sendNetworkMessage(const NetworkMessage& message) { + void sendNetworkMessage(const NetworkMessage &message) { if (client) { client->writeToOutputBuffer(message); } @@ -1535,18 +1510,14 @@ class Player final : public Creature, public Cylinder void sendOpenStash(bool isNpc = false) { if (client && ((getLastDepotId() != -1) || isNpc)) { - client->sendOpenStash(); + client->sendOpenStash(); } } void onThink(uint32_t interval) override; - void postAddNotification(Thing* thing, const Cylinder* oldParent, - int32_t index, - CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(Thing* thing, const Cylinder* newParent, - int32_t index, - CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void setNextAction(int64_t time) { if (time > nextAction) { @@ -1582,15 +1553,15 @@ class Player final : public Creature, public Cylinder uint32_t getNextActionTime() const; uint32_t getNextPotionActionTime() const; - Item* getWriteItem(uint32_t& windowTextId, uint16_t& maxWriteLen); + Item* getWriteItem(uint32_t &windowTextId, uint16_t &maxWriteLen); void setWriteItem(Item* item, uint16_t maxWriteLen = 0); - House* getEditHouse(uint32_t& windowTextId, uint32_t& listId); + House* getEditHouse(uint32_t &windowTextId, uint32_t &listId); void setEditHouse(House* house, uint32_t listId = 0); - void learnInstantSpell(const std::string& spellName); - void forgetInstantSpell(const std::string& spellName); - bool hasLearnedInstantSpell(const std::string& spellName) const; + void learnInstantSpell(const std::string &spellName); + void forgetInstantSpell(const std::string &spellName); + bool hasLearnedInstantSpell(const std::string &spellName) const; void updateRegeneration(); @@ -1622,7 +1593,7 @@ class Player final : public Creature, public Cylinder lastWalking = OTSYS_TIME() + value; } - const std::map& getOpenContainers() const { + const std::map &getOpenContainers() const { return openContainers; } @@ -1682,25 +1653,20 @@ class Player final : public Creature, public Cylinder return false; } - auto it = std::find(quickLootListItemIds.begin(), - quickLootListItemIds.end(), item->getID()); + auto it = std::find(quickLootListItemIds.begin(), quickLootListItemIds.end(), item->getID()); return it != quickLootListItemIds.end(); } - bool updateKillTracker(Container* corpse, - const std::string& playerName, - const Outfit_t creatureOutfit) const - { - if (client) { + bool updateKillTracker(Container* corpse, const std::string &playerName, const Outfit_t creatureOutfit) const { + if (client) { client->sendKillTrackerUpdate(corpse, playerName, creatureOutfit); return true; - } + } return false; - } + } - void updatePartyTrackerAnalyzer() const - { + void updatePartyTrackerAnalyzer() const { if (client && party) { client->updatePartyTrackerAnalyzer(party); } @@ -1708,7 +1674,7 @@ class Player final : public Creature, public Cylinder void sendLootStats(Item* item, uint8_t count) const; void updateSupplyTracker(const Item* item) const; - void updateImpactTracker(CombatType_t type, int32_t amount)const; + void updateImpactTracker(CombatType_t type, int32_t amount) const; void updateInputAnalyzer(CombatType_t type, int32_t amount, std::string target) { if (client) { @@ -1716,27 +1682,22 @@ class Player final : public Creature, public Cylinder } } - - void createLeaderTeamFinder(NetworkMessage &msg) - { - if (client) { - client->createLeaderTeamFinder(msg); - } - } - void sendLeaderTeamFinder(bool reset) - { - if (client) { - client->sendLeaderTeamFinder(reset); - } - } - void sendTeamFinderList() - { - if (client) { - client->sendTeamFinderList(); - } - } - void setItemCustomPrice(uint16_t itemId, uint64_t price) - { + void createLeaderTeamFinder(NetworkMessage &msg) { + if (client) { + client->createLeaderTeamFinder(msg); + } + } + void sendLeaderTeamFinder(bool reset) { + if (client) { + client->sendLeaderTeamFinder(reset); + } + } + void sendTeamFinderList() { + if (client) { + client->sendTeamFinderList(); + } + } + void setItemCustomPrice(uint16_t itemId, uint64_t price) { itemPriceMap[itemId] = price; } uint32_t getCharmPoints() { @@ -1770,75 +1731,151 @@ class Player final : public Creature, public Cylinder bool isImmuneCleanse(ConditionType_t conditiontype) { uint64_t timenow = OTSYS_TIME(); if ((cleanseCondition.first == conditiontype) - && (timenow <= cleanseCondition.second)) { + && (timenow <= cleanseCondition.second)) { return true; } return false; } uint16_t parseRacebyCharm(charmRune_t charmId, bool set, uint16_t newRaceid) { uint16_t raceid = 0; - switch (charmId) { - case CHARM_WOUND: - if (set) { charmRuneWound = newRaceid; } else { raceid = charmRuneWound; } - break; - case CHARM_ENFLAME: - if (set) { charmRuneEnflame = newRaceid; } else { raceid = charmRuneEnflame; } - break; - case CHARM_POISON: - if (set) { charmRunePoison = newRaceid; } else { raceid = charmRunePoison; } - break; - case CHARM_FREEZE: - if (set) { charmRuneFreeze = newRaceid; } else { raceid = charmRuneFreeze; } - break; - case CHARM_ZAP: - if (set) { charmRuneZap = newRaceid; } else { raceid = charmRuneZap; } - break; - case CHARM_CURSE: - if (set) { charmRuneCurse = newRaceid; } else { raceid = charmRuneCurse; } - break; - case CHARM_CRIPPLE: - if (set) { charmRuneCripple = newRaceid; } else { raceid = charmRuneCripple; } - break; - case CHARM_PARRY: - if (set) { charmRuneParry = newRaceid; } else { raceid = charmRuneParry; } - break; - case CHARM_DODGE: - if (set) { charmRuneDodge = newRaceid; } else { raceid = charmRuneDodge; } - break; - case CHARM_ADRENALINE: - if (set) { charmRuneAdrenaline = newRaceid; } else { raceid = charmRuneAdrenaline; } - break; - case CHARM_NUMB: - if (set) { charmRuneNumb = newRaceid; } else { raceid = charmRuneNumb; } - break; - case CHARM_CLEANSE: - if (set) { charmRuneCleanse = newRaceid; } else { raceid = charmRuneCleanse; } - break; - case CHARM_BLESS: - if (set) { charmRuneBless = newRaceid; } else { raceid = charmRuneBless; } - break; - case CHARM_SCAVENGE: - if (set) { charmRuneScavenge = newRaceid; } else { raceid = charmRuneScavenge; } - break; - case CHARM_GUT: - if (set) { charmRuneGut = newRaceid; } else { raceid = charmRuneGut; } - break; - case CHARM_LOW: - if (set) { charmRuneLowBlow = newRaceid; } else { raceid = charmRuneLowBlow; } - break; - case CHARM_DIVINE: - if (set) { charmRuneDivine = newRaceid; } else { raceid = charmRuneDivine; } - break; - case CHARM_VAMP: - if (set) { charmRuneVamp = newRaceid; } else { raceid = charmRuneVamp; } - break; - case CHARM_VOID: - if (set) { charmRuneVoid = newRaceid; } else { raceid = charmRuneVoid; } - break; - default: - raceid = 0; - break; - } + switch (charmId) { + case CHARM_WOUND: + if (set) { + charmRuneWound = newRaceid; + } else { + raceid = charmRuneWound; + } + break; + case CHARM_ENFLAME: + if (set) { + charmRuneEnflame = newRaceid; + } else { + raceid = charmRuneEnflame; + } + break; + case CHARM_POISON: + if (set) { + charmRunePoison = newRaceid; + } else { + raceid = charmRunePoison; + } + break; + case CHARM_FREEZE: + if (set) { + charmRuneFreeze = newRaceid; + } else { + raceid = charmRuneFreeze; + } + break; + case CHARM_ZAP: + if (set) { + charmRuneZap = newRaceid; + } else { + raceid = charmRuneZap; + } + break; + case CHARM_CURSE: + if (set) { + charmRuneCurse = newRaceid; + } else { + raceid = charmRuneCurse; + } + break; + case CHARM_CRIPPLE: + if (set) { + charmRuneCripple = newRaceid; + } else { + raceid = charmRuneCripple; + } + break; + case CHARM_PARRY: + if (set) { + charmRuneParry = newRaceid; + } else { + raceid = charmRuneParry; + } + break; + case CHARM_DODGE: + if (set) { + charmRuneDodge = newRaceid; + } else { + raceid = charmRuneDodge; + } + break; + case CHARM_ADRENALINE: + if (set) { + charmRuneAdrenaline = newRaceid; + } else { + raceid = charmRuneAdrenaline; + } + break; + case CHARM_NUMB: + if (set) { + charmRuneNumb = newRaceid; + } else { + raceid = charmRuneNumb; + } + break; + case CHARM_CLEANSE: + if (set) { + charmRuneCleanse = newRaceid; + } else { + raceid = charmRuneCleanse; + } + break; + case CHARM_BLESS: + if (set) { + charmRuneBless = newRaceid; + } else { + raceid = charmRuneBless; + } + break; + case CHARM_SCAVENGE: + if (set) { + charmRuneScavenge = newRaceid; + } else { + raceid = charmRuneScavenge; + } + break; + case CHARM_GUT: + if (set) { + charmRuneGut = newRaceid; + } else { + raceid = charmRuneGut; + } + break; + case CHARM_LOW: + if (set) { + charmRuneLowBlow = newRaceid; + } else { + raceid = charmRuneLowBlow; + } + break; + case CHARM_DIVINE: + if (set) { + charmRuneDivine = newRaceid; + } else { + raceid = charmRuneDivine; + } + break; + case CHARM_VAMP: + if (set) { + charmRuneVamp = newRaceid; + } else { + raceid = charmRuneVamp; + } + break; + case CHARM_VOID: + if (set) { + charmRuneVoid = newRaceid; + } else { + raceid = charmRuneVoid; + } + break; + default: + raceid = 0; + break; + } return raceid; } @@ -1846,11 +1883,10 @@ class Player final : public Creature, public Cylinder uint16_t getFreeBackpackSlots() const; // Interfaces - error_t SetAccountInterface(account::Account *account); - error_t GetAccountInterface(account::Account *account); + error_t SetAccountInterface(account::Account* account); + error_t GetAccountInterface(account::Account* account); - void sendMessageDialog(const std::string& message) const - { + void sendMessageDialog(const std::string &message) const { if (client) { client->sendMessageDialog(message); } @@ -1885,7 +1921,8 @@ class Player final : public Creature, public Cylinder PreySlot* getPreySlotById(PreySlot_t slotid) { if (auto it = std::find_if(preys.begin(), preys.end(), [slotid](const PreySlot* preyIt) { return preyIt->id == slotid; - }); it != preys.end()) { + }); + it != preys.end()) { return *it; } @@ -1951,7 +1988,8 @@ class Player final : public Creature, public Cylinder if (auto it = std::find_if(preys.begin(), preys.end(), [raceId](const PreySlot* it) { return it->selectedRaceId == raceId; - }); it != preys.end()) { + }); + it != preys.end()) { return *it; } @@ -1981,7 +2019,8 @@ class Player final : public Creature, public Cylinder TaskHuntingSlot* getTaskHuntingSlotById(PreySlot_t slotid) { if (auto it = std::find_if(taskHunting.begin(), taskHunting.end(), [slotid](const TaskHuntingSlot* itTask) { return itTask->id == slotid; - }); it != taskHunting.end()) { + }); + it != taskHunting.end()) { return *it; } @@ -1991,13 +2030,11 @@ class Player final : public Creature, public Cylinder std::vector getTaskHuntingBlackList() const { std::vector rt; - std::for_each(taskHunting.begin(), taskHunting.end(), [&rt](const TaskHuntingSlot* slot) - { + std::for_each(taskHunting.begin(), taskHunting.end(), [&rt](const TaskHuntingSlot* slot) { if (slot->isOccupied()) { rt.push_back(slot->selectedRaceId); } else { - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&rt](uint16_t raceId) - { + std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&rt](uint16_t raceId) { rt.push_back(raceId); }); } @@ -2051,7 +2088,8 @@ class Player final : public Creature, public Cylinder if (auto it = std::find_if(taskHunting.begin(), taskHunting.end(), [raceId](const TaskHuntingSlot* itTask) { return itTask->selectedRaceId == raceId; - }); it != taskHunting.end()) { + }); + it != taskHunting.end()) { return *it; } @@ -2062,10 +2100,10 @@ class Player final : public Creature, public Cylinder void requestDepotItems(); void requestDepotSearchItem(uint16_t itemId, uint8_t tier); void retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool isDepot); - void openContainerFromDepotSearch(const Position& pos); - Item* getItemFromDepotSearch(uint16_t itemId, const Position& pos); + void openContainerFromDepotSearch(const Position &pos); + Item* getItemFromDepotSearch(uint16_t itemId, const Position &pos); - std::pair, std::map>> requestLockerItems(DepotLocker *depotLocker, bool sendToClient = false, uint8_t tier = 0) const; + std::pair, std::map>> requestLockerItems(DepotLocker* depotLocker, bool sendToClient = false, uint8_t tier = 0) const; /** This function returns a pair of an array of items and a 16-bit integer from a DepotLocker instance, a 8-bit byte and a 16-bit integer. @@ -2083,7 +2121,7 @@ class Player final : public Creature, public Cylinder bool saySpell( SpeakClasses type, - const std::string& text, + const std::string &text, bool ghostMode, SpectatorHashSet* spectatorsPtr = nullptr, const Position* pos = nullptr @@ -2095,96 +2133,80 @@ class Player final : public Creature, public Cylinder void forgeResourceConversion(uint8_t action); void forgeHistory(uint8_t page) const; - void sendOpenForge() const - { - if (client) - { + void sendOpenForge() const { + if (client) { client->sendOpenForge(); } } - void sendForgeError(ReturnValue returnValue) const - { - if (client) - { + void sendForgeError(ReturnValue returnValue) const { + if (client) { client->sendForgeError(returnValue); } } void sendForgeFusionItem(uint16_t itemId, uint8_t tier, bool success, uint8_t bonus, uint8_t coreCount) const { - if (client) - { + if (client) { client->sendForgeFusionItem(itemId, tier, success, bonus, coreCount); } } void sendTransferItemTier(uint16_t firstItem, uint8_t tier, uint16_t secondItem) const { - if (client) - { + if (client) { client->sendTransferItemTier(firstItem, tier, secondItem); } } void sendForgeHistory(uint8_t page) const { - if (client) - { + if (client) { client->sendForgeHistory(page); } } - void closeForgeWindow() const - { + void closeForgeWindow() const { if (client) { client->closeForgeWindow(); } } - void setForgeDusts(uint64_t amount) - { + void setForgeDusts(uint64_t amount) { forgeDusts = amount; - if (client) - { + if (client) { client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints(), getForgeDusts()); } } - void addForgeDusts(uint64_t amount) - { + void addForgeDusts(uint64_t amount) { forgeDusts += amount; if (client) { client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints(), getForgeDusts()); } } - void removeForgeDusts(uint64_t amount) - { + void removeForgeDusts(uint64_t amount) { forgeDusts = std::max(0, forgeDusts - amount); if (client) { client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints(), getForgeDusts()); } } - uint64_t getForgeDusts() const - { + uint64_t getForgeDusts() const { return forgeDusts; } - void addForgeDustLevel(uint64_t amount) - { + void addForgeDustLevel(uint64_t amount) { forgeDustLevel += amount; if (client) { client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints(), getForgeDusts()); } } - void removeForgeDustLevel(uint64_t amount) - { + void removeForgeDustLevel(uint64_t amount) { forgeDustLevel = std::max(0, forgeDustLevel - amount); if (client) { client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints(), getForgeDusts()); } } - uint64_t getForgeDustLevel() const - { + uint64_t getForgeDustLevel() const { return forgeDustLevel; } - std::vector& getForgeHistory() { + std::vector &getForgeHistory() { return forgeHistoryVector; } - void setForgeHistory(ForgeHistory const &history) { + void setForgeHistory(const ForgeHistory &history) { forgeHistoryVector.push_back(history); } @@ -2220,22 +2242,16 @@ class Player final : public Creature, public Cylinder void death(Creature* lastHitCreature) override; bool spawn(); void despawn(); - bool dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, - bool lastHitUnjustified, bool mostDamageUnjustified) override; + bool dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; Item* getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) override; - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; - ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, - uint32_t& maxQueryCount, - uint32_t flags) const override; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, - Creature* actor = nullptr) const override; - Cylinder* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) override; - - void addThing(Thing*) override {} + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const override; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + Cylinder* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override; + + void addThing(Thing*) override { } void addThing(int32_t index, Thing* thing) override; void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override; @@ -2256,11 +2272,10 @@ class Player final : public Creature, public Cylinder // This get all player inventory items std::vector getAllInventoryItems(bool ignoreEquiped = false) const; // This function is a override function of base class - std::map& getAllItemTypeCount(std::map& countMap) const override; + std::map &getAllItemTypeCount(std::map &countMap) const override; // Function from player class with correct type sizes (uint16_t) - std::map& getAllSaleItemIdAndCount(std::map & countMap) const; - void getAllItemTypeCountAndSubtype(std::map& countMap) const; + std::map &getAllSaleItemIdAndCount(std::map &countMap) const; + void getAllItemTypeCountAndSubtype(std::map &countMap) const; Item* getForgeItemFromId(uint16_t itemId, uint8_t tier); Thing* getThing(size_t index) const override; @@ -2279,9 +2294,9 @@ class Player final : public Creature, public Cylinder std::map itemPriceMap; std::map maxValuePerSkill = { - {SKILL_LIFE_LEECH_CHANCE, 100}, - {SKILL_MANA_LEECH_CHANCE, 100}, - {SKILL_CRITICAL_HIT_CHANCE, g_configManager().getNumber(CRITICALCHANCE)} + { SKILL_LIFE_LEECH_CHANCE, 100 }, + { SKILL_MANA_LEECH_CHANCE, 100 }, + { SKILL_CRITICAL_HIT_CHANCE, g_configManager().getNumber(CRITICALCHANCE) } }; std::map rewardMap; @@ -2349,7 +2364,7 @@ class Player final : public Creature, public Cylinder Inbox* inbox; Item* imbuingItem = nullptr; Item* tradeItem = nullptr; - Item* inventory[CONST_SLOT_LAST + 1] = {}; + Item* inventory[CONST_SLOT_LAST + 1] = {}; Item* writeItem = nullptr; House* editHouse = nullptr; Npc* shopOwner = nullptr; @@ -2437,7 +2452,7 @@ class Player final : public Creature, public Cylinder uint32_t charmPoints = 0; int32_t UsedRunesBit = 0; int32_t UnlockedRunesBit = 0; - std::pair cleanseCondition = {CONDITION_NONE, 0}; + std::pair cleanseCondition = { CONDITION_NONE, 0 }; uint8_t soul = 0; uint8_t levelPercent = 0; @@ -2511,7 +2526,7 @@ class Player final : public Creature, public Cylinder return conditionSuppressions; } uint16_t getLookCorpse() const override; - void getPathSearchParams(const Creature* creature, FindPathParams& fpp) const override; + void getPathSearchParams(const Creature* creature, FindPathParams &fpp) const override; void setDead(bool isDead) { dead = isDead; @@ -2533,7 +2548,7 @@ class Player final : public Creature, public Cylinder friend class MoveEvent; friend class BedItem; - account::Account *account_; + account::Account* account_; bool hasQuiverEquipped() const; @@ -2543,11 +2558,10 @@ class Player final : public Creature, public Cylinder std::array getFinalDamageReduction() const; void calculateDamageReductionFromEquipedItems(std::array &combatReductionMap) const; - void calculateDamageReductionFromItem(std::array &combatReductionMap, Item *item) const; - void updateDamageReductionFromItemImbuement(std::array &combatReductionMap, Item *item, uint16_t combatTypeIndex) const; - void updateDamageReductionFromItemAbility(std::array &combatReductionMap, const Item *item, uint16_t combatTypeIndex) const; + void calculateDamageReductionFromItem(std::array &combatReductionMap, Item* item) const; + void updateDamageReductionFromItemImbuement(std::array &combatReductionMap, Item* item, uint16_t combatTypeIndex) const; + void updateDamageReductionFromItemAbility(std::array &combatReductionMap, const Item* item, uint16_t combatTypeIndex) const; double_t calculateDamageReduction(double_t currentTotal, int16_t resistance) const; }; - -#endif // SRC_CREATURES_PLAYERS_PLAYER_H_ +#endif // SRC_CREATURES_PLAYERS_PLAYER_H_ diff --git a/src/creatures/players/vocations/vocation.cpp b/src/creatures/players/vocations/vocation.cpp index 878f56404e9..73eed30cd28 100644 --- a/src/creatures/players/vocations/vocation.cpp +++ b/src/creatures/players/vocations/vocation.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,8 +14,7 @@ #include "utils/pugicast.h" #include "utils/tools.h" -bool Vocations::loadFromXml() -{ +bool Vocations::loadFromXml() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/vocations.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); @@ -33,9 +32,8 @@ bool Vocations::loadFromXml() uint16_t id = pugi::cast(attr.value()); - auto res = vocationsMap.emplace(std::piecewise_construct, - std::forward_as_tuple(id), std::forward_as_tuple(id)); - Vocation& voc = res.first->second; + auto res = vocationsMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(id)); + Vocation &voc = res.first->second; if ((attr = vocationNode.attribute("name"))) { voc.name = attr.as_string(); @@ -48,7 +46,7 @@ bool Vocations::loadFromXml() if ((attr = vocationNode.attribute("baseid"))) { voc.baseId = pugi::cast(attr.value()); } - + if ((attr = vocationNode.attribute("description"))) { voc.description = attr.as_string(); } @@ -122,12 +120,13 @@ bool Vocations::loadFromXml() voc.skillMultipliers[skill_id] = pugi::cast(childNode.attribute("multiplier").value()); } else { SPDLOG_WARN("[Vocations::loadFromXml] - " - "No valid skill id: {} for vocation: {}", - skill_id, voc.id); + "No valid skill id: {} for vocation: {}", + skill_id, voc.id); } } else { SPDLOG_WARN("[Vocations::loadFromXml] - " - "Missing skill id for vocation: {}", voc.id); + "Missing skill id for vocation: {}", + voc.id); } } else if (strcasecmp(childNode.name(), "formula") == 0) { pugi::xml_attribute meleeDamageAttribute = childNode.attribute("meleeDamage"); @@ -155,20 +154,19 @@ bool Vocations::loadFromXml() return true; } -Vocation* Vocations::getVocation(uint16_t id) -{ +Vocation* Vocations::getVocation(uint16_t id) { auto it = vocationsMap.find(id); if (it == vocationsMap.end()) { SPDLOG_WARN("[Vocations::getVocation] - " - "Vocation {} not found", id); + "Vocation {} not found", + id); return nullptr; } return &it->second; } -uint16_t Vocations::getVocationId(const std::string& name) const -{ - for (const auto& it : vocationsMap) { +uint16_t Vocations::getVocationId(const std::string &name) const { + for (const auto &it : vocationsMap) { if (strcasecmp(it.second.name.c_str(), name.c_str()) == 0) { return it.first; } @@ -176,9 +174,8 @@ uint16_t Vocations::getVocationId(const std::string& name) const return -1; } -uint16_t Vocations::getPromotedVocation(uint16_t vocationId) const -{ - for (const auto& it : vocationsMap) { +uint16_t Vocations::getPromotedVocation(uint16_t vocationId) const { + for (const auto &it : vocationsMap) { if (it.second.fromVocation == vocationId && it.first != vocationId) { return it.first; } @@ -186,10 +183,9 @@ uint16_t Vocations::getPromotedVocation(uint16_t vocationId) const return VOCATION_NONE; } -uint32_t Vocation::skillBase[SKILL_LAST + 1] = {50, 50, 50, 50, 30, 100, 20}; +uint32_t Vocation::skillBase[SKILL_LAST + 1] = { 50, 50, 50, 50, 30, 100, 20 }; -uint64_t Vocation::getReqSkillTries(uint8_t skill, uint16_t level) -{ +uint64_t Vocation::getReqSkillTries(uint8_t skill, uint16_t level) { if (skill > SKILL_LAST || level <= 10) { return 0; } @@ -204,8 +200,7 @@ uint64_t Vocation::getReqSkillTries(uint8_t skill, uint16_t level) return tries; } -uint64_t Vocation::getReqMana(uint32_t magLevel) -{ +uint64_t Vocation::getReqMana(uint32_t magLevel) { if (magLevel == 0) { return 0; } diff --git a/src/creatures/players/vocations/vocation.h b/src/creatures/players/vocations/vocation.h index ba9197adc3a..9004e24e463 100644 --- a/src/creatures/players/vocations/vocation.h +++ b/src/creatures/players/vocations/vocation.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_CREATURES_PLAYERS_VOCATIONS_VOCATION_H_ #define SRC_CREATURES_PLAYERS_VOCATIONS_VOCATION_H_ @@ -13,15 +13,15 @@ #include "declarations.hpp" #include "items/item.h" -class Vocation -{ +class Vocation { public: - explicit Vocation(uint16_t initId) : id(initId) {} + explicit Vocation(uint16_t initId) : + id(initId) { } - const std::string& getVocName() const { + const std::string &getVocName() const { return name; } - const std::string& getVocDescription() const { + const std::string &getVocDescription() const { return description; } uint64_t getReqSkillTries(uint8_t skill, uint16_t level); @@ -110,7 +110,7 @@ class Vocation std::string name = "none"; std::string description; - float skillMultipliers[SKILL_LAST + 1] = {1.5f, 2.0f, 2.0f, 2.0f, 2.0f, 1.5f, 1.1f}; + float skillMultipliers[SKILL_LAST + 1] = { 1.5f, 2.0f, 2.0f, 2.0f, 2.0f, 1.5f, 1.1f }; float manaMultiplier = 4.0f; uint32_t gainHealthTicks = 6; @@ -137,15 +137,14 @@ class Vocation static uint32_t skillBase[SKILL_LAST + 1]; }; -class Vocations -{ +class Vocations { public: Vocations() = default; - Vocations(Vocations const&) = delete; - void operator=(Vocations const&) = delete; + Vocations(const Vocations &) = delete; + void operator=(const Vocations &) = delete; - static Vocations& getInstance() { + static Vocations &getInstance() { // Guaranteed to be destroyed static Vocations instance; // Instantiated on first use @@ -155,8 +154,10 @@ class Vocations bool loadFromXml(); Vocation* getVocation(uint16_t id); - const std::map& getVocations() const {return vocationsMap;} - uint16_t getVocationId(const std::string& name) const; + const std::map &getVocations() const { + return vocationsMap; + } + uint16_t getVocationId(const std::string &name) const; uint16_t getPromotedVocation(uint16_t vocationId) const; private: @@ -165,4 +166,4 @@ class Vocations constexpr auto g_vocations = &Vocations::getInstance; -#endif // SRC_CREATURES_PLAYERS_VOCATIONS_VOCATION_H_ +#endif // SRC_CREATURES_PLAYERS_VOCATIONS_VOCATION_H_ diff --git a/src/database/database.cpp b/src/database/database.cpp index 1ff7790da11..5389f89eaf5 100644 --- a/src/database/database.cpp +++ b/src/database/database.cpp @@ -5,22 +5,20 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "config/configmanager.h" #include "database/database.h" -Database::~Database() -{ +Database::~Database() { if (handle != nullptr) { mysql_close(handle); } } -bool Database::connect() -{ +bool Database::connect() { // connection handle initialization handle = mysql_init(nullptr); if (!handle) { @@ -45,8 +43,7 @@ bool Database::connect() return true; } -bool Database::connect(const char *host, const char *user, const char *password, - const char *database, uint32_t port, const char *sock) { +bool Database::connect(const char* host, const char* user, const char* password, const char* database, uint32_t port, const char* sock) { // connection handle initialization handle = mysql_init(nullptr); if (!handle) { @@ -59,8 +56,7 @@ bool Database::connect(const char *host, const char *user, const char *password, mysql_options(handle, MYSQL_OPT_RECONNECT, &reconnect); // connects to database - if (!mysql_real_connect(handle, host, user, password, database, port, sock, - 0)) { + if (!mysql_real_connect(handle, host, user, password, database, port, sock, 0)) { SPDLOG_ERROR("MySQL Error Message: {}", mysql_error(handle)); return false; } @@ -72,8 +68,7 @@ bool Database::connect(const char *host, const char *user, const char *password, return true; } -bool Database::beginTransaction() -{ +bool Database::beginTransaction() { if (!executeQuery("BEGIN")) { return false; } @@ -82,8 +77,7 @@ bool Database::beginTransaction() return true; } -bool Database::rollback() -{ +bool Database::rollback() { if (!handle) { SPDLOG_ERROR("Database not initialized!"); return false; @@ -99,12 +93,11 @@ bool Database::rollback() return true; } -bool Database::commit() -{ - if (!handle) { - SPDLOG_ERROR("Database not initialized!"); - return false; - } +bool Database::commit() { + if (!handle) { + SPDLOG_ERROR("Database not initialized!"); + return false; + } if (mysql_commit(handle) != 0) { SPDLOG_ERROR("Message: {}", mysql_error(handle)); @@ -116,12 +109,11 @@ bool Database::commit() return true; } -bool Database::executeQuery(const std::string& query) -{ - if (!handle) { - SPDLOG_ERROR("Database not initialized!"); - return false; - } +bool Database::executeQuery(const std::string &query) { + if (!handle) { + SPDLOG_ERROR("Database not initialized!"); + return false; + } bool success = true; @@ -132,7 +124,7 @@ bool Database::executeQuery(const std::string& query) SPDLOG_ERROR("Query: {}", query.substr(0, 256)); SPDLOG_ERROR("Message: {}", mysql_error(handle)); auto error = mysql_errno(handle); - if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053/*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) { + if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053 /*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) { success = false; break; } @@ -149,21 +141,20 @@ bool Database::executeQuery(const std::string& query) return success; } -DBResult_ptr Database::storeQuery(const std::string& query) -{ - if (!handle) { - SPDLOG_ERROR("Database not initialized!"); - return nullptr; - } +DBResult_ptr Database::storeQuery(const std::string &query) { + if (!handle) { + SPDLOG_ERROR("Database not initialized!"); + return nullptr; + } databaseLock.lock(); - retry: +retry: while (mysql_real_query(handle, query.c_str(), query.length()) != 0) { SPDLOG_ERROR("Query: {}", query); SPDLOG_ERROR("Message: {}", mysql_error(handle)); auto error = mysql_errno(handle); - if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053/*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) { + if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053 /*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) { break; } std::this_thread::sleep_for(std::chrono::seconds(1)); @@ -176,7 +167,7 @@ DBResult_ptr Database::storeQuery(const std::string& query) SPDLOG_ERROR("Query: {}", query); SPDLOG_ERROR("Message: {}", mysql_error(handle)); auto error = mysql_errno(handle); - if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053/*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) { + if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053 /*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) { databaseLock.unlock(); return nullptr; } @@ -192,13 +183,11 @@ DBResult_ptr Database::storeQuery(const std::string& query) return result; } -std::string Database::escapeString(const std::string& s) const -{ +std::string Database::escapeString(const std::string &s) const { return escapeBlob(s.c_str(), s.length()); } -std::string Database::escapeBlob(const char* s, uint32_t length) const -{ +std::string Database::escapeBlob(const char* s, uint32_t length) const { // the worst case is 2n + 1 size_t maxLength = (length * 2) + 1; @@ -217,8 +206,7 @@ std::string Database::escapeBlob(const char* s, uint32_t length) const return escaped; } -DBResult::DBResult(MYSQL_RES* res) -{ +DBResult::DBResult(MYSQL_RES* res) { handle = res; size_t i = 0; @@ -232,13 +220,11 @@ DBResult::DBResult(MYSQL_RES* res) row = mysql_fetch_row(handle); } -DBResult::~DBResult() -{ +DBResult::~DBResult() { mysql_free_result(handle); } -std::string DBResult::getString(const std::string& s) const -{ +std::string DBResult::getString(const std::string &s) const { auto it = listNames.find(s); if (it == listNames.end()) { SPDLOG_ERROR("Column '{}' does not exist in result set", s); @@ -252,8 +238,7 @@ std::string DBResult::getString(const std::string& s) const return std::string(row[it->second]); } -const char* DBResult::getStream(const std::string& s, unsigned long& size) const -{ +const char* DBResult::getStream(const std::string &s, unsigned long &size) const { auto it = listNames.find(s); if (it == listNames.end()) { SPDLOG_ERROR("Column '{}' doesn't exist in the result set", s); @@ -270,8 +255,7 @@ const char* DBResult::getStream(const std::string& s, unsigned long& size) const return row[it->second]; } -uint8_t DBResult::getU8FromString(const std::string &string, const std::string &function) const -{ +uint8_t DBResult::getU8FromString(const std::string &string, const std::string &function) const { auto result = static_cast(std::atoi(string.c_str())); if (result > std::numeric_limits::max()) { SPDLOG_ERROR("[{}] Failed to get number value {} for tier table result, on function call: {}", __FUNCTION__, result, function); @@ -281,8 +265,7 @@ uint8_t DBResult::getU8FromString(const std::string &string, const std::string & return result; } -int8_t DBResult::getInt8FromString(const std::string &string, const std::string &function) const -{ +int8_t DBResult::getInt8FromString(const std::string &string, const std::string &function) const { auto result = static_cast(std::atoi(string.c_str())); if (result > std::numeric_limits::max()) { SPDLOG_ERROR("[{}] Failed to get number value {} for tier table result, on function call: {}", __FUNCTION__, result, function); @@ -292,33 +275,29 @@ int8_t DBResult::getInt8FromString(const std::string &string, const std::string return result; } -size_t DBResult::countResults() const -{ +size_t DBResult::countResults() const { return static_cast(mysql_num_rows(handle)); } -bool DBResult::hasNext() const -{ +bool DBResult::hasNext() const { return row != nullptr; } -bool DBResult::next() -{ - if (!handle) { - SPDLOG_ERROR("Database not initialized!"); - return false; - } +bool DBResult::next() { + if (!handle) { + SPDLOG_ERROR("Database not initialized!"); + return false; + } row = mysql_fetch_row(handle); return row != nullptr; } -DBInsert::DBInsert(std::string insertQuery) : query(std::move(insertQuery)) -{ +DBInsert::DBInsert(std::string insertQuery) : + query(std::move(insertQuery)) { this->length = this->query.length(); } -bool DBInsert::addRow(const std::string& row) -{ +bool DBInsert::addRow(const std::string &row) { // adds new row to buffer const size_t rowLength = row.length(); length += rowLength; @@ -341,15 +320,13 @@ bool DBInsert::addRow(const std::string& row) return true; } -bool DBInsert::addRow(std::ostringstream& row) -{ +bool DBInsert::addRow(std::ostringstream &row) { bool ret = addRow(row.str()); row.str(std::string()); return ret; } -bool DBInsert::execute() -{ +bool DBInsert::execute() { if (values.empty()) { return true; } diff --git a/src/database/database.h b/src/database/database.h index e8e8bf38eea..c9fa09f7ce7 100644 --- a/src/database/database.h +++ b/src/database/database.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_DATABASE_DATABASE_H_ #define SRC_DATABASE_DATABASE_H_ @@ -15,17 +15,16 @@ class DBResult; using DBResult_ptr = std::shared_ptr; -class Database -{ +class Database { public: Database() = default; ~Database(); // Singleton - ensures we don't accidentally copy it. - Database(const Database&) = delete; - Database& operator=(const Database&) = delete; + Database(const Database &) = delete; + Database &operator=(const Database &) = delete; - static Database& getInstance() { + static Database &getInstance() { // Guaranteed to be destroyed. static Database instance; // Instantiated on first use. @@ -34,14 +33,13 @@ class Database bool connect(); - bool connect(const char *host, const char *user, const char *password, - const char *database, uint32_t port, const char *sock); + bool connect(const char* host, const char* user, const char* password, const char* database, uint32_t port, const char* sock); - bool executeQuery(const std::string& query); + bool executeQuery(const std::string &query); - DBResult_ptr storeQuery(const std::string& query); + DBResult_ptr storeQuery(const std::string &query); - std::string escapeString(const std::string& s) const; + std::string escapeString(const std::string &s) const; std::string escapeBlob(const char* s, uint32_t length) const; @@ -67,132 +65,108 @@ class Database std::recursive_mutex databaseLock; uint64_t maxPacketSize = 1048576; - friend class DBTransaction; + friend class DBTransaction; }; -class DBResult -{ +class DBResult { public: - explicit DBResult(MYSQL_RES *res); - ~DBResult(); - - // Non copyable - DBResult(const DBResult &) = delete; - DBResult &operator=(const DBResult &) = delete; - - template < typename T> - T getNumber(const std::string &s) const - { - auto it = listNames.find(s); - if (it == listNames.end()) - { - SPDLOG_ERROR("[DBResult::getNumber] - Column '{}' doesn't exist in the result set", s); - return T(); - } + explicit DBResult(MYSQL_RES* res); + ~DBResult(); + + // Non copyable + DBResult(const DBResult &) = delete; + DBResult &operator=(const DBResult &) = delete; + + template + T getNumber(const std::string &s) const { + auto it = listNames.find(s); + if (it == listNames.end()) { + SPDLOG_ERROR("[DBResult::getNumber] - Column '{}' doesn't exist in the result set", s); + return T(); + } - if (row[it->second] == nullptr) - { - return T(); - } + if (row[it->second] == nullptr) { + return T(); + } - T data = 0; - try - { - // Check if the type T is signed or unsigned - if constexpr(std::is_signed_v) - { - // Check if the type T is int8_t or int16_t - if constexpr(std::is_same_v || std::is_same_v) - { - // Use std::stoi to convert string to int8_t + T data = 0; + try { + // Check if the type T is signed or unsigned + if constexpr (std::is_signed_v) { + // Check if the type T is int8_t or int16_t + if constexpr (std::is_same_v || std::is_same_v) { + // Use std::stoi to convert string to int8_t + data = static_cast(std::stoi(row[it->second])); + } + // Check if the type T is int32_t + else if constexpr (std::is_same_v) { + // Use std::stol to convert string to int32_t + data = static_cast(std::stol(row[it->second])); + } + // Check if the type T is int64_t + else if constexpr (std::is_same_v) { + // Use std::stoll to convert string to int64_t + data = static_cast(std::stoll(row[it->second])); + } else { + // Throws exception indicating that type T is invalid + SPDLOG_ERROR("Invalid signed type T"); + } + } else if (std::is_same::value) { data = static_cast(std::stoi(row[it->second])); + } else { + // Check if the type T is uint8_t or uint16_t or uint32_t + if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) { + // Use std::stoul to convert string to uint8_t + data = static_cast(std::stoul(row[it->second])); + } + // Check if the type T is uint64_t + else if constexpr (std::is_same_v) { + // Use std::stoull to convert string to uint64_t + data = static_cast(std::stoull(row[it->second])); + } else { + // Send log indicating that type T is invalid + SPDLOG_ERROR("Column '{}' has an invalid unsigned T is invalid", s); + } } - // Check if the type T is int32_t - else if constexpr(std::is_same_v) - { - // Use std::stol to convert string to int32_t - data = static_cast(std::stol(row[it->second])); - } - // Check if the type T is int64_t - else if constexpr(std::is_same_v) - { - // Use std::stoll to convert string to int64_t - data = static_cast(std::stoll(row[it->second])); - } - else - { - // Throws exception indicating that type T is invalid - SPDLOG_ERROR("Invalid signed type T"); - } - } - else if (std::is_same::value) - { - data = static_cast(std::stoi(row[it->second])); + } catch (std::invalid_argument &e) { + // Value of string is invalid + SPDLOG_ERROR("Column '{}' has an invalid value set, error code: {}", s, e.what()); + data = T(); + } catch (std::out_of_range &e) { + // Value of string is too large to fit the range allowed by type T + SPDLOG_ERROR("Column '{}' has a value out of range, error code: {}", s, e.what()); + data = T(); } - else - { - // Check if the type T is uint8_t or uint16_t or uint32_t - if constexpr(std::is_same_v || std::is_same_v || std::is_same_v) - { - // Use std::stoul to convert string to uint8_t - data = static_cast(std::stoul(row[it->second])); - } - // Check if the type T is uint64_t - else if constexpr(std::is_same_v) - { - // Use std::stoull to convert string to uint64_t - data = static_cast(std::stoull(row[it->second])); - } - else - { - // Send log indicating that type T is invalid - SPDLOG_ERROR("Column '{}' has an invalid unsigned T is invalid", s); - } - } - } - catch (std::invalid_argument &e) - { - // Value of string is invalid - SPDLOG_ERROR("Column '{}' has an invalid value set, error code: {}", s, e.what()); - data = T(); - } - catch (std::out_of_range &e) - { - // Value of string is too large to fit the range allowed by type T - SPDLOG_ERROR("Column '{}' has a value out of range, error code: {}", s, e.what()); - data = T(); - } - return data; - } + return data; + } - std::string getString(const std::string &s) const; - const char *getStream(const std::string &s, unsigned long &size) const; - uint8_t getU8FromString(const std::string &string, const std::string &function) const; - int8_t getInt8FromString(const std::string &string, const std::string &function) const; + std::string getString(const std::string &s) const; + const char* getStream(const std::string &s, unsigned long &size) const; + uint8_t getU8FromString(const std::string &string, const std::string &function) const; + int8_t getInt8FromString(const std::string &string, const std::string &function) const; - size_t countResults() const; - bool hasNext() const; - bool next(); + size_t countResults() const; + bool hasNext() const; + bool next(); private: - MYSQL_RES * handle; - MYSQL_ROW row; + MYSQL_RES* handle; + MYSQL_ROW row; - std::map listNames; + std::map listNames; - friend class Database; + friend class Database; }; /** * INSERT statement. */ -class DBInsert -{ +class DBInsert { public: explicit DBInsert(std::string query); - bool addRow(const std::string& row); - bool addRow(std::ostringstream& row); + bool addRow(const std::string &row); + bool addRow(std::ostringstream &row); bool execute(); private: @@ -201,8 +175,7 @@ class DBInsert size_t length; }; -class DBTransaction -{ +class DBTransaction { public: constexpr DBTransaction() = default; @@ -217,8 +190,8 @@ class DBTransaction } // non-copyable - DBTransaction(const DBTransaction&) = delete; - DBTransaction& operator=(const DBTransaction&) = delete; + DBTransaction(const DBTransaction &) = delete; + DBTransaction &operator=(const DBTransaction &) = delete; bool begin() { state = STATE_START; @@ -238,4 +211,4 @@ class DBTransaction TransactionStates_t state = STATE_NO_START; }; -#endif // SRC_DATABASE_DATABASE_H_ +#endif // SRC_DATABASE_DATABASE_H_ diff --git a/src/database/database_definitions.hpp b/src/database/database_definitions.hpp index 668bf9f426d..33ac8cf3c67 100644 --- a/src/database/database_definitions.hpp +++ b/src/database/database_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_DATABASE_DATABASE_DEFINITIONS_HPP_ #define SRC_DATABASE_DATABASE_DEFINITIONS_HPP_ @@ -17,4 +17,4 @@ enum TransactionStates_t { STATE_COMMIT, }; -#endif // SRC_DATABASE_DATABASE_DEFINITIONS_HPP_ +#endif // SRC_DATABASE_DATABASE_DEFINITIONS_HPP_ diff --git a/src/database/databasemanager.cpp b/src/database/databasemanager.cpp index 8739d5f453a..f38eac94d3f 100644 --- a/src/database/databasemanager.cpp +++ b/src/database/databasemanager.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,10 +14,8 @@ #include "lua/functions/core/libs/core_libs_functions.hpp" #include "lua/scripts/luascript.h" - -bool DatabaseManager::optimizeTables() -{ - Database& db = Database::getInstance(); +bool DatabaseManager::optimizeTables() { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB)) << " AND `DATA_FREE` > 0"; @@ -45,27 +43,24 @@ bool DatabaseManager::optimizeTables() return true; } -bool DatabaseManager::tableExists(const std::string& tableName) -{ - Database& db = Database::getInstance(); +bool DatabaseManager::tableExists(const std::string &tableName) { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB)) << " AND `TABLE_NAME` = " << db.escapeString(tableName) << " LIMIT 1"; return db.storeQuery(query.str()).get() != nullptr; } -bool DatabaseManager::isDatabaseSetup() -{ - Database& db = Database::getInstance(); +bool DatabaseManager::isDatabaseSetup() { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB)); return db.storeQuery(query.str()).get() != nullptr; } -int32_t DatabaseManager::getDatabaseVersion() -{ +int32_t DatabaseManager::getDatabaseVersion() { if (!tableExists("server_config")) { - Database& db = Database::getInstance(); + Database &db = Database::getInstance(); db.executeQuery("CREATE TABLE `server_config` (`config` VARCHAR(50) NOT NULL, `value` VARCHAR(256) NOT NULL DEFAULT '', UNIQUE(`config`)) ENGINE = InnoDB"); db.executeQuery("INSERT INTO `server_config` VALUES ('db_version', 0)"); return 0; @@ -78,8 +73,7 @@ int32_t DatabaseManager::getDatabaseVersion() return -1; } -void DatabaseManager::updateDatabase() -{ +void DatabaseManager::updateDatabase() { lua_State* L = luaL_newstate(); if (!L) { return; @@ -94,8 +88,9 @@ void DatabaseManager::updateDatabase() std::ostringstream ss; ss << g_configManager().getString(DATA_DIRECTORY) + "/migrations/" << version << ".lua"; if (luaL_dofile(L, ss.str().c_str()) != 0) { - SPDLOG_ERROR("DatabaseManager::updateDatabase - Version: {}""] {}", - version, lua_tostring(L, -1)); + SPDLOG_ERROR("DatabaseManager::updateDatabase - Version: {}" + "] {}", + version, lua_tostring(L, -1)); break; } @@ -106,8 +101,7 @@ void DatabaseManager::updateDatabase() lua_getglobal(L, "onUpdateDatabase"); if (lua_pcall(L, 0, 1, 0) != 0) { LuaScriptInterface::resetScriptEnv(); - SPDLOG_WARN("[DatabaseManager::updateDatabase - Version: {}] {}", - version, lua_tostring(L, -1)); + SPDLOG_WARN("[DatabaseManager::updateDatabase - Version: {}] {}", version, lua_tostring(L, -1)); break; } @@ -125,9 +119,8 @@ void DatabaseManager::updateDatabase() lua_close(L); } -bool DatabaseManager::getDatabaseConfig(const std::string& config, int32_t& value) -{ - Database& db = Database::getInstance(); +bool DatabaseManager::getDatabaseConfig(const std::string &config, int32_t &value) { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `value` FROM `server_config` WHERE `config` = " << db.escapeString(config); @@ -140,9 +133,8 @@ bool DatabaseManager::getDatabaseConfig(const std::string& config, int32_t& valu return true; } -void DatabaseManager::registerDatabaseConfig(const std::string& config, int32_t value) -{ - Database& db = Database::getInstance(); +void DatabaseManager::registerDatabaseConfig(const std::string &config, int32_t value) { + Database &db = Database::getInstance(); std::ostringstream query; int32_t tmp; diff --git a/src/database/databasemanager.h b/src/database/databasemanager.h index f483c773aed..b310cd9ba18 100644 --- a/src/database/databasemanager.h +++ b/src/database/databasemanager.h @@ -5,17 +5,16 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_DATABASE_DATABASEMANAGER_H_ #define SRC_DATABASE_DATABASEMANAGER_H_ #include "database/database.h" -class DatabaseManager -{ +class DatabaseManager { public: - static bool tableExists(const std::string& table); + static bool tableExists(const std::string &table); static int32_t getDatabaseVersion(); static bool isDatabaseSetup(); @@ -23,7 +22,7 @@ class DatabaseManager static bool optimizeTables(); static void updateDatabase(); - static bool getDatabaseConfig(const std::string& config, int32_t& value); - static void registerDatabaseConfig(const std::string& config, int32_t value); + static bool getDatabaseConfig(const std::string &config, int32_t &value); + static void registerDatabaseConfig(const std::string &config, int32_t value); }; -#endif // SRC_DATABASE_DATABASEMANAGER_H_ +#endif // SRC_DATABASE_DATABASEMANAGER_H_ diff --git a/src/database/databasetasks.cpp b/src/database/databasetasks.cpp index ea4c7752be2..baec0d06efc 100644 --- a/src/database/databasetasks.cpp +++ b/src/database/databasetasks.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,34 +13,31 @@ #include "game/scheduling/tasks.h" DatabaseTasks::DatabaseTasks() { - db_ = &Database::getInstance(); + db_ = &Database::getInstance(); } -bool DatabaseTasks::SetDatabaseInterface(Database *database) { - if (database == nullptr) { - return false; - } +bool DatabaseTasks::SetDatabaseInterface(Database* database) { + if (database == nullptr) { + return false; + } - db_ = database; - return true; + db_ = database; + return true; } -void DatabaseTasks::start() -{ - if (db_ == nullptr) { - return; - } +void DatabaseTasks::start() { + if (db_ == nullptr) { + return; + } db_->connect(); ThreadHolder::start(); } -void DatabaseTasks::startThread() -{ +void DatabaseTasks::startThread() { ThreadHolder::start(); } -void DatabaseTasks::threadMain() -{ +void DatabaseTasks::threadMain() { std::unique_lock taskLockUnique(taskLock, std::defer_lock); while (getState() != THREAD_STATE_TERMINATED) { taskLockUnique.lock(); @@ -64,8 +61,7 @@ void DatabaseTasks::threadMain() } } -void DatabaseTasks::addTask(std::string query, std::function callback/* = nullptr*/, bool store/* = false*/) -{ +void DatabaseTasks::addTask(std::string query, std::function callback /* = nullptr*/, bool store /* = false*/) { bool signal = false; taskLock.lock(); if (getState() == THREAD_STATE_RUNNING) { @@ -79,12 +75,11 @@ void DatabaseTasks::addTask(std::string query, std::functionstoreQuery(task.query); @@ -99,9 +94,8 @@ void DatabaseTasks::runTask(const DatabaseTask& task) } } -void DatabaseTasks::flush() -{ - std::unique_lock guard{ taskLock }; +void DatabaseTasks::flush() { + std::unique_lock guard { taskLock }; if (!tasks.empty()) { flushTasks = true; flushSignal.wait(guard, [this] { @@ -111,8 +105,7 @@ void DatabaseTasks::flush() } } -void DatabaseTasks::shutdown() -{ +void DatabaseTasks::shutdown() { taskLock.lock(); setState(THREAD_STATE_TERMINATED); taskLock.unlock(); diff --git a/src/database/databasetasks.h b/src/database/databasetasks.h index 6f35eb4ef37..ef344b06814 100644 --- a/src/database/databasetasks.h +++ b/src/database/databasetasks.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_DATABASE_DATABASETASKS_H_ #define SRC_DATABASE_DATABASETASKS_H_ @@ -14,31 +14,30 @@ #include "utils/thread_holder_base.h" struct DatabaseTask { - DatabaseTask(std::string&& initQuery, std::function&& initCallback, bool initStore) : - query(std::move(initQuery)), callback(std::move(initCallback)), store(initStore) {} + DatabaseTask(std::string &&initQuery, std::function &&initCallback, bool initStore) : + query(std::move(initQuery)), callback(std::move(initCallback)), store(initStore) { } - std::string query; - std::function callback; - bool store; + std::string query; + std::function callback; + bool store; }; -class DatabaseTasks : public ThreadHolder -{ +class DatabaseTasks : public ThreadHolder { public: DatabaseTasks(); // non-copyable - DatabaseTasks(DatabaseTasks const&) = delete; - void operator=(DatabaseTasks const&) = delete; + DatabaseTasks(const DatabaseTasks &) = delete; + void operator=(const DatabaseTasks &) = delete; - static DatabaseTasks& getInstance() { + static DatabaseTasks &getInstance() { // Guaranteed to be destroyed static DatabaseTasks instance; // Instantiated on first use return instance; } - bool SetDatabaseInterface(Database *database); + bool SetDatabaseInterface(Database* database); void start(); void startThread(); void flush(); @@ -47,10 +46,11 @@ class DatabaseTasks : public ThreadHolder void addTask(std::string query, std::function callback = nullptr, bool store = false); void threadMain(); + private: - void runTask(const DatabaseTask& task); + void runTask(const DatabaseTask &task); - Database *db_; + Database* db_; std::thread thread; std::list tasks; std::mutex taskLock; @@ -61,4 +61,4 @@ class DatabaseTasks : public ThreadHolder constexpr auto g_databaseTasks = &DatabaseTasks::getInstance; -#endif // SRC_DATABASE_DATABASETASKS_H_ +#endif // SRC_DATABASE_DATABASETASKS_H_ diff --git a/src/declarations.hpp b/src/declarations.hpp index 9c7ed475fbd..14f94a715cd 100644 --- a/src/declarations.hpp +++ b/src/declarations.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_DECLARATIONS_HPP_ #define SRC_DECLARATIONS_HPP_ @@ -22,4 +22,4 @@ #include "server/server_definitions.hpp" #include "utils/utils_definitions.hpp" -#endif // SRC_DECLARATIONS_HPP_ +#endif // SRC_DECLARATIONS_HPP_ diff --git a/src/enums/item_attribute.hpp b/src/enums/item_attribute.hpp index 93e81e2bc55..57bfd12287b 100644 --- a/src/enums/item_attribute.hpp +++ b/src/enums/item_attribute.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ENUMS_HPP #define SRC_ENUMS_HPP @@ -53,4 +53,4 @@ enum ItemDecayState_t : uint8_t { DECAYING_STOPPING, }; -#endif // SRC_ENUMS_HPP +#endif // SRC_ENUMS_HPP diff --git a/src/game/functions/game_reload.cpp b/src/game/functions/game_reload.cpp index 54c7b70d466..d7425f1ce38 100644 --- a/src/game/functions/game_reload.cpp +++ b/src/game/functions/game_reload.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -21,41 +21,54 @@ GameReload::GameReload() = default; GameReload::~GameReload() = default; -bool GameReload::init(Reload_t reloadTypes) const -{ +bool GameReload::init(Reload_t reloadTypes) const { switch (reloadTypes) { - case Reload_t::RELOAD_TYPE_ALL : return reloadAll(); - case Reload_t::RELOAD_TYPE_CHAT : return reloadChat(); - case Reload_t::RELOAD_TYPE_CONFIG : return reloadConfig(); - case Reload_t::RELOAD_TYPE_EVENTS : return reloadEvents(); - case Reload_t::RELOAD_TYPE_CORE : return reloadCore(); - case Reload_t::RELOAD_TYPE_IMBUEMENTS : return reloadImbuements(); - case Reload_t::RELOAD_TYPE_ITEMS : return reloadItems(); - case Reload_t::RELOAD_TYPE_MODULES : return reloadModules(); - case Reload_t::RELOAD_TYPE_MONSTERS : return reloadMonsters(); - case Reload_t::RELOAD_TYPE_MOUNTS : return reloadMounts(); - case Reload_t::RELOAD_TYPE_NPCS : return reloadNpcs(); - case Reload_t::RELOAD_TYPE_RAIDS : return reloadRaids(); - case Reload_t::RELOAD_TYPE_SCRIPTS : return reloadScripts(); - case Reload_t::RELOAD_TYPE_TALKACTION : return reloadTalkaction(); - case Reload_t::RELOAD_TYPE_GROUPS : return reloadGroups(); - default : return false; + case Reload_t::RELOAD_TYPE_ALL: + return reloadAll(); + case Reload_t::RELOAD_TYPE_CHAT: + return reloadChat(); + case Reload_t::RELOAD_TYPE_CONFIG: + return reloadConfig(); + case Reload_t::RELOAD_TYPE_EVENTS: + return reloadEvents(); + case Reload_t::RELOAD_TYPE_CORE: + return reloadCore(); + case Reload_t::RELOAD_TYPE_IMBUEMENTS: + return reloadImbuements(); + case Reload_t::RELOAD_TYPE_ITEMS: + return reloadItems(); + case Reload_t::RELOAD_TYPE_MODULES: + return reloadModules(); + case Reload_t::RELOAD_TYPE_MONSTERS: + return reloadMonsters(); + case Reload_t::RELOAD_TYPE_MOUNTS: + return reloadMounts(); + case Reload_t::RELOAD_TYPE_NPCS: + return reloadNpcs(); + case Reload_t::RELOAD_TYPE_RAIDS: + return reloadRaids(); + case Reload_t::RELOAD_TYPE_SCRIPTS: + return reloadScripts(); + case Reload_t::RELOAD_TYPE_TALKACTION: + return reloadTalkaction(); + case Reload_t::RELOAD_TYPE_GROUPS: + return reloadGroups(); + default: + return false; } } -uint8_t GameReload::getReloadNumber(Reload_t reloadTypes) const -{ +uint8_t GameReload::getReloadNumber(Reload_t reloadTypes) const { return magic_enum::enum_integer(reloadTypes); } /* -* From here down have the private members functions -* These should only be used within the class itself -* If it is necessary to call elsewhere, seriously think about creating a function that calls this -* Changing this to public may cause some unexpected behavior or bug -*/ -bool GameReload::reloadAll() const -{ + * From here down have the private members functions + * These should only be used within the class itself + * If it is necessary to call elsewhere, seriously think about creating a function that calls this + * Changing this to public may cause some unexpected behavior or bug + */ +bool GameReload::reloadAll() const { std::vector reloadResults; reloadResults.reserve(magic_enum::enum_count()); @@ -70,26 +83,21 @@ bool GameReload::reloadAll() const return std::ranges::any_of(reloadResults, [](bool result) { return result; }); } -bool GameReload::reloadChat() const -{ +bool GameReload::reloadChat() const { return g_chat().load(); } -bool GameReload::reloadConfig() const -{ +bool GameReload::reloadConfig() const { return g_configManager().reload(); } -bool GameReload::reloadEvents() const -{ +bool GameReload::reloadEvents() const { return g_events().loadFromXml(); } -bool GameReload::reloadCore() const -{ +bool GameReload::reloadCore() const { if (auto coreFolder = g_configManager().getString(CORE_DIRECTORY); - g_luaEnvironment.loadFile(coreFolder + "/core.lua", "core.lua") == 0) - { + g_luaEnvironment.loadFile(coreFolder + "/core.lua", "core.lua") == 0) { // Reload scripts lib if (!g_scripts().loadScripts("scripts/lib", true, false)) { return false; @@ -100,23 +108,19 @@ bool GameReload::reloadCore() const return false; } -bool GameReload::reloadImbuements() const -{ +bool GameReload::reloadImbuements() const { return g_imbuements().reload(); } -bool GameReload::reloadItems() const -{ +bool GameReload::reloadItems() const { return Item::items.reload(); } -bool GameReload::reloadModules() const -{ +bool GameReload::reloadModules() const { return g_modules().reload(); } -bool GameReload::reloadMonsters() const -{ +bool GameReload::reloadMonsters() const { // Resets monster spells to prevent the spell from being incorrectly cleared from memory if (!g_scripts().loadScripts("scripts/lib", true, false)) { return false; @@ -128,23 +132,19 @@ bool GameReload::reloadMonsters() const return false; } -bool GameReload::reloadMounts() const -{ +bool GameReload::reloadMounts() const { return g_game().mounts.reload(); } -bool GameReload::reloadNpcs() const -{ +bool GameReload::reloadNpcs() const { return g_npcs().reload(); } -bool GameReload::reloadRaids() const -{ +bool GameReload::reloadRaids() const { return g_game().raids.reload() && g_game().raids.startup(); } -bool GameReload::reloadScripts() const -{ +bool GameReload::reloadScripts() const { // Resets monster spells to prevent the spell from being incorrectly cleared from memory if (!g_scripts().loadScripts("scripts/lib", true, false)) { return false; @@ -157,17 +157,14 @@ bool GameReload::reloadScripts() const return false; } -bool GameReload::reloadTalkaction() const -{ +bool GameReload::reloadTalkaction() const { if (auto coreFolder = g_configManager().getString(CORE_DIRECTORY); - g_luaEnvironment.loadFile(coreFolder + "/scripts/talkactions.lua", "talkactions.lua") == 0) - { + g_luaEnvironment.loadFile(coreFolder + "/scripts/talkactions.lua", "talkactions.lua") == 0) { return true; } return false; } -bool GameReload::reloadGroups() const -{ +bool GameReload::reloadGroups() const { return g_game().groups.reload(); } diff --git a/src/game/functions/game_reload.hpp b/src/game/functions/game_reload.hpp index 4bd535cf0b6..6bace6809d5 100644 --- a/src/game/functions/game_reload.hpp +++ b/src/game/functions/game_reload.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_FUNCTIONS_GAME_RELOAD_HPP_ #define SRC_GAME_FUNCTIONS_GAME_RELOAD_HPP_ @@ -36,37 +36,36 @@ enum class Reload_t : uint8_t { RELOAD_TYPE_LAST }; -class GameReload : public Game -{ -public: - GameReload(); - ~GameReload(); +class GameReload : public Game { + public: + GameReload(); + ~GameReload(); - // non-copyable - GameReload(const GameReload&) = delete; - GameReload &operator = (const GameReload&) = delete; + // non-copyable + GameReload(const GameReload &) = delete; + GameReload &operator=(const GameReload &) = delete; - bool init(Reload_t reloadType) const; - uint8_t getReloadNumber(Reload_t reloadTypes) const; + bool init(Reload_t reloadType) const; + uint8_t getReloadNumber(Reload_t reloadTypes) const; -private: - bool reloadAll() const; - bool reloadChat() const; - bool reloadConfig() const; - bool reloadEvents() const; - bool reloadCore() const; - bool reloadImbuements() const; - bool reloadItems() const; - bool reloadModules() const; - bool reloadMonsters() const; - bool reloadMounts() const; - bool reloadNpcs() const; - bool reloadRaids() const; - bool reloadScripts() const; - bool reloadTalkaction() const; - bool reloadGroups() const; + private: + bool reloadAll() const; + bool reloadChat() const; + bool reloadConfig() const; + bool reloadEvents() const; + bool reloadCore() const; + bool reloadImbuements() const; + bool reloadItems() const; + bool reloadModules() const; + bool reloadMonsters() const; + bool reloadMounts() const; + bool reloadNpcs() const; + bool reloadRaids() const; + bool reloadScripts() const; + bool reloadTalkaction() const; + bool reloadGroups() const; }; const inline GameReload g_gameReload; -#endif // SRC_GAME_FUNCTIONS_GAME_RELOAD_HPP_ +#endif // SRC_GAME_FUNCTIONS_GAME_RELOAD_HPP_ diff --git a/src/game/game.cpp b/src/game/game.cpp index f2915405a02..1fa93d66911 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -38,8 +38,7 @@ #include "server/network/webhook/webhook.h" #include "protobuf/appearances.pb.h" -Game::Game() -{ +Game::Game() { offlineTrainingWindow.choices.emplace_back("Sword Fighting and Shielding", SKILL_SWORD); offlineTrainingWindow.choices.emplace_back("Axe Fighting and Shielding", SKILL_AXE); offlineTrainingWindow.choices.emplace_back("Club Fighting and Shielding", SKILL_CLUB); @@ -52,19 +51,18 @@ Game::Game() offlineTrainingWindow.priority = true; } -Game::~Game() -{ - for (const auto& it : guilds) { +Game::~Game() { + for (const auto &it : guilds) { delete it.second; } - for (const auto& it : CharmList) { + for (const auto &it : CharmList) { delete it; } } -void Game::resetMonsters() const{ - for (const auto& [monsterId, monster] : getMonsters()) { +void Game::resetMonsters() const { + for (const auto &[monsterId, monster] : getMonsters()) { monster->clearTargetList(); monster->clearFriendList(); } @@ -72,29 +70,28 @@ void Game::resetMonsters() const{ void Game::resetNpcs() const { // Close shop window from all npcs and reset the shopPlayerSet - for (const auto& [npcId, npc] : getNpcs()) { + for (const auto &[npcId, npc] : getNpcs()) { npc->closeAllShopWindows(); npc->resetPlayerInteractions(); } } -void Game::loadBoostedCreature() -{ - Database& db = Database::getInstance(); +void Game::loadBoostedCreature() { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `boosted_creature`"; DBResult_ptr result = db.storeQuery(query.str()); if (!result) { SPDLOG_WARN("[Game::loadBoostedCreature] - " - "Failed to detect boosted creature database. (CODE 01)"); + "Failed to detect boosted creature database. (CODE 01)"); return; } uint16_t date = result->getNumber("date"); std::string name = ""; time_t now = time(0); - tm *ltm = localtime(&now); + tm* ltm = localtime(&now); uint8_t today = ltm->tm_mday; if (date == today) { name = result->getString("boostname"); @@ -135,7 +132,7 @@ void Game::loadBoostedCreature() if (!db.executeQuery(query.str())) { SPDLOG_WARN("[Game::loadBoostedCreature] - " - "Failed to detect boosted creature database. (CODE 02)"); + "Failed to detect boosted creature database. (CODE 02)"); return; } } @@ -143,8 +140,7 @@ void Game::loadBoostedCreature() SPDLOG_INFO("Boosted creature: {}", name); } -void Game::start(ServiceManager* manager) -{ +void Game::start(ServiceManager* manager) { serviceManager = manager; time_t now = time(0); @@ -160,20 +156,17 @@ void Game::start(ServiceManager* manager) g_scheduler().addEvent(createSchedulerTask(EVENT_MS + 1000, std::bind_front(&Game::createInfluencedMonsters, this))); } -GameState_t Game::getGameState() const -{ +GameState_t Game::getGameState() const { return gameState; } -void Game::setWorldType(WorldType_t type) -{ +void Game::setWorldType(WorldType_t type) { worldType = type; } -void Game::setGameState(GameState_t newState) -{ +void Game::setGameState(GameState_t newState) { if (gameState == GAME_STATE_SHUTDOWN) { - return; //this cannot be stopped + return; // this cannot be stopped } if (gameState == newState) { @@ -211,7 +204,7 @@ void Game::setGameState(GameState_t newState) case GAME_STATE_SHUTDOWN: { g_globalEvents().execute(GLOBALEVENT_SHUTDOWN); - //kick all players that are still online + // kick all players that are still online auto it = players.begin(); while (it != players.end()) { it->second->removePlayer(true); @@ -222,7 +215,8 @@ void Game::setGameState(GameState_t newState) saveGameState(); g_dispatcher().addTask( - createTask(std::bind(&Game::shutdown, this))); + createTask(std::bind(&Game::shutdown, this)) + ); g_scheduler().stop(); g_databaseTasks().stop(); @@ -251,20 +245,19 @@ void Game::setGameState(GameState_t newState) } } -void Game::saveGameState() -{ +void Game::saveGameState() { if (gameState == GAME_STATE_NORMAL) { setGameState(GAME_STATE_MAINTAIN); } SPDLOG_INFO("Saving server..."); - for (const auto& it : players) { + for (const auto &it : players) { it.second->loginPosition = it.second->getPosition(); IOLoginData::savePlayer(it.second); } - for (const auto& it : guilds) { + for (const auto &it : guilds) { IOGuild::saveGuild(it.second); } @@ -277,13 +270,12 @@ void Game::saveGameState() } } -bool Game::loadItemsPrice() -{ +bool Game::loadItemsPrice() { itemsSaleCount = 0; std::ostringstream query, marketQuery; query << "SELECT DISTINCT `itemtype` FROM `market_offers`;"; - Database& db = Database::getInstance(); + Database &db = Database::getInstance(); DBResult_ptr result = db.storeQuery(query.str()); if (!result) { return false; @@ -304,47 +296,41 @@ bool Game::loadItemsPrice() } } while (result->next()); - return true; } -bool Game::loadMainMap(const std::string& filename) -{ +bool Game::loadMainMap(const std::string &filename) { Monster::despawnRange = g_configManager().getNumber(DEFAULT_DESPAWNRANGE); Monster::despawnRadius = g_configManager().getNumber(DEFAULT_DESPAWNRADIUS); return map.loadMap(g_configManager().getString(DATA_DIRECTORY) + "/world/" + filename + ".otbm", true, true, true, true); } -bool Game::loadCustomMap(const std::string& filename) -{ +bool Game::loadCustomMap(const std::string &filename) { Monster::despawnRange = g_configManager().getNumber(DEFAULT_DESPAWNRANGE); Monster::despawnRadius = g_configManager().getNumber(DEFAULT_DESPAWNRADIUS); return map.loadMapCustom(g_configManager().getString(DATA_DIRECTORY) + "/world/custom/" + filename + ".otbm", true, true, true); } -void Game::loadMap(const std::string& path, const Position& pos, bool unload) -{ +void Game::loadMap(const std::string &path, const Position &pos, bool unload) { map.loadMap(path, false, false, false, false, pos, unload); } -Cylinder* Game::internalGetCylinder(Player* player, const Position& pos) const -{ +Cylinder* Game::internalGetCylinder(Player* player, const Position &pos) const { if (pos.x != 0xFFFF) { return map.getTile(pos); } - //container + // container if (pos.y & 0x40) { uint8_t from_cid = pos.y & 0x0F; return player->getContainerByID(from_cid); } - //inventory + // inventory return player; } -Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index, uint32_t itemId, StackPosType_t type) const -{ +Thing* Game::internalGetThing(Player* player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type) const { if (pos.x != 0xFFFF) { Tile* tile = map.getTile(pos); if (!tile) { @@ -405,7 +391,7 @@ Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index } if (player && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { - //do extra checks here if the thing is accessable + // do extra checks here if the thing is accessable if (thing && thing->getItem()) { if (tile->hasProperty(CONST_PROP_ISVERTICAL)) { if (player->getPosition().x + 1 == tile->getPosition().x && thing->getItem()->isHangable()) { @@ -421,7 +407,7 @@ Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index return thing; } - //container + // container if (pos.y & 0x40) { uint8_t fromCid = pos.y & 0x0F; @@ -458,7 +444,7 @@ Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index return player->getItemFromDepotSearch(static_cast(itemId), pos); } else if (pos.y == 0 && pos.z == 0) { - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0) { return nullptr; } @@ -473,13 +459,12 @@ Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index return findItemOfType(player, it.id, true, subType); } - //inventory + // inventory Slots_t slot = static_cast(pos.y); return player->getInventoryItem(slot); } -void Game::internalGetPosition(Item* item, Position& pos, uint8_t& stackpos) -{ +void Game::internalGetPosition(Item* item, Position &pos, uint8_t &stackpos) { pos.x = 0; pos.y = 0; pos.z = 0; @@ -506,8 +491,7 @@ void Game::internalGetPosition(Item* item, Position& pos, uint8_t& stackpos) } } -Creature* Game::getCreatureByID(uint32_t id) -{ +Creature* Game::getCreatureByID(uint32_t id) { if (id <= Player::playerAutoID) { return getPlayerByID(id); } else if (id <= Monster::monsterAutoID) { @@ -518,8 +502,7 @@ Creature* Game::getCreatureByID(uint32_t id) return nullptr; } -Monster* Game::getMonsterByID(uint32_t id) -{ +Monster* Game::getMonsterByID(uint32_t id) { if (id == 0) { return nullptr; } @@ -531,8 +514,7 @@ Monster* Game::getMonsterByID(uint32_t id) return it->second; } -Npc* Game::getNpcByID(uint32_t id) -{ +Npc* Game::getNpcByID(uint32_t id) { if (id == 0) { return nullptr; } @@ -544,8 +526,7 @@ Npc* Game::getNpcByID(uint32_t id) return it->second; } -Player* Game::getPlayerByID(uint32_t id) -{ +Player* Game::getPlayerByID(uint32_t id) { auto playerMap = players.find(id); if (playerMap != players.end()) { return playerMap->second; @@ -554,26 +535,25 @@ Player* Game::getPlayerByID(uint32_t id) return nullptr; } -Creature* Game::getCreatureByName(const std::string& s) -{ +Creature* Game::getCreatureByName(const std::string &s) { if (s.empty()) { return nullptr; } - const std::string& lowerCaseName = asLowerCaseString(s); + const std::string &lowerCaseName = asLowerCaseString(s); auto m_it = mappedPlayerNames.find(lowerCaseName); if (m_it != mappedPlayerNames.end()) { return m_it->second; } - for (const auto& it : npcs) { + for (const auto &it : npcs) { if (lowerCaseName == asLowerCaseString(it.second->getName())) { return it.second; } } - for (const auto& it : monsters) { + for (const auto &it : monsters) { if (lowerCaseName == asLowerCaseString(it.second->getName())) { return it.second; } @@ -581,14 +561,13 @@ Creature* Game::getCreatureByName(const std::string& s) return nullptr; } -Npc* Game::getNpcByName(const std::string& s) -{ +Npc* Game::getNpcByName(const std::string &s) { if (s.empty()) { return nullptr; } const char* npcName = s.c_str(); - for (const auto& it : npcs) { + for (const auto &it : npcs) { if (strcasecmp(npcName, it.second->getName().c_str()) == 0) { return it.second; } @@ -596,8 +575,7 @@ Npc* Game::getNpcByName(const std::string& s) return nullptr; } -Player* Game::getPlayerByName(const std::string& s) -{ +Player* Game::getPlayerByName(const std::string &s) { if (s.empty()) { return nullptr; } @@ -609,13 +587,12 @@ Player* Game::getPlayerByName(const std::string& s) return it->second; } -Player* Game::getPlayerByGUID(const uint32_t& guid) -{ +Player* Game::getPlayerByGUID(const uint32_t &guid) { if (guid == 0) { return nullptr; } - for (const auto& it : players) { + for (const auto &it : players) { if (guid == it.second->getGUID()) { return it.second; } @@ -623,15 +600,14 @@ Player* Game::getPlayerByGUID(const uint32_t& guid) return nullptr; } -ReturnValue Game::getPlayerByNameWildcard(const std::string& s, Player*& player) -{ +ReturnValue Game::getPlayerByNameWildcard(const std::string &s, Player*&player) { size_t strlen = s.length(); if (strlen == 0 || strlen > 20) { return RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE; } if (s.back() == '~') { - const std::string& query = asLowerCaseString(s.substr(0, strlen - 1)); + const std::string &query = asLowerCaseString(s.substr(0, strlen - 1)); std::string result; ReturnValue ret = wildcardTree.findOne(query, result); if (ret != RETURNVALUE_NOERROR) { @@ -650,9 +626,8 @@ ReturnValue Game::getPlayerByNameWildcard(const std::string& s, Player*& player) return RETURNVALUE_NOERROR; } -Player* Game::getPlayerByAccount(uint32_t acc) -{ - for (const auto& it : players) { +Player* Game::getPlayerByAccount(uint32_t acc) { + for (const auto &it : players) { if (it.second->getAccount() == acc) { return it.second; } @@ -660,8 +635,7 @@ Player* Game::getPlayerByAccount(uint32_t acc) return nullptr; } -bool Game::internalPlaceCreature(Creature* creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/, bool creatureCheck /*= false*/) -{ +bool Game::internalPlaceCreature(Creature* creature, const Position &pos, bool extendedPos /*=false*/, bool forced /*= false*/, bool creatureCheck /*= false*/) { if (creature->getParent() != nullptr) { return false; } @@ -682,8 +656,7 @@ bool Game::internalPlaceCreature(Creature* creature, const Position& pos, bool e return true; } -bool Game::placeCreature(Creature* creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/) -{ +bool Game::placeCreature(Creature* creature, const Position &pos, bool extendedPos /*=false*/, bool forced /*= false*/) { if (!internalPlaceCreature(creature, pos, extendedPos, forced)) { return false; } @@ -707,8 +680,7 @@ bool Game::placeCreature(Creature* creature, const Position& pos, bool extendedP return true; } -bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) -{ +bool Game::removeCreature(Creature* creature, bool isLogout /* = true*/) { if (creature->isRemoved()) { return false; } @@ -727,9 +699,9 @@ bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) tile->removeCreature(creature); - const Position& tilePosition = tile->getPosition(); + const Position &tilePosition = tile->getPosition(); - //send to client + // send to client size_t i = 0; for (Creature* spectator : spectators) { if (Player* player = spectator->getPlayer()) { @@ -737,14 +709,14 @@ bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) } } - //event method + // event method for (Creature* spectator : spectators) { spectator->onRemoveCreature(creature, isLogout); } - if (creature->getMaster() && !creature->getMaster()->isRemoved()) { - creature->setMaster(nullptr); - } + if (creature->getMaster() && !creature->getMaster()->isRemoved()) { + creature->setMaster(nullptr); + } creature->getParent()->postRemoveNotification(creature, nullptr, 0); @@ -769,27 +741,26 @@ bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) return true; } -void Game::executeDeath(uint32_t creatureId) -{ +void Game::executeDeath(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && !creature->isRemoved()) { creature->onDeath(); } } -void Game::playerTeleport(uint32_t playerId, const Position& newPosition) { - Player* player = getPlayerByID(playerId); - if (!player || !player->hasFlag(PlayerFlags_t::CanMapClickTeleport)) { - return; - } +void Game::playerTeleport(uint32_t playerId, const Position &newPosition) { + Player* player = getPlayerByID(playerId); + if (!player || !player->hasFlag(PlayerFlags_t::CanMapClickTeleport)) { + return; + } - ReturnValue returnValue = g_game().internalTeleport(player, newPosition, false); - if (returnValue != RETURNVALUE_NOERROR) { - player->sendCancelMessage(returnValue); - } + ReturnValue returnValue = g_game().internalTeleport(player, newPosition, false); + if (returnValue != RETURNVALUE_NOERROR) { + player->sendCancelMessage(returnValue); + } } -void Game::playerInspectItem(Player* player, const Position& pos) { +void Game::playerInspectItem(Player* player, const Position &pos) { Thing* thing = internalGetThing(player, pos, 0, 0, STACKPOS_TOPDOWN_ITEM); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); @@ -809,8 +780,7 @@ void Game::playerInspectItem(Player* player, uint16_t itemId, uint8_t itemCount, player->sendItemInspection(itemId, itemCount, nullptr, cyclopedia); } -FILELOADER_ERRORS Game::loadAppearanceProtobuf(const std::string& file) -{ +FILELOADER_ERRORS Game::loadAppearanceProtobuf(const std::string &file) { using namespace Canary::protobuf::appearances; std::fstream fileStream(file, std::ios::in | std::ios::binary); @@ -859,9 +829,7 @@ FILELOADER_ERRORS Game::loadAppearanceProtobuf(const std::string& file) return ERROR_NONE; } -void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, - uint16_t itemId, uint8_t fromStackPos, const Position& toPos, uint8_t count) -{ +void Game::playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -869,7 +837,7 @@ void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, // Prevent the player from being able to move the item within the imbuement window if (player->hasImbuingItem()) { - return; + return; } uint8_t fromIndex = 0; @@ -902,13 +870,11 @@ void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, return; } - if (Position::areInRange<1, 1, 0>(movingCreature->getPosition(), - player->getPosition())) { + if (Position::areInRange<1, 1, 0>(movingCreature->getPosition(), player->getPosition())) { SchedulerTask* task = createSchedulerTask( - g_configManager().getNumber(PUSH_DELAY), - std::bind(&Game::playerMoveCreatureByID, this, - player->getID(), movingCreature->getID(), - movingCreature->getPosition(), tile->getPosition())); + g_configManager().getNumber(PUSH_DELAY), + std::bind(&Game::playerMoveCreatureByID, this, player->getID(), movingCreature->getID(), movingCreature->getPosition(), tile->getPosition()) + ); player->setNextActionPushTask(task); } else { playerMoveCreature(player, movingCreature, movingCreature->getPosition(), tile); @@ -924,8 +890,7 @@ void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, } } -void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position& movingCreatureOrigPos, const Position& toPos) -{ +void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position &movingCreatureOrigPos, const Position &toPos) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -945,12 +910,10 @@ void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, playerMoveCreature(player, movingCreature, movingCreatureOrigPos, toTile); } -void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Position& movingCreatureOrigPos, Tile* toTile) -{ +void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Position &movingCreatureOrigPos, Tile* toTile) { if (!player->canDoAction()) { uint32_t delay = 600; - SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerMoveCreatureByID, - this, player->getID(), movingCreature->getID(), movingCreatureOrigPos, toTile->getPosition())); + SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerMoveCreatureByID, this, player->getID(), movingCreature->getID(), movingCreatureOrigPos, toTile->getPosition())); player->setNextActionPushTask(task); return; @@ -959,14 +922,12 @@ void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Po player->setNextActionTask(nullptr); if (!Position::areInRange<1, 1, 0>(movingCreatureOrigPos, player->getPosition())) { - //need to walk to the creature first before moving it + // need to walk to the creature first before moving it std::forward_list listDir; if (player->getPathTo(movingCreatureOrigPos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(600, std::bind(&Game::playerMoveCreatureByID, this, - player->getID(), movingCreature->getID(), movingCreatureOrigPos, toTile->getPosition())); + SchedulerTask* task = createSchedulerTask(600, std::bind(&Game::playerMoveCreatureByID, this, player->getID(), movingCreature->getID(), movingCreatureOrigPos, toTile->getPosition())); player->pushEvent(true); player->setNextActionPushTask(task); @@ -983,15 +944,14 @@ void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Po isFamiliar = monster->isFamiliar(); } - if (!isFamiliar && ((!movingCreature->isPushable() && !player->hasFlag(PlayerFlags_t::CanPushAllCreatures)) || - (movingCreature->isInGhostMode() && !player->isAccessPlayer()))) { + if (!isFamiliar && ((!movingCreature->isPushable() && !player->hasFlag(PlayerFlags_t::CanPushAllCreatures)) || (movingCreature->isInGhostMode() && !player->isAccessPlayer()))) { player->sendCancelMessage(RETURNVALUE_NOTMOVEABLE); return; } - //check throw distance - const Position& movingCreaturePos = movingCreature->getPosition(); - const Position& toPos = toTile->getPosition(); + // check throw distance + const Position &movingCreaturePos = movingCreature->getPosition(); + const Position &toPos = toTile->getPosition(); if ((Position::getDistanceX(movingCreaturePos, toPos) > movingCreature->getThrowRange()) || (Position::getDistanceY(movingCreaturePos, toPos) > movingCreature->getThrowRange()) || (Position::getDistanceZ(movingCreaturePos, toPos) * 4 > movingCreature->getThrowRange())) { player->sendCancelMessage(RETURNVALUE_DESTINATIONOUTOFREACH); return; @@ -1035,16 +995,15 @@ void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Po player->setLastPosition(player->getPosition()); } -ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, uint32_t flags /*= 0*/) -{ +ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, uint32_t flags /*= 0*/) { creature->setLastPosition(creature->getPosition()); - const Position& currentPos = creature->getPosition(); + const Position ¤tPos = creature->getPosition(); Position destPos = getNextPosition(direction, currentPos); Player* player = creature->getPlayer(); bool diagonalMovement = (direction & DIRECTION_DIAGONAL_MASK) != 0; if (player && !diagonalMovement) { - //try go up + // try go up if (currentPos.z != 8 && creature->getTile()->hasHeight(3)) { Tile* tmpTile = map.getTile(currentPos.x, currentPos.y, currentPos.getZ() - 1); if (tmpTile == nullptr || (tmpTile->getGround() == nullptr && !tmpTile->hasFlag(TILESTATE_BLOCKSOLID))) { @@ -1060,7 +1019,7 @@ ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, } } - //try go down + // try go down if (currentPos.z != 7 && currentPos.z == destPos.z) { Tile* tmpTile = map.getTile(destPos.x, destPos.y, destPos.z); if (tmpTile == nullptr || (tmpTile->getGround() == nullptr && !tmpTile->hasFlag(TILESTATE_BLOCKSOLID))) { @@ -1081,13 +1040,12 @@ ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, return internalMoveCreature(*creature, *toTile, flags); } -ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_t flags /*= 0*/) -{ +ReturnValue Game::internalMoveCreature(Creature &creature, Tile &toTile, uint32_t flags /*= 0*/) { if (creature.hasCondition(CONDITION_ROOTED)) { return RETURNVALUE_NOTPOSSIBLE; } - //check if we can move the creature to the destination + // check if we can move the creature to the destination ReturnValue ret = toTile.queryAdd(0, creature, 1, flags); if (ret != RETURNVALUE_NOERROR) { return ret; @@ -1109,7 +1067,7 @@ ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_ map.moveCreature(creature, *subCylinder); if (creature.getParent() != subCylinder) { - //could happen if a script move the creature + // could happen if a script move the creature fromCylinder = nullptr; break; } @@ -1118,15 +1076,15 @@ ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_ toCylinder = subCylinder; flags = 0; - //to prevent infinite loop + // to prevent infinite loop if (++n >= MAP_MAX_LAYERS) { break; } } if (fromCylinder) { - const Position& fromPosition = fromCylinder->getPosition(); - const Position& toPosition = toCylinder->getPosition(); + const Position &fromPosition = fromCylinder->getPosition(); + const Position &toPosition = toCylinder->getPosition(); if (fromPosition.z != toPosition.z && (fromPosition.x != toPosition.x || fromPosition.y != toPosition.y)) { Direction dir = getDirectionTo(fromPosition, toPosition); if ((dir & DIRECTION_DIAGONAL_MASK) == 0) { @@ -1138,8 +1096,7 @@ ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_ return RETURNVALUE_NOERROR; } -void Game::playerMoveItemByPlayerID(uint32_t playerId, const Position& fromPos, uint16_t itemId, uint8_t fromStackPos, const Position& toPos, uint8_t count) -{ +void Game::playerMoveItemByPlayerID(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -1147,13 +1104,10 @@ void Game::playerMoveItemByPlayerID(uint32_t playerId, const Position& fromPos, playerMoveItem(player, fromPos, itemId, fromStackPos, toPos, count, nullptr, nullptr); } -void Game::playerMoveItem(Player* player, const Position& fromPos, - uint16_t itemId, uint8_t fromStackPos, const Position& toPos, uint8_t count, Item* item, Cylinder* toCylinder) -{ +void Game::playerMoveItem(Player* player, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count, Item* item, Cylinder* toCylinder) { if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); - SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerMoveItemByPlayerID, this, - player->getID(), fromPos, itemId, fromStackPos, toPos, count)); + SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerMoveItemByPlayerID, this, player->getID(), fromPos, itemId, fromStackPos, toPos, count)); player->setNextActionTask(task); return; } @@ -1193,8 +1147,7 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, } Cylinder* fromCylinder = nullptr; - if (fromPos.x == 0xFFFF && - (fromPos.y == 0x20 || fromPos.y == 0x21)) { + if (fromPos.x == 0xFFFF && (fromPos.y == 0x20 || fromPos.y == 0x21)) { // '0x20' -> From depot. // '0x21' -> From inbox. // Both only when the item is being moved from depot search window. @@ -1231,24 +1184,20 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, return; } - const Position& playerPos = player->getPosition(); - const Position& mapFromPos = fromCylinder->getTile()->getPosition(); + const Position &playerPos = player->getPosition(); + const Position &mapFromPos = fromCylinder->getTile()->getPosition(); if (playerPos.z != mapFromPos.z) { player->sendCancelMessage(playerPos.z > mapFromPos.z ? RETURNVALUE_FIRSTGOUPSTAIRS : RETURNVALUE_FIRSTGODOWNSTAIRS); return; } if (!Position::areInRange<1, 1>(playerPos, mapFromPos)) { - //need to walk to the item first before using it + // need to walk to the item first before using it std::forward_list listDir; if (player->getPathTo(item->getPosition(), listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerMoveItemByPlayerID, this, - player->getID(), fromPos, itemId, - fromStackPos, toPos, count)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerMoveItemByPlayerID, this, player->getID(), fromPos, itemId, fromStackPos, toPos, count)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -1257,11 +1206,11 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, } const Tile* toCylinderTile = toCylinder->getTile(); - const Position& mapToPos = toCylinderTile->getPosition(); + const Position &mapToPos = toCylinderTile->getPosition(); - //hangable item specific code + // hangable item specific code if (item->isHangable() && toCylinderTile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { - //destination supports hangable objects so need to move there first + // destination supports hangable objects so need to move there first bool vertical = toCylinderTile->hasProperty(CONST_PROP_ISVERTICAL); if (vertical) { if (playerPos.x + 1 == mapToPos.x) { @@ -1287,8 +1236,8 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, uint8_t itemStackPos = fromStackPos; if (fromPos.x != 0xFFFF && Position::areInRange<1, 1>(mapFromPos, playerPos) - && !Position::areInRange<1, 1, 0>(mapFromPos, walkPos)) { - //need to pickup the item first + && !Position::areInRange<1, 1, 0>(mapFromPos, walkPos)) { + // need to pickup the item first Item* moveItem = nullptr; ReturnValue ret = internalMoveItem(fromCylinder, player, INDEX_WHEREEVER, item, count, &moveItem); @@ -1297,19 +1246,15 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, return; } - //changing the position since its now in the inventory of the player + // changing the position since its now in the inventory of the player internalGetPosition(moveItem, itemPos, itemStackPos); } std::forward_list listDir; if (player->getPathTo(walkPos, listDir, 0, 0, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerMoveItemByPlayerID, - this, player->getID(), itemPos, itemId, - itemStackPos, toPos, count)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerMoveItemByPlayerID, this, player->getID(), itemPos, itemId, itemStackPos, toPos, count)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -1318,9 +1263,7 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, } } - if ((Position::getDistanceX(playerPos, mapToPos) > item->getThrowRange()) || - (Position::getDistanceY(playerPos, mapToPos) > item->getThrowRange()) || - (Position::getDistanceZ(mapFromPos, mapToPos) * 4 > item->getThrowRange())) { + if ((Position::getDistanceX(playerPos, mapToPos) > item->getThrowRange()) || (Position::getDistanceY(playerPos, mapToPos) > item->getThrowRange()) || (Position::getDistanceZ(mapFromPos, mapToPos) * 4 > item->getThrowRange())) { player->sendCancelMessage(RETURNVALUE_DESTINATIONOUTOFREACH); return; } @@ -1343,22 +1286,19 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, } } - if (item->isWrapable()){ + if (item->isWrapable()) { HouseTile* toHouseTile = dynamic_cast(map.getTile(mapToPos)); HouseTile* fromHouseTile = dynamic_cast(map.getTile(mapFromPos)); if (fromHouseTile && (!toHouseTile || toHouseTile->getHouse()->getId() != fromHouseTile->getHouse()->getId())) { player->sendCancelMessage("You can't move this item outside a house."); - return; + return; } } ReturnValue ret = internalMoveItem(fromCylinder, toCylinder, toIndex, item, count, nullptr, 0, player); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); - } else if (toCylinder->getContainer() - && fromCylinder->getContainer() - && fromCylinder->getContainer()->countsToLootAnalyzerBalance() - && toCylinder->getContainer()->getTopParent() == player) { + } else if (toCylinder->getContainer() && fromCylinder->getContainer() && fromCylinder->getContainer()->countsToLootAnalyzerBalance() && toCylinder->getContainer()->getTopParent() == player) { player->sendLootStats(item, count); } player->cancelPush(); @@ -1366,18 +1306,11 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, g_events().eventPlayerOnItemMoved(player, item, count, fromPos, toPos, fromCylinder, toCylinder); } -bool Game::isTryingToStow(const Position &toPos, Cylinder *toCylinder) const { - return toCylinder->getContainer() && - toCylinder->getItem()->getID() == ITEM_LOCKER && - toPos.getZ() == ITEM_SUPPLY_STASH_INDEX; +bool Game::isTryingToStow(const Position &toPos, Cylinder* toCylinder) const { + return toCylinder->getContainer() && toCylinder->getItem()->getID() == ITEM_LOCKER && toPos.getZ() == ITEM_SUPPLY_STASH_INDEX; } -ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, - Cylinder* toCylinder, int32_t index, - Item* item, uint32_t count, Item** internalMoveItem, - uint32_t flags /*= 0*/, Creature* actor/*=nullptr*/, - Item* tradeItem/* = nullptr*/) -{ +ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, int32_t index, Item* item, uint32_t count, Item** internalMoveItem, uint32_t flags /*= 0*/, Creature* actor /*=nullptr*/, Item* tradeItem /* = nullptr*/) { if (fromCylinder == nullptr) { SPDLOG_ERROR("[{}] fromCylinder is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; @@ -1404,15 +1337,15 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, toCylinder = subCylinder; flags = 0; - //to prevent infinite loop + // to prevent infinite loop if (++floorN >= MAP_MAX_LAYERS) { break; } } - //destination is the same as the source? + // destination is the same as the source? if (item == toItem) { - return RETURNVALUE_NOERROR; //silently ignore move + return RETURNVALUE_NOERROR; // silently ignore move } // 'Move up' stackable items fix @@ -1421,13 +1354,13 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, count = item->getItemCount(); } - //check if we can add this item + // check if we can add this item ReturnValue ret = toCylinder->queryAdd(index, *item, count, flags, actor); if (ret == RETURNVALUE_NEEDEXCHANGE) { - //check if we can add it to source cylinder + // check if we can add it to source cylinder ret = fromCylinder->queryAdd(fromCylinder->getThingIndex(item), *toItem, toItem->getItemCount(), 0); if (ret == RETURNVALUE_NOERROR) { - //check how much we can move + // check how much we can move uint32_t maxExchangeQueryCount = 0; ReturnValue retExchangeMaxCount = fromCylinder->queryMaxCount(INDEX_WHEREEVER, *toItem, toItem->getItemCount(), maxExchangeQueryCount, 0); @@ -1459,7 +1392,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, return ret; } - //check how much we can move + // check how much we can move uint32_t maxQueryCount = 0; ReturnValue retMaxCount = toCylinder->queryMaxCount(index, *item, count, maxQueryCount, flags); if (retMaxCount != RETURNVALUE_NOERROR && maxQueryCount == 0) { @@ -1474,7 +1407,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, } Item* moveItem = item; - //check if we can remove this item + // check if we can remove this item ret = fromCylinder->queryRemove(*item, m, flags, actor); if (ret != RETURNVALUE_NOERROR) { return ret; @@ -1495,12 +1428,12 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, } } - //remove the item + // remove the item int32_t itemIndex = fromCylinder->getThingIndex(item); Item* updateItem = nullptr; fromCylinder->removeThing(item, m); - //update item(s) + // update item(s) if (item->isStackable()) { uint32_t n; @@ -1526,7 +1459,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, } } - //add item + // add item if (moveItem /*m - n > 0*/) { toCylinder->addThing(index, moveItem); } @@ -1561,19 +1494,19 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Item* quiver = toCylinder->getItem(); if (quiver && quiver->isQuiver() - && quiver->getHoldingPlayer() - && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { + && quiver->getHoldingPlayer() + && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { quiver->getHoldingPlayer()->sendInventoryItem(CONST_SLOT_RIGHT, quiver); } else { quiver = fromCylinder->getItem(); if (quiver && quiver->isQuiver() - && quiver->getHoldingPlayer() - && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { + && quiver->getHoldingPlayer() + && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { quiver->getHoldingPlayer()->sendInventoryItem(CONST_SLOT_RIGHT, quiver); } } - //we could not move all, inform the player + // we could not move all, inform the player if (item->isStackable() && maxQueryCount < count) { return retMaxCount; } @@ -1587,13 +1520,11 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, if (Player* player = actor->getPlayer()) { // Refresh depot search window if necessary - if (player->isDepotSearchOpenOnItem(item->getID()) && - ((fromCylinder->getItem() && fromCylinder->getItem()->isInsideDepot(true)) || - (toCylinder->getItem() && toCylinder->getItem()->isInsideDepot(true)))) { + if (player->isDepotSearchOpenOnItem(item->getID()) && ((fromCylinder->getItem() && fromCylinder->getItem()->isInsideDepot(true)) || (toCylinder->getItem() && toCylinder->getItem()->isInsideDepot(true)))) { player->requestDepotSearchItem(item->getID(), item->getTier()); } - const ItemType& it = Item::items[fromCylinder->getItem()->getID()]; + const ItemType &it = Item::items[fromCylinder->getItem()->getID()]; if (it.id <= 0) { return ret; } @@ -1607,17 +1538,12 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, return ret; } -ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, - int32_t index /*= INDEX_WHEREEVER*/, - uint32_t flags/* = 0*/, bool test/* = false*/) -{ +ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t index /*= INDEX_WHEREEVER*/, uint32_t flags /* = 0*/, bool test /* = false*/) { uint32_t remainderCount = 0; return internalAddItem(toCylinder, item, index, flags, test, remainderCount); } -ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t index, - uint32_t flags, bool test, uint32_t& remainderCount) -{ +ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t index, uint32_t flags, bool test, uint32_t &remainderCount) { if (toCylinder == nullptr) { SPDLOG_ERROR("[{}] fromCylinder is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; @@ -1631,7 +1557,7 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde Item* toItem = nullptr; toCylinder = toCylinder->queryDestination(index, *item, &toItem, flags); - //check if we can add this item + // check if we can add this item ReturnValue ret = toCylinder->queryAdd(index, *item, item->getItemCount(), flags); if (ret != RETURNVALUE_NOERROR) { return ret; @@ -1676,7 +1602,7 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde } } } else { - //fully merged with toItem, item will be destroyed + // fully merged with toItem, item will be destroyed item->onRemoved(); ReleaseItem(item); @@ -1696,16 +1622,15 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde Item* quiver = toCylinder->getItem(); if (quiver && quiver->isQuiver() - && quiver->getHoldingPlayer() - && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { + && quiver->getHoldingPlayer() + && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { quiver->getHoldingPlayer()->sendInventoryItem(CONST_SLOT_RIGHT, quiver); } return RETURNVALUE_NOERROR; } -ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/) -{ +ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/) { if (item == nullptr) { SPDLOG_DEBUG("{} - Item is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; @@ -1725,7 +1650,7 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te if (count == -1) { count = item->getItemCount(); } - //check if we can remove this item + // check if we can remove this item ReturnValue ret = cylinder->queryRemove(*item, count, flags | FLAG_IGNORENOTMOVEABLE); if (ret != RETURNVALUE_NOERROR) { SPDLOG_DEBUG("{} - Failed to execute query remove", __FUNCTION__); @@ -1745,7 +1670,7 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te if (!test) { int32_t index = cylinder->getThingIndex(item); - //remove the item + // remove the item cylinder->removeThing(item, count); if (item->isRemoved()) { @@ -1759,16 +1684,15 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te Item* quiver = cylinder->getItem(); if (quiver && quiver->isQuiver() - && quiver->getHoldingPlayer() - && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { + && quiver->getHoldingPlayer() + && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { quiver->getHoldingPlayer()->sendInventoryItem(CONST_SLOT_RIGHT, quiver); } return RETURNVALUE_NOERROR; } -ReturnValue Game::internalPlayerAddItem(Player* player, Item* item, bool dropOnMap /*= true*/, Slots_t slot /*= CONST_SLOT_WHEREEVER*/) -{ +ReturnValue Game::internalPlayerAddItem(Player* player, Item* item, bool dropOnMap /*= true*/, Slots_t slot /*= CONST_SLOT_WHEREEVER*/) { uint32_t remainderCount = 0; ReturnValue ret = internalAddItem(player, item, static_cast(slot), 0, false, remainderCount); if (remainderCount != 0) { @@ -1784,16 +1708,14 @@ ReturnValue Game::internalPlayerAddItem(Player* player, Item* item, bool dropOnM ret = internalAddItem(player->getTile(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); } - if (ret == RETURNVALUE_NOERROR) - { + if (ret == RETURNVALUE_NOERROR) { player->sendForgingData(); } return ret; } -Item* Game::findItemOfType(const Cylinder* cylinder, uint16_t itemId, bool depthSearch /*= true*/, int32_t subType /*= -1*/) const -{ +Item* Game::findItemOfType(const Cylinder* cylinder, uint16_t itemId, bool depthSearch /*= true*/, int32_t subType /*= -1*/) const { if (cylinder == nullptr) { SPDLOG_ERROR("[{}] Cylinder is nullptr", __FUNCTION__); return nullptr; @@ -1840,8 +1762,7 @@ Item* Game::findItemOfType(const Cylinder* cylinder, uint16_t itemId, bool depth return nullptr; } -bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/, bool useBalance /*= false*/) -{ +bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/, bool useBalance /*= false*/) { if (cylinder == nullptr) { SPDLOG_ERROR("[{}] cylinder is nullptr", __FUNCTION__); return false; @@ -1899,7 +1820,7 @@ bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0* return false; } - for (const auto& moneyEntry : moneyMap) { + for (const auto &moneyEntry : moneyMap) { Item* item = moneyEntry.second; if (moneyEntry.first < money) { internalRemoveItem(item); @@ -1923,8 +1844,7 @@ bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0* return true; } -void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) -{ +void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) { if (cylinder == nullptr) { SPDLOG_ERROR("[{}] cylinder is nullptr", __FUNCTION__); return; @@ -1970,9 +1890,8 @@ void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) } } -Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) -{ - if (item->getID() == newId && (newCount == -1 || (newCount == item->getSubType() && newCount != 0))) { //chargeless item placed on map = infinite +Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) { + if (item->getID() == newId && (newCount == -1 || (newCount == item->getSubType() && newCount != 0))) { // chargeless item placed on map = infinite return item; } @@ -1998,15 +1917,15 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) return item; } - const ItemType& newType = Item::items[newId]; + const ItemType &newType = Item::items[newId]; if (newType.id == 0) { return item; } - const ItemType& curType = Item::items[item->getID()]; + const ItemType &curType = Item::items[item->getID()]; if (item->isAlwaysOnTop() != (newType.alwaysOnTopOrder != 0)) { - //This only occurs when you transform items on tiles from a downItem to a topItem (or vice versa) - //Remove the old, and add the new + // This only occurs when you transform items on tiles from a downItem to a topItem (or vice versa) + // Remove the old, and add the new cylinder->removeThing(item, item->getItemCount()); cylinder->postRemoveNotification(item, cylinder, itemIndex); @@ -2030,7 +1949,7 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) } if (curType.type == newType.type) { - //Both items has the same type so we can safely change id/subtype + // Both items has the same type so we can safely change id/subtype if (newCount == 0 && (item->isStackable() || item->hasAttribute(ItemAttribute_t::CHARGES))) { if (item->isStackable()) { internalRemoveItem(item); @@ -2087,8 +2006,8 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) Item* quiver = cylinder->getItem(); if (quiver && quiver->isQuiver() - && quiver->getHoldingPlayer() - && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { + && quiver->getHoldingPlayer() + && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { quiver->getHoldingPlayer()->sendInventoryItem(CONST_SLOT_RIGHT, quiver); } item->startDecaying(); @@ -2099,12 +2018,12 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) Item* quiver = cylinder->getItem(); if (quiver && quiver->isQuiver() - && quiver->getHoldingPlayer() - && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { + && quiver->getHoldingPlayer() + && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { quiver->getHoldingPlayer()->sendInventoryItem(CONST_SLOT_RIGHT, quiver); } - //Replacing the the old item with the new while maintaining the old position + // Replacing the the old item with the new while maintaining the old position Item* newItem; if (newCount == -1) { newItem = Item::CreateItem(newId); @@ -2128,8 +2047,7 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) return newItem; } -ReturnValue Game::internalTeleport(Thing* thing, const Position& newPos, bool pushMove/* = true*/, uint32_t flags /*= 0*/) -{ +ReturnValue Game::internalTeleport(Thing* thing, const Position &newPos, bool pushMove /* = true*/, uint32_t flags /*= 0*/) { if (thing == nullptr) { SPDLOG_ERROR("[{}] thing is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; @@ -2160,8 +2078,7 @@ ReturnValue Game::internalTeleport(Thing* thing, const Position& newPos, bool pu return RETURNVALUE_NOTPOSSIBLE; } -void Game::internalQuickLootCorpse(Player* player, Container* corpse) -{ +void Game::internalQuickLootCorpse(Player* player, Container* corpse) { if (!player || !corpse) { return; } @@ -2301,27 +2218,26 @@ void Game::internalQuickLootCorpse(Player* player, Container* corpse) player->lastQuickLootNotification = OTSYS_TIME(); } -ReturnValue Game::internalQuickLootItem(Player* player, Item* item, ObjectCategory_t category /* = OBJECTCATEGORY_DEFAULT*/) -{ - if (!player || !item) { - return RETURNVALUE_NOTPOSSIBLE; - } +ReturnValue Game::internalQuickLootItem(Player* player, Item* item, ObjectCategory_t category /* = OBJECTCATEGORY_DEFAULT*/) { + if (!player || !item) { + return RETURNVALUE_NOTPOSSIBLE; + } bool fallbackConsumed = false; uint16_t baseId = 0; Container* lootContainer = player->getLootContainer(category); if (!lootContainer) { - if (player->quickLootFallbackToMainContainer) { - Item* fallbackItem = player->getInventoryItem(CONST_SLOT_BACKPACK); + if (player->quickLootFallbackToMainContainer) { + Item* fallbackItem = player->getInventoryItem(CONST_SLOT_BACKPACK); - if (fallbackItem) { - Container* mainBackpack = fallbackItem->getContainer(); - if (mainBackpack && !fallbackConsumed) { - player->setLootContainer(OBJECTCATEGORY_DEFAULT, mainBackpack); - player->sendInventoryItem(CONST_SLOT_BACKPACK, player->getInventoryItem(CONST_SLOT_BACKPACK)); - } - } + if (fallbackItem) { + Container* mainBackpack = fallbackItem->getContainer(); + if (mainBackpack && !fallbackConsumed) { + player->setLootContainer(OBJECTCATEGORY_DEFAULT, mainBackpack); + player->sendInventoryItem(CONST_SLOT_BACKPACK, player->getInventoryItem(CONST_SLOT_BACKPACK)); + } + } lootContainer = fallbackItem ? fallbackItem->getContainer() : nullptr; fallbackConsumed = true; @@ -2344,9 +2260,9 @@ ReturnValue Game::internalQuickLootItem(Player* player, Item* item, ObjectCatego do { Item* moveItem = nullptr; if (item->getParent()) { // Stash retrive dont have parent cylinder. - ret = internalMoveItem(item->getParent(), lootContainer, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, 0, player); + ret = internalMoveItem(item->getParent(), lootContainer, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, 0, player); } else { - ret = internalAddItem(lootContainer, item, INDEX_WHEREEVER); + ret = internalAddItem(lootContainer, item, INDEX_WHEREEVER); } if (moveItem) { remainderCount -= moveItem->getItemCount(); @@ -2405,14 +2321,13 @@ ReturnValue Game::internalQuickLootItem(Player* player, Item* item, ObjectCatego return ret; } -ObjectCategory_t Game::getObjectCategory(const Item* item) -{ +ObjectCategory_t Game::getObjectCategory(const Item* item) { ObjectCategory_t category = OBJECTCATEGORY_DEFAULT; - if (!item) { - return OBJECTCATEGORY_NONE; - } + if (!item) { + return OBJECTCATEGORY_NONE; + } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (item->getWorth() != 0) { category = OBJECTCATEGORY_GOLD; } else if (it.weaponType != WEAPON_NONE) { @@ -2474,10 +2389,9 @@ ObjectCategory_t Game::getObjectCategory(const Item* item) return category; } -uint64_t Game::getItemMarketPrice(std::map const &itemMap, bool buyPrice) const -{ +uint64_t Game::getItemMarketPrice(const std::map &itemMap, bool buyPrice) const { uint64_t total = 0; - for (const auto& it : itemMap) { + for (const auto &it : itemMap) { if (it.first == ITEM_GOLD_COIN) { total += it.second; } else if (it.first == ITEM_PLATINUM_COIN) { @@ -2491,7 +2405,7 @@ uint64_t Game::getItemMarketPrice(std::map const &itemMap, b total += price * it.second; } } else { - const ItemType& iType = Item::items[it.first]; + const ItemType &iType = Item::items[it.first]; total += (buyPrice ? iType.buyPrice : iType.sellPrice) * it.second; } } @@ -2500,8 +2414,7 @@ uint64_t Game::getItemMarketPrice(std::map const &itemMap, b return total; } -Item* searchForItem(const Container* container, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) -{ +Item* searchForItem(const Container* container, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if ((*it)->getID() == itemId && (!hasTier || (*it)->getTier() == tier)) { return *it; @@ -2511,8 +2424,7 @@ Item* searchForItem(const Container* container, uint16_t itemId, bool hasTier /* return nullptr; } -Slots_t getSlotType(const ItemType& it) -{ +Slots_t getSlotType(const ItemType &it) { Slots_t slot = CONST_SLOT_RIGHT; if (it.weaponType != WeaponType_t::WEAPON_SHIELD) { int32_t slotPosition = it.slotPosition; @@ -2526,7 +2438,7 @@ Slots_t getSlotType(const ItemType& it) } else if (slotPosition & SLOTP_LEGS) { slot = CONST_SLOT_LEGS; } else if (slotPosition & SLOTP_FEET) { - slot = CONST_SLOT_FEET ; + slot = CONST_SLOT_FEET; } else if (slotPosition & SLOTP_RING) { slot = CONST_SLOT_RING; } else if (slotPosition & SLOTP_AMMO) { @@ -2539,9 +2451,8 @@ Slots_t getSlotType(const ItemType& it) return slot; } -//Implementation of player invoked events -void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) -{ +// Implementation of player invoked events +void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2557,7 +2468,7 @@ void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = return; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; Slots_t slot = getSlotType(it); Item* slotItem = player->getInventoryItem(slot); @@ -2577,8 +2488,7 @@ void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = } } -void Game::playerMove(uint32_t playerId, Direction direction) -{ +void Game::playerMove(uint32_t playerId, Direction direction) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2591,23 +2501,21 @@ void Game::playerMove(uint32_t playerId, Direction direction) player->startAutoWalk(std::forward_list { direction }); } -bool Game::playerBroadcastMessage(Player* player, const std::string& text) const -{ +bool Game::playerBroadcastMessage(Player* player, const std::string &text) const { if (!player->hasFlag(PlayerFlags_t::CanBroadcast)) { return false; } SPDLOG_INFO("{} broadcasted: {}", player->getName(), text); - for (const auto& it : players) { + for (const auto &it : players) { it.second->sendPrivateMessage(player, TALKTYPE_BROADCAST, text); } return true; } -void Game::playerCreatePrivateChannel(uint32_t playerId) -{ +void Game::playerCreatePrivateChannel(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player || !player->isPremium()) { return; @@ -2621,8 +2529,7 @@ void Game::playerCreatePrivateChannel(uint32_t playerId) player->sendCreatePrivateChannel(channel->getId(), channel->getName()); } -void Game::playerChannelInvite(uint32_t playerId, const std::string& name) -{ +void Game::playerChannelInvite(uint32_t playerId, const std::string &name) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2645,8 +2552,7 @@ void Game::playerChannelInvite(uint32_t playerId, const std::string& name) channel->invitePlayer(*player, *invitePlayer); } -void Game::playerChannelExclude(uint32_t playerId, const std::string& name) -{ +void Game::playerChannelExclude(uint32_t playerId, const std::string &name) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2669,8 +2575,7 @@ void Game::playerChannelExclude(uint32_t playerId, const std::string& name) channel->excludePlayer(*player, *excludePlayer); } -void Game::playerRequestChannels(uint32_t playerId) -{ +void Game::playerRequestChannels(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2679,8 +2584,7 @@ void Game::playerRequestChannels(uint32_t playerId) player->sendChannelsDialog(); } -void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) -{ +void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2702,8 +2606,7 @@ void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) player->sendChannel(channel->getId(), channel->getName(), users, invitedUsers); } -void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) -{ +void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2712,8 +2615,7 @@ void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) g_chat().removeUserFromChannel(*player, channelId); } -void Game::playerOpenPrivateChannel(uint32_t playerId, std::string& receiver) -{ +void Game::playerOpenPrivateChannel(uint32_t playerId, std::string &receiver) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2732,8 +2634,7 @@ void Game::playerOpenPrivateChannel(uint32_t playerId, std::string& receiver) player->sendOpenPrivateChannel(receiver); } -void Game::playerCloseNpcChannel(uint32_t playerId) -{ +void Game::playerCloseNpcChannel(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2748,8 +2649,7 @@ void Game::playerCloseNpcChannel(uint32_t playerId) } } -void Game::playerReceivePing(uint32_t playerId) -{ +void Game::playerReceivePing(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2758,8 +2658,7 @@ void Game::playerReceivePing(uint32_t playerId) player->receivePing(); } -void Game::playerReceivePingBack(uint32_t playerId) -{ +void Game::playerReceivePingBack(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2768,8 +2667,7 @@ void Game::playerReceivePingBack(uint32_t playerId) player->sendPingBack(); } -void Game::playerAutoWalk(uint32_t playerId, const std::forward_list& listDir) -{ +void Game::playerAutoWalk(uint32_t playerId, const std::forward_list &listDir) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2780,8 +2678,7 @@ void Game::playerAutoWalk(uint32_t playerId, const std::forward_list& player->startAutoWalk(listDir); } -void Game::playerStopAutoWalk(uint32_t playerId) -{ +void Game::playerStopAutoWalk(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2790,9 +2687,7 @@ void Game::playerStopAutoWalk(uint32_t playerId) player->stopWalk(); } -void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint16_t fromItemId, - const Position& toPos, uint8_t toStackPos, uint16_t toItemId) -{ +void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint16_t fromItemId, const Position &toPos, uint8_t toStackPos, uint16_t toItemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2824,7 +2719,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f } } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); @@ -2837,8 +2732,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f Position itemPos = fromPos; uint8_t itemStackPos = fromStackPos; - if (fromPos.x != 0xFFFF && toPos.x != 0xFFFF && Position::areInRange<1, 1, 0>(fromPos, player->getPosition()) && - !Position::areInRange<1, 1, 0>(fromPos, toPos)) { + if (fromPos.x != 0xFFFF && toPos.x != 0xFFFF && Position::areInRange<1, 1, 0>(fromPos, player->getPosition()) && !Position::areInRange<1, 1, 0>(fromPos, toPos)) { Item* moveItem = nullptr; ret = internalMoveItem(item->getParent(), player, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem); @@ -2847,7 +2741,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f return; } - //changing the position since its now in the inventory of the player + // changing the position since its now in the inventory of the player internalGetPosition(moveItem, itemPos, itemStackPos); } @@ -2855,10 +2749,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f if (player->getPathTo(walkToPos, listDir, 0, 1, true, true)) { g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerUseItemEx, this, - playerId, itemPos, itemStackPos, fromItemId, - toPos, toStackPos, toItemId)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerUseItemEx, this, playerId, itemPos, itemStackPos, fromItemId, toPos, toStackPos, toItemId)); if (it.isRune() || it.type == ITEM_TYPE_POTION) { player->setNextPotionActionTask(task); } else { @@ -2884,8 +2775,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f if (it.isRune() || it.type == ITEM_TYPE_POTION) { delay = player->getNextPotionActionTime(); } - SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseItemEx, this, - playerId, fromPos, fromStackPos, fromItemId, toPos, toStackPos, toItemId)); + SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseItemEx, this, playerId, fromPos, fromStackPos, fromItemId, toPos, toStackPos, toItemId)); if (it.isRune() || it.type == ITEM_TYPE_POTION) { player->setNextPotionActionTask(task); } else { @@ -2908,7 +2798,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f mustReloadDepotSearch = true; } else { if (Thing* targetThing = internalGetThing(player, toPos, toStackPos, toItemId, STACKPOS_FIND_THING); - targetThing && targetThing->getItem() && targetThing->getItem()->isInsideDepot(true)) { + targetThing && targetThing->getItem() && targetThing->getItem()->isInsideDepot(true)) { mustReloadDepotSearch = true; } } @@ -2921,9 +2811,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f } } -void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPos, - uint8_t index, uint16_t itemId) -{ +void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPos, uint8_t index, uint16_t itemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -2946,7 +2834,7 @@ void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPo return; } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); @@ -2959,12 +2847,9 @@ void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPo if (ret == RETURNVALUE_TOOFARAWAY) { std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerUseItem, this, - playerId, pos, stackPos, index, itemId)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerUseItem, this, playerId, pos, stackPos, index, itemId)); if (it.isRune() || it.type == ITEM_TYPE_POTION) { player->setNextPotionActionTask(task); } else { @@ -2990,8 +2875,7 @@ void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPo if (it.isRune() || it.type == ITEM_TYPE_POTION) { delay = player->getNextPotionActionTime(); } - SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseItem, this, - playerId, pos, stackPos, index, itemId)); + SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseItem, this, playerId, pos, stackPos, index, itemId)); if (it.isRune() || it.type == ITEM_TYPE_POTION) { player->setNextPotionActionTask(task); } else { @@ -3016,8 +2900,7 @@ void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPo } } -void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t itemId) -{ +void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t itemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3052,7 +2935,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin return; } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); @@ -3082,19 +2965,15 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin return; } - //changing the position since its now in the inventory of the player + // changing the position since its now in the inventory of the player internalGetPosition(moveItem, itemPos, itemStackPos); } std::forward_list listDir; if (player->getPathTo(walkToPos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerUseWithCreature, this, - playerId, itemPos, itemStackPos, - creatureId, itemId)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerUseWithCreature, this, playerId, itemPos, itemStackPos, creatureId, itemId)); if (it.isRune() || it.type == ITEM_TYPE_POTION) { player->setNextPotionActionTask(task); } else { @@ -3120,8 +2999,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin if (it.isRune() || it.type == ITEM_TYPE_POTION) { delay = player->getNextPotionActionTime(); } - SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseWithCreature, this, - playerId, fromPos, fromStackPos, creatureId, itemId)); + SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerUseWithCreature, this, playerId, fromPos, fromStackPos, creatureId, itemId)); if (it.isRune() || it.type == ITEM_TYPE_POTION) { player->setNextPotionActionTask(task); @@ -3141,8 +3019,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin g_actions().useItemEx(player, fromPos, creature->getPosition(), creature->getParent()->getThingIndex(creature), item, isHotkey, creature); } -void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) -{ +void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3152,8 +3029,7 @@ void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) player->sendCloseContainer(cid); } -void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) -{ +void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3198,8 +3074,7 @@ void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) } } -void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) -{ +void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) { Player* player = getPlayerByGUID(playerId); if (!player) { return; @@ -3213,8 +3088,7 @@ void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) player->sendContainer(cid, container, container->hasParent(), player->getContainerIndex(cid)); } -void Game::playerRotateItem(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t itemId) -{ +void Game::playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3234,11 +3108,9 @@ void Game::playerRotateItem(uint32_t playerId, const Position& pos, uint8_t stac if (pos.x != 0xFFFF && !Position::areInRange<1, 1, 0>(pos, player->getPosition())) { std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerRotateItem, this, - playerId, pos, stackPos, itemId)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerRotateItem, this, playerId, pos, stackPos, itemId)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -3252,8 +3124,7 @@ void Game::playerRotateItem(uint32_t playerId, const Position& pos, uint8_t stac } } -void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t itemId) -{ +void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { Player* player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; @@ -3274,9 +3145,7 @@ void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position& pos, std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, false)) { g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerBrowseField, - this, playerId, pos)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerBrowseField, this, playerId, pos)); player->setNextWalkActionTask(task); } else { @@ -3288,8 +3157,7 @@ void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position& pos, player->sendPodiumWindow(item, pos, itemId, stackPos); } -void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t& outfit, const Position& pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction) -{ +void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction) { Player* player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; @@ -3316,9 +3184,7 @@ void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t& outfit, const Pos std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, false)) { g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerBrowseField, - this, playerId, pos)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerBrowseField, this, playerId, pos)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -3371,8 +3237,7 @@ void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t& outfit, const Pos } } -void Game::playerWrapableItem(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t itemId) -{ +void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3398,7 +3263,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position& pos, uint8_t st } if (houseTile->getHouse() != house) { player->sendCancelMessage("Only owners can wrap/unwrap inside a house."); - return; + return; } if (!item || item->getID() != itemId || item->hasAttribute(ItemAttribute_t::UNIQUEID) || (!item->isWrapable() && item->getID() != ITEM_DECORATION_KIT)) { @@ -3409,11 +3274,9 @@ void Game::playerWrapableItem(uint32_t playerId, const Position& pos, uint8_t st if (pos.x != 0xFFFF && !Position::areInRange<1, 1, 0>(pos, player->getPosition())) { std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerWrapableItem, this, - playerId, pos, stackPos, itemId)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerWrapableItem, this, playerId, pos, stackPos, itemId)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -3447,8 +3310,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position& pos, uint8_t st if (item->isWrapable() && item->getID() != ITEM_DECORATION_KIT) { wrapItem(item); - } - else if (item->getID() == ITEM_DECORATION_KIT && unWrapId != 0) { + } else if (item->getID() == ITEM_DECORATION_KIT && unWrapId != 0) { auto hiddenCharges = item->getAttribute(ItemAttribute_t::DATE); Item* newItem = transformItem(item, unWrapId); if (newItem) { @@ -3463,7 +3325,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position& pos, uint8_t st addMagicEffect(pos, CONST_ME_POFF); } -Item* Game::wrapItem(Item *item) { +Item* Game::wrapItem(Item* item) { uint16_t oldItemID = item->getID(); Item* newItem = transformItem(item, ITEM_DECORATION_KIT); newItem->setCustomAttribute("unWrapId", static_cast(oldItemID)); @@ -3478,8 +3340,7 @@ Item* Game::wrapItem(Item *item) { return newItem; } -void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string& text) -{ +void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string &text) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3538,14 +3399,13 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: player->setWriteItem(nullptr); } -void Game::playerBrowseField(uint32_t playerId, const Position& pos) -{ +void Game::playerBrowseField(uint32_t playerId, const Position &pos) { Player* player = getPlayerByID(playerId); if (!player) { return; } - const Position& playerPos = player->getPosition(); + const Position &playerPos = player->getPosition(); if (playerPos.z != pos.z) { player->sendCancelMessage(playerPos.z > pos.z ? RETURNVALUE_FIRSTGOUPSTAIRS : RETURNVALUE_FIRSTGODOWNSTAIRS); return; @@ -3554,11 +3414,8 @@ void Game::playerBrowseField(uint32_t playerId, const Position& pos) if (!Position::areInRange<1, 1>(playerPos, pos)) { std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, - std::bind(&Game::playerBrowseField, - this, playerId, pos)); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerBrowseField, this, playerId, pos)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -3598,8 +3455,7 @@ void Game::playerBrowseField(uint32_t playerId, const Position& pos) } } -void Game::playerStowItem(uint32_t playerId, const Position& pos, uint16_t itemId, uint8_t stackpos, uint8_t count, bool allItems) -{ +void Game::playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackpos, uint8_t count, bool allItems) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3634,8 +3490,7 @@ void Game::playerStowItem(uint32_t playerId, const Position& pos, uint16_t itemI } } -void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t count, uint8_t) -{ +void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t count, uint8_t) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3645,7 +3500,7 @@ void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t coun return; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0 || count == 0) { return; } @@ -3685,7 +3540,7 @@ void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t coun std::stringstream ss; uint32_t WithdrawCount = (SlotsWith > capWith ? capWith : SlotsWith); uint32_t NoWithdrawCount = (noSlotsWith < noCapWith ? noCapWith : noSlotsWith); - const char * NoWithdrawMsg = (noSlotsWith < noCapWith ? "capacity" : "slots"); + const char* NoWithdrawMsg = (noSlotsWith < noCapWith ? "capacity" : "slots"); if (WithdrawCount != count) { ss << "Retrieved " << WithdrawCount << "x " << it.name << ".\n"; @@ -3708,8 +3563,7 @@ void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t coun } } -void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index) -{ +void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3728,8 +3582,7 @@ void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_ player->sendContainer(containerId, container, container->hasParent(), index); } -void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string& text) -{ +void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string &text) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3746,9 +3599,7 @@ void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t w player->setEditHouse(nullptr); } -void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t stackPos, - uint32_t tradePlayerId, uint16_t itemId) -{ +void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t stackPos, uint32_t tradePlayerId, uint16_t itemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3794,8 +3645,8 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st } } - const Position& playerPosition = player->getPosition(); - const Position& tradeItemPosition = tradeItem->getPosition(); + const Position &playerPosition = player->getPosition(); + const Position &tradeItemPosition = tradeItem->getPosition(); if (playerPosition.z != tradeItemPosition.z) { player->sendCancelMessage(playerPosition.z > tradeItemPosition.z ? RETURNVALUE_FIRSTGOUPSTAIRS : RETURNVALUE_FIRSTGODOWNSTAIRS); return; @@ -3804,11 +3655,9 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st if (!Position::areInRange<1, 1>(tradeItemPosition, playerPosition)) { std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { - g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, - this, player->getID(), listDir))); + g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerRequestTrade, this, - playerId, pos, stackPos, tradePlayerId, itemId)); + SchedulerTask* task = createSchedulerTask(400, std::bind(&Game::playerRequestTrade, this, playerId, pos, stackPos, tradePlayerId, itemId)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -3818,7 +3667,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st Container* tradeItemContainer = tradeItem->getContainer(); if (tradeItemContainer) { - for (const auto& it : tradeItems) { + for (const auto &it : tradeItems) { Item* item = it.first; if (tradeItem == item) { player->sendTextMessage(MESSAGE_TRADE, "This item is already being traded."); @@ -3837,7 +3686,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st } } } else { - for (const auto& it : tradeItems) { + for (const auto &it : tradeItems) { Item* item = it.first; if (tradeItem == item) { player->sendTextMessage(MESSAGE_TRADE, "This item is already being traded."); @@ -3865,8 +3714,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st internalStartTrade(player, tradePartner, tradeItem); } -bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeItem) -{ +bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeItem) { if (player->tradeState != TRADE_NONE && !(player->tradeState == TRADE_ACKNOWLEDGE && player->tradePartner == tradePartner)) { player->sendCancelMessage(RETURNVALUE_YOUAREALREADYTRADING); return false; @@ -3898,8 +3746,7 @@ bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeI return true; } -void Game::playerAcceptTrade(uint32_t playerId) -{ +void Game::playerAcceptTrade(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -3999,8 +3846,7 @@ void Game::playerAcceptTrade(uint32_t playerId) } } -std::string Game::getTradeErrorDescription(ReturnValue ret, Item* item) -{ +std::string Game::getTradeErrorDescription(ReturnValue ret, Item* item) { if (item) { if (ret == RETURNVALUE_NOTENOUGHCAPACITY) { std::ostringstream ss; @@ -4012,7 +3858,8 @@ std::string Game::getTradeErrorDescription(ReturnValue ret, Item* item) ss << " this object."; } - ss << std::endl << ' ' << item->getWeightDescription(); + ss << std::endl + << ' ' << item->getWeightDescription(); return ss.str(); } else if (ret == RETURNVALUE_NOTENOUGHROOM || ret == RETURNVALUE_CONTAINERNOTENOUGHROOM) { std::ostringstream ss; @@ -4030,8 +3877,7 @@ std::string Game::getTradeErrorDescription(ReturnValue ret, Item* item) return "Trade could not be completed."; } -void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t index) -{ +void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t index) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4053,12 +3899,13 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t return; } - const Position& playerPosition = player->getPosition(); - const Position& tradeItemPosition = tradeItem->getPosition(); + const Position &playerPosition = player->getPosition(); + const Position &tradeItemPosition = tradeItem->getPosition(); int32_t lookDistance = std::max( - Position::getDistanceX(playerPosition, tradeItemPosition), - Position::getDistanceY(playerPosition, tradeItemPosition)); + Position::getDistanceX(playerPosition, tradeItemPosition), + Position::getDistanceY(playerPosition, tradeItemPosition) + ); if (index == 0) { g_events().eventPlayerOnLookInTrade(player, tradePartner, tradeItem, lookDistance); return; @@ -4069,7 +3916,7 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t return; } - std::vector containers {tradeContainer}; + std::vector containers { tradeContainer }; size_t i = 0; while (i < containers.size()) { const Container* container = containers[i++]; @@ -4087,8 +3934,7 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t } } -void Game::playerCloseTrade(uint32_t playerId) -{ +void Game::playerCloseTrade(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4097,8 +3943,7 @@ void Game::playerCloseTrade(uint32_t playerId) internalCloseTrade(player); } -void Game::internalCloseTrade(Player* player) -{ +void Game::internalCloseTrade(Player* player) { Player* tradePartner = player->tradePartner; if ((tradePartner && tradePartner->getTradeState() == TRADE_TRANSFER) || player->getTradeState() == TRADE_TRANSFER) { return; @@ -4141,9 +3986,7 @@ void Game::internalCloseTrade(Player* player) } } -void Game::playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, - bool ignoreCap/* = false*/, bool inBackpacks/* = false*/) -{ +void Game::playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, bool ignoreCap /* = false*/, bool inBackpacks /* = false*/) { if (amount == 0) { return; } @@ -4158,7 +4001,7 @@ void Game::playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint return; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0) { return; } @@ -4181,8 +4024,7 @@ void Game::playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint player->updateUIExhausted(); } -void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, bool ignoreEquipped) -{ +void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, bool ignoreEquipped) { if (amount == 0) { return; } @@ -4197,7 +4039,7 @@ void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uin return; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0) { return; } @@ -4216,8 +4058,7 @@ void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uin player->updateUIExhausted(); } -void Game::playerCloseShop(uint32_t playerId) -{ +void Game::playerCloseShop(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4226,8 +4067,7 @@ void Game::playerCloseShop(uint32_t playerId) player->closeShopWindow(); } -void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) -{ +void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4238,7 +4078,7 @@ void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) return; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0) { return; } @@ -4254,8 +4094,7 @@ void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) merchant->onPlayerCheckItem(player, it.id, count); } -void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position& pos, uint8_t stackPos) -{ +void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, uint8_t stackPos) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4289,8 +4128,7 @@ void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position& pos, g_events().eventPlayerOnLook(player, pos, thing, stackPos, lookDistance); } -void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) -{ +void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4305,14 +4143,14 @@ void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) return; } - const Position& creaturePos = creature->getPosition(); + const Position &creaturePos = creature->getPosition(); if (!player->canSee(creaturePos)) { return; } int32_t lookDistance; if (creature != player) { - const Position& playerPos = player->getPosition(); + const Position &playerPos = player->getPosition(); lookDistance = std::max(Position::getDistanceX(playerPos, creaturePos), Position::getDistanceY(playerPos, creaturePos)); if (playerPos.z != creaturePos.z) { lookDistance += 15; @@ -4324,8 +4162,7 @@ void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) g_events().eventPlayerOnLookInBattleList(player, creature, lookDistance); } -void Game::playerQuickLoot(uint32_t playerId, const Position& pos, uint16_t itemId, uint8_t stackPos, Item* defaultItem, bool lootAllCorpses, bool autoLoot) -{ +void Game::playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, Item* defaultItem, bool lootAllCorpses, bool autoLoot) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4333,24 +4170,18 @@ void Game::playerQuickLoot(uint32_t playerId, const Position& pos, uint16_t item if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); - SchedulerTask* task = createSchedulerTask(delay, std::bind( - &Game::playerQuickLoot, - this, player->getID(), pos, - itemId, stackPos, defaultItem, lootAllCorpses, autoLoot)); + SchedulerTask* task = createSchedulerTask(delay, std::bind(&Game::playerQuickLoot, this, player->getID(), pos, itemId, stackPos, defaultItem, lootAllCorpses, autoLoot)); player->setNextActionTask(task); return; } if (!autoLoot && pos.x != 0xffff) { if (!Position::areInRange<1, 1, 0>(pos, player->getPosition())) { - //need to walk to the corpse first before looting it + // need to walk to the corpse first before looting it std::forward_list listDir; if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher().addTask(createTask(std::bind(&Game::playerAutoWalk, this, player->getID(), listDir))); - SchedulerTask* task = createSchedulerTask(0, std::bind( - &Game::playerQuickLoot, - this, player->getID(), pos, - itemId, stackPos, defaultItem, lootAllCorpses, autoLoot)); + SchedulerTask* task = createSchedulerTask(0, std::bind(&Game::playerQuickLoot, this, player->getID(), pos, itemId, stackPos, defaultItem, lootAllCorpses, autoLoot)); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -4457,30 +4288,29 @@ void Game::playerQuickLoot(uint32_t playerId, const Position& pos, uint16_t item return; } -void Game::playerLootAllCorpses(Player* player, const Position& pos, bool lootAllCorpses) { +void Game::playerLootAllCorpses(Player* player, const Position &pos, bool lootAllCorpses) { if (lootAllCorpses) { - Tile *tile = g_game().map.getTile(pos.x, pos.y, pos.z); + Tile* tile = g_game().map.getTile(pos.x, pos.y, pos.z); if (!tile) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - const TileItemVector *itemVector = tile->getItemList(); + const TileItemVector* itemVector = tile->getItemList(); uint16_t corpses = 0; - for (Item *tileItem: *itemVector) { + for (Item* tileItem : *itemVector) { if (!tileItem) { continue; } - Container *tileCorpse = tileItem->getContainer(); + Container* tileCorpse = tileItem->getContainer(); if (!tileCorpse || !tileCorpse->isCorpse() || tileCorpse->hasAttribute(ItemAttribute_t::UNIQUEID) || tileCorpse->hasAttribute(ItemAttribute_t::ACTIONID)) { continue; } if (!tileCorpse->isRewardCorpse() - && tileCorpse->getCorpseOwner() != 0 - && !player->canOpenCorpse(tileCorpse->getCorpseOwner())) - { + && tileCorpse->getCorpseOwner() != 0 + && !player->canOpenCorpse(tileCorpse->getCorpseOwner())) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); SPDLOG_DEBUG("Player {} cannot loot corpse from id {} in position {}", player->getName(), tileItem->getID(), tileItem->getPosition()); continue; @@ -4507,8 +4337,7 @@ void Game::playerLootAllCorpses(Player* player, const Position& pos, bool lootAl browseField = false; } -void Game::playerSetLootContainer(uint32_t playerId, ObjectCategory_t category, const Position& pos, uint16_t itemId, uint8_t stackPos) -{ +void Game::playerSetLootContainer(uint32_t playerId, ObjectCategory_t category, const Position &pos, uint16_t itemId, uint8_t stackPos) { Player* player = getPlayerByID(playerId); if (!player || pos.x != 0xffff) { return; @@ -4547,8 +4376,7 @@ void Game::playerSetLootContainer(uint32_t playerId, ObjectCategory_t category, } } -void Game::playerClearLootContainer(uint32_t playerId, ObjectCategory_t category) -{ +void Game::playerClearLootContainer(uint32_t playerId, ObjectCategory_t category) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4565,24 +4393,21 @@ void Game::playerClearLootContainer(uint32_t playerId, ObjectCategory_t category } } -void Game::playerOpenLootContainer(uint32_t playerId, ObjectCategory_t category) -{ - Player* player = getPlayerByID(playerId); - if (!player) { - return; - } +void Game::playerOpenLootContainer(uint32_t playerId, ObjectCategory_t category) { + Player* player = getPlayerByID(playerId); + if (!player) { + return; + } - Container* container = player->getLootContainer(category); - if (!container) { - return; - } + Container* container = player->getLootContainer(category); + if (!container) { + return; + } - player->sendContainer(static_cast(container->getID()), container, container->hasParent(), 0); + player->sendContainer(static_cast(container->getID()), container, container->hasParent(), 0); } - -void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) -{ +void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4591,8 +4416,7 @@ void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) player->quickLootFallbackToMainContainer = fallback; } -void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector itemIds) -{ +void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector itemIds) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4605,8 +4429,7 @@ void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t fi /******************************************************************************* * Depot search system ******************************************************************************/ -void Game::playerRequestDepotItems(uint32_t playerId) -{ +void Game::playerRequestDepotItems(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player || !player->isDepotSearchAvailable()) { return; @@ -4621,8 +4444,7 @@ void Game::playerRequestDepotItems(uint32_t playerId) player->updateUIExhausted(); } -void Game::playerRequestCloseDepotSearch(uint32_t playerId) -{ +void Game::playerRequestCloseDepotSearch(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; @@ -4632,8 +4454,7 @@ void Game::playerRequestCloseDepotSearch(uint32_t playerId) player->sendCloseDepotSearch(); } -void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint8_t tier) -{ +void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint8_t tier) { Player* player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; @@ -4648,8 +4469,7 @@ void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint player->updateUIExhausted(); } -void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, uint8_t tier, uint8_t type) -{ +void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, uint8_t tier, uint8_t type) { Player* player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpenOnItem(itemId)) { return; @@ -4664,8 +4484,7 @@ void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, player->updateUIExhausted(); } -void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position& pos) -{ +void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position &pos) { Player* player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; @@ -4681,8 +4500,7 @@ void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Po } /*******************************************************************************/ -void Game::playerCancelAttackAndFollow(uint32_t playerId) -{ +void Game::playerCancelAttackAndFollow(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4693,8 +4511,7 @@ void Game::playerCancelAttackAndFollow(uint32_t playerId) player->stopWalk(); } -void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) -{ +void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4725,8 +4542,7 @@ void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) g_dispatcher().addTask(createTask(std::bind(&Game::updateCreatureWalk, this, player->getID()))); } -void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) -{ +void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4737,8 +4553,7 @@ void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) player->setFollowCreature(getCreatureByID(creatureId)); } -void Game::playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool chaseMode, bool secureMode) -{ +void Game::playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool chaseMode, bool secureMode) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4749,8 +4564,7 @@ void Game::playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool ch player->setSecureMode(secureMode); } -void Game::playerRequestAddVip(uint32_t playerId, const std::string& name) -{ +void Game::playerRequestAddVip(uint32_t playerId, const std::string &name) { if (name.length() > 25) { return; } @@ -4790,8 +4604,7 @@ void Game::playerRequestAddVip(uint32_t playerId, const std::string& name) } } -void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) -{ +void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4800,8 +4613,7 @@ void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) player->removeVIP(guid); } -void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string& description, uint32_t icon, bool notify) -{ +void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string &description, uint32_t icon, bool notify) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4810,8 +4622,7 @@ void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::str player->editVIP(guid, description, icon, notify); } -void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t slot, bool protectionCharm) -{ +void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t slot, bool protectionCharm) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4840,33 +4651,27 @@ void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t player->onApplyImbuement(imbuement, item, slot, protectionCharm); } -void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) -{ +void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) { Player* player = getPlayerByID(playerid); - if (!player) - { + if (!player) { return; } - if (!player->hasImbuingItem ()) - { + if (!player->hasImbuingItem()) { return; } Item* item = player->imbuingItem; - if (!item) - { + if (!item) { return; } player->onClearImbuement(item, slot); } -void Game::playerCloseImbuementWindow(uint32_t playerid) -{ +void Game::playerCloseImbuementWindow(uint32_t playerid) { Player* player = getPlayerByID(playerid); - if (!player) - { + if (!player) { return; } @@ -4874,8 +4679,7 @@ void Game::playerCloseImbuementWindow(uint32_t playerid) return; } -void Game::playerTurn(uint32_t playerId, Direction dir) -{ +void Game::playerTurn(uint32_t playerId, Direction dir) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4889,8 +4693,7 @@ void Game::playerTurn(uint32_t playerId, Direction dir) internalCreatureTurn(player, dir); } -void Game::playerRequestOutfit(uint32_t playerId) -{ +void Game::playerRequestOutfit(uint32_t playerId) { if (!g_configManager().getBoolean(ALLOW_CHANGEOUTFIT)) { return; } @@ -4903,8 +4706,7 @@ void Game::playerRequestOutfit(uint32_t playerId) player->sendOutfitWindow(); } -void Game::playerToggleMount(uint32_t playerId, bool mount) -{ +void Game::playerToggleMount(uint32_t playerId, bool mount) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4913,8 +4715,7 @@ void Game::playerToggleMount(uint32_t playerId, bool mount) player->toggleMount(mount); } -void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMountRandomized/* = 0*/) -{ +void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMountRandomized /* = 0*/) { if (!g_configManager().getBoolean(ALLOW_CHANGEOUTFIT)) { return; } @@ -4978,8 +4779,7 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMoun } } -void Game::playerShowQuestLog(uint32_t playerId) -{ +void Game::playerShowQuestLog(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4988,8 +4788,7 @@ void Game::playerShowQuestLog(uint32_t playerId) g_events().eventPlayerOnRequestQuestLog(player); } -void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) -{ +void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -4998,9 +4797,7 @@ void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) g_events().eventPlayerOnRequestQuestLine(player, questId); } -void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, - const std::string& receiver, const std::string& text) -{ +void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, const std::string &receiver, const std::string &text) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -5020,7 +4817,6 @@ void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, return; } - if (!text.empty() && text.front() == '/' && player->isAccessPlayer()) { return; } @@ -5066,8 +4862,7 @@ void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, } } -bool Game::playerSaySpell(Player* player, SpeakClasses type, const std::string& text) -{ +bool Game::playerSaySpell(Player* player, SpeakClasses type, const std::string &text) { if (player->walkExhausted()) { return true; } @@ -5097,14 +4892,11 @@ bool Game::playerSaySpell(Player* player, SpeakClasses type, const std::string& return false; } -void Game::playerWhisper(Player* player, const std::string& text) -{ +void Game::playerWhisper(Player* player, const std::string &text) { SpectatorHashSet spectators; - map.getSpectators(spectators, player->getPosition(), false, false, - Map::maxClientViewportX, Map::maxClientViewportX, - Map::maxClientViewportY, Map::maxClientViewportY); + map.getSpectators(spectators, player->getPosition(), false, false, Map::maxClientViewportX, Map::maxClientViewportX, Map::maxClientViewportY, Map::maxClientViewportY); - //send to client + // send to client for (Creature* spectator : spectators) { if (Player* spectatorPlayer = spectator->getPlayer()) { if (!Position::areInRange<1, 1>(player->getPosition(), spectatorPlayer->getPosition())) { @@ -5115,14 +4907,13 @@ void Game::playerWhisper(Player* player, const std::string& text) } } - //event method + // event method for (Creature* spectator : spectators) { spectator->onCreatureSay(player, TALKTYPE_WHISPER, text); } } -bool Game::playerYell(Player* player, const std::string& text) -{ +bool Game::playerYell(Player* player, const std::string &text) { if (player->getLevel() == 1) { player->sendTextMessage(MESSAGE_FAILURE, "You may not yell as long as you are on level 1."); return false; @@ -5142,9 +4933,7 @@ bool Game::playerYell(Player* player, const std::string& text) return true; } -bool Game::playerSpeakTo(Player* player, SpeakClasses type, const std::string& receiver, - const std::string& text) -{ +bool Game::playerSpeakTo(Player* player, SpeakClasses type, const std::string &receiver, const std::string &text) { Player* toPlayer = getPlayerByName(receiver); if (!toPlayer) { player->sendTextMessage(MESSAGE_FAILURE, "A player with this name is not online."); @@ -5170,8 +4959,7 @@ bool Game::playerSpeakTo(Player* player, SpeakClasses type, const std::string& r return true; } -void Game::playerSpeakToNpc(Player* player, const std::string& text) -{ +void Game::playerSpeakToNpc(Player* player, const std::string &text) { if (player == nullptr) { SPDLOG_ERROR("[Game::playerSpeakToNpc] - Player is nullptr"); return; @@ -5195,19 +4983,15 @@ void Game::playerSpeakToNpc(Player* player, const std::string& text) } //-- -bool Game::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/, - int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const -{ +bool Game::canThrowObjectTo(const Position &fromPos, const Position &toPos, bool checkLineOfSight /*= true*/, int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const { return map.canThrowObjectTo(fromPos, toPos, checkLineOfSight, rangex, rangey); } -bool Game::isSightClear(const Position& fromPos, const Position& toPos, bool floorCheck) const -{ +bool Game::isSightClear(const Position &fromPos, const Position &toPos, bool floorCheck) const { return map.isSightClear(fromPos, toPos, floorCheck); } -bool Game::internalCreatureTurn(Creature* creature, Direction dir) -{ +bool Game::internalCreatureTurn(Creature* creature, Direction dir) { if (creature->getDirection() == dir) { return false; } @@ -5222,7 +5006,7 @@ bool Game::internalCreatureTurn(Creature* creature, Direction dir) map.getSpectators(spectators, creature->getPosition(), true, true); for (Creature* spectator : spectators) { Player* tmpPlayer = spectator->getPlayer(); - if(!tmpPlayer) { + if (!tmpPlayer) { continue; } tmpPlayer->sendCreatureTurn(creature); @@ -5230,9 +5014,7 @@ bool Game::internalCreatureTurn(Creature* creature, Direction dir) return true; } -bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std::string& text, - bool ghostMode, SpectatorHashSet* spectatorsPtr/* = nullptr*/, const Position* pos/* = nullptr*/) -{ +bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std::string &text, bool ghostMode, SpectatorHashSet* spectatorsPtr /* = nullptr*/, const Position* pos /* = nullptr*/) { if (text.empty()) { return false; } @@ -5249,19 +5031,15 @@ bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std: // used (hopefully the compiler will optimize away the construction of // the temporary when it's not used). if (type != TALKTYPE_YELL && type != TALKTYPE_MONSTER_YELL) { - map.getSpectators(spectators, *pos, false, false, - Map::maxClientViewportX, Map::maxClientViewportX, - Map::maxClientViewportY, Map::maxClientViewportY); + map.getSpectators(spectators, *pos, false, false, Map::maxClientViewportX, Map::maxClientViewportX, Map::maxClientViewportY, Map::maxClientViewportY); } else { - map.getSpectators(spectators, *pos, true, false, - (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportX + 1) * 2, - (Map::maxClientViewportY + 1) * 2, (Map::maxClientViewportY + 1) * 2); + map.getSpectators(spectators, *pos, true, false, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, (Map::maxClientViewportY + 1) * 2); } } else { spectators = (*spectatorsPtr); } - //send to client + // send to client for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { if (!ghostMode || tmpPlayer->canSeeCreature(creature)) { @@ -5270,7 +5048,7 @@ bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std: } } - //event method + // event method for (Creature* spectator : spectators) { spectator->onCreatureSay(creature, type, text); if (creature != spectator) { @@ -5280,8 +5058,7 @@ bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std: return true; } -void Game::checkCreatureWalk(uint32_t creatureId) -{ +void Game::checkCreatureWalk(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->onCreatureWalk(); @@ -5289,24 +5066,21 @@ void Game::checkCreatureWalk(uint32_t creatureId) } } -void Game::updateCreatureWalk(uint32_t creatureId) -{ +void Game::updateCreatureWalk(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->goToFollowCreature(); } } -void Game::checkCreatureAttack(uint32_t creatureId) -{ +void Game::checkCreatureAttack(uint32_t creatureId) { Creature* creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->onAttacking(0); } } -void Game::addCreatureCheck(Creature* creature) -{ +void Game::addCreatureCheck(Creature* creature) { creature->creatureCheck = true; if (creature->inCheckCreaturesVector) { @@ -5319,18 +5093,16 @@ void Game::addCreatureCheck(Creature* creature) creature->incrementReferenceCounter(); } -void Game::removeCreatureCheck(Creature* creature) -{ +void Game::removeCreatureCheck(Creature* creature) { if (creature->inCheckCreaturesVector) { creature->creatureCheck = false; } } -void Game::checkCreatures(size_t index) -{ +void Game::checkCreatures(size_t index) { g_scheduler().addEvent(createSchedulerTask(EVENT_CHECK_CREATURE_INTERVAL, std::bind(&Game::checkCreatures, this, (index + 1) % EVENT_CREATURECOUNT))); - auto& checkCreatureList = checkCreatureLists[index]; + auto &checkCreatureList = checkCreatureLists[index]; size_t it = 0, end = checkCreatureList.size(); while (it < end) { Creature* creature = checkCreatureList[it]; @@ -5355,14 +5127,13 @@ void Game::checkCreatures(size_t index) cleanup(); } -void Game::changeSpeed(Creature* creature, int32_t varSpeedDelta) -{ +void Game::changeSpeed(Creature* creature, int32_t varSpeedDelta) { int32_t varSpeed = creature->getSpeed() - creature->getBaseSpeed(); varSpeed += varSpeedDelta; creature->setSpeed(varSpeed); - //send to clients + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), false, true); for (Creature* spectator : spectators) { @@ -5370,8 +5141,7 @@ void Game::changeSpeed(Creature* creature, int32_t varSpeedDelta) } } -void Game::changePlayerSpeed(Player& player, int32_t varSpeedDelta) -{ +void Game::changePlayerSpeed(Player &player, int32_t varSpeedDelta) { int32_t varSpeed = player.getSpeed() - player.getBaseSpeed(); varSpeed += varSpeedDelta; @@ -5386,7 +5156,7 @@ void Game::changePlayerSpeed(Player& player, int32_t varSpeedDelta) continue; } - const Player *playerSpectator = creatureSpectator->getPlayer(); + const Player* playerSpectator = creatureSpectator->getPlayer(); if (playerSpectator == nullptr) { SPDLOG_ERROR("[Game::changePlayerSpeed] - Player spectator is nullptr"); continue; @@ -5396,8 +5166,7 @@ void Game::changePlayerSpeed(Player& player, int32_t varSpeedDelta) } } -void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outfit) -{ +void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t &outfit) { if (!g_events().eventCreatureOnChangeOutfit(creature, outfit)) { return; } @@ -5408,7 +5177,7 @@ void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outf return; } - //send to clients + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true, true); for (Creature* spectator : spectators) { @@ -5416,9 +5185,8 @@ void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outf } } -void Game::internalCreatureChangeVisible(Creature* creature, bool visible) -{ - //send to clients +void Game::internalCreatureChangeVisible(Creature* creature, bool visible) { + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true, true); for (Creature* spectator : spectators) { @@ -5426,9 +5194,8 @@ void Game::internalCreatureChangeVisible(Creature* creature, bool visible) } } -void Game::changeLight(const Creature* creature) -{ - //send to clients +void Game::changeLight(const Creature* creature) { + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true, true); for (Creature* spectator : spectators) { @@ -5436,9 +5203,8 @@ void Game::changeLight(const Creature* creature) } } -void Game::updateCreatureIcon(const Creature* creature) -{ - //send to clients +void Game::updateCreatureIcon(const Creature* creature) { + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true, true); for (Creature* spectator : spectators) { @@ -5446,8 +5212,7 @@ void Game::updateCreatureIcon(const Creature* creature) } } -void Game::reloadCreature(const Creature* creature) -{ +void Game::reloadCreature(const Creature* creature) { SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), false, true); for (Creature* spectator : spectators) { @@ -5459,8 +5224,7 @@ void Game::reloadCreature(const Creature* creature) } } -bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* target, bool checkDefense, bool checkArmor, bool field) -{ +bool Game::combatBlockHit(CombatDamage &damage, Creature* attacker, Creature* target, bool checkDefense, bool checkArmor, bool field) { if (damage.primary.type == COMBAT_NONE && damage.secondary.type == COMBAT_NONE) { return true; } @@ -5473,7 +5237,7 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta return false; } - static const auto sendBlockEffect = [this](BlockType_t blockType, CombatType_t combatType, const Position& targetPos) { + static const auto sendBlockEffect = [this](BlockType_t blockType, CombatType_t combatType, const Position &targetPos) { if (blockType == BLOCK_DEFENSE) { addMagicEffect(targetPos, CONST_ME_POFF); } else if (blockType == BLOCK_ARMOR) { @@ -5526,11 +5290,11 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta } bool canHeal = false; - CombatDamage damageHeal; - damageHeal.primary.type = COMBAT_HEALING; + CombatDamage damageHeal; + damageHeal.primary.type = COMBAT_HEALING; bool canReflect = false; - CombatDamage damageReflected; + CombatDamage damageReflected; BlockType_t primaryBlockType, secondaryBlockType; if (damage.primary.type != COMBAT_NONE) { @@ -5583,7 +5347,8 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta // Damage healing secondary if (attacker && target->getMonster()) { uint32_t secondaryHealing = target->getMonster()->getHealingCombatValue(damage.secondary.type); - if (secondaryHealing > 0) {; + if (secondaryHealing > 0) { + ; damageHeal.primary.value += std::ceil((damage.secondary.value) * (secondaryHealing / 100.)); canHeal = true; } @@ -5604,8 +5369,7 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta return (primaryBlockType != BLOCK_NONE) && (secondaryBlockType != BLOCK_NONE); } -void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColor_t& color, uint8_t& effect) -{ +void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColor_t &color, uint8_t &effect) { switch (combatType) { case COMBAT_PHYSICALDAMAGE: { Item* splash = nullptr; @@ -5705,10 +5469,9 @@ void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColo } } -bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage& damage, bool isEvent /*= false*/) -{ +bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage &damage, bool isEvent /*= false*/) { using namespace std; - const Position& targetPos = target->getPosition(); + const Position &targetPos = target->getPosition(); if (damage.primary.value > 0) { if (target->getHealth() <= 0) { return false; @@ -5727,7 +5490,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); + const auto &events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); if (!events.empty()) { for (CreatureEvent* creatureEvent : events) { creatureEvent->executeHealthChange(target, attacker, damage); @@ -5768,8 +5531,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage for (Creature* spectator : spectators) { Player* tmpPlayer = spectator->getPlayer(); - if(!tmpPlayer) - { + if (!tmpPlayer) { continue; } @@ -5882,8 +5644,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage if (charmRune_t activeCharm = g_iobestiary().getCharmFromTarget(targetPlayer, g_monsters().getMonsterTypeByRaceId(attackerMonster->getRaceId())); activeCharm != CHARM_NONE && activeCharm != CHARM_CLEANSE) { if (Charm* charm = g_iobestiary().getBestiaryCharm(activeCharm); - charm->type == CHARM_DEFENSIVE && charm->chance > normal_random(0, 100) && - g_iobestiary().parseCharmCombat(charm, targetPlayer, attacker, (damage.primary.value + damage.secondary.value))) { + charm->type == CHARM_DEFENSIVE && charm->chance > normal_random(0, 100) && g_iobestiary().parseCharmCombat(charm, targetPlayer, attacker, (damage.primary.value + damage.secondary.value))) { return false; // Dodge charm } } @@ -5899,12 +5660,12 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } else { manaDamage = manaShield; target->removeCondition(CONDITION_MANASHIELD); - manaShield = 0; + manaShield = 0; } } if (manaDamage != 0) { if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); + const auto &events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { for (CreatureEvent* creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); @@ -5919,7 +5680,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage target->drainMana(attacker, manaDamage); - if(target->getMana() == 0 && manaShield > 0) { + if (target->getMana() == 0 && manaShield > 0) { target->removeCondition(CONDITION_MANASHIELD); } @@ -6000,7 +5761,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); + const auto &events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); if (!events.empty()) { for (CreatureEvent* creatureEvent : events) { creatureEvent->executeHealthChange(target, attacker, damage); @@ -6072,7 +5833,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage return true; } -void Game::updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const Player *player) const { +void Game::updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const Player* player) const { if (!player) { return; } @@ -6088,11 +5849,10 @@ void Game::updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const Playe } void Game::sendDamageMessageAndEffects( - const Creature *attacker, Creature *target, const CombatDamage &damage, - const Position &targetPos, Player *attackerPlayer, Player *targetPlayer, + const Creature* attacker, Creature* target, const CombatDamage &damage, + const Position &targetPos, Player* attackerPlayer, Player* targetPlayer, TextMessage &message, const SpectatorHashSet &spectators, int32_t realDamage -) -{ +) { message.primary.value = damage.primary.value; message.secondary.value = damage.secondary.value; @@ -6101,20 +5861,17 @@ void Game::sendDamageMessageAndEffects( if (shouldSendMessage(message)) { sendMessages(attacker, target, damage, targetPos, attackerPlayer, targetPlayer, message, spectators, realDamage); } - } -bool Game::shouldSendMessage(const TextMessage &message) const -{ +bool Game::shouldSendMessage(const TextMessage &message) const { return message.primary.color != TEXTCOLOR_NONE || message.secondary.color != TEXTCOLOR_NONE; } void Game::sendMessages( - const Creature *attacker, const Creature *target, const CombatDamage &damage, - const Position &targetPos, Player *attackerPlayer, Player *targetPlayer, + const Creature* attacker, const Creature* target, const CombatDamage &damage, + const Position &targetPos, Player* attackerPlayer, Player* targetPlayer, TextMessage &message, const SpectatorHashSet &spectators, int32_t realDamage -) const -{ +) const { if (attackerPlayer) { attackerPlayer->updateImpactTracker(damage.primary.type, damage.primary.value); if (damage.secondary.type != COMBAT_NONE) { @@ -6152,19 +5909,17 @@ void Game::sendMessages( } else if (tmpPlayer == targetPlayer) { buildMessageAsTarget(attacker, damage, attackerPlayer, targetPlayer, message, ss, damageString); } else { - buildMessageAsSpectator(attacker, target, damage, targetPlayer, message, ss, damageString, - spectatorMessage); + buildMessageAsSpectator(attacker, target, damage, targetPlayer, message, ss, damageString, spectatorMessage); } tmpPlayer->sendTextMessage(message); } } void Game::buildMessageAsSpectator( - const Creature *attacker, const Creature *target, const CombatDamage &damage, - const Player *targetPlayer, TextMessage &message, std::stringstream &ss, + const Creature* attacker, const Creature* target, const CombatDamage &damage, + const Player* targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString, std::string &spectatorMessage -) const -{ +) const { if (spectatorMessage.empty()) { ss.str({}); ss << ucfirst(target->getNameDescription()) << " loses " << damageString; @@ -6192,11 +5947,10 @@ void Game::buildMessageAsSpectator( } void Game::buildMessageAsTarget( - const Creature *attacker, const CombatDamage &damage, const Player *attackerPlayer, - const Player *targetPlayer, TextMessage &message, std::stringstream &ss, + const Creature* attacker, const CombatDamage &damage, const Player* attackerPlayer, + const Player* targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString -) const -{ +) const { ss.str({}); ss << "You lose " << damageString; if (!attacker) { @@ -6214,10 +5968,9 @@ void Game::buildMessageAsTarget( } void Game::buildMessageAsAttacker( - const Creature *target, const CombatDamage &damage, TextMessage &message, + const Creature* target, const CombatDamage &damage, TextMessage &message, std::stringstream &ss, const std::string &damageString -) const -{ +) const { ss.str({}); ss << ucfirst(target->getNameDescription()) << " loses " << damageString << " due to your attack."; if (damage.extension) { @@ -6231,10 +5984,9 @@ void Game::buildMessageAsAttacker( } void Game::sendEffects( - Creature *target, const CombatDamage &damage, const Position &targetPos, TextMessage &message, + Creature* target, const CombatDamage &damage, const Position &targetPos, TextMessage &message, const SpectatorHashSet &spectators -) -{ +) { uint8_t hitEffect; if (message.primary.value) { combatGetTypeInfo(damage.primary.type, target, message.primary.color, hitEffect); @@ -6252,10 +6004,9 @@ void Game::sendEffects( } void Game::applyCharmRune( - const Monster* targetMonster, Player* attackerPlayer, Creature* target, const int32_t& realDamage -) const -{ - if(!targetMonster){ + const Monster* targetMonster, Player* attackerPlayer, Creature* target, const int32_t &realDamage +) const { + if (!targetMonster) { return; } if (charmRune_t activeCharm = g_iobestiary().getCharmFromTarget(attackerPlayer, g_monsters().getMonsterTypeByRaceId(targetMonster->getRaceId())); @@ -6268,15 +6019,14 @@ void Game::applyCharmRune( } void Game::applyManaLeech( - Player* attackerPlayer, const Monster* targetMonster, const CombatDamage& damage, const int32_t& realDamage -) const -{ + Player* attackerPlayer, const Monster* targetMonster, const CombatDamage &damage, const int32_t &realDamage +) const { uint16_t manaChance = attackerPlayer->getSkillLevel(SKILL_MANA_LEECH_CHANCE); uint16_t manaSkill = attackerPlayer->getSkillLevel(SKILL_MANA_LEECH_AMOUNT); if (normal_random(0, 100) >= manaChance) { return; } - // Void charm rune + // Void charm rune if (targetMonster) { if (uint16_t playerCharmRaceidVoid = attackerPlayer->parseRacebyCharm(CHARM_VOID, false, 0); playerCharmRaceidVoid != 0 && playerCharmRaceidVoid == targetMonster->getRace()) { @@ -6297,9 +6047,8 @@ void Game::applyManaLeech( } void Game::applyLifeLeech( - Player* attackerPlayer, const Monster* targetMonster, const CombatDamage& damage, const int32_t& realDamage -) const -{ + Player* attackerPlayer, const Monster* targetMonster, const CombatDamage &damage, const int32_t &realDamage +) const { uint16_t lifeChance = attackerPlayer->getSkillLevel(SKILL_LIFE_LEECH_CHANCE); uint16_t lifeSkill = attackerPlayer->getSkillLevel(SKILL_LIFE_LEECH_AMOUNT); if (normal_random(0, 100) >= lifeChance) { @@ -6324,15 +6073,13 @@ void Game::applyLifeLeech( Combat::doCombatHealth(nullptr, attackerPlayer, tmpDamage, tmpParams); } -int32_t Game::calculateLeechAmount(const int32_t& realDamage, const uint16_t& skillAmount, int targetsAffected) const -{ +int32_t Game::calculateLeechAmount(const int32_t &realDamage, const uint16_t &skillAmount, int targetsAffected) const { auto intermediateResult = realDamage * (skillAmount / 100.0) * (0.1 * targetsAffected + 0.9) / targetsAffected; return std::clamp(static_cast(std::lround(intermediateResult)), 0, realDamage); } -bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& damage) -{ - const Position& targetPos = target->getPosition(); +bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage &damage) { + const Position &targetPos = target->getPosition(); int32_t manaChange = damage.primary.value + damage.secondary.value; if (manaChange > 0) { Player* attackerPlayer; @@ -6348,7 +6095,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& } if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); + const auto &events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { for (CreatureEvent* creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); @@ -6390,8 +6137,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& for (Creature* spectator : spectators) { Player* tmpPlayer = spectator->getPlayer(); - if(!tmpPlayer) - { + if (!tmpPlayer) { continue; } @@ -6446,7 +6192,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& } if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); + const auto &events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { for (CreatureEvent* creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); @@ -6457,7 +6203,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& } if (targetPlayer && attacker && attacker->getMonster()) { - //Charm rune (target as player) + // Charm rune (target as player) MonsterType* mType = g_monsters().getMonsterType(attacker->getName()); if (mType) { charmRune_t activeCharm = g_iobestiary().getCharmFromTarget(targetPlayer, mType); @@ -6490,8 +6236,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& for (Creature* spectator : spectators) { Player* tmpPlayer = spectator->getPlayer(); - if(!tmpPlayer) - { + if (!tmpPlayer) { continue; } @@ -6537,15 +6282,13 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& return true; } -void Game::addCreatureHealth(const Creature* target) -{ +void Game::addCreatureHealth(const Creature* target) { SpectatorHashSet spectators; map.getSpectators(spectators, target->getPosition(), true, true); addCreatureHealth(spectators, target); } -void Game::addCreatureHealth(const SpectatorHashSet& spectators, const Creature* target) -{ +void Game::addCreatureHealth(const SpectatorHashSet &spectators, const Creature* target) { uint8_t healthPercent = std::ceil((static_cast(target->getHealth()) / std::max(target->getMaxHealth(), 1)) * 100); if (const Player* targetPlayer = target->getPlayer()) { if (Party* party = targetPlayer->getParty()) { @@ -6565,16 +6308,14 @@ void Game::addCreatureHealth(const SpectatorHashSet& spectators, const Creature* } } -void Game::addPlayerMana(const Player* target) -{ +void Game::addPlayerMana(const Player* target) { if (Party* party = target->getParty()) { uint8_t manaPercent = std::ceil((static_cast(target->getMana()) / std::max(target->getMaxMana(), 1)) * 100); party->updatePlayerMana(target, manaPercent); } } -void Game::addPlayerVocation(const Player* target) -{ +void Game::addPlayerVocation(const Player* target) { if (Party* party = target->getParty()) { party->updatePlayerVocation(target); } @@ -6589,15 +6330,13 @@ void Game::addPlayerVocation(const Player* target) } } -void Game::addMagicEffect(const Position& pos, uint8_t effect) -{ +void Game::addMagicEffect(const Position &pos, uint8_t effect) { SpectatorHashSet spectators; map.getSpectators(spectators, pos, true, true); addMagicEffect(spectators, pos, effect); } -void Game::addMagicEffect(const SpectatorHashSet& spectators, const Position& pos, uint8_t effect) -{ +void Game::addMagicEffect(const SpectatorHashSet &spectators, const Position &pos, uint8_t effect) { for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendMagicEffect(pos, effect); @@ -6605,16 +6344,14 @@ void Game::addMagicEffect(const SpectatorHashSet& spectators, const Position& po } } -void Game::addDistanceEffect(const Position& fromPos, const Position& toPos, uint8_t effect) -{ +void Game::addDistanceEffect(const Position &fromPos, const Position &toPos, uint8_t effect) { SpectatorHashSet spectators; map.getSpectators(spectators, fromPos, false, true); map.getSpectators(spectators, toPos, false, true); addDistanceEffect(spectators, fromPos, toPos, effect); } -void Game::addDistanceEffect(const SpectatorHashSet& spectators, const Position& fromPos, const Position& toPos, uint8_t effect) -{ +void Game::addDistanceEffect(const SpectatorHashSet &spectators, const Position &fromPos, const Position &toPos, uint8_t effect) { for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendDistanceShoot(fromPos, toPos, effect); @@ -6622,24 +6359,21 @@ void Game::addDistanceEffect(const SpectatorHashSet& spectators, const Position& } } -void Game::checkImbuements() -{ +void Game::checkImbuements() { g_scheduler().addEvent(createSchedulerTask(EVENT_IMBUEMENT_INTERVAL, std::bind(&Game::checkImbuements, this))); std::vector toErase; - for (const auto& [mapPlayerId, mapPlayer] : getPlayers()) { + for (const auto &[mapPlayerId, mapPlayer] : getPlayers()) { if (!mapPlayer) { continue; } mapPlayer->updateInventoryImbuement(); } - } -void Game::checkLight() -{ +void Game::checkLight() { g_scheduler().addEvent(createSchedulerTask(EVENT_LIGHTINTERVAL_MS, std::bind(&Game::checkLight, this))); lightHour += lightHourDelta; @@ -6685,30 +6419,28 @@ void Game::checkLight() LightInfo lightInfo = getWorldLightInfo(); if (lightChange) { - for ([[maybe_unused]] const auto& [mapPlayerId, mapPlayer] : getPlayers()) { + for ([[maybe_unused]] const auto &[mapPlayerId, mapPlayer] : getPlayers()) { mapPlayer->sendWorldLight(lightInfo); mapPlayer->sendTibiaTime(lightHour); } } else { - for ([[maybe_unused]] const auto& [mapPlayerId, mapPlayer] : getPlayers()) { + for ([[maybe_unused]] const auto &[mapPlayerId, mapPlayer] : getPlayers()) { mapPlayer->sendTibiaTime(lightHour); } } if (currentLightState != lightState) { currentLightState = lightState; - for (const auto& [eventName, globalEvent] : g_globalEvents().getEventMap(GLOBALEVENT_PERIODCHANGE)) { + for (const auto &[eventName, globalEvent] : g_globalEvents().getEventMap(GLOBALEVENT_PERIODCHANGE)) { globalEvent.executePeriodChange(lightState, lightInfo); } } } -LightInfo Game::getWorldLightInfo() const -{ - return {lightLevel, 0xD7}; +LightInfo Game::getWorldLightInfo() const { + return { lightLevel, 0xD7 }; } -bool Game::gameIsDay() -{ +bool Game::gameIsDay() { if (lightHour >= (6 * 60) && lightHour <= (18 * 60)) { isDay = true; } else { @@ -6718,14 +6450,12 @@ bool Game::gameIsDay() return isDay; } -void Game::dieSafely(std::string errorMsg /* = "" */) -{ +void Game::dieSafely(std::string errorMsg /* = "" */) { SPDLOG_ERROR(errorMsg); shutdown(); } -void Game::shutdown() -{ +void Game::shutdown() { std::string url = g_configManager().getString(DISCORD_WEBHOOK_URL); webhook_send_message("Server is shutting down", "Shutting down...", WEBHOOK_COLOR_OFFLINE, url); @@ -6750,9 +6480,8 @@ void Game::shutdown() exit(0); } -void Game::cleanup() -{ - //free memory +void Game::cleanup() { + // free memory for (auto creature : ToReleaseCreatures) { creature->decrementReferenceCounter(); } @@ -6764,13 +6493,11 @@ void Game::cleanup() ToReleaseItems.clear(); } -void Game::ReleaseCreature(Creature* creature) -{ +void Game::ReleaseCreature(Creature* creature) { ToReleaseCreatures.push_back(creature); } -void Game::ReleaseItem(Item* item) -{ +void Game::ReleaseItem(Item* item) { if (!item) { return; } @@ -6778,8 +6505,7 @@ void Game::ReleaseItem(Item* item) ToReleaseItems.push_back(item); } -void Game::addBestiaryList(uint16_t raceid, std::string name) -{ +void Game::addBestiaryList(uint16_t raceid, std::string name) { auto it = BestiaryList.find(raceid); if (it != BestiaryList.end()) { return; @@ -6788,17 +6514,15 @@ void Game::addBestiaryList(uint16_t raceid, std::string name) BestiaryList.insert(std::pair(raceid, name)); } -void Game::broadcastMessage(const std::string& text, MessageClasses type) const -{ +void Game::broadcastMessage(const std::string &text, MessageClasses type) const { SPDLOG_INFO("Broadcasted message: {}", text); - for (const auto& it : players) { + for (const auto &it : players) { it.second->sendTextMessage(type, text); } } -void Game::updateCreatureWalkthrough(const Creature* creature) -{ - //send to clients +void Game::updateCreatureWalkthrough(const Creature* creature) { + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true, true); for (Creature* spectator : spectators) { @@ -6807,8 +6531,7 @@ void Game::updateCreatureWalkthrough(const Creature* creature) } } -void Game::updateCreatureSkull(const Creature* creature) -{ +void Game::updateCreatureSkull(const Creature* creature) { if (getWorldType() != WORLD_TYPE_PVP) { return; } @@ -6820,8 +6543,7 @@ void Game::updateCreatureSkull(const Creature* creature) } } -void Game::updatePlayerShield(Player* player) -{ +void Game::updatePlayerShield(Player* player) { SpectatorHashSet spectators; map.getSpectators(spectators, player->getPosition(), true, true); for (Creature* spectator : spectators) { @@ -6829,8 +6551,7 @@ void Game::updatePlayerShield(Player* player) } } -void Game::updateCreatureType(Creature* creature) -{ +void Game::updateCreatureType(Creature* creature) { if (!creature) { return; } @@ -6850,7 +6571,7 @@ void Game::updateCreatureType(Creature* creature) creatureType = CREATURETYPE_HIDDEN; } - //send to clients + // send to clients SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true, true); if (creatureType == CREATURETYPE_SUMMON_OTHERS) { @@ -6873,9 +6594,8 @@ void Game::updateCreatureType(Creature* creature) } } -void Game::updatePremium(account::Account& account) -{ -bool save = false; +void Game::updatePremium(account::Account &account) { + bool save = false; time_t timeNow = time(nullptr); uint32_t rem_days = 0; time_t last_day; @@ -6890,10 +6610,9 @@ bool save = false; uint32_t days = (timeNow - last_day) / 86400; if (days > 0) { if (days >= rem_days) { - if(!account.SetPremiumRemaningDays(0) || !account.SetPremiumLastDay(0)) { + if (!account.SetPremiumRemaningDays(0) || !account.SetPremiumLastDay(0)) { account.GetEmail(&email); - SPDLOG_ERROR("Failed to set account premium days, account email: {}", - email); + SPDLOG_ERROR("Failed to set account premium days, account email: {}", email); } } else { account.SetPremiumRemaningDays((rem_days - days)); @@ -6904,8 +6623,7 @@ bool save = false; save = true; } } - } - else if (last_day != 0) { + } else if (last_day != 0) { account.SetPremiumLastDay(0); save = true; } @@ -6916,9 +6634,8 @@ bool save = false; } } -void Game::loadMotdNum() -{ - Database& db = Database::getInstance(); +void Game::loadMotdNum() { + Database &db = Database::getInstance(); DBResult_ptr result = db.storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'motd_num'"); if (result) { @@ -6938,9 +6655,8 @@ void Game::loadMotdNum() } } -void Game::saveMotdNum() const -{ - Database& db = Database::getInstance(); +void Game::saveMotdNum() const { + Database &db = Database::getInstance(); std::ostringstream query; query << "UPDATE `server_config` SET `value` = '" << motdNum << "' WHERE `config` = 'motd_num'"; @@ -6951,32 +6667,29 @@ void Game::saveMotdNum() const db.executeQuery(query.str()); } -void Game::checkPlayersRecord() -{ +void Game::checkPlayersRecord() { const size_t playersOnline = getPlayersOnline(); if (playersOnline > playersRecord) { uint32_t previousRecord = playersRecord; playersRecord = playersOnline; - for (auto& [key, it] : g_globalEvents().getEventMap(GLOBALEVENT_RECORD)) { + for (auto &[key, it] : g_globalEvents().getEventMap(GLOBALEVENT_RECORD)) { it.executeRecord(playersRecord, previousRecord); } updatePlayersRecord(); } } -void Game::updatePlayersRecord() const -{ - Database& db = Database::getInstance(); +void Game::updatePlayersRecord() const { + Database &db = Database::getInstance(); std::ostringstream query; query << "UPDATE `server_config` SET `value` = '" << playersRecord << "' WHERE `config` = 'players_record'"; db.executeQuery(query.str()); } -void Game::loadPlayersRecord() -{ - Database& db = Database::getInstance(); +void Game::loadPlayersRecord() { + Database &db = Database::getInstance(); DBResult_ptr result = db.storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'players_record'"); if (result) { @@ -6986,9 +6699,8 @@ void Game::loadPlayersRecord() } } -void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) -{ - //Prevent crafted packets from inviting urself to a party (using OTClient) +void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) { + // Prevent crafted packets from inviting urself to a party (using OTClient) if (playerId == invitedId) { return; } @@ -7020,8 +6732,7 @@ void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) party->invitePlayer(*invitedPlayer); } -void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) -{ +void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7045,8 +6756,7 @@ void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) party->joinParty(*player); } -void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) -{ +void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7065,8 +6775,7 @@ void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) party->revokeInvitation(*invitedPlayer); } -void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) -{ +void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7085,8 +6794,7 @@ void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) party->passPartyLeadership(newLeader); } -void Game::playerLeaveParty(uint32_t playerId) -{ +void Game::playerLeaveParty(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7100,8 +6808,7 @@ void Game::playerLeaveParty(uint32_t playerId) party->leaveParty(player); } -void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpActive) -{ +void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpActive) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7116,8 +6823,7 @@ void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpAc party->setSharedExperience(player, sharedExpActive); } -void Game::sendGuildMotd(uint32_t playerId) -{ +void Game::sendGuildMotd(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7129,8 +6835,7 @@ void Game::sendGuildMotd(uint32_t playerId) } } -void Game::kickPlayer(uint32_t playerId, bool displayEffect) -{ +void Game::kickPlayer(uint32_t playerId, bool displayEffect) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7141,19 +6846,25 @@ void Game::kickPlayer(uint32_t playerId, bool displayEffect) void Game::playerCyclopediaCharacterInfo(Player* player, uint32_t characterID, CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage, uint16_t page) { uint32_t playerGUID = player->getGUID(); - if (characterID != playerGUID) { - //For now allow viewing only our character since we don't have tournaments supported + if (characterID != playerGUID) { + // For now allow viewing only our character since we don't have tournaments supported player->sendCyclopediaCharacterNoData(characterInfoType, 2); return; } switch (characterInfoType) { - case CYCLOPEDIA_CHARACTERINFO_BASEINFORMATION: player->sendCyclopediaCharacterBaseInformation(); break; - case CYCLOPEDIA_CHARACTERINFO_GENERALSTATS: player->sendCyclopediaCharacterGeneralStats(); break; - case CYCLOPEDIA_CHARACTERINFO_COMBATSTATS: player->sendCyclopediaCharacterCombatStats(); break; - case CYCLOPEDIA_CHARACTERINFO_RECENTDEATHS: { - std::ostringstream query; - uint32_t offset = static_cast(page - 1) * entriesPerPage; + case CYCLOPEDIA_CHARACTERINFO_BASEINFORMATION: + player->sendCyclopediaCharacterBaseInformation(); + break; + case CYCLOPEDIA_CHARACTERINFO_GENERALSTATS: + player->sendCyclopediaCharacterGeneralStats(); + break; + case CYCLOPEDIA_CHARACTERINFO_COMBATSTATS: + player->sendCyclopediaCharacterCombatStats(); + break; + case CYCLOPEDIA_CHARACTERINFO_RECENTDEATHS: { + std::ostringstream query; + uint32_t offset = static_cast(page - 1) * entriesPerPage; query << "SELECT `time`, `level`, `killed_by`, `mostdamage_by`, (select count(*) FROM `player_deaths` WHERE `player_id` = " << playerGUID << ") as `entries` FROM `player_deaths` WHERE `player_id` = " << playerGUID << " ORDER BY `time` DESC LIMIT " << offset << ", " << entriesPerPage; uint32_t playerID = player->getID(); @@ -7182,7 +6893,7 @@ void Game::playerCyclopediaCharacterInfo(Player* player, uint32_t characterID, C std::ostringstream cause; cause << "Died at Level " << result->getNumber("level") << " by"; if (!cause1.empty()) { - const char& character = cause1.front(); + const char &character = cause1.front(); if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { cause << " an "; } else { @@ -7196,7 +6907,7 @@ void Game::playerCyclopediaCharacterInfo(Player* player, uint32_t characterID, C cause << " and "; } - const char& character = cause2.front(); + const char &character = cause2.front(); if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') { cause << " an "; } else { @@ -7212,11 +6923,11 @@ void Game::playerCyclopediaCharacterInfo(Player* player, uint32_t characterID, C g_databaseTasks().addTask(query.str(), callback, true); player->addAsyncOngoingTask(PlayerAsyncTask_RecentDeaths); break; - } - case CYCLOPEDIA_CHARACTERINFO_RECENTPVPKILLS: { + } + case CYCLOPEDIA_CHARACTERINFO_RECENTPVPKILLS: { // TODO: add guildwar, assists and arena kills - Database& db = Database::getInstance(); - const std::string& escapedName = db.escapeString(player->getName()); + Database &db = Database::getInstance(); + const std::string &escapedName = db.escapeString(player->getName()); std::ostringstream query; uint32_t offset = static_cast(page - 1) * entriesPerPage; query << "SELECT `d`.`time`, `d`.`killed_by`, `d`.`mostdamage_by`, `d`.`unjustified`, `d`.`mostdamage_unjustified`, `p`.`name`, (select count(*) FROM `player_deaths` WHERE ((`killed_by` = " << escapedName << " AND `is_player` = 1) OR (`mostdamage_by` = " << escapedName << " AND `mostdamage_is_player` = 1))) as `entries` FROM `player_deaths` AS `d` INNER JOIN `players` AS `p` ON `d`.`player_id` = `p`.`id` WHERE ((`d`.`killed_by` = " << escapedName << " AND `d`.`is_player` = 1) OR (`d`.`mostdamage_by` = " << escapedName << " AND `d`.`mostdamage_is_player` = 1)) ORDER BY `time` DESC LIMIT " << offset << ", " << entriesPerPage; @@ -7265,34 +6976,65 @@ void Game::playerCyclopediaCharacterInfo(Player* player, uint32_t characterID, C g_databaseTasks().addTask(query.str(), callback, true); player->addAsyncOngoingTask(PlayerAsyncTask_RecentPvPKills); break; - } - case CYCLOPEDIA_CHARACTERINFO_ACHIEVEMENTS: player->sendCyclopediaCharacterAchievements(); break; - case CYCLOPEDIA_CHARACTERINFO_ITEMSUMMARY: player->sendCyclopediaCharacterItemSummary(); break; - case CYCLOPEDIA_CHARACTERINFO_OUTFITSMOUNTS: player->sendCyclopediaCharacterOutfitsMounts(); break; - case CYCLOPEDIA_CHARACTERINFO_STORESUMMARY: player->sendCyclopediaCharacterStoreSummary(); break; - case CYCLOPEDIA_CHARACTERINFO_INSPECTION: player->sendCyclopediaCharacterInspection(); break; - case CYCLOPEDIA_CHARACTERINFO_BADGES: player->sendCyclopediaCharacterBadges(); break; - case CYCLOPEDIA_CHARACTERINFO_TITLES: player->sendCyclopediaCharacterTitles(); break; - default: player->sendCyclopediaCharacterNoData(characterInfoType, 1); break; + } + case CYCLOPEDIA_CHARACTERINFO_ACHIEVEMENTS: + player->sendCyclopediaCharacterAchievements(); + break; + case CYCLOPEDIA_CHARACTERINFO_ITEMSUMMARY: + player->sendCyclopediaCharacterItemSummary(); + break; + case CYCLOPEDIA_CHARACTERINFO_OUTFITSMOUNTS: + player->sendCyclopediaCharacterOutfitsMounts(); + break; + case CYCLOPEDIA_CHARACTERINFO_STORESUMMARY: + player->sendCyclopediaCharacterStoreSummary(); + break; + case CYCLOPEDIA_CHARACTERINFO_INSPECTION: + player->sendCyclopediaCharacterInspection(); + break; + case CYCLOPEDIA_CHARACTERINFO_BADGES: + player->sendCyclopediaCharacterBadges(); + break; + case CYCLOPEDIA_CHARACTERINFO_TITLES: + player->sendCyclopediaCharacterTitles(); + break; + default: + player->sendCyclopediaCharacterNoData(characterInfoType, 1); + break; } } -void Game::playerHighscores(Player* player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string&, uint16_t page, uint8_t entriesPerPage) -{ +void Game::playerHighscores(Player* player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string &, uint16_t page, uint8_t entriesPerPage) { if (player->hasAsyncOngoingTask(PlayerAsyncTask_Highscore)) { return; } std::string categoryName; switch (category) { - case HIGHSCORE_CATEGORY_FIST_FIGHTING: categoryName = "skill_fist"; break; - case HIGHSCORE_CATEGORY_CLUB_FIGHTING: categoryName = "skill_club"; break; - case HIGHSCORE_CATEGORY_SWORD_FIGHTING: categoryName = "skill_sword"; break; - case HIGHSCORE_CATEGORY_AXE_FIGHTING: categoryName = "skill_axe"; break; - case HIGHSCORE_CATEGORY_DISTANCE_FIGHTING: categoryName = "skill_dist"; break; - case HIGHSCORE_CATEGORY_SHIELDING: categoryName = "skill_shielding"; break; - case HIGHSCORE_CATEGORY_FISHING: categoryName = "skill_fishing"; break; - case HIGHSCORE_CATEGORY_MAGIC_LEVEL: categoryName = "maglevel"; break; + case HIGHSCORE_CATEGORY_FIST_FIGHTING: + categoryName = "skill_fist"; + break; + case HIGHSCORE_CATEGORY_CLUB_FIGHTING: + categoryName = "skill_club"; + break; + case HIGHSCORE_CATEGORY_SWORD_FIGHTING: + categoryName = "skill_sword"; + break; + case HIGHSCORE_CATEGORY_AXE_FIGHTING: + categoryName = "skill_axe"; + break; + case HIGHSCORE_CATEGORY_DISTANCE_FIGHTING: + categoryName = "skill_dist"; + break; + case HIGHSCORE_CATEGORY_SHIELDING: + categoryName = "skill_shielding"; + break; + case HIGHSCORE_CATEGORY_FISHING: + categoryName = "skill_fishing"; + break; + case HIGHSCORE_CATEGORY_MAGIC_LEVEL: + categoryName = "maglevel"; + break; default: { category = HIGHSCORE_CATEGORY_EXPERIENCE; categoryName = "experience"; @@ -7308,9 +7050,9 @@ void Game::playerHighscores(Player* player, HighscoreType_t type, uint8_t catego if (vocation != 0xFFFFFFFF) { bool firstVocation = true; - const auto& vocationsMap = g_vocations().getVocations(); - for (const auto& it : vocationsMap) { - const Vocation& voc = it.second; + const auto &vocationsMap = g_vocations().getVocations(); + for (const auto &it : vocationsMap) { + const Vocation &voc = it.second; if (voc.getFromVocation() == vocation) { if (firstVocation) { query << " WHERE `vocation` = " << voc.getId(); @@ -7328,9 +7070,9 @@ void Game::playerHighscores(Player* player, HighscoreType_t type, uint8_t catego if (vocation != 0xFFFFFFFF) { bool firstVocation = true; - const auto& vocationsMap = g_vocations().getVocations(); - for (const auto& it : vocationsMap) { - const Vocation& voc = it.second; + const auto &vocationsMap = g_vocations().getVocations(); + for (const auto &it : vocationsMap) { + const Vocation &voc = it.second; if (voc.getFromVocation() == vocation) { if (firstVocation) { query << " WHERE `vocation` = " << voc.getId(); @@ -7389,8 +7131,7 @@ void Game::playerTournamentLeaderboard(uint32_t playerId, uint8_t leaderboardTyp player->sendTournamentLeaderboard(); } -void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string& targetName, uint8_t reportType, uint8_t reportReason, const std::string& comment, const std::string& translation) -{ +void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7399,8 +7140,7 @@ void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string& g_events().eventPlayerOnReportRuleViolation(player, targetName, reportType, reportReason, comment, translation); } -void Game::playerReportBug(uint32_t playerId, const std::string& message, const Position& position, uint8_t category) -{ +void Game::playerReportBug(uint32_t playerId, const std::string &message, const Position &position, uint8_t category) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7409,8 +7149,7 @@ void Game::playerReportBug(uint32_t playerId, const std::string& message, const g_events().eventPlayerOnReportBug(player, message, position, category); } -void Game::playerDebugAssert(uint32_t playerId, const std::string& assertLine, const std::string& date, const std::string& description, const std::string& comment) -{ +void Game::playerDebugAssert(uint32_t playerId, const std::string &assertLine, const std::string &date, const std::string &description, const std::string &comment) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7425,8 +7164,7 @@ void Game::playerDebugAssert(uint32_t playerId, const std::string& assertLine, c } } -void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uint8_t option, int8_t index, uint16_t raceId) -{ +void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uint8_t option, int8_t index, uint16_t raceId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7435,8 +7173,7 @@ void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uin g_ioprey().ParsePreyAction(player, static_cast(slot), static_cast(action), static_cast(option), index, raceId); } -void Game::playerTaskHuntingAction(uint32_t playerId, uint8_t slot, uint8_t action, bool upgrade, uint16_t raceId) -{ +void Game::playerTaskHuntingAction(uint32_t playerId, uint8_t slot, uint8_t action, bool upgrade, uint16_t raceId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7445,8 +7182,7 @@ void Game::playerTaskHuntingAction(uint32_t playerId, uint8_t slot, uint8_t acti g_ioprey().ParseTaskHuntingAction(player, static_cast(slot), static_cast(action), upgrade, raceId); } -void Game::playerNpcGreet(uint32_t playerId, uint32_t npcId) -{ +void Game::playerNpcGreet(uint32_t playerId, uint32_t npcId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7470,8 +7206,7 @@ void Game::playerNpcGreet(uint32_t playerId, uint32_t npcId) } } -void Game::playerLeaveMarket(uint32_t playerId) -{ +void Game::playerLeaveMarket(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7480,8 +7215,7 @@ void Game::playerLeaveMarket(uint32_t playerId) player->setInMarket(false); } -void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) -{ +void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7491,7 +7225,7 @@ void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) return; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0) { return; } @@ -7500,14 +7234,13 @@ void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) return; } - const MarketOfferList& buyOffers = IOMarket::getActiveOffers(MARKETACTION_BUY, it.id, tier); - const MarketOfferList& sellOffers = IOMarket::getActiveOffers(MARKETACTION_SELL, it.id, tier); + const MarketOfferList &buyOffers = IOMarket::getActiveOffers(MARKETACTION_BUY, it.id, tier); + const MarketOfferList &sellOffers = IOMarket::getActiveOffers(MARKETACTION_SELL, it.id, tier); player->sendMarketBrowseItem(it.id, buyOffers, sellOffers, tier); player->sendMarketDetail(it.id, tier); } -void Game::playerBrowseMarketOwnOffers(uint32_t playerId) -{ +void Game::playerBrowseMarketOwnOffers(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7517,13 +7250,12 @@ void Game::playerBrowseMarketOwnOffers(uint32_t playerId) return; } - const MarketOfferList& buyOffers = IOMarket::getOwnOffers(MARKETACTION_BUY, player->getGUID()); - const MarketOfferList& sellOffers = IOMarket::getOwnOffers(MARKETACTION_SELL, player->getGUID()); + const MarketOfferList &buyOffers = IOMarket::getOwnOffers(MARKETACTION_BUY, player->getGUID()); + const MarketOfferList &sellOffers = IOMarket::getOwnOffers(MARKETACTION_SELL, player->getGUID()); player->sendMarketBrowseOwnOffers(buyOffers, sellOffers); } -void Game::playerBrowseMarketOwnHistory(uint32_t playerId) -{ +void Game::playerBrowseMarketOwnHistory(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7533,81 +7265,77 @@ void Game::playerBrowseMarketOwnHistory(uint32_t playerId) return; } - const HistoryMarketOfferList& buyOffers = IOMarket::getOwnHistory(MARKETACTION_BUY, player->getGUID()); - const HistoryMarketOfferList& sellOffers = IOMarket::getOwnHistory(MARKETACTION_SELL, player->getGUID()); + const HistoryMarketOfferList &buyOffers = IOMarket::getOwnHistory(MARKETACTION_BUY, player->getGUID()); + const HistoryMarketOfferList &sellOffers = IOMarket::getOwnHistory(MARKETACTION_SELL, player->getGUID()); player->sendMarketBrowseOwnHistory(buyOffers, sellOffers); } namespace { -bool removeOfferItems(Player &player, DepotLocker &depotLocker, const ItemType &itemType, uint16_t amount, uint8_t tier, std::ostringstream &offerStatus) -{ - uint16_t removeAmount = amount; - if ( - // Init-statement - auto stashItemCount = player.getStashItemCount(itemType.wareId); - // Condition - stashItemCount > 0 - ) - { - if (removeAmount > stashItemCount && player.withdrawItem(itemType.wareId, stashItemCount)) { - removeAmount -= stashItemCount; - } else if (player.withdrawItem(itemType.wareId, removeAmount)) { - removeAmount = 0; - } else { - offerStatus << "Failed to remove stash items from player " << player.getName(); - return false; - } - } - - auto [itemVector, totalCount] = player.getLockerItemsAndCountById(depotLocker, tier, itemType.id); - if (removeAmount > 0) { - if (totalCount == 0 || itemVector.size() == 0) { - offerStatus << "Player " << player.getName() << " not have item for create offer"; - return false; + bool removeOfferItems(Player &player, DepotLocker &depotLocker, const ItemType &itemType, uint16_t amount, uint8_t tier, std::ostringstream &offerStatus) { + uint16_t removeAmount = amount; + if ( + // Init-statement + auto stashItemCount = player.getStashItemCount(itemType.wareId); + // Condition + stashItemCount > 0 + ) { + if (removeAmount > stashItemCount && player.withdrawItem(itemType.wareId, stashItemCount)) { + removeAmount -= stashItemCount; + } else if (player.withdrawItem(itemType.wareId, removeAmount)) { + removeAmount = 0; + } else { + offerStatus << "Failed to remove stash items from player " << player.getName(); + return false; + } } - uint32_t count = 0; - for (auto item : itemVector) { - if (!item) { - continue; + auto [itemVector, totalCount] = player.getLockerItemsAndCountById(depotLocker, tier, itemType.id); + if (removeAmount > 0) { + if (totalCount == 0 || itemVector.size() == 0) { + offerStatus << "Player " << player.getName() << " not have item for create offer"; + return false; } - if (itemType.stackable) { - uint16_t removeCount = std::min(removeAmount, item->getItemCount()); - removeAmount -= removeCount; - if ( - // Init-statement - auto ret = g_game().internalRemoveItem(item, removeCount); - // Condition - ret != RETURNVALUE_NOERROR - ) - { - offerStatus << "Failed to remove items from player " << player.getName() << " error: " << getReturnMessage(ret); - return false; + uint32_t count = 0; + for (auto item : itemVector) { + if (!item) { + continue; } - if (removeAmount == 0) { - break; - } - } else { - count += Item::countByType(item, -1); - if (count > amount) { - break; - } - auto ret = g_game().internalRemoveItem(item); - if (ret != RETURNVALUE_NOERROR) { - offerStatus << "Failed to remove items from player " << player.getName() << " error: " << getReturnMessage(ret); - return false; + if (itemType.stackable) { + uint16_t removeCount = std::min(removeAmount, item->getItemCount()); + removeAmount -= removeCount; + if ( + // Init-statement + auto ret = g_game().internalRemoveItem(item, removeCount); + // Condition + ret != RETURNVALUE_NOERROR + ) { + offerStatus << "Failed to remove items from player " << player.getName() << " error: " << getReturnMessage(ret); + return false; + } + + if (removeAmount == 0) { + break; + } + } else { + count += Item::countByType(item, -1); + if (count > amount) { + break; + } + auto ret = g_game().internalRemoveItem(item); + if (ret != RETURNVALUE_NOERROR) { + offerStatus << "Failed to remove items from player " << player.getName() << " error: " << getReturnMessage(ret); + return false; + } } } } + return true; } - return true; -} } // namespace -bool checkCanInitCreateMarketOffer(const Player *player, uint8_t type, const ItemType &it, uint16_t amount, uint64_t price, std::ostringstream &offerStatus) -{ +bool checkCanInitCreateMarketOffer(const Player* player, uint8_t type, const ItemType &it, uint16_t amount, uint64_t price, std::ostringstream &offerStatus) { if (!player) { offerStatus << "Failed to load player"; return false; @@ -7664,12 +7392,11 @@ bool checkCanInitCreateMarketOffer(const Player *player, uint8_t type, const Ite return true; } -void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t itemId, uint16_t amount, uint64_t price, uint8_t tier, bool anonymous) -{ +void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t itemId, uint16_t amount, uint64_t price, uint8_t tier, bool anonymous) { // Initialize variables // Before creating the offer we will compare it with the RETURN VALUE ERROR std::ostringstream offerStatus; - Player *player = getPlayerByID(playerId); + Player* player = getPlayerByID(playerId); const ItemType &it = Item::items[itemId]; // Make sure everything is ok before the create market offer starts @@ -7688,7 +7415,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite return; } - DepotLocker *depotLocker = player->getDepotLocker(player->getLastDepotId()); + DepotLocker* depotLocker = player->getDepotLocker(player->getLastDepotId()); if (depotLocker == nullptr) { offerStatus << "Depot locker is nullptr for player " << player->getName(); return; @@ -7736,7 +7463,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite return; } - IOMarket::createOffer(player->getGUID(), static_cast (type), it.id, amount, price, tier, anonymous); + IOMarket::createOffer(player->getGUID(), static_cast(type), it.id, amount, price, tier, anonymous); // uint8_t = tier, uint64_t price std::map tierAndPriceMap; @@ -7758,8 +7485,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite IOLoginData::savePlayer(player); } -void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter) -{ +void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -7780,11 +7506,11 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } if (offer.type == MARKETACTION_BUY) { - player->setBankBalance( player->getBankBalance() + offer.price * offer.amount); + player->setBankBalance(player->getBankBalance() + offer.price * offer.amount); // Send market window again for update stats player->sendMarketEnter(player->getLastDepotId()); } else { - const ItemType& it = Item::items[offer.itemId]; + const ItemType &it = Item::items[offer.itemId]; if (it.id == 0) { return; } @@ -7843,8 +7569,7 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 IOLoginData::savePlayer(player); } -void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount) -{ +void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount) { std::ostringstream offerStatus; Player* player = getPlayerByID(playerId); if (!player) { @@ -7868,14 +7593,13 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 return; } - const ItemType& it = Item::items[offer.itemId]; + const ItemType &it = Item::items[offer.itemId]; if (it.id == 0) { offerStatus << "Failed to load item id"; return; } - if (amount == 0 || !it.stackable && amount > 2000 || it.stackable && amount > 64000 || amount > offer.amount) - { + if (amount == 0 || !it.stackable && amount > 2000 || it.stackable && amount > 64000 || amount > offer.amount) { offerStatus << "Invalid offer amount " << amount << " for player " << player->getName(); return; } @@ -7917,13 +7641,12 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } account.RemoveCoins(amount); - account.RegisterCoinsTransaction(account::COIN_REMOVE, amount, - "Sold on Market"); + account.RegisterCoinsTransaction(account::COIN_REMOVE, amount, "Sold on Market"); } else { - if (!removeOfferItems(*player, *depotLocker, it, amount, offer.tier, offerStatus)) { - SPDLOG_ERROR("[{}] failed to remove item with id {}, from player {}, errorcode: {}", __FUNCTION__, it.id, player->getName(), offerStatus.str()); - return; - } + if (!removeOfferItems(*player, *depotLocker, it, amount, offer.tier, offerStatus)) { + SPDLOG_ERROR("[{}] failed to remove item with id {}, from player {}, errorcode: {}", __FUNCTION__, it.id, player->getName(), offerStatus.str()); + return; + } } player->setBankBalance(player->getBankBalance() + totalPrice); @@ -7931,11 +7654,8 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 account::Account account; account.LoadAccountDB(buyerPlayer->getAccount()); account.AddCoins(amount); - account.RegisterCoinsTransaction(account::COIN_ADD, amount, - "Purchased on Market"); - } - else if (it.stackable) - { + account.RegisterCoinsTransaction(account::COIN_ADD, amount, "Purchased on Market"); + } else if (it.stackable) { uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min(100, tmpAmount); @@ -7952,9 +7672,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 tmpAmount -= stackCount; } - } - else - { + } else { int32_t subType; if (it.charges != 0) { subType = it.charges; @@ -7981,7 +7699,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 delete buyerPlayer; } } else if (offer.type == MARKETACTION_SELL) { - Player *sellerPlayer = getPlayerByGUID(offer.playerId); + Player* sellerPlayer = getPlayerByGUID(offer.playerId); if (!sellerPlayer) { sellerPlayer = new Player(nullptr); if (!IOLoginData::loadPlayerById(sellerPlayer, offer.playerId)) { @@ -8001,12 +7719,9 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } // Have enough money on the bank - if(totalPrice <= player->getBankBalance()) - { + if (totalPrice <= player->getBankBalance()) { player->setBankBalance(player->getBankBalance() - totalPrice); - } - else - { + } else { uint64_t remainsPrice = 0; remainsPrice = totalPrice - player->getBankBalance(); player->setBankBalance(0); @@ -8017,8 +7732,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 account::Account account; account.LoadAccountDB(player->getAccount()); account.AddCoins(amount); - account.RegisterCoinsTransaction(account::COIN_ADD, amount, - "Purchased on Market"); + account.RegisterCoinsTransaction(account::COIN_ADD, amount, "Purchased on Market"); } else if (it.stackable) { uint16_t tmpAmount = amount; while (tmpAmount > 0) { @@ -8029,8 +7743,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 auto ret = internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); // Condition ret != RETURNVALUE_NOERROR - ) - { + ) { SPDLOG_ERROR("{} - Create offer internal add item error code: {}", __FUNCTION__, ret); offerStatus << "Failed to add inbox stackable item for sell offer for player " << player->getName(); delete item; @@ -8057,8 +7770,8 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 // Init-statement auto ret = internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); // Condition - ret != RETURNVALUE_NOERROR) - { + ret != RETURNVALUE_NOERROR + ) { offerStatus << "Failed to add inbox item for sell offer for player " << player->getName(); delete item; break; @@ -8074,8 +7787,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 if (it.id == ITEM_STORE_COIN) { account::Account account; account.LoadAccountDB(sellerPlayer->getAccount()); - account.RegisterCoinsTransaction(account::COIN_REMOVE, amount, - "Sold on Market"); + account.RegisterCoinsTransaction(account::COIN_REMOVE, amount, "Sold on Market"); } if (it.id != ITEM_STORE_COIN) { @@ -8118,8 +7830,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 IOLoginData::savePlayer(player); } -void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string& buffer) -{ +void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string &buffer) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8130,8 +7841,7 @@ void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const st } } -void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t conditionType, ConditionId_t conditionId) -{ +void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t conditionType, ConditionId_t conditionId) { Creature* creature = getCreatureByID(creatureId); if (!creature) { return; @@ -8140,8 +7850,7 @@ void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t conditionTy creature->removeCondition(conditionType, conditionId, true); } -void Game::sendOfflineTrainingDialog(Player* player) -{ +void Game::sendOfflineTrainingDialog(Player* player) { if (!player) { return; } @@ -8151,8 +7860,7 @@ void Game::sendOfflineTrainingDialog(Player* player) } } -void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice) -{ +void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8186,8 +7894,7 @@ void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, ui } } -void Game::playerForgeFuseItems(uint32_t playerId, uint16_t itemId, uint8_t tier, bool usedCore, bool reduceTierLoss) -{ +void Game::playerForgeFuseItems(uint32_t playerId, uint16_t itemId, uint8_t tier, bool usedCore, bool reduceTierLoss) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8202,9 +7909,7 @@ void Game::playerForgeFuseItems(uint32_t playerId, uint16_t itemId, uint8_t tier uint8_t coreCount = (usedCore ? 1 : 0) + (reduceTierLoss ? 1 : 0); auto baseSuccess = static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE)); - auto bonusSuccess = static_cast(g_configManager().getNumber( - FORGE_BASE_SUCCESS_RATE) + g_configManager().getNumber(FORGE_BONUS_SUCCESS_RATE) - ); + auto bonusSuccess = static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE) + g_configManager().getNumber(FORGE_BONUS_SUCCESS_RATE)); auto roll = static_cast(uniform_random(1, 100)) <= (usedCore ? bonusSuccess : baseSuccess); bool success = roll ? true : false; @@ -8214,8 +7919,7 @@ void Game::playerForgeFuseItems(uint32_t playerId, uint16_t itemId, uint8_t tier player->forgeFuseItems(itemId, tier, success, reduceTierLoss, bonus, coreCount); } -void Game::playerForgeTransferItemTier(uint32_t playerId, uint16_t donorItemId, uint8_t tier, uint16_t receiveItemId) -{ +void Game::playerForgeTransferItemTier(uint32_t playerId, uint16_t donorItemId, uint8_t tier, uint16_t receiveItemId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8224,8 +7928,7 @@ void Game::playerForgeTransferItemTier(uint32_t playerId, uint16_t donorItemId, player->forgeTransferItemTier(donorItemId, tier, receiveItemId); } -void Game::playerForgeResourceConversion(uint32_t playerId, uint8_t action) -{ +void Game::playerForgeResourceConversion(uint32_t playerId, uint8_t action) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8240,8 +7943,7 @@ void Game::playerForgeResourceConversion(uint32_t playerId, uint8_t action) player->forgeResourceConversion(action); } -void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) -{ +void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8256,8 +7958,7 @@ void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) player->forgeHistory(page); } -void Game::updatePlayerSaleItems(uint32_t playerId) -{ +void Game::updatePlayerSaleItems(uint32_t playerId) { Player* player = getPlayerByID(playerId); if (!player) { return; @@ -8268,44 +7969,37 @@ void Game::updatePlayerSaleItems(uint32_t playerId) player->setScheduledSaleUpdate(false); } -void Game::addPlayer(Player* player) -{ - const std::string& lowercase_name = asLowerCaseString(player->getName()); +void Game::addPlayer(Player* player) { + const std::string &lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames[lowercase_name] = player; wildcardTree.insert(lowercase_name); players[player->getID()] = player; } -void Game::removePlayer(Player* player) -{ - const std::string& lowercase_name = asLowerCaseString(player->getName()); +void Game::removePlayer(Player* player) { + const std::string &lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames.erase(lowercase_name); wildcardTree.remove(lowercase_name); players.erase(player->getID()); } -void Game::addNpc(Npc* npc) -{ +void Game::addNpc(Npc* npc) { npcs[npc->getID()] = npc; } -void Game::removeNpc(Npc* npc) -{ +void Game::removeNpc(Npc* npc) { npcs.erase(npc->getID()); } -void Game::addMonster(Monster* monster) -{ +void Game::addMonster(Monster* monster) { monsters[monster->getID()] = monster; } -void Game::removeMonster(Monster* monster) -{ +void Game::removeMonster(Monster* monster) { monsters.erase(monster->getID()); } -Guild* Game::getGuild(uint32_t id) const -{ +Guild* Game::getGuild(uint32_t id) const { auto it = guilds.find(id); if (it == guilds.end()) { return nullptr; @@ -8313,25 +8007,22 @@ Guild* Game::getGuild(uint32_t id) const return it->second; } -void Game::addGuild(Guild* guild) -{ - if (!guild) { - return; - } +void Game::addGuild(Guild* guild) { + if (!guild) { + return; + } guilds[guild->getId()] = guild; } -void Game::removeGuild(uint32_t guildId) -{ - auto it = guilds.find(guildId); - if (it != guilds.end()) { - IOGuild::saveGuild(it->second); - } +void Game::removeGuild(uint32_t guildId) { + auto it = guilds.find(guildId); + if (it != guilds.end()) { + IOGuild::saveGuild(it->second); + } guilds.erase(guildId); } -void Game::decreaseBrowseFieldRef(const Position& pos) -{ +void Game::decreaseBrowseFieldRef(const Position &pos) { Tile* tile = map.getTile(pos.x, pos.y, pos.z); if (!tile) { return; @@ -8343,8 +8034,7 @@ void Game::decreaseBrowseFieldRef(const Position& pos) } } -void Game::internalRemoveItems(const std::vector itemVector, uint32_t amount, bool stackable) -{ +void Game::internalRemoveItems(const std::vector itemVector, uint32_t amount, bool stackable) { if (stackable) { for (Item* item : itemVector) { if (item->getItemCount() > amount) { @@ -8362,8 +8052,7 @@ void Game::internalRemoveItems(const std::vector itemVector, uint32_t amo } } -BedItem* Game::getBedBySleeper(uint32_t guid) const -{ +BedItem* Game::getBedBySleeper(uint32_t guid) const { auto it = bedSleepersMap.find(guid); if (it == bedSleepersMap.end()) { return nullptr; @@ -8371,21 +8060,18 @@ BedItem* Game::getBedBySleeper(uint32_t guid) const return it->second; } -void Game::setBedSleeper(BedItem* bed, uint32_t guid) -{ +void Game::setBedSleeper(BedItem* bed, uint32_t guid) { bedSleepersMap[guid] = bed; } -void Game::removeBedSleeper(uint32_t guid) -{ +void Game::removeBedSleeper(uint32_t guid) { auto it = bedSleepersMap.find(guid); if (it != bedSleepersMap.end()) { bedSleepersMap.erase(it); } } -Item* Game::getUniqueItem(uint16_t uniqueId) -{ +Item* Game::getUniqueItem(uint16_t uniqueId) { auto it = uniqueItems.find(uniqueId); if (it == uniqueItems.end()) { return nullptr; @@ -8393,8 +8079,7 @@ Item* Game::getUniqueItem(uint16_t uniqueId) return it->second; } -bool Game::addUniqueItem(uint16_t uniqueId, Item* item) -{ +bool Game::addUniqueItem(uint16_t uniqueId, Item* item) { auto result = uniqueItems.emplace(uniqueId, item); if (!result.second) { SPDLOG_WARN("Duplicate unique id: {}", uniqueId); @@ -8402,8 +8087,7 @@ bool Game::addUniqueItem(uint16_t uniqueId, Item* item) return result.second; } -void Game::removeUniqueItem(uint16_t uniqueId) -{ +void Game::removeUniqueItem(uint16_t uniqueId) { auto it = uniqueItems.find(uniqueId); if (it != uniqueItems.end()) { uniqueItems.erase(it); @@ -8431,7 +8115,7 @@ bool Game::hasDistanceEffect(uint8_t effectId) { } void Game::createLuaItemsOnMap() { - for (auto const [position, itemId] : mapLuaItemsStored) { + for (const auto [position, itemId] : mapLuaItemsStored) { Item* item = Item::CreateItem(itemId, 1); if (!item) { SPDLOG_WARN("[Game::createLuaItemsOnMap] - Cannot create item with id {}", itemId); @@ -8464,8 +8148,8 @@ void Game::sendUpdateCreature(const Creature* creature) { SpectatorHashSet spectators; map.getSpectators(spectators, creature->getPosition(), true); - for (Creature *spectator : spectators) { - if (const Player *tmpPlayer = spectator->getPlayer()) { + for (Creature* spectator : spectators) { + if (const Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendUpdateCreature(creature); } } @@ -8474,8 +8158,7 @@ void Game::sendUpdateCreature(const Creature* creature) { uint32_t Game::makeInfluencedMonster() { if (auto influencedLimit = g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT); // Condition - forgeableMonsters.empty() || influencedMonsters.size() >= influencedLimit) - { + forgeableMonsters.empty() || influencedMonsters.size() >= influencedLimit) { return 0; } @@ -8485,8 +8168,7 @@ uint32_t Game::makeInfluencedMonster() { auto maxTries = forgeableMonsters.size(); uint16_t tries = 0; Monster* monster = nullptr; - while (true) - { + while (true) { if (tries == maxTries) { return 0; } @@ -8522,7 +8204,7 @@ uint32_t Game::makeInfluencedMonster() { return 0; } -uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId/* = 0*/, bool createForgeableMonsters/* = false*/) { +uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId /* = 0*/, bool createForgeableMonsters /* = false*/) { if (createForgeableMonsters) { forgeableMonsters.clear(); // If the forgeable monsters haven't been created @@ -8555,17 +8237,15 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId/* = 0*/, bool cre } if (auto fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT); - //Condition - forgeableMonsters.empty() || fiendishMonsters.size() >= fiendishLimit) - { + // Condition + forgeableMonsters.empty() || fiendishMonsters.size() >= fiendishLimit) { return 0; } auto maxTries = forgeableMonsters.size(); uint16_t tries = 0; - Monster *monster = nullptr; - while (true) - { + Monster* monster = nullptr; + while (true) { if (tries == maxTries) { return 0; } @@ -8627,8 +8307,8 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId/* = 0*/, bool cre fiendishMonsters.insert(monster->getID()); auto schedulerTask = createSchedulerTask( - finalTime, - std::bind_front(&Game::updateFiendishMonsterStatus, this, monster->getID(), monster->getName()) + finalTime, + std::bind_front(&Game::updateFiendishMonsterStatus, this, monster->getID(), monster->getName()) ); forgeMonsterEventIds[monster->getID()] = g_scheduler().addEvent(schedulerTask); return monster->getID(); @@ -8638,7 +8318,7 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId/* = 0*/, bool cre } void Game::updateFiendishMonsterStatus(uint32_t monsterId, const std::string &monsterName) { - Monster *monster = getMonsterByID(monsterId); + Monster* monster = getMonsterByID(monsterId); if (!monster) { SPDLOG_WARN("[{}] Failed to update monster with id {} and name {}, monster not found", __FUNCTION__, monsterId, monsterName); return; @@ -8658,11 +8338,10 @@ bool Game::removeForgeMonster(uint32_t id, ForgeClassifications_t monsterForgeCl return true; } -bool Game::removeInfluencedMonster(uint32_t id, bool create/* = false*/) { +bool Game::removeInfluencedMonster(uint32_t id, bool create /* = false*/) { if (auto find = influencedMonsters.find(id); // Condition - find != influencedMonsters.end()) - { + find != influencedMonsters.end()) { influencedMonsters.erase(find); if (create) { @@ -8674,12 +8353,10 @@ bool Game::removeInfluencedMonster(uint32_t id, bool create/* = false*/) { return false; } -bool Game::removeFiendishMonster(uint32_t id, bool create/* = true*/) -{ +bool Game::removeFiendishMonster(uint32_t id, bool create /* = true*/) { if (auto find = fiendishMonsters.find(id); // Condition - find != fiendishMonsters.end()) - { + find != fiendishMonsters.end()) { fiendishMonsters.erase(find); checkForgeEventId(id); @@ -8693,8 +8370,7 @@ bool Game::removeFiendishMonster(uint32_t id, bool create/* = true*/) return false; } -void Game::updateForgeableMonsters() -{ +void Game::updateForgeableMonsters() { g_scheduler().addEvent(createSchedulerTask(EVENT_FORGEABLEMONSTERCHECKINTERVAL, std::bind_front(&Game::updateForgeableMonsters, this))); forgeableMonsters.clear(); for (auto [monsterId, monster] : monsters) { @@ -8718,22 +8394,18 @@ void Game::updateForgeableMonsters() createFiendishMonsters(); } -void Game::createFiendishMonsters() -{ +void Game::createFiendishMonsters() { uint32_t created = 0; uint32_t fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT); // Fiendish Creatures limit - while (fiendishMonsters.size() < fiendishLimit) - { + while (fiendishMonsters.size() < fiendishLimit) { if (fiendishMonsters.size() >= fiendishLimit) { - SPDLOG_WARN("[{}] - Returning in creation of Fiendish, size: {}, max is: {}.", - __FUNCTION__, fiendishMonsters.size(), fiendishLimit); + SPDLOG_WARN("[{}] - Returning in creation of Fiendish, size: {}, max is: {}.", __FUNCTION__, fiendishMonsters.size(), fiendishLimit); break; } if (auto ret = makeFiendishMonster(); // Condition - ret == 0) - { + ret == 0) { return; } @@ -8741,22 +8413,18 @@ void Game::createFiendishMonsters() } } -void Game::createInfluencedMonsters() -{ +void Game::createInfluencedMonsters() { uint32_t created = 0; uint32_t influencedLimit = g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT); - while (created < influencedLimit) - { + while (created < influencedLimit) { if (influencedMonsters.size() >= influencedLimit) { - SPDLOG_WARN("[{}] - Returning in creation of Influenced, size: {}, max is: {}.", - __FUNCTION__, influencedMonsters.size(), influencedLimit); + SPDLOG_WARN("[{}] - Returning in creation of Influenced, size: {}, max is: {}.", __FUNCTION__, influencedMonsters.size(), influencedLimit); break; } if (auto ret = makeInfluencedMonster(); - //If condition - ret == 0) - { + // If condition + ret == 0) { return; } @@ -8764,8 +8432,7 @@ void Game::createInfluencedMonsters() } } -void Game::checkForgeEventId(uint32_t monsterId) -{ +void Game::checkForgeEventId(uint32_t monsterId) { auto find = forgeMonsterEventIds.find(monsterId); if (find != forgeMonsterEventIds.end()) { g_scheduler().stopEvent(find->second); @@ -8773,14 +8440,11 @@ void Game::checkForgeEventId(uint32_t monsterId) } } -bool Game::addInfluencedMonster(Monster *monster) -{ - if (monster && monster->canBeForgeMonster()) - { +bool Game::addInfluencedMonster(Monster* monster) { + if (monster && monster->canBeForgeMonster()) { if (auto maxInfluencedMonsters = static_cast(g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT)); // If condition - (influencedMonsters.size() + 1) > maxInfluencedMonsters) - { + (influencedMonsters.size() + 1) > maxInfluencedMonsters) { return false; } diff --git a/src/game/game.h b/src/game/game.h index 4c629f13e4b..1615482a80b 100644 --- a/src/game/game.h +++ b/src/game/game.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_GAME_H_ #define SRC_GAME_GAME_H_ @@ -41,17 +41,16 @@ static constexpr int32_t EVENT_DECAYINTERVAL = 250; static constexpr int32_t EVENT_DECAY_BUCKETS = 4; static constexpr int32_t EVENT_FORGEABLEMONSTERCHECKINTERVAL = 300000; -class Game -{ +class Game { public: Game(); ~Game(); // Singleton - ensures we don't accidentally copy it. - Game(const Game&) = delete; - Game& operator=(const Game&) = delete; + Game(const Game &) = delete; + Game &operator=(const Game &) = delete; - static Game& getInstance() { + static Game &getInstance() { // Guaranteed to be destroyed static Game instance; // Instantiated on first use @@ -67,20 +66,20 @@ class Game void forceRemoveCondition(uint32_t creatureId, ConditionType_t type, ConditionId_t conditionId); /** - * Load the main map + * Load the main map * \param filename Is the map custom name (Example: "map".otbm, not is necessary add extension .otbm) * \returns true if the custom map was loaded successfully - */ - bool loadMainMap(const std::string& filename); + */ + bool loadMainMap(const std::string &filename); /** - * Load the custom map + * Load the custom map * \param filename Is the map custom name (Example: "map".otbm, not is necessary add extension .otbm) * \returns true if the custom map was loaded successfully - */ - bool loadCustomMap(const std::string& filename); - void loadMap(const std::string& path, const Position& pos = Position(), bool unload = false); + */ + bool loadCustomMap(const std::string &filename); + void loadMap(const std::string &path, const Position &pos = Position(), bool unload = false); - void getMapDimensions(uint32_t& width, uint32_t& height) const { + void getMapDimensions(uint32_t &width, uint32_t &height) const { width = map.width; height = map.height; } @@ -100,10 +99,9 @@ class Game teamFinderMap.erase(leaderGuid); } - Cylinder* internalGetCylinder(Player* player, const Position& pos) const; - Thing* internalGetThing(Player* player, const Position& pos, int32_t index, - uint32_t itemId, StackPosType_t type) const; - static void internalGetPosition(Item* item, Position& pos, uint8_t& stackpos); + Cylinder* internalGetCylinder(Player* player, const Position &pos) const; + Thing* internalGetThing(Player* player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type) const; + static void internalGetPosition(Item* item, Position &pos, uint8_t &stackpos); static std::string getTradeErrorDescription(ReturnValue ret, Item* item); @@ -115,21 +113,21 @@ class Game Player* getPlayerByID(uint32_t id); - Creature* getCreatureByName(const std::string& s); + Creature* getCreatureByName(const std::string &s); - Npc* getNpcByName(const std::string& s); + Npc* getNpcByName(const std::string &s); - Player* getPlayerByName(const std::string& s); + Player* getPlayerByName(const std::string &s); - Player* getPlayerByGUID(const uint32_t& guid); + Player* getPlayerByGUID(const uint32_t &guid); - ReturnValue getPlayerByNameWildcard(const std::string& s, Player*& player); + ReturnValue getPlayerByNameWildcard(const std::string &s, Player*&player); Player* getPlayerByAccount(uint32_t acc); - bool internalPlaceCreature(Creature* creature, const Position& pos, bool extendedPos = false, bool forced = false, bool creatureCheck = false); + bool internalPlaceCreature(Creature* creature, const Position &pos, bool extendedPos = false, bool forced = false, bool creatureCheck = false); - bool placeCreature(Creature* creature, const Position& pos, bool extendedPos = false, bool force = false); + bool placeCreature(Creature* creature, const Position &pos, bool extendedPos = false, bool force = false); bool removeCreature(Creature* creature, bool isLogout = true); void executeDeath(uint32_t creatureId); @@ -159,7 +157,7 @@ class Game ItemClassification* getItemsClassification(uint8_t id, bool create) { auto it = std::find_if(itemsClassifications.begin(), itemsClassifications.end(), [id](ItemClassification* it) { return it->id == id; - }); + }); if (it != itemsClassifications.end()) { return *it; @@ -176,76 +174,52 @@ class Game bool gameIsDay(); - ReturnValue internalMoveCreature(Creature* creature, - Direction direction, uint32_t flags = 0); - ReturnValue internalMoveCreature(Creature& creature, - Tile& toTile, uint32_t flags = 0); + ReturnValue internalMoveCreature(Creature* creature, Direction direction, uint32_t flags = 0); + ReturnValue internalMoveCreature(Creature &creature, Tile &toTile, uint32_t flags = 0); - ReturnValue internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, - int32_t index, Item* item, uint32_t count, - Item** internalMoveItem, uint32_t flags = 0, - Creature* actor = nullptr, - Item* tradeItem = nullptr); + ReturnValue internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, int32_t index, Item* item, uint32_t count, Item** internalMoveItem, uint32_t flags = 0, Creature* actor = nullptr, Item* tradeItem = nullptr); - ReturnValue internalAddItem(Cylinder* toCylinder, Item* item, - int32_t index = INDEX_WHEREEVER, - uint32_t flags = 0, bool test = false); - ReturnValue internalAddItem(Cylinder* toCylinder, Item* item, int32_t index, - uint32_t flags, bool test, uint32_t& remainderCount); - ReturnValue internalRemoveItem(Item* item, int32_t count = -1, - bool test = false, uint32_t flags = 0); + ReturnValue internalAddItem(Cylinder* toCylinder, Item* item, int32_t index = INDEX_WHEREEVER, uint32_t flags = 0, bool test = false); + ReturnValue internalAddItem(Cylinder* toCylinder, Item* item, int32_t index, uint32_t flags, bool test, uint32_t &remainderCount); + ReturnValue internalRemoveItem(Item* item, int32_t count = -1, bool test = false, uint32_t flags = 0); - ReturnValue internalPlayerAddItem(Player* player, Item* item, - bool dropOnMap = true, - Slots_t slot = CONST_SLOT_WHEREEVER); + ReturnValue internalPlayerAddItem(Player* player, Item* item, bool dropOnMap = true, Slots_t slot = CONST_SLOT_WHEREEVER); - Item* findItemOfType(const Cylinder* cylinder, uint16_t itemId, - bool depthSearch = true, int32_t subType = -1) const; + Item* findItemOfType(const Cylinder* cylinder, uint16_t itemId, bool depthSearch = true, int32_t subType = -1) const; void createLuaItemsOnMap(); - bool removeMoney(Cylinder* cylinder, uint64_t money, - uint32_t flags = 0, bool useBank = false); + bool removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags = 0, bool useBank = false); void addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags = 0); Item* transformItem(Item* item, uint16_t newId, int32_t newCount = -1); - ReturnValue internalTeleport(Thing* thing, const Position& newPos, - bool pushMove = true, uint32_t flags = 0); + ReturnValue internalTeleport(Thing* thing, const Position &newPos, bool pushMove = true, uint32_t flags = 0); bool internalCreatureTurn(Creature* creature, Direction dir); - bool internalCreatureSay(Creature* creature, SpeakClasses type, - const std::string& text, - bool ghostMode, - SpectatorHashSet* spectatorsPtr = nullptr, - const Position* pos = nullptr); + bool internalCreatureSay(Creature* creature, SpeakClasses type, const std::string &text, bool ghostMode, SpectatorHashSet* spectatorsPtr = nullptr, const Position* pos = nullptr); void internalQuickLootCorpse(Player* player, Container* corpse); - ReturnValue internalQuickLootItem(Player* player, Item* item, - ObjectCategory_t category = OBJECTCATEGORY_DEFAULT); + ReturnValue internalQuickLootItem(Player* player, Item* item, ObjectCategory_t category = OBJECTCATEGORY_DEFAULT); ObjectCategory_t getObjectCategory(const Item* item); - uint64_t getItemMarketPrice(std::map const &itemMap, bool buyPrice) const; + uint64_t getItemMarketPrice(const std::map &itemMap, bool buyPrice) const; void loadPlayersRecord(); void checkPlayersRecord(); void sendGuildMotd(uint32_t playerId); void kickPlayer(uint32_t playerId, bool displayEffect); - void playerReportBug(uint32_t playerId, const std::string& message, - const Position& position, uint8_t category); - void playerDebugAssert(uint32_t playerId, const std::string& assertLine, - const std::string& date, const std::string& description, - const std::string& comment); + void playerReportBug(uint32_t playerId, const std::string &message, const Position &position, uint8_t category); + void playerDebugAssert(uint32_t playerId, const std::string &assertLine, const std::string &date, const std::string &description, const std::string &comment); void playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uint8_t option, int8_t index, uint16_t raceId); void playerTaskHuntingAction(uint32_t playerId, uint8_t slot, uint8_t action, bool upgrade, uint16_t raceId); void playerNpcGreet(uint32_t playerId, uint32_t npcId); - void playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, - uint8_t button, uint8_t choice); + void playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice); void playerForgeFuseItems( uint32_t playerId, uint16_t itemId, @@ -261,15 +235,11 @@ class Game ); void playerForgeResourceConversion(uint32_t playerId, uint8_t action); void playerBrowseForgeHistory(uint32_t playerId, uint8_t page); - void playerReportRuleViolationReport(uint32_t playerId, - const std::string& targetName, - uint8_t reportType, uint8_t reportReason, - const std::string& comment, - const std::string& translation); + void playerReportRuleViolationReport(uint32_t playerId, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation); void playerCyclopediaCharacterInfo(Player* player, uint32_t characterID, CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage, uint16_t page); - void playerHighscores(Player* player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string& worldName, uint16_t page, uint8_t entriesPerPage); + void playerHighscores(Player* player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string &worldName, uint16_t page, uint8_t entriesPerPage); void playerTournamentLeaderboard(uint32_t playerId, uint8_t leaderboardType); @@ -277,57 +247,51 @@ class Game bool internalStartTrade(Player* player, Player* partner, Item* tradeItem); void internalCloseTrade(Player* player); - bool playerBroadcastMessage(Player* player, const std::string& text) const; - void broadcastMessage(const std::string& text, MessageClasses type) const; - - //Implementation of player invoked events - void playerTeleport(uint32_t playerId, const Position& pos); - void playerMoveThing(uint32_t playerId, const Position& fromPos, uint16_t itemId, uint8_t fromStackPos, - const Position& toPos, uint8_t count); - void playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position& movingCreatureOrigPos, const Position& toPos); - void playerMoveCreature(Player* playerId, Creature* movingCreature, const Position& movingCreatureOrigPos, Tile* toTile); - void playerMoveItemByPlayerID(uint32_t playerId, const Position& fromPos, uint16_t itemId, uint8_t fromStackPos, const Position& toPos, uint8_t count); - void playerMoveItem(Player* player, const Position& fromPos, - uint16_t itemId, uint8_t fromStackPos, const Position& toPos, uint8_t count, Item* item, Cylinder* toCylinder); + bool playerBroadcastMessage(Player* player, const std::string &text) const; + void broadcastMessage(const std::string &text, MessageClasses type) const; + + // Implementation of player invoked events + void playerTeleport(uint32_t playerId, const Position &pos); + void playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count); + void playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position &movingCreatureOrigPos, const Position &toPos); + void playerMoveCreature(Player* playerId, Creature* movingCreature, const Position &movingCreatureOrigPos, Tile* toTile); + void playerMoveItemByPlayerID(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count); + void playerMoveItem(Player* player, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count, Item* item, Cylinder* toCylinder); void playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier = false, uint8_t tier = 0); void playerMove(uint32_t playerId, Direction direction); void playerCreatePrivateChannel(uint32_t playerId); - void playerChannelInvite(uint32_t playerId, const std::string& name); - void playerChannelExclude(uint32_t playerId, const std::string& name); + void playerChannelInvite(uint32_t playerId, const std::string &name); + void playerChannelExclude(uint32_t playerId, const std::string &name); void playerRequestChannels(uint32_t playerId); void playerOpenChannel(uint32_t playerId, uint16_t channelId); void playerCloseChannel(uint32_t playerId, uint16_t channelId); - void playerOpenPrivateChannel(uint32_t playerId, std::string& receiver); - void playerStowItem(uint32_t playerId, const Position& pos, uint16_t itemId, uint8_t stackpos, uint8_t count, bool allItems); + void playerOpenPrivateChannel(uint32_t playerId, std::string &receiver); + void playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackpos, uint8_t count, bool allItems); void playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t count, uint8_t stackpos); void playerCloseNpcChannel(uint32_t playerId); void playerReceivePing(uint32_t playerId); void playerReceivePingBack(uint32_t playerId); - void playerAutoWalk(uint32_t playerId, const std::forward_list& listDir); + void playerAutoWalk(uint32_t playerId, const std::forward_list &listDir); void playerStopAutoWalk(uint32_t playerId); - void playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, - uint16_t fromItemId, const Position& toPos, uint8_t toStackPos, uint16_t toItemId); - void playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPos, uint8_t index, uint16_t itemId); - void playerUseWithCreature(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t itemId); + void playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint16_t fromItemId, const Position &toPos, uint8_t toStackPos, uint16_t toItemId); + void playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPos, uint8_t index, uint16_t itemId); + void playerUseWithCreature(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t itemId); void playerCloseContainer(uint32_t playerId, uint8_t cid); void playerMoveUpContainer(uint32_t playerId, uint8_t cid); void playerUpdateContainer(uint32_t playerId, uint8_t cid); - void playerRotateItem(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t itemId); - void playerConfigureShowOffSocket(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t itemId); - void playerSetShowOffSocket(uint32_t playerId, Outfit_t& outfit, const Position& pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction); - void playerWrapableItem(uint32_t playerId, const Position& pos, uint8_t stackPos, const uint16_t itemId); - void playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string& text); - void playerBrowseField(uint32_t playerId, const Position& pos); + void playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); + void playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); + void playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction); + void playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); + void playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string &text); + void playerBrowseField(uint32_t playerId, const Position &pos); void playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index); - void playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string& text); - void playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t stackPos, - uint32_t tradePlayerId, uint16_t itemId); + void playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string &text); + void playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t stackPos, uint32_t tradePlayerId, uint16_t itemId); void playerAcceptTrade(uint32_t playerId); void playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t index); - void playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, - bool ignoreCap = false, bool inBackpacks = false); - void playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, - uint16_t amount, bool ignoreEquipped = false); + void playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, bool ignoreCap = false, bool inBackpacks = false); + void playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint16_t amount, bool ignoreEquipped = false); void playerCloseShop(uint32_t playerId); void playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count); void playerCloseTrade(uint32_t playerId); @@ -335,35 +299,27 @@ class Game void playerFollowCreature(uint32_t playerId, uint32_t creatureId); void playerCancelAttackAndFollow(uint32_t playerId); void playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool chaseMode, bool secureMode); - void playerLookAt(uint32_t playerId, uint16_t itemId, const Position& pos, uint8_t stackPos); + void playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, uint8_t stackPos); void playerLookInBattleList(uint32_t playerId, uint32_t creatureId); - void playerQuickLoot(uint32_t playerId, const Position& pos, uint16_t itemId, uint8_t stackPos, - Item* defaultItem = nullptr, bool lootAllCorpses = false, bool autoLoot = false); - void playerLootAllCorpses(Player* player, const Position& pos, bool lootAllCorpses); - void playerSetLootContainer(uint32_t playerId, ObjectCategory_t category, - const Position& pos, uint16_t itemId, uint8_t stackPos); - void playerClearLootContainer(uint32_t playerId, ObjectCategory_t category);; + void playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, Item* defaultItem = nullptr, bool lootAllCorpses = false, bool autoLoot = false); + void playerLootAllCorpses(Player* player, const Position &pos, bool lootAllCorpses); + void playerSetLootContainer(uint32_t playerId, ObjectCategory_t category, const Position &pos, uint16_t itemId, uint8_t stackPos); + void playerClearLootContainer(uint32_t playerId, ObjectCategory_t category); + ; void playerOpenLootContainer(uint32_t playerId, ObjectCategory_t category); void playerSetQuickLootFallback(uint32_t playerId, bool fallback); - void playerQuickLootBlackWhitelist(uint32_t playerId, - QuickLootFilter_t filter, const std::vector itemIds); + void playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector itemIds); void playerRequestDepotItems(uint32_t playerId); void playerRequestCloseDepotSearch(uint32_t playerId); void playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint8_t tier); void playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, uint8_t tier, uint8_t type); - void playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position& pos); - void playerMoveThingFromDepotSearch(Player* player, - uint16_t itemId, - uint8_t tier, - uint8_t count, - const Position& fromPos, - const Position& toPos, - bool allItems = false); - - void playerRequestAddVip(uint32_t playerId, const std::string& name); + void playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position &pos); + void playerMoveThingFromDepotSearch(Player* player, uint16_t itemId, uint8_t tier, uint8_t count, const Position &fromPos, const Position &toPos, bool allItems = false); + + void playerRequestAddVip(uint32_t playerId, const std::string &name); void playerRequestRemoveVip(uint32_t playerId, uint32_t guid); - void playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string& description, uint32_t icon, bool notify); + void playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string &description, uint32_t icon, bool notify); void playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t slot, bool protectionCharm); void playerClearImbuement(uint32_t playerid, uint8_t slot); void playerCloseImbuementWindow(uint32_t playerid); @@ -371,8 +327,7 @@ class Game void playerRequestOutfit(uint32_t playerId); void playerShowQuestLog(uint32_t playerId); void playerShowQuestLine(uint32_t playerId, uint16_t questId); - void playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, - const std::string& receiver, const std::string& text); + void playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, const std::string &receiver, const std::string &text); void playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMountRandomized = 0); void playerInviteToParty(uint32_t playerId, uint32_t invitedId); void playerJoinParty(uint32_t playerId, uint32_t leaderId); @@ -389,9 +344,9 @@ class Game void playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter); void playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount); - void parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string& buffer); + void parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string &buffer); - static void updatePremium(account::Account& account); + static void updatePremium(account::Account &account); void cleanup(); void shutdown(); @@ -399,7 +354,9 @@ class Game void ReleaseCreature(Creature* creature); void ReleaseItem(Item* item); void addBestiaryList(uint16_t raceid, std::string name); - const std::map& getBestiaryList() const { return BestiaryList; } + const std::map &getBestiaryList() const { + return BestiaryList; + } void setBoostedName(std::string name) { boostedCreature = name; @@ -409,13 +366,12 @@ class Game return boostedCreature; } - bool canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight = true, - int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY) const; - bool isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor) const; + bool canThrowObjectTo(const Position &fromPos, const Position &toPos, bool checkLineOfSight = true, int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY) const; + bool isSightClear(const Position &fromPos, const Position &toPos, bool sameFloor) const; void changeSpeed(Creature* creature, int32_t varSpeedDelta); - void changePlayerSpeed(Player& player, int32_t varSpeedDelta); - void internalCreatureChangeOutfit(Creature* creature, const Outfit_t& oufit); + void changePlayerSpeed(Player &player, int32_t varSpeedDelta); + void internalCreatureChangeOutfit(Creature* creature, const Outfit_t &oufit); void internalCreatureChangeVisible(Creature* creature, bool visible); void changeLight(const Creature* creature); void updateCreatureIcon(const Creature* creature); @@ -436,32 +392,32 @@ class Game void checkCreatures(size_t index); void checkLight(); - bool combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* target, bool checkDefense, bool checkArmor, bool field); + bool combatBlockHit(CombatDamage &damage, Creature* attacker, Creature* target, bool checkDefense, bool checkArmor, bool field); - void combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColor_t& color, uint8_t& effect); + void combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColor_t &color, uint8_t &effect); - bool combatChangeHealth(Creature* attacker, Creature* target, CombatDamage& damage, bool isEvent = false); - void applyCharmRune(const Monster* targetMonster, Player* attackerPlayer, Creature* target, const int32_t& realDamage) const; + bool combatChangeHealth(Creature* attacker, Creature* target, CombatDamage &damage, bool isEvent = false); + void applyCharmRune(const Monster* targetMonster, Player* attackerPlayer, Creature* target, const int32_t &realDamage) const; void applyManaLeech( Player* attackerPlayer, const Monster* targetMonster, - const CombatDamage& damage, const int32_t& realDamage + const CombatDamage &damage, const int32_t &realDamage ) const; void applyLifeLeech( Player* attackerPlayer, const Monster* targetMonster, - const CombatDamage& damage, const int32_t& realDamage + const CombatDamage &damage, const int32_t &realDamage ) const; - int32_t calculateLeechAmount(const int32_t& realDamage, const uint16_t& skillAmount, int targetsAffected) const; - bool combatChangeMana(Creature* attacker, Creature* target, CombatDamage& damage); + int32_t calculateLeechAmount(const int32_t &realDamage, const uint16_t &skillAmount, int targetsAffected) const; + bool combatChangeMana(Creature* attacker, Creature* target, CombatDamage &damage); // Animation help functions void addCreatureHealth(const Creature* target); - static void addCreatureHealth(const SpectatorHashSet& spectators, const Creature* target); + static void addCreatureHealth(const SpectatorHashSet &spectators, const Creature* target); void addPlayerMana(const Player* target); void addPlayerVocation(const Player* target); - void addMagicEffect(const Position& pos, uint8_t effect); - static void addMagicEffect(const SpectatorHashSet& spectators, const Position& pos, uint8_t effect); - void addDistanceEffect(const Position& fromPos, const Position& toPos, uint8_t effect); - static void addDistanceEffect(const SpectatorHashSet& spectators, const Position& fromPos, const Position& toPos, uint8_t effect); + void addMagicEffect(const Position &pos, uint8_t effect); + static void addMagicEffect(const SpectatorHashSet &spectators, const Position &pos, uint8_t effect); + void addDistanceEffect(const Position &fromPos, const Position &toPos, uint8_t effect); + static void addDistanceEffect(const SpectatorHashSet &spectators, const Position &fromPos, const Position &toPos, uint8_t effect); int32_t getLightHour() const { return lightHour; @@ -471,20 +427,34 @@ class Game void loadMotdNum(); void saveMotdNum() const; - const std::string& getMotdHash() const { return motdHash; } - uint32_t getMotdNum() const { return motdNum; } - void incrementMotdNum() { motdNum++; } + const std::string &getMotdHash() const { + return motdHash; + } + uint32_t getMotdNum() const { + return motdNum; + } + void incrementMotdNum() { + motdNum++; + } void sendOfflineTrainingDialog(Player* player); - const std::map>& getItemsPrice() const { return itemsPriceMap; } - const phmap::flat_hash_map& getPlayers() const { return players; } - const std::map& getMonsters() const { + const std::map> &getItemsPrice() const { + return itemsPriceMap; + } + const phmap::flat_hash_map &getPlayers() const { + return players; + } + const std::map &getMonsters() const { return monsters; } - const std::map& getNpcs() const { return npcs; } + const std::map &getNpcs() const { + return npcs; + } - const std::vector& getItemsClassifications() const { return itemsClassifications; } + const std::vector &getItemsClassifications() const { + return itemsClassifications; + } void addPlayer(Player* player); void removePlayer(Player* player); @@ -498,7 +468,7 @@ class Game Guild* getGuild(uint32_t id) const; void addGuild(Guild* guild); void removeGuild(uint32_t guildId); - void decreaseBrowseFieldRef(const Position& pos); + void decreaseBrowseFieldRef(const Position &pos); phmap::flat_hash_map browseFields; @@ -534,11 +504,10 @@ class Game tilesToClean.clear(); } - void playerInspectItem(Player* player, const Position& pos); + void playerInspectItem(Player* player, const Position &pos); void playerInspectItem(Player* player, uint16_t itemId, uint8_t itemCount, bool cyclopedia); - void addCharmRune(Charm* charm) - { + void addCharmRune(Charm* charm) { CharmList.push_back(charm); CharmList.shrink_to_fit(); } @@ -547,7 +516,7 @@ class Game return CharmList; } - FILELOADER_ERRORS loadAppearanceProtobuf(const std::string& file); + FILELOADER_ERRORS loadAppearanceProtobuf(const std::string &file); bool isMagicEffectRegistered(uint8_t type) const { return std::find(registeredMagicEffects.begin(), registeredMagicEffects.end(), type) != registeredMagicEffects.end(); } @@ -583,20 +552,20 @@ class Game uint32_t makeFiendishMonster(uint32_t forgeableMonsterId = 0, bool createForgeableMonsters = false); uint32_t makeInfluencedMonster(); - bool addInfluencedMonster(Monster *monster); - void sendUpdateCreature(const Creature *creature); - Item* wrapItem(Item *item); + bool addInfluencedMonster(Monster* monster); + void sendUpdateCreature(const Creature* creature); + Item* wrapItem(Item* item); private: std::map forgeMonsterEventIds; std::set fiendishMonsters; std::set influencedMonsters; void checkImbuements(); - bool playerSaySpell(Player* player, SpeakClasses type, const std::string& text); - void playerWhisper(Player* player, const std::string& text); - bool playerYell(Player* player, const std::string& text); - bool playerSpeakTo(Player* player, SpeakClasses type, const std::string& receiver, const std::string& text); - void playerSpeakToNpc(Player* player, const std::string& text); + bool playerSaySpell(Player* player, SpeakClasses type, const std::string &text); + void playerWhisper(Player* player, const std::string &text); + bool playerYell(Player* player, const std::string &text); + bool playerSpeakTo(Player* player, SpeakClasses type, const std::string &receiver, const std::string &text); + void playerSpeakToNpc(Player* player, const std::string &text); phmap::flat_hash_map players; phmap::flat_hash_map mappedPlayerNames; @@ -607,7 +576,7 @@ class Game /* Items stored from the lua scripts positions * For example: ActionFunctions::luaActionPosition * This basically works so that the item is created after the map is loaded, because the scripts are loaded before the map is loaded, we will use this table to create items that don't exist in the map natively through each script - */ + */ std::map mapLuaItemsStored; std::map BestiaryList; @@ -633,7 +602,7 @@ class Game std::map teamFinderMap; // [leaderGUID] = TeamFinder* - //list of items that are in trading state, mapped to the player + // list of items that are in trading state, mapped to the player std::map tradeItems; std::map bedSleepersMap; @@ -660,7 +629,7 @@ class Game uint8_t lightLevel = LIGHT_LEVEL_DAY; int32_t lightHour = SUNRISE + (SUNSET - SUNRISE) / 2; // (1440 total light of tibian day)/(3600 real seconds each tibian day) * 10 seconds event interval - int32_t lightHourDelta = (LIGHT_DAY_LENGTH * (EVENT_LIGHTINTERVAL_MS/1000)) / DAY_LENGTH_SECONDS; + int32_t lightHourDelta = (LIGHT_DAY_LENGTH * (EVENT_LIGHTINTERVAL_MS / 1000)) / DAY_LENGTH_SECONDS; ServiceManager* serviceManager = nullptr; @@ -675,47 +644,47 @@ class Game std::vector itemsClassifications; - bool isTryingToStow(const Position &toPos, Cylinder *toCylinder) const; + bool isTryingToStow(const Position &toPos, Cylinder* toCylinder) const; void sendDamageMessageAndEffects( - const Creature *attacker, Creature *target, const CombatDamage &damage, const Position &targetPos, - Player *attackerPlayer, Player *targetPlayer, TextMessage &message, + const Creature* attacker, Creature* target, const CombatDamage &damage, const Position &targetPos, + Player* attackerPlayer, Player* targetPlayer, TextMessage &message, const SpectatorHashSet &spectators, int32_t realDamage ); - void updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const Player *player) const; + void updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const Player* player) const; void sendEffects( - Creature *target, const CombatDamage &damage, const Position &targetPos, + Creature* target, const CombatDamage &damage, const Position &targetPos, TextMessage &message, const SpectatorHashSet &spectators ); void sendMessages( - const Creature *attacker, const Creature *target, const CombatDamage &damage, - const Position &targetPos, Player *attackerPlayer, Player *targetPlayer, + const Creature* attacker, const Creature* target, const CombatDamage &damage, + const Position &targetPos, Player* attackerPlayer, Player* targetPlayer, TextMessage &message, const SpectatorHashSet &spectators, int32_t realDamage ) const; bool shouldSendMessage(const TextMessage &message) const; void buildMessageAsAttacker( - const Creature *target, const CombatDamage &damage, TextMessage &message, + const Creature* target, const CombatDamage &damage, TextMessage &message, std::stringstream &ss, const std::string &damageString ) const; void buildMessageAsTarget( - const Creature *attacker, const CombatDamage &damage, const Player *attackerPlayer, - const Player *targetPlayer, TextMessage &message, std::stringstream &ss, + const Creature* attacker, const CombatDamage &damage, const Player* attackerPlayer, + const Player* targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString ) const; void buildMessageAsSpectator( - const Creature *attacker, const Creature *target, const CombatDamage &damage, - const Player *targetPlayer, TextMessage &message, std::stringstream &ss, + const Creature* attacker, const Creature* target, const CombatDamage &damage, + const Player* targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString, std::string &spectatorMessage ) const; }; constexpr auto g_game = &Game::getInstance; -#endif // SRC_GAME_GAME_H_ +#endif // SRC_GAME_GAME_H_ diff --git a/src/game/game_definitions.hpp b/src/game/game_definitions.hpp index e90469e3ff1..a49af459b3c 100644 --- a/src/game/game_definitions.hpp +++ b/src/game/game_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_GAME_DEFINITIONS_HPP_ #define SRC_GAME_GAME_DEFINITIONS_HPP_ @@ -14,20 +14,20 @@ // Enums enum Offer_t { - DISABLED=0, - ITEM=1, - STACKABLE_ITEM=2, - OUTFIT=3, - OUTFIT_ADDON=4, - MOUNT=5, - NAMECHANGE=6, - SEXCHANGE=7, - PROMOTION=8, + DISABLED = 0, + ITEM = 1, + STACKABLE_ITEM = 2, + OUTFIT = 3, + OUTFIT_ADDON = 4, + MOUNT = 5, + NAMECHANGE = 6, + SEXCHANGE = 7, + PROMOTION = 8, PREMIUM_TIME, TELEPORT, BLESSING, - BOOST_XP, //not using yet - BOOST_STAMINA, //not using yet + BOOST_XP, // not using yet + BOOST_STAMINA, // not using yet WRAP_ITEM }; @@ -124,19 +124,19 @@ enum Webhook_Colors_t : uint32_t { }; struct ModalWindow { - std::list> buttons, choices; - std::string title, message; - uint32_t id; - uint8_t defaultEnterButton, defaultEscapeButton; - bool priority; - - ModalWindow(uint32_t newId, std::string newTitle, std::string newMessage) : - title(std::move(newTitle)), - message(std::move(newMessage)), - id(newId), - defaultEnterButton(0xFF), - defaultEscapeButton(0xFF), - priority(false) {} + std::list> buttons, choices; + std::string title, message; + uint32_t id; + uint8_t defaultEnterButton, defaultEscapeButton; + bool priority; + + ModalWindow(uint32_t newId, std::string newTitle, std::string newMessage) : + title(std::move(newTitle)), + message(std::move(newMessage)), + id(newId), + defaultEnterButton(0xFF), + defaultEscapeButton(0xFF), + priority(false) { } }; -#endif // SRC_GAME_GAME_DEFINITIONS_HPP_ +#endif // SRC_GAME_GAME_DEFINITIONS_HPP_ diff --git a/src/game/movement/position.cpp b/src/game/movement/position.cpp index 38d3cc92361..648f5b0ad3b 100644 --- a/src/game/movement/position.cpp +++ b/src/game/movement/position.cpp @@ -5,34 +5,31 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "game/movement/position.h" #include "utils/tools.h" -Direction Position::getRandomDirection() -{ - static std::vector dirList{ - DIRECTION_NORTH, - DIRECTION_WEST, - DIRECTION_EAST, - DIRECTION_SOUTH +Direction Position::getRandomDirection() { + static std::vector dirList { + DIRECTION_NORTH, + DIRECTION_WEST, + DIRECTION_EAST, + DIRECTION_SOUTH }; std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); return dirList.front(); } -std::ostream& operator<<(std::ostream& os, const Position& pos) -{ +std::ostream &operator<<(std::ostream &os, const Position &pos) { os << pos.toString(); return os; } -std::ostream& operator<<(std::ostream& os, const Direction& dir) -{ +std::ostream &operator<<(std::ostream &os, const Direction &dir) { switch (dir) { case DIRECTION_NORTH: os << "North"; diff --git a/src/game/movement/position.h b/src/game/movement/position.h index 341ab0438ac..bbd3d352302 100644 --- a/src/game/movement/position.h +++ b/src/game/movement/position.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_MOVEMENT_POSITION_H_ #define SRC_GAME_MOVEMENT_POSITION_H_ @@ -26,88 +26,94 @@ enum Direction : uint8_t { DIRECTION_NONE = 8, }; -struct Position -{ - constexpr Position() = default; - constexpr Position(uint16_t initX, uint16_t initY, uint8_t initZ) : x(initX), y(initY), z(initZ) {} - - template - static bool areInRange(const Position& p1, const Position& p2) { - return Position::getDistanceX(p1, p2) <= deltax && Position::getDistanceY(p1, p2) <= deltay; - } - - template - static bool areInRange(const Position& p1, const Position& p2) { - return Position::getDistanceX(p1, p2) <= deltax && Position::getDistanceY(p1, p2) <= deltay && Position::getDistanceZ(p1, p2) <= deltaz; - } - - static int_fast32_t getOffsetX(const Position& p1, const Position& p2) { - return p1.getX() - p2.getX(); - } - static int_fast32_t getOffsetY(const Position& p1, const Position& p2) { - return p1.getY() - p2.getY(); - } - static int_fast16_t getOffsetZ(const Position& p1, const Position& p2) { - return p1.getZ() - p2.getZ(); - } - - static int32_t getDistanceX(const Position& p1, const Position& p2) { - return std::abs(Position::getOffsetX(p1, p2)); - } - static int32_t getDistanceY(const Position& p1, const Position& p2) { - return std::abs(Position::getOffsetY(p1, p2)); - } - static int16_t getDistanceZ(const Position& p1, const Position& p2) { - return std::abs(Position::getOffsetZ(p1, p2)); - } - - static Direction getRandomDirection(); - - uint16_t x = 0; - uint16_t y = 0; - uint8_t z = 0; - - bool operator<(const Position& p) const { - return (z < p.z) || (z == p.z && y < p.y) || (z == p.z && y == p.y && x < p.x); - } - - bool operator>(const Position& p) const { - return ! (*this < p); - } - - bool operator==(const Position& p) const { - return p.x == x && p.y == y && p.z == z; - } - - bool operator!=(const Position& p) const { - return p.x != x || p.y != y || p.z != z; - } - - Position operator+(const Position& p1) const { - return Position(x + p1.x, y + p1.y, z + p1.z); - } - - Position operator-(const Position& p1) const { - return Position(x - p1.x, y - p1.y, z - p1.z); - } - - std::string toString() const { - std::string str; - return str.append("( ") - .append(std::to_string(getX())) - .append(", ") - .append(std::to_string(getY())) - .append(", ") - .append(std::to_string(getZ())) - .append(" )"); - } - - int_fast32_t getX() const { return x; } - int_fast32_t getY() const { return y; } - int_fast16_t getZ() const { return z; } +struct Position { + constexpr Position() = default; + constexpr Position(uint16_t initX, uint16_t initY, uint8_t initZ) : + x(initX), y(initY), z(initZ) { } + + template + static bool areInRange(const Position &p1, const Position &p2) { + return Position::getDistanceX(p1, p2) <= deltax && Position::getDistanceY(p1, p2) <= deltay; + } + + template + static bool areInRange(const Position &p1, const Position &p2) { + return Position::getDistanceX(p1, p2) <= deltax && Position::getDistanceY(p1, p2) <= deltay && Position::getDistanceZ(p1, p2) <= deltaz; + } + + static int_fast32_t getOffsetX(const Position &p1, const Position &p2) { + return p1.getX() - p2.getX(); + } + static int_fast32_t getOffsetY(const Position &p1, const Position &p2) { + return p1.getY() - p2.getY(); + } + static int_fast16_t getOffsetZ(const Position &p1, const Position &p2) { + return p1.getZ() - p2.getZ(); + } + + static int32_t getDistanceX(const Position &p1, const Position &p2) { + return std::abs(Position::getOffsetX(p1, p2)); + } + static int32_t getDistanceY(const Position &p1, const Position &p2) { + return std::abs(Position::getOffsetY(p1, p2)); + } + static int16_t getDistanceZ(const Position &p1, const Position &p2) { + return std::abs(Position::getOffsetZ(p1, p2)); + } + + static Direction getRandomDirection(); + + uint16_t x = 0; + uint16_t y = 0; + uint8_t z = 0; + + bool operator<(const Position &p) const { + return (z < p.z) || (z == p.z && y < p.y) || (z == p.z && y == p.y && x < p.x); + } + + bool operator>(const Position &p) const { + return !(*this < p); + } + + bool operator==(const Position &p) const { + return p.x == x && p.y == y && p.z == z; + } + + bool operator!=(const Position &p) const { + return p.x != x || p.y != y || p.z != z; + } + + Position operator+(const Position &p1) const { + return Position(x + p1.x, y + p1.y, z + p1.z); + } + + Position operator-(const Position &p1) const { + return Position(x - p1.x, y - p1.y, z - p1.z); + } + + std::string toString() const { + std::string str; + return str.append("( ") + .append(std::to_string(getX())) + .append(", ") + .append(std::to_string(getY())) + .append(", ") + .append(std::to_string(getZ())) + .append(" )"); + } + + int_fast32_t getX() const { + return x; + } + int_fast32_t getY() const { + return y; + } + int_fast16_t getZ() const { + return z; + } }; -std::ostream& operator<<(std::ostream&, const Position&); -std::ostream& operator<<(std::ostream&, const Direction&); +std::ostream &operator<<(std::ostream &, const Position &); +std::ostream &operator<<(std::ostream &, const Direction &); -#endif // SRC_GAME_MOVEMENT_POSITION_H_ +#endif // SRC_GAME_MOVEMENT_POSITION_H_ diff --git a/src/game/movement/teleport.cpp b/src/game/movement/teleport.cpp index 38a90660bb4..1290d3909f1 100644 --- a/src/game/movement/teleport.cpp +++ b/src/game/movement/teleport.cpp @@ -5,16 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "game/game.h" #include "game/movement/teleport.h" - -Attr_ReadValue Teleport::readAttr(AttrTypes_t attr, PropStream& propStream) -{ +Attr_ReadValue Teleport::readAttr(AttrTypes_t attr, PropStream &propStream) { if (attr == ATTR_TELE_DEST) { if (!propStream.read(destPos.x) || !propStream.read(destPos.y) || !propStream.read(destPos.z)) { return ATTR_READ_ERROR; @@ -24,8 +22,7 @@ Attr_ReadValue Teleport::readAttr(AttrTypes_t attr, PropStream& propStream) return Item::readAttr(attr, propStream); } -void Teleport::serializeAttr(PropWriteStream& propWriteStream) const -{ +void Teleport::serializeAttr(PropWriteStream &propWriteStream) const { Item::serializeAttr(propWriteStream); propWriteStream.write(ATTR_TELE_DEST); @@ -34,23 +31,19 @@ void Teleport::serializeAttr(PropWriteStream& propWriteStream) const propWriteStream.write(destPos.z); } -ReturnValue Teleport::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature*) const -{ +ReturnValue Teleport::queryAdd(int32_t, const Thing &, uint32_t, uint32_t, Creature*) const { return RETURNVALUE_NOTPOSSIBLE; } -ReturnValue Teleport::queryMaxCount(int32_t, const Thing&, uint32_t, uint32_t&, uint32_t) const -{ +ReturnValue Teleport::queryMaxCount(int32_t, const Thing &, uint32_t, uint32_t &, uint32_t) const { return RETURNVALUE_NOTPOSSIBLE; } -ReturnValue Teleport::queryRemove(const Thing&, uint32_t, uint32_t, Creature* /*= nullptr */) const -{ +ReturnValue Teleport::queryRemove(const Thing &, uint32_t, uint32_t, Creature* /*= nullptr */) const { return RETURNVALUE_NOERROR; } -Cylinder* Teleport::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) -{ +Cylinder* Teleport::queryDestination(int32_t &, const Thing &, Item**, uint32_t &) { return this; } @@ -60,7 +53,7 @@ bool Teleport::checkInfinityLoop(Tile* destTile) { } if (Teleport* teleport = destTile->getTeleportItem()) { - const Position& nextDestPos = teleport->getDestPos(); + const Position &nextDestPos = teleport->getDestPos(); if (getPosition() == nextDestPos) { return true; } @@ -69,13 +62,11 @@ bool Teleport::checkInfinityLoop(Tile* destTile) { return false; } -void Teleport::addThing(Thing* thing) -{ +void Teleport::addThing(Thing* thing) { return addThing(0, thing); } -void Teleport::addThing(int32_t, Thing* thing) -{ +void Teleport::addThing(int32_t, Thing* thing) { Tile* destTile = g_game().map.getTile(destPos); if (!destTile) { return; @@ -83,9 +74,10 @@ void Teleport::addThing(int32_t, Thing* thing) // Prevent infinity loop if (checkInfinityLoop(destTile)) { - const Position& pos = getPosition(); + const Position &pos = getPosition(); SPDLOG_WARN("[Teleport:addThing] - " - "Infinity loop teleport at position: {}", pos.toString()); + "Infinity loop teleport at position: {}", + pos.toString()); return; } @@ -108,27 +100,22 @@ void Teleport::addThing(int32_t, Thing* thing) } } -void Teleport::updateThing(Thing*, uint16_t, uint32_t) -{ +void Teleport::updateThing(Thing*, uint16_t, uint32_t) { // } -void Teleport::replaceThing(uint32_t, Thing*) -{ +void Teleport::replaceThing(uint32_t, Thing*) { // } -void Teleport::removeThing(Thing*, uint32_t) -{ +void Teleport::removeThing(Thing*, uint32_t) { // } -void Teleport::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void Teleport::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } -void Teleport::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void Teleport::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/game/movement/teleport.h b/src/game/movement/teleport.h index 9c08db9cc51..9a4a2b5769d 100644 --- a/src/game/movement/teleport.h +++ b/src/game/movement/teleport.h @@ -5,17 +5,17 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_MOVEMENT_TELEPORT_H_ #define SRC_GAME_MOVEMENT_TELEPORT_H_ #include "items/tile.h" -class Teleport final : public Item, public Cylinder -{ +class Teleport final : public Item, public Cylinder { public: - explicit Teleport(uint16_t type) : Item(type) {}; + explicit Teleport(uint16_t type) : + Item(type) {}; Teleport* getTeleport() override { return this; @@ -24,11 +24,11 @@ class Teleport final : public Item, public Cylinder return this; } - //serialization - Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; - void serializeAttr(PropWriteStream& propWriteStream) const override; + // serialization + Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream) override; + void serializeAttr(PropWriteStream &propWriteStream) const override; - const Position& getDestPos() const { + const Position &getDestPos() const { return destPos; } void setDestPos(Position pos) { @@ -37,14 +37,11 @@ class Teleport final : public Item, public Cylinder bool checkInfinityLoop(Tile* destTile); - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; - ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, - uint32_t& maxQueryCount, uint32_t flags) const override; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; - Cylinder* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const override; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + Cylinder* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override; void addThing(Thing* thing) override; void addThing(int32_t index, Thing* thing) override; @@ -61,4 +58,4 @@ class Teleport final : public Item, public Cylinder Position destPos; }; -#endif // SRC_GAME_MOVEMENT_TELEPORT_H_ +#endif // SRC_GAME_MOVEMENT_TELEPORT_H_ diff --git a/src/game/scheduling/events_scheduler.cpp b/src/game/scheduling/events_scheduler.cpp index c62ef61ad51..4222ec46fc6 100644 --- a/src/game/scheduling/events_scheduler.cpp +++ b/src/game/scheduling/events_scheduler.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,8 +14,7 @@ #include "lua/scripts/scripts.h" #include "utils/pugicast.h" -bool EventsScheduler::loadScheduleEventFromXml() const -{ +bool EventsScheduler::loadScheduleEventFromXml() const { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/events.xml"; if ( @@ -23,8 +22,7 @@ bool EventsScheduler::loadScheduleEventFromXml() const pugi::xml_parse_result result = doc.load_file(folder.c_str()); // Condition !result - ) - { + ) { printXMLError(__FUNCTION__, folder, result); consoleHandlerExit(); return false; @@ -72,9 +70,8 @@ bool EventsScheduler::loadScheduleEventFromXml() const } if ((attr = schedNode.attribute("script")) && (!(g_scripts().loadEventSchedulerScripts(attr.as_string())))) { - SPDLOG_WARN("{} - Can not load the file '{}' on '/events/scripts/scheduler/'", - __FUNCTION__, attr.as_string()); - return false; + SPDLOG_WARN("{} - Can not load the file '{}' on '/events/scripts/scheduler/'", __FUNCTION__, attr.as_string()); + return false; } for (auto schedENode : schedNode.children()) { @@ -93,7 +90,7 @@ bool EventsScheduler::loadScheduleEventFromXml() const if ((schedENode.attribute("spawnrate"))) { uint32_t spawnrate = pugi::cast(schedENode.attribute("spawnrate").value()); g_eventsScheduler().setSpawnMonsterSchedule(spawnrate); - ss << ", spawn: " << spawnrate << "%"; + ss << ", spawn: " << spawnrate << "%"; } if ((schedENode.attribute("skillrate"))) { diff --git a/src/game/scheduling/events_scheduler.hpp b/src/game/scheduling/events_scheduler.hpp index c710863f809..13ba55b3d62 100644 --- a/src/game/scheduling/events_scheduler.hpp +++ b/src/game/scheduling/events_scheduler.hpp @@ -5,24 +5,22 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_SCHEDUNLING_EVENTS_SCHEDULER_HPP_ #define SRC_GAME_SCHEDUNLING_EVENTS_SCHEDULER_HPP_ - #include "utils/tools.h" -class EventsScheduler -{ +class EventsScheduler { public: EventsScheduler() = default; // Singleton - ensures we don't accidentally copy it. - EventsScheduler(const EventsScheduler&) = delete; - EventsScheduler& operator=(const EventsScheduler&) = delete; + EventsScheduler(const EventsScheduler &) = delete; + EventsScheduler &operator=(const EventsScheduler &) = delete; - static EventsScheduler& getInstance() { + static EventsScheduler &getInstance() { // Guaranteed to be destroyed static EventsScheduler instance; // Instantiated on first use @@ -31,45 +29,44 @@ class EventsScheduler // Event schedule xml load bool loadScheduleEventFromXml() const; - + // Event schedule uint16_t getExpSchedule() const { return expSchedule; } void setExpSchedule(uint16_t exprate) { - expSchedule = (expSchedule * exprate)/100; + expSchedule = (expSchedule * exprate) / 100; } uint32_t getLootSchedule() const { return lootSchedule; } void setLootSchedule(uint32_t lootrate) { - lootSchedule = (lootSchedule * lootrate)/100; + lootSchedule = (lootSchedule * lootrate) / 100; } uint32_t getSpawnMonsterSchedule() const { return spawnMonsterSchedule; } void setSpawnMonsterSchedule(uint32_t spawnrate) { - spawnMonsterSchedule = (spawnMonsterSchedule * spawnrate)/100; + spawnMonsterSchedule = (spawnMonsterSchedule * spawnrate) / 100; } uint16_t getSkillSchedule() const { return skillSchedule; } void setSkillSchedule(uint16_t skillrate) { - skillSchedule = (skillSchedule * skillrate)/100; + skillSchedule = (skillSchedule * skillrate) / 100; } - + private: // Event schedule uint16_t expSchedule = 100; uint32_t lootSchedule = 100; uint16_t skillSchedule = 100; uint32_t spawnMonsterSchedule = 100; - }; constexpr auto g_eventsScheduler = &EventsScheduler::getInstance; -#endif // SRC_GAME_SCHEDUNLING_EVENTS_SCHEDULER_HPP_ +#endif // SRC_GAME_SCHEDUNLING_EVENTS_SCHEDULER_HPP_ diff --git a/src/game/scheduling/scheduler.cpp b/src/game/scheduling/scheduler.cpp index 9efa786a56c..f16a20c710c 100644 --- a/src/game/scheduling/scheduler.cpp +++ b/src/game/scheduling/scheduler.cpp @@ -5,14 +5,13 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "game/scheduling/scheduler.h" -void Scheduler::threadMain() -{ +void Scheduler::threadMain() { std::unique_lock eventLockUnique(eventLock, std::defer_lock); while (getState() != THREAD_STATE_TERMINATED) { std::cv_status ret = std::cv_status::no_timeout; @@ -50,8 +49,7 @@ void Scheduler::threadMain() } } -uint32_t Scheduler::addEvent(SchedulerTask* task) -{ +uint32_t Scheduler::addEvent(SchedulerTask* task) { bool do_signal; eventLock.lock(); @@ -90,8 +88,7 @@ uint32_t Scheduler::addEvent(SchedulerTask* task) return task->getEventId(); } -bool Scheduler::stopEvent(uint32_t eventid) -{ +bool Scheduler::stopEvent(uint32_t eventid) { if (eventid == 0) { return false; } @@ -108,12 +105,11 @@ bool Scheduler::stopEvent(uint32_t eventid) return true; } -void Scheduler::shutdown() -{ +void Scheduler::shutdown() { setState(THREAD_STATE_TERMINATED); eventLock.lock(); - //this list should already be empty + // this list should already be empty while (!eventList.empty()) { delete eventList.top(); eventList.pop(); @@ -124,7 +120,6 @@ void Scheduler::shutdown() eventSignal.notify_one(); } -SchedulerTask* createSchedulerTask(uint32_t delay, std::function f) -{ +SchedulerTask* createSchedulerTask(uint32_t delay, std::function f) { return new SchedulerTask(delay, std::move(f)); } diff --git a/src/game/scheduling/scheduler.h b/src/game/scheduling/scheduler.h index cb65e727176..4eb82b87810 100644 --- a/src/game/scheduling/scheduler.h +++ b/src/game/scheduling/scheduler.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_SCHEDULING_SCHEDULER_H_ #define SRC_GAME_SCHEDULING_SCHEDULER_H_ @@ -15,8 +15,7 @@ static constexpr int32_t SCHEDULER_MINTICKS = 50; -class SchedulerTask : public Task -{ +class SchedulerTask : public Task { public: void setEventId(uint32_t id) { eventId = id; @@ -30,30 +29,30 @@ class SchedulerTask : public Task } private: - SchedulerTask(uint32_t delay, std::function&& f) : Task(delay, std::move(f)) {} + SchedulerTask(uint32_t delay, std::function &&f) : + Task(delay, std::move(f)) { } uint32_t eventId = 0; - friend SchedulerTask* createSchedulerTask(uint32_t, std::function); + friend SchedulerTask* createSchedulerTask(uint32_t, std::function); }; -SchedulerTask* createSchedulerTask(uint32_t delay, std::function f); +SchedulerTask* createSchedulerTask(uint32_t delay, std::function f); struct TaskComparator { - bool operator()(const SchedulerTask* lhs, const SchedulerTask* rhs) const { - return lhs->getCycle() > rhs->getCycle(); - } + bool operator()(const SchedulerTask* lhs, const SchedulerTask* rhs) const { + return lhs->getCycle() > rhs->getCycle(); + } }; -class Scheduler : public ThreadHolder -{ +class Scheduler : public ThreadHolder { public: Scheduler() = default; - - Scheduler(Scheduler const&) = delete; - void operator=(Scheduler const&) = delete; - static Scheduler& getInstance() { + Scheduler(const Scheduler &) = delete; + void operator=(const Scheduler &) = delete; + + static Scheduler &getInstance() { // Guaranteed to be destroyed static Scheduler instance; // Instantiated on first use @@ -72,11 +71,11 @@ class Scheduler : public ThreadHolder std::mutex eventLock; std::condition_variable eventSignal; - uint32_t lastEventId {0}; + uint32_t lastEventId { 0 }; std::priority_queue, TaskComparator> eventList; phmap::flat_hash_set eventIds; }; constexpr auto g_scheduler = &Scheduler::getInstance; -#endif // SRC_GAME_SCHEDULING_SCHEDULER_H_ +#endif // SRC_GAME_SCHEDULING_SCHEDULER_H_ diff --git a/src/game/scheduling/tasks.cpp b/src/game/scheduling/tasks.cpp index f7516b07e3e..00eb77266dc 100644 --- a/src/game/scheduling/tasks.cpp +++ b/src/game/scheduling/tasks.cpp @@ -5,25 +5,22 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "game/game.h" #include "game/scheduling/tasks.h" -Task* createTask(std::function f) -{ +Task* createTask(std::function f) { return new Task(std::move(f)); } -Task* createTask(uint32_t expiration, std::function f) -{ +Task* createTask(uint32_t expiration, std::function f) { return new Task(expiration, std::move(f)); } -void Dispatcher::threadMain() -{ +void Dispatcher::threadMain() { // NOTE: second argument defer_lock is to prevent from immediate locking std::unique_lock taskLockUnique(taskLock, std::defer_lock); @@ -32,7 +29,7 @@ void Dispatcher::threadMain() taskLockUnique.lock(); if (taskList.empty()) { - //if the list is empty wait for signal + // if the list is empty wait for signal taskSignal.wait(taskLockUnique, [this] { return !taskList.empty() || getState() == THREAD_STATE_TERMINATED; }); @@ -56,8 +53,7 @@ void Dispatcher::threadMain() } } -void Dispatcher::addTask(Task* task, bool push_front /*= false*/) -{ +void Dispatcher::addTask(Task* task, bool push_front /*= false*/) { bool do_signal = false; taskLock.lock(); @@ -82,8 +78,7 @@ void Dispatcher::addTask(Task* task, bool push_front /*= false*/) } } -void Dispatcher::shutdown() -{ +void Dispatcher::shutdown() { Task* task = createTask([this]() { setState(THREAD_STATE_TERMINATED); taskSignal.notify_one(); diff --git a/src/game/scheduling/tasks.h b/src/game/scheduling/tasks.h index 602a4f00910..76c2446438a 100644 --- a/src/game/scheduling/tasks.h +++ b/src/game/scheduling/tasks.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_SCHEDULING_TASKS_H_ #define SRC_GAME_SCHEDULING_TASKS_H_ @@ -15,13 +15,13 @@ const int DISPATCHER_TASK_EXPIRATION = 2000; const auto SYSTEM_TIME_ZERO = std::chrono::system_clock::time_point(std::chrono::milliseconds(0)); -class Task -{ +class Task { public: // DO NOT allocate this class on the stack - explicit Task(std::function&& f) : func(std::move(f)) {} - Task(uint32_t ms, std::function&& f) : - expiration(std::chrono::system_clock::now() + std::chrono::milliseconds(ms)), func(std::move(f)) {} + explicit Task(std::function &&f) : + func(std::move(f)) { } + Task(uint32_t ms, std::function &&f) : + expiration(std::chrono::system_clock::now() + std::chrono::milliseconds(ms)), func(std::move(f)) { } virtual ~Task() = default; void operator()() { @@ -46,20 +46,20 @@ class Task // Expiration has another meaning for scheduler tasks, // then it is the time the task should be added to the // dispatcher - std::function func; + std::function func; }; -Task* createTask(std::function f); -Task* createTask(uint32_t expiration, std::function f); +Task* createTask(std::function f); +Task* createTask(uint32_t expiration, std::function f); class Dispatcher : public ThreadHolder { public: Dispatcher() = default; - Dispatcher(Dispatcher const&) = delete; - void operator=(Dispatcher const&) = delete; + Dispatcher(const Dispatcher &) = delete; + void operator=(const Dispatcher &) = delete; - static Dispatcher& getInstance() { + static Dispatcher &getInstance() { // Guaranteed to be destroyed static Dispatcher instance; // Instantiated on first use @@ -86,4 +86,4 @@ class Dispatcher : public ThreadHolder { constexpr auto g_dispatcher = &Dispatcher::getInstance; -#endif // SRC_GAME_SCHEDULING_TASKS_H_ +#endif // SRC_GAME_SCHEDULING_TASKS_H_ diff --git a/src/io/fileloader.cpp b/src/io/fileloader.cpp index ca2c70dbad2..00a21631fc4 100644 --- a/src/io/fileloader.cpp +++ b/src/io/fileloader.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,100 +13,97 @@ namespace OTB { -constexpr Identifier wildcard = {{'\0', '\0', '\0', '\0'}}; + constexpr Identifier wildcard = { { '\0', '\0', '\0', '\0' } }; -Loader::Loader(const std::string& fileName, const Identifier& acceptedIdentifier): - fileContents(fileName) -{ - constexpr auto minimalSize = sizeof(Identifier) + sizeof(Node::START) + sizeof(Node::type) + sizeof(Node::END); - if (fileContents.size() <= minimalSize) { - throw InvalidOTBFormat{}; - } + Loader::Loader(const std::string &fileName, const Identifier &acceptedIdentifier) : + fileContents(fileName) { + constexpr auto minimalSize = sizeof(Identifier) + sizeof(Node::START) + sizeof(Node::type) + sizeof(Node::END); + if (fileContents.size() <= minimalSize) { + throw InvalidOTBFormat {}; + } - Identifier fileIdentifier; - std::copy(fileContents.begin(), fileContents.begin() + fileIdentifier.size(), fileIdentifier.begin()); - if (fileIdentifier != acceptedIdentifier && fileIdentifier != wildcard) { - throw InvalidOTBFormat{}; + Identifier fileIdentifier; + std::copy(fileContents.begin(), fileContents.begin() + fileIdentifier.size(), fileIdentifier.begin()); + if (fileIdentifier != acceptedIdentifier && fileIdentifier != wildcard) { + throw InvalidOTBFormat {}; + } } -} -using NodeStack = std::stack>; -static Node& getCurrentNode(const NodeStack& nodeStack) { - if (nodeStack.empty()) { - throw InvalidOTBFormat{}; + using NodeStack = std::stack>; + static Node &getCurrentNode(const NodeStack &nodeStack) { + if (nodeStack.empty()) { + throw InvalidOTBFormat {}; + } + return *nodeStack.top(); } - return *nodeStack.top(); -} -const Node& Loader::parseTree() -{ - auto it = fileContents.begin() + sizeof(Identifier); - if (static_cast(*it) != Node::START) { - throw InvalidOTBFormat{}; - } - root.type = *(++it); - root.propsBegin = ++it; - NodeStack parseStack; - parseStack.push(&root); + const Node &Loader::parseTree() { + auto it = fileContents.begin() + sizeof(Identifier); + if (static_cast(*it) != Node::START) { + throw InvalidOTBFormat {}; + } + root.type = *(++it); + root.propsBegin = ++it; + NodeStack parseStack; + parseStack.push(&root); - for (; it != fileContents.end(); ++it) { - switch(static_cast(*it)) { - case Node::START: { - auto& currentNode = getCurrentNode(parseStack); - if (currentNode.children.empty()) { - currentNode.propsEnd = it; + for (; it != fileContents.end(); ++it) { + switch (static_cast(*it)) { + case Node::START: { + auto ¤tNode = getCurrentNode(parseStack); + if (currentNode.children.empty()) { + currentNode.propsEnd = it; + } + currentNode.children.emplace_back(); + auto &child = currentNode.children.back(); + if (++it == fileContents.end()) { + throw InvalidOTBFormat {}; + } + child.type = *it; + child.propsBegin = it + sizeof(Node::type); + parseStack.push(&child); + break; } - currentNode.children.emplace_back(); - auto& child = currentNode.children.back(); - if (++it == fileContents.end()) { - throw InvalidOTBFormat{}; + case Node::END: { + auto ¤tNode = getCurrentNode(parseStack); + if (currentNode.children.empty()) { + currentNode.propsEnd = it; + } + parseStack.pop(); + break; } - child.type = *it; - child.propsBegin = it + sizeof(Node::type); - parseStack.push(&child); - break; - } - case Node::END: { - auto& currentNode = getCurrentNode(parseStack); - if (currentNode.children.empty()) { - currentNode.propsEnd = it; + case Node::ESCAPE: { + if (++it == fileContents.end()) { + throw InvalidOTBFormat {}; + } + break; } - parseStack.pop(); - break; - } - case Node::ESCAPE: { - if (++it == fileContents.end()) { - throw InvalidOTBFormat{}; + default: { + break; } - break; - } - default: { - break; } } - } - if (!parseStack.empty()) { - throw InvalidOTBFormat{}; + if (!parseStack.empty()) { + throw InvalidOTBFormat {}; + } + + return root; } - return root; -} + bool Loader::getProps(const Node &node, PropStream &props) { + auto size = std::distance(node.propsBegin, node.propsEnd); + if (size == 0) { + return false; + } + propBuffer.resize(size); + bool lastEscaped = false; -bool Loader::getProps(const Node& node, PropStream& props) -{ - auto size = std::distance(node.propsBegin, node.propsEnd); - if (size == 0) { - return false; + auto escapedPropEnd = std::copy_if(node.propsBegin, node.propsEnd, propBuffer.begin(), [&lastEscaped](const char &byte) { + lastEscaped = byte == static_cast(Node::ESCAPE) && !lastEscaped; + return !lastEscaped; + }); + props.init(&propBuffer[0], std::distance(propBuffer.begin(), escapedPropEnd)); + return true; } - propBuffer.resize(size); - bool lastEscaped = false; - - auto escapedPropEnd = std::copy_if(node.propsBegin, node.propsEnd, propBuffer.begin(), [&lastEscaped](const char& byte) { - lastEscaped = byte == static_cast(Node::ESCAPE) && !lastEscaped; - return !lastEscaped; - }); - props.init(&propBuffer[0], std::distance(propBuffer.begin(), escapedPropEnd)); - return true; -} -} //namespace OTB +} // namespace OTB diff --git a/src/io/fileloader.h b/src/io/fileloader.h index 47072ffc310..c01a0469fc9 100644 --- a/src/io/fileloader.h +++ b/src/io/fileloader.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_FILELOADER_H_ #define SRC_IO_FILELOADER_H_ @@ -13,51 +13,50 @@ class PropStream; namespace OTB { - using Identifier = std::array < char, 4 > ; + using Identifier = std::array; struct Node { - Node() = default; - Node(Node&&) = default; - Node& operator=(Node&&) = default; - Node(const Node&) = delete; - Node& operator=(const Node&) = delete; - - std::list children; - mio::mmap_source::const_iterator propsBegin; - mio::mmap_source::const_iterator propsEnd; - uint8_t type; - enum NodeChar: uint8_t { - ESCAPE = 0xFD, - START = 0xFE, - END = 0xFF, - }; + Node() = default; + Node(Node &&) = default; + Node &operator=(Node &&) = default; + Node(const Node &) = delete; + Node &operator=(const Node &) = delete; + + std::list children; + mio::mmap_source::const_iterator propsBegin; + mio::mmap_source::const_iterator propsEnd; + uint8_t type; + enum NodeChar : uint8_t { + ESCAPE = 0xFD, + START = 0xFE, + END = 0xFF, + }; }; - struct LoadError: std::exception { - const char * what() const noexcept override = 0; + struct LoadError : std::exception { + const char* what() const noexcept override = 0; }; - struct InvalidOTBFormat final: LoadError { - const char * what() const noexcept override { - return "Invalid OTBM file format"; - } + struct InvalidOTBFormat final : LoadError { + const char* what() const noexcept override { + return "Invalid OTBM file format"; + } }; class Loader { - mio::mmap_source fileContents; - Node root; - std::vector < char > propBuffer; + mio::mmap_source fileContents; + Node root; + std::vector propBuffer; + public: - Loader(const std::string & fileName, - const Identifier & acceptedIdentifier); - bool getProps(const Node & node, PropStream & props); - const Node & parseTree(); + Loader(const std::string &fileName, const Identifier &acceptedIdentifier); + bool getProps(const Node &node, PropStream &props); + const Node &parseTree(); }; -} //namespace OTB +} // namespace OTB -class PropStream -{ +class PropStream { public: void init(const char* a, size_t size) { p = a; @@ -69,7 +68,7 @@ class PropStream } template - bool read(T& ret) { + bool read(T &ret) { if (size() < sizeof(T)) { return false; } @@ -79,7 +78,7 @@ class PropStream return true; } - bool readString(std::string& ret) { + bool readString(std::string &ret) { uint16_t strLen; if (!read(strLen)) { return false; @@ -112,16 +111,15 @@ class PropStream const char* end = nullptr; }; -class PropWriteStream -{ +class PropWriteStream { public: PropWriteStream() = default; // non-copyable - PropWriteStream(const PropWriteStream&) = delete; - PropWriteStream& operator=(const PropWriteStream&) = delete; + PropWriteStream(const PropWriteStream &) = delete; + PropWriteStream &operator=(const PropWriteStream &) = delete; - const char* getStream(size_t& size) const { + const char* getStream(size_t &size) const { size = buffer.size(); return buffer.data(); } @@ -136,7 +134,7 @@ class PropWriteStream std::copy(addr, addr + sizeof(T), std::back_inserter(buffer)); } - void writeString(const std::string& str) { + void writeString(const std::string &str) { size_t strLength = str.size(); if (strLength > std::numeric_limits::max()) { write(0); @@ -151,4 +149,4 @@ class PropWriteStream std::vector buffer; }; -#endif // SRC_IO_FILELOADER_H_ +#endif // SRC_IO_FILELOADER_H_ diff --git a/src/io/functions/iologindata_load_player.cpp b/src/io/functions/iologindata_load_player.cpp index 46e0a03ec56..0816ed68c85 100644 --- a/src/io/functions/iologindata_load_player.cpp +++ b/src/io/functions/iologindata_load_player.cpp @@ -5,13 +5,13 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "io/functions/iologindata_load_player.hpp" -void IOLoginDataLoad::loadPlayerForgeHistory(Player *player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerForgeHistory(Player* player, DBResult_ptr result) { std::ostringstream query; query << "SELECT * FROM `forge_history` WHERE `player_id` = " << player->getGUID(); if (result = Database::getInstance().storeQuery(query.str())) { diff --git a/src/io/functions/iologindata_load_player.hpp b/src/io/functions/iologindata_load_player.hpp index 107110c1c6a..ccd23a5212d 100644 --- a/src/io/functions/iologindata_load_player.hpp +++ b/src/io/functions/iologindata_load_player.hpp @@ -5,17 +5,16 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_FUNCTIONS_IOLOGINDATALOAD_HPP_ #define SRC_IO_FUNCTIONS_IOLOGINDATALOAD_HPP_ #include "io/iologindata.h" -class IOLoginDataLoad : public IOLoginData -{ -public: - static void loadPlayerForgeHistory(Player *player, DBResult_ptr result); +class IOLoginDataLoad : public IOLoginData { + public: + static void loadPlayerForgeHistory(Player* player, DBResult_ptr result); }; -#endif // SRC_IO_FUNCTIONS_IOLOGINDATALOAD_HPP_ +#endif // SRC_IO_FUNCTIONS_IOLOGINDATALOAD_HPP_ diff --git a/src/io/functions/iologindata_save_player.cpp b/src/io/functions/iologindata_save_player.cpp index 81e7026d28a..c4ac5b77237 100644 --- a/src/io/functions/iologindata_save_player.cpp +++ b/src/io/functions/iologindata_save_player.cpp @@ -5,13 +5,13 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "io/functions/iologindata_save_player.hpp" -bool IOLoginDataSave::savePlayerForgeHistory(Player *player) { +bool IOLoginDataSave::savePlayerForgeHistory(Player* player) { std::ostringstream query; query << "DELETE FROM `forge_history` WHERE `player_id` = " << player->getGUID(); if (!Database::getInstance().executeQuery(query.str())) { @@ -26,10 +26,10 @@ bool IOLoginDataSave::savePlayerForgeHistory(Player *player) { auto actionString = magic_enum::enum_integer(history.actionType); // Append query informations query << player->getGUID() << ',' - << std::to_string(actionString) << ',' - << stringDescription << ',' - << history.createdAt << ',' - << history.success; + << std::to_string(actionString) << ',' + << stringDescription << ',' + << history.createdAt << ',' + << history.success; if (!insertQuery.addRow(query)) { return false; diff --git a/src/io/functions/iologindata_save_player.hpp b/src/io/functions/iologindata_save_player.hpp index 8a50ec055fc..fd9476af764 100644 --- a/src/io/functions/iologindata_save_player.hpp +++ b/src/io/functions/iologindata_save_player.hpp @@ -5,17 +5,16 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO__FUNCTIONS_IOLOGINDATASAVE_HPP_ #define SRC_IO__FUNCTIONS_IOLOGINDATASAVE_HPP_ #include "io/iologindata.h" -class IOLoginDataSave : public IOLoginData -{ -public: - static bool savePlayerForgeHistory(Player *player); +class IOLoginDataSave : public IOLoginData { + public: + static bool savePlayerForgeHistory(Player* player); }; -#endif // SRC_IO__FUNCTIONS_IOLOGINDATASAVE_HPP_ +#endif // SRC_IO__FUNCTIONS_IOLOGINDATASAVE_HPP_ diff --git a/src/io/io_definitions.hpp b/src/io/io_definitions.hpp index a2b8ae69edb..890b01f7a85 100644 --- a/src/io/io_definitions.hpp +++ b/src/io/io_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IO_DEFINITIONS_HPP_ #define SRC_IO_IO_DEFINITIONS_HPP_ @@ -77,17 +77,17 @@ enum OTBM_TileFlag_t : uint32_t { // Structs struct MarketStatistics { - MarketStatistics() { - numTransactions = 0; - highestPrice = 0; - totalPrice = 0; - lowestPrice = 0; - } + MarketStatistics() { + numTransactions = 0; + highestPrice = 0; + totalPrice = 0; + lowestPrice = 0; + } - uint32_t numTransactions; - uint64_t highestPrice; - uint64_t totalPrice; - uint64_t lowestPrice; + uint32_t numTransactions; + uint64_t highestPrice; + uint64_t totalPrice; + uint64_t lowestPrice; }; -#endif // SRC_IO_IO_DEFINITIONS_HPP_ +#endif // SRC_IO_IO_DEFINITIONS_HPP_ diff --git a/src/io/iobestiary.cpp b/src/io/iobestiary.cpp index ed048ccec3a..63c1448be74 100644 --- a/src/io/iobestiary.cpp +++ b/src/io/iobestiary.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -15,9 +15,7 @@ #include "creatures/monsters/monsters.h" #include "creatures/players/player.h" - -bool IOBestiary::parseCharmCombat(Charm* charm, Player* player, Creature* target, int32_t realDamage) -{ +bool IOBestiary::parseCharmCombat(Charm* charm, Player* player, Creature* target, int32_t realDamage) { if (!charm || !player || !target) { return false; } @@ -31,7 +29,7 @@ bool IOBestiary::parseCharmCombat(Charm* charm, Player* player, Creature* target target->addCondition(cripple); player->sendCancelMessage(charm->cancelMsg); return false; - } + } int32_t maxHealth = target->getMaxHealth(); charmDamage.primary.type = charm->dmgtype; charmDamage.primary.value = ((-maxHealth * (charm->percent)) / 100); @@ -57,7 +55,7 @@ bool IOBestiary::parseCharmCombat(Charm* charm, Player* player, Creature* target break; } case CHARM_DODGE: { - const Position& targetPos = target->getPosition(); + const Position &targetPos = target->getPosition(); player->sendCancelMessage(charm->cancelMsg); g_game().addMagicEffect(targetPos, charm->effect); return true; @@ -88,8 +86,7 @@ bool IOBestiary::parseCharmCombat(Charm* charm, Player* player, Creature* target return false; } -Charm* IOBestiary::getBestiaryCharm(charmRune_t activeCharm, bool force /*= false*/) -{ +Charm* IOBestiary::getBestiaryCharm(charmRune_t activeCharm, bool force /*= false*/) { std::vector charmInternal = g_game().getCharmList(); for (Charm* tmpCharm : charmInternal) { if (tmpCharm->id == activeCharm) { @@ -108,8 +105,7 @@ Charm* IOBestiary::getBestiaryCharm(charmRune_t activeCharm, bool force /*= fals return nullptr; } -std::map IOBestiary::findRaceByName(const std::string &race, bool Onlystring /*= true*/, BestiaryType_t raceNumber /*= BESTY_RACE_NONE*/) const -{ +std::map IOBestiary::findRaceByName(const std::string &race, bool Onlystring /*= true*/, BestiaryType_t raceNumber /*= BESTY_RACE_NONE*/) const { std::map best_list = g_game().getBestiaryList(); std::map race_list; @@ -117,22 +113,21 @@ std::map IOBestiary::findRaceByName(const std::string &ra for (auto it : best_list) { const MonsterType* tmpType = g_monsters().getMonsterType(it.second); if (tmpType && tmpType->info.bestiaryClass == race) { - race_list.insert({it.first, it.second}); + race_list.insert({ it.first, it.second }); } } } else { for (auto itn : best_list) { const MonsterType* tmpType = g_monsters().getMonsterType(itn.second); if (tmpType && tmpType->info.bestiaryRace == raceNumber) { - race_list.insert({itn.first, itn.second}); + race_list.insert({ itn.first, itn.second }); } } } return race_list; } -uint8_t IOBestiary::getKillStatus(MonsterType* mtype, uint32_t killAmount) const -{ +uint8_t IOBestiary::getKillStatus(MonsterType* mtype, uint32_t killAmount) const { if (killAmount < mtype->info.bestiaryFirstUnlock) { return 1; } else if (killAmount < mtype->info.bestiarySecondUnlock) { @@ -143,8 +138,7 @@ uint8_t IOBestiary::getKillStatus(MonsterType* mtype, uint32_t killAmount) const return 4; } -void IOBestiary::resetCharmRuneCreature(Player* player, Charm* charm) -{ +void IOBestiary::resetCharmRuneCreature(Player* player, Charm* charm) { if (!player || !charm) { return; } @@ -154,8 +148,7 @@ void IOBestiary::resetCharmRuneCreature(Player* player, Charm* charm) player->parseRacebyCharm(charm->id, true, 0); } -void IOBestiary::setCharmRuneCreature(Player* player, Charm* charm, uint16_t raceid) -{ +void IOBestiary::setCharmRuneCreature(Player* player, Charm* charm, uint16_t raceid) { if (!player || !charm) { return; } @@ -165,9 +158,9 @@ void IOBestiary::setCharmRuneCreature(Player* player, Charm* charm, uint16_t rac player->setUsedRunesBit(Toggle); } -std::list IOBestiary::getCharmUsedRuneBitAll(Player* player) -{ - int32_t input = player->getUsedRunesBit();; +std::list IOBestiary::getCharmUsedRuneBitAll(Player* player) { + int32_t input = player->getUsedRunesBit(); + ; int8_t i = 0; std::list rtn; while (input != 0) { @@ -181,8 +174,7 @@ std::list IOBestiary::getCharmUsedRuneBitAll(Player* player) return rtn; } -uint16_t IOBestiary::getBestiaryRaceUnlocked(Player* player, BestiaryType_t race) const -{ +uint16_t IOBestiary::getBestiaryRaceUnlocked(Player* player, BestiaryType_t race) const { if (!player) { return 0; } @@ -199,8 +191,7 @@ uint16_t IOBestiary::getBestiaryRaceUnlocked(Player* player, BestiaryType_t race return count; } -void IOBestiary::addCharmPoints(Player* player, uint16_t amount, bool negative /*= false*/) -{ +void IOBestiary::addCharmPoints(Player* player, uint16_t amount, bool negative /*= false*/) { if (!player) { return; } @@ -214,8 +205,7 @@ void IOBestiary::addCharmPoints(Player* player, uint16_t amount, bool negative / player->setCharmPoints(myCharms); } -void IOBestiary::addBestiaryKill(Player* player, MonsterType* mtype, uint32_t amount /*= 1*/) -{ +void IOBestiary::addBestiaryKill(Player* player, MonsterType* mtype, uint32_t amount /*= 1*/) { uint16_t raceid = mtype->info.raceid; if (raceid == 0 || !player || !mtype) { return; @@ -225,10 +215,10 @@ void IOBestiary::addBestiaryKill(Player* player, MonsterType* mtype, uint32_t am player->addBestiaryKillCount(raceid, amount); - if ((curCount == 0) || // Initial kill stage - (curCount < mtype->info.bestiaryFirstUnlock && (curCount + amount) >= mtype->info.bestiaryFirstUnlock) || // First kill stage reached - (curCount < mtype->info.bestiarySecondUnlock && (curCount + amount) >= mtype->info.bestiarySecondUnlock) || // Second kill stage reached - (curCount < mtype->info.bestiaryToUnlock && (curCount + amount) >= mtype->info.bestiaryToUnlock)) { // Final kill stage reached + if ((curCount == 0) || // Initial kill stage + (curCount < mtype->info.bestiaryFirstUnlock && (curCount + amount) >= mtype->info.bestiaryFirstUnlock) || // First kill stage reached + (curCount < mtype->info.bestiarySecondUnlock && (curCount + amount) >= mtype->info.bestiarySecondUnlock) || // Second kill stage reached + (curCount < mtype->info.bestiaryToUnlock && (curCount + amount) >= mtype->info.bestiaryToUnlock)) { // Final kill stage reached ss << "You unlocked details for the creature '" << mtype->name << "'"; player->sendTextMessage(MESSAGE_STATUS, ss.str()); @@ -246,8 +236,7 @@ void IOBestiary::addBestiaryKill(Player* player, MonsterType* mtype, uint32_t am } } -charmRune_t IOBestiary::getCharmFromTarget(Player* player, MonsterType* mtype) -{ +charmRune_t IOBestiary::getCharmFromTarget(Player* player, MonsterType* mtype) { if (!player || !mtype) { return CHARM_NONE; } @@ -264,8 +253,7 @@ charmRune_t IOBestiary::getCharmFromTarget(Player* player, MonsterType* mtype) return CHARM_NONE; } -bool IOBestiary::hasCharmUnlockedRuneBit(Charm* charm, int32_t input) const -{ +bool IOBestiary::hasCharmUnlockedRuneBit(Charm* charm, int32_t input) const { if (!charm) { return false; } @@ -273,8 +261,7 @@ bool IOBestiary::hasCharmUnlockedRuneBit(Charm* charm, int32_t input) const return ((input & charm->binary) != 0); } -int32_t IOBestiary::bitToggle(int32_t input, Charm* charm, bool on) const -{ +int32_t IOBestiary::bitToggle(int32_t input, Charm* charm, bool on) const { if (!charm) { return CHARM_NONE; } @@ -291,8 +278,7 @@ int32_t IOBestiary::bitToggle(int32_t input, Charm* charm, bool on) const } } -void IOBestiary::sendBuyCharmRune(Player* player, charmRune_t runeID, uint8_t action, uint16_t raceid) -{ +void IOBestiary::sendBuyCharmRune(Player* player, charmRune_t runeID, uint8_t action, uint16_t raceid) { Charm* charm = getBestiaryCharm(runeID); if (!player || !charm) { return; @@ -340,7 +326,7 @@ void IOBestiary::sendBuyCharmRune(Player* player, charmRune_t runeID, uint8_t ac } else if (action == 2) { int32_t fee = player->getLevel() * 100; if (player->hasCharmExpansion()) { - fee = (fee * 75)/100; + fee = (fee * 75) / 100; } if (g_game().removeMoney(player, fee, 0, true)) { @@ -355,13 +341,12 @@ void IOBestiary::sendBuyCharmRune(Player* player, charmRune_t runeID, uint8_t ac return; } -std::map IOBestiary::getMonsterElements(MonsterType* mtype) const -{ +std::map IOBestiary::getMonsterElements(MonsterType* mtype) const { std::map defaultMap = {}; for (uint8_t i = 0; i <= 7; i++) { defaultMap[i] = 100; } - for (const auto& elementEntry : mtype->info.elementMap) { + for (const auto &elementEntry : mtype->info.elementMap) { switch (elementEntry.first) { case COMBAT_PHYSICALDAMAGE: defaultMap[0] -= static_cast(elementEntry.second); @@ -394,8 +379,7 @@ std::map IOBestiary::getMonsterElements(MonsterType* mtype) co return defaultMap; } -std::map IOBestiary::getBestiaryKillCountByMonsterIDs(Player* player, std::map mtype_list) const -{ +std::map IOBestiary::getBestiaryKillCountByMonsterIDs(Player* player, std::map mtype_list) const { std::map raceMonsters = {}; for (auto it : mtype_list) { uint16_t raceid = it.first; @@ -407,8 +391,7 @@ std::map IOBestiary::getBestiaryKillCountByMonsterIDs(Player return raceMonsters; } -std::list IOBestiary::getBestiaryFinished(Player* player) const -{ +std::list IOBestiary::getBestiaryFinished(Player* player) const { std::list finishedMonsters = {}; std::map besty_l = g_game().getBestiaryList(); @@ -423,8 +406,7 @@ std::list IOBestiary::getBestiaryFinished(Player* player) const return finishedMonsters; } -int8_t IOBestiary::calculateDifficult(uint32_t chance) const -{ +int8_t IOBestiary::calculateDifficult(uint32_t chance) const { float chanceInPercent = chance / 1000; if (chanceInPercent < 0.2) { diff --git a/src/io/iobestiary.h b/src/io/iobestiary.h index cc250220729..0457ee10511 100644 --- a/src/io/iobestiary.h +++ b/src/io/iobestiary.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOBESTIARY_H_ #define SRC_IO_IOBESTIARY_H_ @@ -16,41 +16,38 @@ class Game; -class Charm -{ - public: - Charm() = default; - Charm(std::string initname, charmRune_t initcharmRune_t, std::string initdescription, charm_t inittype, uint16_t initpoints, int32_t initbinary) : - name(initname), id(initcharmRune_t), description(initdescription), type(inittype), points(initpoints), binary(initbinary) {} - virtual ~Charm() = default; - - std::string name; - std::string cancelMsg; - std::string logMsg; - std::string description; - - charm_t type; - charmRune_t id = CHARM_NONE; - CombatType_t dmgtype = COMBAT_NONE; - uint8_t effect = CONST_ME_NONE; - - int8_t percent = 0; - int8_t chance = 0; - uint16_t points = 0; - int32_t binary = 0; - +class Charm { + public: + Charm() = default; + Charm(std::string initname, charmRune_t initcharmRune_t, std::string initdescription, charm_t inittype, uint16_t initpoints, int32_t initbinary) : + name(initname), id(initcharmRune_t), description(initdescription), type(inittype), points(initpoints), binary(initbinary) { } + virtual ~Charm() = default; + + std::string name; + std::string cancelMsg; + std::string logMsg; + std::string description; + + charm_t type; + charmRune_t id = CHARM_NONE; + CombatType_t dmgtype = COMBAT_NONE; + uint8_t effect = CONST_ME_NONE; + + int8_t percent = 0; + int8_t chance = 0; + uint16_t points = 0; + int32_t binary = 0; }; -class IOBestiary -{ +class IOBestiary { public: IOBestiary() = default; // non-copyable - IOBestiary(IOBestiary const&) = delete; - void operator=(IOBestiary const&) = delete; + IOBestiary(const IOBestiary &) = delete; + void operator=(const IOBestiary &) = delete; - static IOBestiary& getInstance() { + static IOBestiary &getInstance() { // Guaranteed to be destroyed static IOBestiary instance; // Instantiated on first use @@ -82,9 +79,8 @@ class IOBestiary std::map getBestiaryKillCountByMonsterIDs(Player* player, std::map mtype_list) const; std::map getMonsterElements(MonsterType* mtype) const; std::map findRaceByName(const std::string &race, bool Onlystring = true, BestiaryType_t raceNumber = BESTY_RACE_NONE) const; - }; constexpr auto g_iobestiary = &IOBestiary::getInstance; -#endif // SRC_IO_IOBESTIARY_H_ +#endif // SRC_IO_IOBESTIARY_H_ diff --git a/src/io/ioguild.cpp b/src/io/ioguild.cpp index 083b96ec686..68dfddb93f4 100644 --- a/src/io/ioguild.cpp +++ b/src/io/ioguild.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,14 +13,13 @@ #include "creatures/players/grouping/guild.h" #include "io/ioguild.h" -Guild* IOGuild::loadGuild(uint32_t guildId) -{ - Database& db = Database::getInstance(); +Guild* IOGuild::loadGuild(uint32_t guildId) { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `name`, `balance` FROM `guilds` WHERE `id` = " << guildId; if (DBResult_ptr result = db.storeQuery(query.str())) { Guild* guild = new Guild(guildId, result->getString("name")); - guild->setBankBalance(result->getNumber("balance")); + guild->setBankBalance(result->getNumber("balance")); query.str(std::string()); query << "SELECT `id`, `name`, `level` FROM `guild_ranks` WHERE `guild_id` = " << guildId; @@ -35,19 +34,18 @@ Guild* IOGuild::loadGuild(uint32_t guildId) } void IOGuild::saveGuild(Guild* guild) { - if (!guild) - return; - Database& db = Database::getInstance(); - std::ostringstream updateQuery; - updateQuery << "UPDATE `guilds` SET "; - updateQuery << "`balance` = " << guild->getBankBalance(); - updateQuery << " WHERE `id` = " << guild->getId(); - db.executeQuery(updateQuery.str()); + if (!guild) + return; + Database &db = Database::getInstance(); + std::ostringstream updateQuery; + updateQuery << "UPDATE `guilds` SET "; + updateQuery << "`balance` = " << guild->getBankBalance(); + updateQuery << " WHERE `id` = " << guild->getId(); + db.executeQuery(updateQuery.str()); } -uint32_t IOGuild::getGuildIdByName(const std::string& name) -{ - Database& db = Database::getInstance(); +uint32_t IOGuild::getGuildIdByName(const std::string &name) { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `id` FROM `guilds` WHERE `name` = " << db.escapeString(name); @@ -59,8 +57,7 @@ uint32_t IOGuild::getGuildIdByName(const std::string& name) return result->getNumber("id"); } -void IOGuild::getWarList(uint32_t guildId, GuildWarVector& guildWarVector) -{ +void IOGuild::getWarList(uint32_t guildId, GuildWarVector &guildWarVector) { std::ostringstream query; query << "SELECT `guild1`, `guild2` FROM `guild_wars` WHERE (`guild1` = " << guildId << " OR `guild2` = " << guildId << ") AND `ended` = 0 AND `status` = 1"; diff --git a/src/io/ioguild.h b/src/io/ioguild.h index bffc7ccae39..fc6f55a43d3 100644 --- a/src/io/ioguild.h +++ b/src/io/ioguild.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOGUILD_H_ #define SRC_IO_IOGUILD_H_ @@ -13,13 +13,12 @@ class Guild; using GuildWarVector = std::vector; -class IOGuild -{ +class IOGuild { public: static Guild* loadGuild(uint32_t guildId); - static void saveGuild(Guild* guild); - static uint32_t getGuildIdByName(const std::string& name); - static void getWarList(uint32_t guildId, GuildWarVector& guildWarVector); + static void saveGuild(Guild* guild); + static uint32_t getGuildIdByName(const std::string &name); + static void getWarList(uint32_t guildId, GuildWarVector &guildWarVector); }; -#endif // SRC_IO_IOGUILD_H_ +#endif // SRC_IO_IOGUILD_H_ diff --git a/src/io/iologindata.cpp b/src/io/iologindata.cpp index c90ea92e213..ec264050d21 100644 --- a/src/io/iologindata.cpp +++ b/src/io/iologindata.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,7 +16,7 @@ #include "creatures/monsters/monster.h" #include "io/ioprey.h" -bool IOLoginData::authenticateAccountPassword(const std::string& email, const std::string& password, account::Account *account) { +bool IOLoginData::authenticateAccountPassword(const std::string &email, const std::string &password, account::Account* account) { if (account::ERROR_NO != account->LoadAccountDB(email)) { SPDLOG_ERROR("Email {} doesn't match any account.", email); return false; @@ -25,15 +25,14 @@ bool IOLoginData::authenticateAccountPassword(const std::string& email, const st std::string accountPassword; account->GetPassword(&accountPassword); if (transformToSHA1(password) != accountPassword) { - SPDLOG_ERROR("Password '{}' doesn't match any account", transformToSHA1(password)); - return false; + SPDLOG_ERROR("Password '{}' doesn't match any account", transformToSHA1(password)); + return false; } return true; } -bool IOLoginData::gameWorldAuthentication(const std::string& email, const std::string& password, std::string& characterName, uint32_t *accountId) -{ +bool IOLoginData::gameWorldAuthentication(const std::string &email, const std::string &password, std::string &characterName, uint32_t* accountId) { account::Account account; if (!IOLoginData::authenticateAccountPassword(email, password, &account)) { return false; @@ -50,1409 +49,1381 @@ bool IOLoginData::gameWorldAuthentication(const std::string& email, const std::s return true; } -account::AccountType IOLoginData::getAccountType(uint32_t accountId) -{ - std::ostringstream query; - query << "SELECT `type` FROM `accounts` WHERE `id` = " << accountId; - DBResult_ptr result = Database::getInstance().storeQuery(query.str()); - if (!result) { - return account::ACCOUNT_TYPE_NORMAL; - } - return static_cast(result->getNumber("type")); +account::AccountType IOLoginData::getAccountType(uint32_t accountId) { + std::ostringstream query; + query << "SELECT `type` FROM `accounts` WHERE `id` = " << accountId; + DBResult_ptr result = Database::getInstance().storeQuery(query.str()); + if (!result) { + return account::ACCOUNT_TYPE_NORMAL; + } + return static_cast(result->getNumber("type")); } -void IOLoginData::setAccountType(uint32_t accountId, account::AccountType accountType) -{ - std::ostringstream query; - query << "UPDATE `accounts` SET `type` = " << static_cast(accountType) << " WHERE `id` = " << accountId; - Database::getInstance().executeQuery(query.str()); +void IOLoginData::setAccountType(uint32_t accountId, account::AccountType accountType) { + std::ostringstream query; + query << "UPDATE `accounts` SET `type` = " << static_cast(accountType) << " WHERE `id` = " << accountId; + Database::getInstance().executeQuery(query.str()); } -void IOLoginData::updateOnlineStatus(uint32_t guid, bool login) -{ - if (g_configManager().getBoolean(ALLOW_CLONES)) { - return; - } - - std::ostringstream query; - if (login) { - query << "INSERT INTO `players_online` VALUES (" << guid << ')'; - } else { - query << "DELETE FROM `players_online` WHERE `player_id` = " << guid; - } - Database::getInstance().executeQuery(query.str()); +void IOLoginData::updateOnlineStatus(uint32_t guid, bool login) { + if (g_configManager().getBoolean(ALLOW_CLONES)) { + return; + } + + std::ostringstream query; + if (login) { + query << "INSERT INTO `players_online` VALUES (" << guid << ')'; + } else { + query << "DELETE FROM `players_online` WHERE `player_id` = " << guid; + } + Database::getInstance().executeQuery(query.str()); } -bool IOLoginData::preloadPlayer(Player* player, const std::string& name) -{ - Database& db = Database::getInstance(); - - std::ostringstream query; - query << "SELECT `id`, `account_id`, `group_id`, `deletion`, (SELECT `type` FROM `accounts` WHERE `accounts`.`id` = `account_id`) AS `account_type`"; - if (!g_configManager().getBoolean(FREE_PREMIUM)) { - query << ", (SELECT `premdays` FROM `accounts` WHERE `accounts`.`id` = `account_id`) AS `premium_days`"; - } - query << " FROM `players` WHERE `name` = " << db.escapeString(name); - DBResult_ptr result = db.storeQuery(query.str()); - if (!result) { - return false; - } - - if (result->getNumber("deletion") != 0) { - return false; - } - - player->setGUID(result->getNumber("id")); - Group* group = g_game().groups.getGroup(result->getNumber("group_id")); - if (!group) { - SPDLOG_ERROR("Player {} has group id {} which doesn't exist", player->name, - result->getNumber("group_id")); - return false; - } - player->setGroup(group); - player->accountNumber = result->getNumber("account_id"); - player->accountType = static_cast(result->getNumber("account_type")); - if (!g_configManager().getBoolean(FREE_PREMIUM)) { - player->premiumDays = result->getNumber("premium_days"); - } else { - player->premiumDays = std::numeric_limits::max(); - } - return true; +bool IOLoginData::preloadPlayer(Player* player, const std::string &name) { + Database &db = Database::getInstance(); + + std::ostringstream query; + query << "SELECT `id`, `account_id`, `group_id`, `deletion`, (SELECT `type` FROM `accounts` WHERE `accounts`.`id` = `account_id`) AS `account_type`"; + if (!g_configManager().getBoolean(FREE_PREMIUM)) { + query << ", (SELECT `premdays` FROM `accounts` WHERE `accounts`.`id` = `account_id`) AS `premium_days`"; + } + query << " FROM `players` WHERE `name` = " << db.escapeString(name); + DBResult_ptr result = db.storeQuery(query.str()); + if (!result) { + return false; + } + + if (result->getNumber("deletion") != 0) { + return false; + } + + player->setGUID(result->getNumber("id")); + Group* group = g_game().groups.getGroup(result->getNumber("group_id")); + if (!group) { + SPDLOG_ERROR("Player {} has group id {} which doesn't exist", player->name, result->getNumber("group_id")); + return false; + } + player->setGroup(group); + player->accountNumber = result->getNumber("account_id"); + player->accountType = static_cast(result->getNumber("account_type")); + if (!g_configManager().getBoolean(FREE_PREMIUM)) { + player->premiumDays = result->getNumber("premium_days"); + } else { + player->premiumDays = std::numeric_limits::max(); + } + return true; } -bool IOLoginData::loadPlayerById(Player* player, uint32_t id) -{ - Database& db = Database::getInstance(); - std::ostringstream query; - query << "SELECT * FROM `players` WHERE `id` = " << id; - return loadPlayer(player, db.storeQuery(query.str())); +bool IOLoginData::loadPlayerById(Player* player, uint32_t id) { + Database &db = Database::getInstance(); + std::ostringstream query; + query << "SELECT * FROM `players` WHERE `id` = " << id; + return loadPlayer(player, db.storeQuery(query.str())); } -bool IOLoginData::loadPlayerByName(Player* player, const std::string& name) -{ - Database& db = Database::getInstance(); - std::ostringstream query; - query << "SELECT * FROM `players` WHERE `name` = " << db.escapeString(name); - return loadPlayer(player, db.storeQuery(query.str())); +bool IOLoginData::loadPlayerByName(Player* player, const std::string &name) { + Database &db = Database::getInstance(); + std::ostringstream query; + query << "SELECT * FROM `players` WHERE `name` = " << db.escapeString(name); + return loadPlayer(player, db.storeQuery(query.str())); } -bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) -{ - if (!result || !player) { - return false; - } - - Database& db = Database::getInstance(); - - uint32_t accountId = result->getNumber("account_id"); - account::Account acc; - acc.SetDatabaseInterface(&db); - acc.LoadAccountDB(accountId); - - player->setGUID(result->getNumber("id")); - player->name = result->getString("name"); - acc.GetID(&(player->accountNumber)); - acc.GetAccountType(&(player->accountType)); - - if (g_configManager().getBoolean(FREE_PREMIUM)) { - player->premiumDays = std::numeric_limits::max(); - } else { - acc.GetPremiumRemaningDays(&(player->premiumDays)); - } - - acc.GetCoins(&(player->coinBalance)); - - Group* group = g_game().groups.getGroup(result->getNumber("group_id")); - if (!group) { - SPDLOG_ERROR("Player {} has group id {} which doesn't exist", player->name, result->getNumber("group_id")); - return false; - } - player->setGroup(group); - - player->setBankBalance(result->getNumber("balance")); - - player->quickLootFallbackToMainContainer = result->getNumber("quickloot_fallback"); - - player->setSex(static_cast(result->getNumber("sex"))); - player->level = std::max(1, result->getNumber("level")); - - uint64_t experience = result->getNumber("experience"); - - uint64_t currExpCount = Player::getExpForLevel(player->level); - uint64_t nextExpCount = Player::getExpForLevel(player->level + 1); - if (experience < currExpCount || experience > nextExpCount) { - experience = currExpCount; - } - - player->experience = experience; - - if (currExpCount < nextExpCount) { - player->levelPercent = Player::getPercentLevel(player->experience - currExpCount, nextExpCount - currExpCount); - } else { - player->levelPercent = 0; - } - - player->soul = result->getNumber("soul"); - player->capacity = result->getNumber("cap") * 100; - for (int i = 1; i <= 8; i++) { - std::ostringstream ss; - ss << "blessings" << i; - player->addBlessing(i, result->getNumber(ss.str())); - } - - unsigned long attrSize; - const char* attr = result->getStream("conditions", attrSize); - PropStream propStream; - propStream.init(attr, attrSize); - - Condition* condition = Condition::createCondition(propStream); - while (condition) { - if (condition->unserialize(propStream)) { - player->storedConditionList.push_front(condition); - } else { - delete condition; - } - condition = Condition::createCondition(propStream); - } - - if (!player->setVocation(result->getNumber("vocation"))) { - SPDLOG_ERROR("Player {} has vocation id {} which doesn't exist", - player->name, result->getNumber("vocation")); - return false; - } - - player->mana = result->getNumber("mana"); - player->manaMax = result->getNumber("manamax"); - player->magLevel = result->getNumber("maglevel"); - - uint64_t nextManaCount = player->vocation->getReqMana(player->magLevel + 1); - uint64_t manaSpent = result->getNumber("manaspent"); - if (manaSpent > nextManaCount) { - manaSpent = 0; - } - - player->manaSpent = manaSpent; - player->magLevelPercent = Player::getPercentLevel(player->manaSpent, nextManaCount); - - player->health = result->getNumber("health"); - player->healthMax = result->getNumber("healthmax"); - - player->defaultOutfit.lookType = result->getNumber("looktype"); +bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) { + if (!result || !player) { + return false; + } + + Database &db = Database::getInstance(); + + uint32_t accountId = result->getNumber("account_id"); + account::Account acc; + acc.SetDatabaseInterface(&db); + acc.LoadAccountDB(accountId); + + player->setGUID(result->getNumber("id")); + player->name = result->getString("name"); + acc.GetID(&(player->accountNumber)); + acc.GetAccountType(&(player->accountType)); + + if (g_configManager().getBoolean(FREE_PREMIUM)) { + player->premiumDays = std::numeric_limits::max(); + } else { + acc.GetPremiumRemaningDays(&(player->premiumDays)); + } + + acc.GetCoins(&(player->coinBalance)); + + Group* group = g_game().groups.getGroup(result->getNumber("group_id")); + if (!group) { + SPDLOG_ERROR("Player {} has group id {} which doesn't exist", player->name, result->getNumber("group_id")); + return false; + } + player->setGroup(group); + + player->setBankBalance(result->getNumber("balance")); + + player->quickLootFallbackToMainContainer = result->getNumber("quickloot_fallback"); + + player->setSex(static_cast(result->getNumber("sex"))); + player->level = std::max(1, result->getNumber("level")); + + uint64_t experience = result->getNumber("experience"); + + uint64_t currExpCount = Player::getExpForLevel(player->level); + uint64_t nextExpCount = Player::getExpForLevel(player->level + 1); + if (experience < currExpCount || experience > nextExpCount) { + experience = currExpCount; + } + + player->experience = experience; + + if (currExpCount < nextExpCount) { + player->levelPercent = Player::getPercentLevel(player->experience - currExpCount, nextExpCount - currExpCount); + } else { + player->levelPercent = 0; + } + + player->soul = result->getNumber("soul"); + player->capacity = result->getNumber("cap") * 100; + for (int i = 1; i <= 8; i++) { + std::ostringstream ss; + ss << "blessings" << i; + player->addBlessing(i, result->getNumber(ss.str())); + } + + unsigned long attrSize; + const char* attr = result->getStream("conditions", attrSize); + PropStream propStream; + propStream.init(attr, attrSize); + + Condition* condition = Condition::createCondition(propStream); + while (condition) { + if (condition->unserialize(propStream)) { + player->storedConditionList.push_front(condition); + } else { + delete condition; + } + condition = Condition::createCondition(propStream); + } + + if (!player->setVocation(result->getNumber("vocation"))) { + SPDLOG_ERROR("Player {} has vocation id {} which doesn't exist", player->name, result->getNumber("vocation")); + return false; + } + + player->mana = result->getNumber("mana"); + player->manaMax = result->getNumber("manamax"); + player->magLevel = result->getNumber("maglevel"); + + uint64_t nextManaCount = player->vocation->getReqMana(player->magLevel + 1); + uint64_t manaSpent = result->getNumber("manaspent"); + if (manaSpent > nextManaCount) { + manaSpent = 0; + } + + player->manaSpent = manaSpent; + player->magLevelPercent = Player::getPercentLevel(player->manaSpent, nextManaCount); + + player->health = result->getNumber("health"); + player->healthMax = result->getNumber("healthmax"); + + player->defaultOutfit.lookType = result->getNumber("looktype"); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && player->defaultOutfit.lookType != 0 && !g_game().isLookTypeRegistered(player->defaultOutfit.lookType)) { SPDLOG_WARN("[IOLoginData::loadPlayer] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", player->defaultOutfit.lookType); return false; } - player->defaultOutfit.lookHead = result->getNumber("lookhead"); - player->defaultOutfit.lookBody = result->getNumber("lookbody"); - player->defaultOutfit.lookLegs = result->getNumber("looklegs"); - player->defaultOutfit.lookFeet = result->getNumber("lookfeet"); - player->defaultOutfit.lookAddons = result->getNumber("lookaddons"); - player->defaultOutfit.lookMountHead = result->getNumber("lookmounthead"); - player->defaultOutfit.lookMountBody = result->getNumber("lookmountbody"); - player->defaultOutfit.lookMountLegs = result->getNumber("lookmountlegs"); - player->defaultOutfit.lookMountFeet = result->getNumber("lookmountfeet"); - player->defaultOutfit.lookFamiliarsType = result->getNumber("lookfamiliarstype"); + player->defaultOutfit.lookHead = result->getNumber("lookhead"); + player->defaultOutfit.lookBody = result->getNumber("lookbody"); + player->defaultOutfit.lookLegs = result->getNumber("looklegs"); + player->defaultOutfit.lookFeet = result->getNumber("lookfeet"); + player->defaultOutfit.lookAddons = result->getNumber("lookaddons"); + player->defaultOutfit.lookMountHead = result->getNumber("lookmounthead"); + player->defaultOutfit.lookMountBody = result->getNumber("lookmountbody"); + player->defaultOutfit.lookMountLegs = result->getNumber("lookmountlegs"); + player->defaultOutfit.lookMountFeet = result->getNumber("lookmountfeet"); + player->defaultOutfit.lookFamiliarsType = result->getNumber("lookfamiliarstype"); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && player->defaultOutfit.lookFamiliarsType != 0 && !g_game().isLookTypeRegistered(player->defaultOutfit.lookFamiliarsType)) { SPDLOG_WARN("[IOLoginData::loadPlayer] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", player->defaultOutfit.lookFamiliarsType); return false; } - player->isDailyReward = result->getNumber("isreward"); - player->currentOutfit = player->defaultOutfit; - - if (g_game().getWorldType() != WORLD_TYPE_PVP_ENFORCED) { - const time_t skullSeconds = result->getNumber("skulltime") - time(nullptr); - if (skullSeconds > 0) { - //ensure that we round up the number of ticks - player->skullTicks = (skullSeconds + 2); - - uint16_t skull = result->getNumber("skull"); - if (skull == SKULL_RED) { - player->skull = SKULL_RED; - } else if (skull == SKULL_BLACK) { - player->skull = SKULL_BLACK; - } - } - } - - player->loginPosition.x = result->getNumber("posx"); - player->loginPosition.y = result->getNumber("posy"); - player->loginPosition.z = result->getNumber("posz"); - - player->addPreyCards(result->getNumber("prey_wildcard")); - player->addTaskHuntingPoints(result->getNumber("task_points")); - player->addForgeDusts(result->getNumber("forge_dusts")); - player->addForgeDustLevel(result->getNumber("forge_dust_level")); - player->setRandomMount(result->getNumber("randomize_mount")); - - player->lastLoginSaved = result->getNumber("lastlogin"); - player->lastLogout = result->getNumber("lastlogout"); - - player->offlineTrainingTime = result->getNumber("offlinetraining_time") * 1000; + player->isDailyReward = result->getNumber("isreward"); + player->currentOutfit = player->defaultOutfit; + + if (g_game().getWorldType() != WORLD_TYPE_PVP_ENFORCED) { + const time_t skullSeconds = result->getNumber("skulltime") - time(nullptr); + if (skullSeconds > 0) { + // ensure that we round up the number of ticks + player->skullTicks = (skullSeconds + 2); + + uint16_t skull = result->getNumber("skull"); + if (skull == SKULL_RED) { + player->skull = SKULL_RED; + } else if (skull == SKULL_BLACK) { + player->skull = SKULL_BLACK; + } + } + } + + player->loginPosition.x = result->getNumber("posx"); + player->loginPosition.y = result->getNumber("posy"); + player->loginPosition.z = result->getNumber("posz"); + + player->addPreyCards(result->getNumber("prey_wildcard")); + player->addTaskHuntingPoints(result->getNumber("task_points")); + player->addForgeDusts(result->getNumber("forge_dusts")); + player->addForgeDustLevel(result->getNumber("forge_dust_level")); + player->setRandomMount(result->getNumber("randomize_mount")); + + player->lastLoginSaved = result->getNumber("lastlogin"); + player->lastLogout = result->getNumber("lastlogout"); + + player->offlineTrainingTime = result->getNumber("offlinetraining_time") * 1000; auto skill = result->getInt8FromString(result->getString("offlinetraining_skill"), __FUNCTION__); - player->setOfflineTrainingSkill(skill); - - Town* town = g_game().map.towns.getTown(result->getNumber("town_id")); - if (!town) { - SPDLOG_ERROR("Player {} has town id {} which doesn't exist", player->name, - result->getNumber("town_id")); - return false; - } - - player->town = town; - - const Position& loginPos = player->loginPosition; - if (loginPos.x == 0 && loginPos.y == 0 && loginPos.z == 0) { - player->loginPosition = player->getTemplePosition(); - } - - player->staminaMinutes = result->getNumber("stamina"); - player->setStoreXpBoost(result->getNumber("xpboost_value")); - player->setExpBoostStamina(result->getNumber("xpboost_stamina")); - - static const std::string skillNames[] = {"skill_fist", "skill_club", "skill_sword", "skill_axe", "skill_dist", "skill_shielding", "skill_fishing", "skill_critical_hit_chance", "skill_critical_hit_damage", "skill_life_leech_chance", "skill_life_leech_amount", "skill_mana_leech_chance", "skill_mana_leech_amount"}; - static const std::string skillNameTries[] = {"skill_fist_tries", "skill_club_tries", "skill_sword_tries", "skill_axe_tries", "skill_dist_tries", "skill_shielding_tries", "skill_fishing_tries", "skill_critical_hit_chance_tries", "skill_critical_hit_damage_tries", "skill_life_leech_chance_tries", "skill_life_leech_amount_tries", "skill_mana_leech_chance_tries", "skill_mana_leech_amount_tries"}; - static constexpr size_t size = sizeof(skillNames) / sizeof(std::string); - for (uint8_t i = 0; i < size; ++i) { - uint16_t skillLevel = result->getNumber(skillNames[i]); - uint64_t skillTries = result->getNumber(skillNameTries[i]); - uint64_t nextSkillTries = player->vocation->getReqSkillTries(i, skillLevel + 1); - if (skillTries > nextSkillTries) { - skillTries = 0; - } - - player->skills[i].level = skillLevel; - player->skills[i].tries = skillTries; - player->skills[i].percent = Player::getPercentLevel(skillTries, nextSkillTries); - } - - player->setManaShield(result->getNumber("manashield")); - player->setMaxManaShield(result->getNumber("max_manashield")); - - std::ostringstream query; - query << "SELECT `guild_id`, `rank_id`, `nick` FROM `guild_membership` WHERE `player_id` = " << player->getGUID(); - if ((result = db.storeQuery(query.str()))) { - uint32_t guildId = result->getNumber("guild_id"); - uint32_t playerRankId = result->getNumber("rank_id"); - player->guildNick = result->getString("nick"); - - Guild* guild = g_game().getGuild(guildId); - if (!guild) { - guild = IOGuild::loadGuild(guildId); - g_game().addGuild(guild); - } - - if (guild) { - player->guild = guild; - GuildRank_ptr rank = guild->getRankById(playerRankId); - if (!rank) { - query.str(std::string()); - query << "SELECT `id`, `name`, `level` FROM `guild_ranks` WHERE `id` = " << playerRankId; - - if ((result = db.storeQuery(query.str()))) { - guild->addRank(result->getNumber("id"), result->getString("name"), result->getNumber("level")); - } - - rank = guild->getRankById(playerRankId); - if (!rank) { - player->guild = nullptr; - } - } - - player->guildRank = rank; - - IOGuild::getWarList(guildId, player->guildWarVector); - - query.str(std::string()); - query << "SELECT COUNT(*) AS `members` FROM `guild_membership` WHERE `guild_id` = " << guildId; - if ((result = db.storeQuery(query.str()))) { - guild->setMemberCount(result->getNumber("members")); - } - } - } - - // Stash load items - query.str(std::string()); - query << "SELECT `item_count`, `item_id` FROM `player_stash` WHERE `player_id` = " << player->getGUID(); - if ((result = db.storeQuery(query.str()))) { - do { - player->addItemOnStash(result->getNumber("item_id"), result->getNumber("item_count")); - } while (result->next()); - } - - // Bestiary charms - query.str(std::string()); - query << "SELECT * FROM `player_charms` WHERE `player_guid` = " << player->getGUID(); - if ((result = db.storeQuery(query.str()))) { - player->charmPoints = result->getNumber("charm_points"); - player->charmExpansion = result->getNumber("charm_expansion"); - player->charmRuneWound = result->getNumber("rune_wound"); - player->charmRuneEnflame = result->getNumber("rune_enflame"); - player->charmRunePoison = result->getNumber("rune_poison"); - player->charmRuneFreeze = result->getNumber("rune_freeze"); - player->charmRuneZap = result->getNumber("rune_zap"); - player->charmRuneCurse = result->getNumber("rune_curse"); - player->charmRuneCripple = result->getNumber("rune_cripple"); - player->charmRuneParry = result->getNumber("rune_parry"); - player->charmRuneDodge = result->getNumber("rune_dodge"); - player->charmRuneAdrenaline = result->getNumber("rune_adrenaline"); - player->charmRuneNumb = result->getNumber("rune_numb"); - player->charmRuneCleanse = result->getNumber("rune_cleanse"); - player->charmRuneBless = result->getNumber("rune_bless"); - player->charmRuneScavenge = result->getNumber("rune_scavenge"); - player->charmRuneGut = result->getNumber("rune_gut"); - player->charmRuneLowBlow = result->getNumber("rune_low_blow"); - player->charmRuneDivine = result->getNumber("rune_divine"); - player->charmRuneVamp = result->getNumber("rune_vamp"); - player->charmRuneVoid = result->getNumber("rune_void"); - player->UsedRunesBit = result->getNumber("UsedRunesBit"); - player->UnlockedRunesBit = result->getNumber("UnlockedRunesBit"); - - unsigned long attrBestSize; - const char* Bestattr = result->getStream("tracker list", attrBestSize); - PropStream propBestStream; - propBestStream.init(Bestattr, attrBestSize); - - uint16_t raceid_t; - while (propBestStream.read(raceid_t)) { - MonsterType* tmp_tt = g_monsters().getMonsterTypeByRaceId(raceid_t); - if (tmp_tt) { - player->addBestiaryTrackerList(tmp_tt); - } - } - - - } else { + player->setOfflineTrainingSkill(skill); + + Town* town = g_game().map.towns.getTown(result->getNumber("town_id")); + if (!town) { + SPDLOG_ERROR("Player {} has town id {} which doesn't exist", player->name, result->getNumber("town_id")); + return false; + } + + player->town = town; + + const Position &loginPos = player->loginPosition; + if (loginPos.x == 0 && loginPos.y == 0 && loginPos.z == 0) { + player->loginPosition = player->getTemplePosition(); + } + + player->staminaMinutes = result->getNumber("stamina"); + player->setStoreXpBoost(result->getNumber("xpboost_value")); + player->setExpBoostStamina(result->getNumber("xpboost_stamina")); + + static const std::string skillNames[] = { "skill_fist", "skill_club", "skill_sword", "skill_axe", "skill_dist", "skill_shielding", "skill_fishing", "skill_critical_hit_chance", "skill_critical_hit_damage", "skill_life_leech_chance", "skill_life_leech_amount", "skill_mana_leech_chance", "skill_mana_leech_amount" }; + static const std::string skillNameTries[] = { "skill_fist_tries", "skill_club_tries", "skill_sword_tries", "skill_axe_tries", "skill_dist_tries", "skill_shielding_tries", "skill_fishing_tries", "skill_critical_hit_chance_tries", "skill_critical_hit_damage_tries", "skill_life_leech_chance_tries", "skill_life_leech_amount_tries", "skill_mana_leech_chance_tries", "skill_mana_leech_amount_tries" }; + static constexpr size_t size = sizeof(skillNames) / sizeof(std::string); + for (uint8_t i = 0; i < size; ++i) { + uint16_t skillLevel = result->getNumber(skillNames[i]); + uint64_t skillTries = result->getNumber(skillNameTries[i]); + uint64_t nextSkillTries = player->vocation->getReqSkillTries(i, skillLevel + 1); + if (skillTries > nextSkillTries) { + skillTries = 0; + } + + player->skills[i].level = skillLevel; + player->skills[i].tries = skillTries; + player->skills[i].percent = Player::getPercentLevel(skillTries, nextSkillTries); + } + + player->setManaShield(result->getNumber("manashield")); + player->setMaxManaShield(result->getNumber("max_manashield")); + + std::ostringstream query; + query << "SELECT `guild_id`, `rank_id`, `nick` FROM `guild_membership` WHERE `player_id` = " << player->getGUID(); + if ((result = db.storeQuery(query.str()))) { + uint32_t guildId = result->getNumber("guild_id"); + uint32_t playerRankId = result->getNumber("rank_id"); + player->guildNick = result->getString("nick"); + + Guild* guild = g_game().getGuild(guildId); + if (!guild) { + guild = IOGuild::loadGuild(guildId); + g_game().addGuild(guild); + } + + if (guild) { + player->guild = guild; + GuildRank_ptr rank = guild->getRankById(playerRankId); + if (!rank) { + query.str(std::string()); + query << "SELECT `id`, `name`, `level` FROM `guild_ranks` WHERE `id` = " << playerRankId; + + if ((result = db.storeQuery(query.str()))) { + guild->addRank(result->getNumber("id"), result->getString("name"), result->getNumber("level")); + } + + rank = guild->getRankById(playerRankId); + if (!rank) { + player->guild = nullptr; + } + } + + player->guildRank = rank; + + IOGuild::getWarList(guildId, player->guildWarVector); + + query.str(std::string()); + query << "SELECT COUNT(*) AS `members` FROM `guild_membership` WHERE `guild_id` = " << guildId; + if ((result = db.storeQuery(query.str()))) { + guild->setMemberCount(result->getNumber("members")); + } + } + } + + // Stash load items query.str(std::string()); - query << "INSERT INTO `player_charms` (`player_guid`) VALUES (" << player->getGUID() << ')'; - Database::getInstance().executeQuery(query.str()); - } - - query.str(std::string()); - query << "SELECT `player_id`, `name` FROM `player_spells` WHERE `player_id` = " << player->getGUID(); - if ((result = db.storeQuery(query.str()))) { - do { - player->learnedInstantSpellList.emplace_front(result->getString("name")); - } while (result->next()); - } - - //load inventory items - ItemMap itemMap; - - query.str(std::string()); - query << "SELECT `player_id`, `time`, `target`, `unavenged` FROM `player_kills` WHERE `player_id` = " << player->getGUID(); - if ((result = db.storeQuery(query.str()))) { - do { - time_t killTime = result->getNumber("time"); - if ((time(nullptr) - killTime) <= g_configManager().getNumber(FRAG_TIME)) { - player->unjustifiedKills.emplace_back(result->getNumber("target"), killTime, result->getNumber("unavenged")); - } - } while (result->next()); - } - - query.str(std::string()); - query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_items` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; - - std::vector> openContainersList; - - if ((result = db.storeQuery(query.str()))) { - loadItems(itemMap, result, *player); - - for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { - const std::pair& pair = it->second; - Item* item = pair.first; - if (!item) { - continue; - } - - int32_t pid = pair.second; - - if (pid >= CONST_SLOT_FIRST && pid <= CONST_SLOT_LAST) { - player->internalAddThing(pid, item); - item->startDecaying(); - } else { - ItemMap::const_iterator it2 = itemMap.find(pid); - if (it2 == itemMap.end()) { - continue; - } - - Container* container = it2->second.first->getContainer(); - if (container) { - container->internalAddThing(item); - item->startDecaying(); - } - } - - Container* itemContainer = item->getContainer(); - if (itemContainer) { - auto cid = item->getAttribute(ItemAttribute_t::OPENCONTAINER); - if (cid > 0) { - openContainersList.emplace_back(std::make_pair(cid, itemContainer)); - } - if (item->hasAttribute(ItemAttribute_t::QUICKLOOTCONTAINER)) { - auto flags = item->getAttribute(ItemAttribute_t::QUICKLOOTCONTAINER); - for (uint8_t category = OBJECTCATEGORY_FIRST; category <= OBJECTCATEGORY_LAST; category++) { - if (hasBitSet(1 << category, flags)) { - player->setLootContainer((ObjectCategory_t)category, itemContainer, true); - } - } - } - } - } - } - - std::sort(openContainersList.begin(), openContainersList.end(), [](const std::pair &left, const std::pair &right) { - return left.first < right.first; - }); - - for (auto& it : openContainersList) { - player->addContainer(it.first - 1, it.second); - player->onSendContainer(it.second); - } - - // Store Inbox - if (!player->inventory[CONST_SLOT_STORE_INBOX]) { - player->internalAddThing(CONST_SLOT_STORE_INBOX, Item::CreateItem(ITEM_STORE_INBOX)); - } - - //load depot items - itemMap.clear(); - - query.str(std::string()); - query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_depotitems` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; - if ((result = db.storeQuery(query.str()))) { - loadItems(itemMap, result, *player); - - for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { - const std::pair& pair = it->second; - Item* item = pair.first; - - int32_t pid = pair.second; - if (pid >= 0 && pid < 100) { - DepotChest* depotChest = player->getDepotChest(pid, true); - if (depotChest) { - depotChest->internalAddThing(item); - item->startDecaying(); - } - } else { - ItemMap::const_iterator it2 = itemMap.find(pid); - if (it2 == itemMap.end()) { - continue; - } - - Container* container = it2->second.first->getContainer(); - if (container) { - container->internalAddThing(item); - item->startDecaying(); - } - } - } - } - - //load reward chest items - itemMap.clear(); - - query.str(std::string()); - query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_rewards` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; - if ((result = db.storeQuery(query.str()))) { - loadItems(itemMap, result, *player); - - //first loop handles the reward containers to retrieve its date attribute - //for (ItemMap::iterator it = itemMap.begin(), end = itemMap.end(); it != end; ++it) { - for (auto& it : itemMap) { - const std::pair& pair = it.second; - Item* item = pair.first; - - int32_t pid = pair.second; - if (pid >= 0 && pid < 100) { - auto rewardId = item->getAttribute(ItemAttribute_t::DATE); - Reward* reward = player->getReward(rewardId, true); - if (reward) { - it.second = std::pair(reward->getItem(), pid); //update the map with the special reward container - } - } else { - break; - } - } - - //second loop (this time a reverse one) to insert the items in the correct order - //for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { - for (const auto& it : std::views::reverse(itemMap)) { - const std::pair& pair = it.second; - Item* item = pair.first; - - int32_t pid = pair.second; - if (pid >= 0 && pid < 100) { - break; - } - - ItemMap::const_iterator it2 = itemMap.find(pid); - if (it2 == itemMap.end()) { - continue; - } - - Container* container = it2->second.first->getContainer(); - if (container) { - container->internalAddThing(item); - } - } - } - - //load inbox items - itemMap.clear(); - - query.str(std::string()); - query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_inboxitems` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; - if ((result = db.storeQuery(query.str()))) { - loadItems(itemMap, result, *player); - - for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { - const std::pair& pair = it->second; - Item* item = pair.first; - int32_t pid = pair.second; - - if (pid >= 0 && pid < 100) { - player->getInbox()->internalAddThing(item); - item->startDecaying(); - } else { - ItemMap::const_iterator it2 = itemMap.find(pid); - - if (it2 == itemMap.end()) { - continue; - } - - Container* container = it2->second.first->getContainer(); - if (container) { - container->internalAddThing(item); - item->startDecaying(); - } - } - } - } - - //load storage map - query.str(std::string()); - query << "SELECT `key`, `value` FROM `player_storage` WHERE `player_id` = " << player->getGUID(); - if ((result = db.storeQuery(query.str()))) { - do { - player->addStorageValue(result->getNumber("key"), result->getNumber("value"), true); - } while (result->next()); - } - - //load vip - query.str(std::string()); - query << "SELECT `player_id` FROM `account_viplist` WHERE `account_id` = " << player->getAccount(); - if ((result = db.storeQuery(query.str()))) { - do { - player->addVIPInternal(result->getNumber("player_id")); - } while (result->next()); - } - - // Load prey class - if (g_configManager().getBoolean(PREY_ENABLED)) { - query.str(std::string()); - query << "SELECT * FROM `player_prey` WHERE `player_id` = " << player->getGUID(); - if (result = db.storeQuery(query.str())) { - do { - auto slot = new PreySlot(static_cast(result->getNumber("slot"))); - PreyDataState_t state = static_cast(result->getNumber("state")); - if (slot->id == PreySlot_Two && state == PreyDataState_Locked) { - if (!player->isPremium()) { - slot->state = PreyDataState_Locked; - } else { - slot->state = PreyDataState_Selection; - } - } else { - slot->state = state; - } - slot->selectedRaceId = result->getNumber("raceid"); - slot->option = static_cast(result->getNumber("option")); - slot->bonus = static_cast(result->getNumber("bonus_type")); - slot->bonusRarity = static_cast(result->getNumber("bonus_rarity")); - slot->bonusPercentage = result->getNumber("bonus_percentage"); - slot->bonusTimeLeft = result->getNumber("bonus_time"); - slot->freeRerollTimeStamp = result->getNumber("free_reroll"); - - unsigned long preySize; - const char* preyStream = result->getStream("monster_list", preySize); - PropStream propPreyStream; - propPreyStream.init(preyStream, preySize); - - uint16_t raceId; - while (propPreyStream.read(raceId)) { - slot->raceIdList.push_back(raceId); - } - - player->setPreySlotClass(slot); - } while (result->next()); - } - } - - IOLoginDataLoad::loadPlayerForgeHistory(player, result); - - // Load task hunting class - if (g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { - query.str(std::string()); - query << "SELECT * FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID(); - if (result = db.storeQuery(query.str())) { - do { - auto slot = new TaskHuntingSlot(static_cast(result->getNumber("slot"))); - PreyTaskDataState_t state = static_cast(result->getNumber("state")); - if (slot->id == PreySlot_Two && state == PreyTaskDataState_Locked) { - if (!player->isPremium()) { - slot->state = PreyTaskDataState_Locked; - } else { - slot->state = PreyTaskDataState_Selection; - } - } else { - slot->state = state; - } - slot->selectedRaceId = result->getNumber("raceid"); - slot->upgrade = result->getNumber("upgrade"); - slot->rarity = static_cast(result->getNumber("rarity")); - slot->currentKills = result->getNumber("kills"); - slot->disabledUntilTimeStamp = result->getNumber("disabled_time"); - slot->freeRerollTimeStamp = result->getNumber("free_reroll"); - - unsigned long taskHuntSize; - const char* taskHuntStream = result->getStream("monster_list", taskHuntSize); - PropStream propTaskHuntStream; - propTaskHuntStream.init(taskHuntStream, taskHuntSize); - - uint16_t raceId; - while (propTaskHuntStream.read(raceId)) { - slot->raceIdList.push_back(raceId); - } - - if (slot->state == PreyTaskDataState_Inactive && slot->disabledUntilTimeStamp < OTSYS_TIME()) { - slot->state = PreyTaskDataState_Selection; - } - - player->setTaskHuntingSlotClass(slot); - } while (result->next()); - } - } - - player->initializePrey(); + query << "SELECT `item_count`, `item_id` FROM `player_stash` WHERE `player_id` = " << player->getGUID(); + if ((result = db.storeQuery(query.str()))) { + do { + player->addItemOnStash(result->getNumber("item_id"), result->getNumber("item_count")); + } while (result->next()); + } + + // Bestiary charms + query.str(std::string()); + query << "SELECT * FROM `player_charms` WHERE `player_guid` = " << player->getGUID(); + if ((result = db.storeQuery(query.str()))) { + player->charmPoints = result->getNumber("charm_points"); + player->charmExpansion = result->getNumber("charm_expansion"); + player->charmRuneWound = result->getNumber("rune_wound"); + player->charmRuneEnflame = result->getNumber("rune_enflame"); + player->charmRunePoison = result->getNumber("rune_poison"); + player->charmRuneFreeze = result->getNumber("rune_freeze"); + player->charmRuneZap = result->getNumber("rune_zap"); + player->charmRuneCurse = result->getNumber("rune_curse"); + player->charmRuneCripple = result->getNumber("rune_cripple"); + player->charmRuneParry = result->getNumber("rune_parry"); + player->charmRuneDodge = result->getNumber("rune_dodge"); + player->charmRuneAdrenaline = result->getNumber("rune_adrenaline"); + player->charmRuneNumb = result->getNumber("rune_numb"); + player->charmRuneCleanse = result->getNumber("rune_cleanse"); + player->charmRuneBless = result->getNumber("rune_bless"); + player->charmRuneScavenge = result->getNumber("rune_scavenge"); + player->charmRuneGut = result->getNumber("rune_gut"); + player->charmRuneLowBlow = result->getNumber("rune_low_blow"); + player->charmRuneDivine = result->getNumber("rune_divine"); + player->charmRuneVamp = result->getNumber("rune_vamp"); + player->charmRuneVoid = result->getNumber("rune_void"); + player->UsedRunesBit = result->getNumber("UsedRunesBit"); + player->UnlockedRunesBit = result->getNumber("UnlockedRunesBit"); + + unsigned long attrBestSize; + const char* Bestattr = result->getStream("tracker list", attrBestSize); + PropStream propBestStream; + propBestStream.init(Bestattr, attrBestSize); + + uint16_t raceid_t; + while (propBestStream.read(raceid_t)) { + MonsterType* tmp_tt = g_monsters().getMonsterTypeByRaceId(raceid_t); + if (tmp_tt) { + player->addBestiaryTrackerList(tmp_tt); + } + } + + } else { + query.str(std::string()); + query << "INSERT INTO `player_charms` (`player_guid`) VALUES (" << player->getGUID() << ')'; + Database::getInstance().executeQuery(query.str()); + } + + query.str(std::string()); + query << "SELECT `player_id`, `name` FROM `player_spells` WHERE `player_id` = " << player->getGUID(); + if ((result = db.storeQuery(query.str()))) { + do { + player->learnedInstantSpellList.emplace_front(result->getString("name")); + } while (result->next()); + } + + // load inventory items + ItemMap itemMap; + + query.str(std::string()); + query << "SELECT `player_id`, `time`, `target`, `unavenged` FROM `player_kills` WHERE `player_id` = " << player->getGUID(); + if ((result = db.storeQuery(query.str()))) { + do { + time_t killTime = result->getNumber("time"); + if ((time(nullptr) - killTime) <= g_configManager().getNumber(FRAG_TIME)) { + player->unjustifiedKills.emplace_back(result->getNumber("target"), killTime, result->getNumber("unavenged")); + } + } while (result->next()); + } + + query.str(std::string()); + query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_items` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; + + std::vector> openContainersList; + + if ((result = db.storeQuery(query.str()))) { + loadItems(itemMap, result, *player); + + for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { + const std::pair &pair = it->second; + Item* item = pair.first; + if (!item) { + continue; + } + + int32_t pid = pair.second; + + if (pid >= CONST_SLOT_FIRST && pid <= CONST_SLOT_LAST) { + player->internalAddThing(pid, item); + item->startDecaying(); + } else { + ItemMap::const_iterator it2 = itemMap.find(pid); + if (it2 == itemMap.end()) { + continue; + } + + Container* container = it2->second.first->getContainer(); + if (container) { + container->internalAddThing(item); + item->startDecaying(); + } + } + + Container* itemContainer = item->getContainer(); + if (itemContainer) { + auto cid = item->getAttribute(ItemAttribute_t::OPENCONTAINER); + if (cid > 0) { + openContainersList.emplace_back(std::make_pair(cid, itemContainer)); + } + if (item->hasAttribute(ItemAttribute_t::QUICKLOOTCONTAINER)) { + auto flags = item->getAttribute(ItemAttribute_t::QUICKLOOTCONTAINER); + for (uint8_t category = OBJECTCATEGORY_FIRST; category <= OBJECTCATEGORY_LAST; category++) { + if (hasBitSet(1 << category, flags)) { + player->setLootContainer((ObjectCategory_t)category, itemContainer, true); + } + } + } + } + } + } + + std::sort(openContainersList.begin(), openContainersList.end(), [](const std::pair &left, const std::pair &right) { + return left.first < right.first; + }); + + for (auto &it : openContainersList) { + player->addContainer(it.first - 1, it.second); + player->onSendContainer(it.second); + } + + // Store Inbox + if (!player->inventory[CONST_SLOT_STORE_INBOX]) { + player->internalAddThing(CONST_SLOT_STORE_INBOX, Item::CreateItem(ITEM_STORE_INBOX)); + } + + // load depot items + itemMap.clear(); + + query.str(std::string()); + query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_depotitems` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; + if ((result = db.storeQuery(query.str()))) { + loadItems(itemMap, result, *player); + + for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { + const std::pair &pair = it->second; + Item* item = pair.first; + + int32_t pid = pair.second; + if (pid >= 0 && pid < 100) { + DepotChest* depotChest = player->getDepotChest(pid, true); + if (depotChest) { + depotChest->internalAddThing(item); + item->startDecaying(); + } + } else { + ItemMap::const_iterator it2 = itemMap.find(pid); + if (it2 == itemMap.end()) { + continue; + } + + Container* container = it2->second.first->getContainer(); + if (container) { + container->internalAddThing(item); + item->startDecaying(); + } + } + } + } + + // load reward chest items + itemMap.clear(); + + query.str(std::string()); + query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_rewards` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; + if ((result = db.storeQuery(query.str()))) { + loadItems(itemMap, result, *player); + + // first loop handles the reward containers to retrieve its date attribute + // for (ItemMap::iterator it = itemMap.begin(), end = itemMap.end(); it != end; ++it) { + for (auto &it : itemMap) { + const std::pair &pair = it.second; + Item* item = pair.first; + + int32_t pid = pair.second; + if (pid >= 0 && pid < 100) { + auto rewardId = item->getAttribute(ItemAttribute_t::DATE); + Reward* reward = player->getReward(rewardId, true); + if (reward) { + it.second = std::pair(reward->getItem(), pid); // update the map with the special reward container + } + } else { + break; + } + } + + // second loop (this time a reverse one) to insert the items in the correct order + // for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { + for (const auto &it : std::views::reverse(itemMap)) { + const std::pair &pair = it.second; + Item* item = pair.first; + + int32_t pid = pair.second; + if (pid >= 0 && pid < 100) { + break; + } + + ItemMap::const_iterator it2 = itemMap.find(pid); + if (it2 == itemMap.end()) { + continue; + } + + Container* container = it2->second.first->getContainer(); + if (container) { + container->internalAddThing(item); + } + } + } + + // load inbox items + itemMap.clear(); + + query.str(std::string()); + query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_inboxitems` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; + if ((result = db.storeQuery(query.str()))) { + loadItems(itemMap, result, *player); + + for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { + const std::pair &pair = it->second; + Item* item = pair.first; + int32_t pid = pair.second; + + if (pid >= 0 && pid < 100) { + player->getInbox()->internalAddThing(item); + item->startDecaying(); + } else { + ItemMap::const_iterator it2 = itemMap.find(pid); + + if (it2 == itemMap.end()) { + continue; + } + + Container* container = it2->second.first->getContainer(); + if (container) { + container->internalAddThing(item); + item->startDecaying(); + } + } + } + } + + // load storage map + query.str(std::string()); + query << "SELECT `key`, `value` FROM `player_storage` WHERE `player_id` = " << player->getGUID(); + if ((result = db.storeQuery(query.str()))) { + do { + player->addStorageValue(result->getNumber("key"), result->getNumber("value"), true); + } while (result->next()); + } + + // load vip + query.str(std::string()); + query << "SELECT `player_id` FROM `account_viplist` WHERE `account_id` = " << player->getAccount(); + if ((result = db.storeQuery(query.str()))) { + do { + player->addVIPInternal(result->getNumber("player_id")); + } while (result->next()); + } + + // Load prey class + if (g_configManager().getBoolean(PREY_ENABLED)) { + query.str(std::string()); + query << "SELECT * FROM `player_prey` WHERE `player_id` = " << player->getGUID(); + if (result = db.storeQuery(query.str())) { + do { + auto slot = new PreySlot(static_cast(result->getNumber("slot"))); + PreyDataState_t state = static_cast(result->getNumber("state")); + if (slot->id == PreySlot_Two && state == PreyDataState_Locked) { + if (!player->isPremium()) { + slot->state = PreyDataState_Locked; + } else { + slot->state = PreyDataState_Selection; + } + } else { + slot->state = state; + } + slot->selectedRaceId = result->getNumber("raceid"); + slot->option = static_cast(result->getNumber("option")); + slot->bonus = static_cast(result->getNumber("bonus_type")); + slot->bonusRarity = static_cast(result->getNumber("bonus_rarity")); + slot->bonusPercentage = result->getNumber("bonus_percentage"); + slot->bonusTimeLeft = result->getNumber("bonus_time"); + slot->freeRerollTimeStamp = result->getNumber("free_reroll"); + + unsigned long preySize; + const char* preyStream = result->getStream("monster_list", preySize); + PropStream propPreyStream; + propPreyStream.init(preyStream, preySize); + + uint16_t raceId; + while (propPreyStream.read(raceId)) { + slot->raceIdList.push_back(raceId); + } + + player->setPreySlotClass(slot); + } while (result->next()); + } + } + + IOLoginDataLoad::loadPlayerForgeHistory(player, result); + + // Load task hunting class + if (g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + query.str(std::string()); + query << "SELECT * FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID(); + if (result = db.storeQuery(query.str())) { + do { + auto slot = new TaskHuntingSlot(static_cast(result->getNumber("slot"))); + PreyTaskDataState_t state = static_cast(result->getNumber("state")); + if (slot->id == PreySlot_Two && state == PreyTaskDataState_Locked) { + if (!player->isPremium()) { + slot->state = PreyTaskDataState_Locked; + } else { + slot->state = PreyTaskDataState_Selection; + } + } else { + slot->state = state; + } + slot->selectedRaceId = result->getNumber("raceid"); + slot->upgrade = result->getNumber("upgrade"); + slot->rarity = static_cast(result->getNumber("rarity")); + slot->currentKills = result->getNumber("kills"); + slot->disabledUntilTimeStamp = result->getNumber("disabled_time"); + slot->freeRerollTimeStamp = result->getNumber("free_reroll"); + + unsigned long taskHuntSize; + const char* taskHuntStream = result->getStream("monster_list", taskHuntSize); + PropStream propTaskHuntStream; + propTaskHuntStream.init(taskHuntStream, taskHuntSize); + + uint16_t raceId; + while (propTaskHuntStream.read(raceId)) { + slot->raceIdList.push_back(raceId); + } + + if (slot->state == PreyTaskDataState_Inactive && slot->disabledUntilTimeStamp < OTSYS_TIME()) { + slot->state = PreyTaskDataState_Selection; + } + + player->setTaskHuntingSlotClass(slot); + } while (result->next()); + } + } + + player->initializePrey(); player->initializeTaskHunting(); - player->updateBaseSpeed(); - player->updateInventoryWeight(); - player->updateItemsLight(true); - return true; + player->updateBaseSpeed(); + player->updateInventoryWeight(); + player->updateItemsLight(true); + return true; } -bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream) -{ - Database& db = Database::getInstance(); - - std::ostringstream ss; - - using ContainerBlock = std::pair; - std::list queue; - - int32_t runningId = 100; - - const auto& openContainers = player->getOpenContainers(); - for (const auto& it : itemList) { - int32_t pid = it.first; - Item* item = it.second; - ++runningId; - - if (Container* container = item->getContainer()) { - if (container->getAttribute(ItemAttribute_t::OPENCONTAINER) > 0) { - container->setAttribute(ItemAttribute_t::OPENCONTAINER, 0); - } - - if (!openContainers.empty()) { - for (const auto& its : openContainers) { - auto openContainer = its.second; - auto opcontainer = openContainer.container; - - if (opcontainer == container) { - container->setAttribute(ItemAttribute_t::OPENCONTAINER, ((int)its.first) + 1); - break; - } - } - } - - queue.emplace_back(container, runningId); - } - - propWriteStream.clear(); - item->serializeAttr(propWriteStream); - - size_t attributesSize; - const char* attributes = propWriteStream.getStream(attributesSize); - - ss << player->getGUID() << ',' << pid << ',' << runningId << ',' << item->getID() << ',' << item->getSubType() << ',' << db.escapeBlob(attributes, attributesSize); - if (!query_insert.addRow(ss)) { - return false; - } - - } - - while (!queue.empty()) { - const ContainerBlock& cb = queue.front(); - Container* container = cb.first; - int32_t parentId = cb.second; - queue.pop_front(); - - for (Item* item : container->getItemList()) { - ++runningId; - - Container* subContainer = item->getContainer(); - if (subContainer) { - queue.emplace_back(subContainer, runningId); - if (subContainer->getAttribute(ItemAttribute_t::OPENCONTAINER) > 0) { - subContainer->setAttribute(ItemAttribute_t::OPENCONTAINER, 0); - } - - if (!openContainers.empty()) { - for (const auto& it : openContainers) { - auto openContainer = it.second; - auto opcontainer = openContainer.container; - - if (opcontainer == subContainer) { - subContainer->setAttribute(ItemAttribute_t::OPENCONTAINER, (it.first) + 1); - break; - } - } - } - } - - propWriteStream.clear(); - item->serializeAttr(propWriteStream); - - size_t attributesSize; - const char* attributes = propWriteStream.getStream(attributesSize); - - ss << player->getGUID() << ',' << parentId << ',' << runningId << ',' << item->getID() << ',' << item->getSubType() << ',' << db.escapeBlob(attributes, attributesSize); - if (!query_insert.addRow(ss)) { - return false; - } - } - } - return query_insert.execute(); +bool IOLoginData::saveItems(const Player* player, const ItemBlockList &itemList, DBInsert &query_insert, PropWriteStream &propWriteStream) { + Database &db = Database::getInstance(); + + std::ostringstream ss; + + using ContainerBlock = std::pair; + std::list queue; + + int32_t runningId = 100; + + const auto &openContainers = player->getOpenContainers(); + for (const auto &it : itemList) { + int32_t pid = it.first; + Item* item = it.second; + ++runningId; + + if (Container* container = item->getContainer()) { + if (container->getAttribute(ItemAttribute_t::OPENCONTAINER) > 0) { + container->setAttribute(ItemAttribute_t::OPENCONTAINER, 0); + } + + if (!openContainers.empty()) { + for (const auto &its : openContainers) { + auto openContainer = its.second; + auto opcontainer = openContainer.container; + + if (opcontainer == container) { + container->setAttribute(ItemAttribute_t::OPENCONTAINER, ((int)its.first) + 1); + break; + } + } + } + + queue.emplace_back(container, runningId); + } + + propWriteStream.clear(); + item->serializeAttr(propWriteStream); + + size_t attributesSize; + const char* attributes = propWriteStream.getStream(attributesSize); + + ss << player->getGUID() << ',' << pid << ',' << runningId << ',' << item->getID() << ',' << item->getSubType() << ',' << db.escapeBlob(attributes, attributesSize); + if (!query_insert.addRow(ss)) { + return false; + } + } + + while (!queue.empty()) { + const ContainerBlock &cb = queue.front(); + Container* container = cb.first; + int32_t parentId = cb.second; + queue.pop_front(); + + for (Item* item : container->getItemList()) { + ++runningId; + + Container* subContainer = item->getContainer(); + if (subContainer) { + queue.emplace_back(subContainer, runningId); + if (subContainer->getAttribute(ItemAttribute_t::OPENCONTAINER) > 0) { + subContainer->setAttribute(ItemAttribute_t::OPENCONTAINER, 0); + } + + if (!openContainers.empty()) { + for (const auto &it : openContainers) { + auto openContainer = it.second; + auto opcontainer = openContainer.container; + + if (opcontainer == subContainer) { + subContainer->setAttribute(ItemAttribute_t::OPENCONTAINER, (it.first) + 1); + break; + } + } + } + } + + propWriteStream.clear(); + item->serializeAttr(propWriteStream); + + size_t attributesSize; + const char* attributes = propWriteStream.getStream(attributesSize); + + ss << player->getGUID() << ',' << parentId << ',' << runningId << ',' << item->getID() << ',' << item->getSubType() << ',' << db.escapeBlob(attributes, attributesSize); + if (!query_insert.addRow(ss)) { + return false; + } + } + } + return query_insert.execute(); } -bool IOLoginData::savePlayer(Player* player) -{ - if (player->getHealth() <= 0) { - player->changeHealth(1); - } - Database& db = Database::getInstance(); - - std::ostringstream query; - query << "SELECT `save` FROM `players` WHERE `id` = " << player->getGUID(); - DBResult_ptr result = db.storeQuery(query.str()); - if (!result) { - SPDLOG_WARN("[IOLoginData::savePlayer] - Error for select result query from player: {}", player->getName()); - return false; - } - - if (result->getNumber("save") == 0) { - query.str(std::string()); - query << "UPDATE `players` SET `lastlogin` = " << player->lastLoginSaved << ", `lastip` = " << player->lastIP << " WHERE `id` = " << player->getGUID(); - return db.executeQuery(query.str()); - } - - //First, an UPDATE query to write the player itself - query.str(std::string()); - query << "UPDATE `players` SET "; - query << "`level` = " << player->level << ','; - query << "`group_id` = " << player->group->id << ','; - query << "`vocation` = " << player->getVocationId() << ','; - query << "`health` = " << player->health << ','; - query << "`healthmax` = " << player->healthMax << ','; - query << "`experience` = " << player->experience << ','; - query << "`lookbody` = " << static_cast(player->defaultOutfit.lookBody) << ','; - query << "`lookfeet` = " << static_cast(player->defaultOutfit.lookFeet) << ','; - query << "`lookhead` = " << static_cast(player->defaultOutfit.lookHead) << ','; - query << "`looklegs` = " << static_cast(player->defaultOutfit.lookLegs) << ','; - query << "`looktype` = " << player->defaultOutfit.lookType << ','; - query << "`lookaddons` = " << static_cast(player->defaultOutfit.lookAddons) << ','; - query << "`lookmountbody` = " << static_cast(player->defaultOutfit.lookMountBody) << ','; - query << "`lookmountfeet` = " << static_cast(player->defaultOutfit.lookMountFeet) << ','; - query << "`lookmounthead` = " << static_cast(player->defaultOutfit.lookMountHead) << ','; - query << "`lookmountlegs` = " << static_cast(player->defaultOutfit.lookMountLegs) << ','; - query << "`lookfamiliarstype` = " << player->defaultOutfit.lookFamiliarsType << ','; - query << "`isreward` = " << static_cast(player->isDailyReward) << ','; - query << "`maglevel` = " << player->magLevel << ','; - query << "`mana` = " << player->mana << ','; - query << "`manamax` = " << player->manaMax << ','; - query << "`manaspent` = " << player->manaSpent << ','; - query << "`soul` = " << static_cast(player->soul) << ','; - query << "`town_id` = " << player->town->getID() << ','; - - const Position& loginPosition = player->getLoginPosition(); - query << "`posx` = " << loginPosition.getX() << ','; - query << "`posy` = " << loginPosition.getY() << ','; - query << "`posz` = " << loginPosition.getZ() << ','; - - query << "`prey_wildcard` = " << player->getPreyCards() << ','; - query << "`task_points` = " << player->getTaskHuntingPoints() << ','; - query << "`forge_dusts` = " << player->getForgeDusts() << ','; - query << "`forge_dust_level` = " << player->getForgeDustLevel() << ','; - query << "`randomize_mount` = " << static_cast(player->isRandomMounted()) << ','; - - query << "`cap` = " << (player->capacity / 100) << ','; - query << "`sex` = " << static_cast(player->sex) << ','; - - if (player->lastLoginSaved != 0) { - query << "`lastlogin` = " << player->lastLoginSaved << ','; - } - - if (player->lastIP != 0) { - query << "`lastip` = " << player->lastIP << ','; - } - - //serialize conditions - PropWriteStream propWriteStream; - for (Condition* condition : player->conditions) { - if (condition->isPersistent()) { - condition->serialize(propWriteStream); - propWriteStream.write(CONDITIONATTR_END); - } - } - - size_t attributesSize; - const char* attributes = propWriteStream.getStream(attributesSize); - - query << "`conditions` = " << db.escapeBlob(attributes, attributesSize) << ','; - - if (g_game().getWorldType() != WORLD_TYPE_PVP_ENFORCED) { - int64_t skullTime = 0; - - if (player->skullTicks > 0) { - skullTime = time(nullptr) + player->skullTicks; - } - - query << "`skulltime` = " << skullTime << ','; - - Skulls_t skull = SKULL_NONE; - if (player->skull == SKULL_RED) { - skull = SKULL_RED; - } else if (player->skull == SKULL_BLACK) { - skull = SKULL_BLACK; - } - query << "`skull` = " << static_cast(skull) << ','; - } - - query << "`lastlogout` = " << player->getLastLogout() << ','; - query << "`balance` = " << player->bankBalance << ','; - query << "`offlinetraining_time` = " << player->getOfflineTrainingTime() / 1000 << ','; - query << "`offlinetraining_skill` = " << std::to_string(player->getOfflineTrainingSkill()) << ','; - query << "`stamina` = " << player->getStaminaMinutes() << ','; - query << "`skill_fist` = " << player->skills[SKILL_FIST].level << ','; - query << "`skill_fist_tries` = " << player->skills[SKILL_FIST].tries << ','; - query << "`skill_club` = " << player->skills[SKILL_CLUB].level << ','; - query << "`skill_club_tries` = " << player->skills[SKILL_CLUB].tries << ','; - query << "`skill_sword` = " << player->skills[SKILL_SWORD].level << ','; - query << "`skill_sword_tries` = " << player->skills[SKILL_SWORD].tries << ','; - query << "`skill_axe` = " << player->skills[SKILL_AXE].level << ','; - query << "`skill_axe_tries` = " << player->skills[SKILL_AXE].tries << ','; - query << "`skill_dist` = " << player->skills[SKILL_DISTANCE].level << ','; - query << "`skill_dist_tries` = " << player->skills[SKILL_DISTANCE].tries << ','; - query << "`skill_shielding` = " << player->skills[SKILL_SHIELD].level << ','; - query << "`skill_shielding_tries` = " << player->skills[SKILL_SHIELD].tries << ','; - query << "`skill_fishing` = " << player->skills[SKILL_FISHING].level << ','; - query << "`skill_fishing_tries` = " << player->skills[SKILL_FISHING].tries << ','; - query << "`skill_critical_hit_chance` = " << player->skills[SKILL_CRITICAL_HIT_CHANCE].level << ','; - query << "`skill_critical_hit_chance_tries` = " << player->skills[SKILL_CRITICAL_HIT_CHANCE].tries << ','; - query << "`skill_critical_hit_damage` = " << player->skills[SKILL_CRITICAL_HIT_DAMAGE].level << ','; - query << "`skill_critical_hit_damage_tries` = " << player->skills[SKILL_CRITICAL_HIT_DAMAGE].tries << ','; - query << "`skill_life_leech_chance` = " << player->skills[SKILL_LIFE_LEECH_CHANCE].level << ','; - query << "`skill_life_leech_chance_tries` = " << player->skills[SKILL_LIFE_LEECH_CHANCE].tries << ','; - query << "`skill_life_leech_amount` = " << player->skills[SKILL_LIFE_LEECH_AMOUNT].level << ','; - query << "`skill_life_leech_amount_tries` = " << player->skills[SKILL_LIFE_LEECH_AMOUNT].tries << ','; - query << "`skill_mana_leech_chance` = " << player->skills[SKILL_MANA_LEECH_CHANCE].level << ','; - query << "`skill_mana_leech_chance_tries` = " << player->skills[SKILL_MANA_LEECH_CHANCE].tries << ','; - query << "`skill_mana_leech_amount` = " << player->skills[SKILL_MANA_LEECH_AMOUNT].level << ','; - query << "`skill_mana_leech_amount_tries` = " << player->skills[SKILL_MANA_LEECH_AMOUNT].tries << ','; - query << "`manashield` = " << player->getManaShield() << ','; - query << "`max_manashield` = " << player->getMaxManaShield() << ','; - query << "`xpboost_value` = " << player->getStoreXpBoost() << ','; - query << "`xpboost_stamina` = " << player->getExpBoostStamina() << ','; - query << "`quickloot_fallback` = " << (player->quickLootFallbackToMainContainer ? 1 : 0) << ','; - - if (!player->isOffline()) { - query << "`onlinetime` = `onlinetime` + " << (time(nullptr) - player->lastLoginSaved) << ','; - } - for (int i = 1; i <= 8; i++) { - query << "`blessings" << i << "`" << " = " << static_cast(player->getBlessingCount(i)) << ((i == 8) ? ' ' : ','); - } - query << " WHERE `id` = " << player->getGUID(); - - DBTransaction transaction; - if (!transaction.begin()) { - return false; - } - - if (!db.executeQuery(query.str())) { - return false; - } - - // Stash save items - query.str(std::string()); - query << "DELETE FROM `player_stash` WHERE `player_id` = " << player->getGUID(); - db.executeQuery(query.str()); - for (auto it : player->getStashItems()) { +bool IOLoginData::savePlayer(Player* player) { + if (player->getHealth() <= 0) { + player->changeHealth(1); + } + Database &db = Database::getInstance(); + + std::ostringstream query; + query << "SELECT `save` FROM `players` WHERE `id` = " << player->getGUID(); + DBResult_ptr result = db.storeQuery(query.str()); + if (!result) { + SPDLOG_WARN("[IOLoginData::savePlayer] - Error for select result query from player: {}", player->getName()); + return false; + } + + if (result->getNumber("save") == 0) { + query.str(std::string()); + query << "UPDATE `players` SET `lastlogin` = " << player->lastLoginSaved << ", `lastip` = " << player->lastIP << " WHERE `id` = " << player->getGUID(); + return db.executeQuery(query.str()); + } + + // First, an UPDATE query to write the player itself + query.str(std::string()); + query << "UPDATE `players` SET "; + query << "`level` = " << player->level << ','; + query << "`group_id` = " << player->group->id << ','; + query << "`vocation` = " << player->getVocationId() << ','; + query << "`health` = " << player->health << ','; + query << "`healthmax` = " << player->healthMax << ','; + query << "`experience` = " << player->experience << ','; + query << "`lookbody` = " << static_cast(player->defaultOutfit.lookBody) << ','; + query << "`lookfeet` = " << static_cast(player->defaultOutfit.lookFeet) << ','; + query << "`lookhead` = " << static_cast(player->defaultOutfit.lookHead) << ','; + query << "`looklegs` = " << static_cast(player->defaultOutfit.lookLegs) << ','; + query << "`looktype` = " << player->defaultOutfit.lookType << ','; + query << "`lookaddons` = " << static_cast(player->defaultOutfit.lookAddons) << ','; + query << "`lookmountbody` = " << static_cast(player->defaultOutfit.lookMountBody) << ','; + query << "`lookmountfeet` = " << static_cast(player->defaultOutfit.lookMountFeet) << ','; + query << "`lookmounthead` = " << static_cast(player->defaultOutfit.lookMountHead) << ','; + query << "`lookmountlegs` = " << static_cast(player->defaultOutfit.lookMountLegs) << ','; + query << "`lookfamiliarstype` = " << player->defaultOutfit.lookFamiliarsType << ','; + query << "`isreward` = " << static_cast(player->isDailyReward) << ','; + query << "`maglevel` = " << player->magLevel << ','; + query << "`mana` = " << player->mana << ','; + query << "`manamax` = " << player->manaMax << ','; + query << "`manaspent` = " << player->manaSpent << ','; + query << "`soul` = " << static_cast(player->soul) << ','; + query << "`town_id` = " << player->town->getID() << ','; + + const Position &loginPosition = player->getLoginPosition(); + query << "`posx` = " << loginPosition.getX() << ','; + query << "`posy` = " << loginPosition.getY() << ','; + query << "`posz` = " << loginPosition.getZ() << ','; + + query << "`prey_wildcard` = " << player->getPreyCards() << ','; + query << "`task_points` = " << player->getTaskHuntingPoints() << ','; + query << "`forge_dusts` = " << player->getForgeDusts() << ','; + query << "`forge_dust_level` = " << player->getForgeDustLevel() << ','; + query << "`randomize_mount` = " << static_cast(player->isRandomMounted()) << ','; + + query << "`cap` = " << (player->capacity / 100) << ','; + query << "`sex` = " << static_cast(player->sex) << ','; + + if (player->lastLoginSaved != 0) { + query << "`lastlogin` = " << player->lastLoginSaved << ','; + } + + if (player->lastIP != 0) { + query << "`lastip` = " << player->lastIP << ','; + } + + // serialize conditions + PropWriteStream propWriteStream; + for (Condition* condition : player->conditions) { + if (condition->isPersistent()) { + condition->serialize(propWriteStream); + propWriteStream.write(CONDITIONATTR_END); + } + } + + size_t attributesSize; + const char* attributes = propWriteStream.getStream(attributesSize); + + query << "`conditions` = " << db.escapeBlob(attributes, attributesSize) << ','; + + if (g_game().getWorldType() != WORLD_TYPE_PVP_ENFORCED) { + int64_t skullTime = 0; + + if (player->skullTicks > 0) { + skullTime = time(nullptr) + player->skullTicks; + } + + query << "`skulltime` = " << skullTime << ','; + + Skulls_t skull = SKULL_NONE; + if (player->skull == SKULL_RED) { + skull = SKULL_RED; + } else if (player->skull == SKULL_BLACK) { + skull = SKULL_BLACK; + } + query << "`skull` = " << static_cast(skull) << ','; + } + + query << "`lastlogout` = " << player->getLastLogout() << ','; + query << "`balance` = " << player->bankBalance << ','; + query << "`offlinetraining_time` = " << player->getOfflineTrainingTime() / 1000 << ','; + query << "`offlinetraining_skill` = " << std::to_string(player->getOfflineTrainingSkill()) << ','; + query << "`stamina` = " << player->getStaminaMinutes() << ','; + query << "`skill_fist` = " << player->skills[SKILL_FIST].level << ','; + query << "`skill_fist_tries` = " << player->skills[SKILL_FIST].tries << ','; + query << "`skill_club` = " << player->skills[SKILL_CLUB].level << ','; + query << "`skill_club_tries` = " << player->skills[SKILL_CLUB].tries << ','; + query << "`skill_sword` = " << player->skills[SKILL_SWORD].level << ','; + query << "`skill_sword_tries` = " << player->skills[SKILL_SWORD].tries << ','; + query << "`skill_axe` = " << player->skills[SKILL_AXE].level << ','; + query << "`skill_axe_tries` = " << player->skills[SKILL_AXE].tries << ','; + query << "`skill_dist` = " << player->skills[SKILL_DISTANCE].level << ','; + query << "`skill_dist_tries` = " << player->skills[SKILL_DISTANCE].tries << ','; + query << "`skill_shielding` = " << player->skills[SKILL_SHIELD].level << ','; + query << "`skill_shielding_tries` = " << player->skills[SKILL_SHIELD].tries << ','; + query << "`skill_fishing` = " << player->skills[SKILL_FISHING].level << ','; + query << "`skill_fishing_tries` = " << player->skills[SKILL_FISHING].tries << ','; + query << "`skill_critical_hit_chance` = " << player->skills[SKILL_CRITICAL_HIT_CHANCE].level << ','; + query << "`skill_critical_hit_chance_tries` = " << player->skills[SKILL_CRITICAL_HIT_CHANCE].tries << ','; + query << "`skill_critical_hit_damage` = " << player->skills[SKILL_CRITICAL_HIT_DAMAGE].level << ','; + query << "`skill_critical_hit_damage_tries` = " << player->skills[SKILL_CRITICAL_HIT_DAMAGE].tries << ','; + query << "`skill_life_leech_chance` = " << player->skills[SKILL_LIFE_LEECH_CHANCE].level << ','; + query << "`skill_life_leech_chance_tries` = " << player->skills[SKILL_LIFE_LEECH_CHANCE].tries << ','; + query << "`skill_life_leech_amount` = " << player->skills[SKILL_LIFE_LEECH_AMOUNT].level << ','; + query << "`skill_life_leech_amount_tries` = " << player->skills[SKILL_LIFE_LEECH_AMOUNT].tries << ','; + query << "`skill_mana_leech_chance` = " << player->skills[SKILL_MANA_LEECH_CHANCE].level << ','; + query << "`skill_mana_leech_chance_tries` = " << player->skills[SKILL_MANA_LEECH_CHANCE].tries << ','; + query << "`skill_mana_leech_amount` = " << player->skills[SKILL_MANA_LEECH_AMOUNT].level << ','; + query << "`skill_mana_leech_amount_tries` = " << player->skills[SKILL_MANA_LEECH_AMOUNT].tries << ','; + query << "`manashield` = " << player->getManaShield() << ','; + query << "`max_manashield` = " << player->getMaxManaShield() << ','; + query << "`xpboost_value` = " << player->getStoreXpBoost() << ','; + query << "`xpboost_stamina` = " << player->getExpBoostStamina() << ','; + query << "`quickloot_fallback` = " << (player->quickLootFallbackToMainContainer ? 1 : 0) << ','; + + if (!player->isOffline()) { + query << "`onlinetime` = `onlinetime` + " << (time(nullptr) - player->lastLoginSaved) << ','; + } + for (int i = 1; i <= 8; i++) { + query << "`blessings" << i << "`" + << " = " << static_cast(player->getBlessingCount(i)) << ((i == 8) ? ' ' : ','); + } + query << " WHERE `id` = " << player->getGUID(); + + DBTransaction transaction; + if (!transaction.begin()) { + return false; + } + + if (!db.executeQuery(query.str())) { + return false; + } + + // Stash save items query.str(std::string()); - query << "INSERT INTO `player_stash` (`player_id`,`item_id`,`item_count`) VALUES ("; - query << player->getGUID() << ", "; - query << it.first << ", "; - query << it.second << ")"; + query << "DELETE FROM `player_stash` WHERE `player_id` = " << player->getGUID(); db.executeQuery(query.str()); - } - - // learned spells - query.str(std::string()); - query << "DELETE FROM `player_spells` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - return false; - } - - query.str(std::string()); - - DBInsert spellsQuery("INSERT INTO `player_spells` (`player_id`, `name` ) VALUES "); - for (const std::string& spellName : player->learnedInstantSpellList) { - query << player->getGUID() << ',' << db.escapeString(spellName); - if (!spellsQuery.addRow(query)) { - return false; - } - } - - if (!spellsQuery.execute()) { - return false; - } - - //player kills - query.str(std::string()); - query << "DELETE FROM `player_kills` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - return false; - } - - //player bestiary charms - query.str(std::string()); - query << "UPDATE `player_charms` SET "; - query << "`charm_points` = " << player->charmPoints << ','; - query << "`charm_expansion` = " << ((player->charmExpansion) ? 1 : 0) << ','; - query << "`rune_wound` = " << player->charmRuneWound << ','; - query << "`rune_enflame` = " << player->charmRuneEnflame << ','; - query << "`rune_poison` = " << player->charmRunePoison << ','; - query << "`rune_freeze` = " << player->charmRuneFreeze << ','; - query << "`rune_zap` = " << player->charmRuneZap << ','; - query << "`rune_curse` = " << player->charmRuneCurse << ','; - query << "`rune_cripple` = " << player->charmRuneCripple << ','; - query << "`rune_parry` = " << player->charmRuneParry << ','; - query << "`rune_dodge` = " << player->charmRuneDodge << ','; - query << "`rune_adrenaline` = " << player->charmRuneAdrenaline << ','; - query << "`rune_numb` = " << player->charmRuneNumb << ','; - query << "`rune_cleanse` = " << player->charmRuneCleanse << ','; - query << "`rune_bless` = " << player->charmRuneBless << ','; - query << "`rune_scavenge` = " << player->charmRuneScavenge << ','; - query << "`rune_gut` = " << player->charmRuneGut << ','; - query << "`rune_low_blow` = " << player->charmRuneLowBlow << ','; - query << "`rune_divine` = " << player->charmRuneDivine << ','; - query << "`rune_vamp` = " << player->charmRuneVamp << ','; - query << "`rune_void` = " << player->charmRuneVoid << ','; - query << "`UsedRunesBit` = " << player->UsedRunesBit << ','; - query << "`UnlockedRunesBit` = " << player->UnlockedRunesBit << ','; - - // Bestiary tracker - PropWriteStream propBestiaryStream; - for (MonsterType* trackedType : player->getBestiaryTrackerList()) { - propBestiaryStream.write(trackedType->info.raceid); - } - size_t trackerSize; - const char* trackerList = propBestiaryStream.getStream(trackerSize); - query << " `tracker list` = " << db.escapeBlob(trackerList, trackerSize); - query << " WHERE `player_guid` = " << player->getGUID(); - - if (!db.executeQuery(query.str())) { - SPDLOG_WARN("[IOLoginData::savePlayer] - Error saving bestiary data from player: {}", player->getName()); - return false; - } - - query.str(std::string()); - - DBInsert killsQuery("INSERT INTO `player_kills` (`player_id`, `target`, `time`, `unavenged`) VALUES"); - for (const auto& kill : player->unjustifiedKills) { - query << player->getGUID() << ',' << kill.target << ',' << kill.time << ',' << kill.unavenged; - if (!killsQuery.addRow(query)) { - return false; - } - } - - if (!killsQuery.execute()) { - return false; - } - - //item saving - query << "DELETE FROM `player_items` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - SPDLOG_WARN("[IOLoginData::savePlayer] - Error delete query 'player_items' from player: {}", player->getName()); - return false; - } - - DBInsert itemsQuery("INSERT INTO `player_items` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); - - ItemBlockList itemList; - for (int32_t slotId = CONST_SLOT_FIRST; slotId <= CONST_SLOT_LAST; ++slotId) { - Item* item = player->inventory[slotId]; - if (item) { - itemList.emplace_back(slotId, item); - } - } - - if (!saveItems(player, itemList, itemsQuery, propWriteStream)) { - SPDLOG_WARN("[IOLoginData::savePlayer] - Failed for save items from player: {}", player->getName()); - return false; - } - - if (player->lastDepotId != -1) { - //save depot items - query.str(std::string()); - query << "DELETE FROM `player_depotitems` WHERE `player_id` = " << player->getGUID(); - - if (!db.executeQuery(query.str())) { - return false; - } - - DBInsert depotQuery("INSERT INTO `player_depotitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); - itemList.clear(); - - for (const auto& it : player->depotChests) { - DepotChest* depotChest = it.second; - for (Item* item : depotChest->getItemList()) { - itemList.emplace_back(it.first, item); - } - } - - if (!saveItems(player, itemList, depotQuery, propWriteStream)) { - return false; - } - } - - //save reward items - query.str(std::string()); - query << "DELETE FROM `player_rewards` WHERE `player_id` = " << player->getGUID(); - - if (!db.executeQuery(query.str())) { - return false; - } - - std::vector rewardList; - player->getRewardList(rewardList); - - if (!rewardList.empty()) { - DBInsert rewardQuery("INSERT INTO `player_rewards` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); - itemList.clear(); - - int running = 0; - for (const auto& rewardId : rewardList) { - Reward* reward = player->getReward(rewardId, false); - // rewards that are empty or older than 7 days aren't stored - if (!reward->empty() && (time(nullptr) - rewardId <= 60 * 60 * 24 * 7)) { - itemList.emplace_back(++running, reward); - } - } - - if (!saveItems(player, itemList, rewardQuery, propWriteStream)) { - return false; - } - } - - //save inbox items - query.str(std::string()); - query << "DELETE FROM `player_inboxitems` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - return false; - } - - DBInsert inboxQuery("INSERT INTO `player_inboxitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); - itemList.clear(); - - for (Item* item : player->getInbox()->getItemList()) { - itemList.emplace_back(0, item); - } - - if (!saveItems(player, itemList, inboxQuery, propWriteStream)) { - return false; - } - - // Save prey class - if (g_configManager().getBoolean(PREY_ENABLED)) { - query.str(std::string()); - query << "DELETE FROM `player_prey` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - return false; - } - - for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { - PreySlot* slot = player->getPreySlotById(static_cast(slotId)); - if (slot) { - query.str(std::string()); - query << "INSERT INTO `player_prey` (`player_id`, `slot`, `state`, `raceid`, `option`, `bonus_type`, `bonus_rarity`, `bonus_percentage`, `bonus_time`, `free_reroll`, `monster_list`) VALUES ("; - query << player->getGUID() << ", "; - query << static_cast(slot->id) << ", "; - query << static_cast(slot->state) << ", "; - query << slot->selectedRaceId << ", "; - query << static_cast(slot->option) << ", "; - query << static_cast(slot->bonus) << ", "; - query << static_cast(slot->bonusRarity) << ", "; - query << slot->bonusPercentage << ", "; - query << slot->bonusTimeLeft << ", "; - query << slot->freeRerollTimeStamp << ", "; - - PropWriteStream propPreyStream; - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&propPreyStream](uint16_t raceId) - { - propPreyStream.write(raceId); - }); - - size_t preySize; - const char* preyList = propPreyStream.getStream(preySize); - query << db.escapeBlob(preyList, static_cast(preySize)) << ")"; - - if (!db.executeQuery(query.str())) { - SPDLOG_WARN("[IOLoginData::savePlayer] - Error saving prey slot data from player: {}", player->getName()); - return false; - } - } - } - } - - // Save task hunting class - if (g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { - query.str(std::string()); - query << "DELETE FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - return false; - } - - for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { - TaskHuntingSlot* slot = player->getTaskHuntingSlotById(static_cast(slotId)); - if (slot) { - query.str(std::string()); - query << "INSERT INTO `player_taskhunt` (`player_id`, `slot`, `state`, `raceid`, `upgrade`, `rarity`, `kills`, `disabled_time`, `free_reroll`, `monster_list`) VALUES ("; - query << player->getGUID() << ", "; - query << static_cast(slot->id) << ", "; - query << static_cast(slot->state) << ", "; - query << slot->selectedRaceId << ", "; - query << (slot->upgrade ? 1 : 0) << ", "; - query << static_cast(slot->rarity) << ", "; - query << slot->currentKills << ", "; - query << slot->disabledUntilTimeStamp << ", "; - query << slot->freeRerollTimeStamp << ", "; - - PropWriteStream propTaskHuntingStream; - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&propTaskHuntingStream](uint16_t raceId) - { - propTaskHuntingStream.write(raceId); - }); - - size_t taskHuntingSize; - const char* taskHuntingList = propTaskHuntingStream.getStream(taskHuntingSize); - query << db.escapeBlob(taskHuntingList, static_cast(taskHuntingSize)) << ")"; - - if (!db.executeQuery(query.str())) { - SPDLOG_WARN("[IOLoginData::savePlayer] - Error saving task hunting slot data from player: {}", player->getName()); - return false; - } - } - } - } - - IOLoginDataSave::savePlayerForgeHistory(player); - - query.str(std::string()); - query << "DELETE FROM `player_storage` WHERE `player_id` = " << player->getGUID(); - if (!db.executeQuery(query.str())) { - return false; - } - - query.str(std::string()); - - DBInsert storageQuery("INSERT INTO `player_storage` (`player_id`, `key`, `value`) VALUES "); - player->genReservedStorageRange(); - - for (const auto& it : player->storageMap) { - query << player->getGUID() << ',' << it.first << ',' << it.second; - if (!storageQuery.addRow(query)) { - return false; - } - } - - if (!storageQuery.execute()) { - return false; - } - - //End the transaction - return transaction.commit(); + for (auto it : player->getStashItems()) { + query.str(std::string()); + query << "INSERT INTO `player_stash` (`player_id`,`item_id`,`item_count`) VALUES ("; + query << player->getGUID() << ", "; + query << it.first << ", "; + query << it.second << ")"; + db.executeQuery(query.str()); + } + + // learned spells + query.str(std::string()); + query << "DELETE FROM `player_spells` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + return false; + } + + query.str(std::string()); + + DBInsert spellsQuery("INSERT INTO `player_spells` (`player_id`, `name` ) VALUES "); + for (const std::string &spellName : player->learnedInstantSpellList) { + query << player->getGUID() << ',' << db.escapeString(spellName); + if (!spellsQuery.addRow(query)) { + return false; + } + } + + if (!spellsQuery.execute()) { + return false; + } + + // player kills + query.str(std::string()); + query << "DELETE FROM `player_kills` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + return false; + } + + // player bestiary charms + query.str(std::string()); + query << "UPDATE `player_charms` SET "; + query << "`charm_points` = " << player->charmPoints << ','; + query << "`charm_expansion` = " << ((player->charmExpansion) ? 1 : 0) << ','; + query << "`rune_wound` = " << player->charmRuneWound << ','; + query << "`rune_enflame` = " << player->charmRuneEnflame << ','; + query << "`rune_poison` = " << player->charmRunePoison << ','; + query << "`rune_freeze` = " << player->charmRuneFreeze << ','; + query << "`rune_zap` = " << player->charmRuneZap << ','; + query << "`rune_curse` = " << player->charmRuneCurse << ','; + query << "`rune_cripple` = " << player->charmRuneCripple << ','; + query << "`rune_parry` = " << player->charmRuneParry << ','; + query << "`rune_dodge` = " << player->charmRuneDodge << ','; + query << "`rune_adrenaline` = " << player->charmRuneAdrenaline << ','; + query << "`rune_numb` = " << player->charmRuneNumb << ','; + query << "`rune_cleanse` = " << player->charmRuneCleanse << ','; + query << "`rune_bless` = " << player->charmRuneBless << ','; + query << "`rune_scavenge` = " << player->charmRuneScavenge << ','; + query << "`rune_gut` = " << player->charmRuneGut << ','; + query << "`rune_low_blow` = " << player->charmRuneLowBlow << ','; + query << "`rune_divine` = " << player->charmRuneDivine << ','; + query << "`rune_vamp` = " << player->charmRuneVamp << ','; + query << "`rune_void` = " << player->charmRuneVoid << ','; + query << "`UsedRunesBit` = " << player->UsedRunesBit << ','; + query << "`UnlockedRunesBit` = " << player->UnlockedRunesBit << ','; + + // Bestiary tracker + PropWriteStream propBestiaryStream; + for (MonsterType* trackedType : player->getBestiaryTrackerList()) { + propBestiaryStream.write(trackedType->info.raceid); + } + size_t trackerSize; + const char* trackerList = propBestiaryStream.getStream(trackerSize); + query << " `tracker list` = " << db.escapeBlob(trackerList, trackerSize); + query << " WHERE `player_guid` = " << player->getGUID(); + + if (!db.executeQuery(query.str())) { + SPDLOG_WARN("[IOLoginData::savePlayer] - Error saving bestiary data from player: {}", player->getName()); + return false; + } + + query.str(std::string()); + + DBInsert killsQuery("INSERT INTO `player_kills` (`player_id`, `target`, `time`, `unavenged`) VALUES"); + for (const auto &kill : player->unjustifiedKills) { + query << player->getGUID() << ',' << kill.target << ',' << kill.time << ',' << kill.unavenged; + if (!killsQuery.addRow(query)) { + return false; + } + } + + if (!killsQuery.execute()) { + return false; + } + + // item saving + query << "DELETE FROM `player_items` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + SPDLOG_WARN("[IOLoginData::savePlayer] - Error delete query 'player_items' from player: {}", player->getName()); + return false; + } + + DBInsert itemsQuery("INSERT INTO `player_items` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); + + ItemBlockList itemList; + for (int32_t slotId = CONST_SLOT_FIRST; slotId <= CONST_SLOT_LAST; ++slotId) { + Item* item = player->inventory[slotId]; + if (item) { + itemList.emplace_back(slotId, item); + } + } + + if (!saveItems(player, itemList, itemsQuery, propWriteStream)) { + SPDLOG_WARN("[IOLoginData::savePlayer] - Failed for save items from player: {}", player->getName()); + return false; + } + + if (player->lastDepotId != -1) { + // save depot items + query.str(std::string()); + query << "DELETE FROM `player_depotitems` WHERE `player_id` = " << player->getGUID(); + + if (!db.executeQuery(query.str())) { + return false; + } + + DBInsert depotQuery("INSERT INTO `player_depotitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); + itemList.clear(); + + for (const auto &it : player->depotChests) { + DepotChest* depotChest = it.second; + for (Item* item : depotChest->getItemList()) { + itemList.emplace_back(it.first, item); + } + } + + if (!saveItems(player, itemList, depotQuery, propWriteStream)) { + return false; + } + } + + // save reward items + query.str(std::string()); + query << "DELETE FROM `player_rewards` WHERE `player_id` = " << player->getGUID(); + + if (!db.executeQuery(query.str())) { + return false; + } + + std::vector rewardList; + player->getRewardList(rewardList); + + if (!rewardList.empty()) { + DBInsert rewardQuery("INSERT INTO `player_rewards` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); + itemList.clear(); + + int running = 0; + for (const auto &rewardId : rewardList) { + Reward* reward = player->getReward(rewardId, false); + // rewards that are empty or older than 7 days aren't stored + if (!reward->empty() && (time(nullptr) - rewardId <= 60 * 60 * 24 * 7)) { + itemList.emplace_back(++running, reward); + } + } + + if (!saveItems(player, itemList, rewardQuery, propWriteStream)) { + return false; + } + } + + // save inbox items + query.str(std::string()); + query << "DELETE FROM `player_inboxitems` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + return false; + } + + DBInsert inboxQuery("INSERT INTO `player_inboxitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); + itemList.clear(); + + for (Item* item : player->getInbox()->getItemList()) { + itemList.emplace_back(0, item); + } + + if (!saveItems(player, itemList, inboxQuery, propWriteStream)) { + return false; + } + + // Save prey class + if (g_configManager().getBoolean(PREY_ENABLED)) { + query.str(std::string()); + query << "DELETE FROM `player_prey` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + return false; + } + + for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { + PreySlot* slot = player->getPreySlotById(static_cast(slotId)); + if (slot) { + query.str(std::string()); + query << "INSERT INTO `player_prey` (`player_id`, `slot`, `state`, `raceid`, `option`, `bonus_type`, `bonus_rarity`, `bonus_percentage`, `bonus_time`, `free_reroll`, `monster_list`) VALUES ("; + query << player->getGUID() << ", "; + query << static_cast(slot->id) << ", "; + query << static_cast(slot->state) << ", "; + query << slot->selectedRaceId << ", "; + query << static_cast(slot->option) << ", "; + query << static_cast(slot->bonus) << ", "; + query << static_cast(slot->bonusRarity) << ", "; + query << slot->bonusPercentage << ", "; + query << slot->bonusTimeLeft << ", "; + query << slot->freeRerollTimeStamp << ", "; + + PropWriteStream propPreyStream; + std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&propPreyStream](uint16_t raceId) { + propPreyStream.write(raceId); + }); + + size_t preySize; + const char* preyList = propPreyStream.getStream(preySize); + query << db.escapeBlob(preyList, static_cast(preySize)) << ")"; + + if (!db.executeQuery(query.str())) { + SPDLOG_WARN("[IOLoginData::savePlayer] - Error saving prey slot data from player: {}", player->getName()); + return false; + } + } + } + } + + // Save task hunting class + if (g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + query.str(std::string()); + query << "DELETE FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + return false; + } + + for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { + TaskHuntingSlot* slot = player->getTaskHuntingSlotById(static_cast(slotId)); + if (slot) { + query.str(std::string()); + query << "INSERT INTO `player_taskhunt` (`player_id`, `slot`, `state`, `raceid`, `upgrade`, `rarity`, `kills`, `disabled_time`, `free_reroll`, `monster_list`) VALUES ("; + query << player->getGUID() << ", "; + query << static_cast(slot->id) << ", "; + query << static_cast(slot->state) << ", "; + query << slot->selectedRaceId << ", "; + query << (slot->upgrade ? 1 : 0) << ", "; + query << static_cast(slot->rarity) << ", "; + query << slot->currentKills << ", "; + query << slot->disabledUntilTimeStamp << ", "; + query << slot->freeRerollTimeStamp << ", "; + + PropWriteStream propTaskHuntingStream; + std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&propTaskHuntingStream](uint16_t raceId) { + propTaskHuntingStream.write(raceId); + }); + + size_t taskHuntingSize; + const char* taskHuntingList = propTaskHuntingStream.getStream(taskHuntingSize); + query << db.escapeBlob(taskHuntingList, static_cast(taskHuntingSize)) << ")"; + + if (!db.executeQuery(query.str())) { + SPDLOG_WARN("[IOLoginData::savePlayer] - Error saving task hunting slot data from player: {}", player->getName()); + return false; + } + } + } + } + + IOLoginDataSave::savePlayerForgeHistory(player); + + query.str(std::string()); + query << "DELETE FROM `player_storage` WHERE `player_id` = " << player->getGUID(); + if (!db.executeQuery(query.str())) { + return false; + } + + query.str(std::string()); + + DBInsert storageQuery("INSERT INTO `player_storage` (`player_id`, `key`, `value`) VALUES "); + player->genReservedStorageRange(); + + for (const auto &it : player->storageMap) { + query << player->getGUID() << ',' << it.first << ',' << it.second; + if (!storageQuery.addRow(query)) { + return false; + } + } + + if (!storageQuery.execute()) { + return false; + } + + // End the transaction + return transaction.commit(); } -std::string IOLoginData::getNameByGuid(uint32_t guid) -{ - std::ostringstream query; - query << "SELECT `name` FROM `players` WHERE `id` = " << guid; - DBResult_ptr result = Database::getInstance().storeQuery(query.str()); - if (!result) { - return std::string(); - } - return result->getString("name"); +std::string IOLoginData::getNameByGuid(uint32_t guid) { + std::ostringstream query; + query << "SELECT `name` FROM `players` WHERE `id` = " << guid; + DBResult_ptr result = Database::getInstance().storeQuery(query.str()); + if (!result) { + return std::string(); + } + return result->getString("name"); } -uint32_t IOLoginData::getGuidByName(const std::string& name) -{ - Database& db = Database::getInstance(); - - std::ostringstream query; - query << "SELECT `id` FROM `players` WHERE `name` = " << db.escapeString(name); - DBResult_ptr result = db.storeQuery(query.str()); - if (!result) { - return 0; - } - return result->getNumber("id"); +uint32_t IOLoginData::getGuidByName(const std::string &name) { + Database &db = Database::getInstance(); + + std::ostringstream query; + query << "SELECT `id` FROM `players` WHERE `name` = " << db.escapeString(name); + DBResult_ptr result = db.storeQuery(query.str()); + if (!result) { + return 0; + } + return result->getNumber("id"); } -bool IOLoginData::getGuidByNameEx(uint32_t& guid, bool& specialVip, std::string& name) -{ - Database& db = Database::getInstance(); - - std::ostringstream query; - query << "SELECT `name`, `id`, `group_id`, `account_id` FROM `players` WHERE `name` = " << db.escapeString(name); - DBResult_ptr result = db.storeQuery(query.str()); - if (!result) { - return false; - } - - name = result->getString("name"); - guid = result->getNumber("id"); - if (auto group = g_game().groups.getGroup(result->getNumber("group_id"))) { - specialVip = group->flags[Groups::getFlagNumber(PlayerFlags_t::SpecialVIP)]; - } else { - specialVip = false; - } - return true; +bool IOLoginData::getGuidByNameEx(uint32_t &guid, bool &specialVip, std::string &name) { + Database &db = Database::getInstance(); + + std::ostringstream query; + query << "SELECT `name`, `id`, `group_id`, `account_id` FROM `players` WHERE `name` = " << db.escapeString(name); + DBResult_ptr result = db.storeQuery(query.str()); + if (!result) { + return false; + } + + name = result->getString("name"); + guid = result->getNumber("id"); + if (auto group = g_game().groups.getGroup(result->getNumber("group_id"))) { + specialVip = group->flags[Groups::getFlagNumber(PlayerFlags_t::SpecialVIP)]; + } else { + specialVip = false; + } + return true; } -bool IOLoginData::formatPlayerName(std::string& name) -{ - Database& db = Database::getInstance(); +bool IOLoginData::formatPlayerName(std::string &name) { + Database &db = Database::getInstance(); - std::ostringstream query; - query << "SELECT `name` FROM `players` WHERE `name` = " << db.escapeString(name); + std::ostringstream query; + query << "SELECT `name` FROM `players` WHERE `name` = " << db.escapeString(name); - DBResult_ptr result = db.storeQuery(query.str()); - if (!result) { - return false; - } + DBResult_ptr result = db.storeQuery(query.str()); + if (!result) { + return false; + } - name = result->getString("name"); - return true; + name = result->getString("name"); + return true; } -void IOLoginData::loadItems(ItemMap& itemMap, DBResult_ptr result, Player &player) -{ - do { - uint32_t sid = result->getNumber("sid"); - uint32_t pid = result->getNumber("pid"); - uint16_t type = result->getNumber("itemtype"); - uint16_t count = result->getNumber("count"); - - unsigned long attrSize; - const char* attr = result->getStream("attributes", attrSize); - - PropStream propStream; - propStream.init(attr, attrSize); - - Item* item = Item::CreateItem(type, count); - if (item) { - if (!item->unserializeAttr(propStream)) { - SPDLOG_WARN("[IOLoginData::loadItems] - Failed to unserialize attributes of item {}, of player {}, from account id {}", item->getID(), player.getName(), player.getAccount()); - savePlayer(&player); - } - - std::pair pair(item, pid); - itemMap[sid] = pair; - } - } while (result->next()); +void IOLoginData::loadItems(ItemMap &itemMap, DBResult_ptr result, Player &player) { + do { + uint32_t sid = result->getNumber("sid"); + uint32_t pid = result->getNumber("pid"); + uint16_t type = result->getNumber("itemtype"); + uint16_t count = result->getNumber("count"); + + unsigned long attrSize; + const char* attr = result->getStream("attributes", attrSize); + + PropStream propStream; + propStream.init(attr, attrSize); + + Item* item = Item::CreateItem(type, count); + if (item) { + if (!item->unserializeAttr(propStream)) { + SPDLOG_WARN("[IOLoginData::loadItems] - Failed to unserialize attributes of item {}, of player {}, from account id {}", item->getID(), player.getName(), player.getAccount()); + savePlayer(&player); + } + + std::pair pair(item, pid); + itemMap[sid] = pair; + } + } while (result->next()); } -void IOLoginData::increaseBankBalance(uint32_t guid, uint64_t bankBalance) -{ - std::ostringstream query; - query << "UPDATE `players` SET `balance` = `balance` + " << bankBalance << " WHERE `id` = " << guid; - Database::getInstance().executeQuery(query.str()); +void IOLoginData::increaseBankBalance(uint32_t guid, uint64_t bankBalance) { + std::ostringstream query; + query << "UPDATE `players` SET `balance` = `balance` + " << bankBalance << " WHERE `id` = " << guid; + Database::getInstance().executeQuery(query.str()); } -bool IOLoginData::hasBiddedOnHouse(uint32_t guid) -{ - Database& db = Database::getInstance(); +bool IOLoginData::hasBiddedOnHouse(uint32_t guid) { + Database &db = Database::getInstance(); - std::ostringstream query; - query << "SELECT `id` FROM `houses` WHERE `highest_bidder` = " << guid << " LIMIT 1"; - return db.storeQuery(query.str()).get() != nullptr; + std::ostringstream query; + query << "SELECT `id` FROM `houses` WHERE `highest_bidder` = " << guid << " LIMIT 1"; + return db.storeQuery(query.str()).get() != nullptr; } -std::forward_list IOLoginData::getVIPEntries(uint32_t accountId) -{ - std::forward_list entries; - - std::ostringstream query; - query << "SELECT `player_id`, (SELECT `name` FROM `players` WHERE `id` = `player_id`) AS `name`, `description`, `icon`, `notify` FROM `account_viplist` WHERE `account_id` = " << accountId; - - DBResult_ptr result = Database::getInstance().storeQuery(query.str()); - if (result) { - do { - entries.emplace_front( - result->getNumber("player_id"), - result->getString("name"), - result->getString("description"), - result->getNumber("icon"), - result->getNumber("notify") != 0 - ); - } while (result->next()); - } - return entries; +std::forward_list IOLoginData::getVIPEntries(uint32_t accountId) { + std::forward_list entries; + + std::ostringstream query; + query << "SELECT `player_id`, (SELECT `name` FROM `players` WHERE `id` = `player_id`) AS `name`, `description`, `icon`, `notify` FROM `account_viplist` WHERE `account_id` = " << accountId; + + DBResult_ptr result = Database::getInstance().storeQuery(query.str()); + if (result) { + do { + entries.emplace_front( + result->getNumber("player_id"), + result->getString("name"), + result->getString("description"), + result->getNumber("icon"), + result->getNumber("notify") != 0 + ); + } while (result->next()); + } + return entries; } -void IOLoginData::addVIPEntry(uint32_t accountId, uint32_t guid, const std::string& description, uint32_t icon, bool notify) -{ - Database& db = Database::getInstance(); +void IOLoginData::addVIPEntry(uint32_t accountId, uint32_t guid, const std::string &description, uint32_t icon, bool notify) { + Database &db = Database::getInstance(); - std::ostringstream query; - query << "INSERT INTO `account_viplist` (`account_id`, `player_id`, `description`, `icon`, `notify`) VALUES (" << accountId << ',' << guid << ',' << db.escapeString(description) << ',' << icon << ',' << notify << ')'; - db.executeQuery(query.str()); + std::ostringstream query; + query << "INSERT INTO `account_viplist` (`account_id`, `player_id`, `description`, `icon`, `notify`) VALUES (" << accountId << ',' << guid << ',' << db.escapeString(description) << ',' << icon << ',' << notify << ')'; + db.executeQuery(query.str()); } -void IOLoginData::editVIPEntry(uint32_t accountId, uint32_t guid, const std::string& description, uint32_t icon, bool notify) -{ - Database& db = Database::getInstance(); +void IOLoginData::editVIPEntry(uint32_t accountId, uint32_t guid, const std::string &description, uint32_t icon, bool notify) { + Database &db = Database::getInstance(); - std::ostringstream query; - query << "UPDATE `account_viplist` SET `description` = " << db.escapeString(description) << ", `icon` = " << icon << ", `notify` = " << notify << " WHERE `account_id` = " << accountId << " AND `player_id` = " << guid; - db.executeQuery(query.str()); + std::ostringstream query; + query << "UPDATE `account_viplist` SET `description` = " << db.escapeString(description) << ", `icon` = " << icon << ", `notify` = " << notify << " WHERE `account_id` = " << accountId << " AND `player_id` = " << guid; + db.executeQuery(query.str()); } -void IOLoginData::removeVIPEntry(uint32_t accountId, uint32_t guid) -{ - std::ostringstream query; - query << "DELETE FROM `account_viplist` WHERE `account_id` = " << accountId << " AND `player_id` = " << guid; - Database::getInstance().executeQuery(query.str()); +void IOLoginData::removeVIPEntry(uint32_t accountId, uint32_t guid) { + std::ostringstream query; + query << "DELETE FROM `account_viplist` WHERE `account_id` = " << accountId << " AND `player_id` = " << guid; + Database::getInstance().executeQuery(query.str()); } -void IOLoginData::addPremiumDays(uint32_t accountId, int32_t addDays) -{ - std::ostringstream query; - query << "UPDATE `accounts` SET `premdays` = `premdays` + " << addDays << " WHERE `id` = " << accountId; - Database::getInstance().executeQuery(query.str()); +void IOLoginData::addPremiumDays(uint32_t accountId, int32_t addDays) { + std::ostringstream query; + query << "UPDATE `accounts` SET `premdays` = `premdays` + " << addDays << " WHERE `id` = " << accountId; + Database::getInstance().executeQuery(query.str()); } -void IOLoginData::removePremiumDays(uint32_t accountId, int32_t removeDays) -{ - std::ostringstream query; - query << "UPDATE `accounts` SET `premdays` = `premdays` - " << removeDays << " WHERE `id` = " << accountId; - Database::getInstance().executeQuery(query.str()); +void IOLoginData::removePremiumDays(uint32_t accountId, int32_t removeDays) { + std::ostringstream query; + query << "UPDATE `accounts` SET `premdays` = `premdays` - " << removeDays << " WHERE `id` = " << accountId; + Database::getInstance().executeQuery(query.str()); } diff --git a/src/io/iologindata.h b/src/io/iologindata.h index 82228904b79..955a6d06aef 100644 --- a/src/io/iologindata.h +++ b/src/io/iologindata.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOLOGINDATA_H_ #define SRC_IO_IOLOGINDATA_H_ @@ -16,35 +16,29 @@ using ItemBlockList = std::list>; -class IOLoginData -{ +class IOLoginData { public: - static bool authenticateAccountPassword(const std::string& email, - const std::string& password, - account::Account *account); - static bool gameWorldAuthentication(const std::string& accountName, - const std::string& password, - std::string& characterName, - uint32_t *accountId); + static bool authenticateAccountPassword(const std::string &email, const std::string &password, account::Account* account); + static bool gameWorldAuthentication(const std::string &accountName, const std::string &password, std::string &characterName, uint32_t* accountId); static account::AccountType getAccountType(uint32_t accountId); static void setAccountType(uint32_t accountId, account::AccountType accountType); static void updateOnlineStatus(uint32_t guid, bool login); - static bool preloadPlayer(Player* player, const std::string& name); + static bool preloadPlayer(Player* player, const std::string &name); static bool loadPlayerById(Player* player, uint32_t id); - static bool loadPlayerByName(Player* player, const std::string& name); + static bool loadPlayerByName(Player* player, const std::string &name); static bool loadPlayer(Player* player, DBResult_ptr result); static bool savePlayer(Player* player); - static uint32_t getGuidByName(const std::string& name); - static bool getGuidByNameEx(uint32_t& guid, bool& specialVip, std::string& name); + static uint32_t getGuidByName(const std::string &name); + static bool getGuidByNameEx(uint32_t &guid, bool &specialVip, std::string &name); static std::string getNameByGuid(uint32_t guid); - static bool formatPlayerName(std::string& name); + static bool formatPlayerName(std::string &name); static void increaseBankBalance(uint32_t guid, uint64_t bankBalance); static bool hasBiddedOnHouse(uint32_t guid); static std::forward_list getVIPEntries(uint32_t accountId); - static void addVIPEntry(uint32_t accountId, uint32_t guid, const std::string& description, uint32_t icon, bool notify); - static void editVIPEntry(uint32_t accountId, uint32_t guid, const std::string& description, uint32_t icon, bool notify); + static void addVIPEntry(uint32_t accountId, uint32_t guid, const std::string &description, uint32_t icon, bool notify); + static void editVIPEntry(uint32_t accountId, uint32_t guid, const std::string &description, uint32_t icon, bool notify); static void removeVIPEntry(uint32_t accountId, uint32_t guid); static void addPremiumDays(uint32_t accountId, int32_t addDays); @@ -53,8 +47,8 @@ class IOLoginData private: using ItemMap = std::map>; - static void loadItems(ItemMap& itemMap, DBResult_ptr result, Player &player); - static bool saveItems(const Player* player, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& stream); + static void loadItems(ItemMap &itemMap, DBResult_ptr result, Player &player); + static bool saveItems(const Player* player, const ItemBlockList &itemList, DBInsert &query_insert, PropWriteStream &stream); }; -#endif // SRC_IO_IOLOGINDATA_H_ +#endif // SRC_IO_IOLOGINDATA_H_ diff --git a/src/io/iomap.cpp b/src/io/iomap.cpp index ed14db2a17a..8a44cdc0566 100644 --- a/src/io/iomap.cpp +++ b/src/io/iomap.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -37,8 +37,7 @@ |--- OTBM_ITEM_DEF (not implemented) */ -Tile* IOMap::createTile(Item*& ground, Item* item, uint16_t x, uint16_t y, uint8_t z) -{ +Tile* IOMap::createTile(Item*&ground, Item* item, uint16_t x, uint16_t y, uint8_t z) { if (!ground) { return new StaticTile(x, y, z); } @@ -56,11 +55,10 @@ Tile* IOMap::createTile(Item*& ground, Item* item, uint16_t x, uint16_t y, uint8 return tile; } -bool IOMap::loadMap(Map* map, const std::string& fileName, const Position& pos, bool unload) -{ +bool IOMap::loadMap(Map* map, const std::string &fileName, const Position &pos, bool unload) { int64_t start = OTSYS_TIME(); - OTB::Loader loader{fileName, OTB::Identifier{{'O', 'T', 'B', 'M'}}}; - auto& root = loader.parseTree(); + OTB::Loader loader { fileName, OTB::Identifier { { 'O', 'T', 'B', 'M' } } }; + auto &root = loader.parseTree(); PropStream propStream; if (!loader.getProps(root, propStream)) { @@ -76,9 +74,9 @@ bool IOMap::loadMap(Map* map, const std::string& fileName, const Position& pos, uint32_t headerVersion = root_header.version; if (headerVersion <= 0) { - //In otbm version 1 the count variable after splashes/fluidcontainers and stackables - //are saved as attributes instead, this solves alot of problems with items - //that is changed (stackable/charges/fluidcontainer/splash) during an update. + // In otbm version 1 the count variable after splashes/fluidcontainers and stackables + // are saved as attributes instead, this solves alot of problems with items + // that is changed (stackable/charges/fluidcontainer/splash) during an update. setLastErrorString("This map need to be upgraded by using the latest map editor version to be able to load correctly."); return false; } @@ -102,12 +100,12 @@ bool IOMap::loadMap(Map* map, const std::string& fileName, const Position& pos, return false; } - auto& mapNode = root.children.front(); + auto &mapNode = root.children.front(); if (!parseMapDataAttributes(loader, mapNode, *map, fileName)) { return false; } - for (auto& mapDataNode : mapNode.children) { + for (auto &mapDataNode : mapNode.children) { if (mapDataNode.type == OTBM_TILE_AREA) { if (!parseTileArea(loader, mapDataNode, *map, pos, unload)) { return false; @@ -130,8 +128,7 @@ bool IOMap::loadMap(Map* map, const std::string& fileName, const Position& pos, return true; } -bool IOMap::parseMapDataAttributes(OTB::Loader& loader, const OTB::Node& mapNode, Map& map, const std::string& fileName) -{ +bool IOMap::parseMapDataAttributes(OTB::Loader &loader, const OTB::Node &mapNode, Map &map, const std::string &fileName) { PropStream propStream; if (!loader.getProps(mapNode, propStream)) { setLastErrorString("Could not read map data attributes."); @@ -189,8 +186,7 @@ bool IOMap::parseMapDataAttributes(OTB::Loader& loader, const OTB::Node& mapNode return true; } -bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Map& map, const Position& pos, bool unload) -{ +bool IOMap::parseTileArea(OTB::Loader &loader, const OTB::Node &tileAreaNode, Map &map, const Position &pos, bool unload) { PropStream propStream; if (!loader.getProps(tileAreaNode, propStream)) { setLastErrorString("Invalid map node."); @@ -209,7 +205,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma static std::map teleportMap; - for (auto& tileNode : tileAreaNode.children) { + for (auto &tileNode : tileAreaNode.children) { if (tileNode.type != OTBM_TILE && tileNode.type != OTBM_HOUSETILE) { setLastErrorString("Unknown tile node."); return false; @@ -283,7 +279,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma } uint8_t attribute; - //read tile attributes + // read tile attributes while (propStream.read(attribute)) { switch (attribute) { case OTBM_ATTR_TILE_FLAGS: { @@ -298,11 +294,9 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma if ((flags & OTBM_TILEFLAG_PROTECTIONZONE) != 0) { tileflags |= TILESTATE_PROTECTIONZONE; - } - else if ((flags & OTBM_TILEFLAG_NOPVPZONE) != 0) { + } else if ((flags & OTBM_TILEFLAG_NOPVPZONE) != 0) { tileflags |= TILESTATE_NOPVPZONE; - } - else if ((flags & OTBM_TILEFLAG_PVPZONE) != 0) { + } else if ((flags & OTBM_TILEFLAG_PVPZONE) != 0) { tileflags |= TILESTATE_PVPZONE; } @@ -320,39 +314,40 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Failed to create item."; setLastErrorString(ss.str()); SPDLOG_WARN("[IOMap::loadMap] - {}", ss.str()); - break;; + break; + ; } - if (Teleport* teleport = item->getTeleport()) { - const Position& destPos = teleport->getDestPos(); - uint64_t teleportPosition = (static_cast(x) << 24) | (y << 8) | z; - uint64_t destinationPosition = (static_cast(destPos.x) << 24) | (destPos.y << 8) | destPos.z; - teleportMap.emplace(teleportPosition, destinationPosition); - auto it = teleportMap.find(destinationPosition); - if (it != teleportMap.end()) { - SPDLOG_WARN("[IOMap::loadMap] - " - "Teleport in position: x {}, y {}, z {} " - "is leading to another teleport", x, y, z); - } - for (auto const& it2 : teleportMap) { - if (it2.second == teleportPosition) { - uint16_t fx = (it2.first >> 24) & 0xFFFF; - uint16_t fy = (it2.first >> 8) & 0xFFFF; - uint8_t fz = (it2.first) & 0xFF; - SPDLOG_WARN("[IOMap::loadMap] - " - "Teleport in position: x {}, y {}, z {} " - "is leading to another teleport", - fx, fy, static_cast(fz)); + if (Teleport* teleport = item->getTeleport()) { + const Position &destPos = teleport->getDestPos(); + uint64_t teleportPosition = (static_cast(x) << 24) | (y << 8) | z; + uint64_t destinationPosition = (static_cast(destPos.x) << 24) | (destPos.y << 8) | destPos.z; + teleportMap.emplace(teleportPosition, destinationPosition); + auto it = teleportMap.find(destinationPosition); + if (it != teleportMap.end()) { + SPDLOG_WARN("[IOMap::loadMap] - " + "Teleport in position: x {}, y {}, z {} " + "is leading to another teleport", + x, y, z); + } + for (const auto &it2 : teleportMap) { + if (it2.second == teleportPosition) { + uint16_t fx = (it2.first >> 24) & 0xFFFF; + uint16_t fy = (it2.first >> 8) & 0xFFFF; + uint8_t fz = (it2.first) & 0xFF; + SPDLOG_WARN("[IOMap::loadMap] - " + "Teleport in position: x {}, y {}, z {} " + "is leading to another teleport", + fx, fy, static_cast(fz)); + } + } } - } - - } if (isHouseTile && item->isMoveable()) { SPDLOG_WARN("[IOMap::loadMap] - " - "Moveable item with ID: {}, in house: {}, " - "at position: x {}, y {}, z {}", - item->getID(), house->getId(), x, y, z); + "Moveable item with ID: {}, in house: {}, " + "at position: x {}, y {}, z {}", + item->getID(), house->getId(), x, y, z); delete item; } else { if (item->getItemCount() <= 0) { @@ -384,7 +379,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma } } - for (auto& itemNode : tileNode.children) { + for (auto &itemNode : tileNode.children) { if (itemNode.type != OTBM_ITEM) { std::ostringstream ss; ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Unknown node type."; @@ -404,7 +399,8 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma ss << "[x:" << x << ", y:" << y << ", z:" << z << "] Failed to create item."; setLastErrorString(ss.str()); SPDLOG_WARN("[IOMap::loadMap] - {}", ss.str()); - continue;; + continue; + ; } if (!item->unserializeItemNode(loader, itemNode, stream)) { @@ -417,9 +413,9 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma if (isHouseTile && item->isMoveable()) { SPDLOG_WARN("[IOMap::loadMap] - " - "Moveable item with ID: {}, in house: {}, " - "at position: x {}, y {}, z {}", - item->getID(), house->getId(), x, y, z); + "Moveable item with ID: {}, in house: {}, " + "at position: x {}, y {}, z {}", + item->getID(), house->getId(), x, y, z); delete item; } else { if (item->getItemCount() <= 0) { @@ -453,9 +449,8 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma return true; } -bool IOMap::parseTowns(OTB::Loader& loader, const OTB::Node& townsNode, Map& map) -{ - for (auto& townNode : townsNode.children) { +bool IOMap::parseTowns(OTB::Loader &loader, const OTB::Node &townsNode, Map &map) { + for (auto &townNode : townsNode.children) { PropStream propStream; if (townNode.type != OTBM_TOWN) { setLastErrorString("Unknown town node."); @@ -498,11 +493,9 @@ bool IOMap::parseTowns(OTB::Loader& loader, const OTB::Node& townsNode, Map& map return true; } - -bool IOMap::parseWaypoints(OTB::Loader& loader, const OTB::Node& waypointsNode, Map& map) -{ +bool IOMap::parseWaypoints(OTB::Loader &loader, const OTB::Node &waypointsNode, Map &map) { PropStream propStream; - for (auto& node : waypointsNode.children) { + for (auto &node : waypointsNode.children) { if (node.type != OTBM_WAYPOINT) { setLastErrorString("Unknown waypoint node."); return false; @@ -529,4 +522,3 @@ bool IOMap::parseWaypoints(OTB::Loader& loader, const OTB::Node& waypointsNode, } return true; } - diff --git a/src/io/iomap.h b/src/io/iomap.h index c772d18a80e..1bf2662ea99 100644 --- a/src/io/iomap.h +++ b/src/io/iomap.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOMAP_H_ #define SRC_IO_IOMAP_H_ @@ -22,38 +22,37 @@ #pragma pack(1) struct OTBM_root_header { - uint32_t version; - uint16_t width; - uint16_t height; - uint32_t majorVersionItems; - uint32_t minorVersionItems; + uint32_t version; + uint16_t width; + uint16_t height; + uint32_t majorVersionItems; + uint32_t minorVersionItems; }; struct OTBM_Destination_coords { - uint16_t x; - uint16_t y; - uint8_t z; + uint16_t x; + uint16_t y; + uint8_t z; }; struct OTBM_Tile_coords { - uint8_t x; - uint8_t y; + uint8_t x; + uint8_t y; }; #pragma pack() -class IOMap -{ - static Tile* createTile(Item*& ground, Item* item, uint16_t x, uint16_t y, uint8_t z); +class IOMap { + static Tile* createTile(Item*&ground, Item* item, uint16_t x, uint16_t y, uint8_t z); public: - bool loadMap(Map* map, const std::string& identifier, const Position& pos = Position(), bool unload = false); + bool loadMap(Map* map, const std::string &identifier, const Position &pos = Position(), bool unload = false); /** - * Load main map monsters + * Load main map monsters * \param map Is the map class * \returns true if the monsters spawn map was loaded successfully - */ + */ static bool loadMonsters(Map* map) { if (map->monsterfile.empty()) { // OTBM file doesn't tell us about the monsterfile, @@ -66,10 +65,10 @@ class IOMap } /** - * Load main map npcs + * Load main map npcs * \param map Is the map class * \returns true if the npcs spawn map was loaded successfully - */ + */ static bool loadNpcs(Map* map) { if (map->npcfile.empty()) { // OTBM file doesn't tell us about the npcfile, @@ -82,10 +81,10 @@ class IOMap } /** - * Load main map houses + * Load main map houses * \param map Is the map class * \returns true if the main map houses was loaded successfully - */ + */ static bool loadHouses(Map* map) { if (map->housefile.empty()) { // OTBM file doesn't tell us about the housefile, @@ -98,10 +97,10 @@ class IOMap } /** - * Load custom map monsters + * Load custom map monsters * \param map Is the map class * \returns true if the monsters spawn map custom was loaded successfully - */ + */ static bool loadMonstersCustom(Map* map) { if (map->monsterfile.empty()) { // OTBM file doesn't tell us about the monsterfile, @@ -114,10 +113,10 @@ class IOMap } /** - * Load custom map npcs + * Load custom map npcs * \param map Is the map class * \returns true if the npcs spawn map custom was loaded successfully - */ + */ static bool loadNpcsCustom(Map* map) { if (map->npcfile.empty()) { // OTBM file doesn't tell us about the npcfile, @@ -130,10 +129,10 @@ class IOMap } /** - * Load custom map houses + * Load custom map houses * \param map Is the map class * \returns true if the map custom houses was loaded successfully - */ + */ static bool loadHousesCustom(Map* map) { if (map->housefile.empty()) { // OTBM file doesn't tell us about the housefile, @@ -145,7 +144,7 @@ class IOMap return map->housesCustom.loadHousesXML(map->housefile); } - const std::string& getLastErrorString() const { + const std::string &getLastErrorString() const { return errorString; } @@ -154,10 +153,10 @@ class IOMap } private: - bool parseMapDataAttributes(OTB::Loader& loader, const OTB::Node& mapNode, Map& map, const std::string& fileName); - bool parseWaypoints(OTB::Loader& loader, const OTB::Node& waypointsNode, Map& map); - bool parseTowns(OTB::Loader& loader, const OTB::Node& townsNode, Map& map); - bool parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Map& map, const Position& pos, bool unload); + bool parseMapDataAttributes(OTB::Loader &loader, const OTB::Node &mapNode, Map &map, const std::string &fileName); + bool parseWaypoints(OTB::Loader &loader, const OTB::Node &waypointsNode, Map &map); + bool parseTowns(OTB::Loader &loader, const OTB::Node &townsNode, Map &map); + bool parseTileArea(OTB::Loader &loader, const OTB::Node &tileAreaNode, Map &map, const Position &pos, bool unload); std::string errorString; }; diff --git a/src/io/iomapserialize.cpp b/src/io/iomapserialize.cpp index 93818f10686..f6a6c3c835b 100644 --- a/src/io/iomapserialize.cpp +++ b/src/io/iomapserialize.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,8 +13,7 @@ #include "game/game.h" #include "items/bed.h" -void IOMapSerialize::loadHouseItems(Map* map) -{ +void IOMapSerialize::loadHouseItems(Map* map) { int64_t start = OTSYS_TIME(); DBResult_ptr result = Database::getInstance().storeQuery("SELECT `data` FROM `tile_store`"); @@ -52,19 +51,18 @@ void IOMapSerialize::loadHouseItems(Map* map) SPDLOG_INFO("Loaded house items in {} seconds", (OTSYS_TIME() - start) / (1000.)); } -bool IOMapSerialize::saveHouseItems() -{ +bool IOMapSerialize::saveHouseItems() { int64_t start = OTSYS_TIME(); - Database& db = Database::getInstance(); + Database &db = Database::getInstance(); std::ostringstream query; - //Start the transaction + // Start the transaction DBTransaction transaction; if (!transaction.begin()) { return false; } - //clear old tile data + // clear old tile data if (!db.executeQuery("DELETE FROM `tile_store`")) { return false; } @@ -72,8 +70,8 @@ bool IOMapSerialize::saveHouseItems() DBInsert stmt("INSERT INTO `tile_store` (`house_id`, `data`) VALUES "); PropWriteStream stream; - for (const auto& [key, house] : g_game().map.houses.getHouses()) { - //save house items + for (const auto &[key, house] : g_game().map.houses.getHouses()) { + // save house items for (HouseTile* tile : house->getTiles()) { saveTile(stream, tile); @@ -93,14 +91,13 @@ bool IOMapSerialize::saveHouseItems() return false; } - //End the transaction + // End the transaction bool success = transaction.commit(); SPDLOG_INFO("Saved house items in {} seconds", (OTSYS_TIME() - start) / (1000.)); return success; } -bool IOMapSerialize::loadContainer(PropStream& propStream, Container* container) -{ +bool IOMapSerialize::loadContainer(PropStream &propStream, Container* container) { while (container->serializationCount > 0) { if (!loadItem(propStream, container)) { SPDLOG_WARN("Deserialization error for container item: {}", container->getID()); @@ -117,8 +114,7 @@ bool IOMapSerialize::loadContainer(PropStream& propStream, Container* container) return true; } -bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) -{ +bool IOMapSerialize::loadItem(PropStream &propStream, Cylinder* parent) { uint16_t id; if (!propStream.read(id)) { return false; @@ -129,9 +125,9 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) tile = parent->getTile(); } - const ItemType& iType = Item::items[id]; + const ItemType &iType = Item::items[id]; if (iType.moveable || !tile || iType.isCarpet()) { - //create a new item + // create a new item Item* item = Item::CreateItem(id); if (item) { if (item->unserializeAttr(propStream)) { @@ -179,7 +175,7 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) SPDLOG_WARN("Deserialization error in {}", id); } } else { - //The map changed since the last save, just read the attributes + // The map changed since the last save, just read the attributes std::unique_ptr dummy(Item::CreateItem(id)); if (dummy) { dummy->unserializeAttr(propStream); @@ -200,8 +196,7 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) return true; } -void IOMapSerialize::saveItem(PropWriteStream& stream, const Item* item) -{ +void IOMapSerialize::saveItem(PropWriteStream &stream, const Item* item) { const Container* container = item->getContainer(); // Write ID & props @@ -220,8 +215,7 @@ void IOMapSerialize::saveItem(PropWriteStream& stream, const Item* item) stream.write(0x00); // attr end } -void IOMapSerialize::saveTile(PropWriteStream& stream, const Tile* tile) -{ +void IOMapSerialize::saveTile(PropWriteStream &stream, const Tile* tile) { const TileItemVector* tileItems = tile->getItemList(); if (!tileItems) { return; @@ -230,11 +224,10 @@ void IOMapSerialize::saveTile(PropWriteStream& stream, const Tile* tile) std::forward_list items; uint16_t count = 0; for (Item* item : *tileItems) { - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; // Note that these are NEGATED, ie. these are the items that will be saved. - if (!(it.moveable || it.isCarpet() || item->getDoor() || (item->getContainer() && - !item->getContainer()->empty()) || it.canWriteText || item->getBed())) { + if (!(it.moveable || it.isCarpet() || item->getDoor() || (item->getContainer() && !item->getContainer()->empty()) || it.canWriteText || item->getBed())) { continue; } @@ -243,7 +236,7 @@ void IOMapSerialize::saveTile(PropWriteStream& stream, const Tile* tile) } if (!items.empty()) { - const Position& tilePosition = tile->getPosition(); + const Position &tilePosition = tile->getPosition(); stream.write(tilePosition.x); stream.write(tilePosition.y); stream.write(tilePosition.z); @@ -255,9 +248,8 @@ void IOMapSerialize::saveTile(PropWriteStream& stream, const Tile* tile) } } -bool IOMapSerialize::loadHouseInfo() -{ - Database& db = Database::getInstance(); +bool IOMapSerialize::loadHouseInfo() { + Database &db = Database::getInstance(); DBResult_ptr result = db.storeQuery("SELECT `id`, `owner`, `paid`, `warnings` FROM `houses`"); if (!result) { @@ -285,9 +277,8 @@ bool IOMapSerialize::loadHouseInfo() return true; } -bool IOMapSerialize::saveHouseInfo() -{ - Database& db = Database::getInstance(); +bool IOMapSerialize::saveHouseInfo() { + Database &db = Database::getInstance(); DBTransaction transaction; if (!transaction.begin()) { @@ -299,7 +290,7 @@ bool IOMapSerialize::saveHouseInfo() } std::ostringstream query; - for (const auto& [key, house] : g_game().map.houses.getHouses()) { + for (const auto &[key, house] : g_game().map.houses.getHouses()) { query << "SELECT `id` FROM `houses` WHERE `id` = " << house->getId(); DBResult_ptr result = db.storeQuery(query.str()); if (result) { @@ -316,7 +307,7 @@ bool IOMapSerialize::saveHouseInfo() DBInsert stmt("INSERT INTO `house_lists` (`house_id` , `listid` , `list`) VALUES "); - for (const auto& [key, house] : g_game().map.houses.getHouses()) { + for (const auto &[key, house] : g_game().map.houses.getHouses()) { std::string listText; if (house->getAccessList(GUEST_LIST, listText) && !listText.empty()) { query << house->getId() << ',' << GUEST_LIST << ',' << db.escapeString(listText); diff --git a/src/io/iomapserialize.h b/src/io/iomapserialize.h index fb36de1e6cf..3411c58e967 100644 --- a/src/io/iomapserialize.h +++ b/src/io/iomapserialize.h @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOMAPSERIALIZE_H_ #define SRC_IO_IOMAPSERIALIZE_H_ #include "map/map.h" -class IOMapSerialize -{ +class IOMapSerialize { public: static void loadHouseItems(Map* map); static bool saveHouseItems(); @@ -21,11 +20,11 @@ class IOMapSerialize static bool saveHouseInfo(); private: - static void saveItem(PropWriteStream& stream, const Item* item); - static void saveTile(PropWriteStream& stream, const Tile* tile); + static void saveItem(PropWriteStream &stream, const Item* item); + static void saveTile(PropWriteStream &stream, const Tile* tile); - static bool loadContainer(PropStream& propStream, Container* container); - static bool loadItem(PropStream& propStream, Cylinder* parent); + static bool loadContainer(PropStream &propStream, Container* container); + static bool loadItem(PropStream &propStream, Cylinder* parent); }; -#endif // SRC_IO_IOMAPSERIALIZE_H_ +#endif // SRC_IO_IOMAPSERIALIZE_H_ diff --git a/src/io/iomarket.cpp b/src/io/iomarket.cpp index 95145e20b3a..79401e9596d 100644 --- a/src/io/iomarket.cpp +++ b/src/io/iomarket.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -25,8 +25,7 @@ uint8_t IOMarket::getTierFromDatabaseTable(const std::string &string) { return tier; } -MarketOfferList IOMarket::getActiveOffers(MarketAction_t action, uint16_t itemId, uint8_t tier) -{ +MarketOfferList IOMarket::getActiveOffers(MarketAction_t action, uint16_t itemId, uint8_t tier) { MarketOfferList offerList; std::ostringstream query; @@ -56,8 +55,7 @@ MarketOfferList IOMarket::getActiveOffers(MarketAction_t action, uint16_t itemId return offerList; } -MarketOfferList IOMarket::getOwnOffers(MarketAction_t action, uint32_t playerId) -{ +MarketOfferList IOMarket::getOwnOffers(MarketAction_t action, uint32_t playerId) { MarketOfferList offerList; const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION); @@ -83,8 +81,7 @@ MarketOfferList IOMarket::getOwnOffers(MarketAction_t action, uint32_t playerId) return offerList; } -HistoryMarketOfferList IOMarket::getOwnHistory(MarketAction_t action, uint32_t playerId) -{ +HistoryMarketOfferList IOMarket::getOwnHistory(MarketAction_t action, uint32_t playerId) { HistoryMarketOfferList offerList; std::ostringstream query; @@ -115,8 +112,7 @@ HistoryMarketOfferList IOMarket::getOwnHistory(MarketAction_t action, uint32_t p return offerList; } -void IOMarket::processExpiredOffers(DBResult_ptr result, bool) -{ +void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { if (!result) { return; } @@ -130,7 +126,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) const uint16_t amount = result->getNumber("amount"); auto tier = getTierFromDatabaseTable(result->getString("tier")); if (result->getNumber("sale") == 1) { - const ItemType& itemType = Item::items[result->getNumber("itemtype")]; + const ItemType &itemType = Item::items[result->getNumber("itemtype")]; if (itemType.id == 0) { continue; } @@ -149,8 +145,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) while (tmpAmount > 0) { uint16_t stackCount = std::min(100, tmpAmount); Item* item = Item::CreateItem(itemType.id, stackCount); - if (g_game().internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) - { + if (g_game().internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[{}] Ocurred an error to add item with id {} to player {}", __FUNCTION__, itemType.id, player->getName()); delete item; break; @@ -200,8 +195,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) } while (result->next()); } -void IOMarket::checkExpiredOffers() -{ +void IOMarket::checkExpiredOffers() { const time_t lastExpireDate = getTimeNow() - g_configManager().getNumber(MARKET_OFFER_DURATION); std::ostringstream query; @@ -216,8 +210,7 @@ void IOMarket::checkExpiredOffers() g_scheduler().addEvent(createSchedulerTask(checkExpiredMarketOffersEachMinutes * 60 * 1000, IOMarket::checkExpiredOffers)); } -uint32_t IOMarket::getPlayerOfferCount(uint32_t playerId) -{ +uint32_t IOMarket::getPlayerOfferCount(uint32_t playerId) { std::ostringstream query; query << "SELECT COUNT(*) AS `count` FROM `market_offers` WHERE `player_id` = " << playerId; @@ -228,8 +221,7 @@ uint32_t IOMarket::getPlayerOfferCount(uint32_t playerId) return result->getNumber("count"); } -MarketOfferEx IOMarket::getOfferByCounter(uint32_t timestamp, uint16_t counter) -{ +MarketOfferEx IOMarket::getOfferByCounter(uint32_t timestamp, uint16_t counter) { MarketOfferEx offer; const int32_t created = timestamp - g_configManager().getNumber(MARKET_OFFER_DURATION); @@ -260,39 +252,34 @@ MarketOfferEx IOMarket::getOfferByCounter(uint32_t timestamp, uint16_t counter) return offer; } -void IOMarket::createOffer(uint32_t playerId, MarketAction_t action, uint32_t itemId, uint16_t amount, uint64_t price, uint8_t tier, bool anonymous) -{ +void IOMarket::createOffer(uint32_t playerId, MarketAction_t action, uint32_t itemId, uint16_t amount, uint64_t price, uint8_t tier, bool anonymous) { std::ostringstream query; query << "INSERT INTO `market_offers` (`player_id`, `sale`, `itemtype`, `amount`, `created`, `anonymous`, `price`, `tier`) VALUES (" << playerId << ',' << action << ',' << itemId << ',' << amount << ',' << getTimeNow() << ',' << anonymous << ',' << price << ',' << std::to_string(tier) << ')'; Database::getInstance().executeQuery(query.str()); } -void IOMarket::acceptOffer(uint32_t offerId, uint16_t amount) -{ +void IOMarket::acceptOffer(uint32_t offerId, uint16_t amount) { std::ostringstream query; query << "UPDATE `market_offers` SET `amount` = `amount` - " << amount << " WHERE `id` = " << offerId; Database::getInstance().executeQuery(query.str()); } -void IOMarket::deleteOffer(uint32_t offerId) -{ +void IOMarket::deleteOffer(uint32_t offerId) { std::ostringstream query; query << "DELETE FROM `market_offers` WHERE `id` = " << offerId; Database::getInstance().executeQuery(query.str()); } -void IOMarket::appendHistory(uint32_t playerId, MarketAction_t type, uint16_t itemId, uint16_t amount, uint64_t price, time_t timestamp, uint8_t tier, MarketOfferState_t state) -{ +void IOMarket::appendHistory(uint32_t playerId, MarketAction_t type, uint16_t itemId, uint16_t amount, uint64_t price, time_t timestamp, uint8_t tier, MarketOfferState_t state) { std::ostringstream query; query << "INSERT INTO `market_history` (`player_id`, `sale`, `itemtype`, `amount`, `price`, `expires_at`, `inserted`, `state`, `tier`) VALUES (" - << playerId << ',' << type << ',' << itemId << ',' << amount << ',' << price << ',' - << timestamp << ',' << getTimeNow() << ',' << state << ',' << std::to_string(tier) << ')'; + << playerId << ',' << type << ',' << itemId << ',' << amount << ',' << price << ',' + << timestamp << ',' << getTimeNow() << ',' << state << ',' << std::to_string(tier) << ')'; g_databaseTasks().addTask(query.str()); } -bool IOMarket::moveOfferToHistory(uint32_t offerId, MarketOfferState_t state) -{ - Database& db = Database::getInstance(); +bool IOMarket::moveOfferToHistory(uint32_t offerId, MarketOfferState_t state) { + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `player_id`, `sale`, `itemtype`, `amount`, `price`, `created`, `tier` FROM `market_offers` WHERE `id` = " << offerId; @@ -315,12 +302,12 @@ bool IOMarket::moveOfferToHistory(uint32_t offerId, MarketOfferState_t state) result->getNumber("amount"), result->getNumber("price"), getTimeNow(), - getTierFromDatabaseTable(result->getString("tier")), state); + getTierFromDatabaseTable(result->getString("tier")), state + ); return true; } -void IOMarket::updateStatistics() -{ +void IOMarket::updateStatistics() { std::ostringstream query; query << "SELECT `sale` AS `sale`, `itemtype` AS `itemtype`, COUNT(`price`) AS `num`, MIN(`price`) AS `min`, MAX(`price`) AS `max`, SUM(`price`) AS `sum`, `tier` AS `tier` FROM `market_history` WHERE `state` = " << OFFERSTATE_ACCEPTED << " GROUP BY `itemtype`, `sale`, `tier`"; DBResult_ptr result = Database::getInstance().storeQuery(query.str()); diff --git a/src/io/iomarket.h b/src/io/iomarket.h index 9b34786d7e4..b02779bd041 100644 --- a/src/io/iomarket.h +++ b/src/io/iomarket.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOMARKET_H_ #define SRC_IO_IOMARKET_H_ @@ -13,11 +13,11 @@ #include "database/database.h" #include "declarations.hpp" -class IOMarket -{ - using StatisticsMap = std::map>; +class IOMarket { + using StatisticsMap = std::map>; + public: - static IOMarket& getInstance() { + static IOMarket &getInstance() { static IOMarket instance; return instance; } @@ -58,4 +58,4 @@ class IOMarket StatisticsMap saleStatistics; }; -#endif // SRC_IO_IOMARKET_H_ +#endif // SRC_IO_IOMARKET_H_ diff --git a/src/io/ioprey.cpp b/src/io/ioprey.cpp index 47aca27fd2b..3ff95bf1059 100644 --- a/src/io/ioprey.cpp +++ b/src/io/ioprey.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,15 +18,14 @@ // Prey class PreySlot::PreySlot(PreySlot_t id) : - id(id) { - eraseBonus(); - reloadBonusValue(); - reloadBonusType(); - freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(PREY_FREE_REROLL_TIME) * 1000; + id(id) { + eraseBonus(); + reloadBonusValue(); + reloadBonusType(); + freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(PREY_FREE_REROLL_TIME) * 1000; } -void PreySlot::reloadBonusType() -{ +void PreySlot::reloadBonusType() { if (bonusRarity == 10) { PreyBonus_t bonus_tmp = bonus; while (bonus_tmp == bonus) { @@ -38,8 +37,7 @@ void PreySlot::reloadBonusType() bonus = static_cast(uniform_random(PreyBonus_First, PreyBonus_Last)); } -void PreySlot::reloadBonusValue() -{ +void PreySlot::reloadBonusValue() { if (bonusRarity >= 9) { bonusRarity = 10; } else { @@ -55,8 +53,7 @@ void PreySlot::reloadBonusValue() } } -void PreySlot::reloadMonsterGrid(std::vector blackList, uint32_t level) -{ +void PreySlot::reloadMonsterGrid(std::vector blackList, uint32_t level) { raceIdList.clear(); if (!g_configManager().getBoolean(PREY_ENABLED)) { @@ -133,12 +130,11 @@ void PreySlot::reloadMonsterGrid(std::vector blackList, uint32_t level // Task hunting class TaskHuntingSlot::TaskHuntingSlot(PreySlot_t id) : - id(id) { + id(id) { freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_FREE_REROLL_TIME) * 1000; } -void TaskHuntingSlot::reloadMonsterGrid(std::vector blackList, uint32_t level) -{ +void TaskHuntingSlot::reloadMonsterGrid(std::vector blackList, uint32_t level) { raceIdList.clear(); if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { @@ -213,8 +209,7 @@ void TaskHuntingSlot::reloadMonsterGrid(std::vector blackList, uint32_ } } -void TaskHuntingSlot::reloadReward() -{ +void TaskHuntingSlot::reloadReward() { if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { return; } @@ -251,8 +246,7 @@ void TaskHuntingSlot::reloadReward() } // Prey/Task hunting global class -void IOPrey::CheckPlayerPreys(Player* player, uint8_t amount) const -{ +void IOPrey::CheckPlayerPreys(Player* player, uint8_t amount) const { if (!player) { return; } @@ -295,13 +289,7 @@ void IOPrey::CheckPlayerPreys(Player* player, uint8_t amount) const } } -void IOPrey::ParsePreyAction(Player* player, - PreySlot_t slotId, - PreyAction_t action, - PreyOption_t option, - int8_t index, - uint16_t raceId) const -{ +void IOPrey::ParsePreyAction(Player* player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const { PreySlot* slot = player->getPreySlotById(slotId); if (!slot || slot->state == PreyDataState_Locked) { player->sendMessageDialog("To unlock this prey slot first you must buy it on store."); @@ -401,12 +389,7 @@ void IOPrey::ParsePreyAction(Player* player, player->reloadPreySlot(slotId); } -void IOPrey::ParseTaskHuntingAction(Player* player, - PreySlot_t slotId, - PreyTaskAction_t action, - bool upgrade, - uint16_t raceId) const -{ +void IOPrey::ParseTaskHuntingAction(Player* player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const { TaskHuntingSlot* slot = player->getTaskHuntingSlotById(slotId); if (!slot || slot->state == PreyTaskDataState_Locked) { player->sendMessageDialog("To unlock this task hunting slot first you must buy it on store."); @@ -539,8 +522,7 @@ void IOPrey::ParseTaskHuntingAction(Player* player, player->reloadTaskSlot(slotId); } -void IOPrey::InitializeTaskHuntOptions() -{ +void IOPrey::InitializeTaskHuntOptions() { if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { return; } @@ -554,7 +536,7 @@ void IOPrey::InitializeTaskHuntOptions() uint8_t limitOfStars = 5; uint16_t kills = killStage; NetworkMessage msg; - for (uint8_t difficulty = PreyTaskDifficult_First; difficulty <= PreyTaskDifficult_Last; ++difficulty) { // Difficulties of creatures on bestiary. + for (uint8_t difficulty = PreyTaskDifficult_First; difficulty <= PreyTaskDifficult_Last; ++difficulty) { // Difficulties of creatures on bestiary. auto reward = static_cast(std::round((10 * kills) / killStage)); // Amount of task stars on task hunting for (uint8_t star = 1; star <= limitOfStars; ++star) { @@ -579,8 +561,7 @@ void IOPrey::InitializeTaskHuntOptions() msg.addByte(0xBA); std::map bestiaryList = g_game().getBestiaryList(); msg.add(static_cast(bestiaryList.size())); - std::for_each(bestiaryList.begin(), bestiaryList.end(), [&msg](auto& mType) - { + std::for_each(bestiaryList.begin(), bestiaryList.end(), [&msg](auto &mType) { const MonsterType* mtype = g_monsters().getMonsterType(mType.second); if (!mtype) { return; @@ -597,8 +578,7 @@ void IOPrey::InitializeTaskHuntOptions() }); msg.addByte(static_cast(taskOption.size())); - std::for_each(taskOption.begin(), taskOption.end(), [&msg](const TaskHuntingOption* option) - { + std::for_each(taskOption.begin(), taskOption.end(), [&msg](const TaskHuntingOption* option) { msg.addByte(static_cast(option->difficult)); msg.addByte(option->rarity); msg.add(option->firstKills); @@ -609,8 +589,7 @@ void IOPrey::InitializeTaskHuntOptions() baseDataMessage = msg; } -TaskHuntingOption* IOPrey::GetTaskRewardOption(const TaskHuntingSlot* slot) const -{ +TaskHuntingOption* IOPrey::GetTaskRewardOption(const TaskHuntingSlot* slot) const { if (!slot) { return nullptr; } @@ -631,7 +610,8 @@ TaskHuntingOption* IOPrey::GetTaskRewardOption(const TaskHuntingSlot* slot) cons if (auto it = std::find_if(taskOption.begin(), taskOption.end(), [difficult, slot](const TaskHuntingOption* optionIt) { return optionIt->difficult == difficult && optionIt->rarity == slot->rarity; - }); it != taskOption.end()) { + }); + it != taskOption.end()) { return *it; } diff --git a/src/io/ioprey.h b/src/io/ioprey.h index 235a30a36e9..b838108633b 100644 --- a/src/io/ioprey.h +++ b/src/io/ioprey.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_IO_IOPREY_H_ #define SRC_IO_IOPREY_H_ @@ -42,7 +42,7 @@ enum PreyBonus_t : uint8_t { PreyBonus_Last = PreyBonus_Loot }; -enum PreyOption_t : uint8_t { +enum PreyOption_t : uint8_t { PreyOption_None = 0, PreyOption_AutomaticReroll = 1, PreyOption_Locked = 2 @@ -87,163 +87,159 @@ enum PreyTaskDifficult_t : uint8_t { class NetworkMessage; -class PreySlot -{ - public: - PreySlot() = default; - explicit PreySlot(PreySlot_t id); - virtual ~PreySlot() = default; - - bool isOccupied() const { - return selectedRaceId != 0 && bonusTimeLeft > 0; - } - - bool canSelect() const { - return (state == PreyDataState_Selection || state == PreyDataState_SelectionChangeMonster || state == PreyDataState_ListSelection || state == PreyDataState_Inactive); - } - - void eraseBonus(bool maintainBonus = false) { - if (!maintainBonus) { - bonus = PreyBonus_None; - bonusPercentage = 5; - bonusRarity = 1; +class PreySlot { + public: + PreySlot() = default; + explicit PreySlot(PreySlot_t id); + virtual ~PreySlot() = default; + + bool isOccupied() const { + return selectedRaceId != 0 && bonusTimeLeft > 0; } - state = PreyDataState_Selection; - option = PreyOption_None; - selectedRaceId = 0; - bonusTimeLeft = 0; - } - void removeMonsterType(uint16_t raceId) { - raceIdList.erase(std::remove(raceIdList.begin(), raceIdList.end(), raceId), raceIdList.end()); - } + bool canSelect() const { + return (state == PreyDataState_Selection || state == PreyDataState_SelectionChangeMonster || state == PreyDataState_ListSelection || state == PreyDataState_Inactive); + } - void reloadBonusType(); - void reloadBonusValue(); - void reloadMonsterGrid(std::vector blackList, uint32_t level); + void eraseBonus(bool maintainBonus = false) { + if (!maintainBonus) { + bonus = PreyBonus_None; + bonusPercentage = 5; + bonusRarity = 1; + } + state = PreyDataState_Selection; + option = PreyOption_None; + selectedRaceId = 0; + bonusTimeLeft = 0; + } - PreySlot_t id = PreySlot_First; - PreyBonus_t bonus = PreyBonus_None; - PreyDataState_t state = PreyDataState_Locked; - PreyOption_t option = PreyOption_None; + void removeMonsterType(uint16_t raceId) { + raceIdList.erase(std::remove(raceIdList.begin(), raceIdList.end(), raceId), raceIdList.end()); + } - std::vector raceIdList; + void reloadBonusType(); + void reloadBonusValue(); + void reloadMonsterGrid(std::vector blackList, uint32_t level); - uint8_t bonusRarity = 1; + PreySlot_t id = PreySlot_First; + PreyBonus_t bonus = PreyBonus_None; + PreyDataState_t state = PreyDataState_Locked; + PreyOption_t option = PreyOption_None; - uint16_t selectedRaceId = 0; - uint16_t bonusPercentage = 0; - uint16_t bonusTimeLeft = 0; + std::vector raceIdList; - int64_t freeRerollTimeStamp = 0; + uint8_t bonusRarity = 1; + + uint16_t selectedRaceId = 0; + uint16_t bonusPercentage = 0; + uint16_t bonusTimeLeft = 0; + + int64_t freeRerollTimeStamp = 0; }; -class TaskHuntingSlot -{ - public: - TaskHuntingSlot() = default; - explicit TaskHuntingSlot(PreySlot_t id); - virtual ~TaskHuntingSlot() = default; +class TaskHuntingSlot { + public: + TaskHuntingSlot() = default; + explicit TaskHuntingSlot(PreySlot_t id); + virtual ~TaskHuntingSlot() = default; - bool isOccupied() const { - return selectedRaceId != 0; - } + bool isOccupied() const { + return selectedRaceId != 0; + } - bool canSelect() const { - return (state == PreyTaskDataState_Selection || state == PreyTaskDataState_ListSelection); - } + bool canSelect() const { + return (state == PreyTaskDataState_Selection || state == PreyTaskDataState_ListSelection); + } - void eraseTask() { - upgrade = false; - state = PreyTaskDataState_Selection; - selectedRaceId = 0; - currentKills = 0; - rarity = 1; - } + void eraseTask() { + upgrade = false; + state = PreyTaskDataState_Selection; + selectedRaceId = 0; + currentKills = 0; + rarity = 1; + } - void removeMonsterType(uint16_t raceId) { - raceIdList.erase(std::remove(raceIdList.begin(), raceIdList.end(), raceId), raceIdList.end()); - } + void removeMonsterType(uint16_t raceId) { + raceIdList.erase(std::remove(raceIdList.begin(), raceIdList.end(), raceId), raceIdList.end()); + } - bool isCreatureOnList(uint16_t raceId) const { - auto it = std::find_if(raceIdList.begin(), raceIdList.end(), [raceId](uint16_t it) { - return it == raceId; - }); + bool isCreatureOnList(uint16_t raceId) const { + auto it = std::find_if(raceIdList.begin(), raceIdList.end(), [raceId](uint16_t it) { + return it == raceId; + }); - return it != raceIdList.end(); - } + return it != raceIdList.end(); + } - void reloadReward(); - void reloadMonsterGrid(std::vector blackList, uint32_t level); + void reloadReward(); + void reloadMonsterGrid(std::vector blackList, uint32_t level); - PreySlot_t id = PreySlot_First; - PreyTaskDataState_t state = PreyTaskDataState_Inactive; + PreySlot_t id = PreySlot_First; + PreyTaskDataState_t state = PreyTaskDataState_Inactive; - bool upgrade = false; + bool upgrade = false; - uint8_t rarity = 1; + uint8_t rarity = 1; - uint16_t selectedRaceId = 0; - uint16_t currentKills = 0; + uint16_t selectedRaceId = 0; + uint16_t currentKills = 0; - int64_t disabledUntilTimeStamp = 0; - int64_t freeRerollTimeStamp = 0; + int64_t disabledUntilTimeStamp = 0; + int64_t freeRerollTimeStamp = 0; - std::vector raceIdList; + std::vector raceIdList; }; -class TaskHuntingOption -{ - public: - TaskHuntingOption() = default; - virtual ~TaskHuntingOption() = default; +class TaskHuntingOption { + public: + TaskHuntingOption() = default; + virtual ~TaskHuntingOption() = default; - PreyTaskDifficult_t difficult = PreyTaskDifficult_None; - uint8_t rarity = 1; + PreyTaskDifficult_t difficult = PreyTaskDifficult_None; + uint8_t rarity = 1; - uint16_t firstKills = 0; - uint16_t secondKills = 0; + uint16_t firstKills = 0; + uint16_t secondKills = 0; - uint16_t firstReward = 0; - uint16_t secondReward = 0; + uint16_t firstReward = 0; + uint16_t secondReward = 0; }; -class IOPrey -{ -public: - IOPrey() = default; +class IOPrey { + public: + IOPrey() = default; - // non-copyable - IOPrey(IOPrey const&) = delete; - void operator=(IOPrey const&) = delete; + // non-copyable + IOPrey(const IOPrey &) = delete; + void operator=(const IOPrey &) = delete; - static IOPrey& getInstance() { - // Guaranteed to be destroyed - static IOPrey instance; - // Instantiated on first use - return instance; - } + static IOPrey &getInstance() { + // Guaranteed to be destroyed + static IOPrey instance; + // Instantiated on first use + return instance; + } - void CheckPlayerPreys(Player* player, uint8_t amount) const; - void ParsePreyAction(Player* player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const; + void CheckPlayerPreys(Player* player, uint8_t amount) const; + void ParsePreyAction(Player* player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const; - void ParseTaskHuntingAction(Player* player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const; + void ParseTaskHuntingAction(Player* player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const; - void InitializeTaskHuntOptions(); - TaskHuntingOption* GetTaskRewardOption(const TaskHuntingSlot* slot) const; + void InitializeTaskHuntOptions(); + TaskHuntingOption* GetTaskRewardOption(const TaskHuntingSlot* slot) const; - std::vector GetTaskOptions() const { - return taskOption; - } + std::vector GetTaskOptions() const { + return taskOption; + } - NetworkMessage GetTaskHuntingBaseDate() const { - return baseDataMessage; - } + NetworkMessage GetTaskHuntingBaseDate() const { + return baseDataMessage; + } - NetworkMessage baseDataMessage; - std::vector taskOption; + NetworkMessage baseDataMessage; + std::vector taskOption; }; constexpr auto g_ioprey = &IOPrey::getInstance; -#endif // SRC_IO_IOPREY_H_ +#endif // SRC_IO_IOPREY_H_ diff --git a/src/items/bed.cpp b/src/items/bed.cpp index aab6930b413..ae271dfc601 100644 --- a/src/items/bed.cpp +++ b/src/items/bed.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,13 +14,12 @@ #include "io/iologindata.h" #include "game/scheduling/scheduler.h" -BedItem::BedItem(uint16_t id) : Item(id) -{ +BedItem::BedItem(uint16_t id) : + Item(id) { internalRemoveSleeper(); } -Attr_ReadValue BedItem::readAttr(AttrTypes_t attr, PropStream& propStream) -{ +Attr_ReadValue BedItem::readAttr(AttrTypes_t attr, PropStream &propStream) { switch (attr) { case ATTR_SLEEPERGUID: { uint32_t guid; @@ -55,8 +54,7 @@ Attr_ReadValue BedItem::readAttr(AttrTypes_t attr, PropStream& propStream) return Item::readAttr(attr, propStream); } -void BedItem::serializeAttr(PropWriteStream& propWriteStream) const -{ +void BedItem::serializeAttr(PropWriteStream &propWriteStream) const { if (sleeperGUID != 0) { propWriteStream.write(ATTR_SLEEPERGUID); propWriteStream.write(sleeperGUID); @@ -69,8 +67,7 @@ void BedItem::serializeAttr(PropWriteStream& propWriteStream) const } } -BedItem* BedItem::getNextBedItem() const -{ +BedItem* BedItem::getNextBedItem() const { Direction dir = Item::items[id].bedPartnerDir; Position targetPos = getNextPosition(dir, getPosition()); @@ -81,8 +78,7 @@ BedItem* BedItem::getNextBedItem() const return tile->getBedItem(); } -bool BedItem::canUse(Player* player) -{ +bool BedItem::canUse(Player* player) { if ((player == nullptr) || (house == nullptr) || !player->isPremium()) { return false; } @@ -106,8 +102,7 @@ bool BedItem::canUse(Player* player) return true; } -bool BedItem::trySleep(Player* player) -{ +bool BedItem::trySleep(Player* player) { if (!house || player->isRemoved()) { return false; } @@ -123,8 +118,7 @@ bool BedItem::trySleep(Player* player) return true; } -bool BedItem::sleep(Player* player) -{ +bool BedItem::sleep(Player* player) { if (house == nullptr) { return false; } @@ -163,8 +157,7 @@ bool BedItem::sleep(Player* player) return true; } -void BedItem::wakeUp(Player* player) -{ +void BedItem::wakeUp(Player* player) { if (house == nullptr) { return; } @@ -202,8 +195,7 @@ void BedItem::wakeUp(Player* player) } } -void BedItem::regeneratePlayer(Player* player) const -{ +void BedItem::regeneratePlayer(Player* player) const { const uint32_t sleptTime = time(nullptr) - sleepStart; Condition* condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); @@ -229,17 +221,16 @@ void BedItem::regeneratePlayer(Player* player) const player->changeSoul(soulRegen); } -void BedItem::updateAppearance(const Player* player) -{ - const ItemType& it = Item::items[id]; +void BedItem::updateAppearance(const Player* player) { + const ItemType &it = Item::items[id]; if (it.type == ITEM_TYPE_BED) { if ((player != nullptr) && it.transformToOnUse[player->getSex()] != 0) { - const ItemType& newType = Item::items[it.transformToOnUse[player->getSex()]]; + const ItemType &newType = Item::items[it.transformToOnUse[player->getSex()]]; if (newType.type == ITEM_TYPE_BED) { g_game().transformItem(this, it.transformToOnUse[player->getSex()]); } } else if (it.transformToFree != 0) { - const ItemType& newType = Item::items[it.transformToFree]; + const ItemType &newType = Item::items[it.transformToFree]; if (newType.type == ITEM_TYPE_BED) { g_game().transformItem(this, it.transformToFree); } @@ -247,8 +238,7 @@ void BedItem::updateAppearance(const Player* player) } } -void BedItem::internalSetSleeper(const Player* player) -{ +void BedItem::internalSetSleeper(const Player* player) { std::string desc_str = player->getName() + " is sleeping there."; sleeperGUID = player->getGUID(); @@ -256,8 +246,7 @@ void BedItem::internalSetSleeper(const Player* player) setAttribute(ItemAttribute_t::DESCRIPTION, desc_str); } -void BedItem::internalRemoveSleeper() -{ +void BedItem::internalRemoveSleeper() { sleeperGUID = 0; sleepStart = 0; setAttribute(ItemAttribute_t::DESCRIPTION, "Nobody is sleeping there."); diff --git a/src/items/bed.h b/src/items/bed.h index 6810b4d9c54..6e789ed72b4 100644 --- a/src/items/bed.h +++ b/src/items/bed.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_BED_H_ #define SRC_ITEMS_BED_H_ @@ -15,8 +15,7 @@ class House; class Player; -class BedItem final : public Item -{ +class BedItem final : public Item { public: explicit BedItem(uint16_t id); @@ -27,8 +26,8 @@ class BedItem final : public Item return this; } - Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; - void serializeAttr(PropWriteStream& propWriteStream) const override; + Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream) override; + void serializeAttr(PropWriteStream &propWriteStream) const override; bool canRemove() const override { return house == nullptr; @@ -61,4 +60,4 @@ class BedItem final : public Item uint32_t sleeperGUID; }; -#endif // SRC_ITEMS_BED_H_ +#endif // SRC_ITEMS_BED_H_ diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index c9b01bbd18b..755d3fa92ae 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -25,11 +25,10 @@ Container::Container(uint16_t initType, uint16_t initSize, bool initUnlocked /*= Item(initType), maxSize(initSize), unlocked(initUnlocked), - pagination(initPagination) -{} + pagination(initPagination) { } -Container::Container(Tile* tile) : Container(ITEM_BROWSEFIELD, 30, false, true) -{ +Container::Container(Tile* tile) : + Container(ITEM_BROWSEFIELD, 30, false, true) { TileItemVector* itemVector = tile->getItemList(); if (itemVector) { for (Item* item : *itemVector) { @@ -43,8 +42,7 @@ Container::Container(Tile* tile) : Container(ITEM_BROWSEFIELD, 30, false, true) setParent(tile); } -Container::~Container() -{ +Container::~Container() { if (getID() == ITEM_BROWSEFIELD) { g_game().browseFields.erase(getTile()); @@ -59,8 +57,7 @@ Container::~Container() } } -Item* Container::clone() const -{ +Item* Container::clone() const { Container* clone = static_cast(Item::clone()); for (Item* item : itemlist) { clone->addItem(item->clone()); @@ -69,8 +66,7 @@ Item* Container::clone() const return clone; } -Container* Container::getParentContainer() -{ +Container* Container::getParentContainer() { Thing* thing = getParent(); if (!thing) { return nullptr; @@ -78,8 +74,7 @@ Container* Container::getParentContainer() return thing->getContainer(); } -Container* Container::getTopParentContainer() const -{ +Container* Container::getTopParentContainer() const { Thing* thing = getParent(); Thing* prevThing = const_cast(this); if (!thing) { @@ -98,19 +93,16 @@ Container* Container::getTopParentContainer() const return thing->getContainer(); } -bool Container::hasParent() const -{ +bool Container::hasParent() const { return getID() != ITEM_BROWSEFIELD && dynamic_cast(getParent()) == nullptr; } -void Container::addItem(Item* item) -{ +void Container::addItem(Item* item) { itemlist.push_back(item); item->setParent(this); } -StashContainerList Container::getStowableItems() const -{ +StashContainerList Container::getStowableItems() const { StashContainerList toReturnList; for (auto item : itemlist) { if (item->getContainer() != NULL) { @@ -127,8 +119,7 @@ StashContainerList Container::getStowableItems() const return toReturnList; } -Attr_ReadValue Container::readAttr(AttrTypes_t attr, PropStream& propStream) -{ +Attr_ReadValue Container::readAttr(AttrTypes_t attr, PropStream &propStream) { if (attr == ATTR_CONTAINER_ITEMS) { if (!propStream.read(serializationCount)) { return ATTR_READ_ERROR; @@ -138,15 +129,14 @@ Attr_ReadValue Container::readAttr(AttrTypes_t attr, PropStream& propStream) return Item::readAttr(attr, propStream); } -bool Container::unserializeItemNode(OTB::Loader& loader, const OTB::Node& node, PropStream& propStream) -{ +bool Container::unserializeItemNode(OTB::Loader &loader, const OTB::Node &node, PropStream &propStream) { bool ret = Item::unserializeItemNode(loader, node, propStream); if (!ret) { return false; } - for (auto& itemNode : node.children) { - //load container items + for (auto &itemNode : node.children) { + // load container items if (itemNode.type != OTBM_ITEM) { // unknown type return false; @@ -172,8 +162,7 @@ bool Container::unserializeItemNode(OTB::Loader& loader, const OTB::Node& node, return true; } -bool Container::countsToLootAnalyzerBalance() -{ +bool Container::countsToLootAnalyzerBalance() { if (isCorpse()) { return true; } @@ -185,28 +174,24 @@ bool Container::countsToLootAnalyzerBalance() return false; } -void Container::updateItemWeight(int32_t diff) -{ +void Container::updateItemWeight(int32_t diff) { totalWeight += diff; - Container* parentContainer = this; // credits: SaiyansKing + Container* parentContainer = this; // credits: SaiyansKing while ((parentContainer = parentContainer->getParentContainer()) != nullptr) { parentContainer->totalWeight += diff; } } -uint32_t Container::getWeight() const -{ +uint32_t Container::getWeight() const { return Item::getWeight() + totalWeight; } -std::string Container::getContentDescription() const -{ +std::string Container::getContentDescription() const { std::ostringstream os; return getContentDescription(os).str(); } -std::ostringstream& Container::getContentDescription(std::ostringstream& os) const -{ +std::ostringstream &Container::getContentDescription(std::ostringstream &os) const { bool firstitem = true; for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { Item* item = *it; @@ -231,16 +216,14 @@ std::ostringstream& Container::getContentDescription(std::ostringstream& os) con return os; } -Item* Container::getItemByIndex(size_t index) const -{ +Item* Container::getItemByIndex(size_t index) const { if (index >= size()) { return nullptr; } return itemlist[index]; } -uint32_t Container::getItemHoldingCount() const -{ +uint32_t Container::getItemHoldingCount() const { uint32_t counter = 0; for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { ++counter; @@ -248,8 +231,7 @@ uint32_t Container::getItemHoldingCount() const return counter; } -uint32_t Container::getContainerHoldingCount() const -{ +uint32_t Container::getContainerHoldingCount() const { uint32_t counter = 0; for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { if ((*it)->getContainer()) { @@ -259,8 +241,7 @@ uint32_t Container::getContainerHoldingCount() const return counter; } -bool Container::isHoldingItem(const Item* item) const -{ +bool Container::isHoldingItem(const Item* item) const { for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { if (*it == item) { return true; @@ -269,61 +250,56 @@ bool Container::isHoldingItem(const Item* item) const return false; } -void Container::onAddContainerItem(Item* item) -{ +void Container::onAddContainerItem(Item* item) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, getPosition(), false, true, 2, 2, 2, 2); - //send to client + // send to client for (Creature* spectator : spectators) { spectator->getPlayer()->sendAddContainerItem(this, item); } - //event methods + // event methods for (Creature* spectator : spectators) { spectator->getPlayer()->onAddContainerItem(item); } } -void Container::onUpdateContainerItem(uint32_t index, Item* oldItem, Item* newItem) -{ +void Container::onUpdateContainerItem(uint32_t index, Item* oldItem, Item* newItem) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, getPosition(), false, true, 2, 2, 2, 2); - //send to client + // send to client for (Creature* spectator : spectators) { spectator->getPlayer()->sendUpdateContainerItem(this, index, newItem); } - //event methods + // event methods for (Creature* spectator : spectators) { spectator->getPlayer()->onUpdateContainerItem(this, oldItem, newItem); } } -void Container::onRemoveContainerItem(uint32_t index, Item* item) -{ +void Container::onRemoveContainerItem(uint32_t index, Item* item) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, getPosition(), false, true, 2, 2, 2, 2); - //send change to client + // send change to client for (Creature* spectator : spectators) { spectator->getPlayer()->sendRemoveContainerItem(this, index); } - //event methods + // event methods for (Creature* spectator : spectators) { spectator->getPlayer()->onRemoveContainerItem(this, item); } } -ReturnValue Container::queryAdd(int32_t addIndex, const Thing& addThing, uint32_t addCount, - uint32_t flags, Creature* actor/* = nullptr*/) const -{ +ReturnValue Container::queryAdd(int32_t addIndex, const Thing &addThing, uint32_t addCount, uint32_t flags, Creature* actor /* = nullptr*/) const { bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); if (childIsOwner) { - //a child container is querying, since we are the top container (not carried by a player) - //just return with no error. + // a child container is querying, since we are the top container (not carried by a player) + // just return with no error. return RETURNVALUE_NOERROR; } @@ -403,9 +379,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const Thing& addThing, uint32_ } } -ReturnValue Container::queryMaxCount(int32_t index, const Thing& thing, uint32_t count, - uint32_t& maxQueryCount, uint32_t flags) const -{ +ReturnValue Container::queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const { const Item* item = thing.getItem(); if (item == nullptr) { maxQueryCount = 0; @@ -423,7 +397,7 @@ ReturnValue Container::queryMaxCount(int32_t index, const Thing& thing, uint32_t uint32_t n = 0; if (index == INDEX_WHEREEVER) { - //Iterate through every item and check how much free stackable slots there is. + // Iterate through every item and check how much free stackable slots there is. uint32_t slotIndex = 0; for (Item* containerItem : itemlist) { if (containerItem != item && containerItem->equals(item) && containerItem->getItemCount() < 100) { @@ -454,9 +428,7 @@ ReturnValue Container::queryMaxCount(int32_t index, const Thing& thing, uint32_t return RETURNVALUE_NOERROR; } -ReturnValue Container::queryRemove(const Thing& thing, uint32_t count, uint32_t flags, - Creature* actor /*= nullptr */) const -{ +ReturnValue Container::queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor /*= nullptr */) const { int32_t index = getThingIndex(&thing); if (index == -1) { SPDLOG_DEBUG("{} - Failed to get thing index", __FUNCTION__); @@ -478,16 +450,14 @@ ReturnValue Container::queryRemove(const Thing& thing, uint32_t count, uint32_t SPDLOG_DEBUG("{} - Item is not moveable", __FUNCTION__); return RETURNVALUE_NOTMOVEABLE; } - const HouseTile* houseTile = dynamic_cast(getTopParent()); + const HouseTile* houseTile = dynamic_cast(getTopParent()); if (houseTile) { return houseTile->queryRemove(thing, count, flags, actor); } return RETURNVALUE_NOERROR; } -Cylinder* Container::queryDestination(int32_t& index, const Thing &thing, Item** destItem, - uint32_t& flags) -{ +Cylinder* Container::queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) { if (!unlocked) { *destItem = nullptr; return this; @@ -544,7 +514,7 @@ Cylinder* Container::queryDestination(int32_t& index, const Thing &thing, Item** return this; } - //try find a suitable item to stack with + // try find a suitable item to stack with uint32_t n = 0; for (Item* listItem : itemlist) { if (listItem != item && listItem->equals(item) && listItem->getItemCount() < 100) { @@ -558,13 +528,11 @@ Cylinder* Container::queryDestination(int32_t& index, const Thing &thing, Item** return this; } -void Container::addThing(Thing* thing) -{ +void Container::addThing(Thing* thing) { return addThing(0, thing); } -void Container::addThing(int32_t index, Thing* thing) -{ +void Container::addThing(int32_t index, Thing* thing) { if (index >= static_cast(capacity())) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -578,25 +546,23 @@ void Container::addThing(int32_t index, Thing* thing) itemlist.push_front(item); updateItemWeight(item->getWeight()); - //send change to client + // send change to client if (getParent() && (getParent() != VirtualCylinder::virtualCylinder)) { onAddContainerItem(item); } } -void Container::addItemBack(Item* item) -{ +void Container::addItemBack(Item* item) { addItem(item); updateItemWeight(item->getWeight()); - //send change to client + // send change to client if (getParent() && (getParent() != VirtualCylinder::virtualCylinder)) { onAddContainerItem(item); } } -void Container::updateThing(Thing* thing, uint16_t itemId, uint32_t count) -{ +void Container::updateThing(Thing* thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -612,14 +578,13 @@ void Container::updateThing(Thing* thing, uint16_t itemId, uint32_t count) item->setSubType(count); updateItemWeight(-oldWeight + item->getWeight()); - //send change to client + // send change to client if (getParent()) { onUpdateContainerItem(index, item, item); } } -void Container::replaceThing(uint32_t index, Thing* thing) -{ +void Container::replaceThing(uint32_t index, Thing* thing) { Item* item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -634,7 +599,7 @@ void Container::replaceThing(uint32_t index, Thing* thing) item->setParent(this); updateItemWeight(-static_cast(replacedItem->getWeight()) + item->getWeight()); - //send change to client + // send change to client if (getParent()) { onUpdateContainerItem(index, replacedItem, item); } @@ -642,8 +607,7 @@ void Container::replaceThing(uint32_t index, Thing* thing) replacedItem->setParent(nullptr); } -void Container::removeThing(Thing* thing, uint32_t count) -{ +void Container::removeThing(Thing* thing, uint32_t count) { Item* item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -660,14 +624,14 @@ void Container::removeThing(Thing* thing, uint32_t count) item->setItemCount(newCount); updateItemWeight(-oldWeight + item->getWeight()); - //send change to client + // send change to client if (getParent()) { onUpdateContainerItem(index, item, item); } } else { updateItemWeight(-static_cast(item->getWeight())); - //send change to client + // send change to client if (getParent()) { onRemoveContainerItem(index, item); } @@ -677,8 +641,7 @@ void Container::removeThing(Thing* thing, uint32_t count) } } -int32_t Container::getThingIndex(const Thing* thing) const -{ +int32_t Container::getThingIndex(const Thing* thing) const { int32_t index = 0; for (Item* item : itemlist) { if (item == thing) { @@ -689,18 +652,15 @@ int32_t Container::getThingIndex(const Thing* thing) const return -1; } -size_t Container::getFirstIndex() const -{ +size_t Container::getFirstIndex() const { return 0; } -size_t Container::getLastIndex() const -{ +size_t Container::getLastIndex() const { return size(); } -uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType/* = -1*/) const -{ +uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType /* = -1*/) const { uint32_t count = 0; for (Item* item : itemlist) { if (item->getID() == itemId) { @@ -710,21 +670,18 @@ uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType/* = -1*/) return count; } -std::map& Container::getAllItemTypeCount(std::map& countMap) const -{ +std::map &Container::getAllItemTypeCount(std::map &countMap) const { for (Item* item : itemlist) { countMap[item->getID()] += item->getItemCount(); } return countMap; } -Thing* Container::getThing(size_t index) const -{ +Thing* Container::getThing(size_t index) const { return getItemByIndex(index); } -ItemVector Container::getItems(bool recursive /*= false*/) const -{ +ItemVector Container::getItems(bool recursive /*= false*/) const { ItemVector containerItems; if (recursive) { for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { @@ -738,13 +695,12 @@ ItemVector Container::getItems(bool recursive /*= false*/) const return containerItems; } -void Container::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void Container::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { Cylinder* topParent = getTopParent(); if (topParent->getCreature()) { topParent->postAddNotification(thing, oldParent, index, LINK_TOPPARENT); } else if (topParent == this) { - //let the tile class notify surrounding players + // let the tile class notify surrounding players if (topParent->getParent()) { topParent->getParent()->postAddNotification(thing, oldParent, index, LINK_NEAR); } @@ -753,13 +709,12 @@ void Container::postAddNotification(Thing* thing, const Cylinder* oldParent, int } } -void Container::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void Container::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { Cylinder* topParent = getTopParent(); if (topParent->getCreature()) { topParent->postRemoveNotification(thing, newParent, index, LINK_TOPPARENT); } else if (topParent == this) { - //let the tile class notify surrounding players + // let the tile class notify surrounding players if (topParent->getParent()) { topParent->getParent()->postRemoveNotification(thing, newParent, index, LINK_NEAR); } @@ -768,13 +723,11 @@ void Container::postRemoveNotification(Thing* thing, const Cylinder* newParent, } } -void Container::internalAddThing(Thing* thing) -{ +void Container::internalAddThing(Thing* thing) { internalAddThing(0, thing); } -void Container::internalAddThing(uint32_t, Thing* thing) -{ +void Container::internalAddThing(uint32_t, Thing* thing) { Item* item = thing->getItem(); if (item == nullptr) { return; @@ -785,24 +738,21 @@ void Container::internalAddThing(uint32_t, Thing* thing) updateItemWeight(item->getWeight()); } -void Container::startDecaying() -{ +void Container::startDecaying() { g_decay().startDecay(this); for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { g_decay().startDecay(*it); } } -void Container::stopDecaying() -{ +void Container::stopDecaying() { g_decay().stopDecay(this); for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { g_decay().stopDecay(*it); } } -uint16_t Container::getFreeSlots() const -{ +uint16_t Container::getFreeSlots() const { uint16_t counter = std::max(0, capacity() - size()); for (Item* item : itemlist) { @@ -814,8 +764,7 @@ uint16_t Container::getFreeSlots() const return counter; } -ContainerIterator Container::iterator() const -{ +ContainerIterator Container::iterator() const { ContainerIterator cit; if (!itemlist.empty()) { cit.over.push_back(this); @@ -824,13 +773,11 @@ ContainerIterator Container::iterator() const return cit; } -Item* ContainerIterator::operator*() -{ +Item* ContainerIterator::operator*() { return *cur; } -void ContainerIterator::advance() -{ +void ContainerIterator::advance() { if (Item* i = *cur) { if (Container* c = i->getContainer()) { if (!c->empty()) { diff --git a/src/items/containers/container.h b/src/items/containers/container.h index 42641267e35..7e6c52e2aba 100644 --- a/src/items/containers/container.h +++ b/src/items/containers/container.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_CONTAINER_H_ #define SRC_ITEMS_CONTAINERS_CONTAINER_H_ @@ -20,8 +20,7 @@ class DepotLocker; class RewardChest; class Reward; -class ContainerIterator -{ +class ContainerIterator { public: bool hasNext() const { return !over.empty(); @@ -37,8 +36,7 @@ class ContainerIterator friend class Container; }; -class Container : public Item, public Cylinder -{ +class Container : public Item, public Cylinder { public: explicit Container(uint16_t type); Container(uint16_t type, uint16_t size, bool unlocked = true, bool pagination = false); @@ -46,8 +44,8 @@ class Container : public Item, public Cylinder ~Container(); // non-copyable - Container(const Container&) = delete; - Container& operator=(const Container&) = delete; + Container(const Container &) = delete; + Container &operator=(const Container &) = delete; Item* clone() const override final; @@ -85,8 +83,8 @@ class Container : public Item, public Cylinder return false; } - Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; - bool unserializeItemNode(OTB::Loader& loader, const OTB::Node& node, PropStream& propStream) override; + Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream) override; + bool unserializeItemNode(OTB::Loader &loader, const OTB::Node &node, PropStream &propStream) override; std::string getContentDescription() const; size_t size() const { @@ -101,7 +99,7 @@ class Container : public Item, public Cylinder ContainerIterator iterator() const; - const ItemDeque& getItemList() const { + const ItemDeque &getItemList() const { return itemlist; } @@ -131,14 +129,11 @@ class Container : public Item, public Cylinder return pagination; } - //cylinder implementations - virtual ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; - ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, uint32_t& maxQueryCount, - uint32_t flags) const override final; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override final; - Cylinder* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) override final; + // cylinder implementations + virtual ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const override final; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override final; + Cylinder* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override final; void addThing(Thing* thing) override final; void addThing(int32_t index, Thing* thing) override final; @@ -153,9 +148,9 @@ class Container : public Item, public Cylinder size_t getFirstIndex() const override final; size_t getLastIndex() const override final; uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const override final; - std::map& getAllItemTypeCount(std::map& countMap) const override final; + std::map &getAllItemTypeCount(std::map &countMap) const override final; Thing* getThing(size_t index) const override final; - + ItemVector getItems(bool recursive = false) const; void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; @@ -167,7 +162,7 @@ class Container : public Item, public Cylinder void stopDecaying() override; protected: - std::ostringstream& getContentDescription(std::ostringstream& os) const; + std::ostringstream &getContentDescription(std::ostringstream &os) const; uint32_t maxSize; uint32_t totalWeight = 0; @@ -190,4 +185,4 @@ class Container : public Item, public Cylinder friend class IOMapSerialize; }; -#endif // SRC_ITEMS_CONTAINERS_CONTAINER_H_ +#endif // SRC_ITEMS_CONTAINERS_CONTAINER_H_ diff --git a/src/items/containers/depot/depotchest.cpp b/src/items/containers/depot/depotchest.cpp index 2c901dbb0b3..d907cebc99d 100644 --- a/src/items/containers/depot/depotchest.cpp +++ b/src/items/containers/depot/depotchest.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,16 +13,13 @@ #include "utils/tools.h" DepotChest::DepotChest(uint16_t type) : - Container(type) -{ + Container(type) { maxDepotItems = 2000; maxSize = 32; pagination = true; } -ReturnValue DepotChest::queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor/* = nullptr*/) const -{ +ReturnValue DepotChest::queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor /* = nullptr*/) const { const Item* item = thing.getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; @@ -48,8 +45,7 @@ ReturnValue DepotChest::queryAdd(int32_t index, const Thing& thing, uint32_t cou if (localParent->getContainer()->getItemHoldingCount() + addCount > maxDepotItems) { return RETURNVALUE_DEPOTISFULL; } - } - else if (getItemHoldingCount() + addCount > maxDepotItems) { + } else if (getItemHoldingCount() + addCount > maxDepotItems) { return RETURNVALUE_DEPOTISFULL; } } @@ -57,24 +53,21 @@ ReturnValue DepotChest::queryAdd(int32_t index, const Thing& thing, uint32_t cou return Container::queryAdd(index, thing, count, flags, actor); } -void DepotChest::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void DepotChest::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { Cylinder* localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void DepotChest::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void DepotChest::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { Cylinder* localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -Cylinder* DepotChest::getParent() const -{ +Cylinder* DepotChest::getParent() const { if (parent && parent->getParent()) { return parent->getParent()->getParent(); } diff --git a/src/items/containers/depot/depotchest.h b/src/items/containers/depot/depotchest.h index 0ed06959813..fbe1c9bc573 100644 --- a/src/items/containers/depot/depotchest.h +++ b/src/items/containers/depot/depotchest.h @@ -5,26 +5,24 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_DEPOT_DEPOTCHEST_H_ #define SRC_ITEMS_CONTAINERS_DEPOT_DEPOTCHEST_H_ #include "items/containers/container.h" -class DepotChest final : public Container -{ +class DepotChest final : public Container { public: explicit DepotChest(uint16_t type); - //serialization + // serialization void setMaxDepotItems(uint32_t maxitems) { maxDepotItems = maxitems; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; @@ -33,7 +31,7 @@ class DepotChest final : public Container return true; } - //overrides + // overrides bool canRemove() const override { return false; } @@ -50,5 +48,4 @@ class DepotChest final : public Container uint32_t maxDepotItems; }; -#endif // SRC_ITEMS_CONTAINERS_DEPOT_DEPOTCHEST_H_ - +#endif // SRC_ITEMS_CONTAINERS_DEPOT_DEPOTCHEST_H_ diff --git a/src/items/containers/depot/depotlocker.cpp b/src/items/containers/depot/depotlocker.cpp index abdbb6ebbfc..c4ba0ac664d 100644 --- a/src/items/containers/depot/depotlocker.cpp +++ b/src/items/containers/depot/depotlocker.cpp @@ -5,17 +5,16 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/containers/depot/depotlocker.h" DepotLocker::DepotLocker(uint16_t type) : - Container(type, 4), depotId(0) {} + Container(type, 4), depotId(0) { } -Attr_ReadValue DepotLocker::readAttr(AttrTypes_t attr, PropStream& propStream) -{ +Attr_ReadValue DepotLocker::readAttr(AttrTypes_t attr, PropStream &propStream) { if (attr == ATTR_DEPOT_ID) { if (!propStream.read(depotId)) { return ATTR_READ_ERROR; @@ -25,27 +24,23 @@ Attr_ReadValue DepotLocker::readAttr(AttrTypes_t attr, PropStream& propStream) return Item::readAttr(attr, propStream); } -ReturnValue DepotLocker::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature*) const -{ +ReturnValue DepotLocker::queryAdd(int32_t, const Thing &, uint32_t, uint32_t, Creature*) const { return RETURNVALUE_NOTENOUGHROOM; } -void DepotLocker::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void DepotLocker::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { if (parent != nullptr) { parent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void DepotLocker::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void DepotLocker::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { if (parent != nullptr) { parent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -void DepotLocker::removeInbox(Inbox* inbox) -{ +void DepotLocker::removeInbox(Inbox* inbox) { auto cit = std::find(itemlist.begin(), itemlist.end(), inbox); if (cit == itemlist.end()) { return; diff --git a/src/items/containers/depot/depotlocker.h b/src/items/containers/depot/depotlocker.h index 7bd0e35eeac..634fd3e3a51 100644 --- a/src/items/containers/depot/depotlocker.h +++ b/src/items/containers/depot/depotlocker.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_DEPOT_DEPOTLOCKER_H_ #define SRC_ITEMS_CONTAINERS_DEPOT_DEPOTLOCKER_H_ @@ -13,8 +13,7 @@ #include "items/containers/container.h" #include "items/containers/inbox/inbox.h" -class DepotLocker final : public Container -{ +class DepotLocker final : public Container { public: explicit DepotLocker(uint16_t type); @@ -27,8 +26,8 @@ class DepotLocker final : public Container void removeInbox(Inbox* inbox); - //serialization - Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; + // serialization + Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream) override; uint16_t getDepotId() const { return depotId; @@ -37,9 +36,8 @@ class DepotLocker final : public Container this->depotId = newDepotId; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; @@ -55,5 +53,4 @@ class DepotLocker final : public Container uint16_t depotId; }; -#endif // SRC_ITEMS_CONTAINERS_DEPOT_DEPOTLOCKER_H_ - +#endif // SRC_ITEMS_CONTAINERS_DEPOT_DEPOTLOCKER_H_ diff --git a/src/items/containers/inbox/inbox.cpp b/src/items/containers/inbox/inbox.cpp index ebba45f90cf..221c8f2bd8b 100644 --- a/src/items/containers/inbox/inbox.cpp +++ b/src/items/containers/inbox/inbox.cpp @@ -5,21 +5,19 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/containers/inbox/inbox.h" #include "utils/tools.h" -Inbox::Inbox(uint16_t type) : Container(type, 30, false, true) -{ +Inbox::Inbox(uint16_t type) : + Container(type, 30, false, true) { maxInboxItems = std::numeric_limits::max(); } -ReturnValue Inbox::queryAdd(int32_t, const Thing& thing, uint32_t, - uint32_t flags, Creature*) const -{ +ReturnValue Inbox::queryAdd(int32_t, const Thing &thing, uint32_t, uint32_t flags, Creature*) const { int32_t addCount = 0; if (!hasBitSet(FLAG_NOLIMIT, flags)) { @@ -39,40 +37,36 @@ ReturnValue Inbox::queryAdd(int32_t, const Thing& thing, uint32_t, return RETURNVALUE_CANNOTPICKUP; } - if (item->getTopParent() != this) { //MY + if (item->getTopParent() != this) { // MY if (const Container* container = item->getContainer()) { addCount = container->getItemHoldingCount() + 1; - } - else { + } else { addCount = 1; } } - if (getItemHoldingCount() + addCount > maxInboxItems) { //MY + if (getItemHoldingCount() + addCount > maxInboxItems) { // MY return RETURNVALUE_DEPOTISFULL; } return RETURNVALUE_NOERROR; } -void Inbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void Inbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { Cylinder* localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void Inbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void Inbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { Cylinder* localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -Cylinder* Inbox::getParent() const -{ +Cylinder* Inbox::getParent() const { if (parent) { return parent->getParent(); } diff --git a/src/items/containers/inbox/inbox.h b/src/items/containers/inbox/inbox.h index c3c7ccc635d..75dd353d49c 100644 --- a/src/items/containers/inbox/inbox.h +++ b/src/items/containers/inbox/inbox.h @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_INBOX_INBOX_H_ #define SRC_ITEMS_CONTAINERS_INBOX_INBOX_H_ #include "items/containers/container.h" -class Inbox final : public Container -{ +class Inbox final : public Container { public: explicit Inbox(uint16_t type); @@ -21,9 +20,8 @@ class Inbox final : public Container maxInboxItems = maxitems; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; @@ -32,7 +30,7 @@ class Inbox final : public Container return true; } - //overrides + // overrides bool canRemove() const override { return false; } @@ -44,9 +42,9 @@ class Inbox final : public Container Cylinder* getRealParent() const override { return parent; } + private: uint32_t maxInboxItems; }; -#endif // SRC_ITEMS_CONTAINERS_INBOX_INBOX_H_ - +#endif // SRC_ITEMS_CONTAINERS_INBOX_INBOX_H_ diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index 8ed24952836..0cc8a1a3ce0 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,8 +13,7 @@ #include "game/game.h" #include "io/iologindata.h" -ReturnValue Mailbox::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t, Creature*) const -{ +ReturnValue Mailbox::queryAdd(int32_t, const Thing &thing, uint32_t, uint32_t, Creature*) const { const Item* item = thing.getItem(); if (item && Mailbox::canSend(item)) { return RETURNVALUE_NOERROR; @@ -22,62 +21,51 @@ ReturnValue Mailbox::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t, C return RETURNVALUE_NOTPOSSIBLE; } -ReturnValue Mailbox::queryMaxCount(int32_t, const Thing&, uint32_t count, uint32_t& maxQueryCount, uint32_t) const -{ +ReturnValue Mailbox::queryMaxCount(int32_t, const Thing &, uint32_t count, uint32_t &maxQueryCount, uint32_t) const { maxQueryCount = std::max(1, count); return RETURNVALUE_NOERROR; } -ReturnValue Mailbox::queryRemove(const Thing&, uint32_t, uint32_t, Creature* /*= nullptr */) const -{ +ReturnValue Mailbox::queryRemove(const Thing &, uint32_t, uint32_t, Creature* /*= nullptr */) const { return RETURNVALUE_NOTPOSSIBLE; } -Cylinder* Mailbox::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) -{ +Cylinder* Mailbox::queryDestination(int32_t &, const Thing &, Item**, uint32_t &) { return this; } -void Mailbox::addThing(Thing* thing) -{ +void Mailbox::addThing(Thing* thing) { return addThing(0, thing); } -void Mailbox::addThing(int32_t, Thing* thing) -{ +void Mailbox::addThing(int32_t, Thing* thing) { Item* item = thing->getItem(); if (item && Mailbox::canSend(item)) { sendItem(item); } } -void Mailbox::updateThing(Thing*, uint16_t, uint32_t) -{ +void Mailbox::updateThing(Thing*, uint16_t, uint32_t) { // } -void Mailbox::replaceThing(uint32_t, Thing*) -{ +void Mailbox::replaceThing(uint32_t, Thing*) { // } -void Mailbox::removeThing(Thing*, uint32_t) -{ +void Mailbox::removeThing(Thing*, uint32_t) { // } -void Mailbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void Mailbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } -void Mailbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void Mailbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } -bool Mailbox::sendItem(Item* item) const -{ +bool Mailbox::sendItem(Item* item) const { std::string receiver; if (!getReceiver(item, receiver)) { return false; @@ -98,8 +86,7 @@ bool Mailbox::sendItem(Item* item) const text = item->getAttribute(ItemAttribute_t::TEXT); } if (player && item) { - if (g_game().internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER, - item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { + if (g_game().internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { Item* newItem = g_game().transformItem(item, item->getID() + 1); if (newItem && newItem->getID() == ITEM_LETTER_STAMPED && writer != "") { newItem->setAttribute(ItemAttribute_t::WRITER, writer); @@ -115,8 +102,7 @@ bool Mailbox::sendItem(Item* item) const return false; } - if (item && g_game().internalMoveItem(item->getParent(), tmpPlayer.getInbox(), INDEX_WHEREEVER, - item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { + if (item && g_game().internalMoveItem(item->getParent(), tmpPlayer.getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { Item* newItem = g_game().transformItem(item, item->getID() + 1); if (newItem && newItem->getID() == ITEM_LETTER_STAMPED && writer != "") { newItem->setAttribute(ItemAttribute_t::WRITER, writer); @@ -130,8 +116,7 @@ bool Mailbox::sendItem(Item* item) const return false; } -bool Mailbox::getReceiver(Item* item, std::string& name) const -{ +bool Mailbox::getReceiver(Item* item, std::string &name) const { const Container* container = item->getContainer(); if (container) { for (Item* containerItem : container->getItemList()) { @@ -142,7 +127,7 @@ bool Mailbox::getReceiver(Item* item, std::string& name) const return false; } - const std::string& text = item->getAttribute(ItemAttribute_t::TEXT); + const std::string &text = item->getAttribute(ItemAttribute_t::TEXT); if (text.empty()) { return false; } @@ -152,7 +137,6 @@ bool Mailbox::getReceiver(Item* item, std::string& name) const return true; } -bool Mailbox::canSend(const Item* item) -{ +bool Mailbox::canSend(const Item* item) { return item->getID() == ITEM_PARCEL || item->getID() == ITEM_LETTER; } diff --git a/src/items/containers/mailbox/mailbox.h b/src/items/containers/mailbox/mailbox.h index e30ad0d6d03..c797bb2e6e9 100644 --- a/src/items/containers/mailbox/mailbox.h +++ b/src/items/containers/mailbox/mailbox.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_MAILBOX_MAILBOX_H_ #define SRC_ITEMS_CONTAINERS_MAILBOX_MAILBOX_H_ @@ -13,10 +13,10 @@ #include "items/item.h" #include "items/cylinder.h" -class Mailbox final : public Item, public Cylinder -{ +class Mailbox final : public Item, public Cylinder { public: - explicit Mailbox(uint16_t itemId) : Item(itemId) {} + explicit Mailbox(uint16_t itemId) : + Item(itemId) { } Mailbox* getMailbox() override { return this; @@ -25,14 +25,11 @@ class Mailbox final : public Item, public Cylinder return this; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; - ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, - uint32_t& maxQueryCount, uint32_t flags) const override; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; - Cylinder* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const override; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + Cylinder* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override; void addThing(Thing* thing) override; void addThing(int32_t index, Thing* thing) override; @@ -46,10 +43,10 @@ class Mailbox final : public Item, public Cylinder void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; private: - bool getReceiver(Item* item, std::string& name) const; + bool getReceiver(Item* item, std::string &name) const; bool sendItem(Item* item) const; static bool canSend(const Item* item); }; -#endif // SRC_ITEMS_CONTAINERS_MAILBOX_MAILBOX_H_ +#endif // SRC_ITEMS_CONTAINERS_MAILBOX_MAILBOX_H_ diff --git a/src/items/containers/rewards/reward.cpp b/src/items/containers/rewards/reward.cpp index 76d19b07b30..891a9ef3525 100644 --- a/src/items/containers/rewards/reward.cpp +++ b/src/items/containers/rewards/reward.cpp @@ -5,23 +5,20 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/containers/rewards/reward.h" Reward::Reward() : - Container(ITEM_REWARD_CONTAINER) -{ + Container(ITEM_REWARD_CONTAINER) { maxSize = 32; unlocked = false; pagination = true; } -ReturnValue Reward::queryAdd(int32_t, const Thing& thing, uint32_t, - uint32_t, Creature* actor/* = nullptr*/) const -{ +ReturnValue Reward::queryAdd(int32_t, const Thing &thing, uint32_t, uint32_t, Creature* actor /* = nullptr*/) const { if (actor) { return RETURNVALUE_NOTPOSSIBLE; } @@ -30,11 +27,11 @@ ReturnValue Reward::queryAdd(int32_t, const Thing& thing, uint32_t, if (!item) { return RETURNVALUE_NOTPOSSIBLE; } - + if (item == this) { return RETURNVALUE_THISISIMPOSSIBLE; } - + if (!item->isPickupable()) { return RETURNVALUE_CANNOTPICKUP; } @@ -42,24 +39,21 @@ ReturnValue Reward::queryAdd(int32_t, const Thing& thing, uint32_t, return RETURNVALUE_NOERROR; } -void Reward::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void Reward::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { Cylinder* localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void Reward::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void Reward::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { Cylinder* localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -Cylinder* Reward::getParent() const -{ +Cylinder* Reward::getParent() const { if (parent) { return parent->getParent(); } diff --git a/src/items/containers/rewards/reward.h b/src/items/containers/rewards/reward.h index 4f257b2abfe..54ee41650f0 100644 --- a/src/items/containers/rewards/reward.h +++ b/src/items/containers/rewards/reward.h @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_REWARDS_REWARD_H_ #define SRC_ITEMS_CONTAINERS_REWARDS_REWARD_H_ #include "items/containers/container.h" -class Reward : public Container -{ +class Reward : public Container { public: explicit Reward(); @@ -24,14 +23,13 @@ class Reward : public Container return this; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const final; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const final; void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - //overrides + // overrides bool canRemove() const final { return true; } @@ -42,4 +40,4 @@ class Reward : public Container } }; -#endif // SRC_ITEMS_CONTAINERS_REWARDS_REWARD_H_ +#endif // SRC_ITEMS_CONTAINERS_REWARDS_REWARD_H_ diff --git a/src/items/containers/rewards/rewardchest.cpp b/src/items/containers/rewards/rewardchest.cpp index 06636c0a5b3..aba63cffd1c 100644 --- a/src/items/containers/rewards/rewardchest.cpp +++ b/src/items/containers/rewards/rewardchest.cpp @@ -5,39 +5,34 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/containers/rewards/rewardchest.h" RewardChest::RewardChest(uint16_t type) : - Container(type) -{ + Container(type) { maxSize = 32; unlocked = false; pagination = true; } -ReturnValue RewardChest::queryAdd(int32_t, const Thing&, uint32_t, - uint32_t, Creature* actor/* = nullptr*/) const -{ +ReturnValue RewardChest::queryAdd(int32_t, const Thing &, uint32_t, uint32_t, Creature* actor /* = nullptr*/) const { if (actor) { return RETURNVALUE_NOTPOSSIBLE; } - + return RETURNVALUE_NOERROR; } -void RewardChest::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void RewardChest::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { if (parent != nullptr) { parent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void RewardChest::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void RewardChest::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { if (parent != nullptr) { parent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/items/containers/rewards/rewardchest.h b/src/items/containers/rewards/rewardchest.h index 71830836145..54d176acce2 100644 --- a/src/items/containers/rewards/rewardchest.h +++ b/src/items/containers/rewards/rewardchest.h @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CONTAINERS_REWARDS_REWARDCHEST_H_ #define SRC_ITEMS_CONTAINERS_REWARDS_REWARDCHEST_H_ #include "items/containers/container.h" -class RewardChest final : public Container -{ +class RewardChest final : public Container { public: explicit RewardChest(uint16_t type); @@ -24,9 +23,8 @@ class RewardChest final : public Container return this; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const final; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const final; void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; @@ -36,4 +34,4 @@ class RewardChest final : public Container } }; -#endif // SRC_ITEMS_CONTAINERS_REWARDS_REWARDCHEST_H_ +#endif // SRC_ITEMS_CONTAINERS_REWARDS_REWARDCHEST_H_ diff --git a/src/items/cylinder.cpp b/src/items/cylinder.cpp index 1056d395966..699b26ee5bf 100644 --- a/src/items/cylinder.cpp +++ b/src/items/cylinder.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,47 +13,38 @@ VirtualCylinder* VirtualCylinder::virtualCylinder = new VirtualCylinder; -int32_t Cylinder::getThingIndex(const Thing*) const -{ +int32_t Cylinder::getThingIndex(const Thing*) const { return -1; } -size_t Cylinder::getFirstIndex() const -{ +size_t Cylinder::getFirstIndex() const { return 0; } -size_t Cylinder::getLastIndex() const -{ +size_t Cylinder::getLastIndex() const { return 0; } -uint32_t Cylinder::getItemTypeCount(uint16_t, int32_t) const -{ +uint32_t Cylinder::getItemTypeCount(uint16_t, int32_t) const { return 0; } -std::map& Cylinder::getAllItemTypeCount(std::map& countMap) const -{ +std::map &Cylinder::getAllItemTypeCount(std::map &countMap) const { return countMap; } -Thing* Cylinder::getThing(size_t) const -{ +Thing* Cylinder::getThing(size_t) const { return nullptr; } -void Cylinder::internalAddThing(Thing*) -{ +void Cylinder::internalAddThing(Thing*) { // } -void Cylinder::internalAddThing(uint32_t, Thing*) -{ +void Cylinder::internalAddThing(uint32_t, Thing*) { // } -void Cylinder::startDecaying() -{ +void Cylinder::startDecaying() { // } diff --git a/src/items/cylinder.h b/src/items/cylinder.h index f44fe0d1d3f..f940b3d7fe3 100644 --- a/src/items/cylinder.h +++ b/src/items/cylinder.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_CYLINDER_H_ #define SRC_ITEMS_CYLINDER_H_ @@ -18,35 +18,32 @@ class Creature; static constexpr int32_t INDEX_WHEREEVER = -1; -class Cylinder : virtual public Thing -{ +class Cylinder : virtual public Thing { public: /** * Query if the cylinder can add an object * \param index points to the destination index (inventory slot/container position) - * -1 is a internal value and means add to a empty position, with no destItem + * -1 is a internal value and means add to a empty position, with no destItem * \param thing the object to move/add * \param count is the amount that we want to move/add * \param flags if FLAG_CHILDISOWNER if set the query is from a child-cylinder (check cap etc.) - * if FLAG_NOLIMIT is set blocking items/container limits is ignored + * if FLAG_NOLIMIT is set blocking items/container limits is ignored * \param actor the creature trying to add the thing * \returns ReturnValue holds the return value */ - virtual ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const = 0; + virtual ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const = 0; /** * Query the cylinder how much it can accept * \param index points to the destination index (inventory slot/container position) - * -1 is a internal value and means add to a empty position, with no destItem + * -1 is a internal value and means add to a empty position, with no destItem * \param thing the object to move/add * \param count is the amount that we want to move/add * \param maxQueryCount is the max amount that the cylinder can accept * \param flags optional flags to modify the default behaviour * \returns ReturnValue holds the return value */ - virtual ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, uint32_t& maxQueryCount, - uint32_t flags) const = 0; + virtual ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const = 0; /** * Query if the cylinder can remove an object @@ -55,20 +52,19 @@ class Cylinder : virtual public Thing * \param flags optional flags to modify the default behaviour * \returns ReturnValue holds the return value */ - virtual ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* = nullptr) const = 0; + virtual ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* = nullptr) const = 0; /** * Query the destination cylinder * \param index points to the destination index (inventory slot/container position), - * -1 is a internal value and means add to a empty position, with no destItem - * this method can change the index to point to the new cylinder index + * -1 is a internal value and means add to a empty position, with no destItem + * this method can change the index to point to the new cylinder index * \param destItem is the destination object * \param flags optional flags to modify the default behaviour - * this method can modify the flags + * this method can modify the flags * \returns Cylinder returns the destination cylinder */ - virtual Cylinder* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) = 0; + virtual Cylinder* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) = 0; /** * Add the object to the cylinder @@ -159,7 +155,7 @@ class Cylinder : virtual public Thing * \param countMap a map to put the itemID:count mapping in * \returns a map mapping item id to count (same as first argument) */ - virtual std::map& getAllItemTypeCount(std::map& countMap) const; + virtual std::map &getAllItemTypeCount(std::map &countMap) const; /** * Adds an object to the cylinder without sending to the client(s) @@ -177,32 +173,31 @@ class Cylinder : virtual public Thing virtual void startDecaying(); }; -class VirtualCylinder final : public Cylinder -{ +class VirtualCylinder final : public Cylinder { public: static VirtualCylinder* virtualCylinder; - virtual ReturnValue queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature* = nullptr) const override { + virtual ReturnValue queryAdd(int32_t, const Thing &, uint32_t, uint32_t, Creature* = nullptr) const override { return RETURNVALUE_NOTPOSSIBLE; } - virtual ReturnValue queryMaxCount(int32_t, const Thing&, uint32_t, uint32_t&, uint32_t) const override { + virtual ReturnValue queryMaxCount(int32_t, const Thing &, uint32_t, uint32_t &, uint32_t) const override { return RETURNVALUE_NOTPOSSIBLE; } - virtual ReturnValue queryRemove(const Thing&, uint32_t, uint32_t, Creature* = nullptr) const override { + virtual ReturnValue queryRemove(const Thing &, uint32_t, uint32_t, Creature* = nullptr) const override { return RETURNVALUE_NOTPOSSIBLE; } - virtual Cylinder* queryDestination(int32_t&, const Thing&, Item**, uint32_t&) override { + virtual Cylinder* queryDestination(int32_t &, const Thing &, Item**, uint32_t &) override { return nullptr; } - virtual void addThing(Thing*) override {} - virtual void addThing(int32_t, Thing*) override {} - virtual void updateThing(Thing*, uint16_t, uint32_t) override {} - virtual void replaceThing(uint32_t, Thing*) override {} - virtual void removeThing(Thing*, uint32_t) override {} + virtual void addThing(Thing*) override { } + virtual void addThing(int32_t, Thing*) override { } + virtual void updateThing(Thing*, uint16_t, uint32_t) override { } + virtual void replaceThing(uint32_t, Thing*) override { } + virtual void removeThing(Thing*, uint32_t) override { } - virtual void postAddNotification(Thing*, const Cylinder*, int32_t, CylinderLink_t = LINK_OWNER) override {} - virtual void postRemoveNotification(Thing*, const Cylinder*, int32_t, CylinderLink_t = LINK_OWNER) override {} + virtual void postAddNotification(Thing*, const Cylinder*, int32_t, CylinderLink_t = LINK_OWNER) override { } + virtual void postRemoveNotification(Thing*, const Cylinder*, int32_t, CylinderLink_t = LINK_OWNER) override { } bool isPushable() const override { return false; @@ -218,4 +213,4 @@ class VirtualCylinder final : public Cylinder } }; -#endif // SRC_ITEMS_CYLINDER_H_ +#endif // SRC_ITEMS_CYLINDER_H_ diff --git a/src/items/decay/decay.cpp b/src/items/decay/decay.cpp index b1139f20b6a..63be1948b00 100644 --- a/src/items/decay/decay.cpp +++ b/src/items/decay/decay.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,8 +13,7 @@ #include "game/game.h" #include "game/scheduling/scheduler.h" -void Decay::startDecay(Item* item) -{ +void Decay::startDecay(Item* item) { if (!item) { return; } @@ -57,20 +56,19 @@ void Decay::startDecay(Item* item) } } -void Decay::stopDecay(Item* item) -{ +void Decay::stopDecay(Item* item) { if (item->hasAttribute(ItemAttribute_t::DECAYSTATE)) { auto timestamp = item->getAttribute(ItemAttribute_t::DURATION_TIMESTAMP); if (item->hasAttribute(ItemAttribute_t::DURATION_TIMESTAMP)) { auto it = decayMap.find(timestamp); if (it != decayMap.end()) { - std::vector& decayItems = it->second; + std::vector &decayItems = it->second; size_t i = 0, end = decayItems.size(); if (end == 1) { if (item == decayItems[i]) { if (item->hasAttribute(ItemAttribute_t::DURATION)) { - //Incase we removed duration attribute don't assign new duration + // Incase we removed duration attribute don't assign new duration item->setDuration(item->getDuration()); } item->removeAttribute(ItemAttribute_t::DECAYSTATE); @@ -83,7 +81,7 @@ void Decay::stopDecay(Item* item) while (i < end) { if (item == decayItems[i]) { if (item->hasAttribute(ItemAttribute_t::DURATION)) { - //Incase we removed duration attribute don't assign new duration + // Incase we removed duration attribute don't assign new duration item->setDuration(item->getDuration()); } item->removeAttribute(ItemAttribute_t::DECAYSTATE); @@ -103,12 +101,11 @@ void Decay::stopDecay(Item* item) } } -void Decay::checkDecay() -{ +void Decay::checkDecay() { int64_t timestamp = OTSYS_TIME(); std::vector tempItems; - tempItems.reserve(32);// Small preallocation + tempItems.reserve(32); // Small preallocation auto it = decayMap.begin(), end = decayMap.end(); while (it != end) { @@ -117,7 +114,7 @@ void Decay::checkDecay() } // Iterating here is unsafe so let's copy our items into temporary vector - std::vector& decayItems = it->second; + std::vector &decayItems = it->second; tempItems.insert(tempItems.end(), decayItems.begin(), decayItems.end()); it = decayMap.erase(it); } @@ -139,9 +136,8 @@ void Decay::checkDecay() } } -void Decay::internalDecayItem(Item* item) -{ - const ItemType& it = Item::items[item->getID()]; +void Decay::internalDecayItem(Item* item) { + const ItemType &it = Item::items[item->getID()]; if (it.decayTo != 0) { Player* player = item->getHoldingPlayer(); if (player) { @@ -187,8 +183,8 @@ void Decay::internalDecayItem(Item* item) ReturnValue ret = g_game().internalRemoveItem(item); if (ret != RETURNVALUE_NOERROR) { SPDLOG_ERROR("[Decay::internalDecayItem] - internalDecayItem failed, " - "error code: {}, item id: {}", - static_cast(ret), item->getID()); + "error code: {}, item id: {}", + static_cast(ret), item->getID()); } } } diff --git a/src/items/decay/decay.h b/src/items/decay/decay.h index 842406e08ce..81a7318e80e 100644 --- a/src/items/decay/decay.h +++ b/src/items/decay/decay.h @@ -5,20 +5,19 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_DECAY_DECAY_H_ #define SRC_ITEMS_DECAY_DECAY_H_ #include "items/item.h" -class Decay -{ +class Decay { public: - Decay(Decay const&) = delete; - void operator=(Decay const&) = delete; + Decay(const Decay &) = delete; + void operator=(const Decay &) = delete; - static Decay& getInstance() { + static Decay &getInstance() { // Guaranteed to be destroyed static Decay instance; // Instantiated on first use @@ -34,7 +33,7 @@ class Decay void checkDecay(); void internalDecayItem(Item* item); - uint32_t eventId {0}; + uint32_t eventId { 0 }; std::map> decayMap; }; diff --git a/src/items/functions/item/attribute.cpp b/src/items/functions/item/attribute.cpp index e285a30a041..cf8cc187c10 100644 --- a/src/items/functions/item/attribute.cpp +++ b/src/items/functions/item/attribute.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,7 +16,7 @@ * ItemAttribute class (Attributes methods) ============================= */ -const std::string& ItemAttribute::getAttributeString(ItemAttribute_t type) const { +const std::string &ItemAttribute::getAttributeString(ItemAttribute_t type) const { static std::string emptyString; if (!isAttributeString(type)) { return emptyString; @@ -30,8 +30,7 @@ const std::string& ItemAttribute::getAttributeString(ItemAttribute_t type) const return *attribute->getString().get(); } -const int64_t& ItemAttribute::getAttributeValue(ItemAttribute_t type) const -{ +const int64_t &ItemAttribute::getAttributeValue(ItemAttribute_t type) const { static int64_t emptyInt; if (!isAttributeInteger(type)) { return emptyInt; @@ -45,10 +44,9 @@ const int64_t& ItemAttribute::getAttributeValue(ItemAttribute_t type) const return attribute->getInteger(); } -const Attributes* ItemAttribute::getAttribute(ItemAttribute_t type) const -{ +const Attributes* ItemAttribute::getAttribute(ItemAttribute_t type) const { if (hasAttribute(type)) { - for (const Attributes& attribute : attributeVector) { + for (const Attributes &attribute : attributeVector) { if (attribute.getAttributeType() == type) { return &attribute; } @@ -57,10 +55,9 @@ const Attributes* ItemAttribute::getAttribute(ItemAttribute_t type) const return nullptr; } -Attributes& ItemAttribute::getAttributesByType(ItemAttribute_t type) -{ +Attributes &ItemAttribute::getAttributesByType(ItemAttribute_t type) { if (hasAttribute(type)) { - for (Attributes& attribute : attributeVector) { + for (Attributes &attribute : attributeVector) { if (attribute.getAttributeType() == type) { return attribute; } @@ -92,8 +89,7 @@ void ItemAttribute::setAttribute(ItemAttribute_t type, const std::string &value) getAttributesByType(type).setValue(value); } -bool ItemAttribute::removeAttribute(ItemAttribute_t type) -{ +bool ItemAttribute::removeAttribute(ItemAttribute_t type) { if (!hasAttribute(type)) { return false; } @@ -117,8 +113,7 @@ bool ItemAttribute::removeAttribute(ItemAttribute_t type) * CustomAttribute map methods ============================= */ -const std::map>& ItemAttribute::getCustomAttributeMap() const -{ +const std::map> &ItemAttribute::getCustomAttributeMap() const { return customAttributeMap; } @@ -127,10 +122,8 @@ const std::map>& ItemAttribute::getCus * CustomAttribute object methods ============================= */ -const CustomAttribute* ItemAttribute::getCustomAttribute(const std::string& attributeName) const -{ - if (customAttributeMap.contains(asLowerCaseString(attributeName))) - { +const CustomAttribute* ItemAttribute::getCustomAttribute(const std::string &attributeName) const { + if (customAttributeMap.contains(asLowerCaseString(attributeName))) { return &customAttributeMap.at(asLowerCaseString(attributeName)); } return nullptr; @@ -156,13 +149,11 @@ void ItemAttribute::setCustomAttribute(const std::string &key, const bool value) customAttributeMap[asLowerCaseString(key)] = attribute; } -void ItemAttribute::addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute) -{ +void ItemAttribute::addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute) { customAttributeMap[asLowerCaseString(key)] = customAttribute; } -bool ItemAttribute::removeCustomAttribute(const std::string& attributeName) -{ +bool ItemAttribute::removeCustomAttribute(const std::string &attributeName) { auto it = customAttributeMap.find(asLowerCaseString(attributeName)); if (it == customAttributeMap.end()) { return false; diff --git a/src/items/functions/item/attribute.hpp b/src/items/functions/item/attribute.hpp index 90c64292915..5388cad2673 100644 --- a/src/items/functions/item/attribute.hpp +++ b/src/items/functions/item/attribute.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_FUNCTIONS_ITEM_ATTRIBUTE_HPP #define SRC_ITEMS_FUNCTIONS_ITEM_ATTRIBUTE_HPP @@ -14,159 +14,157 @@ #include "items/functions/item/custom_attribute.hpp" #include "utils/tools.h" -class ItemAttributeHelper -{ -public: - bool isAttributeInteger(ItemAttribute_t type) const - { - std::underlying_type_t checkTypes = 0; - checkTypes |= ItemAttribute_t::ACTIONID; - checkTypes |= ItemAttribute_t::UNIQUEID; - checkTypes |= ItemAttribute_t::DATE; - checkTypes |= ItemAttribute_t::WEIGHT; - checkTypes |= ItemAttribute_t::ATTACK; - checkTypes |= ItemAttribute_t::DEFENSE; - checkTypes |= ItemAttribute_t::EXTRADEFENSE; - checkTypes |= ItemAttribute_t::ARMOR; - checkTypes |= ItemAttribute_t::HITCHANCE; - checkTypes |= ItemAttribute_t::SHOOTRANGE; - checkTypes |= ItemAttribute_t::OWNER; - checkTypes |= ItemAttribute_t::DURATION; - checkTypes |= ItemAttribute_t::DECAYSTATE; - checkTypes |= ItemAttribute_t::CORPSEOWNER; - checkTypes |= ItemAttribute_t::CHARGES; - checkTypes |= ItemAttribute_t::FLUIDTYPE; - checkTypes |= ItemAttribute_t::DOORID; - checkTypes |= ItemAttribute_t::IMBUEMENT_SLOT; - checkTypes |= ItemAttribute_t::OPENCONTAINER; - checkTypes |= ItemAttribute_t::QUICKLOOTCONTAINER; - checkTypes |= ItemAttribute_t::DURATION_TIMESTAMP; - checkTypes |= ItemAttribute_t::TIER; - return (type & static_cast(checkTypes)) != 0; - } - - bool isAttributeString(ItemAttribute_t type) const - { - std::underlying_type_t checkTypes = 0; - checkTypes |= ItemAttribute_t::DESCRIPTION; - checkTypes |= ItemAttribute_t::TEXT; - checkTypes |= ItemAttribute_t::WRITER; - checkTypes |= ItemAttribute_t::NAME; - checkTypes |= ItemAttribute_t::ARTICLE; - checkTypes |= ItemAttribute_t::PLURALNAME; - checkTypes |= ItemAttribute_t::SPECIAL; - return (type & static_cast(checkTypes)) != 0; - } +class ItemAttributeHelper { + public: + bool isAttributeInteger(ItemAttribute_t type) const { + std::underlying_type_t checkTypes = 0; + checkTypes |= ItemAttribute_t::ACTIONID; + checkTypes |= ItemAttribute_t::UNIQUEID; + checkTypes |= ItemAttribute_t::DATE; + checkTypes |= ItemAttribute_t::WEIGHT; + checkTypes |= ItemAttribute_t::ATTACK; + checkTypes |= ItemAttribute_t::DEFENSE; + checkTypes |= ItemAttribute_t::EXTRADEFENSE; + checkTypes |= ItemAttribute_t::ARMOR; + checkTypes |= ItemAttribute_t::HITCHANCE; + checkTypes |= ItemAttribute_t::SHOOTRANGE; + checkTypes |= ItemAttribute_t::OWNER; + checkTypes |= ItemAttribute_t::DURATION; + checkTypes |= ItemAttribute_t::DECAYSTATE; + checkTypes |= ItemAttribute_t::CORPSEOWNER; + checkTypes |= ItemAttribute_t::CHARGES; + checkTypes |= ItemAttribute_t::FLUIDTYPE; + checkTypes |= ItemAttribute_t::DOORID; + checkTypes |= ItemAttribute_t::IMBUEMENT_SLOT; + checkTypes |= ItemAttribute_t::OPENCONTAINER; + checkTypes |= ItemAttribute_t::QUICKLOOTCONTAINER; + checkTypes |= ItemAttribute_t::DURATION_TIMESTAMP; + checkTypes |= ItemAttribute_t::TIER; + return (type & static_cast(checkTypes)) != 0; + } + + bool isAttributeString(ItemAttribute_t type) const { + std::underlying_type_t checkTypes = 0; + checkTypes |= ItemAttribute_t::DESCRIPTION; + checkTypes |= ItemAttribute_t::TEXT; + checkTypes |= ItemAttribute_t::WRITER; + checkTypes |= ItemAttribute_t::NAME; + checkTypes |= ItemAttribute_t::ARTICLE; + checkTypes |= ItemAttribute_t::PLURALNAME; + checkTypes |= ItemAttribute_t::SPECIAL; + return (type & static_cast(checkTypes)) != 0; + } }; -class Attributes : public ItemAttributeHelper -{ -public: - explicit Attributes(ItemAttribute_t type) : type(type), value(getDefaultValueForType(type)) {} - ~Attributes() = default; - - Attributes(const Attributes& i) : type(i.type), value(i.value) {} - Attributes(Attributes&& attribute) noexcept : type(attribute.type), value(std::move(attribute.value)) {} - - Attributes& operator=(Attributes&& other) noexcept { - type = other.type; - value = std::move(other.value); - return *this; - } - - const ItemAttribute_t &getAttributeType() const { - return type; - } - - std::variant> getDefaultValueForType(ItemAttribute_t attributeType) const { - if (isAttributeInteger(attributeType)) { - return 0; - } else if (isAttributeString(attributeType)) { - return std::make_shared(); - } else { - return {}; +class Attributes : public ItemAttributeHelper { + public: + explicit Attributes(ItemAttribute_t type) : + type(type), value(getDefaultValueForType(type)) { } + ~Attributes() = default; + + Attributes(const Attributes &i) : + type(i.type), value(i.value) { } + Attributes(Attributes &&attribute) noexcept : + type(attribute.type), value(std::move(attribute.value)) { } + + Attributes &operator=(Attributes &&other) noexcept { + type = other.type; + value = std::move(other.value); + return *this; } - } - void setValue(int64_t newValue) { - if (std::holds_alternative(value)) { - value = newValue; + const ItemAttribute_t &getAttributeType() const { + return type; } - } - void setValue(const std::string& newValue) { - if (std::holds_alternative>(value)) { - value = std::make_shared(newValue); + + std::variant> getDefaultValueForType(ItemAttribute_t attributeType) const { + if (isAttributeInteger(attributeType)) { + return 0; + } else if (isAttributeString(attributeType)) { + return std::make_shared(); + } else { + return {}; + } + } + + void setValue(int64_t newValue) { + if (std::holds_alternative(value)) { + value = newValue; + } } - } - const int64_t& getInteger() const { - if (std::holds_alternative(value)) { - return std::get(value); + void setValue(const std::string &newValue) { + if (std::holds_alternative>(value)) { + value = std::make_shared(newValue); + } + } + const int64_t &getInteger() const { + if (std::holds_alternative(value)) { + return std::get(value); + } + static int64_t emptyValue; + return emptyValue; } - static int64_t emptyValue; - return emptyValue; - } - const std::shared_ptr& getString() const { - if (std::holds_alternative>(value)) { - return std::get>(value); + const std::shared_ptr &getString() const { + if (std::holds_alternative>(value)) { + return std::get>(value); + } + static std::shared_ptr emptyPtr; + return emptyPtr; } - static std::shared_ptr emptyPtr; - return emptyPtr; - } -private: - ItemAttribute_t type; - std::variant> value; + private: + ItemAttribute_t type; + std::variant> value; }; -class ItemAttribute : public ItemAttributeHelper -{ -public: - ItemAttribute() = default; - - // CustomAttribute map methods - const std::map>& getCustomAttributeMap() const; - // CustomAttribute object methods - const CustomAttribute* getCustomAttribute(const std::string& attributeName) const; - - void setCustomAttribute(const std::string &key, const int64_t value); - void setCustomAttribute(const std::string &key, const std::string &value); - void setCustomAttribute(const std::string &key, const double value); - void setCustomAttribute(const std::string &key, const bool value); - - void addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute); - bool removeCustomAttribute(const std::string& attributeName); - - void setAttribute(ItemAttribute_t type, int64_t value); - void setAttribute(ItemAttribute_t type, const std::string &value); - bool removeAttribute(ItemAttribute_t type); - - const std::string& getAttributeString(ItemAttribute_t type) const; - const int64_t& getAttributeValue(ItemAttribute_t type) const; - - const std::underlying_type_t& getAttributeBits() const { - return attributeBits; - } - const std::vector& getAttributeVector() const { - return attributeVector; - } - - bool hasAttribute(ItemAttribute_t type) const { - return (type & static_cast(attributeBits)) != 0; - } - - const Attributes* getAttribute(ItemAttribute_t type) const; - - Attributes& getAttributesByType(ItemAttribute_t type); - -private: - // Singleton - ensures we don't accidentally copy it. - ItemAttribute(const ItemAttribute&) = delete; - ItemAttribute& operator=(const ItemAttribute&) = delete; - - std::map> customAttributeMap; - std::underlying_type_t attributeBits = 0; - std::vector attributeVector; +class ItemAttribute : public ItemAttributeHelper { + public: + ItemAttribute() = default; + + // CustomAttribute map methods + const std::map> &getCustomAttributeMap() const; + // CustomAttribute object methods + const CustomAttribute* getCustomAttribute(const std::string &attributeName) const; + + void setCustomAttribute(const std::string &key, const int64_t value); + void setCustomAttribute(const std::string &key, const std::string &value); + void setCustomAttribute(const std::string &key, const double value); + void setCustomAttribute(const std::string &key, const bool value); + + void addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute); + bool removeCustomAttribute(const std::string &attributeName); + + void setAttribute(ItemAttribute_t type, int64_t value); + void setAttribute(ItemAttribute_t type, const std::string &value); + bool removeAttribute(ItemAttribute_t type); + + const std::string &getAttributeString(ItemAttribute_t type) const; + const int64_t &getAttributeValue(ItemAttribute_t type) const; + + const std::underlying_type_t &getAttributeBits() const { + return attributeBits; + } + const std::vector &getAttributeVector() const { + return attributeVector; + } + + bool hasAttribute(ItemAttribute_t type) const { + return (type & static_cast(attributeBits)) != 0; + } + + const Attributes* getAttribute(ItemAttribute_t type) const; + + Attributes &getAttributesByType(ItemAttribute_t type); + + private: + // Singleton - ensures we don't accidentally copy it. + ItemAttribute(const ItemAttribute &) = delete; + ItemAttribute &operator=(const ItemAttribute &) = delete; + + std::map> customAttributeMap; + std::underlying_type_t attributeBits = 0; + std::vector attributeVector; }; #endif // SRC_ITEMS_FUNCTIONS_ITEM_ATTRIBUTE_HPP diff --git a/src/items/functions/item/custom_attribute.cpp b/src/items/functions/item/custom_attribute.cpp index da45778e44e..e48426081ab 100644 --- a/src/items/functions/item/custom_attribute.cpp +++ b/src/items/functions/item/custom_attribute.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -17,24 +17,23 @@ CustomAttribute::CustomAttribute() = default; CustomAttribute::~CustomAttribute() = default; // Constructor for int64_t -CustomAttribute::CustomAttribute(const std::string& initStringKey, - const int64_t initInt64) : stringKey(initStringKey) -{ +CustomAttribute::CustomAttribute(const std::string &initStringKey, const int64_t initInt64) : + stringKey(initStringKey) { setValue(initInt64); } // Constructor for string -CustomAttribute::CustomAttribute(const std::string &initStringKey, const std::string &initStringValue) : stringKey(initStringKey) -{ +CustomAttribute::CustomAttribute(const std::string &initStringKey, const std::string &initStringValue) : + stringKey(initStringKey) { setValue(initStringValue); } // Constructor for double -CustomAttribute::CustomAttribute(const std::string &initStringKey, const double initDoubleValue) : stringKey(initStringKey) -{ +CustomAttribute::CustomAttribute(const std::string &initStringKey, const double initDoubleValue) : + stringKey(initStringKey) { setValue(initDoubleValue); } // Constructor for boolean -CustomAttribute::CustomAttribute(const std::string &initStringKey, const bool initBoolValue) : stringKey(initStringKey) -{ +CustomAttribute::CustomAttribute(const std::string &initStringKey, const bool initBoolValue) : + stringKey(initStringKey) { setValue(initBoolValue); } @@ -92,8 +91,8 @@ void CustomAttribute::pushToLua(lua_State* L) const { } } -void CustomAttribute::serialize(PropWriteStream& propWriteStream) const { - +void CustomAttribute::serialize(PropWriteStream &propWriteStream) const { + if (hasValue()) { propWriteStream.write(1); propWriteStream.writeString(getString()); @@ -109,10 +108,10 @@ void CustomAttribute::serialize(PropWriteStream& propWriteStream) const { } } -bool CustomAttribute::unserialize(PropStream& propStream, const std::string& function) { +bool CustomAttribute::unserialize(PropStream &propStream, const std::string &function) { uint8_t type; if (!propStream.read(type)) { - SPDLOG_ERROR("[{}] Failed to read type", function); + SPDLOG_ERROR("[{}] Failed to read type", function); return false; } diff --git a/src/items/functions/item/custom_attribute.hpp b/src/items/functions/item/custom_attribute.hpp index 60eea738e41..f54426764e5 100644 --- a/src/items/functions/item/custom_attribute.hpp +++ b/src/items/functions/item/custom_attribute.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_FUNCTIONS_ITEM_CUSTOM_ATTRIBUTE_HPP_ #define SRC_ITEMS_FUNCTIONS_ITEM_CUSTOM_ATTRIBUTE_HPP_ @@ -13,77 +13,77 @@ #include "io/fileloader.h" class CustomAttribute { -public: - CustomAttribute(); - ~CustomAttribute(); + public: + CustomAttribute(); + ~CustomAttribute(); - CustomAttribute(const std::string &initStringKey, const int64_t initInt64Value); - CustomAttribute(const std::string &initStringKey, const std::string &initStringValue); - CustomAttribute(const std::string &initStringKey, const double initDoubleValue); - CustomAttribute(const std::string &initStringKey, const bool initBoolValue); + CustomAttribute(const std::string &initStringKey, const int64_t initInt64Value); + CustomAttribute(const std::string &initStringKey, const std::string &initStringValue); + CustomAttribute(const std::string &initStringKey, const double initDoubleValue); + CustomAttribute(const std::string &initStringKey, const bool initBoolValue); - const std::string &getStringKey() const; + const std::string &getStringKey() const; - template - T getAttribute() const { - if constexpr (std::is_same_v) { - return getString(); - } else if constexpr (std::is_same_v) { - return getDouble(); - } else if constexpr (std::is_same_v) { - return getBool(); - } else if constexpr (std::is_integral_v) { - return std::clamp( - static_cast(getInteger()), - std::numeric_limits::min(), - std::numeric_limits::max() - ); - } else { - SPDLOG_ERROR("[{}] not found value", __FUNCTION__); + template + T getAttribute() const { + if constexpr (std::is_same_v) { + return getString(); + } else if constexpr (std::is_same_v) { + return getDouble(); + } else if constexpr (std::is_same_v) { + return getBool(); + } else if constexpr (std::is_integral_v) { + return std::clamp( + static_cast(getInteger()), + std::numeric_limits::min(), + std::numeric_limits::max() + ); + } else { + SPDLOG_ERROR("[{}] not found value", __FUNCTION__); + } + return T(); } - return T(); - } - const int64_t &getInteger() const; - const std::string &getString() const; - const double &getDouble() const; - const bool &getBool() const; + const int64_t &getInteger() const; + const std::string &getString() const; + const double &getDouble() const; + const bool &getBool() const; - void setValue(const int64_t newValue) { - if (std::holds_alternative(value)) { - value = newValue; + void setValue(const int64_t newValue) { + if (std::holds_alternative(value)) { + value = newValue; + } } - } - void setValue(const std::string &newValue) { - if (std::holds_alternative(value)) { - value = newValue; + void setValue(const std::string &newValue) { + if (std::holds_alternative(value)) { + value = newValue; + } } - } - void setValue(const double newValue) { - if (std::holds_alternative(value)) { - value = newValue; + void setValue(const double newValue) { + if (std::holds_alternative(value)) { + value = newValue; + } } - } - void setValue(const bool newValue) { - if (std::holds_alternative(value)) { - value = newValue; + void setValue(const bool newValue) { + if (std::holds_alternative(value)) { + value = newValue; + } } - } - template - bool hasValue() const { - return std::holds_alternative(value); - } + template + bool hasValue() const { + return std::holds_alternative(value); + } - void pushToLua(lua_State* L) const; + void pushToLua(lua_State* L) const; - void serialize(PropWriteStream& propWriteStream) const; - bool unserialize(PropStream& propStream, const std::string& function); + void serialize(PropWriteStream &propWriteStream) const; + bool unserialize(PropStream &propStream, const std::string &function); -private: - std::string stringKey; + private: + std::string stringKey; - std::variant value; + std::variant value; }; #endif // SRC_ITEMS_FUNCTIONS_CUSTOM_ATTRIBUTE_HPP_ diff --git a/src/items/functions/item/item_parse.cpp b/src/items/functions/item/item_parse.cpp index 7a3796b044d..0706e0eaf4c 100644 --- a/src/items/functions/item/item_parse.cpp +++ b/src/items/functions/item/item_parse.cpp @@ -5,14 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/functions/item/item_parse.hpp" #include "utils/pugicast.h" -void ItemParse::initParse(const std::string& tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::initParse(const std::string &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType) { // Parse all item attributes ItemParse::parseType(tmpStrValue, valueAttribute, itemType); ItemParse::parseDescription(tmpStrValue, valueAttribute, itemType); @@ -67,7 +67,7 @@ void ItemParse::initParse(const std::string& tmpStrValue, pugi::xml_node attribu ItemParse::parseImbuement(tmpStrValue, attributeNode, valueAttribute, itemType); } -void ItemParse::parseType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "type") { stringValue = asLowerCaseString(valueAttribute.as_string()); @@ -78,83 +78,82 @@ void ItemParse::parseType(const std::string& tmpStrValue, pugi::xml_attribute va itemType.group = ITEM_GROUP_CONTAINER; } } else { - SPDLOG_WARN("[Items::parseItemNode] - Unknown type: {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown type: {}", valueAttribute.as_string()); } } } -void ItemParse::parseDescription(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseDescription(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "description") { itemType.description = valueAttribute.as_string(); } } -void ItemParse::parseRuneSpellName(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseRuneSpellName(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "runespellname") { itemType.runeSpellName = valueAttribute.as_string(); } } -void ItemParse::parseWeight(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseWeight(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "weight") { itemType.weight = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseShowCount(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseShowCount(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "showcount") { itemType.showCount = valueAttribute.as_bool(); } } -void ItemParse::parseArmor(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseArmor(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "armor") { itemType.armor = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseDefense(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseDefense(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "defense") { itemType.defense = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseExtraDefense(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseExtraDefense(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "extradef") { itemType.extraDefense = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseAttack(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseAttack(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "attack") { itemType.attack = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseRotateTo(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseRotateTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "rotateto") { itemType.rotateTo = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseWrapContainer(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseWrapContainer(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "wrapcontainer") { itemType.wrapContainer = valueAttribute.as_bool(); } } -void ItemParse::parseWrapableTo(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseWrapableTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "wrapableto") { itemType.wrapableTo = pugi::cast(valueAttribute.value()); @@ -162,28 +161,28 @@ void ItemParse::parseWrapableTo(const std::string& tmpStrValue, pugi::xml_attrib } } -void ItemParse::parseMoveable(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseMoveable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "moveable") { itemType.moveable = valueAttribute.as_bool(); } } -void ItemParse::parseBlockProjectTile(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseBlockProjectTile(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "blockprojectile") { itemType.blockProjectile = valueAttribute.as_bool(); } } -void ItemParse::parsePickupable(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parsePickupable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "allowpickupable" || stringValue == "pickupable") { itemType.pickupable = valueAttribute.as_bool(); } } -void ItemParse::parseFloorChange(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseFloorChange(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "floorchange") { stringValue = asLowerCaseString(valueAttribute.as_string()); @@ -191,20 +190,19 @@ void ItemParse::parseFloorChange(const std::string& tmpStrValue, pugi::xml_attri if (itemMap != TileStatesMap.end()) { itemType.floorChange = itemMap->second; } else { - SPDLOG_WARN("[ItemParse::parseFloorChange] - Unknown floorChange {}", - valueAttribute.as_string()); + SPDLOG_WARN("[ItemParse::parseFloorChange] - Unknown floorChange {}", valueAttribute.as_string()); } } } -void ItemParse::parseContainerSize(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseContainerSize(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "containersize") { itemType.maxItems = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseFluidSource(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseFluidSource(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "fluidsource") { stringValue = asLowerCaseString(valueAttribute.as_string()); @@ -212,13 +210,12 @@ void ItemParse::parseFluidSource(const std::string& tmpStrValue, pugi::xml_attri if (itemMap != FluidTypesMap.end()) { itemType.fluidSource = itemMap->second; } else { - SPDLOG_WARN("[Items::parseItemNode] - Unknown fluidSource {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown fluidSource {}", valueAttribute.as_string()); } } } -void ItemParse::parseWriteables(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseWriteables(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "readable") { itemType.canReadText = valueAttribute.as_bool(); @@ -232,7 +229,7 @@ void ItemParse::parseWriteables(const std::string& tmpStrValue, pugi::xml_attrib } } -void ItemParse::parseWeaponType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseWeaponType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "weapontype") { stringValue = asLowerCaseString(valueAttribute.as_string()); @@ -240,13 +237,12 @@ void ItemParse::parseWeaponType(const std::string& tmpStrValue, pugi::xml_attrib if (itemMap != WeaponTypesMap.end()) { itemType.weaponType = itemMap->second; } else { - SPDLOG_WARN("[Items::parseItemNode] - Unknown weaponType {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown weaponType {}", valueAttribute.as_string()); } } } -void ItemParse::parseSlotType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseSlotType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "slottype") { itemType.slotPosition = SLOTP_HAND; @@ -276,71 +272,67 @@ void ItemParse::parseSlotType(const std::string& tmpStrValue, pugi::xml_attribut } else if (stringValue == "hand") { itemType.slotPosition |= SLOTP_HAND; } else { - SPDLOG_WARN("[itemParseSlotType - Items::parseItemNode] - Unknown slotType {}", - valueAttribute.as_string()); + SPDLOG_WARN("[itemParseSlotType - Items::parseItemNode] - Unknown slotType {}", valueAttribute.as_string()); } } } -void ItemParse::parseAmmoType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseAmmoType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "ammotype") { itemType.ammoType = getAmmoType(asLowerCaseString(valueAttribute.as_string())); if (itemType.ammoType == AMMO_NONE) { - SPDLOG_WARN("[Items::parseItemNode] - Unknown ammoType {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown ammoType {}", valueAttribute.as_string()); } } } -void ItemParse::parseShootType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseShootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "shoottype") { ShootType_t shoot = getShootType(asLowerCaseString(valueAttribute.as_string())); if (shoot != CONST_ANI_NONE) { itemType.shootType = shoot; } else { - SPDLOG_WARN("[Items::parseItemNode] - Unknown shootType {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown shootType {}", valueAttribute.as_string()); } } } -void ItemParse::parseMagicEffect(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseMagicEffect(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "effect") { MagicEffectClasses effect = getMagicEffect(asLowerCaseString(valueAttribute.as_string())); if (effect != CONST_ME_NONE) { itemType.magicEffect = effect; } else { - SPDLOG_WARN("[Items::parseItemNode] - Unknown effect {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown effect {}", valueAttribute.as_string()); } } } -void ItemParse::parseLootType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseLootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "loottype") { itemType.type = Item::items.getLootType(valueAttribute.as_string()); } } -void ItemParse::parseRange(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseRange(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "range") { itemType.shootRange = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseDecayTo(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseDecayTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "decayto") { itemType.decayTo = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseDuration(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseDuration(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "duration") { itemType.decayTime = pugi::cast(valueAttribute.value()); @@ -351,11 +343,11 @@ void ItemParse::parseDuration(const std::string& tmpStrValue, pugi::xml_attribut } } -void ItemParse::parseTransform(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseTransform(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "transformequipto") { itemType.transformEquipTo = pugi::cast(valueAttribute.value()); - if (ItemType& transform = Item::items.getItemType(itemType.transformEquipTo); + if (ItemType &transform = Item::items.getItemType(itemType.transformEquipTo); transform.type == ITEM_TYPE_NONE) { transform.type = itemType.type; } @@ -368,7 +360,7 @@ void ItemParse::parseTransform(const std::string& tmpStrValue, pugi::xml_attribu } } -void ItemParse::parseCharges(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseCharges(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "charges") { itemType.charges = pugi::cast(valueAttribute.value()); @@ -377,14 +369,14 @@ void ItemParse::parseCharges(const std::string& tmpStrValue, pugi::xml_attribute } } -void ItemParse::parseShowAttributes(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseShowAttributes(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string lowerStringValue = asLowerCaseString(tmpStrValue); if (lowerStringValue == "showattributes") { itemType.showAttributes = valueAttribute.as_bool(); } } -void ItemParse::parseHitChance(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseHitChance(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "hitchance") { itemType.hitChance = std::min(100, std::max(-100, pugi::cast(valueAttribute.value()))); @@ -393,36 +385,36 @@ void ItemParse::parseHitChance(const std::string& tmpStrValue, pugi::xml_attribu } } -void ItemParse::parseInvisible(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseInvisible(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "invisible") { itemType.getAbilities().invisible = valueAttribute.as_bool(); } } -void ItemParse::parseSpeed(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseSpeed(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "speed") { itemType.getAbilities().speed = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseHealthAndMana(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseHealthAndMana(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "healthgain") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.regeneration = true; abilities.setHealthGain(pugi::cast(valueAttribute.value())); } else if (stringValue == "healthticks") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.regeneration = true; abilities.setHealthTicks(pugi::cast(valueAttribute.value())); } else if (stringValue == "managain") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.regeneration = true; abilities.setManaGain(pugi::cast(valueAttribute.value())); } else if (stringValue == "manaticks") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.regeneration = true; abilities.setManaTicks(pugi::cast(valueAttribute.value())); } else if (stringValue == "manashield") { @@ -430,7 +422,7 @@ void ItemParse::parseHealthAndMana(const std::string& tmpStrValue, pugi::xml_att } } -void ItemParse::parseSkills(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseSkills(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "skillsword") { itemType.getAbilities().skills[SKILL_SWORD] = pugi::cast(valueAttribute.value()); @@ -449,7 +441,7 @@ void ItemParse::parseSkills(const std::string& tmpStrValue, pugi::xml_attribute } } -void ItemParse::parseCriticalHit(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseCriticalHit(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "criticalhitchance") { itemType.getAbilities().skills[SKILL_CRITICAL_HIT_CHANCE] = pugi::cast(valueAttribute.value()); @@ -458,7 +450,7 @@ void ItemParse::parseCriticalHit(const std::string& tmpStrValue, pugi::xml_attri } } -void ItemParse::parseLifeAndManaLeech(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseLifeAndManaLeech(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "lifeleechchance") { itemType.getAbilities().skills[SKILL_LIFE_LEECH_CHANCE] = pugi::cast(valueAttribute.value()); @@ -471,7 +463,7 @@ void ItemParse::parseLifeAndManaLeech(const std::string& tmpStrValue, pugi::xml_ } } -void ItemParse::parseMaxHitAndManaPoints(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseMaxHitAndManaPoints(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "maxhitpoints") { itemType.getAbilities().stats[STAT_MAXHITPOINTS] = pugi::cast(valueAttribute.value()); @@ -484,7 +476,7 @@ void ItemParse::parseMaxHitAndManaPoints(const std::string& tmpStrValue, pugi::x } } -void ItemParse::parseMagicPoints(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseMagicPoints(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "magicpoints") { itemType.getAbilities().stats[STAT_MAGICPOINTS] = pugi::cast(valueAttribute.value()); @@ -493,7 +485,7 @@ void ItemParse::parseMagicPoints(const std::string& tmpStrValue, pugi::xml_attri } } -void ItemParse::parseFieldAbsorbPercent(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseFieldAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "fieldabsorbpercentenergy") { itemType.getAbilities().fieldAbsorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += pugi::cast(valueAttribute.value()); @@ -504,24 +496,24 @@ void ItemParse::parseFieldAbsorbPercent(const std::string& tmpStrValue, pugi::xm } } -void ItemParse::parseAbsorbPercent(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "absorbpercentall") { int16_t value = pugi::cast(valueAttribute.value()); - Abilities & abilities = itemType.getAbilities(); - for (auto & i: abilities.absorbPercent) { + Abilities &abilities = itemType.getAbilities(); + for (auto &i : abilities.absorbPercent) { i += value; } } else if (stringValue == "absorbpercentelements") { int16_t value = pugi::cast(valueAttribute.value()); - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.absorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_FIREDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_EARTHDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_ICEDAMAGE)] += value; } else if (stringValue == "absorbpercentmagic") { int16_t value = pugi::cast(valueAttribute.value()); - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.absorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_FIREDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_EARTHDAMAGE)] += value; @@ -553,7 +545,7 @@ void ItemParse::parseAbsorbPercent(const std::string& tmpStrValue, pugi::xml_att } } -void ItemParse::parseSupressDrunk(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseSupressDrunk(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (valueAttribute.as_bool()) { if (stringValue == "suppressdrunk") { @@ -598,8 +590,7 @@ std::tuple ItemParse::parseFieldConditions(std:: conditionType = CONDITION_BLEEDING; return std::make_tuple(conditionId, conditionType); } else { - SPDLOG_WARN("[Items::parseItemNode] Unknown field value {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] Unknown field value {}", valueAttribute.as_string()); } return std::make_tuple(CONDITIONID_DEFAULT, CONDITION_NONE); } @@ -617,13 +608,12 @@ CombatType_t ItemParse::parseFieldCombatType(std::string lowerStringValue, pugi: } else if (lowerStringValue == "physical") { return COMBAT_PHYSICALDAMAGE; } else { - SPDLOG_WARN("[Items::parseItemNode] Unknown field value {}", - valueAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] Unknown field value {}", valueAttribute.as_string()); } return COMBAT_NONE; } -void ItemParse::parseFieldCombatDamage(ConditionDamage *conditionDamage, std::string stringValue, pugi::xml_node attributeNode) { +void ItemParse::parseFieldCombatDamage(ConditionDamage* conditionDamage, std::string stringValue, pugi::xml_node attributeNode) { uint32_t combatTicks = 0; int32_t combatDamage = 0; int32_t combatStart = 0; @@ -653,9 +643,9 @@ void ItemParse::parseFieldCombatDamage(ConditionDamage *conditionDamage, std::st conditionDamage->addDamage(combatCount, combatTicks, combatDamage); } - std::listdamageList; + std::list damageList; ConditionDamage::generateDamageList(combatDamage, combatStart, damageList); - for (int32_t damageValue: damageList) { + for (int32_t damageValue : damageList) { conditionDamage->addDamage(1, combatTicks, -damageValue); } @@ -664,7 +654,7 @@ void ItemParse::parseFieldCombatDamage(ConditionDamage *conditionDamage, std::st } } -void ItemParse::parseField(const std::string& tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseField(const std::string &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType) { if (tmpStrValue == "field") { CombatType_t combatType = COMBAT_NONE; ConditionDamage* conditionDamage = nullptr; @@ -694,21 +684,21 @@ void ItemParse::parseField(const std::string& tmpStrValue, pugi::xml_node attrib } } -void ItemParse::parseReplaceable(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseReplaceable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "replaceable") { itemType.replaceable = valueAttribute.as_bool(); } } -void ItemParse::parseLevelDoor(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseLevelDoor(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "leveldoor") { itemType.levelDoor = pugi::cast(valueAttribute.value()); } } -void ItemParse::parseBeds(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseBeds(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "partnerdirection") { itemType.bedPartnerDir = getDirection(valueAttribute.as_string()); @@ -716,7 +706,7 @@ void ItemParse::parseBeds(const std::string& tmpStrValue, pugi::xml_attribute va if (stringValue == "maletransformto") { uint16_t valueMale = pugi::cast(valueAttribute.value()); - ItemType & other = Item::items.getItemType(valueMale); + ItemType &other = Item::items.getItemType(valueMale); itemType.transformToOnUse[PLAYERSEX_MALE] = valueMale; if (other.transformToFree == 0) { other.transformToFree = itemType.id; @@ -727,7 +717,7 @@ void ItemParse::parseBeds(const std::string& tmpStrValue, pugi::xml_attribute va } } else if (stringValue == "femaletransformto") { uint16_t valueFemale = pugi::cast(valueAttribute.value()); - ItemType & other = Item::items.getItemType(valueFemale); + ItemType &other = Item::items.getItemType(valueFemale); itemType.transformToOnUse[PLAYERSEX_FEMALE] = valueFemale; @@ -741,36 +731,36 @@ void ItemParse::parseBeds(const std::string& tmpStrValue, pugi::xml_attribute va } } -void ItemParse::parseElement(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseElement(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "elementice") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); abilities.elementType = COMBAT_ICEDAMAGE; } else if (stringValue == "elementearth") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); abilities.elementType = COMBAT_EARTHDAMAGE; } else if (stringValue == "elementfire") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); abilities.elementType = COMBAT_FIREDAMAGE; } else if (stringValue == "elementenergy") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); abilities.elementType = COMBAT_ENERGYDAMAGE; } else if (stringValue == "elementdeath") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); abilities.elementType = COMBAT_DEATHDAMAGE; } else if (stringValue == "elementholy") { - Abilities & abilities = itemType.getAbilities(); + Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); abilities.elementType = COMBAT_HOLYDAMAGE; } } -void ItemParse::parseWalk(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseWalk(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "walkstack") { itemType.walkStack = valueAttribute.as_bool(); @@ -779,20 +769,20 @@ void ItemParse::parseWalk(const std::string& tmpStrValue, pugi::xml_attribute va } } -void ItemParse::parseAllowDistanceRead(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseAllowDistanceRead(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { std::string stringValue = tmpStrValue; if (stringValue == "allowdistread") { itemType.allowDistRead = booleanString(valueAttribute.as_string()); } } -void ItemParse::parseImbuement(const std::string& tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType& itemType) { +void ItemParse::parseImbuement(const std::string &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType) { if (tmpStrValue != "imbuementslot") { return; } itemType.imbuementSlot = pugi::cast(valueAttribute.value()); - for (auto subAttributeNode: attributeNode.children()) { + for (auto subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; @@ -810,12 +800,8 @@ void ItemParse::parseImbuement(const std::string& tmpStrValue, pugi::xml_node at itemType.setImbuementType(imbuementType, pugi::cast(subValueAttribute.value())); continue; } + } else { + SPDLOG_WARN("[ParseImbuement::initParseImbuement] - Unknown type: {}", valueAttribute.as_string()); } - else - { - SPDLOG_WARN("[ParseImbuement::initParseImbuement] - Unknown type: {}", - valueAttribute.as_string()); - } - } } diff --git a/src/items/functions/item/item_parse.hpp b/src/items/functions/item/item_parse.hpp index e6ff5eb5e79..3b797dd3a21 100644 --- a/src/items/functions/item/item_parse.hpp +++ b/src/items/functions/item/item_parse.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_FUNCTIONS_ITEM_ITEM_PARSE_HPP_ #define SRC_ITEMS_FUNCTIONS_ITEM_ITEM_PARSE_HPP_ @@ -18,271 +18,270 @@ class ConditionDamage; const phmap::flat_hash_map ItemParseAttributesMap = { - {"type", ITEM_PARSE_TYPE}, - {"description", ITEM_PARSE_DESCRIPTION}, - {"runespellname", ITEM_PARSE_RUNESPELLNAME}, - {"weight", ITEM_PARSE_WEIGHT}, - {"showcount", ITEM_PARSE_SHOWCOUNT}, - {"armor", ITEM_PARSE_ARMOR}, - {"defense", ITEM_PARSE_DEFENSE}, - {"extradef", ITEM_PARSE_EXTRADEF}, - {"attack", ITEM_PARSE_ATTACK}, - {"rotateto", ITEM_PARSE_ROTATETO}, - {"wrapcontainer", ITEM_PARSE_WRAPCONTAINER}, - {"wrapableto", ITEM_PARSE_WRAPABLETO}, - {"unwrapableto", ITEM_PARSE_WRAPABLETO}, - {"moveable", ITEM_PARSE_MOVEABLE}, - {"movable", ITEM_PARSE_MOVEABLE}, - {"blockprojectile", ITEM_PARSE_BLOCKPROJECTILE}, - {"allowpickupable", ITEM_PARSE_PICKUPABLE}, - {"pickupable", ITEM_PARSE_PICKUPABLE}, - {"floorchange", ITEM_PARSE_FLOORCHANGE}, - {"containersize", ITEM_PARSE_CONTAINERSIZE}, - {"fluidsource", ITEM_PARSE_FLUIDSOURCE}, - {"readable", ITEM_PARSE_READABLE}, - {"writeable", ITEM_PARSE_WRITEABLE}, - {"maxtextlen", ITEM_PARSE_MAXTEXTLEN}, - {"writeonceitemid", ITEM_PARSE_WRITEONCEITEMID}, - {"weapontype", ITEM_PARSE_WEAPONTYPE}, - {"slottype", ITEM_PARSE_SLOTTYPE}, - {"ammotype", ITEM_PARSE_AMMOTYPE}, - {"shoottype", ITEM_PARSE_SHOOTTYPE}, - {"effect", ITEM_PARSE_EFFECT}, - {"loottype", ITEM_PARSE_LOOTTYPE}, - {"range", ITEM_PARSE_RANGE}, - {"stopduration", ITEM_PARSE_STOPDURATION}, - {"decayto", ITEM_PARSE_DECAYTO}, - {"transformequipto", ITEM_PARSE_TRANSFORMEQUIPTO}, - {"transformdeequipto", ITEM_PARSE_TRANSFORMDEEQUIPTO}, - {"duration", ITEM_PARSE_DURATION}, - {"showduration", ITEM_PARSE_SHOWDURATION}, - {"charges", ITEM_PARSE_CHARGES}, - {"showcharges", ITEM_PARSE_SHOWCHARGES}, - {"showattributes", ITEM_PARSE_SHOWATTRIBUTES}, - {"hitchance", ITEM_PARSE_HITCHANCE}, - {"maxhitchance", ITEM_PARSE_MAXHITCHANCE}, - {"invisible", ITEM_PARSE_INVISIBLE}, - {"speed", ITEM_PARSE_SPEED}, - {"healthgain", ITEM_PARSE_HEALTHGAIN}, - {"healthticks", ITEM_PARSE_HEALTHTICKS}, - {"managain", ITEM_PARSE_MANAGAIN}, - {"manaticks", ITEM_PARSE_MANATICKS}, - {"manashield", ITEM_PARSE_MANASHIELD}, - {"skillsword", ITEM_PARSE_SKILLSWORD}, - {"skillaxe", ITEM_PARSE_SKILLAXE}, - {"skillclub", ITEM_PARSE_SKILLCLUB}, - {"skilldist", ITEM_PARSE_SKILLDIST}, - {"skillfish", ITEM_PARSE_SKILLFISH}, - {"skillshield", ITEM_PARSE_SKILLSHIELD}, - {"skillfist", ITEM_PARSE_SKILLFIST}, - {"criticalhitchance", ITEM_PARSE_CRITICALHITCHANCE}, - {"criticalhitdamage", ITEM_PARSE_CRITICALHITDAMAGE}, - {"lifeleechchance", ITEM_PARSE_LIFELEECHCHANCE}, - {"lifeleechamount", ITEM_PARSE_LIFELEECHAMOUNT}, - {"manaleechchance", ITEM_PARSE_MANALEECHCHANCE}, - {"manaleechamount", ITEM_PARSE_MANALEECHAMOUNT}, - {"maxhitpoints", ITEM_PARSE_MAXHITPOINTS}, - {"maxhitpointspercent", ITEM_PARSE_MAXHITPOINTSPERCENT}, - {"maxmanapoints", ITEM_PARSE_MAXMANAPOINTS}, - {"maxmanapointspercent", ITEM_PARSE_MAXMANAPOINTSPERCENT}, - {"magicpoints", ITEM_PARSE_MAGICPOINTS}, - {"magicpointspercent", ITEM_PARSE_MAGICPOINTSPERCENT}, - {"fieldabsorbpercentenergy", ITEM_PARSE_FIELDABSORBPERCENTENERGY}, - {"fieldabsorbpercentfire", ITEM_PARSE_FIELDABSORBPERCENTFIRE}, - {"fieldabsorbpercentpoison", ITEM_PARSE_FIELDABSORBPERCENTPOISON}, - {"fieldabsorbpercentearth", ITEM_PARSE_FIELDABSORBPERCENTPOISON}, - {"absorbpercentall", ITEM_PARSE_ABSORBPERCENTALL}, - {"absorbpercentallelements", ITEM_PARSE_ABSORBPERCENTELEMENTS}, - {"absorbpercentelements", ITEM_PARSE_ABSORBPERCENTELEMENTS}, - {"absorbpercentmagic", ITEM_PARSE_ABSORBPERCENTMAGIC}, - {"absorbpercentenergy", ITEM_PARSE_ABSORBPERCENTENERGY}, - {"absorbpercentfire", ITEM_PARSE_ABSORBPERCENTFIRE}, - {"absorbpercentpoison", ITEM_PARSE_ABSORBPERCENTPOISON}, - {"absorbpercentearth", ITEM_PARSE_ABSORBPERCENTPOISON}, - {"absorbpercentice", ITEM_PARSE_ABSORBPERCENTICE}, - {"absorbpercentholy", ITEM_PARSE_ABSORBPERCENTHOLY}, - {"absorbpercentdeath", ITEM_PARSE_ABSORBPERCENTDEATH}, - {"absorbpercentlifedrain", ITEM_PARSE_ABSORBPERCENTLIFEDRAIN}, - {"absorbpercentmanadrain", ITEM_PARSE_ABSORBPERCENTMANADRAIN}, - {"absorbpercentdrown", ITEM_PARSE_ABSORBPERCENTDROWN}, - {"absorbpercentphysical", ITEM_PARSE_ABSORBPERCENTPHYSICAL}, - {"absorbpercenthealing", ITEM_PARSE_ABSORBPERCENTHEALING}, - {"suppressdrunk", ITEM_PARSE_SUPPRESSDRUNK}, - {"suppressenergy", ITEM_PARSE_SUPPRESSENERGY}, - {"suppressfire", ITEM_PARSE_SUPPRESSFIRE}, - {"suppresspoison", ITEM_PARSE_SUPPRESSPOISON}, - {"suppressdrown", ITEM_PARSE_SUPPRESSDROWN}, - {"suppressphysical", ITEM_PARSE_SUPPRESSPHYSICAL}, - {"suppressfreeze", ITEM_PARSE_SUPPRESSFREEZE}, - {"suppressdazzle", ITEM_PARSE_SUPPRESSDAZZLE}, - {"suppresscurse", ITEM_PARSE_SUPPRESSCURSE}, - {"field", ITEM_PARSE_FIELD}, - {"replaceable", ITEM_PARSE_REPLACEABLE}, - {"partnerdirection", ITEM_PARSE_PARTNERDIRECTION}, - {"leveldoor", ITEM_PARSE_LEVELDOOR}, - {"maletransformto", ITEM_PARSE_MALETRANSFORMTO}, - {"malesleeper", ITEM_PARSE_MALETRANSFORMTO}, - {"femaletransformto", ITEM_PARSE_FEMALETRANSFORMTO}, - {"femalesleeper", ITEM_PARSE_FEMALETRANSFORMTO}, - {"transformto", ITEM_PARSE_TRANSFORMTO}, - {"destroyto", ITEM_PARSE_DESTROYTO}, - {"elementice", ITEM_PARSE_ELEMENTICE}, - {"elementearth", ITEM_PARSE_ELEMENTEARTH}, - {"elementfire", ITEM_PARSE_ELEMENTFIRE}, - {"elementenergy", ITEM_PARSE_ELEMENTENERGY}, - {"elementdeath", ITEM_PARSE_ELEMENTDEATH}, - {"elementholy", ITEM_PARSE_ELEMENTHOLY}, - {"walkstack", ITEM_PARSE_WALKSTACK}, - {"blocking", ITEM_PARSE_BLOCK_SOLID}, - {"allowdistread", ITEM_PARSE_ALLOWDISTREAD}, - {"imbuementslot", ITEM_PARSE_IMBUEMENT}, + { "type", ITEM_PARSE_TYPE }, + { "description", ITEM_PARSE_DESCRIPTION }, + { "runespellname", ITEM_PARSE_RUNESPELLNAME }, + { "weight", ITEM_PARSE_WEIGHT }, + { "showcount", ITEM_PARSE_SHOWCOUNT }, + { "armor", ITEM_PARSE_ARMOR }, + { "defense", ITEM_PARSE_DEFENSE }, + { "extradef", ITEM_PARSE_EXTRADEF }, + { "attack", ITEM_PARSE_ATTACK }, + { "rotateto", ITEM_PARSE_ROTATETO }, + { "wrapcontainer", ITEM_PARSE_WRAPCONTAINER }, + { "wrapableto", ITEM_PARSE_WRAPABLETO }, + { "unwrapableto", ITEM_PARSE_WRAPABLETO }, + { "moveable", ITEM_PARSE_MOVEABLE }, + { "movable", ITEM_PARSE_MOVEABLE }, + { "blockprojectile", ITEM_PARSE_BLOCKPROJECTILE }, + { "allowpickupable", ITEM_PARSE_PICKUPABLE }, + { "pickupable", ITEM_PARSE_PICKUPABLE }, + { "floorchange", ITEM_PARSE_FLOORCHANGE }, + { "containersize", ITEM_PARSE_CONTAINERSIZE }, + { "fluidsource", ITEM_PARSE_FLUIDSOURCE }, + { "readable", ITEM_PARSE_READABLE }, + { "writeable", ITEM_PARSE_WRITEABLE }, + { "maxtextlen", ITEM_PARSE_MAXTEXTLEN }, + { "writeonceitemid", ITEM_PARSE_WRITEONCEITEMID }, + { "weapontype", ITEM_PARSE_WEAPONTYPE }, + { "slottype", ITEM_PARSE_SLOTTYPE }, + { "ammotype", ITEM_PARSE_AMMOTYPE }, + { "shoottype", ITEM_PARSE_SHOOTTYPE }, + { "effect", ITEM_PARSE_EFFECT }, + { "loottype", ITEM_PARSE_LOOTTYPE }, + { "range", ITEM_PARSE_RANGE }, + { "stopduration", ITEM_PARSE_STOPDURATION }, + { "decayto", ITEM_PARSE_DECAYTO }, + { "transformequipto", ITEM_PARSE_TRANSFORMEQUIPTO }, + { "transformdeequipto", ITEM_PARSE_TRANSFORMDEEQUIPTO }, + { "duration", ITEM_PARSE_DURATION }, + { "showduration", ITEM_PARSE_SHOWDURATION }, + { "charges", ITEM_PARSE_CHARGES }, + { "showcharges", ITEM_PARSE_SHOWCHARGES }, + { "showattributes", ITEM_PARSE_SHOWATTRIBUTES }, + { "hitchance", ITEM_PARSE_HITCHANCE }, + { "maxhitchance", ITEM_PARSE_MAXHITCHANCE }, + { "invisible", ITEM_PARSE_INVISIBLE }, + { "speed", ITEM_PARSE_SPEED }, + { "healthgain", ITEM_PARSE_HEALTHGAIN }, + { "healthticks", ITEM_PARSE_HEALTHTICKS }, + { "managain", ITEM_PARSE_MANAGAIN }, + { "manaticks", ITEM_PARSE_MANATICKS }, + { "manashield", ITEM_PARSE_MANASHIELD }, + { "skillsword", ITEM_PARSE_SKILLSWORD }, + { "skillaxe", ITEM_PARSE_SKILLAXE }, + { "skillclub", ITEM_PARSE_SKILLCLUB }, + { "skilldist", ITEM_PARSE_SKILLDIST }, + { "skillfish", ITEM_PARSE_SKILLFISH }, + { "skillshield", ITEM_PARSE_SKILLSHIELD }, + { "skillfist", ITEM_PARSE_SKILLFIST }, + { "criticalhitchance", ITEM_PARSE_CRITICALHITCHANCE }, + { "criticalhitdamage", ITEM_PARSE_CRITICALHITDAMAGE }, + { "lifeleechchance", ITEM_PARSE_LIFELEECHCHANCE }, + { "lifeleechamount", ITEM_PARSE_LIFELEECHAMOUNT }, + { "manaleechchance", ITEM_PARSE_MANALEECHCHANCE }, + { "manaleechamount", ITEM_PARSE_MANALEECHAMOUNT }, + { "maxhitpoints", ITEM_PARSE_MAXHITPOINTS }, + { "maxhitpointspercent", ITEM_PARSE_MAXHITPOINTSPERCENT }, + { "maxmanapoints", ITEM_PARSE_MAXMANAPOINTS }, + { "maxmanapointspercent", ITEM_PARSE_MAXMANAPOINTSPERCENT }, + { "magicpoints", ITEM_PARSE_MAGICPOINTS }, + { "magicpointspercent", ITEM_PARSE_MAGICPOINTSPERCENT }, + { "fieldabsorbpercentenergy", ITEM_PARSE_FIELDABSORBPERCENTENERGY }, + { "fieldabsorbpercentfire", ITEM_PARSE_FIELDABSORBPERCENTFIRE }, + { "fieldabsorbpercentpoison", ITEM_PARSE_FIELDABSORBPERCENTPOISON }, + { "fieldabsorbpercentearth", ITEM_PARSE_FIELDABSORBPERCENTPOISON }, + { "absorbpercentall", ITEM_PARSE_ABSORBPERCENTALL }, + { "absorbpercentallelements", ITEM_PARSE_ABSORBPERCENTELEMENTS }, + { "absorbpercentelements", ITEM_PARSE_ABSORBPERCENTELEMENTS }, + { "absorbpercentmagic", ITEM_PARSE_ABSORBPERCENTMAGIC }, + { "absorbpercentenergy", ITEM_PARSE_ABSORBPERCENTENERGY }, + { "absorbpercentfire", ITEM_PARSE_ABSORBPERCENTFIRE }, + { "absorbpercentpoison", ITEM_PARSE_ABSORBPERCENTPOISON }, + { "absorbpercentearth", ITEM_PARSE_ABSORBPERCENTPOISON }, + { "absorbpercentice", ITEM_PARSE_ABSORBPERCENTICE }, + { "absorbpercentholy", ITEM_PARSE_ABSORBPERCENTHOLY }, + { "absorbpercentdeath", ITEM_PARSE_ABSORBPERCENTDEATH }, + { "absorbpercentlifedrain", ITEM_PARSE_ABSORBPERCENTLIFEDRAIN }, + { "absorbpercentmanadrain", ITEM_PARSE_ABSORBPERCENTMANADRAIN }, + { "absorbpercentdrown", ITEM_PARSE_ABSORBPERCENTDROWN }, + { "absorbpercentphysical", ITEM_PARSE_ABSORBPERCENTPHYSICAL }, + { "absorbpercenthealing", ITEM_PARSE_ABSORBPERCENTHEALING }, + { "suppressdrunk", ITEM_PARSE_SUPPRESSDRUNK }, + { "suppressenergy", ITEM_PARSE_SUPPRESSENERGY }, + { "suppressfire", ITEM_PARSE_SUPPRESSFIRE }, + { "suppresspoison", ITEM_PARSE_SUPPRESSPOISON }, + { "suppressdrown", ITEM_PARSE_SUPPRESSDROWN }, + { "suppressphysical", ITEM_PARSE_SUPPRESSPHYSICAL }, + { "suppressfreeze", ITEM_PARSE_SUPPRESSFREEZE }, + { "suppressdazzle", ITEM_PARSE_SUPPRESSDAZZLE }, + { "suppresscurse", ITEM_PARSE_SUPPRESSCURSE }, + { "field", ITEM_PARSE_FIELD }, + { "replaceable", ITEM_PARSE_REPLACEABLE }, + { "partnerdirection", ITEM_PARSE_PARTNERDIRECTION }, + { "leveldoor", ITEM_PARSE_LEVELDOOR }, + { "maletransformto", ITEM_PARSE_MALETRANSFORMTO }, + { "malesleeper", ITEM_PARSE_MALETRANSFORMTO }, + { "femaletransformto", ITEM_PARSE_FEMALETRANSFORMTO }, + { "femalesleeper", ITEM_PARSE_FEMALETRANSFORMTO }, + { "transformto", ITEM_PARSE_TRANSFORMTO }, + { "destroyto", ITEM_PARSE_DESTROYTO }, + { "elementice", ITEM_PARSE_ELEMENTICE }, + { "elementearth", ITEM_PARSE_ELEMENTEARTH }, + { "elementfire", ITEM_PARSE_ELEMENTFIRE }, + { "elementenergy", ITEM_PARSE_ELEMENTENERGY }, + { "elementdeath", ITEM_PARSE_ELEMENTDEATH }, + { "elementholy", ITEM_PARSE_ELEMENTHOLY }, + { "walkstack", ITEM_PARSE_WALKSTACK }, + { "blocking", ITEM_PARSE_BLOCK_SOLID }, + { "allowdistread", ITEM_PARSE_ALLOWDISTREAD }, + { "imbuementslot", ITEM_PARSE_IMBUEMENT }, }; const phmap::flat_hash_map ItemTypesMap = { - {"key", ITEM_TYPE_KEY}, - {"magicfield", ITEM_TYPE_MAGICFIELD}, - {"container", ITEM_TYPE_CONTAINER}, - {"depot", ITEM_TYPE_DEPOT}, - {"rewardchest", ITEM_TYPE_REWARDCHEST}, - {"carpet", ITEM_TYPE_CARPET}, - {"mailbox", ITEM_TYPE_MAILBOX}, - {"trashholder", ITEM_TYPE_TRASHHOLDER}, - {"teleport", ITEM_TYPE_TELEPORT}, - {"door", ITEM_TYPE_DOOR}, - {"bed", ITEM_TYPE_BED}, - {"rune", ITEM_TYPE_RUNE}, - {"supply", ITEM_TYPE_SUPPLY}, - {"creatureproduct", ITEM_TYPE_CREATUREPRODUCT}, - {"food", ITEM_TYPE_FOOD}, - {"valuable", ITEM_TYPE_VALUABLE}, - {"potion", ITEM_TYPE_POTION}, + { "key", ITEM_TYPE_KEY }, + { "magicfield", ITEM_TYPE_MAGICFIELD }, + { "container", ITEM_TYPE_CONTAINER }, + { "depot", ITEM_TYPE_DEPOT }, + { "rewardchest", ITEM_TYPE_REWARDCHEST }, + { "carpet", ITEM_TYPE_CARPET }, + { "mailbox", ITEM_TYPE_MAILBOX }, + { "trashholder", ITEM_TYPE_TRASHHOLDER }, + { "teleport", ITEM_TYPE_TELEPORT }, + { "door", ITEM_TYPE_DOOR }, + { "bed", ITEM_TYPE_BED }, + { "rune", ITEM_TYPE_RUNE }, + { "supply", ITEM_TYPE_SUPPLY }, + { "creatureproduct", ITEM_TYPE_CREATUREPRODUCT }, + { "food", ITEM_TYPE_FOOD }, + { "valuable", ITEM_TYPE_VALUABLE }, + { "potion", ITEM_TYPE_POTION }, }; const phmap::flat_hash_map TileStatesMap = { - {"down", TILESTATE_FLOORCHANGE_DOWN}, - {"north", TILESTATE_FLOORCHANGE_NORTH}, - {"south", TILESTATE_FLOORCHANGE_SOUTH}, - {"southalt", TILESTATE_FLOORCHANGE_SOUTH_ALT}, - {"west", TILESTATE_FLOORCHANGE_WEST}, - {"east", TILESTATE_FLOORCHANGE_EAST}, - {"eastalt", TILESTATE_FLOORCHANGE_EAST_ALT}, + { "down", TILESTATE_FLOORCHANGE_DOWN }, + { "north", TILESTATE_FLOORCHANGE_NORTH }, + { "south", TILESTATE_FLOORCHANGE_SOUTH }, + { "southalt", TILESTATE_FLOORCHANGE_SOUTH_ALT }, + { "west", TILESTATE_FLOORCHANGE_WEST }, + { "east", TILESTATE_FLOORCHANGE_EAST }, + { "eastalt", TILESTATE_FLOORCHANGE_EAST_ALT }, }; const phmap::flat_hash_map FluidTypesMap = { - {"water", FLUID_WATER }, - {"blood", FLUID_BLOOD}, - {"beer", FLUID_BEER}, - {"slime", FLUID_SLIME}, - {"lemonade", FLUID_LEMONADE}, - {"milk", FLUID_MILK }, - {"mana", FLUID_MANA }, - {"life", FLUID_LIFE }, - {"oil", FLUID_OIL }, - {"urine", FLUID_URINE }, - {"coconut", FLUID_COCONUTMILK }, - {"wine", FLUID_WINE }, - {"mud", FLUID_MUD }, - {"fruitjuice", FLUID_FRUITJUICE }, - {"rum", FLUID_RUM }, - {"tea", FLUID_TEA }, - {"mead", FLUID_MEAD }, - {"ink", FLUID_INK }, + { "water", FLUID_WATER }, + { "blood", FLUID_BLOOD }, + { "beer", FLUID_BEER }, + { "slime", FLUID_SLIME }, + { "lemonade", FLUID_LEMONADE }, + { "milk", FLUID_MILK }, + { "mana", FLUID_MANA }, + { "life", FLUID_LIFE }, + { "oil", FLUID_OIL }, + { "urine", FLUID_URINE }, + { "coconut", FLUID_COCONUTMILK }, + { "wine", FLUID_WINE }, + { "mud", FLUID_MUD }, + { "fruitjuice", FLUID_FRUITJUICE }, + { "rum", FLUID_RUM }, + { "tea", FLUID_TEA }, + { "mead", FLUID_MEAD }, + { "ink", FLUID_INK }, }; const phmap::flat_hash_map WeaponTypesMap = { - {"sword", WEAPON_SWORD}, - {"club", WEAPON_CLUB}, - {"axe", WEAPON_AXE}, - {"shield", WEAPON_SHIELD}, - {"distance", WEAPON_DISTANCE}, - {"wand", WEAPON_WAND}, - {"ammunition", WEAPON_AMMO} + { "sword", WEAPON_SWORD }, + { "club", WEAPON_CLUB }, + { "axe", WEAPON_AXE }, + { "shield", WEAPON_SHIELD }, + { "distance", WEAPON_DISTANCE }, + { "wand", WEAPON_WAND }, + { "ammunition", WEAPON_AMMO } }; const phmap::flat_hash_map ImbuementsTypeMap = { - {"elemental damage", IMBUEMENT_ELEMENTAL_DAMAGE}, - {"life leech", IMBUEMENT_LIFE_LEECH}, - {"mana leech", IMBUEMENT_MANA_LEECH}, - {"critical hit", IMBUEMENT_CRITICAL_HIT}, - {"elemental protection death", IMBUEMENT_ELEMENTAL_PROTECTION_DEATH}, - {"elemental protection earth", IMBUEMENT_ELEMENTAL_PROTECTION_EARTH}, - {"elemental protection fire", IMBUEMENT_ELEMENTAL_PROTECTION_FIRE}, - {"elemental protection ice", IMBUEMENT_ELEMENTAL_PROTECTION_ICE}, - {"elemental protection energy", IMBUEMENT_ELEMENTAL_PROTECTION_ENERGY}, - {"elemental protection holy", IMBUEMENT_ELEMENTAL_PROTECTION_HOLY}, - {"increase speed", IMBUEMENT_INCREASE_SPEED}, - {"skillboost axe", IMBUEMENT_SKILLBOOST_AXE}, - {"skillboost sword", IMBUEMENT_SKILLBOOST_SWORD}, - {"skillboost club", IMBUEMENT_SKILLBOOST_CLUB}, - {"skillboost shielding", IMBUEMENT_SKILLBOOST_SHIELDING}, - {"skillboost distance", IMBUEMENT_SKILLBOOST_DISTANCE}, - {"skillboost magic level", IMBUEMENT_SKILLBOOST_MAGIC_LEVEL}, - {"increase capacity", IMBUEMENT_INCREASE_CAPACITY} + { "elemental damage", IMBUEMENT_ELEMENTAL_DAMAGE }, + { "life leech", IMBUEMENT_LIFE_LEECH }, + { "mana leech", IMBUEMENT_MANA_LEECH }, + { "critical hit", IMBUEMENT_CRITICAL_HIT }, + { "elemental protection death", IMBUEMENT_ELEMENTAL_PROTECTION_DEATH }, + { "elemental protection earth", IMBUEMENT_ELEMENTAL_PROTECTION_EARTH }, + { "elemental protection fire", IMBUEMENT_ELEMENTAL_PROTECTION_FIRE }, + { "elemental protection ice", IMBUEMENT_ELEMENTAL_PROTECTION_ICE }, + { "elemental protection energy", IMBUEMENT_ELEMENTAL_PROTECTION_ENERGY }, + { "elemental protection holy", IMBUEMENT_ELEMENTAL_PROTECTION_HOLY }, + { "increase speed", IMBUEMENT_INCREASE_SPEED }, + { "skillboost axe", IMBUEMENT_SKILLBOOST_AXE }, + { "skillboost sword", IMBUEMENT_SKILLBOOST_SWORD }, + { "skillboost club", IMBUEMENT_SKILLBOOST_CLUB }, + { "skillboost shielding", IMBUEMENT_SKILLBOOST_SHIELDING }, + { "skillboost distance", IMBUEMENT_SKILLBOOST_DISTANCE }, + { "skillboost magic level", IMBUEMENT_SKILLBOOST_MAGIC_LEVEL }, + { "increase capacity", IMBUEMENT_INCREASE_CAPACITY } }; -class ItemParse : public Items -{ +class ItemParse : public Items { public: - static void initParse(const std::string& tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType& itemType); + static void initParse(const std::string &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType); protected: - static void parseType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseDescription(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseRuneSpellName(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseWeight(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseShowCount(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseArmor(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseDefense(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseExtraDefense(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseAttack(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseRotateTo(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseWrapContainer(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseWrapableTo(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseMoveable(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseBlockProjectTile(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parsePickupable(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseFloorChange(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseContainerSize(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseFluidSource(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseWriteables(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseWeaponType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseSlotType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseAmmoType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseShootType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseMagicEffect(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseLootType(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseRange(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseDecayTo(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseDuration(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseTransform(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseCharges(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseShowAttributes(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseHitChance(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseInvisible(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseSpeed(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseHealthAndMana(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseSkills(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseCriticalHit(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseLifeAndManaLeech(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseMaxHitAndManaPoints(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseMagicPoints(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseFieldAbsorbPercent(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseAbsorbPercent(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseSupressDrunk(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseField(const std::string& tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseReplaceable(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseLevelDoor(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseBeds(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseElement(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseWalk(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseAllowDistanceRead(const std::string& tmpStrValue, pugi::xml_attribute valueAttribute, ItemType& itemType); - static void parseImbuement(const std::string& tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType& itemType); + static void parseType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseDescription(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseRuneSpellName(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseWeight(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseShowCount(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseArmor(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseDefense(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseExtraDefense(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseAttack(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseRotateTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseWrapContainer(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseWrapableTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseMoveable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseBlockProjectTile(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parsePickupable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseFloorChange(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseContainerSize(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseFluidSource(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseWriteables(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseWeaponType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseSlotType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseAmmoType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseShootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseMagicEffect(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseLootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseRange(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseDecayTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseDuration(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseTransform(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseCharges(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseShowAttributes(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseHitChance(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseInvisible(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseSpeed(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseHealthAndMana(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseSkills(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseCriticalHit(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseLifeAndManaLeech(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseMaxHitAndManaPoints(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseMagicPoints(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseFieldAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseSupressDrunk(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseField(const std::string &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseReplaceable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseLevelDoor(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseBeds(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseElement(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseWalk(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseAllowDistanceRead(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType); + static void parseImbuement(const std::string &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType); private: - // Parent of the function: static void parseField - static std::tuple parseFieldConditions(std::string lowerStringValue, pugi::xml_attribute valueAttribute); - static CombatType_t parseFieldCombatType(std::string string, pugi::xml_attribute valueAttribute); - static void parseFieldCombatDamage(ConditionDamage *conditionDamage, std::string stringValue, pugi::xml_node attributeNode); + // Parent of the function: static void parseField + static std::tuple parseFieldConditions(std::string lowerStringValue, pugi::xml_attribute valueAttribute); + static CombatType_t parseFieldCombatType(std::string string, pugi::xml_attribute valueAttribute); + static void parseFieldCombatDamage(ConditionDamage* conditionDamage, std::string stringValue, pugi::xml_node attributeNode); }; #endif // SRC_ITEMS_FUNCTIONS_ITEM_PARSE_HPP_ diff --git a/src/items/item.cpp b/src/items/item.cpp index 6b1ddb4bd08..ed22153313f 100644 --- a/src/items/item.cpp +++ b/src/items/item.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -26,14 +26,12 @@ #define ITEM_IMBUEMENT_SLOT 500 - Items Item::items; -Item* Item::CreateItem(const uint16_t type, uint16_t count /*= 0*/) -{ +Item* Item::CreateItem(const uint16_t type, uint16_t count /*= 0*/) { Item* newItem = nullptr; - const ItemType& it = Item::items[type]; + const ItemType &it = Item::items[type]; if (it.stackable && count == 0) { count = 1; } @@ -74,8 +72,7 @@ Item* Item::CreateItem(const uint16_t type, uint16_t count /*= 0*/) return newItem; } -bool Item::getImbuementInfo(uint8_t slot, ImbuementInfo *imbuementInfo) const -{ +bool Item::getImbuementInfo(uint8_t slot, ImbuementInfo* imbuementInfo) const { const CustomAttribute* attribute = getCustomAttribute(std::to_string(ITEM_IMBUEMENT_SLOT + slot)); auto info = attribute ? attribute->getAttribute() : 0; imbuementInfo->imbuement = g_imbuements().getImbuement(info & 0xFF); @@ -83,21 +80,19 @@ bool Item::getImbuementInfo(uint8_t slot, ImbuementInfo *imbuementInfo) const return imbuementInfo->duration && imbuementInfo->imbuement; } -void Item::setImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) -{ +void Item::setImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { auto valueDuration = (static_cast(duration > 0 ? (duration << 8) | imbuementId : 0)); setCustomAttribute(std::to_string(ITEM_IMBUEMENT_SLOT + slot), valueDuration); } -void Item::addImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) -{ +void Item::addImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { Player* player = getHoldingPlayer(); if (!player) { return; } // Get imbuement by the id - const Imbuement *imbuement = g_imbuements().getImbuement(imbuementId); + const Imbuement* imbuement = g_imbuements().getImbuement(imbuementId); if (!imbuement) { return; } @@ -131,19 +126,16 @@ bool Item::hasImbuementCategoryId(uint16_t categoryId) const { return false; } -Container* Item::CreateItemAsContainer(const uint16_t type, uint16_t size) -{ - if (const ItemType& it = Item::items[type]; - it.id == 0 - || it.stackable - || it.multiUse - || it.moveable - || it.pickupable - || it.isDepot() - || it.isSplash() - || it.isDoor() - ) - { +Container* Item::CreateItemAsContainer(const uint16_t type, uint16_t size) { + if (const ItemType &it = Item::items[type]; + it.id == 0 + || it.stackable + || it.multiUse + || it.moveable + || it.pickupable + || it.isDepot() + || it.isSplash() + || it.isDoor()) { return nullptr; } @@ -152,8 +144,7 @@ Container* Item::CreateItemAsContainer(const uint16_t type, uint16_t size) return newItem; } -Item* Item::CreateItem(PropStream& propStream) -{ +Item* Item::CreateItem(PropStream &propStream) { uint16_t id; if (!propStream.read(id)) { return nullptr; @@ -196,9 +187,8 @@ Item* Item::CreateItem(PropStream& propStream) } Item::Item(const uint16_t itemId, uint16_t itemCount /*= 0*/) : - id(itemId) -{ - const ItemType& it = items[id]; + id(itemId) { + const ItemType &it = items[id]; auto itemCharges = it.charges; if (it.isFluidContainer() || it.isSplash()) { setAttribute(ItemAttribute_t::FLUIDTYPE, itemCount); @@ -219,16 +209,14 @@ Item::Item(const uint16_t itemId, uint16_t itemCount /*= 0*/) : setDefaultDuration(); } -Item::Item(const Item& i) : - Thing(), id(i.id), count(i.count), loadedFromMap(i.loadedFromMap) -{ +Item::Item(const Item &i) : + Thing(), id(i.id), count(i.count), loadedFromMap(i.loadedFromMap) { if (i.initAttributePtr()) { initAttributePtr().reset(new ItemAttribute()); } } -Item* Item::clone() const -{ +Item* Item::clone() const { Item* item = Item::CreateItem(id, count); if (item == nullptr) { SPDLOG_ERROR("[{}] item is nullptr", __FUNCTION__); @@ -242,8 +230,7 @@ Item* Item::clone() const return item; } -bool Item::equals(const Item* compareItem) const -{ +bool Item::equals(const Item* compareItem) const { if (!compareItem) { return false; } @@ -252,8 +239,8 @@ bool Item::equals(const Item* compareItem) const return false; } - for (const auto& attribute : initAttributePtr()->getAttributeVector()) { - for (const auto& compareAttribute : compareItem->getAttributeVector()) { + for (const auto &attribute : initAttributePtr()->getAttributeVector()) { + for (const auto &compareAttribute : compareItem->getAttributeVector()) { if (attribute.getAttributeType() != compareAttribute.getAttributeType()) { continue; } @@ -271,9 +258,8 @@ bool Item::equals(const Item* compareItem) const return true; } -void Item::setDefaultSubtype() -{ - const ItemType& it = items[id]; +void Item::setDefaultSubtype() { + const ItemType &it = items[id]; setItemCount(1); @@ -287,8 +273,7 @@ void Item::setDefaultSubtype() } } -void Item::onRemoved() -{ +void Item::onRemoved() { ScriptEnvironment::removeTempItem(this); if (hasAttribute(ItemAttribute_t::UNIQUEID)) { @@ -296,16 +281,15 @@ void Item::onRemoved() } } -void Item::setID(uint16_t newid) -{ - const ItemType& prevIt = Item::items[id]; +void Item::setID(uint16_t newid) { + const ItemType &prevIt = Item::items[id]; id = newid; - const ItemType& it = Item::items[newid]; + const ItemType &it = Item::items[newid]; uint32_t newDuration = it.decayTime * 1000; if (newDuration == 0 && !it.stopTime && it.decayTo < 0) { - //We'll get called startDecay anyway so let's schedule it - actually not in all casses + // We'll get called startDecay anyway so let's schedule it - actually not in all casses if (hasAttribute(ItemAttribute_t::DECAYSTATE)) { setDecaying(DECAYING_STOPPING); } @@ -322,8 +306,7 @@ void Item::setID(uint16_t newid) } } -Cylinder* Item::getTopParent() -{ +Cylinder* Item::getTopParent() { Cylinder* aux = getParent(); Cylinder* prevaux = dynamic_cast(this); if (!aux) { @@ -341,8 +324,7 @@ Cylinder* Item::getTopParent() return aux; } -const Cylinder* Item::getTopParent() const -{ +const Cylinder* Item::getTopParent() const { const Cylinder* aux = getParent(); const Cylinder* prevaux = dynamic_cast(this); if (!aux) { @@ -360,29 +342,26 @@ const Cylinder* Item::getTopParent() const return aux; } -Tile* Item::getTile() -{ +Tile* Item::getTile() { Cylinder* cylinder = getTopParent(); - //get root cylinder + // get root cylinder if (cylinder && cylinder->getParent()) { cylinder = cylinder->getParent(); } return dynamic_cast(cylinder); } -const Tile* Item::getTile() const -{ +const Tile* Item::getTile() const { const Cylinder* cylinder = getTopParent(); - //get root cylinder + // get root cylinder if (cylinder && cylinder->getParent()) { cylinder = cylinder->getParent(); } return dynamic_cast(cylinder); } -uint16_t Item::getSubType() const -{ - const ItemType& it = items[id]; +uint16_t Item::getSubType() const { + const ItemType &it = items[id]; if (it.isFluidContainer() || it.isSplash()) { return getAttribute(ItemAttribute_t::FLUIDTYPE); } else if (it.stackable) { @@ -393,8 +372,7 @@ uint16_t Item::getSubType() const return static_cast(count); } -Player* Item::getHoldingPlayer() const -{ +Player* Item::getHoldingPlayer() const { Cylinder* p = getParent(); while (p) { if (p->getCreature()) { @@ -406,15 +384,13 @@ Player* Item::getHoldingPlayer() const return nullptr; } -bool Item::isItemStorable() const -{ +bool Item::isItemStorable() const { auto isContainerAndHasSomethingInside = (getContainer() != NULL) && (getContainer()->getItemList().size() > 0); return (isStowable() || isContainerAndHasSomethingInside); } -void Item::setSubType(uint16_t n) -{ - const ItemType& it = items[id]; +void Item::setSubType(uint16_t n) { + const ItemType &it = items[id]; if (it.isFluidContainer() || it.isSplash()) { setAttribute(ItemAttribute_t::FLUIDTYPE, n); } else if (it.stackable) { @@ -426,8 +402,7 @@ void Item::setSubType(uint16_t n) } } -Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) -{ +Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream &propStream) { switch (attr) { case ATTR_COUNT: case ATTR_RUNE_CHARGES: { @@ -680,11 +655,11 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) break; } - //these should be handled through derived classes - //If these are called then something has changed in the items.xml since the map was saved - //just read the values + // these should be handled through derived classes + // If these are called then something has changed in the items.xml since the map was saved + // just read the values - //Depot class + // Depot class case ATTR_DEPOT_ID: { if (!propStream.skip(2)) { return ATTR_READ_ERROR; @@ -692,7 +667,7 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) break; } - //Door class + // Door class case ATTR_HOUSEDOORID: { if (!propStream.skip(1)) { return ATTR_READ_ERROR; @@ -700,7 +675,7 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) break; } - //Bed class + // Bed class case ATTR_SLEEPERGUID: { if (!propStream.skip(4)) { return ATTR_READ_ERROR; @@ -715,7 +690,7 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) break; } - //Teleport class + // Teleport class case ATTR_TELE_DEST: { if (!propStream.skip(5)) { return ATTR_READ_ERROR; @@ -723,7 +698,7 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) break; } - //Container class + // Container class case ATTR_CONTAINER_ITEMS: { return ATTR_READ_ERROR; } @@ -791,7 +766,6 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) return ATTR_READ_ERROR; }; - CustomAttribute customAttribute; if (!customAttribute.unserialize(propStream, __FUNCTION__)) { SPDLOG_ERROR("[{}] failed to read custom value", __FUNCTION__); @@ -810,8 +784,7 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream& propStream) return ATTR_READ_CONTINUE; } -bool Item::unserializeAttr(PropStream& propStream) -{ +bool Item::unserializeAttr(PropStream &propStream) { uint8_t attr_type; while (propStream.read(attr_type) && attr_type != 0) { Attr_ReadValue ret = readAttr(static_cast(attr_type), propStream); @@ -824,14 +797,12 @@ bool Item::unserializeAttr(PropStream& propStream) return true; } -bool Item::unserializeItemNode(OTB::Loader&, const OTB::Node&, PropStream& propStream) -{ +bool Item::unserializeItemNode(OTB::Loader &, const OTB::Node &, PropStream &propStream) { return unserializeAttr(propStream); } -void Item::serializeAttr(PropWriteStream& propWriteStream) const -{ - const ItemType& it = items[id]; +void Item::serializeAttr(PropWriteStream &propWriteStream) const { + const ItemType &it = items[id]; if (it.stackable || it.isFluidContainer() || it.isSplash()) { propWriteStream.write(ATTR_COUNT); propWriteStream.write(getSubType()); @@ -849,9 +820,8 @@ void Item::serializeAttr(PropWriteStream& propWriteStream) const } } - if (const std::string& text = getString(ItemAttribute_t::TEXT); - !text.empty()) - { + if (const std::string &text = getString(ItemAttribute_t::TEXT); + !text.empty()) { propWriteStream.write(ATTR_TEXT); propWriteStream.writeString(text); } @@ -861,13 +831,13 @@ void Item::serializeAttr(PropWriteStream& propWriteStream) const propWriteStream.write(writtenDate); } - const std::string& writer = getString(ItemAttribute_t::WRITER); + const std::string &writer = getString(ItemAttribute_t::WRITER); if (!writer.empty()) { propWriteStream.write(ATTR_WRITTENBY); propWriteStream.writeString(writer); } - const std::string& specialDesc = getString(ItemAttribute_t::DESCRIPTION); + const std::string &specialDesc = getString(ItemAttribute_t::DESCRIPTION); if (!specialDesc.empty()) { propWriteStream.write(ATTR_DESC); propWriteStream.writeString(specialDesc); @@ -879,8 +849,7 @@ void Item::serializeAttr(PropWriteStream& propWriteStream) const } if (auto decayState = getAttribute(ItemAttribute_t::DECAYSTATE); - decayState == DECAYING_TRUE || decayState == DECAYING_PENDING) - { + decayState == DECAYING_TRUE || decayState == DECAYING_PENDING) { propWriteStream.write(ATTR_DECAYING_STATE); propWriteStream.write(decayState); } @@ -966,13 +935,11 @@ void Item::serializeAttr(PropWriteStream& propWriteStream) const } // Serialize custom attributes, only serialize if the map not is empty - if (hasCustomAttribute()) - { + if (hasCustomAttribute()) { auto customAttributeMap = getCustomAttributeMap(); propWriteStream.write(ATTR_CUSTOM); propWriteStream.write(customAttributeMap.size()); - for (const auto &[attributeKey, customAttribute] : customAttributeMap) - { + for (const auto &[attributeKey, customAttribute] : customAttributeMap) { // Serializing custom attribute key type propWriteStream.writeString(attributeKey); // Serializing custom attribute value type @@ -981,28 +948,39 @@ void Item::serializeAttr(PropWriteStream& propWriteStream) const } } -bool Item::hasProperty(ItemProperty prop) const -{ - const ItemType& it = items[id]; +bool Item::hasProperty(ItemProperty prop) const { + const ItemType &it = items[id]; switch (prop) { - case CONST_PROP_BLOCKSOLID: return it.blockSolid; - case CONST_PROP_MOVEABLE: return it.moveable && !hasAttribute(ItemAttribute_t::UNIQUEID); - case CONST_PROP_HASHEIGHT: return it.hasHeight; - case CONST_PROP_BLOCKPROJECTILE: return it.blockProjectile; - case CONST_PROP_BLOCKPATH: return it.blockPathFind; - case CONST_PROP_ISVERTICAL: return it.isVertical; - case CONST_PROP_ISHORIZONTAL: return it.isHorizontal; - case CONST_PROP_IMMOVABLEBLOCKSOLID: return it.blockSolid && (!it.moveable || hasAttribute(ItemAttribute_t::UNIQUEID)); - case CONST_PROP_IMMOVABLEBLOCKPATH: return it.blockPathFind && (!it.moveable || hasAttribute(ItemAttribute_t::UNIQUEID)); - case CONST_PROP_IMMOVABLENOFIELDBLOCKPATH: return !it.isMagicField() && it.blockPathFind && (!it.moveable || hasAttribute(ItemAttribute_t::UNIQUEID)); - case CONST_PROP_NOFIELDBLOCKPATH: return !it.isMagicField() && it.blockPathFind; - case CONST_PROP_SUPPORTHANGABLE: return it.isHorizontal || it.isVertical; - default: return false; + case CONST_PROP_BLOCKSOLID: + return it.blockSolid; + case CONST_PROP_MOVEABLE: + return it.moveable && !hasAttribute(ItemAttribute_t::UNIQUEID); + case CONST_PROP_HASHEIGHT: + return it.hasHeight; + case CONST_PROP_BLOCKPROJECTILE: + return it.blockProjectile; + case CONST_PROP_BLOCKPATH: + return it.blockPathFind; + case CONST_PROP_ISVERTICAL: + return it.isVertical; + case CONST_PROP_ISHORIZONTAL: + return it.isHorizontal; + case CONST_PROP_IMMOVABLEBLOCKSOLID: + return it.blockSolid && (!it.moveable || hasAttribute(ItemAttribute_t::UNIQUEID)); + case CONST_PROP_IMMOVABLEBLOCKPATH: + return it.blockPathFind && (!it.moveable || hasAttribute(ItemAttribute_t::UNIQUEID)); + case CONST_PROP_IMMOVABLENOFIELDBLOCKPATH: + return !it.isMagicField() && it.blockPathFind && (!it.moveable || hasAttribute(ItemAttribute_t::UNIQUEID)); + case CONST_PROP_NOFIELDBLOCKPATH: + return !it.isMagicField() && it.blockPathFind; + case CONST_PROP_SUPPORTHANGABLE: + return it.isHorizontal || it.isVertical; + default: + return false; } } -uint32_t Item::getWeight() const -{ +uint32_t Item::getWeight() const { uint32_t baseWeight = getBaseWeight(); if (isStackable()) { return baseWeight * std::max(1, getItemCount()); @@ -1011,17 +989,17 @@ uint32_t Item::getWeight() const } std::vector> - Item::getDescriptions(const ItemType& it, const Item* item /*= nullptr*/) { +Item::getDescriptions(const ItemType &it, const Item* item /*= nullptr*/) { std::ostringstream ss; std::vector> descriptions; descriptions.reserve(30); if (item) { - const std::string& specialDescription = item->getAttribute(ItemAttribute_t::DESCRIPTION); + const std::string &specialDescription = item->getAttribute(ItemAttribute_t::DESCRIPTION); if (!specialDescription.empty()) { - descriptions.emplace_back("Description", specialDescription); - } else if (!it.description.empty()) { - descriptions.emplace_back("Description", it.description); - } + descriptions.emplace_back("Description", specialDescription); + } else if (!it.description.empty()) { + descriptions.emplace_back("Description", it.description); + } if (it.showCharges) { auto charges = item->getAttribute(ItemAttribute_t::CHARGES); @@ -1036,10 +1014,10 @@ std::vector> ss.str(""); ss << attack << " physical +" << it.abilities->elementDamage << ' ' << getCombatName(it.abilities->elementType); descriptions.emplace_back("Attack", ss.str()); - } else { + } else { descriptions.emplace_back("Attack", std::to_string(attack)); - } - } + } + } int32_t hitChance = item->getHitChance(); if (hitChance != 0) { @@ -1052,9 +1030,9 @@ std::vector> ss.str(""); ss << defense << ' ' << std::showpos << extraDefense << std::noshowpos; descriptions.emplace_back("Defense", ss.str()); - } else { + } else { descriptions.emplace_back("Defense", std::to_string(defense)); - } + } } int32_t armor = item->getArmor(); @@ -1156,7 +1134,7 @@ std::vector> uint16_t subType = item->getSubType(); if (subType > 0) { - const std::string& itemName = items[subType].name; + const std::string &itemName = items[subType].name; ss << (!itemName.empty() ? itemName : "Nothing"); } else { ss << "Nothing"; @@ -1492,30 +1470,25 @@ std::vector> return descriptions; } -std::string Item::parseImbuementDescription(const Item* item) -{ +std::string Item::parseImbuementDescription(const Item* item) { std::ostringstream s; - if (item && item->getImbuementSlot() >= 1) - { - s << std::endl << "Imbuements: ("; - - for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) - { - if (slotid >= 1) - { + if (item && item->getImbuementSlot() >= 1) { + s << std::endl + << "Imbuements: ("; + + for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) { + if (slotid >= 1) { s << ", "; } ImbuementInfo imbuementInfo; - if (!item->getImbuementInfo(slotid, &imbuementInfo)) - { + if (!item->getImbuementInfo(slotid, &imbuementInfo)) { s << "Empty Slot"; continue; } - const BaseImbuement *baseImbuement = g_imbuements().getBaseByID(imbuementInfo.imbuement->getBaseID()); - if (!baseImbuement) - { + const BaseImbuement* baseImbuement = g_imbuements().getBaseByID(imbuementInfo.imbuement->getBaseID()); + if (!baseImbuement) { continue; } @@ -1532,7 +1505,8 @@ std::string Item::parseImbuementDescription(const Item* item) std::string Item::parseClassificationDescription(const Item* item) { std::ostringstream string; if (item && item->getClassification() >= 1) { - string << std::endl << "Classification: " << std::to_string(item->getClassification()) << " Tier: " << std::to_string(item->getTier()); + string << std::endl + << "Classification: " << std::to_string(item->getClassification()) << " Tier: " << std::to_string(item->getTier()); if (item->getTier() != 0) { if (Item::items[item->getID()].weaponType != WEAPON_NONE) { string << fmt::format(" ({}% Onslaught).", item->getFatalChance()); @@ -1546,10 +1520,9 @@ std::string Item::parseClassificationDescription(const Item* item) { return string.str(); } -std::string Item::parseShowAttributesDescription(const Item *item, const uint16_t itemId) -{ +std::string Item::parseShowAttributesDescription(const Item* item, const uint16_t itemId) { std::ostringstream itemDescription; - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; if (itemType.armor != 0 || (item && item->getArmor() != 0) || itemType.showAttributes) { bool begin = true; @@ -1583,8 +1556,7 @@ std::string Item::parseShowAttributesDescription(const Item *item, const uint16_ if (begin) { begin = false; itemDescription << " ("; - } - else { + } else { itemDescription << ", "; } itemDescription << getSkillName(i) << ' '; @@ -1719,10 +1691,7 @@ std::string Item::parseShowAttributesDescription(const Item *item, const uint16_ return itemDescription.str(); } -std::string Item::getDescription(const ItemType& it, int32_t lookDistance, - const Item* item /*= nullptr*/, - int32_t subType /*= -1*/, bool addArticle /*= true*/) -{ +std::string Item::getDescription(const ItemType &it, int32_t lookDistance, const Item* item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { const std::string* text = nullptr; std::ostringstream s; @@ -1741,13 +1710,13 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, } s << " (\"" << it.runeSpellName << "\"). " << (it.stackable && tmpSubType > 1 ? "They" : "It") << " can only be used by "; - const VocSpellMap& vocMap = rune->getVocMap(); + const VocSpellMap &vocMap = rune->getVocMap(); std::vector showVocMap; // vocations are usually listed with the unpromoted and promoted version, the latter being // hidden from description, so `total / 2` is most likely the amount of vocations to be shown. showVocMap.reserve(vocMap.size() / 2); - for (const auto& voc : vocMap) { + for (const auto &voc : vocMap) { if (voc.second) { showVocMap.push_back(g_vocations().getVocation(voc.first)); } @@ -1833,8 +1802,7 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, if (begin) { begin = false; s << " ("; - } - else { + } else { s << ", "; } s << getSkillName(i) << ' '; @@ -1963,7 +1931,7 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, } if (!begin) { - s << ')'; + s << ')'; } } else if (it.weaponType != WEAPON_AMMO) { bool begin = true; @@ -2026,8 +1994,7 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, if (begin) { begin = false; s << " ("; - } - else { + } else { s << ", "; } s << getSkillName(i) << ' '; @@ -2199,7 +2166,7 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, s << fmt::format(" (Key:{:04})", item ? item->getAttribute(ItemAttribute_t::ACTIONID) : 0); } else if (it.isFluidContainer()) { if (subType > 0) { - const std::string& itemName = items[subType].name; + const std::string &itemName = items[subType].name; s << " of " << (!itemName.empty() ? itemName : "unknown"); } else { s << ". It is empty"; @@ -2220,7 +2187,7 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, auto string = item->getAttribute(ItemAttribute_t::TEXT); text = &string; if (!text->empty()) { - const std::string& writer = item->getAttribute(ItemAttribute_t::WRITER); + const std::string &writer = item->getAttribute(ItemAttribute_t::WRITER); if (!writer.empty()) { s << writer << " wrote"; auto date = item->getAttribute(ItemAttribute_t::DATE); @@ -2257,9 +2224,9 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, } if (it.showCharges) { - if (subType == 0){ + if (subType == 0) { s << " that has " << it.charges << " charge" << (subType != 1 ? "s" : "") << " left"; - } else{ + } else { s << " that has " << subType << " charge" << (subType != 1 ? "s" : "") << " left"; } } @@ -2315,7 +2282,8 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, } if (it.wieldInfo != 0) { - s << std::endl << "It can only be wielded properly by "; + s << std::endl + << "It can only be wielded properly by "; if (it.wieldInfo & WIELDINFO_PREMIUM) { s << "premium "; @@ -2352,22 +2320,27 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, if (item) { const uint32_t weight = item->getWeight(); if (weight != 0 && it.pickupable) { - s << std::endl << getWeightDescription(it, weight, item->getItemCount()); + s << std::endl + << getWeightDescription(it, weight, item->getItemCount()); } } else if (it.weight != 0 && it.pickupable) { - s << std::endl << getWeightDescription(it, it.weight); + s << std::endl + << getWeightDescription(it, it.weight); } } if (item) { - const std::string& specialDescription = item->getAttribute(ItemAttribute_t::DESCRIPTION); + const std::string &specialDescription = item->getAttribute(ItemAttribute_t::DESCRIPTION); if (!specialDescription.empty()) { - s << std::endl << specialDescription; + s << std::endl + << specialDescription; } else if (lookDistance <= 1 && !it.description.empty()) { - s << std::endl << it.description; + s << std::endl + << it.description; } } else if (lookDistance <= 1 && !it.description.empty()) { - s << std::endl << it.description; + s << std::endl + << it.description; } if (it.allowDistRead && it.id >= 7369 && it.id <= 7371) { @@ -2377,27 +2350,26 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, } if (text && !text->empty()) { - s << std::endl << *text; + s << std::endl + << *text; } } return s.str(); } -std::string Item::getDescription(int32_t lookDistance) const -{ - const ItemType& it = items[id]; +std::string Item::getDescription(int32_t lookDistance) const { + const ItemType &it = items[id]; return getDescription(it, lookDistance, this); } -std::string Item::getNameDescription(const ItemType& it, const Item* item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) -{ +std::string Item::getNameDescription(const ItemType &it, const Item* item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { if (item) { subType = item->getSubType(); } std::ostringstream s; - const std::string& name = (item ? item->getName() : it.name); + const std::string &name = (item ? item->getName() : it.name); if (!name.empty()) { if (it.stackable && subType > 1) { if (it.showCount) { @@ -2407,7 +2379,7 @@ std::string Item::getNameDescription(const ItemType& it, const Item* item /*= nu s << (item ? item->getPluralName() : it.getPluralName()); } else { if (addArticle) { - const std::string& article = (item ? item->getArticle() : it.article); + const std::string &article = (item ? item->getArticle() : it.article); if (!article.empty()) { s << article << ' '; } @@ -2421,14 +2393,12 @@ std::string Item::getNameDescription(const ItemType& it, const Item* item /*= nu return s.str(); } -std::string Item::getNameDescription() const -{ - const ItemType& it = items[id]; +std::string Item::getNameDescription() const { + const ItemType &it = items[id]; return getNameDescription(it, this); } -std::string Item::getWeightDescription(const ItemType& it, uint32_t weight, uint32_t count /*= 1*/) -{ +std::string Item::getWeightDescription(const ItemType &it, uint32_t weight, uint32_t count /*= 1*/) { std::ostringstream ss; if (it.stackable && count > 1 && it.showCount != 0) { ss << "They weigh "; @@ -2450,14 +2420,12 @@ std::string Item::getWeightDescription(const ItemType& it, uint32_t weight, uint return ss.str(); } -std::string Item::getWeightDescription(uint32_t weight) const -{ - const ItemType& it = Item::items[id]; +std::string Item::getWeightDescription(uint32_t weight) const { + const ItemType &it = Item::items[id]; return getWeightDescription(it, weight, getItemCount()); } -std::string Item::getWeightDescription() const -{ +std::string Item::getWeightDescription() const { uint32_t weight = getWeight(); if (weight == 0) { return std::string(); @@ -2465,8 +2433,7 @@ std::string Item::getWeightDescription() const return getWeightDescription(weight); } -void Item::addUniqueId(uint16_t uniqueId) -{ +void Item::addUniqueId(uint16_t uniqueId) { if (hasAttribute(ItemAttribute_t::UNIQUEID)) { return; } @@ -2476,13 +2443,12 @@ void Item::addUniqueId(uint16_t uniqueId) } } -bool Item::canDecay() const -{ +bool Item::canDecay() const { if (isRemoved()) { return false; } - const ItemType& it = Item::items[id]; + const ItemType &it = Item::items[id]; if (it.decayTo < 0 || it.decayTime == 0) { return false; } @@ -2494,8 +2460,7 @@ bool Item::canDecay() const return true; } -uint32_t Item::getWorth() const -{ +uint32_t Item::getWorth() const { switch (id) { case ITEM_GOLD_COIN: return count; @@ -2511,45 +2476,39 @@ uint32_t Item::getWorth() const } } -uint32_t Item::getForgeSlivers() const -{ +uint32_t Item::getForgeSlivers() const { if (getID() == ITEM_FORGE_SLIVER) return getItemCount(); else return 0; } -uint32_t Item::getForgeCores() const -{ +uint32_t Item::getForgeCores() const { if (getID() == ITEM_FORGE_CORE) return getItemCount(); else return 0; } -LightInfo Item::getLightInfo() const -{ - const ItemType& it = items[id]; - return {it.lightLevel, it.lightColor}; +LightInfo Item::getLightInfo() const { + const ItemType &it = items[id]; + return { it.lightLevel, it.lightColor }; } -void Item::startDecaying() -{ +void Item::startDecaying() { g_decay().startDecay(this); } -void Item::stopDecaying() -{ +void Item::stopDecaying() { g_decay().stopDecay(this); } -bool Item::hasMarketAttributes() const -{ +bool Item::hasMarketAttributes() const { if (!isInitializedAttributePtr()) { return true; } - for (const auto& attribute : getAttributeVector()) { + for (const auto &attribute : getAttributeVector()) { if (attribute.getAttributeType() == ItemAttribute_t::CHARGES && static_cast(attribute.getInteger()) != items[id].charges) { return false; } @@ -2570,12 +2529,8 @@ bool Item::hasMarketAttributes() const return true; } -bool Item::isInsideDepot(bool includeInbox/* = false*/) const -{ - if (const Container* thisContainer = getContainer(); thisContainer && - (thisContainer->getDepotLocker() || - thisContainer->isDepotChest() || - (includeInbox && thisContainer->isInbox()))) { +bool Item::isInsideDepot(bool includeInbox /* = false*/) const { + if (const Container* thisContainer = getContainer(); thisContainer && (thisContainer->getDepotLocker() || thisContainer->isDepotChest() || (includeInbox && thisContainer->isInbox()))) { return true; } diff --git a/src/items/item.h b/src/items/item.h index ce6072028cc..bab3a768b1e 100644 --- a/src/items/item.h +++ b/src/items/item.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_ITEM_H_ #define SRC_ITEMS_ITEM_H_ @@ -33,201 +33,198 @@ class Imbuement; // This class ItemProperties that serves as an interface to access and modify attributes of an item. The item's attributes are stored in an instance of ItemAttribute. The class ItemProperties has methods to get and set integer and string attributes, check if an attribute exists, remove an attribute, get the underlying attribute bits, and get a vector of attributes. It also has methods to get and set custom attributes, which are stored in a std::map>. The class has a data member attributePtr of type std::unique_ptr that stores a pointer to the item's attributes methods. class ItemProperties { -public: - template - T getAttribute(ItemAttribute_t type) const { - if constexpr (std::is_same_v) { - return getString(type); - } else if constexpr (std::is_integral_v) { - return std::clamp( - static_cast(getInteger(type)), - std::numeric_limits::min(), - std::numeric_limits::max() - ); - } - return T(); - } - - bool hasAttribute(ItemAttribute_t type) const { - if (!attributePtr) { - return false; + public: + template + T getAttribute(ItemAttribute_t type) const { + if constexpr (std::is_same_v) { + return getString(type); + } else if constexpr (std::is_integral_v) { + return std::clamp( + static_cast(getInteger(type)), + std::numeric_limits::min(), + std::numeric_limits::max() + ); + } + return T(); } - return attributePtr->hasAttribute(type); - } - void removeAttribute(ItemAttribute_t type) { - if (attributePtr) { - attributePtr->removeAttribute(type); + bool hasAttribute(ItemAttribute_t type) const { + if (!attributePtr) { + return false; + } + + return attributePtr->hasAttribute(type); + } + void removeAttribute(ItemAttribute_t type) { + if (attributePtr) { + attributePtr->removeAttribute(type); + } } - } - template - void setAttribute(ItemAttribute_t type, GenericAttribute genericAttribute) { - initAttributePtr()->setAttribute(type, genericAttribute); - } + template + void setAttribute(ItemAttribute_t type, GenericAttribute genericAttribute) { + initAttributePtr()->setAttribute(type, genericAttribute); + } - bool isAttributeInteger(ItemAttribute_t type) const { - return initAttributePtr()->isAttributeInteger(type); - } + bool isAttributeInteger(ItemAttribute_t type) const { + return initAttributePtr()->isAttributeInteger(type); + } - bool isAttributeString(ItemAttribute_t type) const { - return initAttributePtr()->isAttributeString(type); - } + bool isAttributeString(ItemAttribute_t type) const { + return initAttributePtr()->isAttributeString(type); + } - // Custom Attributes - const std::map>& getCustomAttributeMap() const { - static std::map> map = {}; - if (!attributePtr) { - return map; + // Custom Attributes + const std::map> &getCustomAttributeMap() const { + static std::map> map = {}; + if (!attributePtr) { + return map; + } + return attributePtr->getCustomAttributeMap(); } - return attributePtr->getCustomAttributeMap(); - } - const CustomAttribute* getCustomAttribute(const std::string& attributeName) const - { - if (!attributePtr) { - return nullptr; + const CustomAttribute* getCustomAttribute(const std::string &attributeName) const { + if (!attributePtr) { + return nullptr; + } + + return attributePtr->getCustomAttribute(attributeName); } - return attributePtr->getCustomAttribute(attributeName); - } + template + void setCustomAttribute(const std::string &key, GenericType value) { + initAttributePtr()->setCustomAttribute(key, value); + } - template - void setCustomAttribute(const std::string &key, GenericType value) { - initAttributePtr()->setCustomAttribute(key, value); - } + void addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute) { + initAttributePtr()->addCustomAttribute(key, customAttribute); + } - void addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute) - { - initAttributePtr()->addCustomAttribute(key, customAttribute); - } + bool hasCustomAttribute() const { + return !getCustomAttributeMap().empty(); + } - bool hasCustomAttribute() const { - return !getCustomAttributeMap().empty(); - } + bool removeCustomAttribute(const std::string &attributeName) { + if (!attributePtr) { + return false; + } - bool removeCustomAttribute(const std::string& attributeName) { - if (!attributePtr) { - return false; + return attributePtr->removeCustomAttribute(attributeName); } - return attributePtr->removeCustomAttribute(attributeName); - } + uint16_t getCharges() const { + return getAttribute(ItemAttribute_t::CHARGES); + } - uint16_t getCharges() const { - return getAttribute(ItemAttribute_t::CHARGES); - } + int32_t getDuration() const { + ItemDecayState_t decayState = getDecaying(); + if (decayState == DECAYING_TRUE || decayState == DECAYING_STOPPING) { + return std::max(0, getAttribute(ItemAttribute_t::DURATION_TIMESTAMP) - static_cast(OTSYS_TIME())); + } else { + return getAttribute(ItemAttribute_t::DURATION); + } + } - int32_t getDuration() const { - ItemDecayState_t decayState = getDecaying(); - if (decayState == DECAYING_TRUE || decayState == DECAYING_STOPPING) { - return std::max(0, getAttribute(ItemAttribute_t::DURATION_TIMESTAMP) - static_cast(OTSYS_TIME())); - } else { - return getAttribute(ItemAttribute_t::DURATION); + void setDecaying(ItemDecayState_t decayState) { + setAttribute(ItemAttribute_t::DECAYSTATE, static_cast(decayState)); + if (decayState == DECAYING_FALSE) { + removeAttribute(ItemAttribute_t::DURATION_TIMESTAMP); + } + } + ItemDecayState_t getDecaying() const { + return getAttribute(ItemAttribute_t::DECAYSTATE); } - } - void setDecaying(ItemDecayState_t decayState) { - setAttribute(ItemAttribute_t::DECAYSTATE, static_cast(decayState)); - if (decayState == DECAYING_FALSE) { - removeAttribute(ItemAttribute_t::DURATION_TIMESTAMP); + uint32_t getCorpseOwner() const { + return getAttribute(ItemAttribute_t::CORPSEOWNER); } - } - ItemDecayState_t getDecaying() const { - return getAttribute(ItemAttribute_t::DECAYSTATE); - } - uint32_t getCorpseOwner() const { - return getAttribute(ItemAttribute_t::CORPSEOWNER); - } + void setRewardCorpse() { + setAttribute(ItemAttribute_t::CORPSEOWNER, static_cast(std::numeric_limits::max())); + } - void setRewardCorpse() { - setAttribute(ItemAttribute_t::CORPSEOWNER, static_cast(std::numeric_limits::max())); - } + bool isRewardCorpse() const { + return getCorpseOwner() == static_cast(std::numeric_limits::max()); + } - bool isRewardCorpse() const { - return getCorpseOwner() == static_cast(std::numeric_limits::max()); - } + protected: + std::unique_ptr &initAttributePtr() { + if (!attributePtr) { + attributePtr.reset(new ItemAttribute()); + } -protected: - std::unique_ptr& initAttributePtr() { - if (!attributePtr) { - attributePtr.reset(new ItemAttribute()); + return attributePtr; } - - return attributePtr; - } - const std::unique_ptr& initAttributePtr() const { - if (!attributePtr) { - std::bit_cast(this)->attributePtr.reset(new ItemAttribute()); + const std::unique_ptr &initAttributePtr() const { + if (!attributePtr) { + std::bit_cast(this)->attributePtr.reset(new ItemAttribute()); + } + + return attributePtr; } - - return attributePtr; - } - const std::underlying_type_t& getAttributeBits() const { - static std::underlying_type_t emptyType = {}; - if (!attributePtr) { - return emptyType; + const std::underlying_type_t &getAttributeBits() const { + static std::underlying_type_t emptyType = {}; + if (!attributePtr) { + return emptyType; + } + + return attributePtr->getAttributeBits(); } + const std::vector &getAttributeVector() const { + static std::vector emptyVector = {}; + if (!attributePtr) { + return emptyVector; + } - return attributePtr->getAttributeBits(); - } - const std::vector& getAttributeVector() const { - static std::vector emptyVector = {}; - if (!attributePtr) { - return emptyVector; + return attributePtr->getAttributeVector(); } - return attributePtr->getAttributeVector(); - } + const int64_t &getInteger(ItemAttribute_t type) const { + static int64_t emptyInt; + if (!attributePtr) { + return emptyInt; + } - const int64_t& getInteger(ItemAttribute_t type) const { - static int64_t emptyInt; - if (!attributePtr) { - return emptyInt; + return attributePtr->getAttributeValue(type); } + const std::string &getString(ItemAttribute_t type) const { + static std::string emptyString; + if (!attributePtr) { + return emptyString; + } - return attributePtr->getAttributeValue(type); - } - const std::string& getString(ItemAttribute_t type) const { - static std::string emptyString; - if (!attributePtr) { - return emptyString; + return attributePtr->getAttributeString(type); } - return attributePtr->getAttributeString(type); - } + bool isInitializedAttributePtr() const { + if (!attributePtr) { + return false; + } - bool isInitializedAttributePtr() const { - if (!attributePtr) { - return false; + return true; } - return true; - } - -private: - std::unique_ptr attributePtr; + private: + std::unique_ptr attributePtr; }; -class Item : virtual public Thing, public ItemProperties -{ +class Item : virtual public Thing, public ItemProperties { public: - //Factory member to create item of right type based on type + // Factory member to create item of right type based on type static Item* CreateItem(const uint16_t type, uint16_t count = 0); static Container* CreateItemAsContainer(const uint16_t type, uint16_t size); - static Item* CreateItem(PropStream& propStream); + static Item* CreateItem(PropStream &propStream); static Items items; // Constructor for items Item(const uint16_t type, uint16_t count = 0); - Item(const Item& i); + Item(const Item &i); virtual Item* clone() const; virtual ~Item() = default; // non-assignable - Item& operator=(const Item&) = delete; + Item &operator=(const Item &) = delete; bool equals(const Item* compareItem) const; @@ -283,25 +280,24 @@ class Item : virtual public Thing, public ItemProperties } static std::string parseImbuementDescription(const Item* item); - static std::string parseShowAttributesDescription(const Item *item, const uint16_t itemId); + static std::string parseShowAttributesDescription(const Item* item, const uint16_t itemId); static std::string parseClassificationDescription(const Item* item); - static std::vector> getDescriptions(const ItemType& it, - const Item* item = nullptr); - static std::string getDescription(const ItemType& it, int32_t lookDistance, const Item* item = nullptr, int32_t subType = -1, bool addArticle = true); - static std::string getNameDescription(const ItemType& it, const Item* item = nullptr, int32_t subType = -1, bool addArticle = true); - static std::string getWeightDescription(const ItemType& it, uint32_t weight, uint32_t count = 1); + static std::vector> getDescriptions(const ItemType &it, const Item* item = nullptr); + static std::string getDescription(const ItemType &it, int32_t lookDistance, const Item* item = nullptr, int32_t subType = -1, bool addArticle = true); + static std::string getNameDescription(const ItemType &it, const Item* item = nullptr, int32_t subType = -1, bool addArticle = true); + static std::string getWeightDescription(const ItemType &it, uint32_t weight, uint32_t count = 1); std::string getDescription(int32_t lookDistance) const override final; std::string getNameDescription() const; std::string getWeightDescription() const; - //serialization - virtual Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream); - bool unserializeAttr(PropStream& propStream); - virtual bool unserializeItemNode(OTB::Loader&, const OTB::Node&, PropStream& propStream); + // serialization + virtual Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream); + bool unserializeAttr(PropStream &propStream); + virtual bool unserializeItemNode(OTB::Loader &, const OTB::Node &, PropStream &propStream); - virtual void serializeAttr(PropWriteStream& propWriteStream) const; + virtual void serializeAttr(PropWriteStream &propWriteStream) const; bool isPushable() const override final { return isMoveable(); @@ -436,7 +432,7 @@ class Item : virtual public Thing, public ItemProperties return items[id].isQuiver(); } - const std::string& getName() const { + const std::string &getName() const { if (hasAttribute(ItemAttribute_t::NAME)) { return getString(ItemAttribute_t::NAME); } @@ -448,7 +444,7 @@ class Item : virtual public Thing, public ItemProperties } return items[id].getPluralName(); } - const std::string& getArticle() const { + const std::string &getArticle() const { if (hasAttribute(ItemAttribute_t::ARTICLE)) { return getString(ItemAttribute_t::ARTICLE); } @@ -489,7 +485,7 @@ class Item : virtual public Thing, public ItemProperties uint32_t getDefaultDuration() const { return items[id].decayTime * 1000; } - + bool canDecay() const; virtual bool canRemove() const { @@ -499,7 +495,7 @@ class Item : virtual public Thing, public ItemProperties return true; } virtual void onRemoved(); - virtual void onTradeEvent(TradeEvents_t, Player*) {} + virtual void onTradeEvent(TradeEvents_t, Player*) { } virtual void startDecaying(); virtual void stopDecaying(); @@ -550,11 +546,11 @@ class Item : virtual public Thing, public ItemProperties * @return true = duration is > 0 (info >> 8) * @return false */ - bool getImbuementInfo(uint8_t slot, ImbuementInfo *imbuementInfo) const; + bool getImbuementInfo(uint8_t slot, ImbuementInfo* imbuementInfo) const; void addImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration); /** * @brief Decay imbuement time duration, only use this for decay the imbuement time - * + * * @param slot Slot id to decay * @param imbuementId Imbuement id to decay * @param duration New duration @@ -638,14 +634,15 @@ class Item : virtual public Thing, public ItemProperties uint32_t referenceCounter = 0; - uint16_t id; // the same id as in ItemType + uint16_t id; // the same id as in ItemType uint8_t count = 1; // number of stacked items bool loadedFromMap = false; bool isLootTrackeable = false; + private: void setImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration); - //Don't add variables here, use the ItemAttribute class. + // Don't add variables here, use the ItemAttribute class. std::string getWeightDescription(uint32_t weight) const; friend class Decay; @@ -655,4 +652,4 @@ using ItemList = std::list; using ItemDeque = std::deque; using StashContainerList = std::vector>; -#endif // SRC_ITEMS_ITEM_H_ +#endif // SRC_ITEMS_ITEM_H_ diff --git a/src/items/items.cpp b/src/items/items.cpp index fa4e327054a..c658e178b57 100644 --- a/src/items/items.cpp +++ b/src/items/items.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -17,8 +17,7 @@ Items::Items() = default; -void Items::clear() -{ +void Items::clear() { items.clear(); nameToItems.clear(); } @@ -26,35 +25,34 @@ void Items::clear() using LootTypeNames = phmap::flat_hash_map; LootTypeNames lootTypeNames = { - {"armor", ITEM_TYPE_ARMOR}, - {"amulet", ITEM_TYPE_AMULET}, - {"boots", ITEM_TYPE_BOOTS}, - {"container", ITEM_TYPE_CONTAINER}, - {"decoration", ITEM_TYPE_DECORATION}, - {"food", ITEM_TYPE_FOOD}, - {"helmet", ITEM_TYPE_HELMET}, - {"legs", ITEM_TYPE_LEGS}, - {"other", ITEM_TYPE_OTHER}, - {"potion", ITEM_TYPE_POTION}, - {"ring", ITEM_TYPE_RING}, - {"rune", ITEM_TYPE_RUNE}, - {"shield", ITEM_TYPE_SHIELD}, - {"tools", ITEM_TYPE_TOOLS}, - {"valuable", ITEM_TYPE_VALUABLE}, - {"ammo", ITEM_TYPE_AMMO}, - {"axe", ITEM_TYPE_AXE}, - {"club", ITEM_TYPE_CLUB}, - {"distance", ITEM_TYPE_DISTANCE}, - {"sword", ITEM_TYPE_SWORD}, - {"wand", ITEM_TYPE_WAND}, - {"creatureproduct", ITEM_TYPE_CREATUREPRODUCT}, - {"retrieve", ITEM_TYPE_RETRIEVE}, - {"gold", ITEM_TYPE_GOLD}, - {"unassigned", ITEM_TYPE_UNASSIGNED}, + { "armor", ITEM_TYPE_ARMOR }, + { "amulet", ITEM_TYPE_AMULET }, + { "boots", ITEM_TYPE_BOOTS }, + { "container", ITEM_TYPE_CONTAINER }, + { "decoration", ITEM_TYPE_DECORATION }, + { "food", ITEM_TYPE_FOOD }, + { "helmet", ITEM_TYPE_HELMET }, + { "legs", ITEM_TYPE_LEGS }, + { "other", ITEM_TYPE_OTHER }, + { "potion", ITEM_TYPE_POTION }, + { "ring", ITEM_TYPE_RING }, + { "rune", ITEM_TYPE_RUNE }, + { "shield", ITEM_TYPE_SHIELD }, + { "tools", ITEM_TYPE_TOOLS }, + { "valuable", ITEM_TYPE_VALUABLE }, + { "ammo", ITEM_TYPE_AMMO }, + { "axe", ITEM_TYPE_AXE }, + { "club", ITEM_TYPE_CLUB }, + { "distance", ITEM_TYPE_DISTANCE }, + { "sword", ITEM_TYPE_SWORD }, + { "wand", ITEM_TYPE_WAND }, + { "creatureproduct", ITEM_TYPE_CREATUREPRODUCT }, + { "retrieve", ITEM_TYPE_RETRIEVE }, + { "gold", ITEM_TYPE_GOLD }, + { "unassigned", ITEM_TYPE_UNASSIGNED }, }; -ItemTypes_t Items::getLootType(const std::string& strValue) -{ +ItemTypes_t Items::getLootType(const std::string &strValue) { auto lootType = lootTypeNames.find(strValue); if (lootType != lootTypeNames.end()) { return lootType->second; @@ -62,8 +60,7 @@ ItemTypes_t Items::getLootType(const std::string& strValue) return ITEM_TYPE_NONE; } -bool Items::reload() -{ +bool Items::reload() { clear(); loadFromProtobuf(); @@ -74,8 +71,7 @@ bool Items::reload() return true; } -void Items::loadFromProtobuf() -{ +void Items::loadFromProtobuf() { using namespace Canary::protobuf::appearances; for (uint32_t it = 0; it < g_game().appearances.object_size(); ++it) { @@ -91,7 +87,7 @@ void Items::loadFromProtobuf() items.resize(object.id() + 1); } - ItemType& iType = items[object.id()]; + ItemType &iType = items[object.id()]; if (object.flags().container()) { iType.type = ITEM_TYPE_CONTAINER; iType.group = ITEM_GROUP_CONTAINER; @@ -155,18 +151,15 @@ void Items::loadFromProtobuf() iType.expireStop = object.flags().expirestop(); if (!iType.name.empty()) { - nameToItems.insert({ - asLowerCaseString(iType.name), - iType.id - }); + nameToItems.insert({ asLowerCaseString(iType.name), + iType.id }); } } items.shrink_to_fit(); } -bool Items::loadFromXml() -{ +bool Items::loadFromXml() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY) + "/items/items.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); @@ -186,8 +179,8 @@ bool Items::loadFromXml() if (!fromIdAttribute) { if (idAttribute) { SPDLOG_WARN("[Items::loadFromXml] - " - "No item id: {} found", - idAttribute.value()); + "No item id: {} found", + idAttribute.value()); } else { SPDLOG_WARN("[Items::loadFromXml] - No item id found"); } @@ -197,8 +190,8 @@ bool Items::loadFromXml() pugi::xml_attribute toIdAttribute = itemNode.attribute("toid"); if (!toIdAttribute) { SPDLOG_WARN("[Items::loadFromXml] - " - "tag fromid: {} without toid", - fromIdAttribute.value()); + "tag fromid: {} without toid", + fromIdAttribute.value()); continue; } @@ -211,21 +204,10 @@ bool Items::loadFromXml() return true; } -void Items::buildInventoryList() -{ +void Items::buildInventoryList() { inventory.reserve(items.size()); - for (const auto& type: items) { - if (type.weaponType != WEAPON_NONE || type.ammoType != AMMO_NONE || - type.attack != 0 || type.defense != 0 || - type.extraDefense != 0 || type.armor != 0 || - type.slotPosition & SLOTP_NECKLACE || - type.slotPosition & SLOTP_RING || - type.slotPosition & SLOTP_AMMO || - type.slotPosition & SLOTP_FEET || - type.slotPosition & SLOTP_HEAD || - type.slotPosition & SLOTP_ARMOR || - type.slotPosition & SLOTP_LEGS) - { + for (const auto &type : items) { + if (type.weaponType != WEAPON_NONE || type.ammoType != AMMO_NONE || type.attack != 0 || type.defense != 0 || type.extraDefense != 0 || type.armor != 0 || type.slotPosition & SLOTP_NECKLACE || type.slotPosition & SLOTP_RING || type.slotPosition & SLOTP_AMMO || type.slotPosition & SLOTP_FEET || type.slotPosition & SLOTP_HEAD || type.slotPosition & SLOTP_ARMOR || type.slotPosition & SLOTP_LEGS) { inventory.push_back(type.id); } } @@ -233,14 +215,14 @@ void Items::buildInventoryList() std::sort(inventory.begin(), inventory.end()); } -void Items::parseItemNode(const pugi::xml_node & itemNode, uint16_t id) { +void Items::parseItemNode(const pugi::xml_node &itemNode, uint16_t id) { if (id >= items.size()) { items.resize(id + 1); } - ItemType & iType = items[id]; + ItemType &iType = items[id]; iType.id = id; - ItemType & itemType = getItemType(id); + ItemType &itemType = getItemType(id); if (itemType.id == 0) { return; } @@ -251,20 +233,19 @@ void Items::parseItemNode(const pugi::xml_node & itemNode, uint16_t id) { } if (std::string xmlName = itemNode.attribute("name").as_string(); - !xmlName.empty() && itemType.name != xmlName) { + !xmlName.empty() && itemType.name != xmlName) { if (!itemType.name.empty()) { if (auto it = std::find_if(nameToItems.begin(), nameToItems.end(), [id](const auto nameMapIt) { return nameMapIt.second == id; - }); it != nameToItems.end()) { + }); + it != nameToItems.end()) { nameToItems.erase(it); } } itemType.name = xmlName; - nameToItems.insert({ - asLowerCaseString(itemType.name), - id - }); + nameToItems.insert({ asLowerCaseString(itemType.name), + id }); } itemType.loaded = true; @@ -294,8 +275,7 @@ void Items::parseItemNode(const pugi::xml_node & itemNode, uint16_t id) { if (parseAttribute != ItemParseAttributesMap.end()) { ItemParse::initParse(tmpStrValue, attributeNode, valueAttribute, itemType); } else { - SPDLOG_WARN("[Items::parseItemNode] - Unknown key value: {}", - keyAttribute.as_string()); + SPDLOG_WARN("[Items::parseItemNode] - Unknown key value: {}", keyAttribute.as_string()); } } @@ -305,24 +285,21 @@ void Items::parseItemNode(const pugi::xml_node & itemNode, uint16_t id) { } } -ItemType& Items::getItemType(size_t id) -{ +ItemType &Items::getItemType(size_t id) { if (id < items.size()) { return items[id]; } return items.front(); } -const ItemType& Items::getItemType(size_t id) const -{ +const ItemType &Items::getItemType(size_t id) const { if (id < items.size()) { return items[id]; } return items.front(); } -uint16_t Items::getItemIdByName(const std::string& name) -{ +uint16_t Items::getItemIdByName(const std::string &name) { auto result = nameToItems.find(asLowerCaseString(name)); if (result == nameToItems.end()) @@ -331,8 +308,7 @@ uint16_t Items::getItemIdByName(const std::string& name) return result->second; } -bool Items::hasItemType(size_t hasId) const -{ +bool Items::hasItemType(size_t hasId) const { if (hasId < items.size()) { return true; } diff --git a/src/items/items.h b/src/items/items.h index 398ed596509..3ef405143b0 100644 --- a/src/items/items.h +++ b/src/items/items.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_ITEMS_H_ #define SRC_ITEMS_ITEMS_H_ @@ -20,11 +20,11 @@ struct Abilities { uint32_t conditionImmunities = 0; uint32_t conditionSuppressions = 0; - //stats modifiers + // stats modifiers int32_t stats[STAT_LAST + 1] = { 0 }; int32_t statsPercent[STAT_LAST + 1] = { 0 }; - //extra skill modifiers + // extra skill modifiers int32_t skills[SKILL_LAST + 1] = { 0 }; int32_t speed = 0; @@ -32,13 +32,13 @@ struct Abilities { // field damage abilities modifiers int16_t fieldAbsorbPercent[COMBAT_COUNT] = { 0 }; - //damage abilities modifiers + // damage abilities modifiers int16_t absorbPercent[COMBAT_COUNT] = { 0 }; - //relfect abilities modifires + // relfect abilities modifires int16_t reflectPercent[COMBAT_COUNT] = { 0 }; - //elemental damage + // elemental damage uint16_t elementDamage = 0; CombatType_t elementType = COMBAT_NONE; @@ -87,17 +87,16 @@ struct Abilities { class ConditionDamage; -class ItemType -{ +class ItemType { public: ItemType() = default; - //non-copyable - ItemType(const ItemType& other) = delete; - ItemType& operator=(const ItemType& other) = delete; + // non-copyable + ItemType(const ItemType &other) = delete; + ItemType &operator=(const ItemType &other) = delete; - ItemType(ItemType&& other) = default; - ItemType& operator=(ItemType&& other) = default; + ItemType(ItemType &&other) = default; + ItemType &operator=(ItemType &&other) = default; bool isGroundTile() const { return group == ITEM_GROUP_GROUND; @@ -160,16 +159,14 @@ class ItemType bool isWeapon() const { return weaponType != WEAPON_NONE && weaponType != WEAPON_SHIELD && weaponType != WEAPON_AMMO; } - bool isArmor() const - { + bool isArmor() const { return slotPosition & SLOTP_ARMOR; } - bool isHelmet() const - { + bool isHelmet() const { return slotPosition & SLOTP_HEAD; } - Abilities& getAbilities() { + Abilities &getAbilities() { if (!abilities) { abilities.reset(new Abilities()); } @@ -233,7 +230,7 @@ class ItemType CombatType_t combatType = COMBAT_NONE; - uint16_t transformToOnUse[2] = {0, 0}; + uint16_t transformToOnUse[2] = { 0, 0 }; uint16_t transformToFree = 0; uint16_t destroyTo = 0; uint16_t maxTextLen = 0; @@ -301,8 +298,7 @@ class ItemType bool loaded = false; }; -class Items -{ +class Items { public: using NameMap = std::unordered_multimap; using InventoryVector = std::vector; @@ -310,38 +306,38 @@ class Items Items(); // non-copyable - Items(const Items&) = delete; - Items& operator=(const Items&) = delete; + Items(const Items &) = delete; + Items &operator=(const Items &) = delete; bool reload(); void clear(); void loadFromProtobuf(); - const ItemType& operator[](size_t id) const { + const ItemType &operator[](size_t id) const { return getItemType(id); } - const ItemType& getItemType(size_t id) const; - ItemType& getItemType(size_t id); + const ItemType &getItemType(size_t id) const; + ItemType &getItemType(size_t id); /** * @brief Check if the itemid "hasId" is stored on "items", if not, return false - * + * * @param hasId check item id - * @return true if the item exist + * @return true if the item exist * @return false if the item not exist */ bool hasItemType(size_t hasId) const; - uint16_t getItemIdByName(const std::string& name); + uint16_t getItemIdByName(const std::string &name); - ItemTypes_t getLootType(const std::string& strValue); + ItemTypes_t getLootType(const std::string &strValue); bool loadFromXml(); - void parseItemNode(const pugi::xml_node& itemNode, uint16_t id); + void parseItemNode(const pugi::xml_node &itemNode, uint16_t id); void buildInventoryList(); - const InventoryVector& getInventory() const { + const InventoryVector &getInventory() const { return inventory; } @@ -352,9 +348,8 @@ class Items NameMap nameToItems; private: - std::vector items; InventoryVector inventory; }; -#endif // SRC_ITEMS_ITEMS_H_ +#endif // SRC_ITEMS_ITEMS_H_ diff --git a/src/items/items_classification.hpp b/src/items/items_classification.hpp index 1572bebb7a4..32d529711e4 100644 --- a/src/items/items_classification.hpp +++ b/src/items/items_classification.hpp @@ -5,35 +5,33 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_ITEMS_CLASSIFICATION_HPP_ #define SRC_ITEMS_ITEMS_CLASSIFICATION_HPP_ // Classification class for forging system and market. -class ItemClassification -{ - public: - ItemClassification() = default; - explicit ItemClassification(uint8_t id) : - id(id) {} - virtual ~ItemClassification() = default; +class ItemClassification { + public: + ItemClassification() = default; + explicit ItemClassification(uint8_t id) : + id(id) { } + virtual ~ItemClassification() = default; - void addTier(uint8_t tierId, uint64_t tierPrice) - { - for (auto [tier, price] : tiers) { - if (tier == tierId) { - price = tierPrice; - return; + void addTier(uint8_t tierId, uint64_t tierPrice) { + for (auto [tier, price] : tiers) { + if (tier == tierId) { + price = tierPrice; + return; + } } - } - tiers.push_back(std::pair({ tierId, tierPrice })); - } + tiers.push_back(std::pair({ tierId, tierPrice })); + } - uint8_t id; - // uint8_t = tier, uint64_t = price - std::vector> tiers; + uint8_t id; + // uint8_t = tier, uint64_t = price + std::vector> tiers; }; -#endif // SRC_ITEMS_ITEMS_CLASSIFICATION_HPP_ +#endif // SRC_ITEMS_ITEMS_CLASSIFICATION_HPP_ diff --git a/src/items/items_definitions.hpp b/src/items/items_definitions.hpp index 33c89523ee8..4af75794c3b 100644 --- a/src/items/items_definitions.hpp +++ b/src/items/items_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_ITEMS_DEFINITIONS_HPP_ #define SRC_ITEMS_ITEMS_DEFINITIONS_HPP_ @@ -189,8 +189,8 @@ enum TradeEvents_t { enum AttrTypes_t { // ATTR_NONE = 0 (last enum) - //ATTR_DESCRIPTION = 1, - //ATTR_EXT_FILE = 2, + // ATTR_DESCRIPTION = 1, + // ATTR_EXT_FILE = 2, ATTR_TILE_FLAGS = 3, ATTR_ACTION_ID = 4, ATTR_UNIQUE_ID = 5, @@ -199,9 +199,9 @@ enum AttrTypes_t { ATTR_TELE_DEST = 8, ATTR_ITEM = 9, ATTR_DEPOT_ID = 10, - //ATTR_EXT_SPAWN_FILE = 11, + // ATTR_EXT_SPAWN_FILE = 11, ATTR_RUNE_CHARGES = 12, - //ATTR_EXT_HOUSE_FILE = 13, + // ATTR_EXT_HOUSE_FILE = 13, ATTR_HOUSEDOORID = 14, ATTR_COUNT = 15, ATTR_DURATION = 16, @@ -302,13 +302,7 @@ enum TileFlags_t : uint32_t { TILESTATE_NOFIELDBLOCKPATH = 1 << 22, TILESTATE_SUPPORTS_HANGABLE = 1 << 23, - TILESTATE_FLOORCHANGE = TILESTATE_FLOORCHANGE_DOWN | - TILESTATE_FLOORCHANGE_NORTH | - TILESTATE_FLOORCHANGE_SOUTH | - TILESTATE_FLOORCHANGE_EAST | - TILESTATE_FLOORCHANGE_WEST | - TILESTATE_FLOORCHANGE_SOUTH_ALT | - TILESTATE_FLOORCHANGE_EAST_ALT, + TILESTATE_FLOORCHANGE = TILESTATE_FLOORCHANGE_DOWN | TILESTATE_FLOORCHANGE_NORTH | TILESTATE_FLOORCHANGE_SOUTH | TILESTATE_FLOORCHANGE_EAST | TILESTATE_FLOORCHANGE_WEST | TILESTATE_FLOORCHANGE_SOUTH_ALT | TILESTATE_FLOORCHANGE_EAST_ALT, }; enum ZoneType_t { @@ -320,14 +314,14 @@ enum ZoneType_t { }; enum CylinderFlags_t { - FLAG_NOLIMIT = 1 << 0, //Bypass limits like capacity/container limits, blocking items/creatures etc. - FLAG_IGNOREBLOCKITEM = 1 << 1, //Bypass movable blocking item checks - FLAG_IGNOREBLOCKCREATURE = 1 << 2, //Bypass creature checks - FLAG_CHILDISOWNER = 1 << 3, //Used by containers to query capacity of the carrier (player) - FLAG_PATHFINDING = 1 << 4, //An additional check is done for floor changing/teleport items - FLAG_IGNOREFIELDDAMAGE = 1 << 5, //Bypass field damage checks - FLAG_IGNORENOTMOVEABLE = 1 << 6, //Bypass check for mobility - FLAG_IGNOREAUTOSTACK = 1 << 7, //queryDestination will not try to stack items together + FLAG_NOLIMIT = 1 << 0, // Bypass limits like capacity/container limits, blocking items/creatures etc. + FLAG_IGNOREBLOCKITEM = 1 << 1, // Bypass movable blocking item checks + FLAG_IGNOREBLOCKCREATURE = 1 << 2, // Bypass creature checks + FLAG_CHILDISOWNER = 1 << 3, // Used by containers to query capacity of the carrier (player) + FLAG_PATHFINDING = 1 << 4, // An additional check is done for floor changing/teleport items + FLAG_IGNOREFIELDDAMAGE = 1 << 5, // Bypass field damage checks + FLAG_IGNORENOTMOVEABLE = 1 << 6, // Bypass check for mobility + FLAG_IGNOREAUTOSTACK = 1 << 7, // queryDestination will not try to stack items together }; enum CylinderLink_t { @@ -451,8 +445,8 @@ enum ItemParseAttributes_t { }; struct ImbuementInfo { - Imbuement *imbuement; - uint32_t duration = 0; + Imbuement* imbuement; + uint32_t duration = 0; }; -#endif // SRC_ITEMS_ITEMS_DEFINITIONS_HPP_ +#endif // SRC_ITEMS_ITEMS_DEFINITIONS_HPP_ diff --git a/src/items/thing.cpp b/src/items/thing.cpp index 0861aed1073..eba49f4a65a 100644 --- a/src/items/thing.cpp +++ b/src/items/thing.cpp @@ -5,15 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/thing.h" #include "items/tile.h" -const Position& Thing::getPosition() const -{ +const Position &Thing::getPosition() const { const Tile* tile = getTile(); if (!tile) { return Tile::nullptr_tile.getPosition(); @@ -21,12 +20,10 @@ const Position& Thing::getPosition() const return tile->getPosition(); } -Tile* Thing::getTile() -{ +Tile* Thing::getTile() { return dynamic_cast(this); } -const Tile* Thing::getTile() const -{ +const Tile* Thing::getTile() const { return dynamic_cast(this); } diff --git a/src/items/thing.h b/src/items/thing.h index 16f812668df..99d3e4bc6f1 100644 --- a/src/items/thing.h +++ b/src/items/thing.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_THING_H_ #define SRC_ITEMS_THING_H_ @@ -18,15 +18,14 @@ class Item; class Creature; class Container; -class Thing -{ +class Thing { public: constexpr Thing() = default; virtual ~Thing() = default; // non-copyable - Thing(const Thing&) = delete; - Thing& operator=(const Thing&) = delete; + Thing(const Thing &) = delete; + Thing &operator=(const Thing &) = delete; virtual std::string getDescription(int32_t lookDistance) const = 0; @@ -44,7 +43,7 @@ class Thing virtual Tile* getTile(); virtual const Tile* getTile() const; - virtual const Position& getPosition() const; + virtual const Position &getPosition() const; virtual int32_t getThrowRange() const = 0; virtual bool isPushable() const = 0; @@ -72,4 +71,4 @@ class Thing } }; -#endif // SRC_ITEMS_THING_H_ +#endif // SRC_ITEMS_THING_H_ diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 4d46c7699ae..737cb46cff0 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -21,12 +21,10 @@ #include "map/house/housetile.h" #include "io/iomap.h" - StaticTile real_nullptr_tile(0xFFFF, 0xFFFF, 0xFF); -Tile& Tile::nullptr_tile = real_nullptr_tile; +Tile &Tile::nullptr_tile = real_nullptr_tile; -bool Tile::hasProperty(ItemProperty prop) const -{ +bool Tile::hasProperty(ItemProperty prop) const { if (ground && ground->hasProperty(prop)) { return true; } @@ -41,8 +39,7 @@ bool Tile::hasProperty(ItemProperty prop) const return false; } -bool Tile::hasProperty(const Item* exclude, ItemProperty prop) const -{ +bool Tile::hasProperty(const Item* exclude, ItemProperty prop) const { assert(exclude); if (ground && exclude != ground && ground->hasProperty(prop)) { @@ -60,8 +57,7 @@ bool Tile::hasProperty(const Item* exclude, ItemProperty prop) const return false; } -bool Tile::hasHeight(uint32_t n) const -{ +bool Tile::hasHeight(uint32_t n) const { uint32_t height = 0; if (ground) { @@ -88,45 +84,39 @@ bool Tile::hasHeight(uint32_t n) const return false; } -size_t Tile::getCreatureCount() const -{ +size_t Tile::getCreatureCount() const { if (const CreatureVector* creatures = getCreatures()) { return creatures->size(); } return 0; } -size_t Tile::getItemCount() const -{ +size_t Tile::getItemCount() const { if (const TileItemVector* items = getItemList()) { return items->size(); } return 0; } -uint32_t Tile::getTopItemCount() const -{ +uint32_t Tile::getTopItemCount() const { if (const TileItemVector* items = getItemList()) { return items->getTopItemCount(); } return 0; } -uint32_t Tile::getDownItemCount() const -{ +uint32_t Tile::getDownItemCount() const { if (const TileItemVector* items = getItemList()) { return items->getDownItemCount(); } return 0; } -std::string Tile::getDescription(int32_t) const -{ +std::string Tile::getDescription(int32_t) const { return "You dont know why, but you cant see anything!"; } -Teleport* Tile::getTeleportItem() const -{ +Teleport* Tile::getTeleportItem() const { if (!hasFlag(TILESTATE_TELEPORT)) { return nullptr; } @@ -141,8 +131,7 @@ Teleport* Tile::getTeleportItem() const return nullptr; } -MagicField* Tile::getFieldItem() const -{ +MagicField* Tile::getFieldItem() const { if (!hasFlag(TILESTATE_MAGICFIELD)) { return nullptr; } @@ -161,8 +150,7 @@ MagicField* Tile::getFieldItem() const return nullptr; } -TrashHolder* Tile::getTrashHolder() const -{ +TrashHolder* Tile::getTrashHolder() const { if (!hasFlag(TILESTATE_TRASHHOLDER)) { return nullptr; } @@ -181,8 +169,7 @@ TrashHolder* Tile::getTrashHolder() const return nullptr; } -Mailbox* Tile::getMailbox() const -{ +Mailbox* Tile::getMailbox() const { if (!hasFlag(TILESTATE_MAILBOX)) { return nullptr; } @@ -201,8 +188,7 @@ Mailbox* Tile::getMailbox() const return nullptr; } -BedItem* Tile::getBedItem() const -{ +BedItem* Tile::getBedItem() const { if (!hasFlag(TILESTATE_BED)) { return nullptr; } @@ -221,8 +207,7 @@ BedItem* Tile::getBedItem() const return nullptr; } -Creature* Tile::getTopCreature() const -{ +Creature* Tile::getTopCreature() const { if (const CreatureVector* creatures = getCreatures()) { if (!creatures->empty()) { return *creatures->begin(); @@ -231,8 +216,7 @@ Creature* Tile::getTopCreature() const return nullptr; } -const Creature* Tile::getBottomCreature() const -{ +const Creature* Tile::getBottomCreature() const { if (const CreatureVector* creatures = getCreatures()) { if (!creatures->empty()) { return *creatures->rbegin(); @@ -241,8 +225,7 @@ const Creature* Tile::getBottomCreature() const return nullptr; } -Creature* Tile::getTopVisibleCreature(const Creature* creature) const -{ +Creature* Tile::getTopVisibleCreature(const Creature* creature) const { if (const CreatureVector* creatures = getCreatures()) { if (creature) { const Player* player = creature->getPlayer(); @@ -269,8 +252,7 @@ Creature* Tile::getTopVisibleCreature(const Creature* creature) const return nullptr; } -const Creature* Tile::getBottomVisibleCreature(const Creature* creature) const -{ +const Creature* Tile::getBottomVisibleCreature(const Creature* creature) const { if (const CreatureVector* creatures = getCreatures()) { if (creature) { const Player* player = creature->getPlayer(); @@ -297,29 +279,26 @@ const Creature* Tile::getBottomVisibleCreature(const Creature* creature) const return nullptr; } -Item* Tile::getTopDownItem() const -{ +Item* Tile::getTopDownItem() const { if (const TileItemVector* items = getItemList()) { return items->getTopDownItem(); } return nullptr; } -Item* Tile::getTopTopItem() const -{ +Item* Tile::getTopTopItem() const { if (const TileItemVector* items = getItemList()) { return items->getTopTopItem(); } return nullptr; } -Item* Tile::getItemByTopOrder(int32_t topOrder) -{ - //topOrder: - //1: borders - //2: ladders, signs, splashes - //3: doors etc - //4: creatures +Item* Tile::getItemByTopOrder(int32_t topOrder) { + // topOrder: + // 1: borders + // 2: ladders, signs, splashes + // 3: doors etc + // 4: creatures if (TileItemVector* items = getItemList()) { for (auto it = ItemVector::const_reverse_iterator(items->getEndTopItem()), end = ItemVector::const_reverse_iterator(items->getBeginTopItem()); it != end; ++it) { if (Item::items[(*it)->getID()].alwaysOnTopOrder == topOrder) { @@ -330,8 +309,7 @@ Item* Tile::getItemByTopOrder(int32_t topOrder) return nullptr; } -Thing* Tile::getTopVisibleThing(const Creature* creature) -{ +Thing* Tile::getTopVisibleThing(const Creature* creature) { Thing* thing = getTopVisibleCreature(creature); if (thing) { return thing; @@ -340,14 +318,14 @@ Thing* Tile::getTopVisibleThing(const Creature* creature) TileItemVector* items = getItemList(); if (items) { for (ItemVector::const_iterator it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { - const ItemType& iit = Item::items[(*it)->getID()]; + const ItemType &iit = Item::items[(*it)->getID()]; if (!iit.lookThrough) { return (*it); } } for (auto it = ItemVector::const_reverse_iterator(items->getEndTopItem()), end = ItemVector::const_reverse_iterator(items->getBeginTopItem()); it != end; ++it) { - const ItemType& iit = Item::items[(*it)->getID()]; + const ItemType &iit = Item::items[(*it)->getID()]; if (!iit.lookThrough) { return (*it); } @@ -357,8 +335,7 @@ Thing* Tile::getTopVisibleThing(const Creature* creature) return ground; } -void Tile::onAddTileItem(Item* item) -{ +void Tile::onAddTileItem(Item* item) { if ((item->hasProperty(CONST_PROP_MOVEABLE) || item->getContainer()) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVEABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) { auto it = g_game().browseFields.find(this); if (it != g_game().browseFields.end()) { @@ -369,33 +346,32 @@ void Tile::onAddTileItem(Item* item) setTileFlags(item); - const Position& cylinderMapPos = getPosition(); + const Position &cylinderMapPos = getPosition(); SpectatorHashSet spectators; g_game().map.getSpectators(spectators, cylinderMapPos, true); - //send to client + // send to client for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendAddTileItem(this, cylinderMapPos, item); } } - //event methods + // event methods for (Creature* spectator : spectators) { spectator->onAddTileItem(this, cylinderMapPos); } - if ((!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES)) - && item->isCleanable()) { + if ((!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES)) + && item->isCleanable()) { if (!dynamic_cast(this)) { g_game().addTileToClean(this); } } } -void Tile::onUpdateTileItem(Item* oldItem, const ItemType& oldType, Item* newItem, const ItemType& newType) -{ +void Tile::onUpdateTileItem(Item* oldItem, const ItemType &oldType, Item* newItem, const ItemType &newType) { if ((newItem->hasProperty(CONST_PROP_MOVEABLE) || newItem->getContainer()) || (newItem->isWrapable() && newItem->hasProperty(CONST_PROP_MOVEABLE) && !oldItem->hasProperty(CONST_PROP_BLOCKPATH))) { auto it = g_game().browseFields.find(this); if (it != g_game().browseFields.end()) { @@ -414,26 +390,25 @@ void Tile::onUpdateTileItem(Item* oldItem, const ItemType& oldType, Item* newIte } } - const Position& cylinderMapPos = getPosition(); + const Position &cylinderMapPos = getPosition(); SpectatorHashSet spectators; g_game().map.getSpectators(spectators, cylinderMapPos, true); - //send to client + // send to client for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendUpdateTileItem(this, cylinderMapPos, newItem); } } - //event methods + // event methods for (Creature* spectator : spectators) { spectator->onUpdateTileItem(this, cylinderMapPos, oldItem, oldType, newItem, newType); } } -void Tile::onRemoveTileItem(const SpectatorHashSet& spectators, const std::vector& oldStackPosVector, Item* item) -{ +void Tile::onRemoveTileItem(const SpectatorHashSet &spectators, const std::vector &oldStackPosVector, Item* item) { if ((item->hasProperty(CONST_PROP_MOVEABLE) || item->getContainer()) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVEABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) { auto it = g_game().browseFields.find(this); if (it != g_game().browseFields.end()) { @@ -443,10 +418,10 @@ void Tile::onRemoveTileItem(const SpectatorHashSet& spectators, const std::vecto resetTileFlags(item); - const Position& cylinderMapPos = getPosition(); - const ItemType& iType = Item::items[item->getID()]; + const Position &cylinderMapPos = getPosition(); + const ItemType &iType = Item::items[item->getID()]; - //send to client + // send to client size_t i = 0; for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { @@ -454,12 +429,12 @@ void Tile::onRemoveTileItem(const SpectatorHashSet& spectators, const std::vecto } } - //event methods + // event methods for (Creature* spectator : spectators) { spectator->onRemoveTileItem(this, cylinderMapPos, iType, item); } - if (!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES)) { + if (!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES)) { auto items = getItemList(); if (!items || items->empty()) { g_game().removeTileToClean(this); @@ -480,18 +455,16 @@ void Tile::onRemoveTileItem(const SpectatorHashSet& spectators, const std::vecto } } -void Tile::onUpdateTile(const SpectatorHashSet& spectators) -{ - const Position& cylinderMapPos = getPosition(); +void Tile::onUpdateTile(const SpectatorHashSet &spectators) { + const Position &cylinderMapPos = getPosition(); - //send to clients + // send to clients for (Creature* spectator : spectators) { spectator->getPlayer()->sendUpdateTile(this, cylinderMapPos); } } -ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileFlags, Creature*) const -{ +ReturnValue Tile::queryAdd(int32_t, const Thing &thing, uint32_t, uint32_t tileFlags, Creature*) const { if (const Creature* creature = thing.getCreature()) { if (hasBitSet(FLAG_NOLIMIT, tileFlags)) { return RETURNVALUE_NOERROR; @@ -506,8 +479,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF } if (const Monster* monster = creature->getMonster()) { - if (hasFlag(TILESTATE_PROTECTIONZONE | TILESTATE_FLOORCHANGE | TILESTATE_TELEPORT) && - (!monster->isFamiliar() || (monster->isFamiliar() && monster->getMaster() && monster->getMaster()->getAttackedCreature()))) { + if (hasFlag(TILESTATE_PROTECTIONZONE | TILESTATE_FLOORCHANGE | TILESTATE_TELEPORT) && (!monster->isFamiliar() || (monster->isFamiliar() && monster->getMaster() && monster->getMaster()->getAttackedCreature()))) { return RETURNVALUE_NOTPOSSIBLE; } @@ -526,8 +498,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF } const Monster* creatureMonster = tileCreature->getMonster(); - if (!creatureMonster || !tileCreature->isPushable() || - (creatureMonster->isSummon() && creatureMonster->getMaster()->getPlayer())) { + if (!creatureMonster || !tileCreature->isPushable() || (creatureMonster->isSummon() && creatureMonster->getMaster()->getPlayer())) { return RETURNVALUE_NOTPOSSIBLE; } } @@ -558,11 +529,11 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF if (field && !field->isBlocking() && field->getDamage() != 0) { CombatType_t combatType = field->getCombatType(); - //There is 3 options for a monster to enter a magic field - //1) Monster is immune + // There is 3 options for a monster to enter a magic field + // 1) Monster is immune if (!monster->isImmune(combatType)) { - //1) Monster is able to walk over field type - //2) Being attacked while random stepping will make it ignore field damages + // 1) Monster is able to walk over field type + // 2) Being attacked while random stepping will make it ignore field damages if (hasBitSet(FLAG_IGNOREFIELDDAMAGE, tileFlags)) { if (!(monster->getIgnoreFieldDamage() || monster->canWalkOnFieldType(combatType))) { return RETURNVALUE_NOTPOSSIBLE; @@ -586,19 +557,19 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF } } - if(hasBitSet(FLAG_PATHFINDING, tileFlags) && hasFlag(TILESTATE_MAGICFIELD) && !fieldIsUnharmable()){ + if (hasBitSet(FLAG_PATHFINDING, tileFlags) && hasFlag(TILESTATE_MAGICFIELD) && !fieldIsUnharmable()) { return RETURNVALUE_NOTPOSSIBLE; } if (player->getParent() == nullptr && hasFlag(TILESTATE_NOLOGOUT)) { - //player is trying to login to a "no logout" tile + // player is trying to login to a "no logout" tile return RETURNVALUE_NOTPOSSIBLE; } const Tile* playerTile = player->getTile(); if (playerTile && player->isPzLocked()) { if (!playerTile->hasFlag(TILESTATE_PVPZONE)) { - //player is trying to enter a pvp zone while being pz-locked + // player is trying to enter a pvp zone while being pz-locked if (hasFlag(TILESTATE_PVPZONE)) { return RETURNVALUE_PLAYERISPZLOCKEDENTERPVPZONE; } @@ -607,8 +578,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF return RETURNVALUE_PLAYERISPZLOCKEDLEAVEPVPZONE; } - if ((!playerTile->hasFlag(TILESTATE_NOPVPZONE) && hasFlag(TILESTATE_NOPVPZONE)) || - (!playerTile->hasFlag(TILESTATE_PROTECTIONZONE) && hasFlag(TILESTATE_PROTECTIONZONE))) { + if ((!playerTile->hasFlag(TILESTATE_NOPVPZONE) && hasFlag(TILESTATE_NOPVPZONE)) || (!playerTile->hasFlag(TILESTATE_PROTECTIONZONE) && hasFlag(TILESTATE_PROTECTIONZONE))) { // player is trying to enter a non-pvp/protection zone while being pz-locked return RETURNVALUE_PLAYERISPZLOCKED; } @@ -622,7 +592,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF } if (!hasBitSet(FLAG_IGNOREBLOCKITEM, tileFlags)) { - //If the FLAG_IGNOREBLOCKITEM bit isn't set we dont have to iterate every single item + // If the FLAG_IGNOREBLOCKITEM bit isn't set we dont have to iterate every single item if (hasFlag(TILESTATE_BLOCKSOLID)) { // NO PVP magic wall or wild growth field check if (creature && creature->getPlayer()) { @@ -640,9 +610,9 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF return RETURNVALUE_NOTENOUGHROOM; } } else { - //FLAG_IGNOREBLOCKITEM is set + // FLAG_IGNOREBLOCKITEM is set if (ground) { - const ItemType& iiType = Item::items[ground->getID()]; + const ItemType &iiType = Item::items[ground->getID()]; if (iiType.blockSolid && (!iiType.moveable || ground->hasAttribute(ItemAttribute_t::UNIQUEID))) { return RETURNVALUE_NOTPOSSIBLE; } @@ -650,7 +620,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF if (const auto items = getItemList()) { for (const Item* item : *items) { - const ItemType& iiType = Item::items[item->getID()]; + const ItemType &iiType = Item::items[item->getID()]; if (iiType.blockSolid && (!iiType.moveable || item->hasAttribute(ItemAttribute_t::UNIQUEID))) { return RETURNVALUE_NOTPOSSIBLE; } @@ -691,7 +661,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF } } else { if (ground) { - const ItemType& iiType = Item::items[ground->getID()]; + const ItemType &iiType = Item::items[ground->getID()]; if (iiType.blockSolid) { if (!iiType.pickupable || item->isMagicField() || item->isBlocking()) { if (!item->isPickupable()) { @@ -707,7 +677,7 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t tileF if (items) { for (const Item* tileItem : *items) { - const ItemType& iiType = Item::items[tileItem->getID()]; + const ItemType &iiType = Item::items[tileItem->getID()]; if (!iiType.blockSolid) { continue; } @@ -735,14 +705,12 @@ bool Tile::fieldIsUnharmable() const { return fieldId == ITEM_FIREFIELD_PVP_SMALL || fieldId == ITEM_FIREFIELD_PERSISTENT_SMALL; } -ReturnValue Tile::queryMaxCount(int32_t, const Thing&, uint32_t count, uint32_t& maxQueryCount, uint32_t) const -{ +ReturnValue Tile::queryMaxCount(int32_t, const Thing &, uint32_t count, uint32_t &maxQueryCount, uint32_t) const { maxQueryCount = std::max(1, count); return RETURNVALUE_NOERROR; } -ReturnValue Tile::queryRemove(const Thing& thing, uint32_t count, uint32_t tileFlags, Creature* /*= nullptr */) const -{ +ReturnValue Tile::queryRemove(const Thing &thing, uint32_t count, uint32_t tileFlags, Creature* /*= nullptr */) const { int32_t index = getThingIndex(&thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; @@ -764,8 +732,7 @@ ReturnValue Tile::queryRemove(const Thing& thing, uint32_t count, uint32_t tileF return RETURNVALUE_NOERROR; } -Tile* Tile::queryDestination(int32_t&, const Thing&, Item** destItem, uint32_t& tileFlags) -{ +Tile* Tile::queryDestination(int32_t &, const Thing &, Item** destItem, uint32_t &tileFlags) { Tile* destTile = nullptr; *destItem = nullptr; @@ -849,7 +816,7 @@ Tile* Tile::queryDestination(int32_t&, const Thing&, Item** destItem, uint32_t& if (destTile == nullptr) { destTile = this; } else { - tileFlags |= FLAG_NOLIMIT; //Will ignore that there is blocking items/creatures + tileFlags |= FLAG_NOLIMIT; // Will ignore that there is blocking items/creatures } if (destTile) { @@ -861,13 +828,11 @@ Tile* Tile::queryDestination(int32_t&, const Thing&, Item** destItem, uint32_t& return destTile; } -void Tile::addThing(Thing* thing) -{ +void Tile::addThing(Thing* thing) { addThing(0, thing); } -void Tile::addThing(int32_t, Thing* thing) -{ +void Tile::addThing(int32_t, Thing* thing) { Creature* creature = thing->getCreature(); if (creature) { g_game().map.clearSpectatorCache(); @@ -887,13 +852,13 @@ void Tile::addThing(int32_t, Thing* thing) item->setParent(this); - const ItemType& itemType = Item::items[item->getID()]; + const ItemType &itemType = Item::items[item->getID()]; if (itemType.isGroundTile()) { if (ground == nullptr) { ground = item; onAddTileItem(item); } else { - const ItemType& oldType = Item::items[ground->getID()]; + const ItemType &oldType = Item::items[ground->getID()]; Item* oldGround = ground; ground->setParent(nullptr); @@ -906,7 +871,7 @@ void Tile::addThing(int32_t, Thing* thing) } } else if (item->isAlwaysOnTop()) { if (itemType.isSplash() && items) { - //remove old splash if exists + // remove old splash if exists for (ItemVector::const_iterator it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { Item* oldSplash = *it; if (!Item::items[oldSplash->getID()].isSplash()) { @@ -925,7 +890,7 @@ void Tile::addThing(int32_t, Thing* thing) if (items) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - //Note: this is different from internalAddThing + // Note: this is different from internalAddThing if (itemType.alwaysOnTopOrder <= Item::items[(*it)->getID()].alwaysOnTopOrder) { items->insert(it, item); isInserted = true; @@ -943,7 +908,7 @@ void Tile::addThing(int32_t, Thing* thing) onAddTileItem(item); } else { if (itemType.isMagicField()) { - //remove old field item if exists + // remove old field item if exists if (items) { for (ItemVector::const_iterator it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { MagicField* oldField = (*it)->getMagicField(); @@ -956,7 +921,7 @@ void Tile::addThing(int32_t, Thing* thing) postRemoveNotification(oldField, nullptr, 0); break; } else { - //This magic field cannot be replaced. + // This magic field cannot be replaced. item->setParent(nullptr); g_game().ReleaseItem(item); return; @@ -974,8 +939,7 @@ void Tile::addThing(int32_t, Thing* thing) } } -void Tile::updateThing(Thing* thing, uint16_t itemId, uint32_t count) -{ +void Tile::updateThing(Thing* thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -986,8 +950,8 @@ void Tile::updateThing(Thing* thing, uint16_t itemId, uint32_t count) return /*RETURNVALUE_NOTPOSSIBLE*/; } - const ItemType& oldType = Item::items[item->getID()]; - const ItemType& newType = Item::items[itemId]; + const ItemType &oldType = Item::items[item->getID()]; + const ItemType &newType = Item::items[itemId]; resetTileFlags(item); item->setID(itemId); item->setSubType(count); @@ -995,8 +959,7 @@ void Tile::updateThing(Thing* thing, uint16_t itemId, uint32_t count) onUpdateTileItem(item, oldType, item, newType); } -void Tile::replaceThing(uint32_t index, Thing* thing) -{ +void Tile::replaceThing(uint32_t index, Thing* thing) { int32_t pos = index; Item* item = thing->getItem(); @@ -1058,8 +1021,8 @@ void Tile::replaceThing(uint32_t index, Thing* thing) resetTileFlags(oldItem); setTileFlags(item); - const ItemType& oldType = Item::items[oldItem->getID()]; - const ItemType& newType = Item::items[item->getID()]; + const ItemType &oldType = Item::items[oldItem->getID()]; + const ItemType &newType = Item::items[item->getID()]; onUpdateTileItem(oldItem, oldType, item, newType); oldItem->setParent(nullptr); @@ -1067,8 +1030,7 @@ void Tile::replaceThing(uint32_t index, Thing* thing) } } -void Tile::removeThing(Thing* thing, uint32_t count) -{ +void Tile::removeThing(Thing* thing, uint32_t count) { Creature* creature = thing->getCreature(); if (creature) { CreatureVector* creatures = getCreatures(); @@ -1132,7 +1094,7 @@ void Tile::removeThing(Thing* thing, uint32_t count) return; } - const ItemType& itemType = Item::items[item->getID()]; + const ItemType &itemType = Item::items[item->getID()]; if (itemType.stackable && count != item->getItemCount()) { uint8_t newCount = static_cast(std::max(0, static_cast(item->getItemCount() - count))); item->setItemCount(newCount); @@ -1156,14 +1118,12 @@ void Tile::removeThing(Thing* thing, uint32_t count) } } -void Tile::removeCreature(Creature* creature) -{ +void Tile::removeCreature(Creature* creature) { g_game().map.getQTNode(tilePos.x, tilePos.y)->removeCreature(creature); removeThing(creature, 0); } -int32_t Tile::getThingIndex(const Thing* thing) const -{ +int32_t Tile::getThingIndex(const Thing* thing) const { int32_t n = -1; if (ground) { if (ground == thing) { @@ -1214,8 +1174,7 @@ int32_t Tile::getThingIndex(const Thing* thing) const return -1; } -int32_t Tile::getClientIndexOfCreature(const Player* player, const Creature* creature) const -{ +int32_t Tile::getClientIndexOfCreature(const Player* player, const Creature* creature) const { int32_t n; if (ground) { n = 1; @@ -1240,8 +1199,7 @@ int32_t Tile::getClientIndexOfCreature(const Player* player, const Creature* cre return -1; } -int32_t Tile::getStackposOfCreature(const Player* player, const Creature* creature) const -{ +int32_t Tile::getStackposOfCreature(const Player* player, const Creature* creature) const { int32_t n; if (ground) { n = 1; @@ -1271,8 +1229,7 @@ int32_t Tile::getStackposOfCreature(const Player* player, const Creature* creatu return -1; } -int32_t Tile::getStackposOfItem(const Player* player, const Item* item) const -{ +int32_t Tile::getStackposOfItem(const Player* player, const Item* item) const { int32_t n = 0; if (ground) { if (ground == item) { @@ -1321,18 +1278,15 @@ int32_t Tile::getStackposOfItem(const Player* player, const Item* item) const return -1; } -size_t Tile::getFirstIndex() const -{ +size_t Tile::getFirstIndex() const { return 0; } -size_t Tile::getLastIndex() const -{ +size_t Tile::getLastIndex() const { return getThingCount(); } -uint32_t Tile::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const -{ +uint32_t Tile::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const { uint32_t count = 0; if (ground && ground->getID() == itemId) { count += Item::countByType(ground, subType); @@ -1349,8 +1303,7 @@ uint32_t Tile::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const return count; } -Thing* Tile::getThing(size_t index) const -{ +Thing* Tile::getThing(size_t index) const { if (ground) { if (index == 0) { return ground; @@ -1381,15 +1334,14 @@ Thing* Tile::getThing(size_t index) const return nullptr; } -void Tile::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) -{ +void Tile::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, getPosition(), true, true); for (Creature* spectator : spectators) { spectator->getPlayer()->postAddNotification(thing, oldParent, index, LINK_NEAR); } - //add a reference to this item, it may be deleted after being added (mailbox for example) + // add a reference to this item, it may be deleted after being added (mailbox for example) Creature* creature = thing->getCreature(); Item* item; if (creature) { @@ -1420,7 +1372,7 @@ void Tile::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t } } - //calling movement scripts + // calling movement scripts if (creature) { g_moveEvents().onCreatureMove(*creature, *this, MOVE_EVENT_STEP_IN); } else if (item) { @@ -1428,7 +1380,7 @@ void Tile::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t } } - //release the reference to this item onces we are finished + // release the reference to this item onces we are finished if (creature) { g_game().ReleaseCreature(creature); } else if (item) { @@ -1436,8 +1388,7 @@ void Tile::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t } } -void Tile::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void Tile::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { SpectatorHashSet spectators; g_game().map.getSpectators(spectators, getPosition(), true, true); @@ -1449,7 +1400,7 @@ void Tile::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32 spectator->getPlayer()->postRemoveNotification(thing, newParent, index, LINK_NEAR); } - //calling movement scripts + // calling movement scripts Creature* creature = thing->getCreature(); if (creature) { g_moveEvents().onCreatureMove(*creature, *this, MOVE_EVENT_STEP_OUT); @@ -1461,8 +1412,7 @@ void Tile::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32 } } -void Tile::internalAddThing(Thing* thing) -{ +void Tile::internalAddThing(Thing* thing) { internalAddThing(0, thing); if (!thing->getParent()) { return; @@ -1480,8 +1430,7 @@ void Tile::internalAddThing(Thing* thing) if (door->getDoorId() != 0) { house->addDoor(door); } - } - else { + } else { BedItem* bed = item->getBed(); if (bed) { house->addBed(bed); @@ -1491,8 +1440,7 @@ void Tile::internalAddThing(Thing* thing) } } -void Tile::internalAddThing(uint32_t, Thing* thing) -{ +void Tile::internalAddThing(uint32_t, Thing* thing) { thing->setParent(this); Creature* creature = thing->getCreature(); @@ -1506,7 +1454,7 @@ void Tile::internalAddThing(uint32_t, Thing* thing) return; } - const ItemType& itemType = Item::items[item->getID()]; + const ItemType &itemType = Item::items[item->getID()]; if (itemType.isGroundTile()) { if (ground == nullptr) { ground = item; @@ -1542,10 +1490,9 @@ void Tile::internalAddThing(uint32_t, Thing* thing) } } -void Tile::setTileFlags(const Item* item) -{ +void Tile::setTileFlags(const Item* item) { if (!hasFlag(TILESTATE_FLOORCHANGE)) { - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.floorChange != 0) { setFlag(it.floorChange); } @@ -1601,9 +1548,8 @@ void Tile::setTileFlags(const Item* item) } } -void Tile::resetTileFlags(const Item* item) -{ - const ItemType& it = Item::items[item->getID()]; +void Tile::resetTileFlags(const Item* item) { + const ItemType &it = Item::items[item->getID()]; if (it.floorChange != 0) { resetFlag(TILESTATE_FLOORCHANGE); } @@ -1662,13 +1608,11 @@ void Tile::resetTileFlags(const Item* item) } } -bool Tile::isMoveableBlocking() const -{ +bool Tile::isMoveableBlocking() const { return !ground || hasFlag(TILESTATE_BLOCKSOLID); } -Item* Tile::getUseItem(int32_t index) const -{ +Item* Tile::getUseItem(int32_t index) const { const TileItemVector* items = getItemList(); if (!items || items->size() == 0) { return ground; @@ -1681,8 +1625,7 @@ Item* Tile::getUseItem(int32_t index) const return nullptr; } -Item* Tile::getDoorItem() const -{ +Item* Tile::getDoorItem() const { const TileItemVector* items = getItemList(); if (!items || items->size() == 0) { return ground; @@ -1690,7 +1633,7 @@ Item* Tile::getDoorItem() const if (items) { for (Item* item : *items) { - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.isDoor()) { return item; } diff --git a/src/items/tile.h b/src/items/tile.h index 1a65c3dc1ad..d5127d809ac 100644 --- a/src/items/tile.h +++ b/src/items/tile.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_TILE_H_ #define SRC_ITEMS_TILE_H_ @@ -27,25 +27,24 @@ using CreatureVector = std::vector; using ItemVector = std::vector; using SpectatorHashSet = phmap::flat_hash_set; -class TileItemVector : private ItemVector -{ +class TileItemVector : private ItemVector { public: + using ItemVector::at; using ItemVector::begin; + using ItemVector::clear; + using ItemVector::const_iterator; + using ItemVector::const_reverse_iterator; + using ItemVector::empty; using ItemVector::end; + using ItemVector::erase; + using ItemVector::insert; + using ItemVector::iterator; + using ItemVector::push_back; using ItemVector::rbegin; using ItemVector::rend; + using ItemVector::reverse_iterator; using ItemVector::size; - using ItemVector::clear; - using ItemVector::at; - using ItemVector::insert; - using ItemVector::erase; - using ItemVector::push_back; using ItemVector::value_type; - using ItemVector::iterator; - using ItemVector::const_iterator; - using ItemVector::reverse_iterator; - using ItemVector::const_reverse_iterator; - using ItemVector::empty; iterator getBeginDownItem() { return begin(); @@ -101,18 +100,18 @@ class TileItemVector : private ItemVector uint32_t downItemCount = 0; }; -class Tile : public Cylinder -{ +class Tile : public Cylinder { public: - static Tile& nullptr_tile; - Tile(uint16_t x, uint16_t y, uint8_t z) : tilePos(x, y, z) {} + static Tile &nullptr_tile; + Tile(uint16_t x, uint16_t y, uint8_t z) : + tilePos(x, y, z) { } virtual ~Tile() { delete ground; }; // non-copyable - Tile(const Tile&) = delete; - Tile& operator=(const Tile&) = delete; + Tile(const Tile &) = delete; + Tile &operator=(const Tile &) = delete; virtual TileItemVector* getItemList() = 0; virtual const TileItemVector* getItemList() const = 0; @@ -193,13 +192,11 @@ class Tile : public Cylinder int32_t getStackposOfCreature(const Player* player, const Creature* creature) const; int32_t getStackposOfItem(const Player* player, const Item* item) const; - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; - ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, - uint32_t& maxQueryCount, uint32_t flags) const override final; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t tileFlags, Creature* actor = nullptr) const override; - Tile* queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& flags) override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const override final; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t tileFlags, Creature* actor = nullptr) const override; + Tile* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override; void addThing(Thing* thing) override final; void addThing(int32_t index, Thing* thing) override; @@ -223,7 +220,7 @@ class Tile : public Cylinder void internalAddThing(Thing* thing) override; void virtual internalAddThing(uint32_t index, Thing* thing) override; - const Position& getPosition() const override final { + const Position &getPosition() const override final { return tilePos; } @@ -243,9 +240,9 @@ class Tile : public Cylinder private: void onAddTileItem(Item* item); - void onUpdateTileItem(Item* oldItem, const ItemType& oldType, Item* newItem, const ItemType& newType); - void onRemoveTileItem(const SpectatorHashSet& spectators, const std::vector& oldStackPosVector, Item* item); - void onUpdateTile(const SpectatorHashSet& spectators); + void onUpdateTileItem(Item* oldItem, const ItemType &oldType, Item* newItem, const ItemType &newType); + void onRemoveTileItem(const SpectatorHashSet &spectators, const std::vector &oldStackPosVector, Item* item); + void onUpdateTile(const SpectatorHashSet &spectators); void setTileFlags(const Item* item); void resetTileFlags(const Item* item); @@ -255,19 +252,18 @@ class Tile : public Cylinder Item* ground = nullptr; Position tilePos; uint32_t flags = 0; - }; // Used for walkable tiles, where there is high likeliness of // items being added/removed -class DynamicTile : public Tile -{ +class DynamicTile : public Tile { // By allocating the vectors in-house, we avoid some memory fragmentation TileItemVector items; CreatureVector creatures; public: - DynamicTile(uint16_t x, uint16_t y, uint8_t z) : Tile(x, y, z) {} + DynamicTile(uint16_t x, uint16_t y, uint8_t z) : + Tile(x, y, z) { } ~DynamicTile() { for (Item* item : items) { item->decrementReferenceCounter(); @@ -275,8 +271,8 @@ class DynamicTile : public Tile } // non-copyable - DynamicTile(const DynamicTile&) = delete; - DynamicTile& operator=(const DynamicTile&) = delete; + DynamicTile(const DynamicTile &) = delete; + DynamicTile &operator=(const DynamicTile &) = delete; TileItemVector* getItemList() override { return &items; @@ -300,14 +296,14 @@ class DynamicTile : public Tile }; // For blocking tiles, where we very rarely actually have items -class StaticTile final : public Tile -{ - // We very rarely even need the vectors, so don't keep them in memory - std::unique_ptr items; - std::unique_ptr creatures; +class StaticTile final : public Tile { + // We very rarely even need the vectors, so don't keep them in memory + std::unique_ptr items; + std::unique_ptr creatures; public: - StaticTile(uint16_t x, uint16_t y, uint8_t z) : Tile(x, y, z) {} + StaticTile(uint16_t x, uint16_t y, uint8_t z) : + Tile(x, y, z) { } ~StaticTile() { if (items) { for (Item* item : *items) { @@ -317,8 +313,8 @@ class StaticTile final : public Tile } // non-copyable - StaticTile(const StaticTile&) = delete; - StaticTile& operator=(const StaticTile&) = delete; + StaticTile(const StaticTile &) = delete; + StaticTile &operator=(const StaticTile &) = delete; TileItemVector* getItemList() override { return items.get(); @@ -347,4 +343,4 @@ class StaticTile final : public Tile } }; -#endif // SRC_ITEMS_TILE_H_ +#endif // SRC_ITEMS_TILE_H_ diff --git a/src/items/trashholder.cpp b/src/items/trashholder.cpp index d31ff58b631..9789c175085 100644 --- a/src/items/trashholder.cpp +++ b/src/items/trashholder.cpp @@ -5,41 +5,35 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "items/trashholder.h" #include "game/game.h" -ReturnValue TrashHolder::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature*) const -{ +ReturnValue TrashHolder::queryAdd(int32_t, const Thing &, uint32_t, uint32_t, Creature*) const { return RETURNVALUE_NOERROR; } -ReturnValue TrashHolder::queryMaxCount(int32_t, const Thing&, uint32_t queryCount, uint32_t& maxQueryCount, uint32_t) const -{ +ReturnValue TrashHolder::queryMaxCount(int32_t, const Thing &, uint32_t queryCount, uint32_t &maxQueryCount, uint32_t) const { maxQueryCount = std::max(1, queryCount); return RETURNVALUE_NOERROR; } -ReturnValue TrashHolder::queryRemove(const Thing&, uint32_t, uint32_t, Creature* /*= nullptr*/) const -{ +ReturnValue TrashHolder::queryRemove(const Thing &, uint32_t, uint32_t, Creature* /*= nullptr*/) const { return RETURNVALUE_NOTPOSSIBLE; } -Cylinder* TrashHolder::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) -{ +Cylinder* TrashHolder::queryDestination(int32_t &, const Thing &, Item**, uint32_t &) { return this; } -void TrashHolder::addThing(Thing* thing) -{ +void TrashHolder::addThing(Thing* thing) { return addThing(0, thing); } -void TrashHolder::addThing(int32_t, Thing* thing) -{ +void TrashHolder::addThing(int32_t, Thing* thing) { Item* item = thing->getItem(); if (!item) { return; @@ -49,7 +43,7 @@ void TrashHolder::addThing(int32_t, Thing* thing) return; } - const ItemType& it = Item::items[id]; + const ItemType &it = Item::items[id]; if (item->isHangable() && it.isGroundTile()) { Tile* tile = dynamic_cast(getParent()); if (tile && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { @@ -64,27 +58,22 @@ void TrashHolder::addThing(int32_t, Thing* thing) } } -void TrashHolder::updateThing(Thing*, uint16_t, uint32_t) -{ +void TrashHolder::updateThing(Thing*, uint16_t, uint32_t) { // } -void TrashHolder::replaceThing(uint32_t, Thing*) -{ +void TrashHolder::replaceThing(uint32_t, Thing*) { // } -void TrashHolder::removeThing(Thing*, uint32_t) -{ +void TrashHolder::removeThing(Thing*, uint32_t) { // } -void TrashHolder::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) -{ +void TrashHolder::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, CylinderLink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } -void TrashHolder::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) -{ +void TrashHolder::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/items/trashholder.h b/src/items/trashholder.h index bd06978ce05..289c8961ec8 100644 --- a/src/items/trashholder.h +++ b/src/items/trashholder.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_TRASHHOLDER_H_ #define SRC_ITEMS_TRASHHOLDER_H_ @@ -13,10 +13,10 @@ #include "items/item.h" #include "items/cylinder.h" -class TrashHolder final : public Item, public Cylinder -{ +class TrashHolder final : public Item, public Cylinder { public: - explicit TrashHolder(uint16_t itemId) : Item(itemId) {} + explicit TrashHolder(uint16_t itemId) : + Item(itemId) { } TrashHolder* getTrashHolder() override { return this; @@ -25,11 +25,11 @@ class TrashHolder final : public Item, public Cylinder return this; } - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; - ReturnValue queryMaxCount(int32_t index, const Thing& thing, uint32_t count, uint32_t& maxQueryCount, uint32_t flags) const override; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; - Cylinder* queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& flags) override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryMaxCount(int32_t index, const Thing &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) const override; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + Cylinder* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override; void addThing(Thing* thing) override; void addThing(int32_t index, Thing* thing) override; @@ -43,4 +43,4 @@ class TrashHolder final : public Item, public Cylinder void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; }; -#endif // SRC_ITEMS_TRASHHOLDER_H_ +#endif // SRC_ITEMS_TRASHHOLDER_H_ diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index 1f781a1d5bd..86ce39c663c 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -17,8 +17,7 @@ Weapons::Weapons() = default; Weapons::~Weapons() = default; -const Weapon* Weapons::getWeapon(const Item* item) const -{ +const Weapon* Weapons::getWeapon(const Item* item) const { if (!item) { return nullptr; } @@ -30,44 +29,37 @@ const Weapon* Weapons::getWeapon(const Item* item) const return it->second; } -void Weapons::clear() -{ +void Weapons::clear() { weapons.clear(); } -bool Weapons::registerLuaEvent(Weapon* event) -{ +bool Weapons::registerLuaEvent(Weapon* event) { weapons[event->getID()] = event; return true; } // Monsters -int32_t Weapons::getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue) -{ +int32_t Weapons::getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue) { // Returns maximum melee attack damage, rounding up return static_cast(std::ceil((attackSkill * (attackValue * 0.05)) + (attackValue * 0.5))); } // Players -int32_t Weapons::getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor, bool isMelee) -{ +int32_t Weapons::getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor, bool isMelee) { if (isMelee) { return static_cast(std::round((0.085 * attackFactor * attackValue * attackSkill) + (level / 5))); - } - else { + } else { return static_cast(std::round((0.09 * attackFactor * attackValue * attackSkill) + (level / 5))); } } -void Weapon::configureWeapon(const ItemType& it) -{ +void Weapon::configureWeapon(const ItemType &it) { id = it.id; } -int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const -{ - const Position& playerPos = player->getPosition(); - const Position& targetPos = target->getPosition(); +int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const { + const Position &playerPos = player->getPosition(); + const Position &targetPos = target->getPosition(); if (playerPos.z != targetPos.z) { return 0; } @@ -115,8 +107,7 @@ int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shoo return 100; } -bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const -{ +bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; @@ -126,33 +117,30 @@ bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const return true; } -CombatDamage Weapon::getCombatDamage(CombatDamage combat, Player * player, Item * item, int32_t damageModifier) const -{ - //Local variables +CombatDamage Weapon::getCombatDamage(CombatDamage combat, Player* player, Item* item, int32_t damageModifier) const { + // Local variables uint32_t level = player->getLevel(); int16_t elementalAttack = getElementDamageValue(); int32_t weaponAttack = std::max(0, item->getAttack()); int32_t playerSkill = player->getWeaponSkill(item); float attackFactor = player->getAttackFactor(); // full atk, balanced or full defense - //Getting values factores + // Getting values factores int32_t totalAttack = elementalAttack + weaponAttack; double weaponAttackProportion = (double)weaponAttack / (double)totalAttack; - //Calculating damage + // Calculating damage int32_t maxDamage = static_cast(Weapons::getMaxWeaponDamage(level, playerSkill, totalAttack, attackFactor, true) * player->getVocation()->meleeDamageMultiplier * damageModifier / 100); int32_t minDamage = level / 5; int32_t realDamage = normal_random(minDamage, maxDamage); - //Setting damage to combat + // Setting damage to combat combat.primary.value = realDamage * weaponAttackProportion; combat.secondary.value = realDamage * (1 - weaponAttackProportion); return combat; } - -bool Weapon::useFist(Player* player, Creature* target) -{ +bool Weapon::useFist(Player* player, Creature* target) { if (!Position::areInRange<1, 1>(player->getPosition(), target->getPosition())) { return false; } @@ -181,8 +169,7 @@ bool Weapon::useFist(Player* player, Creature* target) return true; } -void Weapon::internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const -{ +void Weapon::internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const { if (isLoadedCallback()) { LuaVariant var; var.type = VARIANT_NUMBER; @@ -206,8 +193,7 @@ void Weapon::internalUseWeapon(Player* player, Item* item, Creature* target, int onUsedWeapon(player, item, target->getTile()); } -void Weapon::internalUseWeapon(Player* player, Item* item, Tile* tile) const -{ +void Weapon::internalUseWeapon(Player* player, Item* item, Tile* tile) const { if (isLoadedCallback()) { LuaVariant var; var.type = VARIANT_TARGETPOSITION; @@ -220,8 +206,7 @@ void Weapon::internalUseWeapon(Player* player, Item* item, Tile* tile) const onUsedWeapon(player, item, tile); } -void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const -{ +void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const { if (!player->hasFlag(PlayerFlags_t::NotGainSkill)) { skills_t skillType; uint32_t skillPoint; @@ -253,7 +238,7 @@ void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const switch (action) { case WEAPONACTION_REMOVECOUNT: - if(g_configManager().getBoolean(REMOVE_WEAPON_AMMO)) { + if (g_configManager().getBoolean(REMOVE_WEAPON_AMMO)) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); } @@ -275,8 +260,7 @@ void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const } } -uint32_t Weapon::getManaCost(const Player* player) const -{ +uint32_t Weapon::getManaCost(const Player* player) const { if (mana != 0) { return mana; } @@ -288,8 +272,7 @@ uint32_t Weapon::getManaCost(const Player* player) const return (player->getMaxMana() * manaPercent) / 100; } -int32_t Weapon::getHealthCost(const Player* player) const -{ +int32_t Weapon::getHealthCost(const Player* player) const { if (health != 0) { return health; } @@ -301,13 +284,12 @@ int32_t Weapon::getHealthCost(const Player* player) const return (player->getMaxHealth() * healthPercent) / 100; } -bool Weapon::executeUseWeapon(Player* player, const LuaVariant& var) const -{ - //onUseWeapon(player, var) +bool Weapon::executeUseWeapon(Player* player, const LuaVariant &var) const { + // onUseWeapon(player, var) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[Weapon::executeUseWeapon - Player {} weaponId {}]" - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getID()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getID()); return false; } @@ -324,8 +306,7 @@ bool Weapon::executeUseWeapon(Player* player, const LuaVariant& var) const return getScriptInterface()->callFunction(2); } -void Weapon::decrementItemCount(Item* item) -{ +void Weapon::decrementItemCount(Item* item) { uint16_t count = item->getItemCount(); if (count > 1) { g_game().transformItem(item, item->getID(), count - 1); @@ -334,16 +315,15 @@ void Weapon::decrementItemCount(Item* item) } } -WeaponMelee::WeaponMelee(LuaScriptInterface* interface) : Weapon(interface) -{ +WeaponMelee::WeaponMelee(LuaScriptInterface* interface) : + Weapon(interface) { // Add combat type and blocked attributes to the weapon params.blockedByArmor = true; params.blockedByShield = true; params.combatType = COMBAT_PHYSICALDAMAGE; } -void WeaponMelee::configureWeapon(const ItemType& it) -{ +void WeaponMelee::configureWeapon(const ItemType &it) { if (it.abilities) { elementType = it.abilities->elementType; elementDamage = it.abilities->elementDamage; @@ -356,8 +336,7 @@ void WeaponMelee::configureWeapon(const ItemType& it) Weapon::configureWeapon(it); } -bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const -{ +bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; @@ -367,9 +346,7 @@ bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const return true; } -bool WeaponMelee::getSkillType(const Player* player, const Item* item, - skills_t& skill, uint32_t& skillpoint) const -{ +bool WeaponMelee::getSkillType(const Player* player, const Item* item, skills_t &skill, uint32_t &skillpoint) const { if (player->getAddAttackSkill() && player->getLastAttackBlockType() != BLOCK_IMMUNITY) { skillpoint = 1; } else { @@ -399,8 +376,7 @@ bool WeaponMelee::getSkillType(const Player* player, const Item* item, return false; } -int32_t WeaponMelee::getElementDamage(const Player* player, const Creature*, const Item* item) const -{ +int32_t WeaponMelee::getElementDamage(const Player* player, const Creature*, const Item* item) const { if (elementType == COMBAT_NONE) { return 0; } @@ -415,13 +391,11 @@ int32_t WeaponMelee::getElementDamage(const Player* player, const Creature*, con return -normal_random(minValue, static_cast(maxValue * player->getVocation()->meleeDamageMultiplier)); } -int16_t WeaponMelee::getElementDamageValue() const -{ +int16_t WeaponMelee::getElementDamageValue() const { return elementDamage; } -int32_t WeaponMelee::getWeaponDamage(const Player* player, const Creature*, const Item* item, bool maxDamage /*= false*/) const -{ +int32_t WeaponMelee::getWeaponDamage(const Player* player, const Creature*, const Item* item, bool maxDamage /*= false*/) const { using namespace std; int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = std::max(0, item->getAttack()); @@ -440,15 +414,13 @@ int32_t WeaponMelee::getWeaponDamage(const Player* player, const Creature*, cons } WeaponDistance::WeaponDistance(LuaScriptInterface* interface) : - Weapon(interface) -{ + Weapon(interface) { // Add combat type and distance effect to the weapon params.blockedByArmor = true; params.combatType = COMBAT_PHYSICALDAMAGE; } -void WeaponDistance::configureWeapon(const ItemType& it) -{ +void WeaponDistance::configureWeapon(const ItemType &it) { params.distanceEffect = it.shootType; if (it.abilities) { elementType = it.abilities->elementType; @@ -463,10 +435,9 @@ void WeaponDistance::configureWeapon(const ItemType& it) Weapon::configureWeapon(it); } -bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) const -{ +bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) const { int32_t damageModifier; - const ItemType& it = Item::items[id]; + const ItemType &it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { Item* mainWeaponItem = player->getWeapon(true); const Weapon* mainWeapon = g_weapons().getWeapon(mainWeaponItem); @@ -485,25 +456,25 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con int32_t chance; if (it.hitChance == 0) { - //hit chance is based on distance to target and distance skill + // hit chance is based on distance to target and distance skill uint32_t skill = player->getSkillLevel(SKILL_DISTANCE); - const Position& playerPos = player->getPosition(); - const Position& targetPos = target->getPosition(); + const Position &playerPos = player->getPosition(); + const Position &targetPos = target->getPosition(); uint32_t distance = std::max(Position::getDistanceX(playerPos, targetPos), Position::getDistanceY(playerPos, targetPos)); uint32_t maxHitChance; if (it.maxHitChance != -1) { maxHitChance = it.maxHitChance; } else if (it.ammoType != AMMO_NONE) { - //hit chance on two-handed weapons is limited to 90% + // hit chance on two-handed weapons is limited to 90% maxHitChance = 90; } else { - //one-handed is set to 75% + // one-handed is set to 75% maxHitChance = 75; } if (maxHitChance == 75) { - //chance for one-handed weapons + // chance for one-handed weapons switch (distance) { case 1: case 5: @@ -529,7 +500,7 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con break; } } else if (maxHitChance == 90) { - //formula for two-handed weapons + // formula for two-handed weapons switch (distance) { case 1: case 5: @@ -594,20 +565,18 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con if (chance >= uniform_random(1, 100)) { Weapon::internalUseWeapon(player, item, target, damageModifier); } else { - //miss target + // miss target Tile* destTile = target->getTile(); if (!Position::areInRange<1, 1, 0>(player->getPosition(), target->getPosition())) { static std::vector> destList { - {-1, -1}, {0, -1}, {1, -1}, - {-1, 0}, {0, 0}, {1, 0}, - {-1, 1}, {0, 1}, {1, 1} + { -1, -1 }, { 0, -1 }, { 1, -1 }, { -1, 0 }, { 0, 0 }, { 1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 } }; std::ranges::shuffle(destList.begin(), destList.end(), getRandomGenerator()); Position destPos = target->getPosition(); - for (const auto& dir : destList) { + for (const auto &dir : destList) { // Blocking tiles or tiles without ground ain't valid targets for spears Tile* tmpTile = g_game().map.getTile(static_cast(destPos.x + dir.first), static_cast(destPos.y + dir.second), destPos.z); if (tmpTile && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID) && tmpTile->getGround() != nullptr) { @@ -622,8 +591,7 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con return true; } -int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* target, const Item* item) const -{ +int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* target, const Item* item) const { if (elementType == COMBAT_NONE) { return 0; } @@ -632,7 +600,7 @@ int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* t if (item->getWeaponType() == WEAPON_AMMO) { Item* weapon = player->getWeapon(true); if (weapon) { - attackValue += item->getAttack(); + attackValue += item->getAttack(); attackValue += weapon->getAttack(); } } @@ -640,39 +608,36 @@ int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* t int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); - int32_t minValue = std::round(player->getLevel() / 5); - int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue) / 2; + int32_t minValue = std::round(player->getLevel() / 5); + int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue) / 2; - if (target) { - if (target->getPlayer()) { - minValue /= 4; - } else { - minValue /= 2; - } - } + if (target) { + if (target->getPlayer()) { + minValue /= 4; + } else { + minValue /= 2; + } + } return -normal_random(minValue, static_cast(maxValue * player->getVocation()->distDamageMultiplier)); } -int16_t WeaponDistance::getElementDamageValue() const -{ +int16_t WeaponDistance::getElementDamageValue() const { return elementDamage; } - -int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage /*= false*/) const -{ +int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage /*= false*/) const { int32_t attackValue = item->getAttack(); - bool hasElement = false; + bool hasElement = false; if (item->getWeaponType() == WEAPON_AMMO) { Item* weapon = player->getWeapon(true); if (weapon) { - const ItemType& it = Item::items[item->getID()]; - if (it.abilities && it.abilities->elementDamage != 0) { - attackValue += it.abilities->elementDamage; - hasElement = true; - } + const ItemType &it = Item::items[item->getID()]; + if (it.abilities && it.abilities->elementDamage != 0) { + attackValue += it.abilities->elementDamage; + hasElement = true; + } attackValue += weapon->getAttack(); } @@ -681,30 +646,29 @@ int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* ta int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); - int32_t minValue = player->getLevel() / 5; - int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue); + int32_t minValue = player->getLevel() / 5; + int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue); if (maxDamage) { return -maxValue; } - if (target->getPlayer()) { - if (hasElement) { - minValue /= 4; - } else { - minValue /= 2; - } - } else { - if (hasElement) { - maxValue /= 2; - minValue /= 2; - } - } + if (target->getPlayer()) { + if (hasElement) { + minValue /= 4; + } else { + minValue /= 2; + } + } else { + if (hasElement) { + maxValue /= 2; + minValue /= 2; + } + } return -normal_random(minValue, (maxValue * static_cast(player->getVocation()->distDamageMultiplier))); } -bool WeaponDistance::getSkillType(const Player* player, const Item*, skills_t& skill, uint32_t& skillpoint) const -{ +bool WeaponDistance::getSkillType(const Player* player, const Item*, skills_t &skill, uint32_t &skillpoint) const { skill = SKILL_DISTANCE; if (player->getAddAttackSkill()) { @@ -730,24 +694,20 @@ bool WeaponDistance::getSkillType(const Player* player, const Item*, skills_t& s return true; } -void WeaponWand::configureWeapon(const ItemType& it) -{ +void WeaponWand::configureWeapon(const ItemType &it) { params.distanceEffect = it.shootType; - const_cast(it).combatType = params.combatType; - const_cast(it).maxHitChance = (minChange + maxChange) / 2; + const_cast(it).combatType = params.combatType; + const_cast(it).maxHitChance = (minChange + maxChange) / 2; Weapon::configureWeapon(it); } -int32_t WeaponWand::getWeaponDamage(const Player*, const Creature*, const Item*, bool maxDamage /*= false*/) const -{ +int32_t WeaponWand::getWeaponDamage(const Player*, const Creature*, const Item*, bool maxDamage /*= false*/) const { if (maxDamage) { return -maxChange; } return -normal_random(minChange, maxChange); } -int16_t WeaponWand::getElementDamageValue() const -{ +int16_t WeaponWand::getElementDamageValue() const { return 0; } - diff --git a/src/items/weapons/weapons.h b/src/items/weapons/weapons.h index c9b406561ed..14a76d82e06 100644 --- a/src/items/weapons/weapons.h +++ b/src/items/weapons/weapons.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_ITEMS_WEAPONS_WEAPONS_H_ #define SRC_ITEMS_WEAPONS_WEAPONS_H_ @@ -24,17 +24,16 @@ class WeaponWand; using Weapon_ptr = std::unique_ptr; -class Weapons final : public Scripts -{ +class Weapons final : public Scripts { public: Weapons(); ~Weapons(); // non-copyable - Weapons(const Weapons&) = delete; - Weapons& operator=(const Weapons&) = delete; + Weapons(const Weapons &) = delete; + Weapons &operator=(const Weapons &) = delete; - static Weapons& getInstance() { + static Weapons &getInstance() { // Guaranteed to be destroyed static Weapons instance; // Instantiated on first use @@ -55,12 +54,11 @@ class Weapons final : public Scripts constexpr auto g_weapons = &Weapons::getInstance; -class Weapon : public Script -{ +class Weapon : public Script { public: using Script::Script; - virtual void configureWeapon(const ItemType& it); + virtual void configureWeapon(const ItemType &it); virtual bool interruptSwing() const { return false; } @@ -172,10 +170,10 @@ class Weapon : public Script } } - const std::string& getVocationString() const { + const std::string &getVocationString() const { return vocationString; } - void setVocationString(const std::string& str) { + void setVocationString(const std::string &str) { vocationString = str; } @@ -183,15 +181,14 @@ class Weapon : public Script void internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const; void internalUseWeapon(Player* player, Item* item, Tile* tile) const; - private: - virtual bool getSkillType(const Player*, const Item*, skills_t&, uint32_t&) const { + virtual bool getSkillType(const Player*, const Item*, skills_t &, uint32_t &) const { return false; } uint32_t getManaCost(const Player* player) const; int32_t getHealthCost(const Player* player) const; - bool executeUseWeapon(Player* player, const LuaVariant& var) const; + bool executeUseWeapon(Player* player, const LuaVariant &var) const; uint16_t id = 0; @@ -225,8 +222,7 @@ class Weapon : public Script friend class WeaponFunctions; }; -class WeaponMelee final : public Weapon -{ +class WeaponMelee final : public Weapon { public: explicit WeaponMelee(LuaScriptInterface* interface); @@ -234,24 +230,24 @@ class WeaponMelee final : public Weapon return "onUseWeapon"; } - void configureWeapon(const ItemType& it) override; + void configureWeapon(const ItemType &it) override; bool useWeapon(Player* player, Item* item, Creature* target) const override; int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const override; int32_t getElementDamage(const Player* player, const Creature* target, const Item* item) const override; - CombatType_t getElementType() const override { return elementType; } + CombatType_t getElementType() const override { + return elementType; + } virtual int16_t getElementDamageValue() const override; - private: - bool getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const override; + bool getSkillType(const Player* player, const Item* item, skills_t &skill, uint32_t &skillpoint) const override; uint16_t elementDamage = 0; CombatType_t elementType = COMBAT_NONE; }; -class WeaponDistance final : public Weapon -{ +class WeaponDistance final : public Weapon { public: explicit WeaponDistance(LuaScriptInterface* interface); @@ -259,7 +255,7 @@ class WeaponDistance final : public Weapon return "onUseWeapon"; } - void configureWeapon(const ItemType& it) override; + void configureWeapon(const ItemType &it) override; bool interruptSwing() const override { return true; } @@ -268,17 +264,19 @@ class WeaponDistance final : public Weapon int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const override; int32_t getElementDamage(const Player* player, const Creature* target, const Item* item) const override; - CombatType_t getElementType() const override { return elementType; } + CombatType_t getElementType() const override { + return elementType; + } virtual int16_t getElementDamageValue() const override; + private: - bool getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const override; + bool getSkillType(const Player* player, const Item* item, skills_t &skill, uint32_t &skillpoint) const override; CombatType_t elementType = COMBAT_NONE; uint16_t elementDamage = 0; }; -class WeaponWand final : public Weapon -{ +class WeaponWand final : public Weapon { public: using Weapon::Weapon; @@ -286,11 +284,15 @@ class WeaponWand final : public Weapon return "onUseWeapon"; } - void configureWeapon(const ItemType& it) override; + void configureWeapon(const ItemType &it) override; int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const override; - int32_t getElementDamage(const Player*, const Creature*, const Item*) const override { return 0; } - CombatType_t getElementType() const override { return COMBAT_NONE; } + int32_t getElementDamage(const Player*, const Creature*, const Item*) const override { + return 0; + } + CombatType_t getElementType() const override { + return COMBAT_NONE; + } virtual int16_t getElementDamageValue() const override; void setMinChange(int32_t change) { minChange = change; @@ -301,7 +303,7 @@ class WeaponWand final : public Weapon } private: - bool getSkillType(const Player*, const Item*, skills_t&, uint32_t&) const override { + bool getSkillType(const Player*, const Item*, skills_t &, uint32_t &) const override { return false; } @@ -309,4 +311,4 @@ class WeaponWand final : public Weapon int32_t maxChange = 0; }; -#endif // SRC_ITEMS_WEAPONS_WEAPONS_H_ +#endif // SRC_ITEMS_WEAPONS_WEAPONS_H_ diff --git a/src/lua/callbacks/creaturecallback.cpp b/src/lua/callbacks/creaturecallback.cpp index 4baa5bca1c3..1c0d298e31a 100644 --- a/src/lua/callbacks/creaturecallback.cpp +++ b/src/lua/callbacks/creaturecallback.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "lua/callbacks/creaturecallback.h" @@ -16,16 +16,16 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR( - "[CreatureCallback::startScriptInterface] - {} {} Call stack overflow. Too many lua script calls being nested.", - getCreatureClass(targetCreature), - targetCreature->getName() + "[CreatureCallback::startScriptInterface] - {} {} Call stack overflow. Too many lua script calls being nested.", + getCreatureClass(targetCreature), + targetCreature->getName() ); return false; } scriptInterface - ->getScriptEnv() - ->setScriptId(scriptId, scriptInterface); + ->getScriptEnv() + ->setScriptId(scriptId, scriptInterface); L = scriptInterface->getLuaState(); @@ -34,12 +34,12 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { return true; } -void CreatureCallback::pushSpecificCreature(Creature *creature) { +void CreatureCallback::pushSpecificCreature(Creature* creature) { if (Npc* npc = creature->getNpc()) { LuaScriptInterface::pushUserdata(L, npc); - }else if (Monster* monster = creature->getMonster()) { + } else if (Monster* monster = creature->getMonster()) { LuaScriptInterface::pushUserdata(L, monster); - }else if (Player* player = creature->getPlayer()) { + } else if (Player* player = creature->getPlayer()) { LuaScriptInterface::pushUserdata(L, player); } else { return; @@ -49,7 +49,7 @@ void CreatureCallback::pushSpecificCreature(Creature *creature) { LuaScriptInterface::setMetatable(L, -1, getCreatureClass(creature)); } -std::string CreatureCallback::getCreatureClass(Creature *creature) { +std::string CreatureCallback::getCreatureClass(Creature* creature) { if (creature->getNpc()) { return "Npc"; } diff --git a/src/lua/callbacks/creaturecallback.h b/src/lua/callbacks/creaturecallback.h index 7f1b257d7e4..523078d19a1 100644 --- a/src/lua/callbacks/creaturecallback.h +++ b/src/lua/callbacks/creaturecallback.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CALLBACKS_CREATURECALLBACK_H_ #define SRC_LUA_CALLBACKS_CREATURECALLBACK_H_ @@ -17,19 +17,19 @@ class Creature; class CreatureCallback { public: - CreatureCallback(LuaScriptInterface* scriptInterface, Creature* targetCreature) - : scriptInterface(scriptInterface), targetCreature(targetCreature) {}; - ~CreatureCallback() {} + CreatureCallback(LuaScriptInterface* scriptInterface, Creature* targetCreature) : + scriptInterface(scriptInterface), targetCreature(targetCreature) {}; + ~CreatureCallback() { } bool startScriptInterface(int32_t scriptId); - void pushSpecificCreature(Creature *creature); + void pushSpecificCreature(Creature* creature); bool persistLuaState() { return params > 0 && scriptInterface->callFunction(params); } - void pushCreature(Creature *creature) { + void pushCreature(Creature* creature) { params++; LuaScriptInterface::pushUserdata(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); @@ -45,7 +45,7 @@ class CreatureCallback { lua_pushnumber(L, number); } - void pushString(const std::string& str) { + void pushString(const std::string &str) { params++; LuaScriptInterface::pushString(L, str); } @@ -56,7 +56,7 @@ class CreatureCallback { } protected: - static std::string getCreatureClass(Creature *creature); + static std::string getCreatureClass(Creature* creature); private: LuaScriptInterface* scriptInterface; @@ -65,4 +65,4 @@ class CreatureCallback { lua_State* L = nullptr; }; -#endif // SRC_LUA_CALLBACKS_CREATURECALLBACK_H_ +#endif // SRC_LUA_CALLBACKS_CREATURECALLBACK_H_ diff --git a/src/lua/creature/actions.cpp b/src/lua/creature/actions.cpp index 95f0c1ddc11..e4a5df62560 100644 --- a/src/lua/creature/actions.cpp +++ b/src/lua/creature/actions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -35,7 +35,7 @@ bool Actions::registerLuaItemEvent(Action* action) { std::vector tmpVector; tmpVector.reserve(itemIdVector.size()); - for (const auto& itemId : itemIdVector) { + for (const auto &itemId : itemIdVector) { // Check if the item is already registered and prevent it from being registered again if (hasItemId(itemId)) { SPDLOG_WARN( @@ -68,7 +68,7 @@ bool Actions::registerLuaUniqueEvent(Action* action) { std::vector tmpVector; tmpVector.reserve(uniqueIdVector.size()); - for (const auto& uniqueId : uniqueIdVector) { + for (const auto &uniqueId : uniqueIdVector) { // Check if the unique is already registered and prevent it from being registered again if (!hasUniqueId(uniqueId)) { // Register unique id the unique item map @@ -99,7 +99,7 @@ bool Actions::registerLuaActionEvent(Action* action) { std::vector tmpVector; tmpVector.reserve(actionIdVector.size()); - for (const auto& actionId : actionIdVector) { + for (const auto &actionId : actionIdVector) { // Check if the unique is already registered and prevent it from being registered again if (!hasActionId(actionId)) { // Register action in the action item map @@ -130,7 +130,7 @@ bool Actions::registerLuaPositionEvent(Action* action) { std::vector tmpVector; tmpVector.reserve(positionVector.size()); - for (const auto& position : positionVector) { + for (const auto &position : positionVector) { // Check if the position is already registered and prevent it from being registered again if (!hasPosition(position)) { // Register position in the action position map @@ -151,7 +151,7 @@ bool Actions::registerLuaPositionEvent(Action* action) { } bool Actions::registerLuaEvent(Action* action) { - Action_ptr actionPtr{ action }; + Action_ptr actionPtr { action }; // Call all register lua events if (registerLuaItemEvent(action) || registerLuaUniqueEvent(action) || registerLuaActionEvent(action) || registerLuaPositionEvent(action)) { @@ -164,16 +164,13 @@ bool Actions::registerLuaEvent(Action* action) { ); return false; } - SPDLOG_DEBUG("[{}] missing or incorrect script: {}", - __FUNCTION__, - action->getScriptInterface()->getLoadingScriptName() - ); + SPDLOG_DEBUG("[{}] missing or incorrect script: {}", __FUNCTION__, action->getScriptInterface()->getLoadingScriptName()); return false; } -ReturnValue Actions::canUse(const Player* player, const Position& pos) { +ReturnValue Actions::canUse(const Player* player, const Position &pos) { if (pos.x != 0xFFFF) { - const Position& playerPos = player->getPosition(); + const Position &playerPos = player->getPosition(); if (playerPos.z != pos.z) { return playerPos.z > pos.z ? RETURNVALUE_FIRSTGOUPSTAIRS : RETURNVALUE_FIRSTGODOWNSTAIRS; } @@ -185,7 +182,7 @@ ReturnValue Actions::canUse(const Player* player, const Position& pos) { return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUse(const Player* player, const Position& pos, const Item* item) { +ReturnValue Actions::canUse(const Player* player, const Position &pos, const Item* item) { Action* action = getAction(item); if (action != nullptr) { return action->canExecuteAction(player, pos); @@ -193,16 +190,14 @@ ReturnValue Actions::canUse(const Player* player, const Position& pos, const Ite return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUseFar(const Creature* creature, const Position& toPos, - bool checkLineOfSight, bool checkFloor) { +ReturnValue Actions::canUseFar(const Creature* creature, const Position &toPos, bool checkLineOfSight, bool checkFloor) { if (toPos.x == 0xFFFF) { return RETURNVALUE_NOERROR; } - const Position& creaturePos = creature->getPosition(); + const Position &creaturePos = creature->getPosition(); if (checkFloor && creaturePos.z != toPos.z) { - return creaturePos.z > toPos.z ? - RETURNVALUE_FIRSTGOUPSTAIRS : RETURNVALUE_FIRSTGODOWNSTAIRS; + return creaturePos.z > toPos.z ? RETURNVALUE_FIRSTGOUPSTAIRS : RETURNVALUE_FIRSTGODOWNSTAIRS; } if (!Position::areInRange<7, 5>(toPos, creaturePos)) { @@ -236,16 +231,12 @@ Action* Actions::getAction(const Item* item) { return &it->second; } - if (auto iteratePositions = actionPositionMap.find(item->getPosition()); - iteratePositions != actionPositionMap.end()) - { - if (const Tile * tile = item->getTile(); - tile) - { + iteratePositions != actionPositionMap.end()) { + if (const Tile* tile = item->getTile(); + tile) { if (const Player* player = item->getHoldingPlayer(); - player && item->getTopParent() == player) - { + player && item->getTopParent() == player) { SPDLOG_DEBUG("[Actions::getAction] - The position only is valid for use item in the map, player name {}", player->getName()); return nullptr; } @@ -254,11 +245,11 @@ Action* Actions::getAction(const Item* item) { } } - //rune items + // rune items return g_spells().getRuneSpell(item->getID()); } -ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey) { +ReturnValue Actions::internalUseItem(Player* player, const Position &pos, uint8_t index, Item* item, bool isHotkey) { if (Door* door = item->getDoor()) { if (!door->canUse(player)) { return RETURNVALUE_CANNOTUSETHISOBJECT; @@ -274,9 +265,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ if (item->isRemoved()) { return RETURNVALUE_CANNOTUSETHISOBJECT; } - } else if (action->useFunction - && action->useFunction(player, item, pos, nullptr, pos, isHotkey)) - { + } else if (action->useFunction && action->useFunction(player, item, pos, nullptr, pos, isHotkey)) { return RETURNVALUE_NOERROR; } } @@ -297,7 +286,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ if (Container* container = item->getContainer()) { Container* openContainer; - //depot container + // depot container if (DepotLocker* depot = container->getDepotLocker()) { DepotLocker* myDepotLocker = player->getDepotLocker(depot->getDepotId()); myDepotLocker->setParent(depot->getParent()->getTile()); @@ -307,7 +296,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ openContainer = container; } - //reward chest + // reward chest if (container->getRewardChest() != nullptr) { RewardChest* myRewardChest = player->getRewardChest(); if (myRewardChest->size() == 0) { @@ -315,7 +304,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ } myRewardChest->setParent(container->getParent()->getTile()); - for (auto& it : player->rewardMap) { + for (auto &it : player->rewardMap) { it.second->setParent(myRewardChest); } @@ -335,7 +324,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ uint32_t corpseOwner = container->getCorpseOwner(); if (container->isRewardCorpse()) { - //only players who participated in the fight can open the corpse + // only players who participated in the fight can open the corpse if (player->getGroup()->id >= account::GROUP_TYPE_GAMEMASTER || player->getAccountType() >= account::ACCOUNT_TYPE_SENIORTUTOR) { return RETURNVALUE_YOUCANTOPENCORPSEADM; } @@ -346,7 +335,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ return RETURNVALUE_YOUARENOTTHEOWNER; } - //open/close container + // open/close container int32_t oldContainerId = player->getContainerID(openContainer); if (oldContainerId != -1) { player->onCloseContainer(openContainer); @@ -359,7 +348,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ return RETURNVALUE_NOERROR; } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.canReadText) { if (it.canWriteText) { player->setWriteItem(item, it.maxTextLen); @@ -375,8 +364,8 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ return RETURNVALUE_CANNOTUSETHISOBJECT; } -bool Actions::useItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey) { - const ItemType& it = Item::items[item->getID()]; +bool Actions::useItem(Player* player, const Position &pos, uint8_t index, Item* item, bool isHotkey) { + const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); @@ -406,9 +395,8 @@ bool Actions::useItem(Player* player, const Position& pos, uint8_t index, Item* return true; } -bool Actions::useItemEx(Player* player, const Position& fromPos, const Position& toPos, - uint8_t toStackPos, Item* item, bool isHotkey, Creature* creature/* = nullptr*/) { - const ItemType& it = Item::items[item->getID()]; +bool Actions::useItemEx(Player* player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, Item* item, bool isHotkey, Creature* creature /* = nullptr*/) { + const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); @@ -459,7 +447,7 @@ bool Actions::useItemEx(Player* player, const Position& fromPos, const Position& void Actions::showUseHotkeyMessage(Player* player, const Item* item, uint32_t count) { std::ostringstream ss; - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (!it.showCount) { ss << "Using one of " << item->getName() << "..."; } else if (count == 1) { @@ -470,7 +458,6 @@ void Actions::showUseHotkeyMessage(Player* player, const Item* item, uint32_t co player->sendTextMessage(MESSAGE_HOTKEY_PRESSED, ss.str()); } - /* ================ Action interface @@ -478,9 +465,10 @@ void Actions::showUseHotkeyMessage(Player* player, const Item* item, uint32_t co */ // Action constructor -Action::Action(LuaScriptInterface* interface) : Script(interface) {} +Action::Action(LuaScriptInterface* interface) : + Script(interface) { } -ReturnValue Action::canExecuteAction(const Player* player, const Position& toPos) { +ReturnValue Action::canExecuteAction(const Player* player, const Position &toPos) { if (!allowFarUse) { return g_actions().canUse(player, toPos); } @@ -488,20 +476,19 @@ ReturnValue Action::canExecuteAction(const Player* player, const Position& toPos return g_actions().canUseFar(player, toPos, checkLineOfSight, checkFloor); } -Thing* Action::getTarget(Player* player, Creature* targetCreature, - const Position& toPosition, uint8_t toStackPos) const { +Thing* Action::getTarget(Player* player, Creature* targetCreature, const Position &toPosition, uint8_t toStackPos) const { if (targetCreature != nullptr) { return targetCreature; } return g_game().internalGetThing(player, toPosition, toStackPos, 0, STACKPOS_USETARGET); } -bool Action::executeUse(Player* player, Item* item, const Position& fromPosition, Thing* target, const Position& toPosition, bool isHotkey) { - //onUse(player, item, fromPosition, target, toPosition, isHotkey) +bool Action::executeUse(Player* player, Item* item, const Position &fromPosition, Thing* target, const Position &toPosition, bool isHotkey) { + // onUse(player, item, fromPosition, target, toPosition, isHotkey) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[Action::executeUse - Player {}, on item {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), item->getName()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), item->getName()); return false; } diff --git a/src/lua/creature/actions.h b/src/lua/creature/actions.h index ee304a69385..eb39afc4168 100644 --- a/src/lua/creature/actions.h +++ b/src/lua/creature/actions.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CREATURE_ACTIONS_H_ #define SRC_LUA_CREATURE_ACTIONS_H_ @@ -24,9 +24,7 @@ class Action : public Script { explicit Action(LuaScriptInterface* interface); // Scripting - virtual bool executeUse(Player* player, Item* item, - const Position& fromPosition, Thing* target, - const Position& toPosition, bool isHotkey); + virtual bool executeUse(Player* player, Item* item, const Position &fromPosition, Thing* target, const Position &toPosition, bool isHotkey); bool getAllowFarUse() const { return allowFarUse; @@ -86,11 +84,12 @@ class Action : public Script { bool hasPosition(Position position) { return std::ranges::find_if(positions.begin(), positions.end(), [position](Position storedPosition) { - if (storedPosition == position) { - return true; - } - return false; - }) != positions.end(); + if (storedPosition == position) { + return true; + } + return false; + }) + != positions.end(); } std::vector getPositions() const { @@ -100,15 +99,13 @@ class Action : public Script { positions.emplace_back(pos); } - virtual ReturnValue canExecuteAction(const Player* player, - const Position& toPos); + virtual ReturnValue canExecuteAction(const Player* player, const Position &toPos); virtual bool hasOwnErrorHandler() { return false; } - virtual Thing* getTarget(Player* player, Creature* targetCreature, - const Position& toPosition, uint8_t toStackPos) const; + virtual Thing* getTarget(Player* player, Creature* targetCreature, const Position &toPosition, uint8_t toStackPos) const; private: std::string getScriptTypeName() const override { @@ -117,9 +114,10 @@ class Action : public Script { std::function useFunction = nullptr; + const Position &fromPosition, Thing* target, + const Position &toPosition, bool isHotkey + )> + useFunction = nullptr; // Atributes bool allowFarUse = false; @@ -141,22 +139,22 @@ class Actions final : public Scripts { ~Actions(); // non-copyable - Actions(const Actions&) = delete; - Actions& operator=(const Actions&) = delete; + Actions(const Actions &) = delete; + Actions &operator=(const Actions &) = delete; - static Actions& getInstance() { + static Actions &getInstance() { // Guaranteed to be destroyed static Actions instance; // Instantiated on first use return instance; } - bool useItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey); - bool useItemEx(Player* player, const Position& fromPos, const Position& toPos, uint8_t toStackPos, Item* item, bool isHotkey, Creature* creature = nullptr); + bool useItem(Player* player, const Position &pos, uint8_t index, Item* item, bool isHotkey); + bool useItemEx(Player* player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, Item* item, bool isHotkey, Creature* creature = nullptr); - ReturnValue canUse(const Player* player, const Position& pos); - ReturnValue canUse(const Player* player, const Position& pos, const Item* item); - ReturnValue canUseFar(const Creature* creature, const Position& toPos, bool checkLineOfSight, bool checkFloor); + ReturnValue canUse(const Player* player, const Position &pos); + ReturnValue canUse(const Player* player, const Position &pos, const Item* item); + ReturnValue canUseFar(const Creature* creature, const Position &toPos, bool checkLineOfSight, bool checkFloor); bool registerLuaItemEvent(Action* action); bool registerLuaUniqueEvent(Action* action); @@ -169,8 +167,7 @@ class Actions final : public Scripts { private: bool hasPosition(Position position) const { if (auto it = actionPositionMap.find(position); - it != actionPositionMap.end()) - { + it != actionPositionMap.end()) { return true; } return false; @@ -184,11 +181,9 @@ class Actions final : public Scripts { actionPositionMap.try_emplace(position, action); } - bool hasItemId(uint16_t itemId) const { if (auto it = useItemMap.find(itemId); - it != useItemMap.end()) - { + it != useItemMap.end()) { return true; } return false; @@ -200,8 +195,7 @@ class Actions final : public Scripts { bool hasUniqueId(uint16_t uniqueId) const { if (auto it = uniqueItemMap.find(uniqueId); - it != uniqueItemMap.end()) - { + it != uniqueItemMap.end()) { return true; } return false; @@ -213,8 +207,7 @@ class Actions final : public Scripts { bool hasActionId(uint16_t actionId) const { if (auto it = actionItemMap.find(actionId); - it != actionItemMap.end()) - { + it != actionItemMap.end()) { return true; } return false; @@ -224,7 +217,7 @@ class Actions final : public Scripts { actionItemMap.try_emplace(actionId, action); } - ReturnValue internalUseItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey); + ReturnValue internalUseItem(Player* player, const Position &pos, uint8_t index, Item* item, bool isHotkey); static void showUseHotkeyMessage(Player* player, const Item* item, uint32_t count); using ActionUseMap = std::map; @@ -238,4 +231,4 @@ class Actions final : public Scripts { constexpr auto g_actions = &Actions::getInstance; -#endif // SRC_LUA_CREATURE_ACTIONS_H_ +#endif // SRC_LUA_CREATURE_ACTIONS_H_ diff --git a/src/lua/creature/creatureevent.cpp b/src/lua/creature/creatureevent.cpp index c4392f18177..1e9798d7c48 100644 --- a/src/lua/creature/creatureevent.cpp +++ b/src/lua/creature/creatureevent.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,15 +13,14 @@ #include "utils/tools.h" #include "creatures/players/player.h" -void CreatureEvents::clear() -{ +void CreatureEvents::clear() { for (auto &[name, event] : creatureEvents) { event.clearEvent(); } } bool CreatureEvents::registerLuaEvent(CreatureEvent* event) { - CreatureEvent_ptr creatureEvent{ event }; + CreatureEvent_ptr creatureEvent { event }; if (creatureEvent->getEventType() == CREATURE_EVENT_NONE) { SPDLOG_ERROR( "[{}] - Trying to register event without type for script: {}", @@ -33,7 +32,7 @@ bool CreatureEvents::registerLuaEvent(CreatureEvent* event) { CreatureEvent* oldEvent = getEventByName(creatureEvent->getName(), false); if (oldEvent) { - //if there was an event with the same that is not loaded + // if there was an event with the same that is not loaded //(happens when realoading), it is reused if (!oldEvent->isLoaded() && oldEvent->getEventType() == creatureEvent->getEventType()) { oldEvent->copyEvent(creatureEvent.get()); @@ -41,13 +40,13 @@ bool CreatureEvents::registerLuaEvent(CreatureEvent* event) { return false; } else { - //if not, register it normally + // if not, register it normally creatureEvents.emplace(creatureEvent->getName(), std::move(*creatureEvent)); return true; } } -CreatureEvent* CreatureEvents::getEventByName(const std::string& name, bool forceLoaded /*= true*/) { +CreatureEvent* CreatureEvents::getEventByName(const std::string &name, bool forceLoaded /*= true*/) { auto it = creatureEvents.find(name); if (it != creatureEvents.end()) { if (!forceLoaded || it->second.isLoaded()) { @@ -58,8 +57,8 @@ CreatureEvent* CreatureEvents::getEventByName(const std::string& name, bool forc } bool CreatureEvents::playerLogin(Player* player) const { - //fire global event if is registered - for (const auto& it : creatureEvents) { + // fire global event if is registered + for (const auto &it : creatureEvents) { if (it.second.getEventType() == CREATURE_EVENT_LOGIN) { if (!it.second.executeOnLogin(player)) { return false; @@ -70,8 +69,8 @@ bool CreatureEvents::playerLogin(Player* player) const { } bool CreatureEvents::playerLogout(Player* player) const { - //fire global event if is registered - for (const auto& it : creatureEvents) { + // fire global event if is registered + for (const auto &it : creatureEvents) { if (it.second.getEventType() == CREATURE_EVENT_LOGOUT) { if (!it.second.executeOnLogout(player)) { return false; @@ -86,9 +85,8 @@ bool CreatureEvents::playerAdvance( skills_t skill, uint32_t oldLevel, uint32_t newLevel -) const -{ - for ([[maybe_unused]] const auto& [eventName, eventPtr] : creatureEvents) { +) const { + for ([[maybe_unused]] const auto &[eventName, eventPtr] : creatureEvents) { if (eventPtr.getEventType() == CREATURE_EVENT_ADVANCE) { if (!eventPtr.executeAdvance(player, skill, oldLevel, newLevel)) { return false; @@ -104,7 +102,8 @@ bool CreatureEvents::playerAdvance( ======================= */ -CreatureEvent::CreatureEvent(LuaScriptInterface* interface) : Script(interface) {} +CreatureEvent::CreatureEvent(LuaScriptInterface* interface) : + Script(interface) { } void CreatureEvents::removeInvalidEvents() { for (auto it = creatureEvents.begin(); it != creatureEvents.end(); ++it) { @@ -115,7 +114,7 @@ void CreatureEvents::removeInvalidEvents() { } std::string CreatureEvent::getScriptTypeName() const { - //Depending on the type script event name is different + // Depending on the type script event name is different switch (type) { case CREATURE_EVENT_LOGIN: return "onLogin"; @@ -174,11 +173,11 @@ void CreatureEvent::clearEvent() { } bool CreatureEvent::executeOnLogin(Player* player) const { - //onLogin(player) + // onLogin(player) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeOnLogin - Player {} event {}]" - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getName()); return false; } @@ -194,11 +193,11 @@ bool CreatureEvent::executeOnLogin(Player* player) const { } bool CreatureEvent::executeOnLogout(Player* player) const { - //onLogout(player) + // onLogout(player) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeOnLogout - Player {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getName()); return false; } @@ -214,11 +213,11 @@ bool CreatureEvent::executeOnLogout(Player* player) const { } bool CreatureEvent::executeOnThink(Creature* creature, uint32_t interval) const { - //onThink(creature, interval) + // onThink(creature, interval) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeOnThink - Creature {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), getName()); return false; } @@ -236,11 +235,11 @@ bool CreatureEvent::executeOnThink(Creature* creature, uint32_t interval) const } bool CreatureEvent::executeOnPrepareDeath(Creature* creature, Creature* killer) const { - //onPrepareDeath(creature, killer) + // onPrepareDeath(creature, killer) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeOnPrepareDeath - Creature {} killer {}" - " event {}] Call stack overflow. Too many lua script calls being nested.", - creature->getName(), killer->getName(), getName()); + " event {}] Call stack overflow. Too many lua script calls being nested.", + creature->getName(), killer->getName(), getName()); return false; } @@ -265,11 +264,11 @@ bool CreatureEvent::executeOnPrepareDeath(Creature* creature, Creature* killer) } bool CreatureEvent::executeOnDeath(Creature* creature, Item* corpse, Creature* killer, Creature* mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const { - //onDeath(creature, corpse, lasthitkiller, mostdamagekiller, lasthitunjustified, mostdamageunjustified) + // onDeath(creature, corpse, lasthitkiller, mostdamagekiller, lasthitunjustified, mostdamageunjustified) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeOnDeath - Creature {} killer {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), killer->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), killer->getName(), getName()); return false; } @@ -304,13 +303,12 @@ bool CreatureEvent::executeOnDeath(Creature* creature, Item* corpse, Creature* k return getScriptInterface()->callFunction(6); } -bool CreatureEvent::executeAdvance(Player* player, skills_t skill, uint32_t oldLevel, - uint32_t newLevel) const { - //onAdvance(player, skill, oldLevel, newLevel) +bool CreatureEvent::executeAdvance(Player* player, skills_t skill, uint32_t oldLevel, uint32_t newLevel) const { + // onAdvance(player, skill, oldLevel, newLevel) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeAdvance - Player {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getName()); return false; } @@ -330,11 +328,11 @@ bool CreatureEvent::executeAdvance(Player* player, skills_t skill, uint32_t oldL } void CreatureEvent::executeOnKill(Creature* creature, Creature* target, bool lastHit) const { - //onKill(creature, target, lastHit) + // onKill(creature, target, lastHit) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeOnKill - Creature {} target {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), target->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), target->getName(), getName()); return; } @@ -353,12 +351,12 @@ void CreatureEvent::executeOnKill(Creature* creature, Creature* target, bool las } void CreatureEvent::executeModalWindow(Player* player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const { - //onModalWindow(player, modalWindowId, buttonId, choiceId) + // onModalWindow(player, modalWindowId, buttonId, choiceId) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeModalWindow - " - "Player {} modaw window id {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), modalWindowId, getName()); + "Player {} modaw window id {} event {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), modalWindowId, getName()); return; } @@ -378,12 +376,12 @@ void CreatureEvent::executeModalWindow(Player* player, uint32_t modalWindowId, u getScriptInterface()->callVoidFunction(4); } -bool CreatureEvent::executeTextEdit(Player* player, Item* item, const std::string& text) const { - //onTextEdit(player, item, text) +bool CreatureEvent::executeTextEdit(Player* player, Item* item, const std::string &text) const { + // onTextEdit(player, item, text) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeTextEdit - Player {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getName()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getName()); return false; } @@ -402,13 +400,13 @@ bool CreatureEvent::executeTextEdit(Player* player, Item* item, const std::strin return getScriptInterface()->callFunction(3); } -void CreatureEvent::executeHealthChange(Creature* creature, Creature* attacker, CombatDamage& damage) const { - //onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) +void CreatureEvent::executeHealthChange(Creature* creature, Creature* attacker, CombatDamage &damage) const { + // onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeHealthChange - " - "Creature {} attacker {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), attacker->getName(), getName()); + "Creature {} attacker {} event {}] " + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), attacker->getName(), getName()); return; } @@ -447,13 +445,13 @@ void CreatureEvent::executeHealthChange(Creature* creature, Creature* attacker, getScriptInterface()->resetScriptEnv(); } -void CreatureEvent::executeManaChange(Creature* creature, Creature* attacker, CombatDamage& damage) const { - //onManaChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) +void CreatureEvent::executeManaChange(Creature* creature, Creature* attacker, CombatDamage &damage) const { + // onManaChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeManaChange - " - "Creature {} attacker {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), attacker->getName(), getName()); + "Creature {} attacker {} event {}] " + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), attacker->getName(), getName()); return; } @@ -487,13 +485,13 @@ void CreatureEvent::executeManaChange(Creature* creature, Creature* attacker, Co getScriptInterface()->resetScriptEnv(); } -void CreatureEvent::executeExtendedOpcode(Player* player, uint8_t opcode, const std::string& buffer) const { - //onExtendedOpcode(player, opcode, buffer) +void CreatureEvent::executeExtendedOpcode(Player* player, uint8_t opcode, const std::string &buffer) const { + // onExtendedOpcode(player, opcode, buffer) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[CreatureEvent::executeExtendedOpcode - " - "Player {} event {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getName()); + "Player {} event {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getName()); return; } diff --git a/src/lua/creature/creatureevent.h b/src/lua/creature/creatureevent.h index e08f6804ba7..467e12fb48b 100644 --- a/src/lua/creature/creatureevent.h +++ b/src/lua/creature/creatureevent.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CREATURE_CREATUREEVENT_H_ #define SRC_LUA_CREATURE_CREATUREEVENT_H_ @@ -27,10 +27,10 @@ class CreatureEvent final : public Script { void setEventType(CreatureEventType_t eventType) { type = eventType; } - const std::string& getName() const { + const std::string &getName() const { return eventName; } - void setName(const std::string& name) { + void setName(const std::string &name) { eventName = name; } bool isLoaded() const { @@ -43,7 +43,7 @@ class CreatureEvent final : public Script { void clearEvent(); void copyEvent(const CreatureEvent* creatureEvent); - //scripting + // scripting bool executeOnLogin(Player* player) const; bool executeOnLogout(Player* player) const; bool executeOnThink(Creature* creature, uint32_t interval) const; @@ -52,10 +52,10 @@ class CreatureEvent final : public Script { void executeOnKill(Creature* creature, Creature* target, bool lastHit) const; bool executeAdvance(Player* player, skills_t, uint32_t, uint32_t) const; void executeModalWindow(Player* player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const; - bool executeTextEdit(Player* player, Item* item, const std::string& text) const; - void executeHealthChange(Creature* creature, Creature* attacker, CombatDamage& damage) const; - void executeManaChange(Creature* creature, Creature* attacker, CombatDamage& damage) const; - void executeExtendedOpcode(Player* player, uint8_t opcode, const std::string& buffer) const; + bool executeTextEdit(Player* player, Item* item, const std::string &text) const; + void executeHealthChange(Creature* creature, Creature* attacker, CombatDamage &damage) const; + void executeManaChange(Creature* creature, Creature* attacker, CombatDamage &damage) const; + void executeExtendedOpcode(Player* player, uint8_t opcode, const std::string &buffer) const; // private: @@ -71,10 +71,10 @@ class CreatureEvents final : public Scripts { CreatureEvents() = default; // non-copyable - CreatureEvents(const CreatureEvents&) = delete; - CreatureEvents& operator=(const CreatureEvents&) = delete; + CreatureEvents(const CreatureEvents &) = delete; + CreatureEvents &operator=(const CreatureEvents &) = delete; - static CreatureEvents& getInstance() { + static CreatureEvents &getInstance() { // Guaranteed to be destroyed static CreatureEvents instance; // Instantiated on first use @@ -86,18 +86,18 @@ class CreatureEvents final : public Scripts { bool playerLogout(Player* player) const; bool playerAdvance(Player* player, skills_t, uint32_t, uint32_t) const; - CreatureEvent* getEventByName(const std::string& name, bool forceLoaded = true); + CreatureEvent* getEventByName(const std::string &name, bool forceLoaded = true); bool registerLuaEvent(CreatureEvent* event); void removeInvalidEvents(); void clear(); private: - //creature events + // creature events using CreatureEventMap = std::map; CreatureEventMap creatureEvents; }; constexpr auto g_creatureEvents = &CreatureEvents::getInstance; -#endif // SRC_LUA_CREATURE_CREATUREEVENT_H_ +#endif // SRC_LUA_CREATURE_CREATUREEVENT_H_ diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index 8e8ecc1ecd2..72d43d93ce4 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -36,11 +36,11 @@ bool Events::loadFromXml() { continue; } - const std::string& className = eventNode.attribute("class").as_string(); + const std::string &className = eventNode.attribute("class").as_string(); auto res = classes.insert(className); if (res.second) { - const std::string& lowercase = asLowerCaseString(className); - const std::string& scriptName = lowercase + ".lua"; + const std::string &lowercase = asLowerCaseString(className); + const std::string &scriptName = lowercase + ".lua"; auto coreFolder = g_configManager().getString(CORE_DIRECTORY); if (scriptInterface.loadFile(coreFolder + "/events/scripts/" + scriptName, scriptName) != 0) { SPDLOG_WARN("{} - Can not load script: {}.lua", __FUNCTION__, lowercase); @@ -48,7 +48,7 @@ bool Events::loadFromXml() { } } - const std::string& methodName = eventNode.attribute("method").as_string(); + const std::string &methodName = eventNode.attribute("method").as_string(); const int32_t event = scriptInterface.getMetaEvent(className, methodName); if (className == "Creature") { if (methodName == "onChangeOutfit") { @@ -119,7 +119,7 @@ bool Events::loadFromXml() { info.playerOnStorageUpdate = event; } else if (methodName == "onRemoveCount") { info.playerOnRemoveCount = event; - }else if (methodName == "onCombat") { + } else if (methodName == "onCombat") { info.playerOnCombat = event; } else { SPDLOG_WARN("{} - Unknown player method: {}", __FUNCTION__, methodName); @@ -146,7 +146,7 @@ bool Events::loadFromXml() { } // Monster -void Events::eventMonsterOnSpawn(Monster* monster, const Position& position) { +void Events::eventMonsterOnSpawn(Monster* monster, const Position &position) { // Monster:onSpawn(position) or Monster.onSpawn(self, position) if (info.monsterOnSpawn == -1) { return; @@ -154,9 +154,9 @@ void Events::eventMonsterOnSpawn(Monster* monster, const Position& position) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("{} - " - "Position {}" - ". Call stack overflow. Too many lua script calls being nested.", - __FUNCTION__, position.toString()); + "Position {}" + ". Call stack overflow. Too many lua script calls being nested.", + __FUNCTION__, position.toString()); return; } @@ -180,7 +180,7 @@ void Events::eventMonsterOnSpawn(Monster* monster, const Position& position) { } // Npc -void Events::eventNpcOnSpawn(Npc* npc, const Position& position) { +void Events::eventNpcOnSpawn(Npc* npc, const Position &position) { // Npc:onSpawn(position) or Npc.onSpawn(self, position) if (info.npcOnSpawn == -1) { return; @@ -188,9 +188,9 @@ void Events::eventNpcOnSpawn(Npc* npc, const Position& position) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("{} - " - "Position {}" - ". Call stack overflow. Too many lua script calls being nested.", - __FUNCTION__, position.toString()); + "Position {}" + ". Call stack overflow. Too many lua script calls being nested.", + __FUNCTION__, position.toString()); return; } @@ -214,7 +214,7 @@ void Events::eventNpcOnSpawn(Npc* npc, const Position& position) { } // Creature -bool Events::eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t& outfit) { +bool Events::eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t &outfit) { // Creature:onChangeOutfit(outfit) or Creature.onChangeOutfit(self, outfit) if (info.creatureOnChangeOutfit == -1) { return true; @@ -222,8 +222,8 @@ bool Events::eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t& out if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventCreatureOnChangeOutfit - Creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName()); + "Call stack overflow. Too many lua script calls being nested.", + creature->getName()); return false; } @@ -249,10 +249,9 @@ ReturnValue Events::eventCreatureOnAreaCombat(Creature* creature, Tile* tile, bo if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventCreatureOnAreaCombat - " - "Creature {} on tile position {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), - tile->getPosition().toString()); + "Creature {} on tile position {}] " + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), tile->getPosition().toString()); return RETURNVALUE_NOTPOSSIBLE; } @@ -295,9 +294,9 @@ ReturnValue Events::eventCreatureOnTargetCombat(Creature* creature, Creature* ta if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventCreatureOnTargetCombat - " - "Creature {} target {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), target->getName()); + "Creature {} target {}] " + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), target->getName()); return RETURNVALUE_NOTPOSSIBLE; } @@ -330,7 +329,7 @@ ReturnValue Events::eventCreatureOnTargetCombat(Creature* creature, Creature* ta return returnValue; } -void Events::eventCreatureOnHear(Creature* creature, Creature* speaker, const std::string& words, SpeakClasses type) { +void Events::eventCreatureOnHear(Creature* creature, Creature* speaker, const std::string &words, SpeakClasses type) { // Creature:onHear(speaker, words, type) if (info.creatureOnHear == -1) { return; @@ -338,9 +337,9 @@ void Events::eventCreatureOnHear(Creature* creature, Creature* speaker, const st if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventCreatureOnHear - " - "Creature {} speaker {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), speaker->getName()); + "Creature {} speaker {}] " + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), speaker->getName()); return; } @@ -362,16 +361,16 @@ void Events::eventCreatureOnHear(Creature* creature, Creature* speaker, const st scriptInterface.callVoidFunction(4); } -void Events::eventCreatureOnDrainHealth(Creature* creature, Creature* attacker, CombatType_t& typePrimary, int32_t& damagePrimary, CombatType_t& typeSecondary, int32_t& damageSecondary, TextColor_t& colorPrimary, TextColor_t& colorSecondary) { +void Events::eventCreatureOnDrainHealth(Creature* creature, Creature* attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) { if (info.creatureOnDrainHealth == -1) { return; } if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventCreatureOnDrainHealth - " - "Creature {} attacker {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature->getName(), attacker->getName()); + "Creature {} attacker {}] " + "Call stack overflow. Too many lua script calls being nested.", + creature->getName(), attacker->getName()); return; } @@ -426,9 +425,9 @@ bool Events::eventPartyOnJoin(Party* party, Player* player) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPartyOnJoin - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return false; } @@ -455,9 +454,9 @@ bool Events::eventPartyOnLeave(Party* party, Player* player) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPartyOnLeave - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return false; } @@ -484,8 +483,8 @@ bool Events::eventPartyOnDisband(Party* party) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPartyOnDisband - Party leader {}] Call stack " - "overflow. Too many lua script calls being nested.", - party->getLeader()->getName()); + "overflow. Too many lua script calls being nested.", + party->getLeader()->getName()); return false; } @@ -501,15 +500,14 @@ bool Events::eventPartyOnDisband(Party* party) { return scriptInterface.callFunction(1); } -void Events::eventPartyOnShareExperience(Party* party, uint64_t& exp) { +void Events::eventPartyOnShareExperience(Party* party, uint64_t &exp) { // Party:onShareExperience(exp) or Party.onShareExperience(self, exp) if (info.partyOnShareExperience == -1) { return; } if (!scriptInterface.reserveScriptEnv()) { - SPDLOG_ERROR("Party leader {}. Call stack overflow. Too many lua script calls being nested.", - party->getLeader()->getName()); + SPDLOG_ERROR("Party leader {}. Call stack overflow. Too many lua script calls being nested.", party->getLeader()->getName()); return; } @@ -535,7 +533,7 @@ void Events::eventPartyOnShareExperience(Party* party, uint64_t& exp) { } // Player -bool Events::eventPlayerOnBrowseField(Player* player, const Position& position) { +bool Events::eventPlayerOnBrowseField(Player* player, const Position &position) { // Player:onBrowseField(position) or Player.onBrowseField(self, position) if (info.playerOnBrowseField == -1) { return true; @@ -543,9 +541,9 @@ bool Events::eventPlayerOnBrowseField(Player* player, const Position& position) if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnBrowseField - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return false; } @@ -563,7 +561,7 @@ bool Events::eventPlayerOnBrowseField(Player* player, const Position& position) return scriptInterface.callFunction(2); } -void Events::eventPlayerOnLook(Player* player, const Position& position, Thing* thing, uint8_t stackpos, int32_t lookDistance) { +void Events::eventPlayerOnLook(Player* player, const Position &position, Thing* thing, uint8_t stackpos, int32_t lookDistance) { // Player:onLook(thing, position, distance) or Player.onLook(self, thing, position, distance) if (info.playerOnLook == -1) { return; @@ -571,9 +569,9 @@ void Events::eventPlayerOnLook(Player* player, const Position& position, Thing* if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnLook - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } @@ -610,9 +608,9 @@ void Events::eventPlayerOnLookInBattleList(Player* player, Creature* creature, i if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnLookInBattleList - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } @@ -641,9 +639,9 @@ void Events::eventPlayerOnLookInTrade(Player* player, Player* partner, Item* ite if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnLookInTrade - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } @@ -675,9 +673,9 @@ bool Events::eventPlayerOnLookInShop(Player* player, const ItemType* itemType, u if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnLookInShop - " - "Player {} itemType {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), itemType->getPluralName()); + "Player {} itemType {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), itemType->getPluralName()); return false; } @@ -706,9 +704,9 @@ bool Events::eventPlayerOnRemoveCount(Player* player, Item* item) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnMove - " - "Player {} item {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), item->getName()); + "Player {} item {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), item->getName()); return false; } @@ -727,7 +725,7 @@ bool Events::eventPlayerOnRemoveCount(Player* player, Item* item) { return scriptInterface.callFunction(2); } -bool Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, const Position& fromPosition, const Position& toPosition, Cylinder* fromCylinder, Cylinder* toCylinder) { +bool Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, const Position &fromPosition, const Position &toPosition, Cylinder* fromCylinder, Cylinder* toCylinder) { // Player:onMoveItem(item, count, fromPosition, toPosition) or Player.onMoveItem(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnMoveItem == -1) { return true; @@ -735,9 +733,9 @@ bool Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, c if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnMoveItem - " - "Player {} item {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), item->getName()); + "Player {} item {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), item->getName()); return false; } @@ -763,7 +761,7 @@ bool Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, c return scriptInterface.callFunction(7); } -void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, const Position& fromPosition, const Position& toPosition, Cylinder* fromCylinder, Cylinder* toCylinder) { +void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, const Position &fromPosition, const Position &toPosition, Cylinder* fromCylinder, Cylinder* toCylinder) { // Player:onItemMoved(item, count, fromPosition, toPosition) or Player.onItemMoved(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnItemMoved == -1) { return; @@ -771,9 +769,9 @@ void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnItemMoved - " - "Player {} item {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), item->getName()); + "Player {} item {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), item->getName()); return; } @@ -799,8 +797,7 @@ void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, scriptInterface.callVoidFunction(7); } -void Events::eventPlayerOnChangeZone(Player* player, ZoneType_t zone) -{ +void Events::eventPlayerOnChangeZone(Player* player, ZoneType_t zone) { // Player:onChangeZone(zone) if (info.playerOnChangeZone == -1) { return; @@ -808,16 +805,16 @@ void Events::eventPlayerOnChangeZone(Player* player, ZoneType_t zone) if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnChangeZone - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } - ScriptEnvironment * env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = scriptInterface.getScriptEnv(); env->setScriptId(info.playerOnChangeZone, &scriptInterface); - lua_State * L = scriptInterface.getLuaState(); + lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnChangeZone); LuaScriptInterface::pushUserdata(L, player); @@ -827,7 +824,7 @@ void Events::eventPlayerOnChangeZone(Player* player, ZoneType_t zone) scriptInterface.callVoidFunction(2); } -bool Events::eventPlayerOnMoveCreature(Player* player, Creature* creature, const Position& fromPosition, const Position& toPosition) { +bool Events::eventPlayerOnMoveCreature(Player* player, Creature* creature, const Position &fromPosition, const Position &toPosition) { // Player:onMoveCreature(creature, fromPosition, toPosition) or Player.onMoveCreature(self, creature, fromPosition, toPosition) if (info.playerOnMoveCreature == -1) { return true; @@ -835,9 +832,9 @@ bool Events::eventPlayerOnMoveCreature(Player* player, Creature* creature, const if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnMoveCreature - " - "Player {} creature {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), creature->getName()); + "Player {} creature {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), creature->getName()); return false; } @@ -859,7 +856,7 @@ bool Events::eventPlayerOnMoveCreature(Player* player, Creature* creature, const return scriptInterface.callFunction(4); } -void Events::eventPlayerOnReportRuleViolation(Player* player, const std::string& targetName, uint8_t reportType, uint8_t reportReason, const std::string& comment, const std::string& translation) { +void Events::eventPlayerOnReportRuleViolation(Player* player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) { // Player:onReportRuleViolation(targetName, reportType, reportReason, comment, translation) if (info.playerOnReportRuleViolation == -1) { return; @@ -867,9 +864,9 @@ void Events::eventPlayerOnReportRuleViolation(Player* player, const std::string& if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnReportRuleViolation - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } @@ -893,7 +890,7 @@ void Events::eventPlayerOnReportRuleViolation(Player* player, const std::string& scriptInterface.callVoidFunction(6); } -bool Events::eventPlayerOnReportBug(Player* player, const std::string& message, const Position& position, uint8_t category) { +bool Events::eventPlayerOnReportBug(Player* player, const std::string &message, const Position &position, uint8_t category) { // Player:onReportBug(message, position, category) if (info.playerOnReportBug == -1) { return true; @@ -901,9 +898,9 @@ bool Events::eventPlayerOnReportBug(Player* player, const std::string& message, if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnReportBug - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return false; } @@ -931,9 +928,9 @@ bool Events::eventPlayerOnTurn(Player* player, Direction direction) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnTurn - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return false; } @@ -959,9 +956,9 @@ bool Events::eventPlayerOnTradeRequest(Player* player, Player* target, Item* ite if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnTradeRequest - " - "Player {} target {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), target->getName()); + "Player {} target {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), target->getName()); return false; } @@ -991,9 +988,9 @@ bool Events::eventPlayerOnTradeAccept(Player* player, Player* target, Item* item if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnTradeAccept - " - "Player {} target {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), target->getName()); + "Player {} target {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), target->getName()); return false; } @@ -1018,7 +1015,7 @@ bool Events::eventPlayerOnTradeAccept(Player* player, Player* target, Item* item return scriptInterface.callFunction(4); } -void Events::eventPlayerOnGainExperience(Player* player, Creature* target, uint64_t& exp, uint64_t rawExp) { +void Events::eventPlayerOnGainExperience(Player* player, Creature* target, uint64_t &exp, uint64_t rawExp) { // Player:onGainExperience(target, exp, rawExp) // rawExp gives the original exp which is not multiplied if (info.playerOnGainExperience == -1) { @@ -1027,9 +1024,9 @@ void Events::eventPlayerOnGainExperience(Player* player, Creature* target, uint6 if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnGainExperience - " - "Player {} target {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), target->getName()); + "Player {} target {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), target->getName()); return; } @@ -1062,7 +1059,7 @@ void Events::eventPlayerOnGainExperience(Player* player, Creature* target, uint6 scriptInterface.resetScriptEnv(); } -void Events::eventPlayerOnLoseExperience(Player* player, uint64_t& exp) { +void Events::eventPlayerOnLoseExperience(Player* player, uint64_t &exp) { // Player:onLoseExperience(exp) if (info.playerOnLoseExperience == -1) { return; @@ -1070,9 +1067,9 @@ void Events::eventPlayerOnLoseExperience(Player* player, uint64_t& exp) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnLoseExperience - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } @@ -1097,7 +1094,7 @@ void Events::eventPlayerOnLoseExperience(Player* player, uint64_t& exp) { scriptInterface.resetScriptEnv(); } -void Events::eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_t& tries) { +void Events::eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_t &tries) { // Player:onGainSkillTries(skill, tries) if (info.playerOnGainSkillTries == -1) { return; @@ -1105,9 +1102,9 @@ void Events::eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_ if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnGainSkillTries - " - "Player {} skill {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), skill); + "Player {} skill {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), skill); return; } @@ -1133,7 +1130,7 @@ void Events::eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_ scriptInterface.resetScriptEnv(); } -void Events::eventPlayerOnCombat(Player* player, Creature* target, Item* item, CombatDamage& damage) { +void Events::eventPlayerOnCombat(Player* player, Creature* target, Item* item, CombatDamage &damage) { // Player:onCombat(target, item, primaryDamage, primaryType, secondaryDamage, secondaryType) if (info.playerOnCombat == -1) { return; @@ -1141,9 +1138,9 @@ void Events::eventPlayerOnCombat(Player* player, Creature* target, Item* item, C if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnCombat - " - "Player {} target {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), target->getName()); + "Player {} target {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), target->getName()); return; } @@ -1163,10 +1160,10 @@ void Events::eventPlayerOnCombat(Player* player, Creature* target, Item* item, C lua_pushnil(L); } - if(item){ + if (item) { LuaScriptInterface::pushUserdata(L, item); LuaScriptInterface::setMetatable(L, -1, "Item"); - }else{ + } else { lua_pushnil(L); } @@ -1195,7 +1192,6 @@ void Events::eventPlayerOnCombat(Player* player, Creature* target, Item* item, C damage.secondary.value = 0; } } - } scriptInterface.resetScriptEnv(); @@ -1209,9 +1205,9 @@ void Events::eventPlayerOnRequestQuestLog(Player* player) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnRequestQuestLog - " - "Player {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName()); + "Player {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName()); return; } @@ -1235,9 +1231,9 @@ void Events::eventPlayerOnRequestQuestLine(Player* player, uint16_t questId) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventPlayerOnRequestQuestLine - " - "Player {} questId {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), questId); + "Player {} questId {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), questId); return; } @@ -1263,9 +1259,9 @@ void Events::eventOnStorageUpdate(Player* player, const uint32_t key, const int3 if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventOnStorageUpdate - " - "Player {} key {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), key); + "Player {} key {}] " + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), key); return; } @@ -1295,9 +1291,9 @@ void Events::eventMonsterOnDropLoot(Monster* monster, Container* corpse) { if (!scriptInterface.reserveScriptEnv()) { SPDLOG_ERROR("[Events::eventMonsterOnDropLoot - " - "Monster corpse {}] " - "Call stack overflow. Too many lua script calls being nested.", - corpse->getName()); + "Monster corpse {}] " + "Call stack overflow. Too many lua script calls being nested.", + corpse->getName()); return; } diff --git a/src/lua/creature/events.h b/src/lua/creature/events.h index e9bc0eab798..928a5072890 100644 --- a/src/lua/creature/events.h +++ b/src/lua/creature/events.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CREATURE_EVENTS_H_ #define SRC_LUA_CREATURE_EVENTS_H_ @@ -20,63 +20,62 @@ class Tile; class Imbuements; class Events { - struct EventsInfo { - // Creature - int32_t creatureOnChangeOutfit = -1; - int32_t creatureOnAreaCombat = -1; - int32_t creatureOnTargetCombat = -1; - int32_t creatureOnHear = -1; - int32_t creatureOnDrainHealth = -1; - - // Party - int32_t partyOnJoin = -1; - int32_t partyOnLeave = -1; - int32_t partyOnDisband = -1; - int32_t partyOnShareExperience = -1; - - // Player - int32_t playerOnBrowseField = -1; - int32_t playerOnLook = -1; - int32_t playerOnLookInBattleList = -1; - int32_t playerOnLookInTrade = -1; - int32_t playerOnLookInShop = -1; - int32_t playerOnMoveItem = -1; - int32_t playerOnItemMoved = -1; - int32_t playerOnChangeZone = -1; - int32_t playerOnMoveCreature = -1; - int32_t playerOnReportRuleViolation = -1; - int32_t playerOnReportBug = -1; - int32_t playerOnTurn = -1; - int32_t playerOnTradeRequest = -1; - int32_t playerOnTradeAccept = -1; - int32_t playerOnGainExperience = -1; - int32_t playerOnLoseExperience = -1; - int32_t playerOnGainSkillTries = -1; - int32_t playerOnRequestQuestLog = -1; - int32_t playerOnRequestQuestLine = -1; - int32_t playerOnStorageUpdate = -1; - int32_t playerOnRemoveCount = -1; - int32_t playerOnCombat = -1; - - // Monster - int32_t monsterOnDropLoot = -1; - int32_t monsterOnSpawn = -1; - - // Npc - int32_t npcOnSpawn = -1; - }; + struct EventsInfo { + // Creature + int32_t creatureOnChangeOutfit = -1; + int32_t creatureOnAreaCombat = -1; + int32_t creatureOnTargetCombat = -1; + int32_t creatureOnHear = -1; + int32_t creatureOnDrainHealth = -1; + + // Party + int32_t partyOnJoin = -1; + int32_t partyOnLeave = -1; + int32_t partyOnDisband = -1; + int32_t partyOnShareExperience = -1; + + // Player + int32_t playerOnBrowseField = -1; + int32_t playerOnLook = -1; + int32_t playerOnLookInBattleList = -1; + int32_t playerOnLookInTrade = -1; + int32_t playerOnLookInShop = -1; + int32_t playerOnMoveItem = -1; + int32_t playerOnItemMoved = -1; + int32_t playerOnChangeZone = -1; + int32_t playerOnMoveCreature = -1; + int32_t playerOnReportRuleViolation = -1; + int32_t playerOnReportBug = -1; + int32_t playerOnTurn = -1; + int32_t playerOnTradeRequest = -1; + int32_t playerOnTradeAccept = -1; + int32_t playerOnGainExperience = -1; + int32_t playerOnLoseExperience = -1; + int32_t playerOnGainSkillTries = -1; + int32_t playerOnRequestQuestLog = -1; + int32_t playerOnRequestQuestLine = -1; + int32_t playerOnStorageUpdate = -1; + int32_t playerOnRemoveCount = -1; + int32_t playerOnCombat = -1; + + // Monster + int32_t monsterOnDropLoot = -1; + int32_t monsterOnSpawn = -1; + + // Npc + int32_t npcOnSpawn = -1; + }; public: - Events(); bool loadFromXml(); // non-copyable - Events(Events const&) = delete; - void operator=(Events const&) = delete; + Events(const Events &) = delete; + void operator=(const Events &) = delete; - static Events& getInstance() { + static Events &getInstance() { // Guaranteed to be destroyed static Events instance; // Instantiated on first use @@ -84,48 +83,48 @@ class Events { } // Creature - bool eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t& outfit); + bool eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t &outfit); ReturnValue eventCreatureOnAreaCombat(Creature* creature, Tile* tile, bool aggressive); ReturnValue eventCreatureOnTargetCombat(Creature* creature, Creature* target); - void eventCreatureOnHear(Creature* creature, Creature* speaker, const std::string& words, SpeakClasses type); - void eventCreatureOnDrainHealth(Creature* creature, Creature* attacker, CombatType_t& typePrimary, int32_t& damagePrimary, CombatType_t& typeSecondary, int32_t& damageSecondary, TextColor_t& colorPrimary, TextColor_t& colorSecondary); + void eventCreatureOnHear(Creature* creature, Creature* speaker, const std::string &words, SpeakClasses type); + void eventCreatureOnDrainHealth(Creature* creature, Creature* attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary); // Party bool eventPartyOnJoin(Party* party, Player* player); bool eventPartyOnLeave(Party* party, Player* player); bool eventPartyOnDisband(Party* party); - void eventPartyOnShareExperience(Party* party, uint64_t& exp); + void eventPartyOnShareExperience(Party* party, uint64_t &exp); // Player - bool eventPlayerOnBrowseField(Player* player, const Position& position); - void eventPlayerOnLook(Player* player, const Position& position, Thing* thing, uint8_t stackpos, int32_t lookDistance); + bool eventPlayerOnBrowseField(Player* player, const Position &position); + void eventPlayerOnLook(Player* player, const Position &position, Thing* thing, uint8_t stackpos, int32_t lookDistance); void eventPlayerOnLookInBattleList(Player* player, Creature* creature, int32_t lookDistance); void eventPlayerOnLookInTrade(Player* player, Player* partner, Item* item, int32_t lookDistance); bool eventPlayerOnLookInShop(Player* player, const ItemType* itemType, uint8_t count); - bool eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, const Position& fromPosition, const Position& toPosition, Cylinder* fromCylinder, Cylinder* toCylinder); - void eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, const Position& fromPosition, const Position& toPosition, Cylinder* fromCylinder, Cylinder* toCylinder); + bool eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, const Position &fromPosition, const Position &toPosition, Cylinder* fromCylinder, Cylinder* toCylinder); + void eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, const Position &fromPosition, const Position &toPosition, Cylinder* fromCylinder, Cylinder* toCylinder); void eventPlayerOnChangeZone(Player* player, ZoneType_t zone); - bool eventPlayerOnMoveCreature(Player* player, Creature* creature, const Position& fromPosition, const Position& toPosition); - void eventPlayerOnReportRuleViolation(Player* player, const std::string& targetName, uint8_t reportType, uint8_t reportReason, const std::string& comment, const std::string& translation); - bool eventPlayerOnReportBug(Player* player, const std::string& message, const Position& position, uint8_t category); + bool eventPlayerOnMoveCreature(Player* player, Creature* creature, const Position &fromPosition, const Position &toPosition); + void eventPlayerOnReportRuleViolation(Player* player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation); + bool eventPlayerOnReportBug(Player* player, const std::string &message, const Position &position, uint8_t category); bool eventPlayerOnTurn(Player* player, Direction direction); bool eventPlayerOnTradeRequest(Player* player, Player* target, Item* item); bool eventPlayerOnTradeAccept(Player* player, Player* target, Item* item, Item* targetItem); - void eventPlayerOnGainExperience(Player* player, Creature* target, uint64_t& exp, uint64_t rawExp); - void eventPlayerOnLoseExperience(Player* player, uint64_t& exp); - void eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_t& tries); - bool eventPlayerOnRemoveCount(Player* player, Item * item); + void eventPlayerOnGainExperience(Player* player, Creature* target, uint64_t &exp, uint64_t rawExp); + void eventPlayerOnLoseExperience(Player* player, uint64_t &exp); + void eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_t &tries); + bool eventPlayerOnRemoveCount(Player* player, Item* item); void eventPlayerOnRequestQuestLog(Player* player); void eventPlayerOnRequestQuestLine(Player* player, uint16_t questId); void eventOnStorageUpdate(Player* player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime); - void eventPlayerOnCombat(Player* player, Creature* target, Item* item, CombatDamage& damage); + void eventPlayerOnCombat(Player* player, Creature* target, Item* item, CombatDamage &damage); // Monster void eventMonsterOnDropLoot(Monster* monster, Container* corpse); - void eventMonsterOnSpawn(Monster* monster, const Position& position); + void eventMonsterOnSpawn(Monster* monster, const Position &position); // Monster - void eventNpcOnSpawn(Npc* npc, const Position& position); + void eventNpcOnSpawn(Npc* npc, const Position &position); private: LuaScriptInterface scriptInterface; @@ -134,4 +133,4 @@ class Events { constexpr auto g_events = &Events::getInstance; -#endif // SRC_LUA_CREATURE_EVENTS_H_ +#endif // SRC_LUA_CREATURE_EVENTS_H_ diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index 84494b85be6..fb0f2e9d338 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -20,7 +20,7 @@ void MoveEvents::clear() { positionsMap.clear(); } -bool MoveEvents::registerLuaItemEvent(MoveEvent& moveEvent) { +bool MoveEvents::registerLuaItemEvent(MoveEvent &moveEvent) { auto itemIdVector = moveEvent.getItemIdsVector(); if (itemIdVector.empty()) { return false; @@ -29,9 +29,9 @@ bool MoveEvents::registerLuaItemEvent(MoveEvent& moveEvent) { std::vector tmpVector; tmpVector.reserve(itemIdVector.size()); - for (const auto& itemId : itemIdVector) { + for (const auto &itemId : itemIdVector) { if (moveEvent.getEventType() == MOVE_EVENT_EQUIP) { - ItemType& it = Item::items.getItemType(itemId); + ItemType &it = Item::items.getItemType(itemId); it.wieldInfo = moveEvent.getWieldInfo(); it.minReqLevel = moveEvent.getReqLevel(); it.minReqMagicLevel = moveEvent.getReqMagLv(); @@ -46,7 +46,7 @@ bool MoveEvents::registerLuaItemEvent(MoveEvent& moveEvent) { return !itemIdVector.empty(); } -bool MoveEvents::registerLuaActionEvent(MoveEvent& moveEvent) { +bool MoveEvents::registerLuaActionEvent(MoveEvent &moveEvent) { auto actionIdVector = moveEvent.getActionIdsVector(); if (actionIdVector.empty()) { return false; @@ -55,7 +55,7 @@ bool MoveEvents::registerLuaActionEvent(MoveEvent& moveEvent) { std::vector tmpVector; tmpVector.reserve(actionIdVector.size()); - for (const auto& actionId : actionIdVector) { + for (const auto &actionId : actionIdVector) { if (registerEvent(moveEvent, actionId, actionIdMap)) { tmpVector.emplace_back(actionId); } @@ -65,7 +65,7 @@ bool MoveEvents::registerLuaActionEvent(MoveEvent& moveEvent) { return !actionIdVector.empty(); } -bool MoveEvents::registerLuaUniqueEvent(MoveEvent& moveEvent) { +bool MoveEvents::registerLuaUniqueEvent(MoveEvent &moveEvent) { auto uniqueIdVector = moveEvent.getUniqueIdsVector(); if (uniqueIdVector.empty()) { return false; @@ -74,7 +74,7 @@ bool MoveEvents::registerLuaUniqueEvent(MoveEvent& moveEvent) { std::vector tmpVector; tmpVector.reserve(uniqueIdVector.size()); - for (const auto& uniqueId : uniqueIdVector) { + for (const auto &uniqueId : uniqueIdVector) { if (registerEvent(moveEvent, uniqueId, uniqueIdMap)) { tmpVector.emplace_back(uniqueId); } @@ -84,7 +84,7 @@ bool MoveEvents::registerLuaUniqueEvent(MoveEvent& moveEvent) { return !uniqueIdVector.empty(); } -bool MoveEvents::registerLuaPositionEvent(MoveEvent& moveEvent) { +bool MoveEvents::registerLuaPositionEvent(MoveEvent &moveEvent) { auto positionVector = moveEvent.getPositionsVector(); if (positionVector.empty()) { return false; @@ -93,7 +93,7 @@ bool MoveEvents::registerLuaPositionEvent(MoveEvent& moveEvent) { std::vector tmpVector; tmpVector.reserve(positionVector.size()); - for (const auto& position : positionVector) { + for (const auto &position : positionVector) { if (registerEvent(moveEvent, position, positionsMap)) { tmpVector.emplace_back(position); } @@ -103,13 +103,12 @@ bool MoveEvents::registerLuaPositionEvent(MoveEvent& moveEvent) { return !positionVector.empty(); } -bool MoveEvents::registerLuaEvent(MoveEvent& moveEvent) { +bool MoveEvents::registerLuaEvent(MoveEvent &moveEvent) { // Check if event is correct if (registerLuaItemEvent(moveEvent) - || registerLuaUniqueEvent(moveEvent) - || registerLuaActionEvent(moveEvent) - || registerLuaPositionEvent(moveEvent)) - { + || registerLuaUniqueEvent(moveEvent) + || registerLuaActionEvent(moveEvent) + || registerLuaPositionEvent(moveEvent)) { return true; } else { SPDLOG_WARN( @@ -127,7 +126,7 @@ bool MoveEvents::registerLuaEvent(MoveEvent& moveEvent) { return false; } -bool MoveEvents::registerEvent(MoveEvent& moveEvent, int32_t id, std::map& moveListMap) const { +bool MoveEvents::registerEvent(MoveEvent &moveEvent, int32_t id, std::map &moveListMap) const { auto it = moveListMap.find(id); if (it == moveListMap.end()) { MoveEventList moveEventList; @@ -135,8 +134,8 @@ bool MoveEvents::registerEvent(MoveEvent& moveEvent, int32_t id, std::map& moveEventList = it->second.moveEvent[moveEvent.getEventType()]; - for (MoveEvent& existingMoveEvent : moveEventList) { + std::list &moveEventList = it->second.moveEvent[moveEvent.getEventType()]; + for (MoveEvent &existingMoveEvent : moveEventList) { if (existingMoveEvent.getSlot() == moveEvent.getSlot()) { SPDLOG_WARN( "[{}] duplicate move event found: {}, for script: {}", @@ -152,27 +151,49 @@ bool MoveEvents::registerEvent(MoveEvent& moveEvent, int32_t id, std::map::iterator it = actionIdMap.find(item.getAttribute(ItemAttribute_t::ACTIONID)); if (it != actionIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; - for (MoveEvent& moveEvent : moveEventList) { + std::list &moveEventList = it->second.moveEvent[eventType]; + for (MoveEvent &moveEvent : moveEventList) { if ((moveEvent.getSlot() & slotp) != 0) { return &moveEvent; } @@ -182,8 +203,8 @@ MoveEvent* MoveEvents::getEvent(Item& item, MoveEvent_t eventType, Slots_t slot) auto it = itemIdMap.find(item.getID()); if (it != itemIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; - for (MoveEvent& moveEvent : moveEventList) { + std::list &moveEventList = it->second.moveEvent[eventType]; + for (MoveEvent &moveEvent : moveEventList) { if ((moveEvent.getSlot() & slotp) != 0) { return &moveEvent; } @@ -192,12 +213,12 @@ MoveEvent* MoveEvents::getEvent(Item& item, MoveEvent_t eventType, Slots_t slot) return nullptr; } -MoveEvent* MoveEvents::getEvent(Item& item, MoveEvent_t eventType) { +MoveEvent* MoveEvents::getEvent(Item &item, MoveEvent_t eventType) { std::map::iterator it; if (item.hasAttribute(ItemAttribute_t::UNIQUEID)) { it = uniqueIdMap.find(item.getAttribute(ItemAttribute_t::UNIQUEID)); if (it != uniqueIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; + std::list &moveEventList = it->second.moveEvent[eventType]; if (!moveEventList.empty()) { return &(*moveEventList.begin()); } @@ -207,7 +228,7 @@ MoveEvent* MoveEvents::getEvent(Item& item, MoveEvent_t eventType) { if (item.hasAttribute(ItemAttribute_t::ACTIONID)) { it = actionIdMap.find(item.getAttribute(ItemAttribute_t::ACTIONID)); if (it != actionIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; + std::list &moveEventList = it->second.moveEvent[eventType]; if (!moveEventList.empty()) { return &(*moveEventList.begin()); } @@ -216,7 +237,7 @@ MoveEvent* MoveEvents::getEvent(Item& item, MoveEvent_t eventType) { it = itemIdMap.find(item.getID()); if (it != itemIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; + std::list &moveEventList = it->second.moveEvent[eventType]; if (!moveEventList.empty()) { return &(*moveEventList.begin()); } @@ -224,7 +245,7 @@ MoveEvent* MoveEvents::getEvent(Item& item, MoveEvent_t eventType) { return nullptr; } -bool MoveEvents::registerEvent(MoveEvent& moveEvent, const Position& position, std::map& moveListMap) const { +bool MoveEvents::registerEvent(MoveEvent &moveEvent, const Position &position, std::map &moveListMap) const { auto it = moveListMap.find(position); if (it == moveListMap.end()) { MoveEventList moveEventList; @@ -232,7 +253,7 @@ bool MoveEvents::registerEvent(MoveEvent& moveEvent, const Position& position, s moveListMap[position] = moveEventList; return true; } else { - std::list& moveEventList = it->second.moveEvent[moveEvent.getEventType()]; + std::list &moveEventList = it->second.moveEvent[moveEvent.getEventType()]; if (!moveEventList.empty()) { SPDLOG_WARN( "[{}] duplicate move event found: {}, for script {}", @@ -248,11 +269,10 @@ bool MoveEvents::registerEvent(MoveEvent& moveEvent, const Position& position, s } } -MoveEvent* MoveEvents::getEvent(Tile& tile, MoveEvent_t eventType) { +MoveEvent* MoveEvents::getEvent(Tile &tile, MoveEvent_t eventType) { if (auto it = positionsMap.find(tile.getPosition()); - it != positionsMap.end()) - { - std::list& moveEventList = it->second.moveEvent[eventType]; + it != positionsMap.end()) { + std::list &moveEventList = it->second.moveEvent[eventType]; if (!moveEventList.empty()) { return &(*moveEventList.begin()); } @@ -260,11 +280,12 @@ MoveEvent* MoveEvents::getEvent(Tile& tile, MoveEvent_t eventType) { return nullptr; } -uint32_t MoveEvents::onCreatureMove(Creature& creature, Tile& tile, MoveEvent_t eventType) { - const Position& pos = tile.getPosition(); +uint32_t MoveEvents::onCreatureMove(Creature &creature, Tile &tile, MoveEvent_t eventType) { + const Position &pos = tile.getPosition(); + uint32_t ret = 1; - MoveEvent *moveEvent = getEvent(tile, eventType); + MoveEvent* moveEvent = getEvent(tile, eventType); if (moveEvent) { ret &= moveEvent->fireStepEvent(creature, nullptr, pos); } @@ -293,23 +314,23 @@ uint32_t MoveEvents::onCreatureMove(Creature& creature, Tile& tile, MoveEvent_t return ret; } -uint32_t MoveEvents::onPlayerEquip(Player& player, Item& item, Slots_t slot, bool isCheck) { - MoveEvent *moveEvent = getEvent(item, MOVE_EVENT_EQUIP, slot); +uint32_t MoveEvents::onPlayerEquip(Player &player, Item &item, Slots_t slot, bool isCheck) { + MoveEvent* moveEvent = getEvent(item, MOVE_EVENT_EQUIP, slot); if (!moveEvent) { return 1; } return moveEvent->fireEquip(player, item, slot, isCheck); } -uint32_t MoveEvents::onPlayerDeEquip(Player& player, Item& item, Slots_t slot) { - MoveEvent *moveEvent = getEvent(item, MOVE_EVENT_DEEQUIP, slot); +uint32_t MoveEvents::onPlayerDeEquip(Player &player, Item &item, Slots_t slot) { + MoveEvent* moveEvent = getEvent(item, MOVE_EVENT_DEEQUIP, slot); if (!moveEvent) { return 1; } return moveEvent->fireEquip(player, item, slot, false); } -uint32_t MoveEvents::onItemMove(Item& item, Tile& tile, bool isAdd) { +uint32_t MoveEvents::onItemMove(Item &item, Tile &tile, bool isAdd) { MoveEvent_t eventType1, eventType2; if (isAdd) { eventType1 = MOVE_EVENT_ADD_ITEM; @@ -320,7 +341,7 @@ uint32_t MoveEvents::onItemMove(Item& item, Tile& tile, bool isAdd) { } uint32_t ret = 1; - MoveEvent *moveEvent = getEvent(tile, eventType1); + MoveEvent* moveEvent = getEvent(tile, eventType1); if (moveEvent) { // No tile item ret &= moveEvent->fireAddRemItem(item, tile.getPosition()); @@ -351,7 +372,6 @@ uint32_t MoveEvents::onItemMove(Item& item, Tile& tile, bool isAdd) { break; } } - } return ret; @@ -362,33 +382,34 @@ uint32_t MoveEvents::onItemMove(Item& item, Tile& tile, bool isAdd) { MoveEvent class ================ */ -MoveEvent::MoveEvent(LuaScriptInterface* interface) : Script(interface) {} +MoveEvent::MoveEvent(LuaScriptInterface* interface) : + Script(interface) { } std::string MoveEvent::getScriptTypeName() const { switch (eventType) { - case MOVE_EVENT_STEP_IN: - return "onStepIn"; - case MOVE_EVENT_STEP_OUT: - return "onStepOut"; - case MOVE_EVENT_EQUIP: - return "onEquip"; - case MOVE_EVENT_DEEQUIP: - return "onDeEquip"; - case MOVE_EVENT_ADD_ITEM: - return "onAddItem"; - case MOVE_EVENT_REMOVE_ITEM: - return "onRemoveItem"; - default: - SPDLOG_ERROR( - "[{}] invalid event type for script: {}", - __FUNCTION__, - getScriptInterface()->getLoadingScriptName() - ); - return std::string(); + case MOVE_EVENT_STEP_IN: + return "onStepIn"; + case MOVE_EVENT_STEP_OUT: + return "onStepOut"; + case MOVE_EVENT_EQUIP: + return "onEquip"; + case MOVE_EVENT_DEEQUIP: + return "onDeEquip"; + case MOVE_EVENT_ADD_ITEM: + return "onAddItem"; + case MOVE_EVENT_REMOVE_ITEM: + return "onRemoveItem"; + default: + SPDLOG_ERROR( + "[{}] invalid event type for script: {}", + __FUNCTION__, + getScriptInterface()->getLoadingScriptName() + ); + return std::string(); } } -uint32_t MoveEvent::StepInField(Creature* creature, Item* item, const Position&) { +uint32_t MoveEvent::StepInField(Creature* creature, Item* item, const Position &) { if (creature == nullptr) { SPDLOG_ERROR("[MoveEvent::StepInField] - Creature is nullptr"); return 0; @@ -408,18 +429,17 @@ uint32_t MoveEvent::StepInField(Creature* creature, Item* item, const Position&) return LUA_ERROR_ITEM_NOT_FOUND; } -uint32_t MoveEvent::StepOutField(Creature*, Item*, const Position&) { +uint32_t MoveEvent::StepOutField(Creature*, Item*, const Position &) { return 1; } -uint32_t MoveEvent::AddItemField(Item* item, Item*, const Position&) { +uint32_t MoveEvent::AddItemField(Item* item, Item*, const Position &) { if (item == nullptr) { SPDLOG_ERROR("[MoveEvent::AddItemField] - Item is nullptr"); return 0; } - if (MagicField* field = item->getMagicField()) - { + if (MagicField* field = item->getMagicField()) { Tile* tile = item->getTile(); if (tile == nullptr) { SPDLOG_DEBUG("[MoveEvent::AddItemField] - Tile is nullptr"); @@ -443,11 +463,11 @@ uint32_t MoveEvent::AddItemField(Item* item, Item*, const Position&) { return LUA_ERROR_ITEM_NOT_FOUND; } -uint32_t MoveEvent::RemoveItemField(Item*, Item*, const Position&) { +uint32_t MoveEvent::RemoveItemField(Item*, Item*, const Position &) { return 1; } -uint32_t MoveEvent::EquipItem(MoveEvent *moveEvent, Player* player, Item* item, Slots_t slot, bool isCheck) { +uint32_t MoveEvent::EquipItem(MoveEvent* moveEvent, Player* player, Item* item, Slots_t slot, bool isCheck) { if (player == nullptr) { SPDLOG_ERROR("[MoveEvent::EquipItem] - Player is nullptr"); return 0; @@ -471,7 +491,7 @@ uint32_t MoveEvent::EquipItem(MoveEvent *moveEvent, Player* player, Item* item, return 0; } - const std::map& vocEquipMap = moveEvent->getVocEquipMap(); + const std::map &vocEquipMap = moveEvent->getVocEquipMap(); if (!vocEquipMap.empty() && !vocEquipMap.contains(player->getVocationId())) { return 0; } @@ -481,7 +501,7 @@ uint32_t MoveEvent::EquipItem(MoveEvent *moveEvent, Player* player, Item* item, return 1; } - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.transformEquipTo != 0) { g_game().transformItem(item, it.transformEquipTo); } else { @@ -579,7 +599,7 @@ uint32_t MoveEvent::DeEquipItem(MoveEvent*, Player* player, Item* item, Slots_t player->setItemAbility(slot, false); - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.transformDeEquipTo != 0) { g_game().transformItem(item, it.transformDeEquipTo); } @@ -646,7 +666,7 @@ void MoveEvent::setEventType(MoveEvent_t type) { eventType = type; } -uint32_t MoveEvent::fireStepEvent(Creature& creature, Item* item, const Position& pos) const { +uint32_t MoveEvent::fireStepEvent(Creature &creature, Item* item, const Position &pos) const { if (isLoadedCallback()) { return executeStep(creature, item, pos); } else { @@ -654,17 +674,15 @@ uint32_t MoveEvent::fireStepEvent(Creature& creature, Item* item, const Position } } -bool MoveEvent::executeStep(Creature& creature, Item* item, const Position& pos) const { - //onStepIn(creature, item, pos, fromPosition) - //onStepOut(creature, item, pos, fromPosition) +bool MoveEvent::executeStep(Creature &creature, Item* item, const Position &pos) const { + // onStepIn(creature, item, pos, fromPosition) + // onStepOut(creature, item, pos, fromPosition) // Check if the new position is the same as the old one // If it is, log a warning and either teleport the player to their temple position if item type is an teleport auto fromPosition = creature.getLastPosition(); - if (auto player = creature.getPlayer(); item && fromPosition == pos && getEventType() == MOVE_EVENT_STEP_IN) - { - if (const ItemType& itemType = Item::items[item->getID()]; player && itemType.isTeleport()) - { + if (auto player = creature.getPlayer(); item && fromPosition == pos && getEventType() == MOVE_EVENT_STEP_IN) { + if (const ItemType &itemType = Item::items[item->getID()]; player && itemType.isTeleport()) { SPDLOG_WARN("[{}] cannot teleport player: {}, to the same position: {} of fromPosition: {}", __FUNCTION__, player->getName(), pos.toString(), fromPosition.toString()); g_game().internalTeleport(player, player->getTemplePosition()); player->sendMagicEffect(player->getTemplePosition(), CONST_ME_TELEPORT); @@ -677,14 +695,12 @@ bool MoveEvent::executeStep(Creature& creature, Item* item, const Position& pos) if (!getScriptInterface()->reserveScriptEnv()) { if (item != nullptr) { SPDLOG_ERROR("[MoveEvent::executeStep - Creature {} item {}, position {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature.getName(), item->getName(), pos.toString() - ); + "Call stack overflow. Too many lua script calls being nested.", + creature.getName(), item->getName(), pos.toString()); } else { SPDLOG_ERROR("[MoveEvent::executeStep - Creature {}, position {}] " - "Call stack overflow. Too many lua script calls being nested.", - creature.getName(), pos.toString() - ); + "Call stack overflow. Too many lua script calls being nested.", + creature.getName(), pos.toString()); } return false; } @@ -704,7 +720,7 @@ bool MoveEvent::executeStep(Creature& creature, Item* item, const Position& pos) return getScriptInterface()->callFunction(4); } -uint32_t MoveEvent::fireEquip(Player& player, Item& item, Slots_t toSlot, bool isCheck) { +uint32_t MoveEvent::fireEquip(Player &player, Item &item, Slots_t toSlot, bool isCheck) { if (isLoadedCallback()) { if (!equipFunction || equipFunction(this, &player, &item, toSlot, isCheck) == 1) { if (executeEquip(player, item, toSlot, isCheck)) { @@ -717,13 +733,13 @@ uint32_t MoveEvent::fireEquip(Player& player, Item& item, Slots_t toSlot, bool i } } -bool MoveEvent::executeEquip(Player& player, Item& item, Slots_t onSlot, bool isCheck) const { - //onEquip(player, item, slot, isCheck) - //onDeEquip(player, item, slot, isCheck) +bool MoveEvent::executeEquip(Player &player, Item &item, Slots_t onSlot, bool isCheck) const { + // onEquip(player, item, slot, isCheck) + // onDeEquip(player, item, slot, isCheck) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[MoveEvent::executeEquip - Player {} item {}] " - "Call stack overflow. Too many lua script calls being nested.", - player.getName(), item.getName()); + "Call stack overflow. Too many lua script calls being nested.", + player.getName(), item.getName()); return false; } @@ -742,7 +758,7 @@ bool MoveEvent::executeEquip(Player& player, Item& item, Slots_t onSlot, bool is return getScriptInterface()->callFunction(4); } -uint32_t MoveEvent::fireAddRemItem(Item& item, Item& fromTile, const Position& pos) const { +uint32_t MoveEvent::fireAddRemItem(Item &item, Item &fromTile, const Position &pos) const { if (isLoadedCallback()) { return executeAddRemItem(item, fromTile, pos); } else { @@ -750,15 +766,14 @@ uint32_t MoveEvent::fireAddRemItem(Item& item, Item& fromTile, const Position& p } } -bool MoveEvent::executeAddRemItem(Item& item, Item& fromTile, const Position& pos) const { - //onAddItem(moveitem, tileitem, pos) - //onRemoveItem(moveitem, tileitem, pos) +bool MoveEvent::executeAddRemItem(Item &item, Item &fromTile, const Position &pos) const { + // onAddItem(moveitem, tileitem, pos) + // onRemoveItem(moveitem, tileitem, pos) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[MoveEvent::executeAddRemItem - " - "Item {} item on tile x: {} y: {} z: {}] " - "Call stack overflow. Too many lua script calls being nested.", - item.getName(), - pos.getX(), pos.getY(), pos.getZ()); + "Item {} item on tile x: {} y: {} z: {}] " + "Call stack overflow. Too many lua script calls being nested.", + item.getName(), pos.getX(), pos.getY(), pos.getZ()); return false; } @@ -775,7 +790,7 @@ bool MoveEvent::executeAddRemItem(Item& item, Item& fromTile, const Position& po return getScriptInterface()->callFunction(3); } -uint32_t MoveEvent::fireAddRemItem(Item& item, const Position& pos) const { +uint32_t MoveEvent::fireAddRemItem(Item &item, const Position &pos) const { if (isLoadedCallback()) { return executeAddRemItem(item, pos); } else { @@ -783,15 +798,14 @@ uint32_t MoveEvent::fireAddRemItem(Item& item, const Position& pos) const { } } -bool MoveEvent::executeAddRemItem(Item& item, const Position& pos) const { - //onaddItem(moveitem, pos) - //onRemoveItem(moveitem, pos) +bool MoveEvent::executeAddRemItem(Item &item, const Position &pos) const { + // onaddItem(moveitem, pos) + // onRemoveItem(moveitem, pos) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[MoveEvent::executeAddRemItem - " - "Item {} item on tile x: {} y: {} z: {}] " - "Call stack overflow. Too many lua script calls being nested.", - item.getName(), - pos.getX(), pos.getY(), pos.getZ()); + "Item {} item on tile x: {} y: {} z: {}] " + "Call stack overflow. Too many lua script calls being nested.", + item.getName(), pos.getX(), pos.getY(), pos.getZ()); return false; } diff --git a/src/lua/creature/movement.h b/src/lua/creature/movement.h index 07b853f9e9d..1499deb796e 100644 --- a/src/lua/creature/movement.h +++ b/src/lua/creature/movement.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CREATURE_MOVEMENT_H_ #define SRC_LUA_CREATURE_MOVEMENT_H_ @@ -19,7 +19,7 @@ class MoveEvent; struct MoveEventList { - std::list moveEvent[MOVE_EVENT_LAST]; + std::list moveEvent[MOVE_EVENT_LAST]; }; using VocEquipMap = std::map; @@ -30,20 +30,20 @@ class MoveEvents final : public Scripts { ~MoveEvents() = default; // non-copyable - MoveEvents(const MoveEvents&) = delete; - MoveEvents& operator=(const MoveEvents&) = delete; + MoveEvents(const MoveEvents &) = delete; + MoveEvents &operator=(const MoveEvents &) = delete; - static MoveEvents& getInstance() { + static MoveEvents &getInstance() { // Guaranteed to be destroyed static MoveEvents instance; // Instantiated on first use return instance; } - uint32_t onCreatureMove(Creature& creature, Tile& tile, MoveEvent_t eventType); - uint32_t onPlayerEquip(Player& player, Item& item, Slots_t slot, bool isCheck); - uint32_t onPlayerDeEquip(Player& player, Item& item, Slots_t slot); - uint32_t onItemMove(Item& item, Tile& tile, bool isAdd); + uint32_t onCreatureMove(Creature &creature, Tile &tile, MoveEvent_t eventType); + uint32_t onPlayerEquip(Player &player, Item &item, Slots_t slot, bool isCheck); + uint32_t onPlayerDeEquip(Player &player, Item &item, Slots_t slot); + uint32_t onItemMove(Item &item, Tile &tile, bool isAdd); std::map getPositionsMap() const { return positionsMap; @@ -51,8 +51,7 @@ class MoveEvents final : public Scripts { bool hasPosition(Position position) const { if (auto it = positionsMap.find(position); - it != positionsMap.end()) - { + it != positionsMap.end()) { return true; } return false; @@ -68,8 +67,7 @@ class MoveEvents final : public Scripts { bool hasItemId(int32_t itemId) const { if (auto it = itemIdMap.find(itemId); - it != itemIdMap.end()) - { + it != itemIdMap.end()) { return true; } return false; @@ -85,8 +83,7 @@ class MoveEvents final : public Scripts { bool hasUniqueId(int32_t uniqueId) const { if (auto it = uniqueIdMap.find(uniqueId); - it != uniqueIdMap.end()) - { + it != uniqueIdMap.end()) { return true; } return false; @@ -102,8 +99,7 @@ class MoveEvents final : public Scripts { bool hasActionId(int32_t actionId) const { if (auto it = actionIdMap.find(actionId); - it != actionIdMap.end()) - { + it != actionIdMap.end()) { return true; } return false; @@ -113,24 +109,24 @@ class MoveEvents final : public Scripts { actionIdMap.try_emplace(actionId, moveEventList); } - MoveEvent* getEvent(Item& item, MoveEvent_t eventType); + MoveEvent* getEvent(Item &item, MoveEvent_t eventType); - bool registerLuaItemEvent(MoveEvent& moveEvent); - bool registerLuaActionEvent(MoveEvent& moveEvent); - bool registerLuaUniqueEvent(MoveEvent& moveEvent); - bool registerLuaPositionEvent(MoveEvent& moveEvent); - bool registerLuaEvent(MoveEvent& event); + bool registerLuaItemEvent(MoveEvent &moveEvent); + bool registerLuaActionEvent(MoveEvent &moveEvent); + bool registerLuaUniqueEvent(MoveEvent &moveEvent); + bool registerLuaPositionEvent(MoveEvent &moveEvent); + bool registerLuaEvent(MoveEvent &event); void clear(); private: - void clearMap(std::map& map) const; - void clearPosMap(std::map& map); + void clearMap(std::map &map) const; + void clearPosMap(std::map &map); - bool registerEvent(MoveEvent& moveEvent, int32_t id, std::map& moveListMap) const; - bool registerEvent(MoveEvent& moveEvent, const Position& position, std::map& moveListMap) const; - MoveEvent* getEvent(Tile& tile, MoveEvent_t eventType); + bool registerEvent(MoveEvent &moveEvent, int32_t id, std::map &moveListMap) const; + bool registerEvent(MoveEvent &moveEvent, const Position &position, std::map &moveListMap) const; + MoveEvent* getEvent(Tile &tile, MoveEvent_t eventType); - MoveEvent* getEvent(Item& item, MoveEvent_t eventType, Slots_t slot); + MoveEvent* getEvent(Item &item, MoveEvent_t eventType, Slots_t slot); std::map uniqueIdMap; std::map actionIdMap; @@ -147,24 +143,24 @@ class MoveEvent final : public Script { MoveEvent_t getEventType() const; void setEventType(MoveEvent_t type); - uint32_t fireStepEvent(Creature& creature, Item* item, const Position& pos) const; - uint32_t fireAddRemItem(Item& item, Item& tileItem, const Position& pos) const; - uint32_t fireAddRemItem(Item& item, const Position& pos) const; - uint32_t fireEquip(Player& player, Item& item, Slots_t slot, bool isCheck); + uint32_t fireStepEvent(Creature &creature, Item* item, const Position &pos) const; + uint32_t fireAddRemItem(Item &item, Item &tileItem, const Position &pos) const; + uint32_t fireAddRemItem(Item &item, const Position &pos) const; + uint32_t fireEquip(Player &player, Item &item, Slots_t slot, bool isCheck); uint32_t getSlot() const { return slot; } // Scripting to lua interface - bool executeStep(Creature& creature, Item* item, const Position& pos) const ; - bool executeEquip(Player& player, Item& item, Slots_t slot, bool isCheck) const ; - bool executeAddRemItem(Item& item, Item& tileItem, const Position& pos) const ; + bool executeStep(Creature &creature, Item* item, const Position &pos) const; + bool executeEquip(Player &player, Item &item, Slots_t slot, bool isCheck) const; + bool executeAddRemItem(Item &item, Item &tileItem, const Position &pos) const; // No have tile item - bool executeAddRemItem(Item& item, const Position& pos) const ; + bool executeAddRemItem(Item &item, const Position &pos) const; // - //onEquip information + // onEquip information uint32_t getReqLevel() const { return reqLevel; } @@ -174,16 +170,16 @@ class MoveEvent final : public Script { bool isPremium() const { return premium; } - const std::string& getVocationString() const { + const std::string &getVocationString() const { return vocationString; } - void setVocationString(const std::string& str) { + void setVocationString(const std::string &str) { vocationString = str; } uint32_t getWieldInfo() const { return wieldInfo; } - const std::map& getVocEquipMap() const { + const std::map &getVocEquipMap() const { return vocEquipMap; } void addVocEquipMap(std::string vocName) { @@ -250,11 +246,11 @@ class MoveEvent final : public Script { wieldInfo |= info; } - static uint32_t StepInField(Creature* creature, Item* item, const Position& pos); - static uint32_t StepOutField(Creature* creature, Item* item, const Position& pos); + static uint32_t StepInField(Creature* creature, Item* item, const Position &pos); + static uint32_t StepOutField(Creature* creature, Item* item, const Position &pos); - static uint32_t AddItemField(Item* item, Item* tileItem, const Position& pos); - static uint32_t RemoveItemField(Item* item, Item* tileItem, const Position& pos); + static uint32_t AddItemField(Item* item, Item* tileItem, const Position &pos); + static uint32_t RemoveItemField(Item* item, Item* tileItem, const Position &pos); static uint32_t EquipItem(MoveEvent* moveEvent, Player* player, Item* item, Slots_t slot, bool boolean); static uint32_t DeEquipItem(MoveEvent* moveEvent, Player* player, Item* item, Slots_t slot, bool boolean); @@ -269,14 +265,16 @@ class MoveEvent final : public Script { std::function stepFunction; + const Position &pos + )> + stepFunction; // Move function std::function moveFunction; + const Position &pos + )> + moveFunction; // equipFunction std::function equipFunction; + )> + equipFunction; - //onEquip information + // onEquip information uint32_t reqLevel = 0; uint32_t reqMagLevel = 0; bool premium = false; @@ -303,4 +302,4 @@ class MoveEvent final : public Script { friend class MoveEventFunctions; }; -#endif // SRC_LUA_CREATURE_MOVEMENT_H_ +#endif // SRC_LUA_CREATURE_MOVEMENT_H_ diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index e9de8257c22..719ff12aa00 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -65,8 +65,9 @@ bool Raids::loadFromXml() { interval = pugi::cast(raidNode.attribute("interval2").value()) * 60; if (interval == 0) { SPDLOG_ERROR("{} - " - "'interval2' tag missing or zero " - "(would divide by 0) for raid: {}", __FUNCTION__, name); + "'interval2' tag missing or zero " + "(would divide by 0) for raid: {}", + __FUNCTION__, name); continue; } @@ -74,7 +75,8 @@ bool Raids::loadFromXml() { margin = pugi::cast(attr.value()) * 60 * 1000; } else { SPDLOG_WARN("{} - " - "'margin' tag missing for raid: {}", __FUNCTION__, name); + "'margin' tag missing for raid: {}", + __FUNCTION__, name); margin = 0; } @@ -159,7 +161,7 @@ bool Raids::reload() { return loadFromXml(); } -Raid* Raids::getRaidByName(const std::string& name) { +Raid* Raids::getRaidByName(const std::string &name) { for (Raid* raid : raidList) { if (strcasecmp(raid->getName().c_str(), name.c_str()) == 0) { return raid; @@ -174,7 +176,7 @@ Raid::~Raid() { } } -bool Raid::loadFromXml(const std::string& filename) { +bool Raid::loadFromXml(const std::string &filename) { if (isLoaded()) { return true; } @@ -204,12 +206,13 @@ bool Raid::loadFromXml(const std::string& filename) { raidEvents.push_back(event); } else { SPDLOG_ERROR("{} - " - "In file: {}, eventNode: {}", __FUNCTION__, filename, eventNode.name()); + "In file: {}, eventNode: {}", + __FUNCTION__, filename, eventNode.name()); delete event; } } - //sort by delay time + // sort by delay time std::sort(raidEvents.begin(), raidEvents.end(), [](const RaidEvent* lhs, const RaidEvent* rhs) { return lhs->getDelay() < rhs->getDelay(); }); @@ -264,7 +267,7 @@ RaidEvent* Raid::getNextRaidEvent() { } } -bool RaidEvent::configureRaidEvent(const pugi::xml_node& eventNode) { +bool RaidEvent::configureRaidEvent(const pugi::xml_node &eventNode) { pugi::xml_attribute delayAttribute = eventNode.attribute("delay"); if (!delayAttribute) { SPDLOG_ERROR("{} - 'delay' tag missing", __FUNCTION__); @@ -275,7 +278,7 @@ bool RaidEvent::configureRaidEvent(const pugi::xml_node& eventNode) { return true; } -bool AnnounceEvent::configureRaidEvent(const pugi::xml_node& eventNode) { +bool AnnounceEvent::configureRaidEvent(const pugi::xml_node &eventNode) { if (!RaidEvent::configureRaidEvent(eventNode)) { return false; } @@ -283,7 +286,8 @@ bool AnnounceEvent::configureRaidEvent(const pugi::xml_node& eventNode) { pugi::xml_attribute messageAttribute = eventNode.attribute("message"); if (!messageAttribute) { SPDLOG_ERROR("{} - " - "'message' tag missing for announce event", __FUNCTION__); + "'message' tag missing for announce event", + __FUNCTION__); return false; } message = messageAttribute.as_string(); @@ -306,15 +310,15 @@ bool AnnounceEvent::configureRaidEvent(const pugi::xml_node& eventNode) { } else { SPDLOG_WARN("{} - " "Unknown type tag missing for announce event, " - "using default: {}", __FUNCTION__, - static_cast(messageType)); + "using default: {}", + __FUNCTION__, static_cast(messageType)); } } else { messageType = MESSAGE_EVENT_ADVANCE; SPDLOG_WARN("{} - " "Type tag missing for announce event, " - "using default: {}", __FUNCTION__, - static_cast(messageType)); + "using default: {}", + __FUNCTION__, static_cast(messageType)); } return true; } @@ -326,7 +330,7 @@ bool AnnounceEvent::executeEvent() { return true; } -bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { +bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { if (!RaidEvent::configureRaidEvent(eventNode)) { return false; } @@ -336,7 +340,8 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { monsterName = attr.as_string(); } else { SPDLOG_ERROR("{} - " - "'Name' tag missing for singlespawn event", __FUNCTION__); + "'Name' tag missing for singlespawn event", + __FUNCTION__); return false; } @@ -344,7 +349,8 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { position.x = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'X' tag missing for singlespawn event", __FUNCTION__); + "'X' tag missing for singlespawn event", + __FUNCTION__); return false; } @@ -352,7 +358,8 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { position.y = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'Y' tag missing for singlespawn event", __FUNCTION__); + "'Y' tag missing for singlespawn event", + __FUNCTION__); return false; } @@ -360,7 +367,8 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { position.z = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'Z' tag missing for singlespawn event", __FUNCTION__); + "'Z' tag missing for singlespawn event", + __FUNCTION__); return false; } return true; @@ -369,15 +377,13 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { bool SingleSpawnEvent::executeEvent() { Monster* monster = Monster::createMonster(monsterName); if (!monster) { - SPDLOG_ERROR("{} - Cant create monster {}", __FUNCTION__, - monsterName); + SPDLOG_ERROR("{} - Cant create monster {}", __FUNCTION__, monsterName); return false; } if (!g_game().placeCreature(monster, position, false, true)) { delete monster; - SPDLOG_ERROR("{} - Cant create monster {}", __FUNCTION__, - monsterName); + SPDLOG_ERROR("{} - Cant create monster {}", __FUNCTION__, monsterName); return false; } @@ -385,7 +391,7 @@ bool SingleSpawnEvent::executeEvent() { return true; } -bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { +bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { if (!RaidEvent::configureRaidEvent(eventNode)) { return false; } @@ -399,8 +405,9 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { centerPos.x = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "" - "'centerx' tag missing for areaspawn event", __FUNCTION__); + "" + "'centerx' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -408,7 +415,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { centerPos.y = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'centery' tag missing for areaspawn event", __FUNCTION__); + "'centery' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -416,7 +424,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { centerPos.z = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "centerz' tag missing for areaspawn event", __FUNCTION__); + "centerz' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -432,7 +441,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { fromPos.x = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'fromx' tag missing for areaspawn event", __FUNCTION__); + "'fromx' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -440,7 +450,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { fromPos.y = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'fromy' tag missing for areaspawn event", __FUNCTION__); + "'fromy' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -448,7 +459,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { fromPos.z = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'fromz' tag missing for areaspawn event", __FUNCTION__); + "'fromz' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -456,7 +468,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { toPos.x = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'tox' tag missing for areaspawn event", __FUNCTION__); + "'tox' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -464,7 +477,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { toPos.y = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'toy' tag missing for areaspawn event", __FUNCTION__); + "'toy' tag missing for areaspawn event", + __FUNCTION__); return false; } @@ -472,7 +486,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { toPos.z = pugi::cast(attr.value()); } else { SPDLOG_ERROR("{} - " - "'toz' tag missing for areaspawn event", __FUNCTION__); + "'toz' tag missing for areaspawn event", + __FUNCTION__); return false; } } @@ -484,7 +499,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { name = attr.value(); } else { SPDLOG_ERROR("{} - " - "'name' tag missing for monster node", __FUNCTION__); + "'name' tag missing for monster node", + __FUNCTION__); return false; } @@ -508,7 +524,8 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { maxAmount = minAmount; } else { SPDLOG_ERROR("{} - " - "'amount' tag missing for monster node", __FUNCTION__); + "'amount' tag missing for monster node", + __FUNCTION__); return false; } } @@ -519,13 +536,12 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) { } bool AreaSpawnEvent::executeEvent() { - for (const MonsterSpawn& spawn : spawnMonsterList) { + for (const MonsterSpawn &spawn : spawnMonsterList) { uint32_t amount = uniform_random(spawn.minAmount, spawn.maxAmount); for (uint32_t i = 0; i < amount; ++i) { Monster* monster = Monster::createMonster(spawn.name); if (!monster) { - SPDLOG_ERROR("{} - Can't create monster {}", __FUNCTION__, - spawn.name); + SPDLOG_ERROR("{} - Can't create monster {}", __FUNCTION__, spawn.name); return false; } @@ -547,7 +563,7 @@ bool AreaSpawnEvent::executeEvent() { return true; } -bool ScriptEvent::configureRaidEvent(const pugi::xml_node& eventNode) { +bool ScriptEvent::configureRaidEvent(const pugi::xml_node &eventNode) { if (!RaidEvent::configureRaidEvent(eventNode)) { return false; } @@ -555,7 +571,8 @@ bool ScriptEvent::configureRaidEvent(const pugi::xml_node& eventNode) { pugi::xml_attribute scriptAttribute = eventNode.attribute("script"); if (!scriptAttribute) { SPDLOG_ERROR("{} - " - "No script file found for raid", __FUNCTION__); + "No script file found for raid", + __FUNCTION__); return false; } @@ -576,12 +593,11 @@ std::string ScriptEvent::getScriptEventName() const { } bool ScriptEvent::executeEvent() { - //onRaid() + // onRaid() if (!scriptInterface->reserveScriptEnv()) { SPDLOG_ERROR("{} - Script with name {} " - "Call stack overflow. Too many lua script calls being nested.", - __FUNCTION__, - getScriptName()); + "Call stack overflow. Too many lua script calls being nested.", + __FUNCTION__, getScriptName()); return false; } diff --git a/src/lua/creature/raids.h b/src/lua/creature/raids.h index a0b88f3f006..ae0164711dc 100644 --- a/src/lua/creature/raids.h +++ b/src/lua/creature/raids.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CREATURE_RAIDS_H_ #define SRC_LUA_CREATURE_RAIDS_H_ @@ -16,15 +16,15 @@ #include "lua/global/baseevents.h" struct MonsterSpawn { - MonsterSpawn(std::string initName, uint32_t initMinAmount, uint32_t initMaxAmount) : - name(std::move(initName)), minAmount(initMinAmount), maxAmount(initMaxAmount) {} + MonsterSpawn(std::string initName, uint32_t initMinAmount, uint32_t initMaxAmount) : + name(std::move(initName)), minAmount(initMinAmount), maxAmount(initMaxAmount) { } - std::string name; - uint32_t minAmount; - uint32_t maxAmount; + std::string name; + uint32_t minAmount; + uint32_t maxAmount; }; -//How many times it will try to find a tile to add the monster to before giving up +// How many times it will try to find a tile to add the monster to before giving up static constexpr int32_t MAXIMUM_TRIES_PER_MONSTER = 10; static constexpr int32_t CHECK_RAIDS_INTERVAL = 60; static constexpr int32_t RAID_MINTICKS = 1000; @@ -38,8 +38,8 @@ class Raids { ~Raids(); // non-copyable - Raids(const Raids&) = delete; - Raids& operator=(const Raids&) = delete; + Raids(const Raids &) = delete; + Raids &operator=(const Raids &) = delete; bool loadFromXml(); bool startup(); @@ -61,7 +61,7 @@ class Raids { running = newRunning; } - Raid* getRaidByName(const std::string& name); + Raid* getRaidByName(const std::string &name); uint64_t getLastRaidEnd() const { return lastRaidEnd; @@ -72,12 +72,12 @@ class Raids { void checkRaids(); - LuaScriptInterface& getScriptInterface() { + LuaScriptInterface &getScriptInterface() { return scriptInterface; } private: - LuaScriptInterface scriptInterface{"Raid Interface"}; + LuaScriptInterface scriptInterface { "Raid Interface" }; std::list raidList; Raid* running = nullptr; @@ -90,14 +90,14 @@ class Raids { class Raid { public: Raid(std::string initName, uint32_t initInterval, uint32_t initMarginTime, bool initRepeat) : - name(std::move(initName)), interval(initInterval), margin(initMarginTime), repeat(initRepeat) {} + name(std::move(initName)), interval(initInterval), margin(initMarginTime), repeat(initRepeat) { } ~Raid(); // non-copyable - Raid(const Raid&) = delete; - Raid& operator=(const Raid&) = delete; + Raid(const Raid &) = delete; + Raid &operator=(const Raid &) = delete; - bool loadFromXml(const std::string& filename); + bool loadFromXml(const std::string &filename); void startRaid(); @@ -108,7 +108,7 @@ class Raid { void setState(RaidState_t newState) { state = newState; } - const std::string& getName() const { + const std::string &getName() const { return name; } @@ -143,7 +143,7 @@ class RaidEvent { public: virtual ~RaidEvent() = default; - virtual bool configureRaidEvent(const pugi::xml_node& eventNode); + virtual bool configureRaidEvent(const pugi::xml_node &eventNode); virtual bool executeEvent() = 0; uint32_t getDelay() const { @@ -158,7 +158,7 @@ class AnnounceEvent final : public RaidEvent { public: AnnounceEvent() = default; - bool configureRaidEvent(const pugi::xml_node& eventNode) override; + bool configureRaidEvent(const pugi::xml_node &eventNode) override; bool executeEvent() override; @@ -169,7 +169,7 @@ class AnnounceEvent final : public RaidEvent { class SingleSpawnEvent final : public RaidEvent { public: - bool configureRaidEvent(const pugi::xml_node& eventNode) override; + bool configureRaidEvent(const pugi::xml_node &eventNode) override; bool executeEvent() override; @@ -180,7 +180,7 @@ class SingleSpawnEvent final : public RaidEvent { class AreaSpawnEvent final : public RaidEvent { public: - bool configureRaidEvent(const pugi::xml_node& eventNode) override; + bool configureRaidEvent(const pugi::xml_node &eventNode) override; bool executeEvent() override; @@ -191,14 +191,15 @@ class AreaSpawnEvent final : public RaidEvent { class ScriptEvent final : public RaidEvent, public Event { public: - explicit ScriptEvent(LuaScriptInterface* interface) : Event(interface) {} + explicit ScriptEvent(LuaScriptInterface* interface) : + Event(interface) { } - bool configureRaidEvent(const pugi::xml_node& eventNode) override; - bool configureEvent(const pugi::xml_node&) override { + bool configureRaidEvent(const pugi::xml_node &eventNode) override; + bool configureEvent(const pugi::xml_node &) override { return false; } - std::string& getScriptName() { + std::string &getScriptName() { return scriptName; } void setScriptName(std::string name) { @@ -212,4 +213,4 @@ class ScriptEvent final : public RaidEvent, public Event { std::string scriptName; }; -#endif // SRC_LUA_CREATURE_RAIDS_H_ +#endif // SRC_LUA_CREATURE_RAIDS_H_ diff --git a/src/lua/creature/talkaction.cpp b/src/lua/creature/talkaction.cpp index 79ee3fd296d..5fc0f535c78 100644 --- a/src/lua/creature/talkaction.cpp +++ b/src/lua/creature/talkaction.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -21,7 +21,7 @@ void TalkActions::clear() { } bool TalkActions::registerLuaEvent(TalkAction* event) { - TalkAction_ptr talkAction{ event }; + TalkAction_ptr talkAction { event }; std::vector words = talkAction->getWordsMap(); for (size_t i = 0; i < words.size(); i++) { @@ -35,10 +35,10 @@ bool TalkActions::registerLuaEvent(TalkAction* event) { return true; } -TalkActionResult_t TalkActions::playerSaySpell(Player* player, SpeakClasses type, const std::string& words) const { +TalkActionResult_t TalkActions::playerSaySpell(Player* player, SpeakClasses type, const std::string &words) const { size_t wordsLength = words.length(); - for (auto it = talkActions.begin(); it != talkActions.end(); ) { - const std::string& talkactionWords = it->first; + for (auto it = talkActions.begin(); it != talkActions.end();) { + const std::string &talkactionWords = it->first; size_t talkactionLength = talkactionWords.length(); if (wordsLength < talkactionLength || strncasecmp(words.c_str(), talkactionWords.c_str(), talkactionLength) != 0) { ++it; @@ -76,12 +76,12 @@ TalkActionResult_t TalkActions::playerSaySpell(Player* player, SpeakClasses type return TALKACTION_CONTINUE; } -bool TalkAction::executeSay(Player* player, const std::string& words, const std::string& param, SpeakClasses type) const { - //onSay(player, words, param, type) +bool TalkAction::executeSay(Player* player, const std::string &words, const std::string ¶m, SpeakClasses type) const { + // onSay(player, words, param, type) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[TalkAction::executeSay - Player {} words {}] " - "Call stack overflow. Too many lua script calls being nested.", - player->getName(), getWords()); + "Call stack overflow. Too many lua script calls being nested.", + player->getName(), getWords()); return false; } diff --git a/src/lua/creature/talkaction.h b/src/lua/creature/talkaction.h index 1bdc9b1767c..fa5a7ac3204 100644 --- a/src/lua/creature/talkaction.h +++ b/src/lua/creature/talkaction.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_CREATURE_TALKACTION_H_ #define SRC_LUA_CREATURE_TALKACTION_H_ @@ -23,10 +23,10 @@ class TalkAction : public Script { public: using Script::Script; - const std::string& getWords() const { + const std::string &getWords() const { return words; } - const std::vector& getWordsMap() const { + const std::vector &getWordsMap() const { return wordsMap; } void setWords(std::string word) { @@ -40,8 +40,8 @@ class TalkAction : public Script { separator = sep; } - //scripting - bool executeSay(Player* player, const std::string& words, const std::string& param, SpeakClasses type) const; + // scripting + bool executeSay(Player* player, const std::string &words, const std::string ¶m, SpeakClasses type) const; // private: @@ -60,17 +60,17 @@ class TalkActions final : public Scripts { ~TalkActions(); // non-copyable - TalkActions(const TalkActions&) = delete; - TalkActions& operator=(const TalkActions&) = delete; + TalkActions(const TalkActions &) = delete; + TalkActions &operator=(const TalkActions &) = delete; - static TalkActions& getInstance() { + static TalkActions &getInstance() { // Guaranteed to be destroyed static TalkActions instance; // Instantiated on first use return instance; } - TalkActionResult_t playerSaySpell(Player* player, SpeakClasses type, const std::string& words) const; + TalkActionResult_t playerSaySpell(Player* player, SpeakClasses type, const std::string &words) const; bool registerLuaEvent(TalkAction* event); void clear(); @@ -81,4 +81,4 @@ class TalkActions final : public Scripts { constexpr auto g_talkActions = &TalkActions::getInstance; -#endif // SRC_LUA_CREATURE_TALKACTION_H_ +#endif // SRC_LUA_CREATURE_TALKACTION_H_ diff --git a/src/lua/functions/core/core_functions.hpp b/src/lua/functions/core/core_functions.hpp index 284a201b4c0..fe5db63b1a5 100644 --- a/src/lua/functions/core/core_functions.hpp +++ b/src/lua/functions/core/core_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_CORE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_CORE_FUNCTIONS_HPP_ @@ -24,6 +24,6 @@ class CoreFunctions final : LuaScriptInterface { } private: - }; +}; -#endif // SRC_LUA_FUNCTIONS_CORE_CORE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_CORE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/game/config_functions.cpp b/src/lua/functions/core/game/config_functions.cpp index 85493ec6acb..0edefd708b8 100644 --- a/src/lua/functions/core/game/config_functions.cpp +++ b/src/lua/functions/core/game/config_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -19,165 +19,165 @@ void ConfigFunctions::init(lua_State* L) { registerMethod(L, "configManager", "getBoolean", ConfigFunctions::luaConfigManagerGetBoolean); registerMethod(L, "configManager", "getFloat", ConfigFunctions::luaConfigManagerGetFloat); - #define registerEnumIn(L, tableName, value) { \ - std::string enumName = #value; \ +#define registerEnumIn(L, tableName, value) \ + { \ + std::string enumName = #value; \ registerVariable(L, tableName, enumName.substr(enumName.find_last_of(':') + 1), value); \ } registerTable(L, "configKeys"); - registerEnumIn(L, "configKeys", ALLOW_CHANGEOUTFIT) - registerEnumIn(L, "configKeys", ONE_PLAYER_ON_ACCOUNT) - registerEnumIn(L, "configKeys", AIMBOT_HOTKEY_ENABLED) - registerEnumIn(L, "configKeys", REMOVE_RUNE_CHARGES) - registerEnumIn(L, "configKeys", EXPERIENCE_FROM_PLAYERS) - registerEnumIn(L, "configKeys", FREE_PREMIUM) - registerEnumIn(L, "configKeys", REPLACE_KICK_ON_LOGIN) - registerEnumIn(L, "configKeys", ALLOW_CLONES) - registerEnumIn(L, "configKeys", BIND_ONLY_GLOBAL_ADDRESS) - registerEnumIn(L, "configKeys", OPTIMIZE_DATABASE) - registerEnumIn(L, "configKeys", MARKET_PREMIUM) - registerEnumIn(L, "configKeys", EMOTE_SPELLS) - registerEnumIn(L, "configKeys", STAMINA_SYSTEM) - registerEnumIn(L, "configKeys", WARN_UNSAFE_SCRIPTS) - registerEnumIn(L, "configKeys", CONVERT_UNSAFE_SCRIPTS) - registerEnumIn(L, "configKeys", ALLOW_BLOCK_SPAWN) - registerEnumIn(L, "configKeys", CLASSIC_ATTACK_SPEED) - registerEnumIn(L, "configKeys", REMOVE_WEAPON_AMMO) - registerEnumIn(L, "configKeys", REMOVE_WEAPON_CHARGES) - registerEnumIn(L, "configKeys", REMOVE_POTION_CHARGES) - registerEnumIn(L, "configKeys", WEATHER_RAIN) - registerEnumIn(L, "configKeys", ALLOW_RELOAD) - registerEnumIn(L, "configKeys", WEATHER_THUNDER) - registerEnumIn(L, "configKeys", TOGGLE_FREE_QUEST) - registerEnumIn(L, "configKeys", FREE_QUEST_STAGE) - registerEnumIn(L, "configKeys", ALL_CONSOLE_LOG) - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE) - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_NOTIFY_DURATION) - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_CLEAN_MAP) - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_CLOSE) - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_SHUTDOWN) - registerEnumIn(L, "configKeys", MAP_NAME) - registerEnumIn(L, "configKeys", TOGGLE_MAP_CUSTOM) - registerEnumIn(L, "configKeys", MAP_CUSTOM_NAME) - registerEnumIn(L, "configKeys", HOUSE_RENT_PERIOD) - registerEnumIn(L, "configKeys", SERVER_NAME) - registerEnumIn(L, "configKeys", OWNER_NAME) - registerEnumIn(L, "configKeys", OWNER_EMAIL) - registerEnumIn(L, "configKeys", URL) - registerEnumIn(L, "configKeys", LOCATION) - registerEnumIn(L, "configKeys", IP) - registerEnumIn(L, "configKeys", MOTD) - registerEnumIn(L, "configKeys", WORLD_TYPE) - registerEnumIn(L, "configKeys", MYSQL_HOST) - registerEnumIn(L, "configKeys", MYSQL_USER) - registerEnumIn(L, "configKeys", MYSQL_PASS) - registerEnumIn(L, "configKeys", MYSQL_DB) - registerEnumIn(L, "configKeys", MYSQL_SOCK) - registerEnumIn(L, "configKeys", DEFAULT_PRIORITY) - registerEnumIn(L, "configKeys", MAP_AUTHOR) - registerEnumIn(L, "configKeys", STORE_IMAGES_URL) - registerEnumIn(L, "configKeys", PARTY_LIST_MAX_DISTANCE) - registerEnumIn(L, "configKeys", SQL_PORT) - registerEnumIn(L, "configKeys", MAX_PLAYERS) - registerEnumIn(L, "configKeys", PZ_LOCKED) - registerEnumIn(L, "configKeys", DEFAULT_DESPAWNRANGE) - registerEnumIn(L, "configKeys", PREY_ENABLED) - registerEnumIn(L, "configKeys", PREY_FREE_THIRD_SLOT) - registerEnumIn(L, "configKeys", PREY_REROLL_PRICE_LEVEL) - registerEnumIn(L, "configKeys", PREY_BONUS_TIME) - registerEnumIn(L, "configKeys", PREY_BONUS_REROLL_PRICE) - registerEnumIn(L, "configKeys", PREY_FREE_REROLL_TIME) - registerEnumIn(L, "configKeys", TASK_HUNTING_ENABLED) - registerEnumIn(L, "configKeys", TASK_HUNTING_FREE_THIRD_SLOT) - registerEnumIn(L, "configKeys", TASK_HUNTING_LIMIT_EXHAUST) - registerEnumIn(L, "configKeys", TASK_HUNTING_REROLL_PRICE_LEVEL) - registerEnumIn(L, "configKeys", TASK_HUNTING_SELECTION_LIST_PRICE) - registerEnumIn(L, "configKeys", TASK_HUNTING_BONUS_REROLL_PRICE) - registerEnumIn(L, "configKeys", TASK_HUNTING_FREE_REROLL_TIME) - registerEnumIn(L, "configKeys", DEFAULT_DESPAWNRADIUS) - registerEnumIn(L, "configKeys", RATE_EXPERIENCE) - registerEnumIn(L, "configKeys", RATE_SKILL) - registerEnumIn(L, "configKeys", RATE_LOOT) - registerEnumIn(L, "configKeys", RATE_MAGIC) - registerEnumIn(L, "configKeys", RATE_SPAWN) - registerEnumIn(L, "configKeys", HOUSE_PRICE) - registerEnumIn(L, "configKeys", HOUSE_BUY_LEVEL) - registerEnumIn(L, "configKeys", MAX_MESSAGEBUFFER) - registerEnumIn(L, "configKeys", ACTIONS_DELAY_INTERVAL) - registerEnumIn(L, "configKeys", EX_ACTIONS_DELAY_INTERVAL) - registerEnumIn(L, "configKeys", KICK_AFTER_MINUTES) - registerEnumIn(L, "configKeys", PROTECTION_LEVEL) - registerEnumIn(L, "configKeys", DEATH_LOSE_PERCENT) - registerEnumIn(L, "configKeys", STATUSQUERY_TIMEOUT) - registerEnumIn(L, "configKeys", FRAG_TIME) - registerEnumIn(L, "configKeys", WHITE_SKULL_TIME) - registerEnumIn(L, "configKeys", GAME_PORT) - registerEnumIn(L, "configKeys", LOGIN_PORT) - registerEnumIn(L, "configKeys", STATUS_PORT) - registerEnumIn(L, "configKeys", STAIRHOP_DELAY) - registerEnumIn(L, "configKeys", MARKET_OFFER_DURATION) - registerEnumIn(L, "configKeys", CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES) - registerEnumIn(L, "configKeys", MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER) - registerEnumIn(L, "configKeys", EXP_FROM_PLAYERS_LEVEL_RANGE) - registerEnumIn(L, "configKeys", MAX_PACKETS_PER_SECOND) - registerEnumIn(L, "configKeys", STORE_COIN_PACKET) - registerEnumIn(L, "configKeys", DAY_KILLS_TO_RED) - registerEnumIn(L, "configKeys", WEEK_KILLS_TO_RED) - registerEnumIn(L, "configKeys", MONTH_KILLS_TO_RED) - registerEnumIn(L, "configKeys", RED_SKULL_DURATION) - registerEnumIn(L, "configKeys", BLACK_SKULL_DURATION) - registerEnumIn(L, "configKeys", ORANGE_SKULL_DURATION) - registerEnumIn(L, "configKeys", RATE_MONSTER_HEALTH) - registerEnumIn(L, "configKeys", RATE_MONSTER_ATTACK) - registerEnumIn(L, "configKeys", RATE_MONSTER_DEFENSE) - registerEnumIn(L, "configKeys", RATE_NPC_HEALTH) - registerEnumIn(L, "configKeys", RATE_NPC_ATTACK) - registerEnumIn(L, "configKeys", RATE_NPC_DEFENSE) + registerEnumIn(L, "configKeys", ALLOW_CHANGEOUTFIT); + registerEnumIn(L, "configKeys", ONE_PLAYER_ON_ACCOUNT); + registerEnumIn(L, "configKeys", AIMBOT_HOTKEY_ENABLED); + registerEnumIn(L, "configKeys", REMOVE_RUNE_CHARGES); + registerEnumIn(L, "configKeys", EXPERIENCE_FROM_PLAYERS); + registerEnumIn(L, "configKeys", FREE_PREMIUM); + registerEnumIn(L, "configKeys", REPLACE_KICK_ON_LOGIN); + registerEnumIn(L, "configKeys", ALLOW_CLONES); + registerEnumIn(L, "configKeys", BIND_ONLY_GLOBAL_ADDRESS); + registerEnumIn(L, "configKeys", OPTIMIZE_DATABASE); + registerEnumIn(L, "configKeys", MARKET_PREMIUM); + registerEnumIn(L, "configKeys", EMOTE_SPELLS); + registerEnumIn(L, "configKeys", STAMINA_SYSTEM); + registerEnumIn(L, "configKeys", WARN_UNSAFE_SCRIPTS); + registerEnumIn(L, "configKeys", CONVERT_UNSAFE_SCRIPTS); + registerEnumIn(L, "configKeys", ALLOW_BLOCK_SPAWN); + registerEnumIn(L, "configKeys", CLASSIC_ATTACK_SPEED); + registerEnumIn(L, "configKeys", REMOVE_WEAPON_AMMO); + registerEnumIn(L, "configKeys", REMOVE_WEAPON_CHARGES); + registerEnumIn(L, "configKeys", REMOVE_POTION_CHARGES); + registerEnumIn(L, "configKeys", WEATHER_RAIN); + registerEnumIn(L, "configKeys", ALLOW_RELOAD); + registerEnumIn(L, "configKeys", WEATHER_THUNDER); + registerEnumIn(L, "configKeys", TOGGLE_FREE_QUEST); + registerEnumIn(L, "configKeys", FREE_QUEST_STAGE); + registerEnumIn(L, "configKeys", ALL_CONSOLE_LOG); + registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE); + registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_NOTIFY_DURATION); + registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_CLEAN_MAP); + registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_CLOSE); + registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_SHUTDOWN); + registerEnumIn(L, "configKeys", MAP_NAME); + registerEnumIn(L, "configKeys", TOGGLE_MAP_CUSTOM); + registerEnumIn(L, "configKeys", MAP_CUSTOM_NAME); + registerEnumIn(L, "configKeys", HOUSE_RENT_PERIOD); + registerEnumIn(L, "configKeys", SERVER_NAME); + registerEnumIn(L, "configKeys", OWNER_NAME); + registerEnumIn(L, "configKeys", OWNER_EMAIL); + registerEnumIn(L, "configKeys", URL); + registerEnumIn(L, "configKeys", LOCATION); + registerEnumIn(L, "configKeys", IP); + registerEnumIn(L, "configKeys", MOTD); + registerEnumIn(L, "configKeys", WORLD_TYPE); + registerEnumIn(L, "configKeys", MYSQL_HOST); + registerEnumIn(L, "configKeys", MYSQL_USER); + registerEnumIn(L, "configKeys", MYSQL_PASS); + registerEnumIn(L, "configKeys", MYSQL_DB); + registerEnumIn(L, "configKeys", MYSQL_SOCK); + registerEnumIn(L, "configKeys", DEFAULT_PRIORITY); + registerEnumIn(L, "configKeys", MAP_AUTHOR); + registerEnumIn(L, "configKeys", STORE_IMAGES_URL); + registerEnumIn(L, "configKeys", PARTY_LIST_MAX_DISTANCE); + registerEnumIn(L, "configKeys", SQL_PORT); + registerEnumIn(L, "configKeys", MAX_PLAYERS); + registerEnumIn(L, "configKeys", PZ_LOCKED); + registerEnumIn(L, "configKeys", DEFAULT_DESPAWNRANGE); + registerEnumIn(L, "configKeys", PREY_ENABLED); + registerEnumIn(L, "configKeys", PREY_FREE_THIRD_SLOT); + registerEnumIn(L, "configKeys", PREY_REROLL_PRICE_LEVEL); + registerEnumIn(L, "configKeys", PREY_BONUS_TIME); + registerEnumIn(L, "configKeys", PREY_BONUS_REROLL_PRICE); + registerEnumIn(L, "configKeys", PREY_FREE_REROLL_TIME); + registerEnumIn(L, "configKeys", TASK_HUNTING_ENABLED); + registerEnumIn(L, "configKeys", TASK_HUNTING_FREE_THIRD_SLOT); + registerEnumIn(L, "configKeys", TASK_HUNTING_LIMIT_EXHAUST); + registerEnumIn(L, "configKeys", TASK_HUNTING_REROLL_PRICE_LEVEL); + registerEnumIn(L, "configKeys", TASK_HUNTING_SELECTION_LIST_PRICE); + registerEnumIn(L, "configKeys", TASK_HUNTING_BONUS_REROLL_PRICE); + registerEnumIn(L, "configKeys", TASK_HUNTING_FREE_REROLL_TIME); + registerEnumIn(L, "configKeys", DEFAULT_DESPAWNRADIUS); + registerEnumIn(L, "configKeys", RATE_EXPERIENCE); + registerEnumIn(L, "configKeys", RATE_SKILL); + registerEnumIn(L, "configKeys", RATE_LOOT); + registerEnumIn(L, "configKeys", RATE_MAGIC); + registerEnumIn(L, "configKeys", RATE_SPAWN); + registerEnumIn(L, "configKeys", HOUSE_PRICE); + registerEnumIn(L, "configKeys", MAX_MESSAGEBUFFER); + registerEnumIn(L, "configKeys", ACTIONS_DELAY_INTERVAL); + registerEnumIn(L, "configKeys", EX_ACTIONS_DELAY_INTERVAL); + registerEnumIn(L, "configKeys", KICK_AFTER_MINUTES); + registerEnumIn(L, "configKeys", PROTECTION_LEVEL); + registerEnumIn(L, "configKeys", DEATH_LOSE_PERCENT); + registerEnumIn(L, "configKeys", STATUSQUERY_TIMEOUT); + registerEnumIn(L, "configKeys", FRAG_TIME); + registerEnumIn(L, "configKeys", WHITE_SKULL_TIME); + registerEnumIn(L, "configKeys", GAME_PORT); + registerEnumIn(L, "configKeys", LOGIN_PORT); + registerEnumIn(L, "configKeys", STATUS_PORT); + registerEnumIn(L, "configKeys", STAIRHOP_DELAY); + registerEnumIn(L, "configKeys", MARKET_OFFER_DURATION); + registerEnumIn(L, "configKeys", CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES); + registerEnumIn(L, "configKeys", MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER); + registerEnumIn(L, "configKeys", EXP_FROM_PLAYERS_LEVEL_RANGE); + registerEnumIn(L, "configKeys", MAX_PACKETS_PER_SECOND); + registerEnumIn(L, "configKeys", STORE_COIN_PACKET); + registerEnumIn(L, "configKeys", DAY_KILLS_TO_RED); + registerEnumIn(L, "configKeys", WEEK_KILLS_TO_RED); + registerEnumIn(L, "configKeys", MONTH_KILLS_TO_RED); + registerEnumIn(L, "configKeys", RED_SKULL_DURATION); + registerEnumIn(L, "configKeys", BLACK_SKULL_DURATION); + registerEnumIn(L, "configKeys", ORANGE_SKULL_DURATION); + registerEnumIn(L, "configKeys", RATE_MONSTER_HEALTH); + registerEnumIn(L, "configKeys", RATE_MONSTER_ATTACK); + registerEnumIn(L, "configKeys", RATE_MONSTER_DEFENSE); + registerEnumIn(L, "configKeys", RATE_NPC_HEALTH); + registerEnumIn(L, "configKeys", RATE_NPC_ATTACK); + registerEnumIn(L, "configKeys", RATE_NPC_DEFENSE); - registerEnumIn(L, "configKeys", RATE_HEALTH_REGEN) - registerEnumIn(L, "configKeys", RATE_HEALTH_REGEN_SPEED) - registerEnumIn(L, "configKeys", RATE_MANA_REGEN) - registerEnumIn(L, "configKeys", RATE_MANA_REGEN_SPEED) - registerEnumIn(L, "configKeys", RATE_SOUL_REGEN) - registerEnumIn(L, "configKeys", RATE_SOUL_REGEN_SPEED) + registerEnumIn(L, "configKeys", RATE_HEALTH_REGEN); + registerEnumIn(L, "configKeys", RATE_HEALTH_REGEN_SPEED); + registerEnumIn(L, "configKeys", RATE_MANA_REGEN); + registerEnumIn(L, "configKeys", RATE_MANA_REGEN_SPEED); + registerEnumIn(L, "configKeys", RATE_SOUL_REGEN); + registerEnumIn(L, "configKeys", RATE_SOUL_REGEN_SPEED); - registerEnumIn(L, "configKeys", RATE_SPELL_COOLDOWN) - registerEnumIn(L, "configKeys", RATE_ATTACK_SPEED) - registerEnumIn(L, "configKeys", RATE_OFFLINE_TRAINING_SPEED) - registerEnumIn(L, "configKeys", RATE_EXERCISE_TRAINING_SPEED) + registerEnumIn(L, "configKeys", RATE_SPELL_COOLDOWN); + registerEnumIn(L, "configKeys", RATE_ATTACK_SPEED); + registerEnumIn(L, "configKeys", RATE_OFFLINE_TRAINING_SPEED); + registerEnumIn(L, "configKeys", RATE_EXERCISE_TRAINING_SPEED); - registerEnumIn(L, "configKeys", STAMINA_TRAINER) - registerEnumIn(L, "configKeys", STAMINA_PZ) - registerEnumIn(L, "configKeys", STAMINA_ORANGE_DELAY) - registerEnumIn(L, "configKeys", STAMINA_GREEN_DELAY) - registerEnumIn(L, "configKeys", STAMINA_TRAINER_DELAY) - registerEnumIn(L, "configKeys", STAMINA_PZ_GAIN) - registerEnumIn(L, "configKeys", STAMINA_TRAINER_GAIN) - registerEnumIn(L, "configKeys", SORT_LOOT_BY_CHANCE) - registerEnumIn(L, "configKeys", MAX_ALLOWED_ON_A_DUMMY) + registerEnumIn(L, "configKeys", STAMINA_TRAINER); + registerEnumIn(L, "configKeys", STAMINA_PZ); + registerEnumIn(L, "configKeys", STAMINA_ORANGE_DELAY); + registerEnumIn(L, "configKeys", STAMINA_GREEN_DELAY); + registerEnumIn(L, "configKeys", STAMINA_TRAINER_DELAY); + registerEnumIn(L, "configKeys", STAMINA_PZ_GAIN); + registerEnumIn(L, "configKeys", STAMINA_TRAINER_GAIN); + registerEnumIn(L, "configKeys", SORT_LOOT_BY_CHANCE); + registerEnumIn(L, "configKeys", MAX_ALLOWED_ON_A_DUMMY); - registerEnumIn(L, "configKeys", PUSH_WHEN_ATTACKING) - registerEnumIn(L, "configKeys", TOGGLE_SAVE_INTERVAL) - registerEnumIn(L, "configKeys", SAVE_INTERVAL_TYPE) - registerEnumIn(L, "configKeys", TOGGLE_SAVE_INTERVAL_CLEAN_MAP) - registerEnumIn(L, "configKeys", SAVE_INTERVAL_TIME) - registerEnumIn(L, "configKeys", RATE_USE_STAGES) - registerEnumIn(L, "configKeys", TOGGLE_IMBUEMENT_SHRINE_STORAGE) - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_TIME) - registerEnumIn(L, "configKeys", DATA_DIRECTORY) - registerEnumIn(L, "configKeys", CORE_DIRECTORY) + registerEnumIn(L, "configKeys", PUSH_WHEN_ATTACKING); + registerEnumIn(L, "configKeys", TOGGLE_SAVE_INTERVAL); + registerEnumIn(L, "configKeys", SAVE_INTERVAL_TYPE); + registerEnumIn(L, "configKeys", TOGGLE_SAVE_INTERVAL_CLEAN_MAP); + registerEnumIn(L, "configKeys", SAVE_INTERVAL_TIME); + registerEnumIn(L, "configKeys", RATE_USE_STAGES); + registerEnumIn(L, "configKeys", TOGGLE_IMBUEMENT_SHRINE_STORAGE); + registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_TIME); + registerEnumIn(L, "configKeys", DATA_DIRECTORY); + registerEnumIn(L, "configKeys", CORE_DIRECTORY); - registerEnumIn(L, "configKeys", FORGE_COST_ONE_SLIVER) - registerEnumIn(L, "configKeys", FORGE_SLIVER_AMOUNT) - registerEnumIn(L, "configKeys", FORGE_CORE_COST) - registerEnumIn(L, "configKeys", FORGE_MAX_DUST) - registerEnumIn(L, "configKeys", FORGE_FUSION_DUST_COST) - registerEnumIn(L, "configKeys", FORGE_TRANSFER_DUST_COST) - registerEnumIn(L, "configKeys", FORGE_BASE_SUCCESS_RATE) - registerEnumIn(L, "configKeys", FORGE_BONUS_SUCCESS_RATE) - registerEnumIn(L, "configKeys", FORGE_TIER_LOSS_REDUCTION) - registerEnumIn(L, "configKeys", FORGE_INFLUENCED_CREATURES_LIMIT) + registerEnumIn(L, "configKeys", FORGE_COST_ONE_SLIVER); + registerEnumIn(L, "configKeys", FORGE_SLIVER_AMOUNT); + registerEnumIn(L, "configKeys", FORGE_CORE_COST); + registerEnumIn(L, "configKeys", FORGE_MAX_DUST); + registerEnumIn(L, "configKeys", FORGE_FUSION_DUST_COST); + registerEnumIn(L, "configKeys", FORGE_TRANSFER_DUST_COST); + registerEnumIn(L, "configKeys", FORGE_BASE_SUCCESS_RATE); + registerEnumIn(L, "configKeys", FORGE_BONUS_SUCCESS_RATE); + registerEnumIn(L, "configKeys", FORGE_TIER_LOSS_REDUCTION); + registerEnumIn(L, "configKeys", FORGE_INFLUENCED_CREATURES_LIMIT); - #undef registerEnumIn +#undef registerEnumIn } int ConfigFunctions::luaConfigManagerGetString(lua_State* L) { diff --git a/src/lua/functions/core/game/config_functions.hpp b/src/lua/functions/core/game/config_functions.hpp index 8f6c8ea20be..d72f2557ee2 100644 --- a/src/lua/functions/core/game/config_functions.hpp +++ b/src/lua/functions/core/game/config_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_GAME_CONFIG_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_GAME_CONFIG_FUNCTIONS_HPP_ @@ -24,4 +24,4 @@ class ConfigFunctions final : LuaScriptInterface { static int luaConfigManagerGetString(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_GAME_CONFIG_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_GAME_CONFIG_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/game/core_game_functions.hpp b/src/lua/functions/core/game/core_game_functions.hpp index d3170b17eb4..b2945ed0aeb 100644 --- a/src/lua/functions/core/game/core_game_functions.hpp +++ b/src/lua/functions/core/game/core_game_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_GAME_CORE_GAME_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_GAME_CORE_GAME_FUNCTIONS_HPP_ @@ -28,6 +28,6 @@ class CoreGameFunctions final : LuaScriptInterface { } private: - }; +}; -#endif // SRC_LUA_FUNCTIONS_CORE_GAME_CORE_GAME_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_GAME_CORE_GAME_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/game/game_functions.cpp b/src/lua/functions/core/game/game_functions.cpp index 1db74c45a6a..f785d3d7c74 100644 --- a/src/lua/functions/core/game/game_functions.cpp +++ b/src/lua/functions/core/game/game_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -51,7 +51,7 @@ int GameFunctions::luaGameCreateNpcType(lua_State* L) { int GameFunctions::luaGameGetSpectators(lua_State* L) { // Game.getSpectators(position[, multifloor = false[, onlyPlayer = false[, minRangeX = 0[, maxRangeX = 0[, minRangeY = 0[, maxRangeY = 0]]]]]]) - const Position& position = getPosition(L, 1); + const Position &position = getPosition(L, 1); bool multifloor = getBoolean(L, 2, false); bool onlyPlayers = getBoolean(L, 3, false); int32_t minRangeX = getNumber(L, 4, 0); @@ -90,33 +90,28 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { for (auto ita : mtype_list) { if (name) { pushString(L, ita.second); - } - else { + } else { lua_pushnumber(L, ita.first); } lua_rawseti(L, -2, ++index); } - } - else { + } else { if (isNumber(L, 2)) { std::map tmplist = g_iobestiary().findRaceByName("CANARY", false, getNumber(L, 2)); for (auto itb : tmplist) { if (name) { pushString(L, itb.second); - } - else { + } else { lua_pushnumber(L, itb.first); } lua_rawseti(L, -2, ++index); } - } - else { + } else { std::map tmplist = g_iobestiary().findRaceByName(getString(L, 2)); for (auto itc : tmplist) { if (name) { pushString(L, itc.second); - } - else { + } else { lua_pushnumber(L, itc.first); } lua_rawseti(L, -2, ++index); @@ -131,7 +126,7 @@ int GameFunctions::luaGameGetPlayers(lua_State* L) { lua_createtable(L, g_game().getPlayersOnline(), 0); int index = 0; - for (const auto& playerEntry : g_game().getPlayers()) { + for (const auto &playerEntry : g_game().getPlayers()) { pushUserdata(L, playerEntry.second); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); @@ -141,17 +136,17 @@ int GameFunctions::luaGameGetPlayers(lua_State* L) { int GameFunctions::luaGameLoadMap(lua_State* L) { // Game.loadMap(path) - const std::string& path = getString(L, 1); - g_dispatcher().addTask(createTask([path]() {g_game().loadMap(path); })); + const std::string &path = getString(L, 1); + g_dispatcher().addTask(createTask([path]() { g_game().loadMap(path); })); return 0; } int GameFunctions::luaGameloadMapChunk(lua_State* L) { // Game.loadMapChunk(path, position, remove) - const std::string& path = getString(L, 1); - const Position& position = getPosition(L, 2); + const std::string &path = getString(L, 1); + const Position &position = getPosition(L, 2); bool unload = getBoolean(L, 3); - g_dispatcher().addTask(createTask([path, position, unload]() {g_game().loadMap(path, position, unload); })); + g_dispatcher().addTask(createTask([path, position, unload]() { g_game().loadMap(path, position, unload); })); return 0; } @@ -175,10 +170,10 @@ int GameFunctions::luaGameGetNpcCount(lua_State* L) { int GameFunctions::luaGameGetMonsterTypes(lua_State* L) { // Game.getMonsterTypes() - auto& type = g_monsters().monsters; + auto &type = g_monsters().monsters; lua_createtable(L, type.size(), 0); - for (auto& mType : type) { + for (auto &mType : type) { pushUserdata(L, mType.second); setMetatable(L, -1, "MonsterType"); lua_setfield(L, -2, mType.first.c_str()); @@ -188,7 +183,7 @@ int GameFunctions::luaGameGetMonsterTypes(lua_State* L) { int GameFunctions::luaGameGetTowns(lua_State* L) { // Game.getTowns() - const auto& towns = g_game().map.towns.getTowns(); + const auto &towns = g_game().map.towns.getTowns(); lua_createtable(L, towns.size(), 0); int index = 0; @@ -202,7 +197,7 @@ int GameFunctions::luaGameGetTowns(lua_State* L) { int GameFunctions::luaGameGetHouses(lua_State* L) { // Game.getHouses() - const auto& houses = g_game().map.houses.getHouses(); + const auto &houses = g_game().map.houses.getHouses(); lua_createtable(L, houses.size(), 0); int index = 0; @@ -266,7 +261,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { int32_t itemCount = 1; int32_t subType = 1; - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.hasSubType()) { if (it.stackable) { itemCount = std::ceil(count / 100.f); @@ -364,7 +359,7 @@ int GameFunctions::luaGameCreateContainer(lua_State* L) { } if (lua_gettop(L) >= 3) { - const Position& position = getPosition(L, 3); + const Position &position = getPosition(L, 3); Tile* tile = g_game().map.getTile(position); if (!tile) { delete container; @@ -400,7 +395,7 @@ int GameFunctions::luaGameCreateMonster(lua_State* L) { } } - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); bool extended = getBoolean(L, 3, false); bool force = getBoolean(L, 4, false); if (g_game().placeCreature(monster, position, extended, force)) { @@ -438,7 +433,7 @@ int GameFunctions::luaGameCreateNpc(lua_State* L) { return 1; } - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); bool extended = getBoolean(L, 3, false); bool force = getBoolean(L, 4, false); if (g_game().placeCreature(npc, position, extended, force)) { @@ -488,7 +483,7 @@ int GameFunctions::luaGameGetBestiaryCharm(lua_State* L) { lua_createtable(L, c_list.size(), 0); int index = 0; - for (auto& it : c_list) { + for (auto &it : c_list) { pushUserdata(L, it); setMetatable(L, -1, "Charm"); lua_rawseti(L, -2, ++index); @@ -521,7 +516,7 @@ int GameFunctions::luaGameCreateItemClassification(lua_State* L) { int GameFunctions::luaGameStartRaid(lua_State* L) { // Game.startRaid(raidName) - const std::string& raidName = getString(L, 1); + const std::string &raidName = getString(L, 1); Raid* raid = g_game().raids.getRaidByName(raidName); if (!raid || !raid->isLoaded()) { @@ -545,7 +540,7 @@ int GameFunctions::luaGameGetClientVersion(lua_State* L) { lua_createtable(L, 0, 3); setField(L, "min", CLIENT_VERSION); setField(L, "max", CLIENT_VERSION); - std::string version = fmt::format("{}.{}",CLIENT_VERSION_UPPER,CLIENT_VERSION_LOWER); + std::string version = fmt::format("{}.{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER); setField(L, "string", version); return 1; } @@ -599,9 +594,9 @@ int GameFunctions::luaGameGetOfflinePlayer(lua_State* L) { return 1; } -int GameFunctions::luaGameAddInfluencedMonster(lua_State *L) { +int GameFunctions::luaGameAddInfluencedMonster(lua_State* L) { // Game.addInfluencedMonster(monster) - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -612,7 +607,7 @@ int GameFunctions::luaGameAddInfluencedMonster(lua_State *L) { return 1; } -int GameFunctions::luaGameRemoveInfluencedMonster(lua_State *L) { +int GameFunctions::luaGameRemoveInfluencedMonster(lua_State* L) { // Game.removeInfluencedMonster(monsterId) uint32_t monsterId = getNumber(L, 1); auto create = getBoolean(L, 2, false); @@ -620,7 +615,7 @@ int GameFunctions::luaGameRemoveInfluencedMonster(lua_State *L) { return 1; } -int GameFunctions::luaGameGetInfluencedMonsters(lua_State *L) { +int GameFunctions::luaGameGetInfluencedMonsters(lua_State* L) { // Game.getInfluencedMonsters() const auto monsters = g_game().getInfluencedMonsters(); lua_createtable(L, static_cast(monsters.size()), 0); @@ -634,7 +629,7 @@ int GameFunctions::luaGameGetInfluencedMonsters(lua_State *L) { return 1; } -int GameFunctions::luaGameMakeFiendishMonster(lua_State *L) { +int GameFunctions::luaGameMakeFiendishMonster(lua_State* L) { // Game.makeFiendishMonster(monsterId[default= 0]) uint32_t monsterId = getNumber(L, 1, 0); auto createForgeableMonsters = getBoolean(L, 2, false); @@ -642,7 +637,7 @@ int GameFunctions::luaGameMakeFiendishMonster(lua_State *L) { return 1; } -int GameFunctions::luaGameRemoveFiendishMonster(lua_State *L) { +int GameFunctions::luaGameRemoveFiendishMonster(lua_State* L) { // Game.removeFiendishMonster(monsterId) uint32_t monsterId = getNumber(L, 1); auto create = getBoolean(L, 2, false); @@ -650,7 +645,7 @@ int GameFunctions::luaGameRemoveFiendishMonster(lua_State *L) { return 1; } -int GameFunctions::luaGameGetFiendishMonsters(lua_State *L) { +int GameFunctions::luaGameGetFiendishMonsters(lua_State* L) { // Game.getFiendishMonsters() const auto monsters = g_game().getFiendishMonsters(); diff --git a/src/lua/functions/core/game/game_functions.hpp b/src/lua/functions/core/game/game_functions.hpp index cddc639eef5..262a78a1b3d 100644 --- a/src/lua/functions/core/game/game_functions.hpp +++ b/src/lua/functions/core/game/game_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_GAME_GAME_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_GAME_GAME_FUNCTIONS_HPP_ @@ -14,124 +14,124 @@ class GameFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerTable(L, "Game"); + static void init(lua_State* L) { + registerTable(L, "Game"); - registerMethod(L, "Game", "createNpcType", GameFunctions::luaGameCreateNpcType); - registerMethod(L, "Game", "createMonsterType", GameFunctions::luaGameCreateMonsterType); + registerMethod(L, "Game", "createNpcType", GameFunctions::luaGameCreateNpcType); + registerMethod(L, "Game", "createMonsterType", GameFunctions::luaGameCreateMonsterType); - registerMethod(L, "Game", "getSpectators", GameFunctions::luaGameGetSpectators); + registerMethod(L, "Game", "getSpectators", GameFunctions::luaGameGetSpectators); - registerMethod(L, "Game", "getBoostedCreature", GameFunctions::luaGameGetBoostedCreature); - registerMethod(L, "Game", "getBestiaryList", GameFunctions::luaGameGetBestiaryList); + registerMethod(L, "Game", "getBoostedCreature", GameFunctions::luaGameGetBoostedCreature); + registerMethod(L, "Game", "getBestiaryList", GameFunctions::luaGameGetBestiaryList); - registerMethod(L, "Game", "getPlayers", GameFunctions::luaGameGetPlayers); - registerMethod(L, "Game", "loadMap", GameFunctions::luaGameLoadMap); - registerMethod(L, "Game", "loadMapChunk", GameFunctions::luaGameloadMapChunk); + registerMethod(L, "Game", "getPlayers", GameFunctions::luaGameGetPlayers); + registerMethod(L, "Game", "loadMap", GameFunctions::luaGameLoadMap); + registerMethod(L, "Game", "loadMapChunk", GameFunctions::luaGameloadMapChunk); - registerMethod(L, "Game", "getMonsterCount", GameFunctions::luaGameGetMonsterCount); - registerMethod(L, "Game", "getPlayerCount", GameFunctions::luaGameGetPlayerCount); - registerMethod(L, "Game", "getNpcCount", GameFunctions::luaGameGetNpcCount); - registerMethod(L, "Game", "getMonsterTypes", GameFunctions::luaGameGetMonsterTypes); + registerMethod(L, "Game", "getMonsterCount", GameFunctions::luaGameGetMonsterCount); + registerMethod(L, "Game", "getPlayerCount", GameFunctions::luaGameGetPlayerCount); + registerMethod(L, "Game", "getNpcCount", GameFunctions::luaGameGetNpcCount); + registerMethod(L, "Game", "getMonsterTypes", GameFunctions::luaGameGetMonsterTypes); - registerMethod(L, "Game", "getTowns", GameFunctions::luaGameGetTowns); - registerMethod(L, "Game", "getHouses", GameFunctions::luaGameGetHouses); + registerMethod(L, "Game", "getTowns", GameFunctions::luaGameGetTowns); + registerMethod(L, "Game", "getHouses", GameFunctions::luaGameGetHouses); - registerMethod(L, "Game", "getGameState", GameFunctions::luaGameGetGameState); - registerMethod(L, "Game", "setGameState", GameFunctions::luaGameSetGameState); + registerMethod(L, "Game", "getGameState", GameFunctions::luaGameGetGameState); + registerMethod(L, "Game", "setGameState", GameFunctions::luaGameSetGameState); - registerMethod(L, "Game", "getWorldType", GameFunctions::luaGameGetWorldType); - registerMethod(L, "Game", "setWorldType", GameFunctions::luaGameSetWorldType); + registerMethod(L, "Game", "getWorldType", GameFunctions::luaGameGetWorldType); + registerMethod(L, "Game", "setWorldType", GameFunctions::luaGameSetWorldType); - registerMethod(L, "Game", "getReturnMessage", GameFunctions::luaGameGetReturnMessage); + registerMethod(L, "Game", "getReturnMessage", GameFunctions::luaGameGetReturnMessage); - registerMethod(L, "Game", "createItem", GameFunctions::luaGameCreateItem); - registerMethod(L, "Game", "createContainer", GameFunctions::luaGameCreateContainer); - registerMethod(L, "Game", "createMonster", GameFunctions::luaGameCreateMonster); - registerMethod(L, "Game", "createNpc", GameFunctions::luaGameCreateNpc); - registerMethod(L, "Game", "generateNpc", GameFunctions::luaGameGenerateNpc); - registerMethod(L, "Game", "createTile", GameFunctions::luaGameCreateTile); - registerMethod(L, "Game", "createBestiaryCharm", GameFunctions::luaGameCreateBestiaryCharm); + registerMethod(L, "Game", "createItem", GameFunctions::luaGameCreateItem); + registerMethod(L, "Game", "createContainer", GameFunctions::luaGameCreateContainer); + registerMethod(L, "Game", "createMonster", GameFunctions::luaGameCreateMonster); + registerMethod(L, "Game", "createNpc", GameFunctions::luaGameCreateNpc); + registerMethod(L, "Game", "generateNpc", GameFunctions::luaGameGenerateNpc); + registerMethod(L, "Game", "createTile", GameFunctions::luaGameCreateTile); + registerMethod(L, "Game", "createBestiaryCharm", GameFunctions::luaGameCreateBestiaryCharm); - registerMethod(L, "Game", "createItemClassification", GameFunctions::luaGameCreateItemClassification); + registerMethod(L, "Game", "createItemClassification", GameFunctions::luaGameCreateItemClassification); - registerMethod(L, "Game", "getBestiaryCharm", GameFunctions::luaGameGetBestiaryCharm); + registerMethod(L, "Game", "getBestiaryCharm", GameFunctions::luaGameGetBestiaryCharm); - registerMethod(L, "Game", "startRaid", GameFunctions::luaGameStartRaid); + registerMethod(L, "Game", "startRaid", GameFunctions::luaGameStartRaid); - registerMethod(L, "Game", "getClientVersion", GameFunctions::luaGameGetClientVersion); + registerMethod(L, "Game", "getClientVersion", GameFunctions::luaGameGetClientVersion); - registerMethod(L, "Game", "reload", GameFunctions::luaGameReload); + registerMethod(L, "Game", "reload", GameFunctions::luaGameReload); - registerMethod(L, "Game", "hasDistanceEffect", GameFunctions::luaGameHasDistanceEffect); - registerMethod(L, "Game", "hasEffect", GameFunctions::luaGameHasEffect); - registerMethod(L, "Game", "getOfflinePlayer", GameFunctions::luaGameGetOfflinePlayer); + registerMethod(L, "Game", "hasDistanceEffect", GameFunctions::luaGameHasDistanceEffect); + registerMethod(L, "Game", "hasEffect", GameFunctions::luaGameHasEffect); + registerMethod(L, "Game", "getOfflinePlayer", GameFunctions::luaGameGetOfflinePlayer); - registerMethod(L, "Game", "addInfluencedMonster", GameFunctions::luaGameAddInfluencedMonster); - registerMethod(L, "Game", "removeInfluencedMonster", GameFunctions::luaGameRemoveInfluencedMonster); - registerMethod(L, "Game", "getInfluencedMonsters", GameFunctions::luaGameGetInfluencedMonsters); - registerMethod(L, "Game", "makeFiendishMonster", GameFunctions::luaGameMakeFiendishMonster); - registerMethod(L, "Game", "removeFiendishMonster", GameFunctions::luaGameRemoveFiendishMonster); - registerMethod(L, "Game", "getFiendishMonsters", GameFunctions::luaGameGetFiendishMonsters); - } + registerMethod(L, "Game", "addInfluencedMonster", GameFunctions::luaGameAddInfluencedMonster); + registerMethod(L, "Game", "removeInfluencedMonster", GameFunctions::luaGameRemoveInfluencedMonster); + registerMethod(L, "Game", "getInfluencedMonsters", GameFunctions::luaGameGetInfluencedMonsters); + registerMethod(L, "Game", "makeFiendishMonster", GameFunctions::luaGameMakeFiendishMonster); + registerMethod(L, "Game", "removeFiendishMonster", GameFunctions::luaGameRemoveFiendishMonster); + registerMethod(L, "Game", "getFiendishMonsters", GameFunctions::luaGameGetFiendishMonsters); + } private: - static int luaGameCreateMonsterType(lua_State* L); - static int luaGameCreateNpcType(lua_State* L); + static int luaGameCreateMonsterType(lua_State* L); + static int luaGameCreateNpcType(lua_State* L); - static int luaGameGetSpectators(lua_State* L); + static int luaGameGetSpectators(lua_State* L); - static int luaGameGetBoostedCreature(lua_State* L); - static int luaGameGetBestiaryList(lua_State* L); + static int luaGameGetBoostedCreature(lua_State* L); + static int luaGameGetBestiaryList(lua_State* L); - static int luaGameGetPlayers(lua_State* L); - static int luaGameLoadMap(lua_State* L); - static int luaGameloadMapChunk(lua_State* L); + static int luaGameGetPlayers(lua_State* L); + static int luaGameLoadMap(lua_State* L); + static int luaGameloadMapChunk(lua_State* L); - static int luaGameGetMonsterCount(lua_State* L); - static int luaGameGetPlayerCount(lua_State* L); - static int luaGameGetNpcCount(lua_State* L); - static int luaGameGetMonsterTypes(lua_State* L); + static int luaGameGetMonsterCount(lua_State* L); + static int luaGameGetPlayerCount(lua_State* L); + static int luaGameGetNpcCount(lua_State* L); + static int luaGameGetMonsterTypes(lua_State* L); - static int luaGameGetTowns(lua_State* L); - static int luaGameGetHouses(lua_State* L); + static int luaGameGetTowns(lua_State* L); + static int luaGameGetHouses(lua_State* L); - static int luaGameGetGameState(lua_State* L); - static int luaGameSetGameState(lua_State* L); + static int luaGameGetGameState(lua_State* L); + static int luaGameSetGameState(lua_State* L); - static int luaGameGetWorldType(lua_State* L); - static int luaGameSetWorldType(lua_State* L); + static int luaGameGetWorldType(lua_State* L); + static int luaGameSetWorldType(lua_State* L); - static int luaGameGetReturnMessage(lua_State* L); + static int luaGameGetReturnMessage(lua_State* L); - static int luaGameCreateItem(lua_State* L); - static int luaGameCreateContainer(lua_State* L); - static int luaGameCreateMonster(lua_State* L); - static int luaGameGenerateNpc(lua_State* L); - static int luaGameCreateNpc(lua_State* L); - static int luaGameCreateTile(lua_State* L); + static int luaGameCreateItem(lua_State* L); + static int luaGameCreateContainer(lua_State* L); + static int luaGameCreateMonster(lua_State* L); + static int luaGameGenerateNpc(lua_State* L); + static int luaGameCreateNpc(lua_State* L); + static int luaGameCreateTile(lua_State* L); - static int luaGameGetBestiaryCharm(lua_State* L); - static int luaGameCreateBestiaryCharm(lua_State* L); + static int luaGameGetBestiaryCharm(lua_State* L); + static int luaGameCreateBestiaryCharm(lua_State* L); - static int luaGameCreateItemClassification(lua_State* L); + static int luaGameCreateItemClassification(lua_State* L); - static int luaGameStartRaid(lua_State* L); + static int luaGameStartRaid(lua_State* L); - static int luaGameGetClientVersion(lua_State* L); + static int luaGameGetClientVersion(lua_State* L); - static int luaGameReload(lua_State* L); + static int luaGameReload(lua_State* L); - static int luaGameGetOfflinePlayer(lua_State* L); - static int luaGameHasEffect(lua_State* L); - static int luaGameHasDistanceEffect(lua_State* L); + static int luaGameGetOfflinePlayer(lua_State* L); + static int luaGameHasEffect(lua_State* L); + static int luaGameHasDistanceEffect(lua_State* L); - static int luaGameAddInfluencedMonster(lua_State *L); - static int luaGameRemoveInfluencedMonster(lua_State *L); - static int luaGameGetInfluencedMonsters(lua_State *L); - static int luaGameMakeFiendishMonster(lua_State *L); - static int luaGameRemoveFiendishMonster(lua_State *L); - static int luaGameGetFiendishMonsters(lua_State *L); + static int luaGameAddInfluencedMonster(lua_State* L); + static int luaGameRemoveInfluencedMonster(lua_State* L); + static int luaGameGetInfluencedMonsters(lua_State* L); + static int luaGameMakeFiendishMonster(lua_State* L); + static int luaGameRemoveFiendishMonster(lua_State* L); + static int luaGameGetFiendishMonsters(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_GAME_GAME_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_GAME_GAME_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 388577f6cff..80c1c988b74 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -33,7 +33,7 @@ int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { bool canDropOnMap = getBoolean(L, 4, true); uint16_t subType = getNumber(L, 5, 1); - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; int32_t itemCount; auto parameters = lua_gettop(L); @@ -144,7 +144,7 @@ int GlobalFunctions::luaDoAddContainerItem(lua_State* L) { } uint16_t itemId = getNumber(L, 2); - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; int32_t itemCount = 1; int32_t subType = 1; @@ -336,8 +336,7 @@ int GlobalFunctions::luaDoTargetCombatHealth(lua_State* L) { damage.primary.value = normal_random(getNumber(L, 4), getNumber(L, 5)); // Check if it's a healing then we sould add the non-aggresive tag - if (combatType == COMBAT_HEALING || - (combatType == COMBAT_MANADRAIN && damage.primary.value > 0)) { + if (combatType == COMBAT_HEALING || (combatType == COMBAT_MANADRAIN && damage.primary.value > 0)) { params.aggressive = false; } @@ -565,7 +564,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaDataType type = getNumber(L, -1); if (type != LuaData_Unknown && type != LuaData_Tile) { - indexes.push_back({i, type}); + indexes.push_back({ i, type }); } lua_pop(globalState, 2); } @@ -579,7 +578,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { warningString += 's'; } - for (const auto& entry : indexes) { + for (const auto &entry : indexes) { if (entry == indexes.front()) { warningString += ' '; } else if (entry == indexes.back()) { @@ -601,7 +600,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { } if (g_configManager().getBoolean(CONVERT_UNSAFE_SCRIPTS)) { - for (const auto& entry : indexes) { + for (const auto &entry : indexes) { switch (entry.second) { case LuaData_Item: case LuaData_Container: @@ -640,9 +639,9 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { eventDesc.function = luaL_ref(globalState, LUA_REGISTRYINDEX); eventDesc.scriptId = getScriptEnv()->getScriptId(); - auto& lastTimerEventId = g_luaEnvironment.lastEventTimerId; + auto &lastTimerEventId = g_luaEnvironment.lastEventTimerId; eventDesc.eventId = g_scheduler().addEvent(createSchedulerTask( - delay, std::bind(&LuaEnvironment::executeTimerEvent, &g_luaEnvironment, lastTimerEventId) + delay, std::bind(&LuaEnvironment::executeTimerEvent, &g_luaEnvironment, lastTimerEventId) )); g_luaEnvironment.timerEvents.emplace(lastTimerEventId, std::move(eventDesc)); @@ -661,7 +660,7 @@ int GlobalFunctions::luaStopEvent(lua_State* L) { uint32_t eventId = getNumber(L, 1); - auto& timerEvents = g_luaEnvironment.timerEvents; + auto &timerEvents = g_luaEnvironment.timerEvents; auto it = timerEvents.find(eventId); if (it == timerEvents.end()) { pushBoolean(L, false); @@ -721,7 +720,7 @@ int GlobalFunctions::luaIsInWar(lua_State* L) { int GlobalFunctions::luaGetWaypointPositionByName(lua_State* L) { // getWaypointPositionByName(name) - auto& waypoints = g_game().map.waypoints; + auto &waypoints = g_game().map.waypoints; auto it = waypoints.find(getString(L, -1)); if (it != waypoints.end()) { @@ -807,7 +806,7 @@ int GlobalFunctions::luaSystemTime(lua_State* L) { return 1; } -bool GlobalFunctions::getArea(lua_State* L, std::list& list, uint32_t& rows) { +bool GlobalFunctions::getArea(lua_State* L, std::list &list, uint32_t &rows) { lua_pushnil(L); for (rows = 0; lua_next(L, -2) != 0; ++rows) { if (!isTable(L, -1)) { diff --git a/src/lua/functions/core/game/global_functions.hpp b/src/lua/functions/core/game/global_functions.hpp index 16f8ae8ea29..ba814f06cd5 100644 --- a/src/lua/functions/core/game/global_functions.hpp +++ b/src/lua/functions/core/game/global_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_GAME_GLOBAL_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_GAME_GLOBAL_FUNCTIONS_HPP_ @@ -88,7 +88,7 @@ class GlobalFunctions final : LuaScriptInterface { static int luaCreateTable(lua_State* L); static int luaSystemTime(lua_State* L); - static bool getArea(lua_State* L, std::list& list, uint32_t& rows); + static bool getArea(lua_State* L, std::list &list, uint32_t &rows); }; -#endif // SRC_LUA_FUNCTIONS_CORE_GAME_GLOBAL_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_GAME_GLOBAL_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/game/lua_enums.cpp b/src/lua/functions/core/game/lua_enums.cpp index 0d4c0f3cd7b..7d8591ac382 100644 --- a/src/lua/functions/core/game/lua_enums.cpp +++ b/src/lua/functions/core/game/lua_enums.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -20,16 +20,20 @@ #include "game/functions/game_reload.hpp" #include "game/game.h" -#define registerEnumClass(luaState, enumClassType) { \ - auto number = magic_enum::enum_integer(enumClassType); \ - auto name = magic_enum::enum_name(enumClassType).data(); \ - registerGlobalVariable(luaState, name, number); \ -} void(0) - -#define registerEnum(L, value) { \ - std::string enumName = #value; \ - registerGlobalVariable(L, enumName.substr(enumName.find_last_of(':') + 1), value); \ -} void(0) +#define registerEnumClass(luaState, enumClassType) \ + { \ + auto number = magic_enum::enum_integer(enumClassType); \ + auto name = magic_enum::enum_name(enumClassType).data(); \ + registerGlobalVariable(luaState, name, number); \ + } \ + void(0) + +#define registerEnum(L, value) \ + { \ + std::string enumName = #value; \ + registerGlobalVariable(L, enumName.substr(enumName.find_last_of(':') + 1), value); \ + } \ + void(0) void LuaEnums::init(lua_State* L) { initOthersEnums(L); @@ -121,7 +125,7 @@ void LuaEnums::initOthersEnums(lua_State* L) { registerEnum(L, ORIGIN_SPELL); registerEnum(L, ORIGIN_MELEE); registerEnum(L, ORIGIN_RANGED); - + registerEnum(L, PLAYERSEX_FEMALE); registerEnum(L, PLAYERSEX_MALE); diff --git a/src/lua/functions/core/game/lua_enums.hpp b/src/lua/functions/core/game/lua_enums.hpp index 0f6421f7c61..9c3b79fd45c 100644 --- a/src/lua/functions/core/game/lua_enums.hpp +++ b/src/lua/functions/core/game/lua_enums.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_GAME_LUA_ENUMS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_GAME_LUA_ENUMS_HPP_ @@ -17,51 +17,52 @@ #include "lua/scripts/luascript.h" class LuaEnums final : LuaScriptInterface { -public: - static void init(lua_State* L); -private: - static void initOthersEnums(lua_State* L); - static void initAccountEnums(lua_State* L); - static void initDailyRewardEnums(lua_State* L); - static void initBugCategoryEnums(lua_State* L); - static void initReportTypeEnums(lua_State* L); - static void initCallbackParamEnums(lua_State* L); - static void initCombatEnums(lua_State* L); - static void initCombatParamEnums(lua_State* L); - static void initCombatFormulaEnums(lua_State* L); - static void initDirectionEnums(lua_State* L); - static void initFactionEnums(lua_State* L); - static void initConditionEnums(lua_State* L); - static void initConditionIdEnums(lua_State* L); - static void initConditionParamEnums(lua_State* L); - static void initConstMeEnums(lua_State* L); - static void initConstAniEnums(lua_State* L); - static void initConstPropEnums(lua_State* L); - static void initConstSlotEnums(lua_State* L); - static void initCreatureEventEnums(lua_State* L); - static void initGameStateEnums(lua_State* L); - static void initMessageEnums(lua_State* L); - static void initCreatureTypeEnums(lua_State* L); - static void initClientOsEnums(lua_State* L); - static void initFightModeEnums(lua_State* L); - static void initItemAttributeEnums(lua_State* L); - static void initItemTypeEnums(lua_State* L); - static void initItemIdEnums(lua_State* L); - static void initPlayerFlagEnums(lua_State* L); - static void initReportReasonEnums(lua_State* L); - static void initSkillEnums(lua_State* L); - static void initSkullEnums(lua_State* L); - static void initTalkTypeEnums(lua_State* L); - static void initBestiaryEnums(lua_State* L); - static void initTextColorEnums(lua_State* L); - static void initTileStateEnums(lua_State* L); - static void initSpeechBubbleEnums(lua_State* L); - static void initMapMarkEnums(lua_State* L); - static void initReturnValueEnums(lua_State* L); - static void initReloadTypeEnums(lua_State* L); - static void initCreaturesEventEnums(lua_State* L); - static void initForgeEnums(lua_State* L); - static void initWebhookEnums(lua_State* L); + public: + static void init(lua_State* L); + + private: + static void initOthersEnums(lua_State* L); + static void initAccountEnums(lua_State* L); + static void initDailyRewardEnums(lua_State* L); + static void initBugCategoryEnums(lua_State* L); + static void initReportTypeEnums(lua_State* L); + static void initCallbackParamEnums(lua_State* L); + static void initCombatEnums(lua_State* L); + static void initCombatParamEnums(lua_State* L); + static void initCombatFormulaEnums(lua_State* L); + static void initDirectionEnums(lua_State* L); + static void initFactionEnums(lua_State* L); + static void initConditionEnums(lua_State* L); + static void initConditionIdEnums(lua_State* L); + static void initConditionParamEnums(lua_State* L); + static void initConstMeEnums(lua_State* L); + static void initConstAniEnums(lua_State* L); + static void initConstPropEnums(lua_State* L); + static void initConstSlotEnums(lua_State* L); + static void initCreatureEventEnums(lua_State* L); + static void initGameStateEnums(lua_State* L); + static void initMessageEnums(lua_State* L); + static void initCreatureTypeEnums(lua_State* L); + static void initClientOsEnums(lua_State* L); + static void initFightModeEnums(lua_State* L); + static void initItemAttributeEnums(lua_State* L); + static void initItemTypeEnums(lua_State* L); + static void initItemIdEnums(lua_State* L); + static void initPlayerFlagEnums(lua_State* L); + static void initReportReasonEnums(lua_State* L); + static void initSkillEnums(lua_State* L); + static void initSkullEnums(lua_State* L); + static void initTalkTypeEnums(lua_State* L); + static void initBestiaryEnums(lua_State* L); + static void initTextColorEnums(lua_State* L); + static void initTileStateEnums(lua_State* L); + static void initSpeechBubbleEnums(lua_State* L); + static void initMapMarkEnums(lua_State* L); + static void initReturnValueEnums(lua_State* L); + static void initReloadTypeEnums(lua_State* L); + static void initCreaturesEventEnums(lua_State* L); + static void initForgeEnums(lua_State* L); + static void initWebhookEnums(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_GAME_LUA_ENUMS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_GAME_LUA_ENUMS_HPP_ diff --git a/src/lua/functions/core/game/modal_window_functions.cpp b/src/lua/functions/core/game/modal_window_functions.cpp index e00b3e3bd94..769768aca33 100644 --- a/src/lua/functions/core/game/modal_window_functions.cpp +++ b/src/lua/functions/core/game/modal_window_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,219 +14,219 @@ // ModalWindow int ModalWindowFunctions::luaModalWindowCreate(lua_State* L) { - // ModalWindow(id, title, message) - const std::string& message = getString(L, 4); - const std::string& title = getString(L, 3); - uint32_t id = getNumber(L, 2); + // ModalWindow(id, title, message) + const std::string &message = getString(L, 4); + const std::string &title = getString(L, 3); + uint32_t id = getNumber(L, 2); - pushUserdata(L, new ModalWindow(id, title, message)); - setMetatable(L, -1, "ModalWindow"); - return 1; + pushUserdata(L, new ModalWindow(id, title, message)); + setMetatable(L, -1, "ModalWindow"); + return 1; } int ModalWindowFunctions::luaModalWindowDelete(lua_State* L) { - ModalWindow** windowPtr = getRawUserdata(L, 1); - if (windowPtr && *windowPtr) { - delete *windowPtr; - *windowPtr = nullptr; - } - return 0; + ModalWindow** windowPtr = getRawUserdata(L, 1); + if (windowPtr && *windowPtr) { + delete *windowPtr; + *windowPtr = nullptr; + } + return 0; } int ModalWindowFunctions::luaModalWindowGetId(lua_State* L) { - // modalWindow:getId() - ModalWindow* window = getUserdata(L, 1); - if (window) { - lua_pushnumber(L, window->id); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getId() + ModalWindow* window = getUserdata(L, 1); + if (window) { + lua_pushnumber(L, window->id); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowGetTitle(lua_State* L) { - // modalWindow:getTitle() - ModalWindow* window = getUserdata(L, 1); - if (window) { - pushString(L, window->title); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getTitle() + ModalWindow* window = getUserdata(L, 1); + if (window) { + pushString(L, window->title); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowGetMessage(lua_State* L) { - // modalWindow:getMessage() - ModalWindow* window = getUserdata(L, 1); - if (window) { - pushString(L, window->message); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getMessage() + ModalWindow* window = getUserdata(L, 1); + if (window) { + pushString(L, window->message); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowSetTitle(lua_State* L) { - // modalWindow:setTitle(text) - const std::string& text = getString(L, 2); - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->title = text; - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:setTitle(text) + const std::string &text = getString(L, 2); + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->title = text; + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowSetMessage(lua_State* L) { - // modalWindow:setMessage(text) - const std::string& text = getString(L, 2); - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->message = text; - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:setMessage(text) + const std::string &text = getString(L, 2); + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->message = text; + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowGetButtonCount(lua_State* L) { - // modalWindow:getButtonCount() - ModalWindow* window = getUserdata(L, 1); - if (window) { - lua_pushnumber(L, window->buttons.size()); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getButtonCount() + ModalWindow* window = getUserdata(L, 1); + if (window) { + lua_pushnumber(L, window->buttons.size()); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowGetChoiceCount(lua_State* L) { - // modalWindow:getChoiceCount() - ModalWindow* window = getUserdata(L, 1); - if (window) { - lua_pushnumber(L, window->choices.size()); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getChoiceCount() + ModalWindow* window = getUserdata(L, 1); + if (window) { + lua_pushnumber(L, window->choices.size()); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowAddButton(lua_State* L) { - // modalWindow:addButton(id, text) - const std::string& text = getString(L, 3); - uint8_t id = getNumber(L, 2); - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->buttons.emplace_back(text, id); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:addButton(id, text) + const std::string &text = getString(L, 3); + uint8_t id = getNumber(L, 2); + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->buttons.emplace_back(text, id); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowAddChoice(lua_State* L) { - // modalWindow:addChoice(id, text) - const std::string& text = getString(L, 3); - uint8_t id = getNumber(L, 2); - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->choices.emplace_back(text, id); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:addChoice(id, text) + const std::string &text = getString(L, 3); + uint8_t id = getNumber(L, 2); + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->choices.emplace_back(text, id); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowGetDefaultEnterButton(lua_State* L) { - // modalWindow:getDefaultEnterButton() - ModalWindow* window = getUserdata(L, 1); - if (window) { - lua_pushnumber(L, window->defaultEnterButton); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getDefaultEnterButton() + ModalWindow* window = getUserdata(L, 1); + if (window) { + lua_pushnumber(L, window->defaultEnterButton); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowSetDefaultEnterButton(lua_State* L) { - // modalWindow:setDefaultEnterButton(buttonId) - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->defaultEnterButton = getNumber(L, 2); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:setDefaultEnterButton(buttonId) + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->defaultEnterButton = getNumber(L, 2); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowGetDefaultEscapeButton(lua_State* L) { - // modalWindow:getDefaultEscapeButton() - ModalWindow* window = getUserdata(L, 1); - if (window) { - lua_pushnumber(L, window->defaultEscapeButton); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:getDefaultEscapeButton() + ModalWindow* window = getUserdata(L, 1); + if (window) { + lua_pushnumber(L, window->defaultEscapeButton); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowSetDefaultEscapeButton(lua_State* L) { - // modalWindow:setDefaultEscapeButton(buttonId) - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->defaultEscapeButton = getNumber(L, 2); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:setDefaultEscapeButton(buttonId) + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->defaultEscapeButton = getNumber(L, 2); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowHasPriority(lua_State* L) { - // modalWindow:hasPriority() - ModalWindow* window = getUserdata(L, 1); - if (window) { - pushBoolean(L, window->priority); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:hasPriority() + ModalWindow* window = getUserdata(L, 1); + if (window) { + pushBoolean(L, window->priority); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowSetPriority(lua_State* L) { - // modalWindow:setPriority(priority) - ModalWindow* window = getUserdata(L, 1); - if (window) { - window->priority = getBoolean(L, 2); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:setPriority(priority) + ModalWindow* window = getUserdata(L, 1); + if (window) { + window->priority = getBoolean(L, 2); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } int ModalWindowFunctions::luaModalWindowSendToPlayer(lua_State* L) { - // modalWindow:sendToPlayer(player) - Player* player = getPlayer(L, 2); - if (!player) { - lua_pushnil(L); - return 1; - } - - ModalWindow* window = getUserdata(L, 1); - if (window) { - if (!player->hasModalWindowOpen(window->id)) { - player->sendModalWindow(*window); - } - pushBoolean(L, true); - } else { - lua_pushnil(L); - } - return 1; + // modalWindow:sendToPlayer(player) + Player* player = getPlayer(L, 2); + if (!player) { + lua_pushnil(L); + return 1; + } + + ModalWindow* window = getUserdata(L, 1); + if (window) { + if (!player->hasModalWindowOpen(window->id)) { + player->sendModalWindow(*window); + } + pushBoolean(L, true); + } else { + lua_pushnil(L); + } + return 1; } diff --git a/src/lua/functions/core/game/modal_window_functions.hpp b/src/lua/functions/core/game/modal_window_functions.hpp index ab9324195dd..ed47021ef1d 100644 --- a/src/lua/functions/core/game/modal_window_functions.hpp +++ b/src/lua/functions/core/game/modal_window_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_GAME_MODAL_WINDOW_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_GAME_MODAL_WINDOW_FUNCTIONS_HPP_ @@ -14,64 +14,64 @@ class ModalWindowFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "ModalWindow", "", ModalWindowFunctions::luaModalWindowCreate); - registerMetaMethod(L, "ModalWindow", "__eq", ModalWindowFunctions::luaUserdataCompare); - registerMetaMethod(L, "ModalWindow", "__gc", ModalWindowFunctions::luaModalWindowDelete); - registerMethod(L, "ModalWindow", "delete", ModalWindowFunctions::luaModalWindowDelete); + static void init(lua_State* L) { + registerClass(L, "ModalWindow", "", ModalWindowFunctions::luaModalWindowCreate); + registerMetaMethod(L, "ModalWindow", "__eq", ModalWindowFunctions::luaUserdataCompare); + registerMetaMethod(L, "ModalWindow", "__gc", ModalWindowFunctions::luaModalWindowDelete); + registerMethod(L, "ModalWindow", "delete", ModalWindowFunctions::luaModalWindowDelete); - registerMethod(L, "ModalWindow", "getId", ModalWindowFunctions::luaModalWindowGetId); - registerMethod(L, "ModalWindow", "getTitle", ModalWindowFunctions::luaModalWindowGetTitle); - registerMethod(L, "ModalWindow", "getMessage", ModalWindowFunctions::luaModalWindowGetMessage); + registerMethod(L, "ModalWindow", "getId", ModalWindowFunctions::luaModalWindowGetId); + registerMethod(L, "ModalWindow", "getTitle", ModalWindowFunctions::luaModalWindowGetTitle); + registerMethod(L, "ModalWindow", "getMessage", ModalWindowFunctions::luaModalWindowGetMessage); - registerMethod(L, "ModalWindow", "setTitle", ModalWindowFunctions::luaModalWindowSetTitle); - registerMethod(L, "ModalWindow", "setMessage", ModalWindowFunctions::luaModalWindowSetMessage); + registerMethod(L, "ModalWindow", "setTitle", ModalWindowFunctions::luaModalWindowSetTitle); + registerMethod(L, "ModalWindow", "setMessage", ModalWindowFunctions::luaModalWindowSetMessage); - registerMethod(L, "ModalWindow", "getButtonCount", ModalWindowFunctions::luaModalWindowGetButtonCount); - registerMethod(L, "ModalWindow", "getChoiceCount", ModalWindowFunctions::luaModalWindowGetChoiceCount); + registerMethod(L, "ModalWindow", "getButtonCount", ModalWindowFunctions::luaModalWindowGetButtonCount); + registerMethod(L, "ModalWindow", "getChoiceCount", ModalWindowFunctions::luaModalWindowGetChoiceCount); - registerMethod(L, "ModalWindow", "addButton", ModalWindowFunctions::luaModalWindowAddButton); - registerMethod(L, "ModalWindow", "addChoice", ModalWindowFunctions::luaModalWindowAddChoice); + registerMethod(L, "ModalWindow", "addButton", ModalWindowFunctions::luaModalWindowAddButton); + registerMethod(L, "ModalWindow", "addChoice", ModalWindowFunctions::luaModalWindowAddChoice); - registerMethod(L, "ModalWindow", "getDefaultEnterButton", ModalWindowFunctions::luaModalWindowGetDefaultEnterButton); - registerMethod(L, "ModalWindow", "setDefaultEnterButton", ModalWindowFunctions::luaModalWindowSetDefaultEnterButton); + registerMethod(L, "ModalWindow", "getDefaultEnterButton", ModalWindowFunctions::luaModalWindowGetDefaultEnterButton); + registerMethod(L, "ModalWindow", "setDefaultEnterButton", ModalWindowFunctions::luaModalWindowSetDefaultEnterButton); - registerMethod(L, "ModalWindow", "getDefaultEscapeButton", ModalWindowFunctions::luaModalWindowGetDefaultEscapeButton); - registerMethod(L, "ModalWindow", "setDefaultEscapeButton", ModalWindowFunctions::luaModalWindowSetDefaultEscapeButton); + registerMethod(L, "ModalWindow", "getDefaultEscapeButton", ModalWindowFunctions::luaModalWindowGetDefaultEscapeButton); + registerMethod(L, "ModalWindow", "setDefaultEscapeButton", ModalWindowFunctions::luaModalWindowSetDefaultEscapeButton); - registerMethod(L, "ModalWindow", "hasPriority", ModalWindowFunctions::luaModalWindowHasPriority); - registerMethod(L, "ModalWindow", "setPriority", ModalWindowFunctions::luaModalWindowSetPriority); + registerMethod(L, "ModalWindow", "hasPriority", ModalWindowFunctions::luaModalWindowHasPriority); + registerMethod(L, "ModalWindow", "setPriority", ModalWindowFunctions::luaModalWindowSetPriority); - registerMethod(L, "ModalWindow", "sendToPlayer", ModalWindowFunctions::luaModalWindowSendToPlayer); + registerMethod(L, "ModalWindow", "sendToPlayer", ModalWindowFunctions::luaModalWindowSendToPlayer); } private: - static int luaModalWindowCreate(lua_State* L); - static int luaModalWindowDelete(lua_State* L); + static int luaModalWindowCreate(lua_State* L); + static int luaModalWindowDelete(lua_State* L); - static int luaModalWindowGetId(lua_State* L); - static int luaModalWindowGetTitle(lua_State* L); - static int luaModalWindowGetMessage(lua_State* L); + static int luaModalWindowGetId(lua_State* L); + static int luaModalWindowGetTitle(lua_State* L); + static int luaModalWindowGetMessage(lua_State* L); - static int luaModalWindowSetTitle(lua_State* L); - static int luaModalWindowSetMessage(lua_State* L); + static int luaModalWindowSetTitle(lua_State* L); + static int luaModalWindowSetMessage(lua_State* L); - static int luaModalWindowGetButtonCount(lua_State* L); - static int luaModalWindowGetChoiceCount(lua_State* L); + static int luaModalWindowGetButtonCount(lua_State* L); + static int luaModalWindowGetChoiceCount(lua_State* L); - static int luaModalWindowAddButton(lua_State* L); - static int luaModalWindowAddChoice(lua_State* L); + static int luaModalWindowAddButton(lua_State* L); + static int luaModalWindowAddChoice(lua_State* L); - static int luaModalWindowGetDefaultEnterButton(lua_State* L); - static int luaModalWindowSetDefaultEnterButton(lua_State* L); + static int luaModalWindowGetDefaultEnterButton(lua_State* L); + static int luaModalWindowSetDefaultEnterButton(lua_State* L); - static int luaModalWindowGetDefaultEscapeButton(lua_State* L); - static int luaModalWindowSetDefaultEscapeButton(lua_State* L); + static int luaModalWindowGetDefaultEscapeButton(lua_State* L); + static int luaModalWindowSetDefaultEscapeButton(lua_State* L); - static int luaModalWindowHasPriority(lua_State* L); - static int luaModalWindowSetPriority(lua_State* L); + static int luaModalWindowHasPriority(lua_State* L); + static int luaModalWindowSetPriority(lua_State* L); - static int luaModalWindowSendToPlayer(lua_State* L); + static int luaModalWindowSendToPlayer(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_GAME_MODAL_WINDOW_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_GAME_MODAL_WINDOW_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/libs/bit_functions.cpp b/src/lua/functions/core/libs/bit_functions.cpp index 456e001e66b..310e963afd9 100644 --- a/src/lua/functions/core/libs/bit_functions.cpp +++ b/src/lua/functions/core/libs/bit_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,27 +18,27 @@ int GlobalFunctions::luaBitNot(lua_State* L) { return 1; } -#define MULTIOP(name, op) \ -int GlobalFunctions::luaBit##name(lua_State* L) \ { \ - int n = lua_gettop(L); \ - uint32_t w = getNumber(L, -1); \ - for (int i = 1; i < n; ++i) \ - w op getNumber(L, i); \ - lua_pushnumber(L, w); \ - return 1; \ -} + #define MULTIOP(name, op) \ + int GlobalFunctions::luaBit##name(lua_State* L) \ { \ + int n = lua_gettop(L); \ + uint32_t w = getNumber(L, -1); \ + for (int i = 1; i < n; ++i) \ + w op getNumber(L, i); \ + lua_pushnumber(L, w); \ + return 1; \ + } -MULTIOP(And, &= ) -MULTIOP(Or, |= ) -MULTIOP(Xor, ^= ) +MULTIOP(And, &=) +MULTIOP(Or, |=) +MULTIOP(Xor, ^=) -#define SHIFTOP(name, op) \ -int GlobalFunctions::luaBit##name(lua_State* L) \ { \ - uint32_t n1 = getNumber(L, 1), n2 = getNumber(L, 2); \ - lua_pushnumber(L, (n1 op n2)); \ - return 1; \ -} + #define SHIFTOP(name, op) \ + int GlobalFunctions::luaBit##name(lua_State* L) \ { \ + uint32_t n1 = getNumber(L, 1), n2 = getNumber(L, 2); \ + lua_pushnumber(L, (n1 op n2)); \ + return 1; \ + } -SHIFTOP(LeftShift, << ) -SHIFTOP(RightShift, >> ) +SHIFTOP(LeftShift, <<) +SHIFTOP(RightShift, >>) #endif diff --git a/src/lua/functions/core/libs/bit_functions.hpp b/src/lua/functions/core/libs/bit_functions.hpp index 27aeb9bcd24..e62df55ac1d 100644 --- a/src/lua/functions/core/libs/bit_functions.hpp +++ b/src/lua/functions/core/libs/bit_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_LIBS_BIT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_LIBS_BIT_FUNCTIONS_HPP_ @@ -15,7 +15,7 @@ class BitFunctions final : LuaScriptInterface { public: static void init(lua_State* L) { - #ifndef LUAJIT_VERSION +#ifndef LUAJIT_VERSION registerTable(L, "bit"); registerMethod(L, "bit", "bnot", BitFunctions::luaBitNot); registerMethod(L, "bit", "band", BitFunctions::luaBitAnd); @@ -23,18 +23,18 @@ class BitFunctions final : LuaScriptInterface { registerMethod(L, "bit", "bxor", BitFunctions::luaBitXor); registerMethod(L, "bit", "lshift", BitFunctions::luaBitLeftShift); registerMethod(L, "bit", "rshift", BitFunctions::luaBitRightShift); - #endif +#endif } private: - #ifndef LUAJIT_VERSION +#ifndef LUAJIT_VERSION static int luaBitAnd(lua_State* L); static int luaBitLeftShift(lua_State* L); static int luaBitNot(lua_State* L); static int luaBitOr(lua_State* L); static int luaBitRightShift(lua_State* L); static int luaBitXor(lua_State* L); - #endif +#endif }; -#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_BIT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_BIT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/libs/core_libs_functions.hpp b/src/lua/functions/core/libs/core_libs_functions.hpp index 2bde8219287..8973b52e50a 100644 --- a/src/lua/functions/core/libs/core_libs_functions.hpp +++ b/src/lua/functions/core/libs/core_libs_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_LIBS_CORE_LIBS_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_LIBS_CORE_LIBS_FUNCTIONS_HPP_ @@ -26,6 +26,6 @@ class CoreLibsFunctions final : LuaScriptInterface { } private: - }; +}; -#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_CORE_LIBS_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_CORE_LIBS_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/libs/db_functions.cpp b/src/lua/functions/core/libs/db_functions.cpp index cdbbee5525c..192b62d2068 100644 --- a/src/lua/functions/core/libs/db_functions.cpp +++ b/src/lua/functions/core/libs/db_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -25,23 +25,23 @@ int DBFunctions::luaDatabaseAsyncExecute(lua_State* L) { int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX); auto scriptId = getScriptEnv()->getScriptId(); callback = [ref, scriptId](DBResult_ptr, bool success) { - lua_State* luaState = g_luaEnvironment.getLuaState(); - if (!luaState) { - return; - } - - if (!DBFunctions::reserveScriptEnv()) { - luaL_unref(luaState, LUA_REGISTRYINDEX, ref); - return; - } - - lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref); - pushBoolean(luaState, success); - auto env = getScriptEnv(); - env->setScriptId(scriptId, &g_luaEnvironment); - g_luaEnvironment.callFunction(1); + lua_State* luaState = g_luaEnvironment.getLuaState(); + if (!luaState) { + return; + } + if (!DBFunctions::reserveScriptEnv()) { luaL_unref(luaState, LUA_REGISTRYINDEX, ref); + return; + } + + lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref); + pushBoolean(luaState, success); + auto env = getScriptEnv(); + env->setScriptId(scriptId, &g_luaEnvironment); + g_luaEnvironment.callFunction(1); + + luaL_unref(luaState, LUA_REGISTRYINDEX, ref); }; } g_databaseTasks().addTask(getString(L, -1), callback); @@ -63,27 +63,27 @@ int DBFunctions::luaDatabaseAsyncStoreQuery(lua_State* L) { int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX); auto scriptId = getScriptEnv()->getScriptId(); callback = [ref, scriptId](DBResult_ptr result, bool) { - lua_State* luaState = g_luaEnvironment.getLuaState(); - if (!luaState) { - return; - } - - if (!DBFunctions::reserveScriptEnv()) { - luaL_unref(luaState, LUA_REGISTRYINDEX, ref); - return; - } - - lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref); - if (result) { - lua_pushnumber(luaState, ScriptEnvironment::addResult(result)); - } else { - pushBoolean(luaState, false); - } - auto env = getScriptEnv(); - env->setScriptId(scriptId, &g_luaEnvironment); - g_luaEnvironment.callFunction(1); + lua_State* luaState = g_luaEnvironment.getLuaState(); + if (!luaState) { + return; + } + if (!DBFunctions::reserveScriptEnv()) { luaL_unref(luaState, LUA_REGISTRYINDEX, ref); + return; + } + + lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref); + if (result) { + lua_pushnumber(luaState, ScriptEnvironment::addResult(result)); + } else { + pushBoolean(luaState, false); + } + auto env = getScriptEnv(); + env->setScriptId(scriptId, &g_luaEnvironment); + g_luaEnvironment.callFunction(1); + + luaL_unref(luaState, LUA_REGISTRYINDEX, ref); }; } g_databaseTasks().addTask(getString(L, -1), callback, true); diff --git a/src/lua/functions/core/libs/db_functions.hpp b/src/lua/functions/core/libs/db_functions.hpp index be34762e2f3..0768b64f858 100644 --- a/src/lua/functions/core/libs/db_functions.hpp +++ b/src/lua/functions/core/libs/db_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_LIBS_DB_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_LIBS_DB_FUNCTIONS_HPP_ @@ -37,4 +37,4 @@ class DBFunctions final : LuaScriptInterface { static int luaDatabaseTableExists(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_DB_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_DB_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/libs/result_functions.cpp b/src/lua/functions/core/libs/result_functions.cpp index f5307e0d114..98ab7c6de26 100644 --- a/src/lua/functions/core/libs/result_functions.cpp +++ b/src/lua/functions/core/libs/result_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,7 +18,7 @@ int ResultFunctions::luaResultGetNumber(lua_State* L) { return 1; } - const std::string& s = getString(L, 2); + const std::string &s = getString(L, 2); lua_pushnumber(L, res->getNumber(s)); return 1; } @@ -30,7 +30,7 @@ int ResultFunctions::luaResultGetString(lua_State* L) { return 1; } - const std::string& s = getString(L, 2); + const std::string &s = getString(L, 2); pushString(L, res->getString(s)); return 1; } diff --git a/src/lua/functions/core/libs/result_functions.hpp b/src/lua/functions/core/libs/result_functions.hpp index 2e2cd20aac6..25df98eaca5 100644 --- a/src/lua/functions/core/libs/result_functions.hpp +++ b/src/lua/functions/core/libs/result_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_LIBS_RESULT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_LIBS_RESULT_FUNCTIONS_HPP_ @@ -31,4 +31,4 @@ class ResultFunctions final : LuaScriptInterface { static int luaResultNext(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_RESULT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_RESULT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/libs/spdlog_functions.cpp b/src/lua/functions/core/libs/spdlog_functions.cpp index dba1506eb09..a4de2fbd17d 100644 --- a/src/lua/functions/core/libs/spdlog_functions.cpp +++ b/src/lua/functions/core/libs/spdlog_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/core/libs/spdlog_functions.hpp b/src/lua/functions/core/libs/spdlog_functions.hpp index d18a2efadb1..bf4550a1a0b 100644 --- a/src/lua/functions/core/libs/spdlog_functions.hpp +++ b/src/lua/functions/core/libs/spdlog_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_LIBS_SPDLOG_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_LIBS_SPDLOG_FUNCTIONS_HPP_ @@ -29,4 +29,4 @@ class SpdlogFunctions final : LuaScriptInterface { static int luaSpdlogWarn(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_SPDLOG_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_LIBS_SPDLOG_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/network/core_network_functions.hpp b/src/lua/functions/core/network/core_network_functions.hpp index 9bea3afcf6e..b20abdc9409 100644 --- a/src/lua/functions/core/network/core_network_functions.hpp +++ b/src/lua/functions/core/network/core_network_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_NETWORK_CORE_NETWORK_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_NETWORK_CORE_NETWORK_FUNCTIONS_HPP_ @@ -22,6 +22,6 @@ class CoreNetworkFunctions final : LuaScriptInterface { } private: - }; +}; -#endif // SRC_LUA_FUNCTIONS_CORE_NETWORK_CORE_NETWORK_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_NETWORK_CORE_NETWORK_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/network/network_message_functions.cpp b/src/lua/functions/core/network/network_message_functions.cpp index eba4c3160fc..6b220111401 100644 --- a/src/lua/functions/core/network/network_message_functions.cpp +++ b/src/lua/functions/core/network/network_message_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -149,7 +149,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddU64(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddString(lua_State* L) { // networkMessage:addString(string) - const std::string& string = getString(L, 2); + const std::string &string = getString(L, 2); NetworkMessage* message = getUserdata(L, 1); if (message) { message->addString(string); @@ -162,7 +162,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddString(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddPosition(lua_State* L) { // networkMessage:addPosition(position) - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); NetworkMessage* message = getUserdata(L, 1); if (message) { message->addPosition(position); diff --git a/src/lua/functions/core/network/network_message_functions.hpp b/src/lua/functions/core/network/network_message_functions.hpp index c8fecd9a479..78c8f9eeb66 100644 --- a/src/lua/functions/core/network/network_message_functions.hpp +++ b/src/lua/functions/core/network/network_message_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_NETWORK_NETWORK_MESSAGE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_NETWORK_NETWORK_MESSAGE_FUNCTIONS_HPP_ @@ -66,4 +66,4 @@ class NetworkMessageFunctions final : LuaScriptInterface { static int luaNetworkMessageSendToPlayer(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_NETWORK_NETWORK_MESSAGE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_NETWORK_NETWORK_MESSAGE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/core/network/webhook_functions.cpp b/src/lua/functions/core/network/webhook_functions.cpp index 7262096d6be..d76a07bdda6 100644 --- a/src/lua/functions/core/network/webhook_functions.cpp +++ b/src/lua/functions/core/network/webhook_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/core/network/webhook_functions.hpp b/src/lua/functions/core/network/webhook_functions.hpp index d857c064702..038482a4cb7 100644 --- a/src/lua/functions/core/network/webhook_functions.hpp +++ b/src/lua/functions/core/network/webhook_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CORE_NETWORK_WEBHOOK_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CORE_NETWORK_WEBHOOK_FUNCTIONS_HPP_ @@ -23,4 +23,4 @@ class WebhookFunctions final : LuaScriptInterface { static int webhookSend(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CORE_NETWORK_WEBHOOK_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CORE_NETWORK_WEBHOOK_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/combat/combat_functions.cpp b/src/lua/functions/creatures/combat/combat_functions.cpp index 10f6198b497..b0e00660168 100644 --- a/src/lua/functions/creatures/combat/combat_functions.cpp +++ b/src/lua/functions/creatures/combat/combat_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -117,7 +117,7 @@ int CombatFunctions::luaCombatSetCallback(lua_State* L) { return 1; } - const std::string& function = getString(L, 3); + const std::string &function = getString(L, 3); pushBoolean(L, callback->loadCallBack(getScriptEnv()->getScriptInterface(), function)); return 1; } @@ -152,7 +152,7 @@ int CombatFunctions::luaCombatExecute(lua_State* L) { Creature* creature = getCreature(L, 2); - const LuaVariant& variant = getVariant(L, 3); + const LuaVariant &variant = getVariant(L, 3); switch (variant.type) { case VARIANT_NUMBER: { Creature* target = g_game().getCreatureByID(variant.number); diff --git a/src/lua/functions/creatures/combat/combat_functions.hpp b/src/lua/functions/creatures/combat/combat_functions.hpp index 2c16cb9dc1e..370951a1d12 100644 --- a/src/lua/functions/creatures/combat/combat_functions.hpp +++ b/src/lua/functions/creatures/combat/combat_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_COMBAT_COMBAT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_COMBAT_COMBAT_FUNCTIONS_HPP_ @@ -50,4 +50,4 @@ class CombatFunctions final : LuaScriptInterface { static int luaCombatExecute(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_COMBAT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_COMBAT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/combat/condition_functions.cpp b/src/lua/functions/creatures/combat/condition_functions.cpp index a6e89aace2a..2bb30364606 100644 --- a/src/lua/functions/creatures/combat/condition_functions.cpp +++ b/src/lua/functions/creatures/combat/condition_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/creatures/combat/condition_functions.hpp b/src/lua/functions/creatures/combat/condition_functions.hpp index f78fd7e52fc..7ac68a247d7 100644 --- a/src/lua/functions/creatures/combat/condition_functions.hpp +++ b/src/lua/functions/creatures/combat/condition_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_COMBAT_CONDITION_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_COMBAT_CONDITION_FUNCTIONS_HPP_ @@ -14,28 +14,28 @@ class ConditionFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "Condition", "", ConditionFunctions::luaConditionCreate); - registerMetaMethod(L, "Condition", "__eq", ConditionFunctions::luaUserdataCompare); - registerMetaMethod(L, "Condition", "__gc", ConditionFunctions::luaConditionDelete); - registerMethod(L, "Condition", "delete", ConditionFunctions::luaConditionDelete); + static void init(lua_State* L) { + registerClass(L, "Condition", "", ConditionFunctions::luaConditionCreate); + registerMetaMethod(L, "Condition", "__eq", ConditionFunctions::luaUserdataCompare); + registerMetaMethod(L, "Condition", "__gc", ConditionFunctions::luaConditionDelete); + registerMethod(L, "Condition", "delete", ConditionFunctions::luaConditionDelete); - registerMethod(L, "Condition", "getId", ConditionFunctions::luaConditionGetId); - registerMethod(L, "Condition", "getSubId", ConditionFunctions::luaConditionGetSubId); - registerMethod(L, "Condition", "getType", ConditionFunctions::luaConditionGetType); - registerMethod(L, "Condition", "getIcons", ConditionFunctions::luaConditionGetIcons); - registerMethod(L, "Condition", "getEndTime", ConditionFunctions::luaConditionGetEndTime); + registerMethod(L, "Condition", "getId", ConditionFunctions::luaConditionGetId); + registerMethod(L, "Condition", "getSubId", ConditionFunctions::luaConditionGetSubId); + registerMethod(L, "Condition", "getType", ConditionFunctions::luaConditionGetType); + registerMethod(L, "Condition", "getIcons", ConditionFunctions::luaConditionGetIcons); + registerMethod(L, "Condition", "getEndTime", ConditionFunctions::luaConditionGetEndTime); - registerMethod(L, "Condition", "clone", ConditionFunctions::luaConditionClone); + registerMethod(L, "Condition", "clone", ConditionFunctions::luaConditionClone); - registerMethod(L, "Condition", "getTicks", ConditionFunctions::luaConditionGetTicks); - registerMethod(L, "Condition", "setTicks", ConditionFunctions::luaConditionSetTicks); + registerMethod(L, "Condition", "getTicks", ConditionFunctions::luaConditionGetTicks); + registerMethod(L, "Condition", "setTicks", ConditionFunctions::luaConditionSetTicks); - registerMethod(L, "Condition", "setParameter", ConditionFunctions::luaConditionSetParameter); - registerMethod(L, "Condition", "setFormula", ConditionFunctions::luaConditionSetFormula); - registerMethod(L, "Condition", "setOutfit", ConditionFunctions::luaConditionSetOutfit); + registerMethod(L, "Condition", "setParameter", ConditionFunctions::luaConditionSetParameter); + registerMethod(L, "Condition", "setFormula", ConditionFunctions::luaConditionSetFormula); + registerMethod(L, "Condition", "setOutfit", ConditionFunctions::luaConditionSetOutfit); - registerMethod(L, "Condition", "addDamage", ConditionFunctions::luaConditionAddDamage); + registerMethod(L, "Condition", "addDamage", ConditionFunctions::luaConditionAddDamage); } private: @@ -60,4 +60,4 @@ class ConditionFunctions final : LuaScriptInterface { static int luaConditionAddDamage(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_CONDITION_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_CONDITION_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/combat/spell_functions.cpp b/src/lua/functions/creatures/combat/spell_functions.cpp index 8ca76b9c476..62745b83ba0 100644 --- a/src/lua/functions/creatures/combat/spell_functions.cpp +++ b/src/lua/functions/creatures/combat/spell_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -143,7 +143,7 @@ int SpellFunctions::luaSpellRegister(lua_State* L) { RuneSpell* rune = dynamic_cast(getUserdata(L, 1)); if (rune->getMagicLevel() != 0 || rune->getLevel() != 0) { // Change information in the ItemType to get accurate description - ItemType& iType = Item::items.getItemType(rune->getRuneItemId()); + ItemType &iType = Item::items.getItemType(rune->getRuneItemId()); // If the item is not registered in items.xml then we will register it by rune name if (iType.name.empty()) { iType.name = rune->getName(); @@ -219,14 +219,16 @@ int SpellFunctions::luaSpellGroup(lua_State* L) { spell->setGroup(group); } else { SPDLOG_WARN("[SpellFunctions::luaSpellGroup] - " - "Unknown group: {}", getString(L, 2)); + "Unknown group: {}", + getString(L, 2)); pushBoolean(L, false); return 1; } pushBoolean(L, true); } else { SPDLOG_WARN("[SpellFunctions::luaSpellGroup] - " - "Unknown group: {}", getString(L, 2)); + "Unknown group: {}", + getString(L, 2)); pushBoolean(L, false); return 1; } @@ -243,7 +245,8 @@ int SpellFunctions::luaSpellGroup(lua_State* L) { spell->setGroup(primaryGroup); } else { SPDLOG_WARN("[SpellFunctions::luaSpellGroup] - " - "Unknown primaryGroup: {}", getString(L, 2)); + "Unknown primaryGroup: {}", + getString(L, 2)); pushBoolean(L, false); return 1; } @@ -252,7 +255,8 @@ int SpellFunctions::luaSpellGroup(lua_State* L) { spell->setSecondaryGroup(secondaryGroup); } else { SPDLOG_WARN("[SpellFunctions::luaSpellGroup] - " - "Unknown secondaryGroup: {}", getString(L, 3)); + "Unknown secondaryGroup: {}", + getString(L, 3)); pushBoolean(L, false); return 1; } @@ -536,8 +540,7 @@ int SpellFunctions::luaSpellAggressive(lua_State* L) { return 1; } -int SpellFunctions::luaSpellAllowOnSelf(lua_State* L) -{ +int SpellFunctions::luaSpellAllowOnSelf(lua_State* L) { // spell:allowOnSelf(bool) Spell* spell = getUserdata(L, 1); if (spell) { @@ -553,8 +556,7 @@ int SpellFunctions::luaSpellAllowOnSelf(lua_State* L) return 1; } -int SpellFunctions::luaSpellPzLocked(lua_State* L) -{ +int SpellFunctions::luaSpellPzLocked(lua_State* L) { // spell:isPzLocked(bool) Spell* spell = getUserdata(L, 1); if (spell) { @@ -580,7 +582,7 @@ int SpellFunctions::luaSpellVocation(lua_State* L) { for (auto voc : spell->getVocMap()) { ++it; std::string s = std::to_string(it); - char const *pchar = s.c_str(); + const char* pchar = s.c_str(); std::string name = g_vocations().getVocation(voc.first)->getVocName(); setField(L, pchar, name); } diff --git a/src/lua/functions/creatures/combat/spell_functions.hpp b/src/lua/functions/creatures/combat/spell_functions.hpp index c65c1484cf7..41c6020d166 100644 --- a/src/lua/functions/creatures/combat/spell_functions.hpp +++ b/src/lua/functions/creatures/combat/spell_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_COMBAT_SPELL_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_COMBAT_SPELL_FUNCTIONS_HPP_ @@ -103,4 +103,4 @@ class SpellFunctions final : LuaScriptInterface { static int luaSpellCheckFloor(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_SPELL_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_SPELL_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/combat/variant_functions.cpp b/src/lua/functions/creatures/combat/variant_functions.cpp index cb32d99ebf3..41de0554b2a 100644 --- a/src/lua/functions/creatures/combat/variant_functions.cpp +++ b/src/lua/functions/creatures/combat/variant_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -36,7 +36,7 @@ int VariantFunctions::luaVariantCreate(lua_State* L) { int VariantFunctions::luaVariantGetNumber(lua_State* L) { // Variant:getNumber() - const LuaVariant& variant = getVariant(L, 1); + const LuaVariant &variant = getVariant(L, 1); if (variant.type == VARIANT_NUMBER) { lua_pushnumber(L, variant.number); } else { @@ -47,7 +47,7 @@ int VariantFunctions::luaVariantGetNumber(lua_State* L) { int VariantFunctions::luaVariantGetString(lua_State* L) { // Variant:getString() - const LuaVariant& variant = getVariant(L, 1); + const LuaVariant &variant = getVariant(L, 1); if (variant.type == VARIANT_STRING) { pushString(L, variant.text); } else { @@ -58,7 +58,7 @@ int VariantFunctions::luaVariantGetString(lua_State* L) { int VariantFunctions::luaVariantGetPosition(lua_State* L) { // Variant:getPosition() - const LuaVariant& variant = getVariant(L, 1); + const LuaVariant &variant = getVariant(L, 1); if (variant.type == VARIANT_POSITION || variant.type == VARIANT_TARGETPOSITION) { pushPosition(L, variant.pos); } else { diff --git a/src/lua/functions/creatures/combat/variant_functions.hpp b/src/lua/functions/creatures/combat/variant_functions.hpp index 48aaee8d5b7..b07c78b8358 100644 --- a/src/lua/functions/creatures/combat/variant_functions.hpp +++ b/src/lua/functions/creatures/combat/variant_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_COMBAT_VARIANT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_COMBAT_VARIANT_FUNCTIONS_HPP_ @@ -30,4 +30,4 @@ class VariantFunctions final : LuaScriptInterface { static int luaVariantGetPosition(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_VARIANT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_COMBAT_VARIANT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/creature_functions.cpp b/src/lua/functions/creatures/creature_functions.cpp index e76e47a2cf4..fc60a9f79ad 100644 --- a/src/lua/functions/creatures/creature_functions.cpp +++ b/src/lua/functions/creatures/creature_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -49,7 +49,7 @@ int CreatureFunctions::luaCreatureGetEvents(lua_State* L) { } CreatureEventType_t eventType = getNumber(L, 2); - const auto& eventList = creature->getCreatureEvents(eventType); + const auto &eventList = creature->getCreatureEvents(eventType); lua_createtable(L, eventList.size(), 0); int index = 0; @@ -64,7 +64,7 @@ int CreatureFunctions::luaCreatureRegisterEvent(lua_State* L) { // creature:registerEvent(name) Creature* creature = getUserdata(L, 1); if (creature) { - const std::string& name = getString(L, 2); + const std::string &name = getString(L, 2); pushBoolean(L, creature->registerCreatureEvent(name)); } else { lua_pushnil(L); @@ -74,7 +74,7 @@ int CreatureFunctions::luaCreatureRegisterEvent(lua_State* L) { int CreatureFunctions::luaCreatureUnregisterEvent(lua_State* L) { // creature:unregisterEvent(name) - const std::string& name = getString(L, 2); + const std::string &name = getString(L, 2); Creature* creature = getUserdata(L, 1); if (creature) { pushBoolean(L, creature->unregisterCreatureEvent(name)); @@ -127,7 +127,7 @@ int CreatureFunctions::luaCreatureCanSee(lua_State* L) { // creature:canSee(position) const Creature* creature = getUserdata(L, 1); if (creature) { - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); pushBoolean(L, creature->canSee(position)); } else { lua_pushnil(L); @@ -277,8 +277,7 @@ int CreatureFunctions::luaCreatureGetMaster(lua_State* L) { return 1; } -int CreatureFunctions::luaCreatureReload(lua_State* L) -{ +int CreatureFunctions::luaCreatureReload(lua_State* L) { // creature:reload() Creature* creature = getUserdata(L, 1); if (!creature) { @@ -741,7 +740,7 @@ int CreatureFunctions::luaCreatureTeleportTo(lua_State* L) { // creature:teleportTo(position[, pushMovement = false]) bool pushMovement = getBoolean(L, 3, false); - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); Creature* creature = getUserdata(L, 1); if (creature == nullptr) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); @@ -749,7 +748,7 @@ int CreatureFunctions::luaCreatureTeleportTo(lua_State* L) { return 1; } - const Player *player = creature->getPlayer(); + const Player* player = creature->getPlayer(); if (!player) { return 1; } @@ -764,8 +763,7 @@ int CreatureFunctions::luaCreatureTeleportTo(lua_State* L) { } if (auto ret = g_game().internalTeleport(creature, position, pushMovement); - ret != RETURNVALUE_NOERROR) - { + ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); SPDLOG_ERROR("[{}] Failed to teleport player, error code: {}", __FUNCTION__, getReturnMessage(ret)); pushBoolean(L, false); @@ -811,7 +809,7 @@ int CreatureFunctions::luaCreatureSay(lua_State* L) { bool ghost = getBoolean(L, 4, false); SpeakClasses type = getNumber(L, 3, TALKTYPE_MONSTER_SAY); - const std::string& text = getString(L, 2); + const std::string &text = getString(L, 2); Creature* creature = getUserdata(L, 1); if (!creature) { lua_pushnil(L); @@ -900,7 +898,7 @@ int CreatureFunctions::luaCreatureGetPathTo(lua_State* L) { return 1; } - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); FindPathParams fpp; fpp.minTargetDist = getNumber(L, 3, 0); diff --git a/src/lua/functions/creatures/creature_functions.hpp b/src/lua/functions/creatures/creature_functions.hpp index 27659a95676..01bfefad322 100644 --- a/src/lua/functions/creatures/creature_functions.hpp +++ b/src/lua/functions/creatures/creature_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_CREATURE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_CREATURE_FUNCTIONS_HPP_ @@ -172,4 +172,4 @@ class CreatureFunctions final : LuaScriptInterface { static int luaCreatureGetZone(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_CREATURE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_CREATURE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/monster/charm_functions.cpp b/src/lua/functions/creatures/monster/charm_functions.cpp index 3d842a60160..1113fdb89ef 100644 --- a/src/lua/functions/creatures/monster/charm_functions.cpp +++ b/src/lua/functions/creatures/monster/charm_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -18,7 +18,7 @@ int CharmFunctions::luaCharmCreate(lua_State* L) { if (isNumber(L, 2)) { charmRune_t charmid = getNumber(L, 2); std::vector charmList = g_game().getCharmList(); - for (auto& it : charmList) { + for (auto &it : charmList) { Charm* charm = it; if (charm->id == charmid) { pushUserdata(L, charm); diff --git a/src/lua/functions/creatures/monster/charm_functions.hpp b/src/lua/functions/creatures/monster/charm_functions.hpp index 87f5bb7c8b6..263e980fca4 100644 --- a/src/lua/functions/creatures/monster/charm_functions.hpp +++ b/src/lua/functions/creatures/monster/charm_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_MONSTER_CHARM_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_MONSTER_CHARM_FUNCTIONS_HPP_ @@ -14,20 +14,20 @@ class CharmFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "Charm", "", CharmFunctions::luaCharmCreate); - registerMetaMethod(L, "Charm", "__eq", CharmFunctions::luaUserdataCompare); + static void init(lua_State* L) { + registerClass(L, "Charm", "", CharmFunctions::luaCharmCreate); + registerMetaMethod(L, "Charm", "__eq", CharmFunctions::luaUserdataCompare); - registerMethod(L, "Charm", "name", CharmFunctions::luaCharmName); - registerMethod(L, "Charm", "description", CharmFunctions::luaCharmDescription); - registerMethod(L, "Charm", "type", CharmFunctions::luaCharmType); - registerMethod(L, "Charm", "points", CharmFunctions::luaCharmPoints); - registerMethod(L, "Charm", "damageType", CharmFunctions::luaCharmDamageType); - registerMethod(L, "Charm", "percentage", CharmFunctions::luaCharmPercentage); - registerMethod(L, "Charm", "chance", CharmFunctions::luaCharmChance); - registerMethod(L, "Charm", "messageCancel", CharmFunctions::luaCharmMessageCancel); - registerMethod(L, "Charm", "messageServerLog", CharmFunctions::luaCharmMessageServerLog); - registerMethod(L, "Charm", "effect", CharmFunctions::luaCharmEffect); + registerMethod(L, "Charm", "name", CharmFunctions::luaCharmName); + registerMethod(L, "Charm", "description", CharmFunctions::luaCharmDescription); + registerMethod(L, "Charm", "type", CharmFunctions::luaCharmType); + registerMethod(L, "Charm", "points", CharmFunctions::luaCharmPoints); + registerMethod(L, "Charm", "damageType", CharmFunctions::luaCharmDamageType); + registerMethod(L, "Charm", "percentage", CharmFunctions::luaCharmPercentage); + registerMethod(L, "Charm", "chance", CharmFunctions::luaCharmChance); + registerMethod(L, "Charm", "messageCancel", CharmFunctions::luaCharmMessageCancel); + registerMethod(L, "Charm", "messageServerLog", CharmFunctions::luaCharmMessageServerLog); + registerMethod(L, "Charm", "effect", CharmFunctions::luaCharmEffect); } private: @@ -44,4 +44,4 @@ class CharmFunctions final : LuaScriptInterface { static int luaCharmEffect(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_CHARM_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_CHARM_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/monster/loot_functions.cpp b/src/lua/functions/creatures/monster/loot_functions.cpp index 264be7e46d1..c27a83be807 100644 --- a/src/lua/functions/creatures/monster/loot_functions.cpp +++ b/src/lua/functions/creatures/monster/loot_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -61,14 +61,16 @@ int LootFunctions::luaLootSetIdFromName(lua_State* L) { if (ids.first == Item::items.nameToItems.cend()) { SPDLOG_WARN("[LootFunctions::luaLootSetIdFromName] - " - "Unknown loot item {}", name); + "Unknown loot item {}", + name); lua_pushnil(L); return 1; } if (std::next(ids.first) != ids.second) { SPDLOG_WARN("[LootFunctions::luaLootSetIdFromName] - " - "Non-unique loot item {}", name); + "Non-unique loot item {}", + name); lua_pushnil(L); return 1; } diff --git a/src/lua/functions/creatures/monster/loot_functions.hpp b/src/lua/functions/creatures/monster/loot_functions.hpp index d78ff41ca22..4037060a3db 100644 --- a/src/lua/functions/creatures/monster/loot_functions.hpp +++ b/src/lua/functions/creatures/monster/loot_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_MONSTER_LOOT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_MONSTER_LOOT_FUNCTIONS_HPP_ @@ -14,29 +14,29 @@ class LootFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "Loot", "", LootFunctions::luaCreateLoot); - registerMetaMethod(L, "Loot", "__gc", LootFunctions::luaDeleteLoot); - registerMethod(L, "Loot", "delete", LootFunctions::luaDeleteLoot); + static void init(lua_State* L) { + registerClass(L, "Loot", "", LootFunctions::luaCreateLoot); + registerMetaMethod(L, "Loot", "__gc", LootFunctions::luaDeleteLoot); + registerMethod(L, "Loot", "delete", LootFunctions::luaDeleteLoot); - registerMethod(L, "Loot", "setId", LootFunctions::luaLootSetId); - registerMethod(L, "Loot", "setIdFromName", LootFunctions::luaLootSetIdFromName); - registerMethod(L, "Loot", "setMinCount", LootFunctions::luaLootSetMinCount); - registerMethod(L, "Loot", "setMaxCount", LootFunctions::luaLootSetMaxCount); - registerMethod(L, "Loot", "setSubType", LootFunctions::luaLootSetSubType); - registerMethod(L, "Loot", "setChance", LootFunctions::luaLootSetChance); - registerMethod(L, "Loot", "setActionId", LootFunctions::luaLootSetActionId); - registerMethod(L, "Loot", "setText", LootFunctions::luaLootSetText); - registerMethod(L, "Loot", "setNameItem", LootFunctions::luaLootSetNameItem); - registerMethod(L, "Loot", "setArticle", LootFunctions::luaLootSetArticle); - registerMethod(L, "Loot", "setAttack", LootFunctions::luaLootSetAttack); - registerMethod(L, "Loot", "setDefense", LootFunctions::luaLootSetDefense); - registerMethod(L, "Loot", "setExtraDefense", LootFunctions::luaLootSetExtraDefense); - registerMethod(L, "Loot", "setArmor", LootFunctions::luaLootSetArmor); - registerMethod(L, "Loot", "setShootRange", LootFunctions::luaLootSetShootRange); - registerMethod(L, "Loot", "setHitChance", LootFunctions::luaLootSetHitChance); - registerMethod(L, "Loot", "setUnique", LootFunctions::luaLootSetUnique); - registerMethod(L, "Loot", "addChildLoot", LootFunctions::luaLootAddChildLoot); + registerMethod(L, "Loot", "setId", LootFunctions::luaLootSetId); + registerMethod(L, "Loot", "setIdFromName", LootFunctions::luaLootSetIdFromName); + registerMethod(L, "Loot", "setMinCount", LootFunctions::luaLootSetMinCount); + registerMethod(L, "Loot", "setMaxCount", LootFunctions::luaLootSetMaxCount); + registerMethod(L, "Loot", "setSubType", LootFunctions::luaLootSetSubType); + registerMethod(L, "Loot", "setChance", LootFunctions::luaLootSetChance); + registerMethod(L, "Loot", "setActionId", LootFunctions::luaLootSetActionId); + registerMethod(L, "Loot", "setText", LootFunctions::luaLootSetText); + registerMethod(L, "Loot", "setNameItem", LootFunctions::luaLootSetNameItem); + registerMethod(L, "Loot", "setArticle", LootFunctions::luaLootSetArticle); + registerMethod(L, "Loot", "setAttack", LootFunctions::luaLootSetAttack); + registerMethod(L, "Loot", "setDefense", LootFunctions::luaLootSetDefense); + registerMethod(L, "Loot", "setExtraDefense", LootFunctions::luaLootSetExtraDefense); + registerMethod(L, "Loot", "setArmor", LootFunctions::luaLootSetArmor); + registerMethod(L, "Loot", "setShootRange", LootFunctions::luaLootSetShootRange); + registerMethod(L, "Loot", "setHitChance", LootFunctions::luaLootSetHitChance); + registerMethod(L, "Loot", "setUnique", LootFunctions::luaLootSetUnique); + registerMethod(L, "Loot", "addChildLoot", LootFunctions::luaLootAddChildLoot); } private: @@ -62,4 +62,4 @@ class LootFunctions final : LuaScriptInterface { static int luaLootAddChildLoot(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_LOOT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_LOOT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/monster/monster_functions.cpp b/src/lua/functions/creatures/monster/monster_functions.cpp index a9cff1c4df6..42c46fba2cb 100644 --- a/src/lua/functions/creatures/monster/monster_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -68,7 +68,7 @@ int MonsterFunctions::luaMonsterSetType(lua_State* L) { monsterType = g_monsters().getMonsterType(getString(L, 2)); } // Unregister creature events (current MonsterType) - for (const std::string& scriptName : monster->mType->info.scripts) { + for (const std::string &scriptName : monster->mType->info.scripts) { if (!monster->unregisterCreatureEvent(scriptName)) { SPDLOG_WARN("[Warning - MonsterFunctions::luaMonsterSetType] Unknown event name: {}", scriptName); } @@ -87,7 +87,7 @@ int MonsterFunctions::luaMonsterSetType(lua_State* L) { monster->hiddenHealth = monsterType->info.hiddenHealth; monster->targetDistance = monsterType->info.targetDistance; // Register creature events (new MonsterType) - for (const std::string& scriptName : monsterType->info.scripts) { + for (const std::string &scriptName : monsterType->info.scripts) { if (!monster->registerCreatureEvent(scriptName)) { SPDLOG_WARN("[Warning - MonsterFunctions::luaMonsterSetType] Unknown event name: {}", scriptName); } @@ -223,7 +223,7 @@ int MonsterFunctions::luaMonsterGetFriendList(lua_State* L) { return 1; } - const auto& friendList = monster->getFriendList(); + const auto &friendList = monster->getFriendList(); lua_createtable(L, friendList.size(), 0); int index = 0; @@ -282,7 +282,7 @@ int MonsterFunctions::luaMonsterGetTargetList(lua_State* L) { return 1; } - const auto& targetList = monster->getTargetList(); + const auto &targetList = monster->getTargetList(); lua_createtable(L, targetList.size(), 0); int index = 0; @@ -311,8 +311,7 @@ int MonsterFunctions::luaMonsterChangeTargetDistance(lua_State* L) { if (monster) { int32_t distance = getNumber(L, 2, 1); pushBoolean(L, monster->changeTargetDistance(distance)); - } - else { + } else { lua_pushnil(L); } return 1; @@ -350,11 +349,11 @@ int MonsterFunctions::luaMonsterSetSpawnPosition(lua_State* L) { return 1; } - const Position& pos = monster->getPosition(); + const Position &pos = monster->getPosition(); monster->setMasterPos(pos); g_game().map.spawnsMonster.getspawnMonsterList().emplace_front(pos, 5); - SpawnMonster& spawnMonster = g_game().map.spawnsMonster.getspawnMonsterList().front(); + SpawnMonster &spawnMonster = g_game().map.spawnsMonster.getspawnMonsterList().front(); spawnMonster.addMonster(monster->mType->name, pos, DIRECTION_NORTH, 60000); spawnMonster.startSpawnMonsterCheck(); @@ -362,9 +361,9 @@ int MonsterFunctions::luaMonsterSetSpawnPosition(lua_State* L) { return 1; } -int MonsterFunctions::luaMonsterGetRespawnType(lua_State *L) { +int MonsterFunctions::luaMonsterGetRespawnType(lua_State* L) { // monster:getRespawnType() - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { lua_pushnil(L); @@ -378,9 +377,9 @@ int MonsterFunctions::luaMonsterGetRespawnType(lua_State *L) { return 2; } -int MonsterFunctions::luaMonsterGetTimeToChangeFiendish(lua_State *L) { +int MonsterFunctions::luaMonsterGetTimeToChangeFiendish(lua_State* L) { // monster:getTimeToChangeFiendish() - const Monster *monster = getUserdata(L, 1); + const Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -391,10 +390,10 @@ int MonsterFunctions::luaMonsterGetTimeToChangeFiendish(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterSetTimeToChangeFiendish(lua_State *L) { +int MonsterFunctions::luaMonsterSetTimeToChangeFiendish(lua_State* L) { // monster:setTimeToChangeFiendish(endTime) time_t endTime = getNumber(L, 2, 1); - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -405,9 +404,9 @@ int MonsterFunctions::luaMonsterSetTimeToChangeFiendish(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterGetMonsterForgeClassification(lua_State *L) { +int MonsterFunctions::luaMonsterGetMonsterForgeClassification(lua_State* L) { // monster:getMonsterForgeClassification() - const Monster *monster = getUserdata(L, 1); + const Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -419,10 +418,10 @@ int MonsterFunctions::luaMonsterGetMonsterForgeClassification(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterSetMonsterForgeClassification(lua_State *L) { +int MonsterFunctions::luaMonsterSetMonsterForgeClassification(lua_State* L) { // monster:setMonsterForgeClassification(classication) ForgeClassifications_t classification = getNumber(L, 2); - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -433,9 +432,9 @@ int MonsterFunctions::luaMonsterSetMonsterForgeClassification(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterGetForgeStack(lua_State *L) { +int MonsterFunctions::luaMonsterGetForgeStack(lua_State* L) { // monster:getForgeStack() - const Monster *monster = getUserdata(L, 1); + const Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -446,10 +445,10 @@ int MonsterFunctions::luaMonsterGetForgeStack(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterSetForgeStack(lua_State *L) { +int MonsterFunctions::luaMonsterSetForgeStack(lua_State* L) { // monster:setForgeStack(stack) uint16_t stack = getNumber(L, 2, 0); - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -463,9 +462,9 @@ int MonsterFunctions::luaMonsterSetForgeStack(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterConfigureForgeSystem(lua_State *L) { +int MonsterFunctions::luaMonsterConfigureForgeSystem(lua_State* L) { // monster:configureForgeSystem() - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -476,9 +475,9 @@ int MonsterFunctions::luaMonsterConfigureForgeSystem(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterClearFiendishStatus(lua_State *L) { +int MonsterFunctions::luaMonsterClearFiendishStatus(lua_State* L) { // monster:clearFiendishStatus() - Monster *monster = getUserdata(L, 1); + Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -489,9 +488,9 @@ int MonsterFunctions::luaMonsterClearFiendishStatus(lua_State *L) { return 1; } -int MonsterFunctions::luaMonsterIsForgeable(lua_State *L) { +int MonsterFunctions::luaMonsterIsForgeable(lua_State* L) { // monster:isForgeable() - const Monster *monster = getUserdata(L, 1); + const Monster* monster = getUserdata(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); diff --git a/src/lua/functions/creatures/monster/monster_functions.hpp b/src/lua/functions/creatures/monster/monster_functions.hpp index 328750125c7..9f07ea99d29 100644 --- a/src/lua/functions/creatures/monster/monster_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_FUNCTIONS_HPP_ @@ -18,48 +18,48 @@ class MonsterFunctions final : LuaScriptInterface { private: - static void init(lua_State* L) { - registerClass(L, "Monster", "Creature", MonsterFunctions::luaMonsterCreate); - registerMetaMethod(L, "Monster", "__eq", MonsterFunctions::luaUserdataCompare); - registerMethod(L, "Monster", "isMonster", MonsterFunctions::luaMonsterIsMonster); - registerMethod(L, "Monster", "getType", MonsterFunctions::luaMonsterGetType); - registerMethod(L, "Monster", "setType", MonsterFunctions::luaMonsterSetType); - registerMethod(L, "Monster", "getSpawnPosition", MonsterFunctions::luaMonsterGetSpawnPosition); - registerMethod(L, "Monster", "isInSpawnRange", MonsterFunctions::luaMonsterIsInSpawnRange); - registerMethod(L, "Monster", "isIdle", MonsterFunctions::luaMonsterIsIdle); - registerMethod(L, "Monster", "setIdle", MonsterFunctions::luaMonsterSetIdle); - registerMethod(L, "Monster", "isTarget", MonsterFunctions::luaMonsterIsTarget); - registerMethod(L, "Monster", "isOpponent", MonsterFunctions::luaMonsterIsOpponent); - registerMethod(L, "Monster", "isFriend", MonsterFunctions::luaMonsterIsFriend); - registerMethod(L, "Monster", "addFriend", MonsterFunctions::luaMonsterAddFriend); - registerMethod(L, "Monster", "removeFriend", MonsterFunctions::luaMonsterRemoveFriend); - registerMethod(L, "Monster", "getFriendList", MonsterFunctions::luaMonsterGetFriendList); - registerMethod(L, "Monster", "getFriendCount", MonsterFunctions::luaMonsterGetFriendCount); - registerMethod(L, "Monster", "addTarget", MonsterFunctions::luaMonsterAddTarget); - registerMethod(L, "Monster", "removeTarget", MonsterFunctions::luaMonsterRemoveTarget); - registerMethod(L, "Monster", "getTargetList", MonsterFunctions::luaMonsterGetTargetList); - registerMethod(L, "Monster", "getTargetCount", MonsterFunctions::luaMonsterGetTargetCount); - registerMethod(L, "Monster", "changeTargetDistance", MonsterFunctions::luaMonsterChangeTargetDistance); - registerMethod(L, "Monster", "selectTarget", MonsterFunctions::luaMonsterSelectTarget); - registerMethod(L, "Monster", "searchTarget", MonsterFunctions::luaMonsterSearchTarget); - registerMethod(L, "Monster", "setSpawnPosition", MonsterFunctions::luaMonsterSetSpawnPosition); - registerMethod(L, "Monster", "getRespawnType", MonsterFunctions::luaMonsterGetRespawnType); - - registerMethod(L, "Monster", "getTimeToChangeFiendish", MonsterFunctions::luaMonsterGetTimeToChangeFiendish); - registerMethod(L, "Monster", "setTimeToChangeFiendish", MonsterFunctions::luaMonsterSetTimeToChangeFiendish); - registerMethod(L, "Monster", "getMonsterForgeClassification", MonsterFunctions::luaMonsterGetMonsterForgeClassification); - registerMethod(L, "Monster", "setMonsterForgeClassification", MonsterFunctions::luaMonsterSetMonsterForgeClassification); - registerMethod(L, "Monster", "getForgeStack", MonsterFunctions::luaMonsterGetForgeStack); - registerMethod(L, "Monster", "setForgeStack", MonsterFunctions::luaMonsterSetForgeStack); - registerMethod(L, "Monster", "configureForgeSystem", MonsterFunctions::luaMonsterConfigureForgeSystem); - registerMethod(L, "Monster", "clearFiendishStatus", MonsterFunctions::luaMonsterClearFiendishStatus); - registerMethod(L, "Monster", "isForgeable", MonsterFunctions::luaMonsterIsForgeable); - - CharmFunctions::init(L); - LootFunctions::init(L); - MonsterSpellFunctions::init(L); - MonsterTypeFunctions::init(L); - } + static void init(lua_State* L) { + registerClass(L, "Monster", "Creature", MonsterFunctions::luaMonsterCreate); + registerMetaMethod(L, "Monster", "__eq", MonsterFunctions::luaUserdataCompare); + registerMethod(L, "Monster", "isMonster", MonsterFunctions::luaMonsterIsMonster); + registerMethod(L, "Monster", "getType", MonsterFunctions::luaMonsterGetType); + registerMethod(L, "Monster", "setType", MonsterFunctions::luaMonsterSetType); + registerMethod(L, "Monster", "getSpawnPosition", MonsterFunctions::luaMonsterGetSpawnPosition); + registerMethod(L, "Monster", "isInSpawnRange", MonsterFunctions::luaMonsterIsInSpawnRange); + registerMethod(L, "Monster", "isIdle", MonsterFunctions::luaMonsterIsIdle); + registerMethod(L, "Monster", "setIdle", MonsterFunctions::luaMonsterSetIdle); + registerMethod(L, "Monster", "isTarget", MonsterFunctions::luaMonsterIsTarget); + registerMethod(L, "Monster", "isOpponent", MonsterFunctions::luaMonsterIsOpponent); + registerMethod(L, "Monster", "isFriend", MonsterFunctions::luaMonsterIsFriend); + registerMethod(L, "Monster", "addFriend", MonsterFunctions::luaMonsterAddFriend); + registerMethod(L, "Monster", "removeFriend", MonsterFunctions::luaMonsterRemoveFriend); + registerMethod(L, "Monster", "getFriendList", MonsterFunctions::luaMonsterGetFriendList); + registerMethod(L, "Monster", "getFriendCount", MonsterFunctions::luaMonsterGetFriendCount); + registerMethod(L, "Monster", "addTarget", MonsterFunctions::luaMonsterAddTarget); + registerMethod(L, "Monster", "removeTarget", MonsterFunctions::luaMonsterRemoveTarget); + registerMethod(L, "Monster", "getTargetList", MonsterFunctions::luaMonsterGetTargetList); + registerMethod(L, "Monster", "getTargetCount", MonsterFunctions::luaMonsterGetTargetCount); + registerMethod(L, "Monster", "changeTargetDistance", MonsterFunctions::luaMonsterChangeTargetDistance); + registerMethod(L, "Monster", "selectTarget", MonsterFunctions::luaMonsterSelectTarget); + registerMethod(L, "Monster", "searchTarget", MonsterFunctions::luaMonsterSearchTarget); + registerMethod(L, "Monster", "setSpawnPosition", MonsterFunctions::luaMonsterSetSpawnPosition); + registerMethod(L, "Monster", "getRespawnType", MonsterFunctions::luaMonsterGetRespawnType); + + registerMethod(L, "Monster", "getTimeToChangeFiendish", MonsterFunctions::luaMonsterGetTimeToChangeFiendish); + registerMethod(L, "Monster", "setTimeToChangeFiendish", MonsterFunctions::luaMonsterSetTimeToChangeFiendish); + registerMethod(L, "Monster", "getMonsterForgeClassification", MonsterFunctions::luaMonsterGetMonsterForgeClassification); + registerMethod(L, "Monster", "setMonsterForgeClassification", MonsterFunctions::luaMonsterSetMonsterForgeClassification); + registerMethod(L, "Monster", "getForgeStack", MonsterFunctions::luaMonsterGetForgeStack); + registerMethod(L, "Monster", "setForgeStack", MonsterFunctions::luaMonsterSetForgeStack); + registerMethod(L, "Monster", "configureForgeSystem", MonsterFunctions::luaMonsterConfigureForgeSystem); + registerMethod(L, "Monster", "clearFiendishStatus", MonsterFunctions::luaMonsterClearFiendishStatus); + registerMethod(L, "Monster", "isForgeable", MonsterFunctions::luaMonsterIsForgeable); + + CharmFunctions::init(L); + LootFunctions::init(L); + MonsterSpellFunctions::init(L); + MonsterTypeFunctions::init(L); + } static int luaMonsterCreate(lua_State* L); @@ -96,17 +96,17 @@ class MonsterFunctions final : LuaScriptInterface { static int luaMonsterSetSpawnPosition(lua_State* L); static int luaMonsterGetRespawnType(lua_State* L); - static int luaMonsterGetTimeToChangeFiendish(lua_State *L); - static int luaMonsterSetTimeToChangeFiendish(lua_State *L); - static int luaMonsterGetMonsterForgeClassification(lua_State *L); - static int luaMonsterSetMonsterForgeClassification(lua_State *L); - static int luaMonsterGetForgeStack(lua_State *L); - static int luaMonsterSetForgeStack(lua_State *L); - static int luaMonsterConfigureForgeSystem(lua_State *L); - static int luaMonsterClearFiendishStatus(lua_State *L); - static int luaMonsterIsForgeable(lua_State *L); + static int luaMonsterGetTimeToChangeFiendish(lua_State* L); + static int luaMonsterSetTimeToChangeFiendish(lua_State* L); + static int luaMonsterGetMonsterForgeClassification(lua_State* L); + static int luaMonsterSetMonsterForgeClassification(lua_State* L); + static int luaMonsterGetForgeStack(lua_State* L); + static int luaMonsterSetForgeStack(lua_State* L); + static int luaMonsterConfigureForgeSystem(lua_State* L); + static int luaMonsterClearFiendishStatus(lua_State* L); + static int luaMonsterIsForgeable(lua_State* L); friend class CreatureFunctions; }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/monster/monster_spell_functions.cpp b/src/lua/functions/creatures/monster/monster_spell_functions.cpp index 11c55a90776..3a956da7641 100644 --- a/src/lua/functions/creatures/monster/monster_spell_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_spell_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/creatures/monster/monster_spell_functions.hpp b/src/lua/functions/creatures/monster/monster_spell_functions.hpp index c11a4961563..627746d1aaf 100644 --- a/src/lua/functions/creatures/monster/monster_spell_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_spell_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_SPELL_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_SPELL_FUNCTIONS_HPP_ @@ -67,4 +67,4 @@ class MonsterSpellFunctions final : LuaScriptInterface { static int luaMonsterSpellSetOutfitItem(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_SPELL_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_SPELL_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/monster/monster_type_functions.cpp b/src/lua/functions/creatures/monster/monster_type_functions.cpp index 10150e62e8c..c8af4c55824 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -15,11 +15,11 @@ #include "lua/functions/creatures/monster/monster_type_functions.hpp" #include "lua/scripts/scripts.h" -void MonsterTypeFunctions::createMonsterTypeLootLuaTable(lua_State* L, const std::vector& lootList) { +void MonsterTypeFunctions::createMonsterTypeLootLuaTable(lua_State* L, const std::vector &lootList) { lua_createtable(L, lootList.size(), 0); int index = 0; - for (const auto& lootBlock : lootList) { + for (const auto &lootBlock : lootList) { lua_createtable(L, 0, 8); setField(L, "itemId", lootBlock.id); @@ -238,11 +238,10 @@ int MonsterTypeFunctions::luaMonsterTypeIsForgeCreature(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanSpawn(lua_State* L) { // monsterType:canSpawn(pos) MonsterType* monsterType = getUserdata(L, 1); - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); if (monsterType) { pushBoolean(L, monsterType->canSpawn(position)); - } - else { + } else { lua_pushnil(L); } return 1; @@ -387,27 +386,23 @@ int MonsterTypeFunctions::luaMonsterTypeExperience(lua_State* L) { return 1; } -int MonsterTypeFunctions::luaMonsterTypeFaction(lua_State* L) -{ +int MonsterTypeFunctions::luaMonsterTypeFaction(lua_State* L) { // get: monsterType:faction() set: monsterType:faction(faction) MonsterType* monsterType = getUserdata(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.faction); - } - else { + } else { monsterType->info.faction = getNumber(L, 2); pushBoolean(L, true); } - } - else { + } else { lua_pushnil(L); } return 1; } -int MonsterTypeFunctions::luaMonsterTypeEnemyFactions(lua_State* L) -{ +int MonsterTypeFunctions::luaMonsterTypeEnemyFactions(lua_State* L) { // get: monsterType:enemyFactions() set: monsterType:enemyFactions(enemyFaction) MonsterType* monsterType = getUserdata(L, 1); if (monsterType) { @@ -419,52 +414,44 @@ int MonsterTypeFunctions::luaMonsterTypeEnemyFactions(lua_State* L) lua_pushnumber(L, faction); lua_rawseti(L, -2, ++index); } - } - else { + } else { Faction_t faction = getNumber(L, 2); monsterType->info.enemyFactions.emplace(faction); pushBoolean(L, true); } - } - else { + } else { lua_pushnil(L); } return 1; } -int MonsterTypeFunctions::luaMonsterTypeTargetPreferPlayer(lua_State* L) -{ +int MonsterTypeFunctions::luaMonsterTypeTargetPreferPlayer(lua_State* L) { // get: monsterType:targetPreferPlayer() set: monsterType:targetPreferPlayer(bool) MonsterType* monsterType = getUserdata(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushboolean(L, monsterType->info.targetPreferPlayer); - } - else { + } else { monsterType->info.targetPreferPlayer = getBoolean(L, 2); pushBoolean(L, true); } - } - else { + } else { lua_pushnil(L); } return 1; } -int MonsterTypeFunctions::luaMonsterTypeTargetPreferMaster(lua_State* L) -{ +int MonsterTypeFunctions::luaMonsterTypeTargetPreferMaster(lua_State* L) { // get: monsterType:targetPreferMaster() set: monsterType:targetPreferMaster(bool) MonsterType* monsterType = getUserdata(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.faction); - } - else { + } else { monsterType->info.targetPreferMaster = getBoolean(L, 2); pushBoolean(L, true); } - } - else { + } else { lua_pushnil(L); } return 1; @@ -754,7 +741,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetAttackList(lua_State* L) { lua_createtable(L, monsterType->info.attackSpells.size(), 0); int index = 0; - for (const auto& spellBlock : monsterType->info.attackSpells) { + for (const auto &spellBlock : monsterType->info.attackSpells) { lua_createtable(L, 0, 8); setField(L, "chance", spellBlock.chance); @@ -782,8 +769,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddAttack(lua_State* L) { if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { monsterType->info.attackSpells.push_back(std::move(sb)); } else { - SPDLOG_WARN("Monster: {}, cant load spell: {}", monsterType->name, - spell->name); + SPDLOG_WARN("Monster: {}, cant load spell: {}", monsterType->name, spell->name); } } else { lua_pushnil(L); @@ -804,9 +790,8 @@ int MonsterTypeFunctions::luaMonsterTypeGetDefenseList(lua_State* L) { lua_createtable(L, monsterType->info.defenseSpells.size(), 0); - int index = 0; - for (const auto& spellBlock : monsterType->info.defenseSpells) { + for (const auto &spellBlock : monsterType->info.defenseSpells) { lua_createtable(L, 0, 8); setField(L, "chance", spellBlock.chance); @@ -845,8 +830,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddDefense(lua_State* L) { if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { monsterType->info.defenseSpells.push_back(std::move(sb)); } else { - SPDLOG_WARN("Monster: {}, Cant load spell: {}", monsterType->name, - spell->name); + SPDLOG_WARN("Monster: {}, Cant load spell: {}", monsterType->name, spell->name); } } else { lua_pushnil(L); @@ -905,7 +889,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetElementList(lua_State* L) { } lua_createtable(L, monsterType->info.elementMap.size(), 0); - for (const auto& elementEntry : monsterType->info.elementMap) { + for (const auto &elementEntry : monsterType->info.elementMap) { lua_pushnumber(L, elementEntry.second); lua_rawseti(L, -2, elementEntry.first); } @@ -939,7 +923,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetVoices(lua_State* L) { int index = 0; lua_createtable(L, monsterType->info.voiceVector.size(), 0); - for (const auto& voiceBlock : monsterType->info.voiceVector) { + for (const auto &voiceBlock : monsterType->info.voiceVector) { lua_createtable(L, 0, 2); setField(L, "text", voiceBlock.text); setField(L, "yellText", voiceBlock.yellText); @@ -987,7 +971,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetCreatureEvents(lua_State* L) { int index = 0; lua_createtable(L, monsterType->info.scripts.size(), 0); - for (const std::string& creatureEvent : monsterType->info.scripts) { + for (const std::string &creatureEvent : monsterType->info.scripts) { pushString(L, creatureEvent); lua_rawseti(L, -2, ++index); } @@ -1017,7 +1001,7 @@ int MonsterTypeFunctions::luaMonsterTypeEventOnCallback(lua_State* L) { if (monsterType->loadCallback(&g_scripts().getScriptInterface())) { pushBoolean(L, true); return 1; - } + } pushBoolean(L, false); } else { lua_pushnil(L); @@ -1047,7 +1031,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetSummonList(lua_State* L) { int index = 0; lua_createtable(L, monsterType->info.summons.size(), 0); - for (const auto& summonBlock : monsterType->info.summons) { + for (const auto &summonBlock : monsterType->info.summons) { lua_createtable(L, 0, 3); setField(L, "name", summonBlock.name); setField(L, "speed", summonBlock.speed); @@ -1166,7 +1150,8 @@ int MonsterTypeFunctions::luaMonsterTypeRace(lua_State* L) { monsterType->info.race = RACE_INK; } else { SPDLOG_WARN("[MonsterTypeFunctions::luaMonsterTypeRace] - " - "Unknown race type {}", race); + "Unknown race type {}", + race); lua_pushnil(L); return 1; } @@ -1283,11 +1268,11 @@ int MonsterTypeFunctions::luaMonsterTypeYellChance(lua_State* L) { if (monsterType) { if (lua_gettop(L) == 1) { if (lua_gettop(L) == 1) { - lua_pushnumber(L, monsterType->info.yellChance); - } else { - monsterType->info.yellChance = getNumber(L, 2); - pushBoolean(L, true); - } + lua_pushnumber(L, monsterType->info.yellChance); + } else { + monsterType->info.yellChance = getNumber(L, 2); + pushBoolean(L, true); + } } else { monsterType->info.yellChance = getNumber(L, 2); pushBoolean(L, true); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.hpp b/src/lua/functions/creatures/monster/monster_type_functions.hpp index 831f5870123..2f34b430eba 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_TYPE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_TYPE_FUNCTIONS_HPP_ @@ -13,240 +13,233 @@ #include "lua/scripts/luascript.h" class MonsterTypeFunctions final : LuaScriptInterface { -public: - static void init(lua_State* L) { - registerClass(L, "MonsterType", "", MonsterTypeFunctions::luaMonsterTypeCreate); - registerMetaMethod(L, "MonsterType", "__eq", MonsterTypeFunctions::luaUserdataCompare); - - registerMethod(L, "MonsterType", "isAttackable", MonsterTypeFunctions::luaMonsterTypeIsAttackable); - registerMethod(L, "MonsterType", "isConvinceable", MonsterTypeFunctions::luaMonsterTypeIsConvinceable); - registerMethod(L, "MonsterType", "isSummonable", MonsterTypeFunctions::luaMonsterTypeIsSummonable); - registerMethod(L, "MonsterType", "isIllusionable", MonsterTypeFunctions::luaMonsterTypeIsIllusionable); - registerMethod(L, "MonsterType", "isHostile", MonsterTypeFunctions::luaMonsterTypeIsHostile); - registerMethod(L, "MonsterType", "isPushable", MonsterTypeFunctions::luaMonsterTypeIsPushable); - registerMethod(L, "MonsterType", "isHealthHidden", MonsterTypeFunctions::luaMonsterTypeIsHealthHidden); - registerMethod(L, "MonsterType", "isBlockable", MonsterTypeFunctions::luaMonsterTypeIsBlockable); - registerMethod(L, "MonsterType", "isForgeCreature", MonsterTypeFunctions::luaMonsterTypeIsForgeCreature); - - registerMethod(L, "MonsterType", "familiar", MonsterTypeFunctions::luaMonsterTypeFamiliar); - registerMethod(L, "MonsterType", "isRewardBoss", MonsterTypeFunctions::luaMonsterTypeIsRewardBoss); - - registerMethod(L, "MonsterType", "canSpawn", MonsterTypeFunctions::luaMonsterTypeCanSpawn); - - registerMethod(L, "MonsterType", "canPushItems", MonsterTypeFunctions::luaMonsterTypeCanPushItems); - registerMethod(L, "MonsterType", "canPushCreatures", MonsterTypeFunctions::luaMonsterTypeCanPushCreatures); - - registerMethod(L, "MonsterType", "name", MonsterTypeFunctions::luaMonsterTypeName); - - registerMethod(L, "MonsterType", "nameDescription", MonsterTypeFunctions::luaMonsterTypeNameDescription); - - registerMethod(L, "MonsterType", "getCorpseId", MonsterTypeFunctions::luaMonsterTypegetCorpseId); - - registerMethod(L, "MonsterType", "health", MonsterTypeFunctions::luaMonsterTypeHealth); - registerMethod(L, "MonsterType", "maxHealth", MonsterTypeFunctions::luaMonsterTypeMaxHealth); - registerMethod(L, "MonsterType", "runHealth", MonsterTypeFunctions::luaMonsterTypeRunHealth); - registerMethod(L, "MonsterType", "experience", MonsterTypeFunctions::luaMonsterTypeExperience); - - registerMethod(L, "MonsterType", "faction", MonsterTypeFunctions::luaMonsterTypeFaction); - registerMethod(L, "MonsterType", "enemyFactions", MonsterTypeFunctions::luaMonsterTypeEnemyFactions); - registerMethod(L, "MonsterType", "targetPreferPlayer", MonsterTypeFunctions::luaMonsterTypeTargetPreferPlayer); - registerMethod(L, "MonsterType", "targetPreferMaster", MonsterTypeFunctions::luaMonsterTypeTargetPreferMaster); - - registerMethod(L, "MonsterType", "raceId", MonsterTypeFunctions::luaMonsterTypeRaceid); - registerMethod(L, "MonsterType", "Bestiaryclass", MonsterTypeFunctions::luaMonsterTypeBestiaryclass); - registerMethod(L, "MonsterType", "BestiaryOccurrence", MonsterTypeFunctions::luaMonsterTypeBestiaryOccurrence); - registerMethod(L, "MonsterType", "BestiaryLocations", MonsterTypeFunctions::luaMonsterTypeBestiaryLocations); - registerMethod(L, "MonsterType", "BestiaryStars", MonsterTypeFunctions::luaMonsterTypeBestiaryStars); - registerMethod(L, "MonsterType", "BestiaryCharmsPoints", MonsterTypeFunctions::luaMonsterTypeBestiaryCharmsPoints); - registerMethod(L, "MonsterType", "BestiarySecondUnlock", MonsterTypeFunctions::luaMonsterTypeBestiarySecondUnlock); - registerMethod(L, "MonsterType", "BestiaryFirstUnlock", MonsterTypeFunctions::luaMonsterTypeBestiaryFirstUnlock); - registerMethod(L, "MonsterType", "BestiarytoKill", MonsterTypeFunctions::luaMonsterTypeBestiarytoKill); - registerMethod(L, "MonsterType", "Bestiaryrace", MonsterTypeFunctions::luaMonsterTypeBestiaryrace); - - registerMethod(L, "MonsterType", "combatImmunities", MonsterTypeFunctions::luaMonsterTypeCombatImmunities); - registerMethod(L, "MonsterType", "conditionImmunities", MonsterTypeFunctions::luaMonsterTypeConditionImmunities); - - registerMethod(L, "MonsterType", "getAttackList", MonsterTypeFunctions::luaMonsterTypeGetAttackList); - registerMethod(L, "MonsterType", "addAttack", MonsterTypeFunctions::luaMonsterTypeAddAttack); - - registerMethod(L, "MonsterType", "getDefenseList", MonsterTypeFunctions::luaMonsterTypeGetDefenseList); - registerMethod(L, "MonsterType", "addDefense", MonsterTypeFunctions::luaMonsterTypeAddDefense); - - registerMethod(L, "MonsterType", "getTypeName", MonsterTypeFunctions::luaMonsterTypeGetTypeName); - - registerMethod(L, "MonsterType", "getElementList", MonsterTypeFunctions::luaMonsterTypeGetElementList); - registerMethod(L, "MonsterType", "addElement", MonsterTypeFunctions::luaMonsterTypeAddElement); - - registerMethod(L, "MonsterType", "addReflect", MonsterTypeFunctions::luaMonsterTypeAddReflect); - registerMethod(L, "MonsterType", "addHealing", MonsterTypeFunctions::luaMonsterTypeAddHealing); - - registerMethod(L, "MonsterType", "getVoices", MonsterTypeFunctions::luaMonsterTypeGetVoices); - registerMethod(L, "MonsterType", "addVoice", MonsterTypeFunctions::luaMonsterTypeAddVoice); - - registerMethod(L, "MonsterType", "getLoot", MonsterTypeFunctions::luaMonsterTypeGetLoot); - registerMethod(L, "MonsterType", "addLoot", MonsterTypeFunctions::luaMonsterTypeAddLoot); - - registerMethod(L, "MonsterType", "getCreatureEvents", MonsterTypeFunctions::luaMonsterTypeGetCreatureEvents); - registerMethod(L, "MonsterType", "registerEvent", MonsterTypeFunctions::luaMonsterTypeRegisterEvent); - - registerMethod(L, "MonsterType", "eventType", MonsterTypeFunctions::luaMonsterTypeEventType); - registerMethod(L, "MonsterType", "onThink", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); - registerMethod(L, "MonsterType", "onAppear", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); - registerMethod(L, "MonsterType", "onDisappear", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); - registerMethod(L, "MonsterType", "onMove", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); - registerMethod(L, "MonsterType", "onSay", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); - - registerMethod(L, "MonsterType", "getSummonList", MonsterTypeFunctions::luaMonsterTypeGetSummonList); - registerMethod(L, "MonsterType", "addSummon", MonsterTypeFunctions::luaMonsterTypeAddSummon); - - registerMethod(L, "MonsterType", "maxSummons", MonsterTypeFunctions::luaMonsterTypeMaxSummons); - - registerMethod(L, "MonsterType", "armor", MonsterTypeFunctions::luaMonsterTypeArmor); - registerMethod(L, "MonsterType", "defense", MonsterTypeFunctions::luaMonsterTypeDefense); - registerMethod(L, "MonsterType", "outfit", MonsterTypeFunctions::luaMonsterTypeOutfit); - registerMethod(L, "MonsterType", "race", MonsterTypeFunctions::luaMonsterTypeRace); - registerMethod(L, "MonsterType", "corpseId", MonsterTypeFunctions::luaMonsterTypeCorpseId); - registerMethod(L, "MonsterType", "manaCost", MonsterTypeFunctions::luaMonsterTypeManaCost); - registerMethod(L, "MonsterType", "baseSpeed", MonsterTypeFunctions::luaMonsterTypeBaseSpeed); - registerMethod(L, "MonsterType", "light", MonsterTypeFunctions::luaMonsterTypeLight); - - registerMethod(L, "MonsterType", "staticAttackChance", MonsterTypeFunctions::luaMonsterTypeStaticAttackChance); - registerMethod(L, "MonsterType", "targetDistance", MonsterTypeFunctions::luaMonsterTypeTargetDistance); - registerMethod(L, "MonsterType", "yellChance", MonsterTypeFunctions::luaMonsterTypeYellChance); - registerMethod(L, "MonsterType", "yellSpeedTicks", MonsterTypeFunctions::luaMonsterTypeYellSpeedTicks); - registerMethod(L, "MonsterType", "changeTargetChance", MonsterTypeFunctions::luaMonsterTypeChangeTargetChance); - registerMethod(L, "MonsterType", "changeTargetSpeed", MonsterTypeFunctions::luaMonsterTypeChangeTargetSpeed); - - registerMethod(L, "MonsterType", "canWalkOnEnergy", - MonsterTypeFunctions::luaMonsterTypeCanWalkOnEnergy); - registerMethod(L, "MonsterType", "canWalkOnFire", - MonsterTypeFunctions::luaMonsterTypeCanWalkOnFire); - registerMethod(L, "MonsterType", "canWalkOnPoison", - MonsterTypeFunctions::luaMonsterTypeCanWalkOnPoison); - - registerMethod(L, "MonsterType", "strategiesTargetNearest", - MonsterTypeFunctions::luaMonsterTypeStrategiesTargetNearest); - registerMethod(L, "MonsterType", "strategiesTargetHealth", - MonsterTypeFunctions::luaMonsterTypeStrategiesTargetHealth); - registerMethod(L, "MonsterType", "strategiesTargetDamage", - MonsterTypeFunctions::luaMonsterTypeStrategiesTargetDamage); - registerMethod(L, "MonsterType", "strategiesTargetRandom", - MonsterTypeFunctions::luaMonsterTypeStrategiesTargetRandom); - - registerMethod(L, "MonsterType", "respawnTypePeriod", MonsterTypeFunctions::luaMonsterTypeRespawnTypePeriod); - registerMethod(L, "MonsterType", "respawnTypeIsUnderground", MonsterTypeFunctions::luaMonsterTypeRespawnTypeIsUnderground); - } - -private: - static void createMonsterTypeLootLuaTable(lua_State* L, const std::vector& lootList); - - static int luaMonsterTypeCreate(lua_State* L); - - static int luaMonsterTypeIsAttackable(lua_State* L); - static int luaMonsterTypeIsConvinceable(lua_State* L); - static int luaMonsterTypeIsSummonable(lua_State* L); - static int luaMonsterTypeIsIllusionable(lua_State* L); - static int luaMonsterTypeIsHostile(lua_State* L); - static int luaMonsterTypeIsPushable(lua_State* L); - static int luaMonsterTypeIsHealthHidden(lua_State* L); - static int luaMonsterTypeIsBlockable(lua_State* L); - static int luaMonsterTypeIsForgeCreature(lua_State* L); - - static int luaMonsterTypeFamiliar(lua_State* L); - static int luaMonsterTypeIsRewardBoss(lua_State* L); - static int luaMonsterTypeRespawnType(lua_State* L); - static int luaMonsterTypeCanSpawn(lua_State* L); - - static int luaMonsterTypeCanPushItems(lua_State* L); - static int luaMonsterTypeCanPushCreatures(lua_State* L); - - static int luaMonsterTypeName(lua_State* L); - static int luaMonsterTypeNameDescription(lua_State* L); - - static int luaMonsterTypegetCorpseId(lua_State* L); - - static int luaMonsterTypeHealth(lua_State* L); - static int luaMonsterTypeMaxHealth(lua_State* L); - static int luaMonsterTypeRunHealth(lua_State* L); - static int luaMonsterTypeExperience(lua_State* L); - - static int luaMonsterTypeFaction(lua_State* L); - static int luaMonsterTypeEnemyFactions(lua_State* L); - static int luaMonsterTypeTargetPreferPlayer(lua_State* L); - static int luaMonsterTypeTargetPreferMaster(lua_State* L); - - static int luaMonsterTypeRaceid(lua_State* L); - static int luaMonsterTypeBestiaryclass(lua_State* L); - static int luaMonsterTypeBestiaryOccurrence(lua_State* L); - static int luaMonsterTypeBestiaryLocations(lua_State* L); - static int luaMonsterTypeBestiaryStars(lua_State* L); - static int luaMonsterTypeBestiaryCharmsPoints(lua_State* L); - static int luaMonsterTypeBestiarySecondUnlock(lua_State* L); - static int luaMonsterTypeBestiaryFirstUnlock(lua_State* L); - static int luaMonsterTypeBestiarytoKill(lua_State* L); - static int luaMonsterTypeBestiaryrace(lua_State* L); - - static int luaMonsterTypeCombatImmunities(lua_State* L); - static int luaMonsterTypeConditionImmunities(lua_State* L); - - static int luaMonsterTypeGetAttackList(lua_State* L); - static int luaMonsterTypeAddAttack(lua_State* L); - - static int luaMonsterTypeGetDefenseList(lua_State* L); - static int luaMonsterTypeAddDefense(lua_State* L); - - static int luaMonsterTypeGetTypeName(lua_State* L); - - static int luaMonsterTypeGetElementList(lua_State* L); - static int luaMonsterTypeAddElement(lua_State* L); - - static int luaMonsterTypeAddReflect(lua_State* L); - static int luaMonsterTypeAddHealing(lua_State* L); - - static int luaMonsterTypeGetVoices(lua_State* L); - static int luaMonsterTypeAddVoice(lua_State* L); - - static int luaMonsterTypeGetLoot(lua_State* L); - static int luaMonsterTypeAddLoot(lua_State* L); - - static int luaMonsterTypeGetCreatureEvents(lua_State* L); - static int luaMonsterTypeRegisterEvent(lua_State* L); - - static int luaMonsterTypeEventOnCallback(lua_State* L); - static int luaMonsterTypeEventType(lua_State* L); - - static int luaMonsterTypeGetSummonList(lua_State* L); - static int luaMonsterTypeAddSummon(lua_State* L); - - static int luaMonsterTypeMaxSummons(lua_State* L); - - static int luaMonsterTypeArmor(lua_State* L); - static int luaMonsterTypeDefense(lua_State* L); - static int luaMonsterTypeOutfit(lua_State* L); - static int luaMonsterTypeRace(lua_State* L); - static int luaMonsterTypeCorpseId(lua_State* L); - static int luaMonsterTypeManaCost(lua_State* L); - static int luaMonsterTypeBaseSpeed(lua_State* L); - static int luaMonsterTypeLight(lua_State* L); - - static int luaMonsterTypeStaticAttackChance(lua_State* L); - static int luaMonsterTypeTargetDistance(lua_State* L); - static int luaMonsterTypeYellChance(lua_State* L); - static int luaMonsterTypeYellSpeedTicks(lua_State* L); - static int luaMonsterTypeChangeTargetChance(lua_State* L); - static int luaMonsterTypeChangeTargetSpeed(lua_State* L); - - static int luaMonsterTypeCanWalkOnEnergy(lua_State* L); - static int luaMonsterTypeCanWalkOnFire(lua_State* L); - static int luaMonsterTypeCanWalkOnPoison(lua_State* L); - - static int luaMonsterTypeStrategiesTargetNearest(lua_State* L); - static int luaMonsterTypeStrategiesTargetHealth(lua_State* L); - static int luaMonsterTypeStrategiesTargetDamage(lua_State* L); - static int luaMonsterTypeStrategiesTargetRandom(lua_State* L); - - static int luaMonsterTypeRespawnTypePeriod(lua_State* L); - static int luaMonsterTypeRespawnTypeIsUnderground(lua_State* L); + public: + static void init(lua_State* L) { + registerClass(L, "MonsterType", "", MonsterTypeFunctions::luaMonsterTypeCreate); + registerMetaMethod(L, "MonsterType", "__eq", MonsterTypeFunctions::luaUserdataCompare); + + registerMethod(L, "MonsterType", "isAttackable", MonsterTypeFunctions::luaMonsterTypeIsAttackable); + registerMethod(L, "MonsterType", "isConvinceable", MonsterTypeFunctions::luaMonsterTypeIsConvinceable); + registerMethod(L, "MonsterType", "isSummonable", MonsterTypeFunctions::luaMonsterTypeIsSummonable); + registerMethod(L, "MonsterType", "isIllusionable", MonsterTypeFunctions::luaMonsterTypeIsIllusionable); + registerMethod(L, "MonsterType", "isHostile", MonsterTypeFunctions::luaMonsterTypeIsHostile); + registerMethod(L, "MonsterType", "isPushable", MonsterTypeFunctions::luaMonsterTypeIsPushable); + registerMethod(L, "MonsterType", "isHealthHidden", MonsterTypeFunctions::luaMonsterTypeIsHealthHidden); + registerMethod(L, "MonsterType", "isBlockable", MonsterTypeFunctions::luaMonsterTypeIsBlockable); + registerMethod(L, "MonsterType", "isForgeCreature", MonsterTypeFunctions::luaMonsterTypeIsForgeCreature); + + registerMethod(L, "MonsterType", "familiar", MonsterTypeFunctions::luaMonsterTypeFamiliar); + registerMethod(L, "MonsterType", "isRewardBoss", MonsterTypeFunctions::luaMonsterTypeIsRewardBoss); + + registerMethod(L, "MonsterType", "canSpawn", MonsterTypeFunctions::luaMonsterTypeCanSpawn); + + registerMethod(L, "MonsterType", "canPushItems", MonsterTypeFunctions::luaMonsterTypeCanPushItems); + registerMethod(L, "MonsterType", "canPushCreatures", MonsterTypeFunctions::luaMonsterTypeCanPushCreatures); + + registerMethod(L, "MonsterType", "name", MonsterTypeFunctions::luaMonsterTypeName); + + registerMethod(L, "MonsterType", "nameDescription", MonsterTypeFunctions::luaMonsterTypeNameDescription); + + registerMethod(L, "MonsterType", "getCorpseId", MonsterTypeFunctions::luaMonsterTypegetCorpseId); + + registerMethod(L, "MonsterType", "health", MonsterTypeFunctions::luaMonsterTypeHealth); + registerMethod(L, "MonsterType", "maxHealth", MonsterTypeFunctions::luaMonsterTypeMaxHealth); + registerMethod(L, "MonsterType", "runHealth", MonsterTypeFunctions::luaMonsterTypeRunHealth); + registerMethod(L, "MonsterType", "experience", MonsterTypeFunctions::luaMonsterTypeExperience); + + registerMethod(L, "MonsterType", "faction", MonsterTypeFunctions::luaMonsterTypeFaction); + registerMethod(L, "MonsterType", "enemyFactions", MonsterTypeFunctions::luaMonsterTypeEnemyFactions); + registerMethod(L, "MonsterType", "targetPreferPlayer", MonsterTypeFunctions::luaMonsterTypeTargetPreferPlayer); + registerMethod(L, "MonsterType", "targetPreferMaster", MonsterTypeFunctions::luaMonsterTypeTargetPreferMaster); + + registerMethod(L, "MonsterType", "raceId", MonsterTypeFunctions::luaMonsterTypeRaceid); + registerMethod(L, "MonsterType", "Bestiaryclass", MonsterTypeFunctions::luaMonsterTypeBestiaryclass); + registerMethod(L, "MonsterType", "BestiaryOccurrence", MonsterTypeFunctions::luaMonsterTypeBestiaryOccurrence); + registerMethod(L, "MonsterType", "BestiaryLocations", MonsterTypeFunctions::luaMonsterTypeBestiaryLocations); + registerMethod(L, "MonsterType", "BestiaryStars", MonsterTypeFunctions::luaMonsterTypeBestiaryStars); + registerMethod(L, "MonsterType", "BestiaryCharmsPoints", MonsterTypeFunctions::luaMonsterTypeBestiaryCharmsPoints); + registerMethod(L, "MonsterType", "BestiarySecondUnlock", MonsterTypeFunctions::luaMonsterTypeBestiarySecondUnlock); + registerMethod(L, "MonsterType", "BestiaryFirstUnlock", MonsterTypeFunctions::luaMonsterTypeBestiaryFirstUnlock); + registerMethod(L, "MonsterType", "BestiarytoKill", MonsterTypeFunctions::luaMonsterTypeBestiarytoKill); + registerMethod(L, "MonsterType", "Bestiaryrace", MonsterTypeFunctions::luaMonsterTypeBestiaryrace); + + registerMethod(L, "MonsterType", "combatImmunities", MonsterTypeFunctions::luaMonsterTypeCombatImmunities); + registerMethod(L, "MonsterType", "conditionImmunities", MonsterTypeFunctions::luaMonsterTypeConditionImmunities); + + registerMethod(L, "MonsterType", "getAttackList", MonsterTypeFunctions::luaMonsterTypeGetAttackList); + registerMethod(L, "MonsterType", "addAttack", MonsterTypeFunctions::luaMonsterTypeAddAttack); + + registerMethod(L, "MonsterType", "getDefenseList", MonsterTypeFunctions::luaMonsterTypeGetDefenseList); + registerMethod(L, "MonsterType", "addDefense", MonsterTypeFunctions::luaMonsterTypeAddDefense); + + registerMethod(L, "MonsterType", "getTypeName", MonsterTypeFunctions::luaMonsterTypeGetTypeName); + + registerMethod(L, "MonsterType", "getElementList", MonsterTypeFunctions::luaMonsterTypeGetElementList); + registerMethod(L, "MonsterType", "addElement", MonsterTypeFunctions::luaMonsterTypeAddElement); + + registerMethod(L, "MonsterType", "addReflect", MonsterTypeFunctions::luaMonsterTypeAddReflect); + registerMethod(L, "MonsterType", "addHealing", MonsterTypeFunctions::luaMonsterTypeAddHealing); + + registerMethod(L, "MonsterType", "getVoices", MonsterTypeFunctions::luaMonsterTypeGetVoices); + registerMethod(L, "MonsterType", "addVoice", MonsterTypeFunctions::luaMonsterTypeAddVoice); + + registerMethod(L, "MonsterType", "getLoot", MonsterTypeFunctions::luaMonsterTypeGetLoot); + registerMethod(L, "MonsterType", "addLoot", MonsterTypeFunctions::luaMonsterTypeAddLoot); + + registerMethod(L, "MonsterType", "getCreatureEvents", MonsterTypeFunctions::luaMonsterTypeGetCreatureEvents); + registerMethod(L, "MonsterType", "registerEvent", MonsterTypeFunctions::luaMonsterTypeRegisterEvent); + + registerMethod(L, "MonsterType", "eventType", MonsterTypeFunctions::luaMonsterTypeEventType); + registerMethod(L, "MonsterType", "onThink", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); + registerMethod(L, "MonsterType", "onAppear", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); + registerMethod(L, "MonsterType", "onDisappear", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); + registerMethod(L, "MonsterType", "onMove", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); + registerMethod(L, "MonsterType", "onSay", MonsterTypeFunctions::luaMonsterTypeEventOnCallback); + + registerMethod(L, "MonsterType", "getSummonList", MonsterTypeFunctions::luaMonsterTypeGetSummonList); + registerMethod(L, "MonsterType", "addSummon", MonsterTypeFunctions::luaMonsterTypeAddSummon); + + registerMethod(L, "MonsterType", "maxSummons", MonsterTypeFunctions::luaMonsterTypeMaxSummons); + + registerMethod(L, "MonsterType", "armor", MonsterTypeFunctions::luaMonsterTypeArmor); + registerMethod(L, "MonsterType", "defense", MonsterTypeFunctions::luaMonsterTypeDefense); + registerMethod(L, "MonsterType", "outfit", MonsterTypeFunctions::luaMonsterTypeOutfit); + registerMethod(L, "MonsterType", "race", MonsterTypeFunctions::luaMonsterTypeRace); + registerMethod(L, "MonsterType", "corpseId", MonsterTypeFunctions::luaMonsterTypeCorpseId); + registerMethod(L, "MonsterType", "manaCost", MonsterTypeFunctions::luaMonsterTypeManaCost); + registerMethod(L, "MonsterType", "baseSpeed", MonsterTypeFunctions::luaMonsterTypeBaseSpeed); + registerMethod(L, "MonsterType", "light", MonsterTypeFunctions::luaMonsterTypeLight); + + registerMethod(L, "MonsterType", "staticAttackChance", MonsterTypeFunctions::luaMonsterTypeStaticAttackChance); + registerMethod(L, "MonsterType", "targetDistance", MonsterTypeFunctions::luaMonsterTypeTargetDistance); + registerMethod(L, "MonsterType", "yellChance", MonsterTypeFunctions::luaMonsterTypeYellChance); + registerMethod(L, "MonsterType", "yellSpeedTicks", MonsterTypeFunctions::luaMonsterTypeYellSpeedTicks); + registerMethod(L, "MonsterType", "changeTargetChance", MonsterTypeFunctions::luaMonsterTypeChangeTargetChance); + registerMethod(L, "MonsterType", "changeTargetSpeed", MonsterTypeFunctions::luaMonsterTypeChangeTargetSpeed); + + registerMethod(L, "MonsterType", "canWalkOnEnergy", MonsterTypeFunctions::luaMonsterTypeCanWalkOnEnergy); + registerMethod(L, "MonsterType", "canWalkOnFire", MonsterTypeFunctions::luaMonsterTypeCanWalkOnFire); + registerMethod(L, "MonsterType", "canWalkOnPoison", MonsterTypeFunctions::luaMonsterTypeCanWalkOnPoison); + + registerMethod(L, "MonsterType", "strategiesTargetNearest", MonsterTypeFunctions::luaMonsterTypeStrategiesTargetNearest); + registerMethod(L, "MonsterType", "strategiesTargetHealth", MonsterTypeFunctions::luaMonsterTypeStrategiesTargetHealth); + registerMethod(L, "MonsterType", "strategiesTargetDamage", MonsterTypeFunctions::luaMonsterTypeStrategiesTargetDamage); + registerMethod(L, "MonsterType", "strategiesTargetRandom", MonsterTypeFunctions::luaMonsterTypeStrategiesTargetRandom); + + registerMethod(L, "MonsterType", "respawnTypePeriod", MonsterTypeFunctions::luaMonsterTypeRespawnTypePeriod); + registerMethod(L, "MonsterType", "respawnTypeIsUnderground", MonsterTypeFunctions::luaMonsterTypeRespawnTypeIsUnderground); + } + + private: + static void createMonsterTypeLootLuaTable(lua_State* L, const std::vector &lootList); + + static int luaMonsterTypeCreate(lua_State* L); + + static int luaMonsterTypeIsAttackable(lua_State* L); + static int luaMonsterTypeIsConvinceable(lua_State* L); + static int luaMonsterTypeIsSummonable(lua_State* L); + static int luaMonsterTypeIsIllusionable(lua_State* L); + static int luaMonsterTypeIsHostile(lua_State* L); + static int luaMonsterTypeIsPushable(lua_State* L); + static int luaMonsterTypeIsHealthHidden(lua_State* L); + static int luaMonsterTypeIsBlockable(lua_State* L); + static int luaMonsterTypeIsForgeCreature(lua_State* L); + + static int luaMonsterTypeFamiliar(lua_State* L); + static int luaMonsterTypeIsRewardBoss(lua_State* L); + static int luaMonsterTypeRespawnType(lua_State* L); + static int luaMonsterTypeCanSpawn(lua_State* L); + + static int luaMonsterTypeCanPushItems(lua_State* L); + static int luaMonsterTypeCanPushCreatures(lua_State* L); + + static int luaMonsterTypeName(lua_State* L); + static int luaMonsterTypeNameDescription(lua_State* L); + + static int luaMonsterTypegetCorpseId(lua_State* L); + + static int luaMonsterTypeHealth(lua_State* L); + static int luaMonsterTypeMaxHealth(lua_State* L); + static int luaMonsterTypeRunHealth(lua_State* L); + static int luaMonsterTypeExperience(lua_State* L); + + static int luaMonsterTypeFaction(lua_State* L); + static int luaMonsterTypeEnemyFactions(lua_State* L); + static int luaMonsterTypeTargetPreferPlayer(lua_State* L); + static int luaMonsterTypeTargetPreferMaster(lua_State* L); + + static int luaMonsterTypeRaceid(lua_State* L); + static int luaMonsterTypeBestiaryclass(lua_State* L); + static int luaMonsterTypeBestiaryOccurrence(lua_State* L); + static int luaMonsterTypeBestiaryLocations(lua_State* L); + static int luaMonsterTypeBestiaryStars(lua_State* L); + static int luaMonsterTypeBestiaryCharmsPoints(lua_State* L); + static int luaMonsterTypeBestiarySecondUnlock(lua_State* L); + static int luaMonsterTypeBestiaryFirstUnlock(lua_State* L); + static int luaMonsterTypeBestiarytoKill(lua_State* L); + static int luaMonsterTypeBestiaryrace(lua_State* L); + + static int luaMonsterTypeCombatImmunities(lua_State* L); + static int luaMonsterTypeConditionImmunities(lua_State* L); + + static int luaMonsterTypeGetAttackList(lua_State* L); + static int luaMonsterTypeAddAttack(lua_State* L); + + static int luaMonsterTypeGetDefenseList(lua_State* L); + static int luaMonsterTypeAddDefense(lua_State* L); + + static int luaMonsterTypeGetTypeName(lua_State* L); + + static int luaMonsterTypeGetElementList(lua_State* L); + static int luaMonsterTypeAddElement(lua_State* L); + + static int luaMonsterTypeAddReflect(lua_State* L); + static int luaMonsterTypeAddHealing(lua_State* L); + + static int luaMonsterTypeGetVoices(lua_State* L); + static int luaMonsterTypeAddVoice(lua_State* L); + + static int luaMonsterTypeGetLoot(lua_State* L); + static int luaMonsterTypeAddLoot(lua_State* L); + + static int luaMonsterTypeGetCreatureEvents(lua_State* L); + static int luaMonsterTypeRegisterEvent(lua_State* L); + + static int luaMonsterTypeEventOnCallback(lua_State* L); + static int luaMonsterTypeEventType(lua_State* L); + + static int luaMonsterTypeGetSummonList(lua_State* L); + static int luaMonsterTypeAddSummon(lua_State* L); + + static int luaMonsterTypeMaxSummons(lua_State* L); + + static int luaMonsterTypeArmor(lua_State* L); + static int luaMonsterTypeDefense(lua_State* L); + static int luaMonsterTypeOutfit(lua_State* L); + static int luaMonsterTypeRace(lua_State* L); + static int luaMonsterTypeCorpseId(lua_State* L); + static int luaMonsterTypeManaCost(lua_State* L); + static int luaMonsterTypeBaseSpeed(lua_State* L); + static int luaMonsterTypeLight(lua_State* L); + + static int luaMonsterTypeStaticAttackChance(lua_State* L); + static int luaMonsterTypeTargetDistance(lua_State* L); + static int luaMonsterTypeYellChance(lua_State* L); + static int luaMonsterTypeYellSpeedTicks(lua_State* L); + static int luaMonsterTypeChangeTargetChance(lua_State* L); + static int luaMonsterTypeChangeTargetSpeed(lua_State* L); + + static int luaMonsterTypeCanWalkOnEnergy(lua_State* L); + static int luaMonsterTypeCanWalkOnFire(lua_State* L); + static int luaMonsterTypeCanWalkOnPoison(lua_State* L); + + static int luaMonsterTypeStrategiesTargetNearest(lua_State* L); + static int luaMonsterTypeStrategiesTargetHealth(lua_State* L); + static int luaMonsterTypeStrategiesTargetDamage(lua_State* L); + static int luaMonsterTypeStrategiesTargetRandom(lua_State* L); + + static int luaMonsterTypeRespawnTypePeriod(lua_State* L); + static int luaMonsterTypeRespawnTypeIsUnderground(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_TYPE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_MONSTER_MONSTER_TYPE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/npc/npc_functions.cpp b/src/lua/functions/creatures/npc/npc_functions.cpp index 538b07f2f04..1d486fe9344 100644 --- a/src/lua/functions/creatures/npc/npc_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -59,7 +59,7 @@ int NpcFunctions::luaNpcSetMasterPos(lua_State* L) { return 1; } - const Position& pos = getPosition(L, 2); + const Position &pos = getPosition(L, 2); npc->setMasterPos(pos); pushBoolean(L, true); return 1; @@ -130,7 +130,7 @@ int NpcFunctions::luaNpcGetName(lua_State* L) { int NpcFunctions::luaNpcSetName(lua_State* L) { // npc:setName(name) Npc* npc = getUserdata(L, 1); - const std::string& name = getString(L, 2); + const std::string &name = getString(L, 2); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -149,7 +149,7 @@ int NpcFunctions::luaNpcPlace(lua_State* L) { return 1; } - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); bool extended = getBoolean(L, 3, false); bool force = getBoolean(L, 4, true); if (g_game().placeCreature(npc, position, extended, force)) { @@ -183,7 +183,7 @@ int NpcFunctions::luaNpcSay(lua_State* L) { bool ghost = getBoolean(L, 4, false); SpeakClasses type = getNumber(L, 3, TALKTYPE_PRIVATE_NP); - const std::string& text = getString(L, 2); + const std::string &text = getString(L, 2); Npc* npc = getUserdata(L, 1); if (!npc) { lua_pushnil(L); @@ -300,7 +300,7 @@ int NpcFunctions::luaNpcIsInteractingWithPlayer(lua_State* L) { } int NpcFunctions::luaNpcIsPlayerInteractingOnTopic(lua_State* L) { - //npc:isPlayerInteractingOnTopic(creature, topicId = 0) + // npc:isPlayerInteractingOnTopic(creature, topicId = 0) Npc* npc = getUserdata(L, 1); Creature* creature = getCreature(L, 2); uint32_t topicId = getNumber(L, 3, 0); @@ -324,7 +324,7 @@ int NpcFunctions::luaNpcIsPlayerInteractingOnTopic(lua_State* L) { int NpcFunctions::luaNpcIsInTalkRange(lua_State* L) { // npc:isInTalkRange() Npc* npc = getUserdata(L, 1); - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -357,7 +357,7 @@ int NpcFunctions::luaNpcOpenShopWindow(lua_State* L) { } int NpcFunctions::luaNpcCloseShopWindow(lua_State* L) { - //npc:closeShopWindow(player) + // npc:closeShopWindow(player) Player* player = getPlayer(L, 2); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); @@ -381,7 +381,7 @@ int NpcFunctions::luaNpcCloseShopWindow(lua_State* L) { } int NpcFunctions::luaNpcIsMerchant(lua_State* L) { - //npc:isMerchant() + // npc:isMerchant() Npc* npc = getUserdata(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -401,7 +401,7 @@ int NpcFunctions::luaNpcIsMerchant(lua_State* L) { } int NpcFunctions::luaNpcGetShopItem(lua_State* L) { - //npc:getShopItem(itemId) + // npc:getShopItem(itemId) Npc* npc = getUserdata(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); @@ -410,8 +410,7 @@ int NpcFunctions::luaNpcGetShopItem(lua_State* L) { } const std::vector &shopVector = npc->getShopItemVector(); - for (ShopBlock shopBlock : shopVector) - { + for (ShopBlock shopBlock : shopVector) { setField(L, "id", shopBlock.itemId); setField(L, "name", shopBlock.itemName); setField(L, "subType", shopBlock.itemSubType); @@ -425,8 +424,7 @@ int NpcFunctions::luaNpcGetShopItem(lua_State* L) { return 1; } -int NpcFunctions::luaNpcMove(lua_State* L) -{ +int NpcFunctions::luaNpcMove(lua_State* L) { // npc:move(direction) Npc* npc = getUserdata(L, 1); if (npc) { @@ -435,8 +433,7 @@ int NpcFunctions::luaNpcMove(lua_State* L) return 0; } -int NpcFunctions::luaNpcTurn(lua_State* L) -{ +int NpcFunctions::luaNpcTurn(lua_State* L) { // npc:turn(direction) Npc* npc = getUserdata(L, 1); if (npc) { @@ -445,8 +442,7 @@ int NpcFunctions::luaNpcTurn(lua_State* L) return 0; } -int NpcFunctions::luaNpcFollow(lua_State* L) -{ +int NpcFunctions::luaNpcFollow(lua_State* L) { // npc:follow(player) Npc* npc = getUserdata(L, 1); if (!npc) { @@ -458,8 +454,7 @@ int NpcFunctions::luaNpcFollow(lua_State* L) return 1; } -int NpcFunctions::luaNpcGetId(lua_State* L) -{ +int NpcFunctions::luaNpcGetId(lua_State* L) { // npc:getId() Npc* npc = getUserdata(L, 1); if (!npc) { @@ -467,13 +462,12 @@ int NpcFunctions::luaNpcGetId(lua_State* L) lua_pushnil(L); return 1; } - + lua_pushnumber(L, npc->getID()); return 1; } -int NpcFunctions::luaNpcSellItem(lua_State* L) -{ +int NpcFunctions::luaNpcSellItem(lua_State* L) { // npc:sellItem(player, itemid, amount, subtype, actionid, ignoreCap, inBackpacks) Npc* npc = getUserdata(L, 1); if (!npc) { @@ -496,7 +490,7 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) bool ignoreCap = getBoolean(L, 7, false); bool inBackpacks = getBoolean(L, 8, false); - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.id == 0) { pushBoolean(L, false); return 1; @@ -644,9 +638,8 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) return 1; } -int NpcFunctions::luaNpcGetDistanceTo(lua_State* L) -{ - //npc:getDistanceTo(uid) +int NpcFunctions::luaNpcGetDistanceTo(lua_State* L) { + // npc:getDistanceTo(uid) Npc* npc = getUserdata(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -662,8 +655,8 @@ int NpcFunctions::luaNpcGetDistanceTo(lua_State* L) return 1; } - const Position& thingPos = thing->getPosition(); - const Position& npcPos = npc->getPosition(); + const Position &thingPos = thing->getPosition(); + const Position &npcPos = npc->getPosition(); if (npcPos.z != thingPos.z) { lua_pushnumber(L, -1); } else { diff --git a/src/lua/functions/creatures/npc/npc_functions.hpp b/src/lua/functions/creatures/npc/npc_functions.hpp index d58c840ce83..379d5cb4023 100644 --- a/src/lua/functions/creatures/npc/npc_functions.hpp +++ b/src/lua/functions/creatures/npc/npc_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_FUNCTIONS_HPP_ @@ -16,76 +16,76 @@ class NpcFunctions final : LuaScriptInterface { private: - static void init(lua_State* L) { - registerClass(L, "Npc", "Creature", NpcFunctions::luaNpcCreate); - registerMetaMethod(L, "Npc", "__eq", NpcFunctions::luaUserdataCompare); - registerMethod(L, "Npc", "isNpc", NpcFunctions::luaNpcIsNpc); - registerMethod(L, "Npc", "setMasterPos", NpcFunctions::luaNpcSetMasterPos); - registerMethod(L, "Npc", "getCurrency", NpcFunctions::luaNpcGetCurrency); - registerMethod(L, "Npc", "setCurrency", NpcFunctions::luaNpcSetCurrency); - registerMethod(L, "Npc", "getSpeechBubble", NpcFunctions::luaNpcGetSpeechBubble); - registerMethod(L, "Npc", "setSpeechBubble", NpcFunctions::luaNpcSetSpeechBubble); - registerMethod(L, "Npc", "getId", NpcFunctions::luaNpcGetId); - registerMethod(L, "Npc", "getName", NpcFunctions::luaNpcGetName); - registerMethod(L, "Npc", "setName", NpcFunctions::luaNpcSetName); - registerMethod(L, "Npc", "place", NpcFunctions::luaNpcPlace); - registerMethod(L, "Npc", "say", NpcFunctions::luaNpcSay); - registerMethod(L, "Npc", "turnToCreature", NpcFunctions::luaNpcTurnToCreature); - registerMethod(L, "Npc", "setPlayerInteraction", NpcFunctions::luaNpcSetPlayerInteraction); - registerMethod(L, "Npc", "removePlayerInteraction", NpcFunctions::luaNpcRemovePlayerInteraction); - registerMethod(L, "Npc", "isInteractingWithPlayer", NpcFunctions::luaNpcIsInteractingWithPlayer); - registerMethod(L, "Npc", "isInTalkRange", NpcFunctions::luaNpcIsInTalkRange); - registerMethod(L, "Npc", "isPlayerInteractingOnTopic", NpcFunctions::luaNpcIsPlayerInteractingOnTopic); - registerMethod(L, "Npc", "openShopWindow", NpcFunctions::luaNpcOpenShopWindow); - registerMethod(L, "Npc", "closeShopWindow", NpcFunctions::luaNpcCloseShopWindow); - registerMethod(L, "Npc", "getShopItem", NpcFunctions::luaNpcGetShopItem); - registerMethod(L, "Npc", "isMerchant", NpcFunctions::luaNpcIsMerchant); + static void init(lua_State* L) { + registerClass(L, "Npc", "Creature", NpcFunctions::luaNpcCreate); + registerMetaMethod(L, "Npc", "__eq", NpcFunctions::luaUserdataCompare); + registerMethod(L, "Npc", "isNpc", NpcFunctions::luaNpcIsNpc); + registerMethod(L, "Npc", "setMasterPos", NpcFunctions::luaNpcSetMasterPos); + registerMethod(L, "Npc", "getCurrency", NpcFunctions::luaNpcGetCurrency); + registerMethod(L, "Npc", "setCurrency", NpcFunctions::luaNpcSetCurrency); + registerMethod(L, "Npc", "getSpeechBubble", NpcFunctions::luaNpcGetSpeechBubble); + registerMethod(L, "Npc", "setSpeechBubble", NpcFunctions::luaNpcSetSpeechBubble); + registerMethod(L, "Npc", "getId", NpcFunctions::luaNpcGetId); + registerMethod(L, "Npc", "getName", NpcFunctions::luaNpcGetName); + registerMethod(L, "Npc", "setName", NpcFunctions::luaNpcSetName); + registerMethod(L, "Npc", "place", NpcFunctions::luaNpcPlace); + registerMethod(L, "Npc", "say", NpcFunctions::luaNpcSay); + registerMethod(L, "Npc", "turnToCreature", NpcFunctions::luaNpcTurnToCreature); + registerMethod(L, "Npc", "setPlayerInteraction", NpcFunctions::luaNpcSetPlayerInteraction); + registerMethod(L, "Npc", "removePlayerInteraction", NpcFunctions::luaNpcRemovePlayerInteraction); + registerMethod(L, "Npc", "isInteractingWithPlayer", NpcFunctions::luaNpcIsInteractingWithPlayer); + registerMethod(L, "Npc", "isInTalkRange", NpcFunctions::luaNpcIsInTalkRange); + registerMethod(L, "Npc", "isPlayerInteractingOnTopic", NpcFunctions::luaNpcIsPlayerInteractingOnTopic); + registerMethod(L, "Npc", "openShopWindow", NpcFunctions::luaNpcOpenShopWindow); + registerMethod(L, "Npc", "closeShopWindow", NpcFunctions::luaNpcCloseShopWindow); + registerMethod(L, "Npc", "getShopItem", NpcFunctions::luaNpcGetShopItem); + registerMethod(L, "Npc", "isMerchant", NpcFunctions::luaNpcIsMerchant); - registerMethod(L, "Npc", "move", NpcFunctions::luaNpcMove); - registerMethod(L, "Npc", "turn", NpcFunctions::luaNpcTurn); - registerMethod(L, "Npc", "follow", NpcFunctions::luaNpcFollow); - registerMethod(L, "Npc", "sellItem", NpcFunctions::luaNpcSellItem); + registerMethod(L, "Npc", "move", NpcFunctions::luaNpcMove); + registerMethod(L, "Npc", "turn", NpcFunctions::luaNpcTurn); + registerMethod(L, "Npc", "follow", NpcFunctions::luaNpcFollow); + registerMethod(L, "Npc", "sellItem", NpcFunctions::luaNpcSellItem); - registerMethod(L, "Npc", "getDistanceTo", NpcFunctions::luaNpcGetDistanceTo); - - ShopFunctions::init(L); - NpcTypeFunctions::init(L); - } + registerMethod(L, "Npc", "getDistanceTo", NpcFunctions::luaNpcGetDistanceTo); - static int luaNpcCreate(lua_State* L); + ShopFunctions::init(L); + NpcTypeFunctions::init(L); + } - static int luaNpcIsNpc(lua_State* L); + static int luaNpcCreate(lua_State* L); - static int luaNpcSetMasterPos(lua_State* L); + static int luaNpcIsNpc(lua_State* L); - static int luaNpcGetCurrency(lua_State* L); - static int luaNpcSetCurrency(lua_State* L); - static int luaNpcGetSpeechBubble(lua_State* L); - static int luaNpcSetSpeechBubble(lua_State* L); - static int luaNpcGetId(lua_State* L); - static int luaNpcGetName(lua_State* L); - static int luaNpcSetName(lua_State* L); - static int luaNpcPlace(lua_State* L); - static int luaNpcSay(lua_State* L); - static int luaNpcTurnToCreature(lua_State* L); - static int luaNpcSetPlayerInteraction(lua_State* L); - static int luaNpcRemovePlayerInteraction(lua_State* L); - static int luaNpcIsInteractingWithPlayer(lua_State* L); - static int luaNpcIsInTalkRange(lua_State* L); - static int luaNpcIsPlayerInteractingOnTopic(lua_State* L); - static int luaNpcOpenShopWindow(lua_State* L); - static int luaNpcCloseShopWindow(lua_State* L); - static int luaNpcGetShopItem(lua_State* L); - static int luaNpcIsMerchant(lua_State* L); + static int luaNpcSetMasterPos(lua_State* L); - static int luaNpcMove(lua_State* L); - static int luaNpcTurn(lua_State* L); - static int luaNpcFollow(lua_State* L); - static int luaNpcSellItem(lua_State* L); + static int luaNpcGetCurrency(lua_State* L); + static int luaNpcSetCurrency(lua_State* L); + static int luaNpcGetSpeechBubble(lua_State* L); + static int luaNpcSetSpeechBubble(lua_State* L); + static int luaNpcGetId(lua_State* L); + static int luaNpcGetName(lua_State* L); + static int luaNpcSetName(lua_State* L); + static int luaNpcPlace(lua_State* L); + static int luaNpcSay(lua_State* L); + static int luaNpcTurnToCreature(lua_State* L); + static int luaNpcSetPlayerInteraction(lua_State* L); + static int luaNpcRemovePlayerInteraction(lua_State* L); + static int luaNpcIsInteractingWithPlayer(lua_State* L); + static int luaNpcIsInTalkRange(lua_State* L); + static int luaNpcIsPlayerInteractingOnTopic(lua_State* L); + static int luaNpcOpenShopWindow(lua_State* L); + static int luaNpcCloseShopWindow(lua_State* L); + static int luaNpcGetShopItem(lua_State* L); + static int luaNpcIsMerchant(lua_State* L); - static int luaNpcGetDistanceTo(lua_State* L); + static int luaNpcMove(lua_State* L); + static int luaNpcTurn(lua_State* L); + static int luaNpcFollow(lua_State* L); + static int luaNpcSellItem(lua_State* L); - friend class CreatureFunctions; + static int luaNpcGetDistanceTo(lua_State* L); + + friend class CreatureFunctions; }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/npc/npc_type_functions.cpp b/src/lua/functions/creatures/npc/npc_type_functions.cpp index 5617fd74ab4..dba9f1b2e80 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,11 +14,11 @@ #include "lua/scripts/scripts.h" #include "game/game.h" -void NpcTypeFunctions::createNpcTypeShopLuaTable(lua_State* L, const std::vector& shopVector) { +void NpcTypeFunctions::createNpcTypeShopLuaTable(lua_State* L, const std::vector &shopVector) { lua_createtable(L, shopVector.size(), 0); int index = 0; - for (const auto& shopBlock : shopVector) { + for (const auto &shopBlock : shopVector) { lua_createtable(L, 0, 5); setField(L, "itemId", shopBlock.itemId); @@ -78,11 +78,10 @@ int NpcTypeFunctions::luaNpcTypeFloorChange(lua_State* L) { int NpcTypeFunctions::luaNpcTypeCanSpawn(lua_State* L) { // monsterType:canSpawn(pos) NpcType* npcType = getUserdata(L, 1); - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); if (npcType) { pushBoolean(L, npcType->canSpawn(position)); - } - else { + } else { lua_pushnil(L); } return 1; @@ -229,7 +228,7 @@ int NpcTypeFunctions::luaNpcTypeGetVoices(lua_State* L) { int index = 0; lua_createtable(L, npcType->info.voiceVector.size(), 0); - for (const auto& voiceBlock : npcType->info.voiceVector) { + for (const auto &voiceBlock : npcType->info.voiceVector) { lua_createtable(L, 0, 2); setField(L, "text", voiceBlock.text); setField(L, "yellText", voiceBlock.yellText); @@ -248,7 +247,7 @@ int NpcTypeFunctions::luaNpcTypeGetCreatureEvents(lua_State* L) { int index = 0; lua_createtable(L, npcType->info.scripts.size(), 0); - for (const std::string& creatureEvent : npcType->info.scripts) { + for (const std::string &creatureEvent : npcType->info.scripts) { pushString(L, creatureEvent); lua_rawseti(L, -2, ++index); } @@ -281,7 +280,7 @@ int NpcTypeFunctions::luaNpcTypeEventOnCallback(lua_State* L) { if (npcType->loadCallback(&g_scripts().getScriptInterface())) { pushBoolean(L, true); return 1; - } + } pushBoolean(L, false); } else { lua_pushnil(L); @@ -397,11 +396,11 @@ int NpcTypeFunctions::luaNpcTypeYellChance(lua_State* L) { if (npcType) { if (lua_gettop(L) == 1) { if (lua_gettop(L) == 1) { - lua_pushnumber(L, npcType->info.yellChance); - } else { - npcType->info.yellChance = getNumber(L, 2); - pushBoolean(L, true); - } + lua_pushnumber(L, npcType->info.yellChance); + } else { + npcType->info.yellChance = getNumber(L, 2); + pushBoolean(L, true); + } } else { npcType->info.yellChance = getNumber(L, 2); pushBoolean(L, true); diff --git a/src/lua/functions/creatures/npc/npc_type_functions.hpp b/src/lua/functions/creatures/npc/npc_type_functions.hpp index fdca6335491..366c6716709 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.hpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_TYPE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_TYPE_FUNCTIONS_HPP_ @@ -68,7 +68,7 @@ class NpcTypeFunctions final : LuaScriptInterface { } private: - static void createNpcTypeShopLuaTable(lua_State* L, const std::vector& shopVector); + static void createNpcTypeShopLuaTable(lua_State* L, const std::vector &shopVector); static int luaNpcTypeCreate(lua_State* L); static int luaNpcTypeIsPushable(lua_State* L); static int luaNpcTypeFloorChange(lua_State* L); @@ -115,4 +115,4 @@ class NpcTypeFunctions final : LuaScriptInterface { friend class GameFunctions; }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_TYPE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_NPC_NPC_TYPE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/npc/shop_functions.cpp b/src/lua/functions/creatures/npc/shop_functions.cpp index 80cecb33a01..1789677472c 100644 --- a/src/lua/functions/creatures/npc/shop_functions.cpp +++ b/src/lua/functions/creatures/npc/shop_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -61,14 +61,16 @@ int ShopFunctions::luaShopSetIdFromName(lua_State* L) { if (ids.first == Item::items.nameToItems.cend()) { SPDLOG_WARN("[ShopFunctions::luaShopSetIdFromName] - " - "Unknown shop item {}", name); + "Unknown shop item {}", + name); lua_pushnil(L); return 1; } if (std::next(ids.first) != ids.second) { SPDLOG_WARN("[ShopFunctions::luaShopSetIdFromName] - " - "Non-unique shop item {}", name); + "Non-unique shop item {}", + name); lua_pushnil(L); return 1; } diff --git a/src/lua/functions/creatures/npc/shop_functions.hpp b/src/lua/functions/creatures/npc/shop_functions.hpp index 22207d36211..29145b3c487 100644 --- a/src/lua/functions/creatures/npc/shop_functions.hpp +++ b/src/lua/functions/creatures/npc/shop_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_NPC_SHOP_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_NPC_SHOP_FUNCTIONS_HPP_ @@ -14,20 +14,20 @@ class ShopFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "Shop", "", ShopFunctions::luaCreateShop); - registerMetaMethod(L, "Shop", "__gc", ShopFunctions::luaDeleteShop); - registerMethod(L, "Shop", "delete", ShopFunctions::luaDeleteShop); + static void init(lua_State* L) { + registerClass(L, "Shop", "", ShopFunctions::luaCreateShop); + registerMetaMethod(L, "Shop", "__gc", ShopFunctions::luaDeleteShop); + registerMethod(L, "Shop", "delete", ShopFunctions::luaDeleteShop); - registerMethod(L, "Shop", "setId", ShopFunctions::luaShopSetId); - registerMethod(L, "Shop", "setIdFromName", ShopFunctions::luaShopSetIdFromName); - registerMethod(L, "Shop", "setNameItem", ShopFunctions::luaShopSetNameItem); - registerMethod(L, "Shop", "setCount", ShopFunctions::luaShopSetCount); - registerMethod(L, "Shop", "setBuyPrice", ShopFunctions::luaShopSetBuyPrice); - registerMethod(L, "Shop", "setSellPrice", ShopFunctions::luaShopSetSellPrice); - registerMethod(L, "Shop", "setStorageKey", ShopFunctions::luaShopSetStorageKey); - registerMethod(L, "Shop", "setStorageValue", ShopFunctions::luaShopSetStorageValue); - registerMethod(L, "Shop", "addChildShop", ShopFunctions::luaShopAddChildShop); + registerMethod(L, "Shop", "setId", ShopFunctions::luaShopSetId); + registerMethod(L, "Shop", "setIdFromName", ShopFunctions::luaShopSetIdFromName); + registerMethod(L, "Shop", "setNameItem", ShopFunctions::luaShopSetNameItem); + registerMethod(L, "Shop", "setCount", ShopFunctions::luaShopSetCount); + registerMethod(L, "Shop", "setBuyPrice", ShopFunctions::luaShopSetBuyPrice); + registerMethod(L, "Shop", "setSellPrice", ShopFunctions::luaShopSetSellPrice); + registerMethod(L, "Shop", "setStorageKey", ShopFunctions::luaShopSetStorageKey); + registerMethod(L, "Shop", "setStorageValue", ShopFunctions::luaShopSetStorageValue); + registerMethod(L, "Shop", "addChildShop", ShopFunctions::luaShopAddChildShop); } private: @@ -44,4 +44,4 @@ class ShopFunctions final : LuaScriptInterface { static int luaShopAddChildShop(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_NPC_SHOP_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_NPC_SHOP_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/player/group_functions.cpp b/src/lua/functions/creatures/player/group_functions.cpp index f6bd08f5273..885d25a67f8 100644 --- a/src/lua/functions/creatures/player/group_functions.cpp +++ b/src/lua/functions/creatures/player/group_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/creatures/player/group_functions.hpp b/src/lua/functions/creatures/player/group_functions.hpp index 71ae85f2358..e0725e8c219 100644 --- a/src/lua/functions/creatures/player/group_functions.hpp +++ b/src/lua/functions/creatures/player/group_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GROUP_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GROUP_FUNCTIONS_HPP_ @@ -14,17 +14,17 @@ class GroupFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "Group", "", GroupFunctions::luaGroupCreate); - registerMetaMethod(L, "Group", "__eq", GroupFunctions::luaUserdataCompare); + static void init(lua_State* L) { + registerClass(L, "Group", "", GroupFunctions::luaGroupCreate); + registerMetaMethod(L, "Group", "__eq", GroupFunctions::luaUserdataCompare); - registerMethod(L, "Group", "getId", GroupFunctions::luaGroupGetId); - registerMethod(L, "Group", "getName", GroupFunctions::luaGroupGetName); - registerMethod(L, "Group", "getFlags", GroupFunctions::luaGroupGetFlags); - registerMethod(L, "Group", "getAccess", GroupFunctions::luaGroupGetAccess); - registerMethod(L, "Group", "getMaxDepotItems", GroupFunctions::luaGroupGetMaxDepotItems); - registerMethod(L, "Group", "getMaxVipEntries", GroupFunctions::luaGroupGetMaxVipEntries); - registerMethod(L, "Group", "hasFlag", GroupFunctions::luaGroupHasFlag); + registerMethod(L, "Group", "getId", GroupFunctions::luaGroupGetId); + registerMethod(L, "Group", "getName", GroupFunctions::luaGroupGetName); + registerMethod(L, "Group", "getFlags", GroupFunctions::luaGroupGetFlags); + registerMethod(L, "Group", "getAccess", GroupFunctions::luaGroupGetAccess); + registerMethod(L, "Group", "getMaxDepotItems", GroupFunctions::luaGroupGetMaxDepotItems); + registerMethod(L, "Group", "getMaxVipEntries", GroupFunctions::luaGroupGetMaxVipEntries); + registerMethod(L, "Group", "hasFlag", GroupFunctions::luaGroupHasFlag); } private: @@ -39,4 +39,4 @@ class GroupFunctions final : LuaScriptInterface { static int luaGroupHasFlag(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GROUP_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GROUP_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/player/guild_functions.cpp b/src/lua/functions/creatures/player/guild_functions.cpp index b59ed67e6d2..9a9b5e1cba6 100644 --- a/src/lua/functions/creatures/player/guild_functions.cpp +++ b/src/lua/functions/creatures/player/guild_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -57,7 +57,7 @@ int GuildFunctions::luaGuildGetMembersOnline(lua_State* L) { return 1; } - const auto& members = guild->getMembersOnline(); + const auto &members = guild->getMembersOnline(); lua_createtable(L, members.size(), 0); int index = 0; @@ -98,7 +98,7 @@ int GuildFunctions::luaGuildAddRank(lua_State* L) { Guild* guild = getUserdata(L, 1); if (guild) { uint32_t id = getNumber(L, 2); - const std::string& name = getString(L, 3); + const std::string &name = getString(L, 3); uint8_t level = getNumber(L, 4); guild->addRank(id, name, level); pushBoolean(L, true); @@ -163,7 +163,7 @@ int GuildFunctions::luaGuildGetMotd(lua_State* L) { int GuildFunctions::luaGuildSetMotd(lua_State* L) { // guild:setMotd(motd) - const std::string& motd = getString(L, 2); + const std::string &motd = getString(L, 2); Guild* guild = getUserdata(L, 1); if (guild) { guild->setMotd(motd); diff --git a/src/lua/functions/creatures/player/guild_functions.hpp b/src/lua/functions/creatures/player/guild_functions.hpp index d156b026b4d..99d6fe42694 100644 --- a/src/lua/functions/creatures/player/guild_functions.hpp +++ b/src/lua/functions/creatures/player/guild_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GUILD_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GUILD_FUNCTIONS_HPP_ @@ -51,4 +51,4 @@ class GuildFunctions final : LuaScriptInterface { static int luaGuildSetMotd(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GUILD_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_GUILD_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/player/mount_functions.cpp b/src/lua/functions/creatures/player/mount_functions.cpp index d246ad5778e..8f3eba9f3cb 100644 --- a/src/lua/functions/creatures/player/mount_functions.cpp +++ b/src/lua/functions/creatures/player/mount_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/creatures/player/mount_functions.hpp b/src/lua/functions/creatures/player/mount_functions.hpp index 0b220e938a7..f4509c34b25 100644 --- a/src/lua/functions/creatures/player/mount_functions.hpp +++ b/src/lua/functions/creatures/player/mount_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_PLAYER_MOUNT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_PLAYER_MOUNT_FUNCTIONS_HPP_ @@ -32,4 +32,4 @@ class MountFunctions final : LuaScriptInterface { static int luaMountGetSpeed(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_MOUNT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_MOUNT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/player/party_functions.cpp b/src/lua/functions/creatures/player/party_functions.cpp index ddd79f9d342..bec2f6d5f57 100644 --- a/src/lua/functions/creatures/player/party_functions.cpp +++ b/src/lua/functions/creatures/player/party_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -39,7 +39,7 @@ int PartyFunctions::luaPartyDisband(lua_State* L) { // party:disband() Party** partyPtr = getRawUserdata(L, 1); if (partyPtr && *partyPtr) { - Party*& party = *partyPtr; + Party*&party = *partyPtr; party->disband(); party = nullptr; pushBoolean(L, true); diff --git a/src/lua/functions/creatures/player/party_functions.hpp b/src/lua/functions/creatures/player/party_functions.hpp index c0b07b064fe..0e28f2d9b78 100644 --- a/src/lua/functions/creatures/player/party_functions.hpp +++ b/src/lua/functions/creatures/player/party_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PARTY_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PARTY_FUNCTIONS_HPP_ @@ -53,4 +53,4 @@ class PartyFunctions final : LuaScriptInterface { static int luaPartySetSharedExperience(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PARTY_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PARTY_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index bb801411eb3..63cb30aa6bc 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -27,10 +27,10 @@ int PlayerFunctions::luaPlayerSendInventory(lua_State* L) { return 1; } - player->sendInventoryIds(); + player->sendInventoryIds(); pushBoolean(L, true); - return 1; + return 1; } int PlayerFunctions::luaPlayerSendLootStats(lua_State* L) { @@ -41,22 +41,22 @@ int PlayerFunctions::luaPlayerSendLootStats(lua_State* L) { return 1; } - Item* item = getUserdata(L, 2); + Item* item = getUserdata(L, 2); if (!item) { lua_pushnil(L); return 1; } uint8_t count = getNumber(L, 3, 0); - if(count == 0) { + if (count == 0) { lua_pushnil(L); return 1; } - player->sendLootStats(item, count); + player->sendLootStats(item, count); pushBoolean(L, true); - return 1; + return 1; } int PlayerFunctions::luaPlayerUpdateSupplyTracker(lua_State* L) { @@ -67,16 +67,16 @@ int PlayerFunctions::luaPlayerUpdateSupplyTracker(lua_State* L) { return 1; } - Item* item = getUserdata(L, 2); + Item* item = getUserdata(L, 2); if (!item) { lua_pushnil(L); return 1; } - player->updateSupplyTracker(item); + player->updateSupplyTracker(item); pushBoolean(L, true); - return 1; + return 1; } int PlayerFunctions::luaPlayerUpdateKillTracker(lua_State* L) { @@ -285,20 +285,20 @@ int PlayerFunctions::luaPlayeraddBestiaryKill(lua_State* L) { // player:addBestiaryKill(name[, amount = 1]) Player* player = getUserdata(L, 1); if (player) { - MonsterType* mtype = g_monsters().getMonsterType(getString(L, 2)); - if (mtype) { - g_iobestiary().addBestiaryKill(player, mtype, getNumber(L, 3, 1)); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } + MonsterType* mtype = g_monsters().getMonsterType(getString(L, 2)); + if (mtype) { + g_iobestiary().addBestiaryKill(player, mtype, getNumber(L, 3, 1)); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } } else { lua_pushnil(L); } return 1; } -int PlayerFunctions::luaPlayerIsMonsterBestiaryUnlocked(lua_State *L) { +int PlayerFunctions::luaPlayerIsMonsterBestiaryUnlocked(lua_State* L) { // player:isMonsterBestiaryUnlocked(raceId) Player* player = getUserdata(L, 1); if (player == nullptr) { @@ -315,8 +315,7 @@ int PlayerFunctions::luaPlayerIsMonsterBestiaryUnlocked(lua_State *L) { } for (auto finishedMonsters = g_iobestiary().getBestiaryFinished(player); - uint16_t finishedRaceId : finishedMonsters) - { + uint16_t finishedRaceId : finishedMonsters) { if (raceId == finishedRaceId) { pushBoolean(L, true); return 1; @@ -550,8 +549,7 @@ int PlayerFunctions::luaPlayerSetTraining(lua_State* L) { return 1; } -int PlayerFunctions::luaPlayerGetIsTraining(lua_State* L) -{ +int PlayerFunctions::luaPlayerGetIsTraining(lua_State* L) { // player:isTraining() Player* player = getUserdata(L, 1); if (!player) { @@ -585,7 +583,7 @@ int PlayerFunctions::luaPlayerGetKills(lua_State* L) { lua_createtable(L, player->unjustifiedKills.size(), 0); int idx = 0; - for (const auto& kill : player->unjustifiedKills) { + for (const auto &kill : player->unjustifiedKills) { lua_createtable(L, 3, 0); lua_pushnumber(L, kill.target); lua_rawseti(L, -2, 1); @@ -673,7 +671,7 @@ int PlayerFunctions::luaPlayerGetRewardList(lua_State* L) { lua_createtable(L, rewardVec.size(), 0); int index = 0; - for (const auto& rewardId : rewardVec) { + for (const auto &rewardId : rewardVec) { lua_pushnumber(L, rewardId); lua_rawseti(L, -2, ++index); } @@ -1098,7 +1096,6 @@ int PlayerFunctions::luaPlayerAddOfflineTrainingTime(lua_State* L) { return 1; } - int PlayerFunctions::luaPlayerGetOfflineTrainingTime(lua_State* L) { // player:getOfflineTrainingTime() Player* player = getUserdata(L, 1); @@ -1218,7 +1215,7 @@ int PlayerFunctions::luaPlayerGetStashItemCount(lua_State* L) { } } - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; if (itemType.id == 0) { lua_pushnil(L); return 1; @@ -1430,7 +1427,7 @@ int PlayerFunctions::luaPlayerGetGuildNick(lua_State* L) { int PlayerFunctions::luaPlayerSetGuildNick(lua_State* L) { // player:setGuildNick(nick) - const std::string& nick = getString(L, 2); + const std::string &nick = getString(L, 2); Player* player = getUserdata(L, 1); if (player) { player->setGuildNick(nick); @@ -1626,7 +1623,7 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { int32_t count = getNumber(L, 3, 1); int32_t subType = getNumber(L, 5, 1); - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; int32_t itemCount = 1; int parameters = lua_gettop(L); @@ -1753,7 +1750,7 @@ int PlayerFunctions::luaPlayerRemoveStashItem(lua_State* L) { } } - const ItemType& itemType = Item::items[itemId]; + const ItemType &itemType = Item::items[itemId]; if (itemType.id == 0) { lua_pushnil(L); return 1; @@ -1867,11 +1864,9 @@ int PlayerFunctions::luaPlayerShowTextDialog(lua_State* L) { Item* item; if (isNumber(L, 2)) { item = Item::CreateItem(getNumber(L, 2)); - } - else if (isString(L, 2)) { + } else if (isString(L, 2)) { item = Item::CreateItem(Item::items.getItemIdByName(getString(L, 2))); - } - else if (isUserdata(L, 2)) { + } else if (isUserdata(L, 2)) { if (getUserdataType(L, 2) != LuaData_Item) { pushBoolean(L, false); return 1; @@ -1954,8 +1949,8 @@ int PlayerFunctions::luaPlayerSendChannelMessage(lua_State* L) { uint16_t channelId = getNumber(L, 5); SpeakClasses type = getNumber(L, 4); - const std::string& text = getString(L, 3); - const std::string& author = getString(L, 2); + const std::string &text = getString(L, 3); + const std::string &author = getString(L, 2); player->sendChannelMessage(author, text, type, channelId); pushBoolean(L, true); return 1; @@ -1970,7 +1965,7 @@ int PlayerFunctions::luaPlayerSendPrivateMessage(lua_State* L) { } const Player* speaker = getUserdata(L, 2); - const std::string& text = getString(L, 3); + const std::string &text = getString(L, 3); SpeakClasses type = getNumber(L, 4, TALKTYPE_PRIVATE_FROM); player->sendPrivateMessage(speaker, type, text); pushBoolean(L, true); @@ -1987,7 +1982,7 @@ int PlayerFunctions::luaPlayerChannelSay(lua_State* L) { Creature* speaker = getCreature(L, 2); SpeakClasses type = getNumber(L, 3); - const std::string& text = getString(L, 4); + const std::string &text = getString(L, 4); uint16_t channelId = getNumber(L, 5); player->sendToChannel(speaker, type, text, channelId); pushBoolean(L, true); @@ -2309,12 +2304,12 @@ int PlayerFunctions::luaPlayerGetTibiaCoins(lua_State* L) { // player:getTibiaCoins() Player* player = getUserdata(L, 1); if (player) { - account::Account account(player->getAccount()); - account.LoadAccountDB(); - uint32_t coins; - account.GetCoins(&coins); - lua_pushnumber(L, coins); - } else { + account::Account account(player->getAccount()); + account.LoadAccountDB(); + uint32_t coins; + account.GetCoins(&coins); + lua_pushnumber(L, coins); + } else { lua_pushnil(L); } return 1; @@ -2328,16 +2323,16 @@ int PlayerFunctions::luaPlayerAddTibiaCoins(lua_State* L) { return 1; } - uint32_t coins = getNumber(L, 2); + uint32_t coins = getNumber(L, 2); - account::Account account(player->getAccount()); - account.LoadAccountDB(); - if(account.AddCoins(coins)) { - account.GetCoins(&(player->coinBalance)); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } + account::Account account(player->getAccount()); + account.LoadAccountDB(); + if (account.AddCoins(coins)) { + account.GetCoins(&(player->coinBalance)); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } return 1; } @@ -2350,16 +2345,16 @@ int PlayerFunctions::luaPlayerRemoveTibiaCoins(lua_State* L) { return 1; } - uint32_t coins = getNumber(L, 2); + uint32_t coins = getNumber(L, 2); - account::Account account(player->getAccount()); - account.LoadAccountDB(); - if (account.RemoveCoins(coins)) { - account.GetCoins(&(player->coinBalance)); - pushBoolean(L, true); - } else { - lua_pushnil(L); - } + account::Account account(player->getAccount()); + account.LoadAccountDB(); + if (account.RemoveCoins(coins)) { + account.GetCoins(&(player->coinBalance)); + pushBoolean(L, true); + } else { + lua_pushnil(L); + } return 1; } @@ -2438,7 +2433,7 @@ int PlayerFunctions::luaPlayerCanLearnSpell(lua_State* L) { return 1; } - const std::string& spellName = getString(L, 2); + const std::string &spellName = getString(L, 2); const InstantSpell* spell = g_spells().getInstantSpellByName(spellName); if (!spell) { reportErrorFunc("Spell \"" + spellName + "\" not found"); @@ -2451,7 +2446,7 @@ int PlayerFunctions::luaPlayerCanLearnSpell(lua_State* L) { return 1; } - const auto& vocMap = spell->getVocMap(); + const auto &vocMap = spell->getVocMap(); if (vocMap.count(player->getVocationId()) == 0) { pushBoolean(L, false); } else if (player->getLevel() < spell->getLevel()) { @@ -2468,7 +2463,7 @@ int PlayerFunctions::luaPlayerLearnSpell(lua_State* L) { // player:learnSpell(spellName) Player* player = getUserdata(L, 1); if (player) { - const std::string& spellName = getString(L, 2); + const std::string &spellName = getString(L, 2); player->learnInstantSpell(spellName); pushBoolean(L, true); } else { @@ -2481,7 +2476,7 @@ int PlayerFunctions::luaPlayerForgetSpell(lua_State* L) { // player:forgetSpell(spellName) Player* player = getUserdata(L, 1); if (player) { - const std::string& spellName = getString(L, 2); + const std::string &spellName = getString(L, 2); player->forgetInstantSpell(spellName); pushBoolean(L, true); } else { @@ -2494,7 +2489,7 @@ int PlayerFunctions::luaPlayerHasLearnedSpell(lua_State* L) { // player:hasLearnedSpell(spellName) Player* player = getUserdata(L, 1); if (player) { - const std::string& spellName = getString(L, 2); + const std::string &spellName = getString(L, 2); pushBoolean(L, player->hasLearnedInstantSpell(spellName)); } else { lua_pushnil(L); @@ -2523,7 +2518,7 @@ int PlayerFunctions::luaPlayerOpenImbuementWindow(lua_State* L) { pushBoolean(L, false); return 1; } - + Item* item = getUserdata(L, 2); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); @@ -2552,9 +2547,9 @@ int PlayerFunctions::luaPlayerAddMapMark(lua_State* L) { // player:addMapMark(position, type, description) Player* player = getUserdata(L, 1); if (player) { - const Position& position = getPosition(L, 2); + const Position &position = getPosition(L, 2); uint8_t type = getNumber(L, 3); - const std::string& description = getString(L, 4); + const std::string &description = getString(L, 4); player->sendAddMarker(position, type, description); pushBoolean(L, true); } else { @@ -2570,7 +2565,7 @@ int PlayerFunctions::luaPlayerSave(lua_State* L) { player->loginPosition = player->getPosition(); pushBoolean(L, IOLoginData::savePlayer(player)); if (player->isOffline()) { - delete player; //avoiding memory leak + delete player; // avoiding memory leak } } else { lua_pushnil(L); @@ -2582,7 +2577,7 @@ int PlayerFunctions::luaPlayerPopupFYI(lua_State* L) { // player:popupFYI(message) Player* player = getUserdata(L, 1); if (player) { - const std::string& message = getString(L, 2); + const std::string &message = getString(L, 2); player->sendFYIBox(message); pushBoolean(L, true); } else { @@ -2690,7 +2685,7 @@ int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { player->switchGhostMode(); Tile* tile = player->getTile(); - const Position& position = player->getPosition(); + const Position &position = player->getPosition(); SpectatorHashSet spectators; g_game().map.getSpectators(spectators, position, true, true); @@ -2708,14 +2703,14 @@ int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { } if (player->isInGhostMode()) { - for (const auto& it : g_game().getPlayers()) { + for (const auto &it : g_game().getPlayers()) { if (!it.second->isAccessPlayer()) { it.second->notifyStatusChange(player, VIPSTATUS_OFFLINE); } } IOLoginData::updateOnlineStatus(player->getGUID(), false); } else { - for (const auto& it : g_game().getPlayers()) { + for (const auto &it : g_game().getPlayers()) { if (!it.second->isAccessPlayer()) { it.second->notifyStatusChange(player, player->statusVipList); } @@ -2781,7 +2776,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { } std::vector spells; - for (auto& [key, spell] : g_spells().getInstantSpells()) { + for (auto &[key, spell] : g_spells().getInstantSpells()) { if (spell.canCast(player)) { spells.push_back(&spell); } @@ -2842,7 +2837,7 @@ int PlayerFunctions::luaPlayerGetFightMode(lua_State* L) { return 1; } -int PlayerFunctions::luaPlayerGetBaseXpGain(lua_State *L) { +int PlayerFunctions::luaPlayerGetBaseXpGain(lua_State* L) { // player:getBaseXpGain() Player* player = getUserdata(L, 1); if (player) { @@ -2853,7 +2848,7 @@ int PlayerFunctions::luaPlayerGetBaseXpGain(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerSetBaseXpGain(lua_State *L) { +int PlayerFunctions::luaPlayerSetBaseXpGain(lua_State* L) { // player:setBaseXpGain(value) Player* player = getUserdata(L, 1); if (player) { @@ -2866,7 +2861,7 @@ int PlayerFunctions::luaPlayerSetBaseXpGain(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerGetVoucherXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerGetVoucherXpBoost(lua_State* L) { // player:getVoucherXpBoost() Player* player = getUserdata(L, 1); if (player) { @@ -2877,7 +2872,7 @@ int PlayerFunctions::luaPlayerGetVoucherXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerSetVoucherXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerSetVoucherXpBoost(lua_State* L) { // player:setVoucherXpBoost(value) Player* player = getUserdata(L, 1); if (player) { @@ -2890,7 +2885,7 @@ int PlayerFunctions::luaPlayerSetVoucherXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerGetGrindingXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerGetGrindingXpBoost(lua_State* L) { // player:getGrindingXpBoost() Player* player = getUserdata(L, 1); if (player) { @@ -2901,7 +2896,7 @@ int PlayerFunctions::luaPlayerGetGrindingXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerSetGrindingXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerSetGrindingXpBoost(lua_State* L) { // player:setGrindingXpBoost(value) Player* player = getUserdata(L, 1); if (player) { @@ -2914,7 +2909,7 @@ int PlayerFunctions::luaPlayerSetGrindingXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerGetStoreXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerGetStoreXpBoost(lua_State* L) { // player:getStoreXpBoost() Player* player = getUserdata(L, 1); if (player) { @@ -2925,7 +2920,7 @@ int PlayerFunctions::luaPlayerGetStoreXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerSetStoreXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerSetStoreXpBoost(lua_State* L) { // player:setStoreXpBoost(value) Player* player = getUserdata(L, 1); if (player) { @@ -2938,7 +2933,7 @@ int PlayerFunctions::luaPlayerSetStoreXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerGetStaminaXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerGetStaminaXpBoost(lua_State* L) { // player:getStaminaXpBoost() Player* player = getUserdata(L, 1); if (player) { @@ -2949,7 +2944,7 @@ int PlayerFunctions::luaPlayerGetStaminaXpBoost(lua_State *L) { return 1; } -int PlayerFunctions::luaPlayerSetStaminaXpBoost(lua_State *L) { +int PlayerFunctions::luaPlayerSetStaminaXpBoost(lua_State* L) { // player:setStaminaXpBoost(value) Player* player = getUserdata(L, 1); if (player) { @@ -3099,7 +3094,6 @@ int PlayerFunctions::luaPlayerGetForgeDusts(lua_State* L) { return 0; } - lua_pushnumber(L, static_cast(player->getForgeDusts())); return 1; } @@ -3173,7 +3167,7 @@ int PlayerFunctions::luaPlayerGetForgeSlivers(lua_State* L) { return 1; } -int PlayerFunctions::luaPlayerGetForgeCores(lua_State *L) { +int PlayerFunctions::luaPlayerGetForgeCores(lua_State* L) { // player:getForgeCores() const Player* player = getUserdata(L, 1); if (!player) { @@ -3209,7 +3203,7 @@ int PlayerFunctions::luaPlayerGetFaction(lua_State* L) { pushBoolean(L, false); return 0; } - + lua_pushnumber(L, player->getFaction()); return 1; } diff --git a/src/lua/functions/creatures/player/player_functions.hpp b/src/lua/functions/creatures/player/player_functions.hpp index 2be5eb98233..f894aa45cbb 100644 --- a/src/lua/functions/creatures/player/player_functions.hpp +++ b/src/lua/functions/creatures/player/player_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PLAYER_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PLAYER_FUNCTIONS_HPP_ @@ -485,7 +485,7 @@ class PlayerFunctions final : LuaScriptInterface { static int luaPlayerAddBlessing(lua_State* L); static int luaPlayerRemoveBlessing(lua_State* L); - static int luaPlayerGetBlessingCount(lua_State * L); + static int luaPlayerGetBlessingCount(lua_State* L); static int luaPlayerCanLearnSpell(lua_State* L); static int luaPlayerLearnSpell(lua_State* L); @@ -527,16 +527,16 @@ class PlayerFunctions final : LuaScriptInterface { static int luaPlayerHasSecureMode(lua_State* L); static int luaPlayerGetFightMode(lua_State* L); - static int luaPlayerGetBaseXpGain(lua_State *L); - static int luaPlayerSetBaseXpGain(lua_State *L); - static int luaPlayerGetVoucherXpBoost(lua_State *L); - static int luaPlayerSetVoucherXpBoost(lua_State *L); - static int luaPlayerGetGrindingXpBoost(lua_State *L); - static int luaPlayerSetGrindingXpBoost(lua_State *L); - static int luaPlayerGetStoreXpBoost(lua_State *L); - static int luaPlayerSetStoreXpBoost(lua_State *L); - static int luaPlayerGetStaminaXpBoost(lua_State *L); - static int luaPlayerSetStaminaXpBoost(lua_State *L); + static int luaPlayerGetBaseXpGain(lua_State* L); + static int luaPlayerSetBaseXpGain(lua_State* L); + static int luaPlayerGetVoucherXpBoost(lua_State* L); + static int luaPlayerSetVoucherXpBoost(lua_State* L); + static int luaPlayerGetGrindingXpBoost(lua_State* L); + static int luaPlayerSetGrindingXpBoost(lua_State* L); + static int luaPlayerGetStoreXpBoost(lua_State* L); + static int luaPlayerSetStoreXpBoost(lua_State* L); + static int luaPlayerGetStaminaXpBoost(lua_State* L); + static int luaPlayerSetStaminaXpBoost(lua_State* L); static int luaPlayerGetExpBoostStamina(lua_State* L); static int luaPlayerSetExpBoostStamina(lua_State* L); @@ -552,11 +552,11 @@ class PlayerFunctions final : LuaScriptInterface { static int luaPlayerAddForgeDusts(lua_State* L); static int luaPlayerRemoveForgeDusts(lua_State* L); static int luaPlayerGetForgeDusts(lua_State* L); - static int luaPlayerSetForgeDusts(lua_State *L); + static int luaPlayerSetForgeDusts(lua_State* L); - static int luaPlayerAddForgeDustLevel(lua_State *L); - static int luaPlayerRemoveForgeDustLevel(lua_State *L); - static int luaPlayerGetForgeDustLevel(lua_State *L); + static int luaPlayerAddForgeDustLevel(lua_State* L); + static int luaPlayerRemoveForgeDustLevel(lua_State* L); + static int luaPlayerGetForgeDustLevel(lua_State* L); static int luaPlayerGetForgeSlivers(lua_State* L); static int luaPlayerGetForgeCores(lua_State* L); @@ -567,4 +567,4 @@ class PlayerFunctions final : LuaScriptInterface { friend class CreatureFunctions; }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PLAYER_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_PLAYER_FUNCTIONS_HPP_ diff --git a/src/lua/functions/creatures/player/vocation_functions.cpp b/src/lua/functions/creatures/player/vocation_functions.cpp index aeb4510a829..7dadf3e9b77 100644 --- a/src/lua/functions/creatures/player/vocation_functions.cpp +++ b/src/lua/functions/creatures/player/vocation_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/creatures/player/vocation_functions.hpp b/src/lua/functions/creatures/player/vocation_functions.hpp index f54bd4a21b8..df44663625b 100644 --- a/src/lua/functions/creatures/player/vocation_functions.hpp +++ b/src/lua/functions/creatures/player/vocation_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_CREATURES_PLAYER_VOCATION_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_CREATURES_PLAYER_VOCATION_FUNCTIONS_HPP_ @@ -81,4 +81,4 @@ class VocationFunctions final : LuaScriptInterface { static int luaVocationGetPromotion(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_VOCATION_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_CREATURES_PLAYER_VOCATION_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/action_functions.cpp b/src/lua/functions/events/action_functions.cpp index 8ed573ff49a..80c84e4e1f4 100644 --- a/src/lua/functions/events/action_functions.cpp +++ b/src/lua/functions/events/action_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -125,8 +125,8 @@ int ActionFunctions::luaActionPosition(lua_State* L) { /** @brief Create action position * @param positions = position or table of positions to set a action script * @param itemId or @param itemName = if item id or string name is set, the item is created on position (if not exists), this variable is nil by default - * action:position(positions, itemId or name) - */ + * action:position(positions, itemId or name) + */ Action* action = getUserdata(L, 1); if (!action) { reportErrorFunc(getErrorDesc(LUA_ERROR_ACTION_NOT_FOUND)); @@ -138,8 +138,7 @@ int ActionFunctions::luaActionPosition(lua_State* L) { // The parameter "- 1" because self is a parameter aswell, which we want to skip L 1 (UserData) // isNumber(L, 2) is for skip the itemId if (int parameters = lua_gettop(L) - 1; - parameters > 1 && isNumber(L, 2)) - { + parameters > 1 && isNumber(L, 2)) { for (int i = 0; i < parameters; ++i) { action->setPositionsVector(getPosition(L, 2 + i)); } diff --git a/src/lua/functions/events/action_functions.hpp b/src/lua/functions/events/action_functions.hpp index c4d4b352ef4..16efc5c1615 100644 --- a/src/lua/functions/events/action_functions.hpp +++ b/src/lua/functions/events/action_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_EVENTS_ACTION_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_EVENTS_ACTION_FUNCTIONS_HPP_ @@ -41,4 +41,4 @@ class ActionFunctions final : LuaScriptInterface { static int luaActionCheckFloor(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_EVENTS_ACTION_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_EVENTS_ACTION_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/creature_event_functions.cpp b/src/lua/functions/events/creature_event_functions.cpp index 25923fe384f..629311b390e 100644 --- a/src/lua/functions/events/creature_event_functions.cpp +++ b/src/lua/functions/events/creature_event_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -58,7 +58,8 @@ int CreatureEventFunctions::luaCreatureEventType(lua_State* L) { creature->setEventType(CREATURE_EVENT_EXTENDED_OPCODE); } else { SPDLOG_ERROR("[CreatureEventFunctions::luaCreatureEventType] - " - "Invalid type for creature event: {}", typeName); + "Invalid type for creature event: {}", + typeName); pushBoolean(L, false); } creature->setLoaded(true); diff --git a/src/lua/functions/events/creature_event_functions.hpp b/src/lua/functions/events/creature_event_functions.hpp index c8bfa21d684..058acbb0d5e 100644 --- a/src/lua/functions/events/creature_event_functions.hpp +++ b/src/lua/functions/events/creature_event_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_EVENTS_CREATURE_EVENT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_EVENTS_CREATURE_EVENT_FUNCTIONS_HPP_ @@ -39,4 +39,4 @@ class CreatureEventFunctions final : LuaScriptInterface { static int luaCreatureEventOnCallback(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_EVENTS_CREATURE_EVENT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_EVENTS_CREATURE_EVENT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/events_functions.hpp b/src/lua/functions/events/events_functions.hpp index 05cb82d3239..76100e1164a 100644 --- a/src/lua/functions/events/events_functions.hpp +++ b/src/lua/functions/events/events_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_EVENTS_EVENTS_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_EVENTS_EVENTS_FUNCTIONS_HPP_ @@ -31,6 +31,6 @@ class EventFunctions final : LuaScriptInterface { } private: - }; +}; -#endif // SRC_LUA_FUNCTIONS_EVENTS_EVENTS_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_EVENTS_EVENTS_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/events_scheduler_functions.cpp b/src/lua/functions/events/events_scheduler_functions.cpp index 138a7c597cc..c38f7d5202b 100644 --- a/src/lua/functions/events/events_scheduler_functions.cpp +++ b/src/lua/functions/events/events_scheduler_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/events/events_scheduler_functions.hpp b/src/lua/functions/events/events_scheduler_functions.hpp index ae7f84d2352..5d1a03d0145 100644 --- a/src/lua/functions/events/events_scheduler_functions.hpp +++ b/src/lua/functions/events/events_scheduler_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_GAME_SCHEDUNLING_EVENTS_SCHEDULER_FUNCTIONS_HPP_ #define SRC_GAME_SCHEDUNLING_EVENTS_SCHEDULER_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/global_event_functions.cpp b/src/lua/functions/events/global_event_functions.cpp index 560a7e9d31c..1d9b9190d82 100644 --- a/src/lua/functions/events/global_event_functions.cpp +++ b/src/lua/functions/events/global_event_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -46,7 +46,7 @@ int GlobalEventFunctions::luaGlobalEventType(lua_State* L) { global->setEventType(GLOBALEVENT_ON_THINK); } else { SPDLOG_ERROR("[GlobalEventFunctions::luaGlobalEventType] - " - "Invalid type for global event: {}"); + "Invalid type for global event: {}"); pushBoolean(L, false); } pushBoolean(L, true); @@ -96,8 +96,8 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { int32_t hour = params.front(); if (hour < 0 || hour > 23) { SPDLOG_ERROR("[GlobalEventFunctions::luaGlobalEventTime] - " - "Invalid hour {} for globalevent with name: {}", - timer, globalevent->getName()); + "Invalid hour {} for globalevent with name: {}", + timer, globalevent->getName()); pushBoolean(L, false); return 1; } @@ -110,8 +110,8 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { min = params[1]; if (min < 0 || min > 59) { SPDLOG_ERROR("[GlobalEventFunctions::luaGlobalEventTime] - " - "Invalid minute: {} for globalevent with name: {}", - timer, globalevent->getName()); + "Invalid minute: {} for globalevent with name: {}", + timer, globalevent->getName()); pushBoolean(L, false); return 1; } @@ -120,8 +120,8 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { sec = params[2]; if (sec < 0 || sec > 59) { SPDLOG_ERROR("[GlobalEventFunctions::luaGlobalEventTime] - " - "Invalid minute: {} for globalevent with name: {}", - timer, globalevent->getName()); + "Invalid minute: {} for globalevent with name: {}", + timer, globalevent->getName()); pushBoolean(L, false); return 1; } diff --git a/src/lua/functions/events/global_event_functions.hpp b/src/lua/functions/events/global_event_functions.hpp index 95aa116e369..fec6445bc7e 100644 --- a/src/lua/functions/events/global_event_functions.hpp +++ b/src/lua/functions/events/global_event_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_EVENTS_GLOBAL_EVENT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_EVENTS_GLOBAL_EVENT_FUNCTIONS_HPP_ @@ -37,4 +37,4 @@ class GlobalEventFunctions final : LuaScriptInterface { static int luaGlobalEventInterval(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_EVENTS_GLOBAL_EVENT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_EVENTS_GLOBAL_EVENT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/move_event_functions.cpp b/src/lua/functions/events/move_event_functions.cpp index bd9e6149b1a..0272989c7f8 100644 --- a/src/lua/functions/events/move_event_functions.cpp +++ b/src/lua/functions/events/move_event_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -51,7 +51,8 @@ int MoveEventFunctions::luaMoveEventType(lua_State* L) { moveevent->moveFunction = moveevent->RemoveItemField; } else { SPDLOG_ERROR("[MoveEventFunctions::luaMoveEventType] - " - "No valid event name: {}", typeName); + "No valid event name: {}", + typeName); pushBoolean(L, false); } pushBoolean(L, true); @@ -129,7 +130,8 @@ int MoveEventFunctions::luaMoveEventSlot(lua_State* L) { moveevent->setSlot(SLOTP_AMMO); } else { SPDLOG_WARN("[MoveEventFunctions::luaMoveEventSlot] - " - "Unknown slot type: {}", slotName); + "Unknown slot type: {}", + slotName); pushBoolean(L, false); return 1; } @@ -267,7 +269,7 @@ int MoveEventFunctions::luaMoveEventUniqueId(lua_State* L) { } else { moveevent->setUniqueId(getNumber(L, 2)); } - pushBoolean(L, true); + pushBoolean(L, true); } else { lua_pushnil(L); } diff --git a/src/lua/functions/events/move_event_functions.hpp b/src/lua/functions/events/move_event_functions.hpp index 1103d227f72..1e1ec753129 100644 --- a/src/lua/functions/events/move_event_functions.hpp +++ b/src/lua/functions/events/move_event_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_EVENTS_MOVE_EVENT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_EVENTS_MOVE_EVENT_FUNCTIONS_HPP_ @@ -51,4 +51,4 @@ class MoveEventFunctions final : LuaScriptInterface { static int luaMoveEventPosition(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_EVENTS_MOVE_EVENT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_EVENTS_MOVE_EVENT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/events/talk_action_functions.cpp b/src/lua/functions/events/talk_action_functions.cpp index 04641fcf1a1..357a35890d6 100644 --- a/src/lua/functions/events/talk_action_functions.cpp +++ b/src/lua/functions/events/talk_action_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/events/talk_action_functions.hpp b/src/lua/functions/events/talk_action_functions.hpp index 6aa5976063f..baac56f3cf0 100644 --- a/src/lua/functions/events/talk_action_functions.hpp +++ b/src/lua/functions/events/talk_action_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_EVENTS_TALK_ACTION_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_EVENTS_TALK_ACTION_FUNCTIONS_HPP_ @@ -28,4 +28,4 @@ class TalkActionFunctions final : LuaScriptInterface { static int luaTalkActionSeparator(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_EVENTS_TALK_ACTION_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_EVENTS_TALK_ACTION_FUNCTIONS_HPP_ diff --git a/src/lua/functions/items/container_functions.cpp b/src/lua/functions/items/container_functions.cpp index 5d3602ca47b..d699a10b081 100644 --- a/src/lua/functions/items/container_functions.cpp +++ b/src/lua/functions/items/container_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -132,7 +132,7 @@ int ContainerFunctions::luaContainerAddItem(lua_State* L) { } uint32_t count = getNumber(L, 3, 1); - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.stackable) { count = std::min(count, 100); } @@ -265,7 +265,7 @@ int ContainerFunctions::luaContainerRegisterReward(lua_State* L) { } auto timestamp = time(nullptr); - Item * rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); + Item* rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); rewardContainer->setAttribute(ItemAttribute_t::DATE, timestamp); container->setAttribute(ItemAttribute_t::DATE, timestamp); container->internalAddThing(rewardContainer); diff --git a/src/lua/functions/items/container_functions.hpp b/src/lua/functions/items/container_functions.hpp index 96fad3dde6d..694369f8147 100644 --- a/src/lua/functions/items/container_functions.hpp +++ b/src/lua/functions/items/container_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_ITEMS_CONTAINER_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_ITEMS_CONTAINER_FUNCTIONS_HPP_ @@ -14,26 +14,25 @@ class ContainerFunctions final : LuaScriptInterface { public: - private: - static void init(lua_State* L) { - registerClass(L, "Container", "Item", ContainerFunctions::luaContainerCreate); - registerMetaMethod(L, "Container", "__eq", ContainerFunctions::luaUserdataCompare); - - registerMethod(L, "Container", "getSize", ContainerFunctions::luaContainerGetSize); - registerMethod(L, "Container", "getCapacity", ContainerFunctions::luaContainerGetCapacity); - registerMethod(L, "Container", "getEmptySlots", ContainerFunctions::luaContainerGetEmptySlots); - registerMethod(L, "Container", "getContentDescription", ContainerFunctions::luaContainerGetContentDescription); - registerMethod(L, "Container", "getItems", ContainerFunctions::luaContainerGetItems); - registerMethod(L, "Container", "getItemHoldingCount", ContainerFunctions::luaContainerGetItemHoldingCount); - registerMethod(L, "Container", "getItemCountById", ContainerFunctions::luaContainerGetItemCountById); - - registerMethod(L, "Container", "getItem", ContainerFunctions::luaContainerGetItem); - registerMethod(L, "Container", "hasItem", ContainerFunctions::luaContainerHasItem); - registerMethod(L, "Container", "addItem", ContainerFunctions::luaContainerAddItem); - registerMethod(L, "Container", "addItemEx", ContainerFunctions::luaContainerAddItemEx); - registerMethod(L, "Container", "getCorpseOwner", ContainerFunctions::luaContainerGetCorpseOwner); - registerMethod(L, "Container", "registerReward", ContainerFunctions::luaContainerRegisterReward); + static void init(lua_State* L) { + registerClass(L, "Container", "Item", ContainerFunctions::luaContainerCreate); + registerMetaMethod(L, "Container", "__eq", ContainerFunctions::luaUserdataCompare); + + registerMethod(L, "Container", "getSize", ContainerFunctions::luaContainerGetSize); + registerMethod(L, "Container", "getCapacity", ContainerFunctions::luaContainerGetCapacity); + registerMethod(L, "Container", "getEmptySlots", ContainerFunctions::luaContainerGetEmptySlots); + registerMethod(L, "Container", "getContentDescription", ContainerFunctions::luaContainerGetContentDescription); + registerMethod(L, "Container", "getItems", ContainerFunctions::luaContainerGetItems); + registerMethod(L, "Container", "getItemHoldingCount", ContainerFunctions::luaContainerGetItemHoldingCount); + registerMethod(L, "Container", "getItemCountById", ContainerFunctions::luaContainerGetItemCountById); + + registerMethod(L, "Container", "getItem", ContainerFunctions::luaContainerGetItem); + registerMethod(L, "Container", "hasItem", ContainerFunctions::luaContainerHasItem); + registerMethod(L, "Container", "addItem", ContainerFunctions::luaContainerAddItem); + registerMethod(L, "Container", "addItemEx", ContainerFunctions::luaContainerAddItemEx); + registerMethod(L, "Container", "getCorpseOwner", ContainerFunctions::luaContainerGetCorpseOwner); + registerMethod(L, "Container", "registerReward", ContainerFunctions::luaContainerRegisterReward); } static int luaContainerCreate(lua_State* L); @@ -58,4 +57,4 @@ class ContainerFunctions final : LuaScriptInterface { friend class ItemFunctions; }; -#endif // SRC_LUA_FUNCTIONS_ITEMS_CONTAINER_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_ITEMS_CONTAINER_FUNCTIONS_HPP_ diff --git a/src/lua/functions/items/imbuement_functions.cpp b/src/lua/functions/items/imbuement_functions.cpp index 8f572696fad..ceda02024b0 100644 --- a/src/lua/functions/items/imbuement_functions.cpp +++ b/src/lua/functions/items/imbuement_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -58,10 +58,10 @@ int ImbuementFunctions::luaImbuementGetItems(lua_State* L) { return 1; } - const auto& items = imbuement->getItems(); + const auto &items = imbuement->getItems(); lua_createtable(L, items.size(), 0); - for (const auto& itm : items) { + for (const auto &itm : items) { lua_createtable(L, 0, 2); setField(L, "itemid", itm.first); setField(L, "count", itm.second); @@ -79,9 +79,8 @@ int ImbuementFunctions::luaImbuementGetBase(lua_State* L) { return 1; } - const BaseImbuement *baseImbuement = g_imbuements().getBaseByID(imbuement->getBaseID()); - if (!baseImbuement) - { + const BaseImbuement* baseImbuement = g_imbuements().getBaseByID(imbuement->getBaseID()); + if (!baseImbuement) { lua_pushnil(L); return 1; } diff --git a/src/lua/functions/items/imbuement_functions.hpp b/src/lua/functions/items/imbuement_functions.hpp index 24d8384ca2d..0ad2581ed21 100644 --- a/src/lua/functions/items/imbuement_functions.hpp +++ b/src/lua/functions/items/imbuement_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_ITEMS_IMBUEMENT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_ITEMS_IMBUEMENT_FUNCTIONS_HPP_ @@ -26,7 +26,6 @@ class ImbuementFunctions final : LuaScriptInterface { registerMethod(L, "Imbuement", "isPremium", ImbuementFunctions::luaImbuementIsPremium); registerMethod(L, "Imbuement", "getElementDamage", ImbuementFunctions::luaImbuementGetElementDamage); registerMethod(L, "Imbuement", "getCombatType", ImbuementFunctions::luaImbuementGetCombatType); - } private: @@ -41,4 +40,4 @@ class ImbuementFunctions final : LuaScriptInterface { static int luaImbuementGetCombatType(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_ITEMS_IMBUEMENT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_ITEMS_IMBUEMENT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/items/item_classification_functions.cpp b/src/lua/functions/items/item_classification_functions.cpp index fe558a90d4f..9e099bf533e 100644 --- a/src/lua/functions/items/item_classification_functions.cpp +++ b/src/lua/functions/items/item_classification_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,8 +16,7 @@ int ItemClassificationFunctions::luaItemClassificationCreate(lua_State* L) { // ItemClassification(id) if (isNumber(L, 2)) { const ItemClassification* itemClassification = g_game().getItemsClassification(getNumber(L, 2), false); - if (itemClassification) - { + if (itemClassification) { pushUserdata(L, itemClassification); setMetatable(L, -1, "ItemClassification"); pushBoolean(L, true); diff --git a/src/lua/functions/items/item_classification_functions.hpp b/src/lua/functions/items/item_classification_functions.hpp index a7610ce7d26..6f47aa64fe8 100644 --- a/src/lua/functions/items/item_classification_functions.hpp +++ b/src/lua/functions/items/item_classification_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_ITEMS_ITEM_CLASSIFICATION_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_ITEMS_ITEM_CLASSIFICATION_FUNCTIONS_HPP_ @@ -14,11 +14,11 @@ class ItemClassificationFunctions final : LuaScriptInterface { public: - static void init(lua_State* L) { - registerClass(L, "ItemClassification", "", ItemClassificationFunctions::luaItemClassificationCreate); - registerMetaMethod(L, "ItemClassification", "__eq", ItemClassificationFunctions::luaUserdataCompare); + static void init(lua_State* L) { + registerClass(L, "ItemClassification", "", ItemClassificationFunctions::luaItemClassificationCreate); + registerMetaMethod(L, "ItemClassification", "__eq", ItemClassificationFunctions::luaUserdataCompare); - registerMethod(L, "ItemClassification", "addTier", ItemClassificationFunctions::luaItemClassificationAddTier); + registerMethod(L, "ItemClassification", "addTier", ItemClassificationFunctions::luaItemClassificationAddTier); } private: @@ -26,4 +26,4 @@ class ItemClassificationFunctions final : LuaScriptInterface { static int luaItemClassificationAddTier(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_ITEMS_ITEM_CLASSIFICATION_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_ITEMS_ITEM_CLASSIFICATION_FUNCTIONS_HPP_ diff --git a/src/lua/functions/items/item_functions.cpp b/src/lua/functions/items/item_functions.cpp index b6d6f90467a..3714fae3e6b 100644 --- a/src/lua/functions/items/item_functions.cpp +++ b/src/lua/functions/items/item_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -396,8 +396,7 @@ int ItemFunctions::luaItemSetAttribute(lua_State* L) { switch (attribute) { case ItemAttribute_t::DECAYSTATE: { if (ItemDecayState_t decayState = getNumber(L, 3); - decayState == DECAYING_FALSE || decayState == DECAYING_STOPPING) - { + decayState == DECAYING_FALSE || decayState == DECAYING_STOPPING) { g_decay().stopDecay(item); } else { g_decay().startDecay(item); @@ -417,7 +416,8 @@ int ItemFunctions::luaItemSetAttribute(lua_State* L) { pushBoolean(L, false); return 1; } - default: break; + default: + break; } item->setAttribute(attribute, getNumber(L, 3)); @@ -638,7 +638,7 @@ int ItemFunctions::luaItemTransform(lua_State* L) { return 1; } - Item*& item = *itemPtr; + Item*&item = *itemPtr; if (!item) { lua_pushnil(L); return 1; @@ -661,7 +661,7 @@ int ItemFunctions::luaItemTransform(lua_State* L) { return 1; } - const ItemType& it = Item::items[itemId]; + const ItemType &it = Item::items[itemId]; if (it.stackable) { subType = std::min(subType, 100); } @@ -688,7 +688,7 @@ int ItemFunctions::luaItemDecay(lua_State* L) { Item* item = getUserdata(L, 1); if (item) { if (isNumber(L, 2)) { - ItemType& it = Item::items.getItemType(item->getID()); + ItemType &it = Item::items.getItemType(item->getID()); it.decayTo = getNumber(L, 2); } @@ -750,8 +750,7 @@ int ItemFunctions::luaItemHasProperty(lua_State* L) { return 1; } -int ItemFunctions::luaItemGetImbuement(lua_State* L) -{ +int ItemFunctions::luaItemGetImbuement(lua_State* L) { // item:getImbuement() const Item* item = getUserdata(L, 1); if (!item) { @@ -766,7 +765,7 @@ int ItemFunctions::luaItemGetImbuement(lua_State* L) continue; } - Imbuement *imbuement = imbuementInfo.imbuement; + Imbuement* imbuement = imbuementInfo.imbuement; if (!imbuement) { continue; } @@ -820,7 +819,7 @@ int ItemFunctions::luaItemSetDuration(lua_State* L) { showDuration = getBoolean(L, 5); } - ItemType& it = Item::items.getItemType(item->getID()); + ItemType &it = Item::items.getItemType(item->getID()); if (maxDuration == 0) { it.decayTime = minDuration; } else { diff --git a/src/lua/functions/items/item_functions.hpp b/src/lua/functions/items/item_functions.hpp index fe65c7c920b..cc1c1612bb2 100644 --- a/src/lua/functions/items/item_functions.hpp +++ b/src/lua/functions/items/item_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_ITEMS_ITEM_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_ITEMS_ITEM_FUNCTIONS_HPP_ @@ -150,4 +150,4 @@ class ItemFunctions final : LuaScriptInterface { static int luaItemGetClassification(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_ITEMS_ITEM_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_ITEMS_ITEM_FUNCTIONS_HPP_ diff --git a/src/lua/functions/items/item_type_functions.cpp b/src/lua/functions/items/item_type_functions.cpp index b32acc5dfe6..8c6910f10e6 100644 --- a/src/lua/functions/items/item_type_functions.cpp +++ b/src/lua/functions/items/item_type_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -22,7 +22,7 @@ int ItemTypeFunctions::luaItemTypeCreate(lua_State* L) { id = Item::items.getItemIdByName(getString(L, 2)); } - const ItemType& itemType = Item::items[id]; + const ItemType &itemType = Item::items[id]; pushUserdata(L, &itemType); setMetatable(L, -1, "ItemType"); return 1; @@ -270,7 +270,7 @@ int ItemTypeFunctions::luaItemTypeGetDescription(lua_State* L) { return 1; } -int ItemTypeFunctions::luaItemTypeGetSlotPosition(lua_State *L) { +int ItemTypeFunctions::luaItemTypeGetSlotPosition(lua_State* L) { // itemType:getSlotPosition() const ItemType* itemType = getUserdata(L, 1); if (itemType) { @@ -436,7 +436,7 @@ int ItemTypeFunctions::luaItemTypeGetElementType(lua_State* L) { return 1; } - auto& abilities = itemType->abilities; + auto &abilities = itemType->abilities; if (abilities) { lua_pushnumber(L, abilities->elementType); } else { @@ -453,7 +453,7 @@ int ItemTypeFunctions::luaItemTypeGetElementDamage(lua_State* L) { return 1; } - auto& abilities = itemType->abilities; + auto &abilities = itemType->abilities; if (abilities) { lua_pushnumber(L, abilities->elementDamage); } else { @@ -525,7 +525,7 @@ int ItemTypeFunctions::luaItemTypeGetSpeed(lua_State* L) { return 1; } - auto& abilities = itemType->abilities; + auto &abilities = itemType->abilities; if (abilities) { lua_pushnumber(L, abilities->speed); } else { diff --git a/src/lua/functions/items/item_type_functions.hpp b/src/lua/functions/items/item_type_functions.hpp index 8e55e5834c4..4673deee921 100644 --- a/src/lua/functions/items/item_type_functions.hpp +++ b/src/lua/functions/items/item_type_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_ITEMS_ITEM_TYPE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_ITEMS_ITEM_TYPE_FUNCTIONS_HPP_ @@ -76,7 +76,7 @@ class ItemTypeFunctions final : LuaScriptInterface { registerMethod(L, "ItemType", "getBaseSpeed", ItemTypeFunctions::luaItemTypeGetBaseSpeed); registerMethod(L, "ItemType", "hasSubType", ItemTypeFunctions::luaItemTypeHasSubType); - + ItemClassificationFunctions::init(L); } @@ -106,7 +106,7 @@ class ItemTypeFunctions final : LuaScriptInterface { static int luaItemTypeGetPluralName(lua_State* L); static int luaItemTypeGetArticle(lua_State* L); static int luaItemTypeGetDescription(lua_State* L); - static int luaItemTypeGetSlotPosition(lua_State *L); + static int luaItemTypeGetSlotPosition(lua_State* L); static int luaItemTypeGetCharges(lua_State* L); static int luaItemTypeGetFluidSource(lua_State* L); @@ -141,4 +141,4 @@ class ItemTypeFunctions final : LuaScriptInterface { static int luaItemTypeHasSubType(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_ITEMS_ITEM_TYPE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_ITEMS_ITEM_TYPE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/items/weapon_functions.cpp b/src/lua/functions/items/weapon_functions.cpp index 8ecc2633c6f..312f6c09919 100644 --- a/src/lua/functions/items/weapon_functions.cpp +++ b/src/lua/functions/items/weapon_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -76,7 +76,8 @@ int WeaponFunctions::luaWeaponAction(lua_State* L) { weapon->action = WEAPONACTION_MOVE; } else { SPDLOG_ERROR("[WeaponFunctions::luaWeaponAction] - " - "No valid action {}", typeName); + "No valid action {}", + typeName); pushBoolean(L, false); } pushBoolean(L, true); @@ -100,7 +101,7 @@ int WeaponFunctions::luaWeaponRegister(lua_State* L) { } uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.weaponType = weapon->weaponType; if (weapon->getWieldInfo() != 0) { @@ -283,7 +284,8 @@ int WeaponFunctions::luaWeaponElement(lua_State* L) { weapon->params.combatType = COMBAT_HOLYDAMAGE; } else { SPDLOG_WARN("[WeaponFunctions:luaWeaponElement] - " - "Type {} does not exist", element); + "Type {} does not exist", + element); } } else { weapon->params.combatType = getNumber(L, 2); @@ -364,7 +366,7 @@ int WeaponFunctions::luaWeaponAttack(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.attack = getNumber(L, 2); pushBoolean(L, true); } else { @@ -378,7 +380,7 @@ int WeaponFunctions::luaWeaponDefense(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.defense = getNumber(L, 2); if (lua_gettop(L) > 2) { it.extraDefense = getNumber(L, 3); @@ -395,7 +397,7 @@ int WeaponFunctions::luaWeaponRange(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.shootRange = getNumber(L, 2); pushBoolean(L, true); } else { @@ -413,7 +415,7 @@ int WeaponFunctions::luaWeaponCharges(lua_State* L) { showCharges = getBoolean(L, 3); } uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.charges = getNumber(L, 2); it.showCharges = showCharges; pushBoolean(L, true); @@ -432,7 +434,7 @@ int WeaponFunctions::luaWeaponDuration(lua_State* L) { showDuration = getBoolean(L, 3); } uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.decayTime = getNumber(L, 2); it.showDuration = showDuration; pushBoolean(L, true); @@ -451,7 +453,7 @@ int WeaponFunctions::luaWeaponDecayTo(lua_State* L) { itemid = getNumber(L, 2); } uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.decayTo = itemid; pushBoolean(L, true); } else { @@ -465,7 +467,7 @@ int WeaponFunctions::luaWeaponTransformEquipTo(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.transformEquipTo = getNumber(L, 2); pushBoolean(L, true); } else { @@ -479,7 +481,7 @@ int WeaponFunctions::luaWeaponTransformDeEquipTo(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.transformDeEquipTo = getNumber(L, 2); pushBoolean(L, true); } else { @@ -493,7 +495,7 @@ int WeaponFunctions::luaWeaponShootType(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.shootType = getNumber(L, 2); pushBoolean(L, true); } else { @@ -507,7 +509,7 @@ int WeaponFunctions::luaWeaponSlotType(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); std::string slot = getString(L, 2); if (slot == "two-handed") { @@ -527,16 +529,17 @@ int WeaponFunctions::luaWeaponAmmoType(lua_State* L) { WeaponDistance* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); std::string type = getString(L, 2); if (type == "arrow") { it.ammoType = AMMO_ARROW; - } else if (type == "bolt"){ + } else if (type == "bolt") { it.ammoType = AMMO_BOLT; } else { SPDLOG_WARN("[WeaponFunctions:luaWeaponAmmoType] - " - "Type {} does not exist", type); + "Type {} does not exist", + type); lua_pushnil(L); return 1; } @@ -552,7 +555,7 @@ int WeaponFunctions::luaWeaponHitChance(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.hitChance = getNumber(L, 2); pushBoolean(L, true); } else { @@ -566,7 +569,7 @@ int WeaponFunctions::luaWeaponMaxHitChance(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.maxHitChance = getNumber(L, 2); pushBoolean(L, true); } else { @@ -580,7 +583,7 @@ int WeaponFunctions::luaWeaponExtraElement(lua_State* L) { Weapon* weapon = getUserdata(L, 1); if (weapon) { uint16_t id = weapon->getID(); - ItemType& it = Item::items.getItemType(id); + ItemType &it = Item::items.getItemType(id); it.abilities.get()->elementDamage = getNumber(L, 2); if (!getNumber(L, 3)) { @@ -600,7 +603,8 @@ int WeaponFunctions::luaWeaponExtraElement(lua_State* L) { it.abilities.get()->elementType = COMBAT_HOLYDAMAGE; } else { SPDLOG_WARN("[WeaponFunctions:luaWeaponExtraElement] - " - "Type {} does not exist", element); + "Type {} does not exist", + element); } } else { it.abilities.get()->elementType = getNumber(L, 3); diff --git a/src/lua/functions/items/weapon_functions.hpp b/src/lua/functions/items/weapon_functions.hpp index eb817a69101..ad77f022e4c 100644 --- a/src/lua/functions/items/weapon_functions.hpp +++ b/src/lua/functions/items/weapon_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_ITEMS_WEAPON_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_ITEMS_WEAPON_FUNCTIONS_HPP_ @@ -53,7 +53,6 @@ class WeaponFunctions final : LuaScriptInterface { // exclusively for wands & distance weapons registerMethod(L, "Weapon", "shootType", WeaponFunctions::luaWeaponShootType); - } private: @@ -97,4 +96,4 @@ class WeaponFunctions final : LuaScriptInterface { static int luaWeaponShootType(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_ITEMS_WEAPON_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_ITEMS_WEAPON_FUNCTIONS_HPP_ diff --git a/src/lua/functions/lua_functions_loader.cpp b/src/lua/functions/lua_functions_loader.cpp index 37b13d87a71..5d3f4767baf 100644 --- a/src/lua/functions/lua_functions_loader.cpp +++ b/src/lua/functions/lua_functions_loader.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -42,25 +42,44 @@ void LuaFunctionsLoader::load(lua_State* L) { std::string LuaFunctionsLoader::getErrorDesc(ErrorCode_t code) { switch (code) { - case LUA_ERROR_PLAYER_NOT_FOUND: return "Player not found"; - case LUA_ERROR_CREATURE_NOT_FOUND: return "Creature not found"; - case LUA_ERROR_NPC_NOT_FOUND: return "Npc not found"; - case LUA_ERROR_NPC_TYPE_NOT_FOUND: return "Npc type not found"; - case LUA_ERROR_MONSTER_NOT_FOUND: return "Monster not found"; - case LUA_ERROR_MONSTER_TYPE_NOT_FOUND: return "Monster type not found"; - case LUA_ERROR_ITEM_NOT_FOUND: return "Item not found"; - case LUA_ERROR_THING_NOT_FOUND: return "Thing not found"; - case LUA_ERROR_TILE_NOT_FOUND: return "Tile not found"; - case LUA_ERROR_HOUSE_NOT_FOUND: return "House not found"; - case LUA_ERROR_COMBAT_NOT_FOUND: return "Combat not found"; - case LUA_ERROR_CONDITION_NOT_FOUND: return "Condition not found"; - case LUA_ERROR_AREA_NOT_FOUND: return "Area not found"; - case LUA_ERROR_CONTAINER_NOT_FOUND: return "Container not found"; - case LUA_ERROR_VARIANT_NOT_FOUND: return "Variant not found"; - case LUA_ERROR_VARIANT_UNKNOWN: return "Unknown variant type"; - case LUA_ERROR_SPELL_NOT_FOUND: return "Spell not found"; - case LUA_ERROR_ACTION_NOT_FOUND: return "Action not found"; - default: return "Bad error code"; + case LUA_ERROR_PLAYER_NOT_FOUND: + return "Player not found"; + case LUA_ERROR_CREATURE_NOT_FOUND: + return "Creature not found"; + case LUA_ERROR_NPC_NOT_FOUND: + return "Npc not found"; + case LUA_ERROR_NPC_TYPE_NOT_FOUND: + return "Npc type not found"; + case LUA_ERROR_MONSTER_NOT_FOUND: + return "Monster not found"; + case LUA_ERROR_MONSTER_TYPE_NOT_FOUND: + return "Monster type not found"; + case LUA_ERROR_ITEM_NOT_FOUND: + return "Item not found"; + case LUA_ERROR_THING_NOT_FOUND: + return "Thing not found"; + case LUA_ERROR_TILE_NOT_FOUND: + return "Tile not found"; + case LUA_ERROR_HOUSE_NOT_FOUND: + return "House not found"; + case LUA_ERROR_COMBAT_NOT_FOUND: + return "Combat not found"; + case LUA_ERROR_CONDITION_NOT_FOUND: + return "Condition not found"; + case LUA_ERROR_AREA_NOT_FOUND: + return "Area not found"; + case LUA_ERROR_CONTAINER_NOT_FOUND: + return "Container not found"; + case LUA_ERROR_VARIANT_NOT_FOUND: + return "Variant not found"; + case LUA_ERROR_VARIANT_UNKNOWN: + return "Unknown variant type"; + case LUA_ERROR_SPELL_NOT_FOUND: + return "Spell not found"; + case LUA_ERROR_ACTION_NOT_FOUND: + return "Action not found"; + default: + return "Bad error code"; } } @@ -74,7 +93,7 @@ int LuaFunctionsLoader::protectedCall(lua_State* L, int nargs, int nresults) { return ret; } -void LuaFunctionsLoader::reportError(const char* function, const std::string& error_desc, bool stack_trace/* = false*/) { +void LuaFunctionsLoader::reportError(const char* function, const std::string &error_desc, bool stack_trace /* = false*/) { int32_t scriptId; int32_t callbackId; bool timerEvent; @@ -82,26 +101,19 @@ void LuaFunctionsLoader::reportError(const char* function, const std::string& er getScriptEnv()->getEventInfo(scriptId, scriptInterface, callbackId, timerEvent); SPDLOG_ERROR("Lua script error: \nscriptInterface: [{}]\nscriptId: [{}]" - "\ntimerEvent: [{}]\n callbackId:[{}]\nfunction: [{}]\nerror [{}]", - scriptInterface ? scriptInterface->getInterfaceName() : "", - scriptId ? scriptInterface->getFileById(scriptId) : "", - timerEvent ? "in a timer event called from:" : "", - callbackId ? scriptInterface->getFileById(callbackId) : "", - function ? scriptInterface->getInterfaceName() : "", - (stack_trace && scriptInterface) ? - scriptInterface->getStackTrace(error_desc) : error_desc - ); + "\ntimerEvent: [{}]\n callbackId:[{}]\nfunction: [{}]\nerror [{}]", + scriptInterface ? scriptInterface->getInterfaceName() : "", scriptId ? scriptInterface->getFileById(scriptId) : "", timerEvent ? "in a timer event called from:" : "", callbackId ? scriptInterface->getFileById(callbackId) : "", function ? scriptInterface->getInterfaceName() : "", (stack_trace && scriptInterface) ? scriptInterface->getStackTrace(error_desc) : error_desc); } int LuaFunctionsLoader::luaErrorHandler(lua_State* L) { - const std::string& errorMessage = popString(L); + const std::string &errorMessage = popString(L); auto interface = getScriptEnv()->getScriptInterface(); - assert(interface); //This fires if the ScriptEnvironment hasn't been setup + assert(interface); // This fires if the ScriptEnvironment hasn't been setup pushString(L, interface->getStackTrace(errorMessage)); return 1; } -void LuaFunctionsLoader::pushVariant(lua_State* L, const LuaVariant& var) { +void LuaFunctionsLoader::pushVariant(lua_State* L, const LuaVariant &var) { lua_createtable(L, 0, 2); setField(L, "type", var.type); switch (var.type) { @@ -161,7 +173,7 @@ void LuaFunctionsLoader::pushCylinder(lua_State* L, Cylinder* cylinder) { } } -void LuaFunctionsLoader::pushString(lua_State* L, const std::string& value) { +void LuaFunctionsLoader::pushString(lua_State* L, const std::string &value) { lua_pushlstring(L, value.c_str(), value.length()); } @@ -184,14 +196,14 @@ int32_t LuaFunctionsLoader::popCallback(lua_State* L) { } // Metatables -void LuaFunctionsLoader::setMetatable(lua_State* L, int32_t index, const std::string& name) { +void LuaFunctionsLoader::setMetatable(lua_State* L, int32_t index, const std::string &name) { luaL_getmetatable(L, name.c_str()); lua_setmetatable(L, index - 1); } -void LuaFunctionsLoader::setWeakMetatable(lua_State* L, int32_t index, const std::string& name) { +void LuaFunctionsLoader::setWeakMetatable(lua_State* L, int32_t index, const std::string &name) { static std::set weakObjectTypes; - const std::string& weakName = name + "_weak"; + const std::string &weakName = name + "_weak"; auto result = weakObjectTypes.emplace(name); if (result.second) { @@ -201,16 +213,14 @@ void LuaFunctionsLoader::setWeakMetatable(lua_State* L, int32_t index, const std luaL_newmetatable(L, weakName.c_str()); int metatable = lua_gettop(L); - for (static const std::vector methodKeys = {"__index", "__metatable", "__eq"}; - const std::string& metaKey : methodKeys) - { + for (static const std::vector methodKeys = { "__index", "__metatable", "__eq" }; + const std::string &metaKey : methodKeys) { lua_getfield(L, childMetatable, metaKey.c_str()); lua_setfield(L, metatable, metaKey.c_str()); } - for (static const std::vector methodIndexes = {'h', 'p', 't'}; - int metaIndex : methodIndexes) - { + for (static const std::vector methodIndexes = { 'h', 'p', 't' }; + int metaIndex : methodIndexes) { lua_rawgeti(L, childMetatable, metaIndex); lua_rawseti(L, metatable, metaIndex); } @@ -268,7 +278,7 @@ std::string LuaFunctionsLoader::getString(lua_State* L, int32_t arg) { return std::string(c_str, len); } -Position LuaFunctionsLoader::getPosition(lua_State* L, int32_t arg, int32_t& stackpos) { +Position LuaFunctionsLoader::getPosition(lua_State* L, int32_t arg, int32_t &stackpos) { Position position; position.x = getField(L, arg, "x"); position.y = getField(L, arg, "y"); @@ -353,7 +363,7 @@ Thing* LuaFunctionsLoader::getThing(lua_State* L, int32_t arg) { Thing* thing; if (lua_getmetatable(L, arg) != 0) { lua_rawgeti(L, -1, 't'); - switch(getNumber(L, -1)) { + switch (getNumber(L, -1)) { case LuaData_Item: thing = getUserdata(L, arg); break; @@ -397,7 +407,7 @@ Player* LuaFunctionsLoader::getPlayer(lua_State* L, int32_t arg) { return g_game().getPlayerByID(getNumber(L, arg)); } -std::string LuaFunctionsLoader::getFieldString(lua_State* L, int32_t arg, const std::string& key) { +std::string LuaFunctionsLoader::getFieldString(lua_State* L, int32_t arg, const std::string &key) { lua_getfield(L, arg, key.c_str()); return getString(L, -1); } @@ -419,7 +429,7 @@ void LuaFunctionsLoader::pushBoolean(lua_State* L, bool value) { lua_pushboolean(L, value ? 1 : 0); } -void LuaFunctionsLoader::pushCombatDamage(lua_State* L, const CombatDamage& damage) { +void LuaFunctionsLoader::pushCombatDamage(lua_State* L, const CombatDamage &damage) { lua_pushnumber(L, damage.primary.value); lua_pushnumber(L, damage.primary.type); lua_pushnumber(L, damage.secondary.value); @@ -427,7 +437,7 @@ void LuaFunctionsLoader::pushCombatDamage(lua_State* L, const CombatDamage& dama lua_pushnumber(L, damage.origin); } -void LuaFunctionsLoader::pushInstantSpell(lua_State* L, const InstantSpell& spell) { +void LuaFunctionsLoader::pushInstantSpell(lua_State* L, const InstantSpell &spell) { lua_createtable(L, 0, 6); setField(L, "name", spell.getName()); @@ -440,7 +450,7 @@ void LuaFunctionsLoader::pushInstantSpell(lua_State* L, const InstantSpell& spel setMetatable(L, -1, "Spell"); } -void LuaFunctionsLoader::pushPosition(lua_State* L, const Position& position, int32_t stackpos/* = 0*/) { +void LuaFunctionsLoader::pushPosition(lua_State* L, const Position &position, int32_t stackpos /* = 0*/) { lua_createtable(L, 0, 4); setField(L, "x", position.x); @@ -451,7 +461,7 @@ void LuaFunctionsLoader::pushPosition(lua_State* L, const Position& position, in setMetatable(L, -1, "Position"); } -void LuaFunctionsLoader::pushOutfit(lua_State* L, const Outfit_t& outfit) { +void LuaFunctionsLoader::pushOutfit(lua_State* L, const Outfit_t &outfit) { lua_createtable(L, 0, 13); setField(L, "lookType", outfit.lookType); setField(L, "lookTypeEx", outfit.lookTypeEx); @@ -468,7 +478,7 @@ void LuaFunctionsLoader::pushOutfit(lua_State* L, const Outfit_t& outfit) { setField(L, "lookFamiliarsType", outfit.lookFamiliarsType); } -void LuaFunctionsLoader::registerClass(lua_State* L, const std::string& className, const std::string& baseClass, lua_CFunction newFunction/* = nullptr*/) { +void LuaFunctionsLoader::registerClass(lua_State* L, const std::string &className, const std::string &baseClass, lua_CFunction newFunction /* = nullptr*/) { // className = {} lua_newtable(L); lua_pushvalue(L, -1); @@ -541,7 +551,7 @@ void LuaFunctionsLoader::registerClass(lua_State* L, const std::string& classNam lua_pop(L, 2); } -void LuaFunctionsLoader::registerMethod(lua_State* L, const std::string& globalName, const std::string& methodName, lua_CFunction func) { +void LuaFunctionsLoader::registerMethod(lua_State* L, const std::string &globalName, const std::string &methodName, lua_CFunction func) { // globalName.methodName = func lua_getglobal(L, globalName.c_str()); lua_pushcfunction(L, func); @@ -551,13 +561,13 @@ void LuaFunctionsLoader::registerMethod(lua_State* L, const std::string& globalN lua_pop(L, 1); } -void LuaFunctionsLoader::registerTable(lua_State* L, const std::string& tableName) { +void LuaFunctionsLoader::registerTable(lua_State* L, const std::string &tableName) { // _G[tableName] = {} lua_newtable(L); lua_setglobal(L, tableName.c_str()); } -void LuaFunctionsLoader::registerMetaMethod(lua_State* L, const std::string& className, const std::string& methodName, lua_CFunction func) { +void LuaFunctionsLoader::registerMetaMethod(lua_State* L, const std::string &className, const std::string &methodName, lua_CFunction func) { // className.metatable.methodName = func luaL_getmetatable(L, className.c_str()); lua_pushcfunction(L, func); @@ -567,7 +577,7 @@ void LuaFunctionsLoader::registerMetaMethod(lua_State* L, const std::string& cla lua_pop(L, 1); } -void LuaFunctionsLoader::registerVariable(lua_State* L, const std::string& tableName, const std::string& name, lua_Number value) { +void LuaFunctionsLoader::registerVariable(lua_State* L, const std::string &tableName, const std::string &name, lua_Number value) { // tableName.name = value lua_getglobal(L, tableName.c_str()); setField(L, name.c_str(), value); @@ -576,31 +586,31 @@ void LuaFunctionsLoader::registerVariable(lua_State* L, const std::string& table lua_pop(L, 1); } -void LuaFunctionsLoader::registerGlobalBoolean(lua_State* L, const std::string& name, bool value) { +void LuaFunctionsLoader::registerGlobalBoolean(lua_State* L, const std::string &name, bool value) { // _G[name] = value pushBoolean(L, value); lua_setglobal(L, name.c_str()); } -void LuaFunctionsLoader::registerGlobalMethod(lua_State* L, const std::string& functionName, lua_CFunction func) { +void LuaFunctionsLoader::registerGlobalMethod(lua_State* L, const std::string &functionName, lua_CFunction func) { // _G[functionName] = func lua_pushcfunction(L, func); lua_setglobal(L, functionName.c_str()); } -void LuaFunctionsLoader::registerGlobalVariable(lua_State* L, const std::string& name, lua_Number value) { +void LuaFunctionsLoader::registerGlobalVariable(lua_State* L, const std::string &name, lua_Number value) { // _G[name] = value lua_pushnumber(L, value); lua_setglobal(L, name.c_str()); } -void LuaFunctionsLoader::registerGlobalString(lua_State* L, const std::string& variable, const std::string &name) { +void LuaFunctionsLoader::registerGlobalString(lua_State* L, const std::string &variable, const std::string &name) { // Example: registerGlobalString(L, "VARIABLE_NAME", "variable string"); pushString(L, name); lua_setglobal(L, variable.c_str()); } -std::string LuaFunctionsLoader::escapeString(const std::string& string) { +std::string LuaFunctionsLoader::escapeString(const std::string &string) { std::string s = string; replaceString(s, "\\", "\\\\"); replaceString(s, "\"", "\\\""); diff --git a/src/lua/functions/lua_functions_loader.hpp b/src/lua/functions/lua_functions_loader.hpp index f7be42fb259..faa80735bb5 100644 --- a/src/lua/functions/lua_functions_loader.hpp +++ b/src/lua/functions/lua_functions_loader.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_LUA_FUNCTIONS_LOADER_HPP_ #define SRC_LUA_FUNCTIONS_LUA_FUNCTIONS_LOADER_HPP_ @@ -24,7 +24,7 @@ class Item; class Player; class Thing; -#define reportErrorFunc(a) reportError(__FUNCTION__, a, true) +#define reportErrorFunc(a) reportError(__FUNCTION__, a, true) class LuaFunctionsLoader { public: @@ -32,72 +32,64 @@ class LuaFunctionsLoader { static std::string getErrorDesc(ErrorCode_t code); - static void reportError(const char* function, const std::string& error_desc, bool stack_trace = false); + static void reportError(const char* function, const std::string &error_desc, bool stack_trace = false); static int luaErrorHandler(lua_State* L); static void pushThing(lua_State* L, Thing* thing); - static void pushVariant(lua_State* L, const LuaVariant& var); - static void pushString(lua_State* L, const std::string& value); + static void pushVariant(lua_State* L, const LuaVariant &var); + static void pushString(lua_State* L, const std::string &value); static void pushCallback(lua_State* L, int32_t callback); static void pushCylinder(lua_State* L, Cylinder* cylinder); static std::string popString(lua_State* L); static int32_t popCallback(lua_State* L); - template - static void pushUserdata(lua_State* L, T* value) - { + template + static void pushUserdata(lua_State* L, T* value) { T** userdata = static_cast(lua_newuserdata(L, sizeof(T*))); *userdata = value; } - static void setMetatable(lua_State* L, int32_t index, const std::string& name); - static void setWeakMetatable(lua_State* L, int32_t index, const std::string& name); + static void setMetatable(lua_State* L, int32_t index, const std::string &name); + static void setWeakMetatable(lua_State* L, int32_t index, const std::string &name); static void setItemMetatable(lua_State* L, int32_t index, const Item* item); static void setCreatureMetatable(lua_State* L, int32_t index, const Creature* creature); - template + template static typename std::enable_if::value, T>::type - getNumber(lua_State* L, int32_t arg) - { + getNumber(lua_State* L, int32_t arg) { return static_cast(static_cast(lua_tonumber(L, arg))); } - template + template static typename std::enable_if::value || std::is_floating_point::value, T>::type - getNumber(lua_State* L, int32_t arg) - { + getNumber(lua_State* L, int32_t arg) { return static_cast(lua_tonumber(L, arg)); } - template - static T getNumber(lua_State *L, int32_t arg, T defaultValue) - { + template + static T getNumber(lua_State* L, int32_t arg, T defaultValue) { const auto parameters = lua_gettop(L); if (parameters == 0 || arg > parameters) { return defaultValue; } return getNumber(L, arg); } - template - static T* getUserdata(lua_State* L, int32_t arg) - { + template + static T* getUserdata(lua_State* L, int32_t arg) { T** userdata = getRawUserdata(L, arg); if (!userdata) { return nullptr; } return *userdata; } - template - static T** getRawUserdata(lua_State* L, int32_t arg) - { + template + static T** getRawUserdata(lua_State* L, int32_t arg) { return static_cast(lua_touserdata(L, arg)); } - static bool getBoolean(lua_State* L, int32_t arg) - { + static bool getBoolean(lua_State* L, int32_t arg) { return lua_toboolean(L, arg) != 0; } - static bool getBoolean(lua_State* L, int32_t arg, bool defaultValue) - { + static bool getBoolean(lua_State* L, int32_t arg, bool defaultValue) { const auto parameters = lua_gettop(L); if (parameters == 0 || arg > parameters) { return defaultValue; @@ -107,7 +99,7 @@ class LuaFunctionsLoader { static std::string getString(lua_State* L, int32_t arg); static CombatDamage getCombatDamage(lua_State* L); - static Position getPosition(lua_State* L, int32_t arg, int32_t& stackpos); + static Position getPosition(lua_State* L, int32_t arg, int32_t &stackpos); static Position getPosition(lua_State* L, int32_t arg); static Outfit_t getOutfit(lua_State* L, int32_t arg); static LuaVariant getVariant(lua_State* L, int32_t arg); @@ -116,61 +108,52 @@ class LuaFunctionsLoader { static Creature* getCreature(lua_State* L, int32_t arg); static Player* getPlayer(lua_State* L, int32_t arg); - template - static T getField(lua_State* L, int32_t arg, const std::string& key) - { + template + static T getField(lua_State* L, int32_t arg, const std::string &key) { lua_getfield(L, arg, key.c_str()); return getNumber(L, -1); } - static std::string getFieldString(lua_State* L, int32_t arg, const std::string& key); + static std::string getFieldString(lua_State* L, int32_t arg, const std::string &key); static LuaDataType getUserdataType(lua_State* L, int32_t arg); - static bool isNumber(lua_State* L, int32_t arg) - { + static bool isNumber(lua_State* L, int32_t arg) { return lua_type(L, arg) == LUA_TNUMBER; } - static bool isString(lua_State* L, int32_t arg) - { + static bool isString(lua_State* L, int32_t arg) { return lua_isstring(L, arg) != 0; } - static bool isBoolean(lua_State* L, int32_t arg) - { + static bool isBoolean(lua_State* L, int32_t arg) { return lua_isboolean(L, arg); } - static bool isTable(lua_State* L, int32_t arg) - { + static bool isTable(lua_State* L, int32_t arg) { return lua_istable(L, arg); } - static bool isFunction(lua_State* L, int32_t arg) - { + static bool isFunction(lua_State* L, int32_t arg) { return lua_isfunction(L, arg); } - static bool isUserdata(lua_State* L, int32_t arg) - { + static bool isUserdata(lua_State* L, int32_t arg) { return lua_isuserdata(L, arg) != 0; } static void pushBoolean(lua_State* L, bool value); - static void pushCombatDamage(lua_State* L, const CombatDamage& damage); - static void pushInstantSpell(lua_State* L, const InstantSpell& spell); - static void pushPosition(lua_State* L, const Position& position, int32_t stackpos = 0); - static void pushOutfit(lua_State* L, const Outfit_t& outfit); + static void pushCombatDamage(lua_State* L, const CombatDamage &damage); + static void pushInstantSpell(lua_State* L, const InstantSpell &spell); + static void pushPosition(lua_State* L, const Position &position, int32_t stackpos = 0); + static void pushOutfit(lua_State* L, const Outfit_t &outfit); - static void setField(lua_State* L, const char* index, lua_Number value) - { + static void setField(lua_State* L, const char* index, lua_Number value) { lua_pushnumber(L, value); lua_setfield(L, -2, index); } - static void setField(lua_State* L, const char* index, const std::string& value) - { + static void setField(lua_State* L, const char* index, const std::string &value) { pushString(L, value); lua_setfield(L, -2, index); } - static std::string escapeString(const std::string& string); + static std::string escapeString(const std::string &string); static int protectedCall(lua_State* L, int nargs, int nresults); @@ -189,16 +172,16 @@ class LuaFunctionsLoader { } protected: - static void registerClass(lua_State* L, const std::string& className, const std::string& baseClass, lua_CFunction newFunction = nullptr); - static void registerMethod(lua_State* L, const std::string& globalName, const std::string& methodName, lua_CFunction func); - static void registerMetaMethod(lua_State* L, const std::string& className, const std::string& methodName, lua_CFunction func); - static void registerTable(lua_State* L, const std::string& tableName); - static void registerVariable(lua_State* L, const std::string& tableName, const std::string& name, lua_Number value); - - static void registerGlobalBoolean(lua_State* L, const std::string& name, bool value); - static void registerGlobalMethod(lua_State* L, const std::string& functionName, lua_CFunction func); - static void registerGlobalVariable(lua_State* L, const std::string& name, lua_Number value); - static void registerGlobalString(lua_State* L, const std::string& variable, const std::string &name); + static void registerClass(lua_State* L, const std::string &className, const std::string &baseClass, lua_CFunction newFunction = nullptr); + static void registerMethod(lua_State* L, const std::string &globalName, const std::string &methodName, lua_CFunction func); + static void registerMetaMethod(lua_State* L, const std::string &className, const std::string &methodName, lua_CFunction func); + static void registerTable(lua_State* L, const std::string &tableName); + static void registerVariable(lua_State* L, const std::string &tableName, const std::string &name, lua_Number value); + + static void registerGlobalBoolean(lua_State* L, const std::string &name, bool value); + static void registerGlobalMethod(lua_State* L, const std::string &functionName, lua_CFunction func); + static void registerGlobalVariable(lua_State* L, const std::string &name, lua_Number value); + static void registerGlobalString(lua_State* L, const std::string &variable, const std::string &name); static int luaUserdataCompare(lua_State* L); diff --git a/src/lua/functions/map/house_functions.cpp b/src/lua/functions/map/house_functions.cpp index 60c7ebb33ad..3ea06ce2d7c 100644 --- a/src/lua/functions/map/house_functions.cpp +++ b/src/lua/functions/map/house_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -169,7 +169,7 @@ int HouseFunctions::luaHouseGetBeds(lua_State* L) { return 1; } - const auto& beds = house->getBeds(); + const auto &beds = house->getBeds(); lua_createtable(L, beds.size(), 0); int index = 0; @@ -200,7 +200,7 @@ int HouseFunctions::luaHouseGetDoors(lua_State* L) { return 1; } - const auto& doors = house->getDoors(); + const auto &doors = house->getDoors(); lua_createtable(L, doors.size(), 0); int index = 0; @@ -248,7 +248,7 @@ int HouseFunctions::luaHouseGetTiles(lua_State* L) { return 1; } - const auto& tiles = house->getTiles(); + const auto &tiles = house->getTiles(); lua_newtable(L); int index = 0; @@ -268,7 +268,7 @@ int HouseFunctions::luaHouseGetItems(lua_State* L) { return 1; } - const auto& tiles = house->getTiles(); + const auto &tiles = house->getTiles(); lua_newtable(L); int index = 0; @@ -279,7 +279,6 @@ int HouseFunctions::luaHouseGetItems(lua_State* L) { pushUserdata(L, item); setItemMetatable(L, -1, item); lua_rawseti(L, -2, ++index); - } } } @@ -339,7 +338,7 @@ int HouseFunctions::luaHouseSetAccessList(lua_State* L) { } uint32_t listId = getNumber(L, 2); - const std::string& list = getString(L, 3); + const std::string &list = getString(L, 3); house->setAccessList(listId, list); pushBoolean(L, true); return 1; diff --git a/src/lua/functions/map/house_functions.hpp b/src/lua/functions/map/house_functions.hpp index e3f01be13ed..c5f8a1d8e0d 100644 --- a/src/lua/functions/map/house_functions.hpp +++ b/src/lua/functions/map/house_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_MAP_HOUSE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_MAP_HOUSE_FUNCTIONS_HPP_ @@ -79,4 +79,4 @@ class HouseFunctions final : LuaScriptInterface { static int luaHouseIsInvited(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_MAP_HOUSE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_MAP_HOUSE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/map/map_functions.hpp b/src/lua/functions/map/map_functions.hpp index b86fcd917a8..304a7328791 100644 --- a/src/lua/functions/map/map_functions.hpp +++ b/src/lua/functions/map/map_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_MAP_MAP_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_MAP_MAP_FUNCTIONS_HPP_ @@ -28,6 +28,6 @@ class MapFunctions final : LuaScriptInterface { } private: - }; +}; -#endif // SRC_LUA_FUNCTIONS_MAP_MAP_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_MAP_MAP_FUNCTIONS_HPP_ diff --git a/src/lua/functions/map/position_functions.cpp b/src/lua/functions/map/position_functions.cpp index 25dee04feaf..6345cacf7a5 100644 --- a/src/lua/functions/map/position_functions.cpp +++ b/src/lua/functions/map/position_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -23,7 +23,7 @@ int PositionFunctions::luaPositionCreate(lua_State* L) { int32_t stackpos; if (isTable(L, 2)) { - const Position& position = getPosition(L, 2, stackpos); + const Position &position = getPosition(L, 2, stackpos); pushPosition(L, position, stackpos); } else { uint16_t x = getNumber(L, 2, 0); @@ -39,7 +39,7 @@ int PositionFunctions::luaPositionCreate(lua_State* L) { int PositionFunctions::luaPositionAdd(lua_State* L) { // positionValue = position + positionEx int32_t stackpos; - const Position& position = getPosition(L, 1, stackpos); + const Position &position = getPosition(L, 1, stackpos); Position positionEx; if (stackpos == 0) { @@ -55,7 +55,7 @@ int PositionFunctions::luaPositionAdd(lua_State* L) { int PositionFunctions::luaPositionSub(lua_State* L) { // positionValue = position - positionEx int32_t stackpos; - const Position& position = getPosition(L, 1, stackpos); + const Position &position = getPosition(L, 1, stackpos); Position positionEx; if (stackpos == 0) { @@ -70,30 +70,24 @@ int PositionFunctions::luaPositionSub(lua_State* L) { int PositionFunctions::luaPositionCompare(lua_State* L) { // position == positionEx - const Position& positionEx = getPosition(L, 2); - const Position& position = getPosition(L, 1); + const Position &positionEx = getPosition(L, 2); + const Position &position = getPosition(L, 1); pushBoolean(L, position == positionEx); return 1; } int PositionFunctions::luaPositionGetDistance(lua_State* L) { // position:getDistance(positionEx) - const Position& positionEx = getPosition(L, 2); - const Position& position = getPosition(L, 1); - lua_pushnumber(L, std::max( - std::max( - std::abs(Position::getDistanceX(position, positionEx)), - std::abs(Position::getDistanceY(position, positionEx)) - ), - std::abs(Position::getDistanceZ(position, positionEx)) - )); + const Position &positionEx = getPosition(L, 2); + const Position &position = getPosition(L, 1); + lua_pushnumber(L, std::max(std::max(std::abs(Position::getDistanceX(position, positionEx)), std::abs(Position::getDistanceY(position, positionEx))), std::abs(Position::getDistanceZ(position, positionEx)))); return 1; } int PositionFunctions::luaPositionGetPathTo(lua_State* L) { // position:getPathTo(pos[, minTargetDist = 0[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]]) - const Position& pos = getPosition(L, 1); - const Position& position = getPosition(L, 2); + const Position &pos = getPosition(L, 1); + const Position &position = getPosition(L, 2); FindPathParams fpp; fpp.minTargetDist = getNumber(L, 3, 0); @@ -111,8 +105,7 @@ int PositionFunctions::luaPositionGetPathTo(lua_State* L) { lua_pushnumber(L, dir); lua_rawseti(L, -2, ++index); } - } - else { + } else { pushBoolean(L, false); } return 1; @@ -121,8 +114,8 @@ int PositionFunctions::luaPositionGetPathTo(lua_State* L) { int PositionFunctions::luaPositionIsSightClear(lua_State* L) { // position:isSightClear(positionEx[, sameFloor = true]) bool sameFloor = getBoolean(L, 3, true); - const Position& positionEx = getPosition(L, 2); - const Position& position = getPosition(L, 1); + const Position &positionEx = getPosition(L, 2); + const Position &position = getPosition(L, 1); pushBoolean(L, g_game().isSightClear(position, positionEx, sameFloor)); return 1; } @@ -144,7 +137,7 @@ int PositionFunctions::luaPositionSendMagicEffect(lua_State* L) { return 1; } - const Position& position = getPosition(L, 1); + const Position &position = getPosition(L, 1); if (!spectators.empty()) { Game::addMagicEffect(spectators, position, magicEffect); } else { @@ -166,8 +159,8 @@ int PositionFunctions::luaPositionSendDistanceEffect(lua_State* L) { } ShootType_t distanceEffect = getNumber(L, 3); - const Position& positionEx = getPosition(L, 2); - const Position& position = getPosition(L, 1); + const Position &positionEx = getPosition(L, 2); + const Position &position = getPosition(L, 1); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && !g_game().isDistanceEffectRegistered(distanceEffect)) { SPDLOG_WARN("[PositionFunctions::luaPositionSendDistanceEffect] An unregistered distance effect type with id '{}' was blocked to prevent client crash.", distanceEffect); return 1; diff --git a/src/lua/functions/map/position_functions.hpp b/src/lua/functions/map/position_functions.hpp index f2033763d46..c376ba25818 100644 --- a/src/lua/functions/map/position_functions.hpp +++ b/src/lua/functions/map/position_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_MAP_POSITION_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_MAP_POSITION_FUNCTIONS_HPP_ diff --git a/src/lua/functions/map/teleport_functions.cpp b/src/lua/functions/map/teleport_functions.cpp index ea7d933d249..f5d76840824 100644 --- a/src/lua/functions/map/teleport_functions.cpp +++ b/src/lua/functions/map/teleport_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/map/teleport_functions.hpp b/src/lua/functions/map/teleport_functions.hpp index 466ceef2f67..1df9fb9cb4b 100644 --- a/src/lua/functions/map/teleport_functions.hpp +++ b/src/lua/functions/map/teleport_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_MAP_TELEPORT_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_MAP_TELEPORT_FUNCTIONS_HPP_ @@ -20,7 +20,7 @@ class TeleportFunctions final : LuaScriptInterface { registerMethod(L, "Teleport", "getDestination", TeleportFunctions::luaTeleportGetDestination); registerMethod(L, "Teleport", "setDestination", TeleportFunctions::luaTeleportSetDestination); - } + } private: static int luaTeleportCreate(lua_State* L); @@ -28,4 +28,4 @@ class TeleportFunctions final : LuaScriptInterface { static int luaTeleportSetDestination(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_MAP_TELEPORT_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_MAP_TELEPORT_FUNCTIONS_HPP_ diff --git a/src/lua/functions/map/tile_functions.cpp b/src/lua/functions/map/tile_functions.cpp index 1e1fe660e64..192269ba368 100644 --- a/src/lua/functions/map/tile_functions.cpp +++ b/src/lua/functions/map/tile_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -247,7 +247,7 @@ int TileFunctions::luaTileGetItemByType(lua_State* L) { } if (Item* item = tile->getGround()) { - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.type == itemType) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -257,7 +257,7 @@ int TileFunctions::luaTileGetItemByType(lua_State* L) { if (const TileItemVector* items = tile->getItemList()) { for (Item* item : *items) { - const ItemType& it = Item::items[item->getID()]; + const ItemType &it = Item::items[item->getID()]; if (it.type == itemType) { pushUserdata(L, item); setItemMetatable(L, -1, item); diff --git a/src/lua/functions/map/tile_functions.hpp b/src/lua/functions/map/tile_functions.hpp index 2acdcf9d91f..4e1da33b7ac 100644 --- a/src/lua/functions/map/tile_functions.hpp +++ b/src/lua/functions/map/tile_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_MAP_TILE_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_MAP_TILE_FUNCTIONS_HPP_ @@ -101,4 +101,4 @@ class TileFunctions final : LuaScriptInterface { static int luaTileGetHouse(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_MAP_TILE_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_MAP_TILE_FUNCTIONS_HPP_ diff --git a/src/lua/functions/map/town_functions.cpp b/src/lua/functions/map/town_functions.cpp index 75cfba37bc0..1bd87d84288 100644 --- a/src/lua/functions/map/town_functions.cpp +++ b/src/lua/functions/map/town_functions.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" diff --git a/src/lua/functions/map/town_functions.hpp b/src/lua/functions/map/town_functions.hpp index 7c36a099a4c..626bca1a19c 100644 --- a/src/lua/functions/map/town_functions.hpp +++ b/src/lua/functions/map/town_functions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_FUNCTIONS_MAP_TOWN_FUNCTIONS_HPP_ #define SRC_LUA_FUNCTIONS_MAP_TOWN_FUNCTIONS_HPP_ @@ -31,4 +31,4 @@ class TownFunctions final : LuaScriptInterface { static int luaTownGetTemplePosition(lua_State* L); }; -#endif // SRC_LUA_FUNCTIONS_MAP_TOWN_FUNCTIONS_HPP_ +#endif // SRC_LUA_FUNCTIONS_MAP_TOWN_FUNCTIONS_HPP_ diff --git a/src/lua/global/baseevents.cpp b/src/lua/global/baseevents.cpp index 8798998180f..62335359c07 100644 --- a/src/lua/global/baseevents.cpp +++ b/src/lua/global/baseevents.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -22,12 +22,11 @@ bool BaseEvents::loadFromXml() { std::string scriptsName = getScriptBaseName(); std::string basePath = g_configManager().getString(CORE_DIRECTORY) + "/" + scriptsName + "/"; if (getScriptInterface().loadFile( - basePath + "lib/" + scriptsName + ".lua", - scriptsName + ".lua" - ) == -1) - { - SPDLOG_WARN(__FUNCTION__, - scriptsName, scriptsName); + basePath + "lib/" + scriptsName + ".lua", + scriptsName + ".lua" + ) + == -1) { + SPDLOG_WARN(__FUNCTION__, scriptsName, scriptsName); } std::string filename = basePath + scriptsName + ".xml"; @@ -58,7 +57,7 @@ bool BaseEvents::loadFromXml() { if (scriptAttribute) { std::string scriptFile = "scripts/" + std::string(scriptAttribute.as_string()); success = event->checkScript(basePath, scriptsName, scriptFile) - && event->loadScript(basePath + scriptFile, scriptAttribute.as_string()); + && event->loadScript(basePath + scriptFile, scriptAttribute.as_string()); if (node.attribute("function")) { event->loadFunction(node.attribute("function"), true); } @@ -83,17 +82,15 @@ void BaseEvents::reInitState() { getScriptInterface().reInitState(); } -Event::Event(LuaScriptInterface* interface) : scriptInterface(interface) {} +Event::Event(LuaScriptInterface* interface) : + scriptInterface(interface) { } -bool Event::checkScript(const std::string& basePath, const std::string& - scriptsName, const std::string& scriptFile) const { +bool Event::checkScript(const std::string &basePath, const std::string &scriptsName, const std::string &scriptFile) const { LuaScriptInterface* testInterface = g_luaEnvironment.getTestInterface(); testInterface->reInitState(); - if (testInterface->loadFile(basePath + "lib/" + scriptsName + ".lua", scriptsName + ".lua") == -1) - { - SPDLOG_WARN("[Event::checkScript] - Can not load {}lib/{}.lua", - scriptsName, scriptsName); + if (testInterface->loadFile(basePath + "lib/" + scriptsName + ".lua", scriptsName + ".lua") == -1) { + SPDLOG_WARN("[Event::checkScript] - Can not load {}lib/{}.lua", scriptsName, scriptsName); } if (scriptId != 0) { @@ -110,13 +107,14 @@ bool Event::checkScript(const std::string& basePath, const std::string& int32_t id = testInterface->getEvent(getScriptEventName()); if (id == -1) { SPDLOG_WARN("[Event::checkScript] - Event " - "{} not found {}", getScriptEventName(), scriptFile); + "{} not found {}", + getScriptEventName(), scriptFile); return false; } return true; } -bool Event::loadScript(const std::string& scriptFile, const std::string& scriptName) { +bool Event::loadScript(const std::string &scriptFile, const std::string &scriptName) { if ((scriptInterface == nullptr) || scriptId != 0) { SPDLOG_WARN( "[{}] - ScriptInterface (nullptr), can not load scriptid: {}", @@ -146,8 +144,7 @@ bool Event::loadScript(const std::string& scriptFile, const std::string& scriptN return true; } -bool CallBack::loadCallBack(LuaScriptInterface* interface, const std::string& - name) { +bool CallBack::loadCallBack(LuaScriptInterface* interface, const std::string &name) { if (interface == nullptr) { SPDLOG_WARN("[{}] - ScriptInterface (nullptr) for event: {}", __FUNCTION__, name); return false; diff --git a/src/lua/global/baseevents.h b/src/lua/global/baseevents.h index 589444fede2..c4af1b2426d 100644 --- a/src/lua/global/baseevents.h +++ b/src/lua/global/baseevents.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_GLOBAL_BASEEVENTS_H_ #define SRC_LUA_GLOBAL_BASEEVENTS_H_ @@ -22,70 +22,69 @@ using Event_ptr = std::unique_ptr; class Event { public: /** - * @brief Explicit construtor - * explicit, that is, it cannot be used for implicit conversions and - * copy-initialization. - * - * @param interface Lua Script Interface - */ + * @brief Explicit construtor + * explicit, that is, it cannot be used for implicit conversions and + * copy-initialization. + * + * @param interface Lua Script Interface + */ explicit Event(LuaScriptInterface* interface); virtual ~Event() = default; - virtual bool configureEvent(const pugi::xml_node& node) = 0; + virtual bool configureEvent(const pugi::xml_node &node) = 0; /** - * @brief Test if script can be found and loaded. - * - * E.g.: basePath = data/ - * scriptsName = actions -> actions/lib/actions.lua - * scriptFile = A/X.lua -> actions/scripts/A/X.lua - * - * @param basePath Base path folder - * @param scriptsName Folder|Lib script name (without .lua) - * /lib/.lua - * @param scriptFile Path to script file - * /scripts/ - * @return true Success, script can be loaded. - * @return false Fail, script not found or couldn't be loaded. - */ - bool checkScript(const std::string& basePath, const std::string& - scriptsName, const std::string& scriptFile) const; + * @brief Test if script can be found and loaded. + * + * E.g.: basePath = data/ + * scriptsName = actions -> actions/lib/actions.lua + * scriptFile = A/X.lua -> actions/scripts/A/X.lua + * + * @param basePath Base path folder + * @param scriptsName Folder|Lib script name (without .lua) + * /lib/.lua + * @param scriptFile Path to script file + * /scripts/ + * @return true Success, script can be loaded. + * @return false Fail, script not found or couldn't be loaded. + */ + bool checkScript(const std::string &basePath, const std::string &scriptsName, const std::string &scriptFile) const; /** - * @brief Load the script file. - * - * @param scriptFile Path to script file. - * @return true Success - * @return false Fail - */ - bool loadScript(const std::string& scriptFile, const std::string& scriptName); + * @brief Load the script file. + * + * @param scriptFile Path to script file. + * @return true Success + * @return false Fail + */ + bool loadScript(const std::string &scriptFile, const std::string &scriptName); /** - * @brief Load script ID using the lua script interface - * - * @return true Success - * @return false Fail - */ + * @brief Load script ID using the lua script interface + * + * @return true Success + * @return false Fail + */ - virtual bool loadFunction(const pugi::xml_attribute&, bool) { + virtual bool loadFunction(const pugi::xml_attribute &, bool) { return false; } /** - * @brief Check if event is scripted - * - * @return true - * @return false - */ + * @brief Check if event is scripted + * + * @return true + * @return false + */ bool isScripted() const { return scripted; } /** - * @brief Get the Script Id object - * - * @return int32_t - */ + * @brief Get the Script Id object + * + * @return int32_t + */ int32_t getScriptId() { return scriptId; } @@ -106,35 +105,35 @@ class Event { class BaseEvents { public: /** - * @brief The constexpr specifier declares that it is possible to - * evaluate the value of the function or variable at compile time. - * - */ + * @brief The constexpr specifier declares that it is possible to + * evaluate the value of the function or variable at compile time. + * + */ constexpr BaseEvents() = default; virtual ~BaseEvents() = default; /** - * @brief Load XML file - * - * @return true Success - * @return false Fail - */ + * @brief Load XML file + * + * @return true Success + * @return false Fail + */ bool loadFromXml(); /** - * @brief Reload XML file - * - * @return true Success - * @return false Fail - */ + * @brief Reload XML file + * + * @return true Success + * @return false Fail + */ bool reload(); /** - * @brief Check if it is loaded - * - * @return true - * @return false - */ + * @brief Check if it is loaded + * + * @return true + * @return false + */ bool isLoaded() const { return loaded; } @@ -142,15 +141,14 @@ class BaseEvents { /** * @brief Restart the Lua interface state * - */ + */ void reInitState(); private: - virtual LuaScriptInterface& getScriptInterface() = 0; + virtual LuaScriptInterface &getScriptInterface() = 0; virtual std::string getScriptBaseName() const = 0; - virtual Event_ptr getEvent(const std::string& nodeName) = 0; - virtual bool registerEvent(Event_ptr event, const pugi::xml_node& - node) = 0; + virtual Event_ptr getEvent(const std::string &nodeName) = 0; + virtual bool registerEvent(Event_ptr event, const pugi::xml_node &node) = 0; virtual void clear(bool) = 0; bool loaded = false; @@ -167,15 +165,14 @@ class CallBack { CallBack() = default; /** - * @brief Set the scriptInterface according the event name. - * - * @param interface - * @param name - * @return true - * @return false - */ - bool loadCallBack(LuaScriptInterface* interface, const std::string& - name); + * @brief Set the scriptInterface according the event name. + * + * @param interface + * @param name + * @return true + * @return false + */ + bool loadCallBack(LuaScriptInterface* interface, const std::string &name); protected: int32_t scriptId = 0; @@ -185,4 +182,4 @@ class CallBack { bool loaded = false; }; -#endif // SRC_BASEEVENTS_H_ +#endif // SRC_BASEEVENTS_H_ diff --git a/src/lua/global/globalevent.cpp b/src/lua/global/globalevent.cpp index c4c07dfc41e..cf22231f62c 100644 --- a/src/lua/global/globalevent.cpp +++ b/src/lua/global/globalevent.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -31,7 +31,7 @@ void GlobalEvents::clear() { } bool GlobalEvents::registerLuaEvent(GlobalEvent* event) { - GlobalEvent_ptr globalEvent{ event }; + GlobalEvent_ptr globalEvent { event }; if (globalEvent->getEventType() == GLOBALEVENT_TIMER) { auto result = timerMap.emplace(globalEvent->getName(), std::move(*globalEvent)); if (result.second) { @@ -70,7 +70,7 @@ void GlobalEvents::timer() { auto it = timerMap.begin(); while (it != timerMap.end()) { - GlobalEvent& globalEvent = it->second; + GlobalEvent &globalEvent = it->second; int64_t nextExecutionTime = globalEvent.getNextExecution() - now; if (nextExecutionTime > 0) { @@ -98,8 +98,7 @@ void GlobalEvents::timer() { } if (nextScheduledTime != std::numeric_limits::max()) { - timerEventId = g_scheduler().addEvent(createSchedulerTask(std::max(1000, nextScheduledTime * 1000), - std::bind(&GlobalEvents::timer, this))); + timerEventId = g_scheduler().addEvent(createSchedulerTask(std::max(1000, nextScheduledTime * 1000), std::bind(&GlobalEvents::timer, this))); } } @@ -107,8 +106,8 @@ void GlobalEvents::think() { int64_t now = OTSYS_TIME(); int64_t nextScheduledTime = std::numeric_limits::max(); - for (auto& it : thinkMap) { - GlobalEvent& globalEvent = it.second; + for (auto &it : thinkMap) { + GlobalEvent &globalEvent = it.second; int64_t nextExecutionTime = globalEvent.getNextExecution() - now; if (nextExecutionTime > 0) { @@ -120,7 +119,8 @@ void GlobalEvents::think() { if (!globalEvent.executeEvent()) { SPDLOG_ERROR("[GlobalEvents::think] - " - "Failed to execute event: {}", globalEvent.getName()); + "Failed to execute event: {}", + globalEvent.getName()); } nextExecutionTime = globalEvent.getInterval(); @@ -138,8 +138,8 @@ void GlobalEvents::think() { } void GlobalEvents::execute(GlobalEvent_t type) const { - for (const auto& it : serverMap) { - const GlobalEvent& globalEvent = it.second; + for (const auto &it : serverMap) { + const GlobalEvent &globalEvent = it.second; if (globalEvent.getEventType() == type) { globalEvent.executeEvent(); } @@ -149,34 +149,44 @@ void GlobalEvents::execute(GlobalEvent_t type) const { GlobalEventMap GlobalEvents::getEventMap(GlobalEvent_t type) { // TODO: This should be better implemented. Maybe have a map for every type. switch (type) { - case GLOBALEVENT_NONE: return thinkMap; - case GLOBALEVENT_TIMER: return timerMap; + case GLOBALEVENT_NONE: + return thinkMap; + case GLOBALEVENT_TIMER: + return timerMap; case GLOBALEVENT_PERIODCHANGE: case GLOBALEVENT_STARTUP: case GLOBALEVENT_SHUTDOWN: case GLOBALEVENT_RECORD: { GlobalEventMap retMap; - for (const auto& it : serverMap) { + for (const auto &it : serverMap) { if (it.second.getEventType() == type) { retMap.emplace(it.first, it.second); } } return retMap; } - default: return GlobalEventMap(); + default: + return GlobalEventMap(); } } -GlobalEvent::GlobalEvent(LuaScriptInterface* interface) : Script(interface) {} +GlobalEvent::GlobalEvent(LuaScriptInterface* interface) : + Script(interface) { } std::string GlobalEvent::getScriptTypeName() const { switch (eventType) { - case GLOBALEVENT_STARTUP: return "onStartup"; - case GLOBALEVENT_SHUTDOWN: return "onShutdown"; - case GLOBALEVENT_RECORD: return "onRecord"; - case GLOBALEVENT_TIMER: return "onTime"; - case GLOBALEVENT_PERIODCHANGE: return "onPeriodChange"; - case GLOBALEVENT_ON_THINK: return "onThink"; + case GLOBALEVENT_STARTUP: + return "onStartup"; + case GLOBALEVENT_SHUTDOWN: + return "onShutdown"; + case GLOBALEVENT_RECORD: + return "onRecord"; + case GLOBALEVENT_TIMER: + return "onTime"; + case GLOBALEVENT_PERIODCHANGE: + return "onPeriodChange"; + case GLOBALEVENT_ON_THINK: + return "onThink"; default: SPDLOG_ERROR("[GlobalEvent::getScriptTypeName] - Invalid event type"); return std::string(); @@ -184,11 +194,11 @@ std::string GlobalEvent::getScriptTypeName() const { } bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightInfo) const { - //onPeriodChange(lightState, lightTime) + // onPeriodChange(lightState, lightTime) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[GlobalEvent::executePeriodChange - {}] " - "Call stack overflow. Too many lua script calls being nested.", - getName()); + "Call stack overflow. Too many lua script calls being nested.", + getName()); return false; } @@ -204,11 +214,11 @@ bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightIn } bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { - //onRecord(current, old) + // onRecord(current, old) if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[GlobalEvent::executeRecord - {}] " - "Call stack overflow. Too many lua script calls being nested.", - getName()); + "Call stack overflow. Too many lua script calls being nested.", + getName()); return false; } @@ -226,8 +236,8 @@ bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { bool GlobalEvent::executeEvent() const { if (!getScriptInterface()->reserveScriptEnv()) { SPDLOG_ERROR("[GlobalEvent::executeEvent - {}] " - "Call stack overflow. Too many lua script calls being nested.", - getName()); + "Call stack overflow. Too many lua script calls being nested.", + getName()); return false; } diff --git a/src/lua/global/globalevent.h b/src/lua/global/globalevent.h index 80edd17a30a..0cee20efd65 100644 --- a/src/lua/global/globalevent.h +++ b/src/lua/global/globalevent.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_GLOBAL_GLOBALEVENT_H_ #define SRC_LUA_GLOBAL_GLOBALEVENT_H_ @@ -23,10 +23,10 @@ class GlobalEvents final : public Scripts { ~GlobalEvents(); // non-copyable - GlobalEvents(const GlobalEvents&) = delete; - GlobalEvents& operator=(const GlobalEvents&) = delete; + GlobalEvents(const GlobalEvents &) = delete; + GlobalEvents &operator=(const GlobalEvents &) = delete; - static GlobalEvents& getInstance() { + static GlobalEvents &getInstance() { // Guaranteed to be destroyed static GlobalEvents instance; // Instantiated on first use @@ -55,7 +55,7 @@ class GlobalEvent final : public Script { public: explicit GlobalEvent(LuaScriptInterface* interface); - bool executePeriodChange(LightState_t lightState, LightInfo lightInfo) const ; + bool executePeriodChange(LightState_t lightState, LightInfo lightInfo) const; bool executeRecord(uint32_t current, uint32_t old); bool executeEvent() const; @@ -66,7 +66,7 @@ class GlobalEvent final : public Script { eventType = type; } - const std::string& getName() const { + const std::string &getName() const { return name; } void setName(std::string eventName) { @@ -96,4 +96,4 @@ class GlobalEvent final : public Script { uint32_t interval = 0; }; -#endif // SRC_LUA_GLOBAL_GLOBALEVENT_H_ +#endif // SRC_LUA_GLOBAL_GLOBALEVENT_H_ diff --git a/src/lua/lua_definitions.hpp b/src/lua/lua_definitions.hpp index 4a6788ee8c0..e9948be6758 100644 --- a/src/lua/lua_definitions.hpp +++ b/src/lua/lua_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_LUA_DEFINITIONS_HPP_ #define SRC_LUA_LUA_DEFINITIONS_HPP_ @@ -188,20 +188,20 @@ enum BugReportType_t : uint8_t { // Struct struct LuaVariant { - LuaVariantType_t type = VARIANT_NONE; - std::string text; - Position pos; - uint32_t number = 0; + LuaVariantType_t type = VARIANT_NONE; + std::string text; + Position pos; + uint32_t number = 0; }; struct LuaTimerEventDesc { - int32_t scriptId = -1; - int32_t function = -1; - std::list parameters; - uint32_t eventId = 0; + int32_t scriptId = -1; + int32_t function = -1; + std::list parameters; + uint32_t eventId = 0; - LuaTimerEventDesc() = default; - LuaTimerEventDesc(LuaTimerEventDesc&& other) = default; + LuaTimerEventDesc() = default; + LuaTimerEventDesc(LuaTimerEventDesc &&other) = default; }; -#endif // SRC_LUA_LUA_DEFINITIONS_HPP_ +#endif // SRC_LUA_LUA_DEFINITIONS_HPP_ diff --git a/src/lua/modules/modules.cpp b/src/lua/modules/modules.cpp index 1bd47e12eb4..0a977483558 100644 --- a/src/lua/modules/modules.cpp +++ b/src/lua/modules/modules.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -19,16 +19,16 @@ Modules::Modules() : } void Modules::clear(bool) { - //clear recvbyte list - for (auto& it : recvbyteList) { + // clear recvbyte list + for (auto &it : recvbyteList) { it.second.clearEvent(); } - //clear lua state + // clear lua state scriptInterface.reInitState(); } -LuaScriptInterface& Modules::getScriptInterface() { +LuaScriptInterface &Modules::getScriptInterface() { return scriptInterface; } @@ -36,15 +36,15 @@ std::string Modules::getScriptBaseName() const { return "modules"; } -Event_ptr Modules::getEvent(const std::string& nodeName) { +Event_ptr Modules::getEvent(const std::string &nodeName) { if (strcasecmp(nodeName.c_str(), "module") != 0) { return nullptr; } return Event_ptr(new Module(&scriptInterface)); } -bool Modules::registerEvent(Event_ptr event, const pugi::xml_node&) { - Module_ptr module {static_cast(event.release())}; +bool Modules::registerEvent(Event_ptr event, const pugi::xml_node &) { + Module_ptr module { static_cast(event.release()) }; if (module->getEventType() == MODULE_TYPE_NONE) { SPDLOG_ERROR("Trying to register event without type!"); return false; @@ -77,13 +77,13 @@ Module* Modules::getEventByRecvbyte(uint8_t recvbyte, bool force) { return nullptr; } -void Modules::executeOnRecvbyte(uint32_t playerId, NetworkMessage& msg, uint8_t byte) const { +void Modules::executeOnRecvbyte(uint32_t playerId, NetworkMessage &msg, uint8_t byte) const { Player* player = g_game().getPlayerByID(playerId); if (!player) { return; } - for (auto& it : recvbyteList) { + for (auto &it : recvbyteList) { Module module = it.second; if (module.getEventType() == MODULE_TYPE_RECVBYTE && module.getRecvbyte() == byte && player->canRunModule(module.getRecvbyte())) { player->setModuleDelay(module.getRecvbyte(), module.getDelay()); @@ -93,11 +93,10 @@ void Modules::executeOnRecvbyte(uint32_t playerId, NetworkMessage& msg, uint8_t } } - Module::Module(LuaScriptInterface* interface) : - Event(interface), type(MODULE_TYPE_NONE), loaded(false) {} + Event(interface), type(MODULE_TYPE_NONE), loaded(false) { } -bool Module::configureEvent(const pugi::xml_node& node) { +bool Module::configureEvent(const pugi::xml_node &node) { delay = 0; pugi::xml_attribute typeAttribute = node.attribute("type"); @@ -153,11 +152,10 @@ void Module::clearEvent() { loaded = false; } -void Module::executeOnRecvbyte(Player* player, NetworkMessage& msg) { - //onAdvance(player, skill, oldLevel, newLevel) +void Module::executeOnRecvbyte(Player* player, NetworkMessage &msg) { + // onAdvance(player, skill, oldLevel, newLevel) if (!scriptInterface->reserveScriptEnv()) { - SPDLOG_ERROR("Call stack overflow. Too many lua script calls being nested {}", - player->getName()); + SPDLOG_ERROR("Call stack overflow. Too many lua script calls being nested {}", player->getName()); return; } diff --git a/src/lua/modules/modules.h b/src/lua/modules/modules.h index 4bc6af71bc0..34d80b11ba8 100644 --- a/src/lua/modules/modules.h +++ b/src/lua/modules/modules.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_MODULES_MODULES_H_ #define SRC_LUA_MODULES_MODULES_H_ @@ -22,7 +22,7 @@ class Module final : public Event { public: explicit Module(LuaScriptInterface* interface); - bool configureEvent(const pugi::xml_node& node) final; + bool configureEvent(const pugi::xml_node &node) final; ModuleType_t getEventType() const { return type; @@ -34,8 +34,8 @@ class Module final : public Event { void clearEvent(); void copyEvent(Module* creatureEvent); - //scripting - void executeOnRecvbyte(Player* player, NetworkMessage& msg); + // scripting + void executeOnRecvbyte(Player* player, NetworkMessage &msg); // uint8_t getRecvbyte() { @@ -45,6 +45,7 @@ class Module final : public Event { int16_t getDelay() { return delay; } + protected: std::string getScriptEventName() const final; @@ -59,24 +60,24 @@ class Modules final : public BaseEvents { Modules(); // non-copyable - Modules(const Modules&) = delete; - Modules& operator=(const Modules&) = delete; + Modules(const Modules &) = delete; + Modules &operator=(const Modules &) = delete; - static Modules& getInstance() { + static Modules &getInstance() { // Guaranteed to be destroyed static Modules instance; // Instantiated on first use return instance; } - void executeOnRecvbyte(uint32_t playerId, NetworkMessage& msg, uint8_t byte) const; + void executeOnRecvbyte(uint32_t playerId, NetworkMessage &msg, uint8_t byte) const; Module* getEventByRecvbyte(uint8_t recvbyte, bool force); protected: - LuaScriptInterface& getScriptInterface() override; + LuaScriptInterface &getScriptInterface() override; std::string getScriptBaseName() const override; - Event_ptr getEvent(const std::string& nodeName) override; - bool registerEvent(Event_ptr event, const pugi::xml_node& node) override; + Event_ptr getEvent(const std::string &nodeName) override; + bool registerEvent(Event_ptr event, const pugi::xml_node &node) override; void clear(bool) override final; typedef std::map ModulesList; @@ -87,4 +88,4 @@ class Modules final : public BaseEvents { constexpr auto g_modules = &Modules::getInstance; -#endif // SRC_LUA_MODULES_MODULES_H_ +#endif // SRC_LUA_MODULES_MODULES_H_ diff --git a/src/lua/scripts/lua_environment.cpp b/src/lua/scripts/lua_environment.cpp index 5504ca3c74e..afefa38d38f 100644 --- a/src/lua/scripts/lua_environment.cpp +++ b/src/lua/scripts/lua_environment.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,7 +14,8 @@ #include "lua/functions/lua_functions_loader.hpp" #include "lua/scripts/script_environment.hpp" -LuaEnvironment::LuaEnvironment(): LuaScriptInterface("Main Interface") {} +LuaEnvironment::LuaEnvironment() : + LuaScriptInterface("Main Interface") { } LuaEnvironment::~LuaEnvironment() { if (!testInterface) { @@ -42,17 +43,17 @@ bool LuaEnvironment::closeState() { return false; } - for (const auto & combatEntry: combatIdMap) { + for (const auto &combatEntry : combatIdMap) { clearCombatObjects(combatEntry.first); } - for (const auto & areaEntry: areaIdMap) { + for (const auto &areaEntry : areaIdMap) { clearAreaObjects(areaEntry.first); } - for (auto & timerEntry: timerEvents) { + for (auto &timerEntry : timerEvents) { LuaTimerEventDesc timerEventDesc = std::move(timerEntry.second); - for (int32_t parameter: timerEventDesc.parameters) { + for (int32_t parameter : timerEventDesc.parameters) { luaL_unref(luaState, LUA_REGISTRYINDEX, parameter); } luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function); @@ -68,10 +69,10 @@ bool LuaEnvironment::closeState() { return true; } -LuaScriptInterface * LuaEnvironment::getTestInterface() { +LuaScriptInterface* LuaEnvironment::getTestInterface() { if (!testInterface) { testInterface = new LuaScriptInterface("Test Interface"); - testInterface -> initState(); + testInterface->initState(); } return testInterface; } @@ -84,14 +85,14 @@ std::shared_ptr LuaEnvironment::getCombatObject(uint32_t id) const { return it->second; } -std::shared_ptr LuaEnvironment::createCombatObject(LuaScriptInterface *interface) { +std::shared_ptr LuaEnvironment::createCombatObject(LuaScriptInterface* interface) { auto combat = std::make_shared(); combatMap[++lastCombatId] = combat; combatIdMap[interface].push_back(lastCombatId); return combat; } -void LuaEnvironment::clearCombatObjects(LuaScriptInterface *interface) { +void LuaEnvironment::clearCombatObjects(LuaScriptInterface* interface) { auto it = combatIdMap.find(interface); if (it == combatIdMap.end()) { return; @@ -101,34 +102,34 @@ void LuaEnvironment::clearCombatObjects(LuaScriptInterface *interface) { combatMap.clear(); } -AreaCombat * LuaEnvironment::getAreaObject(uint32_t id) const { +AreaCombat* LuaEnvironment::getAreaObject(uint32_t id) const { auto it = areaMap.find(id); if (it == areaMap.end()) { return nullptr; } - return it -> second; + return it->second; } -uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface * interface) { +uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface* interface) { areaMap[++lastAreaId] = new AreaCombat; areaIdMap[interface].push_back(lastAreaId); return lastAreaId; } -void LuaEnvironment::clearAreaObjects(LuaScriptInterface * interface) { +void LuaEnvironment::clearAreaObjects(LuaScriptInterface* interface) { auto it = areaIdMap.find(interface); if (it == areaIdMap.end()) { return; } - for (uint32_t id: it -> second) { + for (uint32_t id : it->second) { auto itt = areaMap.find(id); if (itt != areaMap.end()) { - delete itt -> second; + delete itt->second; areaMap.erase(itt); } } - it -> second.clear(); + it->second.clear(); } void LuaEnvironment::executeTimerEvent(uint32_t eventIndex) { @@ -137,32 +138,32 @@ void LuaEnvironment::executeTimerEvent(uint32_t eventIndex) { return; } - LuaTimerEventDesc timerEventDesc = std::move(it -> second); + LuaTimerEventDesc timerEventDesc = std::move(it->second); timerEvents.erase(it); // push function lua_rawgeti(luaState, LUA_REGISTRYINDEX, timerEventDesc.function); // push parameters - for (auto parameter: std::views::reverse(timerEventDesc.parameters)) { + for (auto parameter : std::views::reverse(timerEventDesc.parameters)) { lua_rawgeti(luaState, LUA_REGISTRYINDEX, parameter); } // call the function if (reserveScriptEnv()) { - ScriptEnvironment * env = getScriptEnv(); - env -> setTimerEvent(); - env -> setScriptId(timerEventDesc.scriptId, this); + ScriptEnvironment* env = getScriptEnv(); + env->setTimerEvent(); + env->setScriptId(timerEventDesc.scriptId, this); callFunction(timerEventDesc.parameters.size()); } else { SPDLOG_ERROR("[LuaEnvironment::executeTimerEvent - Lua file {}] " - "Call stack overflow. Too many lua script calls being nested", - getLoadingFile()); + "Call stack overflow. Too many lua script calls being nested", + getLoadingFile()); } // free resources luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function); - for (auto parameter: timerEventDesc.parameters) { + for (auto parameter : timerEventDesc.parameters) { luaL_unref(luaState, LUA_REGISTRYINDEX, parameter); } } diff --git a/src/lua/scripts/lua_environment.hpp b/src/lua/scripts/lua_environment.hpp index 7255b1beedb..90aa37062d0 100644 --- a/src/lua/scripts/lua_environment.hpp +++ b/src/lua/scripts/lua_environment.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_SCRIPTS_LUA_ENVIRONMENT_HPP_ #define SRC_LUA_SCRIPTS_LUA_ENVIRONMENT_HPP_ @@ -21,27 +21,27 @@ class Cylinder; class Game; class GlobalFunctions; -class LuaEnvironment: public LuaScriptInterface { +class LuaEnvironment : public LuaScriptInterface { public: LuaEnvironment(); ~LuaEnvironment(); // non-copyable LuaEnvironment(const LuaEnvironment &) = delete; - LuaEnvironment & operator = (const LuaEnvironment &) = delete; + LuaEnvironment &operator=(const LuaEnvironment &) = delete; bool initState() override; bool reInitState(); bool closeState() override; - LuaScriptInterface * getTestInterface(); + LuaScriptInterface* getTestInterface(); std::shared_ptr getCombatObject(uint32_t id) const; - std::shared_ptr createCombatObject(LuaScriptInterface *interface); - void clearCombatObjects(LuaScriptInterface *interface); + std::shared_ptr createCombatObject(LuaScriptInterface* interface); + void clearCombatObjects(LuaScriptInterface* interface); - template - std::shared_ptr createWeaponObject(LuaScriptInterface *interface) { + template + std::shared_ptr createWeaponObject(LuaScriptInterface* interface) { auto weapon = std::make_shared(interface); int weaponId = ++lastWeaponId; weaponMap[weaponId] = weapon; @@ -49,7 +49,7 @@ class LuaEnvironment: public LuaScriptInterface { return weapon; } - template + template std::shared_ptr getWeaponObject(uint32_t id) const { auto it = weaponMap.find(id); if (it == weaponMap.end()) { @@ -58,7 +58,7 @@ class LuaEnvironment: public LuaScriptInterface { return it->second; } - void clearWeaponObjects(LuaScriptInterface *interface) { + void clearWeaponObjects(LuaScriptInterface* interface) { auto it = weaponIdMap.find(interface); if (it == weaponIdMap.end()) { return; @@ -68,9 +68,9 @@ class LuaEnvironment: public LuaScriptInterface { weaponMap.clear(); } - AreaCombat * getAreaObject(uint32_t id) const; - uint32_t createAreaObject(LuaScriptInterface * interface); - void clearAreaObjects(LuaScriptInterface * interface); + AreaCombat* getAreaObject(uint32_t id) const; + uint32_t createAreaObject(LuaScriptInterface* interface); + void clearAreaObjects(LuaScriptInterface* interface); private: void executeTimerEvent(uint32_t eventIndex); @@ -90,7 +90,7 @@ class LuaEnvironment: public LuaScriptInterface { phmap::flat_hash_map> weaponIdMap; uint32_t lastWeaponId = 0; - LuaScriptInterface *testInterface = nullptr; + LuaScriptInterface* testInterface = nullptr; friend class LuaScriptInterface; friend class GlobalFunctions; @@ -99,4 +99,4 @@ class LuaEnvironment: public LuaScriptInterface { inline LuaEnvironment g_luaEnvironment; -#endif // SRC_LUA_SCRIPTS_LUA_ENVIRONMENT_HPP_ +#endif // SRC_LUA_SCRIPTS_LUA_ENVIRONMENT_HPP_ diff --git a/src/lua/scripts/luajit_sync.hpp b/src/lua/scripts/luajit_sync.hpp index 505dbb6eae7..2a0aec4ab35 100644 --- a/src/lua/scripts/luajit_sync.hpp +++ b/src/lua/scripts/luajit_sync.hpp @@ -5,20 +5,20 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_SCRIPTS_LUAJIT_SYNC_HPP_ #define SRC_LUA_SCRIPTS_LUAJIT_SYNC_HPP_ #if LUA_VERSION_NUM >= 502 -#ifndef LUA_COMPAT_ALL -#ifndef LUA_COMPAT_MODULE -#define luaL_register(L, libname, l)(luaL_newlib(L, l), + #ifndef LUA_COMPAT_ALL + #ifndef LUA_COMPAT_MODULE + #define luaL_register(L, libname, l)(luaL_newlib(L, l), lua_pushvalue(L, -1), lua_setglobal(L, libname)) -#endif -#undef lua_equal -#define lua_equal(L, i1, i2) lua_compare(L, (i1), (i2), LUA_OPEQ) -#endif + #endif + #undef lua_equal + #define lua_equal(L, i1, i2) lua_compare(L, (i1), (i2), LUA_OPEQ) + #endif #endif -#endif // SRC_LUA_SCRIPTS_LUAJIT_SYNC_HPP_ +#endif // SRC_LUA_SCRIPTS_LUAJIT_SYNC_HPP_ diff --git a/src/lua/scripts/luascript.cpp b/src/lua/scripts/luascript.cpp index beca412c0fa..a198905e476 100644 --- a/src/lua/scripts/luascript.cpp +++ b/src/lua/scripts/luascript.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -14,12 +14,13 @@ ScriptEnvironment::DBResultMap ScriptEnvironment::tempResults; uint32_t ScriptEnvironment::lastResultId = 0; -std::multimap ScriptEnvironment::tempItems; +std::multimap ScriptEnvironment::tempItems; ScriptEnvironment LuaFunctionsLoader::scriptEnv[16]; int32_t LuaFunctionsLoader::scriptEnvIndex = -1; -LuaScriptInterface::LuaScriptInterface(std::string initInterfaceName) : interfaceName(std::move(initInterfaceName)) { +LuaScriptInterface::LuaScriptInterface(std::string initInterfaceName) : + interfaceName(std::move(initInterfaceName)) { if (!g_luaEnvironment.getLuaState()) { g_luaEnvironment.initState(); } @@ -38,15 +39,15 @@ bool LuaScriptInterface::reInitState() { } /// Same as lua_pcall, but adds stack trace to error strings in called function. -int32_t LuaScriptInterface::loadFile(const std::string& file, const std::string &scriptName) { - //loads file as a chunk at stack top +int32_t LuaScriptInterface::loadFile(const std::string &file, const std::string &scriptName) { + // loads file as a chunk at stack top int ret = luaL_loadfile(luaState, file.c_str()); if (ret != 0) { lastLuaError = popString(luaState); return -1; } - //check that it is loaded as a function + // check that it is loaded as a function if (!isFunction(luaState, -1)) { return -1; } @@ -60,9 +61,9 @@ int32_t LuaScriptInterface::loadFile(const std::string& file, const std::string ScriptEnvironment* env = getScriptEnv(); env->setScriptId(EVENT_ID_LOADING, this); - //env->setNpc(npc); + // env->setNpc(npc); - //execute it + // execute it ret = protectedCall(luaState, 0, 0); if (ret != 0) { reportError(nullptr, popString(luaState)); @@ -74,27 +75,27 @@ int32_t LuaScriptInterface::loadFile(const std::string& file, const std::string return 0; } -int32_t LuaScriptInterface::getEvent(const std::string& eventName) { - //get our events table +int32_t LuaScriptInterface::getEvent(const std::string &eventName) { + // get our events table lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef); if (!isTable(luaState, -1)) { lua_pop(luaState, 1); return -1; } - //get current event function pointer + // get current event function pointer lua_getglobal(luaState, eventName.c_str()); if (!isFunction(luaState, -1)) { lua_pop(luaState, 2); return -1; } - //save in our events table + // save in our events table lua_pushvalue(luaState, -1); lua_rawseti(luaState, -3, runningEventId); lua_pop(luaState, 2); - //reset global value of this event + // reset global value of this event lua_pushnil(luaState); lua_setglobal(luaState, eventName.c_str()); @@ -103,19 +104,19 @@ int32_t LuaScriptInterface::getEvent(const std::string& eventName) { } int32_t LuaScriptInterface::getEvent() { - //check if function is on the stack + // check if function is on the stack if (!isFunction(luaState, -1)) { return -1; } - //get our events table + // get our events table lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef); if (!isTable(luaState, -1)) { lua_pop(luaState, 1); return -1; } - //save in our events table + // save in our events table lua_pushvalue(luaState, -2); lua_rawseti(luaState, -2, runningEventId); lua_pop(luaState, 2); @@ -124,15 +125,15 @@ int32_t LuaScriptInterface::getEvent() { return runningEventId++; } -int32_t LuaScriptInterface::getMetaEvent(const std::string& globalName, const std::string& eventName) { - //get our events table +int32_t LuaScriptInterface::getMetaEvent(const std::string &globalName, const std::string &eventName) { + // get our events table lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef); if (!isTable(luaState, -1)) { lua_pop(luaState, 1); return -1; } - //get current event function pointer + // get current event function pointer lua_getglobal(luaState, globalName.c_str()); lua_getfield(luaState, -1, eventName.c_str()); if (!isFunction(luaState, -1)) { @@ -140,12 +141,12 @@ int32_t LuaScriptInterface::getMetaEvent(const std::string& globalName, const st return -1; } - //save in our events table + // save in our events table lua_pushvalue(luaState, -1); lua_rawseti(luaState, -4, runningEventId); lua_pop(luaState, 1); - //reset global value of this event + // reset global value of this event lua_pushnil(luaState); lua_setfield(luaState, -2, eventName.c_str()); lua_pop(luaState, 2); @@ -154,20 +155,20 @@ int32_t LuaScriptInterface::getMetaEvent(const std::string& globalName, const st return runningEventId++; } -const std::string& LuaScriptInterface::getFileById(int32_t scriptId) { +const std::string &LuaScriptInterface::getFileById(int32_t scriptId) { if (scriptId == EVENT_ID_LOADING) { return loadingFile; } auto it = cacheFiles.find(scriptId); if (it == cacheFiles.end()) { - static const std::string& unk = "(Unknown scriptfile)"; + static const std::string &unk = "(Unknown scriptfile)"; return unk; } return it->second; } -std::string LuaScriptInterface::getStackTrace(const std::string& error_desc) { +std::string LuaScriptInterface::getStackTrace(const std::string &error_desc) { lua_getglobal(luaState, "debug"); if (!isTable(luaState, -1)) { lua_pop(luaState, 1); diff --git a/src/lua/scripts/luascript.h b/src/lua/scripts/luascript.h index bb2aafc00cd..7656a1ffef1 100644 --- a/src/lua/scripts/luascript.h +++ b/src/lua/scripts/luascript.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_SCRIPTS_LUASCRIPT_H_ #define SRC_LUA_SCRIPTS_LUASCRIPT_H_ @@ -19,30 +19,30 @@ class LuaScriptInterface : public LuaFunctionsLoader { virtual ~LuaScriptInterface(); // non-copyable - LuaScriptInterface(const LuaScriptInterface&) = delete; - LuaScriptInterface& operator=(const LuaScriptInterface&) = delete; + LuaScriptInterface(const LuaScriptInterface &) = delete; + LuaScriptInterface &operator=(const LuaScriptInterface &) = delete; virtual bool initState(); bool reInitState(); - int32_t loadFile(const std::string& file, const std::string &scriptName); + int32_t loadFile(const std::string &file, const std::string &scriptName); - const std::string& getFileById(int32_t scriptId); - int32_t getEvent(const std::string& eventName); + const std::string &getFileById(int32_t scriptId); + int32_t getEvent(const std::string &eventName); int32_t getEvent(); - int32_t getMetaEvent(const std::string& globalName, const std::string& eventName); + int32_t getMetaEvent(const std::string &globalName, const std::string &eventName); - const std::string& getInterfaceName() const { + const std::string &getInterfaceName() const { return interfaceName; } - const std::string& getLastLuaError() const { + const std::string &getLastLuaError() const { return lastLuaError; } - const std::string& getLoadingFile() const { + const std::string &getLoadingFile() const { return loadingFile; } - const std::string& getLoadingScriptName() const { + const std::string &getLoadingScriptName() const { // If scripty name is empty, return warning informing if (loadedScriptName.empty()) { SPDLOG_WARN("[LuaScriptInterface::getLoadingScriptName] - Script name is empty"); @@ -63,7 +63,7 @@ class LuaScriptInterface : public LuaFunctionsLoader { bool callFunction(int params); void callVoidFunction(int params); - std::string getStackTrace(const std::string& error_desc); + std::string getStackTrace(const std::string &error_desc); protected: virtual bool closeState(); @@ -79,4 +79,4 @@ class LuaScriptInterface : public LuaFunctionsLoader { std::string loadedScriptName; }; -#endif // SRC_LUA_SCRIPTS_LUASCRIPT_H_ +#endif // SRC_LUA_SCRIPTS_LUASCRIPT_H_ diff --git a/src/lua/scripts/script_environment.cpp b/src/lua/scripts/script_environment.cpp index ffeface5a31..e287f9dcf81 100644 --- a/src/lua/scripts/script_environment.cpp +++ b/src/lua/scripts/script_environment.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -33,51 +33,51 @@ void ScriptEnvironment::resetEnv() { auto pair = tempItems.equal_range(this); auto it = pair.first; while (it != pair.second) { - Item * item = it -> second; - if (item -> getParent() == VirtualCylinder::virtualCylinder) { + Item* item = it->second; + if (item->getParent() == VirtualCylinder::virtualCylinder) { g_game().ReleaseItem(item); } it = tempItems.erase(it); } } -bool ScriptEnvironment::setCallbackId(int32_t newCallbackId, LuaScriptInterface * scriptInterface) { - if (this -> callbackId != 0) { +bool ScriptEnvironment::setCallbackId(int32_t newCallbackId, LuaScriptInterface* scriptInterface) { + if (this->callbackId != 0) { // nested callbacks are not allowed if (interface) { - interface -> reportErrorFunc("Nested callbacks!"); + interface->reportErrorFunc("Nested callbacks!"); } return false; } - this -> callbackId = newCallbackId; + this->callbackId = newCallbackId; interface = scriptInterface; return true; } -void ScriptEnvironment::getEventInfo(int32_t & retScriptId, LuaScriptInterface * & retScriptInterface, int32_t & retCallbackId, bool & retTimerEvent) const { - retScriptId = this -> scriptId; +void ScriptEnvironment::getEventInfo(int32_t &retScriptId, LuaScriptInterface*&retScriptInterface, int32_t &retCallbackId, bool &retTimerEvent) const { + retScriptId = this->scriptId; retScriptInterface = interface; - retCallbackId = this -> callbackId; - retTimerEvent = this -> timerEvent; + retCallbackId = this->callbackId; + retTimerEvent = this->timerEvent; } -uint32_t ScriptEnvironment::addThing(Thing * thing) { - if (!thing || thing -> isRemoved()) { +uint32_t ScriptEnvironment::addThing(Thing* thing) { + if (!thing || thing->isRemoved()) { return 0; } - Creature * creature = thing -> getCreature(); + Creature* creature = thing->getCreature(); if (creature) { - return creature -> getID(); + return creature->getID(); } - Item * item = thing -> getItem(); - if (item && item -> hasAttribute(ItemAttribute_t::UNIQUEID)) { + Item* item = thing->getItem(); + if (item && item->hasAttribute(ItemAttribute_t::UNIQUEID)) { return item->getAttribute(ItemAttribute_t::UNIQUEID); } - for (const auto & it: localMap) { + for (const auto &it : localMap) { if (it.second == item) { return it.first; } @@ -87,21 +87,21 @@ uint32_t ScriptEnvironment::addThing(Thing * thing) { return lastUID; } -void ScriptEnvironment::insertItem(uint32_t uid, Item * item) { +void ScriptEnvironment::insertItem(uint32_t uid, Item* item) { auto result = localMap.emplace(uid, item); if (!result.second) { SPDLOG_ERROR("Thing uid already taken: {}", uid); } } -Thing * ScriptEnvironment::getThingByUID(uint32_t uid) { +Thing* ScriptEnvironment::getThingByUID(uint32_t uid) { if (uid >= 0x10000000) { return g_game().getCreatureByID(uid); } - if (uid <= std::numeric_limits < uint16_t > ::max()) { - Item * item = g_game().getUniqueItem(static_cast(uid)); - if (item && !item -> isRemoved()) { + if (uid <= std::numeric_limits::max()) { + Item* item = g_game().getUniqueItem(static_cast(uid)); + if (item && !item->isRemoved()) { return item; } return nullptr; @@ -109,32 +109,32 @@ Thing * ScriptEnvironment::getThingByUID(uint32_t uid) { auto it = localMap.find(uid); if (it != localMap.end()) { - Item * item = it -> second; - if (!item -> isRemoved()) { + Item* item = it->second; + if (!item->isRemoved()) { return item; } } return nullptr; } -Item * ScriptEnvironment::getItemByUID(uint32_t uid) { - Thing * thing = getThingByUID(uid); +Item* ScriptEnvironment::getItemByUID(uint32_t uid) { + Thing* thing = getThingByUID(uid); if (!thing) { return nullptr; } - return thing -> getItem(); + return thing->getItem(); } -Container * ScriptEnvironment::getContainerByUID(uint32_t uid) { - Item * item = getItemByUID(uid); +Container* ScriptEnvironment::getContainerByUID(uint32_t uid) { + Item* item = getItemByUID(uid); if (!item) { return nullptr; } - return item -> getContainer(); + return item->getContainer(); } void ScriptEnvironment::removeItemByUID(uint32_t uid) { - if (uid <= std::numeric_limits < uint16_t > ::max()) { + if (uid <= std::numeric_limits::max()) { g_game().removeUniqueItem(static_cast(uid)); return; } @@ -145,13 +145,13 @@ void ScriptEnvironment::removeItemByUID(uint32_t uid) { } } -void ScriptEnvironment::addTempItem(Item * item) { +void ScriptEnvironment::addTempItem(Item* item) { tempItems.emplace(this, item); } -void ScriptEnvironment::removeTempItem(Item * item) { +void ScriptEnvironment::removeTempItem(Item* item) { for (auto it = tempItems.begin(), end = tempItems.end(); it != end; ++it) { - if (it -> second == item) { + if (it->second == item) { tempItems.erase(it); break; } @@ -178,5 +178,5 @@ DBResult_ptr ScriptEnvironment::getResultByID(uint32_t id) { if (it == tempResults.end()) { return nullptr; } - return it -> second; + return it->second; } diff --git a/src/lua/scripts/script_environment.hpp b/src/lua/scripts/script_environment.hpp index 7d49f5ec833..c8fe1b2692f 100644 --- a/src/lua/scripts/script_environment.hpp +++ b/src/lua/scripts/script_environment.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_SCRIPTS_SCRIPT_ENVIRONMENT_HPP_ #define SRC_LUA_SCRIPTS_SCRIPT_ENVIRONMENT_HPP_ @@ -26,70 +26,70 @@ class Game; class ScriptEnvironment { public: ScriptEnvironment(); - virtual~ScriptEnvironment(); + virtual ~ScriptEnvironment(); // non-copyable ScriptEnvironment(const ScriptEnvironment &) = delete; - ScriptEnvironment & operator = (const ScriptEnvironment &) = delete; + ScriptEnvironment &operator=(const ScriptEnvironment &) = delete; void resetEnv(); - void setScriptId(int32_t newScriptId, LuaScriptInterface * newScriptInterface) { - this -> scriptId = newScriptId; - this -> interface = newScriptInterface; + void setScriptId(int32_t newScriptId, LuaScriptInterface* newScriptInterface) { + this->scriptId = newScriptId; + this->interface = newScriptInterface; } - bool setCallbackId(int32_t callbackId, LuaScriptInterface * scriptInterface); + bool setCallbackId(int32_t callbackId, LuaScriptInterface* scriptInterface); int32_t getScriptId() const { - return scriptId; + return scriptId; } - LuaScriptInterface * getScriptInterface() { - return interface; + LuaScriptInterface* getScriptInterface() { + return interface; } void setTimerEvent() { - timerEvent = true; + timerEvent = true; } - void getEventInfo(int32_t & scriptId, LuaScriptInterface * & scriptInterface, int32_t & callbackId, bool & timerEvent) const; + void getEventInfo(int32_t &scriptId, LuaScriptInterface*&scriptInterface, int32_t &callbackId, bool &timerEvent) const; - void addTempItem(Item * item); - static void removeTempItem(Item * item); - uint32_t addThing(Thing * thing); - void insertItem(uint32_t uid, Item * item); + void addTempItem(Item* item); + static void removeTempItem(Item* item); + uint32_t addThing(Thing* thing); + void insertItem(uint32_t uid, Item* item); static DBResult_ptr getResultByID(uint32_t id); static uint32_t addResult(DBResult_ptr res); static bool removeResult(uint32_t id); - void setNpc(Npc * npc) { - curNpc = npc; + void setNpc(Npc* npc) { + curNpc = npc; } - Npc * getNpc() const { - return curNpc; + Npc* getNpc() const { + return curNpc; } - Thing * getThingByUID(uint32_t uid); - Item * getItemByUID(uint32_t uid); - Container * getContainerByUID(uint32_t uid); + Thing* getThingByUID(uint32_t uid); + Item* getItemByUID(uint32_t uid); + Container* getContainerByUID(uint32_t uid); void removeItemByUID(uint32_t uid); private: - using VariantVector = std::vector ; - using StorageMap = std::map < uint32_t, int32_t >; - using DBResultMap = std::map < uint32_t, DBResult_ptr>; + using VariantVector = std::vector; + using StorageMap = std::map; + using DBResultMap = std::map; - LuaScriptInterface * interface; + LuaScriptInterface* interface; // for npc scripts - Npc * curNpc = nullptr; + Npc* curNpc = nullptr; // temporary item list - static std::multimap < ScriptEnvironment * , Item * > tempItems; + static std::multimap tempItems; // local item map - phmap::flat_hash_map < uint32_t, Item * > localMap; - uint32_t lastUID = std::numeric_limits < uint16_t > ::max(); + phmap::flat_hash_map localMap; + uint32_t lastUID = std::numeric_limits::max(); // script file id int32_t scriptId; @@ -101,4 +101,4 @@ class ScriptEnvironment { static DBResultMap tempResults; }; -#endif // SRC_LUA_SCRIPTS_SCRIPT_ENVIRONMENT_HPP_ +#endif // SRC_LUA_SCRIPTS_SCRIPT_ENVIRONMENT_HPP_ diff --git a/src/lua/scripts/scripts.cpp b/src/lua/scripts/scripts.cpp index a25cecda994..0a6e3e2bd73 100644 --- a/src/lua/scripts/scripts.cpp +++ b/src/lua/scripts/scripts.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -35,19 +35,19 @@ void Scripts::clearAllScripts() const { g_weapons().clear(); } -bool Scripts::loadEventSchedulerScripts(const std::string& fileName) { +bool Scripts::loadEventSchedulerScripts(const std::string &fileName) { auto coreFolder = g_configManager().getString(CORE_DIRECTORY); const auto dir = std::filesystem::current_path() / coreFolder / "events" / "scripts" / "scheduler"; - if(!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) { + if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) { SPDLOG_WARN("{} - Can not load folder 'scheduler' on {}/events/scripts'", __FUNCTION__, coreFolder); return false; } std::filesystem::recursive_directory_iterator endit; - for(std::filesystem::recursive_directory_iterator it(dir); it != endit; ++it) { - if(std::filesystem::is_regular_file(*it) && it->path().extension() == ".lua") { + for (std::filesystem::recursive_directory_iterator it(dir); it != endit; ++it) { + if (std::filesystem::is_regular_file(*it) && it->path().extension() == ".lua") { if (it->path().filename().string() == fileName) { - if(scriptInterface.loadFile(it->path().string(), it->path().filename().string()) == -1) { + if (scriptInterface.loadFile(it->path().string(), it->path().filename().string()) == -1) { SPDLOG_ERROR(it->path().string()); SPDLOG_ERROR(scriptInterface.getLastLuaError()); continue; @@ -60,14 +60,12 @@ bool Scripts::loadEventSchedulerScripts(const std::string& fileName) { return false; } -bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) -{ +bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) { // Build the full path of the folder that should be loaded auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); const auto dir = std::filesystem::current_path() / datapackFolder / folderName; // Checks if the folder exists and is really a folder - if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) - { + if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) { SPDLOG_ERROR("Can not load folder {}", folderName); return false; } @@ -75,10 +73,9 @@ bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) // Declare a string variable to store the last directory std::string lastDirectory; // Recursive iterate through all entries in the directory - for (const auto &entry: std::filesystem::recursive_directory_iterator(dir)) - { + for (const auto &entry : std::filesystem::recursive_directory_iterator(dir)) { // Get the filename of the entry as a string - const auto& realPath = entry.path(); + const auto &realPath = entry.path(); std::string fileFolder = realPath.parent_path().filename().string(); // Script folder, example: "actions" std::string scriptFolder = realPath.parent_path().string(); @@ -87,16 +84,14 @@ bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) std::string_view scriptFolderView(scriptFolder); // Filename, example: "demon.lua" std::string file(realPath.filename().string()); - if (!std::filesystem::is_regular_file(entry) || realPath.extension() != ".lua") - { + if (!std::filesystem::is_regular_file(entry) || realPath.extension() != ".lua") { // Skip this entry if it is not a regular file or does not have a .lua extension continue; } // Check if file start with "#" if (std::string disable("#"); - file.front() == disable.front()) - { + file.front() == disable.front()) { // Send log of disabled script if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS)) { SPDLOG_INFO("[script]: {} [disabled]", realPath.filename().string()); @@ -106,14 +101,11 @@ bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) } // If the file is a library file or if the file's parent directory is not "lib" or "events" - if (isLib || (fileFolderView != "lib" && fileFolderView != "events")) - { + if (isLib || (fileFolderView != "lib" && fileFolderView != "events")) { // If console logs are enabled and the file is not a library file - if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS)) - { - // If the current directory is different from the last directory that was logged - if (lastDirectory.empty() || lastDirectory != scriptFolderView) - { + if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS)) { + // If the current directory is different from the last directory that was logged + if (lastDirectory.empty() || lastDirectory != scriptFolderView) { // Update the last directory variable and log the directory name SPDLOG_INFO("Loading folder: [{}]", realPath.parent_path().filename().string()); } @@ -121,8 +113,7 @@ bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) } // If the function 'loadFile' returns -1, then there was an error loading the file - if (scriptInterface.loadFile(realPath.string(), realPath.filename().string()) == -1) - { + if (scriptInterface.loadFile(realPath.string(), realPath.filename().string()) == -1) { // Log the error and the file path, and skip to the next iteration of the loop. SPDLOG_ERROR(realPath.string()); SPDLOG_ERROR(scriptInterface.getLastLuaError()); diff --git a/src/lua/scripts/scripts.h b/src/lua/scripts/scripts.h index 65c1f40c03f..0606b3be46a 100644 --- a/src/lua/scripts/scripts.h +++ b/src/lua/scripts/scripts.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_LUA_SCRIPTS_SCRIPTS_H_ #define SRC_LUA_SCRIPTS_SCRIPTS_H_ @@ -18,10 +18,10 @@ class Scripts { ~Scripts(); // non-copyable - Scripts(const Scripts&) = delete; - Scripts& operator=(const Scripts&) = delete; + Scripts(const Scripts &) = delete; + Scripts &operator=(const Scripts &) = delete; - static Scripts& getInstance() { + static Scripts &getInstance() { // Guaranteed to be destroyed static Scripts instance; // Instantiated on first use @@ -30,16 +30,16 @@ class Scripts { void clearAllScripts() const; - bool loadEventSchedulerScripts(const std::string& fileName); + bool loadEventSchedulerScripts(const std::string &fileName); bool loadScripts(std::string folderName, bool isLib, bool reload); - LuaScriptInterface& getScriptInterface() { + LuaScriptInterface &getScriptInterface() { return scriptInterface; } /** * @brief Get the Script Id object * * @return int32_t - */ + */ int32_t getScriptId() const { return scriptId; } @@ -59,8 +59,9 @@ class Script { * copy-initialization. * * @param interface Lua Script Interface - */ - explicit Script(LuaScriptInterface* interface) : scriptInterface(interface) {} + */ + explicit Script(LuaScriptInterface* interface) : + scriptInterface(interface) { } virtual ~Script() = default; /** @@ -68,7 +69,7 @@ class Script { * * @return true * @return false - */ + */ bool isLoadedCallback() const { return loadedCallback; } @@ -94,34 +95,33 @@ class Script { return true; } + // NOTE: Pure virtual method ( = 0) that must be implemented in derived classes + // Script type (Action, CreatureEvent, GlobalEvent, MoveEvent, Spell, Weapon) + virtual std::string getScriptTypeName() const = 0; - // NOTE: Pure virtual method ( = 0) that must be implemented in derived classes - // Script type (Action, CreatureEvent, GlobalEvent, MoveEvent, Spell, Weapon) - virtual std::string getScriptTypeName() const = 0; + // Method to access the scriptInterface in derived classes + virtual LuaScriptInterface* getScriptInterface() const { + return scriptInterface; + } - // Method to access the scriptInterface in derived classes - virtual LuaScriptInterface* getScriptInterface() const { - return scriptInterface; - } - - virtual void setScriptInterface(LuaScriptInterface* newInterface) { - scriptInterface = newInterface; - } + virtual void setScriptInterface(LuaScriptInterface* newInterface) { + scriptInterface = newInterface; + } - // Method to access the scriptId in derived classes - virtual int32_t getScriptId() const { - return scriptId; - } - virtual void setScriptId(int32_t newScriptId) { - scriptId = newScriptId; - } + // Method to access the scriptId in derived classes + virtual int32_t getScriptId() const { + return scriptId; + } + virtual void setScriptId(int32_t newScriptId) { + scriptId = newScriptId; + } private: - // If script is loaded callback - bool loadedCallback = false; + // If script is loaded callback + bool loadedCallback = false; - int32_t scriptId = 0; - LuaScriptInterface* scriptInterface = nullptr; + int32_t scriptId = 0; + LuaScriptInterface* scriptInterface = nullptr; }; -#endif // SRC_LUA_SCRIPTS_SCRIPTS_H_ +#endif // SRC_LUA_SCRIPTS_SCRIPTS_H_ diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index 6b135b49f6b..5372c1a99a3 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -15,18 +15,17 @@ #include "game/game.h" #include "items/bed.h" -House::House(uint32_t houseId) : id(houseId) {} +House::House(uint32_t houseId) : + id(houseId) { } -void House::addTile(HouseTile* tile) -{ +void House::addTile(HouseTile* tile) { tile->setFlag(TILESTATE_PROTECTIONZONE); houseTiles.push_back(tile); } -void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* player/* = nullptr*/) -{ +void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, Player* player /* = nullptr*/) { if (updateDatabase && owner != guid) { - Database& db = Database::getInstance(); + Database &db = Database::getInstance(); std::ostringstream query; query << "UPDATE `houses` SET `owner` = " << guid << ", `bid` = 0, `bid_end` = 0, `last_bid` = 0, `highest_bidder` = 0 WHERE `id` = " << id; @@ -62,7 +61,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play } } - //clean access lists + // clean access lists owner = 0; ownerAccountId = 0; setAccessList(SUBOWNER_LIST, ""); @@ -75,15 +74,15 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD)); time_t currentTime = time(nullptr); if (strRentPeriod == "yearly") { - currentTime += 24 * 60 * 60 * 365; + currentTime += 24 * 60 * 60 * 365; } else if (strRentPeriod == "monthly") { - currentTime += 24 * 60 * 60 * 30; + currentTime += 24 * 60 * 60 * 30; } else if (strRentPeriod == "weekly") { - currentTime += 24 * 60 * 60 * 7; + currentTime += 24 * 60 * 60 * 7; } else if (strRentPeriod == "daily") { - currentTime += 24 * 60 * 60; + currentTime += 24 * 60 * 60; } else { - currentTime = 0; + currentTime = 0; } paidUntil = currentTime; @@ -93,7 +92,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play if (guid != 0) { - Database& db = Database::getInstance(); + Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `name`, `account_id` FROM `players` WHERE `id` = " << guid; DBResult_ptr result = db.storeQuery(query.str()); @@ -105,15 +104,14 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play if (!name.empty()) { owner = guid; ownerName = name; - ownerAccountId = result->getNumber("account_id"); + ownerAccountId = result->getNumber("account_id"); } } updateDoorDescription(); } -void House::updateDoorDescription() const -{ +void House::updateDoorDescription() const { std::ostringstream ss; if (owner != 0) { ss << "It belongs to house '" << houseName << "'. " << ownerName << " owns this house."; @@ -126,13 +124,12 @@ void House::updateDoorDescription() const } } - for (const auto& it : doorList) { + for (const auto &it : doorList) { it->setAttribute(ItemAttribute_t::DESCRIPTION, ss.str()); } } -AccessHouseLevel_t House::getHouseAccessLevel(const Player* player) -{ +AccessHouseLevel_t House::getHouseAccessLevel(const Player* player) { if (!player) { return HOUSE_OWNER; } @@ -162,8 +159,7 @@ AccessHouseLevel_t House::getHouseAccessLevel(const Player* player) return HOUSE_NOT_INVITED; } -bool House::kickPlayer(Player* player, Player* target) -{ +bool House::kickPlayer(Player* player, Player* target) { if (!target) { return false; } @@ -185,8 +181,7 @@ bool House::kickPlayer(Player* player, Player* target) return true; } -void House::setAccessList(uint32_t listId, const std::string& textlist) -{ +void House::setAccessList(uint32_t listId, const std::string &textlist) { if (listId == GUEST_LIST) { guestList.parseList(textlist); } else if (listId == SUBOWNER_LIST) { @@ -201,7 +196,7 @@ void House::setAccessList(uint32_t listId, const std::string& textlist) return; } - //kick uninvited players + // kick uninvited players for (HouseTile* tile : houseTiles) { if (CreatureVector* creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { @@ -214,8 +209,7 @@ void House::setAccessList(uint32_t listId, const std::string& textlist) } } -bool House::transferToDepot() const -{ +bool House::transferToDepot() const { if (townId == 0 || owner == 0) { return false; } @@ -235,8 +229,7 @@ bool House::transferToDepot() const return true; } -bool House::transferToDepot(Player* player) const -{ +bool House::transferToDepot(Player* player) const { if (townId == 0 || owner == 0) { return false; } @@ -261,15 +254,15 @@ bool House::transferToDepot(Player* player) const return true; } -void House::handleWrapableItem(ItemList &moveItemList, Item *item) const { +void House::handleWrapableItem(ItemList &moveItemList, Item* item) const { if (item->isWrapContainer()) { handleContainer(moveItemList, item); } - Item *newItem = g_game().wrapItem(item); + Item* newItem = g_game().wrapItem(item); moveItemList.push_back(newItem); } -void House::handleContainer(ItemList &moveItemList, Item *item) const { +void House::handleContainer(ItemList &moveItemList, Item* item) const { if (const auto container = item->getContainer()) { for (Item* containerItem : container->getItemList()) { moveItemList.push_back(containerItem); @@ -277,8 +270,7 @@ void House::handleContainer(ItemList &moveItemList, Item *item) const { } } -bool House::getAccessList(uint32_t listId, std::string& list) const -{ +bool House::getAccessList(uint32_t listId, std::string &list) const { if (listId == GUEST_LIST) { guestList.getList(list); return true; @@ -295,21 +287,18 @@ bool House::getAccessList(uint32_t listId, std::string& list) const return door->getAccessList(list); } -bool House::isInvited(const Player* player) -{ +bool House::isInvited(const Player* player) { return getHouseAccessLevel(player) != HOUSE_NOT_INVITED; } -void House::addDoor(Door* door) -{ +void House::addDoor(Door* door) { door->incrementReferenceCounter(); doorList.push_back(door); door->setHouse(this); updateDoorDescription(); } -void House::removeDoor(Door* door) -{ +void House::removeDoor(Door* door) { auto it = std::find(doorList.begin(), doorList.end(), door); if (it != doorList.end()) { door->decrementReferenceCounter(); @@ -317,14 +306,12 @@ void House::removeDoor(Door* door) } } -void House::addBed(BedItem* bed) -{ +void House::addBed(BedItem* bed) { bedsList.push_back(bed); bed->setHouse(this); } -Door* House::getDoorByNumber(uint32_t doorId) const -{ +Door* House::getDoorByNumber(uint32_t doorId) const { for (Door* door : doorList) { if (door->getDoorId() == doorId) { return door; @@ -333,8 +320,7 @@ Door* House::getDoorByNumber(uint32_t doorId) const return nullptr; } -Door* House::getDoorByPosition(const Position& pos) -{ +Door* House::getDoorByPosition(const Position &pos) { for (Door* door : doorList) { if (door->getPosition() == pos) { return door; @@ -343,8 +329,7 @@ Door* House::getDoorByPosition(const Position& pos) return nullptr; } -bool House::canEditAccessList(uint32_t listId, const Player* player) -{ +bool House::canEditAccessList(uint32_t listId, const Player* player) { switch (getHouseAccessLevel(player)) { case HOUSE_OWNER: return true; @@ -357,8 +342,7 @@ bool House::canEditAccessList(uint32_t listId, const Player* player) } } -HouseTransferItem* House::getTransferItem() -{ +HouseTransferItem* House::getTransferItem() { if (transferItem != nullptr) { return nullptr; } @@ -369,8 +353,7 @@ HouseTransferItem* House::getTransferItem() return transferItem; } -void House::resetTransferItem() -{ +void House::resetTransferItem() { if (transferItem) { Item* tmpItem = transferItem; transferItem = nullptr; @@ -381,8 +364,7 @@ void House::resetTransferItem() } } -HouseTransferItem* HouseTransferItem::createHouseTransferItem(House* house) -{ +HouseTransferItem* HouseTransferItem::createHouseTransferItem(House* house) { HouseTransferItem* transferItem = new HouseTransferItem(house); transferItem->incrementReferenceCounter(); transferItem->setID(ITEM_DOCUMENT_RO); @@ -393,8 +375,7 @@ HouseTransferItem* HouseTransferItem::createHouseTransferItem(House* house) return transferItem; } -void HouseTransferItem::onTradeEvent(TradeEvents_t event, Player* owner) -{ +void HouseTransferItem::onTradeEvent(TradeEvents_t event, Player* owner) { if (event == ON_TRADE_TRANSFER) { if (house) { house->executeTransfer(this, owner); @@ -408,8 +389,7 @@ void HouseTransferItem::onTradeEvent(TradeEvents_t event, Player* owner) } } -bool House::executeTransfer(HouseTransferItem* item, Player* newOwner) -{ +bool House::executeTransfer(HouseTransferItem* item, Player* newOwner) { if (transferItem != item) { return false; } @@ -419,8 +399,7 @@ bool House::executeTransfer(HouseTransferItem* item, Player* newOwner) return true; } -void AccessList::parseList(const std::string& list) -{ +void AccessList::parseList(const std::string &list) { playerList.clear(); guildRankList.clear(); allowEveryone = false; @@ -430,7 +409,7 @@ void AccessList::parseList(const std::string& list) } auto lines = explodeString(list, "\n", 100); - for (auto& line : lines) { + for (auto &line : lines) { trimString(line); trim_left(line, '\t'); trim_right(line, '\t'); @@ -460,8 +439,7 @@ void AccessList::parseList(const std::string& list) } } -void AccessList::addPlayer(const std::string& name) -{ +void AccessList::addPlayer(const std::string &name) { const Player* player = g_game().getPlayerByName(name); if (player) { playerList.insert(player->getGUID()); @@ -475,35 +453,32 @@ void AccessList::addPlayer(const std::string& name) namespace { -const Guild* getGuildByName(const std::string& name) -{ - uint32_t guildId = IOGuild::getGuildIdByName(name); - if (guildId == 0) { - return nullptr; - } + const Guild* getGuildByName(const std::string &name) { + uint32_t guildId = IOGuild::getGuildIdByName(name); + if (guildId == 0) { + return nullptr; + } - const Guild* guild = g_game().getGuild(guildId); - if (guild) { - return guild; - } + const Guild* guild = g_game().getGuild(guildId); + if (guild) { + return guild; + } - return IOGuild::loadGuild(guildId); -} + return IOGuild::loadGuild(guildId); + } } -void AccessList::addGuild(const std::string& name) -{ +void AccessList::addGuild(const std::string &name) { const Guild* guild = getGuildByName(name); if (guild) { - for (const auto& rank : guild->getRanks()) { + for (const auto &rank : guild->getRanks()) { guildRankList.insert(rank->id); } } } -void AccessList::addGuildRank(const std::string& name, const std::string& guildName) -{ +void AccessList::addGuildRank(const std::string &name, const std::string &guildName) { const Guild* guild = getGuildByName(guildName); if (guild) { const GuildRank_ptr rank = guild->getRankByName(name); @@ -513,8 +488,7 @@ void AccessList::addGuildRank(const std::string& name, const std::string& guildN } } -bool AccessList::isInList(const Player* player) -{ +bool AccessList::isInList(const Player* player) { if (allowEveryone) { return true; } @@ -528,15 +502,14 @@ bool AccessList::isInList(const Player* player) return rank && guildRankList.find(rank->id) != guildRankList.end(); } -void AccessList::getList(std::string& retList) const -{ +void AccessList::getList(std::string &retList) const { retList = this->list; } -Door::Door(uint16_t type) : Item(type) {} +Door::Door(uint16_t type) : + Item(type) { } -Attr_ReadValue Door::readAttr(AttrTypes_t attr, PropStream& propStream) -{ +Attr_ReadValue Door::readAttr(AttrTypes_t attr, PropStream &propStream) { if (attr == ATTR_HOUSEDOORID) { uint8_t doorId; if (!propStream.read(doorId)) { @@ -549,8 +522,7 @@ Attr_ReadValue Door::readAttr(AttrTypes_t attr, PropStream& propStream) return Item::readAttr(attr, propStream); } -void Door::setHouse(House* newHouse) -{ +void Door::setHouse(House* newHouse) { if (this->house != nullptr) { return; } @@ -562,8 +534,7 @@ void Door::setHouse(House* newHouse) } } -bool Door::canUse(const Player* player) -{ +bool Door::canUse(const Player* player) { if (!house) { return true; } @@ -575,8 +546,7 @@ bool Door::canUse(const Player* player) return accessList->isInList(player); } -void Door::setAccessList(const std::string& textlist) -{ +void Door::setAccessList(const std::string &textlist) { if (!accessList) { accessList.reset(new AccessList()); } @@ -584,8 +554,7 @@ void Door::setAccessList(const std::string& textlist) accessList->parseList(textlist); } -bool Door::getAccessList(std::string& list) const -{ +bool Door::getAccessList(std::string &list) const { if (!house) { return false; } @@ -594,8 +563,7 @@ bool Door::getAccessList(std::string& list) const return true; } -void Door::onRemoved() -{ +void Door::onRemoved() { Item::onRemoved(); if (house) { @@ -603,9 +571,8 @@ void Door::onRemoved() } } -House* Houses::getHouseByPlayerId(uint32_t playerId) -{ - for (const auto& it : houseMap) { +House* Houses::getHouseByPlayerId(uint32_t playerId) { + for (const auto &it : houseMap) { if (it.second->getOwner() == playerId) { return it.second; } @@ -613,8 +580,7 @@ House* Houses::getHouseByPlayerId(uint32_t playerId) return nullptr; } -bool Houses::loadHousesXML(const std::string& filename) -{ +bool Houses::loadHousesXML(const std::string &filename) { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(filename.c_str()); if (!result) { @@ -632,8 +598,7 @@ bool Houses::loadHousesXML(const std::string& filename) House* house = getHouse(houseId); if (!house) { - SPDLOG_ERROR("[Houses::loadHousesXML] - Unknown house, id: {}", - houseId); + SPDLOG_ERROR("[Houses::loadHousesXML] - Unknown house, id: {}", houseId); return false; } @@ -646,7 +611,8 @@ bool Houses::loadHousesXML(const std::string& filename) ); if (entryPos.x == 0 && entryPos.y == 0 && entryPos.z == 0) { SPDLOG_WARN("[Houses::loadHousesXML] - Entry not set for house " - "name: {} with id: {}", house->getName(), houseId); + "name: {} with id: {}", + house->getName(), houseId); } house->setEntryPos(entryPos); @@ -658,14 +624,13 @@ bool Houses::loadHousesXML(const std::string& filename) return true; } -void Houses::payHouses(RentPeriod_t rentPeriod) const -{ +void Houses::payHouses(RentPeriod_t rentPeriod) const { if (rentPeriod == RENTPERIOD_NEVER) { return; } time_t currentTime = time(nullptr); - for (const auto& it : houseMap) { + for (const auto &it : houseMap) { House* house = it.second; if (house->getOwner() == 0) { continue; diff --git a/src/map/house/house.h b/src/map/house/house.h index 597b987a590..02b2d3f8674 100644 --- a/src/map/house/house.h +++ b/src/map/house/house.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_MAP_HOUSE_HOUSE_H_ #define SRC_MAP_HOUSE_HOUSE_H_ @@ -19,17 +19,16 @@ class House; class BedItem; class Player; -class AccessList -{ +class AccessList { public: - void parseList(const std::string& list); - void addPlayer(const std::string& name); - void addGuild(const std::string& name); - void addGuildRank(const std::string& name, const std::string& rankName); + void parseList(const std::string &list); + void addPlayer(const std::string &name); + void addGuild(const std::string &name); + void addGuildRank(const std::string &name, const std::string &rankName); bool isInList(const Player* player); - void getList(std::string& list) const; + void getList(std::string &list) const; private: std::string list; @@ -38,14 +37,13 @@ class AccessList bool allowEveryone = false; }; -class Door final : public Item -{ +class Door final : public Item { public: explicit Door(uint16_t type); // non-copyable - Door(const Door&) = delete; - Door& operator=(const Door&) = delete; + Door(const Door &) = delete; + Door &operator=(const Door &) = delete; Door* getDoor() override { return this; @@ -58,9 +56,9 @@ class Door final : public Item return house; } - //serialization - Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; - void serializeAttr(PropWriteStream&) const override {} + // serialization + Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream) override; + void serializeAttr(PropWriteStream &) const override { } void setDoorId(uint32_t doorId) { setAttribute(ItemAttribute_t::DOORID, doorId); @@ -71,8 +69,8 @@ class Door final : public Item bool canUse(const Player* player); - void setAccessList(const std::string& textlist); - bool getAccessList(std::string& list) const; + void setAccessList(const std::string &textlist); + bool getAccessList(std::string &list) const; void onRemoved() override; @@ -87,12 +85,12 @@ class Door final : public Item using HouseTileList = std::list; using HouseBedItemList = std::list; -class HouseTransferItem final : public Item -{ +class HouseTransferItem final : public Item { public: static HouseTransferItem* createHouseTransferItem(House* house); - explicit HouseTransferItem(House* newHouse) : Item(0), house(newHouse) {} + explicit HouseTransferItem(House* newHouse) : + Item(0), house(newHouse) { } void onTradeEvent(TradeEvents_t event, Player* owner) override; bool canTransform() const override { @@ -103,8 +101,7 @@ class HouseTransferItem final : public Item House* house; }; -class House -{ +class House { public: explicit House(uint32_t houseId); @@ -115,8 +112,8 @@ class House // listId special = values: // GUEST_LIST = guest list // SUBOWNER_LIST = subowner list - void setAccessList(uint32_t listId, const std::string& textlist); - bool getAccessList(uint32_t listId, std::string& list) const; + void setAccessList(uint32_t listId, const std::string &textlist); + bool getAccessList(uint32_t listId, std::string &list) const; bool isInvited(const Player* player); @@ -126,14 +123,14 @@ class House void setEntryPos(Position pos) { posEntry = pos; } - const Position& getEntryPosition() const { + const Position &getEntryPosition() const { return posEntry; } void setName(std::string newHouseName) { this->houseName = newHouseName; } - const std::string& getName() const { + const std::string &getName() const { return houseName; } @@ -177,26 +174,26 @@ class House void addDoor(Door* door); void removeDoor(Door* door); Door* getDoorByNumber(uint32_t doorId) const; - Door* getDoorByPosition(const Position& pos); + Door* getDoorByPosition(const Position &pos); HouseTransferItem* getTransferItem(); void resetTransferItem(); bool executeTransfer(HouseTransferItem* item, Player* player); - const HouseTileList& getTiles() const { + const HouseTileList &getTiles() const { return houseTiles; } - const std::list& getDoors() const { + const std::list &getDoors() const { return doorList; } void addBed(BedItem* bed); - const HouseBedItemList& getBeds() const { + const HouseBedItemList &getBeds() const { return bedsList; } uint32_t getBedCount() { - return static_cast(std::ceil(bedsList.size() / 2.)); //each bed takes 2 sqms of space, ceil is just for bad maps + return static_cast(std::ceil(bedsList.size() / 2.)); // each bed takes 2 sqms of space, ceil is just for bad maps } private: @@ -206,7 +203,7 @@ class House AccessList guestList; AccessList subOwnerList; - Container transfer_container{ITEM_LOCKER}; + Container transfer_container { ITEM_LOCKER }; HouseTileList houseTiles; std::list doorList; @@ -230,25 +227,24 @@ class House bool isLoaded = false; - void handleContainer(ItemList &moveItemList, Item *item) const; - void handleWrapableItem(ItemList &moveItemList, Item *item) const; + void handleContainer(ItemList &moveItemList, Item* item) const; + void handleWrapableItem(ItemList &moveItemList, Item* item) const; }; using HouseMap = std::map; -class Houses -{ +class Houses { public: Houses() = default; ~Houses() { - for (const auto& it : houseMap) { + for (const auto &it : houseMap) { delete it.second; } } // non-copyable - Houses(const Houses&) = delete; - Houses& operator=(const Houses&) = delete; + Houses(const Houses &) = delete; + Houses &operator=(const Houses &) = delete; House* addHouse(uint32_t id) { auto it = houseMap.find(id); @@ -271,11 +267,11 @@ class Houses House* getHouseByPlayerId(uint32_t playerId); - bool loadHousesXML(const std::string& filename); + bool loadHousesXML(const std::string &filename); void payHouses(RentPeriod_t rentPeriod) const; - const HouseMap& getHouses() const { + const HouseMap &getHouses() const { return houseMap; } @@ -283,4 +279,4 @@ class Houses HouseMap houseMap; }; -#endif // SRC_MAP_HOUSE_HOUSE_H_ +#endif // SRC_MAP_HOUSE_HOUSE_H_ diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index 1bde4347bd7..e5ca571f760 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,10 +16,9 @@ #include "game/game.h" HouseTile::HouseTile(int32_t initX, int32_t initY, int32_t initZ, House* initHouse) : - DynamicTile(initX, initY, initZ), house(initHouse) {} + DynamicTile(initX, initY, initZ), house(initHouse) { } -void HouseTile::addThing(int32_t index, Thing* thing) -{ +void HouseTile::addThing(int32_t index, Thing* thing) { Tile::addThing(index, thing); if (!thing->getParent()) { @@ -31,8 +30,7 @@ void HouseTile::addThing(int32_t index, Thing* thing) } } -void HouseTile::internalAddThing(uint32_t index, Thing* thing) -{ +void HouseTile::internalAddThing(uint32_t index, Thing* thing) { Tile::internalAddThing(index, thing); if (!thing->getParent()) { @@ -44,8 +42,7 @@ void HouseTile::internalAddThing(uint32_t index, Thing* thing) } } -void HouseTile::updateHouse(Item* item) -{ +void HouseTile::updateHouse(Item* item) { if (item->getParent() != this) { return; } @@ -63,29 +60,25 @@ void HouseTile::updateHouse(Item* item) } } -ReturnValue HouseTile::queryAdd(int32_t index, const Thing& thing, uint32_t count, uint32_t tileFlags, Creature* actor/* = nullptr*/) const -{ +ReturnValue HouseTile::queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t tileFlags, Creature* actor /* = nullptr*/) const { if (const Creature* creature = thing.getCreature()) { if (const Player* player = creature->getPlayer()) { if (!house->isInvited(player)) { return RETURNVALUE_PLAYERISNOTINVITED; } - } - else if (const Monster* monster = creature->getMonster()) { + } else if (const Monster* monster = creature->getMonster()) { if (monster->isSummon()) { if (!house->isInvited(monster->getMaster()->getPlayer())) { return RETURNVALUE_NOTPOSSIBLE; } if (house->isInvited(monster->getMaster()->getPlayer()) && (hasFlag(TILESTATE_BLOCKSOLID) || (hasBitSet(FLAG_PATHFINDING, flags) && hasFlag(TILESTATE_NOFIELDBLOCKPATH)))) { return RETURNVALUE_NOTPOSSIBLE; - } - else { + } else { return RETURNVALUE_NOERROR; } } } - } - else if (thing.getItem() && actor) { + } else if (thing.getItem() && actor) { Player* actorPlayer = actor->getPlayer(); if (!house->isInvited(actorPlayer)) { return RETURNVALUE_CANNOTTHROW; @@ -94,18 +87,17 @@ ReturnValue HouseTile::queryAdd(int32_t index, const Thing& thing, uint32_t coun return Tile::queryAdd(index, thing, count, tileFlags, actor); } -Tile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& tileFlags) -{ +Tile* HouseTile::queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &tileFlags) { if (const Creature* creature = thing.getCreature()) { if (const Player* player = creature->getPlayer()) { if (!house->isInvited(player)) { - const Position& entryPos = house->getEntryPosition(); + const Position &entryPos = house->getEntryPosition(); Tile* destTile = g_game().map.getTile(entryPos); if (!destTile) { SPDLOG_ERROR("[HouseTile::queryDestination] - " - "Entry not correct for house name: {} " - "with id: {} not found tile: {}", - house->getName(), house->getId(), entryPos.toString()); + "Entry not correct for house name: {} " + "with id: {} not found tile: {}", + house->getName(), house->getId(), entryPos.toString()); destTile = g_game().map.getTile(player->getTemplePosition()); if (!destTile) { destTile = &(Tile::nullptr_tile); @@ -122,8 +114,7 @@ Tile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** des return Tile::queryDestination(index, thing, destItem, tileFlags); } -ReturnValue HouseTile::queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor /*= nullptr*/) const -{ +ReturnValue HouseTile::queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor /*= nullptr*/) const { const Item* item = thing.getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; diff --git a/src/map/house/housetile.h b/src/map/house/housetile.h index 198be50d855..61a54f0f044 100644 --- a/src/map/house/housetile.h +++ b/src/map/house/housetile.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_MAP_HOUSE_HOUSETILE_H_ #define SRC_MAP_HOUSE_HOUSETILE_H_ @@ -14,19 +14,16 @@ class House; -class HouseTile final : public DynamicTile -{ +class HouseTile final : public DynamicTile { public: HouseTile(int32_t x, int32_t y, int32_t z, House* house); - //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + // cylinder implementations + ReturnValue queryAdd(int32_t index, const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; - Tile* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) override; + Tile* queryDestination(int32_t &index, const Thing &thing, Item** destItem, uint32_t &flags) override; - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryRemove(const Thing &thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; void addThing(int32_t index, Thing* thing) override; void virtual internalAddThing(uint32_t index, Thing* thing) override; @@ -41,4 +38,4 @@ class HouseTile final : public DynamicTile House* house; }; -#endif // SRC_MAP_HOUSE_HOUSETILE_H_ +#endif // SRC_MAP_HOUSE_HOUSETILE_H_ diff --git a/src/map/map.cpp b/src/map/map.cpp index 9881df4cec5..99d2750355b 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,26 +16,21 @@ #include "game/game.h" #include "creatures/monsters/monster.h" -bool Map::load(const std::string& identifier, const Position& pos, bool unload) { +bool Map::load(const std::string &identifier, const Position &pos, bool unload) { try { IOMap loader; if (!loader.loadMap(this, identifier, pos, unload)) { SPDLOG_ERROR("[Map::load] - {}", loader.getLastErrorString()); return false; } - } - catch(const std::exception) { + } catch (const std::exception) { SPDLOG_ERROR("[Map::load] - The map in folder {} is missing or corrupted", identifier); return false; } return true; } -bool Map::loadMap(const std::string& identifier, - bool mainMap /*= false*/,bool loadHouses /*= false*/, - bool loadMonsters /*= false*/, bool loadNpcs /*= false*/, - const Position& pos /*= Position()*/, bool unload /*= false*/) -{ +bool Map::loadMap(const std::string &identifier, bool mainMap /*= false*/, bool loadHouses /*= false*/, bool loadMonsters /*= false*/, bool loadNpcs /*= false*/, const Position &pos /*= Position()*/, bool unload /*= false*/) { // Only download map if is loading the main map and it is not already downloaded if (mainMap && g_configManager().getBoolean(TOGGLE_DOWNLOAD_MAP) && !std::filesystem::exists(identifier)) { const auto mapDownloadUrl = g_configManager().getString(MAP_DOWNLOAD_URL); @@ -43,9 +38,9 @@ bool Map::loadMap(const std::string& identifier, SPDLOG_WARN("Map download URL in config.lua is empty, download disabled"); } - if (CURL *curl = curl_easy_init(); curl && !mapDownloadUrl.empty()) { + if (CURL* curl = curl_easy_init(); curl && !mapDownloadUrl.empty()) { SPDLOG_INFO("Downloading " + g_configManager().getString(MAP_NAME) + ".otbm to world folder"); - FILE *otbm = fopen(identifier.c_str(), "wb"); + FILE* otbm = fopen(identifier.c_str(), "wb"); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_URL, mapDownloadUrl.c_str()); curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_3); @@ -82,7 +77,7 @@ bool Map::loadMap(const std::string& identifier, * Only load houses items if map custom load is disabled * If map custom is enabled, then it is load in loadMapCustom function * NOTE: This will ensure that the information is not duplicated - */ + */ if (!g_configManager().getBoolean(TOGGLE_MAP_CUSTOM)) { IOMapSerialize::loadHouseInfo(); IOMapSerialize::loadHouseItems(this); @@ -104,8 +99,7 @@ bool Map::loadMap(const std::string& identifier, return true; } -bool Map::loadMapCustom(const std::string& identifier, bool loadHouses, bool loadMonsters, bool loadNpcs) -{ +bool Map::loadMapCustom(const std::string &identifier, bool loadHouses, bool loadMonsters, bool loadNpcs) { // Load the map this->load(identifier); @@ -132,8 +126,7 @@ bool Map::loadMapCustom(const std::string& identifier, bool loadHouses, bool loa return true; } -bool Map::save() -{ +bool Map::save() { bool saved = false; for (uint32_t tries = 0; tries < 6; tries++) { if (IOMapSerialize::saveHouseInfo()) { @@ -146,8 +139,7 @@ bool Map::save() return false; } -Tile* Map::getTile(uint16_t x, uint16_t y, uint8_t z) const -{ +Tile* Map::getTile(uint16_t x, uint16_t y, uint8_t z) const { if (z >= MAP_MAX_LAYERS) { return nullptr; } @@ -164,11 +156,9 @@ Tile* Map::getTile(uint16_t x, uint16_t y, uint8_t z) const return floor->tiles[x & FLOOR_MASK][y & FLOOR_MASK]; } -void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) -{ +void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) { if (z >= MAP_MAX_LAYERS) { - SPDLOG_ERROR("Attempt to set tile on invalid coordinate: {}", - Position(x, y, z).toString()); + SPDLOG_ERROR("Attempt to set tile on invalid coordinate: {}", Position(x, y, z).toString()); return; } @@ -176,25 +166,25 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) QTreeLeafNode* leaf = root.createLeaf(x, y, 15); if (QTreeLeafNode::newLeaf) { - //update north + // update north QTreeLeafNode* northLeaf = root.getLeaf(x, y - FLOOR_SIZE); if (northLeaf) { northLeaf->leafS = leaf; } - //update west leaf + // update west leaf QTreeLeafNode* westLeaf = root.getLeaf(x - FLOOR_SIZE, y); if (westLeaf) { westLeaf->leafE = leaf; } - //update south + // update south QTreeLeafNode* southLeaf = root.getLeaf(x, y + FLOOR_SIZE); if (southLeaf) { leaf->leafS = southLeaf; } - //update east + // update east QTreeLeafNode* eastLeaf = root.getLeaf(x + FLOOR_SIZE, y); if (eastLeaf) { leaf->leafE = eastLeaf; @@ -205,7 +195,7 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) uint32_t offsetX = x & FLOOR_MASK; uint32_t offsetY = y & FLOOR_MASK; - Tile*& tile = floor->tiles[offsetX][offsetY]; + Tile*&tile = floor->tiles[offsetX][offsetY]; if (tile) { TileItemVector* items = newTile->getItemList(); if (items) { @@ -226,8 +216,7 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) } } -bool Map::placeCreature(const Position& centerPos, Creature* creature, bool extendedPos/* = false*/, bool forceLogin/* = false*/) -{ +bool Map::placeCreature(const Position ¢erPos, Creature* creature, bool extendedPos /* = false*/, bool forceLogin /* = false*/) { Monster* monster = creature->getMonster(); if (monster) { monster->ignoreFieldDamage = true; @@ -241,7 +230,7 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte placeInPZ = tile->hasFlag(TILESTATE_PROTECTIONZONE); ReturnValue ret = tile->queryAdd(0, *creature, 1, FLAG_IGNOREBLOCKITEM | FLAG_IGNOREFIELDDAMAGE); foundTile = forceLogin || ret == RETURNVALUE_NOERROR || ret == RETURNVALUE_PLAYERISNOTINVITED; - if (monster) { + if (monster) { monster->ignoreFieldDamage = false; } } else { @@ -251,20 +240,25 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte if (!foundTile) { static std::vector> extendedRelList { - {0, -2}, - {-1, -1}, {0, -1}, {1, -1}, - {-2, 0}, {-1, 0}, {1, 0}, {2, 0}, - {-1, 1}, {0, 1}, {1, 1}, - {0, 2} + { 0, -2 }, + { -1, -1 }, + { 0, -1 }, + { 1, -1 }, + { -2, 0 }, + { -1, 0 }, + { 1, 0 }, + { 2, 0 }, + { -1, 1 }, + { 0, 1 }, + { 1, 1 }, + { 0, 2 } }; static std::vector> normalRelList { - {-1, -1}, {0, -1}, {1, -1}, - {-1, 0}, {1, 0}, - {-1, 1}, {0, 1}, {1, 1} + { -1, -1 }, { 0, -1 }, { 1, -1 }, { -1, 0 }, { 1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 } }; - std::vector>& relList = (extendedPos ? extendedRelList : normalRelList); + std::vector> &relList = (extendedPos ? extendedRelList : normalRelList); if (extendedPos) { std::shuffle(relList.begin(), relList.begin() + 4, getRandomGenerator()); @@ -273,7 +267,7 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte std::shuffle(relList.begin(), relList.end(), getRandomGenerator()); } - for (const auto& it : relList) { + for (const auto &it : relList) { Position tryPos(centerPos.x + it.first, centerPos.y + it.second, centerPos.z); tile = getTile(tryPos.x, tryPos.y, tryPos.z); @@ -309,14 +303,13 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte Cylinder* toCylinder = tile->queryDestination(index, *creature, &toItem, flags); toCylinder->internalAddThing(creature); - const Position& dest = toCylinder->getPosition(); + const Position &dest = toCylinder->getPosition(); getQTNode(dest.x, dest.y)->addCreature(creature); return true; } -void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = false*/) -{ - Tile& oldTile = *creature.getTile(); +void Map::moveCreature(Creature &creature, Tile &newTile, bool forceTeleport /* = false*/) { + Tile &oldTile = *creature.getTile(); Position oldPos = oldTile.getPosition(); Position newPos = newTile.getPosition(); @@ -338,7 +331,7 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = } } - //remove the creature + // remove the creature oldTile.removeThing(&creature, 0); QTreeLeafNode* leaf = getQTNode(oldPos.x, oldPos.y); @@ -350,7 +343,7 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = new_leaf->addCreature(&creature); } - //add the creature + // add the creature newTile.addThing(&creature); if (!teleport) { @@ -367,11 +360,11 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = } } - //send to client + // send to client size_t i = 0; for (Creature* spectator : spectators) { if (Player* tmpPlayer = spectator->getPlayer()) { - //Use the correct stackpos + // Use the correct stackpos int32_t stackpos = oldStackPosVector[i++]; if (stackpos != -1) { tmpPlayer->sendCreatureMove(&creature, newPos, newTile.getStackposOfCreature(tmpPlayer, &creature), oldPos, stackpos, teleport); @@ -379,7 +372,7 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = } } - //event method + // event method for (Creature* spectator : spectators) { spectator->onCreatureMove(&creature, &newTile, newPos, &oldTile, oldPos, teleport); } @@ -388,8 +381,7 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = newTile.postAddNotification(&creature, &oldTile, 0); } -void Map::getSpectatorsInternal(SpectatorHashSet& spectators, const Position& centerPos, int32_t minRangeX, int32_t maxRangeX, int32_t minRangeY, int32_t maxRangeY, int32_t minRangeZ, int32_t maxRangeZ, bool onlyPlayers) const -{ +void Map::getSpectatorsInternal(SpectatorHashSet &spectators, const Position ¢erPos, int32_t minRangeX, int32_t maxRangeX, int32_t minRangeY, int32_t maxRangeY, int32_t minRangeZ, int32_t maxRangeZ, bool onlyPlayers) const { int_fast32_t min_y = centerPos.y + minRangeY; int_fast32_t min_x = centerPos.x + minRangeX; int_fast32_t max_y = centerPos.y + maxRangeY; @@ -416,9 +408,9 @@ void Map::getSpectatorsInternal(SpectatorHashSet& spectators, const Position& ce leafE = leafS; for (int_fast32_t nx = startx1; nx <= endx2; nx += FLOOR_SIZE) { if (leafE) { - const CreatureVector& node_list = (onlyPlayers ? leafE->player_list : leafE->creature_list); + const CreatureVector &node_list = (onlyPlayers ? leafE->player_list : leafE->creature_list); for (Creature* creature : node_list) { - const Position& cpos = creature->getPosition(); + const Position &cpos = creature->getPosition(); if (minRangeZ > cpos.z || maxRangeZ < cpos.z) { continue; } @@ -444,8 +436,7 @@ void Map::getSpectatorsInternal(SpectatorHashSet& spectators, const Position& ce } } -void Map::getSpectators(SpectatorHashSet& spectators, const Position& centerPos, bool multifloor /*= false*/, bool onlyPlayers /*= false*/, int32_t minRangeX /*= 0*/, int32_t maxRangeX /*= 0*/, int32_t minRangeY /*= 0*/, int32_t maxRangeY /*= 0*/) -{ +void Map::getSpectators(SpectatorHashSet &spectators, const Position ¢erPos, bool multifloor /*= false*/, bool onlyPlayers /*= false*/, int32_t minRangeX /*= 0*/, int32_t maxRangeX /*= 0*/, int32_t minRangeY /*= 0*/, int32_t maxRangeY /*= 0*/) { if (centerPos.z >= MAP_MAX_LAYERS) { return; } @@ -463,7 +454,7 @@ void Map::getSpectators(SpectatorHashSet& spectators, const Position& centerPos, auto it = playersSpectatorCache.find(centerPos); if (it != playersSpectatorCache.end()) { if (!spectators.empty()) { - const SpectatorHashSet& cachedSpectators = it->second; + const SpectatorHashSet &cachedSpectators = it->second; spectators.insert(cachedSpectators.begin(), cachedSpectators.end()); } else { spectators = it->second; @@ -478,13 +469,13 @@ void Map::getSpectators(SpectatorHashSet& spectators, const Position& centerPos, if (it != spectatorCache.end()) { if (!onlyPlayers) { if (!spectators.empty()) { - const SpectatorHashSet& cachedSpectators = it->second; + const SpectatorHashSet &cachedSpectators = it->second; spectators.insert(cachedSpectators.begin(), cachedSpectators.end()); } else { spectators = it->second; } } else { - const SpectatorHashSet& cachedSpectators = it->second; + const SpectatorHashSet &cachedSpectators = it->second; for (Creature* spectator : cachedSpectators) { if (spectator->getPlayer()) { spectators.insert(spectator); @@ -505,9 +496,9 @@ void Map::getSpectators(SpectatorHashSet& spectators, const Position& centerPos, if (multifloor) { if (centerPos.z > MAP_INIT_SURFACE_LAYER) { - //underground + // underground - //8->15 + // 8->15 minRangeZ = std::max(centerPos.getZ() - MAP_LAYER_VIEW_LIMIT, 0); maxRangeZ = std::min(centerPos.getZ() + MAP_LAYER_VIEW_LIMIT, MAP_MAX_LAYERS - 1); } else if (centerPos.z == MAP_INIT_SURFACE_LAYER - 1) { @@ -537,18 +528,15 @@ void Map::getSpectators(SpectatorHashSet& spectators, const Position& centerPos, } } -void Map::clearSpectatorCache() -{ +void Map::clearSpectatorCache() { spectatorCache.clear(); playersSpectatorCache.clear(); } -bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/, - int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const -{ - //z checks - //underground 8->15 - //ground level and above 7->0 +bool Map::canThrowObjectTo(const Position &fromPos, const Position &toPos, bool checkLineOfSight /*= true*/, int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const { + // z checks + // underground 8->15 + // ground level and above 7->0 if ((fromPos.z >= 8 && toPos.z <= MAP_INIT_SURFACE_LAYER) || (toPos.z >= MAP_INIT_SURFACE_LAYER + 1 && fromPos.z <= MAP_INIT_SURFACE_LAYER)) { return false; } @@ -562,7 +550,7 @@ bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool return false; } - //distance checks + // distance checks if ((Position::getDistanceY(fromPos, toPos) - deltaz) > rangey) { return false; } @@ -573,8 +561,7 @@ bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool return isSightClear(fromPos, toPos, false); } -bool Map::checkSightLine(const Position& fromPos, const Position& toPos) const -{ +bool Map::checkSightLine(const Position &fromPos, const Position &toPos) const { if (fromPos == toPos) { return true; } @@ -582,8 +569,10 @@ bool Map::checkSightLine(const Position& fromPos, const Position& toPos) const Position start(fromPos.z > toPos.z ? toPos : fromPos); Position destination(fromPos.z > toPos.z ? fromPos : toPos); - const int8_t mx = start.x < destination.x ? 1 : start.x == destination.x ? 0 : -1; - const int8_t my = start.y < destination.y ? 1 : start.y == destination.y ? 0 : -1; + const int8_t mx = start.x < destination.x ? 1 : start.x == destination.x ? 0 + : -1; + const int8_t my = start.y < destination.y ? 1 : start.y == destination.y ? 0 + : -1; int32_t A = Position::getOffsetY(destination, start); int32_t B = Position::getOffsetX(start, destination); @@ -621,8 +610,7 @@ bool Map::checkSightLine(const Position& fromPos, const Position& toPos) const return true; } -bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool floorCheck) const -{ +bool Map::isSightClear(const Position &fromPos, const Position &toPos, bool floorCheck) const { if (floorCheck && fromPos.z != toPos.z) { return false; } @@ -631,8 +619,7 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool floo return checkSightLine(fromPos, toPos) || checkSightLine(toPos, fromPos); } -const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const -{ +const Tile* Map::canWalkTo(const Creature &creature, const Position &pos) const { int32_t walkCache = creature.getWalkCache(pos); if (walkCache == 0) { return nullptr; @@ -640,7 +627,7 @@ const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const return getTile(pos.x, pos.y, pos.z); } - //used for non-cached tiles + // used for non-cached tiles Tile* tile = getTile(pos.x, pos.y, pos.z); if (creature.getTile() != tile) { if (!tile || tile->queryAdd(0, creature, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) != RETURNVALUE_NOERROR) { @@ -650,8 +637,7 @@ const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const return tile; } -bool Map::getPathMatching(const Creature& creature, std::forward_list& dirList, const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const -{ +bool Map::getPathMatching(const Creature &creature, std::forward_list &dirList, const FrozenPathingConditionCall &pathCondition, const FindPathParams &fpp) const { Position pos = creature.getPosition(); Position endPos; @@ -660,17 +646,17 @@ bool Map::getPathMatching(const Creature& creature, std::forward_list int32_t bestMatch = 0; static int_fast32_t dirNeighbors[8][5][2] = { - {{-1, 0}, {0, 1}, {1, 0}, {1, 1}, {-1, 1}}, - {{-1, 0}, {0, 1}, {0, -1}, {-1, -1}, {-1, 1}}, - {{-1, 0}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}}, - {{0, 1}, {1, 0}, {0, -1}, {1, -1}, {1, 1}}, - {{1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}}, - {{-1, 0}, {0, -1}, {-1, -1}, {1, -1}, {-1, 1}}, - {{0, 1}, {1, 0}, {1, -1}, {1, 1}, {-1, 1}}, - {{-1, 0}, {0, 1}, {-1, -1}, {1, 1}, {-1, 1}} + { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 }, { -1, 1 } }, + { { -1, 0 }, { 0, 1 }, { 0, -1 }, { -1, -1 }, { -1, 1 } }, + { { -1, 0 }, { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 } }, + { { 0, 1 }, { 1, 0 }, { 0, -1 }, { 1, -1 }, { 1, 1 } }, + { { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { 1, 1 } }, + { { -1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } }, + { { 0, 1 }, { 1, 0 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }, + { { -1, 0 }, { 0, 1 }, { -1, -1 }, { 1, 1 }, { -1, 1 } } }; static int_fast32_t allNeighbors[8][2] = { - {-1, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1} + { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }; const Position startPos = pos; @@ -755,14 +741,14 @@ bool Map::getPathMatching(const Creature& creature, std::forward_list } } - //The cost (g) for this neighbor + // The cost (g) for this neighbor const int_fast32_t cost = AStarNodes::getMapWalkCost(n, pos); const int_fast32_t extraCost = AStarNodes::getTileWalkCost(creature, tile); const int_fast32_t newf = f + cost + extraCost; if (neighborNode) { if (neighborNode->f <= newf) { - //The node on the closed/open list is cheaper than this one + // The node on the closed/open list is cheaper than this one continue; } @@ -770,7 +756,7 @@ bool Map::getPathMatching(const Creature& creature, std::forward_list neighborNode->parent = n; nodes.openNode(neighborNode); } else { - //Does not exist in the open/closed list, create a new node + // Does not exist in the open/closed list, create a new node neighborNode = nodes.createOpenNode(n, pos.x, pos.y, newf); if (!neighborNode) { if (found) { @@ -825,8 +811,7 @@ bool Map::getPathMatching(const Creature& creature, std::forward_list return true; } -bool Map::getPathMatching(const Position& start, std::forward_list& dirList, const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const -{ +bool Map::getPathMatching(const Position &start, std::forward_list &dirList, const FrozenPathingConditionCall &pathCondition, const FindPathParams &fpp) const { Position pos = start; Position endPos; @@ -835,17 +820,17 @@ bool Map::getPathMatching(const Position& start, std::forward_list& d int32_t bestMatch = 0; static int_fast32_t dirNeighbors[8][5][2] = { - {{-1, 0}, {0, 1}, {1, 0}, {1, 1}, {-1, 1}}, - {{-1, 0}, {0, 1}, {0, -1}, {-1, -1}, {-1, 1}}, - {{-1, 0}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}}, - {{0, 1}, {1, 0}, {0, -1}, {1, -1}, {1, 1}}, - {{1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}}, - {{-1, 0}, {0, -1}, {-1, -1}, {1, -1}, {-1, 1}}, - {{0, 1}, {1, 0}, {1, -1}, {1, 1}, {-1, 1}}, - {{-1, 0}, {0, 1}, {-1, -1}, {1, 1}, {-1, 1}} + { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 }, { -1, 1 } }, + { { -1, 0 }, { 0, 1 }, { 0, -1 }, { -1, -1 }, { -1, 1 } }, + { { -1, 0 }, { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 } }, + { { 0, 1 }, { 1, 0 }, { 0, -1 }, { 1, -1 }, { 1, 1 } }, + { { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { 1, 1 } }, + { { -1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } }, + { { 0, 1 }, { 1, 0 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }, + { { -1, 0 }, { 0, 1 }, { -1, -1 }, { 1, 1 }, { -1, 1 } } }; static int_fast32_t allNeighbors[8][2] = { - {-1, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1} + { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }; const Position startPos = pos; @@ -880,36 +865,28 @@ bool Map::getPathMatching(const Position& start, std::forward_list& d if (offset_y == 0) { if (offset_x == -1) { neighbors = *dirNeighbors[DIRECTION_WEST]; - } - else { + } else { neighbors = *dirNeighbors[DIRECTION_EAST]; } - } - else if (!fpp.allowDiagonal || offset_x == 0) { + } else if (!fpp.allowDiagonal || offset_x == 0) { if (offset_y == -1) { neighbors = *dirNeighbors[DIRECTION_NORTH]; - } - else { + } else { neighbors = *dirNeighbors[DIRECTION_SOUTH]; } - } - else if (offset_y == -1) { + } else if (offset_y == -1) { if (offset_x == -1) { neighbors = *dirNeighbors[DIRECTION_NORTHWEST]; - } - else { + } else { neighbors = *dirNeighbors[DIRECTION_NORTHEAST]; } - } - else if (offset_x == -1) { + } else if (offset_x == -1) { neighbors = *dirNeighbors[DIRECTION_SOUTHWEST]; - } - else { + } else { neighbors = *dirNeighbors[DIRECTION_SOUTHEAST]; } dirCount = fpp.allowDiagonal ? 5 : 3; - } - else { + } else { dirCount = 8; neighbors = *allNeighbors; } @@ -931,31 +908,29 @@ bool Map::getPathMatching(const Position& start, std::forward_list& d AStarNode* neighborNode = nodes.getNodeByPosition(pos.x, pos.y); if (neighborNode) { tile = getTile(pos.x, pos.y, pos.z); - } - else { + } else { tile = getTile(pos.x, pos.y, pos.z); if (!tile || tile->hasFlag(TILESTATE_BLOCKSOLID)) { continue; } } - //The cost (g) for this neighbor + // The cost (g) for this neighbor const int_fast32_t cost = AStarNodes::getMapWalkCost(n, pos, true); const int_fast32_t extraCost = 0; const int_fast32_t newf = f + cost + extraCost; if (neighborNode) { if (neighborNode->f <= newf) { - //The node on the closed/open list is cheaper than this one + // The node on the closed/open list is cheaper than this one continue; } neighborNode->f = newf; neighborNode->parent = n; nodes.openNode(neighborNode); - } - else { - //Does not exist in the open/closed list, create a new node + } else { + // Does not exist in the open/closed list, create a new node neighborNode = nodes.createOpenNode(n, pos.x, pos.y, newf); if (!neighborNode) { if (found) { @@ -989,26 +964,19 @@ bool Map::getPathMatching(const Position& start, std::forward_list& d if (dx == 1 && dy == 1) { dirList.push_front(DIRECTION_NORTHWEST); - } - else if (dx == -1 && dy == 1) { + } else if (dx == -1 && dy == 1) { dirList.push_front(DIRECTION_NORTHEAST); - } - else if (dx == 1 && dy == -1) { + } else if (dx == 1 && dy == -1) { dirList.push_front(DIRECTION_SOUTHWEST); - } - else if (dx == -1 && dy == -1) { + } else if (dx == -1 && dy == -1) { dirList.push_front(DIRECTION_SOUTHEAST); - } - else if (dx == 1) { + } else if (dx == 1) { dirList.push_front(DIRECTION_WEST); - } - else if (dx == -1) { + } else if (dx == -1) { dirList.push_front(DIRECTION_EAST); - } - else if (dy == 1) { + } else if (dy == 1) { dirList.push_front(DIRECTION_NORTH); - } - else if (dy == -1) { + } else if (dy == -1) { dirList.push_front(DIRECTION_SOUTH); } @@ -1019,14 +987,13 @@ bool Map::getPathMatching(const Position& start, std::forward_list& d // AStarNodes -AStarNodes::AStarNodes(uint32_t x, uint32_t y) - : nodes(), openNodes() -{ +AStarNodes::AStarNodes(uint32_t x, uint32_t y) : + nodes(), openNodes() { curNode = 1; closedNodes = 0; openNodes[0] = true; - AStarNode& startNode = nodes[0]; + AStarNode &startNode = nodes[0]; startNode.parent = nullptr; startNode.x = x; startNode.y = y; @@ -1034,8 +1001,7 @@ AStarNodes::AStarNodes(uint32_t x, uint32_t y) nodeTable[(x << 16) | y] = nodes; } -AStarNode* AStarNodes::createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, int_fast32_t f) -{ +AStarNode* AStarNodes::createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, int_fast32_t f) { if (curNode >= MAX_NODES) { return nullptr; } @@ -1052,8 +1018,7 @@ AStarNode* AStarNodes::createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, return node; } -AStarNode* AStarNodes::getBestNode() -{ +AStarNode* AStarNodes::getBestNode() { if (curNode == 0) { return nullptr; } @@ -1073,16 +1038,14 @@ AStarNode* AStarNodes::getBestNode() return nullptr; } -void AStarNodes::closeNode(AStarNode* node) -{ +void AStarNodes::closeNode(AStarNode* node) { size_t index = node - nodes; assert(index < MAX_NODES); openNodes[index] = false; ++closedNodes; } -void AStarNodes::openNode(AStarNode* node) -{ +void AStarNodes::openNode(AStarNode* node) { size_t index = node - nodes; assert(index < MAX_NODES); if (!openNodes[index]) { @@ -1091,13 +1054,11 @@ void AStarNodes::openNode(AStarNode* node) } } -int_fast32_t AStarNodes::getClosedNodes() const -{ +int_fast32_t AStarNodes::getClosedNodes() const { return closedNodes; } -AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) -{ +AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) { auto it = nodeTable.find((x << 16) | y); if (it == nodeTable.end()) { return nullptr; @@ -1105,10 +1066,9 @@ AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) return it->second; } -int_fast32_t AStarNodes::getMapWalkCost(AStarNode* node, const Position& neighborPos, bool preferDiagonal) -{ +int_fast32_t AStarNodes::getMapWalkCost(AStarNode* node, const Position &neighborPos, bool preferDiagonal) { if (std::abs(node->x - neighborPos.x) == std::abs(node->y - neighborPos.y)) { - //diagonal movement extra cost + // diagonal movement extra cost if (preferDiagonal) return MAP_PREFERDIAGONALWALKCOST; else @@ -1117,11 +1077,10 @@ int_fast32_t AStarNodes::getMapWalkCost(AStarNode* node, const Position& neighbo return MAP_NORMALWALKCOST; } -int_fast32_t AStarNodes::getTileWalkCost(const Creature& creature, const Tile* tile) -{ +int_fast32_t AStarNodes::getTileWalkCost(const Creature &creature, const Tile* tile) { int_fast32_t cost = 0; if (tile->getTopVisibleCreature(&creature) != nullptr) { - //destroy creature cost + // destroy creature cost cost += MAP_NORMALWALKCOST * 3; } @@ -1136,9 +1095,8 @@ int_fast32_t AStarNodes::getTileWalkCost(const Creature& creature, const Tile* t } // Floor -Floor::~Floor() -{ - for (auto& row : tiles) { +Floor::~Floor() { + for (auto &row : tiles) { for (auto tile : row) { delete tile; } @@ -1146,15 +1104,13 @@ Floor::~Floor() } // QTreeNode -QTreeNode::~QTreeNode() -{ +QTreeNode::~QTreeNode() { for (auto* ptr : child) { delete ptr; } } -QTreeLeafNode* QTreeNode::getLeaf(uint32_t x, uint32_t y) -{ +QTreeLeafNode* QTreeNode::getLeaf(uint32_t x, uint32_t y) { if (leaf) { return static_cast(this); } @@ -1166,8 +1122,7 @@ QTreeLeafNode* QTreeNode::getLeaf(uint32_t x, uint32_t y) return node->getLeaf(x << 1, y << 1); } -QTreeLeafNode* QTreeNode::createLeaf(uint32_t x, uint32_t y, uint32_t level) -{ +QTreeLeafNode* QTreeNode::createLeaf(uint32_t x, uint32_t y, uint32_t level) { if (!isLeaf()) { uint32_t index = ((x & 0x8000) >> 15) | ((y & 0x8000) >> 14); if (!child[index]) { @@ -1186,23 +1141,20 @@ QTreeLeafNode* QTreeNode::createLeaf(uint32_t x, uint32_t y, uint32_t level) // QTreeLeafNode bool QTreeLeafNode::newLeaf = false; -QTreeLeafNode::~QTreeLeafNode() -{ +QTreeLeafNode::~QTreeLeafNode() { for (auto* ptr : array) { delete ptr; } } -Floor* QTreeLeafNode::createFloor(uint32_t z) -{ +Floor* QTreeLeafNode::createFloor(uint32_t z) { if (!array[z]) { array[z] = new Floor(); } return array[z]; } -void QTreeLeafNode::addCreature(Creature* c) -{ +void QTreeLeafNode::addCreature(Creature* c) { creature_list.push_back(c); if (c->getPlayer()) { @@ -1210,8 +1162,7 @@ void QTreeLeafNode::addCreature(Creature* c) } } -void QTreeLeafNode::removeCreature(Creature* c) -{ +void QTreeLeafNode::removeCreature(Creature* c) { auto iter = std::find(creature_list.begin(), creature_list.end(), c); assert(iter != creature_list.end()); *iter = creature_list.back(); @@ -1225,8 +1176,7 @@ void QTreeLeafNode::removeCreature(Creature* c) } } -uint32_t Map::clean() const -{ +uint32_t Map::clean() const { uint64_t start = OTSYS_TIME(); size_t tiles = 0; @@ -1236,20 +1186,20 @@ uint32_t Map::clean() const std::vector toRemove; for (auto tile : g_game().getTilesToClean()) { - if (!tile) { - continue; - } - if (auto items = tile->getItemList()) { - ++tiles; - for (auto item : *items) { + if (!tile) { + continue; + } + if (auto items = tile->getItemList()) { + ++tiles; + for (auto item : *items) { if (item->isCleanable()) { toRemove.emplace_back(item); } - } + } } } - for (auto item : toRemove) { + for (auto item : toRemove) { g_game().internalRemoveItem(item, -1); } @@ -1260,9 +1210,6 @@ uint32_t Map::clean() const g_game().setGameState(GAME_STATE_NORMAL); } - SPDLOG_INFO("CLEAN: Removed {} item{} from {} tile{} in {} seconds", - count, (count != 1 ? "s" : ""), - tiles, (tiles != 1 ? "s" : ""), - (OTSYS_TIME() - start) / (1000.)); + SPDLOG_INFO("CLEAN: Removed {} item{} from {} tile{} in {} seconds", count, (count != 1 ? "s" : ""), tiles, (tiles != 1 ? "s" : ""), (OTSYS_TIME() - start) / (1000.)); return count; } diff --git a/src/map/map.h b/src/map/map.h index 73f2cbd23d9..5706fd27595 100644 --- a/src/map/map.h +++ b/src/map/map.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_MAP_MAP_H_ #define SRC_MAP_MAP_H_ @@ -30,9 +30,9 @@ static constexpr int8_t MAP_LAYER_VIEW_LIMIT = 2; struct FindPathParams; struct AStarNode { - AStarNode* parent; - int_fast32_t f; - uint16_t x, y; + AStarNode* parent; + int_fast32_t f; + uint16_t x, y; }; static constexpr int32_t MAX_NODES = 512; @@ -41,8 +41,7 @@ static constexpr int32_t MAP_NORMALWALKCOST = 10; static constexpr int32_t MAP_PREFERDIAGONALWALKCOST = 14; static constexpr int32_t MAP_DIAGONALWALKCOST = 25; -class AStarNodes -{ +class AStarNodes { public: AStarNodes(uint32_t x, uint32_t y); @@ -53,8 +52,8 @@ class AStarNodes int_fast32_t getClosedNodes() const; AStarNode* getNodeByPosition(uint32_t x, uint32_t y); - static int_fast32_t getMapWalkCost(AStarNode* node, const Position& neighborPos, bool preferDiagonal = false); - static int_fast32_t getTileWalkCost(const Creature& creature, const Tile* tile); + static int_fast32_t getMapWalkCost(AStarNode* node, const Position &neighborPos, bool preferDiagonal = false); + static int_fast32_t getTileWalkCost(const Creature &creature, const Tile* tile); private: AStarNode nodes[MAX_NODES]; @@ -71,28 +70,27 @@ static constexpr int32_t FLOOR_SIZE = (1 << FLOOR_BITS); static constexpr int32_t FLOOR_MASK = (FLOOR_SIZE - 1); struct Floor { - constexpr Floor() = default; - ~Floor(); + constexpr Floor() = default; + ~Floor(); - // non-copyable - Floor(const Floor&) = delete; - Floor& operator=(const Floor&) = delete; + // non-copyable + Floor(const Floor &) = delete; + Floor &operator=(const Floor &) = delete; - Tile* tiles[FLOOR_SIZE][FLOOR_SIZE] = {}; + Tile* tiles[FLOOR_SIZE][FLOOR_SIZE] = {}; }; class FrozenPathingConditionCall; class QTreeLeafNode; -class QTreeNode -{ +class QTreeNode { public: constexpr QTreeNode() = default; virtual ~QTreeNode(); // non-copyable - QTreeNode(const QTreeNode&) = delete; - QTreeNode& operator=(const QTreeNode&) = delete; + QTreeNode(const QTreeNode &) = delete; + QTreeNode &operator=(const QTreeNode &) = delete; bool isLeaf() const { return leaf; @@ -100,9 +98,8 @@ class QTreeNode QTreeLeafNode* getLeaf(uint32_t x, uint32_t y); - template - static Leaf getLeafStatic(Node node, uint32_t x, uint32_t y) - { + template + static Leaf getLeafStatic(Node node, uint32_t x, uint32_t y) { do { node = node->child[((x & 0x8000) >> 15) | ((y & 0x8000) >> 14)]; if (!node) { @@ -125,15 +122,17 @@ class QTreeNode friend class Map; }; -class QTreeLeafNode final : public QTreeNode -{ +class QTreeLeafNode final : public QTreeNode { public: - QTreeLeafNode() { leaf = true; newLeaf = true; } + QTreeLeafNode() { + leaf = true; + newLeaf = true; + } ~QTreeLeafNode(); // non-copyable - QTreeLeafNode(const QTreeLeafNode&) = delete; - QTreeLeafNode& operator=(const QTreeLeafNode&) = delete; + QTreeLeafNode(const QTreeLeafNode &) = delete; + QTreeLeafNode &operator=(const QTreeLeafNode &) = delete; Floor* createFloor(uint32_t z); Floor* getFloor(uint8_t z) const { @@ -156,115 +155,108 @@ class QTreeLeafNode final : public QTreeNode }; /** - * Map class. - * Holds all the actual map-data - */ + * Map class. + * Holds all the actual map-data + */ -class Map -{ +class Map { public: - static constexpr int32_t maxClientViewportX = 8; static constexpr int32_t maxClientViewportY = 6; - static constexpr int32_t maxViewportX = maxClientViewportX + 3; //min value: maxClientViewportX + 1 - static constexpr int32_t maxViewportY = maxClientViewportY + 5; //min value: maxClientViewportY + 1 + static constexpr int32_t maxViewportX = maxClientViewportX + 3; // min value: maxClientViewportX + 1 + static constexpr int32_t maxViewportY = maxClientViewportY + 5; // min value: maxClientViewportY + 1 uint32_t clean() const; /** - * Load a map. - * \returns true if the map was loaded successfully - */ - bool load(const std::string& identifier, const Position& pos = Position(), bool unload = false); + * Load a map. + * \returns true if the map was loaded successfully + */ + bool load(const std::string &identifier, const Position &pos = Position(), bool unload = false); /** - * Load the main map + * Load the main map * \param identifier Is the main map name (name of file .otbm) * \param loadHouses if true, the main map houses is loaded * \param loadMonsters if true, the main map monsters is loaded * \param loadNpcs if true, the main map npcs is loaded * \returns true if the main map was loaded successfully - */ - bool loadMap(const std::string& identifier, bool mainMap = false, bool loadHouses = false, bool loadMonsters = false, bool loadNpcs = false, const Position& pos = Position(), bool unload = false); + */ + bool loadMap(const std::string &identifier, bool mainMap = false, bool loadHouses = false, bool loadMonsters = false, bool loadNpcs = false, const Position &pos = Position(), bool unload = false); /** - * Load the custom map + * Load the custom map * \param identifier Is the map custom folder * \param loadHouses if true, the map custom houses is loaded * \param loadMonsters if true, the map custom monsters is loaded * \param loadNpcs if true, the map custom npcs is loaded * \returns true if the custom map was loaded successfully - */ - bool loadMapCustom(const std::string& identifier, bool loadHouses, bool loadMonsters, bool loadNpcs); + */ + bool loadMapCustom(const std::string &identifier, bool loadHouses, bool loadMonsters, bool loadNpcs); /** - * Save a map. - * \returns true if the map was saved successfully - */ + * Save a map. + * \returns true if the map was saved successfully + */ static bool save(); /** - * Get a single tile. - * \returns A pointer to that tile. - */ + * Get a single tile. + * \returns A pointer to that tile. + */ Tile* getTile(uint16_t x, uint16_t y, uint8_t z) const; - Tile* getTile(const Position& pos) const { + Tile* getTile(const Position &pos) const { return getTile(pos.x, pos.y, pos.z); } /** - * Set a single tile. - */ + * Set a single tile. + */ void setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile); - void setTile(const Position& pos, Tile* newTile) { + void setTile(const Position &pos, Tile* newTile) { setTile(pos.x, pos.y, pos.z, newTile); } /** - * Place a creature on the map - * \param centerPos The position to place the creature - * \param creature Creature to place on the map - * \param extendedPos If true, the creature will in first-hand be placed 2 tiles away - * \param forceLogin If true, placing the creature will not fail becase of obstacles (creatures/chests) - */ - bool placeCreature(const Position& centerPos, Creature* creature, bool extendedPos = false, bool forceLogin = false); + * Place a creature on the map + * \param centerPos The position to place the creature + * \param creature Creature to place on the map + * \param extendedPos If true, the creature will in first-hand be placed 2 tiles away + * \param forceLogin If true, placing the creature will not fail becase of obstacles (creatures/chests) + */ + bool placeCreature(const Position ¢erPos, Creature* creature, bool extendedPos = false, bool forceLogin = false); - void moveCreature(Creature& creature, Tile& newTile, bool forceTeleport = false); + void moveCreature(Creature &creature, Tile &newTile, bool forceTeleport = false); - void getSpectators(SpectatorHashSet& spectators, const Position& centerPos, bool multifloor = false, bool onlyPlayers = false, - int32_t minRangeX = 0, int32_t maxRangeX = 0, - int32_t minRangeY = 0, int32_t maxRangeY = 0); + void getSpectators(SpectatorHashSet &spectators, const Position ¢erPos, bool multifloor = false, bool onlyPlayers = false, int32_t minRangeX = 0, int32_t maxRangeX = 0, int32_t minRangeY = 0, int32_t maxRangeY = 0); void clearSpectatorCache(); /** - * Checks if you can throw an object to that position - * \param fromPos from Source point - * \param toPos Destination point - * \param rangex maximum allowed range horizontially - * \param rangey maximum allowed range vertically - * \param checkLineOfSight checks if there is any blocking objects in the way - * \returns The result if you can throw there or not - */ - bool canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight = true, - int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY) const; + * Checks if you can throw an object to that position + * \param fromPos from Source point + * \param toPos Destination point + * \param rangex maximum allowed range horizontially + * \param rangey maximum allowed range vertically + * \param checkLineOfSight checks if there is any blocking objects in the way + * \returns The result if you can throw there or not + */ + bool canThrowObjectTo(const Position &fromPos, const Position &toPos, bool checkLineOfSight = true, int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY) const; /** - * Checks if path is clear from fromPos to toPos - * Notice: This only checks a straight line if the path is clear, for path finding use getPathTo. - * \param fromPos from Source point - * \param toPos Destination point - * \param floorCheck if true then view is not clear if fromPos.z is not the same as toPos.z - * \returns The result if there is no obstacles - */ - bool isSightClear(const Position& fromPos, const Position& toPos, bool floorCheck) const; - bool checkSightLine(const Position& fromPos, const Position& toPos) const; + * Checks if path is clear from fromPos to toPos + * Notice: This only checks a straight line if the path is clear, for path finding use getPathTo. + * \param fromPos from Source point + * \param toPos Destination point + * \param floorCheck if true then view is not clear if fromPos.z is not the same as toPos.z + * \returns The result if there is no obstacles + */ + bool isSightClear(const Position &fromPos, const Position &toPos, bool floorCheck) const; + bool checkSightLine(const Position &fromPos, const Position &toPos) const; - const Tile* canWalkTo(const Creature& creature, const Position& pos) const; + const Tile* canWalkTo(const Creature &creature, const Position &pos) const; - bool getPathMatching(const Creature& creature, std::forward_list& dirList, - const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const; + bool getPathMatching(const Creature &creature, std::forward_list &dirList, const FrozenPathingConditionCall &pathCondition, const FindPathParams &fpp) const; - bool getPathMatching(const Position& startPos, std::forward_list& dirList, - const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const; + bool getPathMatching(const Position &startPos, std::forward_list &dirList, const FrozenPathingConditionCall &pathCondition, const FindPathParams &fpp) const; std::map waypoints; @@ -282,6 +274,7 @@ class Map SpawnsMonster spawnsMonsterCustom; SpawnsNpc spawnsNpcCustom; Houses housesCustom; + private: SpectatorCache spectatorCache; SpectatorCache playersSpectatorCache; @@ -296,14 +289,10 @@ class Map uint32_t height = 0; // Actually scans the map for spectators - void getSpectatorsInternal(SpectatorHashSet& spectators, const Position& centerPos, - int32_t minRangeX, int32_t maxRangeX, - int32_t minRangeY, int32_t maxRangeY, - int32_t minRangeZ, int32_t maxRangeZ, - bool onlyPlayers) const; + void getSpectatorsInternal(SpectatorHashSet &spectators, const Position ¢erPos, int32_t minRangeX, int32_t maxRangeX, int32_t minRangeY, int32_t maxRangeY, int32_t minRangeZ, int32_t maxRangeZ, bool onlyPlayers) const; friend class Game; friend class IOMap; }; -#endif // SRC_MAP_MAP_H_ +#endif // SRC_MAP_MAP_H_ diff --git a/src/map/map_definitions.hpp b/src/map/map_definitions.hpp index 47735c1bd31..5a22285f6fb 100644 --- a/src/map/map_definitions.hpp +++ b/src/map/map_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_MAP_MAP_DEFINITIONS_HPP_ #define SRC_MAP_MAP_DEFINITIONS_HPP_ @@ -31,4 +31,4 @@ enum RentPeriod_t { RENTPERIOD_NEVER, }; -#endif // SRC_MAP_MAP_DEFINITIONS_HPP_ +#endif // SRC_MAP_MAP_DEFINITIONS_HPP_ diff --git a/src/map/town.h b/src/map/town.h index 7ad857463fd..4df7213c987 100644 --- a/src/map/town.h +++ b/src/map/town.h @@ -5,22 +5,22 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_MAP_TOWN_H_ #define SRC_MAP_TOWN_H_ #include "game/movement/position.h" -class Town -{ +class Town { public: - explicit Town(uint32_t initId) : id(initId) {} + explicit Town(uint32_t initId) : + id(initId) { } - const Position& getTemplePosition() const { + const Position &getTemplePosition() const { return templePosition; } - const std::string& getName() const { + const std::string &getName() const { return name; } @@ -42,26 +42,25 @@ class Town using TownMap = std::map; -class Towns -{ +class Towns { public: Towns() = default; ~Towns() { - for (const auto& it : townMap) { + for (const auto &it : townMap) { delete it.second; } } // non-copyable - Towns(const Towns&) = delete; - Towns& operator=(const Towns&) = delete; + Towns(const Towns &) = delete; + Towns &operator=(const Towns &) = delete; bool addTown(uint32_t townId, Town* town) { return townMap.emplace(townId, town).second; } - Town* getTown(const std::string& townName) const { - for (const auto& it : townMap) { + Town* getTown(const std::string &townName) const { + for (const auto &it : townMap) { if (strcasecmp(townName.c_str(), it.second->getName().c_str()) == 0) { return it.second; } @@ -77,7 +76,7 @@ class Towns return it->second; } - const TownMap& getTowns() const { + const TownMap &getTowns() const { return townMap; } @@ -85,4 +84,4 @@ class Towns TownMap townMap; }; -#endif // SRC_MAP_TOWN_H_ +#endif // SRC_MAP_TOWN_H_ diff --git a/src/otserv.cpp b/src/otserv.cpp index 1e43e05f8b8..5f389d00ae2 100644 --- a/src/otserv.cpp +++ b/src/otserv.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -50,26 +50,26 @@ bool g_loaderDone = false; * To activate/desactivate window; * \param MF_GRAYED Disable the "x" (force close) button * \param MF_ENABLED Enable the "x" (force close) button -*/ + */ void toggleForceCloseButton() { - #ifdef OS_WINDOWS +#ifdef OS_WINDOWS HWND hwnd = GetConsoleWindow(); HMENU hmenu = GetSystemMenu(hwnd, FALSE); EnableMenuItem(hmenu, SC_CLOSE, MF_GRAYED); - #endif +#endif } std::string getCompiler() { std::string compiler; - #if defined(__clang__) - return compiler = fmt::format("Clang++ {}.{}.{}", __clang_major__, __clang_minor__, __clang_patchlevel__); - #elif defined(_MSC_VER) - return compiler = fmt::format("Microsoft Visual Studio {}", _MSC_VER); - #elif defined(__GNUC__) - return compiler = fmt::format("G++ {}.{}.{}", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); - #else - return compiler = "unknown"; - #endif +#if defined(__clang__) + return compiler = fmt::format("Clang++ {}.{}.{}", __clang_major__, __clang_minor__, __clang_patchlevel__); +#elif defined(_MSC_VER) + return compiler = fmt::format("Microsoft Visual Studio {}", _MSC_VER); +#elif defined(__GNUC__) + return compiler = fmt::format("G++ {}.{}.{}", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); +#else + return compiler = "unknown"; +#endif } void startupErrorMessage() { @@ -84,7 +84,7 @@ void mainLoader(int argc, char* argv[], ServiceManager* servicer); void badAllocationHandler() { // Use functions that only use stack allocation SPDLOG_ERROR("Allocation failed, server out of memory, " - "decrease the size of your map or compile in 64 bits mode"); + "decrease the size of your map or compile in 64 bits mode"); getchar(); exit(-1); } @@ -109,8 +109,7 @@ void loadModules() { startupErrorMessage(); } - SPDLOG_INFO("Server protocol: {}.{}", - CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER); + SPDLOG_INFO("Server protocol: {}.{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER); const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113"); const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101"); @@ -120,7 +119,7 @@ void loadModules() { SPDLOG_ERROR("File key.pem not found or have problem on loading... Setting standard rsa key\n"); g_RSA().setKey(p, q); } - } catch (std::system_error const& e) { + } catch (const std::system_error &e) { SPDLOG_ERROR("Loading RSA Key from key.pem failed with error: {}\n", e.what()); SPDLOG_ERROR("Switching to a default key..."); g_RSA().setKey(p, q); @@ -138,7 +137,8 @@ void loadModules() { SPDLOG_INFO("Running database manager..."); if (!DatabaseManager::isDatabaseSetup()) { SPDLOG_ERROR("The database you have specified in {} is empty, " - "please import the schema.sql to your database.", g_configManager().getConfigFileLua()); + "please import the schema.sql to your database.", + g_configManager().getConfigFileLua()); startupErrorMessage(); } @@ -146,52 +146,36 @@ void loadModules() { DatabaseManager::updateDatabase(); if (g_configManager().getBoolean(OPTIMIZE_DATABASE) - && !DatabaseManager::optimizeTables()) { + && !DatabaseManager::optimizeTables()) { SPDLOG_INFO("No tables were optimized"); } // Core start auto coreFolder = g_configManager().getString(CORE_DIRECTORY); - modulesLoadHelper((g_game().loadAppearanceProtobuf(coreFolder + "/items/appearances.dat") == ERROR_NONE), - "appearances.dat"); - modulesLoadHelper(Item::items.loadFromXml(), - "items.xml"); + modulesLoadHelper((g_game().loadAppearanceProtobuf(coreFolder + "/items/appearances.dat") == ERROR_NONE), "appearances.dat"); + modulesLoadHelper(Item::items.loadFromXml(), "items.xml"); auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); SPDLOG_INFO("Loading core scripts on folder: {}/", coreFolder); - modulesLoadHelper((g_luaEnvironment.loadFile(coreFolder + "/core.lua", "core.lua") == 0), - "core.lua"); - modulesLoadHelper((g_luaEnvironment.loadFile(coreFolder + "/scripts/talkactions.lua", "talkactions.lua") == 0), - "scripts/talkactions.lua"); - modulesLoadHelper(g_vocations().loadFromXml(), - "XML/vocations.xml"); - modulesLoadHelper(g_eventsScheduler().loadScheduleEventFromXml(), - "XML/events.xml"); - modulesLoadHelper(Outfits::getInstance().loadFromXml(), - "XML/outfits.xml"); - modulesLoadHelper(Familiars::getInstance().loadFromXml(), - "XML/familiars.xml"); - modulesLoadHelper(g_imbuements().loadFromXml(), - "XML/imbuements.xml"); - modulesLoadHelper(g_modules().loadFromXml(), - "modules/modules.xml"); - modulesLoadHelper(g_events().loadFromXml(), - "events/events.xml"); - modulesLoadHelper((g_npcs().load(true, false)), - "npclib"); + modulesLoadHelper((g_luaEnvironment.loadFile(coreFolder + "/core.lua", "core.lua") == 0), "core.lua"); + modulesLoadHelper((g_luaEnvironment.loadFile(coreFolder + "/scripts/talkactions.lua", "talkactions.lua") == 0), "scripts/talkactions.lua"); + modulesLoadHelper(g_vocations().loadFromXml(), "XML/vocations.xml"); + modulesLoadHelper(g_eventsScheduler().loadScheduleEventFromXml(), "XML/events.xml"); + modulesLoadHelper(Outfits::getInstance().loadFromXml(), "XML/outfits.xml"); + modulesLoadHelper(Familiars::getInstance().loadFromXml(), "XML/familiars.xml"); + modulesLoadHelper(g_imbuements().loadFromXml(), "XML/imbuements.xml"); + modulesLoadHelper(g_modules().loadFromXml(), "modules/modules.xml"); + modulesLoadHelper(g_events().loadFromXml(), "events/events.xml"); + modulesLoadHelper((g_npcs().load(true, false)), "npclib"); SPDLOG_INFO("Loading datapack scripts on folder: {}/", datapackName); // Load libs first - modulesLoadHelper(g_scripts().loadScripts("scripts/lib", true, false), - "scripts/libs"); + modulesLoadHelper(g_scripts().loadScripts("scripts/lib", true, false), "scripts/libs"); // Load scripts - modulesLoadHelper(g_scripts().loadScripts("scripts", false, false), - "scripts"); + modulesLoadHelper(g_scripts().loadScripts("scripts", false, false), "scripts"); // Load monsters - modulesLoadHelper(g_scripts().loadScripts("monster", false, false), - "monster"); - modulesLoadHelper((g_npcs().load(false, true)), - "npc"); + modulesLoadHelper(g_scripts().loadScripts("monster", false, false), "monster"); + modulesLoadHelper((g_npcs().load(false, true)), "npc"); g_game().loadBoostedCreature(); g_ioprey().InitializeTaskHuntOptions(); @@ -199,12 +183,12 @@ void loadModules() { #ifndef UNIT_TESTING int main(int argc, char* argv[]) { -#ifdef DEBUG_LOG + #ifdef DEBUG_LOG SPDLOG_DEBUG("[CANARY] SPDLOG LOG DEBUG ENABLED"); spdlog::set_pattern("[%Y-%d-%m %H:%M:%S.%e] [file %@] [func %!] [thread %t] [%^%l%$] %v "); -#else + #else spdlog::set_pattern("[%Y-%d-%m %H:%M:%S.%e] [%^%l%$] %v "); -#endif + #endif // Toggle force close button enabled/disabled toggleForceCloseButton(); @@ -216,16 +200,14 @@ int main(int argc, char* argv[]) { g_dispatcher().start(); g_scheduler().start(); - g_dispatcher().addTask(createTask(std::bind(mainLoader, argc, argv, - &serviceManager))); + g_dispatcher().addTask(createTask(std::bind(mainLoader, argc, argv, &serviceManager))); g_loaderSignal.wait(g_loaderUniqueLock, [] { return g_loaderDone; }); if (serviceManager.is_running()) { - SPDLOG_INFO("{} {}", g_configManager().getString(SERVER_NAME), - "server online!"); + SPDLOG_INFO("{} {}", g_configManager().getString(SERVER_NAME), "server online!"); serviceManager.run(); } else { SPDLOG_ERROR("No services running. The server is NOT online!"); @@ -250,8 +232,7 @@ void mainLoader(int, char*[], ServiceManager* services) { SetConsoleTitle(STATUS_SERVER_NAME); #endif #if defined(GIT_RETRIEVED_STATE) && GIT_RETRIEVED_STATE - SPDLOG_INFO("{} - Version [{}] dated [{}]", - STATUS_SERVER_NAME, STATUS_SERVER_VERSION, GIT_COMMIT_DATE_ISO8601); + SPDLOG_INFO("{} - Version [{}] dated [{}]", STATUS_SERVER_NAME, STATUS_SERVER_VERSION, GIT_COMMIT_DATE_ISO8601); #if GIT_IS_DIRTY SPDLOG_WARN("DIRTY - NOT OFFICIAL RELEASE"); #endif @@ -260,15 +241,15 @@ void mainLoader(int, char*[], ServiceManager* services) { #endif std::string platform; - #if defined(__amd64__) || defined(_M_X64) - platform = "x64"; - #elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) - platform = "x86"; - #elif defined(__arm__) - platform = "ARM"; - #else - platform = "unknown"; - #endif +#if defined(__amd64__) || defined(_M_X64) + platform = "x64"; +#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) + platform = "x86"; +#elif defined(__arm__) + platform = "ARM"; +#else + platform = "unknown"; +#endif SPDLOG_INFO("Compiled with {}, on {} {}, for platform {}\n", getCompiler(), __DATE__, __TIME__, platform); @@ -278,7 +259,7 @@ void mainLoader(int, char*[], ServiceManager* services) { SPDLOG_INFO("A server developed by: {}", STATUS_SERVER_DEVELOPERS); SPDLOG_INFO("Visit our website for updates, support, and resources: " - "https://docs.opentibiabr.org/"); + "https://docs.opentibiabr.org/"); std::string configName = "config.lua"; // Check if config or config.dist exist @@ -302,7 +283,7 @@ void mainLoader(int, char*[], ServiceManager* services) { loadModules(); #ifdef _WIN32 - const std::string& defaultPriority = g_configManager().getString(DEFAULT_PRIORITY); + const std::string &defaultPriority = g_configManager().getString(DEFAULT_PRIORITY); if (strcasecmp(defaultPriority.c_str(), "high") == 0) { SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); } else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) { @@ -319,7 +300,8 @@ void mainLoader(int, char*[], ServiceManager* services) { g_game().setWorldType(WORLD_TYPE_PVP_ENFORCED); } else { SPDLOG_ERROR("Unknown world type: {}, valid world types are: pvp, no-pvp " - "and pvp-enforced", g_configManager().getString(WORLD_TYPE)); + "and pvp-enforced", + g_configManager().getString(WORLD_TYPE)); startupErrorMessage(); } @@ -374,8 +356,8 @@ void mainLoader(int, char*[], ServiceManager* services) { #ifndef _WIN32 if (getuid() == 0 || geteuid() == 0) { SPDLOG_WARN("{} has been executed as root user, " - "please consider running it as a normal user", - STATUS_SERVER_NAME); + "please consider running it as a normal user", + STATUS_SERVER_NAME); } #endif diff --git a/src/pch.hpp b/src/pch.hpp index 1f6893b67dd..98fa512cede 100644 --- a/src/pch.hpp +++ b/src/pch.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_PCH_HPP_ #define SRC_PCH_HPP_ @@ -48,4 +48,4 @@ #include #include -#endif // SRC_PCH_HPP_ +#endif // SRC_PCH_HPP_ diff --git a/src/security/rsa.cpp b/src/security/rsa.cpp index 8daae5fa1d6..44f31d80db5 100644 --- a/src/security/rsa.cpp +++ b/src/security/rsa.cpp @@ -5,22 +5,20 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "security/rsa.h" -RSA::RSA() -{ +RSA::RSA() { mpz_init(n); mpz_init2(d, 1024); } RSA::~RSA() = default; -void RSA::setKey(const char* pString, const char* qString, int base/* = 10*/) -{ +void RSA::setKey(const char* pString, const char* qString, int base /* = 10*/) { mpz_t p; mpz_t q; mpz_t e; @@ -63,8 +61,7 @@ void RSA::setKey(const char* pString, const char* qString, int base/* = 10*/) mpz_clear(e); } -void RSA::decrypt(char* msg) const -{ +void RSA::decrypt(char* msg) const { mpz_t c; mpz_t m; mpz_init2(c, 1024); @@ -83,8 +80,7 @@ void RSA::decrypt(char* msg) const mpz_clear(m); } -std::string RSA::base64Decrypt(const std::string& input) const -{ +std::string RSA::base64Decrypt(const std::string &input) const { auto posOfCharacter = [](const uint8_t chr) -> uint16_t { if (chr >= 'A' && chr <= 'Z') { return chr - 'A'; @@ -132,16 +128,14 @@ static const std::string footer_old = "-----END RSA PRIVATE KEY-----"; static const std::string header_new = "-----BEGIN PRIVATE KEY-----"; static const std::string footer_new = "-----END PRIVATE KEY-----"; -enum -{ +enum { CRYPT_RSA_ASN1_SEQUENCE = 48, CRYPT_RSA_ASN1_INTEGER = 2, CRYPT_RSA_ASN1_OBJECT = 6, CRYPT_RSA_ASN1_BITSTRING = 3 }; -uint16_t RSA::decodeLength(char*& pos) const -{ +uint16_t RSA::decodeLength(char*&pos) const { std::string buffer; auto length = static_cast(static_cast(*pos++)); if (length & 0x80) { @@ -152,36 +146,33 @@ uint16_t RSA::decodeLength(char*& pos) const } buffer[0] = buffer[1] = buffer[2] = buffer[3] = 0; switch (length) { - case 4: - buffer[3] = static_cast(*pos++); - case 3: - buffer[2] = static_cast(*pos++); - case 2: - buffer[1] = static_cast(*pos++); - case 1: - buffer[0] = static_cast(*pos++); - default: - break; + case 4: + buffer[3] = static_cast(*pos++); + case 3: + buffer[2] = static_cast(*pos++); + case 2: + buffer[1] = static_cast(*pos++); + case 1: + buffer[0] = static_cast(*pos++); + default: + break; } std::memcpy(&length, buffer.data(), sizeof(length)); } return length; } -void RSA::readHexString(char*& pos, uint16_t length, std::string& output) const -{ +void RSA::readHexString(char*&pos, uint16_t length, std::string &output) const { output.reserve(static_cast(length) * 2); - for (uint16_t i = 0; i < length; ++i) - { + for (uint16_t i = 0; i < length; ++i) { auto hex = static_cast(*pos++); output.push_back("0123456789ABCDEF"[(hex >> 4) & 15]); output.push_back("0123456789ABCDEF"[hex & 15]); } } -bool RSA::loadPEM(const std::string& filename) -{ - std::ifstream file{ filename }; +bool RSA::loadPEM(const std::string &filename) { + std::ifstream file { filename }; if (!file.is_open()) { return false; } @@ -189,7 +180,8 @@ bool RSA::loadPEM(const std::string& filename) std::string key; std::string pString; std::string qString; - for (std::string line; std::getline(file, line); key.append(line)); + for (std::string line; std::getline(file, line); key.append(line)) + ; if (key.compare(0, header_old.size(), header_old) == 0) { if (key.compare(key.size() - footer_old.size(), footer_old.size(), footer_old) != 0) { @@ -257,7 +249,7 @@ bool RSA::loadPEM(const std::string& filename) length = decodeLength(pos); pos += length; if (length != 1 || static_cast(*pos) > 2) { - //public key - we don't have any interest in it + // public key - we don't have any interest in it SPDLOG_ERROR("[RSA::loadPEM] - Invalid unsupported RSA key"); return false; } diff --git a/src/security/rsa.h b/src/security/rsa.h index d5f173166d4..683a1062ef9 100644 --- a/src/security/rsa.h +++ b/src/security/rsa.h @@ -5,23 +5,21 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SECURITY_RSA_H_ #define SRC_SECURITY_RSA_H_ - -class RSA -{ +class RSA { public: RSA(); ~RSA(); // Singleton - ensures we don't accidentally copy it - RSA(RSA const&) = delete; - void operator=(RSA const&) = delete; + RSA(RSA const &) = delete; + void operator=(RSA const &) = delete; - static RSA& getInstance() { + static RSA &getInstance() { // Guaranteed to be destroyed static RSA instance; // Instantiated on first use @@ -31,10 +29,10 @@ class RSA void setKey(const char* pString, const char* qString, int base = 10); void decrypt(char* msg) const; - std::string base64Decrypt(const std::string& input) const; - uint16_t decodeLength(char*& pos) const; - void readHexString(char*& pos, uint16_t length, std::string& output) const; - bool loadPEM(const std::string& filename); + std::string base64Decrypt(const std::string &input) const; + uint16_t decodeLength(char*&pos) const; + void readHexString(char*&pos, uint16_t length, std::string &output) const; + bool loadPEM(const std::string &filename); private: mpz_t n; @@ -43,4 +41,4 @@ class RSA constexpr auto g_RSA = &RSA::getInstance; -#endif // SRC_SECURITY_RSA_H_ +#endif // SRC_SECURITY_RSA_H_ diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index e8cec67e85a..4730dca5705 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,8 +16,7 @@ #include "game/scheduling/scheduler.h" #include "server/server.h" -Connection_ptr ConnectionManager::createConnection(asio::io_service& io_service, ConstServicePort_ptr servicePort) -{ +Connection_ptr ConnectionManager::createConnection(asio::io_service &io_service, ConstServicePort_ptr servicePort) { std::lock_guard lockClass(connectionManagerLock); auto connection = std::make_shared(io_service, servicePort); @@ -25,22 +24,20 @@ Connection_ptr ConnectionManager::createConnection(asio::io_service& io_service, return connection; } -void ConnectionManager::releaseConnection(const Connection_ptr& connection) -{ +void ConnectionManager::releaseConnection(const Connection_ptr &connection) { std::lock_guard lockClass(connectionManagerLock); connections.erase(connection); } -void ConnectionManager::closeAll() -{ +void ConnectionManager::closeAll() { std::lock_guard lockClass(connectionManagerLock); - for (const auto& connection : connections) { + for (const auto &connection : connections) { try { std::error_code error; connection->socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); - } catch (const std::system_error& systemError) { + } catch (const std::system_error &systemError) { SPDLOG_ERROR("[ConnectionManager::closeAll] - Failed to close connection, system error code {}", systemError.what()); } } @@ -49,19 +46,17 @@ void ConnectionManager::closeAll() // Connection // Constructor -Connection::Connection(asio::io_service& initIoService, ConstServicePort_ptr initservicePort) : +Connection::Connection(asio::io_service &initIoService, ConstServicePort_ptr initservicePort) : readTimer(initIoService), writeTimer(initIoService), service_port(std::move(initservicePort)), - socket(initIoService) -{ + socket(initIoService) { timeConnected = time(nullptr); } // Constructor end -void Connection::close(bool force) -{ - //any thread +void Connection::close(bool force) { + // any thread ConnectionManager::getInstance().releaseConnection(shared_from_this()); std::lock_guard lockClass(connectionLock); @@ -72,18 +67,18 @@ void Connection::close(bool force) if (protocol) { g_dispatcher().addTask( - createSchedulerTask(1000, std::bind_front(&Protocol::release, protocol))); + createSchedulerTask(1000, std::bind_front(&Protocol::release, protocol)) + ); } if (messageQueue.empty() || force) { closeSocket(); } else { - //will be closed by the destructor or onWriteOperation + // will be closed by the destructor or onWriteOperation } } -void Connection::closeSocket() -{ +void Connection::closeSocket() { if (socket.is_open()) { try { readTimer.cancel(); @@ -91,14 +86,13 @@ void Connection::closeSocket() std::error_code error; socket.shutdown(asio::ip::tcp::socket::shutdown_both, error); socket.close(error); - } catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::closeSocket] - error: {}", e.what()); } } } -void Connection::accept(Protocol_ptr protocolPtr) -{ +void Connection::accept(Protocol_ptr protocolPtr) { this->connectionState = CONNECTION_STATE_IDENTIFYING; this->protocol = protocolPtr; g_dispatcher().addTask(createSchedulerTask(1000, std::bind_front(&Protocol::onConnect, protocolPtr))); @@ -107,32 +101,26 @@ void Connection::accept(Protocol_ptr protocolPtr) accept(false); } -void Connection::accept(bool toggleParseHeader /* = true */) -{ +void Connection::accept(bool toggleParseHeader /* = true */) { try { readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); readTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr(shared_from_this()), std::placeholders::_1)); - + // If toggleParseHeader is true, execute the parseHeader, if not, execute parseProxyIdentification if (toggleParseHeader) { // Read size of the first packet - asio::async_read(socket, - asio::buffer(msg.getBuffer(), HEADER_LENGTH), - std::bind(&Connection::parseHeader, shared_from_this(), std::placeholders::_1)); + asio::async_read(socket, asio::buffer(msg.getBuffer(), HEADER_LENGTH), std::bind(&Connection::parseHeader, shared_from_this(), std::placeholders::_1)); } else { // Read header bytes to identify if it is proxy identification - asio::async_read(socket, - asio::buffer(msg.getBuffer(), HEADER_LENGTH), - std::bind(&Connection::parseProxyIdentification, shared_from_this(), std::placeholders::_1)); + asio::async_read(socket, asio::buffer(msg.getBuffer(), HEADER_LENGTH), std::bind(&Connection::parseProxyIdentification, shared_from_this(), std::placeholders::_1)); } - } catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::accept] - error: {}", e.what()); close(FORCE_CLOSE); } } -void Connection::parseProxyIdentification(const std::error_code& error) -{ +void Connection::parseProxyIdentification(const std::error_code &error) { std::lock_guard lockClass(connectionLock); readTimer.cancel(); @@ -148,12 +136,12 @@ void Connection::parseProxyIdentification(const std::error_code& error) std::string serverName = g_configManager().getString(SERVER_NAME) + "\n"; if (connectionState == CONNECTION_STATE_IDENTIFYING) { if (msgBuffer[1] == 0x00 || strncasecmp(charData, &serverName[0], 2) != 0) { - //Probably not proxy identification so let's try standard parsing method + // Probably not proxy identification so let's try standard parsing method connectionState = CONNECTION_STATE_OPEN; parseHeader(error); return; } else { - size_t remainder = serverName.length()-2; + size_t remainder = serverName.length() - 2; if (remainder > 0) { connectionState = CONNECTION_STATE_READINGS; try { @@ -161,11 +149,8 @@ void Connection::parseProxyIdentification(const std::error_code& error) readTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr(shared_from_this()), std::placeholders::_1)); // Read the remainder of proxy identification - asio::async_read(socket, - asio::buffer(msg.getBuffer(), remainder), - std::bind(&Connection::parseProxyIdentification, shared_from_this(), std::placeholders::_1)); - } - catch (const std::system_error& e) { + asio::async_read(socket, asio::buffer(msg.getBuffer(), remainder), std::bind(&Connection::parseProxyIdentification, shared_from_this(), std::placeholders::_1)); + } catch (const std::system_error &e) { SPDLOG_ERROR("Connection::parseProxyIdentification] - error: {}", e.what()); close(FORCE_CLOSE); } @@ -188,8 +173,7 @@ void Connection::parseProxyIdentification(const std::error_code& error) accept(true); } -void Connection::parseHeader(const std::error_code& error) -{ +void Connection::parseHeader(const std::error_code &error) { std::lock_guard lockClass(connectionLock); readTimer.cancel(); @@ -224,17 +208,14 @@ void Connection::parseHeader(const std::error_code& error) // Read packet content msg.setLength(size + HEADER_LENGTH); - asio::async_read(socket, - asio::buffer(msg.getBodyBuffer(), size), - std::bind(&Connection::parsePacket, shared_from_this(), std::placeholders::_1)); - } catch (const std::system_error& e) { + asio::async_read(socket, asio::buffer(msg.getBodyBuffer(), size), std::bind(&Connection::parsePacket, shared_from_this(), std::placeholders::_1)); + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::parseHeader] - error: {}", e.what()); close(FORCE_CLOSE); } } -void Connection::parsePacket(const std::error_code& error) -{ +void Connection::parsePacket(const std::error_code &error) { std::lock_guard lockClass(connectionLock); readTimer.cancel(); @@ -251,11 +232,10 @@ void Connection::parsePacket(const std::error_code& error) receivedFirst = true; if (!protocol) { - //Check packet checksum + // Check packet checksum uint32_t checksum; if (int32_t len = msg.getLength() - msg.getBufferPosition() - CHECKSUM_LENGTH; - len > 0) - { + len > 0) { checksum = adlerChecksum(msg.getBuffer() + msg.getBufferPosition() + CHECKSUM_LENGTH, len); } else { checksum = 0; @@ -295,27 +275,25 @@ void Connection::parsePacket(const std::error_code& error) // Wait to the next packet asio::async_read(socket, asio::buffer(msg.getBuffer(), HEADER_LENGTH), std::bind(&Connection::parseHeader, shared_from_this(), std::placeholders::_1)); } - } catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::parsePacket] - error: {}", e.what()); close(FORCE_CLOSE); } } -void Connection::resumeWork() -{ +void Connection::resumeWork() { std::lock_guard lockClass(connectionLock); try { // Wait to the next packet asio::async_read(socket, asio::buffer(msg.getBuffer(), HEADER_LENGTH), std::bind(&Connection::parseHeader, shared_from_this(), std::placeholders::_1)); - } catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::resumeWork] - error: {}", e.what()); close(FORCE_CLOSE); } } -void Connection::send(const OutputMessage_ptr& outputMessage) -{ +void Connection::send(const OutputMessage_ptr &outputMessage) { std::lock_guard lockClass(connectionLock); if (connectionState == CONNECTION_STATE_CLOSED) { return; @@ -327,7 +305,7 @@ void Connection::send(const OutputMessage_ptr& outputMessage) // Make asio thread handle xtea encryption instead of dispatcher try { asio::post(socket.get_executor(), std::bind(&Connection::internalWorker, shared_from_this())); - } catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::send] - error: {}", e.what()); messageQueue.clear(); close(FORCE_CLOSE); @@ -335,11 +313,10 @@ void Connection::send(const OutputMessage_ptr& outputMessage) } } -void Connection::internalWorker() -{ +void Connection::internalWorker() { std::unique_lock lockClass(connectionLock); if (!messageQueue.empty()) { - const OutputMessage_ptr& outputMessage = messageQueue.front(); + const OutputMessage_ptr &outputMessage = messageQueue.front(); lockClass.unlock(); protocol->onSendMessage(outputMessage); lockClass.lock(); @@ -349,8 +326,7 @@ void Connection::internalWorker() } } -uint32_t Connection::getIP() -{ +uint32_t Connection::getIP() { std::lock_guard lockClass(connectionLock); // IP-address is expressed in network byte order @@ -363,22 +339,18 @@ uint32_t Connection::getIP() return htonl(endpoint.address().to_v4().to_ulong()); } -void Connection::internalSend(const OutputMessage_ptr& outputMessage) -{ +void Connection::internalSend(const OutputMessage_ptr &outputMessage) { try { writeTimer.expires_from_now(std::chrono::seconds(CONNECTION_WRITE_TIMEOUT)); writeTimer.async_wait(std::bind(&Connection::handleTimeout, std::weak_ptr(shared_from_this()), std::placeholders::_1)); - asio::async_write(socket, - asio::buffer(outputMessage->getOutputBuffer(), outputMessage->getLength()), - std::bind(&Connection::onWriteOperation, shared_from_this(), std::placeholders::_1)); - } catch (const std::system_error& e) { + asio::async_write(socket, asio::buffer(outputMessage->getOutputBuffer(), outputMessage->getLength()), std::bind(&Connection::onWriteOperation, shared_from_this(), std::placeholders::_1)); + } catch (const std::system_error &e) { SPDLOG_ERROR("[Connection::internalSend] - error: {}", e.what()); } } -void Connection::onWriteOperation(const std::error_code& error) -{ +void Connection::onWriteOperation(const std::error_code &error) { std::unique_lock lockClass(connectionLock); writeTimer.cancel(); messageQueue.pop_front(); @@ -390,7 +362,7 @@ void Connection::onWriteOperation(const std::error_code& error) } if (!messageQueue.empty()) { - const OutputMessage_ptr& outputMessage = messageQueue.front(); + const OutputMessage_ptr &outputMessage = messageQueue.front(); lockClass.unlock(); protocol->onSendMessage(outputMessage); lockClass.lock(); @@ -400,10 +372,9 @@ void Connection::onWriteOperation(const std::error_code& error) } } -void Connection::handleTimeout(ConnectionWeak_ptr connectionWeak, const std::error_code& error) -{ +void Connection::handleTimeout(ConnectionWeak_ptr connectionWeak, const std::error_code &error) { if (error == asio::error::operation_aborted) { - //The timer has been manually cancelled + // The timer has been manually cancelled return; } diff --git a/src/server/network/connection/connection.h b/src/server/network/connection/connection.h index 59c7b8197b5..2b9e28c3730 100644 --- a/src/server/network/connection/connection.h +++ b/src/server/network/connection/connection.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_CONNECTION_CONNECTION_H_ #define SRC_SERVER_NETWORK_CONNECTION_CONNECTION_H_ @@ -29,16 +29,15 @@ class ServicePort; using ServicePort_ptr = std::shared_ptr; using ConstServicePort_ptr = std::shared_ptr; -class ConnectionManager -{ +class ConnectionManager { public: - static ConnectionManager& getInstance() { + static ConnectionManager &getInstance() { static ConnectionManager instance; return instance; } - Connection_ptr createConnection(asio::io_service& io_service, ConstServicePort_ptr servicePort); - void releaseConnection(const Connection_ptr& connection); + Connection_ptr createConnection(asio::io_service &io_service, ConstServicePort_ptr servicePort); + void releaseConnection(const Connection_ptr &connection); void closeAll(); private: @@ -48,20 +47,18 @@ class ConnectionManager std::mutex connectionManagerLock; }; -class Connection : public std::enable_shared_from_this -{ +class Connection : public std::enable_shared_from_this { public: // Constructor - Connection(asio::io_service& initIoService, - ConstServicePort_ptr initservicePort); + Connection(asio::io_service &initIoService, ConstServicePort_ptr initservicePort); // Constructor end // Destructor ~Connection() = default; // Singleton - ensures we don't accidentally copy it - Connection(const Connection&) = delete; - Connection& operator=(const Connection&) = delete; + Connection(const Connection &) = delete; + Connection &operator=(const Connection &) = delete; void close(bool force = false); // Used by protocols that require server to send first @@ -69,24 +66,24 @@ class Connection : public std::enable_shared_from_this void accept(bool toggleParseHeader = true); void resumeWork(); - void send(const OutputMessage_ptr& outputMessage); + void send(const OutputMessage_ptr &outputMessage); uint32_t getIP(); private: - void parseProxyIdentification(const std::error_code& error); - void parseHeader(const std::error_code& error); - void parsePacket(const std::error_code& error); + void parseProxyIdentification(const std::error_code &error); + void parseHeader(const std::error_code &error); + void parsePacket(const std::error_code &error); - void onWriteOperation(const std::error_code& error); + void onWriteOperation(const std::error_code &error); - static void handleTimeout(ConnectionWeak_ptr connectionWeak, const std::error_code& error); + static void handleTimeout(ConnectionWeak_ptr connectionWeak, const std::error_code &error); void closeSocket(); void internalWorker(); - void internalSend(const OutputMessage_ptr& outputMessage); + void internalSend(const OutputMessage_ptr &outputMessage); - asio::ip::tcp::socket& getSocket() { + asio::ip::tcp::socket &getSocket() { return socket; } @@ -114,4 +111,4 @@ class Connection : public std::enable_shared_from_this friend class ConnectionManager; }; -#endif // SRC_SERVER_NETWORK_CONNECTION_CONNECTION_H_ +#endif // SRC_SERVER_NETWORK_CONNECTION_CONNECTION_H_ diff --git a/src/server/network/message/networkmessage.cpp b/src/server/network/message/networkmessage.cpp index cb56af82335..cf4db43afc3 100644 --- a/src/server/network/message/networkmessage.cpp +++ b/src/server/network/message/networkmessage.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,15 +13,13 @@ #include "items/containers/container.h" #include "creatures/creature.h" -int32_t NetworkMessage::decodeHeader() -{ +int32_t NetworkMessage::decodeHeader() { int32_t newSize = buffer[0] | buffer[1] << 8; info.length = newSize; return info.length; } -std::string NetworkMessage::getString(uint16_t stringLen/* = 0*/) -{ +std::string NetworkMessage::getString(uint16_t stringLen /* = 0*/) { if (stringLen == 0) { stringLen = get(); } @@ -30,13 +28,12 @@ std::string NetworkMessage::getString(uint16_t stringLen/* = 0*/) return std::string(); } - char* v = reinterpret_cast(buffer) + info.position; //does not break strict aliasing + char* v = reinterpret_cast(buffer) + info.position; // does not break strict aliasing info.position += stringLen; return std::string(v, stringLen); } -Position NetworkMessage::getPosition() -{ +Position NetworkMessage::getPosition() { Position pos; pos.x = get(); pos.y = get(); @@ -44,8 +41,7 @@ Position NetworkMessage::getPosition() return pos; } -void NetworkMessage::addString(const std::string& value) -{ +void NetworkMessage::addString(const std::string &value) { size_t stringLen = value.length(); if (value.empty()) { SPDLOG_DEBUG("[NetworkMessage::addString] - Value string is empty"); @@ -65,14 +61,12 @@ void NetworkMessage::addString(const std::string& value) info.length += stringLen; } -void NetworkMessage::addDouble(double value, uint8_t precision/* = 2*/) -{ +void NetworkMessage::addDouble(double value, uint8_t precision /* = 2*/) { addByte(precision); add((value * std::pow(static_cast(10), precision)) + std::numeric_limits::max()); } -void NetworkMessage::addBytes(const char* bytes, size_t size) -{ +void NetworkMessage::addBytes(const char* bytes, size_t size) { if (bytes == nullptr) { SPDLOG_ERROR("[NetworkMessage::addBytes] - Bytes is nullptr"); return; @@ -91,20 +85,18 @@ void NetworkMessage::addBytes(const char* bytes, size_t size) info.length += size; } -void NetworkMessage::addPaddingBytes(size_t n) -{ - #define canAdd(size) ((size + info.position) < NETWORKMESSAGE_MAXSIZE) +void NetworkMessage::addPaddingBytes(size_t n) { +#define canAdd(size) ((size + info.position) < NETWORKMESSAGE_MAXSIZE) if (!canAdd(n)) { return; } - #undef canAdd +#undef canAdd memset(buffer + info.position, 0x33, n); info.length += n; } -void NetworkMessage::addPosition(const Position& pos) -{ +void NetworkMessage::addPosition(const Position &pos) { add(pos.x); add(pos.y); addByte(pos.z); diff --git a/src/server/network/message/networkmessage.h b/src/server/network/message/networkmessage.h index a5f5d822057..2a3dabb66b2 100644 --- a/src/server/network/message/networkmessage.h +++ b/src/server/network/message/networkmessage.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_MESSAGE_NETWORKMESSAGE_H_ #define SRC_SERVER_NETWORK_MESSAGE_NETWORKMESSAGE_H_ @@ -19,8 +19,7 @@ class Player; struct Position; class RSA; -class NetworkMessage -{ +class NetworkMessage { public: using MsgSize_t = uint16_t; // Headers: @@ -48,7 +47,7 @@ class NetworkMessage return buffer[--info.position]; } - template + template T get() { if (!canRead(sizeof(T))) { return 0; @@ -78,7 +77,7 @@ class NetworkMessage info.length++; } - template + template void add(T value) { if (!canAdd(sizeof(T))) { return; @@ -92,12 +91,12 @@ class NetworkMessage void addBytes(const char* bytes, size_t size); void addPaddingBytes(size_t n); - void addString(const std::string& value); + void addString(const std::string &value); void addDouble(double value, uint8_t precision = 2); // write functions for complex types - void addPosition(const Position& pos); + void addPosition(const Position &pos); MsgSize_t getLength() const { return info.length; @@ -152,9 +151,9 @@ class NetworkMessage } struct NetworkMessageInfo { - MsgSize_t length = 0; - MsgSize_t position = INITIAL_BUFFER_POSITION; - bool overrun = false; + MsgSize_t length = 0; + MsgSize_t position = INITIAL_BUFFER_POSITION; + bool overrun = false; }; NetworkMessageInfo info; diff --git a/src/server/network/message/outputmessage.cpp b/src/server/network/message/outputmessage.cpp index 958526dceea..4bd9ec8e0a1 100644 --- a/src/server/network/message/outputmessage.cpp +++ b/src/server/network/message/outputmessage.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -13,19 +13,17 @@ #include "server/network/protocol/protocol.h" #include "game/scheduling/scheduler.h" -const std::chrono::milliseconds OUTPUTMESSAGE_AUTOSEND_DELAY {10}; +const std::chrono::milliseconds OUTPUTMESSAGE_AUTOSEND_DELAY { 10 }; -void OutputMessagePool::scheduleSendAll() -{ +void OutputMessagePool::scheduleSendAll() { auto function = std::bind_front(&OutputMessagePool::sendAll, this); g_scheduler().addEvent(createSchedulerTask(OUTPUTMESSAGE_AUTOSEND_DELAY.count(), function)); } -void OutputMessagePool::sendAll() -{ - //dispatcher thread - for (auto& protocol : bufferedProtocols) { - auto& msg = protocol->getCurrentBuffer(); +void OutputMessagePool::sendAll() { + // dispatcher thread + for (auto &protocol : bufferedProtocols) { + auto &msg = protocol->getCurrentBuffer(); if (msg) { protocol->send(std::move(msg)); } @@ -36,18 +34,16 @@ void OutputMessagePool::sendAll() } } -void OutputMessagePool::addProtocolToAutosend(Protocol_ptr protocol) -{ - //dispatcher thread +void OutputMessagePool::addProtocolToAutosend(Protocol_ptr protocol) { + // dispatcher thread if (bufferedProtocols.empty()) { scheduleSendAll(); } bufferedProtocols.emplace_back(protocol); } -void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr& protocol) -{ - //dispatcher thread +void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr &protocol) { + // dispatcher thread auto it = std::ranges::find(bufferedProtocols.begin(), bufferedProtocols.end(), protocol); if (it != bufferedProtocols.end()) { *it = bufferedProtocols.back(); @@ -55,7 +51,6 @@ void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr& protocol) } } -OutputMessage_ptr OutputMessagePool::getOutputMessage() -{ +OutputMessage_ptr OutputMessagePool::getOutputMessage() { return std::make_shared(); } diff --git a/src/server/network/message/outputmessage.h b/src/server/network/message/outputmessage.h index b1e52871a78..eaef7437603 100644 --- a/src/server/network/message/outputmessage.h +++ b/src/server/network/message/outputmessage.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_MESSAGE_OUTPUTMESSAGE_H_ #define SRC_SERVER_NETWORK_MESSAGE_OUTPUTMESSAGE_H_ @@ -16,14 +16,13 @@ class Protocol; -class OutputMessage : public NetworkMessage -{ +class OutputMessage : public NetworkMessage { public: OutputMessage() = default; // non-copyable - OutputMessage(const OutputMessage&) = delete; - OutputMessage& operator=(const OutputMessage&) = delete; + OutputMessage(const OutputMessage &) = delete; + OutputMessage &operator=(const OutputMessage &) = delete; uint8_t* getOutputBuffer() { return buffer + outputBufferStart; @@ -41,14 +40,14 @@ class OutputMessage : public NetworkMessage writeMessageLength(); } - void append(const NetworkMessage& msg) { + void append(const NetworkMessage &msg) { auto msgLen = msg.getLength(); memcpy(buffer + info.position, msg.getBuffer() + INITIAL_BUFFER_POSITION, msgLen); info.length += msgLen; info.position += msgLen; } - void append(const OutputMessage_ptr& msg) { + void append(const OutputMessage_ptr &msg) { auto msgLen = msg->getLength(); memcpy(buffer + info.position, msg->getBuffer() + INITIAL_BUFFER_POSITION, msgLen); info.length += msgLen; @@ -61,21 +60,20 @@ class OutputMessage : public NetworkMessage assert(outputBufferStart >= sizeof(T)); outputBufferStart -= sizeof(T); memcpy(buffer + outputBufferStart, &addHeader, sizeof(T)); - //added header size to the message size + // added header size to the message size info.length += sizeof(T); } MsgSize_t outputBufferStart = INITIAL_BUFFER_POSITION; }; -class OutputMessagePool -{ +class OutputMessagePool { public: // non-copyable - OutputMessagePool(const OutputMessagePool&) = delete; - OutputMessagePool& operator=(const OutputMessagePool&) = delete; + OutputMessagePool(const OutputMessagePool &) = delete; + OutputMessagePool &operator=(const OutputMessagePool &) = delete; - static OutputMessagePool& getInstance() { + static OutputMessagePool &getInstance() { static OutputMessagePool instance; return instance; } @@ -86,13 +84,13 @@ class OutputMessagePool static OutputMessage_ptr getOutputMessage(); void addProtocolToAutosend(Protocol_ptr protocol); - void removeProtocolFromAutosend(const Protocol_ptr& protocol); + void removeProtocolFromAutosend(const Protocol_ptr &protocol); + private: OutputMessagePool() = default; - //NOTE: A vector is used here because this container is mostly read - //and relatively rarely modified (only when a client connects/disconnects) + // NOTE: A vector is used here because this container is mostly read + // and relatively rarely modified (only when a client connects/disconnects) std::vector bufferedProtocols; }; - -#endif // SRC_SERVER_NETWORK_MESSAGE_OUTPUTMESSAGE_H_ +#endif // SRC_SERVER_NETWORK_MESSAGE_OUTPUTMESSAGE_H_ diff --git a/src/server/network/protocol/protocol.cpp b/src/server/network/protocol/protocol.cpp index b5062b26e28..8118acba6ed 100644 --- a/src/server/network/protocol/protocol.cpp +++ b/src/server/network/protocol/protocol.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,8 +16,7 @@ Protocol::~Protocol() = default; -void Protocol::onSendMessage(const OutputMessage_ptr& msg) -{ +void Protocol::onSendMessage(const OutputMessage_ptr &msg) { if (!rawMessages) { uint32_t sendMessageChecksum = 0; if (compreesionEnabled && msg->getLength() >= 128 && compression(*msg)) { @@ -44,15 +43,14 @@ void Protocol::onSendMessage(const OutputMessage_ptr& msg) } } -bool Protocol::sendRecvMessageCallback(NetworkMessage& msg) -{ +bool Protocol::sendRecvMessageCallback(NetworkMessage &msg) { if (encryptionEnabled && !XTEA_decrypt(msg)) { SPDLOG_ERROR("[Protocol::onRecvMessage] - XTEA_decrypt Failed"); return false; } auto protocolWeak = std::weak_ptr(shared_from_this()); - std::function callback = [protocolWeak, &msg]() { + std::function callback = [protocolWeak, &msg]() { if (auto protocol = protocolWeak.lock()) { if (auto protocolConnection = protocol->getConnection()) { protocol->parsePacket(msg); @@ -64,8 +62,7 @@ bool Protocol::sendRecvMessageCallback(NetworkMessage& msg) return true; } -bool Protocol::onRecvMessage(NetworkMessage& msg) -{ +bool Protocol::onRecvMessage(NetworkMessage &msg) { if (checksumMethod != CHECKSUM_METHOD_NONE) { uint32_t recvChecksum = msg.get(); if (checksumMethod == CHECKSUM_METHOD_SEQUENCE) { @@ -88,8 +85,7 @@ bool Protocol::onRecvMessage(NetworkMessage& msg) } else { uint32_t checksum; if (int32_t len = msg.getLength() - msg.getBufferPosition(); - len > 0) - { + len > 0) { checksum = adlerChecksum(msg.getBuffer() + msg.getBufferPosition(), len); } else { checksum = 0; @@ -105,9 +101,8 @@ bool Protocol::onRecvMessage(NetworkMessage& msg) return sendRecvMessageCallback(msg); } -OutputMessage_ptr Protocol::getOutputBuffer(int32_t size) -{ - //dispatcher thread +OutputMessage_ptr Protocol::getOutputBuffer(int32_t size) { + // dispatcher thread if (!outputBuffer) { outputBuffer = OutputMessagePool::getOutputMessage(); } else if ((outputBuffer->getLength() + size) > MAX_PROTOCOL_BODY_LENGTH) { @@ -117,8 +112,7 @@ OutputMessage_ptr Protocol::getOutputBuffer(int32_t size) return outputBuffer; } -void Protocol::XTEA_encrypt(OutputMessage& msg) const -{ +void Protocol::XTEA_encrypt(OutputMessage &msg) const { const uint32_t delta = 0x61C88647; // The message must be a multiple of 8 @@ -130,7 +124,7 @@ void Protocol::XTEA_encrypt(OutputMessage& msg) const uint8_t* buffer = msg.getOutputBuffer(); auto messageLength = static_cast(msg.getLength()); int32_t readPos = 0; - const std::array newKey = {key[0], key[1], key[2], key[3]}; + const std::array newKey = { key[0], key[1], key[2], key[3] }; // TODO: refactor this for not use c-style uint32_t precachedControlSum[32][2]; uint32_t sum = 0; @@ -151,8 +145,7 @@ void Protocol::XTEA_encrypt(OutputMessage& msg) const } } -bool Protocol::XTEA_decrypt(NetworkMessage& msg) const -{ +bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { uint16_t msgLength = msg.getLength() - (checksumMethod == CHECKSUM_METHOD_NONE ? 2 : 6); if ((msgLength & 7) != 0) { return false; @@ -163,7 +156,7 @@ bool Protocol::XTEA_decrypt(NetworkMessage& msg) const uint8_t* buffer = msg.getBuffer() + msg.getBufferPosition(); auto messageLength = static_cast(msgLength); int32_t readPos = 0; - const std::array newKey = {key[0], key[1], key[2], key[3]}; + const std::array newKey = { key[0], key[1], key[2], key[3] }; // TODO: refactor this for not use c-style uint32_t precachedControlSum[32][2]; uint32_t sum = 0xC6EF3720; @@ -192,8 +185,7 @@ bool Protocol::XTEA_decrypt(NetworkMessage& msg) const return true; } -bool Protocol::RSA_decrypt(NetworkMessage& msg) -{ +bool Protocol::RSA_decrypt(NetworkMessage &msg) { if ((msg.getLength() - msg.getBufferPosition()) < 128) { return false; } @@ -204,8 +196,7 @@ bool Protocol::RSA_decrypt(NetworkMessage& msg) return (msg.getByte() == 0); } -uint32_t Protocol::getIP() const -{ +uint32_t Protocol::getIP() const { if (auto protocolConnection = getConnection()) { return protocolConnection->getIP(); } @@ -213,8 +204,7 @@ uint32_t Protocol::getIP() const return 0; } -void Protocol::enableCompression() -{ +void Protocol::enableCompression() { if (!compreesionEnabled) { int32_t compressionLevel = g_configManager().getNumber(COMPRESSION_LEVEL); if (compressionLevel != 0) { @@ -232,8 +222,7 @@ void Protocol::enableCompression() } } -bool Protocol::compression(OutputMessage& msg) const -{ +bool Protocol::compression(OutputMessage &msg) const { auto outputMessageSize = msg.getLength(); if (outputMessageSize > NETWORKMESSAGE_MAXSIZE) { SPDLOG_ERROR("[NetworkMessage::compression] - Exceded NetworkMessage max size: {}, actually size: {}", NETWORKMESSAGE_MAXSIZE, outputMessageSize); @@ -247,8 +236,7 @@ bool Protocol::compression(OutputMessage& msg) const defStream->avail_out = NETWORKMESSAGE_MAXSIZE; if (int32_t ret = deflate(defStream.get(), Z_FINISH); - ret != Z_OK && ret != Z_STREAM_END) - { + ret != Z_OK && ret != Z_STREAM_END) { return false; } auto totalSize = static_cast(defStream->total_out); diff --git a/src/server/network/protocol/protocol.h b/src/server/network/protocol/protocol.h index f3535411e13..f1ca682077e 100644 --- a/src/server/network/protocol/protocol.h +++ b/src/server/network/protocol/protocol.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_PROTOCOL_PROTOCOL_H_ #define SRC_SERVER_NETWORK_PROTOCOL_PROTOCOL_H_ @@ -13,23 +13,23 @@ #include "server/network/connection/connection.h" #include "config/configmanager.h" -class Protocol : public std::enable_shared_from_this -{ +class Protocol : public std::enable_shared_from_this { public: - explicit Protocol(Connection_ptr initConnection) : connectionPtr(initConnection) {} + explicit Protocol(Connection_ptr initConnection) : + connectionPtr(initConnection) { } virtual ~Protocol(); // non-copyable - Protocol(const Protocol&) = delete; - Protocol& operator=(const Protocol&) = delete; + Protocol(const Protocol &) = delete; + Protocol &operator=(const Protocol &) = delete; - virtual void parsePacket(NetworkMessage&) {} + virtual void parsePacket(NetworkMessage &) { } - virtual void onSendMessage(const OutputMessage_ptr& msg); - bool onRecvMessage(NetworkMessage& msg); - bool sendRecvMessageCallback(NetworkMessage& msg); - virtual void onRecvFirstMessage(NetworkMessage& msg) = 0; - virtual void onConnect() {} + virtual void onSendMessage(const OutputMessage_ptr &msg); + bool onRecvMessage(NetworkMessage &msg); + bool sendRecvMessageCallback(NetworkMessage &msg); + virtual void onRecvFirstMessage(NetworkMessage &msg) = 0; + virtual void onConnect() { } bool isConnectionExpired() const { return connectionPtr.expired(); @@ -41,16 +41,16 @@ class Protocol : public std::enable_shared_from_this uint32_t getIP() const; - //Use this function for autosend messages only + // Use this function for autosend messages only OutputMessage_ptr getOutputBuffer(int32_t size); - OutputMessage_ptr& getCurrentBuffer() { + OutputMessage_ptr &getCurrentBuffer() { return outputBuffer; } void send(OutputMessage_ptr msg) const { if (auto connection = getConnection(); - connection != nullptr) { + connection != nullptr) { connection->send(msg); } } @@ -58,7 +58,7 @@ class Protocol : public std::enable_shared_from_this protected: void disconnect() const { if (auto connection = getConnection(); - connection != nullptr) { + connection != nullptr) { connection->close(); } } @@ -73,19 +73,18 @@ class Protocol : public std::enable_shared_from_this } void enableCompression(); - static bool RSA_decrypt(NetworkMessage& msg); + static bool RSA_decrypt(NetworkMessage &msg); void setRawMessages(bool value) { rawMessages = value; } - virtual void release() {} + virtual void release() { } private: - void XTEA_encrypt(OutputMessage& msg) const; - bool XTEA_decrypt(NetworkMessage& msg) const; - bool compression(OutputMessage& msg) const; - + void XTEA_encrypt(OutputMessage &msg) const; + bool XTEA_decrypt(NetworkMessage &msg) const; + bool compression(OutputMessage &msg) const; OutputMessage_ptr outputBuffer; std::unique_ptr defStream; @@ -102,4 +101,4 @@ class Protocol : public std::enable_shared_from_this friend class Connection; }; -#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOL_H_ +#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOL_H_ diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 293b79659e6..a694d981341 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -30,93 +30,85 @@ #include "items/weapons/weapons.h" /* -* NOTE: This namespace is used so that we can add functions without having to declare them in the ".hpp/.h" file -* Do not use functions only in the .cpp scope without having a namespace, it may conflict with functions in other files of the same name -*/ + * NOTE: This namespace is used so that we can add functions without having to declare them in the ".hpp/.h" file + * Do not use functions only in the .cpp scope without having a namespace, it may conflict with functions in other files of the same name + */ // This "getIteration" function will allow us to get the total number of iterations that run within a specific map // Very useful to send the total amount in certain bytes in the ProtocolGame class namespace { -template -uint16_t getIterationIncreaseCount(T& map) { - uint16_t totalIterationCount = 0; - for ([[maybe_unused]] const auto &[first, second] : map) { - totalIterationCount++; + template + uint16_t getIterationIncreaseCount(T &map) { + uint16_t totalIterationCount = 0; + for ([[maybe_unused]] const auto &[first, second] : map) { + totalIterationCount++; + } + + return totalIterationCount; } - return totalIterationCount; -} + template + uint16_t getVectorIterationIncreaseCount(T &vector) { + uint16_t totalIterationCount = 0; + for ([[maybe_unused]] const auto &vectorIteration : vector) { + totalIterationCount++; + } -template -uint16_t getVectorIterationIncreaseCount(T& vector) { - uint16_t totalIterationCount = 0; - for ([[maybe_unused]] const auto &vectorIteration : vector) { - totalIterationCount++; + return totalIterationCount; } - return totalIterationCount; -} - -void addOutfitAndMountBytes(NetworkMessage &msg, const Item* item, const CustomAttribute *attribute, const std::string &head, const std::string &body, const std::string &legs, const std::string &feet, bool addAddon = false, bool addByte = false) -{ - auto look = attribute->getAttribute(); - msg.add(look); - if (look != 0) { - const auto lookHead = item->getCustomAttribute(head); - const auto lookBody = item->getCustomAttribute(body); - const auto lookLegs = item->getCustomAttribute(legs); - const auto lookFeet = item->getCustomAttribute(feet); + void addOutfitAndMountBytes(NetworkMessage &msg, const Item* item, const CustomAttribute* attribute, const std::string &head, const std::string &body, const std::string &legs, const std::string &feet, bool addAddon = false, bool addByte = false) { + auto look = attribute->getAttribute(); + msg.add(look); + if (look != 0) { + const auto lookHead = item->getCustomAttribute(head); + const auto lookBody = item->getCustomAttribute(body); + const auto lookLegs = item->getCustomAttribute(legs); + const auto lookFeet = item->getCustomAttribute(feet); - msg.addByte(lookHead ? lookHead->getAttribute() : 0); - msg.addByte(lookBody ? lookBody->getAttribute() : 0); - msg.addByte(lookLegs ? lookLegs->getAttribute() : 0); - msg.addByte(lookFeet ? lookFeet->getAttribute() : 0); + msg.addByte(lookHead ? lookHead->getAttribute() : 0); + msg.addByte(lookBody ? lookBody->getAttribute() : 0); + msg.addByte(lookLegs ? lookLegs->getAttribute() : 0); + msg.addByte(lookFeet ? lookFeet->getAttribute() : 0); - if (addAddon) { - const auto lookAddons = item->getCustomAttribute("LookAddons"); - msg.addByte(lookAddons ? lookAddons->getAttribute() : 0); - } - } else { - if (addByte) { - msg.add(0); + if (addAddon) { + const auto lookAddons = item->getCustomAttribute("LookAddons"); + msg.addByte(lookAddons ? lookAddons->getAttribute() : 0); + } + } else { + if (addByte) { + msg.add(0); + } } } -} } // namespace -ProtocolGame::ProtocolGame(Connection_ptr initConnection) : Protocol(initConnection) { +ProtocolGame::ProtocolGame(Connection_ptr initConnection) : + Protocol(initConnection) { version = CLIENT_VERSION; } template -void ProtocolGame::addGameTask(Callable function, Args &&... args) -{ +void ProtocolGame::addGameTask(Callable function, Args &&... args) { g_dispatcher().addTask(createTask(std::bind(function, &g_game(), std::forward(args)...))); } template -void ProtocolGame::addGameTaskTimed(uint32_t delay, Callable function, Args &&... args) -{ +void ProtocolGame::addGameTaskTimed(uint32_t delay, Callable function, Args &&... args) { g_dispatcher().addTask(createTask(delay, std::bind(function, &g_game(), std::forward(args)...))); } -void ProtocolGame::AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier) -{ +void ProtocolGame::AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier) { const ItemType &it = Item::items[id]; msg.add(it.id); - if (it.stackable) - { + if (it.stackable) { msg.addByte(count); - } - else if (it.isSplash() || it.isFluidContainer()) - { + } else if (it.isSplash() || it.isFluidContainer()) { msg.addByte(count); - } - else if (it.isContainer()) - { + } else if (it.isContainer()) { msg.addByte(0x00); msg.addByte(0x00); } @@ -141,10 +133,8 @@ void ProtocolGame::AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint } } -void ProtocolGame::AddItem(NetworkMessage &msg, const Item *item) -{ - if (!item) - { +void ProtocolGame::AddItem(NetworkMessage &msg, const Item* item) { + if (!item) { return; } @@ -152,40 +142,27 @@ void ProtocolGame::AddItem(NetworkMessage &msg, const Item *item) msg.add(it.id); - if (it.stackable) - { + if (it.stackable) { msg.addByte(std::min(0xFF, item->getItemCount())); - } - else if (it.isSplash() || it.isFluidContainer()) - { + } else if (it.isSplash() || it.isFluidContainer()) { msg.addByte(item->getAttribute(ItemAttribute_t::FLUIDTYPE)); - } - else if (it.isContainer()) - { - const Container *container = item->getContainer(); - if (container && container->getHoldingPlayer() == player) - { + } else if (it.isContainer()) { + const Container* container = item->getContainer(); + if (container && container->getHoldingPlayer() == player) { uint32_t lootFlags = 0; - for (auto itt : player->quickLootContainers) - { - if (itt.second == container) - { + for (auto itt : player->quickLootContainers) { + if (itt.second == container) { lootFlags |= 1 << itt.first; } } - if (lootFlags != 0) - { + if (lootFlags != 0) { msg.addByte(0x01); msg.add(lootFlags); - } - else - { + } else { msg.addByte(0x00); } - } - else - { + } else { msg.addByte(0x00); } @@ -199,9 +176,7 @@ void ProtocolGame::AddItem(NetworkMessage &msg, const Item *item) } msg.addByte(0x01); msg.add(ammoTotal); - } - else - { + } else { msg.addByte(0x00); } } @@ -254,11 +229,9 @@ void ProtocolGame::AddItem(NetworkMessage &msg, const Item *item) } } -void ProtocolGame::release() -{ - //dispatcher thread - if (player && player->client == shared_from_this()) - { +void ProtocolGame::release() { + // dispatcher thread + if (player && player->client == shared_from_this()) { player->client.reset(); player->decrementReferenceCounter(); player = nullptr; @@ -268,74 +241,60 @@ void ProtocolGame::release() Protocol::release(); } -void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingSystem_t operatingSystem) -{ - //dispatcher thread - Player *foundPlayer = g_game().getPlayerByName(name); - if (!foundPlayer || g_configManager().getBoolean(ALLOW_CLONES)) - { +void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingSystem_t operatingSystem) { + // dispatcher thread + Player* foundPlayer = g_game().getPlayerByName(name); + if (!foundPlayer || g_configManager().getBoolean(ALLOW_CLONES)) { player = new Player(getThis()); player->setName(name); player->incrementReferenceCounter(); player->setID(); - if (!IOLoginData::preloadPlayer(player, name)) - { + if (!IOLoginData::preloadPlayer(player, name)) { disconnectClient("Your character could not be loaded."); return; } - if (IOBan::isPlayerNamelocked(player->getGUID())) - { + if (IOBan::isPlayerNamelocked(player->getGUID())) { disconnectClient("Your character has been namelocked."); return; } - if (g_game().getGameState() == GAME_STATE_CLOSING && !player->hasFlag(PlayerFlags_t::CanAlwaysLogin)) - { + if (g_game().getGameState() == GAME_STATE_CLOSING && !player->hasFlag(PlayerFlags_t::CanAlwaysLogin)) { disconnectClient("The game is just going down.\nPlease try again later."); return; } - if (g_game().getGameState() == GAME_STATE_CLOSED && !player->hasFlag(PlayerFlags_t::CanAlwaysLogin)) - { + if (g_game().getGameState() == GAME_STATE_CLOSED && !player->hasFlag(PlayerFlags_t::CanAlwaysLogin)) { disconnectClient("Server is currently closed.\nPlease try again later."); return; } - if (g_configManager().getBoolean(ONLY_PREMIUM_ACCOUNT) && !player->isPremium() && (player->getGroup()->id < account::GROUP_TYPE_GAMEMASTER || player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER)) - { + if (g_configManager().getBoolean(ONLY_PREMIUM_ACCOUNT) && !player->isPremium() && (player->getGroup()->id < account::GROUP_TYPE_GAMEMASTER || player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER)) { disconnectClient("Your premium time for this account is out.\n\nTo play please buy additional premium time from our website"); return; } - if (g_configManager().getBoolean(ONE_PLAYER_ON_ACCOUNT) && player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER && g_game().getPlayerByAccount(player->getAccount())) - { + if (g_configManager().getBoolean(ONE_PLAYER_ON_ACCOUNT) && player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER && g_game().getPlayerByAccount(player->getAccount())) { disconnectClient("You may only login with one character\nof your account at the same time."); return; } - if (!player->hasFlag(PlayerFlags_t::CannotBeBanned)) - { + if (!player->hasFlag(PlayerFlags_t::CannotBeBanned)) { BanInfo banInfo; - if (IOBan::isAccountBanned(accountId, banInfo)) - { - if (banInfo.reason.empty()) - { + if (IOBan::isAccountBanned(accountId, banInfo)) { + if (banInfo.reason.empty()) { banInfo.reason = "(none)"; } std::ostringstream ss; - if (banInfo.expiresAt > 0) - { + if (banInfo.expiresAt > 0) { ss << "Your account has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" - << banInfo.reason; - } - else - { + << banInfo.reason; + } else { ss << "Your account has been permanently banned by " << banInfo.bannedBy << ".\n\nReason specified:\n" - << banInfo.reason; + << banInfo.reason; } disconnectClient(ss.str()); return; @@ -343,14 +302,13 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS } WaitingList &waitingList = WaitingList::getInstance(); - if (!waitingList.clientLogin(player)) - { + if (!waitingList.clientLogin(player)) { uint32_t currentSlot = waitingList.getClientSlot(player); uint32_t retryTime = WaitingList::getTime(currentSlot); std::ostringstream ss; ss << "Too many players online.\nYou are at place " - << currentSlot << " on the waiting list."; + << currentSlot << " on the waiting list."; auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x16); @@ -361,8 +319,7 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS return; } - if (!IOLoginData::loadPlayerById(player, player->getGUID())) - { + if (!IOLoginData::loadPlayerById(player, player->getGUID())) { disconnectClient("Your character could not be loaded."); SPDLOG_WARN("Player {} could not be loaded", player->getName()); return; @@ -370,61 +327,50 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS player->setOperatingSystem(operatingSystem); - if (!g_game().placeCreature(player, player->getLoginPosition()) && !g_game().placeCreature(player, player->getTemplePosition(), false, true)) - { + if (!g_game().placeCreature(player, player->getLoginPosition()) && !g_game().placeCreature(player, player->getTemplePosition(), false, true)) { disconnectClient("Temple position is wrong. Please, contact the administrator."); SPDLOG_WARN("Player {} temple position is wrong", player->getName()); return; } - if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) - { + if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) { player->registerCreatureEvent("ExtendedOpcode"); } player->lastIP = player->getIP(); player->lastLoginSaved = std::max(time(nullptr), player->lastLoginSaved + 1); acceptPackets = true; - } - else - { - if (eventConnect != 0 || !g_configManager().getBoolean(REPLACE_KICK_ON_LOGIN)) - { - //Already trying to connect + } else { + if (eventConnect != 0 || !g_configManager().getBoolean(REPLACE_KICK_ON_LOGIN)) { + // Already trying to connect disconnectClient("You are already logged in."); return; } - if (foundPlayer->client) - { + if (foundPlayer->client) { foundPlayer->disconnect(); foundPlayer->isConnecting = true; eventConnect = g_scheduler().addEvent(createSchedulerTask(1000, std::bind(&ProtocolGame::connect, getThis(), foundPlayer->getID(), operatingSystem))); - } - else - { + } else { connect(foundPlayer->getID(), operatingSystem); } } OutputMessagePool::getInstance().addProtocolToAutosend(shared_from_this()); } -void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem) -{ +void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem) { eventConnect = 0; - Player *foundPlayer = g_game().getPlayerByID(playerId); - if (!foundPlayer || foundPlayer->client) - { + Player* foundPlayer = g_game().getPlayerByID(playerId); + if (!foundPlayer || foundPlayer->client) { disconnectClient("You are already logged in."); return; } - if (isConnectionExpired()) - { - //ProtocolGame::release() has been called at this point and the Connection object - //no longer exists, so we return to prevent leakage of the Player. + if (isConnectionExpired()) { + // ProtocolGame::release() has been called at this point and the Connection object + // no longer exists, so we return to prevent leakage of the Player. return; } @@ -445,8 +391,7 @@ void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem) acceptPackets = true; } -void ProtocolGame::logout(bool displayEffect, bool forced) -{ +void ProtocolGame::logout(bool displayEffect, bool forced) { if (!player) { return; } @@ -478,10 +423,8 @@ void ProtocolGame::logout(bool displayEffect, bool forced) g_game().removeCreature(player, true); } -void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) -{ - if (g_game().getGameState() == GAME_STATE_SHUTDOWN) - { +void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { + if (g_game().getGameState() == GAME_STATE_SHUTDOWN) { disconnect(); return; } @@ -498,14 +441,13 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) msg.skipBytes(3); // U16 dat revision, U8 game preview state - if (!Protocol::RSA_decrypt(msg)) - { + if (!Protocol::RSA_decrypt(msg)) { SPDLOG_WARN("[ProtocolGame::onRecvFirstMessage] - RSA Decrypt Failed"); disconnect(); return; } - std::array key = {msg.get(), msg.get(), msg.get(), msg.get()}; + std::array key = { msg.get(), msg.get(), msg.get(), msg.get() }; enableXTEAEncryption(); setXTEAKey(key.data()); @@ -513,22 +455,19 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) std::string sessionKey = msg.getString(); size_t pos = sessionKey.find('\n'); - if (pos == std::string::npos) - { + if (pos == std::string::npos) { disconnectClient("You must enter your email."); return; } - if (operatingSystem == CLIENTOS_NEW_LINUX) - { + if (operatingSystem == CLIENTOS_NEW_LINUX) { // TODO: check what new info for linux is send msg.getString(); msg.getString(); } std::string email = sessionKey.substr(0, pos); - if (email.empty()) - { + if (email.empty()) { disconnectClient("You must enter your email."); return; } @@ -538,43 +477,37 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) uint32_t timeStamp = msg.get(); uint8_t randNumber = msg.getByte(); - if (challengeTimestamp != timeStamp || challengeRandom != randNumber) - { + if (challengeTimestamp != timeStamp || challengeRandom != randNumber) { disconnect(); return; } - if (clientVersion != CLIENT_VERSION) - { + if (clientVersion != CLIENT_VERSION) { std::ostringstream ss; ss << "Only clients with protocol " << CLIENT_VERSION_UPPER << "." << CLIENT_VERSION_LOWER << " allowed!"; disconnectClient(ss.str()); return; } - if (g_game().getGameState() == GAME_STATE_STARTUP) - { + if (g_game().getGameState() == GAME_STATE_STARTUP) { disconnectClient("Gameworld is starting up. Please wait."); return; } - if (g_game().getGameState() == GAME_STATE_MAINTAIN) - { + if (g_game().getGameState() == GAME_STATE_MAINTAIN) { disconnectClient("Gameworld is under maintenance. Please re-connect in a while."); return; } BanInfo banInfo; - if (IOBan::isIpBanned(getIP(), banInfo)) - { - if (banInfo.reason.empty()) - { + if (IOBan::isIpBanned(getIP(), banInfo)) { + if (banInfo.reason.empty()) { banInfo.reason = "(none)"; } std::ostringstream ss; ss << "Your IP has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" - << banInfo.reason; + << banInfo.reason; disconnectClient(ss.str()); return; } @@ -588,8 +521,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) g_dispatcher().addTask(createTask(std::bind(&ProtocolGame::login, getThis(), characterName, accountId, operatingSystem))); } -void ProtocolGame::onConnect() -{ +void ProtocolGame::onConnect() { auto output = OutputMessagePool::getOutputMessage(); static std::random_device rd; static std::ranlux24 generator(rd()); @@ -617,8 +549,7 @@ void ProtocolGame::onConnect() send(std::move(output)); } -void ProtocolGame::disconnectClient(const std::string &message) const -{ +void ProtocolGame::disconnectClient(const std::string &message) const { auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x14); output->addString(message); @@ -626,14 +557,12 @@ void ProtocolGame::disconnectClient(const std::string &message) const disconnect(); } -void ProtocolGame::writeToOutputBuffer(const NetworkMessage &msg) -{ +void ProtocolGame::writeToOutputBuffer(const NetworkMessage &msg) { auto out = getOutputBuffer(msg.getLength()); out->append(msg); } -void ProtocolGame::parsePacket(NetworkMessage& msg) -{ +void ProtocolGame::parsePacket(NetworkMessage &msg) { if (!acceptPackets || g_game().getGameState() == GAME_STATE_SHUTDOWN || msg.getLength() <= 0) { return; } @@ -660,8 +589,7 @@ void ProtocolGame::parsePacket(NetworkMessage& msg) g_dispatcher().addTask(createTask(std::bind(&ProtocolGame::parsePacketFromDispatcher, getThis(), msg, recvbyte))); } -void ProtocolGame::parsePacketDead(uint8_t recvbyte) -{ +void ProtocolGame::parsePacketDead(uint8_t recvbyte) { if (recvbyte == 0x14) { disconnect(); g_dispatcher().addTask(createTask(std::bind(&IOLoginData::updateOnlineStatus, player->getGUID(), false))); @@ -693,11 +621,10 @@ void ProtocolGame::parsePacketDead(uint8_t recvbyte) } } -void ProtocolGame::addBless() -{ +void ProtocolGame::addBless() { std::string bless = player->getBlessingsName(); std::ostringstream lostBlesses; - (bless.length() == 0) ? lostBlesses << "You lost all your blessings." : lostBlesses << "You are still blessed with " << bless; + (bless.length() == 0) ? lostBlesses << "You lost all your blessings." : lostBlesses << "You are still blessed with " << bless; player->sendTextMessage(MESSAGE_EVENT_ADVANCE, lostBlesses.str()); if (player->getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL)) { for (uint8_t i = 2; i <= 6; i++) { @@ -709,8 +636,7 @@ void ProtocolGame::addBless() } } -void ProtocolGame::parsePacketFromDispatcher(NetworkMessage msg, uint8_t recvbyte) -{ +void ProtocolGame::parsePacketFromDispatcher(NetworkMessage msg, uint8_t recvbyte) { if (!acceptPackets || g_game().getGameState() == GAME_STATE_SHUTDOWN) { return; } @@ -720,142 +646,361 @@ void ProtocolGame::parsePacketFromDispatcher(NetworkMessage msg, uint8_t recvbyt } switch (recvbyte) { - case 0x14: g_dispatcher().addTask(createTask(std::bind(&ProtocolGame::logout, getThis(), true, false))); break; - case 0x1D: addGameTask(&Game::playerReceivePingBack, player->getID()); break; - case 0x1E: addGameTask(&Game::playerReceivePing, player->getID()); break; - case 0x2a: addBestiaryTrackerList(msg); break; - case 0x2B: parsePartyAnalyzerAction(msg); break; - case 0x2c: parseLeaderFinderWindow(msg); break; - case 0x2d: parseMemberFinderWindow(msg); break; - case 0x28: parseStashWithdraw(msg); break; - case 0x29: parseRetrieveDepotSearch(msg); break; - case 0x32: parseExtendedOpcode(msg); break; //otclient extended opcode - case 0x64: parseAutoWalk(msg); break; - case 0x65: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTH); break; - case 0x66: addGameTask(&Game::playerMove, player->getID(), DIRECTION_EAST); break; - case 0x67: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTH); break; - case 0x68: addGameTask(&Game::playerMove, player->getID(), DIRECTION_WEST); break; - case 0x69: addGameTask(&Game::playerStopAutoWalk, player->getID()); break; - case 0x6A: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHEAST); break; - case 0x6B: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHEAST); break; - case 0x6C: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHWEST); break; - case 0x6D: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHWEST); break; - case 0x6F: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_NORTH); break; - case 0x70: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_EAST); break; - case 0x71: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_SOUTH); break; - case 0x72: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_WEST); break; - case 0x73: parseTeleport(msg); break; - case 0x77: parseHotkeyEquip(msg); break; - case 0x78: parseThrow(msg); break; - case 0x79: parseLookInShop(msg); break; - case 0x7A: parsePlayerBuyOnShop(msg); break; - case 0x7B: parsePlayerSellOnShop(msg); break; - case 0x7C: addGameTask(&Game::playerCloseShop, player->getID()); break; - case 0x7D: parseRequestTrade(msg); break; - case 0x7E: parseLookInTrade(msg); break; - case 0x7F: addGameTask(&Game::playerAcceptTrade, player->getID()); break; - case 0x80: addGameTask(&Game::playerCloseTrade, player->getID()); break; - case 0x82: parseUseItem(msg); break; - case 0x83: parseUseItemEx(msg); break; - case 0x84: parseUseWithCreature(msg); break; - case 0x85: parseRotateItem(msg); break; - case 0x86: parseConfigureShowOffSocket(msg); break; - case 0x87: parseCloseContainer(msg); break; - case 0x88: parseUpArrowContainer(msg); break; - case 0x89: parseTextWindow(msg); break; - case 0x8A: parseHouseWindow(msg); break; - case 0x8B: parseWrapableItem(msg); break; - case 0x8C: parseLookAt(msg); break; - case 0x8D: parseLookInBattleList(msg); break; - case 0x8E: /* join aggression */ break; - case 0x8F: parseQuickLoot(msg); break; - case 0x90: parseLootContainer(msg); break; - case 0x91: parseQuickLootBlackWhitelist(msg); break; - case 0x92: parseOpenDepotSearch(); break; - case 0x93: parseCloseDepotSearch(); break; - case 0x94: parseDepotSearchItemRequest(msg); break; - case 0x95: parseOpenParentContainer(msg); break; - case 0x96: parseSay(msg); break; - case 0x97: addGameTask(&Game::playerRequestChannels, player->getID()); break; - case 0x98: parseOpenChannel(msg); break; - case 0x99: parseCloseChannel(msg); break; - case 0x9A: parseOpenPrivateChannel(msg); break; - case 0x9E: addGameTask(&Game::playerCloseNpcChannel, player->getID()); break; - case 0xA0: parseFightModes(msg); break; - case 0xA1: parseAttack(msg); break; - case 0xA2: parseFollow(msg); break; - case 0xA3: parseInviteToParty(msg); break; - case 0xA4: parseJoinParty(msg); break; - case 0xA5: parseRevokePartyInvite(msg); break; - case 0xA6: parsePassPartyLeadership(msg); break; - case 0xA7: addGameTask(&Game::playerLeaveParty, player->getID()); break; - case 0xA8: parseEnableSharedPartyExperience(msg); break; - case 0xAA: addGameTask(&Game::playerCreatePrivateChannel, player->getID()); break; - case 0xAB: parseChannelInvite(msg); break; - case 0xAC: parseChannelExclude(msg); break; - case 0xB1: parseHighscores(msg); break; - case 0xBA: parseTaskHuntingAction(msg); break; - case 0xBE: addGameTask(&Game::playerCancelAttackAndFollow, player->getID()); break; - case 0xBF: parseForgeEnter(msg); break; - case 0xC0: parseForgeBrowseHistory(msg); break; - case 0xC7: parseTournamentLeaderboard(msg); break; - case 0xC9: /* update tile */ break; - case 0xCA: parseUpdateContainer(msg); break; - case 0xCB: parseBrowseField(msg); break; - case 0xCC: parseSeekInContainer(msg); break; - case 0xCD: parseInspectionObject(msg); break; - case 0xD2: addGameTask(&Game::playerRequestOutfit, player->getID()); break; - //g_dispatcher().addTask(createTask(std::bind(&Modules::executeOnRecvbyte, g_modules, player, msg, recvbyte))); - case 0xD3: g_dispatcher().addTask(createTask(std::bind(&ProtocolGame::parseSetOutfit, getThis(), msg))); break; - case 0xD4: parseToggleMount(msg); break; - case 0xD5: parseApplyImbuement(msg); break; - case 0xD6: parseClearImbuement(msg); break; - case 0xD7: parseCloseImbuementWindow(msg); break; - case 0xDC: parseAddVip(msg); break; - case 0xDD: parseRemoveVip(msg); break; - case 0xDE: parseEditVip(msg); break; - case 0xE1: parseBestiarysendRaces(); break; - case 0xE2: parseBestiarysendCreatures(msg); break; - case 0xE3: parseBestiarysendMonsterData(msg); break; - case 0xE4: parseSendBuyCharmRune(msg); break; - case 0xE5: parseCyclopediaCharacterInfo(msg); break; - case 0xE6: parseBugReport(msg); break; - case 0xE7: /* thank you */ break; - case 0xE8: parseDebugAssert(msg); break; - case 0xEB: parsePreyAction(msg); break; - case 0xED: parseSendResourceBalance(); break; - case 0xEE: parseGreet(msg); break; + case 0x14: + g_dispatcher().addTask(createTask(std::bind(&ProtocolGame::logout, getThis(), true, false))); + break; + case 0x1D: + addGameTask(&Game::playerReceivePingBack, player->getID()); + break; + case 0x1E: + addGameTask(&Game::playerReceivePing, player->getID()); + break; + case 0x2a: + addBestiaryTrackerList(msg); + break; + case 0x2B: + parsePartyAnalyzerAction(msg); + break; + case 0x2c: + parseLeaderFinderWindow(msg); + break; + case 0x2d: + parseMemberFinderWindow(msg); + break; + case 0x28: + parseStashWithdraw(msg); + break; + case 0x29: + parseRetrieveDepotSearch(msg); + break; + case 0x32: + parseExtendedOpcode(msg); + break; // otclient extended opcode + case 0x64: + parseAutoWalk(msg); + break; + case 0x65: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTH); + break; + case 0x66: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_EAST); + break; + case 0x67: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTH); + break; + case 0x68: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_WEST); + break; + case 0x69: + addGameTask(&Game::playerStopAutoWalk, player->getID()); + break; + case 0x6A: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHEAST); + break; + case 0x6B: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHEAST); + break; + case 0x6C: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHWEST); + break; + case 0x6D: + addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHWEST); + break; + case 0x6F: + addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_NORTH); + break; + case 0x70: + addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_EAST); + break; + case 0x71: + addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_SOUTH); + break; + case 0x72: + addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_WEST); + break; + case 0x73: + parseTeleport(msg); + break; + case 0x77: + parseHotkeyEquip(msg); + break; + case 0x78: + parseThrow(msg); + break; + case 0x79: + parseLookInShop(msg); + break; + case 0x7A: + parsePlayerBuyOnShop(msg); + break; + case 0x7B: + parsePlayerSellOnShop(msg); + break; + case 0x7C: + addGameTask(&Game::playerCloseShop, player->getID()); + break; + case 0x7D: + parseRequestTrade(msg); + break; + case 0x7E: + parseLookInTrade(msg); + break; + case 0x7F: + addGameTask(&Game::playerAcceptTrade, player->getID()); + break; + case 0x80: + addGameTask(&Game::playerCloseTrade, player->getID()); + break; + case 0x82: + parseUseItem(msg); + break; + case 0x83: + parseUseItemEx(msg); + break; + case 0x84: + parseUseWithCreature(msg); + break; + case 0x85: + parseRotateItem(msg); + break; + case 0x86: + parseConfigureShowOffSocket(msg); + break; + case 0x87: + parseCloseContainer(msg); + break; + case 0x88: + parseUpArrowContainer(msg); + break; + case 0x89: + parseTextWindow(msg); + break; + case 0x8A: + parseHouseWindow(msg); + break; + case 0x8B: + parseWrapableItem(msg); + break; + case 0x8C: + parseLookAt(msg); + break; + case 0x8D: + parseLookInBattleList(msg); + break; + case 0x8E: /* join aggression */ + break; + case 0x8F: + parseQuickLoot(msg); + break; + case 0x90: + parseLootContainer(msg); + break; + case 0x91: + parseQuickLootBlackWhitelist(msg); + break; + case 0x92: + parseOpenDepotSearch(); + break; + case 0x93: + parseCloseDepotSearch(); + break; + case 0x94: + parseDepotSearchItemRequest(msg); + break; + case 0x95: + parseOpenParentContainer(msg); + break; + case 0x96: + parseSay(msg); + break; + case 0x97: + addGameTask(&Game::playerRequestChannels, player->getID()); + break; + case 0x98: + parseOpenChannel(msg); + break; + case 0x99: + parseCloseChannel(msg); + break; + case 0x9A: + parseOpenPrivateChannel(msg); + break; + case 0x9E: + addGameTask(&Game::playerCloseNpcChannel, player->getID()); + break; + case 0xA0: + parseFightModes(msg); + break; + case 0xA1: + parseAttack(msg); + break; + case 0xA2: + parseFollow(msg); + break; + case 0xA3: + parseInviteToParty(msg); + break; + case 0xA4: + parseJoinParty(msg); + break; + case 0xA5: + parseRevokePartyInvite(msg); + break; + case 0xA6: + parsePassPartyLeadership(msg); + break; + case 0xA7: + addGameTask(&Game::playerLeaveParty, player->getID()); + break; + case 0xA8: + parseEnableSharedPartyExperience(msg); + break; + case 0xAA: + addGameTask(&Game::playerCreatePrivateChannel, player->getID()); + break; + case 0xAB: + parseChannelInvite(msg); + break; + case 0xAC: + parseChannelExclude(msg); + break; + case 0xB1: + parseHighscores(msg); + break; + case 0xBA: + parseTaskHuntingAction(msg); + break; + case 0xBE: + addGameTask(&Game::playerCancelAttackAndFollow, player->getID()); + break; + case 0xBF: + parseForgeEnter(msg); + break; + case 0xC0: + parseForgeBrowseHistory(msg); + break; + case 0xC7: + parseTournamentLeaderboard(msg); + break; + case 0xC9: /* update tile */ + break; + case 0xCA: + parseUpdateContainer(msg); + break; + case 0xCB: + parseBrowseField(msg); + break; + case 0xCC: + parseSeekInContainer(msg); + break; + case 0xCD: + parseInspectionObject(msg); + break; + case 0xD2: + addGameTask(&Game::playerRequestOutfit, player->getID()); + break; + // g_dispatcher().addTask(createTask(std::bind(&Modules::executeOnRecvbyte, g_modules, player, msg, recvbyte))); + case 0xD3: + g_dispatcher().addTask(createTask(std::bind(&ProtocolGame::parseSetOutfit, getThis(), msg))); + break; + case 0xD4: + parseToggleMount(msg); + break; + case 0xD5: + parseApplyImbuement(msg); + break; + case 0xD6: + parseClearImbuement(msg); + break; + case 0xD7: + parseCloseImbuementWindow(msg); + break; + case 0xDC: + parseAddVip(msg); + break; + case 0xDD: + parseRemoveVip(msg); + break; + case 0xDE: + parseEditVip(msg); + break; + case 0xE1: + parseBestiarysendRaces(); + break; + case 0xE2: + parseBestiarysendCreatures(msg); + break; + case 0xE3: + parseBestiarysendMonsterData(msg); + break; + case 0xE4: + parseSendBuyCharmRune(msg); + break; + case 0xE5: + parseCyclopediaCharacterInfo(msg); + break; + case 0xE6: + parseBugReport(msg); + break; + case 0xE7: /* thank you */ + break; + case 0xE8: + parseDebugAssert(msg); + break; + case 0xEB: + parsePreyAction(msg); + break; + case 0xED: + parseSendResourceBalance(); + break; + case 0xEE: + parseGreet(msg); + break; // Premium coins transfer // case 0xEF: parseCoinTransfer(msg); break; - case 0xF0: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerShowQuestLog, player->getID()); break; - case 0xF1: parseQuestLine(msg); break; + case 0xF0: + addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerShowQuestLog, player->getID()); + break; + case 0xF1: + parseQuestLine(msg); + break; // case 0xF2: parseRuleViolationReport(msg); break; - case 0xF3: /* get object info */ break; - case 0xF4: parseMarketLeave(); break; - case 0xF5: parseMarketBrowse(msg); break; - case 0xF6: parseMarketCreateOffer(msg); break; - case 0xF7: parseMarketCancelOffer(msg); break; - case 0xF8: parseMarketAcceptOffer(msg); break; - case 0xF9: parseModalWindowAnswer(msg); break; - // case 0xFA: parseStoreOpen(msg); break; - // case 0xFB: parseStoreRequestOffers(msg); break; - // case 0xFC: parseStoreBuyOffer(msg) break; - // case 0xFD: parseStoreOpenTransactionHistory(msg); break; - // case 0xFE: parseStoreRequestTransactionHistory(msg); break; - - //case 0xDF, 0xE0, 0xE1, 0xFB, 0xFC, 0xFD, 0xFE Premium Shop. + case 0xF3: /* get object info */ + break; + case 0xF4: + parseMarketLeave(); + break; + case 0xF5: + parseMarketBrowse(msg); + break; + case 0xF6: + parseMarketCreateOffer(msg); + break; + case 0xF7: + parseMarketCancelOffer(msg); + break; + case 0xF8: + parseMarketAcceptOffer(msg); + break; + case 0xF9: + parseModalWindowAnswer(msg); + break; + // case 0xFA: parseStoreOpen(msg); break; + // case 0xFB: parseStoreRequestOffers(msg); break; + // case 0xFC: parseStoreBuyOffer(msg) break; + // case 0xFD: parseStoreOpenTransactionHistory(msg); break; + // case 0xFE: parseStoreRequestTransactionHistory(msg); break; + + // case 0xDF, 0xE0, 0xE1, 0xFB, 0xFC, 0xFD, 0xFE Premium Shop. default: - SPDLOG_DEBUG("Player: {} sent an unknown packet header: x0{}", - player->getName(), static_cast(recvbyte)); + SPDLOG_DEBUG("Player: {} sent an unknown packet header: x0{}", player->getName(), static_cast(recvbyte)); break; } } -void ProtocolGame::parseHotkeyEquip(NetworkMessage &msg) -{ - if (!player) - { +void ProtocolGame::parseHotkeyEquip(NetworkMessage &msg) { + if (!player) { return; } uint16_t itemId = msg.get(); @@ -863,58 +1008,44 @@ void ProtocolGame::parseHotkeyEquip(NetworkMessage &msg) addGameTask(&Game::playerEquipItem, player->getID(), itemId, Item::items[itemId].upgradeClassification > 0, tier); } -void ProtocolGame::GetTileDescription(const Tile *tile, NetworkMessage &msg) -{ +void ProtocolGame::GetTileDescription(const Tile* tile, NetworkMessage &msg) { int32_t count; - Item *ground = tile->getGround(); - if (ground) - { + Item* ground = tile->getGround(); + if (ground) { AddItem(msg, ground); count = 1; - } - else - { + } else { count = 0; } - const TileItemVector *items = tile->getItemList(); - if (items) - { - for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) - { + const TileItemVector* items = tile->getItemList(); + if (items) { + for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { AddItem(msg, *it); count++; - if (count == 9 && tile->getPosition() == player->getPosition()) - { + if (count == 9 && tile->getPosition() == player->getPosition()) { break; - } - else if (count == 10) - { + } else if (count == 10) { return; } } } - const CreatureVector *creatures = tile->getCreatures(); - if (creatures) - { + const CreatureVector* creatures = tile->getCreatures(); + if (creatures) { bool playerAdded = false; - for (auto it = creatures->rbegin(); it != creatures->rend(); ++it) - { - const Creature *creature = *it; - if (!player->canSeeCreature(creature)) - { + for (auto it = creatures->rbegin(); it != creatures->rend(); ++it) { + const Creature* creature = *it; + if (!player->canSeeCreature(creature)) { continue; } - if (tile->getPosition() == player->getPosition() && count == 9 && !playerAdded) - { + if (tile->getPosition() == player->getPosition() && count == 9 && !playerAdded) { creature = player; } - if (creature->getID() == player->getID()) - { + if (creature->getID() == player->getID()) { playerAdded = true; } @@ -923,100 +1054,78 @@ void ProtocolGame::GetTileDescription(const Tile *tile, NetworkMessage &msg) checkCreatureAsKnown(creature->getID(), known, removedKnown); AddCreature(msg, creature, known, removedKnown); - if (++count == 10) - { + if (++count == 10) { return; } } } - if (items) - { - for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) - { + if (items) { + for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { AddItem(msg, *it); - if (++count == 10) - { + if (++count == 10) { return; } } } } -void ProtocolGame::GetMapDescription(int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, NetworkMessage &msg) -{ +void ProtocolGame::GetMapDescription(int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, NetworkMessage &msg) { int32_t skip = -1; int32_t startz, endz, zstep; - if (z > MAP_INIT_SURFACE_LAYER) - { + if (z > MAP_INIT_SURFACE_LAYER) { startz = z - MAP_LAYER_VIEW_LIMIT; endz = std::min(MAP_MAX_LAYERS - 1, z + MAP_LAYER_VIEW_LIMIT); zstep = 1; - } - else - { + } else { startz = MAP_INIT_SURFACE_LAYER; endz = 0; zstep = -1; } - for (int32_t nz = startz; nz != endz + zstep; nz += zstep) - { + for (int32_t nz = startz; nz != endz + zstep; nz += zstep) { GetFloorDescription(msg, x, y, nz, width, height, z - nz, skip); } - if (skip >= 0) - { + if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } -void ProtocolGame::GetFloorDescription(NetworkMessage &msg, int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, int32_t offset, int32_t &skip) -{ - for (int32_t nx = 0; nx < width; nx++) - { - for (int32_t ny = 0; ny < height; ny++) - { - const Tile *tile = g_game().map.getTile(static_cast(x + nx + offset), static_cast(y + ny + offset), static_cast(z)); - if (tile) - { - if (skip >= 0) - { +void ProtocolGame::GetFloorDescription(NetworkMessage &msg, int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, int32_t offset, int32_t &skip) { + for (int32_t nx = 0; nx < width; nx++) { + for (int32_t ny = 0; ny < height; ny++) { + const Tile* tile = g_game().map.getTile(static_cast(x + nx + offset), static_cast(y + ny + offset), static_cast(z)); + if (tile) { + if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } skip = 0; GetTileDescription(tile, msg); - } - else if (skip == 0xFE) - { + } else if (skip == 0xFE) { msg.addByte(0xFF); msg.addByte(0xFF); skip = -1; - } - else - { + } else { ++skip; } } } } -void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &removedKnown) -{ +void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &removedKnown) { if (auto [creatureKnown, creatureInserted] = knownCreatureSet.insert(id); - !creatureInserted) - { + !creatureInserted) { known = true; return; } known = false; - if (knownCreatureSet.size() > 1300) - { + if (knownCreatureSet.size() > 1300) { // Look for a creature to remove for (auto it = knownCreatureSet.begin(), end = knownCreatureSet.end(); it != end; ++it) { if (*it == id) { @@ -1024,9 +1133,8 @@ void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &remo } // We need to protect party players from removing Creature* creature = g_game().getCreatureByID(*it); - if (const Player* checkPlayer; - creature && (checkPlayer = creature->getPlayer()) != nullptr) - { + if (const Player * checkPlayer; + creature && (checkPlayer = creature->getPlayer()) != nullptr) { if (player->getParty() != checkPlayer->getParty() && !canSee(creature)) { removedKnown = *it; knownCreatureSet.erase(it); @@ -1041,172 +1149,144 @@ void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &remo // Bad situation. Let's just remove anyone. auto it = knownCreatureSet.begin(); - if (*it == id) - { + if (*it == id) { ++it; } removedKnown = *it; knownCreatureSet.erase(it); - } - else - { + } else { removedKnown = 0; } } -bool ProtocolGame::canSee(const Creature *c) const -{ - if (!c || !player || c->isRemoved()) - { +bool ProtocolGame::canSee(const Creature* c) const { + if (!c || !player || c->isRemoved()) { return false; } - if (!player->canSeeCreature(c)) - { + if (!player->canSeeCreature(c)) { return false; } return canSee(c->getPosition()); } -bool ProtocolGame::canSee(const Position &pos) const -{ +bool ProtocolGame::canSee(const Position &pos) const { return canSee(pos.x, pos.y, pos.z); } -bool ProtocolGame::canSee(int32_t x, int32_t y, int32_t z) const -{ - if (!player) - { +bool ProtocolGame::canSee(int32_t x, int32_t y, int32_t z) const { + if (!player) { return false; } const Position &myPos = player->getPosition(); - if (myPos.z <= MAP_INIT_SURFACE_LAYER) - { - //we are on ground level or above (7 -> 0) - //view is from 7 -> 0 - if (z > MAP_INIT_SURFACE_LAYER) - { + if (myPos.z <= MAP_INIT_SURFACE_LAYER) { + // we are on ground level or above (7 -> 0) + // view is from 7 -> 0 + if (z > MAP_INIT_SURFACE_LAYER) { return false; } - } - else if (myPos.z >= MAP_INIT_SURFACE_LAYER + 1) - { - //we are underground (8 -> 15) - //view is +/- 2 from the floor we stand on - if (std::abs(myPos.getZ() - z) > MAP_LAYER_VIEW_LIMIT) - { + } else if (myPos.z >= MAP_INIT_SURFACE_LAYER + 1) { + // we are underground (8 -> 15) + // view is +/- 2 from the floor we stand on + if (std::abs(myPos.getZ() - z) > MAP_LAYER_VIEW_LIMIT) { return false; } } - //negative offset means that the action taken place is on a lower floor than ourself + // negative offset means that the action taken place is on a lower floor than ourself const int8_t offsetz = myPos.getZ() - z; - return (x >= myPos.getX() - Map::maxClientViewportX + offsetz) && (x <= myPos.getX() + (Map::maxClientViewportX + 1) + offsetz) && - (y >= myPos.getY() - Map::maxClientViewportY + offsetz) && (y <= myPos.getY() + (Map::maxClientViewportY + 1) + offsetz); + return (x >= myPos.getX() - Map::maxClientViewportX + offsetz) && (x <= myPos.getX() + (Map::maxClientViewportX + 1) + offsetz) && (y >= myPos.getY() - Map::maxClientViewportY + offsetz) && (y <= myPos.getY() + (Map::maxClientViewportY + 1) + offsetz); } // Parse methods -void ProtocolGame::parseChannelInvite(NetworkMessage &msg) -{ +void ProtocolGame::parseChannelInvite(NetworkMessage &msg) { const std::string name = msg.getString(); addGameTask(&Game::playerChannelInvite, player->getID(), name); } -void ProtocolGame::parseChannelExclude(NetworkMessage &msg) -{ +void ProtocolGame::parseChannelExclude(NetworkMessage &msg) { const std::string name = msg.getString(); addGameTask(&Game::playerChannelExclude, player->getID(), name); } -void ProtocolGame::parseOpenChannel(NetworkMessage &msg) -{ +void ProtocolGame::parseOpenChannel(NetworkMessage &msg) { uint16_t channelId = msg.get(); addGameTask(&Game::playerOpenChannel, player->getID(), channelId); } -void ProtocolGame::parseCloseChannel(NetworkMessage &msg) -{ +void ProtocolGame::parseCloseChannel(NetworkMessage &msg) { uint16_t channelId = msg.get(); addGameTask(&Game::playerCloseChannel, player->getID(), channelId); } -void ProtocolGame::parseOpenPrivateChannel(NetworkMessage &msg) -{ +void ProtocolGame::parseOpenPrivateChannel(NetworkMessage &msg) { const std::string receiver = msg.getString(); addGameTask(&Game::playerOpenPrivateChannel, player->getID(), receiver); } -void ProtocolGame::parseAutoWalk(NetworkMessage &msg) -{ +void ProtocolGame::parseAutoWalk(NetworkMessage &msg) { uint8_t numdirs = msg.getByte(); - if (numdirs == 0 || (msg.getBufferPosition() + numdirs) != (msg.getLength() + 8)) - { + if (numdirs == 0 || (msg.getBufferPosition() + numdirs) != (msg.getLength() + 8)) { return; } msg.skipBytes(numdirs); std::forward_list path; - for (uint8_t i = 0; i < numdirs; ++i) - { + for (uint8_t i = 0; i < numdirs; ++i) { uint8_t rawdir = msg.getPreviousByte(); - switch (rawdir) - { - case 1: - path.push_front(DIRECTION_EAST); - break; - case 2: - path.push_front(DIRECTION_NORTHEAST); - break; - case 3: - path.push_front(DIRECTION_NORTH); - break; - case 4: - path.push_front(DIRECTION_NORTHWEST); - break; - case 5: - path.push_front(DIRECTION_WEST); - break; - case 6: - path.push_front(DIRECTION_SOUTHWEST); - break; - case 7: - path.push_front(DIRECTION_SOUTH); - break; - case 8: - path.push_front(DIRECTION_SOUTHEAST); - break; - default: - break; + switch (rawdir) { + case 1: + path.push_front(DIRECTION_EAST); + break; + case 2: + path.push_front(DIRECTION_NORTHEAST); + break; + case 3: + path.push_front(DIRECTION_NORTH); + break; + case 4: + path.push_front(DIRECTION_NORTHWEST); + break; + case 5: + path.push_front(DIRECTION_WEST); + break; + case 6: + path.push_front(DIRECTION_SOUTHWEST); + break; + case 7: + path.push_front(DIRECTION_SOUTH); + break; + case 8: + path.push_front(DIRECTION_SOUTHEAST); + break; + default: + break; } } - if (path.empty()) - { + if (path.empty()) { return; } addGameTask(&Game::playerAutoWalk, player->getID(), path); } -void ProtocolGame::parseSetOutfit(NetworkMessage &msg) -{ +void ProtocolGame::parseSetOutfit(NetworkMessage &msg) { if (!player || player->isRemoved()) { return; } uint16_t startBufferPosition = msg.getBufferPosition(); - Module *outfitModule = g_modules().getEventByRecvbyte(0xD3, false); - if (outfitModule) - { + Module* outfitModule = g_modules().getEventByRecvbyte(0xD3, false); + if (outfitModule) { outfitModule->executeOnRecvbyte(player, msg); } - if (msg.getBufferPosition() == startBufferPosition) - { + if (msg.getBufferPosition() == startBufferPosition) { uint8_t outfitType = 0; outfitType = msg.getByte(); Outfit_t newOutfit; @@ -1216,8 +1296,7 @@ void ProtocolGame::parseSetOutfit(NetworkMessage &msg) newOutfit.lookLegs = std::min(132, msg.getByte()); newOutfit.lookFeet = std::min(132, msg.getByte()); newOutfit.lookAddons = msg.getByte(); - if (outfitType == 0) - { + if (outfitType == 0) { newOutfit.lookMount = msg.get(); newOutfit.lookMountHead = std::min(132, msg.getByte()); newOutfit.lookMountBody = std::min(132, msg.getByte()); @@ -1226,11 +1305,9 @@ void ProtocolGame::parseSetOutfit(NetworkMessage &msg) newOutfit.lookFamiliarsType = msg.get(); uint8_t isMountRandomized = msg.getByte(); g_game().playerChangeOutfit(player->getID(), newOutfit, isMountRandomized); - } - else if (outfitType == 1) - { - //This value probably has something to do with try outfit variable inside outfit window dialog - //if try outfit is set to 2 it expects uint32_t value after mounted and disable mounts from outfit window dialog + } else if (outfitType == 1) { + // This value probably has something to do with try outfit variable inside outfit window dialog + // if try outfit is set to 2 it expects uint32_t value after mounted and disable mounts from outfit window dialog newOutfit.lookMount = 0; msg.get(); } else if (outfitType == 2) { @@ -1249,33 +1326,28 @@ void ProtocolGame::parseSetOutfit(NetworkMessage &msg) } } -void ProtocolGame::parseToggleMount(NetworkMessage &msg) -{ +void ProtocolGame::parseToggleMount(NetworkMessage &msg) { bool mount = msg.getByte() != 0; addGameTask(&Game::playerToggleMount, player->getID(), mount); } -void ProtocolGame::parseApplyImbuement(NetworkMessage &msg) -{ +void ProtocolGame::parseApplyImbuement(NetworkMessage &msg) { uint8_t slot = msg.getByte(); uint32_t imbuementId = msg.get(); bool protectionCharm = msg.getByte() != 0x00; addGameTask(&Game::playerApplyImbuement, player->getID(), imbuementId, slot, protectionCharm); } -void ProtocolGame::parseClearImbuement(NetworkMessage &msg) -{ +void ProtocolGame::parseClearImbuement(NetworkMessage &msg) { uint8_t slot = msg.getByte(); addGameTask(&Game::playerClearImbuement, player->getID(), slot); } -void ProtocolGame::parseCloseImbuementWindow(NetworkMessage &) -{ +void ProtocolGame::parseCloseImbuementWindow(NetworkMessage &) { addGameTask(&Game::playerCloseImbuementWindow, player->getID()); } -void ProtocolGame::parseUseItem(NetworkMessage &msg) -{ +void ProtocolGame::parseUseItem(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); @@ -1283,8 +1355,7 @@ void ProtocolGame::parseUseItem(NetworkMessage &msg) addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseItem, player->getID(), pos, stackpos, index, itemId); } -void ProtocolGame::parseUseItemEx(NetworkMessage &msg) -{ +void ProtocolGame::parseUseItemEx(NetworkMessage &msg) { Position fromPos = msg.getPosition(); uint16_t fromItemId = msg.get(); uint8_t fromStackPos = msg.getByte(); @@ -1294,8 +1365,7 @@ void ProtocolGame::parseUseItemEx(NetworkMessage &msg) addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseItemEx, player->getID(), fromPos, fromStackPos, fromItemId, toPos, toStackPos, toItemId); } -void ProtocolGame::parseUseWithCreature(NetworkMessage &msg) -{ +void ProtocolGame::parseUseWithCreature(NetworkMessage &msg) { Position fromPos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t fromStackPos = msg.getByte(); @@ -1303,60 +1373,51 @@ void ProtocolGame::parseUseWithCreature(NetworkMessage &msg) addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseWithCreature, player->getID(), fromPos, fromStackPos, creatureId, itemId); } -void ProtocolGame::parseCloseContainer(NetworkMessage &msg) -{ +void ProtocolGame::parseCloseContainer(NetworkMessage &msg) { uint8_t cid = msg.getByte(); addGameTask(&Game::playerCloseContainer, player->getID(), cid); } -void ProtocolGame::parseUpArrowContainer(NetworkMessage &msg) -{ +void ProtocolGame::parseUpArrowContainer(NetworkMessage &msg) { uint8_t cid = msg.getByte(); addGameTask(&Game::playerMoveUpContainer, player->getID(), cid); } -void ProtocolGame::parseUpdateContainer(NetworkMessage &msg) -{ +void ProtocolGame::parseUpdateContainer(NetworkMessage &msg) { uint8_t cid = msg.getByte(); addGameTask(&Game::playerUpdateContainer, player->getID(), cid); } -void ProtocolGame::parseTeleport(NetworkMessage &msg) -{ +void ProtocolGame::parseTeleport(NetworkMessage &msg) { Position newPosition = msg.getPosition(); addGameTask(&Game::playerTeleport, player->getID(), newPosition); } -void ProtocolGame::parseThrow(NetworkMessage &msg) -{ +void ProtocolGame::parseThrow(NetworkMessage &msg) { Position fromPos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t fromStackpos = msg.getByte(); Position toPos = msg.getPosition(); uint8_t count = msg.getByte(); - if (toPos != fromPos) - { + if (toPos != fromPos) { addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerMoveThing, player->getID(), fromPos, itemId, fromStackpos, toPos, count); } } -void ProtocolGame::parseLookAt(NetworkMessage &msg) -{ +void ProtocolGame::parseLookAt(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookAt, player->getID(), itemId, pos, stackpos); } -void ProtocolGame::parseLookInBattleList(NetworkMessage &msg) -{ +void ProtocolGame::parseLookInBattleList(NetworkMessage &msg) { uint32_t creatureId = msg.get(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInBattleList, player->getID(), creatureId); } -void ProtocolGame::parseQuickLoot(NetworkMessage &msg) -{ +void ProtocolGame::parseQuickLoot(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); @@ -1365,145 +1426,120 @@ void ProtocolGame::parseQuickLoot(NetworkMessage &msg) addGameTask(&Game::playerQuickLoot, player->getID(), pos, itemId, stackpos, nullptr, lootAllCorpses, autoLoot); } -void ProtocolGame::parseLootContainer(NetworkMessage &msg) -{ +void ProtocolGame::parseLootContainer(NetworkMessage &msg) { uint8_t action = msg.getByte(); - if (action == 0) - { + if (action == 0) { ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); addGameTask(&Game::playerSetLootContainer, player->getID(), category, pos, itemId, stackpos); - } - else if (action == 1) - { + } else if (action == 1) { ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); addGameTask(&Game::playerClearLootContainer, player->getID(), category); - } - else if (action == 2) - { + } else if (action == 2) { ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); addGameTask(&Game::playerOpenLootContainer, player->getID(), category); - } - else if (action == 3) - { + } else if (action == 3) { bool useMainAsFallback = msg.getByte() == 1; addGameTask(&Game::playerSetQuickLootFallback, player->getID(), useMainAsFallback); } } -void ProtocolGame::parseQuickLootBlackWhitelist(NetworkMessage &msg) -{ +void ProtocolGame::parseQuickLootBlackWhitelist(NetworkMessage &msg) { QuickLootFilter_t filter = (QuickLootFilter_t)msg.getByte(); std::vector listedItems; uint16_t size = msg.get(); listedItems.reserve(size); - for (int i = 0; i < size; i++) - { + for (int i = 0; i < size; i++) { listedItems.push_back(msg.get()); } addGameTask(&Game::playerQuickLootBlackWhitelist, player->getID(), filter, listedItems); } -void ProtocolGame::parseSay(NetworkMessage &msg) -{ +void ProtocolGame::parseSay(NetworkMessage &msg) { std::string receiver; uint16_t channelId; SpeakClasses type = static_cast(msg.getByte()); - switch (type) - { - case TALKTYPE_PRIVATE_TO: - case TALKTYPE_PRIVATE_RED_TO: - receiver = msg.getString(); - channelId = 0; - break; + switch (type) { + case TALKTYPE_PRIVATE_TO: + case TALKTYPE_PRIVATE_RED_TO: + receiver = msg.getString(); + channelId = 0; + break; - case TALKTYPE_CHANNEL_Y: - case TALKTYPE_CHANNEL_R1: - channelId = msg.get(); - break; + case TALKTYPE_CHANNEL_Y: + case TALKTYPE_CHANNEL_R1: + channelId = msg.get(); + break; - default: - channelId = 0; - break; + default: + channelId = 0; + break; } const std::string text = msg.getString(); - if (text.length() > 255) - { + if (text.length() > 255) { return; } addGameTask(&Game::playerSay, player->getID(), channelId, type, receiver, text); } -void ProtocolGame::parseFightModes(NetworkMessage &msg) -{ - uint8_t rawFightMode = msg.getByte(); // 1 - offensive, 2 - balanced, 3 - defensive - uint8_t rawChaseMode = msg.getByte(); // 0 - stand while fightning, 1 - chase opponent +void ProtocolGame::parseFightModes(NetworkMessage &msg) { + uint8_t rawFightMode = msg.getByte(); // 1 - offensive, 2 - balanced, 3 - defensive + uint8_t rawChaseMode = msg.getByte(); // 0 - stand while fightning, 1 - chase opponent uint8_t rawSecureMode = msg.getByte(); // 0 - can't attack unmarked, 1 - can attack unmarked // uint8_t rawPvpMode = msg.getByte(); // pvp mode introduced in 10.0 FightMode_t fightMode; - if (rawFightMode == 1) - { + if (rawFightMode == 1) { fightMode = FIGHTMODE_ATTACK; - } - else if (rawFightMode == 2) - { + } else if (rawFightMode == 2) { fightMode = FIGHTMODE_BALANCED; - } - else - { + } else { fightMode = FIGHTMODE_DEFENSE; } addGameTask(&Game::playerSetFightModes, player->getID(), fightMode, rawChaseMode != 0, rawSecureMode != 0); } -void ProtocolGame::parseAttack(NetworkMessage &msg) -{ +void ProtocolGame::parseAttack(NetworkMessage &msg) { uint32_t creatureId = msg.get(); // msg.get(); creatureId (same as above) addGameTask(&Game::playerSetAttackedCreature, player->getID(), creatureId); } -void ProtocolGame::parseFollow(NetworkMessage &msg) -{ +void ProtocolGame::parseFollow(NetworkMessage &msg) { uint32_t creatureId = msg.get(); // msg.get(); creatureId (same as above) addGameTask(&Game::playerFollowCreature, player->getID(), creatureId); } -void ProtocolGame::parseTextWindow(NetworkMessage &msg) -{ +void ProtocolGame::parseTextWindow(NetworkMessage &msg) { uint32_t windowTextId = msg.get(); const std::string newText = msg.getString(); addGameTask(&Game::playerWriteItem, player->getID(), windowTextId, newText); } -void ProtocolGame::parseHouseWindow(NetworkMessage &msg) -{ +void ProtocolGame::parseHouseWindow(NetworkMessage &msg) { uint8_t doorId = msg.getByte(); uint32_t id = msg.get(); const std::string text = msg.getString(); addGameTask(&Game::playerUpdateHouseWindow, player->getID(), doorId, id, text); } -void ProtocolGame::parseLookInShop(NetworkMessage &msg) -{ +void ProtocolGame::parseLookInShop(NetworkMessage &msg) { uint16_t id = msg.get(); uint8_t count = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInShop, player->getID(), id, count); } -void ProtocolGame::parsePlayerBuyOnShop(NetworkMessage &msg) -{ +void ProtocolGame::parsePlayerBuyOnShop(NetworkMessage &msg) { uint16_t id = msg.get(); uint8_t count = msg.getByte(); uint16_t amount = msg.get(); @@ -1512,18 +1548,16 @@ void ProtocolGame::parsePlayerBuyOnShop(NetworkMessage &msg) addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerBuyItem, player->getID(), id, count, amount, ignoreCap, inBackpacks); } -void ProtocolGame::parsePlayerSellOnShop(NetworkMessage &msg) -{ +void ProtocolGame::parsePlayerSellOnShop(NetworkMessage &msg) { uint16_t id = msg.get(); - uint8_t count = std::max(msg.getByte(), (uint8_t) 1); + uint8_t count = std::max(msg.getByte(), (uint8_t)1); uint16_t amount = msg.get(); bool ignoreEquipped = msg.getByte() != 0; addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerSellItem, player->getID(), id, count, amount, ignoreEquipped); } -void ProtocolGame::parseRequestTrade(NetworkMessage &msg) -{ +void ProtocolGame::parseRequestTrade(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); @@ -1531,27 +1565,23 @@ void ProtocolGame::parseRequestTrade(NetworkMessage &msg) addGameTask(&Game::playerRequestTrade, player->getID(), pos, stackpos, playerId, itemId); } -void ProtocolGame::parseLookInTrade(NetworkMessage &msg) -{ +void ProtocolGame::parseLookInTrade(NetworkMessage &msg) { bool counterOffer = (msg.getByte() == 0x01); uint8_t index = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInTrade, player->getID(), counterOffer, index); } -void ProtocolGame::parseAddVip(NetworkMessage &msg) -{ +void ProtocolGame::parseAddVip(NetworkMessage &msg) { const std::string name = msg.getString(); addGameTask(&Game::playerRequestAddVip, player->getID(), name); } -void ProtocolGame::parseRemoveVip(NetworkMessage &msg) -{ +void ProtocolGame::parseRemoveVip(NetworkMessage &msg) { uint32_t guid = msg.get(); addGameTask(&Game::playerRequestRemoveVip, player->getID(), guid); } -void ProtocolGame::parseEditVip(NetworkMessage &msg) -{ +void ProtocolGame::parseEditVip(NetworkMessage &msg) { uint32_t guid = msg.get(); const std::string description = msg.getString(); uint32_t icon = std::min(10, msg.get()); // 10 is max icon in 9.63 @@ -1559,40 +1589,33 @@ void ProtocolGame::parseEditVip(NetworkMessage &msg) addGameTask(&Game::playerRequestEditVip, player->getID(), guid, description, icon, notify); } -void ProtocolGame::parseRotateItem(NetworkMessage &msg) -{ +void ProtocolGame::parseRotateItem(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerRotateItem, player->getID(), pos, stackpos, itemId); } -void ProtocolGame::parseWrapableItem(NetworkMessage &msg) -{ +void ProtocolGame::parseWrapableItem(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerWrapableItem, player->getID(), pos, stackpos, itemId); } -void ProtocolGame::parseInspectionObject(NetworkMessage &msg) -{ +void ProtocolGame::parseInspectionObject(NetworkMessage &msg) { uint8_t inspectionType = msg.getByte(); - if (inspectionType == INSPECT_NORMALOBJECT) - { + if (inspectionType == INSPECT_NORMALOBJECT) { Position pos = msg.getPosition(); g_game().playerInspectItem(player, pos); - } - else if (inspectionType == INSPECT_NPCTRADE || inspectionType == INSPECT_CYCLOPEDIA) - { + } else if (inspectionType == INSPECT_NPCTRADE || inspectionType == INSPECT_CYCLOPEDIA) { uint16_t itemId = msg.get(); uint16_t itemCount = msg.getByte(); g_game().playerInspectItem(player, itemId, static_cast(itemCount), (inspectionType == INSPECT_CYCLOPEDIA)); } } -void ProtocolGame::sendSessionEndInformation(SessionEndInformations information) -{ +void ProtocolGame::sendSessionEndInformation(SessionEndInformations information) { auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x18); output->addByte(information); @@ -1600,8 +1623,7 @@ void ProtocolGame::sendSessionEndInformation(SessionEndInformations information) disconnect(); } -void ProtocolGame::sendItemInspection(uint16_t itemId, uint8_t itemCount, const Item *item, bool cyclopedia) -{ +void ProtocolGame::sendItemInspection(uint16_t itemId, uint8_t itemCount, const Item* item, bool cyclopedia) { NetworkMessage msg; msg.addByte(0x76); msg.addByte(0x00); @@ -1610,13 +1632,10 @@ void ProtocolGame::sendItemInspection(uint16_t itemId, uint8_t itemCount, const const ItemType &it = Item::items[itemId]; - if (item) - { + if (item) { msg.addString(item->getName()); AddItem(msg, item); - } - else - { + } else { msg.addString(it.name); AddItem(msg, it.id, itemCount, 0); } @@ -1624,35 +1643,30 @@ void ProtocolGame::sendItemInspection(uint16_t itemId, uint8_t itemCount, const auto descriptions = Item::getDescriptions(it, item); msg.addByte(descriptions.size()); - for (const auto &description : descriptions) - { + for (const auto &description : descriptions) { msg.addString(description.first); msg.addString(description.second); } writeToOutputBuffer(msg); } -void ProtocolGame::parseCyclopediaCharacterInfo(NetworkMessage &msg) -{ +void ProtocolGame::parseCyclopediaCharacterInfo(NetworkMessage &msg) { uint32_t characterID; CyclopediaCharacterInfoType_t characterInfoType; characterID = msg.get(); characterInfoType = static_cast(msg.getByte()); uint16_t entriesPerPage = 0, page = 0; - if (characterInfoType == CYCLOPEDIA_CHARACTERINFO_RECENTDEATHS || characterInfoType == CYCLOPEDIA_CHARACTERINFO_RECENTPVPKILLS) - { + if (characterInfoType == CYCLOPEDIA_CHARACTERINFO_RECENTDEATHS || characterInfoType == CYCLOPEDIA_CHARACTERINFO_RECENTPVPKILLS) { entriesPerPage = std::min(30, std::max(5, msg.get())); page = std::max(1, msg.get()); } - if (characterID == 0) - { + if (characterID == 0) { characterID = player->getGUID(); } g_game().playerCyclopediaCharacterInfo(player, characterID, characterInfoType, entriesPerPage, page); } -void ProtocolGame::parseHighscores(NetworkMessage &msg) -{ +void ProtocolGame::parseHighscores(NetworkMessage &msg) { HighscoreType_t type = static_cast(msg.getByte()); uint8_t category = msg.getByte(); uint32_t vocation = msg.get(); @@ -1660,16 +1674,14 @@ void ProtocolGame::parseHighscores(NetworkMessage &msg) const std::string worldName = msg.getString(); msg.getByte(); // Game World Category msg.getByte(); // BattlEye World Type - if (type == HIGHSCORE_GETENTRIES) - { + if (type == HIGHSCORE_GETENTRIES) { page = std::max(1, msg.get()); } uint8_t entriesPerPage = std::min(30, std::max(5, msg.getByte())); g_game().playerHighscores(player, type, category, vocation, worldName, page, entriesPerPage); } -void ProtocolGame::parseTaskHuntingAction(NetworkMessage &msg) -{ +void ProtocolGame::parseTaskHuntingAction(NetworkMessage &msg) { uint8_t slot = msg.getByte(); uint8_t action = msg.getByte(); bool upgrade = msg.getByte() != 0; @@ -1682,16 +1694,14 @@ void ProtocolGame::parseTaskHuntingAction(NetworkMessage &msg) addGameTask(&Game::playerTaskHuntingAction, player->getID(), slot, action, upgrade, raceId); } -void ProtocolGame::sendHighscoresNoData() -{ +void ProtocolGame::sendHighscoresNoData() { NetworkMessage msg; msg.addByte(0xB1); msg.addByte(0x01); // No data available writeToOutputBuffer(msg); } -void ProtocolGame::sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages) -{ +void ProtocolGame::sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages) { NetworkMessage msg; msg.addByte(0xB1); msg.addByte(0x00); // No data available @@ -1708,57 +1718,51 @@ void ProtocolGame::sendHighscores(const std::vector &charact msg.skipBytes(1); // Vocation Count msg.add(0xFFFFFFFF); // All Vocations - hardcoded - msg.addString("(all)"); // All Vocations - hardcoded + msg.addString("(all)"); // All Vocations - hardcoded uint32_t selectedVocation = 0xFFFFFFFF; const auto &vocationsMap = g_vocations().getVocations(); - for (const auto &it : vocationsMap) - { + for (const auto &it : vocationsMap) { const Vocation &vocation = it.second; - if (vocation.getFromVocation() == static_cast(vocation.getId())) - { + if (vocation.getFromVocation() == static_cast(vocation.getId())) { msg.add(vocation.getFromVocation()); // Vocation Id - msg.addString(vocation.getVocName()); // Vocation Name + msg.addString(vocation.getVocName()); // Vocation Name ++vocations; - if (vocation.getFromVocation() == vocationId) - { + if (vocation.getFromVocation() == vocationId) { selectedVocation = vocationId; } } } msg.add(selectedVocation); // Selected Vocation - HighscoreCategory highscoreCategories[] = - { - {"Experience Points", HIGHSCORE_CATEGORY_EXPERIENCE}, - {"Fist Fighting", HIGHSCORE_CATEGORY_FIST_FIGHTING}, - {"Club Fighting", HIGHSCORE_CATEGORY_CLUB_FIGHTING}, - {"Sword Fighting", HIGHSCORE_CATEGORY_SWORD_FIGHTING}, - {"Axe Fighting", HIGHSCORE_CATEGORY_AXE_FIGHTING}, - {"Distance Fighting", HIGHSCORE_CATEGORY_DISTANCE_FIGHTING}, - {"Shielding", HIGHSCORE_CATEGORY_SHIELDING}, - {"Fishing", HIGHSCORE_CATEGORY_FISHING}, - {"Magic Level", HIGHSCORE_CATEGORY_MAGIC_LEVEL}}; + HighscoreCategory highscoreCategories[] = { + { "Experience Points", HIGHSCORE_CATEGORY_EXPERIENCE }, + { "Fist Fighting", HIGHSCORE_CATEGORY_FIST_FIGHTING }, + { "Club Fighting", HIGHSCORE_CATEGORY_CLUB_FIGHTING }, + { "Sword Fighting", HIGHSCORE_CATEGORY_SWORD_FIGHTING }, + { "Axe Fighting", HIGHSCORE_CATEGORY_AXE_FIGHTING }, + { "Distance Fighting", HIGHSCORE_CATEGORY_DISTANCE_FIGHTING }, + { "Shielding", HIGHSCORE_CATEGORY_SHIELDING }, + { "Fishing", HIGHSCORE_CATEGORY_FISHING }, + { "Magic Level", HIGHSCORE_CATEGORY_MAGIC_LEVEL } + }; uint8_t selectedCategory = 0; msg.addByte(sizeof(highscoreCategories) / sizeof(HighscoreCategory)); // Category Count - for (HighscoreCategory &category : highscoreCategories) - { + for (HighscoreCategory &category : highscoreCategories) { msg.addByte(category.id); // Category Id msg.addString(category.name); // Category Name - if (category.id == categoryId) - { + if (category.id == categoryId) { selectedCategory = categoryId; } } msg.addByte(selectedCategory); // Selected Category - msg.add(page); // Current page + msg.add(page); // Current page msg.add(pages); // Pages msg.addByte(characters.size()); // Character Count - for (const HighscoreCharacter &character : characters) - { + for (const HighscoreCharacter &character : characters) { msg.add(character.rank); // Rank msg.addString(character.name); // Character Name msg.addString(""); // Probably Character Title(not visible in window) @@ -1779,18 +1783,14 @@ void ProtocolGame::sendHighscores(const std::vector &charact writeToOutputBuffer(msg); } -void ProtocolGame::parseTournamentLeaderboard(NetworkMessage &msg) -{ +void ProtocolGame::parseTournamentLeaderboard(NetworkMessage &msg) { uint8_t ledaerboardType = msg.getByte(); - if (ledaerboardType == 0) - { + if (ledaerboardType == 0) { const std::string worldName = msg.getString(); uint16_t currentPage = msg.get(); (void)worldName; (void)currentPage; - } - else if (ledaerboardType == 1) - { + } else if (ledaerboardType == 1) { const std::string worldName = msg.getString(); const std::string characterName = msg.getString(); (void)worldName; @@ -1802,27 +1802,22 @@ void ProtocolGame::parseTournamentLeaderboard(NetworkMessage &msg) addGameTask(&Game::playerTournamentLeaderboard, player->getID(), ledaerboardType); } -void ProtocolGame::parseConfigureShowOffSocket(NetworkMessage& msg) -{ +void ProtocolGame::parseConfigureShowOffSocket(NetworkMessage &msg) { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerConfigureShowOffSocket(player->getID(), pos, stackpos, itemId); } -void ProtocolGame::parseRuleViolationReport(NetworkMessage &msg) -{ +void ProtocolGame::parseRuleViolationReport(NetworkMessage &msg) { uint8_t reportType = msg.getByte(); uint8_t reportReason = msg.getByte(); const std::string &targetName = msg.getString(); const std::string &comment = msg.getString(); std::string translation; - if (reportType == REPORT_TYPE_NAME) - { + if (reportType == REPORT_TYPE_NAME) { translation = msg.getString(); - } - else if (reportType == REPORT_TYPE_STATEMENT) - { + } else if (reportType == REPORT_TYPE_STATEMENT) { translation = msg.getString(); msg.get(); // statement id, used to get whatever player have said, we don't log that. } @@ -1830,25 +1825,20 @@ void ProtocolGame::parseRuleViolationReport(NetworkMessage &msg) addGameTask(&Game::playerReportRuleViolationReport, player->getID(), targetName, reportType, reportReason, comment, translation); } -void ProtocolGame::parseBestiarysendRaces() -{ +void ProtocolGame::parseBestiarysendRaces() { NetworkMessage msg; msg.addByte(0xd5); msg.add(BESTY_RACE_LAST); std::map mtype_list = g_game().getBestiaryList(); - for (uint8_t i = BESTY_RACE_FIRST; i <= BESTY_RACE_LAST; i++) - { + for (uint8_t i = BESTY_RACE_FIRST; i <= BESTY_RACE_LAST; i++) { std::string BestClass = ""; uint16_t count = 0; - for (auto rit : mtype_list) - { - const MonsterType *mtype = g_monsters().getMonsterType(rit.second); - if (!mtype) - { + for (auto rit : mtype_list) { + const MonsterType* mtype = g_monsters().getMonsterType(rit.second); + if (!mtype) { return; } - if (mtype->info.bestiaryRace == static_cast(i)) - { + if (mtype->info.bestiaryRace == static_cast(i)) { count += 1; BestClass = mtype->info.bestiaryClass; } @@ -1863,36 +1853,31 @@ void ProtocolGame::parseBestiarysendRaces() player->BestiarysendCharms(); } -void ProtocolGame::sendBestiaryEntryChanged(uint16_t raceid) -{ +void ProtocolGame::sendBestiaryEntryChanged(uint16_t raceid) { NetworkMessage msg; msg.addByte(0xd9); msg.add(raceid); writeToOutputBuffer(msg); } -void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) -{ +void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) { uint16_t raceId = msg.get(); std::string Class = ""; - MonsterType *mtype = nullptr; + MonsterType* mtype = nullptr; std::map mtype_list = g_game().getBestiaryList(); auto ait = mtype_list.find(raceId); - if (ait != mtype_list.end()) - { - MonsterType *mType = g_monsters().getMonsterType(ait->second); - if (mType) - { + if (ait != mtype_list.end()) { + MonsterType* mType = g_monsters().getMonsterType(ait->second); + if (mType) { Class = mType->info.bestiaryClass; mtype = mType; } } - if (!mtype) - { + if (!mtype) { SPDLOG_WARN("[ProtocolGame::parseBestiarysendMonsterData] - " - "MonsterType was not found"); + "MonsterType was not found"); return; } @@ -1916,53 +1901,44 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) std::vector lootList = mtype->info.lootItems; newmsg.addByte(lootList.size()); - for (LootBlock loot : lootList) - { + for (LootBlock loot : lootList) { int8_t difficult = g_iobestiary().calculateDifficult(loot.chance); bool shouldAddItem = false; - switch (currentLevel) - { - case 1: - shouldAddItem = false; - break; - case 2: - if (difficult < 2) - { - shouldAddItem = true; - } - break; - case 3: - if (difficult < 3) - { + switch (currentLevel) { + case 1: + shouldAddItem = false; + break; + case 2: + if (difficult < 2) { + shouldAddItem = true; + } + break; + case 3: + if (difficult < 3) { + shouldAddItem = true; + } + break; + case 4: shouldAddItem = true; - } - break; - case 4: - shouldAddItem = true; - break; + break; } newmsg.add(shouldAddItem == true ? loot.id : 0); newmsg.addByte(difficult); newmsg.addByte(0); // 1 if special event - 0 if regular loot (?) - if (shouldAddItem == true) - { + if (shouldAddItem == true) { newmsg.addString(loot.name); newmsg.addByte(loot.countmax > 0 ? 0x1 : 0x0); } } - if (currentLevel > 1) - { + if (currentLevel > 1) { newmsg.add(mtype->info.bestiaryCharmsPoints); int8_t attackmode = 0; - if (!mtype->info.isHostile) - { + if (!mtype->info.isHostile) { attackmode = 2; - } - else if (mtype->info.targetDistance) - { + } else if (mtype->info.targetDistance) { attackmode = 1; } @@ -1974,13 +1950,11 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) newmsg.add(mtype->info.armor); } - if (currentLevel > 2) - { + if (currentLevel > 2) { std::map elements = g_iobestiary().getMonsterElements(mtype); newmsg.addByte(elements.size()); - for (auto it = std::begin(elements), end = std::end(elements); it != end; it++) - { + for (auto it = std::begin(elements), end = std::end(elements); it != end; it++) { newmsg.addByte(it->first); newmsg.add(it->second); } @@ -1989,17 +1963,13 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) newmsg.addString(mtype->info.bestiaryLocations); } - if (currentLevel > 3) - { + if (currentLevel > 3) { charmRune_t mType_c = g_iobestiary().getCharmFromTarget(player, mtype); - if (mType_c != CHARM_NONE) - { + if (mType_c != CHARM_NONE) { newmsg.addByte(1); newmsg.addByte(mType_c); newmsg.add(player->getLevel() * 100); - } - else - { + } else { newmsg.addByte(0); newmsg.addByte(1); } @@ -2008,23 +1978,19 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) writeToOutputBuffer(newmsg); } -void ProtocolGame::addBestiaryTrackerList(NetworkMessage &msg) -{ +void ProtocolGame::addBestiaryTrackerList(NetworkMessage &msg) { uint16_t thisrace = msg.get(); std::map mtype_list = g_game().getBestiaryList(); auto it = mtype_list.find(thisrace); - if (it != mtype_list.end()) - { - MonsterType *mtype = g_monsters().getMonsterType(it->second); - if (mtype) - { + if (it != mtype_list.end()) { + MonsterType* mtype = g_monsters().getMonsterType(it->second); + if (mtype) { player->addBestiaryTrackerList(mtype); } } } -void ProtocolGame::sendTeamFinderList() -{ +void ProtocolGame::sendTeamFinderList() { if (!player) return; @@ -2089,8 +2055,7 @@ void ProtocolGame::sendTeamFinderList() writeToOutputBuffer(msg); } -void ProtocolGame::sendLeaderTeamFinder(bool reset) -{ +void ProtocolGame::sendLeaderTeamFinder(bool reset) { if (!player) return; @@ -2172,8 +2137,7 @@ void ProtocolGame::sendLeaderTeamFinder(bool reset) writeToOutputBuffer(msg); } -void ProtocolGame::createLeaderTeamFinder(NetworkMessage &msg) -{ +void ProtocolGame::createLeaderTeamFinder(NetworkMessage &msg) { if (!player) return; @@ -2232,19 +2196,18 @@ void ProtocolGame::createLeaderTeamFinder(NetworkMessage &msg) if (teamAssemble->partyBool && player->getParty()) { for (Player* member : player->getParty()->getMembers()) { if (member && member->getGUID() != player->getGUID()) { - members.insert({member->getGUID(), 3}); + members.insert({ member->getGUID(), 3 }); } } if (player->getParty()->getLeader()->getGUID() != player->getGUID()) { - members.insert({player->getParty()->getLeader()->getGUID(), 3}); + members.insert({ player->getParty()->getLeader()->getGUID(), 3 }); } } teamAssemble->membersMap = members; g_game().registerTeamFinderAssemble(player->getGUID(), teamAssemble); } -void ProtocolGame::parsePartyAnalyzerAction(NetworkMessage &msg) const -{ +void ProtocolGame::parsePartyAnalyzerAction(NetworkMessage &msg) const { if (!player) { return; } @@ -2271,8 +2234,7 @@ void ProtocolGame::parsePartyAnalyzerAction(NetworkMessage &msg) const } } -void ProtocolGame::parseLeaderFinderWindow(NetworkMessage &msg) -{ +void ProtocolGame::parseLeaderFinderWindow(NetworkMessage &msg) { if (!player) return; @@ -2303,7 +2265,7 @@ void ProtocolGame::parseLeaderFinderWindow(NetworkMessage &msg) return; uint8_t memberStatus = msg.getByte(); - for (auto& memberPair : teamAssemble->membersMap) { + for (auto &memberPair : teamAssemble->membersMap) { if (memberPair.first == memberID) { memberPair.second = memberStatus; } @@ -2340,14 +2302,13 @@ void ProtocolGame::parseLeaderFinderWindow(NetworkMessage &msg) } } -void ProtocolGame::parseMemberFinderWindow(NetworkMessage &msg) -{ +void ProtocolGame::parseMemberFinderWindow(NetworkMessage &msg) { if (!player) return; uint8_t action = msg.getByte(); if (action == 0) { - player->sendTeamFinderList(); + player->sendTeamFinderList(); } else { uint32_t leaderID = msg.get(); const Player* leader = g_game().getPlayerByGUID(leaderID); @@ -2366,7 +2327,7 @@ void ProtocolGame::parseMemberFinderWindow(NetworkMessage &msg) if (action == 1) { leader->sendTextMessage(MESSAGE_STATUS, "There is a new request to join your team."); - teamAssemble->membersMap.insert({player->getGUID(), 1}); + teamAssemble->membersMap.insert({ player->getGUID(), 1 }); } else { for (auto itt = teamAssemble->membersMap.begin(), end = teamAssemble->membersMap.end(); itt != end; ++itt) { if (itt->first == player->getGUID()) { @@ -2379,21 +2340,18 @@ void ProtocolGame::parseMemberFinderWindow(NetworkMessage &msg) } } -void ProtocolGame::parseSendBuyCharmRune(NetworkMessage &msg) -{ +void ProtocolGame::parseSendBuyCharmRune(NetworkMessage &msg) { charmRune_t runeID = static_cast(msg.getByte()); uint8_t action = msg.getByte(); uint16_t raceid = msg.get(); g_iobestiary().sendBuyCharmRune(player, runeID, action, raceid); } -void ProtocolGame::refreshBestiaryTracker(std::list trackerList) -{ +void ProtocolGame::refreshBestiaryTracker(std::list trackerList) { NetworkMessage msg; msg.addByte(0xB9); msg.addByte(trackerList.size()); - for (MonsterType *mtype : trackerList) - { + for (MonsterType* mtype : trackerList) { uint32_t killAmount = player->getBestiaryKillCount(mtype->info.raceid); msg.add(mtype->info.raceid); msg.add(killAmount); @@ -2401,55 +2359,43 @@ void ProtocolGame::refreshBestiaryTracker(std::list trackerList) msg.add(mtype->info.bestiarySecondUnlock); msg.add(mtype->info.bestiaryToUnlock); - if (g_iobestiary().getKillStatus(mtype, killAmount) == 4) - { + if (g_iobestiary().getKillStatus(mtype, killAmount) == 4) { msg.addByte(4); - } - else - { + } else { msg.addByte(0); } } writeToOutputBuffer(msg); } -void ProtocolGame::BestiarysendCharms() -{ +void ProtocolGame::BestiarysendCharms() { int32_t removeRuneCost = player->getLevel() * 100; - if (player->hasCharmExpansion()) - { + if (player->hasCharmExpansion()) { removeRuneCost = (removeRuneCost * 75) / 100; } NetworkMessage msg; msg.addByte(0xd8); msg.add(player->getCharmPoints()); - std::vector charmList = g_game().getCharmList(); + std::vector charmList = g_game().getCharmList(); msg.addByte(charmList.size()); - for (Charm *c_type : charmList) - { + for (Charm* c_type : charmList) { msg.addByte(c_type->id); msg.addString(c_type->name); msg.addString(c_type->description); msg.addByte(0); // Unknown msg.add(c_type->points); - if (g_iobestiary().hasCharmUnlockedRuneBit(c_type, player->getUnlockedRunesBit())) - { + if (g_iobestiary().hasCharmUnlockedRuneBit(c_type, player->getUnlockedRunesBit())) { msg.addByte(1); uint16_t raceid = player->parseRacebyCharm(c_type->id, false, 0); - if (raceid > 0) - { + if (raceid > 0) { msg.addByte(1); msg.add(raceid); msg.add(removeRuneCost); - } - else - { + } else { msg.addByte(0); } - } - else - { + } else { msg.addByte(0); msg.addByte(0); } @@ -2459,24 +2405,21 @@ void ProtocolGame::BestiarysendCharms() std::list finishedMonsters = g_iobestiary().getBestiaryFinished(player); std::list usedRunes = g_iobestiary().getCharmUsedRuneBitAll(player); - for (charmRune_t charmRune : usedRunes) - { - Charm *tmpCharm = g_iobestiary().getBestiaryCharm(charmRune); + for (charmRune_t charmRune : usedRunes) { + Charm* tmpCharm = g_iobestiary().getBestiaryCharm(charmRune); uint16_t tmp_raceid = player->parseRacebyCharm(tmpCharm->id, false, 0); finishedMonsters.remove(tmp_raceid); } msg.add(finishedMonsters.size()); - for (uint16_t raceid_tmp : finishedMonsters) - { + for (uint16_t raceid_tmp : finishedMonsters) { msg.add(raceid_tmp); } writeToOutputBuffer(msg); } -void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) -{ +void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) { std::ostringstream ss; std::map race = {}; std::string text = ""; @@ -2490,7 +2433,7 @@ void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) if (player->getBestiaryKillCount(raceid) > 0) { auto it = mtype_list.find(raceid); if (it != mtype_list.end()) { - race.insert({raceid, it->second}); + race.insert({ raceid, it->second }); } } } @@ -2498,10 +2441,10 @@ void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) std::string raceName = msg.getString(); race = g_iobestiary().findRaceByName(raceName); - if (race.size() == 0) - { + if (race.size() == 0) { SPDLOG_WARN("[ProtocolGame::parseBestiarysendCreature] - " - "Race was not found: {}, search: {}", raceName, search); + "Race was not found: {}, search: {}", + raceName, search); return; } text = raceName; @@ -2512,61 +2455,49 @@ void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) newmsg.add(race.size()); std::map creaturesKilled = g_iobestiary().getBestiaryKillCountByMonsterIDs(player, race); - for (auto it_ : race) - { + for (auto it_ : race) { uint16_t raceid_ = it_.first; newmsg.add(raceid_); uint8_t progress = 0; - for (const auto &_it : creaturesKilled) - { - if (_it.first == raceid_) - { - MonsterType *tmpType = g_monsters().getMonsterType(it_.second); - if (!tmpType) - { + for (const auto &_it : creaturesKilled) { + if (_it.first == raceid_) { + MonsterType* tmpType = g_monsters().getMonsterType(it_.second); + if (!tmpType) { return; } progress = g_iobestiary().getKillStatus(tmpType, _it.second); } } - if (progress > 0) - { + if (progress > 0) { newmsg.add(static_cast(progress)); - } - else - { + } else { newmsg.addByte(0); } } writeToOutputBuffer(newmsg); } -void ProtocolGame::parseBugReport(NetworkMessage &msg) -{ +void ProtocolGame::parseBugReport(NetworkMessage &msg) { uint8_t category = msg.getByte(); std::string message = msg.getString(); Position position; - if (category == BUG_CATEGORY_MAP) - { + if (category == BUG_CATEGORY_MAP) { position = msg.getPosition(); } addGameTask(&Game::playerReportBug, player->getID(), message, position, category); } -void ProtocolGame::parseGreet(NetworkMessage &msg) -{ +void ProtocolGame::parseGreet(NetworkMessage &msg) { uint32_t npcId = msg.get(); addGameTask(&Game::playerNpcGreet, player->getID(), npcId); } -void ProtocolGame::parseDebugAssert(NetworkMessage &msg) -{ - if (debugAssertSent) - { +void ProtocolGame::parseDebugAssert(NetworkMessage &msg) { + if (debugAssertSent) { return; } @@ -2579,8 +2510,7 @@ void ProtocolGame::parseDebugAssert(NetworkMessage &msg) addGameTask(&Game::playerDebugAssert, player->getID(), assertLine, date, description, comment); } -void ProtocolGame::parsePreyAction(NetworkMessage &msg) -{ +void ProtocolGame::parsePreyAction(NetworkMessage &msg) { int8_t index = -1; uint8_t slot = msg.getByte(); uint8_t action = msg.getByte(); @@ -2601,8 +2531,7 @@ void ProtocolGame::parsePreyAction(NetworkMessage &msg) addGameTask(&Game::playerPreyAction, player->getID(), slot, action, option, index, raceId); } -void ProtocolGame::parseSendResourceBalance() -{ +void ProtocolGame::parseSendResourceBalance() { auto [sliverCount, coreCount] = player->getForgeSliversAndCores(); sendResourcesBalance( @@ -2616,61 +2545,48 @@ void ProtocolGame::parseSendResourceBalance() ); } -void ProtocolGame::parseInviteToParty(NetworkMessage &msg) -{ +void ProtocolGame::parseInviteToParty(NetworkMessage &msg) { uint32_t targetId = msg.get(); addGameTask(&Game::playerInviteToParty, player->getID(), targetId); } -void ProtocolGame::parseJoinParty(NetworkMessage &msg) -{ +void ProtocolGame::parseJoinParty(NetworkMessage &msg) { uint32_t targetId = msg.get(); addGameTask(&Game::playerJoinParty, player->getID(), targetId); } -void ProtocolGame::parseRevokePartyInvite(NetworkMessage &msg) -{ +void ProtocolGame::parseRevokePartyInvite(NetworkMessage &msg) { uint32_t targetId = msg.get(); addGameTask(&Game::playerRevokePartyInvitation, player->getID(), targetId); } -void ProtocolGame::parsePassPartyLeadership(NetworkMessage &msg) -{ +void ProtocolGame::parsePassPartyLeadership(NetworkMessage &msg) { uint32_t targetId = msg.get(); addGameTask(&Game::playerPassPartyLeadership, player->getID(), targetId); } -void ProtocolGame::parseEnableSharedPartyExperience(NetworkMessage &msg) -{ +void ProtocolGame::parseEnableSharedPartyExperience(NetworkMessage &msg) { bool sharedExpActive = msg.getByte() == 1; addGameTask(&Game::playerEnableSharedPartyExperience, player->getID(), sharedExpActive); } -void ProtocolGame::parseQuestLine(NetworkMessage &msg) -{ +void ProtocolGame::parseQuestLine(NetworkMessage &msg) { uint16_t questId = msg.get(); addGameTask(&Game::playerShowQuestLine, player->getID(), questId); } -void ProtocolGame::parseMarketLeave() -{ +void ProtocolGame::parseMarketLeave() { addGameTask(&Game::playerLeaveMarket, player->getID()); } -void ProtocolGame::parseMarketBrowse(NetworkMessage &msg) -{ +void ProtocolGame::parseMarketBrowse(NetworkMessage &msg) { uint8_t browseId = msg.get(); - if (browseId == MARKETREQUEST_OWN_OFFERS) - { + if (browseId == MARKETREQUEST_OWN_OFFERS) { addGameTask(&Game::playerBrowseMarketOwnOffers, player->getID()); - } - else if (browseId == MARKETREQUEST_OWN_HISTORY) - { + } else if (browseId == MARKETREQUEST_OWN_HISTORY) { addGameTask(&Game::playerBrowseMarketOwnHistory, player->getID()); - } - else - { + } else { uint16_t itemId = msg.get(); uint8_t tier = msg.get(); player->sendMarketEnter(player->getLastDepotId()); @@ -2678,9 +2594,7 @@ void ProtocolGame::parseMarketBrowse(NetworkMessage &msg) } } - -void ProtocolGame::parseMarketCreateOffer(NetworkMessage &msg) -{ +void ProtocolGame::parseMarketCreateOffer(NetworkMessage &msg) { uint8_t type = msg.getByte(); uint16_t itemId = msg.get(); uint8_t itemTier = 0; @@ -2690,69 +2604,59 @@ void ProtocolGame::parseMarketCreateOffer(NetworkMessage &msg) uint16_t amount = msg.get(); uint64_t price = msg.get(); bool anonymous = (msg.getByte() != 0); - if (amount > 0 && price > 0) - { + if (amount > 0 && price > 0) { addGameTask(&Game::playerCreateMarketOffer, player->getID(), type, itemId, amount, price, itemTier, anonymous); } } -void ProtocolGame::parseMarketCancelOffer(NetworkMessage &msg) -{ +void ProtocolGame::parseMarketCancelOffer(NetworkMessage &msg) { uint32_t timestamp = msg.get(); uint16_t counter = msg.get(); - if (counter > 0) - { + if (counter > 0) { addGameTask(&Game::playerCancelMarketOffer, player->getID(), timestamp, counter); } updateCoinBalance(); } -void ProtocolGame::parseMarketAcceptOffer(NetworkMessage &msg) -{ +void ProtocolGame::parseMarketAcceptOffer(NetworkMessage &msg) { uint32_t timestamp = msg.get(); uint16_t counter = msg.get(); uint16_t amount = msg.get(); - if (amount > 0 && counter > 0) - { + if (amount > 0 && counter > 0) { addGameTask(&Game::playerAcceptMarketOffer, player->getID(), timestamp, counter, amount); } updateCoinBalance(); } -void ProtocolGame::parseModalWindowAnswer(NetworkMessage &msg) -{ +void ProtocolGame::parseModalWindowAnswer(NetworkMessage &msg) { uint32_t id = msg.get(); uint8_t button = msg.getByte(); uint8_t choice = msg.getByte(); addGameTask(&Game::playerAnswerModalWindow, player->getID(), id, button, choice); } -void ProtocolGame::parseBrowseField(NetworkMessage &msg) -{ +void ProtocolGame::parseBrowseField(NetworkMessage &msg) { const Position &pos = msg.getPosition(); addGameTask(&Game::playerBrowseField, player->getID(), pos); } -void ProtocolGame::parseSeekInContainer(NetworkMessage &msg) -{ +void ProtocolGame::parseSeekInContainer(NetworkMessage &msg) { uint8_t containerId = msg.getByte(); uint16_t index = msg.get(); addGameTask(&Game::playerSeekInContainer, player->getID(), containerId, index); } // Send methods -void ProtocolGame::sendOpenPrivateChannel(const std::string &receiver) -{ +void ProtocolGame::sendOpenPrivateChannel(const std::string &receiver) { NetworkMessage msg; msg.addByte(0xAD); msg.addString(receiver); writeToOutputBuffer(msg); } -void ProtocolGame::sendExperienceTracker(int64_t rawExp, int64_t finalExp) -{ +void ProtocolGame::sendExperienceTracker(int64_t rawExp, int64_t finalExp) { NetworkMessage msg; msg.addByte(0xAF); msg.add(rawExp); @@ -2760,8 +2664,7 @@ void ProtocolGame::sendExperienceTracker(int64_t rawExp, int64_t finalExp) writeToOutputBuffer(msg); } -void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent) -{ +void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent) { NetworkMessage msg; msg.addByte(0xF3); msg.add(channelId); @@ -2770,10 +2673,8 @@ void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string &playe writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureOutfit(const Creature *creature, const Outfit_t &outfit) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureOutfit(const Creature* creature, const Outfit_t &outfit) { + if (!canSee(creature)) { return; } @@ -2781,8 +2682,7 @@ void ProtocolGame::sendCreatureOutfit(const Creature *creature, const Outfit_t & msg.addByte(0x8E); msg.add(creature->getID()); AddOutfit(msg, outfit); - if (outfit.lookMount != 0) - { + if (outfit.lookMount != 0) { msg.addByte(outfit.lookMountHead); msg.addByte(outfit.lookMountBody); msg.addByte(outfit.lookMountLegs); @@ -2791,10 +2691,8 @@ void ProtocolGame::sendCreatureOutfit(const Creature *creature, const Outfit_t & writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureLight(const Creature *creature) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureLight(const Creature* creature) { + if (!canSee(creature)) { return; } @@ -2803,10 +2701,8 @@ void ProtocolGame::sendCreatureLight(const Creature *creature) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureIcon(const Creature* creature) -{ - if (!creature) - { +void ProtocolGame::sendCreatureIcon(const Creature* creature) { + if (!creature) { return; } @@ -2828,15 +2724,13 @@ void ProtocolGame::sendCreatureIcon(const Creature* creature) writeToOutputBuffer(msg); } -void ProtocolGame::sendWorldLight(const LightInfo &lightInfo) -{ +void ProtocolGame::sendWorldLight(const LightInfo &lightInfo) { NetworkMessage msg; AddWorldLight(msg, lightInfo); writeToOutputBuffer(msg); } -void ProtocolGame::sendTibiaTime(int32_t time) -{ +void ProtocolGame::sendTibiaTime(int32_t time) { NetworkMessage msg; msg.addByte(0xEF); msg.addByte(time / 60); @@ -2844,10 +2738,8 @@ void ProtocolGame::sendTibiaTime(int32_t time) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureWalkthrough(const Creature *creature, bool walkthrough) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureWalkthrough(const Creature* creature, bool walkthrough) { + if (!canSee(creature)) { return; } @@ -2858,10 +2750,8 @@ void ProtocolGame::sendCreatureWalkthrough(const Creature *creature, bool walkth writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureShield(const Creature *creature) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureShield(const Creature* creature) { + if (!canSee(creature)) { return; } @@ -2872,10 +2762,8 @@ void ProtocolGame::sendCreatureShield(const Creature *creature) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureEmblem(const Creature *creature) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureEmblem(const Creature* creature) { + if (!canSee(creature)) { return; } @@ -2891,15 +2779,12 @@ void ProtocolGame::sendCreatureEmblem(const Creature *creature) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSkull(const Creature *creature) -{ - if (g_game().getWorldType() != WORLD_TYPE_PVP) - { +void ProtocolGame::sendCreatureSkull(const Creature* creature) { + if (g_game().getWorldType() != WORLD_TYPE_PVP) { return; } - if (!canSee(creature)) - { + if (!canSee(creature)) { return; } @@ -2910,8 +2795,7 @@ void ProtocolGame::sendCreatureSkull(const Creature *creature) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureType(const Creature *creature, uint8_t creatureType) -{ +void ProtocolGame::sendCreatureType(const Creature* creature, uint8_t creatureType) { NetworkMessage msg; msg.addByte(0x95); msg.add(creature->getID()); @@ -2931,10 +2815,8 @@ void ProtocolGame::sendCreatureType(const Creature *creature, uint8_t creatureTy writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSquare(const Creature *creature, SquareColor_t color) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureSquare(const Creature* creature, SquareColor_t color) { + if (!canSee(creature)) { return; } @@ -2946,16 +2828,14 @@ void ProtocolGame::sendCreatureSquare(const Creature *creature, SquareColor_t co writeToOutputBuffer(msg); } -void ProtocolGame::sendTutorial(uint8_t tutorialId) -{ +void ProtocolGame::sendTutorial(uint8_t tutorialId) { NetworkMessage msg; msg.addByte(0xDC); msg.addByte(tutorialId); writeToOutputBuffer(msg); } -void ProtocolGame::sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc) -{ +void ProtocolGame::sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc) { NetworkMessage msg; msg.addByte(0xDD); msg.addByte(0x00); // unknow @@ -2966,8 +2846,7 @@ void ProtocolGame::sendAddMarker(const Position &pos, uint8_t markType, const st writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t characterInfoType, uint8_t errorCode) -{ +void ProtocolGame::sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t characterInfoType, uint8_t errorCode) { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(static_cast(characterInfoType)); @@ -2975,8 +2854,7 @@ void ProtocolGame::sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t c writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterBaseInformation() -{ +void ProtocolGame::sendCyclopediaCharacterBaseInformation() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_BASEINFORMATION); @@ -2992,8 +2870,7 @@ void ProtocolGame::sendCyclopediaCharacterBaseInformation() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterGeneralStats() -{ +void ProtocolGame::sendCyclopediaCharacterGeneralStats() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_GENERALSTATS); @@ -3022,7 +2899,7 @@ void ProtocolGame::sendCyclopediaCharacterGeneralStats() msg.addByte(player->getSoul()); msg.add(player->getStaminaMinutes()); - Condition *condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); + Condition* condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); msg.add(condition ? condition->getTicks() / 1000 : 0x00); msg.add(player->getOfflineTrainingTime() / 60 / 1000); msg.add(player->getSpeed()); @@ -3038,9 +2915,8 @@ void ProtocolGame::sendCyclopediaCharacterGeneralStats() msg.add(player->getBaseMagicLevel()); msg.add(player->getMagicLevelPercent() * 100); - for (uint8_t i = SKILL_FIRST; i < SKILL_CRITICAL_HIT_CHANCE; ++i) - { - static const uint8_t HardcodedSkillIds[] = {11, 9, 8, 10, 7, 6, 13}; + for (uint8_t i = SKILL_FIRST; i < SKILL_CRITICAL_HIT_CHANCE; ++i) { + static const uint8_t HardcodedSkillIds[] = { 11, 9, 8, 10, 7, 6, 13 }; msg.addByte(HardcodedSkillIds[i]); msg.add(std::min(player->getSkillLevel(i), std::numeric_limits::max())); msg.add(player->getBaseSkill(i)); @@ -3055,14 +2931,12 @@ void ProtocolGame::sendCyclopediaCharacterGeneralStats() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterCombatStats() -{ +void ProtocolGame::sendCyclopediaCharacterCombatStats() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_COMBATSTATS); msg.addByte(0x00); - for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; ++i) - { + for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; ++i) { msg.add(std::min(player->getSkillLevel(i), std::numeric_limits::max())); msg.add(0); } @@ -3077,8 +2951,7 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() msg.add(0); // Percentage bonus // Perfect shot range (12.70) - for (uint16_t i = 1; i <= 5; i++) - { + for (uint16_t i = 1; i <= 5; i++) { msg.add(0x00); } @@ -3087,10 +2960,8 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() uint8_t haveBlesses = 0; uint8_t blessings = 8; - for (uint8_t i = 1; i < blessings; ++i) - { - if (player->hasBlessing(i)) - { + for (uint8_t i = 1; i < blessings; ++i) { + if (player->hasBlessing(i)) { ++haveBlesses; } } @@ -3098,25 +2969,19 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() msg.addByte(haveBlesses); msg.addByte(blessings); - const Item *weapon = player->getWeapon(); - if (weapon) - { + const Item* weapon = player->getWeapon(); + if (weapon) { const ItemType &it = Item::items[weapon->getID()]; - if (it.weaponType == WEAPON_WAND) - { + if (it.weaponType == WEAPON_WAND) { msg.add(it.maxHitChance); msg.addByte(getCipbiaElement(it.combatType)); msg.addByte(0); msg.addByte(CIPBIA_ELEMENTAL_UNDEFINED); - } - else if (it.weaponType == WEAPON_DISTANCE || it.weaponType == WEAPON_AMMO) - { + } else if (it.weaponType == WEAPON_DISTANCE || it.weaponType == WEAPON_AMMO) { int32_t attackValue = weapon->getAttack(); - if (it.weaponType == WEAPON_AMMO) - { - const Item *weaponItem = player->getWeapon(true); - if (weaponItem) - { + if (it.weaponType == WEAPON_AMMO) { + const Item* weaponItem = player->getWeapon(true); + if (weaponItem) { attackValue += weaponItem->getAttack(); } } @@ -3124,49 +2989,37 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); float attackFactor = player->getAttackFactor(); int32_t maxDamage = static_cast(Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue, attackFactor, true) * player->getVocation()->distDamageMultiplier); - if (it.abilities && it.abilities->elementType != COMBAT_NONE) - { + if (it.abilities && it.abilities->elementType != COMBAT_NONE) { maxDamage += static_cast(Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue - weapon->getAttack() + it.abilities->elementDamage, attackFactor, true) * player->getVocation()->distDamageMultiplier); } msg.add(maxDamage >> 1); msg.addByte(CIPBIA_ELEMENTAL_PHYSICAL); - if (it.abilities && it.abilities->elementType != COMBAT_NONE) - { + if (it.abilities && it.abilities->elementType != COMBAT_NONE) { msg.addByte(static_cast(it.abilities->elementDamage) * 100 / attackValue); msg.addByte(getCipbiaElement(it.abilities->elementType)); - } - else - { + } else { msg.addByte(0); msg.addByte(CIPBIA_ELEMENTAL_UNDEFINED); } - } - else - { + } else { int32_t attackValue = std::max(0, weapon->getAttack()); int32_t attackSkill = player->getWeaponSkill(weapon); float attackFactor = player->getAttackFactor(); int32_t maxDamage = static_cast(Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue, attackFactor, true) * player->getVocation()->meleeDamageMultiplier); - if (it.abilities && it.abilities->elementType != COMBAT_NONE) - { + if (it.abilities && it.abilities->elementType != COMBAT_NONE) { maxDamage += static_cast(Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, it.abilities->elementDamage, attackFactor, true) * player->getVocation()->meleeDamageMultiplier); } msg.add(maxDamage >> 1); msg.addByte(CIPBIA_ELEMENTAL_PHYSICAL); - if (it.abilities && it.abilities->elementType != COMBAT_NONE) - { + if (it.abilities && it.abilities->elementType != COMBAT_NONE) { msg.addByte(static_cast(it.abilities->elementDamage) * 100 / attackValue); msg.addByte(getCipbiaElement(it.abilities->elementType)); - } - else - { + } else { msg.addByte(0); msg.addByte(CIPBIA_ELEMENTAL_UNDEFINED); } } - } - else - { + } else { float attackFactor = player->getAttackFactor(); int32_t attackSkill = player->getSkillLevel(SKILL_FIST); int32_t attackValue = 7; @@ -3186,8 +3039,8 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() msg.skipBytes(1); const std::array &damageReduction = player->getFinalDamageReduction(); - static const Cipbia_Elementals_t cipbiaCombats[] = {CIPBIA_ELEMENTAL_PHYSICAL, CIPBIA_ELEMENTAL_ENERGY, CIPBIA_ELEMENTAL_EARTH, CIPBIA_ELEMENTAL_FIRE, CIPBIA_ELEMENTAL_UNDEFINED, - CIPBIA_ELEMENTAL_LIFEDRAIN, CIPBIA_ELEMENTAL_UNDEFINED, CIPBIA_ELEMENTAL_HEALING, CIPBIA_ELEMENTAL_DROWN, CIPBIA_ELEMENTAL_ICE, CIPBIA_ELEMENTAL_HOLY, CIPBIA_ELEMENTAL_DEATH}; + static const Cipbia_Elementals_t cipbiaCombats[] = { CIPBIA_ELEMENTAL_PHYSICAL, CIPBIA_ELEMENTAL_ENERGY, CIPBIA_ELEMENTAL_EARTH, CIPBIA_ELEMENTAL_FIRE, CIPBIA_ELEMENTAL_UNDEFINED, + CIPBIA_ELEMENTAL_LIFEDRAIN, CIPBIA_ELEMENTAL_UNDEFINED, CIPBIA_ELEMENTAL_HEALING, CIPBIA_ELEMENTAL_DROWN, CIPBIA_ELEMENTAL_ICE, CIPBIA_ELEMENTAL_HOLY, CIPBIA_ELEMENTAL_DEATH }; for (size_t i = 0; i < COMBAT_COUNT; ++i) { auto finalDamage = std::clamp(static_cast(damageReduction[i]), 0, 255); if (finalDamage != 0) { @@ -3206,8 +3059,7 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries) -{ +void ProtocolGame::sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries) { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_RECENTDEATHS); @@ -3215,16 +3067,14 @@ void ProtocolGame::sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t p msg.add(page); msg.add(pages); msg.add(entries.size()); - for (const RecentDeathEntry &entry : entries) - { + for (const RecentDeathEntry &entry : entries) { msg.add(entry.timestamp); msg.addString(entry.cause); } writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries) -{ +void ProtocolGame::sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries) { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_RECENTPVPKILLS); @@ -3232,8 +3082,7 @@ void ProtocolGame::sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t msg.add(page); msg.add(pages); msg.add(entries.size()); - for (const RecentPvPKillEntry &entry : entries) - { + for (const RecentPvPKillEntry &entry : entries) { msg.add(entry.timestamp); msg.addString(entry.description); msg.addByte(entry.status); @@ -3241,8 +3090,7 @@ void ProtocolGame::sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterAchievements() -{ +void ProtocolGame::sendCyclopediaCharacterAchievements() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_ACHIEVEMENTS); @@ -3253,8 +3101,7 @@ void ProtocolGame::sendCyclopediaCharacterAchievements() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterItemSummary() -{ +void ProtocolGame::sendCyclopediaCharacterItemSummary() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_ITEMSUMMARY); @@ -3267,8 +3114,7 @@ void ProtocolGame::sendCyclopediaCharacterItemSummary() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() -{ +void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_OUTFITSMOUNTS); @@ -3280,11 +3126,9 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() msg.skipBytes(2); const auto &outfits = Outfits::getInstance().getOutfits(player->getSex()); - for (const Outfit &outfit : outfits) - { + for (const Outfit &outfit : outfits) { uint8_t addons; - if (!player->getOutfitAddons(outfit, addons)) - { + if (!player->getOutfitAddons(outfit, addons)) { continue; } const std::string from = outfit.from; @@ -3299,17 +3143,13 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() msg.addByte(CYCLOPEDIA_CHARACTERINFO_OUTFITTYPE_QUEST); else msg.addByte(CYCLOPEDIA_CHARACTERINFO_OUTFITTYPE_NONE); - if (outfit.lookType == currentOutfit.lookType) - { + if (outfit.lookType == currentOutfit.lookType) { msg.add(1000); - } - else - { + } else { msg.add(0); } } - if (outfitSize > 0) - { + if (outfitSize > 0) { msg.addByte(currentOutfit.lookHead); msg.addByte(currentOutfit.lookBody); msg.addByte(currentOutfit.lookLegs); @@ -3319,11 +3159,9 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() uint16_t mountSize = 0; auto startMounts = msg.getBufferPosition(); msg.skipBytes(2); - for (const Mount &mount : g_game().mounts.getMounts()) - { + for (const Mount &mount : g_game().mounts.getMounts()) { const std::string type = mount.type; - if (player->hasMount(&mount)) - { + if (player->hasMount(&mount)) { ++mountSize; msg.add(mount.clientId); @@ -3337,8 +3175,7 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() msg.add(1000); } } - if (mountSize > 0) - { + if (mountSize > 0) { msg.addByte(currentOutfit.lookMountHead); msg.addByte(currentOutfit.lookMountBody); msg.addByte(currentOutfit.lookMountLegs); @@ -3349,11 +3186,9 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() auto startFamiliars = msg.getBufferPosition(); msg.skipBytes(2); const auto &familiars = Familiars::getInstance().getFamiliars(player->getVocationId()); - for (const Familiar &familiar : familiars) - { + for (const Familiar &familiar : familiars) { const std::string type = familiar.type; - if (!player->getFamiliar(familiar)) - { + if (!player->getFamiliar(familiar)) { continue; } ++familiarsSize; @@ -3375,8 +3210,7 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterStoreSummary() -{ +void ProtocolGame::sendCyclopediaCharacterStoreSummary() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_STORESUMMARY); @@ -3395,8 +3229,7 @@ void ProtocolGame::sendCyclopediaCharacterStoreSummary() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterInspection() -{ +void ProtocolGame::sendCyclopediaCharacterInspection() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_INSPECTION); @@ -3404,11 +3237,9 @@ void ProtocolGame::sendCyclopediaCharacterInspection() uint8_t inventoryItems = 0; auto startInventory = msg.getBufferPosition(); msg.skipBytes(1); - for (std::underlying_type::type slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; slot++) - { - Item *inventoryItem = player->getInventoryItem(static_cast(slot)); - if (inventoryItem) - { + for (std::underlying_type::type slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; slot++) { + Item* inventoryItem = player->getInventoryItem(static_cast(slot)); + if (inventoryItem) { ++inventoryItems; msg.addByte(slot); @@ -3418,8 +3249,7 @@ void ProtocolGame::sendCyclopediaCharacterInspection() auto descriptions = Item::getDescriptions(Item::items[inventoryItem->getID()], inventoryItem); msg.addByte(descriptions.size()); - for (const auto &description : descriptions) - { + for (const auto &description : descriptions) { msg.addString(description.first); msg.addString(description.second); } @@ -3435,15 +3265,13 @@ void ProtocolGame::sendCyclopediaCharacterInspection() msg.addString(player->getVocation()->getVocName()); msg.addString("Outfit"); - const Outfit *outfit = Outfits::getInstance().getOutfitByLookType( - player->getSex(), - player->getDefaultOutfit().lookType); - if (outfit) - { + const Outfit* outfit = Outfits::getInstance().getOutfitByLookType( + player->getSex(), + player->getDefaultOutfit().lookType + ); + if (outfit) { msg.addString(outfit->name); - } - else - { + } else { msg.addString("unknown"); } msg.setBufferPosition(startInventory); @@ -3451,8 +3279,7 @@ void ProtocolGame::sendCyclopediaCharacterInspection() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterBadges() -{ +void ProtocolGame::sendCyclopediaCharacterBadges() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_BADGES); @@ -3462,8 +3289,7 @@ void ProtocolGame::sendCyclopediaCharacterBadges() writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterTitles() -{ +void ProtocolGame::sendCyclopediaCharacterTitles() { NetworkMessage msg; msg.addByte(0xDA); msg.addByte(CYCLOPEDIA_CHARACTERINFO_TITLES); @@ -3473,8 +3299,7 @@ void ProtocolGame::sendCyclopediaCharacterTitles() writeToOutputBuffer(msg); } -void ProtocolGame::sendTournamentLeaderboard() -{ +void ProtocolGame::sendTournamentLeaderboard() { NetworkMessage msg; msg.addByte(0xC5); msg.addByte(0); @@ -3482,8 +3307,7 @@ void ProtocolGame::sendTournamentLeaderboard() writeToOutputBuffer(msg); } -void ProtocolGame::sendReLoginWindow(uint8_t unfairFightReduction) -{ +void ProtocolGame::sendReLoginWindow(uint8_t unfairFightReduction) { NetworkMessage msg; msg.addByte(0x28); msg.addByte(0x00); @@ -3492,64 +3316,52 @@ void ProtocolGame::sendReLoginWindow(uint8_t unfairFightReduction) writeToOutputBuffer(msg); } -void ProtocolGame::sendStats() -{ +void ProtocolGame::sendStats() { NetworkMessage msg; AddPlayerStats(msg); writeToOutputBuffer(msg); } -void ProtocolGame::sendBasicData() -{ +void ProtocolGame::sendBasicData() { NetworkMessage msg; msg.addByte(0x9F); - if (player->isPremium()) - { + if (player->isPremium()) { msg.addByte(1); msg.add(time(nullptr) + (player->premiumDays * 86400)); - } - else - { + } else { msg.addByte(0); msg.add(0); } msg.addByte(player->getVocation()->getClientId()); // Prey window - if (player->getVocation()->getId() == 0) - { + if (player->getVocation()->getId() == 0) { msg.addByte(0); - } - else - { + } else { msg.addByte(1); // has reached Main (allow player to open Prey window) } std::list spellsList = g_spells().getSpellsByVocation(player->getVocationId()); msg.add(spellsList.size()); - for (uint16_t sid : spellsList) - { + for (uint16_t sid : spellsList) { msg.addByte(sid); } msg.addByte(player->getVocation()->getMagicShield()); // bool - determine whether magic shield is active or not writeToOutputBuffer(msg); } -void ProtocolGame::sendBlessStatus() -{ +void ProtocolGame::sendBlessStatus() { if (!player) return; NetworkMessage msg; - //uint8_t maxClientBlessings = (player->operatingSystem == CLIENTOS_NEW_WINDOWS) ? 8 : 6; (compartability for the client 10) - //Ignore ToF (bless 1) + // uint8_t maxClientBlessings = (player->operatingSystem == CLIENTOS_NEW_WINDOWS) ? 8 : 6; (compartability for the client 10) + // Ignore ToF (bless 1) uint8_t blessCount = 0; uint16_t flag = 0; uint16_t pow2 = 2; - for (int i = 1; i <= 8; i++) - { - if (player->hasBlessing(i)) - { + for (int i = 1; i <= 8; i++) { + if (player->hasBlessing(i)) { if (i > 1) blessCount++; flag |= pow2; @@ -3560,31 +3372,27 @@ void ProtocolGame::sendBlessStatus() msg.addByte(0x9C); bool glow = g_configManager().getBoolean(INVENTORY_GLOW) || player->getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL); - msg.add(glow ? 1 : 0); //Show up the glowing effect in items if have all blesses or adventurer's blessing + msg.add(glow ? 1 : 0); // Show up the glowing effect in items if have all blesses or adventurer's blessing msg.addByte((blessCount >= 7) ? 3 : ((blessCount >= 5) ? 2 : 1)); // 1 = Disabled | 2 = normal | 3 = green // msg.add(0); writeToOutputBuffer(msg); } -void ProtocolGame::sendPremiumTrigger() -{ - if (!g_configManager().getBoolean(FREE_PREMIUM)) - { +void ProtocolGame::sendPremiumTrigger() { + if (!g_configManager().getBoolean(FREE_PREMIUM)) { NetworkMessage msg; msg.addByte(0x9E); msg.addByte(16); - for (uint16_t i = 0; i <= 15; i++) - { - //PREMIUM_TRIGGER_TRAIN_OFFLINE = false, PREMIUM_TRIGGER_XP_BOOST = false, PREMIUM_TRIGGER_MARKET = false, PREMIUM_TRIGGER_VIP_LIST = false, PREMIUM_TRIGGER_DEPOT_SPACE = false, PREMIUM_TRIGGER_INVITE_PRIVCHAT = false + for (uint16_t i = 0; i <= 15; i++) { + // PREMIUM_TRIGGER_TRAIN_OFFLINE = false, PREMIUM_TRIGGER_XP_BOOST = false, PREMIUM_TRIGGER_MARKET = false, PREMIUM_TRIGGER_VIP_LIST = false, PREMIUM_TRIGGER_DEPOT_SPACE = false, PREMIUM_TRIGGER_INVITE_PRIVCHAT = false msg.addByte(0x01); } writeToOutputBuffer(msg); } } -void ProtocolGame::sendTextMessage(const TextMessage &message) -{ +void ProtocolGame::sendTextMessage(const TextMessage &message) { if (message.type == MESSAGE_NONE) { SPDLOG_ERROR("[ProtocolGame::sendTextMessage] - Message type is wrong, missing or invalid for player with name {}, on position {}", player->getName(), player->getPosition().toString()); player->sendTextMessage(MESSAGE_ADMINISTRADOR, "There was a problem requesting your message, please contact the administrator"); @@ -3594,53 +3402,47 @@ void ProtocolGame::sendTextMessage(const TextMessage &message) NetworkMessage msg; msg.addByte(0xB4); msg.addByte(message.type); - switch (message.type) - { - case MESSAGE_DAMAGE_DEALT: - case MESSAGE_DAMAGE_RECEIVED: - case MESSAGE_DAMAGE_OTHERS: - { - msg.addPosition(message.position); - msg.add(message.primary.value); - msg.addByte(message.primary.color); - msg.add(message.secondary.value); - msg.addByte(message.secondary.color); - break; - } - case MESSAGE_HEALED: - case MESSAGE_HEALED_OTHERS: - case MESSAGE_EXPERIENCE: - case MESSAGE_EXPERIENCE_OTHERS: - { - msg.addPosition(message.position); - msg.add(message.primary.value); - msg.addByte(message.primary.color); - break; - } - case MESSAGE_GUILD: - case MESSAGE_PARTY_MANAGEMENT: - case MESSAGE_PARTY: - msg.add(message.channelId); - break; - default: - { - break; - } + switch (message.type) { + case MESSAGE_DAMAGE_DEALT: + case MESSAGE_DAMAGE_RECEIVED: + case MESSAGE_DAMAGE_OTHERS: { + msg.addPosition(message.position); + msg.add(message.primary.value); + msg.addByte(message.primary.color); + msg.add(message.secondary.value); + msg.addByte(message.secondary.color); + break; + } + case MESSAGE_HEALED: + case MESSAGE_HEALED_OTHERS: + case MESSAGE_EXPERIENCE: + case MESSAGE_EXPERIENCE_OTHERS: { + msg.addPosition(message.position); + msg.add(message.primary.value); + msg.addByte(message.primary.color); + break; + } + case MESSAGE_GUILD: + case MESSAGE_PARTY_MANAGEMENT: + case MESSAGE_PARTY: + msg.add(message.channelId); + break; + default: { + break; + } } msg.addString(message.text); writeToOutputBuffer(msg); } -void ProtocolGame::sendClosePrivate(uint16_t channelId) -{ +void ProtocolGame::sendClosePrivate(uint16_t channelId) { NetworkMessage msg; msg.addByte(0xB3); msg.add(channelId); writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName) -{ +void ProtocolGame::sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName) { NetworkMessage msg; msg.addByte(0xB2); msg.add(channelId); @@ -3651,15 +3453,13 @@ void ProtocolGame::sendCreatePrivateChannel(uint16_t channelId, const std::strin writeToOutputBuffer(msg); } -void ProtocolGame::sendChannelsDialog() -{ +void ProtocolGame::sendChannelsDialog() { NetworkMessage msg; msg.addByte(0xAB); const ChannelList &list = g_chat().getChannelList(*player); msg.addByte(list.size()); - for (ChatChannel *channel : list) - { + for (ChatChannel* channel : list) { msg.add(channel->getId()); msg.addString(channel->getName()); } @@ -3667,44 +3467,34 @@ void ProtocolGame::sendChannelsDialog() writeToOutputBuffer(msg); } -void ProtocolGame::sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap *channelUsers, const InvitedMap *invitedUsers) -{ +void ProtocolGame::sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers) { NetworkMessage msg; msg.addByte(0xAC); msg.add(channelId); msg.addString(channelName); - if (channelUsers) - { + if (channelUsers) { msg.add(channelUsers->size()); - for (const auto &it : *channelUsers) - { + for (const auto &it : *channelUsers) { msg.addString(it.second->getName()); } - } - else - { + } else { msg.add(0x00); } - if (invitedUsers) - { + if (invitedUsers) { msg.add(invitedUsers->size()); - for (const auto &it : *invitedUsers) - { + for (const auto &it : *invitedUsers) { msg.addString(it.second->getName()); } - } - else - { + } else { msg.add(0x00); } writeToOutputBuffer(msg); } -void ProtocolGame::sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel) -{ +void ProtocolGame::sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel) { NetworkMessage msg; msg.addByte(0xAA); msg.add(0x00); @@ -3716,16 +3506,14 @@ void ProtocolGame::sendChannelMessage(const std::string &author, const std::stri writeToOutputBuffer(msg); } -void ProtocolGame::sendIcons(uint32_t icons) -{ +void ProtocolGame::sendIcons(uint32_t icons) { NetworkMessage msg; msg.addByte(0xA2); msg.add(icons); writeToOutputBuffer(msg); } -void ProtocolGame::sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8_t &dayLeft, const uint8_t &weekProgress, const uint8_t &weekLeft, const uint8_t &monthProgress, const uint8_t &monthLeft, const uint8_t &skullDuration) -{ +void ProtocolGame::sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8_t &dayLeft, const uint8_t &weekProgress, const uint8_t &weekLeft, const uint8_t &monthProgress, const uint8_t &monthLeft, const uint8_t &skullDuration) { NetworkMessage msg; msg.addByte(0xB7); msg.addByte(dayProgress); @@ -3738,20 +3526,16 @@ void ProtocolGame::sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8 writeToOutputBuffer(msg); } -void ProtocolGame::sendContainer(uint8_t cid, const Container *container, bool hasParent, uint16_t firstIndex) -{ +void ProtocolGame::sendContainer(uint8_t cid, const Container* container, bool hasParent, uint16_t firstIndex) { NetworkMessage msg; msg.addByte(0x6E); msg.addByte(cid); - if (container->getID() == ITEM_BROWSEFIELD) - { + if (container->getID() == ITEM_BROWSEFIELD) { AddItem(msg, ITEM_BAG, 1, container->getTier()); msg.addString("Browse Field"); - } - else - { + } else { AddItem(msg, container); msg.addString(container->getName()); } @@ -3772,49 +3556,38 @@ void ProtocolGame::sendContainer(uint8_t cid, const Container *container, bool h uint32_t maxItemsToSend; - if (container->hasPagination() && firstIndex > 0) - { + if (container->hasPagination() && firstIndex > 0) { maxItemsToSend = std::min(container->capacity(), containerSize - firstIndex); - } - else - { + } else { maxItemsToSend = container->capacity(); } - if (firstIndex >= containerSize) - { + if (firstIndex >= containerSize) { msg.addByte(0x00); - } - else - { + } else { msg.addByte(std::min(maxItemsToSend, containerSize)); uint32_t i = 0; const ItemDeque &itemList = container->getItemList(); - for (ItemDeque::const_iterator it = itemList.begin() + firstIndex, end = itemList.end(); i < maxItemsToSend && it != end; ++it, ++i) - { + for (ItemDeque::const_iterator it = itemList.begin() + firstIndex, end = itemList.end(); i < maxItemsToSend && it != end; ++it, ++i) { AddItem(msg, *it); } } writeToOutputBuffer(msg); } -void ProtocolGame::sendLootContainers() -{ +void ProtocolGame::sendLootContainers() { NetworkMessage msg; msg.addByte(0xC0); msg.addByte(player->quickLootFallbackToMainContainer ? 1 : 0); - std::map quickLoot; - for (auto it : player->quickLootContainers) - { - if (it.second && !it.second->isRemoved()) - { + std::map quickLoot; + for (auto it : player->quickLootContainers) { + if (it.second && !it.second->isRemoved()) { quickLoot[it.first] = it.second; } } msg.addByte(quickLoot.size()); - for (auto it : quickLoot) - { + for (auto it : quickLoot) { msg.addByte(it.first); msg.add(it.second->getID()); } @@ -3822,8 +3595,7 @@ void ProtocolGame::sendLootContainers() writeToOutputBuffer(msg); } -void ProtocolGame::sendLootStats(Item *item, uint8_t count) -{ +void ProtocolGame::sendLootStats(Item* item, uint8_t count) { if (!item) { return; } @@ -3842,8 +3614,7 @@ void ProtocolGame::sendLootStats(Item *item, uint8_t count) lootedItem = nullptr; } -void ProtocolGame::sendShop(Npc *npc) -{ +void ProtocolGame::sendShop(Npc* npc) { NetworkMessage msg; msg.addByte(0x7A); msg.addString(npc->getName()); @@ -3856,8 +3627,7 @@ void ProtocolGame::sendShop(Npc *npc) msg.add(itemsToSend); uint16_t i = 0; - for (ShopBlock shopBlock : shoplist) - { + for (ShopBlock shopBlock : shoplist) { if (++i > itemsToSend) { break; } @@ -3868,15 +3638,13 @@ void ProtocolGame::sendShop(Npc *npc) writeToOutputBuffer(msg); } -void ProtocolGame::sendCloseShop() -{ +void ProtocolGame::sendCloseShop() { NetworkMessage msg; msg.addByte(0x7C); writeToOutputBuffer(msg); } -void ProtocolGame::sendClientCheck() -{ +void ProtocolGame::sendClientCheck() { NetworkMessage msg; msg.addByte(0x63); msg.add(1); @@ -3884,18 +3652,15 @@ void ProtocolGame::sendClientCheck() writeToOutputBuffer(msg); } -void ProtocolGame::sendGameNews() -{ +void ProtocolGame::sendGameNews() { NetworkMessage msg; msg.addByte(0x98); msg.add(1); // unknown - msg.addByte(1); //(0 = open | 1 = highlight) + msg.addByte(1); //(0 = open | 1 = highlight) writeToOutputBuffer(msg); } -void ProtocolGame::sendResourcesBalance(uint64_t money /*= 0*/, uint64_t bank /*= 0*/, uint64_t preyCards /*= 0*/, uint64_t taskHunting /*= 0*/, - uint64_t forgeDust /*= 0*/, uint64_t forgeSliver /*= 0*/, uint64_t forgeCores /*= 0*/) -{ +void ProtocolGame::sendResourcesBalance(uint64_t money /*= 0*/, uint64_t bank /*= 0*/, uint64_t preyCards /*= 0*/, uint64_t taskHunting /*= 0*/, uint64_t forgeDust /*= 0*/, uint64_t forgeSliver /*= 0*/, uint64_t forgeCores /*= 0*/) { sendResourceBalance(RESOURCE_BANK, bank); sendResourceBalance(RESOURCE_INVENTORY, money); sendResourceBalance(RESOURCE_PREY_CARDS, preyCards); @@ -3905,8 +3670,7 @@ void ProtocolGame::sendResourcesBalance(uint64_t money /*= 0*/, uint64_t bank /* sendResourceBalance(RESOURCE_FORGE_CORES, forgeCores); } -void ProtocolGame::sendResourceBalance(Resource_t resourceType, uint64_t value) -{ +void ProtocolGame::sendResourceBalance(Resource_t resourceType, uint64_t value) { NetworkMessage msg; msg.addByte(0xEE); msg.addByte(resourceType); @@ -3914,23 +3678,19 @@ void ProtocolGame::sendResourceBalance(Resource_t resourceType, uint64_t value) writeToOutputBuffer(msg); } -void ProtocolGame::sendSaleItemList(const std::vector &shopVector, const std::map &inventoryMap) -{ - //Since we already have full inventory map we shouldn't call getMoney here - it is simply wasting cpu power +void ProtocolGame::sendSaleItemList(const std::vector &shopVector, const std::map &inventoryMap) { + // Since we already have full inventory map we shouldn't call getMoney here - it is simply wasting cpu power uint64_t playerMoney = 0; auto it = inventoryMap.find(ITEM_CRYSTAL_COIN); - if (it != inventoryMap.end()) - { + if (it != inventoryMap.end()) { playerMoney += static_cast(it->second) * 10000; } it = inventoryMap.find(ITEM_PLATINUM_COIN); - if (it != inventoryMap.end()) - { + if (it != inventoryMap.end()) { playerMoney += static_cast(it->second) * 100; } it = inventoryMap.find(ITEM_GOLD_COIN); - if (it != inventoryMap.end()) - { + if (it != inventoryMap.end()) { playerMoney += static_cast(it->second); } @@ -3942,7 +3702,7 @@ void ProtocolGame::sendSaleItemList(const std::vector &shopVector, co msg.addByte(0xEE); if (currency == ITEM_GOLD_COIN) { msg.addByte(0x01); - msg.add(playerMoney); + msg.add(playerMoney); } else { msg.addByte(0x02); uint64_t newCurrency = 0; @@ -3959,16 +3719,13 @@ void ProtocolGame::sendSaleItemList(const std::vector &shopVector, co auto msgPosition = msg.getBufferPosition(); msg.skipBytes(1); - for (ShopBlock shopBlock : shopVector) - { - if (shopBlock.itemSellPrice == 0) - { + for (ShopBlock shopBlock : shopVector) { + if (shopBlock.itemSellPrice == 0) { continue; } it = inventoryMap.find(shopBlock.itemId); - if (it != inventoryMap.end()) - { + if (it != inventoryMap.end()) { itemsToSend++; msg.add(shopBlock.itemId); msg.add(it->second); @@ -3980,15 +3737,13 @@ void ProtocolGame::sendSaleItemList(const std::vector &shopVector, co writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketEnter(uint32_t depotId) -{ +void ProtocolGame::sendMarketEnter(uint32_t depotId) { NetworkMessage msg; msg.addByte(0xF6); msg.addByte(std::min(IOMarket::getPlayerOfferCount(player->getGUID()), std::numeric_limits::max())); - DepotLocker *depotLocker = player->getDepotLocker(depotId); - if (!depotLocker) - { + DepotLocker* depotLocker = player->getDepotLocker(depotId); + if (!depotLocker) { msg.add(0x00); writeToOutputBuffer(msg); return; @@ -4002,8 +3757,7 @@ void ProtocolGame::sendMarketEnter(uint32_t depotId) msg.skipBytes(2); // Total items count uint16_t totalItemsCount = 0; - for (const auto &[itemId, tierAndCountMap] : lockerItems) - { + for (const auto &[itemId, tierAndCountMap] : lockerItems) { for (const auto &[tier, count] : tierAndCountMap) { msg.add(itemId); if (Item::items[itemId].upgradeClassification > 0) { @@ -4022,10 +3776,8 @@ void ProtocolGame::sendMarketEnter(uint32_t depotId) sendResourcesBalance(player->getMoney(), player->getBankBalance(), player->getPreyCards(), player->getTaskHuntingPoints()); } -void ProtocolGame::sendCoinBalance() -{ - if (!player) - { +void ProtocolGame::sendCoinBalance() { + if (!player) { return; } @@ -4045,13 +3797,12 @@ void ProtocolGame::sendCoinBalance() msg.add(player->coinBalance); // Normal Coins msg.add(player->coinBalance); // Transferable Coins msg.add(player->coinBalance); // Reserved Auction Coins - msg.add(0); // Tournament Coins + msg.add(0); // Tournament Coins writeToOutputBuffer(msg); } -void ProtocolGame::updateCoinBalance() -{ +void ProtocolGame::updateCoinBalance() { if (!player) { return; } @@ -4068,18 +3819,17 @@ void ProtocolGame::updateCoinBalance() threadPlayer->sendCoinBalance(); } }, - player->getID()))); + player->getID())) + ); } -void ProtocolGame::sendMarketLeave() -{ +void ProtocolGame::sendMarketLeave() { NetworkMessage msg; msg.addByte(0xF7); writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList &buyOffers, const MarketOfferList &sellOffers, uint8_t tier) -{ +void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList &buyOffers, const MarketOfferList &sellOffers, uint8_t tier) { NetworkMessage msg; msg.addByte(0xF9); @@ -4090,8 +3840,7 @@ void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList & } msg.add(buyOffers.size()); - for (const MarketOffer &offer : buyOffers) - { + for (const MarketOffer &offer : buyOffers) { msg.add(offer.timestamp); msg.add(offer.counter); msg.add(offer.amount); @@ -4100,8 +3849,7 @@ void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList & } msg.add(sellOffers.size()); - for (const MarketOffer &offer : sellOffers) - { + for (const MarketOffer &offer : sellOffers) { msg.add(offer.timestamp); msg.add(offer.counter); msg.add(offer.amount); @@ -4113,8 +3861,7 @@ void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList & writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx &offer) -{ +void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx &offer) { NetworkMessage msg; msg.addByte(0xF9); msg.addByte(MARKETREQUEST_ITEM_BROWSE); @@ -4123,8 +3870,7 @@ void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx &offer) msg.addByte(offer.tier); } - if (offer.type == MARKETACTION_BUY) - { + if (offer.type == MARKETACTION_BUY) { msg.add(0x01); msg.add(offer.timestamp); msg.add(offer.counter); @@ -4132,9 +3878,7 @@ void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx &offer) msg.add(offer.price); msg.addString(offer.playerName); msg.add(0x00); - } - else - { + } else { msg.add(0x00); msg.add(0x01); msg.add(offer.timestamp); @@ -4147,15 +3891,13 @@ void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx &offer) writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, const MarketOfferList &sellOffers) -{ +void ProtocolGame::sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, const MarketOfferList &sellOffers) { NetworkMessage msg; msg.addByte(0xF9); msg.addByte(MARKETREQUEST_OWN_OFFERS); msg.add(buyOffers.size()); - for (const MarketOffer &offer : buyOffers) - { + for (const MarketOffer &offer : buyOffers) { msg.add(offer.timestamp); msg.add(offer.counter); msg.add(offer.itemId); @@ -4167,8 +3909,7 @@ void ProtocolGame::sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, c } msg.add(sellOffers.size()); - for (const MarketOffer &offer : sellOffers) - { + for (const MarketOffer &offer : sellOffers) { msg.add(offer.timestamp); msg.add(offer.counter); msg.add(offer.itemId); @@ -4182,14 +3923,12 @@ void ProtocolGame::sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, c writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketCancelOffer(const MarketOfferEx &offer) -{ +void ProtocolGame::sendMarketCancelOffer(const MarketOfferEx &offer) { NetworkMessage msg; msg.addByte(0xF9); msg.addByte(MARKETREQUEST_OWN_OFFERS); - if (offer.type == MARKETACTION_BUY) - { + if (offer.type == MARKETACTION_BUY) { msg.add(0x01); msg.add(offer.timestamp); msg.add(offer.counter); @@ -4200,9 +3939,7 @@ void ProtocolGame::sendMarketCancelOffer(const MarketOfferEx &offer) msg.add(offer.amount); msg.add(offer.price); msg.add(0x00); - } - else - { + } else { msg.add(0x00); msg.add(0x01); msg.add(offer.timestamp); @@ -4218,8 +3955,7 @@ void ProtocolGame::sendMarketCancelOffer(const MarketOfferEx &offer) writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyOffers, const HistoryMarketOfferList &sellOffers) -{ +void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyOffers, const HistoryMarketOfferList &sellOffers) { uint32_t i = 0; std::map counterMap; uint32_t buyOffersToSend = std::min(buyOffers.size(), 810 + std::max(0, 810 - sellOffers.size())); @@ -4230,8 +3966,7 @@ void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyO msg.addByte(MARKETREQUEST_OWN_HISTORY); msg.add(buyOffersToSend); - for (auto it = buyOffers.begin(); i < buyOffersToSend; ++it, ++i) - { + for (auto it = buyOffers.begin(); i < buyOffersToSend; ++it, ++i) { msg.add(it->timestamp); msg.add(counterMap[it->timestamp]++); msg.add(it->itemId); @@ -4247,8 +3982,7 @@ void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyO i = 0; msg.add(sellOffersToSend); - for (auto it = sellOffers.begin(); i < sellOffersToSend; ++it, ++i) - { + for (auto it = sellOffers.begin(); i < sellOffersToSend; ++it, ++i) { msg.add(it->timestamp); msg.add(counterMap[it->timestamp]++); msg.add(it->itemId); @@ -4263,19 +3997,16 @@ void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyO writeToOutputBuffer(msg); } -void ProtocolGame::sendForgingData() -{ +void ProtocolGame::sendForgingData() { NetworkMessage msg; msg.addByte(0x86); std::vector classifications = g_game().getItemsClassifications(); msg.addByte(classifications.size()); - for (ItemClassification* classification : classifications) - { + for (ItemClassification* classification : classifications) { msg.addByte(classification->id); msg.addByte(classification->tiers.size()); - for (const auto &[tier, price] : classification->tiers) - { + for (const auto &[tier, price] : classification->tiers) { msg.addByte(tier); msg.add(price); } @@ -4321,7 +4052,7 @@ void ProtocolGame::sendOpenForge() { /* *Start - Parsing items informations - */ + */ for (const auto &item : player->getAllInventoryItems(true)) { if (item->hasImbuements()) { continue; @@ -4363,7 +4094,7 @@ void ProtocolGame::sendOpenForge() { /* * Start - Sending bytes - */ + */ NetworkMessage msg; // Header byte (135) msg.addByte(0x87); @@ -4428,7 +4159,7 @@ void ProtocolGame::sendOpenForge() { sendForgingData(); } -void ProtocolGame::parseForgeEnter(NetworkMessage& msg) { +void ProtocolGame::parseForgeEnter(NetworkMessage &msg) { // 0xBF -> 0 = fusion, 1 = transfer, 2 = dust to sliver, 3 = sliver to core, 4 = increase dust limit uint8_t action = msg.getByte(); uint16_t firstItem = msg.get(); @@ -4445,8 +4176,7 @@ void ProtocolGame::parseForgeEnter(NetworkMessage& msg) { } } -void ProtocolGame::parseForgeBrowseHistory(NetworkMessage& msg) -{ +void ProtocolGame::parseForgeBrowseHistory(NetworkMessage &msg) { addGameTask(&Game::playerBrowseForgeHistory, player->getID(), msg.getByte()); } @@ -4465,12 +4195,9 @@ void ProtocolGame::sendForgeFusionItem(uint16_t itemId, uint8_t tier, bool succe msg.addByte(bonus); // Roll fusion bonus // Core kept - if (bonus == 2) - { + if (bonus == 2) { msg.addByte(coreCount); - } - else if (bonus >= 4 && bonus <= 8) - { + } else if (bonus >= 4 && bonus <= 8) { msg.add(itemId); msg.addByte(tier); } @@ -4497,8 +4224,7 @@ void ProtocolGame::sendTransferItemTier(uint16_t firstItem, uint8_t tier, uint16 sendOpenForge(); } -void ProtocolGame::sendForgeHistory(uint8_t page) -{ +void ProtocolGame::sendForgeHistory(uint8_t page) { page = page + 1; auto historyVector = player->getForgeHistory(); auto historyVectorLen = getVectorIterationIncreaseCount(historyVector); @@ -4508,7 +4234,7 @@ void ProtocolGame::sendForgeHistory(uint8_t page) std::vector historyPerPage; uint16_t pageFirstEntry = (0 < historyVectorLen - (currentPage - 1) * 9) ? historyVectorLen - (currentPage - 1) * 9 : 0; - uint16_t pageLastEntry = (0 < historyVectorLen - currentPage * 9) ? historyVectorLen - currentPage * 9: 0; + uint16_t pageLastEntry = (0 < historyVectorLen - currentPage * 9) ? historyVectorLen - currentPage * 9 : 0; for (uint16_t entry = pageFirstEntry; entry > pageLastEntry; --entry) { historyPerPage.push_back(historyVector[entry - 1]); } @@ -4534,21 +4260,18 @@ void ProtocolGame::sendForgeHistory(uint8_t page) writeToOutputBuffer(msg); } -void ProtocolGame::sendForgeError(const ReturnValue returnValue) -{ +void ProtocolGame::sendForgeError(const ReturnValue returnValue) { sendMessageDialog(getReturnMessage(returnValue)); closeForgeWindow(); } -void ProtocolGame::closeForgeWindow() -{ +void ProtocolGame::closeForgeWindow() { NetworkMessage msg; msg.addByte(0x89); writeToOutputBuffer(msg); } -void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) -{ +void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) { NetworkMessage msg; msg.addByte(0xF8); msg.add(itemId); @@ -4558,109 +4281,76 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) msg.addByte(tier); } - if (it.armor != 0) - { + if (it.armor != 0) { msg.addString(std::to_string(it.armor)); - } - else - { + } else { msg.add(0x00); } - if (it.attack != 0) - { + if (it.attack != 0) { // TODO: chance to hit, range // example: // "attack +x, chance to hit +y%, z fields" - if (it.abilities && it.abilities->elementType != COMBAT_NONE && it.abilities->elementDamage != 0) - { + if (it.abilities && it.abilities->elementType != COMBAT_NONE && it.abilities->elementDamage != 0) { std::ostringstream ss; ss << it.attack << " physical +" << it.abilities->elementDamage << ' ' << getCombatName(it.abilities->elementType); msg.addString(ss.str()); - } - else - { + } else { msg.addString(std::to_string(it.attack)); } - } - else - { + } else { msg.add(0x00); } - if (it.isContainer()) - { + if (it.isContainer()) { msg.addString(std::to_string(it.maxItems)); - } - else - { + } else { msg.add(0x00); } - if (it.defense != 0) - { - if (it.extraDefense != 0) - { + if (it.defense != 0) { + if (it.extraDefense != 0) { std::ostringstream ss; ss << it.defense << ' ' << std::showpos << it.extraDefense << std::noshowpos; msg.addString(ss.str()); - } - else - { + } else { msg.addString(std::to_string(it.defense)); } - } - else - { + } else { msg.add(0x00); } - if (!it.description.empty()) - { + if (!it.description.empty()) { const std::string &descr = it.description; - if (descr.back() == '.') - { + if (descr.back() == '.') { msg.addString(std::string(descr, 0, descr.length() - 1)); - } - else - { + } else { msg.addString(descr); } - } - else - { + } else { msg.add(0x00); } - if (it.decayTime != 0) - { + if (it.decayTime != 0) { std::ostringstream ss; ss << it.decayTime << " seconds"; msg.addString(ss.str()); - } - else - { + } else { msg.add(0x00); } - if (it.abilities) - { + if (it.abilities) { std::ostringstream ss; bool separator = false; - for (size_t i = 0; i < COMBAT_COUNT; ++i) - { - if (it.abilities->absorbPercent[i] == 0) - { + for (size_t i = 0; i < COMBAT_COUNT; ++i) { + if (it.abilities->absorbPercent[i] == 0) { continue; } - if (separator) - { + if (separator) { ss << ", "; - } - else - { + } else { separator = true; } @@ -4668,70 +4358,51 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) } msg.addString(ss.str()); - } - else - { + } else { msg.add(0x00); } - if (it.minReqLevel != 0) - { + if (it.minReqLevel != 0) { msg.addString(std::to_string(it.minReqLevel)); - } - else - { + } else { msg.add(0x00); } - if (it.minReqMagicLevel != 0) - { + if (it.minReqMagicLevel != 0) { msg.addString(std::to_string(it.minReqMagicLevel)); - } - else - { + } else { msg.add(0x00); } msg.addString(it.vocationString); msg.addString(it.runeSpellName); - if (it.abilities) - { + if (it.abilities) { std::ostringstream ss; bool separator = false; - for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; i++) - { - if (!it.abilities->skills[i]) - { + for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; i++) { + if (!it.abilities->skills[i]) { continue; } - if (separator) - { + if (separator) { ss << ", "; - } - else - { + } else { separator = true; } ss << fmt::format("{} {:+}", getSkillName(i), it.abilities->skills[i]); } - for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; i++) - { - if (!it.abilities->skills[i]) - { + for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; i++) { + if (!it.abilities->skills[i]) { continue; } - if (separator) - { + if (separator) { ss << ", "; - } - else - { + } else { separator = true; } @@ -4746,24 +4417,18 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) } } - if (it.abilities->stats[STAT_MAGICPOINTS] != 0) - { - if (separator) - { + if (it.abilities->stats[STAT_MAGICPOINTS] != 0) { + if (separator) { ss << ", "; - } - else - { + } else { separator = true; } - ss << fmt::format("magic level {:+}",it.abilities->stats[STAT_MAGICPOINTS]); + ss << fmt::format("magic level {:+}", it.abilities->stats[STAT_MAGICPOINTS]); } - if (it.abilities->speed != 0) - { - if (separator) - { + if (it.abilities->speed != 0) { + if (separator) { ss << ", "; } @@ -4771,68 +4436,48 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) } msg.addString(ss.str()); - } - else - { + } else { msg.add(0x00); } - if (it.charges != 0) - { + if (it.charges != 0) { msg.addString(std::to_string(it.charges)); - } - else - { + } else { msg.add(0x00); } std::string weaponName = getWeaponName(it.weaponType); - if (it.slotPosition & SLOTP_TWO_HAND) - { - if (!weaponName.empty()) - { + if (it.slotPosition & SLOTP_TWO_HAND) { + if (!weaponName.empty()) { weaponName += ", two-handed"; - } - else - { + } else { weaponName = "two-handed"; } } msg.addString(weaponName); - if (it.weight != 0) - { + if (it.weight != 0) { std::ostringstream ss; - if (it.weight < 10) - { + if (it.weight < 10) { ss << "0.0" << it.weight; - } - else if (it.weight < 100) - { + } else if (it.weight < 100) { ss << "0." << it.weight; - } - else - { + } else { std::string weightString = std::to_string(it.weight); weightString.insert(weightString.end() - 2, '.'); ss << weightString; } ss << " oz"; msg.addString(ss.str()); - } - else - { + } else { msg.add(0x00); } - if (it.imbuementSlot > 0) - { + if (it.imbuementSlot > 0) { msg.addString(std::to_string(it.imbuementSlot)); - } - else - { + } else { msg.add(0x00); } @@ -4846,8 +4491,7 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) msg.add(0x00); // Upgrade and tier detail modifier - if (it.upgradeClassification > 0 && tier > 0) - { + if (it.upgradeClassification > 0 && tier > 0) { msg.addString(std::to_string(it.upgradeClassification)); std::ostringstream ss; @@ -4855,88 +4499,68 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) if (it.isWeapon()) { chance = 0.5 * tier + 0.05 * ((tier - 1) * (tier - 1)); ss << fmt::format("{} ({:.2f}% Onslaught)", static_cast(tier), chance); - } - else if (it.isHelmet()) { + } else if (it.isHelmet()) { chance = 2 * tier + 0.05 * ((tier - 1) * (tier - 1)); ss << fmt::format("{} ({:.2f}% Momentum)", static_cast(tier), chance); - } - else if (it.isArmor()) { + } else if (it.isArmor()) { chance = (0.0307576 * tier * tier) + (0.440697 * tier) + 0.026; ss << fmt::format("{} ({:.2f}% Ruse)", static_cast(tier), chance); } msg.addString(ss.str()); - } - else if (it.upgradeClassification > 0 && tier == 0) - { + } else if (it.upgradeClassification > 0 && tier == 0) { msg.addString(std::to_string(it.upgradeClassification)); msg.addString(std::to_string(tier)); - } - else - { + } else { msg.add(0x00); msg.add(0x00); } auto purchase = IOMarket::getInstance().getPurchaseStatistics()[itemId][tier]; - if (const MarketStatistics* purchaseStatistics = &purchase; purchaseStatistics) - { + if (const MarketStatistics* purchaseStatistics = &purchase; purchaseStatistics) { msg.addByte(0x01); msg.add(purchaseStatistics->numTransactions); msg.add(purchaseStatistics->totalPrice); msg.add(purchaseStatistics->highestPrice); msg.add(purchaseStatistics->lowestPrice); - } - else - { + } else { msg.addByte(0x00); } auto sale = IOMarket::getInstance().getSaleStatistics()[itemId][tier]; - if (const MarketStatistics* saleStatistics = &sale; saleStatistics) - { + if (const MarketStatistics* saleStatistics = &sale; saleStatistics) { msg.addByte(0x01); msg.add(saleStatistics->numTransactions); msg.add(std::min(std::numeric_limits::max(), saleStatistics->totalPrice)); msg.add(saleStatistics->highestPrice); msg.add(saleStatistics->lowestPrice); - } - else - { + } else { msg.addByte(0x00); } writeToOutputBuffer(msg); } -void ProtocolGame::sendTradeItemRequest(const std::string &traderName, const Item *item, bool ack) -{ +void ProtocolGame::sendTradeItemRequest(const std::string &traderName, const Item* item, bool ack) { NetworkMessage msg; - if (ack) - { + if (ack) { msg.addByte(0x7D); - } - else - { + } else { msg.addByte(0x7E); } msg.addString(traderName); - if (const Container *tradeContainer = item->getContainer()) - { - std::list listContainer{tradeContainer}; - std::list itemList{tradeContainer}; - while (!listContainer.empty()) - { - const Container *container = listContainer.front(); + if (const Container* tradeContainer = item->getContainer()) { + std::list listContainer { tradeContainer }; + std::list itemList { tradeContainer }; + while (!listContainer.empty()) { + const Container* container = listContainer.front(); listContainer.pop_front(); - for (Item *containerItem : container->getItemList()) - { - Container *tmpContainer = containerItem->getContainer(); - if (tmpContainer) - { + for (Item* containerItem : container->getItemList()) { + Container* tmpContainer = containerItem->getContainer(); + if (tmpContainer) { listContainer.push_back(tmpContainer); } itemList.push_back(containerItem); @@ -4944,38 +4568,31 @@ void ProtocolGame::sendTradeItemRequest(const std::string &traderName, const Ite } msg.addByte(itemList.size()); - for (const Item *listItem : itemList) - { + for (const Item* listItem : itemList) { AddItem(msg, listItem); } - } - else - { + } else { msg.addByte(0x01); AddItem(msg, item); } writeToOutputBuffer(msg); } -void ProtocolGame::sendCloseTrade() -{ +void ProtocolGame::sendCloseTrade() { NetworkMessage msg; msg.addByte(0x7F); writeToOutputBuffer(msg); } -void ProtocolGame::sendCloseContainer(uint8_t cid) -{ +void ProtocolGame::sendCloseContainer(uint8_t cid) { NetworkMessage msg; msg.addByte(0x6F); msg.addByte(cid); writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureTurn(const Creature *creature, uint32_t stackPos) -{ - if (!canSee(creature)) - { +void ProtocolGame::sendCreatureTurn(const Creature* creature, uint32_t stackPos) { + if (!canSee(creature)) { return; } @@ -4990,8 +4607,7 @@ void ProtocolGame::sendCreatureTurn(const Creature *creature, uint32_t stackPos) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSay(const Creature *creature, SpeakClasses type, const std::string &text, const Position *pos /* = nullptr*/) -{ +void ProtocolGame::sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string &text, const Position* pos /* = nullptr*/) { NetworkMessage msg; msg.addByte(0xAA); @@ -5001,23 +4617,17 @@ void ProtocolGame::sendCreatureSay(const Creature *creature, SpeakClasses type, msg.addString(creature->getName()); msg.addByte(0x00); // Show (Traded) - //Add level only for players - if (const Player *speaker = creature->getPlayer()) - { + // Add level only for players + if (const Player* speaker = creature->getPlayer()) { msg.add(speaker->getLevel()); - } - else - { + } else { msg.add(0x00); } msg.addByte(type); - if (pos) - { + if (pos) { msg.addPosition(*pos); - } - else - { + } else { msg.addPosition(creature->getPosition()); } @@ -5025,45 +4635,33 @@ void ProtocolGame::sendCreatureSay(const Creature *creature, SpeakClasses type, writeToOutputBuffer(msg); } -void ProtocolGame::sendToChannel(const Creature *creature, SpeakClasses type, const std::string &text, uint16_t channelId) -{ +void ProtocolGame::sendToChannel(const Creature* creature, SpeakClasses type, const std::string &text, uint16_t channelId) { NetworkMessage msg; msg.addByte(0xAA); static uint32_t statementId = 0; msg.add(++statementId); - if (!creature) - { + if (!creature) { msg.add(0x00); - if (statementId != 0) - { + if (statementId != 0) { msg.addByte(0x00); // Show (Traded) } - } - else if (type == TALKTYPE_CHANNEL_R2) - { + } else if (type == TALKTYPE_CHANNEL_R2) { msg.add(0x00); - if (statementId != 0) - { + if (statementId != 0) { msg.addByte(0x00); // Show (Traded) } type = TALKTYPE_CHANNEL_R1; - } - else - { + } else { msg.addString(creature->getName()); - if (statementId != 0) - { + if (statementId != 0) { msg.addByte(0x00); // Show (Traded) } - //Add level only for players - if (const Player *speaker = creature->getPlayer()) - { + // Add level only for players + if (const Player* speaker = creature->getPlayer()) { msg.add(speaker->getLevel()); - } - else - { + } else { msg.add(0x00); } } @@ -5074,26 +4672,20 @@ void ProtocolGame::sendToChannel(const Creature *creature, SpeakClasses type, co writeToOutputBuffer(msg); } -void ProtocolGame::sendPrivateMessage(const Player *speaker, SpeakClasses type, const std::string &text) -{ +void ProtocolGame::sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string &text) { NetworkMessage msg; msg.addByte(0xAA); static uint32_t statementId = 0; msg.add(++statementId); - if (speaker) - { + if (speaker) { msg.addString(speaker->getName()); - if (statementId != 0) - { + if (statementId != 0) { msg.addByte(0x00); // Show (Traded) } msg.add(speaker->getLevel()); - } - else - { + } else { msg.add(0x00); - if (statementId != 0) - { + if (statementId != 0) { msg.addByte(0x00); // Show (Traded) } } @@ -5102,16 +4694,14 @@ void ProtocolGame::sendPrivateMessage(const Player *speaker, SpeakClasses type, writeToOutputBuffer(msg); } -void ProtocolGame::sendCancelTarget() -{ +void ProtocolGame::sendCancelTarget() { NetworkMessage msg; msg.addByte(0xA3); msg.add(0x00); writeToOutputBuffer(msg); } -void ProtocolGame::sendChangeSpeed(const Creature *creature, uint16_t speed) -{ +void ProtocolGame::sendChangeSpeed(const Creature* creature, uint16_t speed) { NetworkMessage msg; msg.addByte(0x8F); msg.add(creature->getID()); @@ -5120,10 +4710,8 @@ void ProtocolGame::sendChangeSpeed(const Creature *creature, uint16_t speed) writeToOutputBuffer(msg); } -void ProtocolGame::sendCancelWalk() -{ - if (player) - { +void ProtocolGame::sendCancelWalk() { + if (player) { NetworkMessage msg; msg.addByte(0xB5); msg.addByte(player->getDirection()); @@ -5131,32 +4719,27 @@ void ProtocolGame::sendCancelWalk() } } -void ProtocolGame::sendSkills() -{ +void ProtocolGame::sendSkills() { NetworkMessage msg; AddPlayerSkills(msg); writeToOutputBuffer(msg); } -void ProtocolGame::sendPing() -{ - if (player) - { +void ProtocolGame::sendPing() { + if (player) { NetworkMessage msg; msg.addByte(0x1D); writeToOutputBuffer(msg); } } -void ProtocolGame::sendPingBack() -{ +void ProtocolGame::sendPingBack() { NetworkMessage msg; msg.addByte(0x1E); writeToOutputBuffer(msg); } -void ProtocolGame::sendDistanceShoot(const Position &from, const Position &to, uint8_t type) -{ +void ProtocolGame::sendDistanceShoot(const Position &from, const Position &to, uint8_t type) { NetworkMessage msg; msg.addByte(0x83); msg.addPosition(from); @@ -5168,10 +4751,8 @@ void ProtocolGame::sendDistanceShoot(const Position &from, const Position &to, u writeToOutputBuffer(msg); } -void ProtocolGame::sendRestingStatus(uint8_t protection) -{ - if (!player) - { +void ProtocolGame::sendRestingStatus(uint8_t protection) { + if (!player) { return; } @@ -5180,39 +4761,27 @@ void ProtocolGame::sendRestingStatus(uint8_t protection) msg.addByte(protection); // 1 / 0 int32_t PlayerdailyStreak = player->getStorageValue(STORAGEVALUE_DAILYREWARD); msg.addByte(PlayerdailyStreak < 2 ? 0 : 1); - if (PlayerdailyStreak < 2) - { + if (PlayerdailyStreak < 2) { msg.addString("Resting Area (no active bonus)"); - } - else - { + } else { std::ostringstream ss; ss << "Active Resting Area Bonuses: "; - if (PlayerdailyStreak < DAILY_REWARD_DOUBLE_HP_REGENERATION) - { + if (PlayerdailyStreak < DAILY_REWARD_DOUBLE_HP_REGENERATION) { ss << "\nHit Points Regeneration"; - } - else - { + } else { ss << "\nDouble Hit Points Regeneration"; } - if (PlayerdailyStreak >= DAILY_REWARD_MP_REGENERATION) - { - if (PlayerdailyStreak < DAILY_REWARD_DOUBLE_MP_REGENERATION) - { + if (PlayerdailyStreak >= DAILY_REWARD_MP_REGENERATION) { + if (PlayerdailyStreak < DAILY_REWARD_DOUBLE_MP_REGENERATION) { ss << ",\nMana Points Regeneration"; - } - else - { + } else { ss << ",\nDouble Mana Points Regeneration"; } } - if (PlayerdailyStreak >= DAILY_REWARD_STAMINA_REGENERATION) - { + if (PlayerdailyStreak >= DAILY_REWARD_STAMINA_REGENERATION) { ss << ",\nStamina Points Regeneration"; } - if (PlayerdailyStreak >= DAILY_REWARD_SOUL_REGENERATION) - { + if (PlayerdailyStreak >= DAILY_REWARD_SOUL_REGENERATION) { ss << ",\nSoul Points Regeneration"; } ss << "."; @@ -5221,10 +4790,8 @@ void ProtocolGame::sendRestingStatus(uint8_t protection) writeToOutputBuffer(msg); } -void ProtocolGame::sendMagicEffect(const Position &pos, uint8_t type) -{ - if (!canSee(pos)) - { +void ProtocolGame::sendMagicEffect(const Position &pos, uint8_t type) { + if (!canSee(pos)) { return; } @@ -5237,10 +4804,8 @@ void ProtocolGame::sendMagicEffect(const Position &pos, uint8_t type) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureHealth(const Creature *creature) -{ - if (creature->isHealthHidden()) - { +void ProtocolGame::sendCreatureHealth(const Creature* creature) { + if (creature->isHealthHidden()) { return; } @@ -5248,19 +4813,15 @@ void ProtocolGame::sendCreatureHealth(const Creature *creature) msg.addByte(0x8C); msg.add(creature->getID()); - if (creature->isHealthHidden()) - { + if (creature->isHealthHidden()) { msg.addByte(0x00); - } - else - { + } else { msg.addByte(std::ceil((static_cast(creature->getHealth()) / std::max(creature->getMaxHealth(), 1)) * 100)); } writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureUpdate(const Creature* target) -{ +void ProtocolGame::sendPartyCreatureUpdate(const Creature* target) { bool known; uint32_t removedKnown = 0; uint32_t cid = target->getID(); @@ -5269,13 +4830,12 @@ void ProtocolGame::sendPartyCreatureUpdate(const Creature* target) NetworkMessage msg; msg.addByte(0x8B); msg.add(cid); - msg.addByte(0); // creature update + msg.addByte(0); // creature update AddCreature(msg, target, known, removedKnown); writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureShield(const Creature* target) -{ +void ProtocolGame::sendPartyCreatureShield(const Creature* target) { uint32_t cid = target->getID(); if (knownCreatureSet.find(cid) == knownCreatureSet.end()) { sendPartyCreatureUpdate(target); @@ -5289,8 +4849,7 @@ void ProtocolGame::sendPartyCreatureShield(const Creature* target) writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureSkull(const Creature* target) -{ +void ProtocolGame::sendPartyCreatureSkull(const Creature* target) { if (g_game().getWorldType() != WORLD_TYPE_PVP) { return; } @@ -5308,8 +4867,7 @@ void ProtocolGame::sendPartyCreatureSkull(const Creature* target) writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureHealth(const Creature* target, uint8_t healthPercent) -{ +void ProtocolGame::sendPartyCreatureHealth(const Creature* target, uint8_t healthPercent) { uint32_t cid = target->getID(); if (knownCreatureSet.find(cid) == knownCreatureSet.end()) { sendPartyCreatureUpdate(target); @@ -5323,8 +4881,7 @@ void ProtocolGame::sendPartyCreatureHealth(const Creature* target, uint8_t healt writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyPlayerMana(const Player* target, uint8_t manaPercent) -{ +void ProtocolGame::sendPartyPlayerMana(const Player* target, uint8_t manaPercent) { uint32_t cid = target->getID(); if (knownCreatureSet.find(cid) == knownCreatureSet.end()) { sendPartyCreatureUpdate(target); @@ -5333,13 +4890,12 @@ void ProtocolGame::sendPartyPlayerMana(const Player* target, uint8_t manaPercent NetworkMessage msg; msg.addByte(0x8B); msg.add(cid); - msg.addByte(11); // mana percent + msg.addByte(11); // mana percent msg.addByte(manaPercent); writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureShowStatus(const Creature* target, bool showStatus) -{ +void ProtocolGame::sendPartyCreatureShowStatus(const Creature* target, bool showStatus) { uint32_t cid = target->getID(); if (knownCreatureSet.find(cid) == knownCreatureSet.end()) { sendPartyCreatureUpdate(target); @@ -5348,13 +4904,12 @@ void ProtocolGame::sendPartyCreatureShowStatus(const Creature* target, bool show NetworkMessage msg; msg.addByte(0x8B); msg.add(cid); - msg.addByte(12); // show status + msg.addByte(12); // show status msg.addByte((showStatus ? 0x01 : 0x00)); writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyPlayerVocation(const Player* target) -{ +void ProtocolGame::sendPartyPlayerVocation(const Player* target) { uint32_t cid = target->getID(); if (knownCreatureSet.find(cid) == knownCreatureSet.end()) { sendPartyCreatureUpdate(target); @@ -5364,32 +4919,29 @@ void ProtocolGame::sendPartyPlayerVocation(const Player* target) NetworkMessage msg; msg.addByte(0x8B); msg.add(cid); - msg.addByte(13); // vocation + msg.addByte(13); // vocation msg.addByte(target->getVocation()->getClientId()); writeToOutputBuffer(msg); } -void ProtocolGame::sendPlayerVocation(const Player* target) -{ +void ProtocolGame::sendPlayerVocation(const Player* target) { NetworkMessage msg; msg.addByte(0x8B); msg.add(target->getID()); - msg.addByte(13); // vocation + msg.addByte(13); // vocation msg.addByte(target->getVocation()->getClientId()); writeToOutputBuffer(msg); } -void ProtocolGame::sendFYIBox(const std::string &message) -{ +void ProtocolGame::sendFYIBox(const std::string &message) { NetworkMessage msg; msg.addByte(0x15); msg.addString(message); writeToOutputBuffer(msg); } -//tile -void ProtocolGame::sendMapDescription(const Position& pos) -{ +// tile +void ProtocolGame::sendMapDescription(const Position &pos) { NetworkMessage msg; msg.addByte(0x64); msg.addPosition(player->getPosition()); @@ -5397,10 +4949,8 @@ void ProtocolGame::sendMapDescription(const Position& pos) writeToOutputBuffer(msg); } -void ProtocolGame::sendAddTileItem(const Position &pos, uint32_t stackpos, const Item *item) -{ - if (!canSee(pos)) - { +void ProtocolGame::sendAddTileItem(const Position &pos, uint32_t stackpos, const Item* item) { + if (!canSee(pos)) { return; } @@ -5412,10 +4962,8 @@ void ProtocolGame::sendAddTileItem(const Position &pos, uint32_t stackpos, const writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTileItem(const Position &pos, uint32_t stackpos, const Item *item) -{ - if (!canSee(pos)) - { +void ProtocolGame::sendUpdateTileItem(const Position &pos, uint32_t stackpos, const Item* item) { + if (!canSee(pos)) { return; } @@ -5427,10 +4975,8 @@ void ProtocolGame::sendUpdateTileItem(const Position &pos, uint32_t stackpos, co writeToOutputBuffer(msg); } -void ProtocolGame::sendRemoveTileThing(const Position &pos, uint32_t stackpos) -{ - if (!canSee(pos)) - { +void ProtocolGame::sendRemoveTileThing(const Position &pos, uint32_t stackpos) { + if (!canSee(pos)) { return; } @@ -5439,10 +4985,8 @@ void ProtocolGame::sendRemoveTileThing(const Position &pos, uint32_t stackpos) writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTile(const Tile *tile, const Position &pos) -{ - if (!canSee(pos)) - { +void ProtocolGame::sendUpdateTile(const Tile* tile, const Position &pos) { + if (!canSee(pos)) { return; } @@ -5450,14 +4994,11 @@ void ProtocolGame::sendUpdateTile(const Tile *tile, const Position &pos) msg.addByte(0x69); msg.addPosition(pos); - if (tile) - { + if (tile) { GetTileDescription(tile, msg); msg.addByte(0x00); msg.addByte(0xFF); - } - else - { + } else { msg.addByte(0x01); msg.addByte(0xFF); } @@ -5465,22 +5006,19 @@ void ProtocolGame::sendUpdateTile(const Tile *tile, const Position &pos) writeToOutputBuffer(msg); } -void ProtocolGame::sendPendingStateEntered() -{ +void ProtocolGame::sendPendingStateEntered() { NetworkMessage msg; msg.addByte(0x0A); writeToOutputBuffer(msg); } -void ProtocolGame::sendEnterWorld() -{ +void ProtocolGame::sendEnterWorld() { NetworkMessage msg; msg.addByte(0x0F); writeToOutputBuffer(msg); } -void ProtocolGame::sendFightModes() -{ +void ProtocolGame::sendFightModes() { NetworkMessage msg; msg.addByte(0xA7); msg.addByte(player->fightMode); @@ -5490,17 +5028,13 @@ void ProtocolGame::sendFightModes() writeToOutputBuffer(msg); } -void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos, int32_t stackpos, bool isLogin) -{ - if (!canSee(pos)) - { +void ProtocolGame::sendAddCreature(const Creature* creature, const Position &pos, int32_t stackpos, bool isLogin) { + if (!canSee(pos)) { return; } - if (creature != player) - { - if (stackpos >= 10) - { + if (creature != player) { + if (stackpos >= 10) { return; } @@ -5515,16 +5049,11 @@ void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos AddCreature(msg, creature, known, removedKnown); writeToOutputBuffer(msg); - if (isLogin) - { - if (const Player *creaturePlayer = creature->getPlayer()) - { - if (!creaturePlayer->isAccessPlayer() || - creaturePlayer->getAccountType() == account::ACCOUNT_TYPE_NORMAL) + if (isLogin) { + if (const Player* creaturePlayer = creature->getPlayer()) { + if (!creaturePlayer->isAccessPlayer() || creaturePlayer->getAccountType() == account::ACCOUNT_TYPE_NORMAL) sendMagicEffect(pos, CONST_ME_TELEPORT); - } - else - { + } else { sendMagicEffect(pos, CONST_ME_TELEPORT); } } @@ -5543,12 +5072,9 @@ void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos msg.addDouble(Creature::speedC, 3); // can report bugs? - if (player->getAccountType() >= account::ACCOUNT_TYPE_NORMAL) - { + if (player->getAccountType() >= account::ACCOUNT_TYPE_NORMAL) { msg.addByte(0x01); - } - else - { + } else { msg.addByte(0x00); } @@ -5569,13 +5095,11 @@ void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos sendMapDescription(pos); loggedIn = true; - if (isLogin) - { + if (isLogin) { sendMagicEffect(pos, CONST_ME_TELEPORT); } - for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) - { + for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { sendInventoryItem(static_cast(i), player->getInventoryItem(static_cast(i))); } @@ -5592,46 +5116,35 @@ void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos player->sendTaskHuntingData(); sendForgingData(); - //gameworld light-settings + // gameworld light-settings sendWorldLight(g_game().getWorldLightInfo()); - //player light level + // player light level sendCreatureLight(creature); const std::forward_list &vipEntries = IOLoginData::getVIPEntries(player->getAccount()); - if (player->isAccessPlayer()) - { - for (const VIPEntry &entry : vipEntries) - { + if (player->isAccessPlayer()) { + for (const VIPEntry &entry : vipEntries) { VipStatus_t vipStatus; - const Player *vipPlayer = g_game().getPlayerByGUID(entry.guid); - if (!vipPlayer) - { + const Player* vipPlayer = g_game().getPlayerByGUID(entry.guid); + if (!vipPlayer) { vipStatus = VIPSTATUS_OFFLINE; - } - else - { + } else { vipStatus = vipPlayer->statusVipList; } sendVIP(entry.guid, entry.name, entry.description, entry.icon, entry.notify, vipStatus); } - } - else - { - for (const VIPEntry &entry : vipEntries) - { + } else { + for (const VIPEntry &entry : vipEntries) { VipStatus_t vipStatus; - const Player *vipPlayer = g_game().getPlayerByGUID(entry.guid); - if (!vipPlayer || vipPlayer->isInGhostMode()) - { + const Player* vipPlayer = g_game().getPlayerByGUID(entry.guid); + if (!vipPlayer || vipPlayer->isInGhostMode()) { vipStatus = VIPSTATUS_OFFLINE; - } - else - { + } else { vipStatus = vipPlayer->statusVipList; } @@ -5640,13 +5153,11 @@ void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos } sendInventoryIds(); - Item *slotItem = player->getInventoryItem(CONST_SLOT_BACKPACK); - if (slotItem) - { - Container *mainBackpack = slotItem->getContainer(); - Container *hasQuickLootContainer = player->getLootContainer(OBJECTCATEGORY_DEFAULT); - if (mainBackpack && !hasQuickLootContainer) - { + Item* slotItem = player->getInventoryItem(CONST_SLOT_BACKPACK); + if (slotItem) { + Container* mainBackpack = slotItem->getContainer(); + Container* hasQuickLootContainer = player->getLootContainer(OBJECTCATEGORY_DEFAULT); + if (mainBackpack && !hasQuickLootContainer) { player->setLootContainer(OBJECTCATEGORY_DEFAULT, mainBackpack); sendInventoryItem(CONST_SLOT_BACKPACK, player->getInventoryItem(CONST_SLOT_BACKPACK)); } @@ -5660,78 +5171,54 @@ void ProtocolGame::sendAddCreature(const Creature *creature, const Position &pos player->sendIcons(); } -void ProtocolGame::sendMoveCreature(const Creature *creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) -{ - if (creature == player) - { - if (oldStackPos >= 10) - { +void ProtocolGame::sendMoveCreature(const Creature* creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { + if (creature == player) { + if (oldStackPos >= 10) { sendMapDescription(newPos); - } - else if (teleport) - { + } else if (teleport) { NetworkMessage msg; RemoveTileThing(msg, oldPos, oldStackPos); writeToOutputBuffer(msg); sendMapDescription(newPos); - } - else - { + } else { NetworkMessage msg; - if (oldPos.z == MAP_INIT_SURFACE_LAYER && newPos.z >= MAP_INIT_SURFACE_LAYER + 1) - { + if (oldPos.z == MAP_INIT_SURFACE_LAYER && newPos.z >= MAP_INIT_SURFACE_LAYER + 1) { RemoveTileThing(msg, oldPos, oldStackPos); - } - else - { + } else { msg.addByte(0x6D); msg.addPosition(oldPos); msg.addByte(oldStackPos); msg.addPosition(newPos); } - if (newPos.z > oldPos.z) - { + if (newPos.z > oldPos.z) { MoveDownCreature(msg, creature, newPos, oldPos); - } - else if (newPos.z < oldPos.z) - { + } else if (newPos.z < oldPos.z) { MoveUpCreature(msg, creature, newPos, oldPos); } - if (oldPos.y > newPos.y) - { // north, for old x + if (oldPos.y > newPos.y) { // north, for old x msg.addByte(0x65); GetMapDescription(oldPos.x - Map::maxClientViewportX, newPos.y - Map::maxClientViewportY, newPos.z, (Map::maxClientViewportX + 1) * 2, 1, msg); - } - else if (oldPos.y < newPos.y) - { // south, for old x + } else if (oldPos.y < newPos.y) { // south, for old x msg.addByte(0x67); GetMapDescription(oldPos.x - Map::maxClientViewportX, newPos.y + (Map::maxClientViewportY + 1), newPos.z, (Map::maxClientViewportX + 1) * 2, 1, msg); } - if (oldPos.x < newPos.x) - { // east, [with new y] + if (oldPos.x < newPos.x) { // east, [with new y] msg.addByte(0x66); GetMapDescription(newPos.x + (Map::maxClientViewportX + 1), newPos.y - Map::maxClientViewportY, newPos.z, 1, (Map::maxClientViewportY + 1) * 2, msg); - } - else if (oldPos.x > newPos.x) - { // west, [with new y] + } else if (oldPos.x > newPos.x) { // west, [with new y] msg.addByte(0x68); GetMapDescription(newPos.x - Map::maxClientViewportX, newPos.y - Map::maxClientViewportY, newPos.z, 1, (Map::maxClientViewportY + 1) * 2, msg); } writeToOutputBuffer(msg); } - } - else if (canSee(oldPos) && canSee(newPos)) - { - if (teleport || (oldPos.z == MAP_INIT_SURFACE_LAYER && newPos.z >= MAP_INIT_SURFACE_LAYER + 1) || oldStackPos >= 10) - { + } else if (canSee(oldPos) && canSee(newPos)) { + if (teleport || (oldPos.z == MAP_INIT_SURFACE_LAYER && newPos.z >= MAP_INIT_SURFACE_LAYER + 1) || oldStackPos >= 10) { sendRemoveTileThing(oldPos, oldStackPos); sendAddCreature(creature, newPos, newStackPos, false); - } - else - { + } else { NetworkMessage msg; msg.addByte(0x6D); msg.addPosition(oldPos); @@ -5739,36 +5226,27 @@ void ProtocolGame::sendMoveCreature(const Creature *creature, const Position &ne msg.addPosition(newPos); writeToOutputBuffer(msg); } - } - else if (canSee(oldPos)) - { + } else if (canSee(oldPos)) { sendRemoveTileThing(oldPos, oldStackPos); - } - else if (canSee(newPos)) - { + } else if (canSee(newPos)) { sendAddCreature(creature, newPos, newStackPos, false); } } -void ProtocolGame::sendInventoryItem(Slots_t slot, const Item *item) -{ +void ProtocolGame::sendInventoryItem(Slots_t slot, const Item* item) { NetworkMessage msg; - if (item) - { + if (item) { msg.addByte(0x78); msg.addByte(slot); AddItem(msg, item); - } - else - { + } else { msg.addByte(0x79); msg.addByte(slot); } writeToOutputBuffer(msg); } -void ProtocolGame::sendInventoryIds() -{ +void ProtocolGame::sendInventoryIds() { ItemsTierCountList items = player->getInventoryItemsId(); NetworkMessage msg; @@ -5776,8 +5254,7 @@ void ProtocolGame::sendInventoryIds() auto countPosition = msg.getBufferPosition(); msg.skipBytes(2); // Total items count - for (uint16_t i = 1; i <= 11; i++) - { + for (uint16_t i = 1; i <= 11; i++) { msg.add(i); msg.addByte(0x00); msg.add(0x01); @@ -5798,8 +5275,7 @@ void ProtocolGame::sendInventoryIds() writeToOutputBuffer(msg); } -void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const Item *item) -{ +void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const Item* item) { NetworkMessage msg; msg.addByte(0x70); msg.addByte(cid); @@ -5808,8 +5284,7 @@ void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const Item * writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Item *item) -{ +void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Item* item) { NetworkMessage msg; msg.addByte(0x71); msg.addByte(cid); @@ -5818,69 +5293,54 @@ void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Ite writeToOutputBuffer(msg); } -void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Item *lastItem) -{ +void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Item* lastItem) { NetworkMessage msg; msg.addByte(0x72); msg.addByte(cid); msg.add(slot); - if (lastItem) - { + if (lastItem) { AddItem(msg, lastItem); - } - else - { + } else { msg.add(0x00); } writeToOutputBuffer(msg); } -void ProtocolGame::sendTextWindow(uint32_t windowTextId, Item *item, uint16_t maxlen, bool canWrite) -{ +void ProtocolGame::sendTextWindow(uint32_t windowTextId, Item* item, uint16_t maxlen, bool canWrite) { NetworkMessage msg; msg.addByte(0x96); msg.add(windowTextId); AddItem(msg, item); - if (canWrite) - { + if (canWrite) { msg.add(maxlen); msg.addString(item->getAttribute(ItemAttribute_t::TEXT)); - } - else - { + } else { const std::string &text = item->getAttribute(ItemAttribute_t::TEXT); msg.add(text.size()); msg.addString(text); } const std::string &writer = item->getAttribute(ItemAttribute_t::WRITER); - if (!writer.empty()) - { + if (!writer.empty()) { msg.addString(writer); - } - else - { + } else { msg.add(0x00); } msg.addByte(0x00); // Show (Traded) auto writtenDate = item->getAttribute(ItemAttribute_t::DATE); - if (writtenDate != 0) - { + if (writtenDate != 0) { msg.addString(formatDateShort(writtenDate)); - } - else - { + } else { msg.add(0x00); } writeToOutputBuffer(msg); } -void ProtocolGame::sendHouseWindow(uint32_t windowTextId, const std::string &text) -{ +void ProtocolGame::sendHouseWindow(uint32_t windowTextId, const std::string &text) { NetworkMessage msg; msg.addByte(0x97); msg.addByte(0x00); @@ -5889,8 +5349,7 @@ void ProtocolGame::sendHouseWindow(uint32_t windowTextId, const std::string &tex writeToOutputBuffer(msg); } -void ProtocolGame::sendOutfitWindow() -{ +void ProtocolGame::sendOutfitWindow() { NetworkMessage msg; msg.addByte(0xC8); @@ -5935,9 +5394,9 @@ void ProtocolGame::sendOutfitWindow() ++outfitSize; } - const auto& outfits = Outfits::getInstance().getOutfits(player->getSex()); + const auto &outfits = Outfits::getInstance().getOutfits(player->getSex()); - for (const Outfit& outfit : outfits) { + for (const Outfit &outfit : outfits) { uint8_t addons; if (player->getOutfitAddons(outfit, addons)) { msg.add(outfit.lookType); @@ -5981,8 +5440,8 @@ void ProtocolGame::sendOutfitWindow() uint16_t mountSize = 0; msg.skipBytes(2); - const auto& mounts = g_game().mounts.getMounts(); - for (const Mount& mount : mounts) { + const auto &mounts = g_game().mounts.getMounts(); + for (const Mount &mount : mounts) { if (player->hasMount(&mount)) { msg.add(mount.clientId); msg.addString(mount.name); @@ -6011,9 +5470,9 @@ void ProtocolGame::sendOutfitWindow() uint16_t familiarSize = 0; msg.skipBytes(2); - const auto& familiars = Familiars::getInstance().getFamiliars(player->getVocationId()); + const auto &familiars = Familiars::getInstance().getFamiliars(player->getVocationId()); - for (const Familiar& familiar : familiars) { + for (const Familiar &familiar : familiars) { if (!player->getFamiliar(familiar)) { continue; } @@ -6022,7 +5481,7 @@ void ProtocolGame::sendOutfitWindow() msg.addString(familiar.name); msg.addByte(0x00); if (++familiarSize == limitFamiliars) { - break; + break; } } @@ -6031,7 +5490,7 @@ void ProtocolGame::sendOutfitWindow() msg.add(familiarSize); msg.setBufferPosition(endFamiliars); - msg.addByte(0x00); //Try outfit + msg.addByte(0x00); // Try outfit msg.addByte(mounted ? 0x01 : 0x00); // Version 12.81 - Random mount 'bool' @@ -6040,8 +5499,7 @@ void ProtocolGame::sendOutfitWindow() writeToOutputBuffer(msg); } -void ProtocolGame::sendPodiumWindow(const Item* podium, const Position& position, uint16_t itemId, uint8_t stackpos) -{ +void ProtocolGame::sendPodiumWindow(const Item* podium, const Position &position, uint16_t itemId, uint8_t stackpos) { NetworkMessage msg; msg.addByte(0xC8); @@ -6072,8 +5530,8 @@ void ProtocolGame::sendPodiumWindow(const Item* podium, const Position& position uint16_t outfitSize = 0; msg.skipBytes(2); - const auto& outfits = Outfits::getInstance().getOutfits(player->getSex()); - for (const Outfit& outfit : outfits) { + const auto &outfits = Outfits::getInstance().getOutfits(player->getSex()); + for (const Outfit &outfit : outfits) { uint8_t addons; if (!player->getOutfitAddons(outfit, addons)) { continue; @@ -6098,8 +5556,8 @@ void ProtocolGame::sendPodiumWindow(const Item* podium, const Position& position uint16_t mountSize = 0; msg.skipBytes(2); - const auto& mounts = g_game().mounts.getMounts(); - for (const Mount& mount : mounts) { + const auto &mounts = g_game().mounts.getMounts(); + for (const Mount &mount : mounts) { if (player->hasMount(&mount)) { msg.add(mount.clientId); msg.addString(mount.name); @@ -6132,8 +5590,7 @@ void ProtocolGame::sendPodiumWindow(const Item* podium, const Position& position writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus) -{ +void ProtocolGame::sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus) { NetworkMessage msg; msg.addByte(0xD3); msg.add(guid); @@ -6141,8 +5598,7 @@ void ProtocolGame::sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus) writeToOutputBuffer(msg); } -void ProtocolGame::sendVIP(uint32_t guid, const std::string &name, const std::string &description, uint32_t icon, bool notify, VipStatus_t status) -{ +void ProtocolGame::sendVIP(uint32_t guid, const std::string &name, const std::string &description, uint32_t icon, bool notify, VipStatus_t status) { NetworkMessage msg; msg.addByte(0xD2); msg.add(guid); @@ -6155,8 +5611,7 @@ void ProtocolGame::sendVIP(uint32_t guid, const std::string &name, const std::st writeToOutputBuffer(msg); } -void ProtocolGame::sendSpellCooldown(uint8_t spellId, uint32_t time) -{ +void ProtocolGame::sendSpellCooldown(uint8_t spellId, uint32_t time) { NetworkMessage msg; msg.addByte(0xA4); @@ -6165,8 +5620,7 @@ void ProtocolGame::sendSpellCooldown(uint8_t spellId, uint32_t time) writeToOutputBuffer(msg); } -void ProtocolGame::sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) -{ +void ProtocolGame::sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) { NetworkMessage msg; msg.addByte(0xA5); msg.addByte(groupId); @@ -6174,16 +5628,14 @@ void ProtocolGame::sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) writeToOutputBuffer(msg); } -void ProtocolGame::sendUseItemCooldown(uint32_t time) -{ +void ProtocolGame::sendUseItemCooldown(uint32_t time) { NetworkMessage msg; msg.addByte(0xA6); msg.add(time); writeToOutputBuffer(msg); } -void ProtocolGame::sendPreyTimeLeft(const PreySlot* slot) -{ +void ProtocolGame::sendPreyTimeLeft(const PreySlot* slot) { if (!player || !slot) { return; } @@ -6197,8 +5649,7 @@ void ProtocolGame::sendPreyTimeLeft(const PreySlot* slot) writeToOutputBuffer(msg); } -void ProtocolGame::sendPreyData(const PreySlot* slot) -{ +void ProtocolGame::sendPreyData(const PreySlot* slot) { NetworkMessage msg; msg.addByte(0xE8); msg.addByte(static_cast(slot->id)); @@ -6207,7 +5658,7 @@ void ProtocolGame::sendPreyData(const PreySlot* slot) if (slot->state == PreyDataState_Locked) { msg.addByte(player->isPremium() ? 0x01 : 0x00); } else if (slot->state == PreyDataState_Inactive) { - // Empty + // Empty } else if (slot->state == PreyDataState_Active) { if (const MonsterType* mtype = g_monsters().getMonsterTypeByRaceId(slot->selectedRaceId)) { msg.addString(mtype->name); @@ -6230,8 +5681,7 @@ void ProtocolGame::sendPreyData(const PreySlot* slot) } } else if (slot->state == PreyDataState_Selection) { msg.addByte(static_cast(slot->raceIdList.size())); - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&msg](uint16_t raceId) - { + std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&msg](uint16_t raceId) { if (const MonsterType* mtype = g_monsters().getMonsterTypeByRaceId(raceId)) { msg.addString(mtype->name); const Outfit_t outfit = mtype->info.outfit; @@ -6255,8 +5705,7 @@ void ProtocolGame::sendPreyData(const PreySlot* slot) msg.add(slot->bonusPercentage); msg.addByte(slot->bonusRarity); msg.addByte(static_cast(slot->raceIdList.size())); - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&msg](uint16_t raceId) - { + std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&msg](uint16_t raceId) { if (const MonsterType* mtype = g_monsters().getMonsterTypeByRaceId(raceId)) { msg.addString(mtype->name); const Outfit_t outfit = mtype->info.outfit; @@ -6278,8 +5727,7 @@ void ProtocolGame::sendPreyData(const PreySlot* slot) } else if (slot->state == PreyDataState_ListSelection) { const std::map bestiaryList = g_game().getBestiaryList(); msg.add(static_cast(bestiaryList.size())); - std::for_each(bestiaryList.begin(), bestiaryList.end(), [&msg](auto& mType) - { + std::for_each(bestiaryList.begin(), bestiaryList.end(), [&msg](auto &mType) { msg.add(mType.first); }); } else { @@ -6293,8 +5741,7 @@ void ProtocolGame::sendPreyData(const PreySlot* slot) writeToOutputBuffer(msg); } -void ProtocolGame::sendPreyPrices() -{ +void ProtocolGame::sendPreyPrices() { if (!player) { return; } @@ -6314,8 +5761,7 @@ void ProtocolGame::sendPreyPrices() writeToOutputBuffer(msg); } -void ProtocolGame::sendModalWindow(const ModalWindow &modalWindow) -{ +void ProtocolGame::sendModalWindow(const ModalWindow &modalWindow) { NetworkMessage msg; msg.addByte(0xFA); @@ -6324,15 +5770,13 @@ void ProtocolGame::sendModalWindow(const ModalWindow &modalWindow) msg.addString(modalWindow.message); msg.addByte(modalWindow.buttons.size()); - for (const auto &it : modalWindow.buttons) - { + for (const auto &it : modalWindow.buttons) { msg.addString(it.first); msg.addByte(it.second); } msg.addByte(modalWindow.choices.size()); - for (const auto &it : modalWindow.choices) - { + for (const auto &it : modalWindow.choices) { msg.addString(it.first); msg.addByte(it.second); } @@ -6345,78 +5789,57 @@ void ProtocolGame::sendModalWindow(const ModalWindow &modalWindow) } ////////////// Add common messages -void ProtocolGame::AddCreature(NetworkMessage &msg, const Creature *creature, bool known, uint32_t remove) -{ +void ProtocolGame::AddCreature(NetworkMessage &msg, const Creature* creature, bool known, uint32_t remove) { CreatureType_t creatureType = creature->getType(); - const Player *otherPlayer = creature->getPlayer(); + const Player* otherPlayer = creature->getPlayer(); - if (known) - { + if (known) { msg.add(0x62); msg.add(creature->getID()); - } - else - { + } else { msg.add(0x61); msg.add(remove); msg.add(creature->getID()); - if (creature->isHealthHidden()) - { + if (creature->isHealthHidden()) { msg.addByte(CREATURETYPE_HIDDEN); - } - else - { + } else { msg.addByte(creatureType); } - if (creatureType == CREATURETYPE_SUMMON_PLAYER) - { - const Creature *master = creature->getMaster(); - if (master) - { + if (creatureType == CREATURETYPE_SUMMON_PLAYER) { + const Creature* master = creature->getMaster(); + if (master) { msg.add(master->getID()); - } - else - { + } else { msg.add(0x00); } } - if (creature->isHealthHidden()) - { + if (creature->isHealthHidden()) { msg.addString(""); - } - else - { + } else { msg.addString(creature->getName()); } } - if (creature->isHealthHidden()) - { + if (creature->isHealthHidden()) { msg.addByte(0x00); - } - else - { + } else { msg.addByte(std::ceil((static_cast(creature->getHealth()) / std::max(creature->getMaxHealth(), 1)) * 100)); } msg.addByte(creature->getDirection()); - if (!creature->isInGhostMode() && !creature->isInvisible()) - { + if (!creature->isInGhostMode() && !creature->isInvisible()) { const Outfit_t &outfit = creature->getCurrentOutfit(); AddOutfit(msg, outfit); - if (outfit.lookMount != 0) - { + if (outfit.lookMount != 0) { msg.addByte(outfit.lookMountHead); msg.addByte(outfit.lookMountBody); msg.addByte(outfit.lookMountLegs); msg.addByte(outfit.lookMountFeet); } - } - else - { + } else { static Outfit_t outfit; AddOutfit(msg, outfit); } @@ -6440,8 +5863,7 @@ void ProtocolGame::AddCreature(NetworkMessage &msg, const Creature *creature, bo } } else { if (auto monster = creature->getMonster(); - monster) - { + monster) { icon = monster->getIcon(); sendIcon = icon != CREATUREICON_NONE; msg.addByte(sendIcon); // Send Icons true/false @@ -6473,55 +5895,40 @@ void ProtocolGame::AddCreature(NetworkMessage &msg, const Creature *creature, bo msg.addByte(player->getSkullClient(creature)); msg.addByte(player->getPartyShield(otherPlayer)); - if (!known) - { + if (!known) { msg.addByte(player->getGuildEmblem(otherPlayer)); } - if (creatureType == CREATURETYPE_MONSTER) - { - const Creature *master = creature->getMaster(); - if (master) - { - const Player *masterPlayer = master->getPlayer(); - if (masterPlayer) - { + if (creatureType == CREATURETYPE_MONSTER) { + const Creature* master = creature->getMaster(); + if (master) { + const Player* masterPlayer = master->getPlayer(); + if (masterPlayer) { creatureType = CREATURETYPE_SUMMON_PLAYER; } } } - if (creature->isHealthHidden()) - { + if (creature->isHealthHidden()) { msg.addByte(CREATURETYPE_HIDDEN); - } - else - { + } else { msg.addByte(creatureType); // Type (for summons) } - if (creatureType == CREATURETYPE_SUMMON_PLAYER) - { - const Creature *master = creature->getMaster(); - if (master) - { + if (creatureType == CREATURETYPE_SUMMON_PLAYER) { + const Creature* master = creature->getMaster(); + if (master) { msg.add(master->getID()); - } - else - { + } else { msg.add(0x00); } } - if (creatureType == CREATURETYPE_PLAYER) - { - const Player *otherCreature = creature->getPlayer(); - if (otherCreature) - { + if (creatureType == CREATURETYPE_PLAYER) { + const Player* otherCreature = creature->getPlayer(); + if (otherCreature) { msg.addByte(otherCreature->getVocation()->getClientId()); - } - else - { + } else { msg.addByte(0); } } @@ -6532,8 +5939,7 @@ void ProtocolGame::AddCreature(NetworkMessage &msg, const Creature *creature, bo msg.addByte(player->canWalkthroughEx(creature) ? 0x00 : 0x01); } -void ProtocolGame::AddPlayerStats(NetworkMessage &msg) -{ +void ProtocolGame::AddPlayerStats(NetworkMessage &msg) { msg.addByte(0xA0); msg.add(std::min(player->getHealth(), std::numeric_limits::max())); @@ -6560,7 +5966,7 @@ void ProtocolGame::AddPlayerStats(NetworkMessage &msg) msg.add(player->getBaseSpeed()); - Condition *condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); + Condition* condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); msg.add(condition ? condition->getTicks() / 1000 : 0x00); msg.add(player->getOfflineTrainingTime() / 60 / 1000); @@ -6568,12 +5974,11 @@ void ProtocolGame::AddPlayerStats(NetworkMessage &msg) msg.add(player->getExpBoostStamina()); // xp boost time (seconds) msg.addByte(1); // enables exp boost in the store - msg.add(player->getManaShield()); // remaining mana shield - msg.add(player->getMaxManaShield()); // total mana shield + msg.add(player->getManaShield()); // remaining mana shield + msg.add(player->getMaxManaShield()); // total mana shield } -void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) -{ +void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) { msg.addByte(0xA1); msg.add(player->getMagicLevel()); @@ -6581,16 +5986,14 @@ void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) msg.add(player->getBaseMagicLevel()); // Loyalty Bonus msg.add(player->getMagicLevelPercent() * 100); - for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; ++i) - { + for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; ++i) { msg.add(std::min(player->getSkillLevel(i), std::numeric_limits::max())); msg.add(player->getBaseSkill(i)); msg.add(player->getBaseSkill(i)); // Loyalty Bonus msg.add(player->getSkillPercent(i) * 100); } - for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; ++i) - { + for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; ++i) { msg.add(std::min(player->getSkillLevel(i), std::numeric_limits::max())); msg.add(player->getBaseSkill(i)); } @@ -6601,36 +6004,29 @@ void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) // used for imbuement (Feather) msg.add(player->getCapacity()); // total capacity msg.add(player->getBaseCapacity()); // base total capacity - } -void ProtocolGame::AddOutfit(NetworkMessage &msg, const Outfit_t &outfit, bool addMount /* = true*/) -{ +void ProtocolGame::AddOutfit(NetworkMessage &msg, const Outfit_t &outfit, bool addMount /* = true*/) { msg.add(outfit.lookType); - if (outfit.lookType != 0) - { + if (outfit.lookType != 0) { msg.addByte(outfit.lookHead); msg.addByte(outfit.lookBody); msg.addByte(outfit.lookLegs); msg.addByte(outfit.lookFeet); msg.addByte(outfit.lookAddons); - } - else - { + } else { msg.add(outfit.lookTypeEx); } - if (addMount) - { + if (addMount) { msg.add(outfit.lookMount); } } -void ProtocolGame::addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) const -{ - Imbuement *imbuement = g_imbuements().getImbuement(imbuementId); - const BaseImbuement *baseImbuement = g_imbuements().getBaseByID(imbuement->getBaseID()); - const CategoryImbuement *categoryImbuement = g_imbuements().getCategoryByID(imbuement->getCategory()); +void ProtocolGame::addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) const { + Imbuement* imbuement = g_imbuements().getImbuement(imbuementId); + const BaseImbuement* baseImbuement = g_imbuements().getBaseByID(imbuement->getBaseID()); + const CategoryImbuement* categoryImbuement = g_imbuements().getCategoryByID(imbuement->getCategory()); msg.add(imbuementId); msg.addString(baseImbuement->name + " " + imbuement->getName()); @@ -6645,8 +6041,7 @@ void ProtocolGame::addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) c const auto &items = imbuement->getItems(); msg.addByte(items.size()); - for (const auto &itm : items) - { + for (const auto &itm : items) { const ItemType &it = Item::items[itm.first]; msg.add(itm.first); msg.addString(it.name); @@ -6658,10 +6053,8 @@ void ProtocolGame::addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) c msg.add(baseImbuement->protectionPrice); } -void ProtocolGame::openImbuementWindow(Item *item) -{ - if (!item || item->isRemoved()) - { +void ProtocolGame::openImbuementWindow(Item* item) { + if (!item || item->isRemoved()) { return; } @@ -6676,11 +6069,9 @@ void ProtocolGame::openImbuementWindow(Item *item) msg.addByte(item->getImbuementSlot()); // Send imbuement time - for (uint8_t slotid = 0; slotid < static_cast(item->getImbuementSlot()); slotid++) - { + for (uint8_t slotid = 0; slotid < static_cast(item->getImbuementSlot()); slotid++) { ImbuementInfo imbuementInfo; - if (!item->getImbuementInfo(slotid, &imbuementInfo)) - { + if (!item->getImbuementInfo(slotid, &imbuementInfo)) { msg.addByte(0x00); continue; } @@ -6691,19 +6082,16 @@ void ProtocolGame::openImbuementWindow(Item *item) msg.add(g_imbuements().getBaseByID(imbuementInfo.imbuement->getBaseID())->removeCost); } - std::vector imbuements = g_imbuements().getImbuements(player, item); + std::vector imbuements = g_imbuements().getImbuements(player, item); phmap::flat_hash_map needItems; msg.add(imbuements.size()); - for (const Imbuement *imbuement : imbuements) - { + for (const Imbuement* imbuement : imbuements) { addImbuementInfo(msg, imbuement->getID()); const auto &items = imbuement->getItems(); - for (const auto &itm : items) - { - if (!needItems.count(itm.first)) - { + for (const auto &itm : items) { + if (!needItems.count(itm.first)) { needItems[itm.first] = player->getItemTypeCount(itm.first); uint32_t stashCount = player->getStashItemCount(Item::items[itm.first].id); if (stashCount > 0) { @@ -6714,8 +6102,7 @@ void ProtocolGame::openImbuementWindow(Item *item) } msg.add(needItems.size()); - for (const auto &itm : needItems) - { + for (const auto &itm : needItems) { msg.add(itm.first); msg.add(itm.second); } @@ -6725,8 +6112,7 @@ void ProtocolGame::openImbuementWindow(Item *item) writeToOutputBuffer(msg); } -void ProtocolGame::sendMessageDialog(const std::string &message) -{ +void ProtocolGame::sendMessageDialog(const std::string &message) { NetworkMessage msg; msg.addByte(0xED); msg.addByte(0x14); // Unknown type @@ -6734,8 +6120,7 @@ void ProtocolGame::sendMessageDialog(const std::string &message) writeToOutputBuffer(msg); } -void ProtocolGame::sendImbuementResult(const std::string message) -{ +void ProtocolGame::sendImbuementResult(const std::string message) { NetworkMessage msg; msg.addByte(0xED); msg.addByte(0x01); @@ -6743,22 +6128,19 @@ void ProtocolGame::sendImbuementResult(const std::string message) writeToOutputBuffer(msg); } -void ProtocolGame::closeImbuementWindow() -{ +void ProtocolGame::closeImbuementWindow() { NetworkMessage msg; msg.addByte(0xEC); writeToOutputBuffer(msg); } -void ProtocolGame::AddWorldLight(NetworkMessage &msg, LightInfo lightInfo) -{ +void ProtocolGame::AddWorldLight(NetworkMessage &msg, LightInfo lightInfo) { msg.addByte(0x82); msg.addByte((player->isAccessPlayer() ? 0xFF : lightInfo.level)); msg.addByte(lightInfo.color); } -void ProtocolGame::sendSpecialContainersAvailable() -{ +void ProtocolGame::sendSpecialContainersAvailable() { if (!player) return; @@ -6769,8 +6151,7 @@ void ProtocolGame::sendSpecialContainersAvailable() writeToOutputBuffer(msg); } -void ProtocolGame::updatePartyTrackerAnalyzer(const Party* party) -{ +void ProtocolGame::updatePartyTrackerAnalyzer(const Party* party) { if (!player || !party || !party->getLeader()) return; @@ -6809,8 +6190,7 @@ void ProtocolGame::updatePartyTrackerAnalyzer(const Party* party) writeToOutputBuffer(msg); } -void ProtocolGame::AddCreatureLight(NetworkMessage &msg, const Creature *creature) -{ +void ProtocolGame::AddCreatureLight(NetworkMessage &msg, const Creature* creature) { LightInfo lightInfo = creature->getCreatureLight(); msg.addByte(0x8D); @@ -6819,11 +6199,9 @@ void ProtocolGame::AddCreatureLight(NetworkMessage &msg, const Creature *creatur msg.addByte(lightInfo.color); } -//tile -void ProtocolGame::RemoveTileThing(NetworkMessage &msg, const Position &pos, uint32_t stackpos) -{ - if (stackpos >= 10) - { +// tile +void ProtocolGame::RemoveTileThing(NetworkMessage &msg, const Position &pos, uint32_t stackpos) { + if (stackpos >= 10) { return; } @@ -6832,8 +6210,7 @@ void ProtocolGame::RemoveTileThing(NetworkMessage &msg, const Position &pos, uin msg.addByte(stackpos); } -void ProtocolGame::sendKillTrackerUpdate(Container *corpse, const std::string &name, const Outfit_t creatureOutfit) -{ +void ProtocolGame::sendKillTrackerUpdate(Container* corpse, const std::string &name, const Outfit_t creatureOutfit) { bool isCorpseEmpty = corpse->empty(); NetworkMessage msg; @@ -6847,10 +6224,8 @@ void ProtocolGame::sendKillTrackerUpdate(Container *corpse, const std::string &n msg.addByte(creatureOutfit.lookType ? creatureOutfit.lookAddons : 0x00); msg.addByte(isCorpseEmpty ? 0 : corpse->size()); - if (!isCorpseEmpty) - { - for (const auto &it : corpse->getItemList()) - { + if (!isCorpseEmpty) { + for (const auto &it : corpse->getItemList()) { AddItem(msg, it); } } @@ -6858,10 +6233,8 @@ void ProtocolGame::sendKillTrackerUpdate(Container *corpse, const std::string &n writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateSupplyTracker(const Item *item) -{ - if (!player || !item) - { +void ProtocolGame::sendUpdateSupplyTracker(const Item* item) { + if (!player || !item) { return; } @@ -6872,25 +6245,20 @@ void ProtocolGame::sendUpdateSupplyTracker(const Item *item) writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateImpactTracker(CombatType_t type, int32_t amount) -{ +void ProtocolGame::sendUpdateImpactTracker(CombatType_t type, int32_t amount) { NetworkMessage msg; msg.addByte(0xCC); - if (type == COMBAT_HEALING) - { + if (type == COMBAT_HEALING) { msg.addByte(ANALYZER_HEAL); msg.add(amount); - } - else - { + } else { msg.addByte(ANALYZER_DAMAGE_DEALT); msg.add(amount); msg.addByte(getCipbiaElement(type)); } writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, std::string target) -{ +void ProtocolGame::sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, std::string target) { NetworkMessage msg; msg.addByte(0xCC); msg.addByte(ANALYZER_DAMAGE_RECEIVED); @@ -6900,8 +6268,7 @@ void ProtocolGame::sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, st writeToOutputBuffer(msg); } -void ProtocolGame::sendTaskHuntingData(const TaskHuntingSlot* slot) -{ +void ProtocolGame::sendTaskHuntingData(const TaskHuntingSlot* slot) { NetworkMessage msg; msg.addByte(0xBB); msg.addByte(static_cast(slot->id)); @@ -6913,8 +6280,7 @@ void ProtocolGame::sendTaskHuntingData(const TaskHuntingSlot* slot) } else if (slot->state == PreyTaskDataState_Selection) { const Player* user = player; msg.add(static_cast(slot->raceIdList.size())); - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&msg, user](uint16_t raceid) - { + std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&msg, user](uint16_t raceid) { msg.add(raceid); msg.addByte(user->isCreatureUnlockedOnTaskHunting(g_monsters().getMonsterTypeByRaceId(raceid)) ? 0x01 : 0x00); }); @@ -6922,8 +6288,7 @@ void ProtocolGame::sendTaskHuntingData(const TaskHuntingSlot* slot) const Player* user = player; const std::map bestiaryList = g_game().getBestiaryList(); msg.add(static_cast(bestiaryList.size())); - std::for_each(bestiaryList.begin(), bestiaryList.end(), [&msg, user](auto& mType) - { + std::for_each(bestiaryList.begin(), bestiaryList.end(), [&msg, user](auto &mType) { msg.add(mType.first); msg.addByte(user->isCreatureUnlockedOnTaskHunting(g_monsters().getMonsterType(mType.second)) ? 0x01 : 0x00); }); @@ -6969,19 +6334,16 @@ void ProtocolGame::sendTaskHuntingData(const TaskHuntingSlot* slot) writeToOutputBuffer(msg); } -void ProtocolGame::MoveUpCreature(NetworkMessage &msg, const Creature *creature, const Position &newPos, const Position &oldPos) -{ - if (creature != player) - { +void ProtocolGame::MoveUpCreature(NetworkMessage &msg, const Creature* creature, const Position &newPos, const Position &oldPos) { + if (creature != player) { return; } - //floor change up + // floor change up msg.addByte(0xBE); - //going to surface - if (newPos.z == MAP_INIT_SURFACE_LAYER) - { + // going to surface + if (newPos.z == MAP_INIT_SURFACE_LAYER) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, 5, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, 3, skip); //(floor 7 and 6 already set) GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, 4, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, 4, skip); @@ -6990,85 +6352,75 @@ void ProtocolGame::MoveUpCreature(NetworkMessage &msg, const Creature *creature, GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, 1, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, 7, skip); GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, 0, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, 8, skip); - if (skip >= 0) - { + if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } - //underground, going one floor up (still underground) - else if (newPos.z > MAP_INIT_SURFACE_LAYER) - { + // underground, going one floor up (still underground) + else if (newPos.z > MAP_INIT_SURFACE_LAYER) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, oldPos.getZ() - 3, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, 3, skip); - if (skip >= 0) - { + if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } - //moving up a floor up makes us out of sync - //west + // moving up a floor up makes us out of sync + // west msg.addByte(0x68); GetMapDescription(oldPos.x - Map::maxClientViewportX, oldPos.y - (Map::maxClientViewportY - 1), newPos.z, 1, (Map::maxClientViewportY + 1) * 2, msg); - //north + // north msg.addByte(0x65); GetMapDescription(oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, newPos.z, (Map::maxClientViewportX + 1) * 2, 1, msg); } -void ProtocolGame::MoveDownCreature(NetworkMessage &msg, const Creature *creature, const Position &newPos, const Position &oldPos) -{ - if (creature != player) - { +void ProtocolGame::MoveDownCreature(NetworkMessage &msg, const Creature* creature, const Position &newPos, const Position &oldPos) { + if (creature != player) { return; } - //floor change down + // floor change down msg.addByte(0xBF); - //going from surface to underground - if (newPos.z == MAP_INIT_SURFACE_LAYER + 1) - { + // going from surface to underground + if (newPos.z == MAP_INIT_SURFACE_LAYER + 1) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, newPos.z, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, -1, skip); GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, newPos.z + 1, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, -2, skip); GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, newPos.z + 2, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, -3, skip); - if (skip >= 0) - { + if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } - //going further down - else if (newPos.z > oldPos.z && newPos.z > MAP_INIT_SURFACE_LAYER + 1 && newPos.z < MAP_MAX_LAYERS - MAP_LAYER_VIEW_LIMIT) - { + // going further down + else if (newPos.z > oldPos.z && newPos.z > MAP_INIT_SURFACE_LAYER + 1 && newPos.z < MAP_MAX_LAYERS - MAP_LAYER_VIEW_LIMIT) { int32_t skip = -1; GetFloorDescription(msg, oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, newPos.z + MAP_LAYER_VIEW_LIMIT, (Map::maxClientViewportX + 1) * 2, (Map::maxClientViewportY + 1) * 2, -3, skip); - if (skip >= 0) - { + if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); } } - //moving down a floor makes us out of sync - //east + // moving down a floor makes us out of sync + // east msg.addByte(0x66); GetMapDescription(oldPos.x + Map::maxClientViewportX + 1, oldPos.y - (Map::maxClientViewportY + 1), newPos.z, 1, ((Map::maxClientViewportY + 1) * 2), msg); - //south + // south msg.addByte(0x67); GetMapDescription(oldPos.x - Map::maxClientViewportX, oldPos.y + (Map::maxClientViewportY + 1), newPos.z, ((Map::maxClientViewportX + 1) * 2), 1, msg); } -void ProtocolGame::AddHiddenShopItem(NetworkMessage &msg) -{ +void ProtocolGame::AddHiddenShopItem(NetworkMessage &msg) { // Empty bytes from AddShopItem msg.add(0); msg.addByte(0); @@ -7078,11 +6430,9 @@ void ProtocolGame::AddHiddenShopItem(NetworkMessage &msg) msg.add(0); } -void ProtocolGame::AddShopItem(NetworkMessage &msg, const ShopBlock &shopBlock) -{ +void ProtocolGame::AddShopItem(NetworkMessage &msg, const ShopBlock &shopBlock) { // Sends the item information empty if the player doesn't have the storage to buy/sell a certain item - if (shopBlock.itemStorageKey != 0 && player->getStorageValue(shopBlock.itemStorageKey) < shopBlock.itemStorageValue) - { + if (shopBlock.itemStorageKey != 0 && player->getStorageValue(shopBlock.itemStorageKey) < shopBlock.itemStorageValue) { AddHiddenShopItem(msg); return; } @@ -7106,8 +6456,7 @@ void ProtocolGame::AddShopItem(NetworkMessage &msg, const ShopBlock &shopBlock) msg.add(shopBlock.itemSellPrice == 4294967295 ? 0 : shopBlock.itemSellPrice); } -void ProtocolGame::parseExtendedOpcode(NetworkMessage &msg) -{ +void ProtocolGame::parseExtendedOpcode(NetworkMessage &msg) { uint8_t opcode = msg.getByte(); const std::string &buffer = msg.getString(); @@ -7115,21 +6464,16 @@ void ProtocolGame::parseExtendedOpcode(NetworkMessage &msg) addGameTask(&Game::parsePlayerExtendedOpcode, player->getID(), opcode, buffer); } -void ProtocolGame::sendItemsPrice() -{ +void ProtocolGame::sendItemsPrice() { NetworkMessage msg; msg.addByte(0xCD); msg.add(g_game().getItemsPriceCount()); - if (g_game().getItemsPriceCount() > 0) - { - for (const auto &[itemId, tierAndPriceMap] : g_game().getItemsPrice()) - { - for (const auto &[tier, price] : tierAndPriceMap) - { + if (g_game().getItemsPriceCount() > 0) { + for (const auto &[itemId, tierAndPriceMap] : g_game().getItemsPrice()) { + for (const auto &[tier, price] : tierAndPriceMap) { msg.add(itemId); - if (Item::items[itemId].upgradeClassification > 0) - { + if (Item::items[itemId].upgradeClassification > 0) { msg.addByte(tier); } msg.add(price); @@ -7140,8 +6484,7 @@ void ProtocolGame::sendItemsPrice() writeToOutputBuffer(msg); } -void ProtocolGame::reloadCreature(const Creature *creature) -{ +void ProtocolGame::reloadCreature(const Creature* creature) { if (!canSee(creature)) return; @@ -7153,23 +6496,19 @@ void ProtocolGame::reloadCreature(const Creature *creature) NetworkMessage msg; phmap::flat_hash_set::iterator it = std::find(knownCreatureSet.begin(), knownCreatureSet.end(), creature->getID()); - if (it != knownCreatureSet.end()) - { + if (it != knownCreatureSet.end()) { msg.addByte(0x6B); msg.addPosition(creature->getPosition()); msg.addByte(stackpos); AddCreature(msg, creature, false, 0); - } - else - { + } else { sendAddCreature(creature, creature->getPosition(), stackpos, false); } writeToOutputBuffer(msg); } -void ProtocolGame::sendOpenStash() -{ +void ProtocolGame::sendOpenStash() { NetworkMessage msg; msg.addByte(0x29); StashItemList list = player->getStashItems(); @@ -7182,8 +6521,7 @@ void ProtocolGame::sendOpenStash() writeToOutputBuffer(msg); } -void ProtocolGame::parseStashWithdraw(NetworkMessage &msg) -{ +void ProtocolGame::parseStashWithdraw(NetworkMessage &msg) { if (!player->isSupplyStashMenuAvailable()) { player->sendCancelMessage("You can't use supply stash right now."); return; @@ -7195,7 +6533,7 @@ void ProtocolGame::parseStashWithdraw(NetworkMessage &msg) } Supply_Stash_Actions_t action = static_cast(msg.getByte()); - switch (action) { + switch (action) { case SUPPLY_STASH_ACTION_STOW_ITEM: { Position pos = msg.getPosition(); uint16_t itemId = msg.get(); @@ -7233,15 +6571,14 @@ void ProtocolGame::parseStashWithdraw(NetworkMessage &msg) player->updateUIExhausted(); } -void ProtocolGame::sendDepotItems(const ItemsTierCountList &itemMap, uint16_t count) -{ +void ProtocolGame::sendDepotItems(const ItemsTierCountList &itemMap, uint16_t count) { NetworkMessage msg; msg.addByte(0x94); - msg.add(count); // List size + msg.add(count); // List size for (const auto &itemMap_it : itemMap) { - for (const auto& [itemTier, itemCount] : itemMap_it.second) { - msg.add(itemMap_it.first); // Item ID + for (const auto &[itemTier, itemCount] : itemMap_it.second) { + msg.add(itemMap_it.first); // Item ID if (itemTier > 0) { msg.addByte(itemTier - 1); } @@ -7252,21 +6589,13 @@ void ProtocolGame::sendDepotItems(const ItemsTierCountList &itemMap, uint16_t co writeToOutputBuffer(msg); } -void ProtocolGame::sendCloseDepotSearch() -{ +void ProtocolGame::sendCloseDepotSearch() { NetworkMessage msg; msg.addByte(0x9A); writeToOutputBuffer(msg); } -void ProtocolGame::sendDepotSearchResultDetail(uint16_t itemId, - uint8_t tier, - uint32_t depotCount, - const ItemVector &depotItems, - uint32_t inboxCount, - const ItemVector &inboxItems, - uint32_t stashCount) -{ +void ProtocolGame::sendDepotSearchResultDetail(uint16_t itemId, uint8_t tier, uint32_t depotCount, const ItemVector &depotItems, uint32_t inboxCount, const ItemVector &inboxItems, uint32_t stashCount) { NetworkMessage msg; msg.addByte(0x99); msg.add(itemId); @@ -7276,13 +6605,13 @@ void ProtocolGame::sendDepotSearchResultDetail(uint16_t itemId, msg.add(depotCount); msg.addByte(static_cast(depotItems.size())); - for (const auto& item : depotItems) { + for (const auto &item : depotItems) { AddItem(msg, item); } msg.add(inboxCount); msg.addByte(static_cast(inboxItems.size())); - for (const auto& item : inboxItems) { + for (const auto &item : inboxItems) { AddItem(msg, item); } @@ -7295,18 +6624,15 @@ void ProtocolGame::sendDepotSearchResultDetail(uint16_t itemId, writeToOutputBuffer(msg); } -void ProtocolGame::parseOpenDepotSearch() -{ +void ProtocolGame::parseOpenDepotSearch() { addGameTask(&Game::playerRequestDepotItems, player->getID()); } -void ProtocolGame::parseCloseDepotSearch() -{ +void ProtocolGame::parseCloseDepotSearch() { addGameTask(&Game::playerRequestCloseDepotSearch, player->getID()); } -void ProtocolGame::parseDepotSearchItemRequest(NetworkMessage &msg) -{ +void ProtocolGame::parseDepotSearchItemRequest(NetworkMessage &msg) { uint16_t itemId = msg.get(); uint8_t itemTier = 0; if (Item::items[itemId].upgradeClassification > 0) { @@ -7316,8 +6642,7 @@ void ProtocolGame::parseDepotSearchItemRequest(NetworkMessage &msg) addGameTask(&Game::playerRequestDepotSearchItem, player->getID(), itemId, itemTier); } -void ProtocolGame::parseRetrieveDepotSearch(NetworkMessage &msg) -{ +void ProtocolGame::parseRetrieveDepotSearch(NetworkMessage &msg) { uint16_t itemId = msg.get(); uint8_t itemTier = 0; if (Item::items[itemId].upgradeClassification > 0) { @@ -7328,15 +6653,13 @@ void ProtocolGame::parseRetrieveDepotSearch(NetworkMessage &msg) addGameTask(&Game::playerRequestDepotSearchRetrieve, player->getID(), itemId, itemTier, type); } -void ProtocolGame::parseOpenParentContainer(NetworkMessage &msg) -{ +void ProtocolGame::parseOpenParentContainer(NetworkMessage &msg) { Position pos = msg.getPosition(); addGameTask(&Game::playerRequestOpenContainerFromDepotSearch, player->getID(), pos); } -void ProtocolGame::sendUpdateCreature(const Creature* creature) -{ +void ProtocolGame::sendUpdateCreature(const Creature* creature) { if (!creature || !player) { return; } @@ -7357,8 +6680,7 @@ void ProtocolGame::sendUpdateCreature(const Creature* creature) writeToOutputBuffer(msg); } -void ProtocolGame::getForgeInfoMap(const Item *item, std::map>& itemsMap) const -{ +void ProtocolGame::getForgeInfoMap(const Item* item, std::map> &itemsMap) const { std::map itemInfo; itemInfo.insert({ item->getTier(), item->getItemCount() }); auto [first, inserted] = itemsMap.try_emplace(item->getID(), itemInfo); @@ -7371,7 +6693,7 @@ void ProtocolGame::getForgeInfoMap(const Item *item, std::map slots{ CONST_SLOT_LEFT, CONST_SLOT_ARMOR, CONST_SLOT_HEAD }; + std::vector slots { CONST_SLOT_LEFT, CONST_SLOT_ARMOR, CONST_SLOT_HEAD }; for (const auto &slot : slots) { double_t skill = 0; if (const Item* item = player->getInventoryItem(slot); item) { diff --git a/src/server/network/protocol/protocolgame.h b/src/server/network/protocol/protocolgame.h index 0c1700b3699..1576a2dee69 100644 --- a/src/server/network/protocol/protocolgame.h +++ b/src/server/network/protocol/protocolgame.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLGAME_H_ #define SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLGAME_H_ @@ -28,464 +28,450 @@ class TaskHuntingSlot; class TaskHuntingOption; using ProtocolGame_ptr = std::shared_ptr; - -struct TextMessage -{ - TextMessage() = default; - TextMessage(MessageClasses initType, std::string initText) : type(initType), text(std::move(initText)) {} - - MessageClasses type = MESSAGE_STATUS; - std::string text; - Position position; - uint16_t channelId; - struct - { - int32_t value = 0; - TextColor_t color; - } primary, secondary; +struct TextMessage { + TextMessage() = default; + TextMessage(MessageClasses initType, std::string initText) : + type(initType), text(std::move(initText)) { } + + MessageClasses type = MESSAGE_STATUS; + std::string text; + Position position; + uint16_t channelId; + struct + { + int32_t value = 0; + TextColor_t color; + } primary, secondary; }; -class ProtocolGame final : public Protocol -{ -public: - // Static protocol information. - enum {SERVER_SENDS_FIRST = true}; - // Not required as we send first. - enum {PROTOCOL_IDENTIFIER = 0}; - enum {USE_CHECKSUM = true}; - - static const char *protocol_name() { - return "gameworld protocol"; - } - - explicit ProtocolGame(Connection_ptr initConnection); - - void login(const std::string &name, uint32_t accnumber, OperatingSystem_t operatingSystem); - void logout(bool displayEffect, bool forced); - - void AddItem(NetworkMessage &msg, const Item *item); - void AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier); - - uint16_t getVersion() const - { - return version; - } - -private: - // Helpers so we don't need to bind every time - template - void addGameTask(Callable function, Args &&... args); - template - void addGameTaskTimed(uint32_t delay, Callable function, Args &&... args); - - ProtocolGame_ptr getThis() - { - return std::static_pointer_cast(shared_from_this()); - } - void connect(uint32_t playerId, OperatingSystem_t operatingSystem); - void disconnectClient(const std::string &message) const; - void writeToOutputBuffer(const NetworkMessage &msg); - - void release() override; - - void checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &removedKnown); - - bool canSee(int32_t x, int32_t y, int32_t z) const; - bool canSee(const Creature *) const; - bool canSee(const Position &pos) const; - - // we have all the parse methods - void parsePacket(NetworkMessage &msg) override; - void parsePacketFromDispatcher(NetworkMessage msg, uint8_t recvbyte); - void onRecvFirstMessage(NetworkMessage &msg) override; - void onConnect() override; - - //Parse methods - void parseAutoWalk(NetworkMessage &msg); - void parseSetOutfit(NetworkMessage &msg); - void parseSay(NetworkMessage &msg); - void parseLookAt(NetworkMessage &msg); - void parseLookInBattleList(NetworkMessage &msg); - - void parseQuickLoot(NetworkMessage &msg); - void parseLootContainer(NetworkMessage &msg); - void parseQuickLootBlackWhitelist(NetworkMessage &msg); - - // Depot search - void sendDepotItems(const ItemsTierCountList &itemMap, uint16_t count); - void sendCloseDepotSearch(); - void sendDepotSearchResultDetail(uint16_t itemId, - uint8_t tier, - uint32_t depotCount, - const ItemVector &depotItems, - uint32_t inboxCount, - const ItemVector &inboxItems, - uint32_t stashCount); - void parseOpenDepotSearch(); - void parseCloseDepotSearch(); - void parseDepotSearchItemRequest(NetworkMessage &msg); - void parseOpenParentContainer(NetworkMessage &msg); - void parseRetrieveDepotSearch(NetworkMessage &msg); - - void parseFightModes(NetworkMessage &msg); - void parseAttack(NetworkMessage &msg); - void parseFollow(NetworkMessage &msg); - - void sendSessionEndInformation(SessionEndInformations information); - - void sendItemInspection(uint16_t itemId, uint8_t itemCount, const Item *item, bool cyclopedia); - void parseInspectionObject(NetworkMessage &msg); - - void parseCyclopediaCharacterInfo(NetworkMessage &msg); - - void parseHighscores(NetworkMessage &msg); - void parseTaskHuntingAction(NetworkMessage &msg); - void sendHighscoresNoData(); - void sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages); - - void parseTournamentLeaderboard(NetworkMessage &msg); - - void parseGreet(NetworkMessage &msg); - void parseBugReport(NetworkMessage &msg); - void parseDebugAssert(NetworkMessage &msg); - void parsePreyAction(NetworkMessage &msg); - void parseSendResourceBalance(); - void parseRuleViolationReport(NetworkMessage &msg); - - void parseBestiarysendRaces(); - void parseBestiarysendCreatures(NetworkMessage &msg); - void BestiarysendCharms(); - void sendBestiaryEntryChanged(uint16_t raceid); - void refreshBestiaryTracker(std::list trackerList); - void sendTeamFinderList(); - void sendLeaderTeamFinder(bool reset); - void createLeaderTeamFinder(NetworkMessage &msg); - void parsePartyAnalyzerAction(NetworkMessage &msg) const; - void parseLeaderFinderWindow(NetworkMessage &msg); - void parseMemberFinderWindow(NetworkMessage &msg); - void parseSendBuyCharmRune(NetworkMessage &msg); - void parseBestiarysendMonsterData(NetworkMessage &msg); - void addBestiaryTrackerList(NetworkMessage &msg); - void parseObjectInfo(NetworkMessage &msg); - - void parseTeleport(NetworkMessage &msg); - void parseThrow(NetworkMessage &msg); - void parseUseItemEx(NetworkMessage &msg); - void parseUseWithCreature(NetworkMessage &msg); - void parseUseItem(NetworkMessage &msg); - void parseCloseContainer(NetworkMessage &msg); - void parseUpArrowContainer(NetworkMessage &msg); - void parseUpdateContainer(NetworkMessage &msg); - void parseTextWindow(NetworkMessage &msg); - void parseHouseWindow(NetworkMessage &msg); - - void parseLookInShop(NetworkMessage &msg); - void parsePlayerBuyOnShop(NetworkMessage &msg); - void parsePlayerSellOnShop(NetworkMessage &msg); - - void parseQuestLine(NetworkMessage &msg); - - void parseInviteToParty(NetworkMessage &msg); - void parseJoinParty(NetworkMessage &msg); - void parseRevokePartyInvite(NetworkMessage &msg); - void parsePassPartyLeadership(NetworkMessage &msg); - void parseEnableSharedPartyExperience(NetworkMessage &msg); - - void parseToggleMount(NetworkMessage &msg); - - // Imbuements - void parseApplyImbuement(NetworkMessage &msg); - void parseClearImbuement(NetworkMessage &msg); - void parseCloseImbuementWindow(NetworkMessage &msg); - - void parseModalWindowAnswer(NetworkMessage &msg); - - void parseBrowseField(NetworkMessage &msg); - void parseSeekInContainer(NetworkMessage &msg); - - //trade methods - void parseRequestTrade(NetworkMessage &msg); - void parseLookInTrade(NetworkMessage &msg); - - //market methods - void parseMarketLeave(); - void parseMarketBrowse(NetworkMessage &msg); - void parseMarketCreateOffer(NetworkMessage &msg); - void parseMarketCancelOffer(NetworkMessage &msg); - void parseMarketAcceptOffer(NetworkMessage &msg); - - //VIP methods - void parseAddVip(NetworkMessage &msg); - void parseRemoveVip(NetworkMessage &msg); - void parseEditVip(NetworkMessage &msg); - - void parseRotateItem(NetworkMessage &msg); - void parseConfigureShowOffSocket(NetworkMessage& msg); - void parseWrapableItem(NetworkMessage &msg); - - //Channel tabs - void parseChannelInvite(NetworkMessage &msg); - void parseChannelExclude(NetworkMessage &msg); - void parseOpenChannel(NetworkMessage &msg); - void parseOpenPrivateChannel(NetworkMessage &msg); - void parseCloseChannel(NetworkMessage &msg); - - // Imbuement info - void addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) const; - - //Send functions - void sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel); - void sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent); - void sendClosePrivate(uint16_t channelId); - void sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName); - void sendChannelsDialog(); - void sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap *channelUsers, const InvitedMap *invitedUsers); - void sendOpenPrivateChannel(const std::string &receiver); - void sendExperienceTracker(int64_t rawExp, int64_t finalExp); - void sendToChannel(const Creature *creature, SpeakClasses type, const std::string &text, uint16_t channelId); - void sendPrivateMessage(const Player *speaker, SpeakClasses type, const std::string &text); - void sendIcons(uint32_t icons); - void sendFYIBox(const std::string &message); - - void openImbuementWindow(Item *item); - void sendImbuementResult(const std::string message); - void closeImbuementWindow(); - - void sendItemsPrice(); - - //Forge System - void sendForgingData(); - void sendOpenForge(); - void sendForgeError(const ReturnValue returnValue); - void closeForgeWindow(); - void parseForgeEnter(NetworkMessage &msg); - void parseForgeBrowseHistory(NetworkMessage& msg); - void sendForgeFusionItem( - uint16_t itemId, - uint8_t tier, - bool success, - uint8_t bonus, - uint8_t coreCount - ); - void sendTransferItemTier(uint16_t firstItem, uint8_t tier, uint16_t secondItem); - void sendForgeHistory(uint8_t page); - void sendForgeSkillStats(NetworkMessage &msg) const; - - void sendDistanceShoot(const Position &from, const Position &to, uint8_t type); - void sendMagicEffect(const Position &pos, uint8_t type); - void sendRestingStatus(uint8_t protection); - void sendCreatureHealth(const Creature *creature); - void sendPartyCreatureUpdate(const Creature* target); - void sendPartyCreatureShield(const Creature* target); - void sendPartyCreatureSkull(const Creature* target); - void sendPartyCreatureHealth(const Creature* target, uint8_t healthPercent); - void sendPartyPlayerMana(const Player* target, uint8_t manaPercent); - void sendPartyCreatureShowStatus(const Creature* target, bool showStatus); - void sendPartyPlayerVocation(const Player* target); - void sendPlayerVocation(const Player* target); - void sendSkills(); - void sendPing(); - void sendPingBack(); - void sendCreatureTurn(const Creature *creature, uint32_t stackpos); - void sendCreatureSay(const Creature *creature, SpeakClasses type, const std::string &text, const Position *pos = nullptr); - - // Unjust Panel - void sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8_t &dayLeft, const uint8_t &weekProgress, const uint8_t &weekLeft, const uint8_t &monthProgress, const uint8_t &monthLeft, const uint8_t &skullDuration); - - void sendCancelWalk(); - void sendChangeSpeed(const Creature *creature, uint16_t speed); - void sendCancelTarget(); - void sendCreatureOutfit(const Creature *creature, const Outfit_t &outfit); - void sendStats(); - void sendBasicData(); - void sendTextMessage(const TextMessage &message); - void sendReLoginWindow(uint8_t unfairFightReduction); - - void sendTutorial(uint8_t tutorialId); - void sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc); - - void sendTournamentLeaderboard(); - - void sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t characterInfoType, uint8_t errorCode); - void sendCyclopediaCharacterBaseInformation(); - void sendCyclopediaCharacterGeneralStats(); - void sendCyclopediaCharacterCombatStats(); - void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries); - void sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries); - void sendCyclopediaCharacterAchievements(); - void sendCyclopediaCharacterItemSummary(); - void sendCyclopediaCharacterOutfitsMounts(); - void sendCyclopediaCharacterStoreSummary(); - void sendCyclopediaCharacterInspection(); - void sendCyclopediaCharacterBadges(); - void sendCyclopediaCharacterTitles(); - - void sendCreatureWalkthrough(const Creature *creature, bool walkthrough); - void sendCreatureShield(const Creature *creature); - void sendCreatureEmblem(const Creature *creature); - void sendCreatureSkull(const Creature *creature); - void sendCreatureType(const Creature *creature, uint8_t creatureType); - - void sendShop(Npc *npc); - void sendCloseShop(); - void sendClientCheck(); - void sendGameNews(); - void sendResourcesBalance(uint64_t money = 0, uint64_t bank = 0, uint64_t preyCards = 0, uint64_t taskHunting = 0, uint64_t forgeDust = 0, uint64_t forgeSliver = 0, uint64_t forgeCores = 0); - void sendResourceBalance(Resource_t resourceType, uint64_t value); - void sendSaleItemList(const std::vector &shopVector, const std::map &inventoryMap); - void sendMarketEnter(uint32_t depotId); - void updateCoinBalance(); - void sendMarketLeave(); - void sendMarketBrowseItem(uint16_t itemId, const MarketOfferList &buyOffers, const MarketOfferList &sellOffers, uint8_t tier); - void sendMarketAcceptOffer(const MarketOfferEx &offer); - void sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, const MarketOfferList &sellOffers); - void sendMarketCancelOffer(const MarketOfferEx &offer); - void sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyOffers, const HistoryMarketOfferList &sellOffers); - void sendMarketDetail(uint16_t itemId, uint8_t tier); - void sendTradeItemRequest(const std::string &traderName, const Item *item, bool ack); - void sendCloseTrade(); - void updatePartyTrackerAnalyzer(const Party* party); - - void sendTextWindow(uint32_t windowTextId, Item *item, uint16_t maxlen, bool canWrite); - void sendHouseWindow(uint32_t windowTextId, const std::string &text); - void sendOutfitWindow(); - void sendPodiumWindow(const Item* podium, const Position& position, uint16_t itemId, uint8_t stackpos); - - void sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus); - void sendVIP(uint32_t guid, const std::string &name, const std::string &description, uint32_t icon, bool notify, VipStatus_t status); - - void sendPendingStateEntered(); - void sendEnterWorld(); - - void sendFightModes(); - - void sendCreatureLight(const Creature *creature); - void sendCreatureIcon(const Creature* creature); - void sendUpdateCreature(const Creature* creature); - void sendWorldLight(const LightInfo &lightInfo); - void sendTibiaTime(int32_t time); - - void sendCreatureSquare(const Creature *creature, SquareColor_t color); - - void sendSpellCooldown(uint8_t spellId, uint32_t time); - void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time); - void sendUseItemCooldown(uint32_t time); - - void sendCoinBalance(); - - void sendPreyTimeLeft(const PreySlot* slot); - void sendPreyData(const PreySlot* slot); - void sendPreyPrices(); - - //tiles - void sendMapDescription(const Position &pos); - - void sendAddTileItem(const Position &pos, uint32_t stackpos, const Item *item); - void sendUpdateTileItem(const Position &pos, uint32_t stackpos, const Item *item); - void sendRemoveTileThing(const Position &pos, uint32_t stackpos); - void sendUpdateTile(const Tile *tile, const Position &pos); - - void sendAddCreature(const Creature *creature, const Position &pos, int32_t stackpos, bool isLogin); - void sendMoveCreature(const Creature *creature, const Position &newPos, int32_t newStackPos, - const Position &oldPos, int32_t oldStackPos, bool teleport); - - //containers - void sendAddContainerItem(uint8_t cid, uint16_t slot, const Item *item); - void sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Item *item); - void sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Item *lastItem); - - void sendContainer(uint8_t cid, const Container *container, bool hasParent, uint16_t firstIndex); - void sendCloseContainer(uint8_t cid); - - //quickloot - void sendLootContainers(); - void sendLootStats(Item *item, uint8_t count); - - //inventory - void sendInventoryItem(Slots_t slot, const Item *item); - void sendInventoryIds(); - - //messages - void sendModalWindow(const ModalWindow &modalWindow); - - //analyzers - void sendKillTrackerUpdate(Container *corpse, const std::string &name, const Outfit_t creatureOutfit); - void sendUpdateSupplyTracker(const Item *item); - void sendUpdateImpactTracker(CombatType_t type, int32_t amount); - void sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, std::string target); - - // Hotkey equip/dequip item - void parseHotkeyEquip(NetworkMessage &msg); - - //Help functions +class ProtocolGame final : public Protocol { + public: + // Static protocol information. + enum { SERVER_SENDS_FIRST = true }; + // Not required as we send first. + enum { PROTOCOL_IDENTIFIER = 0 }; + enum { USE_CHECKSUM = true }; + + static const char* protocol_name() { + return "gameworld protocol"; + } + + explicit ProtocolGame(Connection_ptr initConnection); + + void login(const std::string &name, uint32_t accnumber, OperatingSystem_t operatingSystem); + void logout(bool displayEffect, bool forced); + + void AddItem(NetworkMessage &msg, const Item* item); + void AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier); + + uint16_t getVersion() const { + return version; + } + + private: + // Helpers so we don't need to bind every time + template + void addGameTask(Callable function, Args &&... args); + template + void addGameTaskTimed(uint32_t delay, Callable function, Args &&... args); + + ProtocolGame_ptr getThis() { + return std::static_pointer_cast(shared_from_this()); + } + void connect(uint32_t playerId, OperatingSystem_t operatingSystem); + void disconnectClient(const std::string &message) const; + void writeToOutputBuffer(const NetworkMessage &msg); + + void release() override; + + void checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &removedKnown); + + bool canSee(int32_t x, int32_t y, int32_t z) const; + bool canSee(const Creature*) const; + bool canSee(const Position &pos) const; + + // we have all the parse methods + void parsePacket(NetworkMessage &msg) override; + void parsePacketFromDispatcher(NetworkMessage msg, uint8_t recvbyte); + void onRecvFirstMessage(NetworkMessage &msg) override; + void onConnect() override; + + // Parse methods + void parseAutoWalk(NetworkMessage &msg); + void parseSetOutfit(NetworkMessage &msg); + void parseSay(NetworkMessage &msg); + void parseLookAt(NetworkMessage &msg); + void parseLookInBattleList(NetworkMessage &msg); + + void parseQuickLoot(NetworkMessage &msg); + void parseLootContainer(NetworkMessage &msg); + void parseQuickLootBlackWhitelist(NetworkMessage &msg); + + // Depot search + void sendDepotItems(const ItemsTierCountList &itemMap, uint16_t count); + void sendCloseDepotSearch(); + void sendDepotSearchResultDetail(uint16_t itemId, uint8_t tier, uint32_t depotCount, const ItemVector &depotItems, uint32_t inboxCount, const ItemVector &inboxItems, uint32_t stashCount); + void parseOpenDepotSearch(); + void parseCloseDepotSearch(); + void parseDepotSearchItemRequest(NetworkMessage &msg); + void parseOpenParentContainer(NetworkMessage &msg); + void parseRetrieveDepotSearch(NetworkMessage &msg); + + void parseFightModes(NetworkMessage &msg); + void parseAttack(NetworkMessage &msg); + void parseFollow(NetworkMessage &msg); + + void sendSessionEndInformation(SessionEndInformations information); + + void sendItemInspection(uint16_t itemId, uint8_t itemCount, const Item* item, bool cyclopedia); + void parseInspectionObject(NetworkMessage &msg); + + void parseCyclopediaCharacterInfo(NetworkMessage &msg); + + void parseHighscores(NetworkMessage &msg); + void parseTaskHuntingAction(NetworkMessage &msg); + void sendHighscoresNoData(); + void sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages); + + void parseTournamentLeaderboard(NetworkMessage &msg); + + void parseGreet(NetworkMessage &msg); + void parseBugReport(NetworkMessage &msg); + void parseDebugAssert(NetworkMessage &msg); + void parsePreyAction(NetworkMessage &msg); + void parseSendResourceBalance(); + void parseRuleViolationReport(NetworkMessage &msg); + + void parseBestiarysendRaces(); + void parseBestiarysendCreatures(NetworkMessage &msg); + void BestiarysendCharms(); + void sendBestiaryEntryChanged(uint16_t raceid); + void refreshBestiaryTracker(std::list trackerList); + void sendTeamFinderList(); + void sendLeaderTeamFinder(bool reset); + void createLeaderTeamFinder(NetworkMessage &msg); + void parsePartyAnalyzerAction(NetworkMessage &msg) const; + void parseLeaderFinderWindow(NetworkMessage &msg); + void parseMemberFinderWindow(NetworkMessage &msg); + void parseSendBuyCharmRune(NetworkMessage &msg); + void parseBestiarysendMonsterData(NetworkMessage &msg); + void addBestiaryTrackerList(NetworkMessage &msg); + void parseObjectInfo(NetworkMessage &msg); + + void parseTeleport(NetworkMessage &msg); + void parseThrow(NetworkMessage &msg); + void parseUseItemEx(NetworkMessage &msg); + void parseUseWithCreature(NetworkMessage &msg); + void parseUseItem(NetworkMessage &msg); + void parseCloseContainer(NetworkMessage &msg); + void parseUpArrowContainer(NetworkMessage &msg); + void parseUpdateContainer(NetworkMessage &msg); + void parseTextWindow(NetworkMessage &msg); + void parseHouseWindow(NetworkMessage &msg); + + void parseLookInShop(NetworkMessage &msg); + void parsePlayerBuyOnShop(NetworkMessage &msg); + void parsePlayerSellOnShop(NetworkMessage &msg); + + void parseQuestLine(NetworkMessage &msg); + + void parseInviteToParty(NetworkMessage &msg); + void parseJoinParty(NetworkMessage &msg); + void parseRevokePartyInvite(NetworkMessage &msg); + void parsePassPartyLeadership(NetworkMessage &msg); + void parseEnableSharedPartyExperience(NetworkMessage &msg); + + void parseToggleMount(NetworkMessage &msg); + + // Imbuements + void parseApplyImbuement(NetworkMessage &msg); + void parseClearImbuement(NetworkMessage &msg); + void parseCloseImbuementWindow(NetworkMessage &msg); + + void parseModalWindowAnswer(NetworkMessage &msg); + + void parseBrowseField(NetworkMessage &msg); + void parseSeekInContainer(NetworkMessage &msg); + + // trade methods + void parseRequestTrade(NetworkMessage &msg); + void parseLookInTrade(NetworkMessage &msg); + + // market methods + void parseMarketLeave(); + void parseMarketBrowse(NetworkMessage &msg); + void parseMarketCreateOffer(NetworkMessage &msg); + void parseMarketCancelOffer(NetworkMessage &msg); + void parseMarketAcceptOffer(NetworkMessage &msg); + + // VIP methods + void parseAddVip(NetworkMessage &msg); + void parseRemoveVip(NetworkMessage &msg); + void parseEditVip(NetworkMessage &msg); + + void parseRotateItem(NetworkMessage &msg); + void parseConfigureShowOffSocket(NetworkMessage &msg); + void parseWrapableItem(NetworkMessage &msg); + + // Channel tabs + void parseChannelInvite(NetworkMessage &msg); + void parseChannelExclude(NetworkMessage &msg); + void parseOpenChannel(NetworkMessage &msg); + void parseOpenPrivateChannel(NetworkMessage &msg); + void parseCloseChannel(NetworkMessage &msg); + + // Imbuement info + void addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) const; + + // Send functions + void sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel); + void sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent); + void sendClosePrivate(uint16_t channelId); + void sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName); + void sendChannelsDialog(); + void sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers); + void sendOpenPrivateChannel(const std::string &receiver); + void sendExperienceTracker(int64_t rawExp, int64_t finalExp); + void sendToChannel(const Creature* creature, SpeakClasses type, const std::string &text, uint16_t channelId); + void sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string &text); + void sendIcons(uint32_t icons); + void sendFYIBox(const std::string &message); + + void openImbuementWindow(Item* item); + void sendImbuementResult(const std::string message); + void closeImbuementWindow(); + + void sendItemsPrice(); + + // Forge System + void sendForgingData(); + void sendOpenForge(); + void sendForgeError(const ReturnValue returnValue); + void closeForgeWindow(); + void parseForgeEnter(NetworkMessage &msg); + void parseForgeBrowseHistory(NetworkMessage &msg); + void sendForgeFusionItem( + uint16_t itemId, + uint8_t tier, + bool success, + uint8_t bonus, + uint8_t coreCount + ); + void sendTransferItemTier(uint16_t firstItem, uint8_t tier, uint16_t secondItem); + void sendForgeHistory(uint8_t page); + void sendForgeSkillStats(NetworkMessage &msg) const; + + void sendDistanceShoot(const Position &from, const Position &to, uint8_t type); + void sendMagicEffect(const Position &pos, uint8_t type); + void sendRestingStatus(uint8_t protection); + void sendCreatureHealth(const Creature* creature); + void sendPartyCreatureUpdate(const Creature* target); + void sendPartyCreatureShield(const Creature* target); + void sendPartyCreatureSkull(const Creature* target); + void sendPartyCreatureHealth(const Creature* target, uint8_t healthPercent); + void sendPartyPlayerMana(const Player* target, uint8_t manaPercent); + void sendPartyCreatureShowStatus(const Creature* target, bool showStatus); + void sendPartyPlayerVocation(const Player* target); + void sendPlayerVocation(const Player* target); + void sendSkills(); + void sendPing(); + void sendPingBack(); + void sendCreatureTurn(const Creature* creature, uint32_t stackpos); + void sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr); + + // Unjust Panel + void sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8_t &dayLeft, const uint8_t &weekProgress, const uint8_t &weekLeft, const uint8_t &monthProgress, const uint8_t &monthLeft, const uint8_t &skullDuration); + + void sendCancelWalk(); + void sendChangeSpeed(const Creature* creature, uint16_t speed); + void sendCancelTarget(); + void sendCreatureOutfit(const Creature* creature, const Outfit_t &outfit); + void sendStats(); + void sendBasicData(); + void sendTextMessage(const TextMessage &message); + void sendReLoginWindow(uint8_t unfairFightReduction); + + void sendTutorial(uint8_t tutorialId); + void sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc); + + void sendTournamentLeaderboard(); + + void sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t characterInfoType, uint8_t errorCode); + void sendCyclopediaCharacterBaseInformation(); + void sendCyclopediaCharacterGeneralStats(); + void sendCyclopediaCharacterCombatStats(); + void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries); + void sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries); + void sendCyclopediaCharacterAchievements(); + void sendCyclopediaCharacterItemSummary(); + void sendCyclopediaCharacterOutfitsMounts(); + void sendCyclopediaCharacterStoreSummary(); + void sendCyclopediaCharacterInspection(); + void sendCyclopediaCharacterBadges(); + void sendCyclopediaCharacterTitles(); + + void sendCreatureWalkthrough(const Creature* creature, bool walkthrough); + void sendCreatureShield(const Creature* creature); + void sendCreatureEmblem(const Creature* creature); + void sendCreatureSkull(const Creature* creature); + void sendCreatureType(const Creature* creature, uint8_t creatureType); + + void sendShop(Npc* npc); + void sendCloseShop(); + void sendClientCheck(); + void sendGameNews(); + void sendResourcesBalance(uint64_t money = 0, uint64_t bank = 0, uint64_t preyCards = 0, uint64_t taskHunting = 0, uint64_t forgeDust = 0, uint64_t forgeSliver = 0, uint64_t forgeCores = 0); + void sendResourceBalance(Resource_t resourceType, uint64_t value); + void sendSaleItemList(const std::vector &shopVector, const std::map &inventoryMap); + void sendMarketEnter(uint32_t depotId); + void updateCoinBalance(); + void sendMarketLeave(); + void sendMarketBrowseItem(uint16_t itemId, const MarketOfferList &buyOffers, const MarketOfferList &sellOffers, uint8_t tier); + void sendMarketAcceptOffer(const MarketOfferEx &offer); + void sendMarketBrowseOwnOffers(const MarketOfferList &buyOffers, const MarketOfferList &sellOffers); + void sendMarketCancelOffer(const MarketOfferEx &offer); + void sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyOffers, const HistoryMarketOfferList &sellOffers); + void sendMarketDetail(uint16_t itemId, uint8_t tier); + void sendTradeItemRequest(const std::string &traderName, const Item* item, bool ack); + void sendCloseTrade(); + void updatePartyTrackerAnalyzer(const Party* party); + + void sendTextWindow(uint32_t windowTextId, Item* item, uint16_t maxlen, bool canWrite); + void sendHouseWindow(uint32_t windowTextId, const std::string &text); + void sendOutfitWindow(); + void sendPodiumWindow(const Item* podium, const Position &position, uint16_t itemId, uint8_t stackpos); + + void sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus); + void sendVIP(uint32_t guid, const std::string &name, const std::string &description, uint32_t icon, bool notify, VipStatus_t status); + + void sendPendingStateEntered(); + void sendEnterWorld(); + + void sendFightModes(); + + void sendCreatureLight(const Creature* creature); + void sendCreatureIcon(const Creature* creature); + void sendUpdateCreature(const Creature* creature); + void sendWorldLight(const LightInfo &lightInfo); + void sendTibiaTime(int32_t time); + + void sendCreatureSquare(const Creature* creature, SquareColor_t color); + + void sendSpellCooldown(uint8_t spellId, uint32_t time); + void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time); + void sendUseItemCooldown(uint32_t time); + + void sendCoinBalance(); + + void sendPreyTimeLeft(const PreySlot* slot); + void sendPreyData(const PreySlot* slot); + void sendPreyPrices(); + + // tiles + void sendMapDescription(const Position &pos); + + void sendAddTileItem(const Position &pos, uint32_t stackpos, const Item* item); + void sendUpdateTileItem(const Position &pos, uint32_t stackpos, const Item* item); + void sendRemoveTileThing(const Position &pos, uint32_t stackpos); + void sendUpdateTile(const Tile* tile, const Position &pos); + + void sendAddCreature(const Creature* creature, const Position &pos, int32_t stackpos, bool isLogin); + void sendMoveCreature(const Creature* creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport); + + // containers + void sendAddContainerItem(uint8_t cid, uint16_t slot, const Item* item); + void sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Item* item); + void sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Item* lastItem); + + void sendContainer(uint8_t cid, const Container* container, bool hasParent, uint16_t firstIndex); + void sendCloseContainer(uint8_t cid); + + // quickloot + void sendLootContainers(); + void sendLootStats(Item* item, uint8_t count); + + // inventory + void sendInventoryItem(Slots_t slot, const Item* item); + void sendInventoryIds(); + + // messages + void sendModalWindow(const ModalWindow &modalWindow); + + // analyzers + void sendKillTrackerUpdate(Container* corpse, const std::string &name, const Outfit_t creatureOutfit); + void sendUpdateSupplyTracker(const Item* item); + void sendUpdateImpactTracker(CombatType_t type, int32_t amount); + void sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, std::string target); + + // Hotkey equip/dequip item + void parseHotkeyEquip(NetworkMessage &msg); - // translate a tile to clientreadable format - void GetTileDescription(const Tile *tile, NetworkMessage &msg); + // Help functions - // translate a floor to clientreadable format - void GetFloorDescription(NetworkMessage &msg, int32_t x, int32_t y, int32_t z, - int32_t width, int32_t height, int32_t offset, int32_t &skip); + // translate a tile to clientreadable format + void GetTileDescription(const Tile* tile, NetworkMessage &msg); - // translate a map area to clientreadable format - void GetMapDescription(int32_t x, int32_t y, int32_t z, - int32_t width, int32_t height, NetworkMessage &msg); + // translate a floor to clientreadable format + void GetFloorDescription(NetworkMessage &msg, int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, int32_t offset, int32_t &skip); - void AddCreature(NetworkMessage &msg, const Creature *creature, bool known, uint32_t remove); - void AddPlayerStats(NetworkMessage &msg); - void AddOutfit(NetworkMessage &msg, const Outfit_t &outfit, bool addMount = true); - void AddPlayerSkills(NetworkMessage &msg); - void sendBlessStatus(); - void sendPremiumTrigger(); - void sendMessageDialog(const std::string &message); - void AddWorldLight(NetworkMessage &msg, LightInfo lightInfo); - void AddCreatureLight(NetworkMessage &msg, const Creature *creature); + // translate a map area to clientreadable format + void GetMapDescription(int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, NetworkMessage &msg); - //tiles - static void RemoveTileThing(NetworkMessage &msg, const Position &pos, uint32_t stackpos); + void AddCreature(NetworkMessage &msg, const Creature* creature, bool known, uint32_t remove); + void AddPlayerStats(NetworkMessage &msg); + void AddOutfit(NetworkMessage &msg, const Outfit_t &outfit, bool addMount = true); + void AddPlayerSkills(NetworkMessage &msg); + void sendBlessStatus(); + void sendPremiumTrigger(); + void sendMessageDialog(const std::string &message); + void AddWorldLight(NetworkMessage &msg, LightInfo lightInfo); + void AddCreatureLight(NetworkMessage &msg, const Creature* creature); - void sendTaskHuntingData(const TaskHuntingSlot* slot); + // tiles + static void RemoveTileThing(NetworkMessage &msg, const Position &pos, uint32_t stackpos); - void MoveUpCreature(NetworkMessage &msg, const Creature *creature, const Position &newPos, const Position &oldPos); - void MoveDownCreature(NetworkMessage &msg, const Creature *creature, const Position &newPos, const Position &oldPos); + void sendTaskHuntingData(const TaskHuntingSlot* slot); - //shop - void AddHiddenShopItem(NetworkMessage &msg); - void AddShopItem(NetworkMessage &msg, const ShopBlock &shopBlock); + void MoveUpCreature(NetworkMessage &msg, const Creature* creature, const Position &newPos, const Position &oldPos); + void MoveDownCreature(NetworkMessage &msg, const Creature* creature, const Position &newPos, const Position &oldPos); - //otclient - void parseExtendedOpcode(NetworkMessage &msg); + // shop + void AddHiddenShopItem(NetworkMessage &msg); + void AddShopItem(NetworkMessage &msg, const ShopBlock &shopBlock); - //reloadCreature - void reloadCreature(const Creature *creature); + // otclient + void parseExtendedOpcode(NetworkMessage &msg); - void getForgeInfoMap(const Item *item, std::map>& itemsMap) const; + // reloadCreature + void reloadCreature(const Creature* creature); - friend class Player; + void getForgeInfoMap(const Item* item, std::map> &itemsMap) const; - phmap::flat_hash_set knownCreatureSet; - Player *player = nullptr; + friend class Player; - uint32_t eventConnect = 0; - uint32_t challengeTimestamp = 0; - uint16_t version = 0; - int32_t clientVersion = 0; + phmap::flat_hash_set knownCreatureSet; + Player* player = nullptr; - uint8_t challengeRandom = 0; + uint32_t eventConnect = 0; + uint32_t challengeTimestamp = 0; + uint16_t version = 0; + int32_t clientVersion = 0; - bool debugAssertSent = false; - bool acceptPackets = false; + uint8_t challengeRandom = 0; - bool loggedIn = false; - bool shouldAddExivaRestrictions = false; + bool debugAssertSent = false; + bool acceptPackets = false; - void sendInventory(); + bool loggedIn = false; + bool shouldAddExivaRestrictions = false; - void sendOpenStash(); - void parseStashWithdraw(NetworkMessage &msg); - void sendSpecialContainersAvailable(); - void addBless(); - void parsePacketDead(uint8_t recvbyte); + void sendInventory(); + void sendOpenStash(); + void parseStashWithdraw(NetworkMessage &msg); + void sendSpecialContainersAvailable(); + void addBless(); + void parsePacketDead(uint8_t recvbyte); }; -#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLGAME_H_ +#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLGAME_H_ diff --git a/src/server/network/protocol/protocollogin.cpp b/src/server/network/protocol/protocollogin.cpp index 9ca9882e117..8b7a5f6b6da 100644 --- a/src/server/network/protocol/protocollogin.cpp +++ b/src/server/network/protocol/protocollogin.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -17,8 +17,7 @@ #include "creatures/players/management/ban.h" #include "game/game.h" -void ProtocolLogin::disconnectClient(const std::string& message, uint16_t version) -{ +void ProtocolLogin::disconnectClient(const std::string &message, uint16_t version) { auto output = OutputMessagePool::getOutputMessage(); output->addByte(version >= 1076 ? 0x0B : 0x0A); @@ -28,8 +27,7 @@ void ProtocolLogin::disconnectClient(const std::string& message, uint16_t versio disconnect(); } -void ProtocolLogin::getCharacterList(const std::string& email, const std::string& password, uint16_t version) -{ +void ProtocolLogin::getCharacterList(const std::string &email, const std::string &password, uint16_t version) { account::Account account; if (!IOLoginData::authenticateAccountPassword(email, password, &account)) { disconnectClient("Email or password is not correct", version); @@ -40,13 +38,14 @@ void ProtocolLogin::getCharacterList(const std::string& email, const std::string Game::updatePremium(account); auto output = OutputMessagePool::getOutputMessage(); - const std::string& motd = g_configManager().getString(MOTD); + const std::string &motd = g_configManager().getString(MOTD); if (!motd.empty()) { // Add MOTD output->addByte(0x14); std::ostringstream ss; - ss << g_game().getMotdNum() << "\n" << motd; + ss << g_game().getMotdNum() << "\n" + << motd; output->addString(ss.str()); } @@ -59,9 +58,9 @@ void ProtocolLogin::getCharacterList(const std::string& email, const std::string account.GetAccountPlayers(&players); output->addByte(0x64); - output->addByte(1); // number of worlds + output->addByte(1); // number of worlds - output->addByte(0); // world id + output->addByte(0); // world id output->addString(g_configManager().getString(SERVER_NAME)); output->addString(g_configManager().getString(IP)); @@ -69,8 +68,7 @@ void ProtocolLogin::getCharacterList(const std::string& email, const std::string output->addByte(0); - uint8_t size = std::min(std::numeric_limits::max(), - players.size()); + uint8_t size = std::min(std::numeric_limits::max(), players.size()); output->addByte(size); for (uint8_t i = 0; i < size; i++) { output->addByte(0); @@ -83,19 +81,18 @@ void ProtocolLogin::getCharacterList(const std::string& email, const std::string output->addByte(1); output->add(0); } else { - uint32_t days; - account.GetPremiumRemaningDays(&days); - output->addByte(0); - output->add(time(nullptr) + (days * 86400)); - } + uint32_t days; + account.GetPremiumRemaningDays(&days); + output->addByte(0); + output->add(time(nullptr) + (days * 86400)); + } send(output); disconnect(); } -void ProtocolLogin::onRecvFirstMessage(NetworkMessage& msg) -{ +void ProtocolLogin::onRecvFirstMessage(NetworkMessage &msg) { if (g_game().getGameState() == GAME_STATE_SHUTDOWN) { disconnect(); return; @@ -119,7 +116,7 @@ void ProtocolLogin::onRecvFirstMessage(NetworkMessage& msg) return; } - std::array key = {msg.get(), msg.get(), msg.get(), msg.get()}; + std::array key = { msg.get(), msg.get(), msg.get(), msg.get() }; enableXTEAEncryption(); setXTEAKey(key.data()); @@ -147,7 +144,8 @@ void ProtocolLogin::onRecvFirstMessage(NetworkMessage& msg) } std::ostringstream ss; - ss << "Your IP has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason; + ss << "Your IP has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" + << banInfo.reason; disconnectClient(ss.str(), version); return; } diff --git a/src/server/network/protocol/protocollogin.h b/src/server/network/protocol/protocollogin.h index cb0405127fe..9163906d305 100644 --- a/src/server/network/protocol/protocollogin.h +++ b/src/server/network/protocol/protocollogin.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLLOGIN_H_ #define SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLLOGIN_H_ @@ -15,25 +15,25 @@ class NetworkMessage; class OutputMessage; -class ProtocolLogin : public Protocol -{ +class ProtocolLogin : public Protocol { public: // static protocol information - enum {SERVER_SENDS_FIRST = false}; - enum {PROTOCOL_IDENTIFIER = 0x01}; - enum {USE_CHECKSUM = true}; + enum { SERVER_SENDS_FIRST = false }; + enum { PROTOCOL_IDENTIFIER = 0x01 }; + enum { USE_CHECKSUM = true }; static const char* protocol_name() { return "login protocol"; } - explicit ProtocolLogin(Connection_ptr loginConnection) : Protocol(loginConnection) {} + explicit ProtocolLogin(Connection_ptr loginConnection) : + Protocol(loginConnection) { } - void onRecvFirstMessage(NetworkMessage& msg); + void onRecvFirstMessage(NetworkMessage &msg); private: - void disconnectClient(const std::string& message, uint16_t version); + void disconnectClient(const std::string &message, uint16_t version); - void getCharacterList(const std::string& accountName, const std::string& password, uint16_t version); + void getCharacterList(const std::string &accountName, const std::string &password, uint16_t version); }; -#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLLOGIN_H_ +#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLLOGIN_H_ diff --git a/src/server/network/protocol/protocolstatus.cpp b/src/server/network/protocol/protocolstatus.cpp index 9ae280bed9a..1109d4da192 100644 --- a/src/server/network/protocol/protocolstatus.cpp +++ b/src/server/network/protocol/protocolstatus.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -19,8 +19,7 @@ std::map ProtocolStatus::ipConnectMap; const uint64_t ProtocolStatus::start = OTSYS_TIME(); -void ProtocolStatus::onRecvFirstMessage(NetworkMessage& msg) -{ +void ProtocolStatus::onRecvFirstMessage(NetworkMessage &msg) { uint32_t ip = getIP(); if (ip != 0x0100007F) { std::string ipStr = convertIPToString(ip); @@ -36,27 +35,27 @@ void ProtocolStatus::onRecvFirstMessage(NetworkMessage& msg) ipConnectMap[ip] = OTSYS_TIME(); switch (msg.getByte()) { - //XML info protocol + // XML info protocol case 0xFF: { if (msg.getString(4) == "info") { g_dispatcher().addTask(createTask(std::bind( - &ProtocolStatus::sendStatusString, - std::static_pointer_cast< - ProtocolStatus>(shared_from_this())))); + &ProtocolStatus::sendStatusString, + std::static_pointer_cast< + ProtocolStatus>(shared_from_this()) + ))); return; } break; } - //Another ServerInfo protocol + // Another ServerInfo protocol case 0x01: { uint16_t requestedInfo = msg.get(); // only a Byte is necessary, though we could add new info here std::string characterName; if (requestedInfo & REQUEST_PLAYER_STATUS_INFO) { characterName = msg.getString(); } - g_dispatcher().addTask(createTask(std::bind(&ProtocolStatus::sendInfo, std::static_pointer_cast(shared_from_this()), - requestedInfo, characterName))); + g_dispatcher().addTask(createTask(std::bind(&ProtocolStatus::sendInfo, std::static_pointer_cast(shared_from_this()), requestedInfo, characterName))); return; } @@ -66,8 +65,7 @@ void ProtocolStatus::onRecvFirstMessage(NetworkMessage& msg) disconnect(); } -void ProtocolStatus::sendStatusString() -{ +void ProtocolStatus::sendStatusString() { auto output = OutputMessagePool::getOutputMessage(); setRawMessages(true); @@ -99,7 +97,7 @@ void ProtocolStatus::sendStatusString() pugi::xml_node players = tsqp.append_child("players"); uint32_t real = 0; std::map listIP; - for (const auto& [key, player] : g_game().getPlayers()) { + for (const auto &[key, player] : g_game().getPlayers()) { if (player->getIP() != 0) { auto ip = listIP.find(player->getIP()); if (ip != listIP.end()) { @@ -151,8 +149,7 @@ void ProtocolStatus::sendStatusString() disconnect(); } -void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string& characterName) -{ +void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string &characterName) { auto output = OutputMessagePool::getOutputMessage(); if (requestedInfo & REQUEST_BASIC_SERVER_INFO) { @@ -196,9 +193,9 @@ void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string& charact if (requestedInfo & REQUEST_EXT_PLAYERS_INFO) { output->addByte(0x21); // players info - online players list - const auto& players = g_game().getPlayers(); + const auto &players = g_game().getPlayers(); output->add(players.size()); - for (const auto& it : players) { + for (const auto &it : players) { output->addString(it.second->getName()); output->add(it.second->getLevel()); } diff --git a/src/server/network/protocol/protocolstatus.h b/src/server/network/protocol/protocolstatus.h index 54bcd04300e..dbbe0f5ad81 100644 --- a/src/server/network/protocol/protocolstatus.h +++ b/src/server/network/protocol/protocolstatus.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLSTATUS_H_ #define SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLSTATUS_H_ @@ -13,23 +13,23 @@ #include "server/network/message/networkmessage.h" #include "server/network/protocol/protocol.h" -class ProtocolStatus final : public Protocol -{ +class ProtocolStatus final : public Protocol { public: // static protocol information - enum {SERVER_SENDS_FIRST = false}; - enum {PROTOCOL_IDENTIFIER = 0xFF}; - enum {USE_CHECKSUM = false}; + enum { SERVER_SENDS_FIRST = false }; + enum { PROTOCOL_IDENTIFIER = 0xFF }; + enum { USE_CHECKSUM = false }; static const char* protocol_name() { return "status protocol"; } - explicit ProtocolStatus(Connection_ptr conn) : Protocol(conn) {} + explicit ProtocolStatus(Connection_ptr conn) : + Protocol(conn) { } - void onRecvFirstMessage(NetworkMessage& msg) override; + void onRecvFirstMessage(NetworkMessage &msg) override; void sendStatusString(); - void sendInfo(uint16_t requestedInfo, const std::string& characterName); + void sendInfo(uint16_t requestedInfo, const std::string &characterName); static const uint64_t start; @@ -37,4 +37,4 @@ class ProtocolStatus final : public Protocol static std::map ipConnectMap; }; -#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLSTATUS_H_ +#endif // SRC_SERVER_NETWORK_PROTOCOL_PROTOCOLSTATUS_H_ diff --git a/src/server/network/webhook/webhook.cpp b/src/server/network/webhook/webhook.cpp index eb01e809f8a..63372816da3 100644 --- a/src/server/network/webhook/webhook.cpp +++ b/src/server/network/webhook/webhook.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -16,7 +16,7 @@ // Go back while you still can. static bool init = false; -static curl_slist *headers = NULL; +static curl_slist* headers = NULL; void webhook_init() { if (curl_global_init(CURL_GLOBAL_ALL) != 0) { @@ -34,7 +34,7 @@ void webhook_init() { init = true; } -static int webhook_send_message_(const char *url, const char *payload, std::string *response_body); +static int webhook_send_message_(const char* url, const char* payload, std::string* response_body); static std::string get_payload(std::string title, std::string message, int color); void webhook_send_message(std::string title, std::string message, int color, std::string url) { @@ -49,7 +49,7 @@ void webhook_send_message(std::string title, std::string message, int color, std if (title.empty() || message.empty()) { SPDLOG_ERROR("Failed to send webhook message; " - "title or message to send was empty"); + "title or message to send was empty"); return; } @@ -59,9 +59,9 @@ void webhook_send_message(std::string title, std::string message, int color, std if (response_code != 204 && response_code != -1) { SPDLOG_ERROR("Failed to send webhook message; " - "HTTP request failed with code: {}" - "response body: {} request body: {}", - response_code, response_body, payload); + "HTTP request failed with code: {}" + "response body: {} request body: {}", + response_code, response_body, payload); } } @@ -71,9 +71,9 @@ static std::string get_payload(std::string title, std::string message, int color struct tm tm; #ifdef _MSC_VER - gmtime_s(&tm, &now); + gmtime_s(&tm, &now); #else - gmtime_r(&now, &tm); + gmtime_r(&now, &tm); #endif char time_buf[sizeof "00:00"]; @@ -81,9 +81,9 @@ static std::string get_payload(std::string title, std::string message, int color std::stringstream footer_text; footer_text - << g_configManager().getString(IP) << ":" - << g_configManager().getNumber(GAME_PORT) << " | " - << time_buf << " UTC"; + << g_configManager().getString(IP) << ":" + << g_configManager().getNumber(GAME_PORT) << " | " + << time_buf << " UTC"; Json::Value footer(Json::objectValue); footer["text"] = Json::Value(footer_text.str()); @@ -112,8 +112,8 @@ static std::string get_payload(std::string title, std::string message, int color return out.str(); } -static int webhook_send_message_(const char *url, const char *payload, std::string *response_body) { - CURL *curl = curl_easy_init(); +static int webhook_send_message_(const char* url, const char* payload, std::string* response_body) { + CURL* curl = curl_easy_init(); if (!curl) { SPDLOG_ERROR("Failed to send webhook message; curl_easy_init failed"); return -1; @@ -123,7 +123,7 @@ static int webhook_send_message_(const char *url, const char *payload, std::stri curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_3); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast(&response_body)); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast(&response_body)); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_USERAGENT, "canary (https://github.com/Hydractify/canary)"); @@ -133,8 +133,7 @@ static int webhook_send_message_(const char *url, const char *payload, std::stri if (res == CURLE_OK) { curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); } else { - SPDLOG_ERROR("Failed to send webhook message with the error: {}", - curl_easy_strerror(res)); + SPDLOG_ERROR("Failed to send webhook message with the error: {}", curl_easy_strerror(res)); } curl_easy_cleanup(curl); diff --git a/src/server/network/webhook/webhook.h b/src/server/network/webhook/webhook.h index 9116b5b8ed9..79dd039e4b8 100644 --- a/src/server/network/webhook/webhook.h +++ b/src/server/network/webhook/webhook.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_NETWORK_WEBHOOK_WEBHOOK_H_ #define SRC_SERVER_NETWORK_WEBHOOK_WEBHOOK_H_ @@ -14,4 +14,4 @@ void webhook_init(); void webhook_send_message(std::string title, std::string message, int color, std::string url); -#endif // SRC_SERVER_NETWORK_WEBHOOK_WEBHOOK_H_ +#endif // SRC_SERVER_NETWORK_WEBHOOK_WEBHOOK_H_ diff --git a/src/server/server.cpp b/src/server/server.cpp index f69b321ab5c..6622a438683 100644 --- a/src/server/server.cpp +++ b/src/server/server.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -17,8 +17,7 @@ Ban g_bans; -ServiceManager::~ServiceManager() -{ +ServiceManager::~ServiceManager() { try { stop(); } catch (std::exception &exception) { @@ -26,30 +25,27 @@ ServiceManager::~ServiceManager() } } -void ServiceManager::die() -{ +void ServiceManager::die() { io_service.stop(); } -void ServiceManager::run() -{ +void ServiceManager::run() { assert(!running); running = true; io_service.run(); } -void ServiceManager::stop() -{ +void ServiceManager::stop() { if (!running) { return; } running = false; - for (auto& servicePortIt : acceptors) { + for (auto &servicePortIt : acceptors) { try { io_service.post(std::bind_front(&ServicePort::onStopServer, servicePortIt.second)); - } catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_WARN("[ServiceManager::stop] - Network error: {}", e.what()); } } @@ -60,18 +56,15 @@ void ServiceManager::stop() death_timer.async_wait(std::bind(&ServiceManager::die, this)); } -ServicePort::~ServicePort() -{ +ServicePort::~ServicePort() { close(); } -bool ServicePort::is_single_socket() const -{ +bool ServicePort::is_single_socket() const { return !services.empty() && services.front()->is_single_socket(); } -std::string ServicePort::get_protocol_names() const -{ +std::string ServicePort::get_protocol_names() const { if (services.empty()) { return std::string(); } @@ -85,8 +78,7 @@ std::string ServicePort::get_protocol_names() const return str; } -void ServicePort::accept() -{ +void ServicePort::accept() { if (!acceptor) { return; } @@ -95,8 +87,7 @@ void ServicePort::accept() acceptor->async_accept(connection->getSocket(), std::bind(&ServicePort::onAccept, shared_from_this(), connection, std::placeholders::_1)); } -void ServicePort::onAccept(Connection_ptr connection, const std::error_code& error) -{ +void ServicePort::onAccept(Connection_ptr connection, const std::error_code &error) { if (!error) { if (services.empty()) { return; @@ -119,18 +110,14 @@ void ServicePort::onAccept(Connection_ptr connection, const std::error_code& err if (!pendingStart) { close(); pendingStart = true; - g_scheduler().addEvent(createSchedulerTask(15000, - std::bind_front(&ServicePort::openAcceptor, - std::weak_ptr(shared_from_this()), - serverPort))); + g_scheduler().addEvent(createSchedulerTask(15000, std::bind_front(&ServicePort::openAcceptor, std::weak_ptr(shared_from_this()), serverPort))); } } } -Protocol_ptr ServicePort::make_protocol(bool checksummed, NetworkMessage& msg, const Connection_ptr& connection) const -{ +Protocol_ptr ServicePort::make_protocol(bool checksummed, NetworkMessage &msg, const Connection_ptr &connection) const { uint8_t protocolID = msg.getByte(); - for (auto& service : services) { + for (auto &service : services) { if (protocolID != service->get_protocol_identifier()) { continue; } @@ -142,20 +129,17 @@ Protocol_ptr ServicePort::make_protocol(bool checksummed, NetworkMessage& msg, c return nullptr; } -void ServicePort::onStopServer() -{ +void ServicePort::onStopServer() { close(); } -void ServicePort::openAcceptor(std::weak_ptr weak_service, uint16_t port) -{ +void ServicePort::openAcceptor(std::weak_ptr weak_service, uint16_t port) { if (auto service = weak_service.lock()) { service->open(port); } } -void ServicePort::open(uint16_t port) -{ +void ServicePort::open(uint16_t port) { close(); serverPort = port; @@ -163,42 +147,31 @@ void ServicePort::open(uint16_t port) try { if (g_configManager().getBoolean(BIND_ONLY_GLOBAL_ADDRESS)) { - acceptor.reset(new asio::ip::tcp::acceptor(io_service, - asio::ip::tcp::endpoint( - asio::ip::address( - asio::ip::address_v4::from_string( - g_configManager().getString(IP))), serverPort))); + acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4::from_string(g_configManager().getString(IP))), serverPort))); } else { - acceptor.reset(new asio::ip::tcp::acceptor(io_service, - asio::ip::tcp::endpoint( - asio::ip::address( - asio::ip::address_v4(INADDR_ANY)), serverPort))); + acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4(INADDR_ANY)), serverPort))); } acceptor->set_option(asio::ip::tcp::no_delay(true)); accept(); - } - catch (const std::system_error& e) { + } catch (const std::system_error &e) { SPDLOG_WARN("[ServicePort::open] - Error code: {}", e.what()); pendingStart = true; - g_scheduler().addEvent(createSchedulerTask(15000, - std::bind_front(&ServicePort::openAcceptor, std::weak_ptr(shared_from_this()), port))); + g_scheduler().addEvent(createSchedulerTask(15000, std::bind_front(&ServicePort::openAcceptor, std::weak_ptr(shared_from_this()), port))); } } -void ServicePort::close() -{ +void ServicePort::close() { if (acceptor && acceptor->is_open()) { std::error_code error; acceptor->close(error); } } -bool ServicePort::add_service(const Service_ptr& new_svc) -{ - if (std::ranges::any_of(services, [](const Service_ptr& svc) {return svc->is_single_socket();})) { +bool ServicePort::add_service(const Service_ptr &new_svc) { + if (std::ranges::any_of(services, [](const Service_ptr &svc) { return svc->is_single_socket(); })) { return false; } diff --git a/src/server/server.h b/src/server/server.h index 934f9c34a5a..b20a87b48ee 100644 --- a/src/server/server.h +++ b/src/server/server.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_SERVER_H_ #define SRC_SERVER_SERVER_H_ @@ -15,20 +15,18 @@ class Protocol; -class ServiceBase -{ +class ServiceBase { public: virtual bool is_single_socket() const = 0; virtual bool is_checksummed() const = 0; virtual uint8_t get_protocol_identifier() const = 0; virtual const char* get_protocol_name() const = 0; - virtual Protocol_ptr make_protocol(const Connection_ptr& c) const = 0; + virtual Protocol_ptr make_protocol(const Connection_ptr &c) const = 0; }; template -class Service final : public ServiceBase -{ +class Service final : public ServiceBase { public: bool is_single_socket() const override { return ProtocolType::SERVER_SENDS_FIRST; @@ -43,20 +41,20 @@ class Service final : public ServiceBase return ProtocolType::protocol_name(); } - Protocol_ptr make_protocol(const Connection_ptr& c) const override { + Protocol_ptr make_protocol(const Connection_ptr &c) const override { return std::make_shared(c); } }; -class ServicePort : public std::enable_shared_from_this -{ +class ServicePort : public std::enable_shared_from_this { public: - explicit ServicePort(asio::io_service& init_io_service) : io_service(init_io_service) {} + explicit ServicePort(asio::io_service &init_io_service) : + io_service(init_io_service) { } ~ServicePort(); // non-copyable - ServicePort(const ServicePort&) = delete; - ServicePort& operator=(const ServicePort&) = delete; + ServicePort(const ServicePort &) = delete; + ServicePort &operator=(const ServicePort &) = delete; static void openAcceptor(std::weak_ptr weak_service, uint16_t port); void open(uint16_t port); @@ -64,16 +62,16 @@ class ServicePort : public std::enable_shared_from_this bool is_single_socket() const; std::string get_protocol_names() const; - bool add_service(const Service_ptr& new_svc); - Protocol_ptr make_protocol(bool checksummed, NetworkMessage& msg, const Connection_ptr& connection) const; + bool add_service(const Service_ptr &new_svc); + Protocol_ptr make_protocol(bool checksummed, NetworkMessage &msg, const Connection_ptr &connection) const; void onStopServer(); - void onAccept(Connection_ptr connection, const std::error_code& error); + void onAccept(Connection_ptr connection, const std::error_code &error); private: void accept(); - asio::io_service& io_service; + asio::io_service &io_service; std::unique_ptr acceptor; std::vector services; @@ -81,15 +79,14 @@ class ServicePort : public std::enable_shared_from_this bool pendingStart = false; }; -class ServiceManager -{ +class ServiceManager { public: ServiceManager() = default; ~ServiceManager(); // non-copyable - ServiceManager(const ServiceManager&) = delete; - ServiceManager& operator=(const ServiceManager&) = delete; + ServiceManager(const ServiceManager &) = delete; + ServiceManager &operator=(const ServiceManager &) = delete; void run(); void stop(); @@ -107,18 +104,17 @@ class ServiceManager phmap::flat_hash_map acceptors; asio::io_service io_service; - Signals signals{io_service}; - asio::high_resolution_timer death_timer{ io_service }; + Signals signals { io_service }; + asio::high_resolution_timer death_timer { io_service }; bool running = false; }; template -bool ServiceManager::add(uint16_t port) -{ +bool ServiceManager::add(uint16_t port) { if (port == 0) { SPDLOG_ERROR("[ServiceManager::add] - " - "No port provided for service {}, service disabled", - ProtocolType::protocol_name()); + "No port provided for service {}, service disabled", + ProtocolType::protocol_name()); return false; } @@ -135,10 +131,8 @@ bool ServiceManager::add(uint16_t port) if (service_port->is_single_socket() || ProtocolType::SERVER_SENDS_FIRST) { SPDLOG_ERROR("[ServiceManager::add] - " - "{} and {} cannot use the same port {}", - ProtocolType::protocol_name(), - service_port->get_protocol_names(), - port); + "{} and {} cannot use the same port {}", + ProtocolType::protocol_name(), service_port->get_protocol_names(), port); return false; } } @@ -146,4 +140,4 @@ bool ServiceManager::add(uint16_t port) return service_port->add_service(std::make_shared>()); } -#endif // SRC_SERVER_SERVER_H_ +#endif // SRC_SERVER_SERVER_H_ diff --git a/src/server/server_definitions.hpp b/src/server/server_definitions.hpp index 144334d2ee0..72c16352415 100644 --- a/src/server/server_definitions.hpp +++ b/src/server/server_definitions.hpp @@ -5,19 +5,19 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_SERVER_DEFINITIONS_HPP_ #define SRC_SERVER_SERVER_DEFINITIONS_HPP_ // Enums // Connection and networkmessage. -enum {FORCE_CLOSE = true}; -enum {HEADER_LENGTH = 2}; -enum {CHECKSUM_LENGTH = 4}; -enum {XTEA_MULTIPLE = 8}; -enum {MAX_BODY_LENGTH = NETWORKMESSAGE_MAXSIZE - HEADER_LENGTH - CHECKSUM_LENGTH - XTEA_MULTIPLE}; -enum {MAX_PROTOCOL_BODY_LENGTH = MAX_BODY_LENGTH - 10}; +enum { FORCE_CLOSE = true }; +enum { HEADER_LENGTH = 2 }; +enum { CHECKSUM_LENGTH = 4 }; +enum { XTEA_MULTIPLE = 8 }; +enum { MAX_BODY_LENGTH = NETWORKMESSAGE_MAXSIZE - HEADER_LENGTH - CHECKSUM_LENGTH - XTEA_MULTIPLE }; +enum { MAX_PROTOCOL_BODY_LENGTH = MAX_BODY_LENGTH - 10 }; enum ConnectionState_t : uint8_t { CONNECTION_STATE_OPEN, @@ -54,7 +54,7 @@ enum SessionEndInformations : uint8_t { SESSION_END_UNK3, }; -enum Resource_t : uint8_t{ +enum Resource_t : uint8_t { RESOURCE_BANK = 0x00, RESOURCE_INVENTORY = 0x01, RESOURCE_PREY_CARDS = 0x0A, @@ -78,7 +78,7 @@ enum CyclopediaCharacterInfo_OutfitType_t : uint8_t { }; enum MagicEffectsType_t : uint8_t { - //ends magic effect loop + // ends magic effect loop MAGIC_EFFECTS_END_LOOP = 0, // needs uint8_t delta after type to adjust position MAGIC_EFFECTS_DELTA = 1, @@ -107,31 +107,29 @@ enum Supply_Stash_Actions_t : uint8_t { // Structs struct HighscoreCategory { - HighscoreCategory(const char* name, uint8_t id) : - name(name), - id(id) {} + HighscoreCategory(const char* name, uint8_t id) : + name(name), + id(id) { } - const char* name; - uint8_t id; + const char* name; + uint8_t id; }; struct HighscoreCharacter { - HighscoreCharacter(std::string name, uint64_t points, - uint32_t id, uint32_t rank, - uint16_t level, uint8_t vocation) : - name(std::move(name)), - points(points), - id(id), - rank(rank), - level(level), - vocation(vocation) {} - - std::string name; - uint64_t points; - uint32_t id; - uint32_t rank; - uint16_t level; - uint8_t vocation; + HighscoreCharacter(std::string name, uint64_t points, uint32_t id, uint32_t rank, uint16_t level, uint8_t vocation) : + name(std::move(name)), + points(points), + id(id), + rank(rank), + level(level), + vocation(vocation) { } + + std::string name; + uint64_t points; + uint32_t id; + uint32_t rank; + uint16_t level; + uint8_t vocation; }; -#endif // SRC_SERVER_SERVER_DEFINITIONS_HPP_ +#endif // SRC_SERVER_SERVER_DEFINITIONS_HPP_ diff --git a/src/server/signals.cpp b/src/server/signals.cpp index 4d10c38ec30..b8ac2fb7973 100644 --- a/src/server/signals.cpp +++ b/src/server/signals.cpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" @@ -19,10 +19,8 @@ #include "lua/scripts/lua_environment.hpp" #include "server/signals.h" - -Signals::Signals(asio::io_service& service) : - set(service) -{ +Signals::Signals(asio::io_service &service) : + set(service) { set.add(SIGINT); set.add(SIGTERM); #ifndef _WIN32 @@ -38,12 +36,12 @@ Signals::Signals(asio::io_service& service) : asyncWait(); } -void Signals::asyncWait() -{ - set.async_wait([this] (std::error_code err, int signal) { +void Signals::asyncWait() { + set.async_wait([this](std::error_code err, int signal) { if (err) { SPDLOG_ERROR("[Signals::asyncWait] - " - "Signal handling error: {}", err.message()); + "Signal handling error: {}", + err.message()); return; } dispatchSignalHandler(signal); @@ -54,24 +52,23 @@ void Signals::asyncWait() // On Windows this function does not need to be signal-safe, // as it is called in a new thread. // https://github.com/otland/forgottenserver/pull/2473 -void Signals::dispatchSignalHandler(int signal) -{ - switch(signal) { - case SIGINT: //Shuts the server down +void Signals::dispatchSignalHandler(int signal) { + switch (signal) { + case SIGINT: // Shuts the server down g_dispatcher().addTask(createTask(sigintHandler)); break; - case SIGTERM: //Shuts the server down + case SIGTERM: // Shuts the server down g_dispatcher().addTask(createTask(sigtermHandler)); break; #ifndef _WIN32 - case SIGHUP: //Reload config/data + case SIGHUP: // Reload config/data g_dispatcher().addTask(createTask(sighupHandler)); break; - case SIGUSR1: //Saves game state + case SIGUSR1: // Saves game state g_dispatcher().addTask(createTask(sigusr1Handler)); break; #else - case SIGBREAK: //Shuts the server down + case SIGBREAK: // Shuts the server down g_dispatcher().addTask(createTask(sigbreakHandler)); // hold the thread until other threads end g_scheduler().join(); @@ -84,30 +81,26 @@ void Signals::dispatchSignalHandler(int signal) } } -void Signals::sigbreakHandler() -{ - //Dispatcher thread +void Signals::sigbreakHandler() { + // Dispatcher thread SPDLOG_INFO("SIGBREAK received, shutting game server down..."); g_game().setGameState(GAME_STATE_SHUTDOWN); } -void Signals::sigtermHandler() -{ - //Dispatcher thread +void Signals::sigtermHandler() { + // Dispatcher thread SPDLOG_INFO("SIGTERM received, shutting game server down..."); g_game().setGameState(GAME_STATE_SHUTDOWN); } -void Signals::sigusr1Handler() -{ - //Dispatcher thread +void Signals::sigusr1Handler() { + // Dispatcher thread SPDLOG_INFO("SIGUSR1 received, saving the game state..."); g_game().saveGameState(); } -void Signals::sighupHandler() -{ - //Dispatcher thread +void Signals::sighupHandler() { + // Dispatcher thread SPDLOG_INFO("SIGHUP received, reloading config files..."); g_configManager().reload(); @@ -135,9 +128,8 @@ void Signals::sighupHandler() lua_gc(g_luaEnvironment.getLuaState(), LUA_GCCOLLECT, 0); } -void Signals::sigintHandler() -{ - //Dispatcher thread +void Signals::sigintHandler() { + // Dispatcher thread SPDLOG_INFO("SIGINT received, shutting game server down..."); g_game().setGameState(GAME_STATE_SHUTDOWN); } diff --git a/src/server/signals.h b/src/server/signals.h index eab27d42392..212b8014925 100644 --- a/src/server/signals.h +++ b/src/server/signals.h @@ -5,16 +5,16 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_SERVER_SIGNALS_H_ #define SRC_SERVER_SIGNALS_H_ -class Signals -{ - asio::signal_set set; +class Signals { + asio::signal_set set; + public: - explicit Signals(asio::io_service& service); + explicit Signals(asio::io_service &service); private: void asyncWait(); @@ -27,4 +27,4 @@ class Signals static void sigusr1Handler(); }; -#endif // SRC_SERVER_SIGNALS_H_ +#endif // SRC_SERVER_SIGNALS_H_ diff --git a/src/utils/const.hpp b/src/utils/const.hpp index 6781530cc9d..01dd5332307 100644 --- a/src/utils/const.hpp +++ b/src/utils/const.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_CONST_H_ #define SRC_UTILS_CONST_H_ @@ -46,7 +46,6 @@ static constexpr int32_t PSTRG_FAMILIARS_RANGE_START = (PSTRG_RESERVED_RANGE_STA static constexpr int32_t PSTRG_FAMILIARS_RANGE_SIZE = 500; #define IS_IN_KEYRANGE(key, range) \ - (key >= PSTRG_##range##_START && \ - ((key - PSTRG_##range##_START) <= PSTRG_##range##_SIZE)) + (key >= PSTRG_##range##_START && ((key - PSTRG_##range##_START) <= PSTRG_##range##_SIZE)) -#endif // SRC_UTILS_CONST_H_ +#endif // SRC_UTILS_CONST_H_ diff --git a/src/utils/definitions.h b/src/utils/definitions.h index 0689807823a..3f3ff73fb03 100644 --- a/src/utils/definitions.h +++ b/src/utils/definitions.h @@ -5,63 +5,63 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_DEFINITIONS_H_ #define SRC_UTILS_DEFINITIONS_H_ #ifndef __FUNCTION__ -#define __FUNCTION__ __func__ + #define __FUNCTION__ __func__ #endif #ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS #endif #ifndef _USE_MATH_DEFINES -#define _USE_MATH_DEFINES + #define _USE_MATH_DEFINES #endif #ifdef _WIN32 -#ifndef NOMINMAX -#define NOMINMAX -#endif + #ifndef NOMINMAX + #define NOMINMAX + #endif -#if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) -#define OS_WINDOWS -#endif + #if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) + #define OS_WINDOWS + #endif -#define WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN -#ifdef _MSC_VER -#ifdef NDEBUG -#define _SECURE_SCL 0 -#define HAS_ITERATOR_DEBUGGING 0 -#endif + #ifdef _MSC_VER + #ifdef NDEBUG + #define _SECURE_SCL 0 + #define HAS_ITERATOR_DEBUGGING 0 + #endif -#pragma warning(disable:4127) // conditional expression is constant -#pragma warning(disable:4244) // 'argument' : conversion from 'type1' to 'type2', possible loss of data -#pragma warning(disable:4250) // 'class1' : inherits 'class2::member' via dominance -#pragma warning(disable:4267) // 'var' : conversion from 'size_t' to 'type', possible loss of data -#pragma warning(disable:4319) // '~': zero extending 'unsigned int' to 'lua_Number' of greater size -#pragma warning(disable:4458) // declaration hides class member -#pragma warning(disable:4101) // local variable not referenced -#pragma warning(disable:4996) // declaration std::fpos<_Mbstatet>::seekpos -#endif + #pragma warning(disable : 4127) // conditional expression is constant + #pragma warning(disable : 4244) // 'argument' : conversion from 'type1' to 'type2', possible loss of data + #pragma warning(disable : 4250) // 'class1' : inherits 'class2::member' via dominance + #pragma warning(disable : 4267) // 'var' : conversion from 'size_t' to 'type', possible loss of data + #pragma warning(disable : 4319) // '~': zero extending 'unsigned int' to 'lua_Number' of greater size + #pragma warning(disable : 4458) // declaration hides class member + #pragma warning(disable : 4101) // local variable not referenced + #pragma warning(disable : 4996) // declaration std::fpos<_Mbstatet>::seekpos + #endif -#define strcasecmp _stricmp -#define strncasecmp _strnicmp + #define strcasecmp _stricmp + #define strncasecmp _strnicmp -#ifndef _WIN32_WINNT -// 0x0602: Windows 7 -#define _WIN32_WINNT 0x0602 -#endif + #ifndef _WIN32_WINNT + // 0x0602: Windows 7 + #define _WIN32_WINNT 0x0602 + #endif #endif #ifndef M_PI -#define M_PI 3.14159265358979323846 + #define M_PI 3.14159265358979323846 #endif typedef int error_t; -#endif // SRC_UTILS_DEFINITIONS_H_ +#endif // SRC_UTILS_DEFINITIONS_H_ diff --git a/src/utils/pugicast.h b/src/utils/pugicast.h index 6294a2c5729..7cf5c0e367b 100644 --- a/src/utils/pugicast.h +++ b/src/utils/pugicast.h @@ -5,13 +5,13 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_PUGICAST_H_ #define SRC_UTILS_PUGICAST_H_ namespace pugi { -template + template // NOTE: std::clamp returns the minimum value if the value is less than the specified minimum value, the maximum value if the value is greater than the specified maximum value, or the value itself if it falls within the range T cast(const pugi::char_t* str) { // Initialize value to return @@ -24,7 +24,7 @@ template // Convert the string to the specified type const auto [pointer, errorCode] = std::from_chars(str, last, value); // If the conversion was successful and all characters were parsed - if (errorCode == std::errc{} && pointer == last) { + if (errorCode == std::errc {} && pointer == last) { // Ensure that the converted value is within the valid range for the type value = std::clamp( value, @@ -48,8 +48,8 @@ template } // Return a default value if no exception is thrown - return T{}; + return T {}; } } -#endif // SRC_UTILS_PUGICAST_H_ +#endif // SRC_UTILS_PUGICAST_H_ diff --git a/src/utils/simd.hpp b/src/utils/simd.hpp index 120d3e52d2a..969606e2b44 100644 --- a/src/utils/simd.hpp +++ b/src/utils/simd.hpp @@ -5,66 +5,65 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_SIMD_HPP_ #define SRC_UTILS_SIMD_HPP_ -//#define __DISABLE_VECTORIZATION__ 1 +// #define __DISABLE_VECTORIZATION__ 1 #if defined(__DISABLE_VECTORIZATION__) -//You might want to disable vectorization on some compilers -//it can just get buggy and the engine will crashes -#undef __NEON__ -#undef __ARM_NEON__ -#undef __ARM_FEATURE_SIMD32 -#undef __SSE__ -#undef __SSE2__ -#undef __SSE3__ -#undef __SSSE3__ -#undef __SSE4_1__ -#undef __SSE4_2__ -#undef __AVX__ -#undef __AVX2__ -#undef __AVX512F__ + // You might want to disable vectorization on some compilers + // it can just get buggy and the engine will crashes + #undef __NEON__ + #undef __ARM_NEON__ + #undef __ARM_FEATURE_SIMD32 + #undef __SSE__ + #undef __SSE2__ + #undef __SSE3__ + #undef __SSSE3__ + #undef __SSE4_1__ + #undef __SSE4_2__ + #undef __AVX__ + #undef __AVX2__ + #undef __AVX512F__ #else -#if defined(__ARM_NEON__) || defined(__ARM_FEATURE_SIMD32) -#define __NEON__ 1 -#include -#endif -#if defined(__SSE__) -#include -#endif -#if defined(__SSE2__) -#include -#endif -#if defined(__SSE3__) -#include -#endif -#if defined(__SSSE3__) -#include -#endif -#if defined(__SSE4_1__) -#include -#endif -#if defined(__SSE4_2__) -#include -#endif -#if defined(__AVX__) || defined(__AVX2__) || defined(__AVX512F__) -#include -#endif + #if defined(__ARM_NEON__) || defined(__ARM_FEATURE_SIMD32) + #define __NEON__ 1 + #include + #endif + #if defined(__SSE__) + #include + #endif + #if defined(__SSE2__) + #include + #endif + #if defined(__SSE3__) + #include + #endif + #if defined(__SSSE3__) + #include + #endif + #if defined(__SSE4_1__) + #include + #endif + #if defined(__SSE4_2__) + #include + #endif + #if defined(__AVX__) || defined(__AVX2__) || defined(__AVX512F__) + #include + #endif #endif #ifdef _MSC_VER -#include -__forceinline unsigned int _mm_ctz(unsigned int value) -{ + #include +__forceinline unsigned int _mm_ctz(unsigned int value) { unsigned long i = 0; _BitScanForward(&i, value); return static_cast(i); } #else -#define _mm_ctz __builtin_ctz + #define _mm_ctz __builtin_ctz #endif -#endif // SRC_UTILS_SIMD_HPP_ +#endif // SRC_UTILS_SIMD_HPP_ diff --git a/src/utils/thread_holder_base.h b/src/utils/thread_holder_base.h index 7e5a046a0b6..81f2f40f4ba 100644 --- a/src/utils/thread_holder_base.h +++ b/src/utils/thread_holder_base.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_THREAD_HOLDER_H_ #define SRC_UTILS_THREAD_HOLDER_H_ @@ -13,10 +13,9 @@ #include "declarations.hpp" template -class ThreadHolder -{ +class ThreadHolder { public: - ThreadHolder() {} + ThreadHolder() { } void start() { setState(THREAD_STATE_RUNNING); thread = std::thread(&Derived::threadMain, static_cast(this)); @@ -31,6 +30,7 @@ class ThreadHolder thread.join(); } } + protected: void setState(ThreadState newState) { threadState.store(newState, std::memory_order_relaxed); @@ -39,9 +39,10 @@ class ThreadHolder ThreadState getState() const { return threadState.load(std::memory_order_relaxed); } + private: - std::atomic threadState{THREAD_STATE_TERMINATED}; + std::atomic threadState { THREAD_STATE_TERMINATED }; std::thread thread; }; -#endif // SRC_UTILS_THREAD_HOLDER_H_ +#endif // SRC_UTILS_THREAD_HOLDER_H_ diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index 010717ddf67..eba0c594349 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -5,16 +5,14 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "core.hpp" #include "utils/tools.h" - -void printXMLError(const std::string& where, const std::string& fileName, const pugi::xml_parse_result& result) -{ +void printXMLError(const std::string &where, const std::string &fileName, const pugi::xml_parse_result &result) { SPDLOG_ERROR("[{}] Failed to load {}: {}", where, fileName, result.description()); FILE* file = fopen(fileName.c_str(), "rb"); @@ -62,13 +60,11 @@ void printXMLError(const std::string& where, const std::string& fileName, const SPDLOG_ERROR("^"); } -static uint32_t circularShift(int bits, uint32_t value) -{ +static uint32_t circularShift(int bits, uint32_t value) { return (value << bits) | (value >> (32 - bits)); } -static void processSHA1MessageBlock(const uint8_t* messageBlock, uint32_t* H) -{ +static void processSHA1MessageBlock(const uint8_t* messageBlock, uint32_t* H) { uint32_t W[80]; for (int i = 0; i < 16; ++i) { const size_t offset = i << 2; @@ -83,22 +79,38 @@ static void processSHA1MessageBlock(const uint8_t* messageBlock, uint32_t* H) for (int i = 0; i < 20; ++i) { const uint32_t tmp = circularShift(5, A) + ((B & C) | ((~B) & D)) + E + W[i] + 0x5A827999; - E = D; D = C; C = circularShift(30, B); B = A; A = tmp; + E = D; + D = C; + C = circularShift(30, B); + B = A; + A = tmp; } for (int i = 20; i < 40; ++i) { const uint32_t tmp = circularShift(5, A) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1; - E = D; D = C; C = circularShift(30, B); B = A; A = tmp; + E = D; + D = C; + C = circularShift(30, B); + B = A; + A = tmp; } for (int i = 40; i < 60; ++i) { const uint32_t tmp = circularShift(5, A) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC; - E = D; D = C; C = circularShift(30, B); B = A; A = tmp; + E = D; + D = C; + C = circularShift(30, B); + B = A; + A = tmp; } for (int i = 60; i < 80; ++i) { const uint32_t tmp = circularShift(5, A) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6; - E = D; D = C; C = circularShift(30, B); B = A; A = tmp; + E = D; + D = C; + C = circularShift(30, B); + B = A; + A = tmp; } H[0] += A; @@ -108,8 +120,7 @@ static void processSHA1MessageBlock(const uint8_t* messageBlock, uint32_t* H) H[4] += E; } -std::string transformToSHA1(const std::string& input) -{ +std::string transformToSHA1(const std::string &input) { uint32_t H[] = { 0x67452301, 0xEFCDAB89, @@ -165,7 +176,7 @@ std::string transformToSHA1(const std::string& input) processSHA1MessageBlock(messageBlock, H); char hexstring[41]; - static const char hexDigits[] = {"0123456789abcdef"}; + static const char hexDigits[] = { "0123456789abcdef" }; for (int hashByte = 20; --hashByte >= 0;) { const uint8_t byte = H[hashByte >> 2] >> (((3 - hashByte) & 3) << 3); index = hashByte << 1; @@ -175,8 +186,7 @@ std::string transformToSHA1(const std::string& input) return std::string(hexstring, 40); } -uint16_t getStashSize(StashItemList itemList) -{ +uint16_t getStashSize(StashItemList itemList) { uint16_t size = 0; for (auto item : itemList) { size += ceil(item.second / 100.0); @@ -184,8 +194,7 @@ uint16_t getStashSize(StashItemList itemList) return size; } -std::string generateToken(const std::string& key, uint32_t ticks) -{ +std::string generateToken(const std::string &key, uint32_t ticks) { // generate message from ticks std::string message(8, 0); for (uint8_t i = 8; --i; ticks >>= 8) { @@ -229,8 +238,7 @@ std::string generateToken(const std::string& key, uint32_t ticks) return message; } -void replaceString(std::string& str, const std::string& sought, const std::string& replacement) -{ +void replaceString(std::string &str, const std::string &sought, const std::string &replacement) { size_t pos = 0; size_t start = 0; size_t soughtLen = sought.length(); @@ -242,35 +250,29 @@ void replaceString(std::string& str, const std::string& sought, const std::strin } } -void trim_right(std::string& source, char t) -{ +void trim_right(std::string &source, char t) { source.erase(source.find_last_not_of(t) + 1); } -void trim_left(std::string& source, char t) -{ +void trim_left(std::string &source, char t) { source.erase(0, source.find_first_not_of(t)); } -void toLowerCaseString(std::string& source) -{ +void toLowerCaseString(std::string &source) { std::transform(source.begin(), source.end(), source.begin(), tolower); } -std::string asLowerCaseString(std::string source) -{ +std::string asLowerCaseString(std::string source) { toLowerCaseString(source); return source; } -std::string asUpperCaseString(std::string source) -{ +std::string asUpperCaseString(std::string source) { std::transform(source.begin(), source.end(), source.begin(), toupper); return source; } -StringVector explodeString(const std::string& inString, const std::string& separator, int32_t limit/* = -1*/) -{ +StringVector explodeString(const std::string &inString, const std::string &separator, int32_t limit /* = -1*/) { StringVector returnVector; std::string::size_type start = 0, end = 0; @@ -283,24 +285,21 @@ StringVector explodeString(const std::string& inString, const std::string& separ return returnVector; } -IntegerVector vectorAtoi(const StringVector& stringVector) -{ +IntegerVector vectorAtoi(const StringVector &stringVector) { IntegerVector returnVector; - for (const auto& string : stringVector) { + for (const auto &string : stringVector) { returnVector.push_back(std::stoi(string)); } return returnVector; } -std::mt19937& getRandomGenerator() -{ +std::mt19937 &getRandomGenerator() { static std::random_device rd; static std::mt19937 generator(rd()); return generator; } -int32_t uniform_random(int32_t minNumber, int32_t maxNumber) -{ +int32_t uniform_random(int32_t minNumber, int32_t maxNumber) { static std::uniform_int_distribution uniformRand; if (minNumber == maxNumber) { return minNumber; @@ -310,8 +309,7 @@ int32_t uniform_random(int32_t minNumber, int32_t maxNumber) return uniformRand(getRandomGenerator(), std::uniform_int_distribution::param_type(minNumber, maxNumber)); } -int32_t normal_random(int32_t minNumber, int32_t maxNumber) -{ +int32_t normal_random(int32_t minNumber, int32_t maxNumber) { static std::normal_distribution normalRand(0.5f, 0.25f); if (minNumber == maxNumber) { return minNumber; @@ -332,32 +330,27 @@ int32_t normal_random(int32_t minNumber, int32_t maxNumber) return minNumber + increment; } -bool boolean_random(double probability/* = 0.5*/) -{ +bool boolean_random(double probability /* = 0.5*/) { static std::bernoulli_distribution booleanRand; return booleanRand(getRandomGenerator(), std::bernoulli_distribution::param_type(probability)); } -void trimString(std::string& str) -{ +void trimString(std::string &str) { str.erase(str.find_last_not_of(' ') + 1); str.erase(0, str.find_first_not_of(' ')); } -std::string convertIPToString(uint32_t ip) -{ - char buffer[17]; - fmt::format_to_n(buffer, sizeof(buffer), "{}.{}.{}.{}", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24)); - return buffer; +std::string convertIPToString(uint32_t ip) { + char buffer[17]; + fmt::format_to_n(buffer, sizeof(buffer), "{}.{}.{}.{}", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24)); + return buffer; } -std::string formatDate(time_t time) -{ +std::string formatDate(time_t time) { return fmt::format("{:%d/%m/%Y %H:%M:%S}", fmt::localtime(time)); } -std::string formatDateShort(time_t time) -{ +std::string formatDateShort(time_t time) { return fmt::format("{:%Y-%m-%d %X}", fmt::localtime(time)); } @@ -365,8 +358,7 @@ std::time_t getTimeNow() { return std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); } -Direction getDirection(const std::string& string) -{ +Direction getDirection(const std::string &string) { Direction direction = DIRECTION_NORTH; if (string == "north" || string == "n" || string == "0") { @@ -390,8 +382,7 @@ Direction getDirection(const std::string& string) return direction; } -Position getNextPosition(Direction direction, Position pos) -{ +Position getNextPosition(Direction direction, Position pos) { switch (direction) { case DIRECTION_NORTH: pos.y--; @@ -436,8 +427,7 @@ Position getNextPosition(Direction direction, Position pos) return pos; } -Direction getDirectionTo(const Position& from, const Position& to) -{ +Direction getDirectionTo(const Position &from, const Position &to) { Direction dir; int32_t x_offset = Position::getOffsetX(from, to); @@ -489,258 +479,258 @@ using ImbuementTypeNames = phmap::flat_hash_map; using SpawnTypeNames = phmap::flat_hash_map; MagicEffectNames magicEffectNames = { - {"assassin", CONST_ME_ASSASSIN}, - {"bluefireworks", CONST_ME_BLUE_FIREWORKS }, - {"bluebubble", CONST_ME_LOSEENERGY}, - {"blackspark", CONST_ME_HITAREA}, - {"blueshimmer", CONST_ME_MAGIC_BLUE}, - {"bluenote", CONST_ME_SOUND_BLUE}, - {"bubbles", CONST_ME_BUBBLES}, - {"bluefirework", CONST_ME_FIREWORK_BLUE}, - {"bigclouds", CONST_ME_BIGCLOUDS}, - {"bigplants", CONST_ME_BIGPLANTS}, - {"bloodysteps", CONST_ME_BLOODYSTEPS}, - {"bats", CONST_ME_BATS}, - {"blueenergyspark", CONST_ME_BLUE_ENERGY_SPARK }, - {"blueghost", CONST_ME_BLUE_GHOST }, - {"blacksmoke", CONST_ME_BLACKSMOKE}, - {"carniphila", CONST_ME_CARNIPHILA}, - {"cake", CONST_ME_CAKE}, - {"confettihorizontal", CONST_ME_CONFETTI_HORIZONTAL}, - {"confettivertical", CONST_ME_CONFETTI_VERTICAL}, - {"criticaldagame", CONST_ME_CRITICAL_DAMAGE}, - {"dice", CONST_ME_CRAPS}, - {"dragonhead", CONST_ME_DRAGONHEAD}, - {"explosionarea", CONST_ME_EXPLOSIONAREA}, - {"explosion", CONST_ME_EXPLOSIONHIT}, - {"energy", CONST_ME_ENERGYHIT}, - {"energyarea", CONST_ME_ENERGYAREA}, - {"earlythunder", CONST_ME_EARLY_THUNDER }, - {"fire", CONST_ME_HITBYFIRE}, - {"firearea", CONST_ME_FIREAREA}, - {"fireattack", CONST_ME_FIREATTACK}, - {"ferumbras", CONST_ME_FERUMBRAS}, - {"greenspark", CONST_ME_HITBYPOISON}, - {"greenbubble", CONST_ME_GREEN_RINGS}, - {"greennote", CONST_ME_SOUND_GREEN}, - {"greenshimmer", CONST_ME_MAGIC_GREEN}, - {"giftwraps", CONST_ME_GIFT_WRAPS}, - {"groundshaker", CONST_ME_GROUNDSHAKER}, - {"giantice", CONST_ME_GIANTICE}, - {"greensmoke", CONST_ME_GREENSMOKE}, - {"greenenergyspark", CONST_ME_GREEN_ENERGY_SPARK }, - {"greenfireworks", CONST_ME_GREEN_FIREWORKS }, - {"hearts", CONST_ME_HEARTS}, - {"holydamage", CONST_ME_HOLYDAMAGE}, - {"holyarea", CONST_ME_HOLYAREA}, - {"icearea", CONST_ME_ICEAREA}, - {"icetornado", CONST_ME_ICETORNADO}, - {"iceattack", CONST_ME_ICEATTACK}, - {"insects", CONST_ME_INSECTS}, - {"mortarea", CONST_ME_MORTAREA}, - {"mirrorhorizontal", CONST_ME_MIRRORHORIZONTAL}, - {"mirrorvertical", CONST_ME_MIRRORVERTICAL}, - {"magicpowder", CONST_ME_MAGIC_POWDER }, - {"orcshaman", CONST_ME_ORCSHAMAN}, - {"orcshamanfire", CONST_ME_ORCSHAMAN_FIRE}, - {"orangeenergyspark", CONST_ME_ORANGE_ENERGY_SPARK }, - {"orangefireworks", CONST_ME_ORANGE_FIREWORKS }, - {"poff", CONST_ME_POFF}, - {"poison", CONST_ME_POISONAREA}, - {"purplenote", CONST_ME_SOUND_PURPLE}, - {"purpleenergy", CONST_ME_PURPLEENERGY}, - {"plantattack", CONST_ME_PLANTATTACK}, - {"plugingfish", CONST_ME_PLUNGING_FISH}, - {"purplesmoke", CONST_ME_PURPLESMOKE}, - {"pixieexplosion", CONST_ME_PIXIE_EXPLOSION }, - {"pixiecoming", CONST_ME_PIXIE_COMING }, - {"pixiegoing", CONST_ME_PIXIE_GOING }, - {"pinkbeam", CONST_ME_PINK_BEAM }, - {"pinkvortex", CONST_ME_PINK_VORTEX }, - {"pinkenergyspark", CONST_ME_PINK_ENERGY_SPARK }, - {"pinkfireworks", CONST_ME_PINK_FIREWORKS }, - {"redspark", CONST_ME_DRAWBLOOD}, - {"redshimmer", CONST_ME_MAGIC_RED}, - {"rednote", CONST_ME_SOUND_RED}, - {"redfirework", CONST_ME_FIREWORK_RED}, - {"redsmoke", CONST_ME_REDSMOKE}, - {"ragiazbonecapsule", CONST_ME_RAGIAZ_BONECAPSULE}, - {"stun", CONST_ME_STUN}, - {"sleep", CONST_ME_SLEEP}, - {"smallclouds", CONST_ME_SMALLCLOUDS}, - {"stones", CONST_ME_STONES}, - {"smallplants", CONST_ME_SMALLPLANTS}, - {"skullhorizontal", CONST_ME_SKULLHORIZONTAL}, - {"skullvertical", CONST_ME_SKULLVERTICAL}, - {"stepshorizontal", CONST_ME_STEPSHORIZONTAL}, - {"stepsvertical", CONST_ME_STEPSVERTICAL}, - {"smoke", CONST_ME_SMOKE}, - {"storm", CONST_ME_STORM }, - {"stonestorm", CONST_ME_STONE_STORM }, - {"teleport", CONST_ME_TELEPORT}, - {"tutorialarrow", CONST_ME_TUTORIALARROW}, - {"tutorialsquare", CONST_ME_TUTORIALSQUARE}, - {"thunder", CONST_ME_THUNDER}, - {"treasuremap", CONST_ME_TREASURE_MAP }, - {"yellowspark", CONST_ME_BLOCKHIT}, - {"yellowbubble", CONST_ME_YELLOW_RINGS}, - {"yellownote", CONST_ME_SOUND_YELLOW}, - {"yellowfirework", CONST_ME_FIREWORK_YELLOW}, - {"yellowenergy", CONST_ME_YELLOWENERGY}, - {"yalaharighost", CONST_ME_YALAHARIGHOST}, - {"yellowsmoke", CONST_ME_YELLOWSMOKE}, - {"yellowenergyspark", CONST_ME_YELLOW_ENERGY_SPARK }, - {"whitenote", CONST_ME_SOUND_WHITE}, - {"watercreature", CONST_ME_WATERCREATURE}, - {"watersplash", CONST_ME_WATERSPLASH}, - {"whiteenergyspark", CONST_ME_WHITE_ENERGY_SPARK }, - {"fatal", CONST_ME_FATAL}, - {"dodge", CONST_ME_DODGE}, - {"hourglass", CONST_ME_HOURGLASS}, - {"ferumbras1", CONST_ME_FERUMBRAS_1}, - {"gazharagoth", CONST_ME_GAZHARAGOTH}, - {"madmage", CONST_ME_MAD_MAGE}, - {"horestis", CONST_ME_HORESTIS}, - {"devovorga", CONST_ME_DEVOVORGA}, - {"ferumbras2", CONST_ME_FERUMBRAS_2}, + { "assassin", CONST_ME_ASSASSIN }, + { "bluefireworks", CONST_ME_BLUE_FIREWORKS }, + { "bluebubble", CONST_ME_LOSEENERGY }, + { "blackspark", CONST_ME_HITAREA }, + { "blueshimmer", CONST_ME_MAGIC_BLUE }, + { "bluenote", CONST_ME_SOUND_BLUE }, + { "bubbles", CONST_ME_BUBBLES }, + { "bluefirework", CONST_ME_FIREWORK_BLUE }, + { "bigclouds", CONST_ME_BIGCLOUDS }, + { "bigplants", CONST_ME_BIGPLANTS }, + { "bloodysteps", CONST_ME_BLOODYSTEPS }, + { "bats", CONST_ME_BATS }, + { "blueenergyspark", CONST_ME_BLUE_ENERGY_SPARK }, + { "blueghost", CONST_ME_BLUE_GHOST }, + { "blacksmoke", CONST_ME_BLACKSMOKE }, + { "carniphila", CONST_ME_CARNIPHILA }, + { "cake", CONST_ME_CAKE }, + { "confettihorizontal", CONST_ME_CONFETTI_HORIZONTAL }, + { "confettivertical", CONST_ME_CONFETTI_VERTICAL }, + { "criticaldagame", CONST_ME_CRITICAL_DAMAGE }, + { "dice", CONST_ME_CRAPS }, + { "dragonhead", CONST_ME_DRAGONHEAD }, + { "explosionarea", CONST_ME_EXPLOSIONAREA }, + { "explosion", CONST_ME_EXPLOSIONHIT }, + { "energy", CONST_ME_ENERGYHIT }, + { "energyarea", CONST_ME_ENERGYAREA }, + { "earlythunder", CONST_ME_EARLY_THUNDER }, + { "fire", CONST_ME_HITBYFIRE }, + { "firearea", CONST_ME_FIREAREA }, + { "fireattack", CONST_ME_FIREATTACK }, + { "ferumbras", CONST_ME_FERUMBRAS }, + { "greenspark", CONST_ME_HITBYPOISON }, + { "greenbubble", CONST_ME_GREEN_RINGS }, + { "greennote", CONST_ME_SOUND_GREEN }, + { "greenshimmer", CONST_ME_MAGIC_GREEN }, + { "giftwraps", CONST_ME_GIFT_WRAPS }, + { "groundshaker", CONST_ME_GROUNDSHAKER }, + { "giantice", CONST_ME_GIANTICE }, + { "greensmoke", CONST_ME_GREENSMOKE }, + { "greenenergyspark", CONST_ME_GREEN_ENERGY_SPARK }, + { "greenfireworks", CONST_ME_GREEN_FIREWORKS }, + { "hearts", CONST_ME_HEARTS }, + { "holydamage", CONST_ME_HOLYDAMAGE }, + { "holyarea", CONST_ME_HOLYAREA }, + { "icearea", CONST_ME_ICEAREA }, + { "icetornado", CONST_ME_ICETORNADO }, + { "iceattack", CONST_ME_ICEATTACK }, + { "insects", CONST_ME_INSECTS }, + { "mortarea", CONST_ME_MORTAREA }, + { "mirrorhorizontal", CONST_ME_MIRRORHORIZONTAL }, + { "mirrorvertical", CONST_ME_MIRRORVERTICAL }, + { "magicpowder", CONST_ME_MAGIC_POWDER }, + { "orcshaman", CONST_ME_ORCSHAMAN }, + { "orcshamanfire", CONST_ME_ORCSHAMAN_FIRE }, + { "orangeenergyspark", CONST_ME_ORANGE_ENERGY_SPARK }, + { "orangefireworks", CONST_ME_ORANGE_FIREWORKS }, + { "poff", CONST_ME_POFF }, + { "poison", CONST_ME_POISONAREA }, + { "purplenote", CONST_ME_SOUND_PURPLE }, + { "purpleenergy", CONST_ME_PURPLEENERGY }, + { "plantattack", CONST_ME_PLANTATTACK }, + { "plugingfish", CONST_ME_PLUNGING_FISH }, + { "purplesmoke", CONST_ME_PURPLESMOKE }, + { "pixieexplosion", CONST_ME_PIXIE_EXPLOSION }, + { "pixiecoming", CONST_ME_PIXIE_COMING }, + { "pixiegoing", CONST_ME_PIXIE_GOING }, + { "pinkbeam", CONST_ME_PINK_BEAM }, + { "pinkvortex", CONST_ME_PINK_VORTEX }, + { "pinkenergyspark", CONST_ME_PINK_ENERGY_SPARK }, + { "pinkfireworks", CONST_ME_PINK_FIREWORKS }, + { "redspark", CONST_ME_DRAWBLOOD }, + { "redshimmer", CONST_ME_MAGIC_RED }, + { "rednote", CONST_ME_SOUND_RED }, + { "redfirework", CONST_ME_FIREWORK_RED }, + { "redsmoke", CONST_ME_REDSMOKE }, + { "ragiazbonecapsule", CONST_ME_RAGIAZ_BONECAPSULE }, + { "stun", CONST_ME_STUN }, + { "sleep", CONST_ME_SLEEP }, + { "smallclouds", CONST_ME_SMALLCLOUDS }, + { "stones", CONST_ME_STONES }, + { "smallplants", CONST_ME_SMALLPLANTS }, + { "skullhorizontal", CONST_ME_SKULLHORIZONTAL }, + { "skullvertical", CONST_ME_SKULLVERTICAL }, + { "stepshorizontal", CONST_ME_STEPSHORIZONTAL }, + { "stepsvertical", CONST_ME_STEPSVERTICAL }, + { "smoke", CONST_ME_SMOKE }, + { "storm", CONST_ME_STORM }, + { "stonestorm", CONST_ME_STONE_STORM }, + { "teleport", CONST_ME_TELEPORT }, + { "tutorialarrow", CONST_ME_TUTORIALARROW }, + { "tutorialsquare", CONST_ME_TUTORIALSQUARE }, + { "thunder", CONST_ME_THUNDER }, + { "treasuremap", CONST_ME_TREASURE_MAP }, + { "yellowspark", CONST_ME_BLOCKHIT }, + { "yellowbubble", CONST_ME_YELLOW_RINGS }, + { "yellownote", CONST_ME_SOUND_YELLOW }, + { "yellowfirework", CONST_ME_FIREWORK_YELLOW }, + { "yellowenergy", CONST_ME_YELLOWENERGY }, + { "yalaharighost", CONST_ME_YALAHARIGHOST }, + { "yellowsmoke", CONST_ME_YELLOWSMOKE }, + { "yellowenergyspark", CONST_ME_YELLOW_ENERGY_SPARK }, + { "whitenote", CONST_ME_SOUND_WHITE }, + { "watercreature", CONST_ME_WATERCREATURE }, + { "watersplash", CONST_ME_WATERSPLASH }, + { "whiteenergyspark", CONST_ME_WHITE_ENERGY_SPARK }, + { "fatal", CONST_ME_FATAL }, + { "dodge", CONST_ME_DODGE }, + { "hourglass", CONST_ME_HOURGLASS }, + { "ferumbras1", CONST_ME_FERUMBRAS_1 }, + { "gazharagoth", CONST_ME_GAZHARAGOTH }, + { "madmage", CONST_ME_MAD_MAGE }, + { "horestis", CONST_ME_HORESTIS }, + { "devovorga", CONST_ME_DEVOVORGA }, + { "ferumbras2", CONST_ME_FERUMBRAS_2 }, }; ShootTypeNames shootTypeNames = { - {"arrow", CONST_ANI_ARROW}, - {"bolt", CONST_ANI_BOLT}, - {"burstarrow", CONST_ANI_BURSTARROW}, - {"cake", CONST_ANI_CAKE}, - {"crystallinearrow", CONST_ANI_CRYSTALLINEARROW}, - {"drillbolt", CONST_ANI_DRILLBOLT}, - {"death", CONST_ANI_DEATH}, - {"energy", CONST_ANI_ENERGY}, - {"enchantedspear", CONST_ANI_ENCHANTEDSPEAR}, - {"etherealspear", CONST_ANI_ETHEREALSPEAR}, - {"eartharrow", CONST_ANI_EARTHARROW}, - {"explosion", CONST_ANI_EXPLOSION}, - {"earth", CONST_ANI_EARTH}, - {"energyball", CONST_ANI_ENERGYBALL}, - {"envenomedarrow", CONST_ANI_ENVENOMEDARROW}, - {"fire", CONST_ANI_FIRE}, - {"flasharrow", CONST_ANI_FLASHARROW}, - {"flammingarrow", CONST_ANI_FLAMMINGARROW}, - {"greenstar", CONST_ANI_GREENSTAR}, - {"gloothspear", CONST_ANI_GLOOTHSPEAR}, - {"huntingspear", CONST_ANI_HUNTINGSPEAR}, - {"holy", CONST_ANI_HOLY}, - {"infernalbolt", CONST_ANI_INFERNALBOLT}, - {"ice", CONST_ANI_ICE}, - {"largerock", CONST_ANI_LARGEROCK}, - {"leafstar", CONST_ANI_LEAFSTAR}, - {"onyxarrow", CONST_ANI_ONYXARROW}, - {"redstar", CONST_ANI_REDSTAR}, - {"royalspear", CONST_ANI_ROYALSPEAR}, - {"spear", CONST_ANI_SPEAR}, - {"sniperarrow", CONST_ANI_SNIPERARROW}, - {"smallstone", CONST_ANI_SMALLSTONE}, - {"smallice", CONST_ANI_SMALLICE}, - {"smallholy", CONST_ANI_SMALLHOLY}, - {"smallearth", CONST_ANI_SMALLEARTH}, - {"snowball", CONST_ANI_SNOWBALL}, - {"suddendeath", CONST_ANI_SUDDENDEATH}, - {"shiverarrow", CONST_ANI_SHIVERARROW}, - {"simplearrow", CONST_ANI_SIMPLEARROW}, - {"poisonarrow", CONST_ANI_POISONARROW}, - {"powerbolt", CONST_ANI_POWERBOLT}, - {"poison", CONST_ANI_POISON}, - {"prismaticbolt", CONST_ANI_PRISMATICBOLT}, - {"piercingbolt", CONST_ANI_PIERCINGBOLT}, - {"throwingstar", CONST_ANI_THROWINGSTAR}, - {"vortexbolt", CONST_ANI_VORTEXBOLT}, - {"throwingknife", CONST_ANI_THROWINGKNIFE}, - {"tarsalarrow", CONST_ANI_TARSALARROW}, - {"whirlwindsword", CONST_ANI_WHIRLWINDSWORD}, - {"whirlwindaxe", CONST_ANI_WHIRLWINDAXE}, - {"whirlwindclub", CONST_ANI_WHIRLWINDCLUB}, - {"diamondarrow", CONST_ANI_DIAMONDARROW}, - {"spectralbolt", CONST_ANI_SPECTRALBOLT}, - {"royalstar", CONST_ANI_ROYALSTAR}, + { "arrow", CONST_ANI_ARROW }, + { "bolt", CONST_ANI_BOLT }, + { "burstarrow", CONST_ANI_BURSTARROW }, + { "cake", CONST_ANI_CAKE }, + { "crystallinearrow", CONST_ANI_CRYSTALLINEARROW }, + { "drillbolt", CONST_ANI_DRILLBOLT }, + { "death", CONST_ANI_DEATH }, + { "energy", CONST_ANI_ENERGY }, + { "enchantedspear", CONST_ANI_ENCHANTEDSPEAR }, + { "etherealspear", CONST_ANI_ETHEREALSPEAR }, + { "eartharrow", CONST_ANI_EARTHARROW }, + { "explosion", CONST_ANI_EXPLOSION }, + { "earth", CONST_ANI_EARTH }, + { "energyball", CONST_ANI_ENERGYBALL }, + { "envenomedarrow", CONST_ANI_ENVENOMEDARROW }, + { "fire", CONST_ANI_FIRE }, + { "flasharrow", CONST_ANI_FLASHARROW }, + { "flammingarrow", CONST_ANI_FLAMMINGARROW }, + { "greenstar", CONST_ANI_GREENSTAR }, + { "gloothspear", CONST_ANI_GLOOTHSPEAR }, + { "huntingspear", CONST_ANI_HUNTINGSPEAR }, + { "holy", CONST_ANI_HOLY }, + { "infernalbolt", CONST_ANI_INFERNALBOLT }, + { "ice", CONST_ANI_ICE }, + { "largerock", CONST_ANI_LARGEROCK }, + { "leafstar", CONST_ANI_LEAFSTAR }, + { "onyxarrow", CONST_ANI_ONYXARROW }, + { "redstar", CONST_ANI_REDSTAR }, + { "royalspear", CONST_ANI_ROYALSPEAR }, + { "spear", CONST_ANI_SPEAR }, + { "sniperarrow", CONST_ANI_SNIPERARROW }, + { "smallstone", CONST_ANI_SMALLSTONE }, + { "smallice", CONST_ANI_SMALLICE }, + { "smallholy", CONST_ANI_SMALLHOLY }, + { "smallearth", CONST_ANI_SMALLEARTH }, + { "snowball", CONST_ANI_SNOWBALL }, + { "suddendeath", CONST_ANI_SUDDENDEATH }, + { "shiverarrow", CONST_ANI_SHIVERARROW }, + { "simplearrow", CONST_ANI_SIMPLEARROW }, + { "poisonarrow", CONST_ANI_POISONARROW }, + { "powerbolt", CONST_ANI_POWERBOLT }, + { "poison", CONST_ANI_POISON }, + { "prismaticbolt", CONST_ANI_PRISMATICBOLT }, + { "piercingbolt", CONST_ANI_PIERCINGBOLT }, + { "throwingstar", CONST_ANI_THROWINGSTAR }, + { "vortexbolt", CONST_ANI_VORTEXBOLT }, + { "throwingknife", CONST_ANI_THROWINGKNIFE }, + { "tarsalarrow", CONST_ANI_TARSALARROW }, + { "whirlwindsword", CONST_ANI_WHIRLWINDSWORD }, + { "whirlwindaxe", CONST_ANI_WHIRLWINDAXE }, + { "whirlwindclub", CONST_ANI_WHIRLWINDCLUB }, + { "diamondarrow", CONST_ANI_DIAMONDARROW }, + { "spectralbolt", CONST_ANI_SPECTRALBOLT }, + { "royalstar", CONST_ANI_ROYALSTAR }, }; CombatTypeNames combatTypeNames = { - {COMBAT_DROWNDAMAGE, "drown" }, - {COMBAT_DEATHDAMAGE, "death" }, - {COMBAT_ENERGYDAMAGE, "energy" }, - {COMBAT_EARTHDAMAGE, "earth" }, - {COMBAT_FIREDAMAGE, "fire" }, - {COMBAT_HEALING, "healing" }, - {COMBAT_HOLYDAMAGE, "holy" }, - {COMBAT_ICEDAMAGE, "ice" }, - {COMBAT_UNDEFINEDDAMAGE, "undefined" }, - {COMBAT_LIFEDRAIN, "lifedrain" }, - {COMBAT_MANADRAIN, "manadrain" }, - {COMBAT_PHYSICALDAMAGE, "physical" }, + { COMBAT_DROWNDAMAGE, "drown" }, + { COMBAT_DEATHDAMAGE, "death" }, + { COMBAT_ENERGYDAMAGE, "energy" }, + { COMBAT_EARTHDAMAGE, "earth" }, + { COMBAT_FIREDAMAGE, "fire" }, + { COMBAT_HEALING, "healing" }, + { COMBAT_HOLYDAMAGE, "holy" }, + { COMBAT_ICEDAMAGE, "ice" }, + { COMBAT_UNDEFINEDDAMAGE, "undefined" }, + { COMBAT_LIFEDRAIN, "lifedrain" }, + { COMBAT_MANADRAIN, "manadrain" }, + { COMBAT_PHYSICALDAMAGE, "physical" }, }; AmmoTypeNames ammoTypeNames = { - {"arrow", AMMO_ARROW}, - {"bolt", AMMO_BOLT}, - {"poisonarrow", AMMO_ARROW}, - {"burstarrow", AMMO_ARROW}, - {"enchantedspear", AMMO_SPEAR}, - {"etherealspear", AMMO_SPEAR}, - {"eartharrow", AMMO_ARROW}, - {"flasharrow", AMMO_ARROW}, - {"flammingarrow", AMMO_ARROW}, - {"huntingspear", AMMO_SPEAR}, - {"infernalbolt", AMMO_BOLT}, - {"largerock", AMMO_STONE}, - {"onyxarrow", AMMO_ARROW}, - {"powerbolt", AMMO_BOLT}, - {"piercingbolt", AMMO_BOLT}, - {"royalspear", AMMO_SPEAR}, - {"snowball", AMMO_SNOWBALL}, - {"smallstone", AMMO_STONE}, - {"spear", AMMO_SPEAR}, - {"sniperarrow", AMMO_ARROW}, - {"shiverarrow", AMMO_ARROW}, - {"throwingstar", AMMO_THROWINGSTAR}, - {"throwingknife", AMMO_THROWINGKNIFE}, - {"diamondarrow", AMMO_ARROW}, - {"spectralbolt", AMMO_BOLT}, + { "arrow", AMMO_ARROW }, + { "bolt", AMMO_BOLT }, + { "poisonarrow", AMMO_ARROW }, + { "burstarrow", AMMO_ARROW }, + { "enchantedspear", AMMO_SPEAR }, + { "etherealspear", AMMO_SPEAR }, + { "eartharrow", AMMO_ARROW }, + { "flasharrow", AMMO_ARROW }, + { "flammingarrow", AMMO_ARROW }, + { "huntingspear", AMMO_SPEAR }, + { "infernalbolt", AMMO_BOLT }, + { "largerock", AMMO_STONE }, + { "onyxarrow", AMMO_ARROW }, + { "powerbolt", AMMO_BOLT }, + { "piercingbolt", AMMO_BOLT }, + { "royalspear", AMMO_SPEAR }, + { "snowball", AMMO_SNOWBALL }, + { "smallstone", AMMO_STONE }, + { "spear", AMMO_SPEAR }, + { "sniperarrow", AMMO_ARROW }, + { "shiverarrow", AMMO_ARROW }, + { "throwingstar", AMMO_THROWINGSTAR }, + { "throwingknife", AMMO_THROWINGKNIFE }, + { "diamondarrow", AMMO_ARROW }, + { "spectralbolt", AMMO_BOLT }, }; WeaponActionNames weaponActionNames = { - {"move", WEAPONACTION_MOVE}, - {"removecharge", WEAPONACTION_REMOVECHARGE}, - {"removecount", WEAPONACTION_REMOVECOUNT}, + { "move", WEAPONACTION_MOVE }, + { "removecharge", WEAPONACTION_REMOVECHARGE }, + { "removecount", WEAPONACTION_REMOVECOUNT }, }; SkullNames skullNames = { - {"black", SKULL_BLACK}, - {"green", SKULL_GREEN}, - {"none", SKULL_NONE}, - {"orange", SKULL_ORANGE}, - {"red", SKULL_RED}, - {"yellow", SKULL_YELLOW}, - {"white", SKULL_WHITE}, + { "black", SKULL_BLACK }, + { "green", SKULL_GREEN }, + { "none", SKULL_NONE }, + { "orange", SKULL_ORANGE }, + { "red", SKULL_RED }, + { "yellow", SKULL_YELLOW }, + { "white", SKULL_WHITE }, }; const ImbuementTypeNames imbuementTypeNames = { - {"elemental damage", IMBUEMENT_ELEMENTAL_DAMAGE}, - {"life leech", IMBUEMENT_LIFE_LEECH}, - {"mana leech", IMBUEMENT_MANA_LEECH}, - {"critical hit", IMBUEMENT_CRITICAL_HIT}, - {"elemental protection death", IMBUEMENT_ELEMENTAL_PROTECTION_DEATH}, - {"elemental protection earth", IMBUEMENT_ELEMENTAL_PROTECTION_EARTH}, - {"elemental protection fire", IMBUEMENT_ELEMENTAL_PROTECTION_FIRE}, - {"elemental protection ice", IMBUEMENT_ELEMENTAL_PROTECTION_ICE}, - {"elemental protection energy", IMBUEMENT_ELEMENTAL_PROTECTION_ENERGY}, - {"elemental protection holy", IMBUEMENT_ELEMENTAL_PROTECTION_HOLY}, - {"increase speed", IMBUEMENT_INCREASE_SPEED}, - {"skillboost axe", IMBUEMENT_SKILLBOOST_AXE}, - {"skillboost sword", IMBUEMENT_SKILLBOOST_SWORD}, - {"skillboost club", IMBUEMENT_SKILLBOOST_CLUB}, - {"skillboost shielding", IMBUEMENT_SKILLBOOST_SHIELDING}, - {"skillboost distance", IMBUEMENT_SKILLBOOST_DISTANCE}, - {"skillboost magic level", IMBUEMENT_SKILLBOOST_MAGIC_LEVEL}, - {"increase capacity", IMBUEMENT_INCREASE_CAPACITY} + { "elemental damage", IMBUEMENT_ELEMENTAL_DAMAGE }, + { "life leech", IMBUEMENT_LIFE_LEECH }, + { "mana leech", IMBUEMENT_MANA_LEECH }, + { "critical hit", IMBUEMENT_CRITICAL_HIT }, + { "elemental protection death", IMBUEMENT_ELEMENTAL_PROTECTION_DEATH }, + { "elemental protection earth", IMBUEMENT_ELEMENTAL_PROTECTION_EARTH }, + { "elemental protection fire", IMBUEMENT_ELEMENTAL_PROTECTION_FIRE }, + { "elemental protection ice", IMBUEMENT_ELEMENTAL_PROTECTION_ICE }, + { "elemental protection energy", IMBUEMENT_ELEMENTAL_PROTECTION_ENERGY }, + { "elemental protection holy", IMBUEMENT_ELEMENTAL_PROTECTION_HOLY }, + { "increase speed", IMBUEMENT_INCREASE_SPEED }, + { "skillboost axe", IMBUEMENT_SKILLBOOST_AXE }, + { "skillboost sword", IMBUEMENT_SKILLBOOST_SWORD }, + { "skillboost club", IMBUEMENT_SKILLBOOST_CLUB }, + { "skillboost shielding", IMBUEMENT_SKILLBOOST_SHIELDING }, + { "skillboost distance", IMBUEMENT_SKILLBOOST_DISTANCE }, + { "skillboost magic level", IMBUEMENT_SKILLBOOST_MAGIC_LEVEL }, + { "increase capacity", IMBUEMENT_INCREASE_CAPACITY } }; /** @@ -748,15 +738,14 @@ const ImbuementTypeNames imbuementTypeNames = { * It will be dropped with monsters. Use RespawnPeriod_t instead. */ SpawnTypeNames spawnTypeNames = { - {"all", RESPAWN_IN_ALL }, - {"day", RESPAWN_IN_DAY }, - {"dayandcave", RESPAWN_IN_DAY_CAVE }, - {"night", RESPAWN_IN_NIGHT }, - {"nightandcave", RESPAWN_IN_NIGHT_CAVE }, + { "all", RESPAWN_IN_ALL }, + { "day", RESPAWN_IN_DAY }, + { "dayandcave", RESPAWN_IN_DAY_CAVE }, + { "night", RESPAWN_IN_NIGHT }, + { "nightandcave", RESPAWN_IN_NIGHT_CAVE }, }; -MagicEffectClasses getMagicEffect(const std::string& strValue) -{ +MagicEffectClasses getMagicEffect(const std::string &strValue) { auto magicEffect = magicEffectNames.find(strValue); if (magicEffect != magicEffectNames.end()) { return magicEffect->second; @@ -764,8 +753,7 @@ MagicEffectClasses getMagicEffect(const std::string& strValue) return CONST_ME_NONE; } -ShootType_t getShootType(const std::string& strValue) -{ +ShootType_t getShootType(const std::string &strValue) { auto shootType = shootTypeNames.find(strValue); if (shootType != shootTypeNames.end()) { return shootType->second; @@ -773,8 +761,7 @@ ShootType_t getShootType(const std::string& strValue) return CONST_ANI_NONE; } -std::string getCombatName(CombatType_t combatType) -{ +std::string getCombatName(CombatType_t combatType) { auto combatName = combatTypeNames.find(combatType); if (combatName != combatTypeNames.end()) { return combatName->second; @@ -782,17 +769,15 @@ std::string getCombatName(CombatType_t combatType) return "unknown"; } -CombatType_t getCombatType(const std::string& combatname) -{ - auto it = std::find_if(combatTypeNames.begin(), combatTypeNames.end(), [combatname](std::pair const& pair) { +CombatType_t getCombatType(const std::string &combatname) { + auto it = std::find_if(combatTypeNames.begin(), combatTypeNames.end(), [combatname](const std::pair &pair) { return pair.second == combatname; }); return it != combatTypeNames.end() ? it->first : COMBAT_NONE; } -Ammo_t getAmmoType(const std::string& strValue) -{ +Ammo_t getAmmoType(const std::string &strValue) { auto ammoType = ammoTypeNames.find(strValue); if (ammoType != ammoTypeNames.end()) { return ammoType->second; @@ -800,8 +785,7 @@ Ammo_t getAmmoType(const std::string& strValue) return AMMO_NONE; } -WeaponAction_t getWeaponAction(const std::string& strValue) -{ +WeaponAction_t getWeaponAction(const std::string &strValue) { auto weaponAction = weaponActionNames.find(strValue); if (weaponAction != weaponActionNames.end()) { return weaponAction->second; @@ -809,8 +793,7 @@ WeaponAction_t getWeaponAction(const std::string& strValue) return WEAPONACTION_NONE; } -Skulls_t getSkullType(const std::string& strValue) -{ +Skulls_t getSkullType(const std::string &strValue) { auto skullType = skullNames.find(strValue); if (skullType != skullNames.end()) { return skullType->second; @@ -818,8 +801,7 @@ Skulls_t getSkullType(const std::string& strValue) return SKULL_NONE; } -ImbuementTypes_t getImbuementType(const std::string& strValue) -{ +ImbuementTypes_t getImbuementType(const std::string &strValue) { auto imbuementType = imbuementTypeNames.find(strValue); if (imbuementType != imbuementTypeNames.end()) { return imbuementType->second; @@ -831,8 +813,7 @@ ImbuementTypes_t getImbuementType(const std::string& strValue) * @Deprecated * It will be dropped with monsters. Use RespawnPeriod_t instead. */ -SpawnType_t getSpawnType(const std::string& strValue) -{ +SpawnType_t getSpawnType(const std::string &strValue) { auto spawnType = spawnTypeNames.find(strValue); if (spawnType != spawnTypeNames.end()) { return spawnType->second; @@ -840,8 +821,7 @@ SpawnType_t getSpawnType(const std::string& strValue) return RESPAWN_IN_ALL; } -std::string getSkillName(uint8_t skillid) -{ +std::string getSkillName(uint8_t skillid) { switch (skillid) { case SKILL_FIST: return "fist fighting"; @@ -893,8 +873,7 @@ std::string getSkillName(uint8_t skillid) } } -uint32_t adlerChecksum(const uint8_t* data, size_t length) -{ +uint32_t adlerChecksum(const uint8_t* data, size_t length) { if (length > NETWORKMESSAGE_MAXSIZE) { return 0; } @@ -919,9 +898,8 @@ uint32_t adlerChecksum(const uint8_t* data, size_t length) return (b << 16) | a; } -std::string ucfirst(std::string str) -{ - for (char& i : str) { +std::string ucfirst(std::string str) { + for (char &i : str) { if (i != ' ') { i = toupper(i); break; @@ -930,8 +908,7 @@ std::string ucfirst(std::string str) return str; } -std::string ucwords(std::string str) -{ +std::string ucwords(std::string str) { size_t strLength = str.length(); if (strLength == 0) { return str; @@ -947,8 +924,7 @@ std::string ucwords(std::string str) return str; } -bool booleanString(const std::string& str) -{ +bool booleanString(const std::string &str) { if (str.empty()) { return false; } @@ -957,21 +933,26 @@ bool booleanString(const std::string& str) return ch != 'f' && ch != 'n' && ch != '0'; } -std::string getWeaponName(WeaponType_t weaponType) -{ +std::string getWeaponName(WeaponType_t weaponType) { switch (weaponType) { - case WEAPON_SWORD: return "sword"; - case WEAPON_CLUB: return "club"; - case WEAPON_AXE: return "axe"; - case WEAPON_DISTANCE: return "distance"; - case WEAPON_WAND: return "wand"; - case WEAPON_AMMO: return "ammunition"; - default: return std::string(); + case WEAPON_SWORD: + return "sword"; + case WEAPON_CLUB: + return "club"; + case WEAPON_AXE: + return "axe"; + case WEAPON_DISTANCE: + return "distance"; + case WEAPON_WAND: + return "wand"; + case WEAPON_AMMO: + return "ammunition"; + default: + return std::string(); } } -size_t combatTypeToIndex(CombatType_t combatType) -{ +size_t combatTypeToIndex(CombatType_t combatType) { switch (combatType) { case COMBAT_PHYSICALDAMAGE: return 0; @@ -1002,13 +983,11 @@ size_t combatTypeToIndex(CombatType_t combatType) } } -CombatType_t indexToCombatType(size_t v) -{ +CombatType_t indexToCombatType(size_t v) { return static_cast(1 << v); } -ItemAttribute_t stringToItemAttribute(const std::string& str) -{ +ItemAttribute_t stringToItemAttribute(const std::string &str) { if (str == "aid") { return ItemAttribute_t::ACTIONID; } else if (str == "uid") { @@ -1061,8 +1040,7 @@ ItemAttribute_t stringToItemAttribute(const std::string& str) return ItemAttribute_t::NONE; } -std::string getFirstLine(const std::string& str) -{ +std::string getFirstLine(const std::string &str) { std::string firstLine; firstLine.reserve(str.length()); for (const char c : str) { @@ -1074,8 +1052,7 @@ std::string getFirstLine(const std::string& str) return firstLine; } -const char* getReturnMessage(ReturnValue value) -{ +const char* getReturnMessage(ReturnValue value) { switch (value) { case RETURNVALUE_NOERROR: return "No error."; @@ -1325,13 +1302,11 @@ const char* getReturnMessage(ReturnValue value) } } -int64_t OTSYS_TIME() -{ +int64_t OTSYS_TIME() { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } -SpellGroup_t stringToSpellGroup(const std::string &value) -{ +SpellGroup_t stringToSpellGroup(const std::string &value) { std::string tmpStr = asLowerCaseString(value); if (tmpStr == "attack" || tmpStr == "1") { return SPELLGROUP_ATTACK; @@ -1358,14 +1333,13 @@ SpellGroup_t stringToSpellGroup(const std::string &value) * capitalize the first letter of every word in source * @param source */ -void capitalizeWords(std::string& source) -{ +void capitalizeWords(std::string &source) { toLowerCaseString(source); - uint8_t size = (uint8_t) source.size(); - for(uint8_t i=0; i< size; i++) { - if(i==0) { + uint8_t size = (uint8_t)source.size(); + for (uint8_t i = 0; i < size; i++) { + if (i == 0) { source[i] = (char)toupper(source[i]); - } else if(source[i-1] == ' ' || source[i-1] == '\'') { + } else if (source[i - 1] == ' ' || source[i - 1] == '\'') { source[i] = (char)toupper(source[i]); } } @@ -1375,17 +1349,15 @@ void capitalizeWords(std::string& source) * @details * Prevents the console from closing so there is time to read the error information * Then can press any key to close -*/ -void consoleHandlerExit() -{ + */ +void consoleHandlerExit() { SPDLOG_ERROR("The program will close after pressing the enter key..."); getchar(); return; } -NameEval_t validateName(const std::string &name) -{ - StringVector prohibitedWords = {"owner", "gamemaster", "hoster", "admin", "staff", "tibia", "account", "god", "anal", "ass", "fuck", "sex", "hitler", "pussy", "dick", "rape", "cm", "gm", "tutor", "counsellor", "god"}; +NameEval_t validateName(const std::string &name) { + StringVector prohibitedWords = { "owner", "gamemaster", "hoster", "admin", "staff", "tibia", "account", "god", "anal", "ass", "fuck", "sex", "hitler", "pussy", "dick", "rape", "cm", "gm", "tutor", "counsellor", "god" }; StringVector toks; std::regex regexValidChars("^[a-zA-Z' ]+$"); @@ -1394,18 +1366,18 @@ NameEval_t validateName(const std::string &name) std::istream_iterator end; std::copy(begin, end, std::back_inserter(toks)); - if(name.length()<3 || name.length()>14) { + if (name.length() < 3 || name.length() > 14) { return INVALID_LENGTH; } - if(!std::regex_match(name, regexValidChars)) { //invalid chars in name + if (!std::regex_match(name, regexValidChars)) { // invalid chars in name return INVALID_CHARACTER; } - for(std::string str : toks) { - if(str.length()<2) + for (std::string str : toks) { + if (str.length() < 2) return INVALID_TOKEN_LENGTH; - else if(std::find(prohibitedWords.begin(), prohibitedWords.end(),str) != prohibitedWords.end()) { //searching for prohibited words + else if (std::find(prohibitedWords.begin(), prohibitedWords.end(), str) != prohibitedWords.end()) { // searching for prohibited words return INVALID_FORBIDDEN; } } @@ -1413,49 +1385,72 @@ NameEval_t validateName(const std::string &name) return VALID; } -bool isCaskItem(uint16_t itemId) -{ - return (itemId >= ITEM_HEALTH_CASK_START && itemId <= ITEM_HEALTH_CASK_END) || - (itemId >= ITEM_MANA_CASK_START && itemId <= ITEM_MANA_CASK_END) || - (itemId >= ITEM_SPIRIT_CASK_START && itemId <= ITEM_SPIRIT_CASK_END); +bool isCaskItem(uint16_t itemId) { + return (itemId >= ITEM_HEALTH_CASK_START && itemId <= ITEM_HEALTH_CASK_END) || (itemId >= ITEM_MANA_CASK_START && itemId <= ITEM_MANA_CASK_END) || (itemId >= ITEM_SPIRIT_CASK_START && itemId <= ITEM_SPIRIT_CASK_END); } -std::string getObjectCategoryName(ObjectCategory_t category) -{ +std::string getObjectCategoryName(ObjectCategory_t category) { switch (category) { - case OBJECTCATEGORY_ARMORS: return "Armors"; - case OBJECTCATEGORY_NECKLACES: return "Amulets"; - case OBJECTCATEGORY_BOOTS: return "Boots"; - case OBJECTCATEGORY_CONTAINERS: return "Containers"; - case OBJECTCATEGORY_DECORATION: return "Decoration"; - case OBJECTCATEGORY_FOOD: return "Food"; - case OBJECTCATEGORY_HELMETS: return "Helmets"; - case OBJECTCATEGORY_LEGS: return "Legs"; - case OBJECTCATEGORY_OTHERS: return "Others"; - case OBJECTCATEGORY_POTIONS: return "Potions"; - case OBJECTCATEGORY_RINGS: return "Rings"; - case OBJECTCATEGORY_RUNES: return "Runes"; - case OBJECTCATEGORY_SHIELDS: return "Shields"; - case OBJECTCATEGORY_TOOLS: return "Tools"; - case OBJECTCATEGORY_VALUABLES: return "Valuables"; - case OBJECTCATEGORY_AMMO: return "Weapons: Ammunition"; - case OBJECTCATEGORY_AXES: return "Weapons: Axes"; - case OBJECTCATEGORY_CLUBS: return "Weapons: Clubs"; - case OBJECTCATEGORY_DISTANCEWEAPONS: return "Weapons: Distance"; - case OBJECTCATEGORY_SWORDS: return "Weapons: Swords"; - case OBJECTCATEGORY_WANDS: return "Weapons: Wands"; - case OBJECTCATEGORY_PREMIUMSCROLLS: return "Premium Scrolls"; - case OBJECTCATEGORY_TIBIACOINS: return "Tibia Coins"; - case OBJECTCATEGORY_CREATUREPRODUCTS: return "Creature Products"; - case OBJECTCATEGORY_STASHRETRIEVE: return "Stash Retrieve"; - case OBJECTCATEGORY_GOLD: return "Gold"; - case OBJECTCATEGORY_DEFAULT: return "Unassigned Loot"; - default: return std::string(); + case OBJECTCATEGORY_ARMORS: + return "Armors"; + case OBJECTCATEGORY_NECKLACES: + return "Amulets"; + case OBJECTCATEGORY_BOOTS: + return "Boots"; + case OBJECTCATEGORY_CONTAINERS: + return "Containers"; + case OBJECTCATEGORY_DECORATION: + return "Decoration"; + case OBJECTCATEGORY_FOOD: + return "Food"; + case OBJECTCATEGORY_HELMETS: + return "Helmets"; + case OBJECTCATEGORY_LEGS: + return "Legs"; + case OBJECTCATEGORY_OTHERS: + return "Others"; + case OBJECTCATEGORY_POTIONS: + return "Potions"; + case OBJECTCATEGORY_RINGS: + return "Rings"; + case OBJECTCATEGORY_RUNES: + return "Runes"; + case OBJECTCATEGORY_SHIELDS: + return "Shields"; + case OBJECTCATEGORY_TOOLS: + return "Tools"; + case OBJECTCATEGORY_VALUABLES: + return "Valuables"; + case OBJECTCATEGORY_AMMO: + return "Weapons: Ammunition"; + case OBJECTCATEGORY_AXES: + return "Weapons: Axes"; + case OBJECTCATEGORY_CLUBS: + return "Weapons: Clubs"; + case OBJECTCATEGORY_DISTANCEWEAPONS: + return "Weapons: Distance"; + case OBJECTCATEGORY_SWORDS: + return "Weapons: Swords"; + case OBJECTCATEGORY_WANDS: + return "Weapons: Wands"; + case OBJECTCATEGORY_PREMIUMSCROLLS: + return "Premium Scrolls"; + case OBJECTCATEGORY_TIBIACOINS: + return "Tibia Coins"; + case OBJECTCATEGORY_CREATUREPRODUCTS: + return "Creature Products"; + case OBJECTCATEGORY_STASHRETRIEVE: + return "Stash Retrieve"; + case OBJECTCATEGORY_GOLD: + return "Gold"; + case OBJECTCATEGORY_DEFAULT: + return "Unassigned Loot"; + default: + return std::string(); } } -uint8_t forgeBonus(int32_t number) -{ +uint8_t forgeBonus(int32_t number) { // None if (number < 7400) return 0; @@ -1484,8 +1479,7 @@ uint8_t forgeBonus(int32_t number) return 0; } -std::string formatPrice(std::string price, bool space/* = false*/) -{ +std::string formatPrice(std::string price, bool space /* = false*/) { std::ranges::reverse(price.begin(), price.end()); price = std::regex_replace(price, std::regex("000"), "k"); std::ranges::reverse(price.begin(), price.end()); diff --git a/src/utils/tools.h b/src/utils/tools.h index 7acc8e4e942..4a42714886e 100644 --- a/src/utils/tools.h +++ b/src/utils/tools.h @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_TOOLS_H_ #define SRC_UTILS_TOOLS_H_ @@ -15,61 +15,61 @@ #include "enums/item_attribute.hpp" #include "game/movement/position.h" -void printXMLError(const std::string& where, const std::string& fileName, const pugi::xml_parse_result& result); +void printXMLError(const std::string &where, const std::string &fileName, const pugi::xml_parse_result &result); -std::string transformToSHA1(const std::string& input); +std::string transformToSHA1(const std::string &input); uint16_t getStashSize(StashItemList itemList); -std::string generateToken(const std::string& secret, uint32_t ticks); +std::string generateToken(const std::string &secret, uint32_t ticks); -void replaceString(std::string& str, const std::string& sought, const std::string& replacement); -void trim_right(std::string& source, char t); -void trim_left(std::string& source, char t); -void toLowerCaseString(std::string& source); +void replaceString(std::string &str, const std::string &sought, const std::string &replacement); +void trim_right(std::string &source, char t); +void trim_left(std::string &source, char t); +void toLowerCaseString(std::string &source); std::string asLowerCaseString(std::string source); std::string asUpperCaseString(std::string source); using StringVector = std::vector; using IntegerVector = std::vector; -StringVector explodeString(const std::string& inString, const std::string& separator, int32_t limit = -1); -IntegerVector vectorAtoi(const StringVector& stringVector); +StringVector explodeString(const std::string &inString, const std::string &separator, int32_t limit = -1); +IntegerVector vectorAtoi(const StringVector &stringVector); constexpr bool hasBitSet(uint32_t flag, uint32_t flags) { return (flags & flag) != 0; } -std::mt19937& getRandomGenerator(); +std::mt19937 &getRandomGenerator(); int32_t uniform_random(int32_t minNumber, int32_t maxNumber); int32_t normal_random(int32_t minNumber, int32_t maxNumber); bool boolean_random(double probability = 0.5); -Direction getDirection(const std::string& string); +Direction getDirection(const std::string &string); Position getNextPosition(Direction direction, Position pos); -Direction getDirectionTo(const Position& from, const Position& to); +Direction getDirectionTo(const Position &from, const Position &to); -std::string getFirstLine(const std::string& str); +std::string getFirstLine(const std::string &str); std::string formatDate(time_t time); std::string formatDateShort(time_t time); std::time_t getTimeNow(); std::string convertIPToString(uint32_t ip); -void trimString(std::string& str); +void trimString(std::string &str); -MagicEffectClasses getMagicEffect(const std::string& strValue); -ShootType_t getShootType(const std::string& strValue); -Ammo_t getAmmoType(const std::string& strValue); -WeaponAction_t getWeaponAction(const std::string& strValue); -Skulls_t getSkullType(const std::string& strValue); -ImbuementTypes_t getImbuementType(const std::string& strValue); +MagicEffectClasses getMagicEffect(const std::string &strValue); +ShootType_t getShootType(const std::string &strValue); +Ammo_t getAmmoType(const std::string &strValue); +WeaponAction_t getWeaponAction(const std::string &strValue); +Skulls_t getSkullType(const std::string &strValue); +ImbuementTypes_t getImbuementType(const std::string &strValue); std::string getCombatName(CombatType_t combatType); /** * @Deprecated * It will be dropped with monsters. Use RespawnPeriod_t instead. */ -SpawnType_t getSpawnType(const std::string& strValue); -CombatType_t getCombatType(const std::string& combatname); +SpawnType_t getSpawnType(const std::string &strValue); +CombatType_t getCombatType(const std::string &combatname); std::string getSkillName(uint8_t skillid); @@ -77,14 +77,14 @@ uint32_t adlerChecksum(const uint8_t* data, size_t len); std::string ucfirst(std::string str); std::string ucwords(std::string str); -bool booleanString(const std::string& str); +bool booleanString(const std::string &str); std::string getWeaponName(WeaponType_t weaponType); size_t combatTypeToIndex(CombatType_t combatType); CombatType_t indexToCombatType(size_t v); -ItemAttribute_t stringToItemAttribute(const std::string& str); +ItemAttribute_t stringToItemAttribute(const std::string &str); const char* getReturnMessage(ReturnValue value); @@ -102,22 +102,33 @@ SpellGroup_t stringToSpellGroup(const std::string &value); uint8_t forgeBonus(int32_t number); -std::string formatPrice(std::string price, bool space/* = false*/); +std::string formatPrice(std::string price, bool space /* = false*/); static inline Cipbia_Elementals_t getCipbiaElement(CombatType_t combatType) { switch (combatType) { - case COMBAT_PHYSICALDAMAGE: return CIPBIA_ELEMENTAL_PHYSICAL; - case COMBAT_ENERGYDAMAGE: return CIPBIA_ELEMENTAL_ENERGY; - case COMBAT_EARTHDAMAGE: return CIPBIA_ELEMENTAL_EARTH; - case COMBAT_FIREDAMAGE: return CIPBIA_ELEMENTAL_FIRE; - case COMBAT_LIFEDRAIN: return CIPBIA_ELEMENTAL_LIFEDRAIN; - case COMBAT_HEALING: return CIPBIA_ELEMENTAL_HEALING; - case COMBAT_DROWNDAMAGE: return CIPBIA_ELEMENTAL_DROWN; - case COMBAT_ICEDAMAGE: return CIPBIA_ELEMENTAL_ICE; - case COMBAT_HOLYDAMAGE: return CIPBIA_ELEMENTAL_HOLY; - case COMBAT_DEATHDAMAGE: return CIPBIA_ELEMENTAL_DEATH; - default: return CIPBIA_ELEMENTAL_UNDEFINED; + case COMBAT_PHYSICALDAMAGE: + return CIPBIA_ELEMENTAL_PHYSICAL; + case COMBAT_ENERGYDAMAGE: + return CIPBIA_ELEMENTAL_ENERGY; + case COMBAT_EARTHDAMAGE: + return CIPBIA_ELEMENTAL_EARTH; + case COMBAT_FIREDAMAGE: + return CIPBIA_ELEMENTAL_FIRE; + case COMBAT_LIFEDRAIN: + return CIPBIA_ELEMENTAL_LIFEDRAIN; + case COMBAT_HEALING: + return CIPBIA_ELEMENTAL_HEALING; + case COMBAT_DROWNDAMAGE: + return CIPBIA_ELEMENTAL_DROWN; + case COMBAT_ICEDAMAGE: + return CIPBIA_ELEMENTAL_ICE; + case COMBAT_HOLYDAMAGE: + return CIPBIA_ELEMENTAL_HOLY; + case COMBAT_DEATHDAMAGE: + return CIPBIA_ELEMENTAL_DEATH; + default: + return CIPBIA_ELEMENTAL_UNDEFINED; } } -#endif // SRC_UTILS_TOOLS_H_ +#endif // SRC_UTILS_TOOLS_H_ diff --git a/src/utils/utils_definitions.hpp b/src/utils/utils_definitions.hpp index 0858930e296..c3885e1159e 100644 --- a/src/utils/utils_definitions.hpp +++ b/src/utils/utils_definitions.hpp @@ -5,7 +5,7 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_UTILS_DEFINITIONS_HPP_ #define SRC_UTILS_UTILS_DEFINITIONS_HPP_ @@ -14,7 +14,7 @@ enum Icons_t { ICON_POISON = 1 << 0, ICON_BURN = 1 << 1, - ICON_ENERGY = 1 << 2, + ICON_ENERGY = 1 << 2, ICON_DRUNK = 1 << 3, ICON_MANASHIELD = 1 << 4, ICON_PARALYZE = 1 << 5, @@ -80,8 +80,7 @@ enum ThreadState { THREAD_STATE_TERMINATED, }; -enum SpawnType_t -{ +enum SpawnType_t { RESPAWN_IN_ALL = 0, RESPAWN_IN_DAY = 1, RESPAWN_IN_NIGHT = 2, @@ -341,19 +340,20 @@ enum SpeakClasses : uint8_t { TALKTYPE_NPC_UNKOWN = 11, /* no effect (?)*/ TALKTYPE_PRIVATE_PN = 12, TALKTYPE_BROADCAST = 13, - TALKTYPE_CHANNEL_R1 = 14, //red - #c text + TALKTYPE_CHANNEL_R1 = 14, // red - #c text TALKTYPE_PRIVATE_RED_FROM = 15, //@name@text TALKTYPE_PRIVATE_RED_TO = 16, //@name@text TALKTYPE_MONSTER_SAY = 36, TALKTYPE_MONSTER_YELL = 37, - TALKTYPE_CHANNEL_R2 = 0xFF, //#d + TALKTYPE_CHANNEL_R2 = 0xFF, // #d }; enum MessageClasses : uint8_t { MESSAGE_NONE = 0, /* None */ - MESSAGE_GAMEMASTER_CONSOLE = 13, /* Red message in the console*/ /* TALKTYPE_BROADCAST */ + MESSAGE_GAMEMASTER_CONSOLE = 13, + /* Red message in the console*/ /* TALKTYPE_BROADCAST */ MESSAGE_LOGIN = 17, /* White message at the bottom of the game window and in the console*/ MESSAGE_ADMINISTRADOR = 18, /* Red message in game window and in the console*/ @@ -514,7 +514,7 @@ enum NameEval_t : uint8_t { enum ItemID_t : uint16_t { ITEM_BROWSEFIELD = 470, // for internal use - ITEM_SUPPLY_STASH_INDEX = 1, //for internal use + ITEM_SUPPLY_STASH_INDEX = 1, // for internal use ITEM_DEPOT_NULL = 22796, // for internal use - Actual Item ID: 168 ITEM_DECORATION_KIT = 23398, // For internal use (wrap item) ITEM_DOCUMENT_RO = 2834, // Read-only @@ -614,7 +614,7 @@ enum ItemID_t : uint16_t { ITEM_SPIRIT_CASK_START = 25899, ITEM_SPIRIT_CASK_END = 25902, - ITEM_KEG_START = 25903, //kegs ids are contiguous in item.otb + ITEM_KEG_START = 25903, // kegs ids are contiguous in item.otb ITEM_KEG_END = 25914, // Walkable sea @@ -666,16 +666,16 @@ enum ItemID_t : uint16_t { // A map which contains items that, when on creating, should be transformed to the default type. const phmap::flat_hash_map ItemTransformationMap = { - {ITEM_SWORD_RING_ACTIVATED, ITEM_SWORD_RING}, - {ITEM_CLUB_RING_ACTIVATED, ITEM_CLUB_RING}, - {ITEM_DWARVEN_RING_ACTIVATED, ITEM_DWARVEN_RING}, - {ITEM_RING_HEALING_ACTIVATED, ITEM_RING_HEALING}, - {ITEM_STEALTH_RING_ACTIVATED, ITEM_STEALTH_RING}, - {ITEM_TIME_RING_ACTIVATED, ITEM_TIME_RING}, - {ITEM_PAIR_SOFT_BOOTS_ACTIVATED, ITEM_PAIR_SOFT_BOOTS}, - {ITEM_DEATH_RING_ACTIVATED, ITEM_DEATH_RING}, - {ITEM_PRISMATIC_RING_ACTIVATED, ITEM_PRISMATIC_RING}, - {ITEM_OLD_DIAMOND_ARROW, ITEM_DIAMOND_ARROW}, + { ITEM_SWORD_RING_ACTIVATED, ITEM_SWORD_RING }, + { ITEM_CLUB_RING_ACTIVATED, ITEM_CLUB_RING }, + { ITEM_DWARVEN_RING_ACTIVATED, ITEM_DWARVEN_RING }, + { ITEM_RING_HEALING_ACTIVATED, ITEM_RING_HEALING }, + { ITEM_STEALTH_RING_ACTIVATED, ITEM_STEALTH_RING }, + { ITEM_TIME_RING_ACTIVATED, ITEM_TIME_RING }, + { ITEM_PAIR_SOFT_BOOTS_ACTIVATED, ITEM_PAIR_SOFT_BOOTS }, + { ITEM_DEATH_RING_ACTIVATED, ITEM_DEATH_RING }, + { ITEM_PRISMATIC_RING_ACTIVATED, ITEM_PRISMATIC_RING }, + { ITEM_OLD_DIAMOND_ARROW, ITEM_DIAMOND_ARROW }, }; enum class PlayerFlags_t : uint8_t { @@ -736,14 +736,14 @@ enum Blessings_t : uint8_t { }; const phmap::flat_hash_map BlessingNames = { - {TWIST_OF_FATE, "Twist of Fate"}, - {WISDOM_OF_SOLITUDE, "The Wisdom of Solitude"}, - {SPARK_OF_THE_PHOENIX, "The Spark of the Phoenix"}, - {FIRE_OF_THE_SUNS, "The Fire of the Suns"}, - {SPIRITUAL_SHIELDING, "The Spiritual Shielding"}, - {EMBRACE_OF_TIBIA, "The Embrace of Tibia"}, - {BLOOD_OF_THE_MOUNTAIN, "Blood of the Mountain"}, - {HEARTH_OF_THE_MOUNTAIN, "Heart of the Mountain"}, + { TWIST_OF_FATE, "Twist of Fate" }, + { WISDOM_OF_SOLITUDE, "The Wisdom of Solitude" }, + { SPARK_OF_THE_PHOENIX, "The Spark of the Phoenix" }, + { FIRE_OF_THE_SUNS, "The Fire of the Suns" }, + { SPIRITUAL_SHIELDING, "The Spiritual Shielding" }, + { EMBRACE_OF_TIBIA, "The Embrace of Tibia" }, + { BLOOD_OF_THE_MOUNTAIN, "Blood of the Mountain" }, + { HEARTH_OF_THE_MOUNTAIN, "Heart of the Mountain" }, }; -#endif // SRC_UTILS_UTILS_DEFINITIONS_HPP_ +#endif // SRC_UTILS_UTILS_DEFINITIONS_HPP_ diff --git a/src/utils/wildcardtree.cpp b/src/utils/wildcardtree.cpp index e130d5d2118..29e5d178d3c 100644 --- a/src/utils/wildcardtree.cpp +++ b/src/utils/wildcardtree.cpp @@ -5,14 +5,13 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #include "pch.hpp" #include "utils/wildcardtree.h" -WildcardTreeNode* WildcardTreeNode::getChild(char ch) -{ +WildcardTreeNode* WildcardTreeNode::getChild(char ch) { auto it = children.find(ch); if (it == children.end()) { return nullptr; @@ -20,8 +19,7 @@ WildcardTreeNode* WildcardTreeNode::getChild(char ch) return &it->second; } -const WildcardTreeNode* WildcardTreeNode::getChild(char ch) const -{ +const WildcardTreeNode* WildcardTreeNode::getChild(char ch) const { auto it = children.find(ch); if (it == children.end()) { return nullptr; @@ -29,23 +27,20 @@ const WildcardTreeNode* WildcardTreeNode::getChild(char ch) const return &it->second; } -WildcardTreeNode* WildcardTreeNode::addChild(char ch, bool breakp) -{ +WildcardTreeNode* WildcardTreeNode::addChild(char ch, bool breakp) { WildcardTreeNode* child = getChild(ch); if (child) { if (breakp && !child->breakpoint) { child->breakpoint = true; } } else { - auto pair = children.emplace(std::piecewise_construct, - std::forward_as_tuple(ch), std::forward_as_tuple(breakp)); + auto pair = children.emplace(std::piecewise_construct, std::forward_as_tuple(ch), std::forward_as_tuple(breakp)); child = &pair.first->second; } return child; } -void WildcardTreeNode::insert(const std::string& str) -{ +void WildcardTreeNode::insert(const std::string &str) { WildcardTreeNode* cur = this; size_t length = str.length() - 1; @@ -56,8 +51,7 @@ void WildcardTreeNode::insert(const std::string& str) cur->addChild(str[length], true); } -void WildcardTreeNode::remove(const std::string& str) -{ +void WildcardTreeNode::remove(const std::string &str) { WildcardTreeNode* cur = this; std::stack path; @@ -90,8 +84,7 @@ void WildcardTreeNode::remove(const std::string& str) } while (true); } -ReturnValue WildcardTreeNode::findOne(const std::string& query, std::string& result) const -{ +ReturnValue WildcardTreeNode::findOne(const std::string &query, std::string &result) const { const WildcardTreeNode* cur = this; for (char pos : query) { cur = cur->getChild(pos); diff --git a/src/utils/wildcardtree.h b/src/utils/wildcardtree.h index 50a4b61990f..95728d34dc3 100644 --- a/src/utils/wildcardtree.h +++ b/src/utils/wildcardtree.h @@ -5,35 +5,35 @@ * License: https://github.com/opentibiabr/canary/blob/main/LICENSE * Contributors: https://github.com/opentibiabr/canary/graphs/contributors * Website: https://docs.opentibiabr.org/ -*/ + */ #ifndef SRC_UTILS_WILDCARDTREE_H_ #define SRC_UTILS_WILDCARDTREE_H_ #include "declarations.hpp" -class WildcardTreeNode -{ +class WildcardTreeNode { public: - explicit WildcardTreeNode(bool initBreakpoint) : breakpoint(initBreakpoint) {} - WildcardTreeNode(WildcardTreeNode&& other) = default; + explicit WildcardTreeNode(bool initBreakpoint) : + breakpoint(initBreakpoint) { } + WildcardTreeNode(WildcardTreeNode &&other) = default; // non-copyable - WildcardTreeNode(const WildcardTreeNode&) = delete; - WildcardTreeNode& operator=(const WildcardTreeNode&) = delete; + WildcardTreeNode(const WildcardTreeNode &) = delete; + WildcardTreeNode &operator=(const WildcardTreeNode &) = delete; WildcardTreeNode* getChild(char ch); const WildcardTreeNode* getChild(char ch) const; WildcardTreeNode* addChild(char ch, bool breakpoint); - void insert(const std::string& str); - void remove(const std::string& str); + void insert(const std::string &str); + void remove(const std::string &str); - ReturnValue findOne(const std::string& query, std::string& result) const; + ReturnValue findOne(const std::string &query, std::string &result) const; private: std::map children; bool breakpoint; }; -#endif // SRC_UTILS_WILDCARDTREE_H_ +#endif // SRC_UTILS_WILDCARDTREE_H_