From 910cbec7efd151ef8c91a09921b2f554371dab7e Mon Sep 17 00:00:00 2001 From: codinablack Date: Fri, 17 Jan 2025 22:53:03 -0600 Subject: [PATCH] Initial Rough Draft w/ working compilation and startup. --- src/actions.cpp | 85 +- src/actions.h | 35 +- src/augment.cpp | 2 +- src/augment.h | 10 +- src/augments.cpp | 4 +- src/augments.h | 4 +- src/baseevents.h | 4 +- src/bed.cpp | 50 +- src/bed.h | 26 +- src/chat.cpp | 187 ++-- src/chat.h | 48 +- src/combat.cpp | 196 ++-- src/combat.h | 59 +- src/condition.cpp | 190 ++-- src/condition.h | 136 ++- src/container.cpp | 279 +++-- src/container.h | 104 +- src/creature.cpp | 256 ++--- src/creature.h | 246 +++-- src/creatureevent.cpp | 86 +- src/creatureevent.h | 34 +- src/cylinder.cpp | 10 +- src/cylinder.h | 73 +- src/damagemodifier.h | 2 +- src/depotchest.cpp | 30 +- src/depotchest.h | 18 +- src/depotlocker.cpp | 18 +- src/depotlocker.h | 22 +- src/events.cpp | 232 ++-- src/events.h | 86 +- src/game.cpp | 1560 +++++++++++++------------- src/game.h | 225 ++-- src/globalevent.cpp | 2 +- src/globalevent.h | 9 +- src/guild.cpp | 16 +- src/guild.h | 24 +- src/house.cpp | 195 ++-- src/house.h | 98 +- src/housetile.cpp | 46 +- src/housetile.h | 24 +- src/inbox.cpp | 24 +- src/inbox.h | 18 +- src/iologindata.cpp | 128 +-- src/iologindata.h | 22 +- src/iomap.cpp | 39 +- src/iomap.h | 4 +- src/iomapserialize.cpp | 71 +- src/iomapserialize.h | 8 +- src/iomarket.cpp | 21 +- src/iomarket.h | 2 +- src/item.cpp | 248 ++--- src/item.h | 235 ++-- src/itemloader.h | 2 - src/items.h | 19 + src/luascript.cpp | 2368 +++++++++++++++++----------------------- src/luascript.h | 131 ++- src/mailbox.cpp | 58 +- src/mailbox.h | 46 +- src/map.cpp | 318 +++--- src/map.h | 53 +- src/matrixarea.cpp | 6 +- src/monster.cpp | 356 +++--- src/monster.h | 107 +- src/movement.cpp | 130 +-- src/movement.h | 99 +- src/networkmessage.cpp | 2 +- src/networkmessage.h | 7 +- src/npc.cpp | 218 ++-- src/npc.h | 81 +- src/party.cpp | 161 ++- src/party.h | 47 +- src/player.cpp | 1248 ++++++++++----------- src/player.h | 561 ++++++---- src/protocol.h | 6 +- src/protocolgame.cpp | 162 ++- src/protocolgame.h | 78 +- src/protocollogin.h | 2 +- src/protocolold.h | 2 +- src/protocolstatus.h | 1 + src/quests.cpp | 16 +- src/quests.h | 22 +- src/raids.cpp | 15 +- src/raids.h | 15 +- src/rewardchest.cpp | 14 +- src/rewardchest.h | 19 +- src/scheduler.h | 2 + src/script.cpp | 2 +- src/script.h | 2 +- src/server.cpp | 6 +- src/server.h | 6 +- src/sharedobject.h | 48 + src/spawn.cpp | 44 +- src/spawn.h | 10 +- src/spectators.h | 15 +- src/spells.cpp | 94 +- src/spells.h | 121 +- src/storeinbox.cpp | 21 +- src/storeinbox.h | 17 +- src/talkaction.cpp | 6 +- src/talkaction.h | 8 +- src/tasks.h | 3 +- src/teleport.cpp | 51 +- src/teleport.h | 38 +- src/thing.cpp | 14 +- src/thing.h | 144 ++- src/tile.cpp | 638 +++++------ src/tile.h | 303 +++-- src/trashholder.cpp | 38 +- src/trashholder.h | 31 +- src/vocation.cpp | 4 +- src/vocation.h | 13 +- src/weapons.cpp | 81 +- src/weapons.h | 68 +- 113 files changed, 6963 insertions(+), 6786 deletions(-) create mode 100644 src/sharedobject.h diff --git a/src/actions.cpp b/src/actions.cpp index f65dd475..5bb31ce3 100644 --- a/src/actions.cpp +++ b/src/actions.cpp @@ -224,7 +224,7 @@ bool Actions::registerLuaEvent(Action* event) return false; } -ReturnValue Actions::canUse(const Player* player, const Position& pos) +ReturnValue Actions::canUse(const PlayerConstPtr& player, const Position& pos) { if (pos.x != 0xFFFF) { const Position& playerPos = player->getPosition(); @@ -239,16 +239,16 @@ 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 PlayerConstPtr& player, const Position& pos, const ItemConstPtr& item) { - Action* action = getAction(item); + auto action = getAction(item); if (action) { return action->canExecuteAction(player, pos); } return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUseFar(const Creature* creature, const Position& toPos, bool checkLineOfSight, bool checkFloor) +ReturnValue Actions::canUseFar(const CreatureConstPtr& creature, const Position& toPos, bool checkLineOfSight, bool checkFloor) { if (toPos.x == 0xFFFF) { return RETURNVALUE_NOERROR; @@ -270,7 +270,7 @@ ReturnValue Actions::canUseFar(const Creature* creature, const Position& toPos, return RETURNVALUE_NOERROR; } -Action* Actions::getAction(const Item* item) +Action* Actions::getAction(const ItemConstPtr& item) { if (item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { auto it = uniqueItemMap.find(item->getUniqueId()); @@ -295,15 +295,15 @@ Action* Actions::getAction(const Item* item) return g_spells->getRuneSpell(item->getID()); } -ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey) +ReturnValue Actions::internalUseItem(PlayerPtr player, const Position& pos, uint8_t index, const ItemPtr& item, bool isHotkey) { - if (Door* door = item->getDoor()) { + if (auto door = item->getDoor()) { if (!door->canUse(player)) { return RETURNVALUE_NOTPOSSIBLE; } } - Action* action = getAction(item); + auto action = getAction(item); if (action) { if (action->isScripted()) { if (action->executeUse(player, item, pos, nullptr, pos, isHotkey)) { @@ -318,7 +318,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ } } - if (BedItem* bed = item->getBed()) { + if (BedItemPtr bed = item->getBed()) { if (!bed->canUse(player)) { if (!bed->getHouse()) { return RETURNVALUE_YOUCANNOTUSETHISBED; @@ -336,7 +336,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ g_game.sendOfflineTrainingDialog(player); } else { - BedItem* bedItem = player->getBedItem(); + auto bedItem = player->getBedItem(); if (bedItem) { bedItem->sleep(player); } @@ -346,28 +346,28 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ return RETURNVALUE_NOERROR; } - if (Container* container = item->getContainer()) { - Container* openContainer; + if (auto container = item->getContainer()) { + ContainerPtr openContainer; //depot container - if (DepotLocker* depot = container->getDepotLocker()) { - DepotLocker& myDepotLocker = player->getDepotLocker(); - myDepotLocker.setParent(depot->getParent()->getTile()); - openContainer = &myDepotLocker; + if (auto depot = container->getDepotLocker()) { + DepotLockerPtr& myDepotLocker = player->getDepotLocker(); + myDepotLocker->setParent(depot->getParent()); + openContainer = myDepotLocker; } else { openContainer = container; } uint32_t corpseOwner = container->getCorpseOwner(); if (container->isRewardCorpse()) { - RewardChest& myRewardChest = player->getRewardChest(); + auto& myRewardChest = player->getRewardChest(); - for (Item* subItem : container->getItemList()) { + for (auto subItem : container->getItemList()) { if (subItem->getID() == ITEM_REWARD_CONTAINER) { int64_t rewardDate = subItem->getIntAttr(ITEM_ATTRIBUTE_DATE); bool foundMatch = false; - for (Item* rewardItem : myRewardChest.getItemList()) { + for (auto rewardItem : myRewardChest->getItemList()) { if (rewardItem->getID() == ITEM_REWARD_CONTAINER && rewardItem->getIntAttr(ITEM_ATTRIBUTE_DATE) == rewardDate) { foundMatch = true; break; @@ -385,32 +385,31 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ } // Reward chest - if (RewardChest* rewardchest = container->getRewardChest()) { - RewardChest& myRewardChest = player->getRewardChest(); - myRewardChest.setParent(rewardchest->getParent()->getTile()); + if (auto rewardchest = container->getRewardChest()) { + auto& myRewardChest = player->getRewardChest(); + myRewardChest->setParent(myRewardChest->getParent()); - if (myRewardChest.getItemList().empty()) { + if (myRewardChest->getItemList().empty()) { return RETURNVALUE_REWARDCHESTEMPTY; } - for (Item* rewardItem : myRewardChest.getItemList()) { + for (auto rewardItem : myRewardChest->getItemList()) { if (rewardItem->getID() == ITEM_REWARD_CONTAINER) { - Container* rewardContainer = rewardItem->getContainer(); + auto rewardContainer = rewardItem->getContainer(); if (rewardContainer) { - rewardContainer->setParent(&myRewardChest); + rewardContainer->setParent(myRewardChest); } } } - openContainer = &myRewardChest; + openContainer = myRewardChest; } else if (item->getID() == ITEM_REWARD_CONTAINER) { - RewardChest& myRewardChest = player->getRewardChest(); + auto& myRewardChest = player->getRewardChest(); int64_t rewardDate = item->getIntAttr(ITEM_ATTRIBUTE_DATE); - for (Item* rewardItem : myRewardChest.getItemList()) { + for (auto rewardItem : myRewardChest->getItemList()) { if (rewardItem->getID() == ITEM_REWARD_CONTAINER && rewardItem->getIntAttr(ITEM_ATTRIBUTE_DATE) == rewardDate && rewardItem->getIntAttr(ITEM_ATTRIBUTE_REWARDID) == item->getIntAttr(ITEM_ATTRIBUTE_REWARDID)) { - Container* rewardContainer = rewardItem->getContainer(); - if (rewardContainer) { + if (const auto rewardContainer = rewardItem->getContainer()) { rewardContainer->setParent(container->getRealParent()); openContainer = rewardContainer; } @@ -420,7 +419,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ } //open/close container - int32_t oldContainerId = player->getContainerID(openContainer); + int32_t oldContainerId = player->getContainerID(std::static_pointer_cast(openContainer)); if (oldContainerId == -1) { player->addContainer(index, openContainer); player->onSendContainer(openContainer); @@ -449,7 +448,7 @@ ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_ } -static void showUseHotkeyMessage(Player* player, const Item* item, uint32_t count) +static void showUseHotkeyMessage(const PlayerPtr& player, const ItemConstPtr& item, uint32_t count) { const ItemType& it = Item::items[item->getID()]; if (!it.showCount) { @@ -461,7 +460,7 @@ static void showUseHotkeyMessage(Player* player, const Item* item, uint32_t coun } } -bool Actions::useItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey) +bool Actions::useItem(PlayerPtr player, const Position& pos, uint8_t index, const ItemPtr& item, bool isHotkey) { player->setNextAction(OTSYS_TIME() + g_config.getNumber(ConfigManager::ACTIONS_DELAY_INTERVAL)); @@ -471,7 +470,7 @@ bool Actions::useItem(Player* player, const Position& pos, uint8_t index, Item* } if (g_config.getBoolean(ConfigManager::ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { - if (const HouseTile* const houseTile = dynamic_cast(item->getTile())) { + if (const auto& houseTile = std::dynamic_pointer_cast(item->getTile())) { if (!item->getTopParent()->getCreature() && !houseTile->getHouse()->isInvited(player)) { player->sendCancelMessage(RETURNVALUE_PLAYERISNOTINVITED); return false; @@ -493,8 +492,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*/) +bool Actions::useItemEx(const PlayerPtr& player, const Position& fromPos, const Position& toPos, + uint8_t toStackPos, const ItemPtr& item, bool isHotkey, const CreaturePtr& creature/* = nullptr*/) { player->setNextAction(OTSYS_TIME() + g_config.getNumber(ConfigManager::EX_ACTIONS_DELAY_INTERVAL)); @@ -516,7 +515,7 @@ bool Actions::useItemEx(Player* player, const Position& fromPos, const Position& } if (g_config.getBoolean(ConfigManager::ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { - if (const HouseTile* const houseTile = dynamic_cast(item->getTile())) { + if (const auto& houseTile = std::static_pointer_cast(item->getTile())) { if (!item->getTopParent()->getCreature() && !houseTile->getHouse()->isInvited(player)) { player->sendCancelMessage(RETURNVALUE_PLAYERISNOTINVITED); return false; @@ -560,7 +559,7 @@ bool Action::configureEvent(const pugi::xml_node& node) namespace { -bool enterMarket(Player* player, Item*, const Position&, Thing*, const Position&, bool) +bool enterMarket(const PlayerPtr& player, ItemPtr, const Position&, ThingPtr, const Position&, bool) { player->sendMarketEnter(); return true; @@ -586,7 +585,7 @@ bool Action::loadFunction(const pugi::xml_attribute& attr, bool isScripted) return true; } -ReturnValue Action::canExecuteAction(const Player* player, const Position& toPos) +ReturnValue Action::canExecuteAction(const PlayerConstPtr& player, const Position& toPos) { if (allowFarUse) { return g_actions->canUseFar(player, toPos, checkLineOfSight, checkFloor); @@ -594,7 +593,7 @@ ReturnValue Action::canExecuteAction(const Player* player, const Position& toPos return g_actions->canUse(player, toPos); } -Thing* Action::getTarget(Player* player, Creature* targetCreature, const Position& toPosition, uint8_t toStackPos) const +ThingPtr Action::getTarget(const PlayerPtr& player, const CreaturePtr& targetCreature, const Position& toPosition, uint8_t toStackPos) const { if (targetCreature) { return targetCreature; @@ -602,7 +601,7 @@ Thing* Action::getTarget(Player* player, Creature* targetCreature, const Positio 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) +bool Action::executeUse(const PlayerPtr& player, const ItemPtr& item, const Position& fromPosition, const ThingPtr& target, const Position& toPosition, bool isHotkey) { //onUse(player, item, fromPosition, target, toPosition, isHotkey) if (!scriptInterface->reserveScriptEnv()) { @@ -617,7 +616,7 @@ bool Action::executeUse(Player* player, Item* item, const Position& fromPosition scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushThing(L, item); diff --git a/src/actions.h b/src/actions.h index 7cd99796..e3241f76 100644 --- a/src/actions.h +++ b/src/actions.h @@ -10,7 +10,7 @@ class Action; using Action_ptr = std::unique_ptr; -using ActionFunction = std::function; +using ActionFunction = std::function; class Action : public Event { @@ -21,12 +21,13 @@ class Action : public Event bool loadFunction(const pugi::xml_attribute& attr, bool isScripted) override; //scripting - virtual bool executeUse(Player* player, Item* item, const Position& fromPosition, - Thing* target, const Position& toPosition, bool isHotkey); + virtual bool executeUse(const PlayerPtr& player, const ItemPtr& item, const Position& fromPosition, + const ThingPtr& target, const Position& toPosition, bool isHotkey); bool getAllowFarUse() const { return allowFarUse; } + void setAllowFarUse(bool v) { allowFarUse = v; } @@ -34,6 +35,7 @@ class Action : public Event bool getCheckLineOfSight() const { return checkLineOfSight; } + void setCheckLineOfSight(bool v) { checkLineOfSight = v; } @@ -41,6 +43,7 @@ class Action : public Event bool getCheckFloor() const { return checkFloor; } + void setCheckFloor(bool v) { checkFloor = v; } @@ -48,9 +51,11 @@ class Action : public Event void clearItemIdRange() { return ids.clear(); } + const std::vector& getItemIdRange() const { return ids; } + void addItemId(uint16_t id) { ids.emplace_back(id); } @@ -58,9 +63,11 @@ class Action : public Event void clearUniqueIdRange() { return uids.clear(); } + const std::vector& getUniqueIdRange() const { return uids; } + void addUniqueId(uint16_t id) { uids.emplace_back(id); } @@ -68,18 +75,22 @@ class Action : public Event void clearActionIdRange() { return aids.clear(); } + const std::vector& getActionIdRange() const { return aids; } + void addActionId(uint16_t id) { aids.emplace_back(id); } - virtual ReturnValue canExecuteAction(const Player* player, const Position& toPos); + virtual ReturnValue canExecuteAction(const PlayerConstPtr& player, const Position& toPos); + virtual bool hasOwnErrorHandler() { return false; } - virtual Thing* getTarget(Player* player, Creature* targetCreature, const Position& toPosition, uint8_t toStackPos) const; + + virtual ThingPtr getTarget(const PlayerPtr& player, const CreaturePtr& targetCreature, const Position& toPosition, uint8_t toStackPos) const; ActionFunction function; @@ -104,18 +115,18 @@ class Actions final : public BaseEvents Actions(const Actions&) = delete; Actions& operator=(const Actions&) = delete; - 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(PlayerPtr player, const Position& pos, uint8_t index, const ItemPtr& item, bool isHotkey); + bool useItemEx(const PlayerPtr& player, const Position& fromPos, const Position& toPos, uint8_t toStackPos, const ItemPtr& item, bool isHotkey, const CreaturePtr& 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 PlayerConstPtr& player, const Position& pos); + ReturnValue canUse(const PlayerConstPtr& player, const Position& pos, const ItemConstPtr& item); + ReturnValue canUseFar(const CreatureConstPtr& creature, const Position& toPos, bool checkLineOfSight, bool checkFloor); bool registerLuaEvent(Action* event); void clear(bool fromLua) override final; private: - ReturnValue internalUseItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey); + ReturnValue internalUseItem(PlayerPtr player, const Position& pos, uint8_t index, const ItemPtr& item, bool isHotkey); LuaScriptInterface& getScriptInterface() override; std::string_view getScriptBaseName() const override { return "actions"; } @@ -127,7 +138,7 @@ class Actions final : public BaseEvents ActionUseMap uniqueItemMap; ActionUseMap actionItemMap; - Action* getAction(const Item* item); + Action* getAction(const ItemConstPtr& item); void clearMap(ActionUseMap& map, bool fromLua); LuaScriptInterface scriptInterface; diff --git a/src/augment.cpp b/src/augment.cpp index b3c09f6b..efa8ca6b 100644 --- a/src/augment.cpp +++ b/src/augment.cpp @@ -8,7 +8,7 @@ #include "augment.h" -Augment::Augment(std::string name, std::string description) : m_name(name), m_description(description) { +Augment::Augment(const std::string& name, const std::string& description) : m_name(name), m_description(description) { } diff --git a/src/augment.h b/src/augment.h index 821807f1..e70be254 100644 --- a/src/augment.h +++ b/src/augment.h @@ -15,7 +15,7 @@ class Augment : public std::enable_shared_from_this { public: Augment() = default; - Augment(std::string name, std::string description = ""); + Augment(const std::string& name, const std::string& description = ""); Augment(std::shared_ptr& original); ~Augment() = default; @@ -30,8 +30,8 @@ class Augment : public std::enable_shared_from_this { const std::string getName() const; const std::string getDescription() const; - void setName(std::string name); - void setDescription(std::string description); + void setName(const std::string& name); + void setDescription(const std::string& description); static std::shared_ptr MakeAugment(std::string augmentName, std::string description = ""); static std::shared_ptr MakeAugment(std::shared_ptr& originalPointer); @@ -146,11 +146,11 @@ inline const std::string Augment::getDescription() const return m_description; } -inline void Augment::setName(std::string name) { +inline void Augment::setName(const std::string& name) { m_name = name; } -inline void Augment::setDescription(std::string description) { +inline void Augment::setDescription(const std::string& description) { m_description = description; } diff --git a/src/augments.cpp b/src/augments.cpp index 9ca2cc11..017fd153 100644 --- a/src/augments.cpp +++ b/src/augments.cpp @@ -331,7 +331,7 @@ void Augments::AddAugment(std::shared_ptr augment) { } } -void Augments::RemoveAugment(std::shared_ptr augment) { +void Augments::RemoveAugment(const std::shared_ptr& augment) { auto it = global_augments.find(augment->getName().data()); if (it != global_augments.end()) { global_augments.erase(it); @@ -345,7 +345,7 @@ void Augments::RemoveAugment(std::string_view augName) { } } -void Augments::RemoveAugment(std::string augName) { +void Augments::RemoveAugment(const std::string& augName) { auto it = global_augments.find(augName); if (it != global_augments.end()) { global_augments.erase(it); diff --git a/src/augments.h b/src/augments.h index 81f06760..8a85d84f 100644 --- a/src/augments.h +++ b/src/augments.h @@ -38,9 +38,9 @@ class Augments { static void clearAll(); static void reload(); static void AddAugment(std::shared_ptr augment); - static void RemoveAugment(std::shared_ptr augment); + static void RemoveAugment(const std::shared_ptr& augment); static void RemoveAugment(std::string_view augName); - static void RemoveAugment(std::string augName); + static void RemoveAugment(const std::string& augName); static std::shared_ptr GetAugment(std::string_view augName); }; diff --git a/src/baseevents.h b/src/baseevents.h index ed738901..1fe3ef24 100644 --- a/src/baseevents.h +++ b/src/baseevents.h @@ -20,6 +20,7 @@ class Event bool checkScript(const std::string& basePath, const std::string& scriptsName, const std::string& scriptFile) const; bool loadScript(const std::string& scriptFile); bool loadCallback(); + virtual bool loadFunction(const pugi::xml_attribute&, bool) { return false; } @@ -31,7 +32,8 @@ class Event bool scripted = false; bool fromLua = false; - int32_t getScriptId() { + int32_t getScriptId() const + { return scriptId; } diff --git a/src/bed.cpp b/src/bed.cpp index 1a72499e..95c8b77f 100644 --- a/src/bed.cpp +++ b/src/bed.cpp @@ -28,7 +28,7 @@ Attr_ReadValue BedItem::readAttr(AttrTypes_t attr, PropStream& propStream) std::string name = IOLoginData::getNameByGuid(guid); if (!name.empty()) { setSpecialDescription(name + " is sleeping there."); - g_game.setBedSleeper(this, guid); + g_game.setBedSleeper(this->getBed(), guid); sleeperGUID = guid; } } @@ -65,19 +65,19 @@ void BedItem::serializeAttr(PropWriteStream& propWriteStream) const } } -BedItem* BedItem::getNextBedItem() const +BedItemPtr BedItem::getNextBedItem() const { Direction dir = Item::items[id].bedPartnerDir; Position targetPos = getNextPosition(dir, getPosition()); - Tile* tile = g_game.map.getTile(targetPos); + auto tile = g_game.map.getTile(targetPos); if (!tile) { return nullptr; } return tile->getBedItem(); } -bool BedItem::canUse(Player* player) +bool BedItem::canUse(PlayerPtr player) const { if (!player || !house || !player->isPremium() || player->getZone() != ZONE_PROTECTION) { return false; @@ -91,18 +91,18 @@ bool BedItem::canUse(Player* player) return true; } - Player sleeper(nullptr); - if (!IOLoginData::loadPlayerById(&sleeper, sleeperGUID)) { + PlayerPtr sleeper(nullptr); + if (!IOLoginData::loadPlayerById(sleeper, sleeperGUID)) { return false; } - if (house->getHouseAccessLevel(&sleeper) > house->getHouseAccessLevel(player)) { + if (house->getHouseAccessLevel(sleeper) > house->getHouseAccessLevel(player)) { return false; } return true; } -bool BedItem::trySleep(Player* player) +bool BedItem::trySleep(const PlayerPtr& player) { if (!house || player->isRemoved()) { return false; @@ -119,7 +119,7 @@ bool BedItem::trySleep(Player* player) return true; } -bool BedItem::sleep(Player* player) +bool BedItem::sleep(const PlayerPtr& player) { if (!house) { return false; @@ -129,7 +129,7 @@ bool BedItem::sleep(Player* player) return false; } - BedItem* nextBedItem = getNextBedItem(); + auto nextBedItem = getNextBedItem(); internalSetSleeper(player); @@ -138,10 +138,12 @@ bool BedItem::sleep(Player* player) } // update the bedSleepersMap - g_game.setBedSleeper(this, player->getGUID()); + g_game.setBedSleeper(this->getBed(), player->getGUID()); // make the player walk onto the bed - g_game.map.moveCreature(*player, *getTile()); + auto creature = player->getCreature(); + auto tile = getTile(); + g_game.map.moveCreature(creature, tile); // display 'Zzzz'/sleep effect g_game.addMagicEffect(player->getPosition(), CONST_ME_SLEEP); @@ -158,7 +160,7 @@ bool BedItem::sleep(Player* player) return true; } -void BedItem::wakeUp(Player* player) +void BedItem::wakeUp(const PlayerPtr& player) { if (!house) { return; @@ -166,10 +168,10 @@ void BedItem::wakeUp(Player* player) if (sleeperGUID != 0) { if (!player) { - Player regenPlayer(nullptr); - if (IOLoginData::loadPlayerById(®enPlayer, sleeperGUID)) { - regeneratePlayer(®enPlayer); - IOLoginData::savePlayer(®enPlayer); + PlayerPtr regenPlayer(nullptr); + if (IOLoginData::loadPlayerById(regenPlayer, sleeperGUID)) { + regeneratePlayer(regenPlayer); + IOLoginData::savePlayer(regenPlayer); } } else { regeneratePlayer(player); @@ -180,7 +182,7 @@ void BedItem::wakeUp(Player* player) // update the bedSleepersMap g_game.removeBedSleeper(sleeperGUID); - BedItem* nextBedItem = getNextBedItem(); + BedItemPtr nextBedItem = getNextBedItem(); // unset sleep info internalRemoveSleeper(); @@ -197,11 +199,11 @@ void BedItem::wakeUp(Player* player) } } -void BedItem::regeneratePlayer(Player* player) const +void BedItem::regeneratePlayer(const PlayerPtr& player) const { const uint32_t sleptTime = time(nullptr) - sleepStart; - Condition* condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); + auto condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); if (condition) { uint32_t regen; if (condition->getTicks() != -1) { @@ -224,25 +226,25 @@ void BedItem::regeneratePlayer(Player* player) const player->changeSoul(soulRegen); } -void BedItem::updateAppearance(const Player* player) +void BedItem::updateAppearance(const PlayerConstPtr& player) { const ItemType& it = Item::items[id]; if (it.type == ITEM_TYPE_BED) { if (player && it.transformToOnUse[player->getSex()] != 0) { const ItemType& newType = Item::items[it.transformToOnUse[player->getSex()]]; if (newType.type == ITEM_TYPE_BED) { - g_game.transformItem(this, it.transformToOnUse[player->getSex()]); + g_game.transformItem(getItem(), it.transformToOnUse[player->getSex()]); } } else if (it.transformToFree != 0) { const ItemType& newType = Item::items[it.transformToFree]; if (newType.type == ITEM_TYPE_BED) { - g_game.transformItem(this, it.transformToFree); + g_game.transformItem(getItem(), it.transformToFree); } } } } -void BedItem::internalSetSleeper(const Player* player) +void BedItem::internalSetSleeper(const PlayerConstPtr& player) { std::string desc_str = player->getName() + " is sleeping there."; diff --git a/src/bed.h b/src/bed.h index f6b465c0..ce2d8e69 100644 --- a/src/bed.h +++ b/src/bed.h @@ -14,11 +14,12 @@ class BedItem final : public Item public: explicit BedItem(uint16_t id); - BedItem* getBed() override { - return this; + BedItemPtr getBed() override { + return dynamic_shared_this(); } - const BedItem* getBed() const override { - return this; + + BedItemConstPtr getBed() const override { + return dynamic_shared_this(); } Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; @@ -35,22 +36,23 @@ class BedItem final : public Item House* getHouse() const { return house; } + void setHouse(House* h) { house = h; } - bool canUse(Player* player); + bool canUse(PlayerPtr player) const; - bool trySleep(Player* player); - bool sleep(Player* player); - void wakeUp(Player* player); + bool trySleep(const PlayerPtr& player); + bool sleep(const PlayerPtr& player); + void wakeUp(const PlayerPtr& player); - BedItem* getNextBedItem() const; + BedItemPtr getNextBedItem() const; private: - void updateAppearance(const Player* player); - void regeneratePlayer(Player* player) const; - void internalSetSleeper(const Player* player); + void updateAppearance(const PlayerConstPtr& player); + void regeneratePlayer(const PlayerPtr& player) const; + void internalSetSleeper(const PlayerConstPtr& player); void internalRemoveSleeper(); House* house = nullptr; diff --git a/src/chat.cpp b/src/chat.cpp index 2db44c92..36f719a9 100644 --- a/src/chat.cpp +++ b/src/chat.cpp @@ -18,7 +18,7 @@ bool PrivateChatChannel::isInvited(uint32_t guid) const if (guid == getOwner()) { return true; } - return invites.find(guid) != invites.end(); + return invites.contains(guid); } bool PrivateChatChannel::removeInvite(uint32_t guid) @@ -26,49 +26,49 @@ bool PrivateChatChannel::removeInvite(uint32_t guid) return invites.erase(guid) != 0; } -void PrivateChatChannel::invitePlayer(const Player& player, Player& invitePlayer) +void PrivateChatChannel::invitePlayer(const PlayerConstPtr& player, const PlayerPtr& invitePlayer) { - auto result = invites.emplace(invitePlayer.getGUID(), &invitePlayer); + auto result = invites.emplace(invitePlayer->getGUID(), invitePlayer); if (!result.second) { return; } - invitePlayer.sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} invites you to {:s} private chat channel.", player.getName(), player.getSex() == PLAYERSEX_FEMALE ? "her" : "his")); + invitePlayer->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} invites you to {:s} private chat channel.", player->getName(), player->getSex() == PLAYERSEX_FEMALE ? "her" : "his")); - player.sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been invited.", invitePlayer.getName())); + player->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been invited.", invitePlayer->getName())); for (const auto& it : users) { - it.second->sendChannelEvent(id, invitePlayer.getName(), CHANNELEVENT_INVITE); + it.second->sendChannelEvent(id, invitePlayer->getName(), CHANNELEVENT_INVITE); } } -void PrivateChatChannel::excludePlayer(const Player& player, Player& excludePlayer) +void PrivateChatChannel::excludePlayer(const PlayerConstPtr& player, const PlayerPtr& excludePlayer) { - if (!removeInvite(excludePlayer.getGUID())) { + if (!removeInvite(excludePlayer->getGUID())) { return; } - + removeUser(excludePlayer); - player.sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been excluded.", excludePlayer.getName())); + player->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been excluded.", excludePlayer->getName())); - excludePlayer.sendClosePrivate(id); + excludePlayer->sendClosePrivate(id); - for (const auto& it : users) { - it.second->sendChannelEvent(id, excludePlayer.getName(), CHANNELEVENT_EXCLUDE); + for (const auto& val : users | std::views::values) { + val->sendChannelEvent(id, excludePlayer->getName(), CHANNELEVENT_EXCLUDE); } } void PrivateChatChannel::closeChannel() const { - for (const auto& it : users) { - it.second->sendClosePrivate(id); + for (const auto& val : users | std::views::values) { + val->sendClosePrivate(id); } } -bool ChatChannel::addUser(Player& player) +bool ChatChannel::addUser(const PlayerPtr& player) { - if (users.find(player.getID()) != users.end()) { + if (users.contains(player->getID())) { return false; } @@ -78,25 +78,25 @@ bool ChatChannel::addUser(Player& player) // TODO: Move to script when guild channels can be scripted if (id == CHANNEL_GUILD) { - Guild* guild = player.getGuild(); + auto guild = player->getGuild(); if (guild && !guild->getMotd().empty()) { - g_scheduler.addEvent(createSchedulerTask(150, [playerID = player.getID()]() { g_game.sendGuildMotd(playerID); })); + g_scheduler.addEvent(createSchedulerTask(150, [playerID = player->getID()]() { g_game.sendGuildMotd(playerID); })); } } if (!publicChannel) { - for (const auto& it : users) { - it.second->sendChannelEvent(id, player.getName(), CHANNELEVENT_JOIN); + for (const auto& val : users | std::views::values) { + val->sendChannelEvent(id, player->getName(), CHANNELEVENT_JOIN); } } - users[player.getID()] = &player; + users[player->getID()] = player; return true; } -bool ChatChannel::removeUser(const Player& player) +bool ChatChannel::removeUser(const PlayerConstPtr& player) { - auto iter = users.find(player.getID()); + auto iter = users.find(player->getID()); if (iter == users.end()) { return false; } @@ -104,8 +104,8 @@ bool ChatChannel::removeUser(const Player& player) users.erase(iter); if (!publicChannel) { - for (const auto& it : users) { - it.second->sendChannelEvent(id, player.getName(), CHANNELEVENT_LEAVE); + for (const auto& val : users | std::views::values) { + val->sendChannelEvent(id, player->getName(), CHANNELEVENT_LEAVE); } } @@ -113,30 +113,30 @@ bool ChatChannel::removeUser(const Player& player) return true; } -bool ChatChannel::hasUser(const Player& player) { - return users.find(player.getID()) != users.end(); +bool ChatChannel::hasUser(const PlayerConstPtr& player) const { + return users.contains(player->getID()); } void ChatChannel::sendToAll(const std::string& message, SpeakClasses type) const { - for (const auto& it : users) { - it.second->sendChannelMessage("", message, type, id); + for (const auto& val : users | std::views::values) { + val->sendChannelMessage("", message, type, id); } } -bool ChatChannel::talk(const Player& fromPlayer, SpeakClasses type, const std::string& text) +bool ChatChannel::talk(const PlayerConstPtr& fromPlayer, SpeakClasses type, const std::string& text) { - if (users.find(fromPlayer.getID()) == users.end()) { + if (!users.contains(fromPlayer->getID())) { return false; } - for (const auto& it : users) { - it.second->sendToChannel(&fromPlayer, type, text, id); + for (const auto& val : users | std::views::values) { + val->sendToChannel(fromPlayer, type, text, id); } return true; } -bool ChatChannel::executeCanJoinEvent(const Player& player) +bool ChatChannel::executeCanJoinEvent(const PlayerConstPtr& player) const { if (canJoinEvent == -1) { return true; @@ -155,13 +155,13 @@ bool ChatChannel::executeCanJoinEvent(const Player& player) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(canJoinEvent); - LuaScriptInterface::pushUserdata(L, &player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnJoinEvent(const Player& player) +bool ChatChannel::executeOnJoinEvent(const PlayerConstPtr& player) const { if (onJoinEvent == -1) { return true; @@ -180,13 +180,13 @@ bool ChatChannel::executeOnJoinEvent(const Player& player) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(onJoinEvent); - LuaScriptInterface::pushUserdata(L, &player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnLeaveEvent(const Player& player) +bool ChatChannel::executeOnLeaveEvent(const PlayerConstPtr& player) const { if (onLeaveEvent == -1) { return true; @@ -205,13 +205,13 @@ bool ChatChannel::executeOnLeaveEvent(const Player& player) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(onLeaveEvent); - LuaScriptInterface::pushUserdata(L, &player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnSpeakEvent(const Player& player, SpeakClasses& type, const std::string& message) +bool ChatChannel::executeOnSpeakEvent(const PlayerConstPtr& player, SpeakClasses& type, const std::string& message) const { if (onSpeakEvent == -1) { return true; @@ -230,7 +230,7 @@ bool ChatChannel::executeOnSpeakEvent(const Player& player, SpeakClasses& type, lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(onSpeakEvent); - LuaScriptInterface::pushUserdata(L, &player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, type); @@ -298,8 +298,8 @@ bool Chat::load() } UsersMap tempUserMap = std::move(channel.users); - for (const auto& pair : tempUserMap) { - channel.addUser(*pair.second); + for (const auto& val : tempUserMap | std::views::values) { + channel.addUser(val); } continue; } @@ -323,7 +323,7 @@ bool Chat::load() return true; } -ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) +ChatChannel* Chat::createChannel(const PlayerConstPtr& player, uint16_t channelId) { if (getChannel(player, channelId)) { return nullptr; @@ -331,7 +331,7 @@ ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) switch (channelId) { case CHANNEL_GUILD: { - Guild* guild = player.getGuild(); + auto guild = player->getGuild(); if (guild) { auto ret = guildChannels.emplace(std::make_pair(guild->getId(), ChatChannel(channelId, guild->getName()))); return &ret.first->second; @@ -340,7 +340,7 @@ ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) } case CHANNEL_PARTY: { - Party* party = player.getParty(); + auto party = player->getParty(); if (party) { auto ret = partyChannels.emplace(std::make_pair(party, ChatChannel(channelId, "Party"))); return &ret.first->second; @@ -350,16 +350,16 @@ ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) case CHANNEL_PRIVATE: { //only 1 private channel for each premium player - if (!player.isPremium() || getPrivateChannel(player)) { + if (!player->isPremium() || getPrivateChannel(player)) { return nullptr; } //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"))); + 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; - newChannel.setOwner(player.getGUID()); + newChannel.setOwner(player->getGUID()); return &newChannel; } } @@ -372,16 +372,16 @@ ChatChannel* Chat::createChannel(const Player& player, uint16_t channelId) return nullptr; } -bool Chat::deleteChannel(const Player& player, uint16_t channelId) +bool Chat::deleteChannel(const PlayerConstPtr& player, uint16_t channelId) { switch (channelId) { case CHANNEL_GUILD: { - Guild* guild = player.getGuild(); + auto guild = player->getGuild(); if (!guild) { return false; } - auto it = guildChannels.find(guild->getId()); + const auto it = guildChannels.find(guild->getId()); if (it == guildChannels.end()) { return false; } @@ -391,12 +391,12 @@ bool Chat::deleteChannel(const Player& player, uint16_t channelId) } case CHANNEL_PARTY: { - Party* party = player.getParty(); + auto party = player->getParty(); if (!party) { return false; } - auto it = partyChannels.find(party); + const auto it = partyChannels.find(party); if (it == partyChannels.end()) { return false; } @@ -406,7 +406,7 @@ bool Chat::deleteChannel(const Player& player, uint16_t channelId) } default: { - auto it = privateChannels.find(channelId); + const auto it = privateChannels.find(channelId); if (it == privateChannels.end()) { return false; } @@ -420,7 +420,7 @@ bool Chat::deleteChannel(const Player& player, uint16_t channelId) return true; } -ChatChannel* Chat::addUserToChannel(Player& player, uint16_t channelId) +ChatChannel* Chat::addUserToChannel(const PlayerPtr& player, uint16_t channelId) { ChatChannel* channel = getChannel(player, channelId); if (channel && channel->addUser(player)) { @@ -429,39 +429,39 @@ ChatChannel* Chat::addUserToChannel(Player& player, uint16_t channelId) return nullptr; } -bool Chat::removeUserFromChannel(const Player& player, uint16_t channelId) +bool Chat::removeUserFromChannel(const PlayerConstPtr& player, uint16_t channelId) { ChatChannel* channel = getChannel(player, channelId); if (!channel || !channel->removeUser(player)) { return false; } - if (channel->getOwner() == player.getGUID()) { + if (channel->getOwner() == player->getGUID()) { deleteChannel(player, channelId); } return true; } -void Chat::removeUserFromAllChannels(const Player& player) +void Chat::removeUserFromAllChannels(const PlayerConstPtr& player) { - for (auto& it : normalChannels) { - it.second.removeUser(player); + for (auto& val : normalChannels | std::views::values) { + val.removeUser(player); } - for (auto& it : partyChannels) { - it.second.removeUser(player); + for (auto& val : partyChannels | std::views::values) { + val.removeUser(player); } - for (auto& it : guildChannels) { - it.second.removeUser(player); + for (auto& val : guildChannels | std::views::values) { + val.removeUser(player); } auto it = privateChannels.begin(); while (it != privateChannels.end()) { PrivateChatChannel* channel = &it->second; - channel->removeInvite(player.getGUID()); + channel->removeInvite(player->getGUID()); channel->removeUser(player); - if (channel->getOwner() == player.getGUID()) { + if (channel->getOwner() == player->getGUID()) { channel->closeChannel(); it = privateChannels.erase(it); } else { @@ -470,15 +470,15 @@ 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 PlayerConstPtr& player, SpeakClasses type, const std::string& text, uint16_t channelId) { - ChatChannel* channel = getChannel(player, channelId); + const auto channel = getChannel(player, channelId); if (!channel) { return false; } if (channelId == CHANNEL_GUILD) { - GuildRank_ptr rank = player.getGuildRank(); + GuildRank_ptr rank = player->getGuildRank(); if (rank && rank->level > 1) { type = TALKTYPE_CHANNEL_O; } else if (type != TALKTYPE_CHANNEL_Y) { @@ -495,12 +495,11 @@ 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 PlayerConstPtr& player) { ChannelList list; - if (player.getGuild()) { - ChatChannel* channel = getChannel(player, CHANNEL_GUILD); - if (channel) { + if (player->getGuild()) { + if (auto channel = getChannel(player, CHANNEL_GUILD)) { list.push_back(channel); } else { channel = createChannel(player, CHANNEL_GUILD); @@ -510,9 +509,8 @@ ChannelList Chat::getChannelList(const Player& player) } } - if (player.getParty()) { - ChatChannel* channel = getChannel(player, CHANNEL_PARTY); - if (channel) { + if (player->getParty()) { + if (auto channel = getChannel(player, CHANNEL_PARTY)) { list.push_back(channel); } else { channel = createChannel(player, CHANNEL_PARTY); @@ -522,17 +520,16 @@ ChannelList Chat::getChannelList(const Player& player) } } - for (const auto& it : normalChannels) { - ChatChannel* channel = getChannel(player, it.first); - if (channel) { + for (const auto& key : normalChannels | std::views::keys) { + if (auto channel = getChannel(player, key)) { list.push_back(channel); } } bool hasPrivate = false; - for (auto& it : privateChannels) { - if (PrivateChatChannel* channel = &it.second) { - uint32_t guid = player.getGUID(); + for (auto& val : privateChannels | std::views::values) { + if (const auto channel = &val) { + uint32_t guid = player->getGUID(); if (channel->isInvited(guid)) { list.push_back(channel); } @@ -543,19 +540,18 @@ ChannelList Chat::getChannelList(const Player& player) } } - if (!hasPrivate && player.isPremium()) { + if (!hasPrivate && player->isPremium()) { list.push_front(&dummyPrivate); } return list; } -ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) +ChatChannel* Chat::getChannel(const PlayerConstPtr& player, uint16_t channelId) { switch (channelId) { case CHANNEL_GUILD: { - Guild* guild = player.getGuild(); - if (guild) { - auto it = guildChannels.find(guild->getId()); + if (auto guild = player->getGuild()) { + const auto it = guildChannels.find(guild->getId()); if (it != guildChannels.end()) { return &it->second; } @@ -564,9 +560,8 @@ ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) } case CHANNEL_PARTY: { - Party* party = player.getParty(); - if (party) { - auto it = partyChannels.find(party); + if (auto party = player->getParty()) { + const auto it = partyChannels.find(party); if (it != partyChannels.end()) { return &it->second; } @@ -575,7 +570,7 @@ ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) } default: { - auto it = normalChannels.find(channelId); + const auto it = normalChannels.find(channelId); if (it != normalChannels.end()) { ChatChannel& channel = it->second; if (!channel.executeCanJoinEvent(player)) { @@ -584,7 +579,7 @@ ChatChannel* Chat::getChannel(const Player& player, uint16_t channelId) return &channel; } else { auto it2 = privateChannels.find(channelId); - if (it2 != privateChannels.end() && it2->second.isInvited(player.getGUID())) { + if (it2 != privateChannels.end() && it2->second.isInvited(player->getGUID())) { return &it2->second; } } @@ -612,10 +607,10 @@ ChatChannel* Chat::getChannelById(uint16_t channelId) return &it->second; } -PrivateChatChannel* Chat::getPrivateChannel(const Player& player) +PrivateChatChannel* Chat::getPrivateChannel(const PlayerConstPtr& player) { for (auto& it : privateChannels) { - if (it.second.getOwner() == player.getGUID()) { + if (it.second.getOwner() == player->getGUID()) { return &it.second; } } diff --git a/src/chat.h b/src/chat.h index 292c703f..30eb675b 100644 --- a/src/chat.h +++ b/src/chat.h @@ -10,8 +10,8 @@ class Party; class Player; -using UsersMap = std::map; -using InvitedMap = std::map; +using UsersMap = std::map; +using InvitedMap = std::map; class ChatChannel { @@ -22,22 +22,25 @@ class ChatChannel virtual ~ChatChannel() = default; - bool addUser(Player& player); - bool removeUser(const Player& player); - bool hasUser(const Player& player); + bool addUser(const PlayerPtr& player); + bool removeUser(const PlayerConstPtr& player); + bool hasUser( const PlayerConstPtr& player) const; - bool talk(const Player& fromPlayer, SpeakClasses type, const std::string& text); + bool talk(const PlayerConstPtr& fromPlayer, SpeakClasses type, const std::string& text); void sendToAll(const std::string& message, SpeakClasses type) const; const std::string& getName() const { return name; } + uint16_t getId() const { return id; } + const UsersMap& getUsers() const { return users; } + virtual const InvitedMap* getInvitedUsers() const { return nullptr; } @@ -48,10 +51,10 @@ class ChatChannel 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 PlayerConstPtr& player) const; + bool executeCanJoinEvent(const PlayerConstPtr& player) const; + bool executeOnLeaveEvent(const PlayerConstPtr& player) const; + bool executeOnSpeakEvent(const PlayerConstPtr& player, SpeakClasses& type, const std::string& message) const; protected: UsersMap users; @@ -74,19 +77,20 @@ class ChatChannel class PrivateChatChannel final : public ChatChannel { public: - PrivateChatChannel(uint16_t channelId, std::string channelName) : ChatChannel(channelId, channelName) {} + PrivateChatChannel(uint16_t channelId, const std::string& channelName) : ChatChannel(channelId, channelName) {} uint32_t getOwner() const override { return owner; } + void setOwner(uint32_t owner) { this->owner = owner; } bool isInvited(uint32_t guid) const; - void invitePlayer(const Player& player, Player& invitePlayer); - void excludePlayer(const Player& player, Player& excludePlayer); + void invitePlayer(const PlayerConstPtr& player, const PlayerPtr& invitePlayer); + void excludePlayer(const PlayerConstPtr& player, const PlayerPtr& excludePlayer); bool removeInvite(uint32_t guid); @@ -114,21 +118,21 @@ class Chat bool load(); - ChatChannel* createChannel(const Player& player, uint16_t channelId); - bool deleteChannel(const Player& player, uint16_t channelId); + ChatChannel* createChannel(const PlayerConstPtr& player, uint16_t channelId); + bool deleteChannel(const PlayerConstPtr& 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(const PlayerPtr& player, uint16_t channelId); + bool removeUserFromChannel(const PlayerConstPtr& player, uint16_t channelId); + void removeUserFromAllChannels(const PlayerConstPtr& player); - bool talkToChannel(const Player& player, SpeakClasses type, const std::string& text, uint16_t channelId); + bool talkToChannel(const PlayerConstPtr& player, SpeakClasses type, const std::string& text, uint16_t channelId); - ChannelList getChannelList(const Player& player); + ChannelList getChannelList(const PlayerConstPtr& player); - ChatChannel* getChannel(const Player& player, uint16_t channelId); + ChatChannel* getChannel(const PlayerConstPtr& player, uint16_t channelId); ChatChannel* getChannelById(uint16_t channelId); ChatChannel* getGuildChannelById(uint32_t guildId); - PrivateChatChannel* getPrivateChannel(const Player& player); + PrivateChatChannel* getPrivateChannel(const PlayerConstPtr& player); LuaScriptInterface* getScriptInterface() { return &scriptInterface; diff --git a/src/combat.cpp b/src/combat.cpp index 57077a3e..eadfa051 100644 --- a/src/combat.cpp +++ b/src/combat.cpp @@ -17,11 +17,11 @@ extern Weapons* g_weapons; extern ConfigManager g_config; extern Events* g_events; -std::vector getList(const MatrixArea& area, const Position& targetPos, const Direction dir) +std::vector getList(const MatrixArea& area, const Position& targetPos, const Direction dir) { auto casterPos = getNextPosition(dir, targetPos); - std::vector vec; + std::vector vec; auto center = area.getCenter(); @@ -30,9 +30,9 @@ std::vector getList(const MatrixArea& area, const Position& targetPos, co for (uint32_t col = 0; col < area.getCols(); ++col, ++tmpPos.x) { if (area(row, col)) { if (g_game.isSightClear(casterPos, tmpPos, true)) { - Tile* tile = g_game.map.getTile(tmpPos); + auto tile = g_game.map.getTile(tmpPos); if (!tile) { - tile = new StaticTile(tmpPos.x, tmpPos.y, tmpPos.z); + tile = std::make_shared(tmpPos.x, tmpPos.y, tmpPos.z); g_game.map.setTile(tmpPos, tile); } vec.push_back(tile); @@ -44,7 +44,7 @@ std::vector getList(const MatrixArea& area, const Position& targetPos, co return vec; } -std::vector getCombatArea(const Position& centerPos, const Position& targetPos, const AreaCombat* area) +std::vector getCombatArea(const Position& centerPos, const Position& targetPos, const AreaCombat* area) { if (targetPos.z >= MAP_MAX_LAYERS) { return {}; @@ -54,15 +54,15 @@ std::vector getCombatArea(const Position& centerPos, const Position& targ return getList(area->getArea(centerPos, targetPos), targetPos, getDirectionTo(targetPos, centerPos)); } - Tile* tile = g_game.map.getTile(targetPos); + auto tile = g_game.map.getTile(targetPos); if (!tile) { - tile = new StaticTile(targetPos.x, targetPos.y, targetPos.z); + tile = std::make_shared(targetPos.x, targetPos.y, targetPos.z); g_game.map.setTile(targetPos, tile); } return {tile}; } -CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const +CombatDamage Combat::getCombatDamage(const CreaturePtr& creature, const CreaturePtr& target) const { CombatDamage damage; damage.origin = params.origin; @@ -76,14 +76,14 @@ CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const int32_t min, max; if (creature->getCombatValues(min, max)) { damage.primary.value = normal_random(min, max); - } else if (Player* player = creature->getPlayer()) { + } else if (auto player = creature->getPlayer()) { if (params.valueCallback) { params.valueCallback->getMinMaxValues(player, damage); } else if (formulaType == COMBAT_FORMULA_LEVELMAGIC) { int32_t levelFormula = player->getLevel() * 2 + player->getMagicLevel() * 3; damage.primary.value = normal_random(std::fma(levelFormula, mina, minb), std::fma(levelFormula, maxa, maxb)); } else if (formulaType == COMBAT_FORMULA_SKILL) { - Item* tool = player->getWeapon(); + auto tool = player->getWeapon(); const Weapon* weapon = g_weapons->getWeapon(tool); if (weapon) { damage.primary.value = normal_random(minb, std::fma(weapon->getWeaponDamage(player, target, tool, true), maxa, maxb)); @@ -98,7 +98,7 @@ CombatDamage Combat::getCombatDamage(Creature* creature, Creature* target) const return damage; } -CombatType_t Combat::ConditionToDamageType(ConditionType_t type) +CombatType_t Combat::ConditionToDamageType(const ConditionType_t type) { switch (type) { case CONDITION_FIRE: @@ -132,7 +132,7 @@ CombatType_t Combat::ConditionToDamageType(ConditionType_t type) return COMBAT_NONE; } -ConditionType_t Combat::DamageToConditionType(CombatType_t type) +ConditionType_t Combat::DamageToConditionType(const CombatType_t type) { switch (type) { case COMBAT_FIREDAMAGE: @@ -164,7 +164,7 @@ ConditionType_t Combat::DamageToConditionType(CombatType_t type) } } -bool Combat::isPlayerCombat(const Creature* target) +bool Combat::isPlayerCombat(const CreatureConstPtr& target) { if (target->getPlayer()) { return true; @@ -177,7 +177,7 @@ bool Combat::isPlayerCombat(const Creature* target) return false; } -ReturnValue Combat::canTargetCreature(Player* attacker, Creature* target) +ReturnValue Combat::canTargetCreature(const PlayerPtr& attacker, const CreaturePtr& target) { if (attacker == target) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; @@ -212,9 +212,10 @@ ReturnValue Combat::canTargetCreature(Player* attacker, Creature* target) return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE; } } - - if (target->getPlayer()) { - if (isProtected(attacker, target->getPlayer())) { + // we use implicit conversion here to get the const + // auto won't work for that as it will not know we need the const version + if (PlayerConstPtr p_target = target->getPlayer()) { + if (isProtected(attacker, p_target)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } @@ -226,7 +227,7 @@ ReturnValue Combat::canTargetCreature(Player* attacker, Creature* target) return Combat::canDoCombat(attacker, target); } -ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) +ReturnValue Combat::canDoCombat(const CreaturePtr& caster, const TilePtr& tile, bool aggressive) { if (tile->hasProperty(CONST_PROP_BLOCKPROJECTILE)) { return RETURNVALUE_NOTENOUGHROOM; @@ -249,7 +250,7 @@ ReturnValue Combat::canDoCombat(Creature* caster, Tile* tile, bool aggressive) return RETURNVALUE_FIRSTGOUPSTAIRS; } - if (const Player* player = caster->getPlayer()) { + if (const auto player = caster->getPlayer()) { if (player->hasFlag(PlayerFlag_IgnoreProtectionZone)) { return RETURNVALUE_NOERROR; } @@ -264,12 +265,12 @@ 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 CreatureConstPtr& attacker, const CreatureConstPtr& target) { return attacker->getZone() == ZONE_PVP && target->getZone() == ZONE_PVP; } -bool Combat::isProtected(const Player* attacker, const Player* target) +bool Combat::isProtected(const PlayerConstPtr& attacker, const PlayerConstPtr& target) { uint32_t protectionLevel = g_config.getNumber(ConfigManager::PROTECTION_LEVEL); if (target->getLevel() < protectionLevel || attacker->getLevel() < protectionLevel) { @@ -287,18 +288,18 @@ bool Combat::isProtected(const Player* attacker, const Player* target) return false; } -ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) +ReturnValue Combat::canDoCombat(const CreaturePtr& attacker,const CreaturePtr& target) { if (!attacker) { return g_events->eventCreatureOnTargetCombat(attacker, target); } - if (const Player* targetPlayer = target->getPlayer()) { + if (const auto targetPlayer = target->getPlayer()) { if (targetPlayer->hasFlag(PlayerFlag_CannotBeAttacked)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } - if (const Player* attackerPlayer = attacker->getPlayer()) { + if (const auto attackerPlayer = attacker->getPlayer()) { if (attackerPlayer->hasFlag(PlayerFlag_CannotAttackPlayer)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } @@ -308,7 +309,7 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) } //nopvp-zone - const Tile* targetPlayerTile = targetPlayer->getTile(); + const auto targetPlayerTile = targetPlayer->getTile(); if (targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE)) { return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; } else if (attackerPlayer->getTile()->hasFlag(TILESTATE_NOPVPZONE) && !targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE | TILESTATE_PROTECTIONZONE)) { @@ -317,7 +318,7 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) } if (attacker->isSummon()) { - if (const Player* masterAttackerPlayer = attacker->getMaster()->getPlayer()) { + if (const auto masterAttackerPlayer = attacker->getMaster()->getPlayer()) { if (masterAttackerPlayer->hasFlag(PlayerFlag_CannotAttackPlayer)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } @@ -332,7 +333,7 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) } } } else if (target->getMonster()) { - if (const Player* attackerPlayer = attacker->getPlayer()) { + if (const auto attackerPlayer = attacker->getPlayer()) { if (attackerPlayer->hasFlag(PlayerFlag_CannotAttackMonster)) { return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE; } @@ -341,10 +342,10 @@ ReturnValue Combat::canDoCombat(Creature* attacker, Creature* target) return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; } } else if (attacker->getMonster()) { - const Creature* targetMaster = target->getMaster(); + const auto targetMaster = target->getMaster(); if (!targetMaster || !targetMaster->getPlayer()) { - const Creature* attackerMaster = attacker->getMaster(); + const auto attackerMaster = attacker->getMaster(); if (!attackerMaster || !attackerMaster->getPlayer()) { return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE; @@ -436,7 +437,7 @@ bool Combat::setParam(CombatParam_t param, uint32_t value) return false; } -int32_t Combat::getParam(CombatParam_t param) +int32_t Combat::getParam(CombatParam_t param) const { switch (param) { case COMBAT_PARAM_TYPE: @@ -505,7 +506,7 @@ bool Combat::setCallback(CallBackParam_t key) return false; } -CallBack* Combat::getCallback(CallBackParam_t key) +CallBack* Combat::getCallback(CallBackParam_t key) const { switch (key) { case CALLBACK_PARAM_LEVELMAGICVALUE: @@ -524,7 +525,7 @@ CallBack* Combat::getCallback(CallBackParam_t key) return nullptr; } -void Combat::combatTileEffects(const SpectatorVec& spectators, Creature* caster, Tile* tile, const CombatParams& params) +void Combat::combatTileEffects(const SpectatorVec& spectators,const CreaturePtr& caster, TilePtr tile, const CombatParams& params) { if (params.itemId != 0) { uint16_t itemId = params.itemId; @@ -562,7 +563,7 @@ void Combat::combatTileEffects(const SpectatorVec& spectators, Creature* caster, } if (caster) { - Player* casterPlayer; + PlayerPtr casterPlayer; if (caster->isSummon()) { casterPlayer = caster->getMaster()->getPlayer(); } else { @@ -588,16 +589,16 @@ void Combat::combatTileEffects(const SpectatorVec& spectators, Creature* caster, } } - Item* item = Item::CreateItem(itemId); + auto item = Item::CreateItem(itemId); if (caster) { item->setOwner(caster->getID()); } - - ReturnValue ret = g_game.internalAddItem(tile, item); + CylinderPtr holder = tile; + ReturnValue ret = g_game.internalAddItem(holder, item); if (ret == RETURNVALUE_NOERROR) { g_game.startDecay(item); } else { - delete item; + // } } @@ -610,21 +611,21 @@ void Combat::combatTileEffects(const SpectatorVec& spectators, Creature* caster, } } -void Combat::postCombatEffects(Creature* caster, const Position& pos, const CombatParams& params) +void Combat::postCombatEffects(const CreaturePtr& caster, const Position& pos, const CombatParams& params) { 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(const CreaturePtr& caster, const Position& fromPos, const Position& toPos, uint8_t effect) { if (effect == CONST_ANI_WEAPONTYPE) { if (!caster) { return; } - Player* player = caster->getPlayer(); + auto player = caster->getPlayer(); if (!player) { return; } @@ -650,7 +651,7 @@ void Combat::addDistanceEffect(Creature* caster, const Position& fromPos, const } } -void Combat::doCombat(Creature* caster, Creature* target) const +void Combat::doCombat(const CreaturePtr& caster,const CreaturePtr& target) const { //target combat callback function if (params.combatType != COMBAT_NONE) { @@ -672,7 +673,7 @@ void Combat::doCombat(Creature* caster, Creature* target) const if (params.origin != ORIGIN_MELEE) { for (const auto& condition : params.conditionList) { if (caster == target || !target->isImmune(condition->getType())) { - Condition* conditionCopy = condition->clone(); + auto conditionCopy = condition->clone(); conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID()); target->addCombatCondition(conditionCopy); } @@ -704,7 +705,7 @@ void Combat::doCombat(Creature* caster, Creature* target) const } } -void Combat::doCombat(Creature* caster, const Position& position) const +void Combat::doCombat(const CreaturePtr& caster, const Position& position) const { //area combat callback function if (params.combatType != COMBAT_NONE) { @@ -718,7 +719,7 @@ void Combat::doCombat(Creature* caster, const Position& position) const uint32_t maxY = 0; //calculate the max viewable range - for (Tile* tile : tiles) { + for (const auto tile : tiles) { const Position& tilePos = tile->getPosition(); uint32_t diff = Position::getDistanceX(tilePos, position); @@ -738,16 +739,16 @@ void Combat::doCombat(Creature* caster, const Position& position) const postCombatEffects(caster, position, params); - for (Tile* tile : tiles) { + for (auto tile : tiles) { if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) { continue; } combatTileEffects(spectators, caster, tile, params); - if (CreatureVector* creatures = tile->getCreatures()) { - const Creature* topCreature = tile->getTopCreature(); - for (Creature* creature : *creatures) { + if (auto creatures = tile->getCreatures()) { + const auto topCreature = tile->getTopCreature(); + for (auto creature : *creatures) { if (params.targetCasterOrTopMost) { if (caster && caster->getTile() == tile) { if (creature != caster) { @@ -761,7 +762,7 @@ void Combat::doCombat(Creature* caster, const Position& position) const if (!params.aggressive || (caster != creature && Combat::canDoCombat(caster, creature) == RETURNVALUE_NOERROR)) { for (const auto& condition : params.conditionList) { if (caster == creature || !creature->isImmune(condition->getType())) { - Condition* conditionCopy = condition->clone(); + const auto conditionCopy = condition->clone(); if (caster) { conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID()); } @@ -791,7 +792,7 @@ void Combat::doCombat(Creature* caster, const Position& position) const } } -void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params, bool sendDistanceEffect) +void Combat::doTargetCombat(const CreaturePtr& caster, const CreaturePtr& target, CombatDamage& damage, const CombatParams& params, bool sendDistanceEffect) { // To-do : I need to properly handle augment based damage which requires entire reworking of this method. // The thing that needs to happen is for augment based damage should not interact again with other aumgent @@ -802,9 +803,9 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da } // To-do : Get rid of these optionals (unsure, but I think they are a leak) // by adding isPlayer and isMonster member methods to all the Creature classes. - std::optional casterPlayer = caster && caster->getPlayer() ? std::optional(caster->getPlayer()) : std::nullopt; - std::optional targetPlayer = target && target->getPlayer() ? std::optional(target->getPlayer()) : std::nullopt; - std::optional casterMonster = caster && caster->getMonster() ? std::optional(caster->getMonster()) : std::nullopt; + std::optional casterPlayer = caster && caster->getPlayer() ? std::optional(caster->getPlayer()) : std::nullopt; + std::optional targetPlayer = target && target->getPlayer() ? std::optional(target->getPlayer()) : std::nullopt; + std::optional casterMonster = caster && caster->getMonster() ? std::optional(caster->getMonster()) : std::nullopt; std::unordered_map attackModData; @@ -813,7 +814,7 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da auto targetType = CREATURETYPE_ATTACKABLE; // to-do: this is ugly, lets make it a function and assign its return to the variable above instead. if (target->getMonster()) { - targetType = casterPlayer.value()->getCreatureType(*target->getMonster()); + targetType = casterPlayer.value()->getCreatureType(target->getMonster()); } else if (target->getPlayer()) { targetType = CREATURETYPE_PLAYER; } @@ -913,7 +914,7 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da if (targetPlayer.has_value() && (casterPlayer.value() != targetPlayer.value()) && params.origin != ORIGIN_AUGMENT) { const auto& reformTotals = targetPlayer.value()->getConvertedTotals(DEFENSE_MODIFIER_REFORM, damage.primary.type, damage.origin, CREATURETYPE_PLAYER, caster->getRace(), caster->getName()); if (!reformTotals.empty()) { - targetPlayer.value()->reformDamage(*casterPlayer.value()->getCreature(), damage, reformTotals); + targetPlayer.value()->reformDamage(casterPlayer.value()->getCreature(), damage, reformTotals); if (damage.primary.value == 0) { return; } @@ -923,7 +924,7 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da if (!defenseModData.empty()) { for (const auto& [modkind, modTotals] : defenseModData) { if (modTotals.percentTotal || modTotals.flatTotal) { - applyDamageReductionModifier(modkind, damage, *targetPlayer.value()->getPlayer(), *caster->getCreature(), static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), params.origin, params.impactEffect, params.distanceEffect); + applyDamageReductionModifier(modkind, damage, targetPlayer.value(), caster->getCreature(), static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), params.origin, params.impactEffect, params.distanceEffect); if (damage.primary.value == 0) { return; } @@ -931,7 +932,6 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da } } } - } } else if (casterMonster.has_value()) { if (g_game.combatBlockHit(damage, caster, target, params.blockedByShield, params.blockedByArmor, params.itemId != 0, params.ignoreResistances)) { @@ -939,11 +939,11 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da } if (targetPlayer.has_value()) { - const auto& attackerType = targetPlayer.value()->getCreatureType(*casterMonster.value()->getMonster()); + const auto& attackerType = targetPlayer.value()->getCreatureType(casterMonster.value()->getMonster()); const auto& defenseModData = targetPlayer.value()->getDefenseModifierTotals(damage.primary.type, damage.origin, attackerType, casterMonster.value()->getRace(), casterMonster.value()->getName()); auto reformTotals = targetPlayer.value()->getConvertedTotals(DEFENSE_MODIFIER_REFORM, damage.primary.type, damage.origin, attackerType, casterMonster.value()->getRace(), casterMonster.value()->getName()); if (!reformTotals.empty() && params.origin != ORIGIN_AUGMENT) { - targetPlayer.value()->reformDamage(*casterMonster.value()->getCreature(), damage, reformTotals); + targetPlayer.value()->reformDamage(casterMonster.value()->getCreature(), damage, reformTotals); if (damage.primary.value == 0) { return; } @@ -952,7 +952,7 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da if (!defenseModData.empty() && params.origin != ORIGIN_AUGMENT) { for (const auto& [modkind, modTotals] : defenseModData) { if (modTotals.percentTotal || modTotals.flatTotal) { - applyDamageReductionModifier(modkind, damage, *targetPlayer.value()->getPlayer(), *caster->getCreature(), static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), params.origin, params.impactEffect, params.distanceEffect); + applyDamageReductionModifier(modkind, damage, targetPlayer.value(), caster->getCreature(), static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), params.origin, params.impactEffect, params.distanceEffect); if (damage.primary.value == 0) { return; } @@ -992,7 +992,7 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da && (damage.primary.type != COMBAT_HEALING && damage.primary.type != COMBAT_MANADRAIN )) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = casterPlayer.value()->getInventoryItem(static_cast(slot)); + auto item = casterPlayer.value()->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -1048,7 +1048,7 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da if (targetPlayer.has_value() && damage.primary.type != COMBAT_HEALING && damage.primary.type != COMBAT_MANADRAIN ) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = targetPlayer.value()->getInventoryItem(static_cast(slot)); + auto item = targetPlayer.value()->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -1262,17 +1262,17 @@ void Combat::doTargetCombat(Creature* caster, Creature* target, CombatDamage& da } } -void Combat::doAreaCombat(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params) +void Combat::doAreaCombat(const CreaturePtr& caster, const Position& position, const AreaCombat* area, const CombatDamage& damage, const CombatParams& params) { auto tiles = caster ? getCombatArea(caster->getPosition(), position, area) : getCombatArea(position, position, area); - Player* casterPlayer = caster ? caster->getPlayer() : nullptr; + auto casterPlayer = caster ? caster->getPlayer() : nullptr; uint32_t maxX = 0; uint32_t maxY = 0; //calculate the max viewable range - for (Tile* tile : tiles) { + for (const auto tile : tiles) { const Position& tilePos = tile->getPosition(); uint32_t diff = Position::getDistanceX(tilePos, position); @@ -1294,19 +1294,19 @@ void Combat::doAreaCombat(Creature* caster, const Position& position, const Area postCombatEffects(caster, position, params); - std::vector toDamageCreatures; + std::vector toDamageCreatures; toDamageCreatures.reserve(100); - for (Tile* tile : tiles) { + for (const auto tile : tiles) { if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) { continue; } combatTileEffects(spectators, caster, tile, params); - if (CreatureVector* creatures = tile->getCreatures()) { - const Creature* topCreature = tile->getTopCreature(); - for (Creature* creature : *creatures) { + if (auto creatures = tile->getCreatures()) { + const auto topCreature = tile->getTopCreature(); + for (auto creature : *creatures) { if (params.targetCasterOrTopMost) { if (caster && caster->getTile() == tile) { if (creature != caster) { @@ -1328,7 +1328,7 @@ void Combat::doAreaCombat(Creature* caster, const Position& position, const Area } } - for (Creature* target : toDamageCreatures) { + for (const auto target : toDamageCreatures) { CombatDamage damageCopy = damage; // we cannot avoid copying here, because we don't know if it's player combat or not, so we can't modify the initial damage. Combat::doTargetCombat(caster, target, damageCopy, params, false); } @@ -1346,42 +1346,41 @@ void Combat::applyDamageIncreaseModifier(uint8_t modifierType, CombatDamage& dam if (percentValue) { damage.primary.value += percentValue; } - } -void Combat::applyDamageReductionModifier(uint8_t modifierType, CombatDamage& damage, Player& damageTarget, std::optional> attacker, int32_t percent, int32_t flat, CombatOrigin paramOrigin, uint8_t areaEffect, uint8_t distanceEffect) { +void Combat::applyDamageReductionModifier(uint8_t modifierType, CombatDamage& damage,const PlayerPtr& damageTarget,const std::optional& attacker, int32_t percent, int32_t flat, CombatOrigin paramOrigin, uint8_t areaEffect, uint8_t distanceEffect) { switch (modifierType) { case DEFENSE_MODIFIER_ABSORB: - damageTarget.absorbDamage(attacker, damage, percent, flat); + damageTarget->absorbDamage(attacker, damage, percent, flat); return; case DEFENSE_MODIFIER_RESTORE: - damageTarget.restoreManaFromDamage(attacker, damage, percent, flat); + damageTarget->restoreManaFromDamage(attacker, damage, percent, flat); return; case DEFENSE_MODIFIER_REPLENISH: - damageTarget.replenishStaminaFromDamage(attacker, damage, percent, flat); + damageTarget->replenishStaminaFromDamage(attacker, damage, percent, flat); return; case DEFENSE_MODIFIER_RESIST: - damageTarget.resistDamage(attacker, damage, percent, flat); + damageTarget->resistDamage(attacker, damage, percent, flat); return; case DEFENSE_MODIFIER_REVIVE: - damageTarget.reviveSoulFromDamage(attacker, damage, percent, flat); + damageTarget->reviveSoulFromDamage(attacker, damage, percent, flat); return; case DEFENSE_MODIFIER_REFLECT: - damageTarget.reflectDamage(attacker, damage, percent, flat, areaEffect, distanceEffect); + damageTarget->reflectDamage(attacker, damage, percent, flat, areaEffect, distanceEffect); return; case DEFENSE_MODIFIER_DEFLECT: - damageTarget.deflectDamage(attacker, damage, percent, flat, paramOrigin, areaEffect, distanceEffect); + damageTarget->deflectDamage(attacker, damage, percent, flat, paramOrigin, areaEffect, distanceEffect); return; case DEFENSE_MODIFIER_RICOCHET: - damageTarget.ricochetDamage(damage, percent, flat, areaEffect, distanceEffect); + damageTarget->ricochetDamage(damage, percent, flat, areaEffect, distanceEffect); return; default: @@ -1391,7 +1390,7 @@ void Combat::applyDamageReductionModifier(uint8_t modifierType, CombatDamage& da //**********************************************************// -void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage) const +void ValueCallback::getMinMaxValues(const PlayerPtr& player, CombatDamage& damage) const { //onGetPlayerMinMaxValues(...) if (!scriptInterface->reserveScriptEnv()) { @@ -1409,7 +1408,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage) const scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); int parameters = 1; @@ -1424,9 +1423,9 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage) const case COMBAT_FORMULA_SKILL: { //onGetPlayerMinMaxValues(player, attackSkill, attackValue, attackFactor) - Item* tool = player->getWeapon(); + auto tool = player->getWeapon(); const Weapon* weapon = g_weapons->getWeapon(tool); - Item* item = nullptr; + ItemPtr item; int32_t attackValue = 7; if (weapon) { @@ -1476,7 +1475,7 @@ void ValueCallback::getMinMaxValues(Player* player, CombatDamage& damage) const //**********************************************************// -void TileCallback::onTileCombat(Creature* creature, Tile* tile) const +void TileCallback::onTileCombat(const CreaturePtr& creature, const TilePtr& tile) const { //onTileCombat(creature, pos) if (!scriptInterface->reserveScriptEnv()) { @@ -1494,7 +1493,7 @@ void TileCallback::onTileCombat(Creature* creature, Tile* tile) const scriptInterface->pushFunction(scriptId); if (creature) { - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); } else { lua_pushnil(L); @@ -1506,7 +1505,7 @@ void TileCallback::onTileCombat(Creature* creature, Tile* tile) const //**********************************************************// -void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const +void TargetCallback::onTargetCombat(const CreaturePtr& creature, const CreaturePtr& target) const { //onTargetCombat(creature, target) if (!scriptInterface->reserveScriptEnv()) { @@ -1525,14 +1524,14 @@ void TargetCallback::onTargetCombat(Creature* creature, Creature* target) const scriptInterface->pushFunction(scriptId); if (creature) { - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); } else { lua_pushnil(L); } if (target) { - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setCreatureMetatable(L, -1, target); } else { lua_pushnil(L); @@ -1686,12 +1685,12 @@ void AreaCombat::setupExtArea(const std::vector& vec, uint32_t rows) //**********************************************************// -void MagicField::onStepInField(Creature* creature) +void MagicField::onStepInField(const CreaturePtr& creature) { //remove magic walls/wild growth if (id == ITEM_MAGICWALL || id == ITEM_WILDGROWTH || id == ITEM_MAGICWALL_SAFE || id == ITEM_WILDGROWTH_SAFE || isBlocking()) { if (!creature->isInGhostMode()) { - g_game.internalRemoveItem(this, 1); + g_game.internalRemoveItem(getItem(), 1); } return; @@ -1700,31 +1699,28 @@ void MagicField::onStepInField(Creature* creature) //remove magic walls/wild growth (only nopvp tiles/world) if (id == ITEM_MAGICWALL_NOPVP || id == ITEM_WILDGROWTH_NOPVP) { if (g_game.getWorldType() == WORLD_TYPE_NO_PVP || getTile()->hasFlag(TILESTATE_NOPVPZONE)) { - g_game.internalRemoveItem(this, 1); + g_game.internalRemoveItem(getItem(), 1); } return; } const ItemType& it = items[getID()]; if (it.conditionDamage) { - Condition* conditionCopy = it.conditionDamage->clone(); + auto conditionCopy = it.conditionDamage->clone(); uint32_t ownerId = getOwner(); if (ownerId) { bool harmfulField = true; if (g_game.getWorldType() == WORLD_TYPE_NO_PVP || getTile()->hasFlag(TILESTATE_NOPVPZONE)) { - Creature* owner = g_game.getCreatureByID(ownerId); - if (owner) { + if (auto owner = g_game.getCreatureByID(ownerId)) { if (owner->getPlayer() || (owner->isSummon() && owner->getMaster()->getPlayer())) { harmfulField = false; } } } - Player* targetPlayer = creature->getPlayer(); - if (targetPlayer) { - Player* attackerPlayer = g_game.getPlayerByID(ownerId); - if (attackerPlayer) { + if (auto targetPlayer = creature->getPlayer()) { + if (auto attackerPlayer = g_game.getPlayerByID(ownerId)) { if (Combat::isProtected(attackerPlayer, targetPlayer)) { harmfulField = false; } diff --git a/src/combat.h b/src/combat.h index b1f319b1..cd7cecdc 100644 --- a/src/combat.h +++ b/src/combat.h @@ -25,7 +25,7 @@ class ValueCallback final : public CallBack { public: explicit ValueCallback(formulaType_t type): type(type) {} - void getMinMaxValues(Player* player, CombatDamage& damage) const; + void getMinMaxValues(const PlayerPtr& player, CombatDamage& damage) const; private: formulaType_t type; @@ -34,13 +34,13 @@ class ValueCallback final : public CallBack class TileCallback final : public CallBack { public: - void onTileCombat(Creature* creature, Tile* tile) const; + void onTileCombat(const CreaturePtr& creature, const TilePtr& tile) const; }; class TargetCallback final : public CallBack { public: - void onTargetCombat(Creature* creature, Creature* target) const; + void onTargetCombat(const CreaturePtr& creature, const CreaturePtr& target) const; }; struct CombatParams { @@ -91,9 +91,9 @@ class Combat Combat(const Combat&) = delete; Combat& operator=(const Combat&) = delete; - static bool isInPvpZone(const Creature* attacker, const Creature* target); - static bool isProtected(const Player* attacker, const Player* target); - static bool isPlayerCombat(const Creature* target); + static bool isInPvpZone(const CreatureConstPtr& attacker, const CreatureConstPtr& target); + static bool isProtected(const PlayerConstPtr& attacker, const PlayerConstPtr& target); + static bool isPlayerCombat(const CreatureConstPtr& target); static CombatType_t ConditionToDamageType(ConditionType_t type); static ConditionType_t DamageToConditionType(CombatType_t type); // To-do : follow this call stack and improve it. @@ -101,41 +101,45 @@ class Combat // to remove those same checks out of game::combatHealthChange // with the breaking down of the smaller parts of combatHealthChange as well // we can eliminate the need in it all together and provide cleaner code. - 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 ReturnValue canTargetCreature(const PlayerPtr& attacker, const CreaturePtr& target); + static ReturnValue canDoCombat(const CreaturePtr& caster, const TilePtr& tile, bool aggressive); + static ReturnValue canDoCombat(const CreaturePtr& attacker, const CreaturePtr& target); + static void postCombatEffects(const CreaturePtr& caster, const Position& pos, const CombatParams& params); - static void addDistanceEffect(Creature* caster, const Position& fromPos, const Position& toPos, uint8_t effect); + static void addDistanceEffect(const CreaturePtr& caster, const Position& fromPos, const Position& toPos, uint8_t effect); - void doCombat(Creature* caster, Creature* target) const; - void doCombat(Creature* caster, const Position& position) const; + void doCombat(const CreaturePtr& caster,const CreaturePtr& target) const; + void doCombat(const CreaturePtr& caster, const Position& position) const; - static void doTargetCombat(Creature* caster, Creature* target, CombatDamage& damage, const CombatParams& params, bool sendDistanceEffect = true); - static void doAreaCombat(Creature* caster, const Position& position, const AreaCombat* area, CombatDamage& damage, const CombatParams& params); + static void doTargetCombat(const CreaturePtr& caster, const CreaturePtr& target, CombatDamage& damage, const CombatParams& params, bool sendDistanceEffect = true); + static void doAreaCombat(const CreaturePtr& caster, const Position& position, const AreaCombat* area, const CombatDamage& damage, const CombatParams& params); static void applyDamageIncreaseModifier(uint8_t modifierType, CombatDamage& damage, int32_t percentValue, int32_t flatValue); - static void applyDamageReductionModifier(uint8_t modifierType, CombatDamage& damage, Player& damageTarget, std::optional> attacker, int32_t percentValue, int32_t flatValue, CombatOrigin paramOrigin, uint8_t areaEffect = CONST_ME_NONE, uint8_t distanceEffect = CONST_ANI_NONE); + static void applyDamageReductionModifier(uint8_t modifierType, CombatDamage& damage, const PlayerPtr& damageTarget, const std::optional& attacker, int32_t percentValue, int32_t flatValue, CombatOrigin paramOrigin, uint8_t areaEffect = CONST_ME_NONE, uint8_t distanceEffect = CONST_ANI_NONE); bool setCallback(CallBackParam_t key); - CallBack* getCallback(CallBackParam_t key); + CallBack* getCallback(CallBackParam_t key) const; bool setParam(CombatParam_t param, uint32_t value); - int32_t getParam(CombatParam_t param); + int32_t getParam(CombatParam_t param) const; void setArea(AreaCombat* area); bool hasArea() const { return area != nullptr; } + void addCondition(const Condition* condition) { params.conditionList.emplace_front(condition); } + void clearConditions() { params.conditionList.clear(); } + void setPlayerCombatValues(formulaType_t formulaType, double mina, double minb, double maxa, double maxb); - void postCombatEffects(Creature* caster, const Position& pos) const { + + void postCombatEffects(CreaturePtr& caster, const Position& pos) const { postCombatEffects(caster, pos, params); } @@ -144,8 +148,8 @@ class Combat } private: - static void combatTileEffects(const SpectatorVec& spectators, Creature* caster, Tile* tile, const CombatParams& params); - CombatDamage getCombatDamage(Creature* creature, Creature* target) const; + static void combatTileEffects(const SpectatorVec& spectators,const CreaturePtr& caster, TilePtr tile, const CombatParams& params); + CombatDamage getCombatDamage(const CreaturePtr& creature, const CreaturePtr& target) const; //configurable CombatParams params; @@ -165,20 +169,23 @@ class MagicField final : public Item public: explicit MagicField(uint16_t type) : Item(type), createTime(OTSYS_TIME()) {} - MagicField* getMagicField() override { - return this; + MagicFieldPtr getMagicField() override { + return dynamic_shared_this(); } - const MagicField* getMagicField() const override { - return this; + + MagicFieldConstPtr getMagicField() const override { + return dynamic_shared_this(); } bool isReplaceable() const { return Item::items[getID()].replaceable; } + CombatType_t getCombatType() const { const ItemType& it = items[getID()]; return it.combatType; } + int32_t getDamage() const { const ItemType& it = items[getID()]; if (it.conditionDamage) { @@ -186,7 +193,7 @@ class MagicField final : public Item } return 0; } - void onStepInField(Creature* creature); + void onStepInField(const CreaturePtr& creature); private: int64_t createTime; diff --git a/src/condition.cpp b/src/condition.cpp index 08a190f6..d1df06d4 100644 --- a/src/condition.cpp +++ b/src/condition.cpp @@ -152,7 +152,7 @@ void Condition::setTicks(int32_t newTicks) endTime = ticks + OTSYS_TIME(); } -bool Condition::executeCondition(Creature*, int32_t interval) +bool Condition::executeCondition(CreaturePtr, int32_t interval) { if (ticks == -1) { return true; @@ -283,7 +283,7 @@ Condition* Condition::createCondition(PropStream& propStream) return createCondition(static_cast(id), static_cast(type), ticks, 0, buff != 0, subId, aggressive); } -bool Condition::startCondition(Creature*) +bool Condition::startCondition(CreaturePtr) { if (ticks > 0) { endTime = ticks + OTSYS_TIME(); @@ -326,22 +326,22 @@ bool Condition::updateCondition(const Condition* addCondition) return true; } -bool ConditionGeneric::startCondition(Creature* creature) +bool ConditionGeneric::startCondition(const CreaturePtr creature) { return Condition::startCondition(creature); } -bool ConditionGeneric::executeCondition(Creature* creature, int32_t interval) +bool ConditionGeneric::executeCondition(const CreaturePtr creature, int32_t interval) { return Condition::executeCondition(creature, interval); } -void ConditionGeneric::endCondition(Creature*) +void ConditionGeneric::endCondition(CreaturePtr) { // } -void ConditionGeneric::addCondition(Creature*, const Condition* condition) +void ConditionGeneric::addCondition(CreaturePtr, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); @@ -368,7 +368,7 @@ uint32_t ConditionGeneric::getIcons() const return icons; } -void ConditionAttributes::addCondition(Creature* creature, const Condition* condition) +void ConditionAttributes::addCondition(const CreaturePtr creature, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); @@ -385,7 +385,7 @@ void ConditionAttributes::addCondition(Creature* creature, const Condition* cond memcpy(statsPercent, conditionAttrs.statsPercent, sizeof(statsPercent)); disableDefense = conditionAttrs.disableDefense; - if (Player* player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); @@ -431,7 +431,7 @@ void ConditionAttributes::serialize(PropWriteStream& propWriteStream) } } -bool ConditionAttributes::startCondition(Creature* creature) +bool ConditionAttributes::startCondition(CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -439,7 +439,7 @@ bool ConditionAttributes::startCondition(Creature* creature) creature->setUseDefense(!disableDefense); - if (Player* player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); @@ -449,7 +449,7 @@ bool ConditionAttributes::startCondition(Creature* creature) return true; } -void ConditionAttributes::updatePercentStats(Player* player) +void ConditionAttributes::updatePercentStats(const PlayerPtr& player) { for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { if (statsPercent[i] == 0) { @@ -472,7 +472,7 @@ void ConditionAttributes::updatePercentStats(Player* player) } } -void ConditionAttributes::updateStats(Player* player) +void ConditionAttributes::updateStats(const PlayerPtr& player) const { bool needUpdateStats = false; @@ -488,7 +488,7 @@ void ConditionAttributes::updateStats(Player* player) } } -void ConditionAttributes::updatePercentSkills(Player* player) +void ConditionAttributes::updatePercentSkills(const PlayerPtr& player) { for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { if (skillsPercent[i] == 0) { @@ -500,7 +500,7 @@ void ConditionAttributes::updatePercentSkills(Player* player) } } -void ConditionAttributes::updateSkills(Player* player) +void ConditionAttributes::updateSkills(const PlayerPtr& player) const { bool needUpdateSkills = false; @@ -523,15 +523,14 @@ void ConditionAttributes::updateSkills(Player* player) } } -bool ConditionAttributes::executeCondition(Creature* creature, int32_t interval) +bool ConditionAttributes::executeCondition(const CreaturePtr creature, int32_t interval) { return ConditionGeneric::executeCondition(creature, interval); } -void ConditionAttributes::endCondition(Creature* creature) +void ConditionAttributes::endCondition(const CreaturePtr creature) { - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { @@ -735,7 +734,7 @@ bool ConditionAttributes::setParam(ConditionParam_t param, int32_t value) } } -int32_t ConditionAttributes::getParam(ConditionParam_t param) +int32_t ConditionAttributes::getParam(const ConditionParam_t param) { switch (param) { case CONDITION_PARAM_SKILL_FIST: @@ -824,7 +823,7 @@ int32_t ConditionAttributes::getParam(ConditionParam_t param) } } -void ConditionRegeneration::addCondition(Creature*, const Condition* condition) +void ConditionRegeneration::addCondition(CreaturePtr, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); @@ -839,7 +838,7 @@ void ConditionRegeneration::addCondition(Creature*, const Condition* condition) } } -bool ConditionRegeneration::unserializeProp(ConditionAttr_t attr, PropStream& propStream) +bool ConditionRegeneration::unserializeProp(const ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_HEALTHTICKS) { return propStream.read(healthTicks); @@ -870,7 +869,7 @@ void ConditionRegeneration::serialize(PropWriteStream& propWriteStream) propWriteStream.write(manaGain); } -bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interval) +bool ConditionRegeneration::executeCondition(const CreaturePtr creature, int32_t interval) { internalHealthTicks += interval; internalManaTicks += interval; @@ -887,8 +886,7 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva realHealthGain = creature->getHealth() - realHealthGain; if (isBuff && realHealthGain > 0) { - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { std::string healString = std::to_string(realHealthGain) + (realHealthGain != 1 ? " hitpoints." : " hitpoint."); TextMessage message(MESSAGE_HEALED, "You were healed for " + healString); @@ -903,9 +901,11 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva if (!spectators.empty()) { message.type = MESSAGE_HEALED_OTHERS; message.text = player->getName() + " was healed for " + healString; - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendTextMessage(message); + for (auto spectator : spectators) { + if (auto t_player = spectator->getPlayer()) + { + t_player->sendTextMessage(message); + } } } } @@ -915,7 +915,7 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva if (internalManaTicks >= manaTicks) { internalManaTicks = 0; - if (Player* player = creature->getPlayer()) { + if (auto player = creature->getPlayer()) { int32_t realManaGain = player->getMana(); player->changeMana(manaGain); realManaGain = player->getMana() - realManaGain; @@ -935,9 +935,11 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva if (!spectators.empty()) { message.type = MESSAGE_HEALED_OTHERS; message.text = player->getName() + " gained " + manaGainString + " mana."; - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendTextMessage(message); + for (auto spectator : spectators) { + if (auto t_player = spectator->getPlayer()) + { + t_player->sendTextMessage(message); + } } } } @@ -949,7 +951,7 @@ bool ConditionRegeneration::executeCondition(Creature* creature, int32_t interva bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) { - bool ret = ConditionGeneric::setParam(param, value); + const bool ret = ConditionGeneric::setParam(param, value); switch (param) { case CONDITION_PARAM_HEALTHGAIN: @@ -993,12 +995,12 @@ int32_t ConditionRegeneration::getParam(ConditionParam_t param) } } -void ConditionSoul::addCondition(Creature*, const Condition* condition) +void ConditionSoul::addCondition(CreaturePtr, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); - const ConditionSoul& conditionSoul = static_cast(*condition); + const auto& conditionSoul = static_cast(*condition); soulTicks = conditionSoul.soulTicks; soulGain = conditionSoul.soulGain; @@ -1026,11 +1028,11 @@ void ConditionSoul::serialize(PropWriteStream& propWriteStream) propWriteStream.write(soulTicks); } -bool ConditionSoul::executeCondition(Creature* creature, int32_t interval) +bool ConditionSoul::executeCondition(const CreaturePtr creature, int32_t interval) { internalSoulTicks += interval; - if (Player* player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (player->getZone() != ZONE_PROTECTION) { if (internalSoulTicks >= soulTicks) { internalSoulTicks = 0; @@ -1042,9 +1044,9 @@ 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(const ConditionParam_t param, const int32_t value) { - bool ret = ConditionGeneric::setParam(param, value); + const bool ret = ConditionGeneric::setParam(param, value); switch (param) { case CONDITION_PARAM_SOULGAIN: soulGain = value; @@ -1059,7 +1061,7 @@ bool ConditionSoul::setParam(ConditionParam_t param, int32_t value) } } -int32_t ConditionSoul::getParam(ConditionParam_t param) +int32_t ConditionSoul::getParam(const ConditionParam_t param) { switch (param) { case CONDITION_PARAM_SOULGAIN: @@ -1073,7 +1075,7 @@ int32_t ConditionSoul::getParam(ConditionParam_t param) } } -bool ConditionDamage::setParam(ConditionParam_t param, int32_t value) +bool ConditionDamage::setParam(const ConditionParam_t param, const int32_t value) { bool ret = Condition::setParam(param, value); @@ -1121,7 +1123,7 @@ bool ConditionDamage::setParam(ConditionParam_t param, int32_t value) return ret; } -int32_t ConditionDamage::getParam(ConditionParam_t param) +int32_t ConditionDamage::getParam(const ConditionParam_t param) { switch (param) { case CONDITION_PARAM_OWNER: @@ -1156,7 +1158,7 @@ int32_t ConditionDamage::getParam(ConditionParam_t param) } } -bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream& propStream) +bool ConditionDamage::unserializeProp(const ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_DELAYED) { uint8_t value; @@ -1203,7 +1205,7 @@ void ConditionDamage::serialize(PropWriteStream& propWriteStream) bool ConditionDamage::updateCondition(const Condition* addCondition) { - const ConditionDamage& conditionDamage = static_cast(*addCondition); + const auto& conditionDamage = static_cast(*addCondition); if (conditionDamage.doForceUpdate()) { return true; } @@ -1215,7 +1217,7 @@ 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(const int32_t rounds, int32_t time, const int32_t value) { time = std::max(time, EVENT_CREATURE_THINK_INTERVAL); if (rounds == -1) { @@ -1259,8 +1261,7 @@ bool ConditionDamage::init() setTicks(0); - int32_t amount = uniform_random(minDamage, maxDamage); - if (amount != 0) { + if (const auto amount = uniform_random(minDamage, maxDamage); amount != 0) { if (startDamage > maxDamage) { startDamage = maxDamage; } else if (startDamage == 0) { @@ -1276,7 +1277,7 @@ bool ConditionDamage::init() return !damageList.empty(); } -bool ConditionDamage::startCondition(Creature* creature) +bool ConditionDamage::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -1295,7 +1296,7 @@ bool ConditionDamage::startCondition(Creature* creature) return true; } -bool ConditionDamage::executeCondition(Creature* creature, int32_t interval) +bool ConditionDamage::executeCondition(const CreaturePtr creature, int32_t interval) { if (periodDamage != 0) { periodDamageTick += interval; @@ -1341,7 +1342,7 @@ bool ConditionDamage::getNextDamage(int32_t& damage) damage = periodDamage; return true; } else if (!damageList.empty()) { - IntervalInfo& damageInfo = damageList.front(); + const IntervalInfo& damageInfo = damageList.front(); damage = damageInfo.value; if (ticks != -1) { damageList.pop_front(); @@ -1351,7 +1352,7 @@ bool ConditionDamage::getNextDamage(int32_t& damage) return false; } -bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) +bool ConditionDamage::doDamage(CreaturePtr creature, int32_t healthChange) const { if (creature->isSuppress(getType()) || creature->isImmune(getType())) { return false; @@ -1362,7 +1363,7 @@ bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) damage.primary.value = healthChange; damage.primary.type = Combat::ConditionToDamageType(conditionType); - Creature* attacker = g_game.getCreatureByID(owner); + auto attacker = g_game.getCreatureByID(owner); if (field && creature->getPlayer() && attacker && attacker->getPlayer()) { damage.primary.value = static_cast(std::round(damage.primary.value / 2.)); } @@ -1378,20 +1379,20 @@ bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) return false; } - if (Player* player = creature->getPlayer()) { + if (auto player = creature->getPlayer()) { if (attacker) { auto creatureType = CREATURETYPE_ATTACKABLE; - if (Player* attackPlayer = attacker->getPlayer()) { + if (auto attackPlayer = attacker->getPlayer()) { creatureType = CREATURETYPE_PLAYER; - } else if (Monster* attackMonster = attacker->getMonster()) { - creatureType = player->getCreatureType(*attackMonster); + } else if (auto attackMonster = attacker->getMonster()) { + creatureType = player->getCreatureType(attackMonster); } auto reformTotals = player->getConvertedTotals(DEFENSE_MODIFIER_REFORM, damage.primary.type, ORIGIN_CONDITION, creatureType, attacker->getRace(), attacker->getName()); if (!reformTotals.empty()) { std::cout << "Reform Modifier Activated on " << damage.primary.value << " damage \n"; - player->reformDamage(*attacker, damage, reformTotals); + player->reformDamage(attacker, damage, reformTotals); if (damage.primary.value == 0) { return true; } @@ -1401,7 +1402,7 @@ bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) if (!defenseModData.empty()) { for (const auto& [modkind, modTotals] : defenseModData) { if (modTotals.percentTotal || modTotals.flatTotal) { - Combat::applyDamageReductionModifier(modkind, damage, *player, *attacker, static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), ORIGIN_CONDITION); + Combat::applyDamageReductionModifier(modkind, damage, player, attacker, static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), ORIGIN_CONDITION); } if (damage.primary.value == 0) { return true; @@ -1423,7 +1424,7 @@ bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) if (!defenseModData.empty()) { for (const auto& [modkind, modTotals] : defenseModData) { if (modTotals.percentTotal || modTotals.flatTotal) { - Combat::applyDamageReductionModifier(modkind, damage, *player, std::nullopt, static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), ORIGIN_CONDITION); + Combat::applyDamageReductionModifier(modkind, damage, player, std::nullopt, static_cast(modTotals.percentTotal), static_cast(modTotals.flatTotal), ORIGIN_CONDITION); } if (damage.primary.value == 0) { return true; @@ -1436,12 +1437,12 @@ bool ConditionDamage::doDamage(Creature* creature, int32_t healthChange) return g_game.combatChangeHealth(attacker, creature, damage); } -void ConditionDamage::endCondition(Creature*) +void ConditionDamage::endCondition(CreaturePtr) { // } -void ConditionDamage::addCondition(Creature* creature, const Condition* condition) +void ConditionDamage::addCondition(const CreaturePtr creature, const Condition* condition) { if (condition->getType() != conditionType) { return; @@ -1640,7 +1641,7 @@ static std::pair getFormulaValues(int32_t var, float mina, flo return {std::fma(var, mina, minb), std::fma(var, maxa, maxb)}; } -bool ConditionSpeed::startCondition(Creature* creature) +bool ConditionSpeed::startCondition(CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -1655,17 +1656,17 @@ bool ConditionSpeed::startCondition(Creature* creature) return true; } -bool ConditionSpeed::executeCondition(Creature* creature, int32_t interval) +bool ConditionSpeed::executeCondition(const CreaturePtr creature, const int32_t interval) { return Condition::executeCondition(creature, interval); } -void ConditionSpeed::endCondition(Creature* creature) +void ConditionSpeed::endCondition(const CreaturePtr creature) { g_game.changeSpeed(creature, -speedDelta); } -void ConditionSpeed::addCondition(Creature* creature, const Condition* condition) +void ConditionSpeed::addCondition(const CreaturePtr creature, const Condition* condition) { if (conditionType != condition->getType()) { return; @@ -1714,7 +1715,7 @@ uint32_t ConditionSpeed::getIcons() const return icons; } -bool ConditionInvisible::startCondition(Creature* creature) +bool ConditionInvisible::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -1726,7 +1727,7 @@ bool ConditionInvisible::startCondition(Creature* creature) return true; } -void ConditionInvisible::endCondition(Creature* creature) +void ConditionInvisible::endCondition(const CreaturePtr creature) { if (!creature->isInGhostMode() && !creature->isInvisible()) { g_game.internalCreatureChangeVisible(creature, true); @@ -1738,7 +1739,7 @@ void ConditionOutfit::setOutfit(const Outfit_t& outfit) this->outfit = outfit; } -bool ConditionOutfit::unserializeProp(ConditionAttr_t attr, PropStream& propStream) +bool ConditionOutfit::unserializeProp(const ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_OUTFIT) { return propStream.read(outfit); @@ -1754,7 +1755,7 @@ void ConditionOutfit::serialize(PropWriteStream& propWriteStream) propWriteStream.write(outfit); } -bool ConditionOutfit::startCondition(Creature* creature) +bool ConditionOutfit::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -1764,29 +1765,29 @@ bool ConditionOutfit::startCondition(Creature* creature) return true; } -bool ConditionOutfit::executeCondition(Creature* creature, int32_t interval) +bool ConditionOutfit::executeCondition(const CreaturePtr creature, const int32_t interval) { return Condition::executeCondition(creature, interval); } -void ConditionOutfit::endCondition(Creature* creature) +void ConditionOutfit::endCondition(const CreaturePtr creature) { g_game.internalCreatureChangeOutfit(creature, creature->getDefaultOutfit()); } -void ConditionOutfit::addCondition(Creature* creature, const Condition* condition) +void ConditionOutfit::addCondition(const CreaturePtr creature, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); - const ConditionOutfit& conditionOutfit = static_cast(*condition); + const auto& conditionOutfit = static_cast(*condition); outfit = conditionOutfit.outfit; g_game.internalCreatureChangeOutfit(creature, outfit); } } -bool ConditionLight::startCondition(Creature* creature) +bool ConditionLight::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -1799,7 +1800,7 @@ bool ConditionLight::startCondition(Creature* creature) return true; } -bool ConditionLight::executeCondition(Creature* creature, int32_t interval) +bool ConditionLight::executeCondition(const CreaturePtr creature, const int32_t interval) { internalLightTicks += interval; @@ -1817,18 +1818,18 @@ bool ConditionLight::executeCondition(Creature* creature, int32_t interval) return Condition::executeCondition(creature, interval); } -void ConditionLight::endCondition(Creature* creature) +void ConditionLight::endCondition(const CreaturePtr creature) { creature->setNormalCreatureLight(); g_game.changeLight(creature); } -void ConditionLight::addCondition(Creature* creature, const Condition* condition) +void ConditionLight::addCondition(const CreaturePtr creature, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); - const ConditionLight& conditionLight = static_cast(*condition); + const auto& conditionLight = static_cast(*condition); lightInfo.level = conditionLight.lightInfo.level; lightInfo.color = conditionLight.lightInfo.color; lightChangeInterval = ticks / lightInfo.level; @@ -1838,10 +1839,9 @@ void ConditionLight::addCondition(Creature* creature, const Condition* condition } } -bool ConditionLight::setParam(ConditionParam_t param, int32_t value) +bool ConditionLight::setParam(const ConditionParam_t param, const int32_t value) { - bool ret = Condition::setParam(param, value); - if (ret) { + if (const bool ret = Condition::setParam(param, value)) { return false; } @@ -1873,7 +1873,7 @@ int32_t ConditionLight::getParam(ConditionParam_t param) } } -bool ConditionLight::unserializeProp(ConditionAttr_t attr, PropStream& propStream) +bool ConditionLight::unserializeProp(const ConditionAttr_t attr, PropStream& propStream) { if (attr == CONDITIONATTR_LIGHTCOLOR) { uint32_t value; @@ -1919,65 +1919,61 @@ void ConditionLight::serialize(PropWriteStream& propWriteStream) propWriteStream.write(lightChangeInterval); } -void ConditionSpellCooldown::addCondition(Creature* creature, const Condition* condition) +void ConditionSpellCooldown::addCondition(const CreaturePtr creature, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); if (subId != 0 && ticks > 0) { - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { player->sendSpellCooldown(subId, ticks); } } } } -bool ConditionSpellCooldown::startCondition(Creature* creature) +bool ConditionSpellCooldown::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; } if (subId != 0 && ticks > 0) { - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { player->sendSpellCooldown(subId, ticks); } } return true; } -void ConditionSpellGroupCooldown::addCondition(Creature* creature, const Condition* condition) +void ConditionSpellGroupCooldown::addCondition(const CreaturePtr creature, const Condition* condition) { if (updateCondition(condition)) { setTicks(condition->getTicks()); if (subId != 0 && ticks > 0) { - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { player->sendSpellGroupCooldown(static_cast(subId), ticks); } } } } -bool ConditionSpellGroupCooldown::startCondition(Creature* creature) +bool ConditionSpellGroupCooldown::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; } if (subId != 0 && ticks > 0) { - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { player->sendSpellGroupCooldown(static_cast(subId), ticks); } } return true; } -bool ConditionDrunk::startCondition(Creature* creature) +bool ConditionDrunk::startCondition(const CreaturePtr creature) { if (!Condition::startCondition(creature)) { return false; @@ -1993,7 +1989,7 @@ bool ConditionDrunk::updateCondition(const Condition* addCondition) return conditionDrunk->drunkenness > drunkenness; } -void ConditionDrunk::addCondition(Creature* creature, const Condition* condition) +void ConditionDrunk::addCondition(const CreaturePtr creature, const Condition* condition) { if (!updateCondition(condition)) { return; @@ -2004,7 +2000,7 @@ void ConditionDrunk::addCondition(Creature* creature, const Condition* condition creature->setDrunkenness(conditionDrunk->drunkenness); } -void ConditionDrunk::endCondition(Creature* creature) +void ConditionDrunk::endCondition(const CreaturePtr creature) { creature->setDrunkenness(0); } @@ -2014,7 +2010,7 @@ uint32_t ConditionDrunk::getIcons() const return ICON_DRUNK; } -bool ConditionDrunk::setParam(ConditionParam_t param, int32_t value) +bool ConditionDrunk::setParam(const ConditionParam_t param, const int32_t value) { bool ret = Condition::setParam(param, value); diff --git a/src/condition.h b/src/condition.h index 5f458432..f86de072 100644 --- a/src/condition.h +++ b/src/condition.h @@ -7,9 +7,41 @@ #include "fileloader.h" #include "enums.h" +class PropStream; class Creature; +using CreaturePtr = std::shared_ptr; +using CreatureConstPtr = std::shared_ptr; class Player; -class PropStream; +using PlayerPtr = std::shared_ptr; +using PlayerConstPtr = std::shared_ptr; +class Monster; +using MonsterPtr = std::shared_ptr; +using MonsterConstPtr = std::shared_ptr; +class Npc; +using NpcPtr = std::shared_ptr; +using NpcConstPtr = std::shared_ptr; +class Depot; +using DepotPtr = std::shared_ptr; + +class Teleport; +using TeleportPtr = std::shared_ptr; + +class TrashHolder; +using TrashHolderPtr = std::shared_ptr; + +class Mailbox; +using MailboxPtr = std::shared_ptr; + +class Door; +using DoorPtr = std::shared_ptr; + +class MagicField; +using MagicFieldPtr = std::shared_ptr; + +class Bed; +class BedItem; +using BedItemPtr = std::shared_ptr; + enum ConditionAttr_t { CONDITIONATTR_TYPE = 1, @@ -62,14 +94,16 @@ class Condition subId(subId), ticks(ticks), conditionType(type), isBuff(buff), aggressive(aggressive), id(id) {} virtual ~Condition() = default; - virtual bool startCondition(Creature* creature); - virtual bool executeCondition(Creature* creature, int32_t interval); - virtual void endCondition(Creature* creature) = 0; - virtual void addCondition(Creature* creature, const Condition* condition) = 0; + virtual bool startCondition(CreaturePtr creature); + virtual bool executeCondition(CreaturePtr creature, int32_t interval); + virtual void endCondition(CreaturePtr creature) = 0; + virtual void addCondition(CreaturePtr creature, const Condition* condition) = 0; virtual uint32_t getIcons() const; + ConditionId_t getId() const { return id; } + uint32_t getSubId() const { return subId; } @@ -79,13 +113,17 @@ class Condition ConditionType_t getType() const { return conditionType; } + int64_t getEndTime() const { return endTime; } + int32_t getTicks() const { return ticks; } + void setTicks(int32_t newTicks); + bool isAggressive() const { return aggressive; } @@ -115,7 +153,7 @@ class Condition private: ConditionId_t id; - Creature* source = nullptr; + CreaturePtr source = nullptr; }; class ConditionGeneric : public Condition @@ -124,10 +162,10 @@ class ConditionGeneric : public Condition ConditionGeneric(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false): Condition(id, type, ticks, buff, subId, aggressive) {} - bool startCondition(Creature* creature) override; - bool executeCondition(Creature* creature, int32_t interval) override; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; + void endCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; uint32_t getIcons() const override; ConditionGeneric* clone() const override { @@ -141,10 +179,10 @@ class ConditionAttributes final : public ConditionGeneric ConditionAttributes(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false) : ConditionGeneric(id, type, ticks, buff, subId, aggressive) {} - bool startCondition(Creature* creature) override; - bool executeCondition(Creature* creature, int32_t interval) override; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; + void endCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; bool setParam(ConditionParam_t param, int32_t value) override; int32_t getParam(ConditionParam_t param) override; @@ -169,10 +207,10 @@ class ConditionAttributes final : public ConditionGeneric bool disableDefense = false; - void updatePercentStats(Player* player); - void updateStats(Player* player); - void updatePercentSkills(Player* player); - void updateSkills(Player* player); + void updatePercentStats(const PlayerPtr& player); + void updateStats(const PlayerPtr& player) const; + void updatePercentSkills(const PlayerPtr& player); + void updateSkills(const PlayerPtr& player) const; }; class ConditionRegeneration final : public ConditionGeneric @@ -181,8 +219,8 @@ class ConditionRegeneration final : public ConditionGeneric ConditionRegeneration(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false): ConditionGeneric(id, type, ticks, buff, subId, aggressive) {} - void addCondition(Creature* creature, const Condition* condition) override; - bool executeCondition(Creature* creature, int32_t interval) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; bool setParam(ConditionParam_t param, int32_t value) override; int32_t getParam(ConditionParam_t param) override; @@ -211,8 +249,8 @@ class ConditionSoul final : public ConditionGeneric ConditionSoul(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false) : ConditionGeneric(id, type, ticks, buff, subId, aggressive) {} - void addCondition(Creature* creature, const Condition* condition) override; - bool executeCondition(Creature* creature, int32_t interval) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; bool setParam(ConditionParam_t param, int32_t value) override; int32_t getParam(ConditionParam_t param) override; @@ -237,8 +275,8 @@ class ConditionInvisible final : public ConditionGeneric ConditionInvisible(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false) : ConditionGeneric(id, type, ticks, buff, subId, aggressive) {} - bool startCondition(Creature* creature) override; - void endCondition(Creature* creature) override; + bool startCondition(CreaturePtr creature) override; + void endCondition(CreaturePtr creature) override; ConditionInvisible* clone() const override { return new ConditionInvisible(*this); @@ -254,10 +292,10 @@ class ConditionDamage final : public Condition 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; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; + void endCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; uint32_t getIcons() const override; ConditionDamage* clone() const override { @@ -268,9 +306,11 @@ class ConditionDamage final : public Condition int32_t getParam(ConditionParam_t param) override; bool addDamage(int32_t rounds, int32_t time, int32_t value); + bool doForceUpdate() const { return forceUpdate; } + int32_t getTotalDamage() const; void setInitDamage(int32_t initDamage) { @@ -300,7 +340,7 @@ class ConditionDamage final : public Condition std::list damageList; bool getNextDamage(int32_t& damage); - bool doDamage(Creature* creature, int32_t healthChange); + bool doDamage(CreaturePtr creature, int32_t healthChange) const; bool updateCondition(const Condition* addCondition) override; }; @@ -311,10 +351,10 @@ class ConditionSpeed final : public Condition ConditionSpeed(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff, uint32_t subId, int32_t changeSpeed, bool aggressive = false) : Condition(id, type, ticks, buff, subId, aggressive), speedDelta(changeSpeed) {} - bool startCondition(Creature* creature) override; - bool executeCondition(Creature* creature, int32_t interval) override; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; + void endCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; uint32_t getIcons() const override; ConditionSpeed* clone() const override { @@ -346,10 +386,10 @@ class ConditionOutfit final : public Condition ConditionOutfit(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false) : Condition(id, type, ticks, buff, subId, aggressive) {} - bool startCondition(Creature* creature) override; - bool executeCondition(Creature* creature, int32_t interval) override; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; + void endCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; ConditionOutfit* clone() const override { return new ConditionOutfit(*this); @@ -371,10 +411,10 @@ class ConditionLight final : public Condition ConditionLight(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff, uint32_t subId, uint8_t lightlevel, uint8_t lightcolor, bool aggressive = false) : Condition(id, type, ticks, buff, subId, aggressive), lightInfo(lightlevel, lightcolor) {} - bool startCondition(Creature* creature) override; - bool executeCondition(Creature* creature, int32_t interval) override; - void endCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + bool executeCondition(CreaturePtr creature, int32_t interval) override; + void endCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; ConditionLight* clone() const override { return new ConditionLight(*this); @@ -399,8 +439,8 @@ class ConditionSpellCooldown final : public ConditionGeneric ConditionSpellCooldown(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false) : ConditionGeneric(id, type, ticks, buff, subId, aggressive) {} - bool startCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; ConditionSpellCooldown* clone() const override { return new ConditionSpellCooldown(*this); @@ -413,8 +453,8 @@ class ConditionSpellGroupCooldown final : public ConditionGeneric ConditionSpellGroupCooldown(ConditionId_t id, ConditionType_t type, int32_t ticks, bool buff = false, uint32_t subId = 0, bool aggressive = false) : ConditionGeneric(id, type, ticks, buff, subId, aggressive) {} - bool startCondition(Creature* creature) override; - void addCondition(Creature* creature, const Condition* condition) override; + bool startCondition(CreaturePtr creature) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; ConditionSpellGroupCooldown* clone() const override { return new ConditionSpellGroupCooldown(*this); @@ -432,10 +472,10 @@ class ConditionDrunk final : public Condition } uint32_t getIcons() const override; - void endCondition(Creature* creature) override; - bool startCondition(Creature* creature) override; + void endCondition(CreaturePtr creature) override; + bool startCondition(CreaturePtr creature) override; bool setParam(ConditionParam_t param, int32_t value) override; - void addCondition(Creature* creature, const Condition* condition) override; + void addCondition(CreaturePtr creature, const Condition* condition) override; ConditionDrunk* clone() const override { return new ConditionDrunk(*this); diff --git a/src/container.cpp b/src/container.cpp index 81b6ded6..5f7c3c4c 100644 --- a/src/container.cpp +++ b/src/container.cpp @@ -19,19 +19,17 @@ Container::Container(uint16_t type, uint16_t size, bool unlocked /*= true*/, boo pagination(pagination) {} -Container::Container(Tile* tile) : Container(ITEM_BROWSEFIELD, 30, false, true) +Container::Container(const TilePtr& tile) : Container(ITEM_BROWSEFIELD, 30, false, true) { - TileItemVector* itemVector = tile->getItemList(); - if (itemVector) { - for (Item* item : *itemVector) { + if (const auto& itemVector = tile->getItemList()) { + for (const auto& item : *itemVector) { if ((item->getContainer() || item->hasProperty(CONST_PROP_MOVEABLE)) && !item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { itemlist.push_front(item); - item->setParent(this); + item->setParent(getContainer()); } } } - - setParent(tile); + Item::setParent(tile); } Container::~Container() @@ -39,30 +37,28 @@ Container::~Container() if (getID() == ITEM_BROWSEFIELD) { g_game.browseFields.erase(getTile()); - for (Item* item : itemlist) { + for (const auto item : itemlist) { item->setParent(parent); } } else { - for (Item* item : itemlist) { - item->setParent(nullptr); - item->decrementReferenceCounter(); + for (const auto item : itemlist) { + item->clearParent(); } } } -Item* Container::clone() const +ItemPtr Container::clone() const { - Container* clone = static_cast(Item::clone()); - for (Item* item : itemlist) { + const auto& clone = std::dynamic_pointer_cast(Item::clone()); + for (const auto& item : itemlist) { clone->addItem(item->clone()); } clone->totalWeight = totalWeight; return clone; } -Container* Container::getParentContainer() -{ - Thing* thing = getParent(); +ContainerPtr Container::getParentContainer() { + const auto& thing = getParent(); if (!thing) { return nullptr; } @@ -71,21 +67,21 @@ Container* Container::getParentContainer() std::string Container::getName(bool addArticle /* = false*/) const { const ItemType& it = items[id]; - return getNameDescription(it, this, -1, addArticle); + return getNameDescription(it, std::dynamic_pointer_cast(shared_from_this()), -1, addArticle); } -bool Container::hasParent() const +bool Container::hasParent() { - return getID() != ITEM_BROWSEFIELD && dynamic_cast(getParent()) == nullptr; + return getID() != ITEM_BROWSEFIELD && std::dynamic_pointer_cast(getParent()) == nullptr; } -void Container::addItem(Item* item) +void Container::addItem(const ItemPtr& item) { itemlist.push_back(item); - item->setParent(this); + item->setParent(getContainer()); } -Attr_ReadValue Container::readAttr(AttrTypes_t attr, PropStream& propStream) +Attr_ReadValue Container::readAttr(const AttrTypes_t attr, PropStream& propStream) { if (attr == ATTR_CONTAINER_ITEMS) { if (!propStream.read(serializationCount)) { @@ -115,7 +111,7 @@ bool Container::unserializeItemNode(OTB::Loader& loader, const OTB::Node& node, return false; } - Item* item = Item::CreateItem(itemPropStream); + auto item = Item::CreateItem(itemPropStream); if (!item) { return false; } @@ -133,7 +129,7 @@ bool Container::unserializeItemNode(OTB::Loader& loader, const OTB::Node& node, void Container::updateItemWeight(int32_t diff) { totalWeight += diff; - Container* parentContainer = this; + auto parentContainer = getContainer(); while ((parentContainer = parentContainer->getParentContainer()) != nullptr) { parentContainer->totalWeight += diff; } @@ -154,9 +150,9 @@ std::ostringstream& Container::getContentDescription(std::ostringstream& os) con { bool firstitem = true; for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { - Item* item = *it; + const auto item = *it; - Container* container = item->getContainer(); + const auto container = item->getContainer(); if (container && !container->empty()) { continue; } @@ -176,7 +172,7 @@ std::ostringstream& Container::getContentDescription(std::ostringstream& os) con return os; } -Item* Container::getItemByIndex(size_t index) const +ItemPtr Container::getItemByIndex(size_t index) const { if (index >= size()) { return nullptr; @@ -193,18 +189,18 @@ uint32_t Container::getItemHoldingCount() const return counter; } -bool Container::isHoldingItem(const Item* item) const +bool Container::isHoldingItem(const ItemConstPtr& item) const { for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { - if (*it == item) { - return true; - } + if ((*it)->equals(item)) { + return true; + } } return false; } bool Container::isRewardCorpse() const { - for (Item* subItem : getItemList()) { + for (const auto subItem : getItemList()) { if (subItem->getID() == ITEM_REWARD_CONTAINER) { return true; } @@ -212,62 +208,53 @@ bool Container::isRewardCorpse() const { return false; } -void Container::onAddContainerItem(Item* item) +void Container::onAddContainerItem(ItemPtr& item) { SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), false, true, 1, 1, 1, 1); - - //send to client - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendAddContainerItem(this, item); - } - - //event methods - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->onAddContainerItem(item); + + for (auto spectator : spectators) { + if (const auto c_player = spectator->getPlayer()) + { + const auto t_container = std::dynamic_pointer_cast(shared_from_this()); + c_player->sendAddContainerItem(t_container, item); + c_player->onAddContainerItem(item); + } } } -void Container::onUpdateContainerItem(uint32_t index, Item* oldItem, Item* newItem) +void Container::onUpdateContainerItem(uint32_t index, const ItemPtr& oldItem, const ItemPtr& newItem) { SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), false, true, 1, 1, 1, 1); - - //send to client - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendUpdateContainerItem(this, index, newItem); - } - - //event methods - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->onUpdateContainerItem(this, oldItem, newItem); + + for (auto spectator : spectators) { + if (const auto c_player = spectator->getPlayer()) + { + auto t_container = std::dynamic_pointer_cast(shared_from_this()); + c_player->sendUpdateContainerItem(t_container, index, newItem); + c_player->onUpdateContainerItem(t_container, oldItem, newItem); + } } } -void Container::onRemoveContainerItem(uint32_t index, Item* item) +void Container::onRemoveContainerItem(uint32_t index, const ItemPtr& item) { SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), false, true, 1, 1, 1, 1); - - //send change to client - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendRemoveContainerItem(this, index); - } - - //event methods - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->onRemoveContainerItem(this, item); + + for (auto spectator : spectators) { + if (const auto c_player = spectator->getPlayer()) + { + auto t_container = std::dynamic_pointer_cast(shared_from_this()); + c_player->sendRemoveContainerItem(t_container, index); + c_player->onRemoveContainerItem(t_container, item); + } } } -ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor/* = nullptr*/) const +ReturnValue Container::queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor/* = std::nullopt*/) { bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); if (childIsOwner) { @@ -280,7 +267,7 @@ ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t coun return RETURNVALUE_NOTPOSSIBLE; } - const Item* item = thing.getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -289,7 +276,7 @@ ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t coun return RETURNVALUE_CANNOTPICKUP; } - if (item == this) { + if (item.get() == this) { return RETURNVALUE_THISISIMPOSSIBLE; } @@ -303,10 +290,10 @@ ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t coun return RETURNVALUE_ITEMCANNOTBEMOVEDTHERE; } - const Cylinder* cylinder = getParent(); + auto cylinder = getParent(); // don't allow moving items into container that is store item and is in store inbox - if (isStoreItem() && dynamic_cast(cylinder)) { + if (isStoreItem() && std::dynamic_pointer_cast(cylinder)) { ReturnValue ret = RETURNVALUE_ITEMCANNOTBEMOVEDTHERE; if (!item->isStoreItem()) { ret = RETURNVALUE_CANNOTMOVEITEMISNOTSTOREITEM; @@ -316,11 +303,11 @@ ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t coun if (!hasBitSet(FLAG_NOLIMIT, flags)) { while (cylinder) { - if (cylinder == &thing) { + if (cylinder == thing) { return RETURNVALUE_THISISIMPOSSIBLE; } - if (dynamic_cast(cylinder)) { + if (std::dynamic_pointer_cast(cylinder)) { return RETURNVALUE_CONTAINERNOTENOUGHROOM; } @@ -332,7 +319,7 @@ ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t coun } } else { while (cylinder) { - if (cylinder == &thing) { + if (cylinder == thing) { return RETURNVALUE_THISISIMPOSSIBLE; } @@ -340,26 +327,26 @@ ReturnValue Container::queryAdd(int32_t index, const Thing& thing, uint32_t coun } } - const Cylinder* const topParent = getTopParent(); + const auto topParent = getTopParent(); if (actor && g_config.getBoolean(ConfigManager::ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { - if (const HouseTile* const houseTile = dynamic_cast(topParent->getTile())) { + if (const auto& houseTile = std::dynamic_pointer_cast(topParent->getTile())) { if (!topParent->getCreature() && !houseTile->getHouse()->isInvited(actor->getPlayer())) { return RETURNVALUE_PLAYERISNOTINVITED; } } } - if (topParent != this) { - return topParent->queryAdd(INDEX_WHEREEVER, *item, count, flags | FLAG_CHILDISOWNER, actor); + if (topParent.get() != this) { + return topParent->queryAdd(INDEX_WHEREEVER, item, count, flags | FLAG_CHILDISOWNER, actor); } else { return RETURNVALUE_NOERROR; } } -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 ThingPtr& thing, uint32_t count, + uint32_t& maxQueryCount, uint32_t flags) { - const Item* item = thing.getItem(); + auto item = thing->getItem(); if (item == nullptr) { maxQueryCount = 0; return RETURNVALUE_NOTPOSSIBLE; @@ -378,17 +365,17 @@ ReturnValue Container::queryMaxCount(int32_t index, const Thing& thing, uint32_t if (index == INDEX_WHEREEVER) { //Iterate through every item and check how much free stackable slots there is. uint32_t slotIndex = 0; - for (Item* containerItem : itemlist) { + for (auto containerItem : itemlist) { if (containerItem != item && containerItem->equals(item) && containerItem->getItemCount() < 100) { - if (queryAdd(slotIndex++, *item, count, flags) == RETURNVALUE_NOERROR) { + if (queryAdd(slotIndex++, item, count, flags) == RETURNVALUE_NOERROR) { n += 100 - containerItem->getItemCount(); } } } } else { - const Item* destItem = getItemByIndex(index); + const auto destItem = getItemByIndex(index); if (item->equals(destItem) && destItem->getItemCount() < 100) { - if (queryAdd(index, *item, count, flags) == RETURNVALUE_NOERROR) { + if (queryAdd(index, item, count, flags) == RETURNVALUE_NOERROR) { n = 100 - destItem->getItemCount(); } } @@ -407,14 +394,14 @@ 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 ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor /*= nullptr */) { - int32_t index = getThingIndex(&thing); + int32_t index = getThingIndex(thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; } - const Item* item = thing.getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -428,8 +415,8 @@ ReturnValue Container::queryRemove(const Thing& thing, uint32_t count, uint32_t } if (actor && g_config.getBoolean(ConfigManager::ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { - const Cylinder* const topParent = getTopParent(); - if (const HouseTile* const houseTile = dynamic_cast(topParent->getTile())) { + const auto topParent = getTopParent(); + if (const auto& houseTile = std::dynamic_pointer_cast(topParent->getTile())) { if (!topParent->getCreature() && !houseTile->getHouse()->isInvited(actor->getPlayer())) { return RETURNVALUE_PLAYERISNOTINVITED; } @@ -439,23 +426,22 @@ ReturnValue Container::queryRemove(const Thing& thing, uint32_t count, uint32_t return RETURNVALUE_NOERROR; } -Cylinder* Container::queryDestination(int32_t& index, const Thing& thing, Item** destItem, +CylinderPtr Container::queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, uint32_t& flags) { if (!unlocked) { *destItem = nullptr; - return this; + return {std::move(shared_from_this()), this}; } if (index == 254 /*move up*/) { index = INDEX_WHEREEVER; *destItem = nullptr; - Container* parentContainer = dynamic_cast(getParent()); - if (parentContainer) { + if (const auto& parentContainer = std::dynamic_pointer_cast(getParent())) { return parentContainer; } - return this; + return {shared_from_this(), this}; } if (index == 255 /*add wherever*/) { @@ -473,19 +459,17 @@ Cylinder* Container::queryDestination(int32_t& index, const Thing& thing, Item** *destItem = nullptr; } - const Item* item = thing.getItem(); + const auto item = thing->getItem(); if (!item) { - return this; + return {shared_from_this(), this}; } if (index != INDEX_WHEREEVER) { - Item* itemFromIndex = getItemByIndex(index); - if (itemFromIndex) { + if (const auto itemFromIndex = getItemByIndex(index)) { *destItem = itemFromIndex; } - Cylinder* subCylinder = dynamic_cast(*destItem); - if (subCylinder) { + if (CylinderPtr subCylinder = std::dynamic_pointer_cast(*destItem)) { index = INDEX_WHEREEVER; *destItem = nullptr; return subCylinder; @@ -493,42 +477,42 @@ Cylinder* Container::queryDestination(int32_t& index, const Thing& thing, Item** } bool autoStack = !hasBitSet(FLAG_IGNOREAUTOSTACK, flags); - if (autoStack && item->isStackable() && item->getParent() != this) { + if (autoStack && item->isStackable() && item->getParent().get() != this) { if (*destItem && (*destItem)->equals(item) && (*destItem)->getItemCount() < 100) { - return this; + return {shared_from_this(), this}; } //try find a suitable item to stack with uint32_t n = 0; - for (Item* listItem : itemlist) { + for (auto listItem : itemlist) { if (listItem != item && listItem->equals(item) && listItem->getItemCount() < 100) { *destItem = listItem; index = n; - return this; + return {std::move(shared_from_this()), this}; } ++n; } } - return this; + return {std::move(shared_from_this()), this}; } -void Container::addThing(Thing* thing) +void Container::addThing(ThingPtr thing) { return addThing(0, thing); } -void Container::addThing(int32_t index, Thing* thing) +void Container::addThing(int32_t index, ThingPtr thing) { if (index >= static_cast(capacity())) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* item = thing->getItem(); + ItemPtr item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - item->setParent(this); + item->setParent(getContainer()); itemlist.push_front(item); updateItemWeight(item->getWeight()); ammoCount += item->getItemCount(); @@ -539,7 +523,7 @@ void Container::addThing(int32_t index, Thing* thing) } } -void Container::addItemBack(Item* item) +void Container::addItemBack(ItemPtr& item) { addItem(item); updateItemWeight(item->getWeight()); @@ -551,14 +535,14 @@ void Container::addItemBack(Item* item) } } -void Container::updateThing(Thing* thing, uint16_t itemId, uint32_t count) +void Container::updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -577,21 +561,21 @@ void Container::updateThing(Thing* thing, uint16_t itemId, uint32_t count) } } -void Container::replaceThing(uint32_t index, Thing* thing) +void Container::replaceThing(uint32_t index, ThingPtr thing) { - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* replacedItem = getItemByIndex(index); + const auto replacedItem = getItemByIndex(index); if (!replacedItem) { return /*RETURNVALUE_NOTPOSSIBLE*/; } ammoCount -= replacedItem->getItemCount(); itemlist[index] = item; - item->setParent(this); + item->setParent(getContainer()); updateItemWeight(-static_cast(replacedItem->getWeight()) + item->getWeight()); ammoCount += item->getItemCount(); @@ -600,12 +584,12 @@ void Container::replaceThing(uint32_t index, Thing* thing) onUpdateContainerItem(index, replacedItem, item); } - replacedItem->setParent(nullptr); + replacedItem->clearParent(); } -void Container::removeThing(Thing* thing, uint32_t count) +void Container::removeThing(ThingPtr thing, uint32_t count) { - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -634,15 +618,15 @@ void Container::removeThing(Thing* thing, uint32_t count) onRemoveContainerItem(index, item); } - item->setParent(nullptr); + item->clearParent(); itemlist.erase(itemlist.begin() + index); } } -int32_t Container::getThingIndex(const Thing* thing) const +int32_t Container::getThingIndex(ThingPtr thing) { int32_t index = 0; - for (Item* item : itemlist) { + for (const auto item : itemlist) { if (item == thing) { return index; } @@ -664,7 +648,7 @@ size_t Container::getLastIndex() const uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType/* = -1*/) const { uint32_t count = 0; - for (Item* item : itemlist) { + for (const auto item : itemlist) { if (item->getID() == itemId) { count += countByType(item, subType); } @@ -674,13 +658,13 @@ uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType/* = -1*/) std::map& Container::getAllItemTypeCount(std::map& countMap) const { - for (Item* item : itemlist) { + for (const auto item : itemlist) { countMap[item->getID()] += item->getItemCount(); } return countMap; } -ItemVector Container::getItems(bool recursive /*= false*/) +ItemVector Container::getItems(bool recursive /*= false*/) const { ItemVector containerItems; if (recursive) { @@ -688,24 +672,24 @@ ItemVector Container::getItems(bool recursive /*= false*/) containerItems.push_back(*it); } } else { - for (Item* item : itemlist) { + for (auto item : itemlist) { containerItems.push_back(item); } } return containerItems; } -Thing* Container::getThing(size_t index) const +ThingPtr Container::getThing(size_t index) { return getItemByIndex(index); } -void Container::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void Container::postAddNotification (ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - Cylinder* topParent = getTopParent(); + auto topParent = getTopParent(); if (topParent->getCreature()) { topParent->postAddNotification(thing, oldParent, index, LINK_TOPPARENT); - } else if (topParent == this) { + } else if (topParent.get() == this) { //let the tile class notify surrounding players if (topParent->getParent()) { topParent->getParent()->postAddNotification(thing, oldParent, index, LINK_NEAR); @@ -715,12 +699,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(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - Cylinder* topParent = getTopParent(); + auto topParent = getTopParent(); if (topParent->getCreature()) { topParent->postRemoveNotification(thing, newParent, index, LINK_TOPPARENT); - } else if (topParent == this) { + } else if (topParent.get() == this) { //let the tile class notify surrounding players if (topParent->getParent()) { topParent->getParent()->postRemoveNotification(thing, newParent, index, LINK_NEAR); @@ -730,19 +714,18 @@ void Container::postRemoveNotification(Thing* thing, const Cylinder* newParent, } } -void Container::internalAddThing(Thing* thing) +void Container::internalAddThing(ThingPtr thing) { internalAddThing(0, thing); } -void Container::internalAddThing(uint32_t, Thing* thing) +void Container::internalAddThing(uint32_t, ThingPtr thing) { - Item* item = thing->getItem(); + auto item = thing->getItem(); if (item == nullptr) { return; } - - item->setParent(this); + item->setParent(getContainer()); itemlist.push_front(item); updateItemWeight(item->getWeight()); ammoCount += item->getItemCount(); @@ -752,7 +735,7 @@ void Container::startDecaying() { Item::startDecaying(); - for (Item* item : itemlist) { + for (const auto item : itemlist) { item->startDecaying(); } } @@ -761,21 +744,21 @@ ContainerIterator Container::iterator() const { ContainerIterator cit; if (!itemlist.empty()) { - cit.over.push_back(this); + cit.over.push_back(std::dynamic_pointer_cast(shared_from_this())); cit.cur = itemlist.begin(); } return cit; } -Item* ContainerIterator::operator*() +ItemPtr ContainerIterator::operator*() const { return *cur; } void ContainerIterator::advance() { - if (Item* i = *cur) { - if (Container* c = i->getContainer()) { + if (const auto i = *cur) { + if (const auto c = i->getContainer()) { if (!c->empty()) { over.push_back(c); } diff --git a/src/container.h b/src/container.h index 9d657e42..d45647f4 100644 --- a/src/container.h +++ b/src/container.h @@ -16,6 +16,15 @@ class DepotLocker; class StoreInbox; class RewardChest; +using DepotLockerPtr = std::shared_ptr; +using DepotLockerConstPtr = std::shared_ptr; + +using StoreInboxPtr = std::shared_ptr; +using StoreInboxConstPtr = std::shared_ptr; + +using RewardChestPtr = std::shared_ptr; +using RewardChestConstPtr = std::shared_ptr; + class ContainerIterator { public: @@ -24,10 +33,10 @@ class ContainerIterator } void advance(); - Item* operator*(); + ItemPtr operator*() const; private: - std::list over; + std::list over; ItemDeque::const_iterator cur; friend class Container; @@ -38,40 +47,44 @@ 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); - explicit Container(Tile* tile); - ~Container(); + explicit Container(const TilePtr& tile); + ~Container() override; // non-copyable Container(const Container&) = delete; Container& operator=(const Container&) = delete; - Item* clone() const override final; + ItemPtr clone() const override final; - Container* getContainer() override final { - return this; + ContainerPtr getContainer() override final { + return dynamic_shared_this(); } - const Container* getContainer() const override final { - return this; + + ContainerConstPtr getContainer() const override final { + return dynamic_shared_this(); } - virtual DepotLocker* getDepotLocker() { + virtual DepotLockerPtr getDepotLocker() { return nullptr; } - virtual const DepotLocker* getDepotLocker() const { + + virtual DepotLockerConstPtr getDepotLocker() const { return nullptr; } - virtual StoreInbox* getStoreInbox() { + virtual StoreInboxPtr getStoreInbox() { return nullptr; } - virtual const StoreInbox* getStoreInbox() const { + + virtual StoreInboxConstPtr getStoreInbox() const { return nullptr; } - virtual RewardChest* getRewardChest() { + virtual RewardChestPtr getRewardChest() { return nullptr; } - virtual const RewardChest* getRewardChest() const { + + virtual RewardChestConstPtr getRewardChest() const { return nullptr; } @@ -82,12 +95,15 @@ class Container : public Item, public Cylinder size_t size() const { return itemlist.size(); } + bool empty() const { return itemlist.empty(); } + uint32_t capacity() const { return maxSize; } + uint32_t getAmmoCount() const { return ammoCount; } @@ -101,16 +117,17 @@ class Container : public Item, public Cylinder ItemDeque::const_reverse_iterator getReversedItems() const { return itemlist.rbegin(); } + ItemDeque::const_reverse_iterator getReversedEnd() const { return itemlist.rend(); } std::string getName(bool addArticle = false) const; - bool hasParent() const; - void addItem(Item* item); - Item* getItemByIndex(size_t index) const; - bool isHoldingItem(const Item* item) const; + bool hasParent(); + void addItem(const ItemPtr& item); + ItemPtr getItemByIndex(size_t index) const; + bool isHoldingItem(const ItemConstPtr& item) const; bool isRewardCorpse() const; uint32_t getItemHoldingCount() const; @@ -119,42 +136,43 @@ class Container : public Item, public Cylinder bool isUnlocked() const { return unlocked; } + bool hasPagination() const { 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; + virtual ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr = nullptr) override; + ReturnValue queryMaxCount(int32_t index, const ThingPtr& thing, uint32_t count, uint32_t& maxQueryCount, + uint32_t flags) override final; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override final; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, + uint32_t& flags) override final; // again optional ref wrapper - void addThing(Thing* thing) override final; - void addThing(int32_t index, Thing* thing) override final; - void addItemBack(Item* item); + void addThing(ThingPtr thing) override final; + void addThing(int32_t index, ThingPtr thing) override final; + void addItemBack(ItemPtr& item); - void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override final; - void replaceThing(uint32_t index, Thing* thing) override final; + void updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) override final; + void replaceThing(uint32_t index, ThingPtr thing) override final; - void removeThing(Thing* thing, uint32_t count) override final; + void removeThing(ThingPtr thing, uint32_t count) override final; - int32_t getThingIndex(const Thing* thing) const override final; + int32_t getThingIndex(ThingPtr thing) override final; 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; - Thing* getThing(size_t index) const override final; + ThingPtr getThing(size_t index) override final; - ItemVector getItems(bool recursive = false); + ItemVector getItems(bool recursive = false) const; - 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; - void internalAddThing(Thing* thing) override final; - void internalAddThing(uint32_t index, Thing* thing) override final; + void internalAddThing(ThingPtr thing) override final; + void internalAddThing(uint32_t index, ThingPtr thing) override final; void startDecaying() override final; protected: @@ -171,11 +189,11 @@ class Container : public Item, public Cylinder bool unlocked; bool pagination; - void onAddContainerItem(Item* item); - void onUpdateContainerItem(uint32_t index, Item* oldItem, Item* newItem); - void onRemoveContainerItem(uint32_t index, Item* item); + void onAddContainerItem(ItemPtr& item); + void onUpdateContainerItem(uint32_t index, const ItemPtr& oldItem, const ItemPtr& newItem); + void onRemoveContainerItem(uint32_t index, const ItemPtr& item); - Container* getParentContainer(); + ContainerPtr getParentContainer(); void updateItemWeight(int32_t diff); friend class ContainerIterator; diff --git a/src/creature.cpp b/src/creature.cpp index 92868291..b87881ce 100644 --- a/src/creature.cpp +++ b/src/creature.cpp @@ -26,13 +26,13 @@ Creature::Creature() Creature::~Creature() { - for (Creature* summon : summons) { + for (CreaturePtr summon : summons) { summon->setAttackedCreature(nullptr); summon->removeMaster(); } for (Condition* condition : conditions) { - condition->endCondition(this); + condition->endCondition(std::dynamic_pointer_cast(shared_from_this())); } for (auto condition : conditions) { @@ -71,7 +71,7 @@ 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 CreatureConstPtr& creature) const { if (!canSeeGhostMode(creature) && creature->isInGhostMode()) { return false; @@ -86,7 +86,7 @@ bool Creature::canSeeCreature(const Creature* creature) const void Creature::setSkull(Skulls_t newSkull) { skull = newSkull; - g_game.updateCreatureSkull(this); + g_game.updateCreatureSkull(std::dynamic_pointer_cast(shared_from_this())); } int64_t Creature::getTimeSinceLastMove() const @@ -158,7 +158,7 @@ void Creature::onThink(uint32_t interval) //scripting event - onThink const CreatureEventList& thinkEvents = getCreatureEvents(CREATURE_EVENT_THINK); for (CreatureEvent* thinkEvent : thinkEvents) { - thinkEvent->executeOnThink(this, interval); + thinkEvent->executeOnThink(getCreature(), interval); } } @@ -190,9 +190,9 @@ void Creature::onWalk() Direction dir; uint32_t flags = FLAG_IGNOREFIELDDAMAGE; if (getNextStep(dir, flags)) { - ReturnValue ret = g_game.internalMoveCreature(this, dir, flags); + ReturnValue ret = g_game.internalMoveCreature(getCreature(), dir, flags); if (ret != RETURNVALUE_NOERROR) { - if (Player* player = getPlayer()) { + if (auto player = getPlayer()) { player->sendCancelMessage(ret); player->sendCancelWalk(); } @@ -232,7 +232,7 @@ void Creature::onWalk(Direction& dir) } dir = static_cast(rand % 4); - g_game.internalCreatureSay(this, TALKTYPE_MONSTER_SAY, "Hicks!", false); + g_game.internalCreatureSay(getCreature(), TALKTYPE_MONSTER_SAY, "Hicks!", false); } bool Creature::getNextStep(Direction& dir, uint32_t&) @@ -249,7 +249,7 @@ bool Creature::getNextStep(Direction& dir, uint32_t&) void Creature::startAutoWalk() { - Player* player = getPlayer(); + auto player = getPlayer(); if (player && player->isMovementBlocked()) { player->sendCancelWalk(); return; @@ -260,7 +260,7 @@ void Creature::startAutoWalk() void Creature::startAutoWalk(Direction direction) { - Player* player = getPlayer(); + auto player = getPlayer(); if (player && player->isMovementBlocked()) { player->sendCancelWalk(); return; @@ -273,7 +273,7 @@ void Creature::startAutoWalk(Direction direction) void Creature::startAutoWalk(const std::vector& listDir) { - Player* player = getPlayer(); + auto player = getPlayer(); if (player && player->isMovementBlocked()) { player->sendCancelWalk(); return; @@ -318,7 +318,6 @@ void Creature::stopEventWalk() void Creature::updateMapCache() { - Tile* tile; const Position& myPos = getPosition(); Position pos(0, 0, myPos.z); @@ -326,20 +325,20 @@ void Creature::updateMapCache() for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) { pos.x = myPos.getX() + x; pos.y = myPos.getY() + y; - tile = g_game.map.getTile(pos); + TilePtr tile = g_game.map.getTile(pos); updateTileCache(tile, pos); } } } -void Creature::updateTileCache(const Tile* tile, int32_t dx, int32_t dy) +void Creature::updateTileCache(TilePtr tile, int32_t dx, int32_t dy) { if (std::abs(dx) <= maxWalkCacheWidth && std::abs(dy) <= maxWalkCacheHeight) { - localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx] = tile && tile->queryAdd(*this, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR; + localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx] = tile && tile->queryAdd(getCreature(), FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR; } } -void Creature::updateTileCache(const Tile* tile, const Position& pos) +void Creature::updateTileCache(TilePtr tile, const Position& pos) { const Position& myPos = getPosition(); if (pos.z == myPos.z) { @@ -380,15 +379,19 @@ int32_t Creature::getWalkCache(const Position& pos) const return 2; } -void Creature::onAddTileItem(const Tile* tile, const Position& pos) +void Creature::onAddTileItem(TilePtr tile, const Position& pos) { if (isMapLoaded && pos.z == getPosition().z) { updateTileCache(tile, pos); } } -void Creature::onUpdateTileItem(const Tile* tile, const Position& pos, const Item*, - const ItemType& oldType, const Item*, const ItemType& newType) +void Creature::onUpdateTileItem(const TilePtr& tile, + const Position& pos, + const ItemPtr&, + const ItemType& oldType, + const ItemPtr&, + const ItemType& newType) { if (!isMapLoaded) { return; @@ -401,7 +404,7 @@ void Creature::onUpdateTileItem(const Tile* tile, const Position& pos, const Ite } } -void Creature::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, const Item*) +void Creature::onRemoveTileItem(const TilePtr& tile, const Position& pos, const ItemType& iType, const ItemPtr&) { if (!isMapLoaded) { return; @@ -414,9 +417,9 @@ void Creature::onRemoveTileItem(const Tile* tile, const Position& pos, const Ite } } -void Creature::onCreatureAppear(Creature* creature, bool isLogin) +void Creature::onCreatureAppear(const CreaturePtr& creature, bool isLogin) { - if (creature == this) { + if (creature == shared_from_this()) { if (useCacheMap()) { isMapLoaded = true; updateMapCache(); @@ -432,17 +435,17 @@ void Creature::onCreatureAppear(Creature* creature, bool isLogin) } } -void Creature::onRemoveCreature(Creature* creature, bool) +void Creature::onRemoveCreature(const CreaturePtr& creature, bool) { onCreatureDisappear(creature, true); - if (creature != this && isMapLoaded) { + if (creature != shared_from_this() && isMapLoaded) { if (creature->getPosition().z == getPosition().z) { updateTileCache(creature->getTile(), creature->getPosition()); } } } -void Creature::onCreatureDisappear(const Creature* creature, bool isLogout) +void Creature::onCreatureDisappear(const CreatureConstPtr& creature, bool isLogout) { if (attackedCreature == creature) { setAttackedCreature(nullptr); @@ -469,10 +472,14 @@ void Creature::onAttackedCreatureChangeZone(ZoneType_t zone) } } -void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport) +void Creature::onCreatureMove(const CreaturePtr& creature, + const TilePtr& newTile, + const Position& newPos, + const TilePtr& oldTile, + const Position& oldPos, + bool teleport) { - if (creature == this) { + if (creature == shared_from_this()) { lastStep = OTSYS_TIME(); lastStepCost = 1; @@ -490,15 +497,15 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos if (!summons.empty()) { //check if any of our summons is out of range (+/- 2 floors or 30 tiles away) - std::forward_list despawnList; - for (Creature* summon : summons) { + std::forward_list despawnList; + for (CreaturePtr summon : summons) { const Position& pos = summon->getPosition(); if (Position::getDistanceZ(newPos, pos) > 2 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 30)) { despawnList.push_front(summon); } } - for (Creature* despawnCreature : despawnList) { + for (CreaturePtr despawnCreature : despawnList) { g_game.removeCreature(despawnCreature, true); } } @@ -522,7 +529,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos //update 0 for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) { - Tile* cacheTile = g_game.map.getTile(myPos.getX() + x, myPos.getY() - maxWalkCacheHeight, myPos.z); + auto cacheTile = g_game.map.getTile(myPos.getX() + x, myPos.getY() - maxWalkCacheHeight, myPos.z); updateTileCache(cacheTile, x, -maxWalkCacheHeight); } } else if (oldPos.y < newPos.y) { // south @@ -533,7 +540,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos //update mapWalkHeight - 1 for (int32_t x = -maxWalkCacheWidth; x <= maxWalkCacheWidth; ++x) { - Tile* cacheTile = g_game.map.getTile(myPos.getX() + x, myPos.getY() + maxWalkCacheHeight, myPos.z); + auto cacheTile = g_game.map.getTile(myPos.getX() + x, myPos.getY() + maxWalkCacheHeight, myPos.z); updateTileCache(cacheTile, x, maxWalkCacheHeight); } } @@ -558,7 +565,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos //update mapWalkWidth - 1 for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) { - Tile* cacheTile = g_game.map.getTile(myPos.x + maxWalkCacheWidth, myPos.y + y, myPos.z); + auto cacheTile = g_game.map.getTile(myPos.x + maxWalkCacheWidth, myPos.y + y, myPos.z); updateTileCache(cacheTile, maxWalkCacheWidth, y); } } else if (oldPos.x > newPos.x) { // west @@ -581,7 +588,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos //update 0 for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) { - Tile* cacheTile = g_game.map.getTile(myPos.x - maxWalkCacheWidth, myPos.y + y, myPos.z); + auto cacheTile = g_game.map.getTile(myPos.x - maxWalkCacheWidth, myPos.y + y, myPos.z); updateTileCache(cacheTile, -maxWalkCacheWidth, y); } } @@ -603,7 +610,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } - if (creature == followCreature || (creature == this && followCreature)) { + if (creature == followCreature || (creature == shared_from_this() && followCreature)) { if (hasFollowPath) { if ((creature == followCreature) && listWalkDir.empty()) { isUpdatingPath = false; @@ -618,7 +625,7 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } - if (creature == attackedCreature || (creature == this && attackedCreature)) { + if (creature == attackedCreature || (creature == shared_from_this() && attackedCreature)) { if (newPos.z != oldPos.z || !canSee(attackedCreature->getPosition())) { onCreatureDisappear(attackedCreature, false); } else { @@ -634,14 +641,14 @@ void Creature::onCreatureMove(Creature* creature, const Tile* newTile, const Pos } } -CreatureVector Creature::getKillers() +CreatureVector Creature::getKillers() const { CreatureVector killers; const int64_t timeNow = OTSYS_TIME(); const uint32_t inFightTicks = g_config.getNumber(ConfigManager::PZ_LOCKED); for (const auto& it : damageMap) { - Creature* attacker = g_game.getCreatureByID(it.first); - if (attacker && attacker != this && timeNow - it.second.ticks <= inFightTicks) { + auto attacker = g_game.getCreatureByID(it.first); + if (attacker && attacker != shared_from_this() && timeNow - it.second.ticks <= inFightTicks) { killers.push_back(attacker); } } @@ -652,32 +659,32 @@ void Creature::onDeath() { bool lastHitUnjustified = false; bool mostDamageUnjustified = false; - Creature* lastHitCreature = g_game.getCreatureByID(lastHitCreatureId); - Creature* lastHitCreatureMaster; + CreaturePtr lastHitCreature = g_game.getCreatureByID(lastHitCreatureId); + CreaturePtr lastHitCreatureMaster; if (lastHitCreature) { - lastHitUnjustified = lastHitCreature->onKilledCreature(this); + lastHitUnjustified = lastHitCreature->onKilledCreature(getCreature()); lastHitCreatureMaster = lastHitCreature->getMaster(); } else { lastHitCreatureMaster = nullptr; } - Creature* mostDamageCreature = nullptr; + CreaturePtr mostDamageCreature = nullptr; const int64_t timeNow = OTSYS_TIME(); const uint32_t inFightTicks = g_config.getNumber(ConfigManager::PZ_LOCKED); int32_t mostDamage = 0; - std::map experienceMap; + std::map experienceMap; for (const auto& it : damageMap) { - if (Creature* attacker = g_game.getCreatureByID(it.first)) { + if (auto attacker = g_game.getCreatureByID(it.first)) { CountBlock_t cb = it.second; if ((cb.total > mostDamage && (timeNow - cb.ticks <= inFightTicks))) { mostDamage = cb.total; mostDamageCreature = attacker; } - if (attacker != this) { + if (attacker != shared_from_this()) { uint64_t gainExp = getGainedExperience(attacker); - if (Player* attackerPlayer = attacker->getPlayer()) { + if (auto attackerPlayer = attacker->getPlayer()) { attackerPlayer->removeAttacked(getPlayer()); Party* party = attackerPlayer->getParty(); @@ -697,14 +704,14 @@ void Creature::onDeath() } for (const auto& it : experienceMap) { - it.first->onGainExperience(it.second, this); + it.first->onGainExperience(it.second, getCreature()); } if (mostDamageCreature) { if (mostDamageCreature != lastHitCreature && mostDamageCreature != lastHitCreatureMaster) { - Creature* mostDamageCreatureMaster = mostDamageCreature->getMaster(); + auto mostDamageCreatureMaster = mostDamageCreature->getMaster(); if (lastHitCreature != mostDamageCreatureMaster && (lastHitCreatureMaster == nullptr || mostDamageCreatureMaster != lastHitCreatureMaster)) { - mostDamageUnjustified = mostDamageCreature->onKilledCreature(this, false); + mostDamageUnjustified = mostDamageCreature->onKilledCreature(getCreature(), false); } } } @@ -714,30 +721,27 @@ void Creature::onDeath() if (master) { setMaster(nullptr); - if (dynamic_cast(this) != nullptr) { - decrementReferenceCounter(); - } } if (droppedCorpse) { - g_game.removeCreature(this, false); + g_game.removeCreature(getCreature(), false); } } -bool Creature::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) +bool Creature::dropCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { if (!lootDrop && getMonster()) { if (master) { //scripting event - onDeath const CreatureEventList& deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH); for (CreatureEvent* deathEvent : deathEvents) { - deathEvent->executeOnDeath(this, nullptr, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); + deathEvent->executeOnDeath(getCreature(), nullptr, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } } g_game.addMagicEffect(getPosition(), CONST_ME_POFF); } else { - Item* splash; + ItemPtr splash; switch (getRace()) { case RACE_VENOM: splash = Item::CreateItem(ITEM_FULLSPLASH, FLUID_SLIME); @@ -752,22 +756,22 @@ bool Creature::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreatur break; } - Tile* tile = getTile(); - + TilePtr tile = getTile(); + CylinderPtr c_tile = tile; if (splash) { - g_game.internalAddItem(tile, splash, INDEX_WHEREEVER, FLAG_NOLIMIT); + g_game.internalAddItem(c_tile, splash, INDEX_WHEREEVER, FLAG_NOLIMIT); g_game.startDecay(splash); } - Item* corpse = getCorpse(lastHitCreature, mostDamageCreature); + ItemPtr corpse = getCorpse(lastHitCreature, mostDamageCreature); if (corpse) { - g_game.internalAddItem(tile, corpse, INDEX_WHEREEVER, FLAG_NOLIMIT); + g_game.internalAddItem(c_tile, corpse, INDEX_WHEREEVER, FLAG_NOLIMIT); g_game.startDecay(corpse); } //scripting event - onDeath for (CreatureEvent* deathEvent : getCreatureEvents(CREATURE_EVENT_DEATH)) { - deathEvent->executeOnDeath(this, corpse, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); + deathEvent->executeOnDeath(getCreature(), corpse, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } if (corpse) { @@ -787,7 +791,7 @@ bool Creature::hasBeenAttacked(uint32_t attackerId) return (OTSYS_TIME() - it->second.ticks) <= g_config.getNumber(ConfigManager::PZ_LOCKED); } -Item* Creature::getCorpse(Creature*, Creature*) +ItemPtr Creature::getCorpse(const CreaturePtr&, const CreaturePtr&) { return Item::CreateItem(getLookCorpse()); } @@ -803,7 +807,8 @@ void Creature::changeHealth(int32_t healthChange, bool sendHealthChange/* = true } if (sendHealthChange && oldHealth != health) { - g_game.addCreatureHealth(this); + CreatureConstPtr c_creature = this->getCreature(); + g_game.addCreatureHealth(c_creature); // this is broken or something idk. } if (health <= 0) { @@ -811,26 +816,26 @@ void Creature::changeHealth(int32_t healthChange, bool sendHealthChange/* = true } } -void Creature::gainHealth(Creature* healer, int32_t healthGain) +void Creature::gainHealth(const CreaturePtr& healer, int32_t healthGain) { changeHealth(healthGain); if (healer) { - healer->onTargetCreatureGainHealth(this, healthGain); + healer->onTargetCreatureGainHealth(std::dynamic_pointer_cast(shared_from_this()), healthGain); } } -void Creature::drainHealth(Creature* attacker, int32_t damage) +void Creature::drainHealth(const CreaturePtr& attacker, int32_t damage) { changeHealth(-damage, false); if (attacker) { - attacker->onAttackedCreatureDrainHealth(this, damage); + attacker->onAttackedCreatureDrainHealth(std::dynamic_pointer_cast(shared_from_this()), damage); } else { lastHitCreatureId = 0; } } -BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, +BlockType_t Creature::blockHit(const CreaturePtr& attacker, CombatType_t combatType, int32_t& damage, bool checkDefense /* = false */, bool checkArmor /* = false */, bool /* field = false */, bool /* ignoreResistances = false */) { BlockType_t blockType = BLOCK_NONE; @@ -881,7 +886,7 @@ BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int3 } if (attacker) { - attacker->onAttackedCreature(this); + attacker->onAttackedCreature(std::dynamic_pointer_cast(shared_from_this())); attacker->onAttackedCreatureBlockHit(blockType); } @@ -889,7 +894,7 @@ BlockType_t Creature::blockHit(Creature* attacker, CombatType_t combatType, int3 return blockType; } -bool Creature::setAttackedCreature(Creature* creature) +bool Creature::setAttackedCreature(const CreaturePtr& creature) { if (creature) { const Position& creaturePos = creature->getPosition(); @@ -905,13 +910,13 @@ bool Creature::setAttackedCreature(Creature* creature) attackedCreature = nullptr; } - for (Creature* summon : summons) { + for (CreaturePtr summon : summons) { summon->setAttackedCreature(creature); } return true; } -void Creature::getPathSearchParams(const Creature*, FindPathParams& fpp) const +void Creature::getPathSearchParams(const CreatureConstPtr&, FindPathParams& fpp) const { fpp.fullPathSearch = !hasFollowPath; fpp.clearSight = true; @@ -926,7 +931,7 @@ void Creature::goToFollowCreature() FindPathParams fpp; getPathSearchParams(followCreature, fpp); - Monster* monster = getMonster(); + auto monster = getMonster(); if (monster && !monster->getMaster() && (monster->isFleeing() || fpp.maxTargetDist > 1)) { Direction dir = DIRECTION_NONE; @@ -967,7 +972,7 @@ void Creature::goToFollowCreature() onFollowCreatureComplete(followCreature); } -bool Creature::setFollowCreature(Creature* creature) +bool Creature::setFollowCreature(const CreaturePtr& creature) { if (creature) { if (followCreature == creature) { @@ -1003,7 +1008,7 @@ bool Creature::setFollowCreature(Creature* creature) return true; } -double Creature::getDamageRatio(Creature* attacker) const +double Creature::getDamageRatio(const CreaturePtr& attacker) const { uint32_t totalDamage = 0; uint32_t attackerDamage = 0; @@ -1023,12 +1028,12 @@ double Creature::getDamageRatio(Creature* attacker) const return (static_cast(attackerDamage) / totalDamage); } -uint64_t Creature::getGainedExperience(Creature* attacker) const +uint64_t Creature::getGainedExperience(const CreaturePtr& attacker) const { return std::floor(getDamageRatio(attacker) * getLostExperience()); } -void Creature::addDamagePoints(Creature* attacker, int32_t damagePoints) +void Creature::addDamagePoints(const CreaturePtr& attacker, int32_t damagePoints) { if (damagePoints <= 0) { return; @@ -1064,7 +1069,7 @@ void Creature::onEndCondition(ConditionType_t) void Creature::onTickCondition(ConditionType_t type, bool& bRemove) { - const MagicField* field = getTile()->getFieldItem(); + const auto field = getTile()->getFieldItem(); if (!field) { return; } @@ -1109,12 +1114,12 @@ void Creature::onAttacked() // } -void Creature::onAttackedCreatureDrainHealth(Creature* target, int32_t points) +void Creature::onAttackedCreatureDrainHealth(const CreaturePtr& target, int32_t points) { - target->addDamagePoints(this, points); + target->addDamagePoints(std::dynamic_pointer_cast(shared_from_this()), points); } -bool Creature::onKilledCreature(Creature* target, bool) +bool Creature::onKilledCreature(const CreaturePtr& target, bool) { if (master) { master->onKilledCreature(target); @@ -1123,12 +1128,12 @@ bool Creature::onKilledCreature(Creature* target, bool) //scripting event - onKill const CreatureEventList& killEvents = getCreatureEvents(CREATURE_EVENT_KILL); for (CreatureEvent* killEvent : killEvents) { - killEvent->executeOnKill(this, target); + killEvent->executeOnKill(std::dynamic_pointer_cast(shared_from_this()), target); } return false; } -void Creature::onGainExperience(uint64_t gainExp, Creature* target) +void Creature::onGainExperience(uint64_t gainExp, const CreaturePtr& target) { if (gainExp == 0 || !master) { return; @@ -1148,30 +1153,30 @@ void Creature::onGainExperience(uint64_t gainExp, Creature* target) message.primary.color = TEXTCOLOR_WHITE_EXP; message.primary.value = gainExp; - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendTextMessage(message); + for (CreaturePtr spectator : spectators) + { + if (auto player = spectator->getPlayer()) + { + player->sendTextMessage(message); + } } } -bool Creature::setMaster(Creature* newMaster) { +bool Creature::setMaster(const CreaturePtr& newMaster) { if (!newMaster && !master) { return false; } if (newMaster) { - incrementReferenceCounter(); - newMaster->summons.push_back(this); + newMaster->summons.push_back(std::dynamic_pointer_cast(shared_from_this())); } - Creature* oldMaster = master; + CreaturePtr oldMaster = master; master = newMaster; if (oldMaster) { - auto summon = std::find(oldMaster->summons.begin(), oldMaster->summons.end(), this); - if (summon != oldMaster->summons.end()) { + if (auto summon = std::find(oldMaster->summons.begin(), oldMaster->summons.end(), this->getCreature()); summon != oldMaster->summons.end()) { oldMaster->summons.erase(summon); - decrementReferenceCounter(); } } return true; @@ -1195,7 +1200,7 @@ bool Creature::addCondition(Condition* condition, bool force/* = false*/) if (condition->getType() == CONDITION_PARALYZE && this->getPlayer() && this->getPlayer()->isWearingImbuedItem() && this->getID() != casterId) { int32_t chance = 0; for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = this->getPlayer()->getInventoryItem(slot); + auto item = this->getPlayer()->getInventoryItem(slot); if (item && item->hasImbuementType(IMBUEMENT_TYPE_PARALYSIS_DEFLECTION)) { for (auto imbuement : item->getImbuements()) { if (imbuement->imbuetype == IMBUEMENT_TYPE_PARALYSIS_DEFLECTION) { @@ -1208,12 +1213,12 @@ bool Creature::addCondition(Condition* condition, bool force/* = false*/) if (chance > 0) { - Creature* caster = g_game.getCreatureByID(casterId); - if (Player* player = caster->getPlayer()) { + const auto caster = g_game.getCreatureByID(casterId); + if (const auto player = caster->getPlayer()) { player->addCondition(condition); return true; } - if (Monster* monster = caster->getMonster()) { + if (const auto monster = caster->getMonster()) { int32_t roll = uniform_random(1, 100); if (roll <= chance) { monster->addCondition(condition); @@ -1225,12 +1230,12 @@ bool Creature::addCondition(Condition* condition, bool force/* = false*/) Condition* prevCond = getCondition(condition->getType(), condition->getId(), condition->getSubId()); if (prevCond) { - prevCond->addCondition(this, condition); + prevCond->addCondition(std::dynamic_pointer_cast(shared_from_this()), condition); delete condition; return true; } - if (condition->startCondition(this)) { + if (condition->startCondition(std::dynamic_pointer_cast(shared_from_this()))) { conditions.push_back(condition); onAddCondition(condition->getType()); return true; @@ -1273,7 +1278,7 @@ void Creature::removeCondition(ConditionType_t type, bool force/* = false*/) it = conditions.erase(it); - condition->endCondition(this); + condition->endCondition(std::dynamic_pointer_cast(shared_from_this())); delete condition; onEndCondition(type); @@ -1300,7 +1305,7 @@ void Creature::removeCondition(ConditionType_t type, ConditionId_t conditionId, it = conditions.erase(it); - condition->endCondition(this); + condition->endCondition(std::dynamic_pointer_cast(shared_from_this())); delete condition; onEndCondition(type); @@ -1323,7 +1328,7 @@ void Creature::removeCombatCondition(ConditionType_t type) void Creature::removeCondition(Condition* condition, bool force/* = false*/) { - auto it = std::find(conditions.begin(), conditions.end(), condition); + auto it = std::ranges::find(conditions, condition); if (it == conditions.end()) { return; } @@ -1338,7 +1343,7 @@ void Creature::removeCondition(Condition* condition, bool force/* = false*/) conditions.erase(it); - condition->endCondition(this); + condition->endCondition(std::dynamic_pointer_cast(shared_from_this())); onEndCondition(condition->getType()); delete condition; } @@ -1367,16 +1372,16 @@ void Creature::executeConditions(uint32_t interval) { ConditionList tempConditions{ conditions }; for (Condition* condition : tempConditions) { - auto it = std::find(conditions.begin(), conditions.end(), condition); + auto it = std::ranges::find(conditions, condition); if (it == conditions.end()) { continue; } - if (!condition->executeCondition(this, interval)) { - it = std::find(conditions.begin(), conditions.end(), condition); + if (!condition->executeCondition(std::dynamic_pointer_cast(shared_from_this()), interval)) { + it = std::ranges::find(conditions, condition); if (it != conditions.end()) { conditions.erase(it); - condition->endCondition(this); + condition->endCondition(std::dynamic_pointer_cast(shared_from_this())); onEndCondition(condition->getType()); delete condition; } @@ -1434,7 +1439,7 @@ int64_t Creature::getStepDuration() const } uint32_t calculatedStepSpeed; - uint32_t groundSpeed; + uint32_t groundSpeed = 0; int32_t stepSpeed = getStepSpeed(); if (stepSpeed > -Creature::speedB) { @@ -1446,20 +1451,22 @@ int64_t Creature::getStepDuration() const calculatedStepSpeed = 1; } - Item* ground = tile->getGround(); - if (ground) { - groundSpeed = Item::items[ground->getID()].speed; - if (groundSpeed == 0) { - groundSpeed = 150; + if (auto ground = tile.lock()->getGround()) + { + if (ground) { + groundSpeed = Item::items[ground->getID()].speed; + if (groundSpeed == 0) { + groundSpeed = 150; + } } - } else { + } else { groundSpeed = 150; } - + double duration = std::floor(1000 * groundSpeed / calculatedStepSpeed); int64_t stepDuration = std::ceil(duration / 50) * 50; - const Monster* monster = getMonster(); + const MonsterConstPtr monster = getMonster(); if (monster && monster->isTargetNearby() && !monster->isFleeing() && !monster->getMaster()) { stepDuration *= 2; } @@ -1551,7 +1558,7 @@ bool Creature::unregisterCreatureEvent(const std::string& name) return true; } -CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) +CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) const { CreatureEventList tmpEventList; @@ -1656,17 +1663,18 @@ bool FrozenPathingConditionCall::operator()(const Position& startPos, const Posi bool Creature::isInvisible() const { - return std::find_if(conditions.begin(), conditions.end(), [] (const Condition* condition) { + return std::ranges::find_if(conditions, [] (const Condition* condition) { return condition->getType() == CONDITION_INVISIBLE; }) != conditions.end(); } -bool Creature::getPathTo(const Position& targetPos, std::vector& dirList, const FindPathParams& fpp) const +bool Creature::getPathTo(const Position& targetPos, std::vector& dirList, const FindPathParams& fpp) { - return g_game.map.getPathMatching(*this, dirList, FrozenPathingConditionCall(targetPos), fpp); + CreaturePtr t_c = getCreature(); + return g_game.map.getPathMatching(t_c, dirList, FrozenPathingConditionCall(targetPos), fpp); } -bool Creature::getPathTo(const Position& targetPos, std::vector& 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::vector& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch /*= true*/, bool clearSight /*= true*/, int32_t maxSearchDist /*= 0*/) { FindPathParams fpp; fpp.fullPathSearch = fullPathSearch; diff --git a/src/creature.h b/src/creature.h index 5a16e114..ac5ebc00 100644 --- a/src/creature.h +++ b/src/creature.h @@ -52,6 +52,15 @@ class Npc; class Item; class Tile; +using PlayerPtr = std::shared_ptr; +using PlayerConstPtr = std::shared_ptr; + +using MonsterPtr = std::shared_ptr; +using MonsterConstPtr = std::shared_ptr; + +using NpcPtr = std::shared_ptr; +using NpcConstPtr = std::shared_ptr; + 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); @@ -75,7 +84,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, public SharedObject { protected: Creature(); @@ -89,37 +98,44 @@ class Creature : virtual public Thing Creature(const Creature&) = delete; Creature& operator=(const Creature&) = delete; - Creature* getCreature() override final { - return this; + CreaturePtr getCreature() override final { + return dynamic_shared_this(); } - const Creature* getCreature() const override final { - return this; + + CreatureConstPtr getCreature() const override final { + return dynamic_shared_this(); } - virtual Player* getPlayer() { + + virtual PlayerPtr getPlayer() { return nullptr; } - virtual const Player* getPlayer() const { + + virtual PlayerConstPtr getPlayer() const { return nullptr; } - virtual Npc* getNpc() { + + virtual NpcPtr getNpc() { return nullptr; } - virtual const Npc* getNpc() const { + + virtual NpcConstPtr getNpc() const { return nullptr; } - virtual Monster* getMonster() { + + virtual MonsterPtr getMonster() { return nullptr; } - virtual const Monster* getMonster() const { + + virtual MonsterConstPtr getMonster() const { return nullptr; } virtual const std::string& getName() const = 0; virtual const std::string& getNameDescription() const = 0; - + virtual CreatureType_t getType() const = 0; - virtual void setID() = 0; + void setRemoved() { isInternalRemoved = true; } @@ -127,25 +143,31 @@ class Creature : virtual public Thing uint32_t getID() const { return id; } + virtual void removeList() = 0; virtual void addList() = 0; virtual bool canSee(const Position& pos) const; - virtual bool canSeeCreature(const Creature* creature) const; + virtual bool canSeeCreature(const CreatureConstPtr& creature) const; virtual RaceType_t getRace() const { return RACE_NONE; } + virtual Skulls_t getSkull() const { return skull; } - virtual Skulls_t getSkullClient(const Creature* creature) const { + + virtual Skulls_t getSkullClient(const CreatureConstPtr& creature) const { return creature->getSkull(); } + void setSkull(Skulls_t newSkull); + Direction getDirection() const { return direction; } + void setDirection(Direction dir) { direction = dir; } @@ -153,6 +175,7 @@ class Creature : virtual public Thing bool isHealthHidden() const { return hiddenHealth; } + void setHiddenHealth(bool b) { hiddenHealth = b; } @@ -164,19 +187,24 @@ class Creature : virtual public Thing int32_t getThrowRange() const override final { return 1; } + bool isPushable() const override { return getWalkDelay() <= 0; } + bool isRemoved() const override final { return isInternalRemoved; } + virtual bool canSeeInvisibility() const { return false; } + virtual bool isInGhostMode() const { return false; } - virtual bool canSeeGhostMode(const Creature*) const { + + virtual bool canSeeGhostMode(const CreatureConstPtr&) const { return false; } @@ -187,12 +215,15 @@ class Creature : virtual public Thing int64_t getEventStepTicks(bool onlyDelay = false) const; int64_t getStepDuration(Direction dir) const; int64_t getStepDuration() const; + virtual int32_t getStepSpeed() const { return getSpeed(); } + int32_t getSpeed() const { return baseSpeed + varSpeed; } + void setSpeed(int32_t varSpeedDelta) { int32_t oldSpeed = getSpeed(); varSpeed = varSpeedDelta; @@ -208,12 +239,15 @@ class Creature : virtual public Thing void setBaseSpeed(uint32_t newBaseSpeed) { baseSpeed = newBaseSpeed; } + uint32_t getBaseSpeed() const { return baseSpeed; } + void setDodgeChance(uint8_t newDodgeChance) { dodgeChance = newDodgeChance; } + uint8_t getDodgeChance() const { return dodgeChance; } @@ -237,15 +271,19 @@ class Creature : virtual public Thing int32_t getHealth() const { return health; } + virtual int32_t getMaxHealth() const { return healthMax; } + bool isDead() const { return health <= 0; } + void setDrunkenness(uint8_t newDrunkenness) { drunkenness = newDrunkenness; } + uint8_t getDrunkenness() const { return drunkenness; } @@ -253,13 +291,17 @@ class Creature : virtual public Thing const Outfit_t getCurrentOutfit() const { return currentOutfit; } + void setCurrentOutfit(Outfit_t outfit) { currentOutfit = outfit; } + const Outfit_t getDefaultOutfit() const { return defaultOutfit; } + bool isInvisible() const; + ZoneType_t getZone() const { return getTile()->getZone(); } @@ -278,52 +320,57 @@ class Creature : virtual public Thing virtual void onWalkComplete() {} //follow functions - Creature* getFollowCreature() const { + CreaturePtr getFollowCreature() const { return followCreature; } - virtual bool setFollowCreature(Creature* creature); + + virtual bool setFollowCreature(const CreaturePtr& creature); //follow events - virtual void onFollowCreature(const Creature*) {} - virtual void onFollowCreatureComplete(const Creature*) {} + virtual void onFollowCreature(const CreatureConstPtr&) {} + virtual void onFollowCreatureComplete(const CreatureConstPtr&) {} //combat functions - Creature* getAttackedCreature() { + CreaturePtr getAttackedCreature() { return attackedCreature; } - virtual bool setAttackedCreature(Creature* creature); - virtual BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, + virtual bool setAttackedCreature(const CreaturePtr& creature); + virtual BlockType_t blockHit(const CreaturePtr& attacker, CombatType_t combatType, int32_t& damage, bool checkDefense = false, bool checkArmor = false, bool field = false, bool ignoreResistances = false); - bool setMaster(Creature* newMaster); + bool setMaster(const CreaturePtr& newMaster); void removeMaster() { if (master) { - master = nullptr; - decrementReferenceCounter(); + master.reset(); } } bool isSummon() const { + // could use an optional here return master != nullptr; } - Creature* getMaster() const { + + CreaturePtr getMaster() const { return master; } - const std::list& getSummons() const { + const std::list& getSummons() const { return summons; } virtual int32_t getArmor() const { return 0; } + virtual int32_t getDefense() const { return 0; } + virtual float getAttackFactor() const { return 1.0f; } + virtual float getDefenseFactor() const { return 1.0f; } @@ -345,32 +392,36 @@ class Creature : virtual public Thing virtual bool isImmune(ConditionType_t type) const; virtual bool isImmune(CombatType_t type) const; virtual bool isSuppress(ConditionType_t type) const; + virtual uint32_t getDamageImmunities() const { return 0; } + virtual uint32_t getConditionImmunities() const { return 0; } + virtual uint32_t getConditionSuppressions() const { return 0; } + virtual bool isAttackable() const { return true; } virtual void changeHealth(int32_t healthChange, bool sendHealthChange = true); - void gainHealth(Creature* healer, int32_t healthGain); - virtual void drainHealth(Creature* attacker, int32_t damage); + void gainHealth(const CreaturePtr& healer, int32_t healthGain); + virtual void drainHealth(const CreaturePtr& attacker, int32_t damage); - virtual bool challengeCreature(Creature*, bool) { + virtual bool challengeCreature(const CreaturePtr&, bool) { return false; } - CreatureVector getKillers(); + CreatureVector getKillers() const; void onDeath(); - virtual uint64_t getGainedExperience(Creature* attacker) const; - void addDamagePoints(Creature* attacker, int32_t damagePoints); + virtual uint64_t getGainedExperience(const CreaturePtr& attacker) const; + void addDamagePoints(const CreaturePtr& attacker, int32_t damagePoints); bool hasBeenAttacked(uint32_t attackerId); //combat event functions @@ -379,12 +430,12 @@ class Creature : virtual public Thing virtual void onEndCondition(ConditionType_t type); void onTickCondition(ConditionType_t type, bool& bRemove); virtual void onCombatRemoveCondition(Condition* condition); - virtual void onAttackedCreature(Creature*, bool = true) {} + virtual void onAttackedCreature(const CreaturePtr&, bool = true) {} virtual void onAttacked(); - virtual void onAttackedCreatureDrainHealth(Creature* target, int32_t points); - virtual void onTargetCreatureGainHealth(Creature*, int32_t) {} - virtual bool onKilledCreature(Creature* target, bool lastHit = true); - virtual void onGainExperience(uint64_t gainExp, Creature* target); + virtual void onAttackedCreatureDrainHealth(const CreaturePtr& target, int32_t points); + virtual void onTargetCreatureGainHealth(const CreaturePtr&, int32_t) {} + virtual bool onKilledCreature(const CreaturePtr& target, bool lastHit = true); + virtual void onGainExperience(uint64_t gainExp, const CreaturePtr& target); virtual void onAttackedCreatureBlockHit(BlockType_t) {} virtual void onBlockHit() {} virtual void onChangeZone(ZoneType_t zone); @@ -400,22 +451,20 @@ class Creature : virtual public Thing virtual void onWalk(); virtual bool getNextStep(Direction& dir, uint32_t& flags); - 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(TilePtr tile, const Position& pos); + virtual void onUpdateTileItem(const TilePtr& tile, const Position& pos, const ItemPtr& oldItem, + const ItemType& oldType, const ItemPtr& newItem, const ItemType& newType); + virtual void onRemoveTileItem(const TilePtr& tile, const Position& pos, const ItemType& iType, + const ItemPtr& item); - virtual void onCreatureAppear(Creature* creature, bool isLogin); - virtual void onRemoveCreature(Creature* creature, bool isLogout); - virtual void onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport); + virtual void onCreatureAppear(const CreaturePtr& creature, bool isLogin); + virtual void onRemoveCreature(const CreaturePtr& creature, bool isLogout); + virtual void onCreatureMove(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, + const TilePtr& oldTile, const Position& oldPos, bool teleport); virtual void onAttackedCreatureDisappear(bool) {} virtual void onFollowCreatureDisappear(bool) {} - - virtual void onCreatureSay(Creature*, SpeakClasses, const std::string&) {} - + virtual void onCreatureSay(const CreaturePtr&, SpeakClasses, const std::string&) {} virtual void onPlacedCreature() {} virtual bool getCombatValues(int32_t&, int32_t&) { @@ -425,19 +474,24 @@ class Creature : virtual public Thing size_t getSummonCount() const { return summons.size(); } + void setDropLoot(bool lootDrop) { this->lootDrop = lootDrop; } + void setSkillLoss(bool skillLoss) { this->skillLoss = skillLoss; } + void setUseDefense(bool useDefense) { canUseDefense = useDefense; } + void setMovementBlocked(bool state) { movementBlocked = state; cancelNextWalk = true; } + bool isMovementBlocked() const { return movementBlocked; } @@ -446,23 +500,43 @@ class Creature : virtual public Thing bool registerCreatureEvent(const std::string& name); bool unregisterCreatureEvent(const std::string& name); - Cylinder* getParent() const override final { - return tile; - } - void setParent(Cylinder* cylinder) override final { - tile = static_cast(cylinder); - position = tile->getPosition(); + CylinderPtr getParent() override final { + [[likely]] if (auto shared_ptr = tile.lock()) + { + return shared_ptr; + // this was never casted; + // It is a TilePtr which is a derived class of CylinderPtr + // is it implicitly casted here? + } + [[unlikely]] return nullptr; + } + + void setParent(std::weak_ptr cylinder) override final { + if (const auto shared_ptr = cylinder.lock()) + { + tile = shared_ptr->getTile(); + position = shared_ptr->getPosition(); + } } const Position& getPosition() const override final { return position; } - Tile* getTile() override final { - return tile; + TilePtr getTile() override final { + [[likely]] if (auto shared_ptr = tile.lock()) + { + return shared_ptr; + } + [[unlikely]] return nullptr; } - const Tile* getTile() const override final { - return tile; + + TileConstPtr getTile() const override final { + [[likely]] if (auto shared_ptr = tile.lock()) + { + return shared_ptr; + } + [[unlikely]] return nullptr; } int32_t getWalkCache(const Position& pos) const; @@ -470,25 +544,17 @@ class Creature : virtual public Thing 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); - double getDamageRatio(Creature* attacker) const; + double getDamageRatio(const CreaturePtr& attacker) const; - bool getPathTo(const Position& targetPos, std::vector& dirList, const FindPathParams& fpp) const; - bool getPathTo(const Position& targetPos, std::vector& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 0) const; - - void incrementReferenceCounter() { - ++referenceCounter; - } - void decrementReferenceCounter() { - if (--referenceCounter == 0) { - delete this; - } - } + bool getPathTo(const Position& targetPos, std::vector& dirList, const FindPathParams& fpp); + bool getPathTo(const Position& targetPos, std::vector& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 0); protected: virtual bool useCacheMap() const { @@ -510,19 +576,18 @@ class Creature : virtual public Thing using CountMap = std::map; CountMap damageMap; - std::list summons; + std::list summons; CreatureEventList eventsList; ConditionList conditions; std::vector listWalkDir; - Tile* tile = nullptr; - Creature* attackedCreature = nullptr; - Creature* master = nullptr; - Creature* followCreature = nullptr; + TileWeakPtr tile; + CreaturePtr attackedCreature = nullptr; + CreaturePtr master = nullptr; + CreaturePtr followCreature = nullptr; uint64_t lastStep = 0; - uint32_t referenceCounter = 0; uint32_t id = 0; uint32_t scriptEventsBitField = 0; uint32_t eventWalk = 0; @@ -566,13 +631,15 @@ class Creature : virtual public Thing bool hasEventRegistered(CreatureEventType_t event) const { return (0 != (scriptEventsBitField & (static_cast(1) << event))); } - CreatureEventList getCreatureEvents(CreatureEventType_t type); + + CreatureEventList getCreatureEvents(CreatureEventType_t type) const; void updateMapCache(); - void updateTileCache(const Tile* tile, int32_t dx, int32_t dy); - void updateTileCache(const Tile* tile, const Position& pos); - void onCreatureDisappear(const Creature* creature, bool isLogout); + void updateTileCache(TilePtr tile, int32_t dx, int32_t dy); + void updateTileCache(TilePtr tile, const Position& pos); + void onCreatureDisappear(const CreatureConstPtr& creature, bool isLogout); virtual void doAttacking(uint32_t) {} + virtual bool hasExtraSwing() { return false; } @@ -580,14 +647,17 @@ class Creature : virtual public Thing virtual uint64_t getLostExperience() const { return 0; } - virtual void dropLoot(Container*, Creature*) {} + + virtual void dropLoot(const ContainerPtr& corpse, const CreaturePtr& lastHitKiller) {} + virtual uint16_t getLookCorpse() const { return 0; } - 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); + + virtual void getPathSearchParams(const CreatureConstPtr& creature, FindPathParams& fpp) const; + virtual void death(const CreaturePtr&) {} + virtual bool dropCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); + virtual ItemPtr getCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature); friend class Game; friend class Map; diff --git a/src/creatureevent.cpp b/src/creatureevent.cpp index 1caf1b0c..1b5604f2 100644 --- a/src/creatureevent.cpp +++ b/src/creatureevent.cpp @@ -61,7 +61,7 @@ bool CreatureEvents::registerEvent(Event_ptr event, const pugi::xml_node&) //if there was an event with the same that is not loaded //(happens when reloading), it is reused if (!oldEvent->isLoaded() && oldEvent->getEventType() == creatureEvent->getEventType()) { - oldEvent->copyEvent(creatureEvent.get()); + oldEvent->copyEvent(creatureEvent); } return false; @@ -85,7 +85,7 @@ bool CreatureEvents::registerLuaEvent(CreatureEvent* event) //if there was an event with the same that is not loaded //(happens when reloading), it is reused if (!oldEvent->isLoaded() && oldEvent->getEventType() == creatureEvent->getEventType()) { - oldEvent->copyEvent(creatureEvent.get()); + oldEvent->copyEvent(creatureEvent); } return false; @@ -107,7 +107,7 @@ CreatureEvent* CreatureEvents::getEventByName(const std::string& name, bool forc return nullptr; } -bool CreatureEvents::playerLogin(Player* player) const +bool CreatureEvents::playerLogin(const PlayerPtr& player) const { //fire global event if is registered for (const auto& it : creatureEvents) { @@ -120,12 +120,12 @@ bool CreatureEvents::playerLogin(Player* player) const return true; } -bool CreatureEvents::playerLogout(Player* player) const +bool CreatureEvents::playerLogout(const PlayerPtr& player) const { //fire global event if is registered - for (const auto& it : creatureEvents) { - if (it.second.getEventType() == CREATURE_EVENT_LOGOUT) { - if (!it.second.executeOnLogout(player)) { + for (const auto& val : creatureEvents | std::views::values) { + if (val.getEventType() == CREATURE_EVENT_LOGOUT) { + if (!val.executeOnLogout(player)) { return false; } } @@ -133,12 +133,12 @@ bool CreatureEvents::playerLogout(Player* player) const return true; } -bool CreatureEvents::playerAdvance(Player* player, skills_t skill, uint32_t oldLevel, +bool CreatureEvents::playerAdvance(const PlayerPtr& player, skills_t skill, uint32_t oldLevel, uint32_t newLevel) { - for (auto& it : creatureEvents) { - if (it.second.getEventType() == CREATURE_EVENT_ADVANCE) { - if (!it.second.executeAdvance(player, skill, oldLevel, newLevel)) { + for (auto& val : creatureEvents | std::views::values) { + if (val.getEventType() == CREATURE_EVENT_ADVANCE) { + if (!val.executeAdvance(player, skill, oldLevel, newLevel)) { return false; } } @@ -249,7 +249,7 @@ std::string_view CreatureEvent::getScriptEventName() const } } -void CreatureEvent::copyEvent(CreatureEvent* creatureEvent) +void CreatureEvent::copyEvent(const CreatureEvent_ptr& creatureEvent) { scriptId = creatureEvent->scriptId; scriptInterface = creatureEvent->scriptInterface; @@ -265,7 +265,7 @@ void CreatureEvent::clearEvent() loaded = false; } -bool CreatureEvent::executeOnLogin(Player* player) const +bool CreatureEvent::executeOnLogin(const PlayerPtr& player) const { //onLogin(player) if (!scriptInterface->reserveScriptEnv()) { @@ -279,12 +279,12 @@ bool CreatureEvent::executeOnLogin(Player* player) const lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface->callFunction(1); } -bool CreatureEvent::executeOnLogout(Player* player) const +bool CreatureEvent::executeOnLogout(const PlayerPtr& player) const { //onLogout(player) if (!scriptInterface->reserveScriptEnv()) { @@ -298,12 +298,12 @@ bool CreatureEvent::executeOnLogout(Player* player) const lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface->callFunction(1); } -bool CreatureEvent::executeOnThink(Creature* creature, uint32_t interval) +bool CreatureEvent::executeOnThink(const CreaturePtr& creature, uint32_t interval) const { //onThink(creature, interval) if (!scriptInterface->reserveScriptEnv()) { @@ -317,14 +317,14 @@ bool CreatureEvent::executeOnThink(Creature* creature, uint32_t interval) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); lua_pushinteger(L, interval); return scriptInterface->callFunction(2); } -bool CreatureEvent::executeOnPrepareDeath(Creature* creature, Creature* killer) +bool CreatureEvent::executeOnPrepareDeath(const CreaturePtr& creature, const CreaturePtr& killer) const { //onPrepareDeath(creature, killer) if (!scriptInterface->reserveScriptEnv()) { @@ -339,11 +339,11 @@ bool CreatureEvent::executeOnPrepareDeath(Creature* creature, Creature* killer) scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); if (killer) { - LuaScriptInterface::pushUserdata(L, killer); + LuaScriptInterface::pushSharedPtr(L, killer); LuaScriptInterface::setCreatureMetatable(L, -1, killer); } else { lua_pushnil(L); @@ -352,7 +352,7 @@ bool CreatureEvent::executeOnPrepareDeath(Creature* creature, Creature* killer) return scriptInterface->callFunction(2); } -bool CreatureEvent::executeOnDeath(Creature* creature, Item* corpse, Creature* killer, Creature* mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) +bool CreatureEvent::executeOnDeath(const CreaturePtr& creature, const ItemPtr& corpse, const CreaturePtr& killer, const CreaturePtr& mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const { //onDeath(creature, corpse, killer, mostDamageKiller, lastHitUnjustified, mostDamageUnjustified) if (!scriptInterface->reserveScriptEnv()) { @@ -366,20 +366,20 @@ bool CreatureEvent::executeOnDeath(Creature* creature, Item* corpse, Creature* k lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushThing(L, corpse); if (killer) { - LuaScriptInterface::pushUserdata(L, killer); + LuaScriptInterface::pushSharedPtr(L, killer); LuaScriptInterface::setCreatureMetatable(L, -1, killer); } else { lua_pushnil(L); } if (mostDamageKiller) { - LuaScriptInterface::pushUserdata(L, mostDamageKiller); + LuaScriptInterface::pushSharedPtr(L, mostDamageKiller); LuaScriptInterface::setCreatureMetatable(L, -1, mostDamageKiller); } else { lua_pushnil(L); @@ -391,8 +391,8 @@ bool CreatureEvent::executeOnDeath(Creature* creature, Item* corpse, Creature* k return scriptInterface->callFunction(6); } -bool CreatureEvent::executeAdvance(Player* player, skills_t skill, uint32_t oldLevel, - uint32_t newLevel) +bool CreatureEvent::executeAdvance(const PlayerPtr& player, skills_t skill, uint32_t oldLevel, + uint32_t newLevel) const { //onAdvance(player, skill, oldLevel, newLevel) if (!scriptInterface->reserveScriptEnv()) { @@ -406,7 +406,7 @@ bool CreatureEvent::executeAdvance(Player* player, skills_t skill, uint32_t oldL lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, static_cast(skill)); lua_pushinteger(L, oldLevel); @@ -415,7 +415,7 @@ bool CreatureEvent::executeAdvance(Player* player, skills_t skill, uint32_t oldL return scriptInterface->callFunction(4); } -void CreatureEvent::executeOnKill(Creature* creature, Creature* target) +void CreatureEvent::executeOnKill(const CreaturePtr& creature, const CreaturePtr& target) const { //onKill(creature, target) if (!scriptInterface->reserveScriptEnv()) { @@ -429,14 +429,14 @@ void CreatureEvent::executeOnKill(Creature* creature, Creature* target) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setCreatureMetatable(L, -1, target); scriptInterface->callVoidFunction(2); } -void CreatureEvent::executeModalWindow(Player* player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) +void CreatureEvent::executeModalWindow(const PlayerPtr& player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const { //onModalWindow(player, modalWindowId, buttonId, choiceId) if (!scriptInterface->reserveScriptEnv()) { @@ -450,7 +450,7 @@ void CreatureEvent::executeModalWindow(Player* player, uint32_t modalWindowId, u lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, modalWindowId); @@ -460,7 +460,7 @@ void CreatureEvent::executeModalWindow(Player* player, uint32_t modalWindowId, u scriptInterface->callVoidFunction(4); } -bool CreatureEvent::executeTextEdit(Player* player, Item* item, const std::string& text) +bool CreatureEvent::executeTextEdit(const PlayerPtr& player, const ItemPtr& item, const std::string& text) const { //onTextEdit(player, item, text) if (!scriptInterface->reserveScriptEnv()) { @@ -474,7 +474,7 @@ bool CreatureEvent::executeTextEdit(Player* player, Item* item, const std::strin lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushThing(L, item); @@ -483,7 +483,7 @@ bool CreatureEvent::executeTextEdit(Player* player, Item* item, const std::strin return scriptInterface->callFunction(3); } -void CreatureEvent::executeHealthChange(Creature* creature, Creature* attacker, CombatDamage& damage) +void CreatureEvent::executeHealthChange(const CreaturePtr& creature, const CreaturePtr& attacker, CombatDamage& damage) const { //onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) if (!scriptInterface->reserveScriptEnv()) { @@ -497,10 +497,10 @@ void CreatureEvent::executeHealthChange(Creature* creature, Creature* attacker, lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); if (attacker) { - LuaScriptInterface::pushUserdata(L, attacker); + LuaScriptInterface::pushSharedPtr(L, attacker); LuaScriptInterface::setCreatureMetatable(L, -1, attacker); } else { lua_pushnil(L); @@ -526,7 +526,7 @@ void CreatureEvent::executeHealthChange(Creature* creature, Creature* attacker, scriptInterface->resetScriptEnv(); } -void CreatureEvent::executeManaChange(Creature* creature, Creature* attacker, CombatDamage& damage) { +void CreatureEvent::executeManaChange(const CreaturePtr& creature, const CreaturePtr& attacker, CombatDamage& damage) const { //onManaChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) if (!scriptInterface->reserveScriptEnv()) { std::cout << "[Error - CreatureEvent::executeManaChange] Call stack overflow" << std::endl; @@ -539,10 +539,10 @@ void CreatureEvent::executeManaChange(Creature* creature, Creature* attacker, Co lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); if (attacker) { - LuaScriptInterface::pushUserdata(L, attacker); + LuaScriptInterface::pushSharedPtr(L, attacker); LuaScriptInterface::setCreatureMetatable(L, -1, attacker); } else { lua_pushnil(L); @@ -563,7 +563,7 @@ void CreatureEvent::executeManaChange(Creature* creature, Creature* attacker, Co scriptInterface->resetScriptEnv(); } -void CreatureEvent::executeExtendedOpcode(Player* player, uint8_t opcode, const std::string& buffer) +void CreatureEvent::executeExtendedOpcode(const PlayerPtr& player, uint8_t opcode, const std::string& buffer) const { //onExtendedOpcode(player, opcode, buffer) if (!scriptInterface->reserveScriptEnv()) { @@ -578,7 +578,7 @@ void CreatureEvent::executeExtendedOpcode(Player* player, uint8_t opcode, const scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, opcode); diff --git a/src/creatureevent.h b/src/creatureevent.h index cb21b34e..b7eae6b8 100644 --- a/src/creatureevent.h +++ b/src/creatureevent.h @@ -4,9 +4,9 @@ #ifndef FS_CREATUREEVENT_H #define FS_CREATUREEVENT_H -#include "luascript.h" #include "baseevents.h" #include "enums.h" +#include "luascript.h" class CreatureEvent; using CreatureEvent_ptr = std::unique_ptr; @@ -54,21 +54,21 @@ class CreatureEvent final : public Event } void clearEvent(); - void copyEvent(CreatureEvent* creatureEvent); + void copyEvent(const CreatureEvent_ptr& creatureEvent); //scripting - bool executeOnLogin(Player* player) const; - bool executeOnLogout(Player* player) const; - bool executeOnThink(Creature* creature, uint32_t interval); - bool executeOnPrepareDeath(Creature* creature, Creature* killer); - bool executeOnDeath(Creature* creature, Item* corpse, Creature* killer, Creature* mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified); - void executeOnKill(Creature* creature, Creature* target); - bool executeAdvance(Player* player, skills_t, uint32_t, uint32_t); - void executeModalWindow(Player* player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId); - bool executeTextEdit(Player* player, Item* item, const std::string& text); - void executeHealthChange(Creature* creature, Creature* attacker, CombatDamage& damage); - void executeManaChange(Creature* creature, Creature* attacker, CombatDamage& damage); - void executeExtendedOpcode(Player* player, uint8_t opcode, const std::string& buffer); + bool executeOnLogin(const PlayerPtr& player) const; + bool executeOnLogout(const PlayerPtr& player) const; + bool executeOnThink(const CreaturePtr& creature, uint32_t interval) const; + bool executeOnPrepareDeath(const CreaturePtr& creature, const CreaturePtr& killer) const; + bool executeOnDeath(const CreaturePtr& creature, const ItemPtr& corpse, const CreaturePtr& killer, const CreaturePtr& mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const; + void executeOnKill(const CreaturePtr& creature, const CreaturePtr& target) const; + bool executeAdvance(const PlayerPtr& player, skills_t, uint32_t, uint32_t) const; + void executeModalWindow(const PlayerPtr& player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const; + bool executeTextEdit(const PlayerPtr& player, const ItemPtr& item, const std::string& text) const; + void executeHealthChange(const CreaturePtr& creature, const CreaturePtr& attacker, CombatDamage& damage) const; + void executeManaChange(const CreaturePtr& creature, const CreaturePtr& attacker, CombatDamage& damage) const; + void executeExtendedOpcode(const PlayerPtr& player, uint8_t opcode, const std::string& buffer) const; // private: @@ -89,9 +89,9 @@ class CreatureEvents final : public BaseEvents CreatureEvents& operator=(const CreatureEvents&) = delete; // global events - bool playerLogin(Player* player) const; - bool playerLogout(Player* player) const; - bool playerAdvance(Player* player, skills_t, uint32_t, uint32_t); + bool playerLogin(const PlayerPtr& player) const; + bool playerLogout(const PlayerPtr& player) const; + bool playerAdvance(const PlayerPtr& player, skills_t, uint32_t, uint32_t); CreatureEvent* getEventByName(const std::string& name, bool forceLoaded = true); diff --git a/src/cylinder.cpp b/src/cylinder.cpp index ea441282..5f3e240d 100644 --- a/src/cylinder.cpp +++ b/src/cylinder.cpp @@ -5,9 +5,9 @@ #include "cylinder.h" -VirtualCylinder* VirtualCylinder::virtualCylinder = new VirtualCylinder; +VirtualCylinderPtr VirtualCylinder::virtualCylinder = std::make_shared(); -int32_t Cylinder::getThingIndex(const Thing*) const +int32_t Cylinder::getThingIndex(ThingPtr) { return -1; } @@ -32,17 +32,17 @@ std::map& Cylinder::getAllItemTypeCount(std::map; +using VirtualCylinderConstPtr = std::shared_ptr; + class VirtualCylinder final : public Cylinder { public: - static VirtualCylinder* virtualCylinder; + static VirtualCylinderPtr virtualCylinder; - virtual ReturnValue queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature* = nullptr) const override { + virtual ReturnValue queryAdd(int32_t, const ThingPtr&, uint32_t, uint32_t, CreaturePtr = nullptr) 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 ThingPtr&, uint32_t, uint32_t&, uint32_t) override { return RETURNVALUE_NOTPOSSIBLE; } - virtual ReturnValue queryRemove(const Thing&, uint32_t, uint32_t, Creature* = nullptr) const override { + + virtual ReturnValue queryRemove(const ThingPtr&, uint32_t, uint32_t, CreaturePtr = nullptr ) override { return RETURNVALUE_NOTPOSSIBLE; } - virtual Cylinder* queryDestination(int32_t&, const Thing&, Item**, uint32_t&) override { + + virtual CylinderPtr queryDestination(int32_t&, const ThingPtr&, ItemPtr*, 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(ThingPtr) override {} + virtual void addThing(int32_t, ThingPtr) override {} + virtual void updateThing(ThingPtr, uint16_t, uint32_t) override {} + virtual void replaceThing(uint32_t, ThingPtr) override {} + virtual void removeThing(ThingPtr, 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(ThingPtr, CylinderPtr, int32_t, cylinderlink_t = LINK_OWNER) override {} + virtual void postRemoveNotification(ThingPtr, CylinderPtr, int32_t, cylinderlink_t = LINK_OWNER) override {} bool isPushable() const override { return false; } + int32_t getThrowRange() const override { return 1; } + std::string getDescription(int32_t) const override { return {}; } + bool isRemoved() const override { return false; } }; + + #endif diff --git a/src/damagemodifier.h b/src/damagemodifier.h index 6c8c5b7f..281b76c5 100644 --- a/src/damagemodifier.h +++ b/src/damagemodifier.h @@ -144,7 +144,7 @@ class DamageModifier : public std::enable_shared_from_this { DamageModifier(const DamageModifier&) = default; DamageModifier& operator=(const DamageModifier&) = default; - DamageModifier(uint8_t stance, uint8_t modType, uint16_t amount, ModFactor factorType, uint8_t chance, CombatType_t combatType = COMBAT_NONE , CombatOrigin source = ORIGIN_NONE, CreatureType_t creatureType = CREATURETYPE_ATTACKABLE, RaceType_t race = RACE_NONE, std::string creatureName = "none") : + DamageModifier(uint8_t stance, uint8_t modType, uint16_t amount, ModFactor factorType, uint8_t chance, CombatType_t combatType = COMBAT_NONE , CombatOrigin source = ORIGIN_NONE, CreatureType_t creatureType = CREATURETYPE_ATTACKABLE, RaceType_t race = RACE_NONE, const std::string& creatureName = "none") : m_mod_stance(stance), // attack / defense m_mod_type(modType), // the enum specific type m_value(amount), // value to modify; default = percent diff --git a/src/depotchest.cpp b/src/depotchest.cpp index c42118e1..9a58e165 100644 --- a/src/depotchest.cpp +++ b/src/depotchest.cpp @@ -9,10 +9,10 @@ DepotChest::DepotChest(uint16_t type, bool paginated /*= true*/) : Container{ type, items[type].maxItems, true, paginated } {} -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 ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor/* = nullptr*/) { - const Item* item = thing.getItem(); + auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -25,8 +25,8 @@ ReturnValue DepotChest::queryAdd(int32_t index, const Thing& thing, uint32_t cou addCount = 1; } - if (item->getTopParent() != this) { - if (const Container* container = item->getContainer()) { + if (item->getTopParent().get() != this) { + if (const auto container = item->getContainer()) { addCount = container->getItemHoldingCount() + 1; } else { addCount = 1; @@ -41,26 +41,24 @@ 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - Cylinder* parent = getParent(); - if (parent != nullptr) { - parent->postAddNotification(thing, oldParent, index, LINK_PARENT); + if (getParent()) { + getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void DepotChest::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void DepotChest::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - Cylinder* parent = getParent(); - if (parent != nullptr) { - parent->postRemoveNotification(thing, newParent, index, LINK_PARENT); + if (getParent()) { + getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -Cylinder* DepotChest::getParent() const +CylinderPtr DepotChest::getParent() { - if (parent) { - return parent->getParent(); + if (parent.lock()) { + return parent.lock()->getParent(); } return nullptr; } diff --git a/src/depotchest.h b/src/depotchest.h index 55815a3f..1160669b 100644 --- a/src/depotchest.h +++ b/src/depotchest.h @@ -17,25 +17,29 @@ class DepotChest final : public Container } //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; //overrides bool canRemove() const override { return false; } - Cylinder* getParent() const override; - Cylinder* getRealParent() const override { - return parent; + CylinderPtr getParent() override; + + CylinderPtr getRealParent() override { + return parent.lock(); } private: uint32_t maxDepotItems = 0; }; +using DepotChestPtr = std::shared_ptr; +using DepotChestConstPtr = std::shared_ptr; + #endif diff --git a/src/depotlocker.cpp b/src/depotlocker.cpp index 4c19e33e..d162047c 100644 --- a/src/depotlocker.cpp +++ b/src/depotlocker.cpp @@ -19,28 +19,28 @@ 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 ThingPtr&, uint32_t, uint32_t, CreaturePtr) { return RETURNVALUE_NOTENOUGHROOM; } -void DepotLocker::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void DepotLocker::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - if (parent != nullptr) { - parent->postAddNotification(thing, oldParent, index, LINK_PARENT); + if (getParent()) { + getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void DepotLocker::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void DepotLocker::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - if (parent != nullptr) { - parent->postRemoveNotification(thing, newParent, index, LINK_PARENT); + if (getParent()) { + getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -void DepotLocker::removeInbox(Inbox* inbox) +void DepotLocker::removeInbox(const InboxPtr& inbox) { - auto cit = std::find(itemlist.begin(), itemlist.end(), inbox); + auto cit = std::ranges::find(itemlist, inbox); if (cit == itemlist.end()) { return; } diff --git a/src/depotlocker.h b/src/depotlocker.h index d4461b5d..f4068377 100644 --- a/src/depotlocker.h +++ b/src/depotlocker.h @@ -7,21 +7,20 @@ #include "container.h" #include "inbox.h" -using DepotLocker_ptr = std::shared_ptr; - class DepotLocker final : public Container { public: explicit DepotLocker(uint16_t type); - DepotLocker* getDepotLocker() override { - return this; + DepotLockerPtr getDepotLocker() override { + return dynamic_shared_this(); } - const DepotLocker* getDepotLocker() const override { - return this; + + DepotLockerConstPtr getDepotLocker() const override { + return dynamic_shared_this(); } - void removeInbox(Inbox* inbox); + void removeInbox(const InboxPtr& inbox); //serialization Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; @@ -29,16 +28,17 @@ class DepotLocker final : public Container uint16_t getDepotId() const { return depotId; } + void setDepotId(uint16_t depotId) { this->depotId = depotId; } //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; bool canRemove() const override { return false; diff --git a/src/events.cpp b/src/events.cpp index f1979d84..e3519f5d 100644 --- a/src/events.cpp +++ b/src/events.cpp @@ -159,7 +159,7 @@ bool Events::load() } // Monster -bool Events::eventMonsterOnSpawn(Monster* monster, const Position& position, bool startup, bool artificial) +bool Events::eventMonsterOnSpawn(const MonsterPtr& monster, const Position& position, bool startup, bool artificial) { // Monster:onSpawn(position, startup, artificial) if (info.monsterOnSpawn == -1) { @@ -177,7 +177,7 @@ bool Events::eventMonsterOnSpawn(Monster* monster, const Position& position, boo lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.monsterOnSpawn); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushSharedPtr(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushPosition(L, position); LuaScriptInterface::pushBoolean(L, startup); @@ -187,7 +187,7 @@ bool Events::eventMonsterOnSpawn(Monster* monster, const Position& position, boo } // Creature -bool Events::eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t& outfit) +bool Events::eventCreatureOnChangeOutfit(const CreaturePtr& creature, const Outfit_t& outfit) { // Creature:onChangeOutfit(outfit) or Creature.onChangeOutfit(self, outfit) if (info.creatureOnChangeOutfit == -1) { @@ -205,7 +205,7 @@ bool Events::eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t& out lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.creatureOnChangeOutfit); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushOutfit(L, outfit); @@ -213,7 +213,7 @@ bool Events::eventCreatureOnChangeOutfit(Creature* creature, const Outfit_t& out return scriptInterface.callFunction(2); } -ReturnValue Events::eventCreatureOnAreaCombat(Creature* creature, Tile* tile, bool aggressive) +ReturnValue Events::eventCreatureOnAreaCombat(const CreaturePtr& creature, const TilePtr& tile, bool aggressive) { // Creature:onAreaCombat(tile, aggressive) or Creature.onAreaCombat(self, tile, aggressive) if (info.creatureOnAreaCombat == -1) { @@ -232,13 +232,13 @@ ReturnValue Events::eventCreatureOnAreaCombat(Creature* creature, Tile* tile, bo scriptInterface.pushFunction(info.creatureOnAreaCombat); if (creature) { - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); } else { lua_pushnil(L); } - LuaScriptInterface::pushUserdata(L, tile); + LuaScriptInterface::pushSharedPtr(L, tile); LuaScriptInterface::setMetatable(L, -1, "Tile"); LuaScriptInterface::pushBoolean(L, aggressive); @@ -256,7 +256,7 @@ ReturnValue Events::eventCreatureOnAreaCombat(Creature* creature, Tile* tile, bo return returnValue; } -ReturnValue Events::eventCreatureOnTargetCombat(Creature* creature, Creature* target) +ReturnValue Events::eventCreatureOnTargetCombat(const CreaturePtr& creature, const CreaturePtr& target) { // Creature:onTargetCombat(target) or Creature.onTargetCombat(self, target) if (info.creatureOnTargetCombat == -1) { @@ -275,13 +275,13 @@ ReturnValue Events::eventCreatureOnTargetCombat(Creature* creature, Creature* ta scriptInterface.pushFunction(info.creatureOnTargetCombat); if (creature) { - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); } else { lua_pushnil(L); } - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setCreatureMetatable(L, -1, target); ReturnValue returnValue; @@ -297,7 +297,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(const CreaturePtr& creature, const CreaturePtr& speaker, const std::string& words, SpeakClasses type) { // Creature:onHear(speaker, words, type) if (info.creatureOnHear == -1) { @@ -315,10 +315,10 @@ void Events::eventCreatureOnHear(Creature* creature, Creature* speaker, const st lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.creatureOnHear); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - LuaScriptInterface::pushUserdata(L, speaker); + LuaScriptInterface::pushSharedPtr(L, speaker); LuaScriptInterface::setCreatureMetatable(L, -1, speaker); LuaScriptInterface::pushString(L, words); @@ -327,7 +327,7 @@ void Events::eventCreatureOnHear(Creature* creature, Creature* speaker, const st scriptInterface.callVoidFunction(4); } -void Events::eventCreatureOnAttack(Creature* attacker, Creature* target, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) +void Events::eventCreatureOnAttack(const CreaturePtr& attacker, const CreaturePtr& target, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) { // Creature:onAttack(target, blockType, combatType, origin, criticalHit, leechedDamage) if (info.creatureOnAttack == -1) { @@ -345,10 +345,10 @@ void Events::eventCreatureOnAttack(Creature* attacker, Creature* target, BlockTy lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.creatureOnAttack); - LuaScriptInterface::pushUserdata(L, attacker); + LuaScriptInterface::pushSharedPtr(L, attacker); LuaScriptInterface::setCreatureMetatable(L, -1, attacker); - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setCreatureMetatable(L, -1, target); lua_pushinteger(L, static_cast(blockType)); @@ -361,7 +361,7 @@ void Events::eventCreatureOnAttack(Creature* attacker, Creature* target, BlockTy scriptInterface.callVoidFunction(7); } -void Events::eventCreatureOnDefend(Creature* defender, Creature* attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) +void Events::eventCreatureOnDefend(const CreaturePtr& defender, const CreaturePtr& attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) { // Creature:onDefend(attacker, blockType, combatType, origin, criticalHit, leechedDamage) if (info.creatureOnDefend == -1) { @@ -379,10 +379,10 @@ void Events::eventCreatureOnDefend(Creature* defender, Creature* attacker, Block lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.creatureOnDefend); - LuaScriptInterface::pushUserdata(L, defender); + LuaScriptInterface::pushSharedPtr(L, defender); LuaScriptInterface::setCreatureMetatable(L, -1, defender); - LuaScriptInterface::pushUserdata(L, attacker); + LuaScriptInterface::pushSharedPtr(L, attacker); LuaScriptInterface::setCreatureMetatable(L, -1, attacker); lua_pushinteger(L, static_cast(blockType)); @@ -396,7 +396,7 @@ void Events::eventCreatureOnDefend(Creature* defender, Creature* attacker, Block } // Party -bool Events::eventPartyOnJoin(Party* party, Player* player) +bool Events::eventPartyOnJoin(Party* party, const PlayerPtr& player) { // Party:onJoin(player) or Party.onJoin(self, player) if (info.partyOnJoin == -1) { @@ -417,13 +417,13 @@ bool Events::eventPartyOnJoin(Party* party, Player* player) LuaScriptInterface::pushUserdata(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface.callFunction(2); } -bool Events::eventPartyOnLeave(Party* party, Player* player) +bool Events::eventPartyOnLeave(Party* party, const PlayerPtr& player) { // Party:onLeave(player) or Party.onLeave(self, player) if (info.partyOnLeave == -1) { @@ -444,7 +444,7 @@ bool Events::eventPartyOnLeave(Party* party, Player* player) LuaScriptInterface::pushUserdata(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface.callFunction(2); @@ -507,7 +507,7 @@ void Events::eventPartyOnShareExperience(Party* party, uint64_t& exp) scriptInterface.resetScriptEnv(); } -bool Events::eventPartyOnInvite(Party* party, Player* player) +bool Events::eventPartyOnInvite(Party* party, const PlayerPtr& player) { // Party:onInvite(player) or Party.onInvite(self, player) if (info.partyOnInvite == -1) { @@ -528,13 +528,13 @@ bool Events::eventPartyOnInvite(Party* party, Player* player) LuaScriptInterface::pushUserdata(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface.callFunction(2); } -bool Events::eventPartyOnRevokeInvitation(Party* party, Player* player) +bool Events::eventPartyOnRevokeInvitation(Party* party, const PlayerPtr& player) { // Party:onRevokeInvitation(player) or Party.onRevokeInvitation(self, player) if (info.partyOnRevokeInvitation == -1) { @@ -555,13 +555,13 @@ bool Events::eventPartyOnRevokeInvitation(Party* party, Player* player) LuaScriptInterface::pushUserdata(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface.callFunction(2); } -bool Events::eventPartyOnPassLeadership(Party* party, Player* player) +bool Events::eventPartyOnPassLeadership(Party* party, const PlayerPtr& player) { // Party:onPassLeadership(player) or Party.onPassLeadership(self, player) if (info.partyOnPassLeadership == -1) { @@ -582,14 +582,14 @@ bool Events::eventPartyOnPassLeadership(Party* party, Player* player) LuaScriptInterface::pushUserdata(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); return scriptInterface.callFunction(2); } // Player -bool Events::eventPlayerOnBrowseField(Player* player, const Position& position) +bool Events::eventPlayerOnBrowseField(const PlayerPtr& player, const Position& position) { // Player:onBrowseField(position) or Player.onBrowseField(self, position) if (info.playerOnBrowseField == -1) { @@ -607,7 +607,7 @@ bool Events::eventPlayerOnBrowseField(Player* player, const Position& position) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnBrowseField); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushPosition(L, position); @@ -615,7 +615,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(const PlayerPtr& player, const Position& position, const ThingPtr& thing, uint8_t stackpos, int32_t lookDistance) { // Player:onLook(thing, position, distance) or Player.onLook(self, thing, position, distance) if (info.playerOnLook == -1) { @@ -633,14 +633,14 @@ void Events::eventPlayerOnLook(Player* player, const Position& position, Thing* lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnLook); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - if (Creature* creature = thing->getCreature()) { - LuaScriptInterface::pushUserdata(L, creature); + if (auto creature = thing->getCreature()) { + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - } else if (Item* item = thing->getItem()) { - LuaScriptInterface::pushUserdata(L, item); + } else if (auto item = thing->getItem()) { + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -652,7 +652,7 @@ void Events::eventPlayerOnLook(Player* player, const Position& position, Thing* scriptInterface.callVoidFunction(4); } -void Events::eventPlayerOnLookInBattleList(Player* player, Creature* creature, int32_t lookDistance) +void Events::eventPlayerOnLookInBattleList(const PlayerPtr& player, const CreaturePtr& creature, int32_t lookDistance) { // Player:onLookInBattleList(creature, position, distance) or Player.onLookInBattleList(self, creature, position, distance) if (info.playerOnLookInBattleList == -1) { @@ -670,10 +670,10 @@ void Events::eventPlayerOnLookInBattleList(Player* player, Creature* creature, i lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnLookInBattleList); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); lua_pushinteger(L, lookDistance); @@ -681,7 +681,7 @@ void Events::eventPlayerOnLookInBattleList(Player* player, Creature* creature, i scriptInterface.callVoidFunction(3); } -void Events::eventPlayerOnLookInTrade(Player* player, Player* partner, Item* item, int32_t lookDistance) +void Events::eventPlayerOnLookInTrade(const PlayerPtr& player, const PlayerPtr& partner, const ItemPtr& item, int32_t lookDistance) { // Player:onLookInTrade(partner, item, distance) or Player.onLookInTrade(self, partner, item, distance) if (info.playerOnLookInTrade == -1) { @@ -699,13 +699,13 @@ void Events::eventPlayerOnLookInTrade(Player* player, Player* partner, Item* ite lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnLookInTrade); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, partner); + LuaScriptInterface::pushSharedPtr(L, partner); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); lua_pushinteger(L, lookDistance); @@ -713,7 +713,7 @@ void Events::eventPlayerOnLookInTrade(Player* player, Player* partner, Item* ite scriptInterface.callVoidFunction(4); } -bool Events::eventPlayerOnLookInShop(Player* player, const ItemType* itemType, uint8_t count, const std::string& description) +bool Events::eventPlayerOnLookInShop(const PlayerPtr& player, const ItemType* itemType, uint8_t count, const std::string& description) { // Player:onLookInShop(itemType, count, description) or Player.onLookInShop(self, itemType, count, description) if (info.playerOnLookInShop == -1) { @@ -731,7 +731,7 @@ bool Events::eventPlayerOnLookInShop(Player* player, const ItemType* itemType, u lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnLookInShop); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata(L, itemType); @@ -743,7 +743,7 @@ bool Events::eventPlayerOnLookInShop(Player* player, const ItemType* itemType, u return scriptInterface.callFunction(4); } -ReturnValue Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t count, const Position& fromPosition, const Position& toPosition, Cylinder* fromCylinder, Cylinder* toCylinder) +ReturnValue Events::eventPlayerOnMoveItem(const PlayerPtr& player, const ItemPtr& item, uint16_t count, const Position& fromPosition, const Position& toPosition, const CylinderPtr& fromCylinder, const CylinderPtr& toCylinder) { // Player:onMoveItem(item, count, fromPosition, toPosition) or Player.onMoveItem(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnMoveItem == -1) { @@ -761,10 +761,10 @@ ReturnValue Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t c lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnMoveItem); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); lua_pushinteger(L, count); @@ -787,7 +787,7 @@ ReturnValue Events::eventPlayerOnMoveItem(Player* player, Item* item, uint16_t c return returnValue; } -void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, const Position& fromPosition, const Position& toPosition, Cylinder* fromCylinder, Cylinder* toCylinder) +void Events::eventPlayerOnItemMoved(const PlayerPtr& player, const ItemPtr& item, uint16_t count, const Position& fromPosition, const Position& toPosition, const CylinderPtr& fromCylinder, const CylinderPtr& toCylinder) { // Player:onItemMoved(item, count, fromPosition, toPosition) or Player.onItemMoved(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnItemMoved == -1) { @@ -805,10 +805,10 @@ void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnItemMoved); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); lua_pushinteger(L, count); @@ -821,7 +821,7 @@ void Events::eventPlayerOnItemMoved(Player* player, Item* item, uint16_t count, scriptInterface.callVoidFunction(7); } -bool Events::eventPlayerOnMoveCreature(Player* player, Creature* creature, const Position& fromPosition, const Position& toPosition) +bool Events::eventPlayerOnMoveCreature(const PlayerPtr& player, const CreaturePtr& creature, const Position& fromPosition, const Position& toPosition) { // Player:onMoveCreature(creature, fromPosition, toPosition) or Player.onMoveCreature(self, creature, fromPosition, toPosition) if (info.playerOnMoveCreature == -1) { @@ -839,10 +839,10 @@ bool Events::eventPlayerOnMoveCreature(Player* player, Creature* creature, const lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnMoveCreature); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushPosition(L, fromPosition); @@ -851,7 +851,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(const PlayerPtr& 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) { @@ -869,7 +869,7 @@ void Events::eventPlayerOnReportRuleViolation(Player* player, const std::string& lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnReportRuleViolation); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushString(L, targetName); @@ -883,7 +883,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(const PlayerPtr& player, const std::string& message, const Position& position, uint8_t category) { // Player:onReportBug(message, position, category) if (info.playerOnReportBug == -1) { @@ -901,7 +901,7 @@ bool Events::eventPlayerOnReportBug(Player* player, const std::string& message, lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnReportBug); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushString(L, message); @@ -911,7 +911,7 @@ bool Events::eventPlayerOnReportBug(Player* player, const std::string& message, return scriptInterface.callFunction(4); } -bool Events::eventPlayerOnTurn(Player* player, Direction direction) +bool Events::eventPlayerOnTurn(const PlayerPtr& player, Direction direction) { // Player:onTurn(direction) or Player.onTurn(self, direction) if (info.playerOnTurn == -1) { @@ -929,7 +929,7 @@ bool Events::eventPlayerOnTurn(Player* player, Direction direction) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnTurn); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, direction); @@ -937,7 +937,7 @@ bool Events::eventPlayerOnTurn(Player* player, Direction direction) return scriptInterface.callFunction(2); } -bool Events::eventPlayerOnTradeRequest(Player* player, Player* target, Item* item) +bool Events::eventPlayerOnTradeRequest(const PlayerPtr& player, const PlayerPtr& target, const ItemPtr& item) { // Player:onTradeRequest(target, item) if (info.playerOnTradeRequest == -1) { @@ -955,19 +955,19 @@ bool Events::eventPlayerOnTradeRequest(Player* player, Player* target, Item* ite lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnTradeRequest); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); return scriptInterface.callFunction(3); } -bool Events::eventPlayerOnTradeAccept(Player* player, Player* target, Item* item, Item* targetItem) +bool Events::eventPlayerOnTradeAccept(const PlayerPtr& player, const PlayerPtr& target, const ItemPtr& item, const ItemPtr& targetItem) { // Player:onTradeAccept(target, item, targetItem) if (info.playerOnTradeAccept == -1) { @@ -985,22 +985,22 @@ bool Events::eventPlayerOnTradeAccept(Player* player, Player* target, Item* item lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnTradeAccept); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); - LuaScriptInterface::pushUserdata(L, targetItem); + LuaScriptInterface::pushSharedPtr(L, targetItem); LuaScriptInterface::setItemMetatable(L, -1, targetItem); return scriptInterface.callFunction(4); } -void Events::eventPlayerOnTradeCompleted(Player* player, Player* target, Item* item, Item* targetItem, bool isSuccess) +void Events::eventPlayerOnTradeCompleted(const PlayerPtr& player, const PlayerPtr& target, const ItemPtr& item, const ItemPtr& targetItem, bool isSuccess) { // Player:onTradeCompleted(target, item, targetItem, isSuccess) if (info.playerOnTradeCompleted == -1) { @@ -1018,16 +1018,16 @@ void Events::eventPlayerOnTradeCompleted(Player* player, Player* target, Item* i lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnTradeCompleted); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, target); + LuaScriptInterface::pushSharedPtr(L, target); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); - LuaScriptInterface::pushUserdata(L, targetItem); + LuaScriptInterface::pushSharedPtr(L, targetItem); LuaScriptInterface::setItemMetatable(L, -1, targetItem); LuaScriptInterface::pushBoolean(L, isSuccess); @@ -1035,7 +1035,7 @@ void Events::eventPlayerOnTradeCompleted(Player* player, Player* target, Item* i return scriptInterface.callVoidFunction(5); } -void Events::eventPlayerOnGainExperience(Player* player, Creature* source, uint64_t& exp, uint64_t rawExp) +void Events::eventPlayerOnGainExperience(const PlayerPtr& player, const CreaturePtr& source, uint64_t& exp, uint64_t rawExp) { // Player:onGainExperience(source, exp, rawExp) // rawExp gives the original exp which is not multiplied @@ -1054,11 +1054,11 @@ void Events::eventPlayerOnGainExperience(Player* player, Creature* source, uint6 lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnGainExperience); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); if (source) { - LuaScriptInterface::pushUserdata(L, source); + LuaScriptInterface::pushSharedPtr(L, source); LuaScriptInterface::setCreatureMetatable(L, -1, source); } else { lua_pushnil(L); @@ -1077,7 +1077,7 @@ void Events::eventPlayerOnGainExperience(Player* player, Creature* source, uint6 scriptInterface.resetScriptEnv(); } -void Events::eventPlayerOnLoseExperience(Player* player, uint64_t& exp) +void Events::eventPlayerOnLoseExperience(const PlayerPtr& player, uint64_t& exp) { // Player:onLoseExperience(exp) if (info.playerOnLoseExperience == -1) { @@ -1095,7 +1095,7 @@ void Events::eventPlayerOnLoseExperience(Player* player, uint64_t& exp) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnLoseExperience); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, exp); @@ -1110,7 +1110,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(const PlayerPtr& player, skills_t skill, uint64_t& tries) { // Player:onGainSkillTries(skill, tries) if (info.playerOnGainSkillTries == -1) { @@ -1128,7 +1128,7 @@ void Events::eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_ lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnGainSkillTries); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, skill); @@ -1144,7 +1144,7 @@ void Events::eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_ scriptInterface.resetScriptEnv(); } -void Events::eventPlayerOnWrapItem(Player* player, Item* item) +void Events::eventPlayerOnWrapItem(const PlayerPtr& player, const ItemPtr& item) { // Player:onWrapItem(item) if (info.playerOnWrapItem == -1) { @@ -1162,16 +1162,16 @@ void Events::eventPlayerOnWrapItem(Player* player, Item* item) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnWrapItem); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnInventoryUpdate(Player* player, Item* item, slots_t slot, bool equip) +void Events::eventPlayerOnInventoryUpdate(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool equip) { // Player:onInventoryUpdate(item, slot, equip) if (info.playerOnInventoryUpdate == -1) { @@ -1189,10 +1189,10 @@ void Events::eventPlayerOnInventoryUpdate(Player* player, Item* item, slots_t sl lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnInventoryUpdate); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); lua_pushinteger(L, slot); @@ -1201,7 +1201,7 @@ void Events::eventPlayerOnInventoryUpdate(Player* player, Item* item, slots_t sl scriptInterface.callVoidFunction(4); } -void Events::eventPlayerOnRotateItem(Player* player, Item* item) +void Events::eventPlayerOnRotateItem(const PlayerPtr& player, const ItemPtr& item) { // Player:onRotateItem(item) if (info.playerOnRotateItem == -1) { @@ -1219,16 +1219,16 @@ void Events::eventPlayerOnRotateItem(Player* player, Item* item) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnRotateItem); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); scriptInterface.callVoidFunction(2); } -bool Events::eventPlayerOnSpellTry(Player* player, const Spell* spell, SpellType_t spellType) +bool Events::eventPlayerOnSpellTry(const PlayerPtr& player, const Spell* spell, SpellType_t spellType) { // Player:onSpellTry(spell, spellType) if (info.playerOnSpellTry == -1) { @@ -1246,7 +1246,7 @@ bool Events::eventPlayerOnSpellTry(Player* player, const Spell* spell, SpellType lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnSpellTry); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushSpell(L, *spell); @@ -1254,7 +1254,7 @@ bool Events::eventPlayerOnSpellTry(Player* player, const Spell* spell, SpellType return scriptInterface.callFunction(3); } -void Events::eventPlayerOnAugment(Player* player, std::shared_ptr augment) +void Events::eventPlayerOnAugment(const PlayerPtr& player, std::shared_ptr augment) { // Player:onAugment(augment) if (info.playerOnAugment == -1) { @@ -1272,7 +1272,7 @@ void Events::eventPlayerOnAugment(Player* player, std::shared_ptr augme lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnAugment); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushSharedPtr(L, augment); @@ -1281,7 +1281,7 @@ void Events::eventPlayerOnAugment(Player* player, std::shared_ptr augme scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnRemoveAugment(Player* player, std::shared_ptr augment) +void Events::eventPlayerOnRemoveAugment(const PlayerPtr& player, std::shared_ptr augment) { // Player:onRemoveAugment(augment) if (info.playerOnRemoveAugment == -1) { @@ -1299,7 +1299,7 @@ void Events::eventPlayerOnRemoveAugment(Player* player, std::shared_ptr lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnRemoveAugment); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushSharedPtr(L, augment); @@ -1308,7 +1308,7 @@ void Events::eventPlayerOnRemoveAugment(Player* player, std::shared_ptr scriptInterface.callVoidFunction(2); } -void Events::eventMonsterOnDropLoot(Monster* monster, Container* corpse) +void Events::eventMonsterOnDropLoot(const MonsterPtr& monster, const ContainerPtr& corpse) { // Monster:onDropLoot(corpse) if (info.monsterOnDropLoot == -1) { @@ -1326,16 +1326,16 @@ void Events::eventMonsterOnDropLoot(Monster* monster, Container* corpse) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.monsterOnDropLoot); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushSharedPtr(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); - LuaScriptInterface::pushUserdata(L, corpse); + LuaScriptInterface::pushSharedPtr(L, corpse); LuaScriptInterface::setMetatable(L, -1, "Container"); scriptInterface.callVoidFunction(2); } -bool Events::eventItemOnImbue(Item* item, std::shared_ptr imbuement, bool created) +bool Events::eventItemOnImbue(const ItemPtr& item, const std::shared_ptr& imbuement, bool created) { // Item:onImbue(imbuement, created) if (info.itemOnImbue == -1) { @@ -1353,7 +1353,7 @@ bool Events::eventItemOnImbue(Item* item, std::shared_ptr imbuement, lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.itemOnImbue); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); LuaScriptInterface::pushSharedPtr(L, imbuement); @@ -1364,7 +1364,7 @@ bool Events::eventItemOnImbue(Item* item, std::shared_ptr imbuement, return scriptInterface.callFunction(3); } -void Events::eventItemOnRemoveImbue(Item* item, ImbuementType imbueType, bool decayed) +void Events::eventItemOnRemoveImbue(const ItemPtr& item, ImbuementType imbueType, bool decayed) { // Item:onRemoveImbue(imbueType, decayed) if (info.itemOnRemoveImbue == -1) { @@ -1382,7 +1382,7 @@ void Events::eventItemOnRemoveImbue(Item* item, ImbuementType imbueType, bool de lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.itemOnRemoveImbue); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); lua_pushinteger(L, static_cast(imbueType)); @@ -1391,7 +1391,7 @@ void Events::eventItemOnRemoveImbue(Item* item, ImbuementType imbueType, bool de scriptInterface.callVoidFunction(3); } -void Events::eventItemOnAttack(Item* item, Player* itemHolder, Creature* defender, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) +void Events::eventItemOnAttack(const ItemPtr& item, const PlayerPtr& itemHolder, const CreaturePtr& defender, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) { // Item:onAttack(attacker, defender, blockType, combatType, origin, criticalDamage, leechedDamage) if (info.itemOnAttack == -1) { @@ -1409,13 +1409,13 @@ void Events::eventItemOnAttack(Item* item, Player* itemHolder, Creature* defende lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.itemOnAttack); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); - LuaScriptInterface::pushUserdata(L, itemHolder); + LuaScriptInterface::pushSharedPtr(L, itemHolder); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, defender); + LuaScriptInterface::pushSharedPtr(L, defender); LuaScriptInterface::setCreatureMetatable(L, -1, defender); lua_pushinteger(L, static_cast(blockType)); @@ -1428,7 +1428,7 @@ void Events::eventItemOnAttack(Item* item, Player* itemHolder, Creature* defende scriptInterface.callVoidFunction(8); } -void Events::eventItemOnDefend(Item* item, Player* itemHolder, Creature* attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) +void Events::eventItemOnDefend(const ItemPtr& item, const PlayerPtr& itemHolder, const CreaturePtr& attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage, bool leechedDamage) { // Item:onDefend(defender, attacker, blockType, combatType, origin, criticalDamage, leechedDamage) if (info.itemOnDefend == -1) { @@ -1446,13 +1446,13 @@ void Events::eventItemOnDefend(Item* item, Player* itemHolder, Creature* attacke lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.itemOnDefend); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); - LuaScriptInterface::pushUserdata(L, itemHolder); + LuaScriptInterface::pushSharedPtr(L, itemHolder); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, attacker); + LuaScriptInterface::pushSharedPtr(L, attacker); LuaScriptInterface::setCreatureMetatable(L, -1, attacker); lua_pushinteger(L, blockType); @@ -1465,7 +1465,7 @@ void Events::eventItemOnDefend(Item* item, Player* itemHolder, Creature* attacke scriptInterface.callVoidFunction(8); } -void Events::eventItemOnAugment(Item* item, std::shared_ptr augment) +void Events::eventItemOnAugment(const ItemPtr& item, std::shared_ptr augment) { // Item:onAugment(augment) if (info.itemOnAugment == -1) { @@ -1483,7 +1483,7 @@ void Events::eventItemOnAugment(Item* item, std::shared_ptr augment) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.itemOnAugment); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setMetatable(L, -1, "Item"); LuaScriptInterface::pushSharedPtr(L, augment); @@ -1492,7 +1492,7 @@ void Events::eventItemOnAugment(Item* item, std::shared_ptr augment) scriptInterface.callVoidFunction(2); } -void Events::eventItemOnRemoveAugment(Item* item, std::shared_ptr augment) +void Events::eventItemOnRemoveAugment(const ItemPtr& item, std::shared_ptr augment) { // Item:onRemoveAugment(augment) if (info.itemOnRemoveAugment == -1) { @@ -1510,7 +1510,7 @@ void Events::eventItemOnRemoveAugment(Item* item, std::shared_ptr augme lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.itemOnRemoveAugment); - LuaScriptInterface::pushUserdata(L, item); + LuaScriptInterface::pushSharedPtr(L, item); LuaScriptInterface::setMetatable(L, -1, "Item"); LuaScriptInterface::pushSharedPtr(L, augment); diff --git a/src/events.h b/src/events.h index 555d84f2..f6faa653 100644 --- a/src/events.h +++ b/src/events.h @@ -86,62 +86,62 @@ class Events bool load(); // Creature - 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 eventCreatureOnAttack(Creature* attacker, Creature* target, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); - void eventCreatureOnDefend(Creature* defender, Creature* attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); + bool eventCreatureOnChangeOutfit(const CreaturePtr& creature, const Outfit_t& outfit); + ReturnValue eventCreatureOnAreaCombat(const CreaturePtr& creature, const TilePtr& tile, bool aggressive); + ReturnValue eventCreatureOnTargetCombat(const CreaturePtr& creature, const CreaturePtr& target); + void eventCreatureOnHear(const CreaturePtr& creature, const CreaturePtr& speaker, const std::string& words, SpeakClasses type); + void eventCreatureOnAttack(const CreaturePtr& attacker, const CreaturePtr& target, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); + void eventCreatureOnDefend(const CreaturePtr& defender, const CreaturePtr& attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); // Party - bool eventPartyOnJoin(Party* party, Player* player); - bool eventPartyOnLeave(Party* party, Player* player); + bool eventPartyOnJoin(Party* party, const PlayerPtr& player); + bool eventPartyOnLeave(Party* party, const PlayerPtr& player); bool eventPartyOnDisband(Party* party); void eventPartyOnShareExperience(Party* party, uint64_t& exp); - bool eventPartyOnInvite(Party* party, Player* player); - bool eventPartyOnRevokeInvitation(Party* party, Player* player); - bool eventPartyOnPassLeadership(Party* party, Player* player); + bool eventPartyOnInvite(Party* party, const PlayerPtr& player); + bool eventPartyOnRevokeInvitation(Party* party, const PlayerPtr& player); + bool eventPartyOnPassLeadership(Party* party, const PlayerPtr& player); // Player - 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, const std::string& description); - ReturnValue 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 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 eventPlayerOnTradeCompleted(Player* player, Player* target, Item* item, Item* targetItem, bool isSuccess); - void eventPlayerOnGainExperience(Player* player, Creature* source, uint64_t& exp, uint64_t rawExp); - void eventPlayerOnLoseExperience(Player* player, uint64_t& exp); - void eventPlayerOnGainSkillTries(Player* player, skills_t skill, uint64_t& tries); - void eventPlayerOnWrapItem(Player* player, Item* item); - void eventPlayerOnInventoryUpdate(Player* player, Item* item, slots_t slot, bool equip); - void eventPlayerOnRotateItem(Player* player, Item* item); - bool eventPlayerOnSpellTry(Player* player, const Spell* spell, SpellType_t spellType); - void eventPlayerOnAugment(Player* player, std::shared_ptr augment); - void eventPlayerOnRemoveAugment(Player* player, std::shared_ptr augment); + bool eventPlayerOnBrowseField(const PlayerPtr& player, const Position& position); + void eventPlayerOnLook(const PlayerPtr& player, const Position& position, const ThingPtr& thing, uint8_t stackpos, int32_t lookDistance); + void eventPlayerOnLookInBattleList(const PlayerPtr& player, const CreaturePtr& creature, int32_t lookDistance); + void eventPlayerOnLookInTrade(const PlayerPtr& player, const PlayerPtr& partner, const ItemPtr& item, int32_t lookDistance); + bool eventPlayerOnLookInShop(const PlayerPtr& player, const ItemType* itemType, uint8_t count, const std::string& description); + ReturnValue eventPlayerOnMoveItem(const PlayerPtr& player, const ItemPtr& item, uint16_t count, const Position& fromPosition, const Position& toPosition, const CylinderPtr& fromCylinder, const CylinderPtr& toCylinder); + void eventPlayerOnItemMoved(const PlayerPtr& player, const ItemPtr& item, uint16_t count, const Position& fromPosition, const Position& toPosition, const CylinderPtr& fromCylinder, const CylinderPtr& toCylinder); + bool eventPlayerOnMoveCreature(const PlayerPtr& player, const CreaturePtr& creature, const Position& fromPosition, const Position& toPosition); + void eventPlayerOnReportRuleViolation(const PlayerPtr& player, const std::string& targetName, uint8_t reportType, uint8_t reportReason, const std::string& comment, const std::string& translation); + bool eventPlayerOnReportBug(const PlayerPtr& player, const std::string& message, const Position& position, uint8_t category); + bool eventPlayerOnTurn(const PlayerPtr& player, Direction direction); + bool eventPlayerOnTradeRequest(const PlayerPtr& player, const PlayerPtr& target, const ItemPtr& item); + bool eventPlayerOnTradeAccept(const PlayerPtr& player, const PlayerPtr& target, const ItemPtr& item, const ItemPtr& targetItem); + void eventPlayerOnTradeCompleted(const PlayerPtr& player, const PlayerPtr& target, const ItemPtr& item, const ItemPtr& targetItem, bool isSuccess); + void eventPlayerOnGainExperience(const PlayerPtr& player, const CreaturePtr& source, uint64_t& exp, uint64_t rawExp); + void eventPlayerOnLoseExperience(const PlayerPtr& player, uint64_t& exp); + void eventPlayerOnGainSkillTries(const PlayerPtr& player, skills_t skill, uint64_t& tries); + void eventPlayerOnWrapItem(const PlayerPtr& player, const ItemPtr& item); + void eventPlayerOnInventoryUpdate(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool equip); + void eventPlayerOnRotateItem(const PlayerPtr& player, const ItemPtr& item); + bool eventPlayerOnSpellTry(const PlayerPtr& player, const Spell* spell, SpellType_t spellType); + void eventPlayerOnAugment(const PlayerPtr& player, std::shared_ptr augment); + void eventPlayerOnRemoveAugment(const PlayerPtr& player, std::shared_ptr augment); // Monster - void eventMonsterOnDropLoot(Monster* monster, Container* corpse); - bool eventMonsterOnSpawn(Monster* monster, const Position& position, bool startup, bool artificial); + void eventMonsterOnDropLoot(const MonsterPtr& monster, const ContainerPtr& corpse); + bool eventMonsterOnSpawn(const MonsterPtr& monster, const Position& position, bool startup, bool artificial); // Item - bool eventItemOnImbue(Item* item, std::shared_ptr imbuement, bool created = true); - void eventItemOnRemoveImbue(Item* item, ImbuementType imbueType, bool decayed = false); + bool eventItemOnImbue(const ItemPtr& item, const std::shared_ptr& imbuement, bool created = true); + void eventItemOnRemoveImbue(const ItemPtr& item, ImbuementType imbueType, bool decayed = false); - void eventItemOnAttack(Item* item, Player* itemHolder, Creature* defender, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); - void eventItemOnDefend(Item* item, Player* itemHolder, Creature* attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); - void eventItemOnAugment(Item* item, std::shared_ptr augment); - void eventItemOnRemoveAugment(Item* item, std::shared_ptr augment); + void eventItemOnAttack(const ItemPtr& item, const PlayerPtr& itemHolder, const CreaturePtr& defender, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); + void eventItemOnDefend(const ItemPtr& item, const PlayerPtr& itemHolder, const CreaturePtr& attacker, BlockType_t blockType, CombatType_t combatType, CombatOrigin origin, bool criticalDamage = false, bool leechedDamage = false); + void eventItemOnAugment(const ItemPtr& item, std::shared_ptr augment); + void eventItemOnRemoveAugment(const ItemPtr& item, std::shared_ptr augment); - int32_t getScriptId(EventInfoId eventInfoId) { + constexpr auto getScriptId(EventInfoId eventInfoId) const { switch (eventInfoId) { case EventInfoId::CREATURE_ONHEAR: diff --git a/src/game.cpp b/src/game.cpp index 31d0503e..557ea189 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -205,7 +205,7 @@ void Game::loadMap(const std::string& path) map.loadMap(path, false); } -Cylinder* Game::internalGetCylinder(Player* player, const Position& pos) const +CylinderPtr Game::internalGetCylinder(const PlayerPtr& player, const Position& pos) { if (pos.x != 0xFFFF) { return map.getTile(pos); @@ -221,22 +221,22 @@ Cylinder* Game::internalGetCylinder(Player* player, const Position& pos) const return player; } -Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index, uint32_t spriteId, stackPosType_t type) const +ThingPtr Game::internalGetThing(const PlayerPtr& player, const Position& pos, int32_t index, uint32_t spriteId, stackPosType_t type) { if (pos.x != 0xFFFF) { - Tile* tile = map.getTile(pos); + auto tile = map.getTile(pos); if (!tile) { return nullptr; } - Thing* thing; + ThingPtr thing; switch (type) { case STACKPOS_LOOK: { return tile->getTopVisibleThing(player); } case STACKPOS_MOVE: { - Item* item = tile->getTopDownItem(); + auto item = tile->getTopDownItem(); if (item && item->isMoveable()) { thing = item; } else { @@ -290,13 +290,13 @@ Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index if (pos.y & 0x40) { uint8_t fromCid = pos.y & 0x0F; - Container* parentContainer = player->getContainerByID(fromCid); + auto parentContainer = player->getContainerByID(fromCid); if (!parentContainer) { return nullptr; } if (parentContainer->getID() == ITEM_BROWSEFIELD) { - Tile* tile = parentContainer->getTile(); + auto tile = parentContainer->getTile(); if (tile && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { if (tile->hasProperty(CONST_PROP_ISVERTICAL)) { if (player->getPosition().x + 1 == tile->getPosition().x) { @@ -337,35 +337,34 @@ Thing* Game::internalGetThing(Player* player, const Position& pos, int32_t index return player->getInventoryItem(slot); } -void Game::internalGetPosition(Item* item, Position& pos, uint8_t& stackpos) +void Game::internalGetPosition(const ItemPtr& item, Position& pos, uint8_t& stackpos) { pos.x = 0; pos.y = 0; pos.z = 0; stackpos = 0; - Cylinder* topParent = item->getTopParent(); + auto topParent = item->getTopParent(); if (topParent) { - if (Player* player = dynamic_cast(topParent)) { + if (auto player = std::dynamic_pointer_cast(topParent)) { pos.x = 0xFFFF; - Container* container = dynamic_cast(item->getParent()); - if (container) { - pos.y = static_cast(0x40) | static_cast(player->getContainerID(container)); - pos.z = container->getThingIndex(item); - stackpos = pos.z; - } else { + if (const auto container = std::dynamic_pointer_cast(item->getParent())) { + pos.y = static_cast(0x40) | static_cast(player->getContainerID(std::dynamic_pointer_cast(container))); + pos.z = container->getThingIndex(item); + stackpos = pos.z; + } else { pos.y = player->getThingIndex(item); stackpos = pos.y; } - } else if (Tile* tile = topParent->getTile()) { + } else if (auto tile = topParent->getTile()) { pos = tile->getPosition(); stackpos = tile->getThingIndex(item); } } } -Creature* Game::getCreatureByID(uint32_t id) +CreaturePtr Game::getCreatureByID(const uint32_t id) { if (id <= Player::playerAutoID) { return getPlayerByID(id); @@ -377,46 +376,46 @@ Creature* Game::getCreatureByID(uint32_t id) return nullptr; } -Monster* Game::getMonsterByID(uint32_t id) +MonsterPtr Game::getMonsterByID(const uint32_t id) { if (id == 0) { return nullptr; } - auto it = monsters.find(id); + const auto it = monsters.find(id); if (it == monsters.end()) { return nullptr; } return it->second; } -Npc* Game::getNpcByID(uint32_t id) +NpcPtr Game::getNpcByID(const uint32_t id) { if (id == 0) { return nullptr; } - auto it = npcs.find(id); + const auto it = npcs.find(id); if (it == npcs.end()) { return nullptr; } return it->second; } -Player* Game::getPlayerByID(uint32_t id) +PlayerPtr Game::getPlayerByID(const uint32_t id) { if (id == 0) { return nullptr; } - auto it = players.find(id); + const auto it = players.find(id); if (it == players.end()) { return nullptr; } return it->second; } -Creature* Game::getCreatureByName(const std::string& s) +CreaturePtr Game::getCreatureByName(const std::string& s) { if (s.empty()) { return nullptr; @@ -425,13 +424,13 @@ Creature* Game::getCreatureByName(const std::string& s) const std::string& lowerCaseName = asLowerCaseString(s); { - auto it = mappedPlayerNames.find(lowerCaseName); + const auto it = mappedPlayerNames.find(lowerCaseName); if (it != mappedPlayerNames.end()) { return it->second; } } - auto equalCreatureName = [&](const std::pair& it) { + auto equalCreatureName = [&](const std::pair& it) { auto name = it.second->getName(); return lowerCaseName.size() == name.size() && std::equal(lowerCaseName.begin(), lowerCaseName.end(), name.begin(), [](char a, char b) { return a == std::tolower(b); @@ -439,15 +438,13 @@ Creature* Game::getCreatureByName(const std::string& s) }; { - auto it = std::find_if(npcs.begin(), npcs.end(), equalCreatureName); - if (it != npcs.end()) { + if (const auto it = std::ranges::find_if(npcs, equalCreatureName); it != npcs.end()) { return it->second; } } { - auto it = std::find_if(monsters.begin(), monsters.end(), equalCreatureName); - if (it != monsters.end()) { + if (const auto it = std::ranges::find_if(monsters, equalCreatureName); it != monsters.end()) { return it->second; } } @@ -455,49 +452,50 @@ Creature* Game::getCreatureByName(const std::string& s) return nullptr; } -Npc* Game::getNpcByName(const std::string& s) +NpcPtr Game::getNpcByName(const std::string& s) const { if (s.empty()) { return nullptr; } const char* npcName = s.c_str(); - for (const auto& it : npcs) { - if (caseInsensitiveEqual(npcName, it.second->getName())) { - return it.second; + for (const auto& val : npcs | std::views::values) { + if (caseInsensitiveEqual(npcName, val->getName())) { + return val; } } return nullptr; } -Player* Game::getPlayerByName(const std::string& s) +PlayerPtr Game::getPlayerByName(const std::string& s) { if (s.empty()) { return nullptr; } - auto it = mappedPlayerNames.find(asLowerCaseString(s)); + const auto it = mappedPlayerNames.find(asLowerCaseString(s)); if (it == mappedPlayerNames.end()) { return nullptr; } return it->second; } -Player* Game::getPlayerByGUID(const uint32_t& guid) +PlayerPtr Game::getPlayerByGUID(const uint32_t& guid) { if (guid == 0) { return nullptr; } - auto it = mappedPlayerGuids.find(guid); + const auto it = mappedPlayerGuids.find(guid); if (it == mappedPlayerGuids.end()) { return nullptr; } return it->second; } -ReturnValue Game::getPlayerByNameWildcard(const std::string& s, Player*& player) +ReturnValue Game::getPlayerByNameWildcard(const std::string& s) { + bool found = false; size_t strlen = s.length(); if (strlen == 0 || strlen > PLAYER_NAME_LENGTH) { return RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE; @@ -506,34 +504,33 @@ ReturnValue Game::getPlayerByNameWildcard(const std::string& s, Player*& player) if (s.back() == '~') { const std::string& query = asLowerCaseString(s.substr(0, strlen - 1)); std::string result; - ReturnValue ret = wildcardTree.findOne(query, result); - if (ret != RETURNVALUE_NOERROR) { + if (const ReturnValue ret = wildcardTree.findOne(query, result); ret != RETURNVALUE_NOERROR) { return ret; } - player = getPlayerByName(result); + found = getPlayerByName(result) ? true : false; } else { - player = getPlayerByName(s); + found = getPlayerByName(s) ? true : false; } - if (!player) { + if (!found) { return RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE; } return RETURNVALUE_NOERROR; } -Player* Game::getPlayerByAccount(uint32_t acc) +PlayerPtr Game::getPlayerByAccount(const uint32_t acc) { - for (const auto& it : players) { - if (it.second->getAccount() == acc) { - return it.second; + for (const auto& val : players | std::views::values) { + if (val->getAccount() == acc) { + return val; } } return nullptr; } -bool Game::internalPlaceCreature(Creature* creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/) +bool Game::internalPlaceCreature(CreaturePtr creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/) { if (creature->getParent() != nullptr) { return false; @@ -542,14 +539,13 @@ bool Game::internalPlaceCreature(Creature* creature, const Position& pos, bool e if (!map.placeCreature(pos, creature, extendedPos, forced)) { return false; } - - creature->incrementReferenceCounter(); + creature->setID(); creature->addList(); return true; } -bool Game::placeCreature(Creature* creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/, MagicEffectClasses magicEffect /*= CONST_ME_TELEPORT*/) +bool Game::placeCreature(CreaturePtr creature, const Position& pos, bool extendedPos /*=false*/, bool forced /*= false*/, MagicEffectClasses magicEffect /*= CONST_ME_TELEPORT*/) { if (!internalPlaceCreature(creature, pos, extendedPos, forced)) { return false; @@ -557,37 +553,38 @@ bool Game::placeCreature(Creature* creature, const Position& pos, bool extendedP SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true); - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendCreatureAppear(creature, creature->getPosition(), magicEffect); } } - for (Creature* spectator : spectators) { + for (const auto spectator : spectators) { spectator->onCreatureAppear(creature, true); } - creature->getParent()->postAddNotification(creature, nullptr, 0); - + if (creature->getParent() != nullptr) { + creature->getParent()->postAddNotification(creature, nullptr, 0); + } addCreatureCheck(creature); creature->onPlacedCreature(); return true; } -bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) +bool Game::removeCreature(CreaturePtr creature, bool isLogout/* = true*/) { if (creature->isRemoved()) { return false; } - Tile* tile = creature->getTile(); + const auto tile = creature->getTile(); std::vector oldStackPosVector; SpectatorVec spectators; map.getSpectators(spectators, tile->getPosition(), true); - for (Creature* spectator : spectators) { - if (Player* player = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto player = spectator->getPlayer()) { oldStackPosVector.push_back(player->canSeeCreature(creature) ? tile->getClientIndexOfCreature(player, creature) : -1); } } @@ -598,18 +595,18 @@ bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) //send to client size_t i = 0; - for (Creature* spectator : spectators) { - if (Player* player = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto player = spectator->getPlayer()) { player->sendRemoveTileCreature(creature, tilePosition, oldStackPosVector[i++]); } } //event method - for (Creature* spectator : spectators) { + for (const auto spectator : spectators) { spectator->onRemoveCreature(creature, isLogout); } - Creature* master = creature->getMaster(); + const auto master = creature->getMaster(); if (master && !master->isRemoved()) { creature->setMaster(nullptr); } @@ -618,11 +615,11 @@ bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) creature->removeList(); creature->setRemoved(); - ReleaseCreature(creature); + // ReleaseCreature(creature); removeCreatureCheck(creature); - for (Creature* summon : creature->summons) { + for (auto summon : creature->summons) { summon->setSkillLoss(false); removeCreature(summon); } @@ -631,16 +628,16 @@ bool Game::removeCreature(Creature* creature, bool isLogout/* = true*/) void Game::executeDeath(uint32_t creatureId) { - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (creature && !creature->isRemoved()) { creature->onDeath(); } } -void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, - uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count) +void Game::playerMoveThing(const uint32_t playerId, const Position& fromPos, + const uint16_t spriteId, const uint8_t fromStackPos, const Position& toPos, const uint8_t count) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } @@ -656,14 +653,14 @@ void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, fromIndex = fromStackPos; } - Thing* thing = internalGetThing(player, fromPos, fromIndex, 0, STACKPOS_MOVE); + auto thing = internalGetThing(player, fromPos, fromIndex, 0, STACKPOS_MOVE); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - if (Creature* movingCreature = thing->getCreature()) { - Tile* tile = map.getTile(toPos); + if (auto movingCreature = thing->getCreature()) { + auto tile = map.getTile(toPos); if (!tile) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -678,29 +675,30 @@ void Game::playerMoveThing(uint32_t playerId, const Position& fromPos, playerMoveCreature(player, movingCreature, movingCreature->getPosition(), tile); } } else if (thing->getItem()) { - Cylinder* toCylinder = internalGetCylinder(player, toPos); + auto toCylinder = internalGetCylinder(player, toPos); if (!toCylinder) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - playerMoveItem(player, fromPos, spriteId, fromStackPos, toPos, count, thing->getItem(), toCylinder); + ItemPtr item = thing->getItem(); + playerMoveItem(player, fromPos, spriteId, fromStackPos, toPos, count, item, toCylinder); } } -void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position& movingCreatureOrigPos, const Position& toPos) +void Game::playerMoveCreatureByID(const uint32_t playerId, const uint32_t movingCreatureId, const Position& movingCreatureOrigPos, const Position& toPos) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Creature* movingCreature = getCreatureByID(movingCreatureId); + auto movingCreature = getCreatureByID(movingCreatureId); if (!movingCreature) { return; } - Tile* toTile = map.getTile(toPos); + auto toTile = map.getTile(toPos); if (!toTile) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -709,7 +707,7 @@ 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(PlayerPtr& player, CreaturePtr& movingCreature, const Position& movingCreatureOrigPos, TilePtr& toTile) { if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); @@ -771,8 +769,8 @@ void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Po player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } else { - if (CreatureVector* tileCreatures = toTile->getCreatures()) { - for (Creature* tileCreature : *tileCreatures) { + if (const auto tileCreatures = toTile->getCreatures()) { + for (const auto tileCreature : *tileCreatures) { if (!tileCreature->isInGhostMode()) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); return; @@ -780,7 +778,7 @@ void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Po } } - Npc* movingNpc = movingCreature->getNpc(); + const auto movingNpc = movingCreature->getNpc(); if (movingNpc && !Spawns::isInZone(movingNpc->getMasterPos(), movingNpc->getMasterRadius(), toPos)) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); return; @@ -792,24 +790,24 @@ void Game::playerMoveCreature(Player* player, Creature* movingCreature, const Po return; } - ReturnValue ret = internalMoveCreature(*movingCreature, *toTile); + ReturnValue ret = internalMoveCreature(movingCreature, toTile); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); } } -ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, uint32_t flags /*= 0*/) +ReturnValue Game::internalMoveCreature(CreaturePtr creature, const Direction direction, uint32_t flags /*= 0*/) { creature->setLastPosition(creature->getPosition()); const Position& currentPos = creature->getPosition(); Position destPos = getNextPosition(direction, currentPos); - Player* player = creature->getPlayer(); + auto player = creature->getPlayer(); bool diagonalMovement = (direction & DIRECTION_DIAGONAL_MASK) != 0; if (player && !diagonalMovement) { //try to go up if (currentPos.z != 8 && creature->getTile()->hasHeight(3)) { - Tile* tmpTile = map.getTile(currentPos.x, currentPos.y, currentPos.getZ() - 1); + auto tmpTile = map.getTile(currentPos.x, currentPos.y, currentPos.getZ() - 1); if (tmpTile == nullptr || (tmpTile->getGround() == nullptr && !tmpTile->hasFlag(TILESTATE_BLOCKSOLID))) { tmpTile = map.getTile(destPos.x, destPos.y, destPos.getZ() - 1); if (tmpTile && tmpTile->getGround() && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID)) { @@ -825,7 +823,7 @@ ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, //try to go down if (currentPos.z != 7 && currentPos.z == destPos.z) { - Tile* tmpTile = map.getTile(destPos.x, destPos.y, destPos.z); + auto tmpTile = map.getTile(destPos.x, destPos.y, destPos.z); if (tmpTile == nullptr || (tmpTile->getGround() == nullptr && !tmpTile->hasFlag(TILESTATE_BLOCKSOLID))) { tmpTile = map.getTile(destPos.x, destPos.y, destPos.z + 1); if (tmpTile && tmpTile->hasHeight(3) && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID)) { @@ -837,44 +835,46 @@ ReturnValue Game::internalMoveCreature(Creature* creature, Direction direction, } } - Tile* toTile = map.getTile(destPos); + const auto toTile = map.getTile(destPos); if (!toTile) { return RETURNVALUE_NOTPOSSIBLE; } - return internalMoveCreature(*creature, *toTile, flags); + return internalMoveCreature(creature, toTile, flags); } -ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_t flags /*= 0*/) +ReturnValue Game::internalMoveCreature(CreaturePtr creature, TilePtr toTile, uint32_t flags /*= 0*/) { //check if we can move the creature to the destination - ReturnValue ret = toTile.queryAdd(creature, flags); + ReturnValue ret = toTile->queryAdd(creature, flags); if (ret != RETURNVALUE_NOERROR) { return ret; } map.moveCreature(creature, toTile); - if (creature.getParent() != &toTile) { + if (creature->getParent() != toTile) { return RETURNVALUE_NOERROR; } int32_t index = 0; - Item* toItem = nullptr; - Tile* subCylinder = nullptr; - Tile* toCylinder = &toTile; - Tile* fromCylinder = nullptr; + ItemPtr toItem = nullptr; + CylinderPtr subCylinder = nullptr; + TilePtr toCylinder = toTile; + TilePtr fromCylinder = nullptr; uint32_t n = 0; + while ((subCylinder = toCylinder->queryDestination(index, creature, &toItem, flags)) != toCylinder) { - map.moveCreature(creature, *subCylinder); + const auto subTile = std::dynamic_pointer_cast(subCylinder); + map.moveCreature(creature, subTile); - if (creature.getParent() != subCylinder) { + if (creature->getParent() != subCylinder) { //could happen if a script move the creature fromCylinder = nullptr; break; } fromCylinder = toCylinder; - toCylinder = subCylinder; + toCylinder = subTile; flags = 0; //to prevent infinite loop @@ -889,7 +889,7 @@ ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_ if (fromPosition.z != toPosition.z && (fromPosition.x != toPosition.x || fromPosition.y != toPosition.y)) { Direction dir = getDirectionTo(fromPosition, toPosition); if ((dir & DIRECTION_DIAGONAL_MASK) == 0) { - internalCreatureTurn(&creature, dir); + internalCreatureTurn(creature, dir); } } } @@ -897,17 +897,20 @@ ReturnValue Game::internalMoveCreature(Creature& creature, Tile& toTile, uint32_ return RETURNVALUE_NOERROR; } -void Game::playerMoveItemByPlayerID(uint32_t playerId, const Position& fromPos, uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count) +void Game::playerMoveItemByPlayerID(const uint32_t playerId, const Position& fromPos, uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - playerMoveItem(player, fromPos, spriteId, fromStackPos, toPos, count, nullptr, nullptr); + ItemPtr item = nullptr; + CylinderPtr toCylinder = nullptr; + // perfect example of needing an optional + playerMoveItem(player, fromPos, spriteId, fromStackPos, toPos, count, item, toCylinder); } -void Game::playerMoveItem(Player* player, const Position& fromPos, - uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count, Item* item, Cylinder* toCylinder) +void Game::playerMoveItem(const PlayerPtr& player, const Position& fromPos, + uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count, ItemPtr& item, CylinderPtr& toCylinder) { if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); @@ -932,12 +935,11 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, fromIndex = fromStackPos; } - Thing* thing = internalGetThing(player, fromPos, fromIndex, 0, STACKPOS_MOVE); + auto thing = internalGetThing(player, fromPos, fromIndex, 0, STACKPOS_MOVE); if (!thing || !thing->getItem()) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - item = thing->getItem(); } @@ -946,7 +948,7 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, return; } - Cylinder* fromCylinder = internalGetCylinder(player, fromPos); + auto fromCylinder = internalGetCylinder(player, fromPos); if (fromCylinder == nullptr) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -987,7 +989,7 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, return; } - const Tile* toCylinderTile = toCylinder->getTile(); + const auto toCylinderTile = toCylinder->getTile(); const Position& mapToPos = toCylinderTile->getPosition(); //hangable item specific code @@ -1020,9 +1022,9 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, if (fromPos.x != 0xFFFF && Position::areInRange<1, 1>(mapFromPos, playerPos) && !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, 0, player, nullptr, &fromPos, &toPos); + ItemPtr moveItem = nullptr; + CylinderPtr p_cylinder = std::dynamic_pointer_cast(player); + ReturnValue ret = internalMoveItem(fromCylinder, p_cylinder, INDEX_WHEREEVER, item, count, &moveItem, 0, player, nullptr, &fromPos, &toPos); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); return; @@ -1079,10 +1081,10 @@ void Game::playerMoveItem(Player* player, const Position& fromPos, } } -ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, int32_t index, - Item* item, uint32_t count, Item** _moveItem, uint32_t flags /*= 0*/, Creature* actor/* = nullptr*/, Item* tradeItem/* = nullptr*/, const Position* fromPos /*= nullptr*/, const Position* toPos/*= nullptr*/) +ReturnValue Game::internalMoveItem(CylinderPtr& fromCylinder, CylinderPtr& toCylinder, int32_t index, + ItemPtr item, uint32_t count, ItemPtr* _moveItem, uint32_t flags /*= 0*/, const std::optional& actor/* = std::nullopt*/, const std::optional& tradeItem/* = std::nullopt*/, const Position* fromPos /*= nullptr*/, const Position* toPos/*= nullptr*/) { - Player* actorPlayer = actor ? actor->getPlayer() : nullptr; + PlayerPtr actorPlayer = actor.value() ? actor.value()->getPlayer() : nullptr; if (actorPlayer && fromPos && toPos) { const ReturnValue ret = g_events->eventPlayerOnMoveItem(actorPlayer, item, count, *fromPos, *toPos, fromCylinder, toCylinder); if (ret != RETURNVALUE_NOERROR) { @@ -1090,20 +1092,18 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, } } - Tile* fromTile = fromCylinder->getTile(); - if (fromTile) { - auto it = browseFields.find(fromTile); - if (it != browseFields.end() && it->second == fromCylinder) { + if (const auto fromTile = fromCylinder->getTile()) { + if (const auto it = browseFields.find(fromTile); it != browseFields.end() && it->second == fromCylinder) { fromCylinder = fromTile; } } - Item* toItem = nullptr; + ItemPtr toItem = nullptr; - Cylinder* subCylinder; + CylinderPtr subCylinder; int floorN = 0; - while ((subCylinder = toCylinder->queryDestination(index, *item, &toItem, flags)) != toCylinder) { + while ((subCylinder = toCylinder->queryDestination(index, item, &toItem, flags)) != toCylinder) { toCylinder = subCylinder; //to prevent infinite loop @@ -1117,23 +1117,23 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, return RETURNVALUE_NOERROR; //silently ignore move } - if (Container* toContainer = dynamic_cast(toCylinder)) { + if (ContainerPtr toContainer = std::dynamic_pointer_cast(toCylinder)) { if (toContainer->isRewardCorpse() || toContainer->getID() == ITEM_REWARD_CONTAINER) { return RETURNVALUE_NOTPOSSIBLE; } } - if (Container* itemContainer = dynamic_cast(item)) { + if (ContainerPtr itemContainer = std::dynamic_pointer_cast(item)) { if (itemContainer->isRewardCorpse() || item->getID() == ITEM_REWARD_CONTAINER) { return RETURNVALUE_NOERROR; // silently ignore move } } //check if we can add this item - ReturnValue ret = toCylinder->queryAdd(index, *item, count, flags, actor); + ReturnValue ret = toCylinder->queryAdd(index, item, count, flags, actor.value()); if (ret == RETURNVALUE_NEEDEXCHANGE) { //check if we can add it to source cylinder - ret = fromCylinder->queryAdd(fromCylinder->getThingIndex(item), *toItem, toItem->getItemCount(), 0); + ret = fromCylinder->queryAdd(fromCylinder->getThingIndex(item), toItem, toItem->getItemCount(), 0); if (ret == RETURNVALUE_NOERROR) { if (actorPlayer && fromPos && toPos) { const ReturnValue eventRet = g_events->eventPlayerOnMoveItem(actorPlayer, toItem, toItem->getItemCount(), *toPos, *fromPos, toCylinder, fromCylinder); @@ -1144,13 +1144,13 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, //check how much we can move uint32_t maxExchangeQueryCount = 0; - ReturnValue retExchangeMaxCount = fromCylinder->queryMaxCount(INDEX_WHEREEVER, *toItem, toItem->getItemCount(), maxExchangeQueryCount, 0); + ReturnValue retExchangeMaxCount = fromCylinder->queryMaxCount(INDEX_WHEREEVER, toItem, toItem->getItemCount(), maxExchangeQueryCount, 0); if (retExchangeMaxCount != RETURNVALUE_NOERROR && maxExchangeQueryCount == 0) { return retExchangeMaxCount; } - if (toCylinder->queryRemove(*toItem, toItem->getItemCount(), flags, actor) == RETURNVALUE_NOERROR) { + if (toCylinder->queryRemove(toItem, toItem->getItemCount(), flags, actor.value()) == RETURNVALUE_NOERROR) { int32_t oldToItemIndex = toCylinder->getThingIndex(toItem); toCylinder->removeThing(toItem, toItem->getItemCount()); fromCylinder->addThing(toItem); @@ -1164,7 +1164,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, fromCylinder->postAddNotification(toItem, toCylinder, newToItemIndex); } - ret = toCylinder->queryAdd(index, *item, count, flags); + ret = toCylinder->queryAdd(index, item, count, flags); if (actorPlayer && fromPos && toPos && !toItem->isRemoved()) { g_events->eventPlayerOnItemMoved(actorPlayer, toItem, toItem->getItemCount(), *toPos, *fromPos, toCylinder, fromCylinder); @@ -1181,7 +1181,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, //check how much we can move uint32_t maxQueryCount = 0; - ReturnValue retMaxCount = toCylinder->queryMaxCount(index, *item, count, maxQueryCount, flags); + ReturnValue retMaxCount = toCylinder->queryMaxCount(index, item, count, maxQueryCount, flags); if (retMaxCount != RETURNVALUE_NOERROR && maxQueryCount == 0) { return retMaxCount; } @@ -1193,10 +1193,10 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, m = maxQueryCount; } - Item* moveItem = item; + ItemPtr moveItem = item; //check if we can remove this item - ret = fromCylinder->queryRemove(*item, m, flags, actor); + ret = fromCylinder->queryRemove(item, m, flags, actor.value()); if (ret != RETURNVALUE_NOERROR) { return ret; } @@ -1206,7 +1206,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, return RETURNVALUE_NOTENOUGHROOM; } - Cylinder* tmpCylinder = toCylinder->getParent(); + auto tmpCylinder = toCylinder->getParent(); while (tmpCylinder) { if (tmpCylinder->getItem() == tradeItem) { return RETURNVALUE_NOTENOUGHROOM; @@ -1218,7 +1218,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, //remove the item int32_t itemIndex = fromCylinder->getThingIndex(item); - Item* updateItem = nullptr; + ItemPtr updateItem = nullptr; fromCylinder->removeThing(item, m); //update item(s) @@ -1242,7 +1242,7 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, } if (item->isRemoved()) { - ReleaseItem(item); + item.reset(); } } @@ -1284,7 +1284,6 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, if (moveItem && moveItem->getDuration() > 0) { if (moveItem->getDecaying() != DECAYING_TRUE) { - moveItem->incrementReferenceCounter(); moveItem->setDecaying(DECAYING_TRUE); toDecayItems.push_front(moveItem); } @@ -1303,26 +1302,26 @@ ReturnValue Game::internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, return ret; } -ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t index /*= INDEX_WHEREEVER*/, +ReturnValue Game::internalAddItem(CylinderPtr& toCylinder, ItemPtr 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, +ReturnValue Game::internalAddItem(CylinderPtr& toCylinder, ItemPtr& item, int32_t index, uint32_t flags, bool test, uint32_t& remainderCount) { if (toCylinder == nullptr || item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } - Cylinder* destCylinder = toCylinder; - Item* toItem = nullptr; - toCylinder = toCylinder->queryDestination(index, *item, &toItem, flags); + auto destCylinder = toCylinder; + ItemPtr toItem = nullptr; + toCylinder = toCylinder->queryDestination(index, item, &toItem, flags); //check if we can add this item - ReturnValue ret = toCylinder->queryAdd(index, *item, item->getItemCount(), flags); + ReturnValue ret = toCylinder->queryAdd(index, item, item->getItemCount(), flags); if (ret != RETURNVALUE_NOERROR) { return ret; } @@ -1332,7 +1331,7 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde since the queryDestination can return a cylinder that might only hold a part of the full amount. */ uint32_t maxQueryCount = 0; - ret = destCylinder->queryMaxCount(INDEX_WHEREEVER, *item, item->getItemCount(), maxQueryCount, flags); + ret = destCylinder->queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), maxQueryCount, flags); if (ret != RETURNVALUE_NOERROR) { return ret; @@ -1351,10 +1350,10 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde int32_t count = m - n; if (count > 0) { if (item->getItemCount() != count) { - Item* remainderItem = item->clone(); + const auto remainderItem = item->clone(); remainderItem->setItemCount(count); if (internalAddItem(destCylinder, remainderItem, INDEX_WHEREEVER, flags, false) != RETURNVALUE_NOERROR) { - ReleaseItem(remainderItem); + // ReleaseItem(remainderItem); remainderCount = count; } } else { @@ -1368,7 +1367,7 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde } else { //fully merged with toItem, item will be destroyed item->onRemoved(); - ReleaseItem(item); + // ReleaseItem(item); int32_t itemIndex = toCylinder->getThingIndex(toItem); if (itemIndex != -1) { @@ -1385,24 +1384,21 @@ ReturnValue Game::internalAddItem(Cylinder* toCylinder, Item* item, int32_t inde } if (item->getDuration() > 0) { - item->incrementReferenceCounter(); item->setDecaying(DECAYING_TRUE); toDecayItems.push_front(item); } return RETURNVALUE_NOERROR; } -ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/) +ReturnValue Game::internalRemoveItem(ItemPtr item, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/) { - Cylinder* cylinder = item->getParent(); + auto cylinder = item->getParent(); if (cylinder == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } - Tile* fromTile = cylinder->getTile(); - if (fromTile) { - auto it = browseFields.find(fromTile); - if (it != browseFields.end() && it->second == cylinder) { + if (const auto fromTile = cylinder->getTile()) { + if (const auto it = browseFields.find(fromTile); it != browseFields.end() && it->second == cylinder) { cylinder = fromTile; } } @@ -1412,7 +1408,7 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te } //check if we can remove this item - ReturnValue ret = cylinder->queryRemove(*item, count, flags | FLAG_IGNORENOTMOVEABLE); + ReturnValue ret = cylinder->queryRemove(item, count, flags | FLAG_IGNORENOTMOVEABLE); if (ret != RETURNVALUE_NOERROR) { return ret; } @@ -1422,7 +1418,7 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te } if (!test) { - int32_t index = cylinder->getThingIndex(item); + const int32_t index = cylinder->getThingIndex(item); //remove the item cylinder->removeThing(item, count); @@ -1432,7 +1428,7 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te if (item->canDecay()) { decayItems->remove(item); } - ReleaseItem(item); + // ReleaseItem(item); } cylinder->postRemoveNotification(item, nullptr, index); @@ -1441,40 +1437,43 @@ ReturnValue Game::internalRemoveItem(Item* item, int32_t count /*= -1*/, bool te return RETURNVALUE_NOERROR; } -ReturnValue Game::internalPlayerAddItem(Player* player, Item* item, bool dropOnMap /*= true*/, slots_t slot /*= CONST_SLOT_WHEREEVER*/) +ReturnValue Game::internalPlayerAddItem(const PlayerPtr& player, ItemPtr 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); + CylinderPtr holder = std::static_pointer_cast(player); + ReturnValue ret = internalAddItem(holder, item, static_cast(slot), 0, false, remainderCount); if (remainderCount != 0) { - Item* remainderItem = Item::CreateItem(item->getID(), remainderCount); - ReturnValue remaindRet = internalAddItem(player->getTile(), remainderItem, INDEX_WHEREEVER, FLAG_NOLIMIT); + auto remainderItem = Item::CreateItem(item->getID(), remainderCount); + CylinderPtr tile = player->getTile(); + ReturnValue remaindRet = internalAddItem(tile, remainderItem, INDEX_WHEREEVER, FLAG_NOLIMIT); if (remaindRet != RETURNVALUE_NOERROR) { - ReleaseItem(remainderItem); + // ReleaseItem(remainderItem); } } if (ret != RETURNVALUE_NOERROR && dropOnMap) { - ret = internalAddItem(player->getTile(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); + CylinderPtr tile = player->getTile(); + ret = internalAddItem(tile, item, INDEX_WHEREEVER, FLAG_NOLIMIT); } return ret; } -Item* Game::findItemOfType(Cylinder* cylinder, uint16_t itemId, +ItemPtr Game::findItemOfType(const CylinderPtr& cylinder, uint16_t itemId, bool depthSearch /*= true*/, int32_t subType /*= -1*/) const { if (cylinder == nullptr) { return nullptr; } - std::vector containers; + std::vector containers; for (size_t i = cylinder->getFirstIndex(), j = cylinder->getLastIndex(); i < j; ++i) { - Thing* thing = cylinder->getThing(i); + auto thing = cylinder->getThing(i); if (!thing) { continue; } - Item* item = thing->getItem(); + auto item = thing->getItem(); if (!item) { continue; } @@ -1484,8 +1483,7 @@ Item* Game::findItemOfType(Cylinder* cylinder, uint16_t itemId, } if (depthSearch) { - Container* container = item->getContainer(); - if (container) { + if (auto container = item->getContainer()) { containers.push_back(container); } } @@ -1493,14 +1491,12 @@ Item* Game::findItemOfType(Cylinder* cylinder, uint16_t itemId, size_t i = 0; while (i < containers.size()) { - Container* container = containers[i++]; - for (Item* item : container->getItemList()) { + for (const auto container = containers[i++]; auto item : container->getItemList()) { if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) { return item; } - Container* subContainer = item->getContainer(); - if (subContainer) { + if (auto subContainer = item->getContainer()) { containers.push_back(subContainer); } } @@ -1508,7 +1504,7 @@ Item* Game::findItemOfType(Cylinder* cylinder, uint16_t itemId, return nullptr; } -bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) +bool Game::removeMoney(CylinderPtr& cylinder, uint64_t money, uint32_t flags /*= 0*/) { if (cylinder == nullptr) { return false; @@ -1518,24 +1514,23 @@ bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0* return true; } - std::vector containers; + std::vector containers; - std::multimap moneyMap; + std::multimap moneyMap; uint64_t moneyCount = 0; for (size_t i = cylinder->getFirstIndex(), j = cylinder->getLastIndex(); i < j; ++i) { - Thing* thing = cylinder->getThing(i); + auto thing = cylinder->getThing(i); if (!thing) { continue; } - Item* item = thing->getItem(); + auto item = thing->getItem(); if (!item) { continue; } - Container* container = item->getContainer(); - if (container) { + if (auto container = item->getContainer()) { containers.push_back(container); } else { const uint32_t worth = item->getWorth(); @@ -1548,10 +1543,8 @@ bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0* size_t i = 0; while (i < containers.size()) { - Container* container = containers[i++]; - for (Item* item : container->getItemList()) { - Container* tmpContainer = item->getContainer(); - if (tmpContainer) { + for (const auto container = containers[i++]; auto item : container->getItemList()) { + if (auto tmpContainer = item->getContainer()) { containers.push_back(tmpContainer); } else { const uint32_t worth = item->getWorth(); @@ -1568,7 +1561,7 @@ bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0* } for (const auto& moneyEntry : moneyMap) { - Item* item = moneyEntry.second; + auto item = moneyEntry.second; if (moneyEntry.first < money) { internalRemoveItem(item); money -= moneyEntry.first; @@ -1587,7 +1580,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(CylinderPtr& cylinder, uint64_t money, const uint32_t flags /*= 0*/) { if (money == 0) { return; @@ -1605,11 +1598,12 @@ void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) while (currencyCoins > 0) { const uint16_t count = std::min(100, currencyCoins); - Item* remaindItem = Item::CreateItem(it.second, count); + auto remaindItem = Item::CreateItem(it.second, count); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RETURNVALUE_NOERROR) { - internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); + CylinderPtr cylinder_tile = cylinder->getTile(); + internalAddItem(cylinder_tile, remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } currencyCoins -= count; @@ -1617,7 +1611,7 @@ void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) } } -Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) +ItemPtr Game::transformItem(const ItemPtr& item, const uint16_t newId, const int32_t newCount /*= -1*/) { if (item->getID() == newId && (newCount == -1 || (newCount == item->getSubType() && newCount != 0))) { //chargeless item placed on map = infinite return item; @@ -1628,15 +1622,13 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) return item; } - Cylinder* cylinder = item->getParent(); + auto cylinder = item->getParent(); if (cylinder == nullptr) { return nullptr; } - Tile* fromTile = cylinder->getTile(); - if (fromTile) { - auto it = browseFields.find(fromTile); - if (it != browseFields.end() && it->second == cylinder) { + if (auto fromTile = cylinder->getTile()) { + if (auto it = browseFields.find(fromTile); it != browseFields.end() && it->second == cylinder) { cylinder = fromTile; } } @@ -1668,9 +1660,9 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) } cylinder->addThing(item); - Cylinder* newParent = item->getParent(); + auto newParent = item->getParent(); if (newParent == nullptr) { - ReleaseItem(item); + // ReleaseItem(item); return nullptr; } @@ -1695,7 +1687,7 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) return nullptr; } else if (newItemId != newId) { //Replacing the the old item with the new while maintaining the old position - Item* newItem = Item::CreateItem(newItemId, 1); + ItemPtr newItem = Item::CreateItem(newItemId, 1); if (newItem == nullptr) { return nullptr; } @@ -1703,9 +1695,9 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) cylinder->replaceThing(itemIndex, newItem); cylinder->postAddNotification(newItem, cylinder, itemIndex); - item->setParent(nullptr); + item->clearParent(); cylinder->postRemoveNotification(item, cylinder, itemIndex); - ReleaseItem(item); + // ReleaseItem(item); return newItem; } else { return transformItem(item, newItemId); @@ -1735,7 +1727,7 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) } //Replacing the old item with the new while maintaining the old position - Item* newItem; + ItemPtr newItem; if (newCount == -1) { newItem = Item::CreateItem(newId); } else { @@ -1749,13 +1741,12 @@ Item* Game::transformItem(Item* item, uint16_t newId, int32_t newCount /*= -1*/) cylinder->replaceThing(itemIndex, newItem); cylinder->postAddNotification(newItem, cylinder, itemIndex); - item->setParent(nullptr); + item->clearParent(); cylinder->postRemoveNotification(item, cylinder, itemIndex); - ReleaseItem(item); + // ReleaseItem(item); if (newItem->getDuration() > 0) { if (newItem->getDecaying() != DECAYING_TRUE) { - newItem->incrementReferenceCounter(); newItem->setDecaying(DECAYING_TRUE); toDecayItems.push_front(newItem); } @@ -1764,7 +1755,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(const ThingPtr& thing, const Position& newPos, bool pushMove/* = true*/, uint32_t flags /*= 0*/) { if (newPos == thing->getPosition()) { return RETURNVALUE_NOERROR; @@ -1772,26 +1763,27 @@ ReturnValue Game::internalTeleport(Thing* thing, const Position& newPos, bool pu return RETURNVALUE_NOTPOSSIBLE; } - Tile* toTile = map.getTile(newPos); + const TilePtr toTile = map.getTile(newPos); + CylinderPtr toCylinder = toTile; if (!toTile) { return RETURNVALUE_NOTPOSSIBLE; } - if (Creature* creature = thing->getCreature()) { - ReturnValue ret = toTile->queryAdd(*creature, FLAG_NOLIMIT); - if (ret != RETURNVALUE_NOERROR) { + if (auto creature = thing->getCreature()) { + if (ReturnValue ret = toTile->queryAdd(creature, FLAG_NOLIMIT); ret != RETURNVALUE_NOERROR) { return ret; } - map.moveCreature(*creature, *toTile, !pushMove); + map.moveCreature(creature, toTile, !pushMove); return RETURNVALUE_NOERROR; - } else if (Item* item = thing->getItem()) { - return internalMoveItem(item->getParent(), toTile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, flags); + } else if (const auto item = thing->getItem()) { + auto t_parent = item->getParent(); + return internalMoveItem(t_parent, toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, flags); } return RETURNVALUE_NOTPOSSIBLE; } -Item* searchForItem(Container* container, uint16_t itemId) +ItemPtr searchForItem(const ContainerPtr& container, const uint16_t itemId) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if ((*it)->getID() == itemId) { @@ -1831,28 +1823,28 @@ slots_t getSlotType(const ItemType& it) } //Implementation of player invoked events -void Game::playerEquipItem(uint32_t playerId, uint16_t spriteId) +void Game::playerEquipItem(const uint32_t playerId, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Item* item = player->getInventoryItem(CONST_SLOT_BACKPACK); + const auto item = player->getInventoryItem(CONST_SLOT_BACKPACK); if (!item) { return; } - Container* backpack = item->getContainer(); + const auto backpack = item->getContainer(); if (!backpack) { return; } const ItemType& it = Item::items.getItemIdByClientId(spriteId); - slots_t slot = getSlotType(it); + const slots_t slot = getSlotType(it); - Item* slotItem = player->getInventoryItem(slot); - Item* equipItem = searchForItem(backpack, it.id); + const auto slotItem = player->getInventoryItem(slot); + const auto equipItem = searchForItem(backpack, it.id); Position fromPos, toPos; uint8_t fromStackPos, toStackPos; @@ -1865,15 +1857,19 @@ void Game::playerEquipItem(uint32_t playerId, uint16_t spriteId) } if (slotItem && slotItem->getID() == it.id && (!it.stackable || slotItem->getItemCount() == 100 || !equipItem)) { - internalMoveItem(slotItem->getParent(), player, CONST_SLOT_WHEREEVER, slotItem, slotItem->getItemCount(), nullptr, 0, player, nullptr, &fromPos, &toPos); + CylinderPtr t_slot = slotItem->getParent(); + CylinderPtr p_slot = player; + internalMoveItem(t_slot, p_slot, CONST_SLOT_WHEREEVER, slotItem, slotItem->getItemCount(), nullptr, 0, player, nullptr, &fromPos, &toPos); } else if (equipItem) { - internalMoveItem(equipItem->getParent(), player, slot, equipItem, equipItem->getItemCount(), nullptr, 0, player, nullptr, &fromPos, &toPos); + CylinderPtr t_slot = equipItem->getParent(); + CylinderPtr p_slot = player; + internalMoveItem(t_slot, p_slot, slot, equipItem, equipItem->getItemCount(), nullptr, 0, player, nullptr, &fromPos, &toPos); } } -void Game::playerMove(uint32_t playerId, Direction direction) +void Game::playerMove(const uint32_t playerId, const Direction direction) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -1889,7 +1885,7 @@ void Game::playerMove(uint32_t playerId, Direction direction) player->startAutoWalk(direction); } -bool Game::playerBroadcastMessage(Player* player, const std::string& text) const +bool Game::playerBroadcastMessage(const PlayerPtr& player, const std::string& text) const { if (!player->hasFlag(PlayerFlag_CanBroadcast)) { return false; @@ -1897,41 +1893,41 @@ bool Game::playerBroadcastMessage(Player* player, const std::string& text) const std::cout << "> " << player->getName() << " broadcasted: \"" << text << "\"." << std::endl; - for (const auto& it : players) { - it.second->sendPrivateMessage(player, TALKTYPE_BROADCAST, text); + for (const auto& val : players | std::views::values) { + val->sendPrivateMessage(player, TALKTYPE_BROADCAST, text); } return true; } -void Game::playerCreatePrivateChannel(uint32_t playerId) +void Game::playerCreatePrivateChannel(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isPremium()) { return; } - ChatChannel* channel = g_chat->createChannel(*player, CHANNEL_PRIVATE); - if (!channel || !channel->addUser(*player)) { + ChatChannel* channel = g_chat->createChannel(player, CHANNEL_PRIVATE); + if (!channel || !channel->addUser(player)) { return; } player->sendCreatePrivateChannel(channel->getId(), channel->getName()); } -void Game::playerChannelInvite(uint32_t playerId, const std::string& name) +void Game::playerChannelInvite(const uint32_t playerId, const std::string& name) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - PrivateChatChannel* channel = g_chat->getPrivateChannel(*player); + PrivateChatChannel* channel = g_chat->getPrivateChannel(player); if (!channel) { return; } - Player* invitePlayer = getPlayerByName(name); + const auto invitePlayer = getPlayerByName(name); if (!invitePlayer) { return; } @@ -1940,22 +1936,22 @@ void Game::playerChannelInvite(uint32_t playerId, const std::string& name) return; } - channel->invitePlayer(*player, *invitePlayer); + channel->invitePlayer(player, invitePlayer); } -void Game::playerChannelExclude(uint32_t playerId, const std::string& name) +void Game::playerChannelExclude(const uint32_t playerId, const std::string& name) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - PrivateChatChannel* channel = g_chat->getPrivateChannel(*player); + PrivateChatChannel* channel = g_chat->getPrivateChannel(player); if (!channel) { return; } - Player* excludePlayer = getPlayerByName(name); + const auto excludePlayer = getPlayerByName(name); if (!excludePlayer) { return; } @@ -1964,12 +1960,12 @@ void Game::playerChannelExclude(uint32_t playerId, const std::string& name) return; } - channel->excludePlayer(*player, *excludePlayer); + channel->excludePlayer(player, excludePlayer); } -void Game::playerRequestChannels(uint32_t playerId) +void Game::playerRequestChannels(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -1977,14 +1973,14 @@ void Game::playerRequestChannels(uint32_t playerId) player->sendChannelsDialog(); } -void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) +void Game::playerOpenChannel(const uint32_t playerId, uint16_t channelId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - ChatChannel* channel = g_chat->addUserToChannel(*player, channelId); + ChatChannel* channel = g_chat->addUserToChannel(player, channelId); if (!channel) { return; } @@ -2000,19 +1996,19 @@ 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(const uint32_t playerId, uint16_t channelId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - g_chat->removeUserFromChannel(*player, channelId); + g_chat->removeUserFromChannel(player, channelId); } -void Game::playerOpenPrivateChannel(uint32_t playerId, std::string receiver) +void Game::playerOpenPrivateChannel(const uint32_t playerId, std::string receiver) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2030,25 +2026,25 @@ void Game::playerOpenPrivateChannel(uint32_t playerId, std::string receiver) player->sendOpenPrivateChannel(receiver); } -void Game::playerCloseNpcChannel(uint32_t playerId) +void Game::playerCloseNpcChannel(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } SpectatorVec spectators; map.getSpectators(spectators, player->getPosition()); - for (Creature* spectator : spectators) { - if (Npc* npc = spectator->getNpc()) { + for (const auto spectator : spectators) { + if (const auto npc = spectator->getNpc()) { npc->onPlayerCloseChannel(player); } } } -void Game::playerReceivePing(uint32_t playerId) +void Game::playerReceivePing(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2056,9 +2052,9 @@ void Game::playerReceivePing(uint32_t playerId) player->receivePing(); } -void Game::playerReceivePingBack(uint32_t playerId) +void Game::playerReceivePingBack(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2066,9 +2062,9 @@ void Game::playerReceivePingBack(uint32_t playerId) player->sendPingBack(); } -void Game::playerAutoWalk(uint32_t playerId, const std::vector& listDir) +void Game::playerAutoWalk(const uint32_t playerId, const std::vector& listDir) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2077,9 +2073,9 @@ void Game::playerAutoWalk(uint32_t playerId, const std::vector& listD player->startAutoWalk(listDir); } -void Game::playerStopAutoWalk(uint32_t playerId) +void Game::playerStopAutoWalk(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2087,26 +2083,26 @@ void Game::playerStopAutoWalk(uint32_t playerId) player->stopWalk(); } -void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint16_t fromSpriteId, - const Position& toPos, uint8_t toStackPos, uint16_t toSpriteId) +void Game::playerUseItemEx(const uint32_t playerId, const Position& fromPos, const uint8_t fromStackPos, const uint16_t fromSpriteId, + const Position& toPos, const uint8_t toStackPos, const uint16_t toSpriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - bool isHotkey = (fromPos.x == 0xFFFF && fromPos.y == 0 && fromPos.z == 0); + const bool isHotkey = (fromPos.x == 0xFFFF && fromPos.y == 0 && fromPos.z == 0); if (isHotkey && !g_config.getBoolean(ConfigManager::AIMBOT_HOTKEY_ENABLED)) { return; } - Thing* thing = internalGetThing(player, fromPos, fromStackPos, fromSpriteId, STACKPOS_USEITEM); + const auto thing = internalGetThing(player, fromPos, fromStackPos, fromSpriteId, STACKPOS_USEITEM); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item || !item->isUseable() || item->getClientID() != fromSpriteId) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; @@ -2128,9 +2124,11 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f 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; + ItemPtr moveItem = nullptr; + CylinderPtr t_cylinder = item->getParent(); + CylinderPtr p_cylinder = player; - ret = internalMoveItem(item->getParent(), player, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, 0, player, nullptr, &fromPos, &toPos); + ret = internalMoveItem(t_cylinder, p_cylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, 0, player, nullptr, &fromPos, &toPos); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); return; @@ -2158,7 +2156,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f } if (!player->canDoAction()) { - uint32_t delay = player->getNextActionTime(); + const uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, [=, this]() { playerUseItemEx(playerId, fromPos, fromStackPos, fromSpriteId, toPos, toStackPos, toSpriteId); }); @@ -2172,36 +2170,34 @@ void Game::playerUseItemEx(uint32_t playerId, const Position& fromPos, uint8_t f g_actions->useItemEx(player, fromPos, toPos, toStackPos, item, isHotkey); } -void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPos, - uint8_t index, uint16_t spriteId) +void Game::playerUseItem(const uint32_t playerId, const Position& pos, const uint8_t stackPos, + const uint8_t index, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - bool isHotkey = (pos.x == 0xFFFF && pos.y == 0 && pos.z == 0); + const bool isHotkey = (pos.x == 0xFFFF && pos.y == 0 && pos.z == 0); if (isHotkey && !g_config.getBoolean(ConfigManager::AIMBOT_HOTKEY_ENABLED)) { return; } - Thing* thing = internalGetThing(player, pos, stackPos, spriteId, STACKPOS_USEITEM); + const auto thing = internalGetThing(player, pos, stackPos, spriteId, STACKPOS_USEITEM); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->isUseable() || item->getClientID() != spriteId) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; } - ReturnValue ret = g_actions->canUse(player, pos); - if (ret != RETURNVALUE_NOERROR) { + if (ReturnValue ret = g_actions->canUse(player, pos); ret != RETURNVALUE_NOERROR) { if (ret == RETURNVALUE_TOOFARAWAY) { - std::vector listDir; - if (player->getPathTo(pos, listDir, 0, 1, true, true)) { + if (std::vector listDir; player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask([this, playerID = player->getID(), listDir = std::move(listDir)]() { playerAutoWalk(playerID, listDir); })); SchedulerTask* task = createSchedulerTask(RANGE_USE_ITEM_INTERVAL, [=, this]() { playerUseItem(playerId, pos, stackPos, index, spriteId); }); player->setNextWalkActionTask(task); @@ -2216,7 +2212,7 @@ void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPo } if (!player->canDoAction()) { - uint32_t delay = player->getNextActionTime(); + const uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, [=, this]() { playerUseItem(playerId, pos, stackPos, index, spriteId); }); player->setNextActionTask(task); return; @@ -2228,14 +2224,14 @@ void Game::playerUseItem(uint32_t playerId, const Position& pos, uint8_t stackPo g_actions->useItem(player, pos, index, item, isHotkey); } -void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t spriteId) +void Game::playerUseWithCreature(const uint32_t playerId, const Position& fromPos, const uint8_t fromStackPos, const uint32_t creatureId, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (!creature) { return; } @@ -2244,7 +2240,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin return; } - bool isHotkey = (fromPos.x == 0xFFFF && fromPos.y == 0 && fromPos.z == 0); + const bool isHotkey = (fromPos.x == 0xFFFF && fromPos.y == 0 && fromPos.z == 0); if (!g_config.getBoolean(ConfigManager::AIMBOT_HOTKEY_ENABLED)) { if (creature->getPlayer() || isHotkey) { player->sendCancelMessage(RETURNVALUE_DIRECTPLAYERSHOOT); @@ -2252,19 +2248,19 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin } } - Thing* thing = internalGetThing(player, fromPos, fromStackPos, spriteId, STACKPOS_USEITEM); + const auto thing = internalGetThing(player, fromPos, fromStackPos, spriteId, STACKPOS_USEITEM); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item || !item->isUseable() || item->getClientID() != spriteId) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; } - Position toPos = creature->getPosition(); + const Position toPos = creature->getPosition(); Position walkToPos = fromPos; ReturnValue ret = g_actions->canUse(player, fromPos); if (ret == RETURNVALUE_NOERROR) { @@ -2280,8 +2276,11 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin uint8_t itemStackPos = fromStackPos; if (fromPos.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, 0, player, nullptr, &fromPos, &toPos); + ItemPtr moveItem = nullptr; + CylinderPtr t_cylinder = item->getParent(); + CylinderPtr p_cylinder = player; + + ret = internalMoveItem(t_cylinder, p_cylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, 0, player, nullptr, &fromPos, &toPos); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); return; @@ -2291,8 +2290,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin internalGetPosition(moveItem, itemPos, itemStackPos); } - std::vector listDir; - if (player->getPathTo(walkToPos, listDir, 0, 1, true, true)) { + if (std::vector listDir; player->getPathTo(walkToPos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask([this, playerID = player->getID(), listDir = std::move(listDir)]() { playerAutoWalk(playerID, listDir); })); SchedulerTask* task = createSchedulerTask(RANGE_USE_WITH_CREATURE_INTERVAL, [=, this]() { playerUseWithCreature(playerId, itemPos, itemStackPos, creatureId, spriteId); @@ -2309,7 +2307,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position& fromPos, uin } if (!player->canDoAction()) { - uint32_t delay = player->getNextActionTime(); + const uint32_t delay = player->getNextActionTime(); SchedulerTask* task = createSchedulerTask(delay, [=, this]() { playerUseWithCreature(playerId, fromPos, fromStackPos, creatureId, spriteId); }); player->setNextActionTask(task); return; @@ -2321,9 +2319,9 @@ 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(const uint32_t playerId, const uint8_t cid) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2332,21 +2330,21 @@ void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) player->sendCloseContainer(cid); } -void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) +void Game::playerMoveUpContainer(const uint32_t playerId, uint8_t cid) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Container* container = player->getContainerByID(cid); + const auto container = player->getContainerByID(cid); if (!container) { return; } - Container* parentContainer = dynamic_cast(container->getRealParent()); + auto parentContainer = std::dynamic_pointer_cast(container->getRealParent()); if (!parentContainer) { - Tile* tile = container->getTile(); + const auto tile = container->getTile(); if (!tile) { return; } @@ -2355,10 +2353,8 @@ void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) return; } - auto it = browseFields.find(tile); - if (it == browseFields.end()) { - parentContainer = new Container(tile); - parentContainer->incrementReferenceCounter(); + if (const auto it = browseFields.find(tile); it == browseFields.end()) { + parentContainer = std::make_shared(tile); browseFields[tile] = parentContainer; g_scheduler.addEvent(createSchedulerTask(30000, [this, position = tile->getPosition()]() { decreaseBrowseFieldRef(position); })); } else { @@ -2370,14 +2366,14 @@ void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) player->sendContainer(cid, parentContainer, parentContainer->hasParent(), player->getContainerIndex(cid)); } -void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) +void Game::playerUpdateContainer(const uint32_t playerId, uint8_t cid) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Container* container = player->getContainerByID(cid); + auto container = player->getContainerByID(cid); if (!container) { return; } @@ -2385,27 +2381,26 @@ 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 spriteId) +void Game::playerRotateItem(const uint32_t playerId, const Position& pos, const uint8_t stackPos, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Thing* thing = internalGetThing(player, pos, stackPos, 0, STACKPOS_TOPDOWN_ITEM); + const auto thing = internalGetThing(player, pos, stackPos, 0, STACKPOS_TOPDOWN_ITEM); if (!thing) { return; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getClientID() != spriteId || !item->isRotatable() || item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } if (pos.x != 0xFFFF && !Position::areInRange<1, 1, 0>(pos, player->getPosition())) { - std::vector listDir; - if (player->getPathTo(pos, listDir, 0, 1, true, true)) { + if (std::vector listDir; player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask([this, playerID = player->getID(), listDir = std::move(listDir)]() { playerAutoWalk(playerID, listDir); })); SchedulerTask* task = createSchedulerTask(RANGE_ROTATE_ITEM_INTERVAL, [=, this]() { playerRotateItem(playerId, pos, stackPos, spriteId); }); player->setNextWalkActionTask(task); @@ -2415,16 +2410,15 @@ void Game::playerRotateItem(uint32_t playerId, const Position& pos, uint8_t stac return; } - uint16_t newId = Item::items[item->getID()].rotateTo; - if (newId != 0) { + if (const uint16_t newId = Item::items[item->getID()].rotateTo; newId != 0) { transformItem(item, newId); g_events->eventPlayerOnRotateItem(player, item); } } -void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string& text) +void Game::playerWriteItem(const uint32_t playerId, const uint32_t windowTextId, const std::string& text) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2432,7 +2426,7 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: uint16_t maxTextLength = 0; uint32_t internalWindowTextId = 0; - Item* writeItem = player->getWriteItem(internalWindowTextId, maxTextLength); + const auto writeItem = player->getWriteItem(internalWindowTextId, maxTextLength); if (text.length() > maxTextLength || windowTextId != internalWindowTextId) { return; } @@ -2442,10 +2436,9 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: return; } - Cylinder* topParent = writeItem->getTopParent(); + const auto topParent = writeItem->getTopParent(); - Player* owner = dynamic_cast(topParent); - if (owner && owner != player) { + if (const auto owner = std::dynamic_pointer_cast(topParent); owner && owner != player) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -2455,7 +2448,7 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: return; } - for (auto creatureEvent : player->getCreatureEvents(CREATURE_EVENT_TEXTEDIT)) { + for (const auto creatureEvent : player->getCreatureEvents(CREATURE_EVENT_TEXTEDIT)) { if (!creatureEvent->executeTextEdit(player, writeItem, text)) { player->setWriteItem(nullptr); return; @@ -2482,9 +2475,9 @@ 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(const uint32_t playerId, const Position& pos) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2496,8 +2489,7 @@ void Game::playerBrowseField(uint32_t playerId, const Position& pos) } if (!Position::areInRange<1, 1>(playerPos, pos)) { - std::vector listDir; - if (player->getPathTo(pos, listDir, 0, 1, true, true)) { + if (std::vector listDir; player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask([this, playerID = player->getID(), listDir = std::move(listDir)]() { playerAutoWalk(playerID, listDir); })); SchedulerTask* task = createSchedulerTask(RANGE_BROWSE_FIELD_INTERVAL, [=, this]() { playerBrowseField(playerId, pos); }); player->setNextWalkActionTask(task); @@ -2507,7 +2499,7 @@ void Game::playerBrowseField(uint32_t playerId, const Position& pos) return; } - Tile* tile = map.getTile(pos); + const auto tile = map.getTile(pos); if (!tile) { return; } @@ -2516,21 +2508,18 @@ void Game::playerBrowseField(uint32_t playerId, const Position& pos) return; } - Container* container; + ContainerPtr container; - auto it = browseFields.find(tile); - if (it == browseFields.end()) { - container = new Container(tile); - container->incrementReferenceCounter(); + if (const auto it = browseFields.find(tile); it == browseFields.end()) { + container = std::make_shared(tile); browseFields[tile] = container; g_scheduler.addEvent(createSchedulerTask(30000, [this, position = tile->getPosition()]() { decreaseBrowseFieldRef(position); })); } else { container = it->second; } - uint8_t dummyContainerId = 0xF - ((pos.x % 3) * 3 + (pos.y % 3)); - Container* openContainer = player->getContainerByID(dummyContainerId); - if (openContainer) { + const uint8_t dummyContainerId = 0xF - ((pos.x % 3) * 3 + (pos.y % 3)); + if (const auto openContainer = player->getContainerByID(dummyContainerId)) { player->onCloseContainer(openContainer); player->closeContainer(dummyContainerId); } else { @@ -2539,14 +2528,14 @@ void Game::playerBrowseField(uint32_t playerId, const Position& pos) } } -void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index) +void Game::playerSeekInContainer(const uint32_t playerId, uint8_t containerId, uint16_t index) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Container* container = player->getContainerByID(containerId); + const auto container = player->getContainerByID(containerId); if (!container || !container->hasPagination()) { return; } @@ -2559,9 +2548,9 @@ 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(const uint32_t playerId, const uint8_t listId, const uint32_t windowTextId, const std::string& text) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2569,7 +2558,7 @@ void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t w uint32_t internalWindowTextId; uint32_t internalListId; - House* house = player->getEditHouse(internalWindowTextId, internalListId); + auto house = player->getEditHouse(internalWindowTextId, internalListId); if (house && house->canEditAccessList(internalListId, player) && internalWindowTextId == windowTextId && listId == 0) { house->setAccessList(internalListId, text); } @@ -2577,29 +2566,28 @@ void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t w player->setEditHouse(nullptr); } -void Game::playerWrapItem(uint32_t playerId, const Position& position, uint8_t stackPos, const uint16_t spriteId) +void Game::playerWrapItem(const uint32_t playerId, const Position& position, const uint8_t stackPos, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Thing* thing = internalGetThing(player, position, stackPos, 0, STACKPOS_TOPDOWN_ITEM); + const auto thing = internalGetThing(player, position, stackPos, 0, STACKPOS_TOPDOWN_ITEM); if (!thing) { return; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getClientID() != spriteId || !item->hasAttribute(ITEM_ATTRIBUTE_WRAPID) || item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } if (position.x != 0xFFFF && !Position::areInRange<1, 1, 0>(position, player->getPosition())) { - std::vector listDir; - if (player->getPathTo(position, listDir, 0, 1, true, true)) { + if (std::vector listDir; player->getPathTo(position, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask([this, playerID = player->getID(), listDir = std::move(listDir)]() { playerAutoWalk(playerID, listDir); })); - SchedulerTask* task = createSchedulerTask(RANGE_WRAP_ITEM_INTERVAL, [=, this]() { playerWrapItem(playerId, position, stackPos, spriteId); }); + const auto task = createSchedulerTask(RANGE_WRAP_ITEM_INTERVAL, [=, this]() { playerWrapItem(playerId, position, stackPos, spriteId); }); player->setNextWalkActionTask(task); } else { player->sendCancelMessage(RETURNVALUE_THEREISNOWAY); @@ -2610,15 +2598,15 @@ void Game::playerWrapItem(uint32_t playerId, const Position& position, uint8_t s g_events->eventPlayerOnWrapItem(player, item); } -void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t stackPos, - uint32_t tradePlayerId, uint16_t spriteId) +void Game::playerRequestTrade(const uint32_t playerId, const Position& pos, uint8_t stackPos, + const uint32_t tradePlayerId, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Player* tradePartner = getPlayerByID(tradePlayerId); + const auto tradePartner = getPlayerByID(tradePlayerId); if (!tradePartner || tradePartner == player) { player->sendCancelMessage("Select a player to trade with."); return; @@ -2634,20 +2622,20 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st return; } - Thing* tradeThing = internalGetThing(player, pos, stackPos, 0, STACKPOS_TOPDOWN_ITEM); + const auto tradeThing = internalGetThing(player, pos, stackPos, 0, STACKPOS_TOPDOWN_ITEM); if (!tradeThing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - Item* tradeItem = tradeThing->getItem(); + auto tradeItem = tradeThing->getItem(); if (tradeItem->getClientID() != spriteId || !tradeItem->isPickupable() || tradeItem->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } if (g_config.getBoolean(ConfigManager::ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { - if (const HouseTile* const houseTile = dynamic_cast(tradeItem->getTile())) { + if (const auto houseTile = std::dynamic_pointer_cast(tradeItem->getTile())) { if (!tradeItem->getTopParent()->getCreature() && !houseTile->getHouse()->isInvited(player)) { player->sendCancelMessage(RETURNVALUE_PLAYERISNOTINVITED); return; @@ -2663,10 +2651,9 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st } if (!Position::areInRange<1, 1>(tradeItemPosition, playerPosition)) { - std::vector listDir; - if (player->getPathTo(pos, listDir, 0, 1, true, true)) { + if (std::vector listDir; player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher.addTask(createTask([this, playerID = player->getID(), listDir = std::move(listDir)]() { playerAutoWalk(playerID, listDir); })); - SchedulerTask* task = createSchedulerTask(RANGE_REQUEST_TRADE_INTERVAL, [=, this]() { + const auto task = createSchedulerTask(RANGE_REQUEST_TRADE_INTERVAL, [=, this]() { playerRequestTrade(playerId, pos, stackPos, tradePlayerId, spriteId); }); player->setNextWalkActionTask(task); @@ -2676,10 +2663,9 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st return; } - Container* tradeItemContainer = tradeItem->getContainer(); - if (tradeItemContainer) { - for (const auto& it : tradeItems) { - Item* item = it.first; + if (const auto tradeItemContainer = tradeItem->getContainer()) { + for (const auto& key : tradeItems | std::views::keys) { + const auto item = key; if (tradeItem == item) { player->sendCancelMessage("This item is already being traded."); return; @@ -2690,30 +2676,27 @@ void Game::playerRequestTrade(uint32_t playerId, const Position& pos, uint8_t st return; } - Container* container = item->getContainer(); - if (container && container->isHoldingItem(tradeItem)) { + if (const auto container = item->getContainer(); container && container->isHoldingItem(tradeItem)) { player->sendCancelMessage("This item is already being traded."); return; } } } else { - for (const auto& it : tradeItems) { - Item* item = it.first; + for (const auto& key : tradeItems | std::views::keys) { + const auto item = key; if (tradeItem == item) { player->sendCancelMessage("This item is already being traded."); return; } - Container* container = item->getContainer(); - if (container && container->isHoldingItem(tradeItem)) { + if (const auto container = item->getContainer(); container && container->isHoldingItem(tradeItem)) { player->sendCancelMessage("This item is already being traded."); return; } } } - Container* tradeContainer = tradeItem->getContainer(); - if (tradeContainer && tradeContainer->getItemHoldingCount() + 1 > 100) { + if (const auto tradeContainer = tradeItem->getContainer(); tradeContainer && tradeContainer->getItemHoldingCount() + 1 > 100) { player->sendCancelMessage("You can only trade up to 100 objects at once."); return; } @@ -2725,7 +2708,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(const PlayerPtr& player, const PlayerPtr& tradePartner, const ItemPtr& tradeItem) { if (player->tradeState != TRADE_NONE && !(player->tradeState == TRADE_ACKNOWLEDGE && player->tradePartner == tradePartner)) { player->sendCancelMessage(RETURNVALUE_YOUAREALREADYTRADING); @@ -2738,7 +2721,6 @@ bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeI player->tradePartner = tradePartner; player->tradeItem = tradeItem; player->tradeState = TRADE_INITIATED; - tradeItem->incrementReferenceCounter(); tradeItems[tradeItem] = player->getID(); player->sendTradeItemRequest(player->getName(), tradeItem, true); @@ -2748,7 +2730,7 @@ bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeI tradePartner->tradeState = TRADE_ACKNOWLEDGE; tradePartner->tradePartner = player; } else { - Item* counterOfferItem = tradePartner->tradeItem; + const auto counterOfferItem = tradePartner->tradeItem; player->sendTradeItemRequest(tradePartner->getName(), counterOfferItem, false); tradePartner->sendTradeItemRequest(player->getName(), tradeItem, false); } @@ -2756,9 +2738,9 @@ bool Game::internalStartTrade(Player* player, Player* tradePartner, Item* tradeI return true; } -void Game::playerAcceptTrade(uint32_t playerId) +void Game::playerAcceptTrade(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2767,7 +2749,7 @@ void Game::playerAcceptTrade(uint32_t playerId) return; } - Player* tradePartner = player->tradePartner; + const auto tradePartner = player->tradePartner; if (!tradePartner) { return; } @@ -2782,8 +2764,8 @@ void Game::playerAcceptTrade(uint32_t playerId) return; } - Item* playerTradeItem = player->tradeItem; - Item* partnerTradeItem = tradePartner->tradeItem; + const auto playerTradeItem = player->tradeItem; + const auto partnerTradeItem = tradePartner->tradeItem; if (!g_events->eventPlayerOnTradeAccept(player, tradePartner, playerTradeItem, partnerTradeItem)) { internalCloseTrade(player, false); @@ -2795,13 +2777,13 @@ void Game::playerAcceptTrade(uint32_t playerId) auto it = tradeItems.find(playerTradeItem); if (it != tradeItems.end()) { - ReleaseItem(it->first); + // ReleaseItem(it->first); tradeItems.erase(it); } it = tradeItems.find(partnerTradeItem); if (it != tradeItems.end()) { - ReleaseItem(it->first); + // ReleaseItem(it->first); tradeItems.erase(it); } @@ -2825,15 +2807,20 @@ void Game::playerAcceptTrade(uint32_t playerId) } if (tradePartnerRet == RETURNVALUE_NOERROR && playerRet == RETURNVALUE_NOERROR) { - tradePartnerRet = internalAddItem(tradePartner, playerTradeItem, INDEX_WHEREEVER, 0, true); - playerRet = internalAddItem(player, partnerTradeItem, INDEX_WHEREEVER, 0, true); + CylinderPtr t_player = tradePartner; + tradePartnerRet = internalAddItem(t_player, playerTradeItem, INDEX_WHEREEVER, 0, true); + CylinderPtr c_player = player; + playerRet = internalAddItem(c_player, partnerTradeItem, INDEX_WHEREEVER, 0, true); if (tradePartnerRet == RETURNVALUE_NOERROR && playerRet == RETURNVALUE_NOERROR) { playerRet = internalRemoveItem(playerTradeItem, playerTradeItem->getItemCount(), true); tradePartnerRet = internalRemoveItem(partnerTradeItem, partnerTradeItem->getItemCount(), true); if (tradePartnerRet == RETURNVALUE_NOERROR && playerRet == RETURNVALUE_NOERROR) { - tradePartnerRet = internalMoveItem(playerTradeItem->getParent(), tradePartner, INDEX_WHEREEVER, playerTradeItem, playerTradeItem->getItemCount(), nullptr, FLAG_IGNOREAUTOSTACK, nullptr, partnerTradeItem); + CylinderPtr t_parent = playerTradeItem->getParent(); + CylinderPtr c_parent = tradePartner; + tradePartnerRet = internalMoveItem(t_parent, c_parent, INDEX_WHEREEVER, playerTradeItem, playerTradeItem->getItemCount(), nullptr, FLAG_IGNOREAUTOSTACK, nullptr, partnerTradeItem); if (tradePartnerRet == RETURNVALUE_NOERROR) { - internalMoveItem(partnerTradeItem->getParent(), player, INDEX_WHEREEVER, partnerTradeItem, partnerTradeItem->getItemCount(), nullptr, FLAG_IGNOREAUTOSTACK); + CylinderPtr pt_parent = partnerTradeItem->getParent(); + internalMoveItem(pt_parent, c_player, INDEX_WHEREEVER, partnerTradeItem, partnerTradeItem->getItemCount(), nullptr, FLAG_IGNOREAUTOSTACK); playerTradeItem->onTradeEvent(ON_TRADE_TRANSFER, tradePartner); partnerTradeItem->onTradeEvent(ON_TRADE_TRANSFER, player); isSuccess = true; @@ -2872,7 +2859,7 @@ void Game::playerAcceptTrade(uint32_t playerId) } } -std::string Game::getTradeErrorDescription(ReturnValue ret, Item* item) +std::string Game::getTradeErrorDescription(const ReturnValue ret, const ItemPtr& item) { if (item) { if (ret == RETURNVALUE_NOTENOUGHCAPACITY) { @@ -2884,19 +2871,19 @@ 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(const uint32_t playerId, const bool lookAtCounterOffer, uint8_t index) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Player* tradePartner = player->tradePartner; + const auto tradePartner = player->tradePartner; if (!tradePartner) { return; } - Item* tradeItem; + ItemPtr tradeItem; if (lookAtCounterOffer) { tradeItem = tradePartner->getTradeItem(); } else { @@ -2917,18 +2904,16 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t return; } - Container* tradeContainer = tradeItem->getContainer(); + const auto tradeContainer = tradeItem->getContainer(); if (!tradeContainer) { return; } - std::vector containers {tradeContainer}; + std::vector containers {tradeContainer}; size_t i = 0; while (i < containers.size()) { - const Container* container = containers[i++]; - for (Item* item : container->getItemList()) { - Container* tmpContainer = item->getContainer(); - if (tmpContainer) { + for (const auto container = containers[i++]; const auto item : container->getItemList()) { + if (auto tmpContainer = item->getContainer()) { containers.push_back(tmpContainer); } @@ -2940,9 +2925,9 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t } } -void Game::playerCloseTrade(uint32_t playerId) +void Game::playerCloseTrade(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -2950,17 +2935,16 @@ void Game::playerCloseTrade(uint32_t playerId) internalCloseTrade(player); } -void Game::internalCloseTrade(Player* player, bool sendCancel/* = true*/) +void Game::internalCloseTrade(const PlayerPtr& player, const bool sendCancel/* = true*/) { - Player* tradePartner = player->tradePartner; + auto tradePartner = player->tradePartner; if ((tradePartner && tradePartner->getTradeState() == TRADE_TRANSFER) || player->getTradeState() == TRADE_TRANSFER) { return; } if (player->getTradeItem()) { - auto it = tradeItems.find(player->getTradeItem()); - if (it != tradeItems.end()) { - ReleaseItem(it->first); + if (const auto it = tradeItems.find(player->getTradeItem()); it != tradeItems.end()) { + // ReleaseItem(it->first); tradeItems.erase(it); } @@ -2978,9 +2962,8 @@ void Game::internalCloseTrade(Player* player, bool sendCancel/* = true*/) if (tradePartner) { if (tradePartner->getTradeItem()) { - auto it = tradeItems.find(tradePartner->getTradeItem()); - if (it != tradeItems.end()) { - ReleaseItem(it->first); + if (const auto it = tradeItems.find(tradePartner->getTradeItem()); it != tradeItems.end()) { + // ReleaseItem(it->first); tradeItems.erase(it); } @@ -2998,21 +2981,21 @@ void Game::internalCloseTrade(Player* player, bool sendCancel/* = true*/) } } -void Game::playerPurchaseItem(uint32_t playerId, uint16_t spriteId, uint8_t count, uint8_t amount, +void Game::playerPurchaseItem(const uint32_t playerId, const uint16_t spriteId, const uint8_t count, uint8_t amount, bool ignoreCap/* = false*/, bool inBackpacks/* = false*/) { if (amount == 0 || amount > 100) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } int32_t onBuy, onSell; - Npc* merchant = player->getShopOwner(onBuy, onSell); + auto merchant = player->getShopOwner(onBuy, onSell); if (!merchant) { return; } @@ -3036,20 +3019,20 @@ void Game::playerPurchaseItem(uint32_t playerId, uint16_t spriteId, uint8_t coun merchant->onPlayerTrade(player, onBuy, it.id, subType, amount, ignoreCap, inBackpacks); } -void Game::playerSellItem(uint32_t playerId, uint16_t spriteId, uint8_t count, uint8_t amount, bool ignoreEquipped) +void Game::playerSellItem(const uint32_t playerId, const uint16_t spriteId, const uint8_t count, uint8_t amount, bool ignoreEquipped) { if (amount == 0 || amount > 100) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } int32_t onBuy, onSell; - Npc* merchant = player->getShopOwner(onBuy, onSell); + auto merchant = player->getShopOwner(onBuy, onSell); if (!merchant) { return; } @@ -3069,9 +3052,9 @@ void Game::playerSellItem(uint32_t playerId, uint16_t spriteId, uint8_t count, u merchant->onPlayerTrade(player, onSell, it.id, subType, amount, ignoreEquipped); } -void Game::playerCloseShop(uint32_t playerId) +void Game::playerCloseShop(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3079,17 +3062,16 @@ void Game::playerCloseShop(uint32_t playerId) player->closeShopWindow(); } -void Game::playerLookInShop(uint32_t playerId, uint16_t spriteId, uint8_t count) +void Game::playerLookInShop(const uint32_t playerId, const uint16_t spriteId, const uint8_t count) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } int32_t onBuy, onSell; - Npc* merchant = player->getShopOwner(onBuy, onSell); - if (!merchant) { + if (const auto merchant = player->getShopOwner(onBuy, onSell); !merchant) { return; } @@ -3113,26 +3095,26 @@ void Game::playerLookInShop(uint32_t playerId, uint16_t spriteId, uint8_t count) g_events->eventPlayerOnLookInShop(player, &it, subType, description); } -void Game::playerLookAt(uint32_t playerId, const Position& pos, uint8_t stackPos) +void Game::playerLookAt(const uint32_t playerId, const Position& pos, uint8_t stackPos) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Thing* thing = internalGetThing(player, pos, stackPos, 0, STACKPOS_LOOK); + const auto thing = internalGetThing(player, pos, stackPos, 0, STACKPOS_LOOK); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - Position thingPos = thing->getPosition(); + const Position thingPos = thing->getPosition(); if (!player->canSee(thingPos)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - Position playerPos = player->getPosition(); + const Position playerPos = player->getPosition(); int32_t lookDistance; if (thing != player) { @@ -3147,14 +3129,14 @@ void Game::playerLookAt(uint32_t playerId, const Position& pos, uint8_t stackPos g_events->eventPlayerOnLook(player, pos, thing, stackPos, lookDistance); } -void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) +void Game::playerLookInBattleList(const uint32_t playerId, const uint32_t creatureId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (!creature) { return; } @@ -3182,9 +3164,9 @@ void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) g_events->eventPlayerOnLookInBattleList(player, creature, lookDistance); } -void Game::playerCancelAttackAndFollow(uint32_t playerId) +void Game::playerCancelAttackAndFollow(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3194,9 +3176,9 @@ void Game::playerCancelAttackAndFollow(uint32_t playerId) player->stopWalk(); } -void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) +void Game::playerSetAttackedCreature(const uint32_t playerId, const uint32_t creatureId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3207,14 +3189,14 @@ void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) return; } - Creature* attackCreature = getCreatureByID(creatureId); + const auto attackCreature = getCreatureByID(creatureId); if (!attackCreature) { player->setAttackedCreature(nullptr); player->sendCancelTarget(); return; } - ReturnValue ret = Combat::canTargetCreature(player, attackCreature); + const ReturnValue ret = Combat::canTargetCreature(player, attackCreature); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); player->sendCancelTarget(); @@ -3226,9 +3208,9 @@ void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) g_dispatcher.addTask(createTask([this, id = player->getID()]() { updateCreatureWalk(id); })); } -void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) +void Game::playerFollowCreature(const uint32_t playerId, const uint32_t creatureId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3238,9 +3220,9 @@ 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(const uint32_t playerId, const fightMode_t fightMode, const bool chaseMode, const bool secureMode) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3250,18 +3232,18 @@ 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(const uint32_t playerId, const std::string& name) { if (name.length() > PLAYER_NAME_LENGTH) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Player* vipPlayer = getPlayerByName(name); + const auto vipPlayer = getPlayerByName(name); if (!vipPlayer) { uint32_t guid; bool specialVip; @@ -3291,9 +3273,9 @@ void Game::playerRequestAddVip(uint32_t playerId, const std::string& name) } } -void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) +void Game::playerRequestRemoveVip(const uint32_t playerId, const uint32_t guid) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3301,9 +3283,9 @@ 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(const uint32_t playerId, const uint32_t guid, const std::string& description, const uint32_t icon, const bool notify) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3311,9 +3293,9 @@ void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::str player->editVIP(guid, description, icon, notify); } -void Game::playerTurn(uint32_t playerId, Direction dir) +void Game::playerTurn(const uint32_t playerId, const Direction dir) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3326,13 +3308,13 @@ void Game::playerTurn(uint32_t playerId, Direction dir) internalCreatureTurn(player, dir); } -void Game::playerRequestOutfit(uint32_t playerId) +void Game::playerRequestOutfit(const uint32_t playerId) { if (!g_config.getBoolean(ConfigManager::ALLOW_CHANGEOUTFIT)) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3340,9 +3322,9 @@ void Game::playerRequestOutfit(uint32_t playerId) player->sendOutfitWindow(); } -void Game::playerToggleMount(uint32_t playerId, bool mount) +void Game::playerToggleMount(const uint32_t playerId, const bool mount) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3350,24 +3332,23 @@ void Game::playerToggleMount(uint32_t playerId, bool mount) player->toggleMount(mount); } -void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit) +void Game::playerChangeOutfit(const uint32_t playerId, Outfit_t outfit) { if (!g_config.getBoolean(ConfigManager::ALLOW_CHANGEOUTFIT)) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - const Outfit* playerOutfit = Outfits::getInstance().getOutfitByLookType(player->getSex(), outfit.lookType); - if (!playerOutfit) { + if (const auto playerOutfit = Outfits::getInstance().getOutfitByLookType(player->getSex(), outfit.lookType); !playerOutfit) { outfit.lookMount = 0; } if (outfit.lookMount != 0) { - Mount* mount = mounts.getMountByClientID(outfit.lookMount); + const auto mount = mounts.getMountByClientID(outfit.lookMount); if (!mount) { return; } @@ -3377,8 +3358,7 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit) } if (player->isMounted()) { - Mount* prevMount = mounts.getMountByID(player->getCurrentMount()); - if (prevMount) { + if (const auto prevMount = mounts.getMountByID(player->getCurrentMount())) { changeSpeed(player, mount->speed - prevMount->speed); } @@ -3402,9 +3382,9 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit) } } -void Game::playerShowQuestLog(uint32_t playerId) +void Game::playerShowQuestLog(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3412,14 +3392,14 @@ void Game::playerShowQuestLog(uint32_t playerId) player->sendQuestLog(); } -void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) +void Game::playerShowQuestLine(const uint32_t playerId, const uint16_t questId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Quest* quest = quests.getQuestByID(questId); + const auto quest = quests.getQuestByID(questId); if (!quest) { return; } @@ -3427,10 +3407,10 @@ void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) player->sendQuestLine(quest); } -void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, +void Game::playerSay(const uint32_t playerId, const uint16_t channelId, const SpeakClasses type, const std::string& receiver, const std::string& text) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3446,8 +3426,7 @@ void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, return; } - uint32_t muteTime = player->isMuted(); - if (muteTime > 0) { + if (const uint32_t muteTime = player->isMuted(); muteTime > 0) { player->sendTextMessage(MESSAGE_STATUS_SMALL, fmt::format("You are still muted for {:d} seconds.", muteTime)); return; } @@ -3479,7 +3458,7 @@ void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, case TALKTYPE_CHANNEL_O: case TALKTYPE_CHANNEL_Y: case TALKTYPE_CHANNEL_R1: - g_chat->talkToChannel(*player, type, text, channelId); + g_chat->talkToChannel(player, type, text, channelId); break; case TALKTYPE_BROADCAST: @@ -3491,7 +3470,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(const PlayerPtr& player, const SpeakClasses type, const std::string& text) { std::string words = text; @@ -3515,7 +3494,7 @@ bool Game::playerSaySpell(Player* player, SpeakClasses type, const std::string& return false; } -void Game::playerWhisper(Player* player, const std::string& text) +void Game::playerWhisper(const PlayerPtr& player, const std::string& text) { SpectatorVec spectators; map.getSpectators(spectators, player->getPosition(), false, false, @@ -3523,8 +3502,8 @@ void Game::playerWhisper(Player* player, const std::string& text) Map::maxClientViewportY, Map::maxClientViewportY); //send to client - for (Creature* spectator : spectators) { - if (Player* spectatorPlayer = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto spectatorPlayer = spectator->getPlayer()) { if (!Position::areInRange<1, 1>(player->getPosition(), spectatorPlayer->getPosition())) { spectatorPlayer->sendCreatureSay(player, TALKTYPE_WHISPER, "pspsps"); } else { @@ -3534,20 +3513,19 @@ void Game::playerWhisper(Player* player, const std::string& text) } //event method - for (Creature* spectator : spectators) { + for (const auto spectator : spectators) { spectator->onCreatureSay(player, TALKTYPE_WHISPER, text); } } -bool Game::playerYell(Player* player, const std::string& text) +bool Game::playerYell(const PlayerPtr& player, const std::string& text) { if (player->hasCondition(CONDITION_YELLTICKS)) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); return false; } - uint32_t minimumLevel = g_config.getNumber(ConfigManager::YELL_MINIMUM_LEVEL); - if (player->getLevel() < minimumLevel) { + if (uint32_t minimumLevel = g_config.getNumber(ConfigManager::YELL_MINIMUM_LEVEL); player->getLevel() < minimumLevel) { if (g_config.getBoolean(ConfigManager::YELL_ALLOW_PREMIUM)) { if (player->isPremium()) { internalCreatureSay(player, TALKTYPE_YELL, asUpperCaseString(text), false); @@ -3570,10 +3548,10 @@ bool Game::playerYell(Player* player, const std::string& text) return true; } -bool Game::playerSpeakTo(Player* player, SpeakClasses type, const std::string& receiver, +bool Game::playerSpeakTo(const PlayerPtr& player, SpeakClasses type, const std::string& receiver, const std::string& text) { - Player* toPlayer = getPlayerByName(receiver); + const auto toPlayer = getPlayerByName(receiver); if (!toPlayer) { player->sendTextMessage(MESSAGE_STATUS_SMALL, "A player with this name is not online."); return false; @@ -3586,8 +3564,7 @@ bool Game::playerSpeakTo(Player* player, SpeakClasses type, const std::string& r } if (!player->isAccessPlayer()) { - uint32_t minimumLevel = g_config.getNumber(ConfigManager::MINIMUM_LEVEL_TO_SEND_PRIVATE); - if (player->getLevel() < minimumLevel) { + if (uint32_t minimumLevel = g_config.getNumber(ConfigManager::MINIMUM_LEVEL_TO_SEND_PRIVATE); player->getLevel() < minimumLevel) { if (g_config.getBoolean(ConfigManager::PREMIUM_TO_SEND_PRIVATE)) { if (!player->isPremium()) { player->sendTextMessage( @@ -3618,11 +3595,11 @@ 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(const PlayerPtr& player, const std::string& text) { SpectatorVec spectators; map.getSpectators(spectators, player->getPosition()); - for (Creature* spectator : spectators) { + for (const auto spectator : spectators) { if (spectator->getNpc()) { spectator->onCreatureSay(player, TALKTYPE_PRIVATE_PN, text); } @@ -3630,18 +3607,18 @@ void Game::playerSpeakToNpc(Player* player, const std::string& text) } //-- -bool Game::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/, bool sameFloor /*= false*/, - int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const +bool Game::canThrowObjectTo(const Position& fromPos, const Position& toPos, const bool checkLineOfSight /*= true*/, const bool sameFloor /*= false*/, + const int32_t rangex /*= Map::maxClientViewportX*/, const int32_t rangey /*= Map::maxClientViewportY*/) { return map.canThrowObjectTo(fromPos, toPos, checkLineOfSight, sameFloor, rangex, rangey); } -bool Game::isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor /*= false*/) const +bool Game::isSightClear(const Position& fromPos, const Position& toPos, const bool sameFloor /*= false*/) { return map.isSightClear(fromPos, toPos, sameFloor); } -bool Game::internalCreatureTurn(Creature* creature, Direction dir) +bool Game::internalCreatureTurn(const CreaturePtr& creature, const Direction dir) { if (creature->getDirection() == dir) { return false; @@ -3652,15 +3629,15 @@ bool Game::internalCreatureTurn(Creature* creature, Direction dir) //send to client SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendCreatureTurn(creature); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendCreatureTurn(creature); } return true; } -bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std::string& text, - bool ghostMode, SpectatorVec* spectatorsPtr/* = nullptr*/, const Position* pos/* = nullptr*/, bool echo/* = false*/) +bool Game::internalCreatureSay(const CreaturePtr& creature, const SpeakClasses type, const std::string& text, + const bool ghostMode, SpectatorVec* spectatorsPtr/* = nullptr*/, const Position* pos/* = nullptr*/, const bool echo/* = false*/) { if (text.empty()) { return false; @@ -3689,8 +3666,8 @@ bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std: } //send to client - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto tmpPlayer = spectator->getPlayer()) { if (!ghostMode || tmpPlayer->canSeeCreature(creature)) { tmpPlayer->sendCreatureSay(creature, type, text, pos); } @@ -3699,7 +3676,7 @@ bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std: //event method if (!echo) { - for (Creature* spectator : spectators) { + for (const auto spectator : spectators) { spectator->onCreatureSay(creature, type, text); if (creature != spectator) { g_events->eventCreatureOnHear(spectator, creature, text, type); @@ -3709,32 +3686,32 @@ bool Game::internalCreatureSay(Creature* creature, SpeakClasses type, const std: return true; } -void Game::checkCreatureWalk(uint32_t creatureId) +void Game::checkCreatureWalk(const uint32_t creatureId) { - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->onWalk(); cleanup(); } } -void Game::updateCreatureWalk(uint32_t creatureId) +void Game::updateCreatureWalk(const uint32_t creatureId) { - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->goToFollowCreature(); } } -void Game::checkCreatureAttack(uint32_t creatureId) +void Game::checkCreatureAttack(const uint32_t creatureId) { - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (creature && creature->getHealth() > 0) { creature->onAttacking(0); } } -void Game::addCreatureCheck(Creature* creature) +void Game::addCreatureCheck(const CreaturePtr& creature) { creature->creatureCheck = true; @@ -3745,25 +3722,24 @@ void Game::addCreatureCheck(Creature* creature) creature->inCheckCreaturesVector = true; checkCreatureLists[uniform_random(0, EVENT_CREATURECOUNT - 1)].push_back(creature); - creature->incrementReferenceCounter(); } -void Game::removeCreatureCheck(Creature* creature) +void Game::removeCreatureCheck(const CreaturePtr& creature) { if (creature->inCheckCreaturesVector) { creature->creatureCheck = false; } } -void Game::checkCreatures(size_t index) +void Game::checkCreatures(const size_t index) { g_scheduler.addEvent(createSchedulerTask(EVENT_CHECK_CREATURE_INTERVAL, [=, this]() { checkCreatures((index + 1) % EVENT_CREATURECOUNT); })); auto& checkCreatureList = checkCreatureLists[index]; - auto it = checkCreatureList.begin(), end = checkCreatureList.end(); + auto it = checkCreatureList.begin(); + const auto end = checkCreatureList.end(); while (it != end) { - Creature* creature = *it; - if (creature->creatureCheck) { + if (const auto creature = *it; creature->creatureCheck) { if (creature->getHealth() > 0) { creature->onThink(EVENT_CREATURE_THINK_INTERVAL); creature->onAttacking(EVENT_CREATURE_THINK_INTERVAL); @@ -3773,14 +3749,14 @@ void Game::checkCreatures(size_t index) } else { creature->inCheckCreaturesVector = false; it = checkCreatureList.erase(it); - ReleaseCreature(creature); + // ReleaseCreature(creature); } } cleanup(); } -void Game::changeSpeed(Creature* creature, int32_t varSpeedDelta) +void Game::changeSpeed(const CreaturePtr& creature, const int32_t varSpeedDelta) { int32_t varSpeed = creature->getSpeed() - creature->getBaseSpeed(); varSpeed += varSpeedDelta; @@ -3790,13 +3766,13 @@ void Game::changeSpeed(Creature* creature, int32_t varSpeedDelta) //send to clients SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), false, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendChangeSpeed(creature, creature->getStepSpeed()); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendChangeSpeed(creature, creature->getStepSpeed()); } } -void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outfit) +void Game::internalCreatureChangeOutfit(const CreaturePtr& creature, const Outfit_t& outfit) { if (!g_events->eventCreatureOnChangeOutfit(creature, outfit)) { return; @@ -3811,35 +3787,35 @@ void Game::internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outf //send to clients SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendCreatureChangeOutfit(creature, outfit); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendCreatureChangeOutfit(creature, outfit); } } -void Game::internalCreatureChangeVisible(Creature* creature, bool visible) +void Game::internalCreatureChangeVisible(const CreaturePtr& creature, bool visible) { //send to clients SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendCreatureChangeVisible(creature, visible); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendCreatureChangeVisible(creature, visible); } } -void Game::changeLight(const Creature* creature) +void Game::changeLight(const CreatureConstPtr& creature) { //send to clients SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendCreatureLight(creature); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendCreatureLight(creature); } } -bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* target, bool checkDefense, bool checkArmor, bool field, bool ignoreResistances /*= false */) +bool Game::combatBlockHit(CombatDamage& damage, const CreaturePtr& attacker, const CreaturePtr& target, const bool checkDefense, const bool checkArmor, const bool field, const bool ignoreResistances /*= false */) { if (damage.primary.type == COMBAT_NONE && damage.secondary.type == COMBAT_NONE) { return true; @@ -3853,7 +3829,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](const BlockType_t blockType, const CombatType_t combatType, const Position& targetPos) { if (blockType == BLOCK_DEFENSE) { addMagicEffect(targetPos, CONST_ME_POFF); } else if (blockType == BLOCK_ARMOR) { @@ -3897,9 +3873,9 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta g_events->eventCreatureOnAttack(attacker, target, primaryBlockType, damage.primary.type, damage.origin, damage.critical, damage.leeched); g_events->eventCreatureOnDefend(target, attacker, primaryBlockType, damage.primary.type, damage.origin, damage.critical, damage.leeched); - if (Player* aggressor = attacker->getPlayer()) { + if (const auto aggressor = attacker->getPlayer()) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = aggressor->getInventoryItem(static_cast(slot)); + const auto item = aggressor->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -3909,9 +3885,9 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta } } - if (Player* victim = target->getPlayer()) { + if (const auto victim = target->getPlayer()) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = victim->getInventoryItem(static_cast(slot)); + const auto item = victim->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -3935,9 +3911,9 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta g_events->eventCreatureOnAttack(attacker, target, secondaryBlockType, damage.secondary.type, damage.origin, damage.critical, damage.leeched); g_events->eventCreatureOnDefend(target, attacker, secondaryBlockType, damage.secondary.type, damage.origin, damage.critical, damage.leeched); - if (Player* aggressor = attacker->getPlayer()) { + if (const auto aggressor = attacker->getPlayer()) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = aggressor->getInventoryItem(static_cast(slot)); + const auto item = aggressor->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -3947,9 +3923,9 @@ bool Game::combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* ta } } - if (Player* victim = target->getPlayer()) { + if (const auto victim = target->getPlayer()) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = victim->getInventoryItem(static_cast(slot)); + const auto item = victim->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -3971,11 +3947,11 @@ 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(const CombatType_t combatType, const CreaturePtr& target, TextColor_t& color, uint8_t& effect) { switch (combatType) { case COMBAT_PHYSICALDAMAGE: { - Item* splash = nullptr; + ItemPtr splash = nullptr; switch (target->getRace()) { case RACE_VENOM: color = TEXTCOLOR_LIGHTGREEN; @@ -3985,7 +3961,7 @@ void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColo case RACE_BLOOD: color = TEXTCOLOR_RED; effect = CONST_ME_DRAWBLOOD; - if (const Tile* tile = target->getTile()) { + if (const auto tile = target->getTile()) { if (!tile->hasFlag(TILESTATE_PROTECTIONZONE)) { splash = Item::CreateItem(ITEM_SMALLSPLASH, FLUID_BLOOD); } @@ -4010,7 +3986,8 @@ void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColo } if (splash) { - internalAddItem(target->getTile(), splash, INDEX_WHEREEVER, FLAG_NOLIMIT); + CylinderPtr t_tile = target->getTile(); + internalAddItem(t_tile, splash, INDEX_WHEREEVER, FLAG_NOLIMIT); startDecay(splash); } @@ -4034,31 +4011,37 @@ void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColo effect = CONST_ME_LOSEENERGY; break; } + case COMBAT_FIREDAMAGE: { color = TEXTCOLOR_ORANGE; effect = CONST_ME_HITBYFIRE; break; } + case COMBAT_ICEDAMAGE: { color = TEXTCOLOR_SKYBLUE; effect = CONST_ME_ICEATTACK; break; } + case COMBAT_HOLYDAMAGE: { color = TEXTCOLOR_YELLOW; effect = CONST_ME_HOLYDAMAGE; break; } + case COMBAT_DEATHDAMAGE: { color = TEXTCOLOR_DARKRED; effect = CONST_ME_SMALLCLOUDS; break; } + case COMBAT_LIFEDRAIN: { color = TEXTCOLOR_RED; effect = CONST_ME_MAGIC_RED; break; } + default: { color = TEXTCOLOR_NONE; effect = CONST_ME_NONE; @@ -4067,7 +4050,7 @@ void Game::combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColo } } -bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage& damage) +bool Game::combatChangeHealth(const CreaturePtr& attacker, const CreaturePtr& target, CombatDamage& damage) { // Get the position of the target for later use in displaying messages and effects const Position& targetPos = target->getPosition(); @@ -4080,7 +4063,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } // Determine if the attacker is a player, if not, set to nullptr - Player* attackerPlayer; + PlayerPtr attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { @@ -4088,7 +4071,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } // Check if the target is a player - Player* targetPlayer = target->getPlayer(); + auto targetPlayer = target->getPlayer(); // If the attacker is a player with a black skull and the target is not marked with a skull, // the attack should not proceed. @@ -4101,7 +4084,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage const auto& events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); if (!events.empty()) { // Execute each health change event - for (CreatureEvent* creatureEvent : events) { + for (const auto creatureEvent : events) { creatureEvent->executeHealthChange(target, attacker, damage); } // Reset the damage origin to prevent recursive calls from re-triggering the event @@ -4118,13 +4101,10 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage // rewardboss healing contribution if (target && target->getPlayer()) { - for (const auto& [monsterId, rewardInfo] : g_game.rewardBossTracking) { - Monster* monster = getMonsterByID(monsterId); - if (monster && monster->isRewardBoss()) { - const Position& targetPos = target->getPosition(); + for (const auto& monsterId : g_game.rewardBossTracking | std::views::keys) { + if (const auto monster = getMonsterByID(monsterId); monster && monster->isRewardBoss()) { const Position& monsterPos = monster->getPosition(); - double distBetweenTargetAndBoss = std::sqrt(std::pow(targetPos.x - monsterPos.x, 2) + std::pow(targetPos.y - monsterPos.y, 2)); - if (distBetweenTargetAndBoss < 7) { + if (double distBetweenTargetAndBoss = std::sqrt(std::pow(targetPos.x - monsterPos.x, 2) + std::pow(targetPos.y - monsterPos.y, 2)); distBetweenTargetAndBoss < 7) { uint32_t playerGuid = target->getPlayer()->getGUID(); rewardBossTracking[monsterId].playerScoreTable[playerGuid].damageTaken += realHealthChange * g_config.getFloat(ConfigManager::REWARD_RATE_HEALING_DONE); } @@ -4147,10 +4127,10 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage // Get all spectators around the target SpectatorVec spectators; map.getSpectators(spectators, targetPos, false, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); - Player* spectatorPlayer = static_cast(spectator); + auto spectatorPlayer = std::static_pointer_cast(spectator); if (spectatorPlayer == attackerPlayer && attackerPlayer != targetPlayer) { message.type = MESSAGE_HEALED; message.text = fmt::format("You heal {:s} for {:s}.", target->getNameDescription(), damageString); @@ -4192,14 +4172,14 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } // Similar logic for attacker and target player checks as before - Player* attackerPlayer; + PlayerPtr attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { attackerPlayer = nullptr; } - Player* targetPlayer = target->getPlayer(); + const auto targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer && attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(targetPlayer) == SKULL_NONE) { return false; } @@ -4221,12 +4201,10 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage // Check if the target has a mana shield, which can absorb some or all of the damage if (targetPlayer && target->hasCondition(CONDITION_MANASHIELD) && damage.primary.type != COMBAT_UNDEFINEDDAMAGE) { - int32_t manaDamage = std::min(targetPlayer->getMana(), healthChange); - if (manaDamage != 0) { + if (int32_t manaDamage = std::min(targetPlayer->getMana(), healthChange); manaDamage != 0) { if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); - if (!events.empty()) { - for (CreatureEvent* creatureEvent : events) { + if (const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); !events.empty()) { + for (const auto creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); } healthChange = damage.primary.value + damage.secondary.value; @@ -4248,10 +4226,10 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage message.primary.color = TEXTCOLOR_BLUE; // Notify spectators about the mana drain - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); - Player* spectatorPlayer = static_cast(spectator); + PlayerPtr spectatorPlayer = std::static_pointer_cast(spectator); if (spectatorPlayer->getPosition().z != targetPos.z) { continue; } @@ -4303,9 +4281,8 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage // Handle health change events again if necessary if (damage.origin != ORIGIN_NONE) { - const auto& events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); - if (!events.empty()) { - for (CreatureEvent* creatureEvent : events) { + if (const auto& events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); !events.empty()) { + for (const auto creatureEvent : events) { creatureEvent->executeHealthChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -4356,8 +4333,8 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage std::string spectatorMessage; - for (Creature* spectator : spectators) { - Player* tmpPlayer = spectator->getPlayer(); + for (const auto spectator : spectators) { + const auto tmpPlayer = spectator->getPlayer(); if (tmpPlayer->getPosition().z != targetPos.z) { continue; } @@ -4396,7 +4373,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage if (target && target->getMonster() && target->getMonster()->isRewardBoss()) { uint32_t monsterId = target->getMonster()->getID(); - if (rewardBossTracking.find(monsterId) == rewardBossTracking.end()) { + if (!rewardBossTracking.contains(monsterId)) { rewardBossTracking[monsterId] = RewardBossContributionInfo(); } @@ -4410,7 +4387,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage if (attacker && attacker->getMonster() && attacker->getMonster()->isRewardBoss()) { uint32_t monsterId = attacker->getMonster()->getID(); - if (rewardBossTracking.find(monsterId) == rewardBossTracking.end()) { + if (!rewardBossTracking.contains(monsterId)) { rewardBossTracking[monsterId] = RewardBossContributionInfo(); } @@ -4421,7 +4398,7 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } // If the damage is enough to kill the target, execute death preparation events if (realDamage >= targetHealth) { - for (CreatureEvent* creatureEvent : target->getCreatureEvents(CREATURE_EVENT_PREPAREDEATH)) { + for (const auto creatureEvent : target->getCreatureEvents(CREATURE_EVENT_PREPAREDEATH)) { if (!creatureEvent->executeOnPrepareDeath(target, attacker)) { return false; } @@ -4437,9 +4414,9 @@ bool Game::combatChangeHealth(Creature* attacker, Creature* target, CombatDamage } -bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& damage) +bool Game::combatChangeMana(const CreaturePtr& attacker, const CreaturePtr& target, CombatDamage& damage) { - Player* targetPlayer = target->getPlayer(); + const auto targetPlayer = target->getPlayer(); if (!targetPlayer) { return true; } @@ -4447,7 +4424,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& int32_t manaChange = damage.primary.value + damage.secondary.value; if (manaChange > 0) { if (attacker) { - const Player* attackerPlayer = attacker->getPlayer(); + const auto attackerPlayer = attacker->getPlayer(); if (attackerPlayer && attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(target) == SKULL_NONE) { return false; } @@ -4456,7 +4433,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& if (damage.origin != ORIGIN_NONE) { const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { - for (CreatureEvent* creatureEvent : events) { + for (const auto creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -4484,7 +4461,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& return false; } - Player* attackerPlayer; + PlayerPtr attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { @@ -4509,7 +4486,7 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& if (damage.origin != ORIGIN_NONE) { const auto& events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { - for (CreatureEvent* creatureEvent : events) { + for (const auto creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -4528,10 +4505,10 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& SpectatorVec spectators; map.getSpectators(spectators, targetPos, false, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); - Player* spectatorPlayer = static_cast(spectator); + PlayerPtr spectatorPlayer = std::static_pointer_cast(spectator); if (spectatorPlayer == attackerPlayer && attackerPlayer != targetPlayer) { message.type = MESSAGE_DAMAGE_DEALT; message.text = fmt::format("{:s} loses {:d} mana due to your attack.", target->getNameDescription(), manaLoss); @@ -4566,39 +4543,39 @@ bool Game::combatChangeMana(Creature* attacker, Creature* target, CombatDamage& return true; } -void Game::addCreatureHealth(const Creature* target) +void Game::addCreatureHealth(const CreatureConstPtr& target) { SpectatorVec spectators; map.getSpectators(spectators, target->getPosition(), true, true); addCreatureHealth(spectators, target); } -void Game::addCreatureHealth(const SpectatorVec& spectators, const Creature* target) +void Game::addCreatureHealth(const SpectatorVec& spectators, const CreatureConstPtr& target) { - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendCreatureHealth(target); } } } -void Game::addMagicEffect(const Position& pos, uint8_t effect) +void Game::addMagicEffect(const Position& pos, const uint8_t effect) { SpectatorVec spectators; map.getSpectators(spectators, pos, true, true); addMagicEffect(spectators, pos, effect); } -void Game::addMagicEffect(const SpectatorVec& spectators, const Position& pos, uint8_t effect) +void Game::addMagicEffect(const SpectatorVec& spectators, const Position& pos, const uint8_t effect) { - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendMagicEffect(pos, effect); } } } -void Game::addDistanceEffect(const Position& fromPos, const Position& toPos, uint8_t effect) +void Game::addDistanceEffect(const Position& fromPos, const Position& toPos, const uint8_t effect) { SpectatorVec spectators, toPosSpectators; map.getSpectators(spectators, fromPos, true, true); @@ -4610,8 +4587,8 @@ void Game::addDistanceEffect(const Position& fromPos, const Position& toPos, uin void Game::addDistanceEffect(const SpectatorVec& spectators, const Position& fromPos, const Position& toPos, uint8_t effect) { - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { + for (const auto spectator : spectators) { + if (const auto tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendDistanceShoot(fromPos, toPos, effect); } } @@ -4684,7 +4661,7 @@ bool Game::saveAccountStorageValues() const return transaction.commit(); } -void Game::startDecay(Item* item) +void Game::startDecay(const ItemPtr& item) { if (!item || !item->canDecay()) { return; @@ -4696,7 +4673,6 @@ void Game::startDecay(Item* item) } if (item->getDuration() > 0) { - item->incrementReferenceCounter(); item->setDecaying(DECAYING_TRUE); toDecayItems.push_front(item); } else { @@ -4704,14 +4680,12 @@ void Game::startDecay(Item* item) } } -void Game::internalDecayItem(Item* item) +void Game::internalDecayItem(const ItemPtr& item) { - const int32_t decayTo = item->getDecayTo(); - if (decayTo > 0) { + if (const int32_t decayTo = item->getDecayTo(); decayTo > 0) { startDecay(transformItem(item, decayTo)); } else { - ReturnValue ret = internalRemoveItem(item); - if (ret != RETURNVALUE_NOERROR) { + if (const ReturnValue ret = internalRemoveItem(item); ret != RETURNVALUE_NOERROR) { std::cout << "[Debug - Game::internalDecayItem] internalDecayItem failed, error code: " << static_cast(ret) << ", item id: " << item->getID() << std::endl; } } @@ -4721,20 +4695,21 @@ void Game::checkDecay() { g_scheduler.addEvent(createSchedulerTask(EVENT_DECAYINTERVAL, [=, this]() { checkDecay(); })); - size_t bucket = (lastBucket + 1) % EVENT_DECAY_BUCKETS; + const size_t bucket = (lastBucket + 1) % EVENT_DECAY_BUCKETS; - auto it = decayItems[bucket].begin(), end = decayItems[bucket].end(); + auto it = decayItems[bucket].begin(); + const auto end = decayItems[bucket].end(); while (it != end) { - Item* item = *it; + const auto item = *it; if (!item->canDecay()) { item->setDecaying(DECAYING_FALSE); - ReleaseItem(item); + // ReleaseItem(item); it = decayItems[bucket].erase(it); continue; } int32_t duration = item->getDuration(); - int32_t decreaseTime = std::min(EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS, duration); + const int32_t decreaseTime = std::min(EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS, duration); duration -= decreaseTime; item->decreaseDuration(decreaseTime); @@ -4742,13 +4717,12 @@ void Game::checkDecay() if (duration <= 0) { it = decayItems[bucket].erase(it); internalDecayItem(item); - ReleaseItem(item); + // ReleaseItem(item); } else if (duration < EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS) { it = decayItems[bucket].erase(it); - size_t newBucket = (bucket + ((duration + EVENT_DECAYINTERVAL / 2) / 1000)) % EVENT_DECAY_BUCKETS; - if (newBucket == bucket) { + if (const size_t newBucket = (bucket + ((duration + EVENT_DECAYINTERVAL / 2) / 1000)) % EVENT_DECAY_BUCKETS; newBucket == bucket) { internalDecayItem(item); - ReleaseItem(item); + // ReleaseItem(item); } else { decayItems[newBucket].push_back(item); } @@ -4770,8 +4744,8 @@ void Game::checkLight() if (previousLightLevel != lightLevel) { LightInfo lightInfo = getWorldLightInfo(); - for (const auto& it : players) { - it.second->sendWorldLight(lightInfo); + for (const auto& val : players | std::views::values) { + val->sendWorldLight(lightInfo); } } } @@ -4779,9 +4753,9 @@ void Game::checkLight() void Game::updateWorldLightLevel() { if (getWorldTime() >= GAME_SUNRISE && getWorldTime() <= GAME_DAYTIME) { - lightLevel = ((GAME_DAYTIME - GAME_SUNRISE) - (GAME_DAYTIME - getWorldTime())) * float(LIGHT_CHANGE_SUNRISE) + LIGHT_NIGHT; + lightLevel = ((GAME_DAYTIME - GAME_SUNRISE) - (GAME_DAYTIME - getWorldTime())) * static_cast(LIGHT_CHANGE_SUNRISE) + LIGHT_NIGHT; } else if (getWorldTime() >= GAME_SUNSET && getWorldTime() <= GAME_NIGHTTIME) { - lightLevel = LIGHT_DAY - ((getWorldTime() - GAME_SUNSET) * float(LIGHT_CHANGE_SUNSET)); + lightLevel = LIGHT_DAY - ((getWorldTime() - GAME_SUNSET) * static_cast(LIGHT_CHANGE_SUNSET)); } else if (getWorldTime() >= GAME_NIGHTTIME || getWorldTime() < GAME_SUNRISE) { lightLevel = LIGHT_NIGHT; } else { @@ -4792,8 +4766,8 @@ void Game::updateWorldLightLevel() void Game::updateWorldTime() { g_scheduler.addEvent(createSchedulerTask(EVENT_WORLDTIMEINTERVAL, [=, this]() { updateWorldTime(); })); - time_t osTime = time(nullptr); - tm* timeInfo = localtime(&osTime); + const time_t osTime = time(nullptr); + const auto timeInfo = localtime(&osTime); worldTime = (timeInfo->tm_sec + (timeInfo->tm_min * 60)) / 2.5f; } @@ -4822,17 +4796,7 @@ void Game::shutdown() void Game::cleanup() { //free memory - for (auto creature : ToReleaseCreatures) { - creature->decrementReferenceCounter(); - } - ToReleaseCreatures.clear(); - - for (auto item : ToReleaseItems) { - item->decrementReferenceCounter(); - } - ToReleaseItems.clear(); - - for (Item* item : toDecayItems) { + for (const auto item : toDecayItems) { const uint32_t dur = item->getDuration(); if (dur >= EVENT_DECAYINTERVAL * EVENT_DECAY_BUCKETS) { decayItems[lastBucket].push_back(item); @@ -4843,49 +4807,39 @@ void Game::cleanup() toDecayItems.clear(); } -void Game::ReleaseCreature(Creature* creature) -{ - ToReleaseCreatures.push_back(creature); -} - -void Game::ReleaseItem(Item* item) -{ - ToReleaseItems.push_back(item); -} - -void Game::broadcastMessage(const std::string& text, MessageClasses type) const +void Game::broadcastMessage(const std::string& text, const MessageClasses type) const { std::cout << "> Broadcasted message: \"" << text << "\"." << std::endl; - for (const auto& it : players) { - it.second->sendTextMessage(type, text); + for (const auto& val : players | std::views::values) { + val->sendTextMessage(type, text); } } -void Game::updateCreatureWalkthrough(const Creature* creature) +void Game::updateCreatureWalkthrough(const CreatureConstPtr& creature) { //send to clients SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); - Player* spectatorPlayer = static_cast(spectator); + const PlayerPtr spectatorPlayer = std::static_pointer_cast(spectator); spectatorPlayer->sendCreatureWalkthrough(creature, spectatorPlayer->canWalkthroughEx(creature)); } } -void Game::notifySpectators(const Creature* creature) +void Game::notifySpectators(const CreatureConstPtr& creature) { // send to clients SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendUpdateTileCreature(creature); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendUpdateTileCreature(creature); } } -void Game::updateCreatureSkull(const Creature* creature) +void Game::updateCreatureSkull(const CreatureConstPtr& creature) { if (getWorldType() != WORLD_TYPE_PVP) { return; @@ -4893,43 +4847,42 @@ void Game::updateCreatureSkull(const Creature* creature) SpectatorVec spectators; map.getSpectators(spectators, creature->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendCreatureSkull(creature); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendCreatureSkull(creature); } } -void Game::updatePlayerShield(Player* player) +void Game::updatePlayerShield(const PlayerPtr& player) { SpectatorVec spectators; map.getSpectators(spectators, player->getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendCreatureShield(player); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendCreatureShield(player); } } -void Game::updatePlayerHelpers(const Player& player) +void Game::updatePlayerHelpers(const PlayerConstPtr& player) { - uint32_t creatureId = player.getID(); - uint16_t helpers = player.getHelpers(); + uint32_t creatureId = player->getID(); + uint16_t helpers = player->getHelpers(); SpectatorVec spectators; - map.getSpectators(spectators, player.getPosition(), true, true); - for (Creature* spectator : spectators) { + map.getSpectators(spectators, player->getPosition(), true, true); + for (const auto spectator : spectators) { spectator->getPlayer()->sendCreatureHelpers(creatureId, helpers); } } -void Game::updateCreatureType(Creature* creature) +void Game::updateCreatureType(const CreaturePtr& creature) { - const Player* masterPlayer = nullptr; + PlayerPtr masterPlayer = nullptr; - uint32_t creatureId = creature->getID(); + const uint32_t creatureId = creature->getID(); CreatureType_t creatureType = creature->getType(); if (creatureType == CREATURETYPE_MONSTER) { - const Creature* master = creature->getMaster(); - if (master) { + if (const auto master = creature->getMaster()) { masterPlayer = master->getPlayer(); if (masterPlayer) { creatureType = CREATURETYPE_SUMMON_HOSTILE; @@ -4942,8 +4895,8 @@ void Game::updateCreatureType(Creature* creature) map.getSpectators(spectators, creature->getPosition(), true, true); if (creatureType == CREATURETYPE_SUMMON_HOSTILE) { - for (Creature* spectator : spectators) { - Player* player = spectator->getPlayer(); + for (const auto spectator : spectators) { + const auto player = spectator->getPlayer(); if (masterPlayer == player) { player->sendCreatureType(creatureId, CREATURETYPE_SUMMON_OWN); } else { @@ -4951,7 +4904,7 @@ void Game::updateCreatureType(Creature* creature) } } } else { - for (Creature* spectator : spectators) { + for (const auto spectator : spectators) { spectator->getPlayer()->sendCreatureType(creatureId, creatureType); } } @@ -4990,7 +4943,7 @@ void Game::checkPlayersRecord() { const size_t playersOnline = getPlayersOnline(); if (playersOnline > playersRecord) { - uint32_t previousRecord = playersRecord; + const uint32_t previousRecord = playersRecord; playersRecord = playersOnline; for (auto& it : g_globalEvents->getEventMap(GLOBALEVENT_RECORD)) { @@ -5010,26 +4963,25 @@ void Game::loadPlayersRecord() { Database& db = Database::getInstance(); - DBResult_ptr result = db.storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'players_record'"); - if (result) { + if (const DBResult_ptr result = db.storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'players_record'")) { playersRecord = result->getNumber("value"); } else { db.executeQuery("INSERT INTO `server_config` (`config`, `value`) VALUES ('players_record', '0')"); } } -void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) +void Game::playerInviteToParty(const uint32_t playerId, const uint32_t invitedId) { if (playerId == invitedId) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Player* invitedPlayer = getPlayerByID(invitedId); + auto invitedPlayer = getPlayerByID(invitedId); if (!invitedPlayer || invitedPlayer->isInviting(player)) { return; } @@ -5039,7 +4991,7 @@ void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) return; } - Party* party = player->getParty(); + auto party = player->getParty(); if (!party) { party = new Party(player); } else if (party->getLeader() != player) { @@ -5054,22 +5006,22 @@ void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) return; } - party->invitePlayer(*invitedPlayer); + party->invitePlayer(invitedPlayer); } -void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) +void Game::playerJoinParty(const uint32_t playerId, const uint32_t leaderId) { - Player* player = getPlayerByID(playerId); + auto player = getPlayerByID(playerId); if (!player) { return; } - Player* leader = getPlayerByID(leaderId); + const auto leader = getPlayerByID(leaderId); if (!leader || !leader->isInviting(player)) { return; } - Party* party = leader->getParty(); + const auto party = leader->getParty(); if (!party || party->getLeader() != leader) { return; } @@ -5079,42 +5031,42 @@ void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) return; } - party->joinParty(*player); + party->joinParty(player); } -void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) +void Game::playerRevokePartyInvitation(const uint32_t playerId, const uint32_t invitedId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Party* party = player->getParty(); + const auto party = player->getParty(); if (!party || party->getLeader() != player) { return; } - Player* invitedPlayer = getPlayerByID(invitedId); + auto invitedPlayer = getPlayerByID(invitedId); if (!invitedPlayer || !player->isInviting(invitedPlayer)) { return; } - party->revokeInvitation(*invitedPlayer); + party->revokeInvitation(invitedPlayer); } -void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) +void Game::playerPassPartyLeadership(const uint32_t playerId, const uint32_t newLeaderId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Party* party = player->getParty(); + const auto party = player->getParty(); if (!party || party->getLeader() != player) { return; } - Player* newLeader = getPlayerByID(newLeaderId); + const auto newLeader = getPlayerByID(newLeaderId); if (!newLeader || !player->isPartner(newLeader)) { return; } @@ -5122,14 +5074,14 @@ void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) party->passPartyLeadership(newLeader); } -void Game::playerLeaveParty(uint32_t playerId) +void Game::playerLeaveParty(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Party* party = player->getParty(); + const auto party = player->getParty(); if (!party || player->hasCondition(CONDITION_INFIGHT)) { return; } @@ -5137,14 +5089,14 @@ void Game::playerLeaveParty(uint32_t playerId) party->leaveParty(player); } -void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpActive) +void Game::playerEnableSharedPartyExperience(const uint32_t playerId, bool sharedExpActive) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Party* party = player->getParty(); + const auto party = player->getParty(); if (!party || (player->hasCondition(CONDITION_INFIGHT) && player->getZone() != ZONE_PROTECTION)) { return; } @@ -5152,22 +5104,21 @@ void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpAc party->setSharedExperience(player, sharedExpActive); } -void Game::sendGuildMotd(uint32_t playerId) +void Game::sendGuildMotd(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - Guild* guild = player->getGuild(); - if (guild) { + if (const auto guild = player->getGuild()) { player->sendChannelMessage("Message of the Day", guild->getMotd(), TALKTYPE_CHANNEL_R1, CHANNEL_GUILD); } } -void Game::kickPlayer(uint32_t playerId, bool displayEffect) +void Game::kickPlayer(const uint32_t playerId, const bool displayEffect) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5175,9 +5126,9 @@ void Game::kickPlayer(uint32_t playerId, bool displayEffect) player->kickPlayer(displayEffect); } -void Game::playerReportRuleViolation(uint32_t playerId, const std::string& targetName, uint8_t reportType, uint8_t reportReason, const std::string& comment, const std::string& translation) +void Game::playerReportRuleViolation(const 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); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5185,9 +5136,9 @@ void Game::playerReportRuleViolation(uint32_t playerId, const std::string& targe 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(const uint32_t playerId, const std::string& message, const Position& position, uint8_t category) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5195,25 +5146,24 @@ 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(const uint32_t playerId, const std::string& assertLine, const std::string& date, const std::string& description, const std::string& comment) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } // TODO: move debug assertions to database - FILE* file = fopen("client_assertions.txt", "a"); - if (file) { + if (const auto file = fopen("client_assertions.txt", "a")) { fprintf(file, "----- %s - %s (%s) -----\n", formatDate(time(nullptr)).c_str(), player->getName().c_str(), convertIPToString(player->getIP()).c_str()); fprintf(file, "%s\n%s\n%s\n%s\n", assertLine.c_str(), date.c_str(), description.c_str(), comment.c_str()); fclose(file); } } -void Game::playerLeaveMarket(uint32_t playerId) +void Game::playerLeaveMarket(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5221,9 +5171,9 @@ void Game::playerLeaveMarket(uint32_t playerId) player->setInMarket(false); } -void Game::playerBrowseMarket(uint32_t playerId, uint16_t spriteId) +void Game::playerBrowseMarket(const uint32_t playerId, const uint16_t spriteId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5247,9 +5197,9 @@ void Game::playerBrowseMarket(uint32_t playerId, uint16_t spriteId) player->sendMarketDetail(it.id); } -void Game::playerBrowseMarketOwnOffers(uint32_t playerId) +void Game::playerBrowseMarketOwnOffers(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5263,9 +5213,9 @@ void Game::playerBrowseMarketOwnOffers(uint32_t playerId) player->sendMarketBrowseOwnOffers(buyOffers, sellOffers); } -void Game::playerBrowseMarketOwnHistory(uint32_t playerId) +void Game::playerBrowseMarketOwnHistory(const uint32_t playerId) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5279,7 +5229,7 @@ void Game::playerBrowseMarketOwnHistory(uint32_t playerId) player->sendMarketBrowseOwnHistory(buyOffers, sellOffers); } -void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spriteId, uint16_t amount, uint32_t price, bool anonymous) +void Game::playerCreateMarketOffer(const uint32_t playerId, uint8_t type, const uint16_t spriteId, const uint16_t amount, const uint32_t price, const bool anonymous) { if (amount == 0 || amount > 64000) { return; @@ -5293,7 +5243,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spr return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5338,15 +5288,15 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spr return; } - const auto& itemList = getMarketItemList(it.wareId, amount, *player); + const auto& itemList = getMarketItemList(it.wareId, amount, player); if (itemList.empty()) { return; } if (it.stackable) { uint16_t tmpAmount = amount; - for (Item* item : itemList) { - uint16_t removeCount = std::min(tmpAmount, item->getItemCount()); + for (const auto item : itemList) { + const uint16_t removeCount = std::min(tmpAmount, item->getItemCount()); tmpAmount -= removeCount; internalRemoveItem(item, removeCount); @@ -5355,14 +5305,15 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spr } } } else { - for (Item* item : itemList) { + for (const auto item : itemList) { internalRemoveItem(item); } } const auto debitCash = std::min(player->getMoney(), fee); const auto debitBank = fee - debitCash; - removeMoney(player, debitCash); + CylinderPtr c_player = player; + removeMoney(c_player, debitCash); player->bankBalance -= debitBank; } else { uint64_t totalPrice = static_cast(price) * amount; @@ -5373,7 +5324,8 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spr const auto debitCash = std::min(player->getMoney(), totalPrice); const auto debitBank = totalPrice - debitCash; - removeMoney(player, debitCash); + CylinderPtr c_player = player; + removeMoney(c_player, debitCash); player->bankBalance -= debitBank; } @@ -5385,9 +5337,9 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t spr player->sendMarketBrowseItem(it.id, buyOffers, sellOffers); } -void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter) +void Game::playerCancelMarketOffer(const uint32_t playerId, const uint32_t timestamp, const uint16_t counter) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5414,9 +5366,9 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 uint16_t tmpAmount = offer.amount; while (tmpAmount > 0) { int32_t stackCount = std::min(100, tmpAmount); - Item* item = Item::CreateItem(it.id, stackCount); - if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(it.id, stackCount); + if (CylinderPtr inbox = player->getInbox(); internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { + item.reset(); break; } @@ -5431,9 +5383,9 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } for (uint16_t i = 0; i < offer.amount; ++i) { - Item* item = Item::CreateItem(it.id, subType); - if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(it.id, subType); + if (CylinderPtr inbox = player->getInbox(); internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { + item.reset(); break; } } @@ -5447,13 +5399,13 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 player->sendMarketEnter(); } -void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount) +void Game::playerAcceptMarketOffer(const uint32_t playerId, const uint32_t timestamp, const uint16_t counter, const uint16_t amount) { if (amount == 0 || amount > 64000) { return; } - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5484,24 +5436,24 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 uint64_t totalPrice = static_cast(offer.price) * amount; if (offer.type == MARKETACTION_BUY) { - const auto& itemList = getMarketItemList(it.wareId, amount, *player); + const auto& itemList = getMarketItemList(it.wareId, amount, player); if (itemList.empty()) { return; } - Player* buyerPlayer = getPlayerByGUID(offer.playerId); + auto buyerPlayer = getPlayerByGUID(offer.playerId); if (!buyerPlayer) { - buyerPlayer = new Player(nullptr); + buyerPlayer = std::make_shared(nullptr); if (!IOLoginData::loadPlayerById(buyerPlayer, offer.playerId)) { - delete buyerPlayer; + buyerPlayer.reset(); return; } } if (it.stackable) { uint16_t tmpAmount = amount; - for (Item* item : itemList) { - uint16_t removeCount = std::min(tmpAmount, item->getItemCount()); + for (const auto item : itemList) { + const uint16_t removeCount = std::min(tmpAmount, item->getItemCount()); tmpAmount -= removeCount; internalRemoveItem(item, removeCount); @@ -5510,7 +5462,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } } } else { - for (Item* item : itemList) { + for (const auto item : itemList) { internalRemoveItem(item); } } @@ -5521,9 +5473,10 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min(100, tmpAmount); - Item* item = Item::CreateItem(it.id, stackCount); - if (internalAddItem(buyerPlayer->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(it.id, stackCount); + CylinderPtr inbox = player->getInbox(); + if (internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { + item.reset(); break; } @@ -5538,9 +5491,10 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } for (uint16_t i = 0; i < amount; ++i) { - Item* item = Item::CreateItem(it.id, subType); - if (internalAddItem(buyerPlayer->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(it.id, subType); + CylinderPtr inbox = player->getInbox(); + if (internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { + item.reset(); break; } } @@ -5548,7 +5502,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 if (buyerPlayer->isOffline()) { IOLoginData::savePlayer(buyerPlayer); - delete buyerPlayer; + buyerPlayer.reset(); } else { buyerPlayer->onReceiveMail(); } @@ -5559,16 +5513,18 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 const auto debitCash = std::min(player->getMoney(), totalPrice); const auto debitBank = totalPrice - debitCash; - removeMoney(player, debitCash); + CylinderPtr coinholder = player; + removeMoney(coinholder, debitCash); player->bankBalance -= debitBank; if (it.stackable) { uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min(100, tmpAmount); - Item* item = Item::CreateItem(it.id, stackCount); - if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(it.id, stackCount); + CylinderPtr inbox = player->getInbox(); + if (internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { + item.reset(); break; } @@ -5583,16 +5539,16 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } for (uint16_t i = 0; i < amount; ++i) { - Item* item = Item::CreateItem(it.id, subType); - if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(it.id, subType); + CylinderPtr inbox = player->getInbox(); + if (internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { + item.reset(); break; } } } - Player* sellerPlayer = getPlayerByGUID(offer.playerId); - if (sellerPlayer) { + if (const auto sellerPlayer = getPlayerByGUID(offer.playerId)) { sellerPlayer->bankBalance += totalPrice; } else { IOLoginData::increaseBankBalance(offer.playerId, totalPrice); @@ -5620,36 +5576,36 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 player->sendMarketAcceptOffer(offer); } -void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string& buffer) +void Game::parsePlayerExtendedOpcode(const uint32_t playerId, const uint8_t opcode, const std::string& buffer) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - for (CreatureEvent* creatureEvent : player->getCreatureEvents(CREATURE_EVENT_EXTENDED_OPCODE)) { + for (const auto creatureEvent : player->getCreatureEvents(CREATURE_EVENT_EXTENDED_OPCODE)) { creatureEvent->executeExtendedOpcode(player, opcode, buffer); } } -std::vector Game::getMarketItemList(uint16_t wareId, uint16_t sufficientCount, const Player& player) +std::vector Game::getMarketItemList(const uint16_t wareId, const uint16_t sufficientCount, const PlayerConstPtr& player) { uint16_t count = 0; - std::list containers{ player.getInbox() }; + std::list containers{ player->getInbox() }; - for (const auto& chest : player.depotChests) { - if (!chest.second->empty()) { - containers.push_front(chest.second); + for (const auto& val : player->depotChests | std::views::values) { + if (!val->empty()) { + containers.push_front(val); } } - std::vector itemList; + std::vector itemList; do { - Container* container = containers.front(); + auto container = containers.front(); containers.pop_front(); - for (Item* item : container->getItemList()) { - Container* containerItem = item->getContainer(); + for (const auto item : container->getItemList()) { + const auto containerItem = item->getContainer(); if (containerItem && !containerItem->empty()) { containers.push_back(containerItem); continue; @@ -5679,9 +5635,9 @@ std::vector Game::getMarketItemList(uint16_t wareId, uint16_t sufficientC return {}; } -void Game::forceAddCondition(uint32_t creatureId, Condition* condition) +void Game::forceAddCondition(const uint32_t creatureId, Condition* condition) { - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (!creature) { delete condition; return; @@ -5690,9 +5646,9 @@ void Game::forceAddCondition(uint32_t creatureId, Condition* condition) creature->addCondition(condition, true); } -void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t type) +void Game::forceRemoveCondition(const uint32_t creatureId, ConditionType_t type) { - Creature* creature = getCreatureByID(creatureId); + const auto creature = getCreatureByID(creatureId); if (!creature) { return; } @@ -5700,7 +5656,7 @@ void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t type) creature->removeCondition(type, true); } -void Game::sendOfflineTrainingDialog(Player* player) +void Game::sendOfflineTrainingDialog(const PlayerPtr& player) const { if (!player) { return; @@ -5711,9 +5667,9 @@ void Game::sendOfflineTrainingDialog(Player* player) } } -void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice) +void Game::playerAnswerModalWindow(const uint32_t playerId, const uint32_t modalWindowId, const uint8_t button, const uint8_t choice) { - Player* player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5728,7 +5684,7 @@ void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, ui if (modalWindowId == std::numeric_limits::max()) { if (button == offlineTrainingWindow.defaultEnterButton) { if (choice == SKILL_SWORD || choice == SKILL_AXE || choice == SKILL_CLUB || choice == SKILL_DISTANCE || choice == SKILL_MAGLEVEL) { - BedItem* bedItem = player->getBedItem(); + const auto bedItem = player->getBedItem(); if (bedItem && bedItem->sleep(player)) { player->setOfflineTrainingSkill(choice); return; @@ -5746,7 +5702,7 @@ void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, ui } } -void Game::addPlayer(Player* player) +void Game::addPlayer(PlayerPtr player) { const std::string& lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames[lowercase_name] = player; @@ -5755,7 +5711,7 @@ void Game::addPlayer(Player* player) players[player->getID()] = player; } -void Game::removePlayer(Player* player) +void Game::removePlayer(const PlayerPtr& player) { const std::string& lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames.erase(lowercase_name); @@ -5764,29 +5720,29 @@ void Game::removePlayer(Player* player) players.erase(player->getID()); } -void Game::addNpc(Npc* npc) +void Game::addNpc(NpcPtr npc) { npcs[npc->getID()] = npc; } -void Game::removeNpc(Npc* npc) +void Game::removeNpc(const NpcPtr& npc) { npcs.erase(npc->getID()); } -void Game::addMonster(Monster* monster) +void Game::addMonster(MonsterPtr monster) { monsters[monster->getID()] = monster; } -void Game::removeMonster(Monster* monster) +void Game::removeMonster(const MonsterPtr& monster) { monsters.erase(monster->getID()); } -Guild* Game::getGuild(uint32_t id) const +Guild* Game::getGuild(const uint32_t id) const { - auto it = guilds.find(id); + const auto it = guilds.find(id); if (it == guilds.end()) { return nullptr; } @@ -5805,21 +5761,21 @@ void Game::removeGuild(uint32_t guildId) void Game::decreaseBrowseFieldRef(const Position& pos) { - Tile* tile = map.getTile(pos.x, pos.y, pos.z); + const auto tile = map.getTile(pos.x, pos.y, pos.z); if (!tile) { return; } auto it = browseFields.find(tile); if (it != browseFields.end()) { - it->second->decrementReferenceCounter(); + } } -void Game::internalRemoveItems(std::vector itemList, uint32_t amount, bool stackable) +void Game::internalRemoveItems(const std::vector& itemList, uint32_t amount, const bool stackable) { if (stackable) { - for (Item* item : itemList) { + for (const auto item : itemList) { if (item->getItemCount() > amount) { internalRemoveItem(item, amount); break; @@ -5829,61 +5785,59 @@ void Game::internalRemoveItems(std::vector itemList, uint32_t amount, boo } } } else { - for (Item* item : itemList) { + for (const auto item : itemList) { internalRemoveItem(item); } } } -BedItem* Game::getBedBySleeper(uint32_t guid) const +BedItemPtr Game::getBedBySleeper(const uint32_t guid) const { - auto it = bedSleepersMap.find(guid); + const auto it = bedSleepersMap.find(guid); if (it == bedSleepersMap.end()) { return nullptr; } return it->second; } -void Game::setBedSleeper(BedItem* bed, uint32_t guid) +void Game::setBedSleeper(const BedItemPtr& bed, const uint32_t guid) { bedSleepersMap[guid] = bed; } -void Game::removeBedSleeper(uint32_t guid) +void Game::removeBedSleeper(const uint32_t guid) { - auto it = bedSleepersMap.find(guid); - if (it != bedSleepersMap.end()) { + if (auto it = bedSleepersMap.find(guid); it != bedSleepersMap.end()) { bedSleepersMap.erase(it); } } -Item* Game::getUniqueItem(uint16_t uniqueId) +ItemPtr Game::getUniqueItem(const uint16_t uniqueId) { - auto it = uniqueItems.find(uniqueId); + const auto it = uniqueItems.find(uniqueId); if (it == uniqueItems.end()) { return nullptr; } return it->second; } -bool Game::addUniqueItem(uint16_t uniqueId, Item* item) +bool Game::addUniqueItem(const uint16_t uniqueId, const ItemPtr& item) { - auto result = uniqueItems.emplace(uniqueId, item); + const auto result = uniqueItems.emplace(uniqueId, item); if (!result.second) { std::cout << "Duplicate unique id: " << uniqueId << std::endl; } return result.second; } -void Game::removeUniqueItem(uint16_t uniqueId) +void Game::removeUniqueItem(const uint16_t uniqueId) { - auto it = uniqueItems.find(uniqueId); - if (it != uniqueItems.end()) { + if (auto it = uniqueItems.find(uniqueId); it != uniqueItems.end()) { uniqueItems.erase(it); } } -bool Game::reload(ReloadTypes_t reloadType) +bool Game::reload(const ReloadTypes_t reloadType) { switch (reloadType) { case RELOAD_TYPE_ACTIONS: return g_actions->reload(); @@ -5992,7 +5946,7 @@ bool Game::reload(ReloadTypes_t reloadType) return true; } -void Game::resetDamageTracking(uint32_t monsterId) +void Game::resetDamageTracking(const uint32_t monsterId) { rewardBossTracking.erase(monsterId); } diff --git a/src/game.h b/src/game.h index 820f7523..4669a68d 100644 --- a/src/game.h +++ b/src/game.h @@ -110,12 +110,12 @@ class Game return worldType; } - Cylinder* internalGetCylinder(Player* player, const Position& pos) const; - Thing* internalGetThing(Player* player, const Position& pos, int32_t index, - uint32_t spriteId, stackPosType_t type) const; - static void internalGetPosition(Item* item, Position& pos, uint8_t& stackpos); + CylinderPtr internalGetCylinder(const PlayerPtr& player, const Position& pos); + ThingPtr internalGetThing(const PlayerPtr& player, const Position& pos, int32_t index, + uint32_t spriteId, stackPosType_t type); + static void internalGetPosition(const ItemPtr& item, Position& pos, uint8_t& stackpos); - static std::string getTradeErrorDescription(ReturnValue ret, Item* item); + static std::string getTradeErrorDescription(ReturnValue ret, const ItemPtr& item); // Struct to store damage info for a rewardboss struct PlayerScoreInfo { @@ -139,70 +139,69 @@ class Game * \param id is the unique creature id to get a creature pointer to * \returns A Creature pointer to the creature */ - Creature* getCreatureByID(uint32_t id); + CreaturePtr getCreatureByID(uint32_t id); /** * Returns a monster based on the unique creature identifier * \param id is the unique monster id to get a monster pointer to * \returns A Monster pointer to the monster */ - Monster* getMonsterByID(uint32_t id); + MonsterPtr getMonsterByID(uint32_t id); /** * Returns an npc based on the unique creature identifier * \param id is the unique npc id to get a npc pointer to * \returns A NPC pointer to the npc */ - Npc* getNpcByID(uint32_t id); + NpcPtr getNpcByID(uint32_t id); /** * Returns a player based on the unique creature identifier * \param id is the unique player id to get a player pointer to * \returns A Pointer to the player */ - Player* getPlayerByID(uint32_t id); + PlayerPtr getPlayerByID(uint32_t id); /** * Returns a creature based on a string name identifier * \param s is the name identifier * \returns A Pointer to the creature */ - Creature* getCreatureByName(const std::string& s); + CreaturePtr getCreatureByName(const std::string& s); /** * Returns a npc based on a string name identifier * \param s is the name identifier * \returns A Pointer to the npc */ - Npc* getNpcByName(const std::string& s); + NpcPtr getNpcByName(const std::string& s) const; /** * Returns a player based on a string name identifier * \param s is the name identifier * \returns A Pointer to the player */ - Player* getPlayerByName(const std::string& s); + PlayerPtr getPlayerByName(const std::string& s); /** * Returns a player based on guid * \returns A Pointer to the player */ - Player* getPlayerByGUID(const uint32_t& guid); + PlayerPtr getPlayerByGUID(const uint32_t& guid); /** * Returns a player based on a string name identifier, with support for the "~" wildcard. * \param s is the name identifier, with or without wildcard - * \param player will point to the found player (if any) * \return "RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE" or "RETURNVALUE_NAMEISTOOAMBIGIOUS" */ - ReturnValue getPlayerByNameWildcard(const std::string& s, Player*& player); + ReturnValue getPlayerByNameWildcard(const std::string& s); /** * Returns a player based on an account number identifier * \param acc is the account identifier * \returns A Pointer to the player */ - Player* getPlayerByAccount(uint32_t acc); + PlayerPtr getPlayerByAccount(uint32_t acc); /** * Place Creature on the map without sending out events to the surrounding. @@ -211,7 +210,7 @@ class Game * \param extendedPos If true, the creature will in first-hand be placed 2 tiles away * \param forced If true, placing the creature will not fail because of obstacles (creatures/items) */ - bool internalPlaceCreature(Creature* creature, const Position& pos, bool extendedPos = false, bool forced = false); + bool internalPlaceCreature(CreaturePtr creature, const Position& pos, bool extendedPos = false, bool forced = false); /** * Place Creature on the map. @@ -221,7 +220,7 @@ class Game * \param force If true, placing the creature will not fail because of obstacles (creatures/items) * \param MagicEffect the magic effect that appears with creature when placed. */ - bool placeCreature(Creature* creature, const Position& pos, bool extendedPos = false, bool forced = false, MagicEffectClasses magicEffect = CONST_ME_TELEPORT); + bool placeCreature(CreaturePtr creature, const Position& pos, bool extendedPos = false, bool forced = false, MagicEffectClasses magicEffect = CONST_ME_TELEPORT); @@ -230,21 +229,24 @@ class Game * Removes the Creature from the map * \param c Creature to remove */ - bool removeCreature(Creature* creature, bool isLogout = true); + bool removeCreature(CreaturePtr creature, bool isLogout = true); void executeDeath(uint32_t creatureId); - void addCreatureCheck(Creature* creature); - static void removeCreatureCheck(Creature* creature); + void addCreatureCheck(const CreaturePtr& creature); + static void removeCreatureCheck(const CreaturePtr& creature); size_t getPlayersOnline() const { return players.size(); } + size_t getMonstersOnline() const { return monsters.size(); } + size_t getNpcsOnline() const { return npcs.size(); } + uint32_t getPlayersRecord() const { return playersRecord; } @@ -252,6 +254,7 @@ class Game LightInfo getWorldLightInfo() const { return {lightLevel, lightColor}; } + void setWorldLightInfo(LightInfo lightInfo) { lightLevel = lightInfo.level; lightColor = lightInfo.color; @@ -259,21 +262,23 @@ class Game it.second->sendWorldLight(lightInfo); } } + void updateWorldLightLevel(); - ReturnValue internalMoveCreature(Creature* creature, Direction direction, uint32_t flags = 0); - ReturnValue internalMoveCreature(Creature& creature, Tile& toTile, uint32_t flags = 0); + ReturnValue internalMoveCreature(CreaturePtr creature, Direction direction, uint32_t flags = 0); + ReturnValue internalMoveCreature(CreaturePtr creature, TilePtr toTile, uint32_t flags = 0); - ReturnValue internalMoveItem(Cylinder* fromCylinder, Cylinder* toCylinder, int32_t index, - Item* item, uint32_t count, Item** _moveItem, uint32_t flags = 0, Creature* actor = nullptr, Item* tradeItem = nullptr, const Position* fromPos = nullptr, const Position* toPos = nullptr); + ReturnValue internalMoveItem(CylinderPtr& fromCylinder, CylinderPtr& toCylinder, int32_t index, + ItemPtr item, uint32_t count, ItemPtr* _moveItem, uint32_t flags = 0, const std::optional& actor = std::nullopt, const std::optional& tradeItem = std::nullopt, const Position* fromPos = nullptr, const Position* toPos = nullptr); + // another spot to use a ref wrapper and possibly optional for ItemPtr* above - ReturnValue internalAddItem(Cylinder* toCylinder, Item* item, int32_t index = INDEX_WHEREEVER, + ReturnValue internalAddItem(CylinderPtr& toCylinder, ItemPtr item, int32_t index = INDEX_WHEREEVER, uint32_t flags = 0, bool test = false); - ReturnValue internalAddItem(Cylinder* toCylinder, Item* item, int32_t index, + ReturnValue internalAddItem(CylinderPtr& toCylinder, ItemPtr& 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 internalRemoveItem(ItemPtr 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(const PlayerPtr& player, ItemPtr item, bool dropOnMap = true, slots_t slot = CONST_SLOT_WHEREEVER); /** * Find an item of a certain type @@ -284,7 +289,7 @@ class Game * \param depthSearch if true it will check child containers aswell * \returns A pointer to the item to an item and nullptr if not found */ - Item* findItemOfType(Cylinder* cylinder, uint16_t itemId, + ItemPtr findItemOfType(const CylinderPtr& cylinder, uint16_t itemId, bool depthSearch = true, int32_t subType = -1) const; /** @@ -294,7 +299,7 @@ class Game * \param flags optional flags to modify the default behavior * \returns true if the removal was successful */ - bool removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags = 0); + bool removeMoney(CylinderPtr& cylinder, uint64_t money, uint32_t flags = 0); /** * Add item(s) with monetary value @@ -302,7 +307,7 @@ class Game * \param money the amount to give * \param flags optional flags to modify default behavior */ - void addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags = 0); + void addMoney( CylinderPtr& cylinder, uint64_t money, uint32_t flags = 0); /** * Transform one item to another type/count @@ -311,7 +316,7 @@ class Game * \param newCount is the new count value, use default value (-1) to not change it * \returns true if the transformation was successful */ - Item* transformItem(Item* item, uint16_t newId, int32_t newCount = -1); + ItemPtr transformItem(const ItemPtr& item, uint16_t newId, int32_t newCount = -1); /** * Teleports an object to another position @@ -321,14 +326,14 @@ class Game * \param flags optional flags to modify default behavior * \returns true if the teleportation was successful */ - ReturnValue internalTeleport(Thing* thing, const Position& newPos, bool pushMove = true, uint32_t flags = 0); + ReturnValue internalTeleport(const ThingPtr& thing, const Position& newPos, bool pushMove = true, uint32_t flags = 0); /** * Turn a creature to a different direction. * \param creature Creature to change the direction * \param dir Direction to turn to */ - bool internalCreatureTurn(Creature* creature, Direction dir); + bool internalCreatureTurn(const CreaturePtr& creature, Direction dir); /** * Creature wants to say something. @@ -336,7 +341,7 @@ class Game * \param type Type of message * \param text The text to say */ - bool internalCreatureSay(Creature* creature, SpeakClasses type, const std::string& text, + bool internalCreatureSay(const CreaturePtr& creature, SpeakClasses type, const std::string& text, bool ghostMode, SpectatorVec* spectatorsPtr = nullptr, const Position* pos = nullptr, bool echo = false); void loadPlayersRecord(); @@ -349,19 +354,19 @@ class Game void playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice); void playerReportRuleViolation(uint32_t playerId, const std::string& targetName, uint8_t reportType, uint8_t reportReason, const std::string& comment, const std::string& translation); - bool internalStartTrade(Player* player, Player* tradePartner, Item* tradeItem); - void internalCloseTrade(Player* player, bool sendCancel = true); - bool playerBroadcastMessage(Player* player, const std::string& text) const; + bool internalStartTrade(const PlayerPtr& player, const PlayerPtr& tradePartner, const ItemPtr& tradeItem); + void internalCloseTrade(const PlayerPtr& player, bool sendCancel = true); + bool playerBroadcastMessage(const PlayerPtr& player, const std::string& text) const; void broadcastMessage(const std::string& text, MessageClasses type) const; //Implementation of player invoked events void playerMoveThing(uint32_t playerId, const Position& fromPos, uint16_t spriteId, 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* player, Creature* movingCreature, const Position& movingCreatureOrigPos, Tile* toTile); + void playerMoveCreature(PlayerPtr& player, CreaturePtr& movingCreature, const Position& movingCreatureOrigPos, TilePtr& toTile); void playerMoveItemByPlayerID(uint32_t playerId, const Position& fromPos, uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count); - void playerMoveItem(Player* player, const Position& fromPos, - uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count, Item* item, Cylinder* toCylinder); + void playerMoveItem(const PlayerPtr& player, const Position& fromPos, + uint16_t spriteId, uint8_t fromStackPos, const Position& toPos, uint8_t count, ItemPtr& item, CylinderPtr& toCylinder); void playerEquipItem(uint32_t playerId, uint16_t spriteId); void playerMove(uint32_t playerId, Direction direction); void playerCreatePrivateChannel(uint32_t playerId); @@ -433,27 +438,25 @@ class Game void parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string& buffer); - std::vector getMarketItemList(uint16_t wareId, uint16_t sufficientCount, const Player& player); + std::vector getMarketItemList(uint16_t wareId, uint16_t sufficientCount, const PlayerConstPtr& player); void cleanup(); void shutdown(); - void ReleaseCreature(Creature* creature); - void ReleaseItem(Item* item); bool canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight = true, bool sameFloor = false, - int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY) const; - bool isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor = false) const; - - void changeSpeed(Creature* creature, int32_t varSpeedDelta); - void internalCreatureChangeOutfit(Creature* creature, const Outfit_t& outfit); - void internalCreatureChangeVisible(Creature* creature, bool visible); - void changeLight(const Creature* creature); - void updateCreatureSkull(const Creature* creature); - void updatePlayerShield(Player* player); - void updatePlayerHelpers(const Player& player); - void updateCreatureType(Creature* creature); - void updateCreatureWalkthrough(const Creature* creature); - void notifySpectators(const Creature* creature); + int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY); + bool isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor = false); + + void changeSpeed(const CreaturePtr& creature, int32_t varSpeedDelta); + void internalCreatureChangeOutfit(const CreaturePtr& creature, const Outfit_t& outfit); + void internalCreatureChangeVisible(const CreaturePtr& creature, bool visible); + void changeLight(const CreatureConstPtr& creature); + void updateCreatureSkull(const CreatureConstPtr& creature); + void updatePlayerShield(const PlayerPtr& player); + void updatePlayerHelpers(const PlayerConstPtr& player); + void updateCreatureType(const CreaturePtr& creature); + void updateCreatureWalkthrough(const CreatureConstPtr& creature); + void notifySpectators(const CreatureConstPtr& creature); GameState_t getGameState() const; void setGameState(GameState_t newState); @@ -466,16 +469,16 @@ class Game void checkCreatures(size_t index); void checkLight(); - bool combatBlockHit(CombatDamage& damage, Creature* attacker, Creature* target, bool checkDefense, bool checkArmor, bool field, bool ignoreResistances = false); + bool combatBlockHit(CombatDamage& damage, const CreaturePtr& attacker, const CreaturePtr& target, bool checkDefense, bool checkArmor, bool field, bool ignoreResistances = false); - void combatGetTypeInfo(CombatType_t combatType, Creature* target, TextColor_t& color, uint8_t& effect); + void combatGetTypeInfo(CombatType_t combatType, const CreaturePtr& target, TextColor_t& color, uint8_t& effect); - bool combatChangeHealth(Creature* attacker, Creature* target, CombatDamage& damage); - bool combatChangeMana(Creature* attacker, Creature* target, CombatDamage& damage); + bool combatChangeHealth(const CreaturePtr& attacker, const CreaturePtr& target, CombatDamage& damage); + bool combatChangeMana(const CreaturePtr& attacker, const CreaturePtr& target, CombatDamage& damage); //animation help functions - void addCreatureHealth(const Creature* target); - static void addCreatureHealth(const SpectatorVec& spectators, const Creature* target); + void addCreatureHealth(const CreatureConstPtr& target); + static void addCreatureHealth(const SpectatorVec& spectators, const CreatureConstPtr& target); void addMagicEffect(const Position& pos, uint8_t effect); static void addMagicEffect(const SpectatorVec& spectators, const Position& pos, uint8_t effect); void addDistanceEffect(const Position& fromPos, const Position& toPos, uint8_t effect); @@ -486,9 +489,9 @@ class Game void loadAccountStorageValues(); bool saveAccountStorageValues() const; - void startDecay(Item* item); + void startDecay(const ItemPtr& item); - int16_t getWorldTime() { return worldTime; } + int16_t getWorldTime() const { return worldTime; } void updateWorldTime(); void loadMotdNum(); @@ -497,36 +500,36 @@ class Game uint32_t getMotdNum() const { return motdNum; } void incrementMotdNum() { motdNum++; } - void sendOfflineTrainingDialog(Player* player); + void sendOfflineTrainingDialog(const PlayerPtr& player) const; - const std::unordered_map& getPlayers() const { return players; } - const std::map& getNpcs() const { return npcs; } - const std::map& getMonsters() const { return monsters; } + const std::unordered_map& getPlayers() const { return players; } + const std::map& getNpcs() const { return npcs; } + const std::map& getMonsters() const { return monsters; } - void addPlayer(Player* player); - void removePlayer(Player* player); + void addPlayer(PlayerPtr player); + void removePlayer(const PlayerPtr& player); - void addNpc(Npc* npc); - void removeNpc(Npc* npc); + void addNpc(NpcPtr npc); + void removeNpc(const NpcPtr& npc); - void addMonster(Monster* monster); - void removeMonster(Monster* monster); + void addMonster(MonsterPtr monster); + void removeMonster(const MonsterPtr& monster); Guild* getGuild(uint32_t id) const; void addGuild(Guild* guild); void removeGuild(uint32_t guildId); void decreaseBrowseFieldRef(const Position& pos); - std::unordered_map browseFields; + std::unordered_map browseFields; - void internalRemoveItems(std::vector itemList, uint32_t amount, bool stackable); + void internalRemoveItems(const std::vector& itemList, uint32_t amount, bool stackable); - BedItem* getBedBySleeper(uint32_t guid) const; - void setBedSleeper(BedItem* bed, uint32_t guid); + BedItemPtr getBedBySleeper(uint32_t guid) const; + void setBedSleeper(const BedItemPtr& bed, uint32_t guid); void removeBedSleeper(uint32_t guid); - Item* getUniqueItem(uint16_t uniqueId); - bool addUniqueItem(uint16_t uniqueId, Item* item); + ItemPtr getUniqueItem(uint16_t uniqueId); + bool addUniqueItem(uint16_t uniqueId, const ItemPtr& item); void removeUniqueItem(uint16_t uniqueId); bool reload(ReloadTypes_t reloadType); @@ -537,63 +540,67 @@ class Game Raids raids; Quests quests; - std::forward_list toDecayItems; + std::forward_list toDecayItems; - std::unordered_set getTilesToClean() const { + std::unordered_set getTilesToClean() const { return tilesToClean; } - bool isTileInCleanList(Tile* tile) { - return tilesToClean.find(tile) != tilesToClean.end(); + + bool isTileInCleanList(const TilePtr& tile) const { + return tilesToClean.contains(tile); } - void addTileToClean(Tile* tile) { + + void addTileToClean(TilePtr tile) { tilesToClean.emplace(tile); } - void removeTileToClean(Tile* tile) { + + void removeTileToClean(const TilePtr& tile) { tilesToClean.erase(tile); } + void clearTilesToClean() { tilesToClean.clear(); } + CURL* curl; private: - 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(const PlayerPtr& player, SpeakClasses type, const std::string& text); + void playerWhisper(const PlayerPtr& player, const std::string& text); + bool playerYell(const PlayerPtr& player, const std::string& text); + bool playerSpeakTo(const PlayerPtr& player, SpeakClasses type, const std::string& receiver, const std::string& text); + void playerSpeakToNpc(const PlayerPtr& player, const std::string& text); void checkDecay(); - void internalDecayItem(Item* item); + void internalDecayItem(const ItemPtr& item); - std::unordered_map players; - std::unordered_map mappedPlayerNames; - std::unordered_map mappedPlayerGuids; + std::unordered_map players; + std::unordered_map mappedPlayerNames; + std::unordered_map mappedPlayerGuids; std::unordered_map guilds; - std::unordered_map uniqueItems; + std::vector loaded_tiles; + std::vector loaded_tile_items; + std::unordered_map uniqueItems; std::map stages; std::unordered_map> accountStorageMap; - std::list decayItems[EVENT_DECAY_BUCKETS]; - std::list checkCreatureLists[EVENT_CREATURECOUNT]; - - std::vector ToReleaseCreatures; - std::vector ToReleaseItems; - + std::list decayItems[EVENT_DECAY_BUCKETS]; + std::list checkCreatureLists[EVENT_CREATURECOUNT]; + size_t lastBucket = 0; WildcardTreeNode wildcardTree { false }; - std::map npcs; - std::map monsters; + std::map npcs; + std::map monsters; //list of items that are in trading state, mapped to the player - std::map tradeItems; + std::map tradeItems; - std::map bedSleepersMap; + std::map bedSleepersMap; - std::unordered_set tilesToClean; + std::unordered_set tilesToClean; ModalWindow offlineTrainingWindow { std::numeric_limits::max(), "Choose a Skill", "Please choose a skill:" }; diff --git a/src/globalevent.cpp b/src/globalevent.cpp index 3e4e5246..bd2078e2 100644 --- a/src/globalevent.cpp +++ b/src/globalevent.cpp @@ -327,7 +327,7 @@ std::string_view GlobalEvent::getScriptEventName() const } } -bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) +bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) const { //onRecord(current, old) if (!scriptInterface->reserveScriptEnv()) { diff --git a/src/globalevent.h b/src/globalevent.h index b65a71de..74484cef 100644 --- a/src/globalevent.h +++ b/src/globalevent.h @@ -53,6 +53,7 @@ class GlobalEvents final : public BaseEvents LuaScriptInterface& getScriptInterface() override { return scriptInterface; } + LuaScriptInterface scriptInterface; GlobalEventMap thinkMap, serverMap, timerMap; @@ -66,12 +67,13 @@ class GlobalEvent final : public Event bool configureEvent(const pugi::xml_node& node) override; - bool executeRecord(uint32_t current, uint32_t old); + bool executeRecord(uint32_t current, uint32_t old) const; bool executeEvent() const; GlobalEvent_t getEventType() const { return eventType; } + void setEventType(GlobalEvent_t type) { eventType = type; } @@ -79,13 +81,15 @@ class GlobalEvent final : public Event const std::string& getName() const { return name; } - void setName(std::string eventName) { + + void setName(const std::string& eventName) { name = eventName; } uint32_t getInterval() const { return interval; } + void setInterval(uint32_t eventInterval) { interval |= eventInterval; } @@ -93,6 +97,7 @@ class GlobalEvent final : public Event int64_t getNextExecution() const { return nextExecution; } + void setNextExecution(int64_t time) { nextExecution = time; } diff --git a/src/guild.cpp b/src/guild.cpp index 011c32ab..782ff4b8 100644 --- a/src/guild.cpp +++ b/src/guild.cpp @@ -9,21 +9,21 @@ extern Game g_game; -void Guild::addMember(Player* player) +void Guild::addMember(const PlayerPtr& player) { membersOnline.push_back(player); - for (Player* member : membersOnline) { - g_game.updatePlayerHelpers(*member); + for (const auto member : membersOnline) { + g_game.updatePlayerHelpers(member); } } -void Guild::removeMember(Player* player) +void Guild::removeMember(const PlayerPtr& player) { membersOnline.remove(player); - for (Player* member : membersOnline) { - g_game.updatePlayerHelpers(*member); + for (const auto member : membersOnline) { + g_game.updatePlayerHelpers(member); } - g_game.updatePlayerHelpers(*player); + g_game.updatePlayerHelpers(player); if (membersOnline.empty()) { g_game.removeGuild(id); @@ -31,7 +31,7 @@ void Guild::removeMember(Player* player) } } -GuildRank_ptr Guild::getRankById(uint32_t rankId) +GuildRank_ptr Guild::getRankById(const uint32_t rankId) const { for (auto rank : ranks) { if (rank->id == rankId) { diff --git a/src/guild.h b/src/guild.h index 57b76d2a..44a26fc6 100644 --- a/src/guild.h +++ b/src/guild.h @@ -3,6 +3,7 @@ #ifndef FS_GUILD_H #define FS_GUILD_H +#include "creature.h" class Player; @@ -11,7 +12,7 @@ struct GuildRank { std::string name; uint8_t level; - GuildRank(uint32_t id, std::string_view name, uint8_t level) : id{ id }, name{ name }, level{ level } {} + GuildRank(const uint32_t id, const std::string_view name, const uint8_t level) : id{ id }, name{ name }, level{ level } {} }; using GuildRank_ptr = std::shared_ptr; @@ -19,44 +20,51 @@ using GuildRank_ptr = std::shared_ptr; class Guild { public: - Guild(uint32_t id, std::string_view name) : name{ name }, id{ id } {} + Guild(const uint32_t id, const std::string_view name) : name{ name }, id{ id } {} - void addMember(Player* player); - void removeMember(Player* player); + void addMember(const PlayerPtr& player); + void removeMember(const PlayerPtr& player); uint32_t getId() const { return id; } + const std::string& getName() const { return name; } - const std::list& getMembersOnline() const { + + const std::list& getMembersOnline() const { return membersOnline; } + uint32_t getMemberCount() const { return memberCount; } - void setMemberCount(uint32_t count) { + + void setMemberCount(const uint32_t count) { memberCount = count; } const std::vector& getRanks() const { return ranks; } - GuildRank_ptr getRankById(uint32_t rankId); + + GuildRank_ptr getRankById(uint32_t rankId) const; GuildRank_ptr getRankByName(const std::string& name) const; GuildRank_ptr getRankByLevel(uint8_t level) const; + void addRank(uint32_t rankId, std::string_view rankName, uint8_t level); const std::string& getMotd() const { return motd; } + void setMotd(const std::string& motd) { this->motd = motd; } private: - std::list membersOnline; + std::list membersOnline; std::vector ranks; std::string name; std::string motd; diff --git a/src/house.cpp b/src/house.cpp index 37a55b97..f5fb7b64 100644 --- a/src/house.cpp +++ b/src/house.cpp @@ -16,15 +16,15 @@ extern ConfigManager g_config; extern Game g_game; -House::House(uint32_t houseId) : id(houseId) {} +House::House(const uint32_t houseId) : id(houseId) {} -void House::addTile(HouseTile* tile) +void House::addTile(const HouseTilePtr& 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*/, const PlayerPtr& player) { if (updateDatabase && owner != guid) { Database& db = Database::getInstance(); @@ -45,8 +45,8 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play transferToDepot(); } - for (HouseTile* tile : houseTiles) { - if (const CreatureVector* creatures = tile->getCreatures()) { + for (const auto tile : houseTiles) { + if (const auto creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { kickPlayer(nullptr, (*creatures)[i]->getPlayer()); } @@ -54,7 +54,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play } // Remove players from beds - for (BedItem* bed : bedsList) { + for (const auto bed : bedsList) { if (bed->getSleeper() != 0) { bed->wakeUp(nullptr); } @@ -66,7 +66,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play setAccessList(SUBOWNER_LIST, ""); setAccessList(GUEST_LIST, ""); - for (Door* door : doorSet) { + for (const auto door : doorSet) { door->setAccessList(""); } } else { @@ -90,8 +90,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase/* = true*/, Player* play rentWarnings = 0; if (guid != 0) { - std::string name = IOLoginData::getNameByGuid(guid); - if (!name.empty()) { + if (const std::string name = IOLoginData::getNameByGuid(guid); !name.empty()) { owner = guid; ownerName = name; ownerAccountId = IOLoginData::getAccountIdByPlayerName(name); @@ -109,7 +108,7 @@ void House::updateDoorDescription() const } } -AccessHouseLevel_t House::getHouseAccessLevel(const Player* player) const +AccessHouseLevel_t House::getHouseAccessLevel(const PlayerConstPtr& player) const { if (!player) { return HOUSE_OWNER; @@ -140,13 +139,13 @@ AccessHouseLevel_t House::getHouseAccessLevel(const Player* player) const return HOUSE_NOT_INVITED; } -bool House::kickPlayer(Player* player, Player* target) +bool House::kickPlayer(const PlayerPtr& player, const PlayerPtr& target) { if (!target) { return false; } - HouseTile* houseTile = dynamic_cast(target->getTile()); + HouseTilePtr houseTile = std::dynamic_pointer_cast(target->getTile()); if (!houseTile || houseTile->getHouse() != this) { return false; } @@ -163,15 +162,14 @@ bool House::kickPlayer(Player* player, Player* target) return true; } -void House::setAccessList(uint32_t listId, std::string_view textlist) +void House::setAccessList(const uint32_t listId, const std::string_view textlist) { if (listId == GUEST_LIST) { guestList.parseList(textlist); } else if (listId == SUBOWNER_LIST) { subOwnerList.parseList(textlist); } else { - Door* door = getDoorByNumber(listId); - if (door) { + if (const auto door = getDoorByNumber(listId)) { door->setAccessList(textlist); } @@ -180,10 +178,10 @@ void House::setAccessList(uint32_t listId, std::string_view textlist) } //kick uninvited players - for (HouseTile* tile : houseTiles) { - if (CreatureVector* creatures = tile->getCreatures()) { + for (const auto tile : houseTiles) { + if (const auto creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { - Player* player = (*creatures)[i]->getPlayer(); + const auto player = (*creatures)[i]->getPlayer(); if (player && !isInvited(player)) { kickPlayer(nullptr, player); } @@ -198,37 +196,35 @@ bool House::transferToDepot() const return false; } - Player* player = g_game.getPlayerByGUID(owner); - if (player) { + if (const auto player = g_game.getPlayerByGUID(owner)) { transferToDepot(player); } else { - Player tmpPlayer(nullptr); - if (!IOLoginData::loadPlayerById(&tmpPlayer, owner)) { + const PlayerPtr tmpPlayer = std::make_shared(nullptr); + if (!IOLoginData::loadPlayerById(tmpPlayer, owner)) { return false; } - transferToDepot(&tmpPlayer); - IOLoginData::savePlayer(&tmpPlayer); + transferToDepot(tmpPlayer); + IOLoginData::savePlayer(tmpPlayer); } return true; } -bool House::transferToDepot(Player* player) const +bool House::transferToDepot(const PlayerPtr& player) const { if (townId == 0 || owner == 0) { return false; } ItemList moveItemList; - for (HouseTile* tile : houseTiles) { - if (const TileItemVector* items = tile->getItemList()) { - for (Item* item : *items) { + for (const auto tile : houseTiles) { + if (const auto items = tile->getItemList()) { + for (const auto item : *items) { if (item->isPickupable()) { moveItemList.push_back(item); } else { - Container* container = item->getContainer(); - if (container) { - for (Item* containerItem : container->getItemList()) { + if (const auto container = item->getContainer()) { + for (const auto containerItem : container->getItemList()) { moveItemList.push_back(containerItem); } } @@ -236,14 +232,16 @@ bool House::transferToDepot(Player* player) const } } } - - for (Item* item : moveItemList) { - g_game.internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT); + + CylinderPtr inbox = player->getInbox(); + for (const auto item : moveItemList) { + CylinderPtr parent = item->getParent(); + g_game.internalMoveItem(parent, inbox, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT); } return true; } -bool House::getAccessList(uint32_t listId, std::string& list) const +bool House::getAccessList(const uint32_t listId, std::string& list) const { if (listId == GUEST_LIST) { guestList.getList(list); @@ -253,7 +251,7 @@ bool House::getAccessList(uint32_t listId, std::string& list) const return true; } - Door* door = getDoorByNumber(listId); + const auto door = getDoorByNumber(listId); if (!door) { return false; } @@ -261,37 +259,34 @@ bool House::getAccessList(uint32_t listId, std::string& list) const return door->getAccessList(list); } -bool House::isInvited(const Player* player) const +bool House::isInvited(const PlayerConstPtr& player) const { return getHouseAccessLevel(player) != HOUSE_NOT_INVITED; } -void House::addDoor(Door* door) +void House::addDoor(const DoorPtr& door) { - door->incrementReferenceCounter(); doorSet.insert(door); door->setHouse(this); updateDoorDescription(); } -void House::removeDoor(Door* door) +void House::removeDoor(const DoorPtr& door) { - auto it = doorSet.find(door); - if (it != doorSet.end()) { - door->decrementReferenceCounter(); + if (const auto it = doorSet.find(door); it != doorSet.end()) { doorSet.erase(it); } } -void House::addBed(BedItem* bed) +void House::addBed(const BedItemPtr& bed) { bedsList.push_back(bed); bed->setHouse(this); } -Door* House::getDoorByNumber(uint32_t doorId) const +DoorPtr House::getDoorByNumber(const uint32_t doorId) const { - for (Door* door : doorSet) { + for (const auto door : doorSet) { if (door->getDoorId() == doorId) { return door; } @@ -299,9 +294,9 @@ Door* House::getDoorByNumber(uint32_t doorId) const return nullptr; } -Door* House::getDoorByPosition(const Position& pos) +DoorPtr House::getDoorByPosition(const Position& pos) { - for (Door* door : doorSet) { + for (const auto door : doorSet) { if (door->getPosition() == pos) { return door; } @@ -309,7 +304,7 @@ Door* House::getDoorByPosition(const Position& pos) return nullptr; } -bool House::canEditAccessList(uint32_t listId, const Player* player) +bool House::canEditAccessList(const uint32_t listId, const PlayerConstPtr& player) const { switch (getHouseAccessLevel(player)) { case HOUSE_OWNER: @@ -323,13 +318,13 @@ bool House::canEditAccessList(uint32_t listId, const Player* player) } } -HouseTransferItem* House::getTransferItem() +HouseTransferItemPtr House::getTransferItem() { if (transferItem != nullptr) { return nullptr; } - transfer_container.setParent(nullptr); + transfer_container.clearParent(); transferItem = HouseTransferItem::createHouseTransferItem(this); transfer_container.addThing(transferItem); return transferItem; @@ -338,33 +333,32 @@ HouseTransferItem* House::getTransferItem() void House::resetTransferItem() { if (transferItem) { - Item* tmpItem = transferItem; + ItemPtr tmpItem = transferItem; transferItem = nullptr; - transfer_container.setParent(nullptr); + transfer_container.clearParent(); transfer_container.removeThing(tmpItem, tmpItem->getItemCount()); - g_game.ReleaseItem(tmpItem); + // g_game.ReleaseItem(tmpItem); } } -HouseTransferItem* HouseTransferItem::createHouseTransferItem(House* house) +HouseTransferItemPtr HouseTransferItem::createHouseTransferItem(House* house) { - HouseTransferItem* transferItem = new HouseTransferItem(house); - transferItem->incrementReferenceCounter(); + HouseTransferItemPtr transferItem = std::make_shared(house); transferItem->setID(ITEM_DOCUMENT_RO); transferItem->setSubType(1); transferItem->setSpecialDescription(fmt::format("It is a house transfer document for '{:s}'.", house->getName())); return transferItem; } -void HouseTransferItem::onTradeEvent(TradeEvents_t event, Player* owner) +void HouseTransferItem::onTradeEvent(const TradeEvents_t event, const PlayerPtr& owner) { if (event == ON_TRADE_TRANSFER) { if (house) { - house->executeTransfer(this, owner); + house->executeTransfer(static_cast(this), owner); } - g_game.internalRemoveItem(this, 1); + g_game.internalRemoveItem(static_cast(this), 1); } else if (event == ON_TRADE_CANCEL) { if (house) { house->resetTransferItem(); @@ -372,7 +366,7 @@ void HouseTransferItem::onTradeEvent(TradeEvents_t event, Player* owner) } } -bool House::executeTransfer(HouseTransferItem* item, Player* newOwner) +bool House::executeTransfer(const HouseTransferItemPtr& item, const PlayerPtr& newOwner) { if (transferItem != item) { return false; @@ -383,7 +377,7 @@ bool House::executeTransfer(HouseTransferItem* item, Player* newOwner) return true; } -void AccessList::parseList(std::string_view list) +void AccessList::parseList(const std::string_view list) { playerList.clear(); guildRankList.clear(); @@ -413,8 +407,7 @@ void AccessList::parseList(std::string_view list) toLowerCaseString(line); - std::string::size_type at_pos = line.find("@"); - if (at_pos != std::string::npos) { + if (const std::string::size_type at_pos = line.find("@"); at_pos != std::string::npos) { if (at_pos == 0) { addGuild(line.substr(1)); } else { @@ -432,12 +425,10 @@ void AccessList::parseList(std::string_view list) void AccessList::addPlayer(const std::string& name) { - Player* player = g_game.getPlayerByName(name); - if (player) { + if (const auto player = g_game.getPlayerByName(name)) { playerList.insert(player->getGUID()); } else { - uint32_t guid = IOLoginData::getGuidByName(name); - if (guid != 0) { + if (const uint32_t guid = IOLoginData::getGuidByName(name); guid != 0) { playerList.insert(guid); } } @@ -452,8 +443,7 @@ const Guild* getGuildByName(const std::string& name) return nullptr; } - const Guild* guild = g_game.getGuild(guildId); - if (guild) { + if (const auto guild = g_game.getGuild(guildId)) { return guild; } @@ -464,9 +454,8 @@ const Guild* getGuildByName(const std::string& name) void AccessList::addGuild(const std::string& name) { - const Guild* guild = getGuildByName(name); - if (guild) { - for (auto rank : guild->getRanks()) { + if (const auto guild = getGuildByName(name)) { + for (const auto rank : guild->getRanks()) { guildRankList.insert(rank->id); } } @@ -474,16 +463,14 @@ void AccessList::addGuild(const std::string& name) void AccessList::addGuildRank(const std::string& name, const std::string& rankName) { - const Guild* guild = getGuildByName(name); - if (guild) { - GuildRank_ptr rank = guild->getRankByName(rankName); - if (rank) { + if (const auto guild = getGuildByName(name)) { + if (const GuildRank_ptr rank = guild->getRankByName(rankName)) { guildRankList.insert(rank->id); } } } -bool AccessList::isInList(const Player* player) const +bool AccessList::isInList(const PlayerConstPtr& player) const { if (allowEveryone) { return true; @@ -494,8 +481,8 @@ bool AccessList::isInList(const Player* player) const return true; } - GuildRank_ptr rank = player->getGuildRank(); - return rank && guildRankList.find(rank->id) != guildRankList.end(); + const GuildRank_ptr rank = player->getGuildRank(); + return rank && guildRankList.contains(rank->id); } void AccessList::getList(std::string& list) const @@ -503,9 +490,9 @@ void AccessList::getList(std::string& list) const list = this->list; } -Door::Door(uint16_t type) : Item(type) {} +Door::Door(const uint16_t type) : Item(type) {} -Attr_ReadValue Door::readAttr(AttrTypes_t attr, PropStream& propStream) +Attr_ReadValue Door::readAttr(const AttrTypes_t attr, PropStream& propStream) { if (attr == ATTR_HOUSEDOORID) { uint8_t doorId; @@ -532,7 +519,7 @@ void Door::setHouse(House* house) } } -bool Door::canUse(const Player* player) +bool Door::canUse(const PlayerConstPtr& player) const { if (!house) { return true; @@ -545,7 +532,7 @@ bool Door::canUse(const Player* player) return accessList->isInList(player); } -void Door::setAccessList(std::string_view textlist) +void Door::setAccessList(const std::string_view textlist) { if (!accessList) { accessList.reset(new AccessList()); @@ -569,15 +556,15 @@ void Door::onRemoved() Item::onRemoved(); if (house) { - house->removeDoor(this); + house->removeDoor(static_cast(this)); } } -House* Houses::getHouseByPlayerId(uint32_t playerId) +House* Houses::getHouseByPlayerId(const uint32_t playerId) const { - for (const auto& it : houseMap) { - if (it.second->getOwner() == playerId) { - return it.second; + for (const auto& val : houseMap | std::views::values) { + if (val->getOwner() == playerId) { + return val; } } return nullptr; @@ -586,8 +573,7 @@ House* Houses::getHouseByPlayerId(uint32_t playerId) bool Houses::loadHousesXML(const std::string& filename) { pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(filename.c_str()); - if (!result) { + if (const pugi::xml_parse_result result = doc.load_file(filename.c_str()); !result) { printXMLError("Error - Houses::loadHousesXML", filename, result); return false; } @@ -598,7 +584,7 @@ bool Houses::loadHousesXML(const std::string& filename) return false; } - int32_t houseId = pugi::cast(houseIdAttribute.value()); + const int32_t houseId = pugi::cast(houseIdAttribute.value()); House* house = getHouse(houseId); if (!house) { @@ -628,15 +614,15 @@ bool Houses::loadHousesXML(const std::string& filename) return true; } -void Houses::payHouses(RentPeriod_t rentPeriod) const +void Houses::payHouses(const RentPeriod_t rentPeriod) const { if (rentPeriod == RENTPERIOD_NEVER) { return; } time_t currentTime = time(nullptr); - for (const auto& it : houseMap) { - House* house = it.second; + for (const auto& val : houseMap | std::views::values) { + House* house = val; if (house->getOwner() == 0) { continue; } @@ -647,20 +633,20 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const } const uint32_t ownerId = house->getOwner(); - Town* town = g_game.map.towns.getTown(house->getTownId()); + const auto town = g_game.map.towns.getTown(house->getTownId()); if (!town) { continue; } - Player player(nullptr); - if (!IOLoginData::loadPlayerById(&player, ownerId)) { + PlayerPtr player = std::make_shared(nullptr); + if (!IOLoginData::loadPlayerById(player, ownerId)) { // Player doesn't exist, reset house owner house->setOwner(0); continue; } - if (player.getBankBalance() >= rent) { - player.setBankBalance(player.getBankBalance() - rent); + if (player->getBankBalance() >= rent) { + player->setBankBalance(player->getBankBalance() - rent); time_t paidUntil = currentTime; switch (rentPeriod) { @@ -686,7 +672,7 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const if (house->getPayRentWarnings() < 7) { int32_t daysLeft = 7 - house->getPayRentWarnings(); - Item* letter = Item::CreateItem(ITEM_LETTER_STAMPED); + auto letter = Item::CreateItem(ITEM_LETTER_STAMPED); std::string period; switch (rentPeriod) { @@ -711,13 +697,14 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const } letter->setText(fmt::format("Warning! \nThe {:s} rent of {:d} gold for your house \"{:s}\" is payable. Have it within {:d} days or you will lose this house.", period, house->getRent(), house->getName(), daysLeft)); - g_game.internalAddItem(player.getInbox(), letter, INDEX_WHEREEVER, FLAG_NOLIMIT); + CylinderPtr inbox = player->getInbox(); + g_game.internalAddItem(inbox, letter, INDEX_WHEREEVER, FLAG_NOLIMIT); house->setPayRentWarnings(house->getPayRentWarnings() + 1); } else { - house->setOwner(0, true, &player); + house->setOwner(0, true, player); } } - IOLoginData::savePlayer(&player); + IOLoginData::savePlayer(player); } } diff --git a/src/house.h b/src/house.h index f702a883..3373824b 100644 --- a/src/house.h +++ b/src/house.h @@ -4,6 +4,7 @@ #ifndef FS_HOUSE_H #define FS_HOUSE_H +#include #include #include @@ -23,7 +24,7 @@ class AccessList void addGuild(const std::string& name); void addGuildRank(const std::string& name, const std::string& rankName); - bool isInList(const Player* player) const; + bool isInList(const PlayerConstPtr& player) const; void getList(std::string& list) const; @@ -43,14 +44,15 @@ class Door final : public Item Door(const Door&) = delete; Door& operator=(const Door&) = delete; - Door* getDoor() override { - return this; + DoorPtr getDoor() override { + return dynamic_shared_this(); } - const Door* getDoor() const override { - return this; + + DoorConstPtr getDoor() const override { + return dynamic_shared_this(); } - House* getHouse() { + House* getHouse() const { return house; } @@ -61,11 +63,12 @@ class Door final : public Item void setDoorId(uint32_t doorId) { setIntAttr(ITEM_ATTRIBUTE_DOORID, doorId); } + uint32_t getDoorId() const { return getIntAttr(ITEM_ATTRIBUTE_DOORID); } - bool canUse(const Player* player); + bool canUse(const PlayerConstPtr& player) const; void setAccessList(std::string_view textlist); bool getAccessList(std::string& list) const; @@ -92,17 +95,21 @@ enum AccessHouseLevel_t { HOUSE_OWNER = 3, }; -using HouseTileList = std::list; -using HouseBedItemList = std::list; +using HouseTileList = std::list; +using HouseBedItemList = std::list; + +class HouseTransferItem; +using HouseTransferItemPtr = std::shared_ptr; +using HouseTransferItemConstPtr = std::shared_ptr; class HouseTransferItem final : public Item { public: - static HouseTransferItem* createHouseTransferItem(House* house); + static HouseTransferItemPtr createHouseTransferItem(House* house); explicit HouseTransferItem(House* house) : Item(0), house(house) {} - void onTradeEvent(TradeEvents_t event, Player* owner) override; + void onTradeEvent(TradeEvents_t event, const PlayerPtr& owner) override; bool canTransform() const override { return false; } @@ -114,66 +121,73 @@ class HouseTransferItem final : public Item class House { public: - explicit House(uint32_t houseId); + explicit House(const uint32_t houseId); - void addTile(HouseTile* tile); + void addTile(const HouseTilePtr& tile); void updateDoorDescription() const; - bool canEditAccessList(uint32_t listId, const Player* player); + bool canEditAccessList(uint32_t listId, const PlayerConstPtr& player) const; // listId special values: // GUEST_LIST guest list // SUBOWNER_LIST subowner list void setAccessList(uint32_t listId, std::string_view textlist); bool getAccessList(uint32_t listId, std::string& list) const; - bool isInvited(const Player* player) const; + bool isInvited(const PlayerConstPtr& player) const; - AccessHouseLevel_t getHouseAccessLevel(const Player* player) const; - bool kickPlayer(Player* player, Player* target); + AccessHouseLevel_t getHouseAccessLevel(const PlayerConstPtr& player) const; + bool kickPlayer(const PlayerPtr& player, const PlayerPtr& target); - void setEntryPos(Position pos) { + void setEntryPos(const Position pos) { posEntry = pos; } + const Position& getEntryPosition() const { return posEntry; } - void setName(std::string houseName) { + void setName(const std::string& houseName) { this->houseName = houseName; } + const std::string& getName() const { return houseName; } - void setOwner(uint32_t guid, bool updateDatabase = true, Player* player = nullptr); + void setOwner(uint32_t guid, bool updateDatabase = true, const PlayerPtr& player = nullptr); + uint32_t getOwner() const { return owner; } - void setPaidUntil(time_t paid) { + void setPaidUntil(const time_t paid) { paidUntil = paid; } + time_t getPaidUntil() const { return paidUntil; } - void setRent(uint32_t rent) { + void setRent(const uint32_t rent) { this->rent = rent; } + uint32_t getRent() const { return rent; } - void setPayRentWarnings(uint32_t warnings) { + void setPayRentWarnings(const uint32_t warnings) { rentWarnings = warnings; } + uint32_t getPayRentWarnings() const { return rentWarnings; } - void setTownId(uint32_t townId) { + void setTownId(const uint32_t townId) { this->townId = townId; } + uint32_t getTownId() const { return townId; } @@ -182,34 +196,36 @@ class House return id; } - void addDoor(Door* door); - void removeDoor(Door* door); - Door* getDoorByNumber(uint32_t doorId) const; - Door* getDoorByPosition(const Position& pos); + void addDoor(const DoorPtr& door); + void removeDoor(const DoorPtr& door); + DoorPtr getDoorByNumber(uint32_t doorId) const; + DoorPtr getDoorByPosition(const Position& pos); - HouseTransferItem* getTransferItem(); + HouseTransferItemPtr getTransferItem(); void resetTransferItem(); - bool executeTransfer(HouseTransferItem* item, Player* newOwner); + bool executeTransfer(const HouseTransferItemPtr& item, const PlayerPtr& newOwner); const HouseTileList& getTiles() const { return houseTiles; } - const std::set& getDoors() const { + const std::set& getDoors() const { return doorSet; } - void addBed(BedItem* bed); + void addBed(const BedItemPtr& bed); + const HouseBedItemList& getBeds() const { return bedsList; } - uint32_t getBedCount() { + + uint32_t getBedCount() const { return static_cast(std::ceil(bedsList.size() / 2.)); //each bed takes 2 sqms of space, ceil is just for bad maps } private: bool transferToDepot() const; - bool transferToDepot(Player* player) const; + bool transferToDepot(const PlayerPtr& player) const; AccessList guestList; AccessList subOwnerList; @@ -217,13 +233,13 @@ class House Container transfer_container{ITEM_LOCKER1}; HouseTileList houseTiles; - std::set doorSet; + std::set doorSet; HouseBedItemList bedsList; std::string houseName; std::string ownerName; - HouseTransferItem* transferItem = nullptr; + HouseTransferItemPtr transferItem = nullptr; time_t paidUntil = 0; @@ -254,8 +270,8 @@ class Houses public: Houses() = default; ~Houses() { - for (const auto& it : houseMap) { - delete it.second; + for (const auto& val : houseMap | std::views::values) { + delete val; } } @@ -263,13 +279,13 @@ class Houses Houses(const Houses&) = delete; Houses& operator=(const Houses&) = delete; - House* addHouse(uint32_t id) { + House* addHouse(const uint32_t id) { auto it = houseMap.find(id); if (it != houseMap.end()) { return it->second; } - House* house = new House(id); + auto house = new House(id); houseMap[id] = house; return house; } @@ -282,7 +298,7 @@ class Houses return it->second; } - House* getHouseByPlayerId(uint32_t playerId); + House* getHouseByPlayerId(uint32_t playerId) const; bool loadHousesXML(const std::string& filename); diff --git a/src/housetile.cpp b/src/housetile.cpp index d5d23a39..3330a358 100644 --- a/src/housetile.cpp +++ b/src/housetile.cpp @@ -11,10 +11,10 @@ extern Game g_game; extern ConfigManager g_config; -HouseTile::HouseTile(int32_t x, int32_t y, int32_t z, House* house) : +HouseTile::HouseTile(const int32_t x, int32_t y, const int32_t z, House* house) : DynamicTile(x, y, z), house(house) {} -void HouseTile::addThing(int32_t index, Thing* thing) +void HouseTile::addThing(int32_t index, ThingPtr thing) { Tile::addThing(index, thing); @@ -22,12 +22,12 @@ void HouseTile::addThing(int32_t index, Thing* thing) return; } - if (Item* item = thing->getItem()) { + if (const auto item = thing->getItem()) { updateHouse(item); } } -void HouseTile::internalAddThing(uint32_t index, Thing* thing) +void HouseTile::internalAddThing(uint32_t index, ThingPtr thing) { Tile::internalAddThing(index, thing); @@ -35,44 +35,42 @@ void HouseTile::internalAddThing(uint32_t index, Thing* thing) return; } - if (Item* item = thing->getItem()) { + if (const auto item = thing->getItem()) { updateHouse(item); } } -void HouseTile::updateHouse(Item* item) +void HouseTile::updateHouse(const ItemPtr& item) { - if (item->getParent() != this) { + if (item->getParent() != getParent()) { return; } - Door* door = item->getDoor(); - if (door) { + if (auto door = item->getDoor()) { if (door->getDoorId() != 0) { house->addDoor(door); } } else { - BedItem* bed = item->getBed(); - if (bed) { + if (const auto bed = item->getBed()) { house->addBed(bed); } } } -ReturnValue HouseTile::queryAdd(int32_t index, const Thing& thing, uint32_t count, uint32_t flags, Creature* actor/* = nullptr*/) const +ReturnValue HouseTile::queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor/* = nullptr*/) { - if (const Creature* creature = dynamic_cast(&thing)) { - if (const Player* player = creature->getPlayer()) { + if (CreaturePtr creature = std::dynamic_pointer_cast(thing)) { + if (const auto player = creature->getPlayer()) { if (!house->isInvited(player)) { return RETURNVALUE_PLAYERISNOTINVITED; } } else { return RETURNVALUE_NOTPOSSIBLE; } - return Tile::queryAdd(*creature, flags); + return Tile::queryAdd(creature, flags); } - if (const Item* item = dynamic_cast(&thing)) { + if (ItemPtr item = std::dynamic_pointer_cast(thing)) { if (item->isStoreItem() && !item->hasAttribute(ITEM_ATTRIBUTE_WRAPID)) { return RETURNVALUE_ITEMCANNOTBEMOVEDTHERE; } @@ -82,18 +80,18 @@ ReturnValue HouseTile::queryAdd(int32_t index, const Thing& thing, uint32_t coun return RETURNVALUE_PLAYERISNOTINVITED; } } - return Tile::queryAdd(*item, flags); + return Tile::queryAdd(item, flags); } return RETURNVALUE_NOERROR; } -Tile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& flags) +CylinderPtr HouseTile::queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, uint32_t& flags) { - if (const Creature* creature = thing.getCreature()) { - if (const Player* player = creature->getPlayer()) { + if (const auto creature = thing->getCreature()) { + if (const auto player = creature->getPlayer()) { if (!house->isInvited(player)) { const Position& entryPos = house->getEntryPosition(); - Tile* destTile = g_game.map.getTile(entryPos); + auto destTile = g_game.map.getTile(entryPos); if (!destTile) { std::cout << "Error: [HouseTile::queryDestination] House entry not correct" << " - Name: " << house->getName() @@ -102,7 +100,7 @@ Tile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** des destTile = g_game.map.getTile(player->getTemplePosition()); if (!destTile) { - destTile = &(Tile::nullptr_tile); + destTile = std::make_shared(0xFFFF, 0xFFFF, 0xFF); } } @@ -116,9 +114,9 @@ Tile* HouseTile::queryDestination(int32_t& index, const Thing& thing, Item** des return Tile::queryDestination(index, thing, destItem, flags); } -ReturnValue HouseTile::queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor /*= nullptr*/) const +ReturnValue HouseTile::queryRemove(const ThingPtr& thing, const uint32_t count, const uint32_t flags, CreaturePtr actor /*= nullptr*/) { - const Item* item = thing.getItem(); + const auto item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/housetile.h b/src/housetile.h index 761a17b3..a374d2e9 100644 --- a/src/housetile.h +++ b/src/housetile.h @@ -14,23 +14,31 @@ class HouseTile final : public DynamicTile 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; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) override; - Tile* queryDestination(int32_t& index, const Thing& thing, Item** destItem, - uint32_t& flags) override; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, + uint32_t& flags) override; // another optional ref wrapper - ReturnValue queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; - void addThing(int32_t index, Thing* thing) override; - void internalAddThing(uint32_t index, Thing* thing) override; + void addThing(int32_t index, ThingPtr thing) override; + void internalAddThing(uint32_t index, ThingPtr thing) override; House* getHouse() const { return house; } + HouseTilePtr getHouseTilePtr() { + return dynamic_shared_this(); + } + + HouseTileConstPtr getHouseTileConstPtr() { + return dynamic_shared_this(); + } + private: - void updateHouse(Item* item); + void updateHouse(const ItemPtr& item); House* house; }; diff --git a/src/inbox.cpp b/src/inbox.cpp index a253ba71..4b751ec6 100644 --- a/src/inbox.cpp +++ b/src/inbox.cpp @@ -8,19 +8,19 @@ Inbox::Inbox(uint16_t type) : Container(type, 30, false, true) {} -ReturnValue Inbox::queryAdd(int32_t, const Thing& thing, uint32_t, - uint32_t flags, Creature*) const +ReturnValue Inbox::queryAdd(int32_t, const ThingPtr& thing, uint32_t, + uint32_t flags, CreaturePtr) { if (!hasBitSet(FLAG_NOLIMIT, flags)) { return RETURNVALUE_CONTAINERNOTENOUGHROOM; } - const Item* item = thing.getItem(); + auto item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } - if (item == this) { + if (item.get() == this) { return RETURNVALUE_THISISIMPOSSIBLE; } @@ -31,26 +31,24 @@ ReturnValue Inbox::queryAdd(int32_t, const Thing& thing, uint32_t, return RETURNVALUE_NOERROR; } -void Inbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void Inbox::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - Cylinder* parent = getParent(); - if (parent != nullptr) { + if (const auto parent = getParent(); parent != nullptr) { parent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void Inbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void Inbox::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - Cylinder* parent = getParent(); - if (parent != nullptr) { + if (const auto parent = getParent(); parent != nullptr) { parent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } -Cylinder* Inbox::getParent() const +CylinderPtr Inbox::getParent() { - if (parent) { - return parent->getParent(); + if (parent.lock()) { + return parent.lock()->getParent(); } return nullptr; } diff --git a/src/inbox.h b/src/inbox.h index a8674328..53a6d82f 100644 --- a/src/inbox.h +++ b/src/inbox.h @@ -12,22 +12,26 @@ class Inbox final : public Container explicit Inbox(uint16_t type); //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; //overrides bool canRemove() const override { return false; } - Cylinder* getParent() const override; - Cylinder* getRealParent() const override { - return parent; + CylinderPtr getParent() override; + + CylinderPtr getRealParent() override { + return getParent(); } }; +using InboxPtr = std::shared_ptr; +using InboxConstPtr = std::shared_ptr; + #endif diff --git a/src/iologindata.cpp b/src/iologindata.cpp index 69eea6fe..ec44c43c 100644 --- a/src/iologindata.cpp +++ b/src/iologindata.cpp @@ -35,7 +35,7 @@ Account IOLoginData::loadAccount(uint32_t accno) return account; } -std::string decodeSecret(std::string_view secret) +std::string decodeSecret(const std::string_view secret) { // simple base32 decoding std::string key; @@ -174,7 +174,7 @@ void IOLoginData::updateOnlineStatus(uint32_t guid, bool login) } } -bool IOLoginData::preloadPlayer(Player* player) +bool IOLoginData::preloadPlayer(const PlayerPtr& player) { Database& db = Database::getInstance(); @@ -196,13 +196,13 @@ bool IOLoginData::preloadPlayer(Player* player) return true; } -bool IOLoginData::loadPlayerById(Player* player, uint32_t id) +bool IOLoginData::loadPlayerById(const PlayerPtr& player, uint32_t id) { Database& db = Database::getInstance(); return loadPlayer(player, db.storeQuery(fmt::format("SELECT `id`, `name`, `account_id`, `group_id`, `sex`, `vocation`, `experience`, `level`, `maglevel`, `health`, `healthmax`, `blessings`, `mana`, `manamax`, `manaspent`, `soul`, `lookbody`, `lookfeet`, `lookhead`, `looklegs`, `looktype`, `lookaddons`, `posx`, `posy`, `posz`, `cap`, `lastlogin`, `lastlogout`, `lastip`, `conditions`, `skulltime`, `skull`, `town_id`, `balance`, `offlinetraining_time`, `offlinetraining_skill`, `stamina`, `skill_fist`, `skill_fist_tries`, `skill_club`, `skill_club_tries`, `skill_sword`, `skill_sword_tries`, `skill_axe`, `skill_axe_tries`, `skill_dist`, `skill_dist_tries`, `skill_shielding`, `skill_shielding_tries`, `skill_fishing`, `skill_fishing_tries`, `direction` FROM `players` WHERE `id` = {:d}", id))); } -bool IOLoginData::loadPlayerByName(Player* player, const std::string& name) +bool IOLoginData::loadPlayerByName(const PlayerPtr& player, const std::string& name) { Database& db = Database::getInstance(); return loadPlayer(player, db.storeQuery(fmt::format("SELECT `id`, `name`, `account_id`, `group_id`, `sex`, `vocation`, `experience`, `level`, `maglevel`, `health`, `healthmax`, `blessings`, `mana`, `manamax`, `manaspent`, `soul`, `lookbody`, `lookfeet`, `lookhead`, `looklegs`, `looktype`, `lookaddons`, `posx`, `posy`, `posz`, `cap`, `lastlogin`, `lastlogout`, `lastip`, `conditions`, `skulltime`, `skull`, `town_id`, `balance`, `offlinetraining_time`, `offlinetraining_skill`, `stamina`, `skill_fist`, `skill_fist_tries`, `skill_club`, `skill_club_tries`, `skill_sword`, `skill_sword_tries`, `skill_axe`, `skill_axe_tries`, `skill_dist`, `skill_dist_tries`, `skill_shielding`, `skill_shielding_tries`, `skill_fishing`, `skill_fishing_tries`, `direction` FROM `players` WHERE `name` = {:s}", db.escapeString(name)))); @@ -227,7 +227,7 @@ static GuildWarVector getWarList(uint32_t guildId) return std::move(guildWarVector); } -bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) +bool IOLoginData::loadPlayer(const PlayerPtr& player, DBResult_ptr result) { if (!result) { return false; @@ -347,7 +347,7 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) player->offlineTrainingTime = result->getNumber("offlinetraining_time") * 1000; player->offlineTrainingSkill = result->getNumber("offlinetraining_skill"); - Town* town = g_game.map.towns.getTown(result->getNumber("town_id")); + auto town = g_game.map.towns.getTown(result->getNumber("town_id")); if (!town) { std::cout << "[Error - IOLoginData::loadPlayer] " << player->name << " has Town ID " << result->getNumber("town_id") << " which doesn't exist" << std::endl; return false; @@ -383,7 +383,7 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) uint32_t playerRankId = result->getNumber("rank_id"); player->guildNick = result->getString("nick"); - Guild* guild = g_game.getGuild(guildId); + auto guild = g_game.getGuild(guildId); if (!guild) { guild = IOGuild::loadGuild(guildId); if (guild) { @@ -429,8 +429,8 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) loadItems(itemMap, result); for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { - const std::pair& pair = it->second; - Item* item = pair.first; + const std::pair& pair = it->second; + auto item = pair.first; int32_t pid = pair.second; if (pid >= CONST_SLOT_FIRST && pid <= CONST_SLOT_LAST) { player->internalAddThing(pid, item); @@ -441,8 +441,7 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) continue; } - Container* container = it2->second.first->getContainer(); - if (container) { + if (auto container = it2->second.first->getContainer()) { container->internalAddThing(item); } } @@ -456,13 +455,12 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) loadItems(itemMap, result); for (ItemMap::const_reverse_iterator it = itemMap.rbegin(), end = itemMap.rend(); it != end; ++it) { - const std::pair& pair = it->second; - Item* item = pair.first; + const std::pair& pair = it->second; + auto item = pair.first; int32_t pid = pair.second; if (pid >= 0 && pid < 100) { - DepotChest* depotChest = player->getDepotChest(pid, true); - if (depotChest) { + if (auto depotChest = player->getDepotChest(pid, true)) { depotChest->internalAddThing(item); } } else { @@ -471,8 +469,7 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) continue; } - Container* container = it2->second.first->getContainer(); - if (container) { + if (auto container = it2->second.first->getContainer()) { container->internalAddThing(item); } } @@ -486,21 +483,19 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) loadItems(itemMap, result); 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) { + const std::pair& pair = it->second; + auto item = pair.first; + + if (int32_t pid = pair.second; pid == 0) { auto& rewardChest = player->getRewardChest(); - rewardChest.internalAddThing(item); + rewardChest->internalAddThing(item); } else { ItemMap::const_iterator it2 = itemMap.find(pid); if (it2 == itemMap.end()) { continue; } - Container* container = it2->second.first->getContainer(); - if (container) { + if (auto container = it2->second.first->getContainer()) { container->internalAddThing(item); } } @@ -514,11 +509,10 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) loadItems(itemMap, result); 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; + const std::pair& pair = it->second; + auto item = pair.first; - if (pid >= 0 && pid < 100) { + if (int32_t pid = pair.second; pid >= 0 && pid < 100) { player->getInbox()->internalAddThing(item); } else { ItemMap::const_iterator it2 = itemMap.find(pid); @@ -527,8 +521,7 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) continue; } - Container* container = it2->second.first->getContainer(); - if (container) { + if (auto container = it2->second.first->getContainer()) { container->internalAddThing(item); } } @@ -542,11 +535,10 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) loadItems(itemMap, result); 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; + const std::pair& pair = it->second; + auto item = pair.first; - if (pid >= 0 && pid < 100) { + if (int32_t pid = pair.second; pid >= 0 && pid < 100) { player->getStoreInbox()->internalAddThing(item); } else { ItemMap::const_iterator it2 = itemMap.find(pid); @@ -555,8 +547,7 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) continue; } - Container* container = it2->second.first->getContainer(); - if (container) { + if (auto container = it2->second.first->getContainer()) { container->internalAddThing(item); } } @@ -601,9 +592,9 @@ bool IOLoginData::loadPlayer(Player* player, DBResult_ptr result) return true; } -bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream) +bool IOLoginData::saveItems(const PlayerConstPtr& player, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream) { - using ContainerBlock = std::pair; + using ContainerBlock = std::pair; std::list queue; int32_t runningId = 100; @@ -612,12 +603,12 @@ bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, for (const auto& it : itemList) { int32_t pid = it.first; - Item* item = it.second; + auto item = it.second; ++runningId; propWriteStream.clear(); item->serializeAttr(propWriteStream); - auto attributesData = propWriteStream.getStream(); + const auto attributesData = propWriteStream.getStream(); auto augmentStream = PropWriteStream(); const auto& augments = item->getAugments(); @@ -627,7 +618,8 @@ bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, for (const auto& augment : augments) { augment->serialize(augmentStream); } - auto augmentsData = augmentStream.getStream(); + + const auto augmentsData = augmentStream.getStream(); if (!query_insert.addRow(fmt::format("{:d}, {:d}, {:d}, {:d}, {:d}, {:s}, {:s}", player->getGUID(), pid, runningId, item->getID(), item->getSubType(), @@ -636,18 +628,18 @@ bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, return false; } - if (Container* container = item->getContainer()) { + if (auto container = item->getContainer()) { queue.emplace_back(container, runningId); } } while (!queue.empty()) { const ContainerBlock& cb = queue.front(); - Container* container = cb.first; + const auto container = cb.first; int32_t parentId = cb.second; queue.pop_front(); - for (Item* item : container->getItemList()) { + for (auto item : container->getItemList()) { ++runningId; propWriteStream.clear(); @@ -672,7 +664,7 @@ bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, return false; } - if (Container* subContainer = item->getContainer()) { + if (auto subContainer = item->getContainer()) { queue.emplace_back(subContainer, runningId); } } @@ -681,10 +673,10 @@ bool IOLoginData::saveItems(const Player* player, const ItemBlockList& itemList, return query_insert.execute(); } -bool IOLoginData::saveAugments(const Player* player, DBInsert& query_insert, PropWriteStream& augmentStream) { - Database& db = Database::getInstance(); +bool IOLoginData::saveAugments(const PlayerConstPtr& player, DBInsert& query_insert, PropWriteStream& augmentStream) { + const Database& db = Database::getInstance(); auto& augments = player->getPlayerAugments(); - uint32_t augmentCount = augments.size(); + const uint32_t augmentCount = augments.size(); augmentStream.clear(); augmentStream.write(augmentCount); @@ -719,18 +711,18 @@ bool IOLoginData::saveAugments(const Player* player, DBInsert& query_insert, Pro bool IOLoginData::addRewardItems(uint32_t playerID, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream) { - using ContainerBlock = std::pair; + using ContainerBlock = std::pair; std::list queue; int32_t runningId = 100; Database& db = Database::getInstance(); for (const auto& it : itemList) { int32_t pid = it.first; - Item* item = it.second; + const auto item = it.second; ++runningId; propWriteStream.clear(); item->serializeAttr(propWriteStream); - auto attributesData = propWriteStream.getStream(); + const auto attributesData = propWriteStream.getStream(); auto augmentStream = PropWriteStream(); const auto& augments = item->getAugments(); @@ -739,7 +731,7 @@ bool IOLoginData::addRewardItems(uint32_t playerID, const ItemBlockList& itemLis for (const auto& augment : augments) { augment->serialize(augmentStream); } - auto augmentsData = augmentStream.getStream(); + const auto augmentsData = augmentStream.getStream(); if (!query_insert.addRow(fmt::format("{:d}, {:d}, {:d}, {:d}, {:d}, {:s}, {:s}", playerID, pid, runningId, item->getID(), item->getSubType(), @@ -748,18 +740,18 @@ bool IOLoginData::addRewardItems(uint32_t playerID, const ItemBlockList& itemLis return false; } - if (Container* container = item->getContainer()) { + if (auto container = item->getContainer()) { queue.emplace_back(container, runningId); } } while (!queue.empty()) { const ContainerBlock& cb = queue.front(); - Container* container = cb.first; + auto container = cb.first; int32_t parentId = cb.second; queue.pop_front(); - for (Item* item : container->getItemList()) { + for (auto item : container->getItemList()) { ++runningId; propWriteStream.clear(); item->serializeAttr(propWriteStream); @@ -781,7 +773,7 @@ bool IOLoginData::addRewardItems(uint32_t playerID, const ItemBlockList& itemLis return false; } - if (Container* subContainer = item->getContainer()) { + if (auto subContainer = item->getContainer()) { queue.emplace_back(subContainer, runningId); } } @@ -791,7 +783,7 @@ bool IOLoginData::addRewardItems(uint32_t playerID, const ItemBlockList& itemLis } -bool IOLoginData::savePlayer(Player* player) +bool IOLoginData::savePlayer(const PlayerPtr& player) { if (player->getHealth() <= 0) { player->changeHealth(1); @@ -810,7 +802,7 @@ bool IOLoginData::savePlayer(Player* player) //serialize conditions PropWriteStream propWriteStream; - for (Condition* condition : player->conditions) { + for (auto condition : player->conditions) { if (condition->isPersistent()) { condition->serialize(propWriteStream); propWriteStream.write(CONDITIONATTR_END); @@ -936,8 +928,7 @@ bool IOLoginData::savePlayer(Player* player) ItemBlockList itemList; for (int32_t slotId = CONST_SLOT_FIRST; slotId <= CONST_SLOT_LAST; ++slotId) { - Item* item = player->inventory[slotId]; - if (item) { + if (auto item = player->inventory[slotId]) { itemList.emplace_back(slotId, item); } } @@ -955,7 +946,7 @@ bool IOLoginData::savePlayer(Player* player) itemList.clear(); for (const auto& it : player->depotChests) { - for (Item* item : it.second->getItemList()) { + for (auto item : it.second->getItemList()) { itemList.emplace_back(it.first, item); } } @@ -972,7 +963,7 @@ bool IOLoginData::savePlayer(Player* player) DBInsert rewardQuery("INSERT INTO `player_rewarditems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`, `augments`) VALUES "); itemList.clear(); - for (Item* item : player->getRewardChest().getItemList()) { + for (auto item : player->getRewardChest()->getItemList()) { itemList.emplace_back(0, item); } @@ -989,7 +980,7 @@ bool IOLoginData::savePlayer(Player* player) DBInsert inboxQuery("INSERT INTO `player_inboxitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`, `augments`) VALUES "); itemList.clear(); - for (Item* item : player->getInbox()->getItemList()) { + for (auto item : player->getInbox()->getItemList()) { itemList.emplace_back(0, item); } @@ -1005,7 +996,7 @@ bool IOLoginData::savePlayer(Player* player) DBInsert storeInboxQuery("INSERT INTO `player_storeinboxitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`, `augments`) VALUES "); itemList.clear(); - for (Item* item : player->getStoreInbox()->getItemList()) { + for (auto item : player->getStoreInbox()->getItemList()) { itemList.emplace_back(0, item); } @@ -1105,7 +1096,7 @@ bool IOLoginData::formatPlayerName(std::string& name) return true; } -void IOLoginData::loadPlayerAugments(std::vector>& augmentList, DBResult_ptr result) { +void IOLoginData::loadPlayerAugments(std::vector>& augmentList, const DBResult_ptr& result) { try { if (!result) { std::cout << "ERROR: Null result in loadPlayerAugments" << std::endl; @@ -1162,7 +1153,7 @@ void IOLoginData::loadPlayerAugments(std::vector>& augm } } -void IOLoginData::loadItems(ItemMap& itemMap, DBResult_ptr result) +void IOLoginData::loadItems(ItemMap& itemMap, const DBResult_ptr& result) { Database& db = Database::getInstance(); @@ -1182,8 +1173,7 @@ void IOLoginData::loadItems(ItemMap& itemMap, DBResult_ptr result) augmentStream.init(augmentData.data(), augmentData.size()); - Item* item = Item::CreateItem(type, count); - if (item) { + if (auto item = Item::CreateItem(type, count)) { // Deserialize the item's attributes if (!item->unserializeAttr(propStream)) { } diff --git a/src/iologindata.h b/src/iologindata.h index 94c13521..b7fcd52d 100644 --- a/src/iologindata.h +++ b/src/iologindata.h @@ -8,7 +8,7 @@ #include "player.h" #include "database.h" -using ItemBlockList = std::list>; +using ItemBlockList = std::list>; class IOLoginData { @@ -23,12 +23,12 @@ class IOLoginData static AccountType_t getAccountType(uint32_t accountId); static void setAccountType(uint32_t accountId, AccountType_t accountType); static void updateOnlineStatus(uint32_t guid, bool login); - static bool preloadPlayer(Player* player); + static bool preloadPlayer(const PlayerPtr& player); - static bool loadPlayerById(Player* player, uint32_t id); - static bool loadPlayerByName(Player* player, const std::string& name); - static bool loadPlayer(Player* player, DBResult_ptr result); - static bool savePlayer(Player* player); + static bool loadPlayerById(const PlayerPtr& player, uint32_t id); + static bool loadPlayerByName(const PlayerPtr& player, const std::string& name); + static bool loadPlayer(const PlayerPtr& player, DBResult_ptr result); + static bool savePlayer(const PlayerPtr& player); 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); @@ -46,12 +46,12 @@ class IOLoginData static bool addRewardItems(uint32_t playerId, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream); private: - using ItemMap = std::map>; + using ItemMap = std::map>; - static void loadItems(ItemMap& itemMap, DBResult_ptr result); - static bool saveItems(const Player* player, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream); - static bool saveAugments(const Player* player, DBInsert& query_insert, PropWriteStream& augmentStream); - static void loadPlayerAugments(std::vector>& augmentList, DBResult_ptr result); + static void loadItems(ItemMap& itemMap, const DBResult_ptr& result); + static bool saveItems(const PlayerConstPtr& player, const ItemBlockList& itemList, DBInsert& query_insert, PropWriteStream& propWriteStream); + static bool saveAugments(const PlayerConstPtr& player, DBInsert& query_insert, PropWriteStream& augmentStream); + static void loadPlayerAugments(std::vector>& augmentList, const DBResult_ptr& result); }; #endif diff --git a/src/iomap.cpp b/src/iomap.cpp index 540d4d5d..07b096ad 100644 --- a/src/iomap.cpp +++ b/src/iomap.cpp @@ -33,22 +33,22 @@ |--- OTBM_ITEM_DEF (not implemented) */ -Tile* IOMap::createTile(Item*& ground, Item* item, uint16_t x, uint16_t y, uint8_t z) +TilePtr IOMap::createTile(ItemPtr& ground, ItemPtr item, uint16_t x, uint16_t y, uint8_t z) { if (!ground) { - return new StaticTile(x, y, z); + return std::make_shared(x, y, z); } - Tile* tile; + TilePtr tile; if ((item && item->isBlocking()) || ground->isBlocking()) { - tile = new StaticTile(x, y, z); + tile = std::make_shared(x, y, z); } else { - tile = new DynamicTile(x, y, z); + tile = std::make_shared(x, y, z); } tile->internalAddThing(ground); ground->startDecaying(); - ground = nullptr; + ground.reset(); return tile; } @@ -232,8 +232,8 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma bool isHouseTile = false; House* house = nullptr; - Tile* tile = nullptr; - Item* ground_item = nullptr; + TilePtr tile = nullptr; + ItemPtr ground_item = nullptr; uint32_t tileflags = TILESTATE_NONE; if (tileNode.type == OTBM_HOUSETILE) { @@ -248,9 +248,10 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma setLastErrorString(fmt::format("[x:{:d}, y:{:d}, z:{:d}] Could not create house id: {:d}", x, y, z, houseId)); return false; } - - tile = new HouseTile(x, y, z, house); - house->addTile(static_cast(tile)); + + HouseTilePtr houseTile = std::make_shared(x, y, z, house); + tile = houseTile; + house->addTile(houseTile); isHouseTile = true; } @@ -280,7 +281,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma } case OTBM_ATTR_ITEM: { - Item* item = Item::CreateItem(propStream); + auto item = Item::CreateItem(propStream); if (!item) { setLastErrorString(fmt::format("[x:{:d}, y:{:d}, z:{:d}] Failed to create item.", x, y, z)); return false; @@ -288,7 +289,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma if (isHouseTile && item->isMoveable()) { std::cout << "[Warning - IOMap::loadMap] Moveable item with ID: " << item->getID() << ", in house: " << house->getId() << ", at position [x: " << x << ", y: " << y << ", z: " << z << "]." << std::endl; - delete item; + item.reset(); } else { if (item->getItemCount() == 0) { item->setItemCount(1); @@ -299,7 +300,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma item->startDecaying(); item->setLoadedFromMap(true); } else if (item->isGroundTile()) { - delete ground_item; + ground_item.reset(); ground_item = item; } else { tile = createTile(ground_item, item, x, y, z); @@ -329,7 +330,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma return false; } - Item* item = Item::CreateItem(stream); + auto item = Item::CreateItem(stream); if (!item) { setLastErrorString(fmt::format("[x:{:d}, y:{:d}, z:{:d}] Failed to create item.", x, y, z)); return false; @@ -337,13 +338,13 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma if (!item->unserializeItemNode(loader, itemNode, stream)) { setLastErrorString(fmt::format("[x:{:d}, y:{:d}, z:{:d}] Failed to load item {:d}.", x, y, z, item->getID())); - delete item; + item.reset(); return false; } if (isHouseTile && item->isMoveable()) { std::cout << "[Warning - IOMap::loadMap] Moveable item with ID: " << item->getID() << ", in house: " << house->getId() << ", at position [x: " << x << ", y: " << y << ", z: " << z << "]." << std::endl; - delete item; + item.reset(); } else { if (item->getItemCount() == 0) { item->setItemCount(1); @@ -354,7 +355,7 @@ bool IOMap::parseTileArea(OTB::Loader& loader, const OTB::Node& tileAreaNode, Ma item->startDecaying(); item->setLoadedFromMap(true); } else if (item->isGroundTile()) { - delete ground_item; + ground_item.reset(); ground_item = item; } else { tile = createTile(ground_item, item, x, y, z); @@ -396,7 +397,7 @@ bool IOMap::parseTowns(OTB::Loader& loader, const OTB::Node& townsNode, Map& map return false; } - Town* town = map.towns.getTown(townId); + auto town = map.towns.getTown(townId); if (!town) { town = new Town(townId); map.towns.addTown(townId, town); diff --git a/src/iomap.h b/src/iomap.h index cbba069b..c31dd836 100644 --- a/src/iomap.h +++ b/src/iomap.h @@ -88,7 +88,7 @@ struct OTBM_Tile_coords { class IOMap { - static Tile* createTile(Item*& ground, Item* item, uint16_t x, uint16_t y, uint8_t z); + static TilePtr createTile(ItemPtr& ground, ItemPtr item, uint16_t x, uint16_t y, uint8_t z); public: bool loadMap(Map* map, const std::filesystem::path& fileName); @@ -127,7 +127,7 @@ class IOMap return errorString; } - void setLastErrorString(std::string error) { + void setLastErrorString(const std::string& error) { errorString = error; } diff --git a/src/iomapserialize.cpp b/src/iomapserialize.cpp index 47fc6a5c..ecde8963 100644 --- a/src/iomapserialize.cpp +++ b/src/iomapserialize.cpp @@ -32,11 +32,11 @@ void IOMapSerialize::loadHouseItems(Map* map) continue; } - Tile* tile = map->getTile(x, y, z); + TilePtr tile = map->getTile(x, y, z); if (!tile) { continue; } - + //g_game.addGameTile(tile); uint32_t item_count; if (!propStream.read(item_count)) { continue; @@ -71,7 +71,7 @@ bool IOMapSerialize::saveHouseItems() for (const auto& it : g_game.map.houses.getHouses()) { //save house items House* house = it.second; - for (HouseTile* tile : house->getTiles()) { + for (auto tile : house->getTiles()) { saveTile(stream, tile); if (auto attributes = stream.getStream(); !attributes.empty()) { @@ -94,7 +94,7 @@ bool IOMapSerialize::saveHouseItems() return success; } -bool IOMapSerialize::loadContainer(PropStream& propStream, Container* container) +bool IOMapSerialize::loadContainer(PropStream& propStream, const ContainerPtr& container) { while (container->serializationCount > 0) { if (!loadItem(propStream, container)) { @@ -112,14 +112,14 @@ bool IOMapSerialize::loadContainer(PropStream& propStream, Container* container) return true; } -bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) +bool IOMapSerialize::loadItem(PropStream& propStream, const CylinderPtr& parent) { uint16_t id; if (!propStream.read(id)) { return false; } - Tile* tile = nullptr; + TilePtr tile = nullptr; if (parent->getParent() == nullptr) { tile = parent->getTile(); } @@ -127,12 +127,10 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) const ItemType& iType = Item::items[id]; if (iType.moveable || iType.forceSerialize || !tile) { //create a new item - Item* item = Item::CreateItem(id); - if (item) { + if (auto item = Item::CreateItem(id)) { if (item->unserializeAttr(propStream)) { - Container* container = item->getContainer(); + const auto& container = item->getContainer(); if (container && !loadContainer(propStream, container)) { - delete item; return false; } @@ -140,15 +138,14 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) item->startDecaying(); } else { std::cout << "WARNING: Unserialization error in IOMapSerialize::loadItem()" << id << std::endl; - delete item; return false; } } } else { // Stationary items like doors/beds/blackboards/bookcases - Item* item = nullptr; - if (const TileItemVector* items = tile->getItemList()) { - for (Item* findItem : *items) { + ItemPtr item = nullptr; + if (const auto items = tile->getItemList()) { + for (auto findItem : *items) { if (findItem->getID() == id) { item = findItem; break; @@ -164,26 +161,25 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) if (item) { if (item->unserializeAttr(propStream)) { - Container* container = item->getContainer(); + auto container = item->getContainer(); if (container && !loadContainer(propStream, container)) { return false; } - g_game.transformItem(item, id); + auto newItem = g_game.transformItem(item, id); } else { std::cout << "WARNING: Unserialization error in IOMapSerialize::loadItem()" << id << std::endl; } } else { //The map changed since the last save, just read the attributes - std::unique_ptr dummy(Item::CreateItem(id)); + auto dummy = Item::CreateItem(id); if (dummy) { dummy->unserializeAttr(propStream); - Container* container = dummy->getContainer(); - if (container) { + if (const auto container = dummy->getContainer()) { if (!loadContainer(propStream, container)) { return false; } - } else if (BedItem* bedItem = dynamic_cast(dummy.get())) { + } else if (auto bedItem = dynamic_cast(dummy.get())) { uint32_t sleeperGUID = bedItem->getSleeper(); if (sleeperGUID != 0) { g_game.removeBedSleeper(sleeperGUID); @@ -195,9 +191,9 @@ bool IOMapSerialize::loadItem(PropStream& propStream, Cylinder* parent) return true; } -void IOMapSerialize::saveItem(PropWriteStream& stream, const Item* item) +void IOMapSerialize::saveItem(PropWriteStream& stream, const ItemPtr& item) { - const Container* container = item->getContainer(); + const auto container = item->getContainer(); // Write ID & props stream.write(item->getID()); @@ -215,16 +211,16 @@ 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 TilePtr& tile) { - const TileItemVector* tileItems = tile->getItemList(); + const auto tileItems = tile->getItemList(); if (!tileItems) { return; } - std::forward_list items; + std::forward_list items; uint16_t count = 0; - for (Item* item : *tileItems) { + for (auto item : *tileItems) { const ItemType& it = Item::items[item->getID()]; // Note that these are NEGATED, ie. these are the items that will be saved. @@ -243,7 +239,7 @@ void IOMapSerialize::saveTile(PropWriteStream& stream, const Tile* tile) stream.write(tilePosition.z); stream.write(count); - for (const Item* item : items) { + for (const auto item : items) { saveItem(stream, item); } } @@ -259,8 +255,7 @@ bool IOMapSerialize::loadHouseInfo() } do { - House* house = g_game.map.houses.getHouse(result->getNumber("id")); - if (house) { + if (const auto house = g_game.map.houses.getHouse(result->getNumber("id"))) { house->setOwner(result->getNumber("owner"), false); house->setPaidUntil(result->getNumber("paid")); house->setPayRentWarnings(result->getNumber("warnings")); @@ -270,8 +265,7 @@ bool IOMapSerialize::loadHouseInfo() result = db.storeQuery("SELECT `house_id`, `listid`, `list` FROM `house_lists`"); if (result) { do { - House* house = g_game.map.houses.getHouse(result->getNumber("house_id")); - if (house) { + if (const auto house = g_game.map.houses.getHouse(result->getNumber("house_id"))) { house->setAccessList(result->getNumber("listid"), result->getString("list")); } } while (result->next()); @@ -292,10 +286,9 @@ bool IOMapSerialize::saveHouseInfo() return false; } - for (const auto& it : g_game.map.houses.getHouses()) { - House* house = it.second; - DBResult_ptr result = db.storeQuery(fmt::format("SELECT `id` FROM `houses` WHERE `id` = {:d}", house->getId())); - if (result) { + for (const auto& val : g_game.map.houses.getHouses() | std::views::values) { + const auto house = val; + if (DBResult_ptr result = db.storeQuery(fmt::format("SELECT `id` FROM `houses` WHERE `id` = {:d}", house->getId()))) { db.executeQuery(fmt::format("UPDATE `houses` SET `owner` = {:d}, `paid` = {:d}, `warnings` = {:d}, `name` = {:s}, `town_id` = {:d}, `rent` = {:d}, `size` = {:d}, `beds` = {:d} WHERE `id` = {:d}", house->getOwner(), house->getPaidUntil(), house->getPayRentWarnings(), db.escapeString(house->getName()), house->getTownId(), house->getRent(), house->getTiles().size(), house->getBedCount(), house->getId())); } else { db.executeQuery(fmt::format("INSERT INTO `houses` (`id`, `owner`, `paid`, `warnings`, `name`, `town_id`, `rent`, `size`, `beds`) VALUES ({:d}, {:d}, {:d}, {:d}, {:s}, {:d}, {:d}, {:d}, {:d})", house->getId(), house->getOwner(), house->getPaidUntil(), house->getPayRentWarnings(), db.escapeString(house->getName()), house->getTownId(), house->getRent(), house->getTiles().size(), house->getBedCount())); @@ -304,8 +297,8 @@ bool IOMapSerialize::saveHouseInfo() DBInsert stmt("INSERT INTO `house_lists` (`house_id` , `listid` , `list`) VALUES "); - for (const auto& it : g_game.map.houses.getHouses()) { - House* house = it.second; + for (const auto& val : g_game.map.houses.getHouses() | std::views::values) { + const auto house = val; std::string listText; if (house->getAccessList(GUEST_LIST, listText) && !listText.empty()) { @@ -324,7 +317,7 @@ bool IOMapSerialize::saveHouseInfo() listText.clear(); } - for (Door* door : house->getDoors()) { + for (const auto door : house->getDoors()) { if (door->getAccessList(listText) && !listText.empty()) { if (!stmt.addRow(fmt::format("{:d}, {:d}, {:s}", house->getId(), door->getDoorId(), db.escapeString(listText)))) { return false; @@ -362,7 +355,7 @@ bool IOMapSerialize::saveHouse(House* house) DBInsert stmt("INSERT INTO `tile_store` (`house_id`, `data`) VALUES "); PropWriteStream stream; - for (HouseTile* tile : house->getTiles()) { + for (const auto tile : house->getTiles()) { saveTile(stream, tile); if (auto attributes = stream.getStream(); attributes.size() > 0) { diff --git a/src/iomapserialize.h b/src/iomapserialize.h index b6b2e055..3a5b8a6a 100644 --- a/src/iomapserialize.h +++ b/src/iomapserialize.h @@ -19,11 +19,11 @@ class IOMapSerialize static bool saveHouse(House* house); private: - static void saveItem(PropWriteStream& stream, const Item* item); - static void saveTile(PropWriteStream& stream, const Tile* tile); + static void saveItem(PropWriteStream& stream, const ItemPtr& item); + static void saveTile(PropWriteStream& stream, const TilePtr& tile); - static bool loadContainer(PropStream& propStream, Container* container); - static bool loadItem(PropStream& propStream, Cylinder* parent); + static bool loadContainer(PropStream& propStream, const ContainerPtr& container); + static bool loadItem(PropStream& propStream, const CylinderPtr& parent); }; #endif diff --git a/src/iomarket.cpp b/src/iomarket.cpp index 1bc31965..b1a06cb8 100644 --- a/src/iomarket.cpp +++ b/src/iomarket.cpp @@ -95,7 +95,7 @@ HistoryMarketOfferList IOMarket::getOwnHistory(MarketAction_t action, uint32_t p return offerList; } -void IOMarket::processExpiredOffers(DBResult_ptr result, bool) +void IOMarket::processExpiredOffers(const DBResult_ptr& result, bool) { if (!result) { return; @@ -114,11 +114,10 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) continue; } - Player* player = g_game.getPlayerByGUID(playerId); + auto player = g_game.getPlayerByGUID(playerId); if (!player) { - player = new Player(nullptr); + player = std::make_shared(nullptr); if (!IOLoginData::loadPlayerById(player, playerId)) { - delete player; continue; } } @@ -127,9 +126,8 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) uint16_t tmpAmount = amount; 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) { - delete item; + auto item = Item::CreateItem(itemType.id, stackCount); + if (CylinderPtr inbox = player->getInbox(); g_game.internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { break; } @@ -144,9 +142,8 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) } for (uint16_t i = 0; i < amount; ++i) { - Item* item = Item::CreateItem(itemType.id, subType); - if (g_game.internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { - delete item; + auto item = Item::CreateItem(itemType.id, subType); + if (CylinderPtr inbox = player->getInbox(); g_game.internalAddItem(inbox, item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { break; } } @@ -154,13 +151,11 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) if (player->isOffline()) { IOLoginData::savePlayer(player); - delete player; } } else { uint64_t totalPrice = result->getNumber("price") * amount; - Player* player = g_game.getPlayerByGUID(playerId); - if (player) { + if (const auto player = g_game.getPlayerByGUID(playerId)) { player->setBankBalance(player->getBankBalance() + totalPrice); } else { IOLoginData::increaseBankBalance(playerId, totalPrice); diff --git a/src/iomarket.h b/src/iomarket.h index 9f6ebf8a..314527a0 100644 --- a/src/iomarket.h +++ b/src/iomarket.h @@ -19,7 +19,7 @@ class IOMarket static MarketOfferList getOwnOffers(MarketAction_t action, uint32_t playerId); static HistoryMarketOfferList getOwnHistory(MarketAction_t action, uint32_t playerId); - static void processExpiredOffers(DBResult_ptr result, bool); + static void processExpiredOffers(const DBResult_ptr& result, bool); static void checkExpiredOffers(); static uint32_t getPlayerOfferCount(uint32_t playerId); diff --git a/src/item.cpp b/src/item.cpp index c9d5172e..e2721fb4 100644 --- a/src/item.cpp +++ b/src/item.cpp @@ -25,84 +25,80 @@ extern Events* g_events; Items Item::items; // Description Utility Functions -void handleRuneDescription(std::ostringstream& s, const ItemType& it, const Item* item, int32_t& subType); -void handleWeaponDistanceDescription(std::ostringstream& s, const ItemType& it, const Item* item, int32_t& subType); -void handleWeaponMeleeDescription(std::ostringstream& s, const ItemType& it, const Item* item, int32_t& subType, bool& begin); +void handleRuneDescription(std::ostringstream& s, const ItemType& it, const ItemConstPtr& item, int32_t& subType); +void handleWeaponDistanceDescription(std::ostringstream& s, const ItemType& it, const ItemConstPtr& item, int32_t& subType); +void handleWeaponMeleeDescription(std::ostringstream& s, const ItemType& it, const ItemConstPtr& item, int32_t& subType, bool& begin); void handleSkillsDescription(std::ostringstream& s, const ItemType& it, bool& begin); void handleStatsDescription(std::ostringstream& s, const ItemType& it, bool& begin); void handleStatsPercentDescription(std::ostringstream& s, const ItemType& it, bool& begin); void handleAbilitiesDescription(std::ostringstream& s, const ItemType& it, bool& begin); void handleMiscDescription(std::ostringstream& s, const ItemType& it, bool& begin); -Item* Item::CreateItem(const uint16_t type, uint16_t count /*= 0*/) +ItemPtr Item::CreateItem(const uint16_t type, uint16_t count /*= 0*/) { - Item* newItem = nullptr; - - const ItemType& it = Item::items[type]; - if (it.group == ITEM_GROUP_DEPRECATED) { - return nullptr; - } - - if (it.stackable && count == 0) { - count = 1; - } - - if (it.id != 0) { - if (it.isDepot()) { - newItem = new DepotLocker(type); - } else if (it.isRewardChest()) { - newItem = new RewardChest(type); - } else if (it.isContainer()) { - newItem = new Container(type); - } else if (it.isTeleport()) { - newItem = new Teleport(type); - } else if (it.isMagicField()) { - newItem = new MagicField(type); - } else if (it.isDoor()) { - newItem = new Door(type); - } else if (it.isTrashHolder()) { - newItem = new TrashHolder(type); - } else if (it.isMailbox()) { - newItem = new Mailbox(type); - } else if (it.isBed()) { - newItem = new BedItem(type); - } else if (it.id >= 2210 && it.id <= 2212) { // magic rings - newItem = new Item(type - 3, count); - } else if (it.id == 2215 || it.id == 2216) { // magic rings - newItem = new Item(type - 2, count); - } else if (it.id >= 2202 && it.id <= 2206) { // magic rings - newItem = new Item(type - 37, count); - } else if (it.id == 2640) { // soft boots - newItem = new Item(6132, count); - } else if (it.id == 6301) { // death ring - newItem = new Item(6300, count); - } else if (it.id == 18528) { // prismatic ring - newItem = new Item(18408, count); - } else { - newItem = new Item(type, count); - } - - - - newItem->incrementReferenceCounter(); - } - - return newItem; -} - -Container* Item::CreateItemAsContainer(const uint16_t type, uint16_t size) + const ItemType& it = Item::items[type]; + if (it.group == ITEM_GROUP_DEPRECATED) { + return nullptr; + } + + if (it.stackable && count == 0) { + count = 1; + } + + if (it.id == 0) { + return nullptr; + } + + ItemPtr newItem; + + if (it.isDepot()) { + return std::make_shared(type); + } else if (it.isRewardChest()) { + return std::make_shared(type); + } else if (it.isContainer()) { + return std::make_shared(type); + } else if (it.isTeleport()) { + return std::make_shared(type); + } else if (it.isMagicField()) { + return std::make_shared(type); + } else if (it.isDoor()) { + return std::make_shared(type); + } else if (it.isTrashHolder()) { + return std::make_shared(type); + } else if (it.isMailbox()) { + return std::make_shared(type); + } else if (it.isBed()) { + return std::make_shared(type); + } else if (it.id >= 2210 && it.id <= 2212) { // magic rings + return std::make_shared(type - 3, count); + } else if (it.id == 2215 || it.id == 2216) { // magic rings + return std::make_shared(type - 2, count); + } else if (it.id >= 2202 && it.id <= 2206) { // magic rings + return std::make_shared(type - 37, count); + } else if (it.id == 2640) { // soft boots + return std::make_shared(6132, count); + } else if (it.id == 6301) { // death ring + return std::make_shared(6300, count); + } else if (it.id == 18528) { // prismatic ring + return std::make_shared(18408, count); + } else { + return std::make_shared(type, count); + } + return nullptr; +} + +ContainerPtr Item::CreateItemAsContainer(const uint16_t type, uint16_t size) { const ItemType& it = Item::items[type]; if (it.id == 0 || it.group == ITEM_GROUP_DEPRECATED || it.stackable || it.useable || it.moveable || it.pickupable || it.isDepot() || it.isSplash() || it.isDoor()) { return nullptr; } - Container* newItem = new Container(type, size); - newItem->incrementReferenceCounter(); + auto newItem = std::make_shared(type, size); return newItem; } -Item* Item::CreateItem(PropStream& propStream) +ItemPtr Item::CreateItem(PropStream& propStream) { uint16_t id; if (!propStream.read(id)) { @@ -181,13 +177,12 @@ Item::Item(const Item& i) : } } -Item* Item::clone() const +ItemPtr Item::clone() const { - Item* item = Item::CreateItem(id, count); + auto item = Item::CreateItem(id, count); if (attributes) { item->attributes.reset(new ItemAttributes(*attributes)); if (item->getDuration() > 0) { - item->incrementReferenceCounter(); item->setDecaying(DECAYING_TRUE); g_game.toDecayItems.push_front(item); } @@ -195,7 +190,7 @@ Item* Item::clone() const return item; } -bool Item::equals(const Item* otherItem) const +bool Item::equals(const ItemConstPtr& otherItem) const { if (!otherItem || id != otherItem->id) { return false; @@ -255,10 +250,10 @@ void Item::setDefaultSubtype() void Item::onRemoved() { - ScriptEnvironment::removeTempItem(this); + ScriptEnvironment::removeTempItem(std::dynamic_pointer_cast(shared_from_this())); if (hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { - g_game.removeUniqueItem(getUniqueId()); + g_game.removeUniqueItem(getUniqueId()); } } @@ -283,10 +278,10 @@ void Item::setID(uint16_t newid) } } -Cylinder* Item::getTopParent() +CylinderPtr Item::getTopParent() { - Cylinder* aux = getParent(); - Cylinder* prevaux = dynamic_cast(this); + CylinderPtr aux = getParent(); + CylinderPtr prevaux = std::dynamic_pointer_cast(shared_from_this()); if (!aux) { return prevaux; } @@ -302,43 +297,15 @@ Cylinder* Item::getTopParent() return aux; } -const Cylinder* Item::getTopParent() const -{ - const Cylinder* aux = getParent(); - const Cylinder* prevaux = dynamic_cast(this); - if (!aux) { - return prevaux; - } - while (aux->getParent() != nullptr) { - prevaux = aux; - aux = aux->getParent(); - } - - if (prevaux) { - return prevaux; - } - return aux; -} - -Tile* Item::getTile() +TilePtr Item::getTile() { - Cylinder* cylinder = getTopParent(); + auto cylinder = getTopParent(); //get root cylinder if (cylinder && cylinder->getParent()) { cylinder = cylinder->getParent(); } - return dynamic_cast(cylinder); -} - -const Tile* Item::getTile() const -{ - const Cylinder* cylinder = getTopParent(); - //get root cylinder - if (cylinder && cylinder->getParent()) { - cylinder = cylinder->getParent(); - } - return dynamic_cast(cylinder); + return cylinder->getTile(); } uint16_t Item::getSubType() const @@ -354,9 +321,9 @@ uint16_t Item::getSubType() const return count; } -Player* Item::getHoldingPlayer() const +PlayerPtr Item::getHoldingPlayer() { - Cylinder* p = getParent(); + CylinderPtr p = getParent(); while (p) { if (p->getCreature()) { return p->getCreature()->getPlayer(); @@ -1041,7 +1008,7 @@ uint32_t Item::getWeight() const } std::string Item::getDescription(const ItemType& it, int32_t lookDistance, - const Item* item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) + const ItemConstPtr& item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { const std::string* text = nullptr; @@ -1336,10 +1303,10 @@ std::string Item::getDescription(const ItemType& it, int32_t lookDistance, std::string Item::getDescription(int32_t lookDistance) const { const ItemType& it = items[id]; - return getDescription(it, lookDistance, this); + return getDescription(it, lookDistance, getItem()); } -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 ItemConstPtr& item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { if (item) { subType = item->getSubType(); @@ -1377,7 +1344,7 @@ std::string Item::getNameDescription(const ItemType& it, const Item* item /*= nu std::string Item::getNameDescription() const { const ItemType& it = items[id]; - return getNameDescription(it, this); + return getNameDescription(it, getItem()); } std::string Item::getWeightDescription(const ItemType& it, uint32_t weight, uint32_t count /*= 1*/) @@ -1424,12 +1391,12 @@ void Item::setUniqueId(uint16_t n) return; } - if (g_game.addUniqueItem(n, this)) { + if (g_game.addUniqueItem(n, getItem())) { getAttributes()->setUniqueId(n); } } -bool Item::canDecay() const +bool Item::canDecay() { if (isRemoved()) { return false; @@ -1573,7 +1540,7 @@ ItemAttributes::Attribute& ItemAttributes::getAttr(itemAttrTypes type) void Item::startDecaying() { - g_game.startDecay(this); + g_game.startDecay(getItem()); } bool Item::hasMarketAttributes() const @@ -1637,11 +1604,10 @@ const bool& ItemAttributes::CustomAttribute::get() { return emptyBool; } -const bool Item::isEquipped() const { - Player* player = getHoldingPlayer(); - if (player) { +const bool Item::isEquipped() { + if (auto player = getHoldingPlayer()) { for (uint32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; slot++) { - if(player->getInventoryItem(slot) == this) { + if(player->getInventoryItem(slot).get() == this) { return true; } } @@ -1661,7 +1627,7 @@ uint16_t Item::getFreeImbuementSlots() const return (imbuementSlots - (static_cast(imbuements.size()))); } -bool Item::canImbue() const +bool Item::canImbue() { // todo: known bug, stackables are imbueable, but no protection is offered for someone copying items with imbuements, // unless the stackables are items created a new, in that case, the imbuements don't carry over when broken down, @@ -1736,7 +1702,7 @@ bool Item::removeImbuementSlots(const uint16_t amount, const bool destroyImbues) bool Item::hasImbuementType(const ImbuementType imbuetype) const { // item:hasImbuementType(type) - return std::any_of(imbuements.begin(), imbuements.end(), [imbuetype](std::shared_ptr elem) { + return std::any_of(imbuements.begin(), imbuements.end(), [imbuetype](const std::shared_ptr& elem) { return elem->imbuetype == imbuetype; }); } @@ -1759,14 +1725,14 @@ bool Item::hasImbuements() const bool Item::addImbuement(std::shared_ptr imbuement, bool created) { // item:addImbuement(imbuement) -- returns true if it successfully adds the imbuement - if (canImbue() && getFreeImbuementSlots() > 0 && g_events->eventItemOnImbue(this, imbuement, created)) + if (canImbue() && getFreeImbuementSlots() > 0 && g_events->eventItemOnImbue(getItem(), imbuement, created)) { imbuements.push_back(imbuement); for (auto imbue : imbuements) { if (imbue == imbuement) { - Player* player = getHoldingPlayer(); + auto player = getHoldingPlayer(); if (player && isEquipped()) { player->addImbuementEffect(imbue); } @@ -1777,19 +1743,19 @@ bool Item::addImbuement(std::shared_ptr imbuement, bool created) return false; } -bool Item::removeImbuement(std::shared_ptr imbuement, bool decayed) +bool Item::removeImbuement(const std::shared_ptr& imbuement, bool decayed) { // item:removeImbuement(imbuement) -- returns true if it found and removed the imbuement for (auto imbue : imbuements) { if (imbue == imbuement) { - Player* player = getHoldingPlayer(); + auto player = getHoldingPlayer(); if (player && isEquipped()) { player->removeImbuementEffect(imbue); } - g_events->eventItemOnRemoveImbue(this, imbuement->imbuetype, decayed); - imbuements.erase(std::remove(imbuements.begin(), imbuements.end(), imbue), imbuements.end()); + g_events->eventItemOnRemoveImbue(getItem(), imbuement->imbuetype, decayed); + std::erase(imbuements, imbue); return true; } @@ -1806,14 +1772,14 @@ const std::vector>& Item::getImbuements() const return imbuements; } -const bool Item::addAugment(std::shared_ptr& augment) +const bool Item::addAugment(const std::shared_ptr& augment) { - if (std::find(augments.begin(), augments.end(), augment) != augments.end()) { + if (std::ranges::find(augments, augment) != augments.end()) { return false; } augments.push_back(augment); - g_events->eventItemOnAugment(this, augment); + g_events->eventItemOnAugment(getItem(), augment); return true; } @@ -1821,7 +1787,7 @@ const bool Item::addAugment(std::string_view augmentName) { if (auto augment = Augments::GetAugment(augmentName)) { augments.emplace_back(augment); - g_events->eventItemOnAugment(this, augment); + g_events->eventItemOnAugment(std::dynamic_pointer_cast(shared_from_this()), augment); return true; } return false; @@ -1830,10 +1796,10 @@ const bool Item::addAugment(std::string_view augmentName) const bool Item::removeAugment(std::shared_ptr& augment) { auto originalSize = augments.size(); - augments.erase(std::remove(augments.begin(), augments.end(), augment), augments.end()); - auto removed = (augments.size() - originalSize) > 0 ? true : false; + std::erase(augments, augment); + const auto removed = (augments.size() - originalSize) > 0 ? true : false; if (removed) { - g_events->eventItemOnRemoveAugment(this, augment); + g_events->eventItemOnRemoveAugment(std::dynamic_pointer_cast(shared_from_this()), augment); } return removed; } @@ -1841,14 +1807,14 @@ const bool Item::removeAugment(std::shared_ptr& augment) const bool Item::removeAugment(std::string_view name) { auto originalSize = augments.size(); - augments.erase(std::remove_if(augments.begin(), augments.end(), - [this, &name](const std::shared_ptr& augment) { - auto match = augment->getName() == name; - if (match) { - g_events->eventItemOnRemoveAugment(this, augment); - } - return match; - }), augments.end()); + std::erase_if(augments, + [this, &name](const std::shared_ptr& augment) { + const auto match = augment->getName() == name; + if (match) { + g_events->eventItemOnRemoveAugment(std::dynamic_pointer_cast(shared_from_this()), augment); + } + return match; + }); return augments.size() < originalSize; } @@ -1904,7 +1870,7 @@ void Item::decayImbuements(bool infight) { } } -void handleRuneDescription(std::ostringstream& s, const ItemType& it, const Item* item, int32_t& subType) { +void handleRuneDescription(std::ostringstream& s, const ItemType& it, const ItemConstPtr& item, int32_t& subType) { if (RuneSpell* rune = g_spells->getRuneSpell(it.id)) { int32_t tmpSubType = subType; if (item) { @@ -1958,7 +1924,7 @@ void handleRuneDescription(std::ostringstream& s, const ItemType& it, const Item } } -void handleWeaponDistanceDescription(std::ostringstream& s, const ItemType& it, const Item* item, int32_t& subType) { +void handleWeaponDistanceDescription(std::ostringstream& s, const ItemType& it, const ItemConstPtr& item, int32_t& subType) { s << " (Range:" << static_cast(item ? item->getShootRange() : it.shootRange); int32_t attack; @@ -1980,7 +1946,7 @@ void handleWeaponDistanceDescription(std::ostringstream& s, const ItemType& it, } } -void handleWeaponMeleeDescription(std::ostringstream& s, const ItemType& it, const Item* item, int32_t& subType, bool& begin) { +void handleWeaponMeleeDescription(std::ostringstream& s, const ItemType& it, const ItemConstPtr& item, int32_t& subType, bool& begin) { int32_t attack, defense, extraDefense; if (item) { attack = item->getAttack(); diff --git a/src/item.h b/src/item.h index bf0bf8c6..7d7aa06d 100644 --- a/src/item.h +++ b/src/item.h @@ -15,6 +15,7 @@ #include #include + class Creature; class Player; class Container; @@ -26,6 +27,27 @@ class Door; class MagicField; class BedItem; +using DepotPtr = std::shared_ptr; +using DepotConstPtr = std::shared_ptr; + +using TeleportPtr = std::shared_ptr; +using TeleportConstPtr = std::shared_ptr; + +using TrashHolderPtr = std::shared_ptr; +using TrashHolderConstPtr = std::shared_ptr; + +using MailboxPtr = std::shared_ptr; +using MailboxConstPtr = std::shared_ptr; + +using DoorPtr = std::shared_ptr; +using DoorConstPtr = std::shared_ptr; + +using MagicFieldPtr = std::shared_ptr; +using MagicFieldConstPtr = std::shared_ptr; + +using BedItemPtr = std::shared_ptr; +using BedItemConstPtr = std::shared_ptr; + enum ITEMPROPERTY { CONST_PROP_BLOCKSOLID = 0, CONST_PROP_HASHEIGHT, @@ -114,6 +136,7 @@ class ItemAttributes void setSpecialDescription(const std::string& desc) { setStrAttr(ITEM_ATTRIBUTE_DESCRIPTION, desc); } + const std::string& getSpecialDescription() const { return getStrAttr(ITEM_ATTRIBUTE_DESCRIPTION); } @@ -121,9 +144,11 @@ class ItemAttributes void setText(const std::string& text) { setStrAttr(ITEM_ATTRIBUTE_TEXT, text); } + void resetText() { removeAttribute(ITEM_ATTRIBUTE_TEXT); } + const std::string& getText() const { return getStrAttr(ITEM_ATTRIBUTE_TEXT); } @@ -131,9 +156,11 @@ class ItemAttributes void setDate(int32_t n) { setIntAttr(ITEM_ATTRIBUTE_DATE, n); } + void resetDate() { removeAttribute(ITEM_ATTRIBUTE_DATE); } + time_t getDate() const { return static_cast(getIntAttr(ITEM_ATTRIBUTE_DATE)); } @@ -141,9 +168,11 @@ class ItemAttributes void setWriter(const std::string& writer) { setStrAttr(ITEM_ATTRIBUTE_WRITER, writer); } + void resetWriter() { removeAttribute(ITEM_ATTRIBUTE_WRITER); } + const std::string& getWriter() const { return getStrAttr(ITEM_ATTRIBUTE_WRITER); } @@ -151,6 +180,7 @@ class ItemAttributes void setActionId(uint16_t n) { setIntAttr(ITEM_ATTRIBUTE_ACTIONID, n); } + uint16_t getActionId() const { return static_cast(getIntAttr(ITEM_ATTRIBUTE_ACTIONID)); } @@ -158,6 +188,7 @@ class ItemAttributes void setUniqueId(uint16_t n) { setIntAttr(ITEM_ATTRIBUTE_UNIQUEID, n); } + uint16_t getUniqueId() const { return static_cast(getIntAttr(ITEM_ATTRIBUTE_UNIQUEID)); } @@ -165,6 +196,7 @@ class ItemAttributes void setCharges(uint16_t n) { setIntAttr(ITEM_ATTRIBUTE_CHARGES, n); } + uint16_t getCharges() const { return static_cast(getIntAttr(ITEM_ATTRIBUTE_CHARGES)); } @@ -172,6 +204,7 @@ class ItemAttributes void setFluidType(uint16_t n) { setIntAttr(ITEM_ATTRIBUTE_FLUIDTYPE, n); } + uint16_t getFluidType() const { return static_cast(getIntAttr(ITEM_ATTRIBUTE_FLUIDTYPE)); } @@ -179,6 +212,7 @@ class ItemAttributes void setOwner(uint32_t owner) { setIntAttr(ITEM_ATTRIBUTE_OWNER, owner); } + uint32_t getOwner() const { return getIntAttr(ITEM_ATTRIBUTE_OWNER); } @@ -186,6 +220,7 @@ class ItemAttributes void setCorpseOwner(uint32_t corpseOwner) { setIntAttr(ITEM_ATTRIBUTE_CORPSEOWNER, corpseOwner); } + uint32_t getCorpseOwner() const { return getIntAttr(ITEM_ATTRIBUTE_CORPSEOWNER); } @@ -193,9 +228,11 @@ class ItemAttributes void setDuration(int32_t time) { setIntAttr(ITEM_ATTRIBUTE_DURATION, time); } + void decreaseDuration(int32_t time) { increaseIntAttr(ITEM_ATTRIBUTE_DURATION, -time); } + uint32_t getDuration() const { return getIntAttr(ITEM_ATTRIBUTE_DURATION); } @@ -377,10 +414,12 @@ class ItemAttributes memset(&value, 0, sizeof(value)); } } + Attribute(Attribute&& attribute) : value(attribute.value), type(attribute.type) { memset(&attribute.value, 0, sizeof(value)); attribute.type = ITEM_ATTRIBUTE_NONE; } + ~Attribute() { if (ItemAttributes::isStrAttrType(type)) { delete value.string; @@ -388,10 +427,12 @@ class ItemAttributes delete value.custom; } } + Attribute& operator=(Attribute other) { Attribute::swap(*this, other); return *this; } + Attribute& operator=(Attribute&& other) { if (this != &other) { if (ItemAttributes::isStrAttrType(type)) { @@ -503,13 +544,13 @@ class ItemAttributes return false; } - const static uint32_t intAttributeTypes = ITEM_ATTRIBUTE_ACTIONID | ITEM_ATTRIBUTE_UNIQUEID | ITEM_ATTRIBUTE_DATE + static constexpr uint32_t intAttributeTypes = ITEM_ATTRIBUTE_ACTIONID | ITEM_ATTRIBUTE_UNIQUEID | ITEM_ATTRIBUTE_DATE | ITEM_ATTRIBUTE_WEIGHT | ITEM_ATTRIBUTE_ATTACK | ITEM_ATTRIBUTE_DEFENSE | ITEM_ATTRIBUTE_EXTRADEFENSE | ITEM_ATTRIBUTE_ARMOR | ITEM_ATTRIBUTE_HITCHANCE | ITEM_ATTRIBUTE_SHOOTRANGE | ITEM_ATTRIBUTE_OWNER | ITEM_ATTRIBUTE_DURATION | ITEM_ATTRIBUTE_DECAYSTATE | ITEM_ATTRIBUTE_CORPSEOWNER | ITEM_ATTRIBUTE_CHARGES | ITEM_ATTRIBUTE_FLUIDTYPE | ITEM_ATTRIBUTE_DOORID | ITEM_ATTRIBUTE_DECAYTO | ITEM_ATTRIBUTE_WRAPID | ITEM_ATTRIBUTE_STOREITEM | ITEM_ATTRIBUTE_ATTACK_SPEED | ITEM_ATTRIBUTE_REWARDID; - const static uint32_t stringAttributeTypes = ITEM_ATTRIBUTE_DESCRIPTION | ITEM_ATTRIBUTE_TEXT | ITEM_ATTRIBUTE_WRITER + static constexpr uint32_t stringAttributeTypes = ITEM_ATTRIBUTE_DESCRIPTION | ITEM_ATTRIBUTE_TEXT | ITEM_ATTRIBUTE_WRITER | ITEM_ATTRIBUTE_NAME | ITEM_ATTRIBUTE_ARTICLE | ITEM_ATTRIBUTE_PLURALNAME | ITEM_ATTRIBUTE_CLASSIFICATION | ITEM_ATTRIBUTE_TIER; public: @@ -530,67 +571,80 @@ class ItemAttributes friend class Item; }; -class Item : virtual public Thing +class Item : virtual public Thing, public SharedObject { public: //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 ItemPtr CreateItem(const uint16_t type, uint16_t count = 0); + static ContainerPtr CreateItemAsContainer(const uint16_t type, uint16_t size); + static ItemPtr CreateItem(PropStream& propStream); static Items items; // Constructor for items - Item(const uint16_t type, uint16_t count = 0); + explicit Item(const uint16_t type, uint16_t count = 0); Item(const Item& i); - virtual Item* clone() const; + virtual ItemPtr clone() const; - virtual ~Item() = default; + ~Item() = default; // non-assignable Item& operator=(const Item&) = delete; - bool equals(const Item* otherItem) const; - - Item* getItem() override final { - return this; + bool equals(const ItemConstPtr& otherItem) const; + + ItemPtr getItem() override final { + return dynamic_shared_this(); } - const Item* getItem() const override final { - return this; + + ItemConstPtr getItem() const override final { + return dynamic_shared_this(); } - virtual Teleport* getTeleport() { + + virtual TeleportPtr getTeleport() { return nullptr; } - virtual const Teleport* getTeleport() const { + + virtual TeleportConstPtr getTeleport() const { return nullptr; } - virtual TrashHolder* getTrashHolder() { + + virtual TrashHolderPtr getTrashHolder() { return nullptr; } - virtual const TrashHolder* getTrashHolder() const { + + virtual TrashHolderConstPtr getTrashHolder() const { return nullptr; } - virtual Mailbox* getMailbox() { + + virtual MailboxPtr getMailbox() { return nullptr; } - virtual const Mailbox* getMailbox() const { + + virtual MailboxConstPtr getMailbox() const { return nullptr; } - virtual Door* getDoor() { + + virtual DoorPtr getDoor() { return nullptr; } - virtual const Door* getDoor() const { + + virtual DoorConstPtr getDoor() const { return nullptr; } - virtual MagicField* getMagicField() { + + virtual MagicFieldPtr getMagicField() { return nullptr; } - virtual const MagicField* getMagicField() const { + + virtual MagicFieldConstPtr getMagicField() const { return nullptr; } - virtual BedItem* getBed() { + + virtual BedItemPtr getBed() { return nullptr; } - virtual const BedItem* getBed() const { + + virtual BedItemConstPtr getBed() const { return nullptr; } @@ -612,18 +666,21 @@ class Item : virtual public Thing } return attributes->getIntAttr(type); } + void setIntAttr(itemAttrTypes type, int64_t value) { getAttributes()->setIntAttr(type, value); } + void increaseIntAttr(itemAttrTypes type, int64_t value) { getAttributes()->increaseIntAttr(type, value); } - void removeAttribute(itemAttrTypes type) { + void removeAttribute(itemAttrTypes type) const { if (attributes) { attributes->removeAttribute(type); } } + bool hasAttribute(itemAttrTypes type) const { if (!attributes) { return false; @@ -680,9 +737,10 @@ class Item : virtual public Thing setStrAttr(ITEM_ATTRIBUTE_TEXT, text); } - void resetText() { + void resetText() const { removeAttribute(ITEM_ATTRIBUTE_TEXT); } + const std::string& getText() const { return getStrAttr(ITEM_ATTRIBUTE_TEXT); } @@ -690,9 +748,12 @@ class Item : virtual public Thing void setDate(int32_t n) { setIntAttr(ITEM_ATTRIBUTE_DATE, n); } - void resetDate() { + + void resetDate() const + { removeAttribute(ITEM_ATTRIBUTE_DATE); } + time_t getDate() const { return static_cast(getIntAttr(ITEM_ATTRIBUTE_DATE)); } @@ -701,9 +762,10 @@ class Item : virtual public Thing setStrAttr(ITEM_ATTRIBUTE_WRITER, writer); } - void resetWriter() { + void resetWriter() const { removeAttribute(ITEM_ATTRIBUTE_WRITER); } + const std::string& getWriter() const { return getStrAttr(ITEM_ATTRIBUTE_WRITER); } @@ -715,6 +777,7 @@ class Item : virtual public Thing setIntAttr(ITEM_ATTRIBUTE_ACTIONID, n); } + uint16_t getActionId() const { if (!attributes) { return 0; @@ -732,6 +795,7 @@ class Item : virtual public Thing void setCharges(uint16_t n) { setIntAttr(ITEM_ATTRIBUTE_CHARGES, n); } + uint16_t getCharges() const { if (!attributes) { return 0; @@ -742,6 +806,7 @@ class Item : virtual public Thing void setFluidType(uint16_t n) { setIntAttr(ITEM_ATTRIBUTE_FLUIDTYPE, n); } + uint16_t getFluidType() const { if (!attributes) { return 0; @@ -752,6 +817,7 @@ class Item : virtual public Thing void setOwner(uint32_t owner) { setIntAttr(ITEM_ATTRIBUTE_OWNER, owner); } + uint32_t getOwner() const { if (!attributes) { return 0; @@ -762,6 +828,7 @@ class Item : virtual public Thing void setCorpseOwner(uint32_t corpseOwner) { setIntAttr(ITEM_ATTRIBUTE_CORPSEOWNER, corpseOwner); } + uint32_t getCorpseOwner() const { if (!attributes) { return 0; @@ -772,9 +839,11 @@ class Item : virtual public Thing void setDuration(int32_t time) { setIntAttr(ITEM_ATTRIBUTE_DURATION, time); } + void decreaseDuration(int32_t time) { increaseIntAttr(ITEM_ATTRIBUTE_DURATION, -time); } + uint32_t getDuration() const { if (!attributes) { return 0; @@ -785,6 +854,7 @@ class Item : virtual public Thing void setDecaying(ItemDecayState_t decayState) { setIntAttr(ITEM_ATTRIBUTE_DECAYSTATE, decayState); } + ItemDecayState_t getDecaying() const { if (!attributes) { return DECAYING_FALSE; @@ -802,6 +872,7 @@ class Item : virtual public Thing void setDecayTo(int32_t decayTo) { setIntAttr(ITEM_ATTRIBUTE_DECAYTO, decayTo); } + int32_t getDecayTo() const { if (hasAttribute(ITEM_ATTRIBUTE_DECAYTO)) { return getIntAttr(ITEM_ATTRIBUTE_DECAYTO); @@ -809,11 +880,11 @@ class Item : virtual public Thing return items[id].decayTo; } - const bool isEquipped() const; + const bool isEquipped(); void decayImbuements(bool infight); - 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 getDescription(const ItemType& it, int32_t lookDistance, const ItemConstPtr& item = nullptr, int32_t subType = -1, bool addArticle = true); + static std::string getNameDescription(const ItemType& it, const ItemConstPtr& 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; @@ -831,6 +902,7 @@ class Item : virtual public Thing bool isPushable() const override final { return isMoveable(); } + int32_t getThrowRange() const override final { return (isPickupable() ? 15 : 2); } @@ -838,20 +910,24 @@ class Item : virtual public Thing uint16_t getID() const { return id; } + uint16_t getClientID() const { return items[id].clientId; } + void setID(uint16_t newid); // Returns the player that is holding this item in his inventory - Player* getHoldingPlayer() const; + PlayerPtr getHoldingPlayer(); WeaponType_t getWeaponType() const { return items[id].weaponType; } + Ammo_t getAmmoType() const { return items[id].ammoType; } + uint8_t getShootRange() const { if (hasAttribute(ITEM_ATTRIBUTE_SHOOTRANGE)) { return getIntAttr(ITEM_ATTRIBUTE_SHOOTRANGE); @@ -860,45 +936,53 @@ class Item : virtual public Thing } virtual uint32_t getWeight() const; + uint32_t getBaseWeight() const { if (hasAttribute(ITEM_ATTRIBUTE_WEIGHT)) { return getIntAttr(ITEM_ATTRIBUTE_WEIGHT); } return items[id].weight; } + int32_t getAttack() const { if (hasAttribute(ITEM_ATTRIBUTE_ATTACK)) { return getIntAttr(ITEM_ATTRIBUTE_ATTACK); } return items[id].attack; } + uint32_t getAttackSpeed() const { if (hasAttribute(ITEM_ATTRIBUTE_ATTACK_SPEED)) { return getIntAttr(ITEM_ATTRIBUTE_ATTACK_SPEED); } return items[id].attackSpeed; } + int32_t getArmor() const { if (hasAttribute(ITEM_ATTRIBUTE_ARMOR)) { return getIntAttr(ITEM_ATTRIBUTE_ARMOR); } return items[id].armor; } + int32_t getDefense() const { if (hasAttribute(ITEM_ATTRIBUTE_DEFENSE)) { return getIntAttr(ITEM_ATTRIBUTE_DEFENSE); } return items[id].defense; } + int32_t getExtraDefense() const { if (hasAttribute(ITEM_ATTRIBUTE_EXTRADEFENSE)) { return getIntAttr(ITEM_ATTRIBUTE_EXTRADEFENSE); } return items[id].extraDefense; } + int32_t getSlotPosition() const { return items[id].slotPosition; } + int8_t getHitChance() const { if (hasAttribute(ITEM_ATTRIBUTE_HITCHANCE)) { return getIntAttr(ITEM_ATTRIBUTE_HITCHANCE); @@ -914,37 +998,48 @@ class Item : virtual public Thing LightInfo getLightInfo() const; bool hasProperty(ITEMPROPERTY prop) const; + bool isBlocking() const { return items[id].blockSolid; } + bool isStackable() const { return items[id].stackable; } + bool isAlwaysOnTop() const { return items[id].alwaysOnTop; } + bool isGroundTile() const { return items[id].isGroundTile(); } + bool isMagicField() const { return items[id].isMagicField(); } + bool isMoveable() const { return items[id].moveable; } + bool isPickupable() const { return items[id].pickupable; } + bool isUseable() const { return items[id].useable; } + bool isHangable() const { return items[id].isHangable; } + bool isRotatable() const { const ItemType& it = items[id]; return it.rotatable && it.rotateTo; } + bool hasWalkStack() const { return items[id].walkStack; } @@ -952,36 +1047,42 @@ class Item : virtual public Thing void setStoreItem(bool storeItem) { setIntAttr(ITEM_ATTRIBUTE_STOREITEM, static_cast(storeItem)); } + bool isStoreItem() const { if (hasAttribute(ITEM_ATTRIBUTE_STOREITEM)) { return getIntAttr(ITEM_ATTRIBUTE_STOREITEM) == 1; } return items[id].storeItem; } + const std::string& getName() const { if (hasAttribute(ITEM_ATTRIBUTE_NAME)) { return getStrAttr(ITEM_ATTRIBUTE_NAME); } return items[id].name; } + const std::string getPluralName() const { if (hasAttribute(ITEM_ATTRIBUTE_PLURALNAME)) { return getStrAttr(ITEM_ATTRIBUTE_PLURALNAME); } return items[id].getPluralName(); } + const std::string& getArticle() const { if (hasAttribute(ITEM_ATTRIBUTE_ARTICLE)) { return getStrAttr(ITEM_ATTRIBUTE_ARTICLE); } return items[id].article; } + const std::string getClassification() const { if (hasAttribute(ITEM_ATTRIBUTE_CLASSIFICATION)) { return getStrAttr(ITEM_ATTRIBUTE_CLASSIFICATION); } return items[id].classification; } + const std::string getTier() const { if (hasAttribute(ITEM_ATTRIBUTE_TIER)) { return getStrAttr(ITEM_ATTRIBUTE_TIER); @@ -993,11 +1094,12 @@ class Item : virtual public Thing uint16_t getItemCount() const { return count; } + void setItemCount(uint8_t n) { count = n; } - static uint32_t countByType(const Item* i, int32_t subType) { + static uint32_t countByType(const ItemConstPtr& i, int32_t subType) { if (subType == -1 || subType == i->getSubType()) { return i->getItemCount(); } @@ -1017,28 +1119,34 @@ class Item : virtual public Thing setDuration(duration); } } + uint32_t getDefaultDuration() const { return items[id].decayTime * 1000; } - bool canDecay() const; + + bool canDecay(); virtual bool canRemove() const { return true; } + virtual bool canTransform() const { return true; } + virtual void onRemoved(); - virtual void onTradeEvent(TradeEvents_t, Player*) {} + virtual void onTradeEvent(TradeEvents_t, const PlayerPtr&) {} virtual void startDecaying(); bool isLoadedFromMap() const { return loadedFromMap; } + void setLoadedFromMap(bool value) { loadedFromMap = value; } + bool isCleanable() const { return !loadedFromMap && canRemove() && isPickupable() && !hasAttribute(ITEM_ATTRIBUTE_UNIQUEID) && !hasAttribute(ITEM_ATTRIBUTE_ACTIONID); } @@ -1051,46 +1159,46 @@ class Item : virtual public Thing } return attributes; } - - void incrementReferenceCounter() { - ++referenceCounter; - } - void decrementReferenceCounter() { - if (--referenceCounter == 0) { - delete this; - } - } - - Cylinder* getParent() const override { - return parent; + + CylinderPtr getParent() override { + return parent.lock(); } - void setParent(Cylinder* cylinder) override { + + void setParent(std::weak_ptr cylinder) override { parent = cylinder; } - Cylinder* getTopParent(); - const Cylinder* getTopParent() const; - Tile* getTile() override; - const Tile* getTile() const override; - bool isRemoved() const override { - return !parent || parent->isRemoved(); + + void clearParent() override + { + parent.reset(); + }; + + CylinderPtr getTopParent(); + TilePtr getTile() override; + + bool isRemoved() { + if (parent.lock()) { + return parent.lock()->isRemoved(); + } + return true; } uint16_t getImbuementSlots() const; uint16_t getFreeImbuementSlots() const; - bool canImbue() const; + bool canImbue(); bool addImbuementSlots(const uint16_t amount); bool removeImbuementSlots(const uint16_t amount, const bool destroyImbues = false); bool hasImbuementType(const ImbuementType imbuetype) const; bool hasImbuement(const std::shared_ptr& imbuement) const; bool hasImbuements() const; /// change to isImbued(); bool addImbuement(std::shared_ptr imbuement, bool created = true); - bool removeImbuement(std::shared_ptr imbuement, bool decayed = false); + bool removeImbuement(const std::shared_ptr& imbuement, bool decayed = false); std::vector>& getImbuements(); const std::vector>& getImbuements() const; const bool addAugment(std::string_view augmentName); - const bool addAugment(std::shared_ptr& augment); + const bool addAugment(const std::shared_ptr& augment); const bool removeAugment(std::string_view name); const bool removeAugment(std::shared_ptr& augment); @@ -1102,7 +1210,7 @@ class Item : virtual public Thing const std::vector>& getAugments(); protected: - Cylinder* parent = nullptr; + std::weak_ptr parent; uint16_t id; // the same id as in ItemType @@ -1114,7 +1222,6 @@ class Item : virtual public Thing uint16_t imbuementSlots = 0; std::vector> imbuements{}; std::vector> augments{}; - uint32_t referenceCounter = 0; uint8_t count = 1; // number of stacked items bool loadedFromMap = false; @@ -1122,7 +1229,7 @@ class Item : virtual public Thing //Don't add variables here, use the ItemAttribute class. }; -using ItemList = std::list; -using ItemDeque = std::deque; +using ItemList = std::list; +using ItemDeque = std::deque; #endif diff --git a/src/itemloader.h b/src/itemloader.h index 38ec7753..94283742 100644 --- a/src/itemloader.h +++ b/src/itemloader.h @@ -4,8 +4,6 @@ #ifndef FS_ITEMLOADER_H #define FS_ITEMLOADER_H -#include "fileloader.h" - enum itemgroup_t { ITEM_GROUP_NONE, diff --git a/src/items.h b/src/items.h index da07c0a4..77d6fba7 100644 --- a/src/items.h +++ b/src/items.h @@ -188,12 +188,15 @@ class ItemType bool isGroundTile() const { return group == ITEM_GROUP_GROUND; } + bool isContainer() const { return group == ITEM_GROUP_CONTAINER; } + bool isSplash() const { return group == ITEM_GROUP_SPLASH; } + bool isFluidContainer() const { return group == ITEM_GROUP_FLUID; } @@ -201,42 +204,55 @@ class ItemType bool isDoor() const { return (type == ITEM_TYPE_DOOR); } + bool isMagicField() const { return (type == ITEM_TYPE_MAGICFIELD); } + bool isTeleport() const { return (type == ITEM_TYPE_TELEPORT); } + bool isKey() const { return (type == ITEM_TYPE_KEY); } + bool isDepot() const { return (type == ITEM_TYPE_DEPOT); } + bool isRewardChest() const { return (type == ITEM_TYPE_REWARDCHEST); } + bool isRewardContainer() const { return (type == ITEM_TYPE_REWARDCONTAINER); } + bool isMailbox() const { return (type == ITEM_TYPE_MAILBOX); } + bool isTrashHolder() const { return (type == ITEM_TYPE_TRASHHOLDER); } + bool isBed() const { return (type == ITEM_TYPE_BED); } + bool isRune() const { return (type == ITEM_TYPE_RUNE); } + bool isPickupable() const { return (allowPickupable || pickupable); } + bool isUseable() const { return (useable); } + bool hasSubType() const { return (isFluidContainer() || isSplash() || stackable || charges != 0); } @@ -389,6 +405,7 @@ class Items const ItemType& operator[](size_t id) const { return getItemType(id); } + const ItemType& getItemType(size_t id) const; ItemType& getItemType(size_t id); const ItemType& getItemIdByClientId(uint16_t spriteId) const; @@ -403,6 +420,7 @@ class Items void parseItemNode(const pugi::xml_node& itemNode, uint16_t id); void buildInventoryList(); + const InventoryVector& getInventory() const { return inventory; } @@ -428,6 +446,7 @@ class Items if (clientId >= vec.size()) { vec.resize(clientId + 1, 0); } + if (vec[clientId] == 0) { vec[clientId] = serverId; } diff --git a/src/luascript.cpp b/src/luascript.cpp index 05ccd2ff..6c41fa86 100644 --- a/src/luascript.cpp +++ b/src/luascript.cpp @@ -48,7 +48,7 @@ extern Weapons* g_weapons; ScriptEnvironment::DBResultMap ScriptEnvironment::tempResults; uint32_t ScriptEnvironment::lastResultId = 0; -std::multimap ScriptEnvironment::tempItems; +std::multimap ScriptEnvironment::tempItems; LuaEnvironment g_luaEnvironment; @@ -74,9 +74,9 @@ void ScriptEnvironment::resetEnv() auto pair = tempItems.equal_range(this); auto it = pair.first; while (it != pair.second) { - Item* item = it->second; + auto item = it->second; if (item && item->getParent() == VirtualCylinder::virtualCylinder) { - g_game.ReleaseItem(item); + // g_game.ReleaseItem(item); } it = tempItems.erase(it); } @@ -105,18 +105,17 @@ void ScriptEnvironment::getEventInfo(int32_t& scriptId, LuaScriptInterface*& scr timerEvent = this->timerEvent; } -uint32_t ScriptEnvironment::addThing(Thing* thing) +uint32_t ScriptEnvironment::addThing(const ThingPtr& thing) { if (!thing || thing->isRemoved()) { return 0; } - Creature* creature = thing->getCreature(); - if (creature) { + if (const auto creature = thing->getCreature()) { return creature->getID(); } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (item && item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { return item->getUniqueId(); } @@ -131,7 +130,7 @@ uint32_t ScriptEnvironment::addThing(Thing* thing) return lastUID; } -void ScriptEnvironment::insertItem(uint32_t uid, Item* item) +void ScriptEnvironment::insertItem(uint32_t uid, const ItemPtr& item) { auto result = localMap.emplace(uid, item); if (!result.second) { @@ -139,23 +138,22 @@ void ScriptEnvironment::insertItem(uint32_t uid, Item* item) } } -Thing* ScriptEnvironment::getThingByUID(uint32_t uid) +ThingPtr ScriptEnvironment::getThingByUID(const uint32_t uid) { if (uid >= 0x10000000) { return g_game.getCreatureByID(uid); } if (uid <= std::numeric_limits::max()) { - Item* item = g_game.getUniqueItem(uid); + auto item = g_game.getUniqueItem(uid); if (item && !item->isRemoved()) { return item; } return nullptr; } - auto it = localMap.find(uid); - if (it != localMap.end()) { - Item* item = it->second; + if (const auto it = localMap.find(uid); it != localMap.end()) { + auto item = it->second; if (!item->isRemoved()) { return item; } @@ -163,43 +161,42 @@ Thing* ScriptEnvironment::getThingByUID(uint32_t uid) return nullptr; } -Item* ScriptEnvironment::getItemByUID(uint32_t uid) +ItemPtr ScriptEnvironment::getItemByUID(const uint32_t uid) { - Thing* thing = getThingByUID(uid); + const auto thing = getThingByUID(uid); if (!thing) { return nullptr; } return thing->getItem(); } -Container* ScriptEnvironment::getContainerByUID(uint32_t uid) +ContainerPtr ScriptEnvironment::getContainerByUID(const uint32_t uid) { - Item* item = getItemByUID(uid); + const auto item = getItemByUID(uid); if (!item) { return nullptr; } return item->getContainer(); } -void ScriptEnvironment::removeItemByUID(uint32_t uid) +void ScriptEnvironment::removeItemByUID(const uint32_t uid) { if (uid <= std::numeric_limits::max()) { g_game.removeUniqueItem(uid); return; } - auto it = localMap.find(uid); - if (it != localMap.end()) { + if (auto it = localMap.find(uid); it != localMap.end()) { localMap.erase(it); } } -void ScriptEnvironment::addTempItem(Item* item) +void ScriptEnvironment::addTempItem(const ItemPtr& item) { tempItems.emplace(this, item); } -void ScriptEnvironment::removeTempItem(Item* item) +void ScriptEnvironment::removeTempItem(const ItemPtr& item) { for (auto it = tempItems.begin(), end = tempItems.end(); it != end; ++it) { if (it->second == item) { @@ -209,7 +206,7 @@ void ScriptEnvironment::removeTempItem(Item* item) } } -uint32_t ScriptEnvironment::addResult(DBResult_ptr res) +uint32_t ScriptEnvironment::addResult(const DBResult_ptr& res) { tempResults[++lastResultId] = res; return lastResultId; @@ -291,7 +288,7 @@ int LuaScriptInterface::protectedCall(lua_State* L, int nargs, int nresults) return ret; } -int32_t LuaScriptInterface::loadFile(const std::string& file, Npc* npc /* = nullptr*/) +int32_t LuaScriptInterface::loadFile(const std::string& file, std::optional npc /* = std::nullopt*/) { //loads file as a chunk at stack top int ret = luaL_loadfile(luaState, file.c_str()); @@ -315,7 +312,11 @@ int32_t LuaScriptInterface::loadFile(const std::string& file, Npc* npc /* = null ScriptEnvironment* env = getScriptEnv(); env->setScriptId(EVENT_ID_LOADING, this); - env->setNpc(npc); + if (npc.has_value()) { + // probably need to use move here?? + env->setNpc(npc.value()); + } + //execute it ret = protectedCall(luaState, 0, 0); @@ -467,7 +468,7 @@ void LuaScriptInterface::reportError(const char* function, const std::string& er } } -bool LuaScriptInterface::pushFunction(int32_t functionId) +bool LuaScriptInterface::pushFunction(int32_t functionId) const { lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef); if (!isTable(luaState, -1)) { @@ -515,7 +516,7 @@ int LuaScriptInterface::luaErrorHandler(lua_State* L) return 1; } -bool LuaScriptInterface::callFunction(int params) +bool LuaScriptInterface::callFunction(int params) const { bool result = false; int size = lua_gettop(luaState); @@ -534,7 +535,7 @@ bool LuaScriptInterface::callFunction(int params) return result; } -void LuaScriptInterface::callVoidFunction(int params) +void LuaScriptInterface::callVoidFunction(int params) const { int size = lua_gettop(luaState); if (protectedCall(luaState, params, 0) != 0) { @@ -577,7 +578,7 @@ void LuaScriptInterface::pushVariant(lua_State* L, const LuaVariant& var) setMetatable(L, -1, "Variant"); } -void LuaScriptInterface::pushThing(lua_State* L, Thing* thing) +void LuaScriptInterface::pushThing(lua_State* L, const ThingPtr& thing) { if (!thing) { lua_createtable(L, 0, 4); @@ -588,27 +589,27 @@ void LuaScriptInterface::pushThing(lua_State* L, Thing* thing) return; } - if (Item* item = thing->getItem()) { - pushUserdata(L, item); + if (auto item = thing->getItem()) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); - } else if (Creature* creature = thing->getCreature()) { - pushUserdata(L, creature); + } else if (auto creature = thing->getCreature()) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); } else { lua_pushnil(L); } } -void LuaScriptInterface::pushCylinder(lua_State* L, Cylinder* cylinder) +void LuaScriptInterface::pushCylinder(lua_State* L, const CylinderPtr& cylinder) { - if (Creature* creature = cylinder->getCreature()) { - pushUserdata(L, creature); + if (auto creature = cylinder->getCreature()) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); - } else if (Item* parentItem = cylinder->getItem()) { - pushUserdata(L, parentItem); + } else if (auto parentItem = cylinder->getItem()) { + pushSharedPtr(L, parentItem); setItemMetatable(L, -1, parentItem); - } else if (Tile* tile = cylinder->getTile()) { - pushUserdata(L, tile); + } else if (auto tile = cylinder->getTile()) { + pushSharedPtr(L, tile); setMetatable(L, -1, "Tile"); } else if (cylinder == VirtualCylinder::virtualCylinder) { pushBoolean(L, true); @@ -685,7 +686,7 @@ void LuaScriptInterface::setWeakMetatable(lua_State* L, int32_t index, const std lua_setmetatable(L, index - 1); } -void LuaScriptInterface::setItemMetatable(lua_State* L, int32_t index, const Item* item) +void LuaScriptInterface::setItemMetatable(lua_State* L, int32_t index, const ItemConstPtr& item) { if (item->getContainer()) { luaL_getmetatable(L, "Container"); @@ -697,7 +698,7 @@ void LuaScriptInterface::setItemMetatable(lua_State* L, int32_t index, const Ite lua_setmetatable(L, index - 1); } -void LuaScriptInterface::setCreatureMetatable(lua_State* L, int32_t index, const Creature* creature) +void LuaScriptInterface::setCreatureMetatable(lua_State* L, int32_t index, const CreatureConstPtr& creature) { if (creature->getPlayer()) { luaL_getmetatable(L, "Player"); @@ -823,29 +824,29 @@ InstantSpell* LuaScriptInterface::getInstantSpell(lua_State* L, int32_t arg) return spell; } -Thing* LuaScriptInterface::getThing(lua_State* L, int32_t arg) +ThingPtr LuaScriptInterface::getThing(lua_State* L, int32_t arg) { - Thing* thing; + ThingPtr thing; if (lua_getmetatable(L, arg) != 0) { lua_rawgeti(L, -1, 't'); switch(getNumber(L, -1)) { case LuaData_Item: - thing = getUserdata(L, arg); + thing = getSharedPtr(L, arg); break; case LuaData_Container: - thing = getUserdata(L, arg); + thing = getSharedPtr(L, arg); break; case LuaData_Teleport: - thing = getUserdata(L, arg); + thing = getSharedPtr(L, arg); break; case LuaData_Player: - thing = getUserdata(L, arg); + thing = getSharedPtr(L, arg); break; case LuaData_Monster: - thing = getUserdata(L, arg); + thing = getSharedPtr(L, arg); break; case LuaData_Npc: - thing = getUserdata(L, arg); + thing = getSharedPtr(L, arg); break; default: thing = nullptr; @@ -858,18 +859,18 @@ Thing* LuaScriptInterface::getThing(lua_State* L, int32_t arg) return thing; } -Creature* LuaScriptInterface::getCreature(lua_State* L, int32_t arg) +CreaturePtr LuaScriptInterface::getCreature(lua_State* L, int32_t arg) { if (isUserdata(L, arg)) { - return getUserdata(L, arg); + return getSharedPtr(L, arg); } return g_game.getCreatureByID(getNumber(L, arg)); } -Player* LuaScriptInterface::getPlayer(lua_State* L, int32_t arg) +PlayerPtr LuaScriptInterface::getPlayer(lua_State* L, int32_t arg) { if (isUserdata(L, arg)) { - return getUserdata(L, arg); + return getSharedPtr(L, arg); } return g_game.getPlayerByID(getNumber(L, arg)); } @@ -3327,7 +3328,7 @@ void LuaScriptInterface::registerFunctions() #undef registerEnum #undef registerEnumIn -void LuaScriptInterface::registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction/* = nullptr*/) +void LuaScriptInterface::registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction/* = nullptr*/) const { // className = {} lua_newtable(luaState); @@ -3401,14 +3402,14 @@ void LuaScriptInterface::registerClass(const std::string& className, const std:: lua_pop(luaState, 2); } -void LuaScriptInterface::registerTable(const std::string& tableName) +void LuaScriptInterface::registerTable(const std::string& tableName) const { // _G[tableName] = {} lua_newtable(luaState); lua_setglobal(luaState, tableName.c_str()); } -void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func) +void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func) const { // globalName.methodName = func lua_getglobal(luaState, globalName.c_str()); @@ -3419,7 +3420,7 @@ void LuaScriptInterface::registerMethod(const std::string& globalName, const std lua_pop(luaState, 1); } -void LuaScriptInterface::registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func) +void LuaScriptInterface::registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func) const { // className.metatable.methodName = func luaL_getmetatable(luaState, className.c_str()); @@ -3430,14 +3431,14 @@ void LuaScriptInterface::registerMetaMethod(const std::string& className, const lua_pop(luaState, 1); } -void LuaScriptInterface::registerGlobalMethod(const std::string& functionName, lua_CFunction func) +void LuaScriptInterface::registerGlobalMethod(const std::string& functionName, lua_CFunction func) const { // _G[functionName] = func lua_pushcfunction(luaState, func); lua_setglobal(luaState, functionName.c_str()); } -void LuaScriptInterface::registerVariable(const std::string& tableName, const std::string& name, lua_Number value) +void LuaScriptInterface::registerVariable(const std::string& tableName, const std::string& name, lua_Number value) const { // tableName.name = value lua_getglobal(luaState, tableName.c_str()); @@ -3447,14 +3448,14 @@ void LuaScriptInterface::registerVariable(const std::string& tableName, const st lua_pop(luaState, 1); } -void LuaScriptInterface::registerGlobalVariable(const std::string& name, lua_Number value) +void LuaScriptInterface::registerGlobalVariable(const std::string& name, lua_Number value) const { // _G[name] = value lua_pushinteger(luaState, value); lua_setglobal(luaState, name.c_str()); } -void LuaScriptInterface::registerGlobalBoolean(const std::string& name, bool value) +void LuaScriptInterface::registerGlobalBoolean(const std::string& name, bool value) const { // _G[name] = value pushBoolean(luaState, value); @@ -3465,7 +3466,7 @@ int LuaScriptInterface::luaDoPlayerAddItem(lua_State* L) { //doPlayerAddItem(cid, itemid, count/subtype, canDropOnMap) //doPlayerAddItem(cid, itemid, count, canDropOnMap, subtype) - Player* player = getPlayer(L, 1); + auto player = getPlayer(L, 1); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3501,7 +3502,7 @@ int LuaScriptInterface::luaDoPlayerAddItem(lua_State* L) stackCount = 100; } - Item* newItem = Item::CreateItem(itemId, stackCount); + auto newItem = Item::CreateItem(itemId, stackCount); if (!newItem) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -3514,7 +3515,7 @@ int LuaScriptInterface::luaDoPlayerAddItem(lua_State* L) ReturnValue ret = g_game.internalPlayerAddItem(player, newItem, canDropOnMap); if (ret != RETURNVALUE_NOERROR) { - delete newItem; + newItem.reset(); pushBoolean(L, false); return 1; } @@ -3661,7 +3662,7 @@ int LuaScriptInterface::luaCreateCombatArea(lua_State* L) int LuaScriptInterface::luaDoAreaCombat(lua_State* L) { //doAreaCombat(cid, type, pos, area, min, max, effect[, origin = ORIGIN_SPELL[, blockArmor = false[, blockShield = false[, ignoreResistances = false]]]]) - Creature* creature = getCreature(L, 1); + auto creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber(L, 1) != 0)) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -3697,14 +3698,14 @@ int LuaScriptInterface::luaDoAreaCombat(lua_State* L) int LuaScriptInterface::luaDoTargetCombat(lua_State* L) { //doTargetCombat(cid, target, type, min, max, effect[, origin = ORIGIN_SPELL[, blockArmor = false[, blockShield = false[, ignoreResistances = false]]]]) - Creature* creature = getCreature(L, 1); + auto creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber(L, 1) != 0)) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - Creature* target = getCreature(L, 2); + auto target = getCreature(L, 2); if (!target) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -3733,14 +3734,14 @@ int LuaScriptInterface::luaDoTargetCombat(lua_State* L) int LuaScriptInterface::luaDoChallengeCreature(lua_State* L) { //doChallengeCreature(cid, target[, force = false]) - Creature* creature = getCreature(L, 1); + auto creature = getCreature(L, 1); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - Creature* target = getCreature(L, 2); + auto target = getCreature(L, 2); if (!target) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -3762,7 +3763,7 @@ int LuaScriptInterface::luaIsValidUID(lua_State* L) int LuaScriptInterface::luaIsDepot(lua_State* L) { //isDepot(uid) - Container* container = getScriptEnv()->getContainerByUID(getNumber(L, -1)); + auto container = getScriptEnv()->getContainerByUID(getNumber(L, -1)); pushBoolean(L, container && container->getDepotLocker()); return 1; } @@ -3771,7 +3772,7 @@ int LuaScriptInterface::luaIsMoveable(lua_State* L) { //isMoveable(uid) //isMovable(uid) - Thing* thing = getScriptEnv()->getThingByUID(getNumber(L, -1)); + auto thing = getScriptEnv()->getThingByUID(getNumber(L, -1)); pushBoolean(L, thing && thing->isPushable()); return 1; } @@ -3781,14 +3782,14 @@ int LuaScriptInterface::luaGetDepotId(lua_State* L) //getDepotId(uid) uint32_t uid = getNumber(L, -1); - Container* container = getScriptEnv()->getContainerByUID(uid); + auto container = getScriptEnv()->getContainerByUID(uid); if (!container) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND)); pushBoolean(L, false); return 1; } - DepotLocker* depotLocker = container->getDepotLocker(); + auto depotLocker = container->getDepotLocker(); if (!depotLocker) { reportErrorFunc(L, "Depot not found"); pushBoolean(L, false); @@ -3958,14 +3959,14 @@ int LuaScriptInterface::luaCleanMap(lua_State* L) int LuaScriptInterface::luaIsInWar(lua_State* L) { //isInWar(cid, target) - Player* player = getPlayer(L, 1); + auto player = getPlayer(L, 1); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); return 1; } - Player* targetPlayer = getPlayer(L, 2); + auto targetPlayer = getPlayer(L, 2); if (!targetPlayer) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3981,8 +3982,7 @@ int LuaScriptInterface::luaGetWaypointPositionByName(lua_State* L) //getWaypointPositionByName(name) auto& waypoints = g_game.map.waypoints; - auto it = waypoints.find(getString(L, -1)); - if (it != waypoints.end()) { + if (const auto it = waypoints.find(getString(L, -1)); it != waypoints.end()) { pushPosition(L, it->second); } else { pushBoolean(L, false); @@ -4185,7 +4185,7 @@ int LuaScriptInterface::luaDatabaseAsyncStoreQuery(lua_State* L) if (lua_gettop(L) > 1) { int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX); auto scriptId = getScriptEnv()->getScriptId(); - callback = [ref, scriptId](DBResult_ptr result, bool) { + callback = [ref, scriptId](const DBResult_ptr& result, bool) { lua_State* luaState = g_luaEnvironment.getLuaState(); if (!luaState) { return; @@ -4494,8 +4494,8 @@ int LuaScriptInterface::luaGameGetSpectators(lua_State* L) lua_createtable(L, spectators.size(), 0); int index = 0; - for (Creature* creature : spectators) { - pushUserdata(L, creature); + for (auto creature : spectators) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); lua_rawseti(L, -2, ++index); } @@ -4508,8 +4508,8 @@ int LuaScriptInterface::luaGameGetPlayers(lua_State* L) lua_createtable(L, g_game.getPlayersOnline(), 0); int index = 0; - for (const auto& playerEntry : g_game.getPlayers()) { - pushUserdata(L, playerEntry.second); + for (const auto& val : g_game.getPlayers() | std::views::values) { + pushSharedPtr(L, val); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); } @@ -4522,8 +4522,8 @@ int LuaScriptInterface::luaGameGetNpcs(lua_State* L) lua_createtable(L, g_game.getNpcsOnline(), 0); int index = 0; - for (const auto& npcEntry : g_game.getNpcs()) { - pushUserdata(L, npcEntry.second); + for (const auto& val : g_game.getNpcs() | std::views::values) { + pushSharedPtr(L, val); setMetatable(L, -1, "Npc"); lua_rawseti(L, -2, ++index); } @@ -4536,8 +4536,8 @@ int LuaScriptInterface::luaGameGetMonsters(lua_State* L) lua_createtable(L, g_game.getMonstersOnline(), 0); int index = 0; - for (const auto& monsterEntry : g_game.getMonsters()) { - pushUserdata(L, monsterEntry.second); + for (const auto& val : g_game.getMonsters() | std::views::values) { + pushSharedPtr(L, val); setMetatable(L, -1, "Monster"); lua_rawseti(L, -2, ++index); } @@ -4622,8 +4622,8 @@ int LuaScriptInterface::luaGameGetCurrencyItems(lua_State* L) size_t size = currencyItems.size(); lua_createtable(L, size, 0); - for (const auto& it : currencyItems) { - const ItemType& itemType = Item::items[it.second]; + for (const auto& val : currencyItems | std::views::values) { + const ItemType& itemType = Item::items[val]; pushUserdata(L, &itemType); setMetatable(L, -1, "ItemType"); lua_rawseti(L, -2, size--); @@ -4638,8 +4638,8 @@ int LuaScriptInterface::luaGameGetTowns(lua_State* L) lua_createtable(L, towns.size(), 0); int index = 0; - for (auto townEntry : towns) { - pushUserdata(L, townEntry.second); + for (auto val : towns | std::views::values) { + pushUserdata(L, val); setMetatable(L, -1, "Town"); lua_rawseti(L, -2, ++index); } @@ -4653,8 +4653,8 @@ int LuaScriptInterface::luaGameGetHouses(lua_State* L) lua_createtable(L, houses.size(), 0); int index = 0; - for (auto houseEntry : houses) { - pushUserdata(L, houseEntry.second); + for (auto val : houses | std::views::values) { + pushUserdata(L, val); setMetatable(L, -1, "House"); lua_rawseti(L, -2, ++index); } @@ -4782,7 +4782,7 @@ int LuaScriptInterface::luaGameCreateItem(lua_State* L) count = std::min(count, 100); } - Item* item = Item::CreateItem(id, count); + auto item = Item::CreateItem(id, count); if (!item) { lua_pushnil(L); return 1; @@ -4790,9 +4790,9 @@ int LuaScriptInterface::luaGameCreateItem(lua_State* L) if (lua_gettop(L) >= 3) { const Position& position = getPosition(L, 3); - Tile* tile = g_game.map.getTile(position); + CylinderPtr tile = g_game.map.getTile(position); if (!tile) { - delete item; + item.reset(); lua_pushnil(L); return 1; } @@ -4803,7 +4803,7 @@ int LuaScriptInterface::luaGameCreateItem(lua_State* L) item->setParent(VirtualCylinder::virtualCylinder); } - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); return 1; } @@ -4823,7 +4823,7 @@ int LuaScriptInterface::luaGameCreateContainer(lua_State* L) } } - Container* container = Item::CreateItemAsContainer(id, size); + auto container = Item::CreateItemAsContainer(id, size); if (!container) { lua_pushnil(L); return 1; @@ -4831,9 +4831,9 @@ int LuaScriptInterface::luaGameCreateContainer(lua_State* L) if (lua_gettop(L) >= 3) { const Position& position = getPosition(L, 3); - Tile* tile = g_game.map.getTile(position); + CylinderPtr tile = g_game.map.getTile(position); if (!tile) { - delete container; + container.reset(); lua_pushnil(L); return 1; } @@ -4844,7 +4844,7 @@ int LuaScriptInterface::luaGameCreateContainer(lua_State* L) container->setParent(VirtualCylinder::virtualCylinder); } - pushUserdata(L, container); + pushSharedPtr(L, container); setMetatable(L, -1, "Container"); return 1; } @@ -4852,7 +4852,7 @@ int LuaScriptInterface::luaGameCreateContainer(lua_State* L) int LuaScriptInterface::luaGameCreateMonster(lua_State* L) { // Game.createMonster(monsterName, position[, extended = false[, force = false[, magicEffect = CONST_ME_TELEPORT]]]) - Monster* monster = Monster::createMonster(getString(L, 1)); + auto monster = Monster::createMonster(getString(L, 1)); if (!monster) { lua_pushnil(L); return 1; @@ -4864,14 +4864,12 @@ int LuaScriptInterface::luaGameCreateMonster(lua_State* L) MagicEffectClasses magicEffect = getNumber(L, 5, CONST_ME_TELEPORT); if (g_events->eventMonsterOnSpawn(monster, position, false, true) || force) { if (g_game.placeCreature(monster, position, extended, force, magicEffect)) { - pushUserdata(L, monster); + pushSharedPtr(L, monster); setMetatable(L, -1, "Monster"); } else { - delete monster; lua_pushnil(L); } } else { - delete monster; lua_pushnil(L); } return 1; @@ -4880,7 +4878,7 @@ int LuaScriptInterface::luaGameCreateMonster(lua_State* L) int LuaScriptInterface::luaGameCreateNpc(lua_State* L) { // Game.createNpc(npcName, position[, extended = false[, force = false[, magicEffect = CONST_ME_TELEPORT]]]) - Npc* npc = Npc::createNpc(getString(L, 1)); + auto npc = Npc::createNpc(getString(L, 1)); if (!npc) { lua_pushnil(L); return 1; @@ -4891,10 +4889,10 @@ int LuaScriptInterface::luaGameCreateNpc(lua_State* L) bool force = getBoolean(L, 4, false); MagicEffectClasses magicEffect = getNumber(L, 5, CONST_ME_TELEPORT); if (g_game.placeCreature(npc, position, extended, force, magicEffect)) { - pushUserdata(L, npc); + pushSharedPtr(L, npc); setMetatable(L, -1, "Npc"); } else { - delete npc; + npc.reset(); lua_pushnil(L); } return 1; @@ -4916,18 +4914,18 @@ int LuaScriptInterface::luaGameCreateTile(lua_State* L) isDynamic = getBoolean(L, 4, false); } - Tile* tile = g_game.map.getTile(position); + TilePtr tile = g_game.map.getTile(position); if (!tile) { if (isDynamic) { - tile = new DynamicTile(position.x, position.y, position.z); + tile = std::make_shared(position.x, position.y, position.z); } else { - tile = new StaticTile(position.x, position.y, position.z); + tile = std::make_shared(position.x, position.y, position.z); } g_game.map.setTile(position, tile); } - pushUserdata(L, tile); + pushSharedPtr(L, tile); setMetatable(L, -1, "Tile"); return 1; } @@ -4974,7 +4972,7 @@ int LuaScriptInterface::luaGameStartRaid(lua_State* L) // Game.startRaid(raidName) const std::string& raidName = getString(L, 1); - Raid* raid = g_game.raids.getRaidByName(raidName); + const auto raid = g_game.raids.getRaidByName(raidName); if (!raid || !raid->isLoaded()) { lua_pushinteger(L, RETURNVALUE_NOSUCHRAIDEXISTS); return 1; @@ -5138,7 +5136,7 @@ int LuaScriptInterface::luaVariantCreate(lua_State* L) // Variant(number or string or position or thing) LuaVariant variant; if (isUserdata(L, 2)) { - if (Thing* thing = getThing(L, 2)) { + if (auto thing = getThing(L, 2)) { variant.setTargetPosition(thing->getPosition()); } } else if (isTable(L, 2)) { @@ -5288,8 +5286,7 @@ int LuaScriptInterface::luaPositionSendMagicEffect(lua_State* L) // position:sendMagicEffect(magicEffect[, player = nullptr]) SpectatorVec spectators; if (lua_gettop(L) >= 3) { - Player* player = getPlayer(L, 3); - if (player) { + if (const auto player = getPlayer(L, 3)) { spectators.emplace_back(player); } } @@ -5315,8 +5312,7 @@ int LuaScriptInterface::luaPositionSendDistanceEffect(lua_State* L) // position:sendDistanceEffect(positionEx, distanceEffect[, player = nullptr]) SpectatorVec spectators; if (lua_gettop(L) >= 4) { - Player* player = getPlayer(L, 4); - if (player) { + if (const auto player = getPlayer(L, 4)) { spectators.emplace_back(player); } } @@ -5339,7 +5335,7 @@ int LuaScriptInterface::luaTileCreate(lua_State* L) { // Tile(x, y, z) // Tile(position) - Tile* tile; + TilePtr tile; if (isTable(L, 2)) { tile = g_game.map.getTile(getPosition(L, 2)); } else { @@ -5350,7 +5346,7 @@ int LuaScriptInterface::luaTileCreate(lua_State* L) } if (tile) { - pushUserdata(L, tile); + pushSharedPtr(L, tile); setMetatable(L, -1, "Tile"); } else { lua_pushnil(L); @@ -5361,7 +5357,7 @@ int LuaScriptInterface::luaTileCreate(lua_State* L) int LuaScriptInterface::luaTileRemove(lua_State* L) { // tile:remove() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5379,8 +5375,7 @@ int LuaScriptInterface::luaTileRemove(lua_State* L) int LuaScriptInterface::luaTileGetPosition(lua_State* L) { // tile:getPosition() - Tile* tile = getUserdata(L, 1); - if (tile) { + if (const auto tile = getSharedPtr(L, 1)) { pushPosition(L, tile->getPosition()); } else { lua_pushnil(L); @@ -5391,9 +5386,9 @@ int LuaScriptInterface::luaTileGetPosition(lua_State* L) int LuaScriptInterface::luaTileGetGround(lua_State* L) { // tile:getGround() - Tile* tile = getUserdata(L, 1); + auto tile = getSharedPtr(L, 1); if (tile && tile->getGround()) { - pushUserdata(L, tile->getGround()); + pushSharedPtr(L, tile->getGround()); setItemMetatable(L, -1, tile->getGround()); } else { lua_pushnil(L); @@ -5405,23 +5400,23 @@ int LuaScriptInterface::luaTileGetThing(lua_State* L) { // tile:getThing(index) int32_t index = getNumber(L, 2); - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Thing* thing = tile->getThing(index); + const auto thing = tile->getThing(index); if (!thing) { lua_pushnil(L); return 1; } - if (Creature* creature = thing->getCreature()) { - pushUserdata(L, creature); + if (const auto creature = thing->getCreature()) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); - } else if (Item* item = thing->getItem()) { - pushUserdata(L, item); + } else if (const auto item = thing->getItem()) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -5432,8 +5427,7 @@ int LuaScriptInterface::luaTileGetThing(lua_State* L) int LuaScriptInterface::luaTileGetThingCount(lua_State* L) { // tile:getThingCount() - Tile* tile = getUserdata(L, 1); - if (tile) { + if (const auto tile = getSharedPtr(L, 1)) { lua_pushinteger(L, tile->getThingCount()); } else { lua_pushnil(L); @@ -5444,24 +5438,24 @@ int LuaScriptInterface::luaTileGetThingCount(lua_State* L) int LuaScriptInterface::luaTileGetTopVisibleThing(lua_State* L) { // tile:getTopVisibleThing(creature) - Creature* creature = getCreature(L, 2); - Tile* tile = getUserdata(L, 1); + const auto creature = getCreature(L, 2); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Thing* thing = tile->getTopVisibleThing(creature); + const auto thing = tile->getTopVisibleThing(creature); if (!thing) { lua_pushnil(L); return 1; } - if (Creature* visibleCreature = thing->getCreature()) { - pushUserdata(L, visibleCreature); + if (const auto visibleCreature = thing->getCreature()) { + pushSharedPtr(L, visibleCreature); setCreatureMetatable(L, -1, visibleCreature); - } else if (Item* visibleItem = thing->getItem()) { - pushUserdata(L, visibleItem); + } else if (const auto visibleItem = thing->getItem()) { + pushSharedPtr(L, visibleItem); setItemMetatable(L, -1, visibleItem); } else { lua_pushnil(L); @@ -5472,15 +5466,14 @@ int LuaScriptInterface::luaTileGetTopVisibleThing(lua_State* L) int LuaScriptInterface::luaTileGetTopTopItem(lua_State* L) { // tile:getTopTopItem() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Item* item = tile->getTopTopItem(); - if (item) { - pushUserdata(L, item); + if (const auto item = tile->getTopTopItem()) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -5491,15 +5484,14 @@ int LuaScriptInterface::luaTileGetTopTopItem(lua_State* L) int LuaScriptInterface::luaTileGetTopDownItem(lua_State* L) { // tile:getTopDownItem() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Item* item = tile->getTopDownItem(); - if (item) { - pushUserdata(L, item); + if (const auto item = tile->getTopDownItem()) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -5510,15 +5502,14 @@ int LuaScriptInterface::luaTileGetTopDownItem(lua_State* L) int LuaScriptInterface::luaTileGetFieldItem(lua_State* L) { // tile:getFieldItem() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Item* item = tile->getFieldItem(); - if (item) { - pushUserdata(L, item); + if (const auto item = tile->getFieldItem()) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -5529,7 +5520,7 @@ int LuaScriptInterface::luaTileGetFieldItem(lua_State* L) int LuaScriptInterface::luaTileGetItemById(lua_State* L) { // tile:getItemById(itemId[, subType = -1]) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5547,9 +5538,8 @@ int LuaScriptInterface::luaTileGetItemById(lua_State* L) } int32_t subType = getNumber(L, 3, -1); - Item* item = g_game.findItemOfType(tile, itemId, false, subType); - if (item) { - pushUserdata(L, item); + if (const auto item = g_game.findItemOfType(tile, itemId, false, subType)) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -5560,7 +5550,7 @@ int LuaScriptInterface::luaTileGetItemById(lua_State* L) int LuaScriptInterface::luaTileGetItemByType(lua_State* L) { // tile:getItemByType(itemType) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5598,20 +5588,20 @@ int LuaScriptInterface::luaTileGetItemByType(lua_State* L) return 1; } - if (Item* item = tile->getGround()) { + if (const auto item = tile->getGround()) { const ItemType& it = Item::items[item->getID()]; if (it.type == itemType) { - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); return 1; } } - if (const TileItemVector* items = tile->getItemList()) { - for (Item* item : *items) { + if (const TileItemsPtr items = tile->getItemList()) { + for (const auto item : *items) { const ItemType& it = Item::items[item->getID()]; if (it.type == itemType) { - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); return 1; } @@ -5633,13 +5623,13 @@ int LuaScriptInterface::luaTileGetItemByTopOrder(lua_State* L) int32_t topOrder = getNumber(L, 2); - Item* item = tile->getItemByTopOrder(topOrder); + const auto item = tile->getItemByTopOrder(topOrder); if (!item) { lua_pushnil(L); return 1; } - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); return 1; } @@ -5647,7 +5637,7 @@ int LuaScriptInterface::luaTileGetItemByTopOrder(lua_State* L) int LuaScriptInterface::luaTileGetItemCountById(lua_State* L) { // tile:getItemCountById(itemId[, subType = -1]) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5673,19 +5663,19 @@ int LuaScriptInterface::luaTileGetItemCountById(lua_State* L) int LuaScriptInterface::luaTileGetBottomCreature(lua_State* L) { // tile:getBottomCreature() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - const Creature* creature = tile->getBottomCreature(); + const auto creature = tile->getBottomCreature(); if (!creature) { lua_pushnil(L); return 1; } - pushUserdata(L, creature); + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); return 1; } @@ -5693,19 +5683,19 @@ int LuaScriptInterface::luaTileGetBottomCreature(lua_State* L) int LuaScriptInterface::luaTileGetTopCreature(lua_State* L) { // tile:getTopCreature() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Creature* creature = tile->getTopCreature(); + const auto creature = tile->getTopCreature(); if (!creature) { lua_pushnil(L); return 1; } - pushUserdata(L, creature); + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); return 1; } @@ -5713,21 +5703,20 @@ int LuaScriptInterface::luaTileGetTopCreature(lua_State* L) int LuaScriptInterface::luaTileGetBottomVisibleCreature(lua_State* L) { // tile:getBottomVisibleCreature(creature) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Creature* creature = getCreature(L, 2); + const auto creature = getCreature(L, 2); if (!creature) { lua_pushnil(L); return 1; } - const Creature* visibleCreature = tile->getBottomVisibleCreature(creature); - if (visibleCreature) { - pushUserdata(L, visibleCreature); + if (const auto visibleCreature = tile->getBottomVisibleCreature(creature)) { + pushSharedPtr(L, visibleCreature); setCreatureMetatable(L, -1, visibleCreature); } else { lua_pushnil(L); @@ -5738,21 +5727,20 @@ int LuaScriptInterface::luaTileGetBottomVisibleCreature(lua_State* L) int LuaScriptInterface::luaTileGetTopVisibleCreature(lua_State* L) { // tile:getTopVisibleCreature(creature) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Creature* creature = getCreature(L, 2); + const auto creature = getCreature(L, 2); if (!creature) { lua_pushnil(L); return 1; } - Creature* visibleCreature = tile->getTopVisibleCreature(creature); - if (visibleCreature) { - pushUserdata(L, visibleCreature); + if (const auto visibleCreature = tile->getTopVisibleCreature(creature)) { + pushSharedPtr(L, visibleCreature); setCreatureMetatable(L, -1, visibleCreature); } else { lua_pushnil(L); @@ -5763,13 +5751,13 @@ int LuaScriptInterface::luaTileGetTopVisibleCreature(lua_State* L) int LuaScriptInterface::luaTileGetItems(lua_State* L) { // tile:getItems() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - TileItemVector* itemVector = tile->getItemList(); + auto itemVector = tile->getItemList(); if (!itemVector) { lua_pushnil(L); return 1; @@ -5778,8 +5766,8 @@ int LuaScriptInterface::luaTileGetItems(lua_State* L) lua_createtable(L, itemVector->size(), 0); int index = 0; - for (Item* item : *itemVector) { - pushUserdata(L, item); + for (const auto item : *itemVector) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); lua_rawseti(L, -2, ++index); } @@ -5789,7 +5777,7 @@ int LuaScriptInterface::luaTileGetItems(lua_State* L) int LuaScriptInterface::luaTileGetItemCount(lua_State* L) { // tile:getItemCount() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5802,8 +5790,7 @@ int LuaScriptInterface::luaTileGetItemCount(lua_State* L) int LuaScriptInterface::luaTileGetDownItemCount(lua_State* L) { // tile:getDownItemCount() - Tile* tile = getUserdata(L, 1); - if (tile) { + if (const auto tile = getSharedPtr(L, 1)) { lua_pushinteger(L, tile->getDownItemCount()); } else { lua_pushnil(L); @@ -5814,7 +5801,7 @@ int LuaScriptInterface::luaTileGetDownItemCount(lua_State* L) int LuaScriptInterface::luaTileGetTopItemCount(lua_State* L) { // tile:getTopItemCount() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5827,13 +5814,13 @@ int LuaScriptInterface::luaTileGetTopItemCount(lua_State* L) int LuaScriptInterface::luaTileGetCreatures(lua_State* L) { // tile:getCreatures() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - CreatureVector* creatureVector = tile->getCreatures(); + const auto creatureVector = tile->getCreatures(); if (!creatureVector) { lua_pushnil(L); return 1; @@ -5842,8 +5829,8 @@ int LuaScriptInterface::luaTileGetCreatures(lua_State* L) lua_createtable(L, creatureVector->size(), 0); int index = 0; - for (Creature* creature : *creatureVector) { - pushUserdata(L, creature); + for (const auto creature : *creatureVector) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); lua_rawseti(L, -2, ++index); } @@ -5853,7 +5840,7 @@ int LuaScriptInterface::luaTileGetCreatures(lua_State* L) int LuaScriptInterface::luaTileGetCreatureCount(lua_State* L) { // tile:getCreatureCount() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5866,15 +5853,15 @@ int LuaScriptInterface::luaTileGetCreatureCount(lua_State* L) int LuaScriptInterface::luaTileHasProperty(lua_State* L) { // tile:hasProperty(property[, item]) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Item* item; + ItemPtr item; if (lua_gettop(L) >= 3) { - item = getUserdata(L, 3); + item = getSharedPtr(L, 3); } else { item = nullptr; } @@ -5891,13 +5878,13 @@ int LuaScriptInterface::luaTileHasProperty(lua_State* L) int LuaScriptInterface::luaTileGetThingIndex(lua_State* L) { // tile:getThingIndex(thing) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Thing* thing = getThing(L, 2); + const auto thing = getThing(L, 2); if (thing) { lua_pushinteger(L, tile->getThingIndex(thing)); } else { @@ -5909,8 +5896,7 @@ int LuaScriptInterface::luaTileGetThingIndex(lua_State* L) int LuaScriptInterface::luaTileHasFlag(lua_State* L) { // tile:hasFlag(flag) - Tile* tile = getUserdata(L, 1); - if (tile) { + if (const auto tile = getSharedPtr(L, 1)) { tileflags_t flag = getNumber(L, 2); pushBoolean(L, tile->hasFlag(flag)); } else { @@ -5922,27 +5908,27 @@ int LuaScriptInterface::luaTileHasFlag(lua_State* L) int LuaScriptInterface::luaTileQueryAdd(lua_State* L) { // tile:queryAdd(thing[, flags]) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - Thing* thing = getThing(L, 2); + const auto thing = getThing(L, 2); if (!thing) { lua_pushnil(L); return 1; } - if (Creature* creature = thing->getCreature()) { + if (const auto creature = thing->getCreature()) { uint32_t flags = getNumber(L, 3, 0); - lua_pushinteger(L, tile->queryAdd(*creature, flags)); + lua_pushinteger(L, tile->queryAdd(creature, flags)); return 1; } - if (Item* item = thing->getItem()) { + if (const auto item = thing->getItem()) { uint32_t flags = getNumber(L, 3, 0); - lua_pushinteger(L, tile->queryAdd(*item, flags)); + lua_pushinteger(L, tile->queryAdd(item, flags)); return 1; } @@ -5953,7 +5939,7 @@ int LuaScriptInterface::luaTileQueryAdd(lua_State* L) int LuaScriptInterface::luaTileAddItem(lua_State* L) { // tile:addItem(itemId[, count/subType = 1[, flags = 0]]) - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -5972,20 +5958,20 @@ int LuaScriptInterface::luaTileAddItem(lua_State* L) uint32_t subType = getNumber(L, 3, 1); - Item* item = Item::CreateItem(itemId, std::min(subType, 100)); + auto item = Item::CreateItem(itemId, std::min(subType, 100)); if (!item) { lua_pushnil(L); return 1; } uint32_t flags = getNumber(L, 4, 0); - - ReturnValue ret = g_game.internalAddItem(tile, item, INDEX_WHEREEVER, flags); + CylinderPtr holder = tile; + ReturnValue ret = g_game.internalAddItem(holder, item, INDEX_WHEREEVER, flags); if (ret == RETURNVALUE_NOERROR) { - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { - delete item; + item.reset(); lua_pushnil(L); } return 1; @@ -5994,13 +5980,13 @@ int LuaScriptInterface::luaTileAddItem(lua_State* L) int LuaScriptInterface::luaTileAddItemEx(lua_State* L) { // tile:addItemEx(item[, flags = 0]) - Item* item = getUserdata(L, 2); + const auto item = getSharedPtr(L, 2); if (!item) { lua_pushnil(L); return 1; } - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -6013,7 +5999,8 @@ int LuaScriptInterface::luaTileAddItemEx(lua_State* L) } uint32_t flags = getNumber(L, 3, 0); - ReturnValue ret = g_game.internalAddItem(tile, item, INDEX_WHEREEVER, flags); + CylinderPtr holder = tile; + ReturnValue ret = g_game.internalAddItem(holder, item, INDEX_WHEREEVER, flags); if (ret == RETURNVALUE_NOERROR) { ScriptEnvironment::removeTempItem(item); } @@ -6024,13 +6011,13 @@ int LuaScriptInterface::luaTileAddItemEx(lua_State* L) int LuaScriptInterface::luaTileGetHouse(lua_State* L) { // tile:getHouse() - Tile* tile = getUserdata(L, 1); + const auto tile = getSharedPtr(L, 1); if (!tile) { lua_pushnil(L); return 1; } - if (HouseTile* houseTile = dynamic_cast(tile)) { + if (HouseTilePtr houseTile = std::dynamic_pointer_cast(tile)) { pushUserdata(L, houseTile->getHouse()); setMetatable(L, -1, "House"); } else { @@ -6231,7 +6218,7 @@ int LuaScriptInterface::luaNetworkMessageAddDouble(lua_State* L) int LuaScriptInterface::luaNetworkMessageAddItem(lua_State* L) { // networkMessage:addItem(item) - Item* item = getUserdata(L, 2); + const auto item = getSharedPtr(L, 2); if (!item) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); lua_pushnil(L); @@ -6345,8 +6332,7 @@ int LuaScriptInterface::luaNetworkMessageSendToPlayer(lua_State* L) return 1; } - Player* player = getPlayer(L, 2); - if (player) { + if (const auto player = getPlayer(L, 2)) { player->sendNetworkMessage(*message); pushBoolean(L, true); } else { @@ -6575,7 +6561,7 @@ int LuaScriptInterface::luaModalWindowSetPriority(lua_State* L) int LuaScriptInterface::luaModalWindowSendToPlayer(lua_State* L) { // modalWindow:sendToPlayer(player) - Player* player = getPlayer(L, 2); + const auto player = getPlayer(L, 2); if (!player) { lua_pushnil(L); return 1; @@ -6599,9 +6585,8 @@ int LuaScriptInterface::luaItemCreate(lua_State* L) // Item(uid) uint32_t id = getNumber(L, 2); - Item* item = getScriptEnv()->getItemByUID(id); - if (item) { - pushUserdata(L, item); + if (const auto item = getScriptEnv()->getItemByUID(id)) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -6612,20 +6597,20 @@ int LuaScriptInterface::luaItemCreate(lua_State* L) int LuaScriptInterface::luaItemIsItem(lua_State* L) { // item:isItem() - pushBoolean(L, getUserdata(L, 1) != nullptr); + pushBoolean(L, getSharedPtr(L, 1) != nullptr); return 1; } int LuaScriptInterface::luaItemGetParent(lua_State* L) { // item:getParent() - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } - Cylinder* parent = item->getParent(); + CylinderPtr parent = item->getParent(); if (!parent) { lua_pushnil(L); return 1; @@ -6638,13 +6623,13 @@ int LuaScriptInterface::luaItemGetParent(lua_State* L) int LuaScriptInterface::luaItemGetTopParent(lua_State* L) { // item:getTopParent() - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } - Cylinder* topParent = item->getTopParent(); + CylinderPtr topParent = item->getTopParent(); if (!topParent) { lua_pushnil(L); return 1; @@ -6657,8 +6642,7 @@ int LuaScriptInterface::luaItemGetTopParent(lua_State* L) int LuaScriptInterface::luaItemGetId(lua_State* L) { // item:getId() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getID()); } else { lua_pushnil(L); @@ -6669,13 +6653,13 @@ int LuaScriptInterface::luaItemGetId(lua_State* L) int LuaScriptInterface::luaItemClone(lua_State* L) { // item:clone() - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } - Item* clone = item->clone(); + const auto clone = item->clone(); if (!clone) { lua_pushnil(L); return 1; @@ -6684,7 +6668,7 @@ int LuaScriptInterface::luaItemClone(lua_State* L) getScriptEnv()->addTempItem(clone); clone->setParent(VirtualCylinder::virtualCylinder); - pushUserdata(L, clone); + pushSharedPtr(L, clone); setItemMetatable(L, -1, clone); return 1; } @@ -6692,13 +6676,13 @@ int LuaScriptInterface::luaItemClone(lua_State* L) int LuaScriptInterface::luaItemSplit(lua_State* L) { // item:split([count = 1]) - Item** itemPtr = getRawUserdata(L, 1); + auto& itemPtr = getSharedPtr(L, 1); if (!itemPtr) { lua_pushnil(L); return 1; } - Item* item = *itemPtr; + ItemPtr item = itemPtr; if (!item || !item->isStackable()) { lua_pushnil(L); return 1; @@ -6707,7 +6691,7 @@ int LuaScriptInterface::luaItemSplit(lua_State* L) uint16_t count = std::min(getNumber(L, 2, 1), item->getItemCount()); uint16_t diff = item->getItemCount() - count; - Item* splitItem = item->clone(); + ItemPtr splitItem = item->clone(); if (!splitItem) { lua_pushnil(L); return 1; @@ -6718,7 +6702,7 @@ int LuaScriptInterface::luaItemSplit(lua_State* L) ScriptEnvironment* env = getScriptEnv(); uint32_t uid = env->addThing(item); - Item* newItem = g_game.transformItem(item, item->getID(), diff); + ItemPtr newItem = g_game.transformItem(item, item->getID(), diff); if (item->isRemoved()) { env->removeItemByUID(uid); } @@ -6727,12 +6711,12 @@ int LuaScriptInterface::luaItemSplit(lua_State* L) env->insertItem(uid, newItem); } - *itemPtr = newItem; - + itemPtr.reset(newItem.get()); + splitItem->setParent(VirtualCylinder::virtualCylinder); env->addTempItem(splitItem); - pushUserdata(L, splitItem); + pushSharedPtr(L, splitItem); setItemMetatable(L, -1, splitItem); return 1; } @@ -6740,9 +6724,9 @@ int LuaScriptInterface::luaItemSplit(lua_State* L) int LuaScriptInterface::luaItemRemove(lua_State* L) { // item:remove([count = -1]) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (item) { - int32_t count = getNumber(L, 2, -1); + const int32_t count = getNumber(L, 2, -1); pushBoolean(L, g_game.internalRemoveItem(item, count) == RETURNVALUE_NOERROR); } else { lua_pushnil(L); @@ -6753,8 +6737,7 @@ int LuaScriptInterface::luaItemRemove(lua_State* L) int LuaScriptInterface::luaItemGetUniqueId(lua_State* L) { // item:getUniqueId() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { uint32_t uniqueId = item->getUniqueId(); if (uniqueId == 0) { uniqueId = getScriptEnv()->addThing(item); @@ -6769,8 +6752,7 @@ int LuaScriptInterface::luaItemGetUniqueId(lua_State* L) int LuaScriptInterface::luaItemGetActionId(lua_State* L) { // item:getActionId() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getActionId()); } else { lua_pushnil(L); @@ -6782,8 +6764,7 @@ int LuaScriptInterface::luaItemSetActionId(lua_State* L) { // item:setActionId(actionId) uint16_t actionId = getNumber(L, 2); - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { item->setActionId(actionId); pushBoolean(L, true); } else { @@ -6795,8 +6776,7 @@ int LuaScriptInterface::luaItemSetActionId(lua_State* L) int LuaScriptInterface::luaItemGetCount(lua_State* L) { // item:getCount() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getItemCount()); } else { lua_pushnil(L); @@ -6807,8 +6787,7 @@ int LuaScriptInterface::luaItemGetCount(lua_State* L) int LuaScriptInterface::luaItemGetCharges(lua_State* L) { // item:getCharges() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getCharges()); } else { lua_pushnil(L); @@ -6819,8 +6798,7 @@ int LuaScriptInterface::luaItemGetCharges(lua_State* L) int LuaScriptInterface::luaItemGetFluidType(lua_State* L) { // item:getFluidType() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getFluidType()); } else { lua_pushnil(L); @@ -6831,8 +6809,7 @@ int LuaScriptInterface::luaItemGetFluidType(lua_State* L) int LuaScriptInterface::luaItemGetWeight(lua_State* L) { // item:getWeight() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getWeight()); } else { lua_pushnil(L); @@ -6843,8 +6820,7 @@ int LuaScriptInterface::luaItemGetWeight(lua_State* L) int LuaScriptInterface::luaItemGetWorth(lua_State* L) { // item:getWorth() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getWorth()); } else { lua_pushnil(L); @@ -6855,8 +6831,7 @@ int LuaScriptInterface::luaItemGetWorth(lua_State* L) int LuaScriptInterface::luaItemGetSubType(lua_State* L) { // item:getSubType() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getSubType()); } else { lua_pushnil(L); @@ -6867,8 +6842,7 @@ int LuaScriptInterface::luaItemGetSubType(lua_State* L) int LuaScriptInterface::luaItemGetName(lua_State* L) { // item:getName() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushString(L, item->getName()); } else { lua_pushnil(L); @@ -6879,8 +6853,7 @@ int LuaScriptInterface::luaItemGetName(lua_State* L) int LuaScriptInterface::luaItemGetPluralName(lua_State* L) { // item:getPluralName() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushString(L, item->getPluralName()); } else { lua_pushnil(L); @@ -6891,8 +6864,7 @@ int LuaScriptInterface::luaItemGetPluralName(lua_State* L) int LuaScriptInterface::luaItemGetArticle(lua_State* L) { // item:getArticle() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushString(L, item->getArticle()); } else { lua_pushnil(L); @@ -6903,8 +6875,7 @@ int LuaScriptInterface::luaItemGetArticle(lua_State* L) int LuaScriptInterface::luaItemGetPosition(lua_State* L) { // item:getPosition() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushPosition(L, item->getPosition()); } else { lua_pushnil(L); @@ -6915,15 +6886,14 @@ int LuaScriptInterface::luaItemGetPosition(lua_State* L) int LuaScriptInterface::luaItemGetTile(lua_State* L) { // item:getTile() - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } - Tile* tile = item->getTile(); - if (tile) { - pushUserdata(L, tile); + if (const auto tile = item->getTile()) { + pushSharedPtr(L, tile); setMetatable(L, -1, "Tile"); } else { lua_pushnil(L); @@ -6934,7 +6904,7 @@ int LuaScriptInterface::luaItemGetTile(lua_State* L) int LuaScriptInterface::luaItemHasAttribute(lua_State* L) { // item:hasAttribute(key) - Item* item = getUserdata(L, 1); + const auto item = getUserdata(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -6956,7 +6926,7 @@ int LuaScriptInterface::luaItemHasAttribute(lua_State* L) int LuaScriptInterface::luaItemGetAttribute(lua_State* L) { // item:getAttribute(key) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -6984,7 +6954,7 @@ int LuaScriptInterface::luaItemGetAttribute(lua_State* L) int LuaScriptInterface::luaItemSetAttribute(lua_State* L) { // item:setAttribute(key, value) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7020,7 +6990,7 @@ int LuaScriptInterface::luaItemSetAttribute(lua_State* L) int LuaScriptInterface::luaItemRemoveAttribute(lua_State* L) { // item:removeAttribute(key) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7047,7 +7017,7 @@ int LuaScriptInterface::luaItemRemoveAttribute(lua_State* L) int LuaScriptInterface::luaItemGetCustomAttribute(lua_State* L) { // item:getCustomAttribute(key) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7073,7 +7043,7 @@ int LuaScriptInterface::luaItemGetCustomAttribute(lua_State* L) { int LuaScriptInterface::luaItemSetCustomAttribute(lua_State* L) { // item:setCustomAttribute(key, value) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7113,7 +7083,7 @@ int LuaScriptInterface::luaItemSetCustomAttribute(lua_State* L) { int LuaScriptInterface::luaItemRemoveCustomAttribute(lua_State* L) { // item:removeCustomAttribute(key) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7132,30 +7102,29 @@ int LuaScriptInterface::luaItemRemoveCustomAttribute(lua_State* L) { int LuaScriptInterface::luaItemMoveTo(lua_State* L) { // item:moveTo(position or cylinder[, flags]) - Item** itemPtr = getRawUserdata(L, 1); + auto& itemPtr = getSharedPtr(L, 1); if (!itemPtr) { lua_pushnil(L); return 1; } - Item* item = *itemPtr; + ItemPtr item = itemPtr; if (!item || item->isRemoved()) { lua_pushnil(L); return 1; } - Cylinder* toCylinder; + CylinderPtr toCylinder; if (isUserdata(L, 2)) { - const LuaDataType type = getUserdataType(L, 2); - switch (type) { + switch (const LuaDataType type = getUserdataType(L, 2)) { case LuaData_Container: - toCylinder = getUserdata(L, 2); + toCylinder = getSharedPtr(L, 2); break; case LuaData_Player: - toCylinder = getUserdata(L, 2); + toCylinder = getSharedPtr(L, 2); break; case LuaData_Tile: - toCylinder = getUserdata(L, 2); + toCylinder = getSharedPtr(L, 2); break; default: toCylinder = nullptr; @@ -7180,10 +7149,11 @@ int LuaScriptInterface::luaItemMoveTo(lua_State* L) if (item->getParent() == VirtualCylinder::virtualCylinder) { pushBoolean(L, g_game.internalAddItem(toCylinder, item, INDEX_WHEREEVER, flags) == RETURNVALUE_NOERROR); } else { - Item* moveItem = nullptr; - ReturnValue ret = g_game.internalMoveItem(item->getParent(), toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, flags); + ItemPtr moveItem = nullptr; + CylinderPtr i_parent = item->getParent(); + ReturnValue ret = g_game.internalMoveItem(i_parent, toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, flags); if (moveItem) { - *itemPtr = moveItem; + itemPtr = moveItem; } pushBoolean(L, ret == RETURNVALUE_NOERROR); } @@ -7193,13 +7163,13 @@ int LuaScriptInterface::luaItemMoveTo(lua_State* L) int LuaScriptInterface::luaItemTransform(lua_State* L) { // item:transform(itemId[, count/subType = -1]) - Item** itemPtr = getRawUserdata(L, 1); + auto& itemPtr = getSharedPtr(L, 1); if (!itemPtr) { lua_pushnil(L); return 1; } - Item*& item = *itemPtr; + ItemPtr item = itemPtr; if (!item) { lua_pushnil(L); return 1; @@ -7235,7 +7205,7 @@ int LuaScriptInterface::luaItemTransform(lua_State* L) ScriptEnvironment* env = getScriptEnv(); uint32_t uid = env->addThing(item); - Item* newItem = g_game.transformItem(item, itemId, subType); + const auto newItem = g_game.transformItem(item, itemId, subType); if (item->isRemoved()) { env->removeItemByUID(uid); } @@ -7252,8 +7222,7 @@ int LuaScriptInterface::luaItemTransform(lua_State* L) int LuaScriptInterface::luaItemDecay(lua_State* L) { // item:decay(decayId) - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { if (item->isAugmented() || item->hasImbuements()) { lua_pushboolean(L, false); @@ -7275,8 +7244,7 @@ int LuaScriptInterface::luaItemDecay(lua_State* L) int LuaScriptInterface::luaItemGetDescription(lua_State* L) { // item:getDescription(distance) - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { int32_t distance = getNumber(L, 2); pushString(L, item->getDescription(distance)); } else { @@ -7288,8 +7256,7 @@ int LuaScriptInterface::luaItemGetDescription(lua_State* L) int LuaScriptInterface::luaItemGetSpecialDescription(lua_State* L) { // item:getSpecialDescription() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushString(L, item->getSpecialDescription()); } else { lua_pushnil(L); @@ -7300,9 +7267,8 @@ int LuaScriptInterface::luaItemGetSpecialDescription(lua_State* L) int LuaScriptInterface::luaItemHasProperty(lua_State* L) { // item:hasProperty(property) - Item* item = getUserdata(L, 1); - if (item) { - ITEMPROPERTY property = getNumber(L, 2); + if (const auto item = getSharedPtr(L, 1)) { + auto property = getNumber(L, 2); pushBoolean(L, item->hasProperty(property)); } else { lua_pushnil(L); @@ -7313,8 +7279,7 @@ int LuaScriptInterface::luaItemHasProperty(lua_State* L) int LuaScriptInterface::luaItemIsLoadedFromMap(lua_State* L) { // item:isLoadedFromMap() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->isLoadedFromMap()); } else { lua_pushnil(L); @@ -7325,7 +7290,7 @@ int LuaScriptInterface::luaItemIsLoadedFromMap(lua_State* L) int LuaScriptInterface::luaItemSetStoreItem(lua_State* L) { // item:setStoreItem(storeItem) - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7338,8 +7303,7 @@ int LuaScriptInterface::luaItemSetStoreItem(lua_State* L) int LuaScriptInterface::luaItemIsStoreItem(lua_State* L) { // item:isStoreItem() - Item* item = getUserdata(L, 1); - if (item) { + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->isStoreItem()); } else { lua_pushnil(L); @@ -7350,8 +7314,7 @@ int LuaScriptInterface::luaItemIsStoreItem(lua_State* L) int LuaScriptInterface::luaItemGetImbuementSlots(lua_State* L) { // item:getImbuementSlots() -- returns how many total slots - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getImbuementSlots()); } else { @@ -7363,8 +7326,7 @@ int LuaScriptInterface::luaItemGetImbuementSlots(lua_State* L) int LuaScriptInterface::luaItemGetFreeImbuementSlots(lua_State* L) { // item:getFreeImbuementSlots() -- returns how many slots are available for use - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { lua_pushinteger(L, item->getFreeImbuementSlots()); } else { @@ -7376,8 +7338,7 @@ int LuaScriptInterface::luaItemGetFreeImbuementSlots(lua_State* L) int LuaScriptInterface::luaItemCanImbue(lua_State* L) { // item:canImbue(amount) -- returns true if item has slots that are free - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->canImbue()); } else { @@ -7389,8 +7350,7 @@ int LuaScriptInterface::luaItemCanImbue(lua_State* L) int LuaScriptInterface::luaItemAddImbuementSlots(lua_State* L) { // item:addImbuementSlots(amount) -- tries to add imbuement slot(s), returns true if successful - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->addImbuementSlots(getNumber(L, 2))); } else { @@ -7402,8 +7362,7 @@ int LuaScriptInterface::luaItemAddImbuementSlots(lua_State* L) int LuaScriptInterface::luaItemRemoveImbuementSlots(lua_State* L) { // item:removeImbuementSlots(amount, destroy) -- tries to remove imbuement slot(s), returns true if successful - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->removeImbuementSlots(getNumber(L, 2), getBoolean(L, 5, false))); } else { @@ -7415,8 +7374,7 @@ int LuaScriptInterface::luaItemRemoveImbuementSlots(lua_State* L) int LuaScriptInterface::luaItemHasImbuementType(lua_State* L) { // item:hasImbuementType(type) - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->hasImbuementType(getNumber(L, 2, ImbuementType::IMBUEMENT_TYPE_NONE))); } else { @@ -7428,11 +7386,9 @@ int LuaScriptInterface::luaItemHasImbuementType(lua_State* L) int LuaScriptInterface::luaItemHasImbuement(lua_State* L) { // item:hasImbuement(imbueType, amount, duration, realtime) - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { - std::shared_ptr imbue = getSharedPtr(L, 2); - if (imbue) { + if (const std::shared_ptr imbue = getSharedPtr(L, 2)) { pushBoolean(L, item->hasImbuement(imbue)); } else { lua_pushnil(L); @@ -7446,8 +7402,7 @@ int LuaScriptInterface::luaItemHasImbuement(lua_State* L) int LuaScriptInterface::luaItemHasImbuements(lua_State* L) { // item:hasImbuements() -- returns true if item has any imbuements - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { pushBoolean(L, item->hasImbuements()); } else { @@ -7459,11 +7414,9 @@ int LuaScriptInterface::luaItemHasImbuements(lua_State* L) int LuaScriptInterface::luaItemAddImbuement(lua_State* L) { // item:addImbuement(imbuement) -- returns true if it successfully adds the imbuement - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { - std::shared_ptr imbue = getSharedPtr(L, 2); - if (imbue) { + if (const std::shared_ptr imbue = getSharedPtr(L, 2)) { pushBoolean(L, item->addImbuement(imbue, true)); } } else { @@ -7475,11 +7428,9 @@ int LuaScriptInterface::luaItemAddImbuement(lua_State* L) int LuaScriptInterface::luaItemRemoveImbuement(lua_State* L) { // item:removeImbuement(imbuement) - Item* item = getUserdata(L, 1); - if (item) + if (const auto item = getSharedPtr(L, 1)) { - std::shared_ptr imbue = getSharedPtr(L, 2); - if (imbue) { + if (const std::shared_ptr imbue = getSharedPtr(L, 2)) { pushBoolean(L, item->removeImbuement(imbue, false)); } } else { @@ -7492,17 +7443,17 @@ int LuaScriptInterface::luaItemRemoveImbuement(lua_State* L) int LuaScriptInterface::luaItemGetImbuements(lua_State* L) { // item:getImbuements() -- returns a table that contains values that are imbuement userdata? - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } - std::vector> imbuements = item->getImbuements(); + const std::vector> imbuements = item->getImbuements(); lua_createtable(L, imbuements.size(), 0); int index = 0; - for (std::shared_ptr imbuement : imbuements) { + for (const auto imbuement : imbuements) { pushSharedPtr(L, imbuement); setMetatable(L, -1, "Imbuement"); lua_rawseti(L, -2, ++index); @@ -7512,7 +7463,7 @@ int LuaScriptInterface::luaItemGetImbuements(lua_State* L) int LuaScriptInterface::luaItemAddAugment(lua_State* L) { - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7532,7 +7483,7 @@ int LuaScriptInterface::luaItemAddAugment(lua_State* L) reportError(__FUNCTION__, "Item::addAugment() argument not found as any name in augments loaded on startup! \n"); } } else if (isUserdata(L, 2)) { - if (std::shared_ptr augment = getSharedPtr(L, 2)) { + if (auto augment = getSharedPtr(L, 2)) { lua_pushboolean(L, item->addAugment(augment)); } else { lua_pushnil(L); @@ -7547,17 +7498,17 @@ int LuaScriptInterface::luaItemAddAugment(lua_State* L) int LuaScriptInterface::luaItemRemoveAugment(lua_State* L) { - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } if (isString(L, 2)) { - auto name = getString(L, 2); + const auto name = getString(L, 2); lua_pushboolean(L, item->removeAugment(name)); } else if (isUserdata(L, 2)) { - if (std::shared_ptr augment = getSharedPtr(L, 2)) { + if (auto augment = getSharedPtr(L, 2)) { lua_pushboolean(L, item->removeAugment(augment)); } else { reportError(__FUNCTION__, "Item::removeAugment() invalid userdata type passed as argument! \n"); @@ -7572,7 +7523,7 @@ int LuaScriptInterface::luaItemRemoveAugment(lua_State* L) int LuaScriptInterface::luaItemIsAugmented(lua_State* L) { - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -7583,14 +7534,14 @@ int LuaScriptInterface::luaItemIsAugmented(lua_State* L) int LuaScriptInterface::luaItemHasAugment(lua_State* L) { - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } if (isString(L, 2)) { - auto name = getString(L, 2); + const auto name = getString(L, 2); lua_pushboolean(L, item->hasAugment(name)); } else if (isUserdata(L, 2)) { if (std::shared_ptr augment = getSharedPtr(L, 2)) { @@ -7608,17 +7559,17 @@ int LuaScriptInterface::luaItemHasAugment(lua_State* L) int LuaScriptInterface::luaItemGetAugments(lua_State* L) { - Item* item = getUserdata(L, 1); + const auto item = getSharedPtr(L, 1); if (!item) { lua_pushnil(L); return 1; } - std::vector> augments = item->getAugments(); + const auto augments = item->getAugments(); lua_createtable(L, augments.size(), 0); int index = 0; - for (std::shared_ptr augment : augments) { + for (const auto augment : augments) { pushSharedPtr(L, augment); setMetatable(L, -1, "Augment"); lua_rawseti(L, -2, ++index); @@ -7643,8 +7594,7 @@ int LuaScriptInterface::luaImbuementCreate(lua_State* L) int LuaScriptInterface::luaImbuementGetType(lua_State* L) { // imbuement:getType() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->imbuetype); } else { lua_pushnil(L); @@ -7655,8 +7605,7 @@ int LuaScriptInterface::luaImbuementGetType(lua_State* L) int LuaScriptInterface::luaImbuementGetValue(lua_State* L) { // imbuement:getValue() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->value); } else { lua_pushnil(L); @@ -7668,8 +7617,7 @@ int LuaScriptInterface::luaImbuementGetValue(lua_State* L) int LuaScriptInterface::luaImbuementGetDuration(lua_State* L) { // imbuement:getDuration() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->duration); } else { lua_pushnil(L); @@ -7680,8 +7628,7 @@ int LuaScriptInterface::luaImbuementGetDuration(lua_State* L) int LuaScriptInterface::luaImbuementIsSkill(lua_State* L) { // imbuement:isSkill() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->isSkill()); } else { lua_pushnil(L); @@ -7692,8 +7639,7 @@ int LuaScriptInterface::luaImbuementIsSkill(lua_State* L) int LuaScriptInterface::luaImbuementIsSpecialSkill(lua_State* L) { // imbuement:isSpecialSkill() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->isSpecialSkill()); } else { lua_pushnil(L); @@ -7704,8 +7650,7 @@ int LuaScriptInterface::luaImbuementIsSpecialSkill(lua_State* L) int LuaScriptInterface::luaImbuementIsDamage(lua_State* L) { // imbuement:isDamage() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->isDamage()); } else { @@ -7717,8 +7662,7 @@ int LuaScriptInterface::luaImbuementIsDamage(lua_State* L) int LuaScriptInterface::luaImbuementIsResist(lua_State* L) { // imbuement:isResist() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->isResist()); } else { lua_pushnil(L); @@ -7729,8 +7673,7 @@ int LuaScriptInterface::luaImbuementIsResist(lua_State* L) int LuaScriptInterface::luaImbuementIsStat(lua_State* L) { // imbuement:isStat() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { lua_pushinteger(L, imbue->isStat()); } else { lua_pushnil(L); @@ -7741,8 +7684,7 @@ int LuaScriptInterface::luaImbuementIsStat(lua_State* L) int LuaScriptInterface::luaImbuementSetValue(lua_State* L) { // imbuement:setAmount(amount) - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { imbue->value = getNumber(L, 2); pushBoolean(L, true); } else { @@ -7754,8 +7696,7 @@ int LuaScriptInterface::luaImbuementSetValue(lua_State* L) int LuaScriptInterface::luaImbuementSetDuration(lua_State* L) { // imbuement:setDuration(duration) - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { imbue->duration = getNumber(L, 2); pushBoolean(L, true); } else { @@ -7767,8 +7708,7 @@ int LuaScriptInterface::luaImbuementSetDuration(lua_State* L) int LuaScriptInterface::luaImbuementSetEquipDecay(lua_State* L) { // imbuement:makeEquipDecayed() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { imbue->decaytype = ImbuementDecayType::IMBUEMENT_DECAY_EQUIPPED; pushBoolean(L, true); } else { @@ -7780,8 +7720,7 @@ int LuaScriptInterface::luaImbuementSetEquipDecay(lua_State* L) int LuaScriptInterface::luaImbuementSetInfightDecay(lua_State* L) { // imbuement:makeInfightDecayed() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { imbue->decaytype = ImbuementDecayType::IMBUEMENT_DECAY_INFIGHT; pushBoolean(L, true); } else { @@ -7793,8 +7732,7 @@ int LuaScriptInterface::luaImbuementSetInfightDecay(lua_State* L) int LuaScriptInterface::luaImbuementIsEquipDecay(lua_State* L) { // imbuement:isEquipDecayed() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { pushBoolean(L, imbue->decaytype == ImbuementDecayType::IMBUEMENT_DECAY_EQUIPPED); } else { lua_pushnil(L); @@ -7805,8 +7743,7 @@ int LuaScriptInterface::luaImbuementIsEquipDecay(lua_State* L) int LuaScriptInterface::luaImbuementIsInfightDecay(lua_State* L) { // imbuement:isInfightDecayed() - std::shared_ptr imbue = getSharedPtr(L, 1); - if (imbue) { + if (const auto imbue = getSharedPtr(L, 1)) { pushBoolean(L, imbue->decaytype == ImbuementDecayType::IMBUEMENT_DECAY_INFIGHT); } else { lua_pushnil(L); @@ -7821,7 +7758,7 @@ int LuaScriptInterface::luaDamageModifierCreate(lua_State* L) auto modType = getNumber(L, 3); auto amount = getNumber(L, 4); auto factor = getNumber(L, 5); - auto chance = getNumber(L, 6); + auto chance = getNumber(L, 6, 100); auto combatType = getNumber(L, 7, COMBAT_NONE); auto originType = getNumber(L, 8, ORIGIN_NONE); auto creatureType = getNumber(L, 9, CREATURETYPE_ATTACKABLE); @@ -7840,11 +7777,9 @@ int LuaScriptInterface::luaDamageModifierCreate(lua_State* L) int LuaScriptInterface::luaDamageModifierSetValue(lua_State* L) { - std::shared_ptr modifier = getSharedPtr(L, 1); - if (modifier) { + if (const auto modifier = getSharedPtr(L, 1)) { // to-do: handle no param defaults and throw error - uint8_t amount = getNumber(L, 2); - if (amount) { + if (const uint8_t amount = getNumber(L, 2)) { modifier->setValue(amount); } } else { @@ -7855,11 +7790,9 @@ int LuaScriptInterface::luaDamageModifierSetValue(lua_State* L) int LuaScriptInterface::luaDamageModifierSetRateFactor(lua_State* L) { - std::shared_ptr modifier = getSharedPtr(L, 1); - if (modifier) { + if (const auto modifier = getSharedPtr(L, 1)) { // to-do: handle no param defaults and throw error - uint8_t factor = getNumber(L, 2); - if (factor >= 0) { + if (const uint8_t factor = getNumber(L, 2)) { modifier->setFactor(factor); } } else { @@ -7870,8 +7803,7 @@ int LuaScriptInterface::luaDamageModifierSetRateFactor(lua_State* L) int LuaScriptInterface::luaDamageModifierSetCombatFilter(lua_State* L) { - std::shared_ptr modifier = getSharedPtr(L, 1); - if (modifier) { + if (const auto modifier = getSharedPtr(L, 1)) { // to-do: handle no param defaults and throw error CombatType_t combatType = getNumber(L, 2); if (combatType >= 0) { @@ -7885,11 +7817,9 @@ int LuaScriptInterface::luaDamageModifierSetCombatFilter(lua_State* L) int LuaScriptInterface::luaDamageModifierSetOriginFilter(lua_State* L) { - std::shared_ptr modifier = getSharedPtr(L, 1); - if (modifier) { + if (const auto modifier = getSharedPtr(L, 1)) { // to-do: handle no param defaults and throw error - CombatOrigin origin = getNumber(L, 2); - if (origin >= 0) { + if (const CombatOrigin origin = getNumber(L, 2)) { modifier->setOriginType(origin); } } else { @@ -7903,10 +7833,9 @@ int LuaScriptInterface::luaAugmentCreate(lua_State* L) // Augment(name, description, modifier or table_of_modifiers) if (isString(L, 2)) { - auto name = getString(L, 2); - auto augment = Augments::GetAugment(name); + const auto name = getString(L, 2); - if (augment) { + if (const auto augment = Augments::GetAugment(name)) { pushSharedPtr(L, augment); setMetatable(L, -1, "Augment"); return 1; // return early here because we found a global augment with this name @@ -7914,8 +7843,7 @@ int LuaScriptInterface::luaAugmentCreate(lua_State* L) auto description = getString(L, 3); if (isUserdata(L, 4)) { - auto modifier = getSharedPtr(L, 4); - if (modifier) { + if (auto modifier = getSharedPtr(L, 4)) { auto augment = Augment::MakeAugment(name, description); augment->addModifier(modifier); pushSharedPtr(L, augment); @@ -7933,8 +7861,7 @@ int LuaScriptInterface::luaAugmentCreate(lua_State* L) while (lua_next(L, 4) != 0) { // Check if the value is userdata and of type DamageModifier if (isUserdata(L, -1)) { - auto modifier = getSharedPtr(L, -1); - if (modifier) { + if (auto modifier = getSharedPtr(L, -1)) { list.emplace_back(modifier); } else { reportError(__FUNCTION__, "Invalid userdata in table element\n"); @@ -7948,7 +7875,7 @@ int LuaScriptInterface::luaAugmentCreate(lua_State* L) // Create augment with all modifiers // To-do : Add augments created this particular way to global table - auto augment = Augment::MakeAugment(name, description); + const auto augment = Augment::MakeAugment(name, description); for (auto& modifier : list) { augment->addModifier(modifier); } @@ -7968,7 +7895,7 @@ int LuaScriptInterface::luaAugmentCreate(lua_State* L) int LuaScriptInterface::luaAugmentSetName(lua_State* L) { // Augment:setName(newName) - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); return 0; @@ -7982,41 +7909,41 @@ int LuaScriptInterface::luaAugmentSetName(lua_State* L) int LuaScriptInterface::luaAugmentSetDescription(lua_State* L) { // Augment:getDescription(newDescription) - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); return 0; } - auto newDescription = getString(L, 2); + const auto newDescription = getString(L, 2); augment->setDescription(newDescription); return 0; } int LuaScriptInterface::luaAugmentGetName(lua_State* L) { // Augment:getName() - auto augment = getSharedPtr(L, 1); // Get augment object + const auto augment = getSharedPtr(L, 1); // Get augment object if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); lua_pushnil(L); return 1; } - std::string name = augment->getName(); + const std::string name = augment->getName(); pushString(L, name); return 1; } int LuaScriptInterface::luaAugmentGetDescription(lua_State* L) { // Augment:getDescription() - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); lua_pushnil(L); return 1; } - std::string description = augment->getDescription(); + const std::string description = augment->getDescription(); pushString(L, description); return 1; } @@ -8025,7 +7952,7 @@ int LuaScriptInterface::luaAugmentGetDescription(lua_State* L) { int LuaScriptInterface::luaAugmentAddDamageModifier(lua_State* L) { // Augment:addDamageModifier(modifier) - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); return 0; @@ -8044,7 +7971,7 @@ int LuaScriptInterface::luaAugmentAddDamageModifier(lua_State* L) int LuaScriptInterface::luaAugmentRemoveDamageModifier(lua_State* L) { // Augment:RemoveDamageModifier(modifier) - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); return 0; @@ -8062,7 +7989,7 @@ int LuaScriptInterface::luaAugmentRemoveDamageModifier(lua_State* L) int LuaScriptInterface::luaAugmentGetAttackModifiers(lua_State* L) { // Augment:GetAttackModifiers([modType]) - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); lua_pushnil(L); @@ -8072,7 +7999,7 @@ int LuaScriptInterface::luaAugmentGetAttackModifiers(lua_State* L) { std::vector> modifiers; if (lua_gettop(L) > 1 && lua_isinteger(L, 2)) { - uint8_t modType = static_cast(lua_tointeger(L, 2)); + const uint8_t modType = static_cast(lua_tointeger(L, 2)); modifiers = augment->getAttackModifiers(modType); } else { modifiers = augment->getAttackModifiers(); @@ -8091,7 +8018,7 @@ int LuaScriptInterface::luaAugmentGetAttackModifiers(lua_State* L) { int LuaScriptInterface::luaAugmentGetDefenseModifiers(lua_State* L) { // Augment:GetDefenseModifiers([modType]) - auto augment = getSharedPtr(L, 1); + const auto augment = getSharedPtr(L, 1); if (!augment) { reportError(__FUNCTION__, "Invalid Augment userdata\n"); lua_pushnil(L); @@ -8123,11 +8050,10 @@ int LuaScriptInterface::luaAugmentGetDefenseModifiers(lua_State* L) { int LuaScriptInterface::luaContainerCreate(lua_State* L) { // Container(uid) - uint32_t id = getNumber(L, 2); + const uint32_t id = getNumber(L, 2); - Container* container = getScriptEnv()->getContainerByUID(id); - if (container) { - pushUserdata(L, container); + if (const auto container = getScriptEnv()->getContainerByUID(id)) { + pushSharedPtr(L, container); setMetatable(L, -1, "Container"); } else { lua_pushnil(L); @@ -8138,8 +8064,7 @@ int LuaScriptInterface::luaContainerCreate(lua_State* L) int LuaScriptInterface::luaContainerGetSize(lua_State* L) { // container:getSize() - Container* container = getUserdata(L, 1); - if (container) { + if (const auto container = getSharedPtr(L, 1)) { lua_pushinteger(L, container->size()); } else { lua_pushnil(L); @@ -8150,8 +8075,7 @@ int LuaScriptInterface::luaContainerGetSize(lua_State* L) int LuaScriptInterface::luaContainerGetCapacity(lua_State* L) { // container:getCapacity() - Container* container = getUserdata(L, 1); - if (container) { + if (const auto container = getSharedPtr(L, 1)) { lua_pushinteger(L, container->capacity()); } else { lua_pushnil(L); @@ -8162,17 +8086,16 @@ int LuaScriptInterface::luaContainerGetCapacity(lua_State* L) int LuaScriptInterface::luaContainerGetEmptySlots(lua_State* L) { // container:getEmptySlots([recursive = false]) - Container* container = getUserdata(L, 1); + const auto container = getSharedPtr(L, 1); if (!container) { lua_pushnil(L); return 1; } uint32_t slots = container->capacity() - container->size(); - bool recursive = getBoolean(L, 2, false); - if (recursive) { + if (getBoolean(L, 2, false)) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - if (Container* tmpContainer = (*it)->getContainer()) { + if (const auto tmpContainer = (*it)->getContainer()) { slots += tmpContainer->capacity() - tmpContainer->size(); } } @@ -8184,8 +8107,7 @@ int LuaScriptInterface::luaContainerGetEmptySlots(lua_State* L) int LuaScriptInterface::luaContainerGetItemHoldingCount(lua_State* L) { // container:getItemHoldingCount() - Container* container = getUserdata(L, 1); - if (container) { + if (const auto container = getSharedPtr(L, 1)) { lua_pushinteger(L, container->getItemHoldingCount()); } else { lua_pushnil(L); @@ -8196,16 +8118,15 @@ int LuaScriptInterface::luaContainerGetItemHoldingCount(lua_State* L) int LuaScriptInterface::luaContainerGetItem(lua_State* L) { // container:getItem(index) - Container* container = getUserdata(L, 1); + const auto container = getSharedPtr(L, 1); if (!container) { lua_pushnil(L); return 1; } uint32_t index = getNumber(L, 2); - Item* item = container->getItemByIndex(index); - if (item) { - pushUserdata(L, item); + if (const auto item = container->getItemByIndex(index)) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -8216,9 +8137,8 @@ int LuaScriptInterface::luaContainerGetItem(lua_State* L) int LuaScriptInterface::luaContainerHasItem(lua_State* L) { // container:hasItem(item) - Item* item = getUserdata(L, 2); - Container* container = getUserdata(L, 1); - if (container) { + if (const auto container = getSharedPtr(L, 1); + const auto item = getSharedPtr(L, 2)) { pushBoolean(L, container->isHoldingItem(item)); } else { lua_pushnil(L); @@ -8229,7 +8149,7 @@ int LuaScriptInterface::luaContainerHasItem(lua_State* L) int LuaScriptInterface::luaContainerAddItem(lua_State* L) { // container:addItem(itemId[, count/subType = 1[, index = INDEX_WHEREEVER[, flags = 0]]]) - Container* container = getUserdata(L, 1); + const auto container = getSharedPtr(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -8272,8 +8192,8 @@ int LuaScriptInterface::luaContainerAddItem(lua_State* L) uint32_t flags = getNumber(L, 5, 0); for (int32_t i = 1; i <= itemCount; ++i) { - int32_t stackCount = std::min(subType, 100); - Item* item = Item::CreateItem(itemId, stackCount); + const int32_t stackCount = std::min(subType, 100); + auto item = Item::CreateItem(itemId, stackCount); if (!item) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); if (!hasTable) { @@ -8285,10 +8205,10 @@ int LuaScriptInterface::luaContainerAddItem(lua_State* L) if (it.stackable) { subType -= stackCount; } - - ReturnValue ret = g_game.internalAddItem(container, item, index, flags); + CylinderPtr holder = container; + ReturnValue ret = g_game.internalAddItem(holder, item, index, flags); if (ret != RETURNVALUE_NOERROR) { - delete item; + item.reset(); if (!hasTable) { lua_pushnil(L); } @@ -8297,11 +8217,11 @@ int LuaScriptInterface::luaContainerAddItem(lua_State* L) if (hasTable) { lua_pushinteger(L, i); - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); lua_settable(L, -3); } else { - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } } @@ -8311,13 +8231,13 @@ int LuaScriptInterface::luaContainerAddItem(lua_State* L) int LuaScriptInterface::luaContainerAddItemEx(lua_State* L) { // container:addItemEx(item[, index = INDEX_WHEREEVER[, flags = 0]]) - Item* item = getUserdata(L, 2); + const auto item = getSharedPtr(L, 2); if (!item) { lua_pushnil(L); return 1; } - Container* container = getUserdata(L, 1); + const auto container = getSharedPtr(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -8331,7 +8251,8 @@ int LuaScriptInterface::luaContainerAddItemEx(lua_State* L) int32_t index = getNumber(L, 3, INDEX_WHEREEVER); uint32_t flags = getNumber(L, 4, 0); - ReturnValue ret = g_game.internalAddItem(container, item, index, flags); + CylinderPtr holder = container; + ReturnValue ret = g_game.internalAddItem(holder, item, index, flags); if (ret == RETURNVALUE_NOERROR) { ScriptEnvironment::removeTempItem(item); } @@ -8342,8 +8263,7 @@ int LuaScriptInterface::luaContainerAddItemEx(lua_State* L) int LuaScriptInterface::luaContainerGetCorpseOwner(lua_State* L) { // container:getCorpseOwner() - Container* container = getUserdata(L, 1); - if (container) { + if (const auto container = getSharedPtr(L, 1)) { lua_pushinteger(L, container->getCorpseOwner()); } else { lua_pushnil(L); @@ -8354,7 +8274,7 @@ int LuaScriptInterface::luaContainerGetCorpseOwner(lua_State* L) int LuaScriptInterface::luaContainerGetItemCountById(lua_State* L) { // container:getItemCountById(itemId[, subType = -1]) - Container* container = getUserdata(L, 1); + const auto container = getSharedPtr(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -8379,8 +8299,7 @@ int LuaScriptInterface::luaContainerGetItemCountById(lua_State* L) int LuaScriptInterface::luaContainerGetContentDescription(lua_State* L) { // container:getContentDescription() - Container* container = getUserdata(L, 1); - if (container) { + if (const auto container = getSharedPtr(L, 1)) { pushString(L, container->getContentDescription()); } else { lua_pushnil(L); @@ -8391,20 +8310,20 @@ int LuaScriptInterface::luaContainerGetContentDescription(lua_State* L) int LuaScriptInterface::luaContainerGetItems(lua_State* L) { // container:getItems([recursive = false]) - Container* container = getUserdata(L, 1); + const auto container = getSharedPtr(L, 1); if (!container) { lua_pushnil(L); return 1; } bool recursive = getBoolean(L, 2, false); - std::vector items = container->getItems(recursive); + const auto items = container->getItems(recursive); lua_createtable(L, items.size(), 0); int index = 0; - for (Item* item : items) { - pushUserdata(L, item); + for (const auto item : items) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); lua_rawseti(L, -2, ++index); } @@ -8415,11 +8334,10 @@ int LuaScriptInterface::luaContainerGetItems(lua_State* L) int LuaScriptInterface::luaTeleportCreate(lua_State* L) { // Teleport(uid) - uint32_t id = getNumber(L, 2); + const uint32_t id = getNumber(L, 2); - Item* item = getScriptEnv()->getItemByUID(id); - if (item && item->getTeleport()) { - pushUserdata(L, item); + if (const auto item = getScriptEnv()->getItemByUID(id); item && item->getTeleport()) { + pushSharedPtr(L, item); setMetatable(L, -1, "Teleport"); } else { lua_pushnil(L); @@ -8430,8 +8348,7 @@ int LuaScriptInterface::luaTeleportCreate(lua_State* L) int LuaScriptInterface::luaTeleportGetDestination(lua_State* L) { // teleport:getDestination() - Teleport* teleport = getUserdata(L, 1); - if (teleport) { + if (const auto teleport = getSharedPtr(L, 1)) { pushPosition(L, teleport->getDestPos()); } else { lua_pushnil(L); @@ -8442,8 +8359,7 @@ int LuaScriptInterface::luaTeleportGetDestination(lua_State* L) int LuaScriptInterface::luaTeleportSetDestination(lua_State* L) { // teleport:setDestination(position) - Teleport* teleport = getUserdata(L, 1); - if (teleport) { + if (const auto teleport = getSharedPtr(L, 1)) { teleport->setDestPos(getPosition(L, 2)); pushBoolean(L, true); } else { @@ -8456,24 +8372,23 @@ int LuaScriptInterface::luaTeleportSetDestination(lua_State* L) int LuaScriptInterface::luaCreatureCreate(lua_State* L) { // Creature(id or name or userdata) - Creature* creature; + CreaturePtr creature; if (isNumber(L, 2)) { creature = g_game.getCreatureByID(getNumber(L, 2)); } else if (isString(L, 2)) { creature = g_game.getCreatureByName(getString(L, 2)); } else if (isUserdata(L, 2)) { - LuaDataType type = getUserdataType(L, 2); - if (type != LuaData_Player && type != LuaData_Monster && type != LuaData_Npc) { + if (const LuaDataType type = getUserdataType(L, 2); type != LuaData_Player && type != LuaData_Monster && type != LuaData_Npc) { lua_pushnil(L); return 1; } - creature = getUserdata(L, 2); + creature = getSharedPtr(L, 2); } else { creature = nullptr; } if (creature) { - pushUserdata(L, creature); + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); } else { lua_pushnil(L); @@ -8484,18 +8399,18 @@ int LuaScriptInterface::luaCreatureCreate(lua_State* L) int LuaScriptInterface::luaCreatureGetEvents(lua_State* L) { // creature:getEvents(type) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - CreatureEventType_t eventType = getNumber(L, 2); + const CreatureEventType_t eventType = getNumber(L, 2); const auto& eventList = creature->getCreatureEvents(eventType); lua_createtable(L, eventList.size(), 0); int index = 0; - for (CreatureEvent* event : eventList) { + for (const auto event : eventList) { pushString(L, event->getName()); lua_rawseti(L, -2, ++index); } @@ -8505,8 +8420,7 @@ int LuaScriptInterface::luaCreatureGetEvents(lua_State* L) int LuaScriptInterface::luaCreatureRegisterEvent(lua_State* L) { // creature:registerEvent(name) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { const std::string& name = getString(L, 2); pushBoolean(L, creature->registerCreatureEvent(name)); } else { @@ -8519,8 +8433,7 @@ int LuaScriptInterface::luaCreatureUnregisterEvent(lua_State* L) { // creature:unregisterEvent(name) const std::string& name = getString(L, 2); - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->unregisterCreatureEvent(name)); } else { lua_pushnil(L); @@ -8531,8 +8444,7 @@ int LuaScriptInterface::luaCreatureUnregisterEvent(lua_State* L) int LuaScriptInterface::luaCreatureIsRemoved(lua_State* L) { // creature:isRemoved() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->isRemoved()); } else { lua_pushnil(L); @@ -8543,15 +8455,14 @@ int LuaScriptInterface::luaCreatureIsRemoved(lua_State* L) int LuaScriptInterface::luaCreatureIsCreature(lua_State* L) { // creature:isCreature() - pushBoolean(L, getUserdata(L, 1) != nullptr); + pushBoolean(L, getSharedPtr(L, 1) != nullptr); return 1; } int LuaScriptInterface::luaCreatureIsInGhostMode(lua_State* L) { // creature:isInGhostMode() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->isInGhostMode()); } else { lua_pushnil(L); @@ -8562,8 +8473,7 @@ int LuaScriptInterface::luaCreatureIsInGhostMode(lua_State* L) int LuaScriptInterface::luaCreatureIsHealthHidden(lua_State* L) { // creature:isHealthHidden() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->isHealthHidden()); } else { lua_pushnil(L); @@ -8574,8 +8484,7 @@ int LuaScriptInterface::luaCreatureIsHealthHidden(lua_State* L) int LuaScriptInterface::luaCreatureIsMovementBlocked(lua_State* L) { // creature:isMovementBlocked() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->isMovementBlocked()); } else { lua_pushnil(L); @@ -8586,8 +8495,7 @@ int LuaScriptInterface::luaCreatureIsMovementBlocked(lua_State* L) int LuaScriptInterface::luaCreatureCanSee(lua_State* L) { // creature:canSee(position) - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { const Position& position = getPosition(L, 2); pushBoolean(L, creature->canSee(position)); } else { @@ -8599,16 +8507,15 @@ int LuaScriptInterface::luaCreatureCanSee(lua_State* L) int LuaScriptInterface::luaCreatureCanSeeCreature(lua_State* L) { // creature:canSeeCreature(creature) - const Creature* creature = getUserdata(L, 1); - if (creature) { - const Creature* otherCreature = getCreature(L, 2); - if (!otherCreature) { + if (const auto creature = getSharedPtr(L, 1)) { + const auto other_creature = getCreature(L, 2); + if (!other_creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - pushBoolean(L, creature->canSeeCreature(otherCreature)); + pushBoolean(L, creature->canSeeCreature(other_creature)); } else { lua_pushnil(L); } @@ -8618,9 +8525,8 @@ int LuaScriptInterface::luaCreatureCanSeeCreature(lua_State* L) int LuaScriptInterface::luaCreatureCanSeeGhostMode(lua_State* L) { // creature:canSeeGhostMode(creature) - const Creature* creature = getUserdata(L, 1); - if (creature) { - const Creature* otherCreature = getCreature(L, 2); + if (const auto creature = getSharedPtr(L, 1)) { + const auto otherCreature = getCreature(L, 2); if (!otherCreature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -8637,8 +8543,7 @@ int LuaScriptInterface::luaCreatureCanSeeGhostMode(lua_State* L) int LuaScriptInterface::luaCreatureCanSeeInvisibility(lua_State* L) { // creature:canSeeInvisibility() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->canSeeInvisibility()); } else { lua_pushnil(L); @@ -8649,13 +8554,13 @@ int LuaScriptInterface::luaCreatureCanSeeInvisibility(lua_State* L) int LuaScriptInterface::luaCreatureGetParent(lua_State* L) { // creature:getParent() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - Cylinder* parent = creature->getParent(); + CylinderPtr parent = creature->getParent(); if (!parent) { lua_pushnil(L); return 1; @@ -8668,8 +8573,7 @@ int LuaScriptInterface::luaCreatureGetParent(lua_State* L) int LuaScriptInterface::luaCreatureGetId(lua_State* L) { // creature:getId() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getID()); } else { lua_pushnil(L); @@ -8680,8 +8584,7 @@ int LuaScriptInterface::luaCreatureGetId(lua_State* L) int LuaScriptInterface::luaCreatureGetName(lua_State* L) { // creature:getName() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushString(L, creature->getName()); } else { lua_pushnil(L); @@ -8692,15 +8595,14 @@ int LuaScriptInterface::luaCreatureGetName(lua_State* L) int LuaScriptInterface::luaCreatureGetTarget(lua_State* L) { // creature:getTarget() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - Creature* target = creature->getAttackedCreature(); - if (target) { - pushUserdata(L, target); + if (const auto target = creature->getAttackedCreature()) { + pushSharedPtr(L, target); setCreatureMetatable(L, -1, target); } else { lua_pushnil(L); @@ -8711,8 +8613,7 @@ int LuaScriptInterface::luaCreatureGetTarget(lua_State* L) int LuaScriptInterface::luaCreatureSetTarget(lua_State* L) { // creature:setTarget(target) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->setAttackedCreature(getCreature(L, 2))); } else { lua_pushnil(L); @@ -8723,15 +8624,14 @@ int LuaScriptInterface::luaCreatureSetTarget(lua_State* L) int LuaScriptInterface::luaCreatureGetFollowCreature(lua_State* L) { // creature:getFollowCreature() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - Creature* followCreature = creature->getFollowCreature(); - if (followCreature) { - pushUserdata(L, followCreature); + if (const auto followCreature = creature->getFollowCreature()) { + pushSharedPtr(L, followCreature); setCreatureMetatable(L, -1, followCreature); } else { lua_pushnil(L); @@ -8742,8 +8642,7 @@ int LuaScriptInterface::luaCreatureGetFollowCreature(lua_State* L) int LuaScriptInterface::luaCreatureSetFollowCreature(lua_State* L) { // creature:setFollowCreature(followedCreature) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, creature->setFollowCreature(getCreature(L, 2))); } else { lua_pushnil(L); @@ -8754,19 +8653,19 @@ int LuaScriptInterface::luaCreatureSetFollowCreature(lua_State* L) int LuaScriptInterface::luaCreatureGetMaster(lua_State* L) { // creature:getMaster() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - Creature* master = creature->getMaster(); + const auto master = creature->getMaster(); if (!master) { lua_pushnil(L); return 1; } - pushUserdata(L, master); + pushSharedPtr(L, master); setCreatureMetatable(L, -1, master); return 1; } @@ -8774,7 +8673,7 @@ int LuaScriptInterface::luaCreatureGetMaster(lua_State* L) int LuaScriptInterface::luaCreatureSetMaster(lua_State* L) { // creature:setMaster(master) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -8790,13 +8689,13 @@ int LuaScriptInterface::luaCreatureSetMaster(lua_State* L) int LuaScriptInterface::luaCreatureGetLight(lua_State* L) { // creature:getLight() - const Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - LightInfo lightInfo = creature->getCreatureLight(); + const LightInfo lightInfo = creature->getCreatureLight(); lua_pushinteger(L, lightInfo.level); lua_pushinteger(L, lightInfo.color); return 2; @@ -8805,7 +8704,7 @@ int LuaScriptInterface::luaCreatureGetLight(lua_State* L) int LuaScriptInterface::luaCreatureSetLight(lua_State* L) { // creature:setLight(color, level) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -8823,8 +8722,7 @@ int LuaScriptInterface::luaCreatureSetLight(lua_State* L) int LuaScriptInterface::luaCreatureGetSpeed(lua_State* L) { // creature:getSpeed() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getUserdata(L, 1)) { lua_pushinteger(L, creature->getSpeed()); } else { lua_pushnil(L); @@ -8835,8 +8733,7 @@ int LuaScriptInterface::luaCreatureGetSpeed(lua_State* L) int LuaScriptInterface::luaCreatureGetBaseSpeed(lua_State* L) { // creature:getBaseSpeed() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getBaseSpeed()); } else { lua_pushnil(L); @@ -8847,7 +8744,7 @@ int LuaScriptInterface::luaCreatureGetBaseSpeed(lua_State* L) int LuaScriptInterface::luaCreatureChangeSpeed(lua_State* L) { // creature:changeSpeed(delta) - Creature* creature = getCreature(L, 1); + const auto creature = getCreature(L, 1); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -8863,8 +8760,7 @@ int LuaScriptInterface::luaCreatureChangeSpeed(lua_State* L) int LuaScriptInterface::luaCreatureSetDropLoot(lua_State* L) { // creature:setDropLoot(doDrop) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { creature->setDropLoot(getBoolean(L, 2)); pushBoolean(L, true); } else { @@ -8876,8 +8772,7 @@ int LuaScriptInterface::luaCreatureSetDropLoot(lua_State* L) int LuaScriptInterface::luaCreatureSetSkillLoss(lua_State* L) { // creature:setSkillLoss(skillLoss) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { creature->setSkillLoss(getBoolean(L, 2)); pushBoolean(L, true); } else { @@ -8889,8 +8784,7 @@ int LuaScriptInterface::luaCreatureSetSkillLoss(lua_State* L) int LuaScriptInterface::luaCreatureGetPosition(lua_State* L) { // creature:getPosition() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushPosition(L, creature->getPosition()); } else { lua_pushnil(L); @@ -8901,15 +8795,14 @@ int LuaScriptInterface::luaCreatureGetPosition(lua_State* L) int LuaScriptInterface::luaCreatureGetTile(lua_State* L) { // creature:getTile() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - Tile* tile = creature->getTile(); - if (tile) { - pushUserdata(L, tile); + if (const auto tile = creature->getTile()) { + pushSharedPtr(L, tile); setMetatable(L, -1, "Tile"); } else { lua_pushnil(L); @@ -8920,8 +8813,7 @@ int LuaScriptInterface::luaCreatureGetTile(lua_State* L) int LuaScriptInterface::luaCreatureGetDirection(lua_State* L) { // creature:getDirection() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getDirection()); } else { lua_pushnil(L); @@ -8932,8 +8824,7 @@ int LuaScriptInterface::luaCreatureGetDirection(lua_State* L) int LuaScriptInterface::luaCreatureSetDirection(lua_State* L) { // creature:setDirection(direction) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushBoolean(L, g_game.internalCreatureTurn(creature, getNumber(L, 2))); } else { lua_pushnil(L); @@ -8944,8 +8835,7 @@ int LuaScriptInterface::luaCreatureSetDirection(lua_State* L) int LuaScriptInterface::luaCreatureGetHealth(lua_State* L) { // creature:getHealth() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getHealth()); } else { lua_pushnil(L); @@ -8956,7 +8846,7 @@ int LuaScriptInterface::luaCreatureGetHealth(lua_State* L) int LuaScriptInterface::luaCreatureSetHealth(lua_State* L) { // creature:setHealth(health) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -8965,8 +8855,7 @@ int LuaScriptInterface::luaCreatureSetHealth(lua_State* L) creature->health = std::min(getNumber(L, 2), creature->healthMax); g_game.addCreatureHealth(creature); - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } pushBoolean(L, true); @@ -8976,7 +8865,7 @@ int LuaScriptInterface::luaCreatureSetHealth(lua_State* L) int LuaScriptInterface::luaCreatureAddHealth(lua_State* L) { // creature:addHealth(healthChange) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -8996,8 +8885,7 @@ int LuaScriptInterface::luaCreatureAddHealth(lua_State* L) int LuaScriptInterface::luaCreatureGetMaxHealth(lua_State* L) { // creature:getMaxHealth() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getMaxHealth()); } else { lua_pushnil(L); @@ -9008,7 +8896,7 @@ int LuaScriptInterface::luaCreatureGetMaxHealth(lua_State* L) int LuaScriptInterface::luaCreatureSetMaxHealth(lua_State* L) { // creature:setMaxHealth(maxHealth) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9018,8 +8906,7 @@ int LuaScriptInterface::luaCreatureSetMaxHealth(lua_State* L) creature->health = std::min(creature->health, creature->healthMax); g_game.addCreatureHealth(creature); - Player* player = creature->getPlayer(); - if (player) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } pushBoolean(L, true); @@ -9029,8 +8916,7 @@ int LuaScriptInterface::luaCreatureSetMaxHealth(lua_State* L) int LuaScriptInterface::luaCreatureSetHiddenHealth(lua_State* L) { // creature:setHiddenHealth(hide) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { creature->setHiddenHealth(getBoolean(L, 2)); g_game.addCreatureHealth(creature); pushBoolean(L, true); @@ -9043,8 +8929,7 @@ int LuaScriptInterface::luaCreatureSetHiddenHealth(lua_State* L) int LuaScriptInterface::luaCreatureSetMovementBlocked(lua_State* L) { // creature:setMovementBlocked(state) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { creature->setMovementBlocked(getBoolean(L, 2)); pushBoolean(L, true); } else { @@ -9056,8 +8941,7 @@ int LuaScriptInterface::luaCreatureSetMovementBlocked(lua_State* L) int LuaScriptInterface::luaCreatureGetSkull(lua_State* L) { // creature:getSkull() - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getSkull()); } else { lua_pushnil(L); @@ -9068,8 +8952,7 @@ int LuaScriptInterface::luaCreatureGetSkull(lua_State* L) int LuaScriptInterface::luaCreatureSetSkull(lua_State* L) { // creature:setSkull(skull) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { creature->setSkull(getNumber(L, 2)); pushBoolean(L, true); } else { @@ -9081,8 +8964,7 @@ int LuaScriptInterface::luaCreatureSetSkull(lua_State* L) int LuaScriptInterface::luaCreatureGetOutfit(lua_State* L) { // creature:getOutfit() - const Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushOutfit(L, creature->getCurrentOutfit()); } else { lua_pushnil(L); @@ -9093,8 +8975,7 @@ int LuaScriptInterface::luaCreatureGetOutfit(lua_State* L) int LuaScriptInterface::luaCreatureSetOutfit(lua_State* L) { // creature:setOutfit(outfit) - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { creature->defaultOutfit = getOutfit(L, 2); g_game.internalCreatureChangeOutfit(creature, creature->defaultOutfit); pushBoolean(L, true); @@ -9107,7 +8988,7 @@ int LuaScriptInterface::luaCreatureSetOutfit(lua_State* L) int LuaScriptInterface::luaCreatureGetCondition(lua_State* L) { // creature:getCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0]]) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9117,8 +8998,7 @@ int LuaScriptInterface::luaCreatureGetCondition(lua_State* L) ConditionId_t conditionId = getNumber(L, 3, CONDITIONID_COMBAT); uint32_t subId = getNumber(L, 4, 0); - Condition* condition = creature->getCondition(conditionType, conditionId, subId); - if (condition) { + if (const auto condition = creature->getCondition(conditionType, conditionId, subId)) { pushUserdata(L, condition); setWeakMetatable(L, -1, "Condition"); } else { @@ -9130,10 +9010,10 @@ int LuaScriptInterface::luaCreatureGetCondition(lua_State* L) int LuaScriptInterface::luaCreatureAddCondition(lua_State* L) { // creature:addCondition(condition[, force = false]) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); Condition* condition = getUserdata(L, 2); if (creature && condition) { - bool force = getBoolean(L, 3, false); + const bool force = getBoolean(L, 3, false); pushBoolean(L, creature->addCondition(condition->clone(), force)); } else { lua_pushnil(L); @@ -9145,7 +9025,7 @@ int LuaScriptInterface::luaCreatureRemoveCondition(lua_State* L) { // creature:removeCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0[, force = false]]]) // creature:removeCondition(condition[, force = false]) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9178,14 +9058,14 @@ int LuaScriptInterface::luaCreatureRemoveCondition(lua_State* L) int LuaScriptInterface::luaCreatureHasCondition(lua_State* L) { // creature:hasCondition(conditionType[, subId = 0]) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } - ConditionType_t conditionType = getNumber(L, 2); - uint32_t subId = getNumber(L, 3, 0); + const auto conditionType = getNumber(L, 2); + const uint32_t subId = getNumber(L, 3, 0); pushBoolean(L, creature->hasCondition(conditionType, subId)); return 1; } @@ -9193,7 +9073,7 @@ int LuaScriptInterface::luaCreatureHasCondition(lua_State* L) int LuaScriptInterface::luaCreatureIsImmune(lua_State* L) { // creature:isImmune(condition or conditionType) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9212,26 +9092,25 @@ int LuaScriptInterface::luaCreatureIsImmune(lua_State* L) int LuaScriptInterface::luaCreatureRemove(lua_State* L) { // creature:remove() - Creature** creaturePtr = getRawUserdata(L, 1); + auto creaturePtr = getSharedPtr(L, 1); if (!creaturePtr) { lua_pushnil(L); return 1; } - Creature* creature = *creaturePtr; + auto creature = creaturePtr; if (!creature) { lua_pushnil(L); return 1; } - Player* player = creature->getPlayer(); - if (player) { + if (auto player = creature->getPlayer()) { player->kickPlayer(true); } else { g_game.removeCreature(creature); } - *creaturePtr = nullptr; + creaturePtr = nullptr; pushBoolean(L, true); return 1; } @@ -9242,7 +9121,7 @@ int LuaScriptInterface::luaCreatureTeleportTo(lua_State* L) bool pushMovement = getBoolean(L, 3) || false ; const Position& position = getPosition(L, 2); - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9286,16 +9165,16 @@ int LuaScriptInterface::luaCreatureSay(lua_State* L) } } - Creature* target = nullptr; + CreaturePtr target = nullptr; if (parameters >= 5) { target = getCreature(L, 5); } - bool ghost = getBoolean(L, 4, false); + const bool ghost = getBoolean(L, 4, false); - SpeakClasses type = getNumber(L, 3, TALKTYPE_MONSTER_SAY); + const SpeakClasses type = getNumber(L, 3, TALKTYPE_MONSTER_SAY); const std::string& text = getString(L, 2); - Creature* creature = getUserdata(L, 1); + const CreaturePtr creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9307,7 +9186,7 @@ int LuaScriptInterface::luaCreatureSay(lua_State* L) } // Prevent infinity echo on event onHear - bool echo = getScriptEnv()->getScriptId() == g_events->getScriptId(EventInfoId::CREATURE_ONHEAR); + const bool echo = getScriptEnv()->getScriptId() == g_events->getScriptId(EventInfoId::CREATURE_ONHEAR); if (position.x != 0) { pushBoolean(L, g_game.internalCreatureSay(creature, type, text, ghost, &spectators, &position, echo)); @@ -9320,18 +9199,18 @@ int LuaScriptInterface::luaCreatureSay(lua_State* L) int LuaScriptInterface::luaCreatureGetDamageMap(lua_State* L) { // creature:getDamageMap() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } lua_createtable(L, creature->damageMap.size(), 0); - for (const auto& damageEntry : creature->damageMap) { + for (const auto& [index, value] : creature->damageMap) { lua_createtable(L, 0, 2); - setField(L, "total", damageEntry.second.total); - setField(L, "ticks", damageEntry.second.ticks); - lua_rawseti(L, -2, damageEntry.first); + setField(L, "total", value.total); + setField(L, "ticks", value.ticks); + lua_rawseti(L, -2, index); } return 1; } @@ -9339,7 +9218,7 @@ int LuaScriptInterface::luaCreatureGetDamageMap(lua_State* L) int LuaScriptInterface::luaCreatureGetSummons(lua_State* L) { // creature:getSummons() - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9348,8 +9227,8 @@ int LuaScriptInterface::luaCreatureGetSummons(lua_State* L) lua_createtable(L, creature->getSummonCount(), 0); int index = 0; - for (Creature* summon : creature->getSummons()) { - pushUserdata(L, summon); + for (const auto summon : creature->getSummons()) { + pushSharedPtr(L, summon); setCreatureMetatable(L, -1, summon); lua_rawseti(L, -2, ++index); } @@ -9360,8 +9239,7 @@ int LuaScriptInterface::luaCreatureGetDescription(lua_State* L) { // creature:getDescription(distance) int32_t distance = getNumber(L, 2); - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { pushString(L, creature->getDescription(distance)); } else { lua_pushnil(L); @@ -9372,7 +9250,7 @@ int LuaScriptInterface::luaCreatureGetDescription(lua_State* L) int LuaScriptInterface::luaCreatureGetPathTo(lua_State* L) { // creature:getPathTo(pos[, minTargetDist = 0[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]]) - Creature* creature = getUserdata(L, 1); + const auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -9387,8 +9265,7 @@ int LuaScriptInterface::luaCreatureGetPathTo(lua_State* L) fpp.clearSight = getBoolean(L, 6, fpp.clearSight); fpp.maxSearchDist = getNumber(L, 7, fpp.maxSearchDist); - std::vector dirList; - if (creature->getPathTo(position, dirList, fpp)) { + if (std::vector dirList; creature->getPathTo(position, dirList, fpp)) { lua_newtable(L); int index = 0; @@ -9406,26 +9283,26 @@ int LuaScriptInterface::luaCreatureMove(lua_State* L) { // creature:move(direction) // creature:move(tile[, flags = 0]) - Creature* creature = getUserdata(L, 1); + auto creature = getSharedPtr(L, 1); if (!creature) { lua_pushnil(L); return 1; } if (isNumber(L, 2)) { - Direction direction = getNumber(L, 2); + const Direction direction = getNumber(L, 2); if (direction > DIRECTION_LAST) { lua_pushnil(L); return 1; } lua_pushinteger(L, g_game.internalMoveCreature(creature, direction, FLAG_NOLIMIT)); } else { - Tile* tile = getUserdata(L, 2); + const auto tile = getSharedPtr(L, 2); if (!tile) { lua_pushnil(L); return 1; } - lua_pushinteger(L, g_game.internalMoveCreature(*creature, *tile, getNumber(L, 3))); + lua_pushinteger(L, g_game.internalMoveCreature(creature, tile, getNumber(L, 3))); } return 1; } @@ -9433,8 +9310,7 @@ int LuaScriptInterface::luaCreatureMove(lua_State* L) int LuaScriptInterface::luaCreatureGetZone(lua_State* L) { // creature:getZone() - Creature* creature = getUserdata(L, 1); - if (creature) { + if (const auto creature = getSharedPtr(L, 1)) { lua_pushinteger(L, creature->getZone()); } else { lua_pushnil(L); @@ -9446,17 +9322,15 @@ int LuaScriptInterface::luaCreatureGetZone(lua_State* L) int LuaScriptInterface::luaPlayerCreate(lua_State* L) { // Player(id or guid or name or userdata) - Player* player; + PlayerPtr player; if (isNumber(L, 2)) { - uint32_t id = getNumber(L, 2); - if (id >= 0x10000000 && id <= Player::playerAutoID) { + if (const uint32_t id = getNumber(L, 2); id >= 0x10000000 && id <= Player::playerAutoID) { player = g_game.getPlayerByID(id); } else { player = g_game.getPlayerByGUID(id); } } else if (isString(L, 2)) { - ReturnValue ret = g_game.getPlayerByNameWildcard(getString(L, 2), player); - if (ret != RETURNVALUE_NOERROR) { + if (const ReturnValue ret = g_game.getPlayerByNameWildcard(getString(L, 2)); ret != RETURNVALUE_NOERROR) { lua_pushnil(L); lua_pushinteger(L, ret); return 2; @@ -9466,13 +9340,13 @@ int LuaScriptInterface::luaPlayerCreate(lua_State* L) lua_pushnil(L); return 1; } - player = getUserdata(L, 2); + player = getSharedPtr(L, 2); } else { player = nullptr; } if (player) { - pushUserdata(L, player); + pushSharedPtr(L, player); setMetatable(L, -1, "Player"); } else { lua_pushnil(L); @@ -9483,15 +9357,14 @@ int LuaScriptInterface::luaPlayerCreate(lua_State* L) int LuaScriptInterface::luaPlayerIsPlayer(lua_State* L) { // player:isPlayer() - pushBoolean(L, getUserdata(L, 1) != nullptr); + pushBoolean(L, getSharedPtr(L, 1) != nullptr); return 1; } int LuaScriptInterface::luaPlayerGetGuid(lua_State* L) { // player:getGuid() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getGUID()); } else { lua_pushnil(L); @@ -9502,8 +9375,7 @@ int LuaScriptInterface::luaPlayerGetGuid(lua_State* L) int LuaScriptInterface::luaPlayerGetIp(lua_State* L) { // player:getIp() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getIP()); } else { lua_pushnil(L); @@ -9514,8 +9386,7 @@ int LuaScriptInterface::luaPlayerGetIp(lua_State* L) int LuaScriptInterface::luaPlayerGetAccountId(lua_State* L) { // player:getAccountId() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getAccount()); } else { lua_pushnil(L); @@ -9526,8 +9397,7 @@ int LuaScriptInterface::luaPlayerGetAccountId(lua_State* L) int LuaScriptInterface::luaPlayerGetLastLoginSaved(lua_State* L) { // player:getLastLoginSaved() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getLastLoginSaved()); } else { lua_pushnil(L); @@ -9538,8 +9408,7 @@ int LuaScriptInterface::luaPlayerGetLastLoginSaved(lua_State* L) int LuaScriptInterface::luaPlayerGetLastLogout(lua_State* L) { // player:getLastLogout() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getLastLogout()); } else { lua_pushnil(L); @@ -9550,8 +9419,7 @@ int LuaScriptInterface::luaPlayerGetLastLogout(lua_State* L) int LuaScriptInterface::luaPlayerGetAccountType(lua_State* L) { // player:getAccountType() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getAccountType()); } else { lua_pushnil(L); @@ -9562,8 +9430,7 @@ int LuaScriptInterface::luaPlayerGetAccountType(lua_State* L) int LuaScriptInterface::luaPlayerSetAccountType(lua_State* L) { // player:setAccountType(accountType) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->accountType = getNumber(L, 2); IOLoginData::setAccountType(player->getAccount(), player->accountType); pushBoolean(L, true); @@ -9576,8 +9443,7 @@ int LuaScriptInterface::luaPlayerSetAccountType(lua_State* L) int LuaScriptInterface::luaPlayerGetCapacity(lua_State* L) { // player:getCapacity() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getCapacity()); } else { lua_pushnil(L); @@ -9588,8 +9454,7 @@ int LuaScriptInterface::luaPlayerGetCapacity(lua_State* L) int LuaScriptInterface::luaPlayerSetCapacity(lua_State* L) { // player:setCapacity(capacity) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->capacity = getNumber(L, 2); player->sendStats(); pushBoolean(L, true); @@ -9602,8 +9467,7 @@ int LuaScriptInterface::luaPlayerSetCapacity(lua_State* L) int LuaScriptInterface::luaPlayerGetFreeCapacity(lua_State* L) { // player:getFreeCapacity() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getFreeCapacity()); } else { lua_pushnil(L); @@ -9614,8 +9478,7 @@ int LuaScriptInterface::luaPlayerGetFreeCapacity(lua_State* L) int LuaScriptInterface::luaPlayerGetDepotItemCount(lua_State* L) { // player:getDepotItemCount() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getDepotItemCount()); } else { @@ -9627,18 +9490,17 @@ int LuaScriptInterface::luaPlayerGetDepotItemCount(lua_State* L) int LuaScriptInterface::luaPlayerGetDepotChest(lua_State* L) { // player:getDepotChest(depotId[, autoCreate = false]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - uint32_t depotId = getNumber(L, 2); - bool autoCreate = getBoolean(L, 3, true); - DepotChest* depotChest = player->getDepotChest(depotId, autoCreate); - - if (depotChest) { - pushUserdata(L, depotChest); + const uint32_t depotId = getNumber(L, 2); + const bool autoCreate = getBoolean(L, 3, true); + + if (const auto depotChest = player->getDepotChest(depotId, autoCreate)) { + pushSharedPtr(L, depotChest); setItemMetatable(L, -1, depotChest); } else { pushBoolean(L, false); @@ -9649,15 +9511,14 @@ int LuaScriptInterface::luaPlayerGetDepotChest(lua_State* L) int LuaScriptInterface::luaPlayerGetInbox(lua_State* L) { // player:getInbox() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Inbox* inbox = player->getInbox(); - if (inbox) { - pushUserdata(L, inbox); + if (const auto inbox = player->getInbox()) { + pushSharedPtr(L, inbox); setItemMetatable(L, -1, inbox); } else { pushBoolean(L, false); @@ -9668,16 +9529,15 @@ int LuaScriptInterface::luaPlayerGetInbox(lua_State* L) int LuaScriptInterface::luaPlayerGetRewardChest(lua_State* L) { // player:getRewardChest() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - RewardChest& rewardChest = player->getRewardChest(); - if (&rewardChest) { - pushUserdata(L, &rewardChest); - setItemMetatable(L, -1, &rewardChest); + if (const auto rewardChest = player->getRewardChest()) { + pushSharedPtr(L, rewardChest); + setItemMetatable(L, -1, rewardChest); } else { pushBoolean(L, false); @@ -9688,8 +9548,7 @@ int LuaScriptInterface::luaPlayerGetRewardChest(lua_State* L) int LuaScriptInterface::luaPlayerGetSkullTime(lua_State* L) { // player:getSkullTime() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getSkullTicks()); } else { lua_pushnil(L); @@ -9700,8 +9559,7 @@ int LuaScriptInterface::luaPlayerGetSkullTime(lua_State* L) int LuaScriptInterface::luaPlayerSetSkullTime(lua_State* L) { // player:setSkullTime(skullTime) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->setSkullTicks(getNumber(L, 2)); pushBoolean(L, true); } else { @@ -9713,8 +9571,7 @@ int LuaScriptInterface::luaPlayerSetSkullTime(lua_State* L) int LuaScriptInterface::luaPlayerGetDeathPenalty(lua_State* L) { // player:getDeathPenalty() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushnumber(L, player->getLostPercent() * 100); } else { lua_pushnil(L); @@ -9725,8 +9582,7 @@ int LuaScriptInterface::luaPlayerGetDeathPenalty(lua_State* L) int LuaScriptInterface::luaPlayerGetExperience(lua_State* L) { // player:getExperience() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getExperience()); } else { lua_pushnil(L); @@ -9737,10 +9593,10 @@ int LuaScriptInterface::luaPlayerGetExperience(lua_State* L) int LuaScriptInterface::luaPlayerAddExperience(lua_State* L) { // player:addExperience(experience[, sendText = false]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (player) { - uint64_t experience = getNumber(L, 2); - bool sendText = getBoolean(L, 3, false); + const uint64_t experience = getNumber(L, 2); + const bool sendText = getBoolean(L, 3, false); player->addExperience(nullptr, experience, sendText); pushBoolean(L, true); } else { @@ -9752,10 +9608,9 @@ int LuaScriptInterface::luaPlayerAddExperience(lua_State* L) int LuaScriptInterface::luaPlayerRemoveExperience(lua_State* L) { // player:removeExperience(experience[, sendText = false]) - Player* player = getUserdata(L, 1); - if (player) { - uint64_t experience = getNumber(L, 2); - bool sendText = getBoolean(L, 3, false); + if (const auto player = getSharedPtr(L, 1)) { + const uint64_t experience = getNumber(L, 2); + const bool sendText = getBoolean(L, 3, false); player->removeExperience(experience, sendText); pushBoolean(L, true); } else { @@ -9767,8 +9622,7 @@ int LuaScriptInterface::luaPlayerRemoveExperience(lua_State* L) int LuaScriptInterface::luaPlayerGetLevel(lua_State* L) { // player:getLevel() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getLevel()); } else { lua_pushnil(L); @@ -9779,8 +9633,7 @@ int LuaScriptInterface::luaPlayerGetLevel(lua_State* L) int LuaScriptInterface::luaPlayerGetMagicLevel(lua_State* L) { // player:getMagicLevel() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getMagicLevel()); } else { lua_pushnil(L); @@ -9791,8 +9644,7 @@ int LuaScriptInterface::luaPlayerGetMagicLevel(lua_State* L) int LuaScriptInterface::luaPlayerGetBaseMagicLevel(lua_State* L) { // player:getBaseMagicLevel() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getBaseMagicLevel()); } else { lua_pushnil(L); @@ -9803,8 +9655,7 @@ int LuaScriptInterface::luaPlayerGetBaseMagicLevel(lua_State* L) int LuaScriptInterface::luaPlayerGetMana(lua_State* L) { // player:getMana() - const Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getMana()); } else { lua_pushnil(L); @@ -9815,14 +9666,14 @@ int LuaScriptInterface::luaPlayerGetMana(lua_State* L) int LuaScriptInterface::luaPlayerAddMana(lua_State* L) { // player:addMana(manaChange[, animationOnLoss = false]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - int32_t manaChange = getNumber(L, 2); - bool animationOnLoss = getBoolean(L, 3, false); + const int32_t manaChange = getNumber(L, 2); + const bool animationOnLoss = getBoolean(L, 3, false); if (!animationOnLoss && manaChange < 0) { player->changeMana(manaChange); } else { @@ -9838,8 +9689,7 @@ int LuaScriptInterface::luaPlayerAddMana(lua_State* L) int LuaScriptInterface::luaPlayerGetMaxMana(lua_State* L) { // player:getMaxMana() - const Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getMaxMana()); } else { lua_pushnil(L); @@ -9850,8 +9700,7 @@ int LuaScriptInterface::luaPlayerGetMaxMana(lua_State* L) int LuaScriptInterface::luaPlayerSetMaxMana(lua_State* L) { // player:setMaxMana(maxMana) - Player* player = getPlayer(L, 1); - if (player) { + if (const auto player = getPlayer(L, 1)) { player->manaMax = getNumber(L, 2); player->mana = std::min(player->mana, player->manaMax); player->sendStats(); @@ -9865,8 +9714,7 @@ int LuaScriptInterface::luaPlayerSetMaxMana(lua_State* L) int LuaScriptInterface::luaPlayerGetManaSpent(lua_State* L) { // player:getManaSpent() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getSpentMana()); } else { lua_pushnil(L); @@ -9877,8 +9725,7 @@ int LuaScriptInterface::luaPlayerGetManaSpent(lua_State* L) int LuaScriptInterface::luaPlayerAddManaSpent(lua_State* L) { // player:addManaSpent(amount) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->addManaSpent(getNumber(L, 2)); pushBoolean(L, true); } else { @@ -9890,8 +9737,7 @@ int LuaScriptInterface::luaPlayerAddManaSpent(lua_State* L) int LuaScriptInterface::luaPlayerRemoveManaSpent(lua_State* L) { // player:removeManaSpent(amount[, notify = true]) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->removeManaSpent(getNumber(L, 2), getBoolean(L, 3, true)); pushBoolean(L, true); } else { @@ -9903,8 +9749,7 @@ int LuaScriptInterface::luaPlayerRemoveManaSpent(lua_State* L) int LuaScriptInterface::luaPlayerGetBaseMaxHealth(lua_State* L) { // player:getBaseMaxHealth() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->healthMax); } else { lua_pushnil(L); @@ -9915,8 +9760,7 @@ int LuaScriptInterface::luaPlayerGetBaseMaxHealth(lua_State* L) int LuaScriptInterface::luaPlayerGetBaseMaxMana(lua_State* L) { // player:getBaseMaxMana() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->manaMax); } else { lua_pushnil(L); @@ -9927,8 +9771,8 @@ int LuaScriptInterface::luaPlayerGetBaseMaxMana(lua_State* L) int LuaScriptInterface::luaPlayerGetSkillLevel(lua_State* L) { // player:getSkillLevel(skillType) - skills_t skillType = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const auto skillType = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushinteger(L, player->skills[skillType].level); } else { @@ -9940,8 +9784,8 @@ int LuaScriptInterface::luaPlayerGetSkillLevel(lua_State* L) int LuaScriptInterface::luaPlayerGetEffectiveSkillLevel(lua_State* L) { // player:getEffectiveSkillLevel(skillType) - skills_t skillType = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const auto skillType = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushinteger(L, player->getSkillLevel(skillType)); } else { @@ -9953,8 +9797,8 @@ int LuaScriptInterface::luaPlayerGetEffectiveSkillLevel(lua_State* L) int LuaScriptInterface::luaPlayerGetSkillPercent(lua_State* L) { // player:getSkillPercent(skillType) - skills_t skillType = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const auto skillType = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushinteger(L, player->skills[skillType].percent); } else { @@ -9966,8 +9810,8 @@ int LuaScriptInterface::luaPlayerGetSkillPercent(lua_State* L) int LuaScriptInterface::luaPlayerGetSkillTries(lua_State* L) { // player:getSkillTries(skillType) - skills_t skillType = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const auto skillType = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushinteger(L, player->skills[skillType].tries); } else { @@ -9979,10 +9823,9 @@ int LuaScriptInterface::luaPlayerGetSkillTries(lua_State* L) int LuaScriptInterface::luaPlayerAddSkillTries(lua_State* L) { // player:addSkillTries(skillType, tries) - Player* player = getUserdata(L, 1); - if (player) { - skills_t skillType = getNumber(L, 2); - uint64_t tries = getNumber(L, 3); + if (const auto player = getSharedPtr(L, 1)) { + const auto skillType = getNumber(L, 2); + const auto tries = getNumber(L, 3); player->addSkillAdvance(skillType, tries); pushBoolean(L, true); } else { @@ -9994,10 +9837,9 @@ int LuaScriptInterface::luaPlayerAddSkillTries(lua_State* L) int LuaScriptInterface::luaPlayerRemoveSkillTries(lua_State* L) { // player:removeSkillTries(skillType, tries[, notify = true]) - Player* player = getUserdata(L, 1); - if (player) { - skills_t skillType = getNumber(L, 2); - uint64_t tries = getNumber(L, 3); + if (const auto player = getSharedPtr(L, 1)) { + const auto skillType = getNumber(L, 2); + const uint64_t tries = getNumber(L, 3); player->removeSkillTries(skillType, tries, getBoolean(L, 4, true)); pushBoolean(L, true); } else { @@ -10009,8 +9851,8 @@ int LuaScriptInterface::luaPlayerRemoveSkillTries(lua_State* L) int LuaScriptInterface::luaPlayerGetSpecialSkill(lua_State* L) { // player:getSpecialSkill(specialSkillType) - SpecialSkills_t specialSkillType = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const auto specialSkillType = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (player && specialSkillType <= SPECIALSKILL_LAST) { lua_pushinteger(L, player->getSpecialSkill(specialSkillType)); } else { @@ -10022,13 +9864,13 @@ int LuaScriptInterface::luaPlayerGetSpecialSkill(lua_State* L) int LuaScriptInterface::luaPlayerAddSpecialSkill(lua_State* L) { // player:addSpecialSkill(specialSkillType, value) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - SpecialSkills_t specialSkillType = getNumber(L, 2); + const auto specialSkillType = getNumber(L, 2); if (specialSkillType > SPECIALSKILL_LAST) { lua_pushnil(L); return 1; @@ -10043,9 +9885,8 @@ int LuaScriptInterface::luaPlayerAddSpecialSkill(lua_State* L) int LuaScriptInterface::luaPlayerAddOfflineTrainingTime(lua_State* L) { // player:addOfflineTrainingTime(time) - Player* player = getUserdata(L, 1); - if (player) { - int32_t time = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const int32_t time = getNumber(L, 2); player->addOfflineTrainingTime(time); player->sendStats(); pushBoolean(L, true); @@ -10058,8 +9899,7 @@ int LuaScriptInterface::luaPlayerAddOfflineTrainingTime(lua_State* L) int LuaScriptInterface::luaPlayerGetOfflineTrainingTime(lua_State* L) { // player:getOfflineTrainingTime() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getOfflineTrainingTime()); } else { lua_pushnil(L); @@ -10070,9 +9910,8 @@ int LuaScriptInterface::luaPlayerGetOfflineTrainingTime(lua_State* L) int LuaScriptInterface::luaPlayerRemoveOfflineTrainingTime(lua_State* L) { // player:removeOfflineTrainingTime(time) - Player* player = getUserdata(L, 1); - if (player) { - int32_t time = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const int32_t time = getNumber(L, 2); player->removeOfflineTrainingTime(time); player->sendStats(); pushBoolean(L, true); @@ -10085,10 +9924,9 @@ int LuaScriptInterface::luaPlayerRemoveOfflineTrainingTime(lua_State* L) int LuaScriptInterface::luaPlayerAddOfflineTrainingTries(lua_State* L) { // player:addOfflineTrainingTries(skillType, tries) - Player* player = getUserdata(L, 1); - if (player) { - skills_t skillType = getNumber(L, 2); - uint64_t tries = getNumber(L, 3); + if (const auto player = getSharedPtr(L, 1)) { + const auto skillType = getNumber(L, 2); + const uint64_t tries = getNumber(L, 3); pushBoolean(L, player->addOfflineTrainingTries(skillType, tries)); } else { lua_pushnil(L); @@ -10099,8 +9937,7 @@ int LuaScriptInterface::luaPlayerAddOfflineTrainingTries(lua_State* L) int LuaScriptInterface::luaPlayerGetOfflineTrainingSkill(lua_State* L) { // player:getOfflineTrainingSkill() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getOfflineTrainingSkill()); } else { lua_pushnil(L); @@ -10111,9 +9948,8 @@ int LuaScriptInterface::luaPlayerGetOfflineTrainingSkill(lua_State* L) int LuaScriptInterface::luaPlayerSetOfflineTrainingSkill(lua_State* L) { // player:setOfflineTrainingSkill(skillId) - Player* player = getUserdata(L, 1); - if (player) { - uint32_t skillId = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const uint32_t skillId = getNumber(L, 2); player->setOfflineTrainingSkill(skillId); pushBoolean(L, true); } else { @@ -10125,7 +9961,7 @@ int LuaScriptInterface::luaPlayerSetOfflineTrainingSkill(lua_State* L) int LuaScriptInterface::luaPlayerGetItemCount(lua_State* L) { // player:getItemCount(itemId[, subType = -1]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10150,7 +9986,7 @@ int LuaScriptInterface::luaPlayerGetItemCount(lua_State* L) int LuaScriptInterface::luaPlayerGetItemById(lua_State* L) { // player:getItemById(itemId, deepSearch[, subType = -1]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10166,12 +10002,11 @@ int LuaScriptInterface::luaPlayerGetItemById(lua_State* L) return 1; } } - bool deepSearch = getBoolean(L, 3); - int32_t subType = getNumber(L, 4, -1); + const bool deepSearch = getBoolean(L, 3); + const int32_t subType = getNumber(L, 4, -1); - Item* item = g_game.findItemOfType(player, itemId, deepSearch, subType); - if (item) { - pushUserdata(L, item); + if (const auto item = g_game.findItemOfType(player, itemId, deepSearch, subType)) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -10182,8 +10017,7 @@ int LuaScriptInterface::luaPlayerGetItemById(lua_State* L) int LuaScriptInterface::luaPlayerGetVocation(lua_State* L) { // player:getVocation() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushUserdata(L, player->getVocation()); setMetatable(L, -1, "Vocation"); } else { @@ -10195,7 +10029,7 @@ int LuaScriptInterface::luaPlayerGetVocation(lua_State* L) int LuaScriptInterface::luaPlayerSetVocation(lua_State* L) { // player:setVocation(id or name or userdata) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10225,8 +10059,7 @@ int LuaScriptInterface::luaPlayerSetVocation(lua_State* L) int LuaScriptInterface::luaPlayerGetSex(lua_State* L) { // player:getSex() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getSex()); } else { lua_pushnil(L); @@ -10237,9 +10070,8 @@ int LuaScriptInterface::luaPlayerGetSex(lua_State* L) int LuaScriptInterface::luaPlayerSetSex(lua_State* L) { // player:setSex(newSex) - Player* player = getUserdata(L, 1); - if (player) { - PlayerSex_t newSex = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const PlayerSex_t newSex = getNumber(L, 2); player->setSex(newSex); pushBoolean(L, true); } else { @@ -10251,8 +10083,7 @@ int LuaScriptInterface::luaPlayerSetSex(lua_State* L) int LuaScriptInterface::luaPlayerGetTown(lua_State* L) { // player:getTown() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushUserdata(L, player->getTown()); setMetatable(L, -1, "Town"); } else { @@ -10264,14 +10095,13 @@ int LuaScriptInterface::luaPlayerGetTown(lua_State* L) int LuaScriptInterface::luaPlayerSetTown(lua_State* L) { // player:setTown(town) - Town* town = getUserdata(L, 2); + const auto town = getUserdata(L, 2); if (!town) { pushBoolean(L, false); return 1; } - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->setTown(town); pushBoolean(L, true); } else { @@ -10283,13 +10113,13 @@ int LuaScriptInterface::luaPlayerSetTown(lua_State* L) int LuaScriptInterface::luaPlayerGetGuild(lua_State* L) { // player:getGuild() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Guild* guild = player->getGuild(); + const auto guild = player->getGuild(); if (!guild) { lua_pushnil(L); return 1; @@ -10303,7 +10133,7 @@ int LuaScriptInterface::luaPlayerGetGuild(lua_State* L) int LuaScriptInterface::luaPlayerSetGuild(lua_State* L) { // player:setGuild(guild) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10317,8 +10147,7 @@ int LuaScriptInterface::luaPlayerSetGuild(lua_State* L) int LuaScriptInterface::luaPlayerGetGuildLevel(lua_State* L) { // player:getGuildLevel() - Player* player = getUserdata(L, 1); - if (player && player->getGuild()) { + if (const auto player = getSharedPtr(L, 1); player && player->getGuild()) { lua_pushinteger(L, player->getGuildRank()->level); } else { lua_pushnil(L); @@ -10329,14 +10158,14 @@ int LuaScriptInterface::luaPlayerGetGuildLevel(lua_State* L) int LuaScriptInterface::luaPlayerSetGuildLevel(lua_State* L) { // player:setGuildLevel(level) - uint8_t level = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const auto level = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (!player || !player->getGuild()) { lua_pushnil(L); return 1; } - GuildRank_ptr rank = player->getGuild()->getRankByLevel(level); + const auto rank = player->getGuild()->getRankByLevel(level); if (!rank) { pushBoolean(L, false); } else { @@ -10350,8 +10179,7 @@ int LuaScriptInterface::luaPlayerSetGuildLevel(lua_State* L) int LuaScriptInterface::luaPlayerGetGuildNick(lua_State* L) { // player:getGuildNick() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushString(L, player->getGuildNick()); } else { lua_pushnil(L); @@ -10363,8 +10191,7 @@ int LuaScriptInterface::luaPlayerSetGuildNick(lua_State* L) { // player:setGuildNick(nick) const std::string& nick = getString(L, 2); - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->setGuildNick(nick); pushBoolean(L, true); } else { @@ -10376,8 +10203,7 @@ int LuaScriptInterface::luaPlayerSetGuildNick(lua_State* L) int LuaScriptInterface::luaPlayerGetGroup(lua_State* L) { // player:getGroup() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushUserdata(L, player->getGroup()); setMetatable(L, -1, "Group"); } else { @@ -10395,8 +10221,7 @@ int LuaScriptInterface::luaPlayerSetGroup(lua_State* L) return 1; } - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->setGroup(group); pushBoolean(L, true); } else { @@ -10408,8 +10233,7 @@ int LuaScriptInterface::luaPlayerSetGroup(lua_State* L) int LuaScriptInterface::luaPlayerGetStamina(lua_State* L) { // player:getStamina() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getStaminaMinutes()); } else { lua_pushnil(L); @@ -10420,9 +10244,8 @@ int LuaScriptInterface::luaPlayerGetStamina(lua_State* L) int LuaScriptInterface::luaPlayerSetStamina(lua_State* L) { // player:setStamina(stamina) - uint16_t stamina = getNumber(L, 2); - Player* player = getUserdata(L, 1); - if (player) { + const uint16_t stamina = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { player->staminaMinutes = std::min(2520, stamina); player->sendStats(); pushBoolean(L, true); @@ -10435,8 +10258,7 @@ int LuaScriptInterface::luaPlayerSetStamina(lua_State* L) int LuaScriptInterface::luaPlayerGetSoul(lua_State* L) { // player:getSoul() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getSoul()); } else { lua_pushnil(L); @@ -10448,8 +10270,7 @@ int LuaScriptInterface::luaPlayerAddSoul(lua_State* L) { // player:addSoul(soulChange) int32_t soulChange = getNumber(L, 2); - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->changeSoul(soulChange); pushBoolean(L, true); } else { @@ -10461,8 +10282,7 @@ int LuaScriptInterface::luaPlayerAddSoul(lua_State* L) int LuaScriptInterface::luaPlayerGetMaxSoul(lua_State* L) { // player:getMaxSoul() - Player* player = getUserdata(L, 1); - if (player && player->vocation) { + if (const auto player = getSharedPtr(L, 1); player && player->vocation) { lua_pushinteger(L, player->vocation->getSoulMax()); } else { lua_pushnil(L); @@ -10473,8 +10293,7 @@ int LuaScriptInterface::luaPlayerGetMaxSoul(lua_State* L) int LuaScriptInterface::luaPlayerGetBankBalance(lua_State* L) { // player:getBankBalance() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getBankBalance()); } else { lua_pushnil(L); @@ -10485,7 +10304,7 @@ int LuaScriptInterface::luaPlayerGetBankBalance(lua_State* L) int LuaScriptInterface::luaPlayerSetBankBalance(lua_State* L) { // player:setBankBalance(bankBalance) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10506,15 +10325,14 @@ int LuaScriptInterface::luaPlayerSetBankBalance(lua_State* L) int LuaScriptInterface::luaPlayerGetStorageValue(lua_State* L) { // player:getStorageValue(key) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - uint32_t key = getNumber(L, 2); - int32_t value; - if (player->getStorageValue(key, value)) { + const uint32_t key = getNumber(L, 2); + if (int32_t value; player->getStorageValue(key, value)) { lua_pushinteger(L, value); } else { lua_pushinteger(L, -1); @@ -10525,9 +10343,9 @@ int LuaScriptInterface::luaPlayerGetStorageValue(lua_State* L) int LuaScriptInterface::luaPlayerSetStorageValue(lua_State* L) { // player:setStorageValue(key, value) - int32_t value = getNumber(L, 3); - uint32_t key = getNumber(L, 2); - Player* player = getUserdata(L, 1); + const int32_t value = getNumber(L, 3); + const uint32_t key = getNumber(L, 2); + const auto player = getSharedPtr(L, 1); if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) { reportErrorFunc(L, fmt::format("Accessing reserved range: {:d}", key)); pushBoolean(L, false); @@ -10546,7 +10364,7 @@ int LuaScriptInterface::luaPlayerSetStorageValue(lua_State* L) int LuaScriptInterface::luaPlayerAddItem(lua_State* L) { // player:addItem(itemId[, count = 1[, canDropOnMap = true[, subType = 1[, slot = CONST_SLOT_WHEREEVER]]]]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { pushBoolean(L, false); return 1; @@ -10563,7 +10381,7 @@ int LuaScriptInterface::luaPlayerAddItem(lua_State* L) } } - int32_t count = getNumber(L, 3, 1); + const int32_t count = getNumber(L, 3, 1); int32_t subType = getNumber(L, 5, 1); const ItemType& it = Item::items[itemId]; @@ -10582,7 +10400,7 @@ int LuaScriptInterface::luaPlayerAddItem(lua_State* L) itemCount = std::max(1, count); } - bool hasTable = itemCount > 1; + const bool hasTable = itemCount > 1; if (hasTable) { lua_newtable(L); } else if (itemCount == 0) { @@ -10591,7 +10409,7 @@ int LuaScriptInterface::luaPlayerAddItem(lua_State* L) } bool canDropOnMap = getBoolean(L, 4, true); - slots_t slot = getNumber(L, 6, CONST_SLOT_WHEREEVER); + const auto slot = getNumber(L, 6, CONST_SLOT_WHEREEVER); for (int32_t i = 1; i <= itemCount; ++i) { int32_t stackCount = subType; if (it.stackable) { @@ -10599,7 +10417,7 @@ int LuaScriptInterface::luaPlayerAddItem(lua_State* L) subType -= stackCount; } - Item* item = Item::CreateItem(itemId, stackCount); + auto item = Item::CreateItem(itemId, stackCount); if (!item) { if (!hasTable) { lua_pushnil(L); @@ -10609,7 +10427,7 @@ int LuaScriptInterface::luaPlayerAddItem(lua_State* L) ReturnValue ret = g_game.internalPlayerAddItem(player, item, canDropOnMap, slot); if (ret != RETURNVALUE_NOERROR) { - delete item; + item.reset(); if (!hasTable) { lua_pushnil(L); } @@ -10618,11 +10436,11 @@ int LuaScriptInterface::luaPlayerAddItem(lua_State* L) if (hasTable) { lua_pushinteger(L, i); - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); lua_settable(L, -3); } else { - pushUserdata(L, item); + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } } @@ -10633,14 +10451,14 @@ int LuaScriptInterface::luaPlayerAddItemEx(lua_State* L) { // player:addItemEx(item[, canDropOnMap = false[, index = INDEX_WHEREEVER[, flags = 0]]]) // player:addItemEx(item[, canDropOnMap = true[, slot = CONST_SLOT_WHEREEVER]]) - Item* item = getUserdata(L, 2); + const auto item = getSharedPtr(L, 2); if (!item) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); return 1; } - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10655,12 +10473,13 @@ int LuaScriptInterface::luaPlayerAddItemEx(lua_State* L) bool canDropOnMap = getBoolean(L, 3, false); ReturnValue returnValue; if (canDropOnMap) { - slots_t slot = getNumber(L, 4, CONST_SLOT_WHEREEVER); + const auto slot = getNumber(L, 4, CONST_SLOT_WHEREEVER); returnValue = g_game.internalPlayerAddItem(player, item, true, slot); } else { int32_t index = getNumber(L, 4, INDEX_WHEREEVER); uint32_t flags = getNumber(L, 5, 0); - returnValue = g_game.internalAddItem(player, item, index, flags); + CylinderPtr holder = player; + returnValue = g_game.internalAddItem(holder, item, index, flags); } if (returnValue == RETURNVALUE_NOERROR) { @@ -10673,7 +10492,7 @@ int LuaScriptInterface::luaPlayerAddItemEx(lua_State* L) int LuaScriptInterface::luaPlayerRemoveItem(lua_State* L) { // player:removeItem(itemId, count[, subType = -1[, ignoreEquipped = false]]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10690,9 +10509,9 @@ int LuaScriptInterface::luaPlayerRemoveItem(lua_State* L) } } - uint32_t count = getNumber(L, 3); - int32_t subType = getNumber(L, 4, -1); - bool ignoreEquipped = getBoolean(L, 5, false); + const uint32_t count = getNumber(L, 3); + const int32_t subType = getNumber(L, 4, -1); + const bool ignoreEquipped = getBoolean(L, 5, false); pushBoolean(L, player->removeItemOfType(itemId, count, subType, ignoreEquipped)); return 1; } @@ -10700,8 +10519,7 @@ int LuaScriptInterface::luaPlayerRemoveItem(lua_State* L) int LuaScriptInterface::luaPlayerGetMoney(lua_State* L) { // player:getMoney() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getMoney()); } else { lua_pushnil(L); @@ -10713,9 +10531,9 @@ int LuaScriptInterface::luaPlayerAddMoney(lua_State* L) { // player:addMoney(money) uint64_t money = getNumber(L, 2); - Player* player = getUserdata(L, 1); - if (player) { - g_game.addMoney(player, money); + if (const auto player = getSharedPtr(L, 1)) { + CylinderPtr holder = player; + g_game.addMoney(holder, money); pushBoolean(L, true); } else { lua_pushnil(L); @@ -10726,10 +10544,10 @@ int LuaScriptInterface::luaPlayerAddMoney(lua_State* L) int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L) { // player:removeMoney(money) - Player* player = getUserdata(L, 1); - if (player) { - uint64_t money = getNumber(L, 2); - pushBoolean(L, g_game.removeMoney(player, money)); + if (const auto player = getSharedPtr(L, 1)) { + const uint64_t money = getNumber(L, 2); + CylinderPtr holder = player; + pushBoolean(L, g_game.removeMoney(holder, money)); } else { lua_pushnil(L); } @@ -10739,7 +10557,7 @@ int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L) int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L) { // player:showTextDialog(id or name or userdata[, text[, canWrite[, length]]]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10754,7 +10572,7 @@ int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L) text = getString(L, 3); } - Item* item; + ItemPtr item; if (isNumber(L, 2)) { item = Item::CreateItem(getNumber(L, 2)); } else if (isString(L, 2)) { @@ -10765,7 +10583,7 @@ int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L) return 1; } - item = getUserdata(L, 2); + item = getSharedPtr(L, 2); } else { item = nullptr; } @@ -10784,7 +10602,6 @@ int LuaScriptInterface::luaPlayerShowTextDialog(lua_State* L) item->setText(text); length = std::max(text.size(), length); } - item->setParent(player); player->windowTextId++; player->writeItem = item; @@ -10799,7 +10616,7 @@ int LuaScriptInterface::luaPlayerSendTextMessage(lua_State* L) // player:sendTextMessage(type, text[, position, primaryValue = 0, primaryColor = TEXTCOLOR_NONE[, secondaryValue = 0, secondaryColor = TEXTCOLOR_NONE]]) // player:sendTextMessage(type, text, channelId) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -10809,9 +10626,9 @@ int LuaScriptInterface::luaPlayerSendTextMessage(lua_State* L) TextMessage message(getNumber(L, 2), getString(L, 3)); if (parameters == 4) { - uint16_t channelId = getNumber(L, 4); - ChatChannel* channel = g_chat->getChannel(*player, channelId); - if (!channel || !channel->hasUser(*player)) { + const uint16_t channelId = getNumber(L, 4); + const auto channel = g_chat->getChannel(player, channelId); + if (!channel || !channel->hasUser(player)) { pushBoolean(L, false); return 1; } @@ -10838,14 +10655,14 @@ int LuaScriptInterface::luaPlayerSendTextMessage(lua_State* L) int LuaScriptInterface::luaPlayerSendChannelMessage(lua_State* L) { // player:sendChannelMessage(author, text, type, channelId) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - uint16_t channelId = getNumber(L, 5); - SpeakClasses type = getNumber(L, 4); + const uint16_t channelId = getNumber(L, 5); + const auto type = getNumber(L, 4); const std::string& text = getString(L, 3); const std::string& author = getString(L, 2); player->sendChannelMessage(author, text, type, channelId); @@ -10856,15 +10673,15 @@ int LuaScriptInterface::luaPlayerSendChannelMessage(lua_State* L) int LuaScriptInterface::luaPlayerSendPrivateMessage(lua_State* L) { // player:sendPrivateMessage(speaker, text[, type]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - const Player* speaker = getUserdata(L, 2); + const auto speaker = getSharedPtr(L, 2); const std::string& text = getString(L, 3); - SpeakClasses type = getNumber(L, 4, TALKTYPE_PRIVATE_FROM); + const auto type = getNumber(L, 4, TALKTYPE_PRIVATE_FROM); player->sendPrivateMessage(speaker, type, text); pushBoolean(L, true); return 1; @@ -10873,16 +10690,16 @@ int LuaScriptInterface::luaPlayerSendPrivateMessage(lua_State* L) int LuaScriptInterface::luaPlayerChannelSay(lua_State* L) { // player:channelSay(speaker, type, text, channelId) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Creature* speaker = getCreature(L, 2); - SpeakClasses type = getNumber(L, 3); + const auto speaker = getCreature(L, 2); + const auto type = getNumber(L, 3); const std::string& text = getString(L, 4); - uint16_t channelId = getNumber(L, 5); + const uint16_t channelId = getNumber(L, 5); player->sendToChannel(speaker, type, text, channelId); pushBoolean(L, true); return 1; @@ -10892,8 +10709,7 @@ int LuaScriptInterface::luaPlayerOpenChannel(lua_State* L) { // player:openChannel(channelId) uint16_t channelId = getNumber(L, 2); - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { g_game.playerOpenChannel(player->getID(), channelId); pushBoolean(L, true); } else { @@ -10905,22 +10721,21 @@ int LuaScriptInterface::luaPlayerOpenChannel(lua_State* L) int LuaScriptInterface::luaPlayerGetSlotItem(lua_State* L) { // player:getSlotItem(slot) - const Player* player = getUserdata(L, 1); + auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - uint32_t slot = getNumber(L, 2); - Thing* thing = player->getThing(slot); + const uint32_t slot = getNumber(L, 2); + auto thing = player->getThing(slot); if (!thing) { lua_pushnil(L); return 1; } - Item* item = thing->getItem(); - if (item) { - pushUserdata(L, item); + if (const auto item = thing->getItem()) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); } else { lua_pushnil(L); @@ -10931,14 +10746,13 @@ int LuaScriptInterface::luaPlayerGetSlotItem(lua_State* L) int LuaScriptInterface::luaPlayerGetParty(lua_State* L) { // player:getParty() - const Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Party* party = player->getParty(); - if (party) { + if (const auto party = player->getParty()) { pushUserdata(L, party); setMetatable(L, -1, "Party"); } else { @@ -10950,8 +10764,7 @@ int LuaScriptInterface::luaPlayerGetParty(lua_State* L) int LuaScriptInterface::luaPlayerAddOutfit(lua_State* L) { // player:addOutfit(lookType) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->addOutfit(getNumber(L, 2), 0); pushBoolean(L, true); } else { @@ -10963,10 +10776,9 @@ int LuaScriptInterface::luaPlayerAddOutfit(lua_State* L) int LuaScriptInterface::luaPlayerAddOutfitAddon(lua_State* L) { // player:addOutfitAddon(lookType, addon) - Player* player = getUserdata(L, 1); - if (player) { - uint16_t lookType = getNumber(L, 2); - uint8_t addon = getNumber(L, 3); + if (const auto player = getSharedPtr(L, 1)) { + const uint16_t lookType = getNumber(L, 2); + const uint8_t addon = getNumber(L, 3); player->addOutfit(lookType, addon); pushBoolean(L, true); } else { @@ -10978,9 +10790,8 @@ int LuaScriptInterface::luaPlayerAddOutfitAddon(lua_State* L) int LuaScriptInterface::luaPlayerRemoveOutfit(lua_State* L) { // player:removeOutfit(lookType) - Player* player = getUserdata(L, 1); - if (player) { - uint16_t lookType = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const uint16_t lookType = getNumber(L, 2); pushBoolean(L, player->removeOutfit(lookType)); } else { lua_pushnil(L); @@ -10991,10 +10802,9 @@ int LuaScriptInterface::luaPlayerRemoveOutfit(lua_State* L) int LuaScriptInterface::luaPlayerRemoveOutfitAddon(lua_State* L) { // player:removeOutfitAddon(lookType, addon) - Player* player = getUserdata(L, 1); - if (player) { - uint16_t lookType = getNumber(L, 2); - uint8_t addon = getNumber(L, 3); + if (const auto player = getSharedPtr(L, 1)) { + const uint16_t lookType = getNumber(L, 2); + const uint8_t addon = getNumber(L, 3); pushBoolean(L, player->removeOutfitAddon(lookType, addon)); } else { lua_pushnil(L); @@ -11005,10 +10815,9 @@ int LuaScriptInterface::luaPlayerRemoveOutfitAddon(lua_State* L) int LuaScriptInterface::luaPlayerHasOutfit(lua_State* L) { // player:hasOutfit(lookType[, addon = 0]) - Player* player = getUserdata(L, 1); - if (player) { - uint16_t lookType = getNumber(L, 2); - uint8_t addon = getNumber(L, 3, 0); + if (const auto player = getSharedPtr(L, 1)) { + const uint16_t lookType = getNumber(L, 2); + const uint8_t addon = getNumber(L, 3, 0); pushBoolean(L, player->hasOutfit(lookType, addon)); } else { lua_pushnil(L); @@ -11019,10 +10828,9 @@ int LuaScriptInterface::luaPlayerHasOutfit(lua_State* L) int LuaScriptInterface::luaPlayerCanWearOutfit(lua_State* L) { // player:canWearOutfit(lookType[, addon = 0]) - Player* player = getUserdata(L, 1); - if (player) { - uint16_t lookType = getNumber(L, 2); - uint8_t addon = getNumber(L, 3, 0); + if (const auto player = getSharedPtr(L, 1)) { + const uint16_t lookType = getNumber(L, 2); + const uint8_t addon = getNumber(L, 3, 0); pushBoolean(L, player->canWear(lookType, addon)); } else { lua_pushnil(L); @@ -11033,8 +10841,7 @@ int LuaScriptInterface::luaPlayerCanWearOutfit(lua_State* L) int LuaScriptInterface::luaPlayerSendOutfitWindow(lua_State* L) { // player:sendOutfitWindow() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->sendOutfitWindow(); pushBoolean(L, true); } else { @@ -11045,7 +10852,7 @@ int LuaScriptInterface::luaPlayerSendOutfitWindow(lua_State* L) int LuaScriptInterface::luaPlayerAddMount(lua_State* L) { // player:addMount(mountId or mountName) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11055,7 +10862,7 @@ int LuaScriptInterface::luaPlayerAddMount(lua_State* L) { if (isNumber(L, 2)) { mountId = getNumber(L, 2); } else { - Mount* mount = g_game.mounts.getMountByName(getString(L, 2)); + const auto mount = g_game.mounts.getMountByName(getString(L, 2)); if (!mount) { lua_pushnil(L); return 1; @@ -11068,7 +10875,7 @@ int LuaScriptInterface::luaPlayerAddMount(lua_State* L) { int LuaScriptInterface::luaPlayerRemoveMount(lua_State* L) { // player:removeMount(mountId or mountName) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11078,7 +10885,7 @@ int LuaScriptInterface::luaPlayerRemoveMount(lua_State* L) { if (isNumber(L, 2)) { mountId = getNumber(L, 2); } else { - Mount* mount = g_game.mounts.getMountByName(getString(L, 2)); + const auto mount = g_game.mounts.getMountByName(getString(L, 2)); if (!mount) { lua_pushnil(L); return 1; @@ -11091,7 +10898,7 @@ int LuaScriptInterface::luaPlayerRemoveMount(lua_State* L) { int LuaScriptInterface::luaPlayerHasMount(lua_State* L) { // player:hasMount(mountId or mountName) - const Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11115,8 +10922,7 @@ int LuaScriptInterface::luaPlayerHasMount(lua_State* L) { int LuaScriptInterface::luaPlayerGetPremiumEndsAt(lua_State* L) { // player:getPremiumEndsAt() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->premiumEndsAt); } else { lua_pushnil(L); @@ -11127,13 +10933,13 @@ int LuaScriptInterface::luaPlayerGetPremiumEndsAt(lua_State* L) int LuaScriptInterface::luaPlayerSetPremiumEndsAt(lua_State* L) { // player:setPremiumEndsAt(timestamp) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - time_t timestamp = getNumber(L, 2); + const time_t timestamp = getNumber(L, 2); player->setPremiumTime(timestamp); IOLoginData::updatePremiumTime(player->getAccount(), timestamp); @@ -11144,9 +10950,8 @@ int LuaScriptInterface::luaPlayerSetPremiumEndsAt(lua_State* L) int LuaScriptInterface::luaPlayerHasBlessing(lua_State* L) { // player:hasBlessing(blessing) - uint8_t blessing = getNumber(L, 2) - 1; - Player* player = getUserdata(L, 1); - if (player) { + const uint8_t blessing = getNumber(L, 2) - 1; + if (const auto player = getSharedPtr(L, 1)) { pushBoolean(L, player->hasBlessing(blessing)); } else { lua_pushnil(L); @@ -11157,13 +10962,13 @@ int LuaScriptInterface::luaPlayerHasBlessing(lua_State* L) int LuaScriptInterface::luaPlayerAddBlessing(lua_State* L) { // player:addBlessing(blessing) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - uint8_t blessing = getNumber(L, 2) - 1; + const auto blessing = getNumber(L, 2) - 1; if (player->hasBlessing(blessing)) { pushBoolean(L, false); return 1; @@ -11177,13 +10982,13 @@ int LuaScriptInterface::luaPlayerAddBlessing(lua_State* L) int LuaScriptInterface::luaPlayerRemoveBlessing(lua_State* L) { // player:removeBlessing(blessing) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - uint8_t blessing = getNumber(L, 2) - 1; + const auto blessing = getNumber(L, 2) - 1; if (!player->hasBlessing(blessing)) { pushBoolean(L, false); return 1; @@ -11197,14 +11002,14 @@ int LuaScriptInterface::luaPlayerRemoveBlessing(lua_State* L) int LuaScriptInterface::luaPlayerCanLearnSpell(lua_State* L) { // player:canLearnSpell(spellName) - const Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } const std::string& spellName = getString(L, 2); - InstantSpell* spell = g_spells->getInstantSpellByName(spellName); + const auto spell = g_spells->getInstantSpellByName(spellName); if (!spell) { reportErrorFunc(L, "Spell \"" + spellName + "\" not found"); pushBoolean(L, false); @@ -11217,7 +11022,7 @@ int LuaScriptInterface::luaPlayerCanLearnSpell(lua_State* L) } const auto& vocMap = spell->getVocMap(); - if (vocMap.count(player->getVocationId()) == 0) { + if (!vocMap.contains(player->getVocationId())) { pushBoolean(L, false); } else if (player->getLevel() < spell->getLevel()) { pushBoolean(L, false); @@ -11232,8 +11037,7 @@ int LuaScriptInterface::luaPlayerCanLearnSpell(lua_State* L) int LuaScriptInterface::luaPlayerLearnSpell(lua_State* L) { // player:learnSpell(spellName) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { const std::string& spellName = getString(L, 2); player->learnInstantSpell(spellName); pushBoolean(L, true); @@ -11246,8 +11050,7 @@ int LuaScriptInterface::luaPlayerLearnSpell(lua_State* L) int LuaScriptInterface::luaPlayerForgetSpell(lua_State* L) { // player:forgetSpell(spellName) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { const std::string& spellName = getString(L, 2); player->forgetInstantSpell(spellName); pushBoolean(L, true); @@ -11260,8 +11063,7 @@ int LuaScriptInterface::luaPlayerForgetSpell(lua_State* L) int LuaScriptInterface::luaPlayerHasLearnedSpell(lua_State* L) { // player:hasLearnedSpell(spellName) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { const std::string& spellName = getString(L, 2); pushBoolean(L, player->hasLearnedInstantSpell(spellName)); } else { @@ -11273,9 +11075,8 @@ int LuaScriptInterface::luaPlayerHasLearnedSpell(lua_State* L) int LuaScriptInterface::luaPlayerSendTutorial(lua_State* L) { // player:sendTutorial(tutorialId) - Player* player = getUserdata(L, 1); - if (player) { - uint8_t tutorialId = getNumber(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const auto tutorialId = getNumber(L, 2); player->sendTutorial(tutorialId); pushBoolean(L, true); } else { @@ -11287,11 +11088,10 @@ int LuaScriptInterface::luaPlayerSendTutorial(lua_State* L) int LuaScriptInterface::luaPlayerAddMapMark(lua_State* L) { // player:addMapMark(position, type, description) - Player* player = getUserdata(L, 1); - if (player) { - const Position& position = getPosition(L, 2); - uint8_t type = getNumber(L, 3); - const std::string& description = getString(L, 4); + if (const auto player = getSharedPtr(L, 1)) { + const auto& position = getPosition(L, 2); + const auto type = getNumber(L, 3); + const auto& description = getString(L, 4); player->sendAddMarker(position, type, description); pushBoolean(L, true); } else { @@ -11303,8 +11103,7 @@ int LuaScriptInterface::luaPlayerAddMapMark(lua_State* L) int LuaScriptInterface::luaPlayerSave(lua_State* L) { // player:save() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { player->loginPosition = player->getPosition(); pushBoolean(L, IOLoginData::savePlayer(player)); } else { @@ -11316,9 +11115,8 @@ int LuaScriptInterface::luaPlayerSave(lua_State* L) int LuaScriptInterface::luaPlayerPopupFYI(lua_State* L) { // player:popupFYI(message) - Player* player = getUserdata(L, 1); - if (player) { - const std::string& message = getString(L, 2); + if (const auto player = getSharedPtr(L, 1)) { + const auto& message = getString(L, 2); player->sendFYIBox(message); pushBoolean(L, true); } else { @@ -11330,8 +11128,7 @@ int LuaScriptInterface::luaPlayerPopupFYI(lua_State* L) int LuaScriptInterface::luaPlayerIsPzLocked(lua_State* L) { // player:isPzLocked() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushBoolean(L, player->isPzLocked()); } else { lua_pushnil(L); @@ -11342,8 +11139,7 @@ int LuaScriptInterface::luaPlayerIsPzLocked(lua_State* L) int LuaScriptInterface::luaPlayerGetClient(lua_State* L) { // player:getClient() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_createtable(L, 0, 2); setField(L, "version", player->getProtocolVersion()); setField(L, "os", player->getOperatingSystem()); @@ -11356,14 +11152,13 @@ int LuaScriptInterface::luaPlayerGetClient(lua_State* L) int LuaScriptInterface::luaPlayerGetHouse(lua_State* L) { // player:getHouse() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - House* house = g_game.map.houses.getHouseByPlayerId(player->getGUID()); - if (house) { + if (const auto house = g_game.map.houses.getHouseByPlayerId(player->getGUID())) { pushUserdata(L, house); setMetatable(L, -1, "House"); } else { @@ -11375,19 +11170,19 @@ int LuaScriptInterface::luaPlayerGetHouse(lua_State* L) int LuaScriptInterface::luaPlayerSendHouseWindow(lua_State* L) { // player:sendHouseWindow(house, listId) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - House* house = getUserdata(L, 2); + const auto house = getUserdata(L, 2); if (!house) { lua_pushnil(L); return 1; } - uint32_t listId = getNumber(L, 3); + const auto listId = getNumber(L, 3); player->sendHouseWindow(house, listId); pushBoolean(L, true); return 1; @@ -11396,19 +11191,19 @@ int LuaScriptInterface::luaPlayerSendHouseWindow(lua_State* L) int LuaScriptInterface::luaPlayerSetEditHouse(lua_State* L) { // player:setEditHouse(house, listId) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - House* house = getUserdata(L, 2); + const auto house = getUserdata(L, 2); if (!house) { lua_pushnil(L); return 1; } - uint32_t listId = getNumber(L, 3); + const auto listId = getNumber(L, 3); player->setEditHouse(house, listId); pushBoolean(L, true); return 1; @@ -11417,32 +11212,32 @@ int LuaScriptInterface::luaPlayerSetEditHouse(lua_State* L) int LuaScriptInterface::luaPlayerSetGhostMode(lua_State* L) { // player:setGhostMode(enabled[, magicEffect = CONST_ME_TELEPORT]) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - bool enabled = getBoolean(L, 2); + const bool enabled = getBoolean(L, 2); if (player->isInGhostMode() == enabled) { pushBoolean(L, true); return 1; } - MagicEffectClasses magicEffect = getNumber(L, 3, CONST_ME_TELEPORT); + const auto magicEffect = getNumber(L, 3, CONST_ME_TELEPORT); player->switchGhostMode(); - Tile* tile = player->getTile(); + const auto tile = player->getTile(); const Position& position = player->getPosition(); const bool isInvisible = player->isInvisible(); SpectatorVec spectators; g_game.map.getSpectators(spectators, position, true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); + for (auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); - Player* spectatorPlayer = static_cast(spectator); + PlayerPtr spectatorPlayer = std::static_pointer_cast(spectator); if (spectatorPlayer != player && !spectatorPlayer->isAccessPlayer()) { if (enabled) { spectatorPlayer->sendRemoveTileCreature(player, position, tile->getClientIndexOfCreature(spectatorPlayer, player)); @@ -11459,16 +11254,16 @@ int LuaScriptInterface::luaPlayerSetGhostMode(lua_State* L) } if (player->isInGhostMode()) { - for (const auto& it : g_game.getPlayers()) { - if (!it.second->isAccessPlayer()) { - it.second->notifyStatusChange(player, VIPSTATUS_OFFLINE); + for (const auto& val : g_game.getPlayers() | std::views::values) { + if (!val->isAccessPlayer()) { + val->notifyStatusChange(player, VIPSTATUS_OFFLINE); } } IOLoginData::updateOnlineStatus(player->getGUID(), false); } else { - for (const auto& it : g_game.getPlayers()) { - if (!it.second->isAccessPlayer()) { - it.second->notifyStatusChange(player, VIPSTATUS_ONLINE); + for (const auto& val : g_game.getPlayers() | std::views::values) { + if (!val->isAccessPlayer()) { + val->notifyStatusChange(player, VIPSTATUS_ONLINE); } } IOLoginData::updateOnlineStatus(player->getGUID(), true); @@ -11480,14 +11275,13 @@ int LuaScriptInterface::luaPlayerSetGhostMode(lua_State* L) int LuaScriptInterface::luaPlayerGetContainerId(lua_State* L) { // player:getContainerId(container) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Container* container = getUserdata(L, 2); - if (container) { + if (const auto container = getSharedPtr(L, 2)) { lua_pushinteger(L, player->getContainerID(container)); } else { lua_pushnil(L); @@ -11498,15 +11292,14 @@ int LuaScriptInterface::luaPlayerGetContainerId(lua_State* L) int LuaScriptInterface::luaPlayerGetContainerById(lua_State* L) { // player:getContainerById(id) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Container* container = player->getContainerByID(getNumber(L, 2)); - if (container) { - pushUserdata(L, container); + if (const auto container = player->getContainerByID(getNumber(L, 2))) { + pushSharedPtr(L, container); setMetatable(L, -1, "Container"); } else { lua_pushnil(L); @@ -11517,8 +11310,7 @@ int LuaScriptInterface::luaPlayerGetContainerById(lua_State* L) int LuaScriptInterface::luaPlayerGetContainerIndex(lua_State* L) { // player:getContainerIndex(id) - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->getContainerIndex(getNumber(L, 2))); } else { lua_pushnil(L); @@ -11529,23 +11321,23 @@ int LuaScriptInterface::luaPlayerGetContainerIndex(lua_State* L) int LuaScriptInterface::luaPlayerGetInstantSpells(lua_State* L) { // player:getInstantSpells() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } std::vector spells; - for (auto& spell : g_spells->getInstantSpells()) { - if (spell.second.canCast(player)) { - spells.push_back(&spell.second); + for (const auto& val : g_spells->getInstantSpells() | std::views::values) { + if (val.canCast(player)) { + spells.push_back(&val); } } lua_createtable(L, spells.size(), 0); int index = 0; - for (auto spell : spells) { + for (const auto spell : spells) { pushInstantSpell(L, *spell); lua_rawseti(L, -2, ++index); } @@ -11555,8 +11347,8 @@ int LuaScriptInterface::luaPlayerGetInstantSpells(lua_State* L) int LuaScriptInterface::luaPlayerCanCast(lua_State* L) { // player:canCast(spell) - Player* player = getUserdata(L, 1); - InstantSpell* spell = getUserdata(L, 2); + const auto player = getSharedPtr(L, 1); + const auto spell = getUserdata(L, 2); if (player && spell) { pushBoolean(L, spell->canCast(player)); } else { @@ -11568,8 +11360,7 @@ int LuaScriptInterface::luaPlayerCanCast(lua_State* L) int LuaScriptInterface::luaPlayerHasChaseMode(lua_State* L) { // player:hasChaseMode() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushBoolean(L, player->chaseMode); } else { lua_pushnil(L); @@ -11580,8 +11371,7 @@ int LuaScriptInterface::luaPlayerHasChaseMode(lua_State* L) int LuaScriptInterface::luaPlayerHasSecureMode(lua_State* L) { // player:hasSecureMode() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { pushBoolean(L, player->secureMode); } else { lua_pushnil(L); @@ -11592,8 +11382,7 @@ int LuaScriptInterface::luaPlayerHasSecureMode(lua_State* L) int LuaScriptInterface::luaPlayerGetFightMode(lua_State* L) { // player:getFightMode() - Player* player = getUserdata(L, 1); - if (player) { + if (const auto player = getSharedPtr(L, 1)) { lua_pushinteger(L, player->fightMode); } else { lua_pushnil(L); @@ -11604,19 +11393,19 @@ int LuaScriptInterface::luaPlayerGetFightMode(lua_State* L) int LuaScriptInterface::luaPlayerGetStoreInbox(lua_State* L) { // player:getStoreInbox() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - Container* storeInbox = player->getStoreInbox(); + const auto storeInbox = player->getStoreInbox(); if (!storeInbox) { lua_pushnil(L); return 1; } - pushUserdata(L, storeInbox); + pushSharedPtr(L, storeInbox); setMetatable(L, -1, "Container"); return 1; } @@ -11624,7 +11413,7 @@ int LuaScriptInterface::luaPlayerGetStoreInbox(lua_State* L) int LuaScriptInterface::luaPlayerIsNearDepotBox(lua_State* L) { // player:isNearDepotBox() - const Player* const player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11635,7 +11424,7 @@ int LuaScriptInterface::luaPlayerIsNearDepotBox(lua_State* L) int LuaScriptInterface::luaPlayerGetIdleTime(lua_State* L) { // player:getIdleTime() - const Player* const player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11647,7 +11436,7 @@ int LuaScriptInterface::luaPlayerGetIdleTime(lua_State* L) int LuaScriptInterface::luaPlayerResetIdleTime(lua_State* L) { // player:resetIdleTime() - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11661,12 +11450,12 @@ int LuaScriptInterface::luaPlayerResetIdleTime(lua_State* L) int LuaScriptInterface::luaPlayerSendCreatureSquare(lua_State* L) { // player:sendCreatureSquare(creature, color) - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - auto creature = getCreature(L, 2); + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -11679,7 +11468,7 @@ int LuaScriptInterface::luaPlayerSendCreatureSquare(lua_State* L) int LuaScriptInterface::luaPlayerAddAugment(lua_State* L) { - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11708,14 +11497,14 @@ int LuaScriptInterface::luaPlayerAddAugment(lua_State* L) int LuaScriptInterface::luaPlayerRemoveAugment(lua_State* L) { - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } if (isString(L, 2)) { - auto name = getString(L, 2); + const auto name = getString(L, 2); lua_pushboolean(L, player->removeAugment(name)); } else if (isUserdata(L, 2)) { if (std::shared_ptr augment = getSharedPtr(L, 2)) { @@ -11733,7 +11522,7 @@ int LuaScriptInterface::luaPlayerRemoveAugment(lua_State* L) int LuaScriptInterface::luaPlayerIsAugmented(lua_State* L) { - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -11744,20 +11533,20 @@ int LuaScriptInterface::luaPlayerIsAugmented(lua_State* L) int LuaScriptInterface::luaPlayerHasAugment(lua_State* L) { - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } if (isString(L, 2) && isBoolean(L, 3)) { - auto name = getString(L, 2); - auto checkItems = getBoolean(L, 3); + const auto name = getString(L, 2); + const auto checkItems = getBoolean(L, 3); lua_pushboolean(L, player->hasAugment(name, checkItems)); } else if (isUserdata(L, 2)) { if (std::shared_ptr& augment = getSharedPtr(L, 2)) { if (isBoolean(L, 3)) { - auto checkItems = getBoolean(L, 3); + const auto checkItems = getBoolean(L, 3); lua_pushboolean(L, player->hasAugment(augment, checkItems)); } else { lua_pushboolean(L, player->hasAugment(augment, true)); @@ -11769,13 +11558,13 @@ int LuaScriptInterface::luaPlayerHasAugment(lua_State* L) int LuaScriptInterface::luaPlayerGetAugments(lua_State* L) { - Player* player = getUserdata(L, 1); + const auto player = getSharedPtr(L, 1); if (!player) { lua_pushnil(L); return 1; } - - std::vector> augments; + + const std::vector> augments; lua_newtable(L); int index = 1; @@ -11791,7 +11580,7 @@ int LuaScriptInterface::luaPlayerGetAugments(lua_State* L) int LuaScriptInterface::luaMonsterCreate(lua_State* L) { // Monster(id or userdata) - Monster* monster; + MonsterPtr monster; if (isNumber(L, 2)) { monster = g_game.getMonsterByID(getNumber(L, 2)); } else if (isUserdata(L, 2)) { @@ -11799,13 +11588,13 @@ int LuaScriptInterface::luaMonsterCreate(lua_State* L) lua_pushnil(L); return 1; } - monster = getUserdata(L, 2); + monster = getSharedPtr(L, 2); } else { monster = nullptr; } if (monster) { - pushUserdata(L, monster); + pushSharedPtr(L, monster); setMetatable(L, -1, "Monster"); } else { lua_pushnil(L); @@ -11816,8 +11605,7 @@ int LuaScriptInterface::luaMonsterCreate(lua_State* L) int LuaScriptInterface::luaMonsterGetId(lua_State* L) { // monster:getId() - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { // Set monster id if it's not set yet (only for onSpawn event) if (getScriptEnv()->getScriptId() == g_events->getScriptId(EventInfoId::MONSTER_ONSPAWN)) { monster->setID(); @@ -11840,8 +11628,7 @@ int LuaScriptInterface::luaMonsterIsMonster(lua_State* L) int LuaScriptInterface::luaMonsterGetType(lua_State* L) { // monster:getType() - const Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { pushUserdata(L, monster->mType); setMetatable(L, -1, "MonsterType"); } else { @@ -11853,7 +11640,7 @@ int LuaScriptInterface::luaMonsterGetType(lua_State* L) int LuaScriptInterface::luaMonsterRename(lua_State* L) { // monster:rename(name[, nameDescription]) - Monster* monster = getUserdata(L, 1); + const auto monster = getSharedPtr(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -11871,8 +11658,7 @@ int LuaScriptInterface::luaMonsterRename(lua_State* L) int LuaScriptInterface::luaMonsterGetSpawnPosition(lua_State* L) { // monster:getSpawnPosition() - const Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { pushPosition(L, monster->getMasterPos()); } else { lua_pushnil(L); @@ -11883,8 +11669,7 @@ int LuaScriptInterface::luaMonsterGetSpawnPosition(lua_State* L) int LuaScriptInterface::luaMonsterIsInSpawnRange(lua_State* L) { // monster:isInSpawnRange([position]) - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { pushBoolean(L, monster->isInSpawnRange(lua_gettop(L) >= 2 ? getPosition(L, 2) : monster->getPosition())); } else { lua_pushnil(L); @@ -11895,8 +11680,7 @@ int LuaScriptInterface::luaMonsterIsInSpawnRange(lua_State* L) int LuaScriptInterface::luaMonsterIsIdle(lua_State* L) { // monster:isIdle() - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { pushBoolean(L, monster->getIdleStatus()); } else { lua_pushnil(L); @@ -11907,7 +11691,7 @@ int LuaScriptInterface::luaMonsterIsIdle(lua_State* L) int LuaScriptInterface::luaMonsterSetIdle(lua_State* L) { // monster:setIdle(idle) - Monster* monster = getUserdata(L, 1); + const auto monster = getSharedPtr(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -11921,9 +11705,8 @@ int LuaScriptInterface::luaMonsterSetIdle(lua_State* L) int LuaScriptInterface::luaMonsterIsTarget(lua_State* L) { // monster:isTarget(creature) - Monster* monster = getUserdata(L, 1); - if (monster) { - const Creature* creature = getCreature(L, 2); + if (const auto monster = getSharedPtr(L, 1)) { + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -11940,9 +11723,8 @@ int LuaScriptInterface::luaMonsterIsTarget(lua_State* L) int LuaScriptInterface::luaMonsterIsOpponent(lua_State* L) { // monster:isOpponent(creature) - Monster* monster = getUserdata(L, 1); - if (monster) { - const Creature* creature = getCreature(L, 2); + if (const auto monster = getSharedPtr(L, 1)) { + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -11959,9 +11741,8 @@ int LuaScriptInterface::luaMonsterIsOpponent(lua_State* L) int LuaScriptInterface::luaMonsterIsFriend(lua_State* L) { // monster:isFriend(creature) - Monster* monster = getUserdata(L, 1); - if (monster) { - const Creature* creature = getCreature(L, 2); + if (const auto monster = getSharedPtr(L, 1)) { + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -11978,9 +11759,8 @@ int LuaScriptInterface::luaMonsterIsFriend(lua_State* L) int LuaScriptInterface::luaMonsterAddFriend(lua_State* L) { // monster:addFriend(creature) - Monster* monster = getUserdata(L, 1); - if (monster) { - Creature* creature = getCreature(L, 2); + if (const auto monster = getSharedPtr(L, 1)) { + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -11998,9 +11778,8 @@ int LuaScriptInterface::luaMonsterAddFriend(lua_State* L) int LuaScriptInterface::luaMonsterRemoveFriend(lua_State* L) { // monster:removeFriend(creature) - Monster* monster = getUserdata(L, 1); - if (monster) { - Creature* creature = getCreature(L, 2); + if (const auto monster = getSharedPtr(L, 1)) { + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -12018,7 +11797,7 @@ int LuaScriptInterface::luaMonsterRemoveFriend(lua_State* L) int LuaScriptInterface::luaMonsterGetFriendList(lua_State* L) { // monster:getFriendList() - Monster* monster = getUserdata(L, 1); + const auto monster = getSharedPtr(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -12028,8 +11807,8 @@ int LuaScriptInterface::luaMonsterGetFriendList(lua_State* L) lua_createtable(L, friendList.size(), 0); int index = 0; - for (Creature* creature : friendList) { - pushUserdata(L, creature); + for (const auto creature : friendList) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); lua_rawseti(L, -2, ++index); } @@ -12039,8 +11818,7 @@ int LuaScriptInterface::luaMonsterGetFriendList(lua_State* L) int LuaScriptInterface::luaMonsterGetFriendCount(lua_State* L) { // monster:getFriendCount() - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { lua_pushinteger(L, monster->getFriendList().size()); } else { lua_pushnil(L); @@ -12051,20 +11829,20 @@ int LuaScriptInterface::luaMonsterGetFriendCount(lua_State* L) int LuaScriptInterface::luaMonsterAddTarget(lua_State* L) { // monster:addTarget(creature[, pushFront = false]) - Monster* monster = getUserdata(L, 1); + const auto monster = getSharedPtr(L, 1); if (!monster) { lua_pushnil(L); return 1; } - Creature* creature = getCreature(L, 2); + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - bool pushFront = getBoolean(L, 3, false); + const bool pushFront = getBoolean(L, 3, false); monster->addTarget(creature, pushFront); pushBoolean(L, true); return 1; @@ -12073,13 +11851,13 @@ int LuaScriptInterface::luaMonsterAddTarget(lua_State* L) int LuaScriptInterface::luaMonsterRemoveTarget(lua_State* L) { // monster:removeTarget(creature) - Monster* monster = getUserdata(L, 1); + const auto monster = getSharedPtr(L, 1); if (!monster) { lua_pushnil(L); return 1; } - Creature* creature = getCreature(L, 2); + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -12094,7 +11872,7 @@ int LuaScriptInterface::luaMonsterRemoveTarget(lua_State* L) int LuaScriptInterface::luaMonsterGetTargetList(lua_State* L) { // monster:getTargetList() - Monster* monster = getUserdata(L, 1); + const auto monster = getUserdata(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -12104,8 +11882,8 @@ int LuaScriptInterface::luaMonsterGetTargetList(lua_State* L) lua_createtable(L, targetList.size(), 0); int index = 0; - for (Creature* creature : targetList) { - pushUserdata(L, creature); + for (const auto creature : targetList) { + pushSharedPtr(L, creature); setCreatureMetatable(L, -1, creature); lua_rawseti(L, -2, ++index); } @@ -12115,8 +11893,7 @@ int LuaScriptInterface::luaMonsterGetTargetList(lua_State* L) int LuaScriptInterface::luaMonsterGetTargetCount(lua_State* L) { // monster:getTargetCount() - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { lua_pushinteger(L, monster->getTargetList().size()); } else { lua_pushnil(L); @@ -12127,9 +11904,8 @@ int LuaScriptInterface::luaMonsterGetTargetCount(lua_State* L) int LuaScriptInterface::luaMonsterSelectTarget(lua_State* L) { // monster:selectTarget(creature) - Monster* monster = getUserdata(L, 1); - if (monster) { - Creature* creature = getCreature(L, 2); + if (const auto monster = getSharedPtr(L, 1)) { + const auto creature = getCreature(L, 2); if (!creature) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -12146,9 +11922,8 @@ int LuaScriptInterface::luaMonsterSelectTarget(lua_State* L) int LuaScriptInterface::luaMonsterSearchTarget(lua_State* L) { // monster:searchTarget([searchType = TARGETSEARCH_DEFAULT]) - Monster* monster = getUserdata(L, 1); - if (monster) { - TargetSearchType_t searchType = getNumber(L, 2, TARGETSEARCH_DEFAULT); + if (const auto monster = getSharedPtr(L, 1)) { + const auto searchType = getNumber(L, 2, TARGETSEARCH_DEFAULT); pushBoolean(L, monster->searchTarget(searchType)); } else { lua_pushnil(L); @@ -12159,8 +11934,7 @@ int LuaScriptInterface::luaMonsterSearchTarget(lua_State* L) int LuaScriptInterface::luaMonsterIsWalkingToSpawn(lua_State* L) { // monster:isWalkingToSpawn() - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { pushBoolean(L, monster->isWalkingToSpawn()); } else { lua_pushnil(L); @@ -12171,8 +11945,7 @@ int LuaScriptInterface::luaMonsterIsWalkingToSpawn(lua_State* L) int LuaScriptInterface::luaMonsterWalkToSpawn(lua_State* L) { // monster:walkToSpawn() - Monster* monster = getUserdata(L, 1); - if (monster) { + if (const auto monster = getSharedPtr(L, 1)) { pushBoolean(L, monster->walkToSpawn()); } else { lua_pushnil(L); @@ -12184,7 +11957,7 @@ int LuaScriptInterface::luaMonsterWalkToSpawn(lua_State* L) int LuaScriptInterface::luaNpcCreate(lua_State* L) { // Npc([id or name or userdata]) - Npc* npc; + NpcPtr npc; if (lua_gettop(L) >= 2) { if (isNumber(L, 2)) { npc = g_game.getNpcByID(getNumber(L, 2)); @@ -12195,7 +11968,7 @@ int LuaScriptInterface::luaNpcCreate(lua_State* L) lua_pushnil(L); return 1; } - npc = getUserdata(L, 2); + npc = getSharedPtr(L, 2); } else { npc = nullptr; } @@ -12204,7 +11977,7 @@ int LuaScriptInterface::luaNpcCreate(lua_State* L) } if (npc) { - pushUserdata(L, npc); + pushSharedPtr(L, npc); setMetatable(L, -1, "Npc"); } else { lua_pushnil(L); @@ -12215,21 +11988,21 @@ int LuaScriptInterface::luaNpcCreate(lua_State* L) int LuaScriptInterface::luaNpcIsNpc(lua_State* L) { // npc:isNpc() - pushBoolean(L, getUserdata(L, 1) != nullptr); + pushBoolean(L, getSharedPtr(L, 1) != nullptr); return 1; } int LuaScriptInterface::luaNpcSetMasterPos(lua_State* L) { // npc:setMasterPos(pos[, radius]) - Npc* npc = getUserdata(L, 1); + const auto npc = getSharedPtr(L, 1); if (!npc) { lua_pushnil(L); return 1; } const Position& pos = getPosition(L, 2); - int32_t radius = getNumber(L, 3, 1); + const int32_t radius = getNumber(L, 3, 1); npc->setMasterPos(pos, radius); pushBoolean(L, true); return 1; @@ -12238,8 +12011,7 @@ int LuaScriptInterface::luaNpcSetMasterPos(lua_State* L) int LuaScriptInterface::luaNpcGetSpeechBubble(lua_State* L) { // npc:getSpeechBubble() - Npc* npc = getUserdata(L, 1); - if (npc) { + if (const auto npc = getSharedPtr(L, 1)) { lua_pushinteger(L, npc->getSpeechBubble()); } else { lua_pushnil(L); @@ -12250,7 +12022,7 @@ int LuaScriptInterface::luaNpcGetSpeechBubble(lua_State* L) int LuaScriptInterface::luaNpcSetSpeechBubble(lua_State* L) { // npc:setSpeechBubble(speechBubble) - Npc* npc = getUserdata(L, 1); + const auto npc = getSharedPtr(L, 1); if (!npc) { lua_pushnil(L); return 1; @@ -12261,8 +12033,7 @@ int LuaScriptInterface::luaNpcSetSpeechBubble(lua_State* L) return 1; } - uint8_t speechBubble = getNumber(L, 2); - if (speechBubble > SPEECHBUBBLE_LAST) { + if (const uint8_t speechBubble = getNumber(L, 2); speechBubble > SPEECHBUBBLE_LAST) { lua_pushnil(L); } else { npc->setSpeechBubble(speechBubble); @@ -12276,7 +12047,7 @@ int LuaScriptInterface::luaNpcSetSpeechBubble(lua_State* L) int LuaScriptInterface::luaNpcGetSpectators(lua_State* L) { // npc:getSpectators() - Npc* npc = getUserdata(L, 1); + const auto npc = getSharedPtr(L, 1); if (!npc) { lua_pushnil(L); return 1; @@ -12287,7 +12058,7 @@ int LuaScriptInterface::luaNpcGetSpectators(lua_State* L) int index = 0; for (const auto& spectatorPlayer : npc->getSpectators()) { - pushUserdata(L, spectatorPlayer); + pushSharedPtr(L, spectatorPlayer); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); } @@ -12298,10 +12069,9 @@ int LuaScriptInterface::luaNpcGetSpectators(lua_State* L) int LuaScriptInterface::luaGuildCreate(lua_State* L) { // Guild(id) - uint32_t id = getNumber(L, 2); + const uint32_t id = getNumber(L, 2); - Guild* guild = g_game.getGuild(id); - if (guild) { + if (const auto guild = g_game.getGuild(id)) { pushUserdata(L, guild); setMetatable(L, -1, "Guild"); } else { @@ -12313,8 +12083,7 @@ int LuaScriptInterface::luaGuildCreate(lua_State* L) int LuaScriptInterface::luaGuildGetId(lua_State* L) { // guild:getId() - Guild* guild = getUserdata(L, 1); - if (guild) { + if (const auto guild = getUserdata(L, 1)) { lua_pushinteger(L, guild->getId()); } else { lua_pushnil(L); @@ -12325,8 +12094,7 @@ int LuaScriptInterface::luaGuildGetId(lua_State* L) int LuaScriptInterface::luaGuildGetName(lua_State* L) { // guild:getName() - Guild* guild = getUserdata(L, 1); - if (guild) { + if (const auto guild = getUserdata(L, 1)) { pushString(L, guild->getName()); } else { lua_pushnil(L); @@ -12337,7 +12105,7 @@ int LuaScriptInterface::luaGuildGetName(lua_State* L) int LuaScriptInterface::luaGuildGetMembersOnline(lua_State* L) { // guild:getMembersOnline() - const Guild* guild = getUserdata(L, 1); + const auto guild = getUserdata(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -12347,8 +12115,8 @@ int LuaScriptInterface::luaGuildGetMembersOnline(lua_State* L) lua_createtable(L, members.size(), 0); int index = 0; - for (Player* player : members) { - pushUserdata(L, player); + for (const auto player : members) { + pushSharedPtr(L, player); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); } @@ -12358,11 +12126,10 @@ int LuaScriptInterface::luaGuildGetMembersOnline(lua_State* L) int LuaScriptInterface::luaGuildAddRank(lua_State* L) { // guild:addRank(id, name, level) - Guild* guild = getUserdata(L, 1); - if (guild) { - uint32_t id = getNumber(L, 2); + if (const auto guild = getSharedPtr(L, 1)) { + const uint32_t id = getNumber(L, 2); const std::string& name = getString(L, 3); - uint8_t level = getNumber(L, 4); + const uint8_t level = getNumber(L, 4); guild->addRank(id, name, level); pushBoolean(L, true); } else { @@ -12374,15 +12141,14 @@ int LuaScriptInterface::luaGuildAddRank(lua_State* L) int LuaScriptInterface::luaGuildGetRankById(lua_State* L) { // guild:getRankById(id) - Guild* guild = getUserdata(L, 1); + const auto guild = getUserdata(L, 1); if (!guild) { lua_pushnil(L); return 1; } - uint32_t id = getNumber(L, 2); - GuildRank_ptr rank = guild->getRankById(id); - if (rank) { + const uint32_t id = getNumber(L, 2); + if (const auto rank = guild->getRankById(id)) { lua_createtable(L, 0, 3); setField(L, "id", rank->id); setField(L, "name", rank->name); @@ -12396,15 +12162,14 @@ int LuaScriptInterface::luaGuildGetRankById(lua_State* L) int LuaScriptInterface::luaGuildGetRankByLevel(lua_State* L) { // guild:getRankByLevel(level) - const Guild* guild = getUserdata(L, 1); + const auto guild = getUserdata(L, 1); if (!guild) { lua_pushnil(L); return 1; } - uint8_t level = getNumber(L, 2); - GuildRank_ptr rank = guild->getRankByLevel(level); - if (rank) { + const uint8_t level = getNumber(L, 2); + if (const auto rank = guild->getRankByLevel(level)) { lua_createtable(L, 0, 3); setField(L, "id", rank->id); setField(L, "name", rank->name); @@ -12418,8 +12183,7 @@ int LuaScriptInterface::luaGuildGetRankByLevel(lua_State* L) int LuaScriptInterface::luaGuildGetMotd(lua_State* L) { // guild:getMotd() - Guild* guild = getUserdata(L, 1); - if (guild) { + if (const auto guild = getUserdata(L, 1)) { pushString(L, guild->getMotd()); } else { lua_pushnil(L); @@ -12431,8 +12195,7 @@ int LuaScriptInterface::luaGuildSetMotd(lua_State* L) { // guild:setMotd(motd) const std::string& motd = getString(L, 2); - Guild* guild = getUserdata(L, 1); - if (guild) { + if (const auto guild = getUserdata(L, 1)) { guild->setMotd(motd); pushBoolean(L, true); } else { @@ -12445,10 +12208,9 @@ int LuaScriptInterface::luaGuildSetMotd(lua_State* L) int LuaScriptInterface::luaGroupCreate(lua_State* L) { // Group(id) - uint32_t id = getNumber(L, 2); + const uint32_t id = getNumber(L, 2); - Group* group = g_game.groups.getGroup(id); - if (group) { + if (const auto group = g_game.groups.getGroup(id)) { pushUserdata(L, group); setMetatable(L, -1, "Group"); } else { @@ -12460,8 +12222,7 @@ int LuaScriptInterface::luaGroupCreate(lua_State* L) int LuaScriptInterface::luaGroupGetId(lua_State* L) { // group:getId() - Group* group = getUserdata(L, 1); - if (group) { + if (const auto group = getUserdata(L, 1)) { lua_pushinteger(L, group->id); } else { lua_pushnil(L); @@ -12472,8 +12233,7 @@ int LuaScriptInterface::luaGroupGetId(lua_State* L) int LuaScriptInterface::luaGroupGetName(lua_State* L) { // group:getName() - Group* group = getUserdata(L, 1); - if (group) { + if (const auto group = getUserdata(L, 1)) { pushString(L, group->name); } else { lua_pushnil(L); @@ -12484,8 +12244,7 @@ int LuaScriptInterface::luaGroupGetName(lua_State* L) int LuaScriptInterface::luaGroupGetFlags(lua_State* L) { // group:getFlags() - Group* group = getUserdata(L, 1); - if (group) { + if (const auto group = getUserdata(L, 1)) { lua_pushinteger(L, group->flags); } else { lua_pushnil(L); @@ -12496,8 +12255,7 @@ int LuaScriptInterface::luaGroupGetFlags(lua_State* L) int LuaScriptInterface::luaGroupGetAccess(lua_State* L) { // group:getAccess() - Group* group = getUserdata(L, 1); - if (group) { + if (const auto group = getUserdata(L, 1)) { pushBoolean(L, group->access); } else { lua_pushnil(L); @@ -12508,8 +12266,7 @@ int LuaScriptInterface::luaGroupGetAccess(lua_State* L) int LuaScriptInterface::luaGroupGetMaxDepotItems(lua_State* L) { // group:getMaxDepotItems() - Group* group = getUserdata(L, 1); - if (group) { + if (const auto group = getUserdata(L, 1)) { lua_pushinteger(L, group->maxDepotItems); } else { lua_pushnil(L); @@ -12520,8 +12277,7 @@ int LuaScriptInterface::luaGroupGetMaxDepotItems(lua_State* L) int LuaScriptInterface::luaGroupGetMaxVipEntries(lua_State* L) { // group:getMaxVipEntries() - Group* group = getUserdata(L, 1); - if (group) { + if (const auto group = getUserdata(L, 1)) { lua_pushinteger(L, group->maxVipEntries); } else { lua_pushnil(L); @@ -12532,9 +12288,8 @@ int LuaScriptInterface::luaGroupGetMaxVipEntries(lua_State* L) int LuaScriptInterface::luaGroupHasFlag(lua_State* L) { // group:hasFlag(flag) - Group* group = getUserdata(L, 1); - if (group) { - PlayerFlags flag = getNumber(L, 2); + if (const auto group = getUserdata(L, 1)) { + const auto flag = getNumber(L, 2); pushBoolean(L, (group->flags & flag) != 0); } else { lua_pushnil(L); @@ -12553,8 +12308,7 @@ int LuaScriptInterface::luaVocationCreate(lua_State* L) id = g_vocations.getVocationId(getString(L, 2)); } - Vocation* vocation = g_vocations.getVocation(id); - if (vocation) { + if (const auto vocation = g_vocations.getVocation(id)) { pushUserdata(L, vocation); setMetatable(L, -1, "Vocation"); } else { @@ -12566,8 +12320,7 @@ int LuaScriptInterface::luaVocationCreate(lua_State* L) int LuaScriptInterface::luaVocationGetId(lua_State* L) { // vocation:getId() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getId()); } else { lua_pushnil(L); @@ -12578,8 +12331,7 @@ int LuaScriptInterface::luaVocationGetId(lua_State* L) int LuaScriptInterface::luaVocationGetClientId(lua_State* L) { // vocation:getClientId() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getClientId()); } else { lua_pushnil(L); @@ -12590,8 +12342,7 @@ int LuaScriptInterface::luaVocationGetClientId(lua_State* L) int LuaScriptInterface::luaVocationGetName(lua_State* L) { // vocation:getName() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { pushString(L, vocation->getVocName()); } else { lua_pushnil(L); @@ -12602,8 +12353,7 @@ int LuaScriptInterface::luaVocationGetName(lua_State* L) int LuaScriptInterface::luaVocationGetDescription(lua_State* L) { // vocation:getDescription() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { pushString(L, vocation->getVocDescription()); } else { lua_pushnil(L); @@ -12614,10 +12364,9 @@ int LuaScriptInterface::luaVocationGetDescription(lua_State* L) int LuaScriptInterface::luaVocationGetRequiredSkillTries(lua_State* L) { // vocation:getRequiredSkillTries(skillType, skillLevel) - Vocation* vocation = getUserdata(L, 1); - if (vocation) { - skills_t skillType = getNumber(L, 2); - uint16_t skillLevel = getNumber(L, 3); + if (const auto vocation = getUserdata(L, 1)) { + const auto skillType = getNumber(L, 2); + const uint16_t skillLevel = getNumber(L, 3); lua_pushinteger(L, vocation->getReqSkillTries(skillType, skillLevel)); } else { lua_pushnil(L); @@ -12628,9 +12377,8 @@ int LuaScriptInterface::luaVocationGetRequiredSkillTries(lua_State* L) int LuaScriptInterface::luaVocationGetRequiredManaSpent(lua_State* L) { // vocation:getRequiredManaSpent(magicLevel) - Vocation* vocation = getUserdata(L, 1); - if (vocation) { - uint32_t magicLevel = getNumber(L, 2); + if (const auto vocation = getUserdata(L, 1)) { + const uint32_t magicLevel = getNumber(L, 2); lua_pushinteger(L, vocation->getReqMana(magicLevel)); } else { lua_pushnil(L); @@ -12641,8 +12389,7 @@ int LuaScriptInterface::luaVocationGetRequiredManaSpent(lua_State* L) int LuaScriptInterface::luaVocationGetCapacityGain(lua_State* L) { // vocation:getCapacityGain() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getCapGain()); } else { lua_pushnil(L); @@ -12653,8 +12400,7 @@ int LuaScriptInterface::luaVocationGetCapacityGain(lua_State* L) int LuaScriptInterface::luaVocationGetHealthGain(lua_State* L) { // vocation:getHealthGain() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getHPGain()); } else { lua_pushnil(L); @@ -12665,8 +12411,7 @@ int LuaScriptInterface::luaVocationGetHealthGain(lua_State* L) int LuaScriptInterface::luaVocationGetHealthGainTicks(lua_State* L) { // vocation:getHealthGainTicks() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getHealthGainTicks()); } else { lua_pushnil(L); @@ -12677,8 +12422,7 @@ int LuaScriptInterface::luaVocationGetHealthGainTicks(lua_State* L) int LuaScriptInterface::luaVocationGetHealthGainAmount(lua_State* L) { // vocation:getHealthGainAmount() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getHealthGainAmount()); } else { lua_pushnil(L); @@ -12689,8 +12433,7 @@ int LuaScriptInterface::luaVocationGetHealthGainAmount(lua_State* L) int LuaScriptInterface::luaVocationGetManaGain(lua_State* L) { // vocation:getManaGain() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getManaGain()); } else { lua_pushnil(L); @@ -12701,8 +12444,7 @@ int LuaScriptInterface::luaVocationGetManaGain(lua_State* L) int LuaScriptInterface::luaVocationGetManaGainTicks(lua_State* L) { // vocation:getManaGainTicks() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getManaGainTicks()); } else { lua_pushnil(L); @@ -12713,8 +12455,7 @@ int LuaScriptInterface::luaVocationGetManaGainTicks(lua_State* L) int LuaScriptInterface::luaVocationGetManaGainAmount(lua_State* L) { // vocation:getManaGainAmount() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getManaGainAmount()); } else { lua_pushnil(L); @@ -12725,8 +12466,7 @@ int LuaScriptInterface::luaVocationGetManaGainAmount(lua_State* L) int LuaScriptInterface::luaVocationGetMaxSoul(lua_State* L) { // vocation:getMaxSoul() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getSoulMax()); } else { lua_pushnil(L); @@ -12737,8 +12477,7 @@ int LuaScriptInterface::luaVocationGetMaxSoul(lua_State* L) int LuaScriptInterface::luaVocationGetSoulGainTicks(lua_State* L) { // vocation:getSoulGainTicks() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getSoulGainTicks()); } else { lua_pushnil(L); @@ -12749,8 +12488,7 @@ int LuaScriptInterface::luaVocationGetSoulGainTicks(lua_State* L) int LuaScriptInterface::luaVocationGetAttackSpeed(lua_State* L) { // vocation:getAttackSpeed() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getAttackSpeed()); } else { lua_pushnil(L); @@ -12761,8 +12499,7 @@ int LuaScriptInterface::luaVocationGetAttackSpeed(lua_State* L) int LuaScriptInterface::luaVocationGetBaseSpeed(lua_State* L) { // vocation:getBaseSpeed() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { lua_pushinteger(L, vocation->getBaseSpeed()); } else { lua_pushnil(L); @@ -12773,21 +12510,21 @@ int LuaScriptInterface::luaVocationGetBaseSpeed(lua_State* L) int LuaScriptInterface::luaVocationGetDemotion(lua_State* L) { // vocation:getDemotion() - Vocation* vocation = getUserdata(L, 1); + const auto vocation = getUserdata(L, 1); if (!vocation) { lua_pushnil(L); return 1; } - uint16_t fromId = vocation->getFromVocation(); + const uint16_t fromId = vocation->getFromVocation(); if (fromId == VOCATION_NONE) { lua_pushnil(L); return 1; } - Vocation* demotedVocation = g_vocations.getVocation(fromId); + const auto demotedVocation = g_vocations.getVocation(fromId); if (demotedVocation && demotedVocation != vocation) { - pushUserdata(L, demotedVocation); + pushSharedPtr(L, demotedVocation); setMetatable(L, -1, "Vocation"); } else { lua_pushnil(L); @@ -12798,21 +12535,21 @@ int LuaScriptInterface::luaVocationGetDemotion(lua_State* L) int LuaScriptInterface::luaVocationGetPromotion(lua_State* L) { // vocation:getPromotion() - Vocation* vocation = getUserdata(L, 1); + const auto vocation = getUserdata(L, 1); if (!vocation) { lua_pushnil(L); return 1; } - uint16_t promotedId = g_vocations.getPromotedVocation(vocation->getId()); + const uint16_t promotedId = g_vocations.getPromotedVocation(vocation->getId()); if (promotedId == VOCATION_NONE) { lua_pushnil(L); return 1; } - Vocation* promotedVocation = g_vocations.getVocation(promotedId); + const auto promotedVocation = g_vocations.getVocation(promotedId); if (promotedVocation && promotedVocation != vocation) { - pushUserdata(L, promotedVocation); + pushSharedPtr(L, promotedVocation); setMetatable(L, -1, "Vocation"); } else { lua_pushnil(L); @@ -12823,8 +12560,7 @@ int LuaScriptInterface::luaVocationGetPromotion(lua_State* L) int LuaScriptInterface::luaVocationAllowsPvp(lua_State* L) { // vocation:allowsPvp() - Vocation* vocation = getUserdata(L, 1); - if (vocation) { + if (const auto vocation = getUserdata(L, 1)) { pushBoolean(L, vocation->allowsPvp()); } else { lua_pushnil(L); @@ -12857,8 +12593,7 @@ int LuaScriptInterface::luaTownCreate(lua_State* L) int LuaScriptInterface::luaTownGetId(lua_State* L) { // town:getId() - Town* town = getUserdata(L, 1); - if (town) { + if (const auto town = getUserdata(L, 1)) { lua_pushinteger(L, town->getID()); } else { lua_pushnil(L); @@ -12869,8 +12604,7 @@ int LuaScriptInterface::luaTownGetId(lua_State* L) int LuaScriptInterface::luaTownGetName(lua_State* L) { // town:getName() - Town* town = getUserdata(L, 1); - if (town) { + if (const auto town = getUserdata(L, 1)) { pushString(L, town->getName()); } else { lua_pushnil(L); @@ -12881,8 +12615,7 @@ int LuaScriptInterface::luaTownGetName(lua_State* L) int LuaScriptInterface::luaTownGetTemplePosition(lua_State* L) { // town:getTemplePosition() - Town* town = getUserdata(L, 1); - if (town) { + if (const auto town = getUserdata(L, 1)) { pushPosition(L, town->getTemplePosition()); } else { lua_pushnil(L); @@ -12894,8 +12627,7 @@ int LuaScriptInterface::luaTownGetTemplePosition(lua_State* L) int LuaScriptInterface::luaHouseCreate(lua_State* L) { // House(id) - House* house = g_game.map.houses.getHouse(getNumber(L, 2)); - if (house) { + if (const auto house = g_game.map.houses.getHouse(getNumber(L, 2))) { pushUserdata(L, house); setMetatable(L, -1, "House"); } else { @@ -12907,8 +12639,7 @@ int LuaScriptInterface::luaHouseCreate(lua_State* L) int LuaScriptInterface::luaHouseGetId(lua_State* L) { // house:getId() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getId()); } else { lua_pushnil(L); @@ -12919,8 +12650,7 @@ int LuaScriptInterface::luaHouseGetId(lua_State* L) int LuaScriptInterface::luaHouseGetName(lua_State* L) { // house:getName() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { pushString(L, house->getName()); } else { lua_pushnil(L); @@ -12931,14 +12661,13 @@ int LuaScriptInterface::luaHouseGetName(lua_State* L) int LuaScriptInterface::luaHouseGetTown(lua_State* L) { // house:getTown() - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; } - Town* town = g_game.map.towns.getTown(house->getTownId()); - if (town) { + if (const auto town = g_game.map.towns.getTown(house->getTownId())) { pushUserdata(L, town); setMetatable(L, -1, "Town"); } else { @@ -12950,8 +12679,7 @@ int LuaScriptInterface::luaHouseGetTown(lua_State* L) int LuaScriptInterface::luaHouseGetExitPosition(lua_State* L) { // house:getExitPosition() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { pushPosition(L, house->getEntryPosition()); } else { lua_pushnil(L); @@ -12962,8 +12690,7 @@ int LuaScriptInterface::luaHouseGetExitPosition(lua_State* L) int LuaScriptInterface::luaHouseGetRent(lua_State* L) { // house:getRent() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getRent()); } else { lua_pushnil(L); @@ -12974,9 +12701,8 @@ int LuaScriptInterface::luaHouseGetRent(lua_State* L) int LuaScriptInterface::luaHouseSetRent(lua_State* L) { // house:setRent(rent) - uint32_t rent = getNumber(L, 2); - House* house = getUserdata(L, 1); - if (house) { + const uint32_t rent = getNumber(L, 2); + if (const auto house = getUserdata(L, 1)) { house->setRent(rent); pushBoolean(L, true); } else { @@ -12988,8 +12714,7 @@ int LuaScriptInterface::luaHouseSetRent(lua_State* L) int LuaScriptInterface::luaHouseGetPaidUntil(lua_State* L) { // house:getPaidUntil() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getPaidUntil()); } else { lua_pushnil(L); @@ -13000,9 +12725,8 @@ int LuaScriptInterface::luaHouseGetPaidUntil(lua_State* L) int LuaScriptInterface::luaHouseSetPaidUntil(lua_State* L) { // house:setPaidUntil(timestamp) - time_t timestamp = getNumber(L, 2); - House* house = getUserdata(L, 1); - if (house) { + const time_t timestamp = getNumber(L, 2); + if (const auto house = getUserdata(L, 1)) { house->setPaidUntil(timestamp); pushBoolean(L, true); } else { @@ -13014,8 +12738,7 @@ int LuaScriptInterface::luaHouseSetPaidUntil(lua_State* L) int LuaScriptInterface::luaHouseGetPayRentWarnings(lua_State* L) { // house:getPayRentWarnings() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getPayRentWarnings()); } else { lua_pushnil(L); @@ -13026,9 +12749,8 @@ int LuaScriptInterface::luaHouseGetPayRentWarnings(lua_State* L) int LuaScriptInterface::luaHouseSetPayRentWarnings(lua_State* L) { // house:setPayRentWarnings(warnings) - uint32_t warnings = getNumber(L, 2); - House* house = getUserdata(L, 1); - if (house) { + const uint32_t warnings = getNumber(L, 2); + if (const auto house = getUserdata(L, 1)) { house->setPayRentWarnings(warnings); pushBoolean(L, true); } else { @@ -13040,8 +12762,7 @@ int LuaScriptInterface::luaHouseSetPayRentWarnings(lua_State* L) int LuaScriptInterface::luaHouseGetOwnerGuid(lua_State* L) { // house:getOwnerGuid() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getOwner()); } else { lua_pushnil(L); @@ -13052,10 +12773,9 @@ int LuaScriptInterface::luaHouseGetOwnerGuid(lua_State* L) int LuaScriptInterface::luaHouseSetOwnerGuid(lua_State* L) { // house:setOwnerGuid(guid[, updateDatabase = true]) - House* house = getUserdata(L, 1); - if (house) { - uint32_t guid = getNumber(L, 2); - bool updateDatabase = getBoolean(L, 3, true); + if (const auto house = getUserdata(L, 1)) { + const uint32_t guid = getNumber(L, 2); + const bool updateDatabase = getBoolean(L, 3, true); house->setOwner(guid, updateDatabase); pushBoolean(L, true); } else { @@ -13067,9 +12787,9 @@ int LuaScriptInterface::luaHouseSetOwnerGuid(lua_State* L) int LuaScriptInterface::luaHouseStartTrade(lua_State* L) { // house:startTrade(player, tradePartner) - House* house = getUserdata(L, 1); - Player* player = getUserdata(L, 2); - Player* tradePartner = getUserdata(L, 3); + const auto house = getUserdata(L, 1); + const auto player = getSharedPtr(L, 2); + const auto tradePartner = getSharedPtr(L, 3); if (!player || !tradePartner || !house) { lua_pushnil(L); @@ -13096,12 +12816,11 @@ int LuaScriptInterface::luaHouseStartTrade(lua_State* L) return 1; } - Item* transferItem = house->getTransferItem(); + const auto transferItem = house->getTransferItem(); if (!transferItem) { lua_pushinteger(L, RETURNVALUE_YOUCANNOTTRADETHISHOUSE); return 1; } - transferItem->getParent()->setParent(player); if (!g_game.internalStartTrade(player, tradePartner, transferItem)) { house->resetTransferItem(); @@ -13114,7 +12833,7 @@ int LuaScriptInterface::luaHouseStartTrade(lua_State* L) int LuaScriptInterface::luaHouseGetBeds(lua_State* L) { // house:getBeds() - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; @@ -13124,8 +12843,8 @@ int LuaScriptInterface::luaHouseGetBeds(lua_State* L) lua_createtable(L, beds.size(), 0); int index = 0; - for (BedItem* bedItem : beds) { - pushUserdata(L, bedItem); + for (const auto bedItem : beds) { + pushSharedPtr(L, bedItem); setItemMetatable(L, -1, bedItem); lua_rawseti(L, -2, ++index); } @@ -13135,8 +12854,7 @@ int LuaScriptInterface::luaHouseGetBeds(lua_State* L) int LuaScriptInterface::luaHouseGetBedCount(lua_State* L) { // house:getBedCount() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getBedCount()); } else { lua_pushnil(L); @@ -13147,7 +12865,7 @@ int LuaScriptInterface::luaHouseGetBedCount(lua_State* L) int LuaScriptInterface::luaHouseGetDoors(lua_State* L) { // house:getDoors() - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; @@ -13157,8 +12875,8 @@ int LuaScriptInterface::luaHouseGetDoors(lua_State* L) lua_createtable(L, doors.size(), 0); int index = 0; - for (Door* door : doors) { - pushUserdata(L, door); + for (const auto door : doors) { + pushSharedPtr(L, door); setItemMetatable(L, -1, door); lua_rawseti(L, -2, ++index); } @@ -13168,8 +12886,7 @@ int LuaScriptInterface::luaHouseGetDoors(lua_State* L) int LuaScriptInterface::luaHouseGetDoorCount(lua_State* L) { // house:getDoorCount() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getDoors().size()); } else { lua_pushnil(L); @@ -13180,14 +12897,13 @@ int LuaScriptInterface::luaHouseGetDoorCount(lua_State* L) int LuaScriptInterface::luaHouseGetDoorIdByPosition(lua_State* L) { // house:getDoorIdByPosition(position) - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; } - Door* door = house->getDoorByPosition(getPosition(L, 2)); - if (door) { + if (const auto door = house->getDoorByPosition(getPosition(L, 2))) { lua_pushinteger(L, door->getDoorId()); } else { lua_pushnil(L); @@ -13198,7 +12914,7 @@ int LuaScriptInterface::luaHouseGetDoorIdByPosition(lua_State* L) int LuaScriptInterface::luaHouseGetTiles(lua_State* L) { // house:getTiles() - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; @@ -13208,8 +12924,8 @@ int LuaScriptInterface::luaHouseGetTiles(lua_State* L) lua_createtable(L, tiles.size(), 0); int index = 0; - for (Tile* tile : tiles) { - pushUserdata(L, tile); + for (const auto tile : tiles) { + pushSharedPtr(L, tile); setMetatable(L, -1, "Tile"); lua_rawseti(L, -2, ++index); } @@ -13219,7 +12935,7 @@ int LuaScriptInterface::luaHouseGetTiles(lua_State* L) int LuaScriptInterface::luaHouseGetItems(lua_State* L) { // house:getItems() - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; @@ -13229,11 +12945,10 @@ int LuaScriptInterface::luaHouseGetItems(lua_State* L) lua_newtable(L); int index = 0; - for (Tile* tile : tiles) { - TileItemVector* itemVector = tile->getItemList(); - if(itemVector) { - for(Item* item : *itemVector) { - pushUserdata(L, item); + for (const auto tile : tiles) { + if(const auto itemVector = tile->getItemList()) { + for(const auto item : *itemVector) { + pushSharedPtr(L, item); setItemMetatable(L, -1, item); lua_rawseti(L, -2, ++index); } @@ -13245,8 +12960,7 @@ int LuaScriptInterface::luaHouseGetItems(lua_State* L) int LuaScriptInterface::luaHouseGetTileCount(lua_State* L) { // house:getTileCount() - House* house = getUserdata(L, 1); - if (house) { + if (const auto house = getUserdata(L, 1)) { lua_pushinteger(L, house->getTiles().size()); } else { lua_pushnil(L); @@ -13257,14 +12971,14 @@ int LuaScriptInterface::luaHouseGetTileCount(lua_State* L) int LuaScriptInterface::luaHouseCanEditAccessList(lua_State* L) { // house:canEditAccessList(listId, player) - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; } uint32_t listId = getNumber(L, 2); - Player* player = getPlayer(L, 3); + const auto player = getPlayer(L, 3); pushBoolean(L, house->canEditAccessList(listId, player)); return 1; @@ -13273,15 +12987,14 @@ int LuaScriptInterface::luaHouseCanEditAccessList(lua_State* L) int LuaScriptInterface::luaHouseGetAccessList(lua_State* L) { // house:getAccessList(listId) - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; } std::string list; - uint32_t listId = getNumber(L, 2); - if (house->getAccessList(listId, list)) { + if (const uint32_t listId = getNumber(L, 2); house->getAccessList(listId, list)) { pushString(L, list); } else { pushBoolean(L, false); @@ -13292,13 +13005,13 @@ int LuaScriptInterface::luaHouseGetAccessList(lua_State* L) int LuaScriptInterface::luaHouseSetAccessList(lua_State* L) { // house:setAccessList(listId, list) - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; } - uint32_t listId = getNumber(L, 2); + const uint32_t listId = getNumber(L, 2); const std::string& list = getString(L, 3); house->setAccessList(listId, list); pushBoolean(L, true); @@ -13308,7 +13021,7 @@ int LuaScriptInterface::luaHouseSetAccessList(lua_State* L) int LuaScriptInterface::luaHouseKickPlayer(lua_State* L) { // house:kickPlayer(player, targetPlayer) - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; @@ -13321,7 +13034,7 @@ int LuaScriptInterface::luaHouseKickPlayer(lua_State* L) int LuaScriptInterface::luaHouseSave(lua_State* L) { // house:save() - House* house = getUserdata(L, 1); + const auto house = getUserdata(L, 1); if (!house) { lua_pushnil(L); return 1; @@ -13354,8 +13067,7 @@ int LuaScriptInterface::luaItemTypeCreate(lua_State* L) int LuaScriptInterface::luaItemTypeIsCorpse(lua_State* L) { // itemType:isCorpse() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->corpseType != RACE_NONE); } else { lua_pushnil(L); @@ -13366,8 +13078,7 @@ int LuaScriptInterface::luaItemTypeIsCorpse(lua_State* L) int LuaScriptInterface::luaItemTypeIsDoor(lua_State* L) { // itemType:isDoor() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isDoor()); } else { lua_pushnil(L); @@ -13378,8 +13089,7 @@ int LuaScriptInterface::luaItemTypeIsDoor(lua_State* L) int LuaScriptInterface::luaItemTypeIsContainer(lua_State* L) { // itemType:isContainer() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isContainer()); } else { lua_pushnil(L); @@ -13390,8 +13100,7 @@ int LuaScriptInterface::luaItemTypeIsContainer(lua_State* L) int LuaScriptInterface::luaItemTypeIsFluidContainer(lua_State* L) { // itemType:isFluidContainer() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isFluidContainer()); } else { lua_pushnil(L); @@ -13402,8 +13111,7 @@ int LuaScriptInterface::luaItemTypeIsFluidContainer(lua_State* L) int LuaScriptInterface::luaItemTypeIsMovable(lua_State* L) { // itemType:isMovable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->moveable); } else { lua_pushnil(L); @@ -13414,8 +13122,7 @@ int LuaScriptInterface::luaItemTypeIsMovable(lua_State* L) int LuaScriptInterface::luaItemTypeIsRune(lua_State* L) { // itemType:isRune() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isRune()); } else { lua_pushnil(L); @@ -13426,8 +13133,7 @@ int LuaScriptInterface::luaItemTypeIsRune(lua_State* L) int LuaScriptInterface::luaItemTypeIsStackable(lua_State* L) { // itemType:isStackable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->stackable); } else { lua_pushnil(L); @@ -13438,8 +13144,7 @@ int LuaScriptInterface::luaItemTypeIsStackable(lua_State* L) int LuaScriptInterface::luaItemTypeIsReadable(lua_State* L) { // itemType:isReadable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->canReadText); } else { lua_pushnil(L); @@ -13450,8 +13155,7 @@ int LuaScriptInterface::luaItemTypeIsReadable(lua_State* L) int LuaScriptInterface::luaItemTypeIsWritable(lua_State* L) { // itemType:isWritable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->canWriteText); } else { lua_pushnil(L); @@ -13462,8 +13166,7 @@ int LuaScriptInterface::luaItemTypeIsWritable(lua_State* L) int LuaScriptInterface::luaItemTypeIsBlocking(lua_State* L) { // itemType:isBlocking() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->blockProjectile || itemType->blockSolid); } else { lua_pushnil(L); @@ -13474,8 +13177,7 @@ int LuaScriptInterface::luaItemTypeIsBlocking(lua_State* L) int LuaScriptInterface::luaItemTypeIsGroundTile(lua_State* L) { // itemType:isGroundTile() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isGroundTile()); } else { lua_pushnil(L); @@ -13486,8 +13188,7 @@ int LuaScriptInterface::luaItemTypeIsGroundTile(lua_State* L) int LuaScriptInterface::luaItemTypeIsMagicField(lua_State* L) { // itemType:isMagicField() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isMagicField()); } else { lua_pushnil(L); @@ -13498,8 +13199,7 @@ int LuaScriptInterface::luaItemTypeIsMagicField(lua_State* L) int LuaScriptInterface::luaItemTypeIsUseable(lua_State* L) { // itemType:isUseable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isUseable()); } else { lua_pushnil(L); @@ -13510,8 +13210,7 @@ int LuaScriptInterface::luaItemTypeIsUseable(lua_State* L) int LuaScriptInterface::luaItemTypeIsPickupable(lua_State* L) { // itemType:isPickupable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->isPickupable()); } else { lua_pushnil(L); @@ -13522,8 +13221,7 @@ int LuaScriptInterface::luaItemTypeIsPickupable(lua_State* L) int LuaScriptInterface::luaItemTypeIsRotatable(lua_State* L) { // itemType:isRotatable() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->rotatable); } else { lua_pushnil(L); @@ -13534,8 +13232,7 @@ int LuaScriptInterface::luaItemTypeIsRotatable(lua_State* L) int LuaScriptInterface::luaItemTypeGetType(lua_State* L) { // itemType:getType() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->type); } else { lua_pushnil(L); @@ -13546,8 +13243,7 @@ int LuaScriptInterface::luaItemTypeGetType(lua_State* L) int LuaScriptInterface::luaItemTypeGetGroup(lua_State* L) { // itemType:getGroup() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->group); } else { lua_pushnil(L); @@ -13558,8 +13254,7 @@ int LuaScriptInterface::luaItemTypeGetGroup(lua_State* L) int LuaScriptInterface::luaItemTypeGetId(lua_State* L) { // itemType:getId() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->id); } else { lua_pushnil(L); @@ -13570,8 +13265,7 @@ int LuaScriptInterface::luaItemTypeGetId(lua_State* L) int LuaScriptInterface::luaItemTypeGetClientId(lua_State* L) { // itemType:getClientId() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->clientId); } else { lua_pushnil(L); @@ -13582,7 +13276,7 @@ int LuaScriptInterface::luaItemTypeGetClientId(lua_State* L) int LuaScriptInterface::luaItemTypeGetName(lua_State* L) { // itemType:getName() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->name); } else { @@ -13594,8 +13288,7 @@ int LuaScriptInterface::luaItemTypeGetName(lua_State* L) int LuaScriptInterface::luaItemTypeGetPluralName(lua_State* L) { // itemType:getPluralName() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushString(L, itemType->getPluralName()); } else { lua_pushnil(L); @@ -13606,8 +13299,7 @@ int LuaScriptInterface::luaItemTypeGetPluralName(lua_State* L) int LuaScriptInterface::luaItemTypeGetRotateTo(lua_State* L) { // itemType:getRotateTo() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->rotateTo); } else { lua_pushnil(L); @@ -13618,7 +13310,7 @@ int LuaScriptInterface::luaItemTypeGetRotateTo(lua_State* L) int LuaScriptInterface::luaItemTypeGetArticle(lua_State* L) { // itemType:getArticle() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->article); } else { @@ -13630,7 +13322,7 @@ int LuaScriptInterface::luaItemTypeGetArticle(lua_State* L) int LuaScriptInterface::luaItemTypeGetDescription(lua_State* L) { // itemType:getDescription() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->description); } else { @@ -13642,7 +13334,7 @@ int LuaScriptInterface::luaItemTypeGetDescription(lua_State* L) int LuaScriptInterface::luaItemTypeGetSlotPosition(lua_State *L) { // itemType:getSlotPosition() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->slotPosition); } else { @@ -13654,7 +13346,7 @@ int LuaScriptInterface::luaItemTypeGetSlotPosition(lua_State *L) int LuaScriptInterface::luaItemTypeGetCharges(lua_State* L) { // itemType:getCharges() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->charges); } else { @@ -13666,7 +13358,7 @@ int LuaScriptInterface::luaItemTypeGetCharges(lua_State* L) int LuaScriptInterface::luaItemTypeGetFluidSource(lua_State* L) { // itemType:getFluidSource() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->fluidSource); } else { @@ -13678,7 +13370,7 @@ int LuaScriptInterface::luaItemTypeGetFluidSource(lua_State* L) int LuaScriptInterface::luaItemTypeGetCapacity(lua_State* L) { // itemType:getCapacity() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->maxItems); } else { @@ -13690,15 +13382,15 @@ int LuaScriptInterface::luaItemTypeGetCapacity(lua_State* L) int LuaScriptInterface::luaItemTypeGetWeight(lua_State* L) { // itemType:getWeight([count = 1]) - uint16_t count = getNumber(L, 2, 1); + const uint16_t count = getNumber(L, 2, 1); - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; } - uint64_t weight = static_cast(itemType->weight) * std::max(1, count); + const uint64_t weight = static_cast(itemType->weight) * std::max(1, count); lua_pushinteger(L, weight); return 1; } @@ -13706,7 +13398,7 @@ int LuaScriptInterface::luaItemTypeGetWeight(lua_State* L) int LuaScriptInterface::luaItemTypeGetWorth(lua_State* L) { // itemType:getWorth() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; @@ -13719,8 +13411,7 @@ int LuaScriptInterface::luaItemTypeGetWorth(lua_State* L) int LuaScriptInterface::luaItemTypeGetHitChance(lua_State* L) { // itemType:getHitChance() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->hitChance); } else { lua_pushnil(L); @@ -13731,8 +13422,7 @@ int LuaScriptInterface::luaItemTypeGetHitChance(lua_State* L) int LuaScriptInterface::luaItemTypeGetShootRange(lua_State* L) { // itemType:getShootRange() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->shootRange); } else { lua_pushnil(L); @@ -13743,8 +13433,7 @@ int LuaScriptInterface::luaItemTypeGetShootRange(lua_State* L) int LuaScriptInterface::luaItemTypeGetAttack(lua_State* L) { // itemType:getAttack() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->attack); } else { lua_pushnil(L); @@ -13755,8 +13444,7 @@ int LuaScriptInterface::luaItemTypeGetAttack(lua_State* L) int LuaScriptInterface::luaItemTypeGetAttackSpeed(lua_State* L) { // itemType:getAttackSpeed() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->attackSpeed); } else { lua_pushnil(L); @@ -13767,7 +13455,7 @@ int LuaScriptInterface::luaItemTypeGetAttackSpeed(lua_State* L) int LuaScriptInterface::luaItemTypeGetClassification(lua_State* L) { // itemType:getClassification() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->classification); } else { @@ -13779,7 +13467,7 @@ int LuaScriptInterface::luaItemTypeGetClassification(lua_State* L) int LuaScriptInterface::luaItemTypeGetTier(lua_State* L) { // itemType:getTier() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->tier); } else { @@ -13791,7 +13479,7 @@ int LuaScriptInterface::luaItemTypeGetTier(lua_State* L) int LuaScriptInterface::luaItemTypeGetDefense(lua_State* L) { // itemType:getDefense() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->defense); } else { @@ -13803,7 +13491,7 @@ int LuaScriptInterface::luaItemTypeGetDefense(lua_State* L) int LuaScriptInterface::luaItemTypeGetExtraDefense(lua_State* L) { // itemType:getExtraDefense() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->extraDefense); } else { @@ -13815,7 +13503,7 @@ int LuaScriptInterface::luaItemTypeGetExtraDefense(lua_State* L) int LuaScriptInterface::luaItemTypeGetArmor(lua_State* L) { // itemType:getArmor() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->armor); } else { @@ -13827,7 +13515,7 @@ int LuaScriptInterface::luaItemTypeGetArmor(lua_State* L) int LuaScriptInterface::luaItemTypeGetWeaponType(lua_State* L) { // itemType:getWeaponType() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { lua_pushinteger(L, itemType->weaponType); } else { @@ -13839,8 +13527,7 @@ int LuaScriptInterface::luaItemTypeGetWeaponType(lua_State* L) int LuaScriptInterface::luaItemTypeGetAmmoType(lua_State* L) { // itemType:getAmmoType() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->ammoType); } else { lua_pushnil(L); @@ -13851,8 +13538,7 @@ int LuaScriptInterface::luaItemTypeGetAmmoType(lua_State* L) int LuaScriptInterface::luaItemTypeGetShootType(lua_State* L) { // itemType:getShootType() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->shootType); } else { @@ -13866,8 +13552,7 @@ int LuaScriptInterface::luaItemTypeGetShootType(lua_State* L) int LuaScriptInterface::luaItemTypeGetCorpseType(lua_State* L) { // itemType:getCorpseType() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->corpseType); } else { lua_pushnil(L); @@ -13878,8 +13563,7 @@ int LuaScriptInterface::luaItemTypeGetCorpseType(lua_State* L) int LuaScriptInterface::luaItemTypeGetAbilities(lua_State* L) { // itemType:getAbilities() - ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { Abilities& abilities = itemType->getAbilities(); lua_createtable(L, 10, 12); setField(L, "healthGain", abilities.healthGain); @@ -13937,8 +13621,7 @@ int LuaScriptInterface::luaItemTypeGetAbilities(lua_State* L) int LuaScriptInterface::luaItemTypeHasShowAttributes(lua_State* L) { // itemType:hasShowAttributes() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->showAttributes); } else { lua_pushnil(L); @@ -13949,8 +13632,7 @@ int LuaScriptInterface::luaItemTypeHasShowAttributes(lua_State* L) int LuaScriptInterface::luaItemTypeHasShowCount(lua_State* L) { // itemType:hasShowCount() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->showCount); } else { lua_pushnil(L); @@ -13961,8 +13643,7 @@ int LuaScriptInterface::luaItemTypeHasShowCount(lua_State* L) int LuaScriptInterface::luaItemTypeHasShowCharges(lua_State* L) { // itemType:hasShowCharges() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->showCharges); } else { lua_pushnil(L); @@ -13973,8 +13654,7 @@ int LuaScriptInterface::luaItemTypeHasShowCharges(lua_State* L) int LuaScriptInterface::luaItemTypeHasShowDuration(lua_State* L) { // itemType:hasShowDuration() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->showDuration); } else { lua_pushnil(L); @@ -13985,8 +13665,7 @@ int LuaScriptInterface::luaItemTypeHasShowDuration(lua_State* L) int LuaScriptInterface::luaItemTypeHasAllowDistRead(lua_State* L) { // itemType:hasAllowDistRead() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->allowDistRead); } else { lua_pushnil(L); @@ -13997,8 +13676,7 @@ int LuaScriptInterface::luaItemTypeHasAllowDistRead(lua_State* L) int LuaScriptInterface::luaItemTypeGetWieldInfo(lua_State* L) { // itemType:getWieldInfo() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->wieldInfo); } else { lua_pushnil(L); @@ -14009,8 +13687,7 @@ int LuaScriptInterface::luaItemTypeGetWieldInfo(lua_State* L) int LuaScriptInterface::luaItemTypeGetDuration(lua_State* L) { // itemType:getDuration() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->decayTime); } else { lua_pushnil(L); @@ -14021,8 +13698,7 @@ int LuaScriptInterface::luaItemTypeGetDuration(lua_State* L) int LuaScriptInterface::luaItemTypeGetLevelDoor(lua_State* L) { // itemType:getLevelDoor() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->levelDoor); } else { lua_pushnil(L); @@ -14033,7 +13709,7 @@ int LuaScriptInterface::luaItemTypeGetLevelDoor(lua_State* L) int LuaScriptInterface::luaItemTypeGetVocationString(lua_State* L) { // itemType:getVocationString() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->vocationString); } else { @@ -14045,8 +13721,7 @@ int LuaScriptInterface::luaItemTypeGetVocationString(lua_State* L) int LuaScriptInterface::luaItemTypeGetMinReqLevel(lua_State* L) { // itemType:getMinReqLevel() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->minReqLevel); } else { lua_pushnil(L); @@ -14057,8 +13732,7 @@ int LuaScriptInterface::luaItemTypeGetMinReqLevel(lua_State* L) int LuaScriptInterface::luaItemTypeGetMinReqMagicLevel(lua_State* L) { // itemType:getMinReqMagicLevel() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->minReqMagicLevel); } else { lua_pushnil(L); @@ -14069,14 +13743,13 @@ int LuaScriptInterface::luaItemTypeGetMinReqMagicLevel(lua_State* L) int LuaScriptInterface::luaItemTypeGetElementType(lua_State* L) { // itemType:getElementType() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; } - auto& abilities = itemType->abilities; - if (abilities) { + if (auto& abilities = itemType->abilities) { lua_pushinteger(L, abilities->elementType); } else { lua_pushnil(L); @@ -14087,14 +13760,13 @@ int LuaScriptInterface::luaItemTypeGetElementType(lua_State* L) int LuaScriptInterface::luaItemTypeGetElementDamage(lua_State* L) { // itemType:getElementDamage() - const ItemType* itemType = getUserdata(L, 1); + const auto itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; } - auto& abilities = itemType->abilities; - if (abilities) { + if (auto& abilities = itemType->abilities) { lua_pushinteger(L, abilities->elementDamage); } else { lua_pushnil(L); @@ -14105,8 +13777,7 @@ int LuaScriptInterface::luaItemTypeGetElementDamage(lua_State* L) int LuaScriptInterface::luaItemTypeGetTransformEquipId(lua_State* L) { // itemType:getTransformEquipId() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->transformEquipTo); } else { lua_pushnil(L); @@ -14117,8 +13788,7 @@ int LuaScriptInterface::luaItemTypeGetTransformEquipId(lua_State* L) int LuaScriptInterface::luaItemTypeGetTransformDeEquipId(lua_State* L) { // itemType:getTransformDeEquipId() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->transformDeEquipTo); } else { lua_pushnil(L); @@ -14129,8 +13799,7 @@ int LuaScriptInterface::luaItemTypeGetTransformDeEquipId(lua_State* L) int LuaScriptInterface::luaItemTypeGetDestroyId(lua_State* L) { // itemType:getDestroyId() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->destroyTo); } else { lua_pushnil(L); @@ -14141,8 +13810,7 @@ int LuaScriptInterface::luaItemTypeGetDestroyId(lua_State* L) int LuaScriptInterface::luaItemTypeGetDecayId(lua_State* L) { // itemType:getDecayId() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->decayTo); } else { lua_pushnil(L); @@ -14153,8 +13821,7 @@ int LuaScriptInterface::luaItemTypeGetDecayId(lua_State* L) int LuaScriptInterface::luaItemTypeGetRequiredLevel(lua_State* L) { // itemType:getRequiredLevel() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { lua_pushinteger(L, itemType->minReqLevel); } else { lua_pushnil(L); @@ -14165,8 +13832,7 @@ int LuaScriptInterface::luaItemTypeGetRequiredLevel(lua_State* L) int LuaScriptInterface::luaItemTypeHasSubType(lua_State* L) { // itemType:hasSubType() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->hasSubType()); } else { lua_pushnil(L); @@ -14177,8 +13843,7 @@ int LuaScriptInterface::luaItemTypeHasSubType(lua_State* L) int LuaScriptInterface::luaItemTypeIsStoreItem(lua_State* L) { // itemType:isStoreItem() - const ItemType* itemType = getUserdata(L, 1); - if (itemType) { + if (const auto itemType = getUserdata(L, 1)) { pushBoolean(L, itemType->storeItem); } else { lua_pushnil(L); @@ -14197,8 +13862,7 @@ int LuaScriptInterface::luaCombatCreate(lua_State* L) int LuaScriptInterface::luaCombatDelete(lua_State* L) { - Combat_ptr& combat = getSharedPtr(L, 1); - if (combat) { + if (Combat_ptr& combat = getSharedPtr(L, 1)) { combat.reset(); } return 0; @@ -14389,12 +14053,12 @@ int LuaScriptInterface::luaCombatExecute(lua_State* L) } } - Creature* creature = getCreature(L, 2); + auto creature = getCreature(L, 2); const LuaVariant& variant = getVariant(L, 3); switch (variant.type()) { case VARIANT_NUMBER: { - Creature* target = g_game.getCreatureByID(variant.getNumber()); + const auto target = g_game.getCreatureByID(variant.getNumber()); if (!target) { pushBoolean(L, false); return 1; @@ -14424,7 +14088,7 @@ int LuaScriptInterface::luaCombatExecute(lua_State* L) } case VARIANT_STRING: { - Player* target = g_game.getPlayerByName(variant.getString()); + const auto target = g_game.getPlayerByName(variant.getString()); if (!target) { pushBoolean(L, false); return 1; @@ -16255,13 +15919,13 @@ int LuaScriptInterface::luaMonsterSpellSetOutfit(lua_State* L) int32_t LuaScriptInterface::luaPartyCreate(lua_State* L) { // Party(userdata) - Player* player = getUserdata(L, 2); + auto player = getSharedPtr(L, 2); if (!player) { lua_pushnil(L); return 1; } - Party* party = player->getParty(); + auto party = player->getParty(); if (!party) { party = new Party(player); g_game.updatePlayerShield(player); @@ -16298,9 +15962,8 @@ int LuaScriptInterface::luaPartyGetLeader(lua_State* L) return 1; } - Player* leader = party->getLeader(); - if (leader) { - pushUserdata(L, leader); + if (const auto leader = party->getLeader()) { + pushSharedPtr(L, leader); setMetatable(L, -1, "Player"); } else { lua_pushnil(L); @@ -16311,8 +15974,8 @@ int LuaScriptInterface::luaPartyGetLeader(lua_State* L) int LuaScriptInterface::luaPartySetLeader(lua_State* L) { // party:setLeader(player) - Player* player = getPlayer(L, 2); - Party* party = getUserdata(L, 1); + const auto player = getPlayer(L, 2); + const auto party = getUserdata(L, 1); if (party && player) { pushBoolean(L, party->passPartyLeadership(player, true)); } else { @@ -16332,8 +15995,8 @@ int LuaScriptInterface::luaPartyGetMembers(lua_State* L) int index = 0; lua_createtable(L, party->getMemberCount(), 0); - for (Player* player : party->getMembers()) { - pushUserdata(L, player); + for (const auto player : party->getMembers()) { + pushSharedPtr(L, player); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); } @@ -16355,13 +16018,12 @@ int LuaScriptInterface::luaPartyGetMemberCount(lua_State* L) int LuaScriptInterface::luaPartyGetInvitees(lua_State* L) { // party:getInvitees() - Party* party = getUserdata(L, 1); - if (party) { + if (const auto party = getUserdata(L, 1)) { lua_createtable(L, party->getInvitationCount(), 0); int index = 0; - for (Player* player : party->getInvitees()) { - pushUserdata(L, player); + for (const auto player : party->getInvitees()) { + pushSharedPtr(L, player); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); } @@ -16374,7 +16036,7 @@ int LuaScriptInterface::luaPartyGetInvitees(lua_State* L) int LuaScriptInterface::luaPartyGetInviteeCount(lua_State* L) { // party:getInviteeCount() - Party* party = getUserdata(L, 1); + const auto party = getUserdata(L, 1); if (party) { lua_pushinteger(L, party->getInvitationCount()); } else { @@ -16386,10 +16048,10 @@ int LuaScriptInterface::luaPartyGetInviteeCount(lua_State* L) int LuaScriptInterface::luaPartyAddInvite(lua_State* L) { // party:addInvite(player) - Player* player = getPlayer(L, 2); - Party* party = getUserdata(L, 1); + auto player = getPlayer(L, 2); + const auto party = getUserdata(L, 1); if (party && player) { - pushBoolean(L, party->invitePlayer(*player)); + pushBoolean(L, party->invitePlayer(player)); } else { lua_pushnil(L); } @@ -16399,10 +16061,10 @@ int LuaScriptInterface::luaPartyAddInvite(lua_State* L) int LuaScriptInterface::luaPartyRemoveInvite(lua_State* L) { // party:removeInvite(player) - Player* player = getPlayer(L, 2); - Party* party = getUserdata(L, 1); + auto player = getPlayer(L, 2); + const auto party = getUserdata(L, 1); if (party && player) { - pushBoolean(L, party->removeInvite(*player)); + pushBoolean(L, party->removeInvite(player)); } else { lua_pushnil(L); } @@ -16412,10 +16074,10 @@ int LuaScriptInterface::luaPartyRemoveInvite(lua_State* L) int LuaScriptInterface::luaPartyAddMember(lua_State* L) { // party:addMember(player) - Player* player = getPlayer(L, 2); - Party* party = getUserdata(L, 1); + auto player = getPlayer(L, 2); + const auto party = getUserdata(L, 1); if (party && player) { - pushBoolean(L, party->joinParty(*player)); + pushBoolean(L, party->joinParty(player)); } else { lua_pushnil(L); } @@ -16425,8 +16087,8 @@ int LuaScriptInterface::luaPartyAddMember(lua_State* L) int LuaScriptInterface::luaPartyRemoveMember(lua_State* L) { // party:removeMember(player) - Player* player = getPlayer(L, 2); - Party* party = getUserdata(L, 1); + const auto player = getPlayer(L, 2); + const auto party = getUserdata(L, 1); if (party && player) { pushBoolean(L, party->leaveParty(player)); } else { @@ -16438,8 +16100,7 @@ int LuaScriptInterface::luaPartyRemoveMember(lua_State* L) int LuaScriptInterface::luaPartyIsSharedExperienceActive(lua_State* L) { // party:isSharedExperienceActive() - Party* party = getUserdata(L, 1); - if (party) { + if (const auto party = getUserdata(L, 1)) { pushBoolean(L, party->isSharedExperienceActive()); } else { lua_pushnil(L); @@ -16450,8 +16111,7 @@ int LuaScriptInterface::luaPartyIsSharedExperienceActive(lua_State* L) int LuaScriptInterface::luaPartyIsSharedExperienceEnabled(lua_State* L) { // party:isSharedExperienceEnabled() - Party* party = getUserdata(L, 1); - if (party) { + if (const auto party = getUserdata(L, 1)) { pushBoolean(L, party->isSharedExperienceEnabled()); } else { lua_pushnil(L); @@ -16463,8 +16123,7 @@ int LuaScriptInterface::luaPartyShareExperience(lua_State* L) { // party:shareExperience(experience) uint64_t experience = getNumber(L, 2); - Party* party = getUserdata(L, 1); - if (party) { + if (const auto party = getUserdata(L, 1)) { party->shareExperience(experience); pushBoolean(L, true); } else { @@ -16476,9 +16135,8 @@ int LuaScriptInterface::luaPartyShareExperience(lua_State* L) int LuaScriptInterface::luaPartySetSharedExperience(lua_State* L) { // party:setSharedExperience(active) - bool active = getBoolean(L, 2); - Party* party = getUserdata(L, 1); - if (party) { + const bool active = getBoolean(L, 2); + if (const auto party = getUserdata(L, 1)) { pushBoolean(L, party->setSharedExperience(party->getLeader(), active)); } else { lua_pushnil(L); diff --git a/src/luascript.h b/src/luascript.h index 37117dad..0dc7c677 100644 --- a/src/luascript.h +++ b/src/luascript.h @@ -94,6 +94,56 @@ class LuaScriptInterface; class Cylinder; class Game; +using PlayerPtr = std::shared_ptr; +using PlayerConstPtr = std::shared_ptr; + +using MonsterPtr = std::shared_ptr; +using MonsterConstPtr = std::shared_ptr; + +using NpcPtr = std::shared_ptr; +using NpcConstPtr = std::shared_ptr; +class Depot; +using DepotPtr = std::shared_ptr; +using DepotConstPtr = std::shared_ptr; +class Teleport; +using TeleportPtr = std::shared_ptr; +using TeleportConstPtr = std::shared_ptr; +class TrashHolder; +using TrashHolderPtr = std::shared_ptr; +using TrashHolderConstPtr = std::shared_ptr; +class Mailbox; +using MailboxPtr = std::shared_ptr; +using MailboxConstPtr = std::shared_ptr; +class Door; +using DoorPtr = std::shared_ptr; +using DoorConstPtr = std::shared_ptr; +class MagicField; +using MagicFieldPtr = std::shared_ptr; +using MagicFieldConstPtr = std::shared_ptr; +class BedItem; +using BedItemPtr = std::shared_ptr; +using BedItemConstPtr = std::shared_ptr; + +using ThingPtr = std::shared_ptr; +using ThingConstPtr = std::shared_ptr; +class Tile; +using TilePtr = std::shared_ptr; +using TileConstPtr = std::shared_ptr; +using TileWeakPtr = std::weak_ptr; + +using CylinderPtr = std::shared_ptr; +using CylinderConstPtr = std::shared_ptr; +using CylinderWeakPtr = std::weak_ptr; + +using ItemPtr = std::shared_ptr; +using ItemConstPtr = std::shared_ptr; +class Container; +using ContainerPtr = std::shared_ptr; +using ContainerConstPtr = std::shared_ptr; +class Creature; +using CreaturePtr = std::shared_ptr; +using CreatureConstPtr = std::shared_ptr; + struct LootBlock; class ScriptEnvironment @@ -112,12 +162,14 @@ class ScriptEnvironment this->scriptId = scriptId; interface = scriptInterface; } + bool setCallbackId(int32_t callbackId, LuaScriptInterface* scriptInterface); int32_t getScriptId() const { return scriptId; } - LuaScriptInterface* getScriptInterface() { + + LuaScriptInterface* getScriptInterface() const { return interface; } @@ -127,25 +179,26 @@ class ScriptEnvironment 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(const ItemPtr& item); + static void removeTempItem(const ItemPtr& item); + uint32_t addThing(const ThingPtr& thing); + void insertItem(uint32_t uid, const ItemPtr& item); static DBResult_ptr getResultByID(uint32_t id); - static uint32_t addResult(DBResult_ptr res); + static uint32_t addResult(const DBResult_ptr& res); static bool removeResult(uint32_t id); - void setNpc(Npc* npc) { + void setNpc(const NpcPtr& npc) { curNpc = npc; } - Npc* getNpc() const { + + NpcPtr getNpc() const { return curNpc; } - Thing* getThingByUID(uint32_t uid); - Item* getItemByUID(uint32_t uid); - Container* getContainerByUID(uint32_t uid); + ThingPtr getThingByUID(uint32_t uid); + ItemPtr getItemByUID(uint32_t uid); + ContainerPtr getContainerByUID(uint32_t uid); void removeItemByUID(uint32_t uid); private: @@ -156,13 +209,13 @@ class ScriptEnvironment LuaScriptInterface* interface; //for npc scripts - Npc* curNpc = nullptr; + NpcPtr curNpc = nullptr; //temporary item list - static std::multimap tempItems; + static std::multimap tempItems; //local item map - std::unordered_map localMap; + std::unordered_map localMap; uint32_t lastUID = std::numeric_limits::max(); //script file id @@ -206,7 +259,7 @@ class LuaScriptInterface virtual bool initState(); bool reInitState(); - int32_t loadFile(const std::string& file, Npc* npc = nullptr); + int32_t loadFile(const std::string& file, std::optional npc = std::nullopt); const std::string& getFileById(int32_t scriptId); int32_t getEvent(std::string_view eventName); @@ -232,6 +285,7 @@ class LuaScriptInterface const std::string& getInterfaceName() const { return interfaceName; } + const std::string& getLastLuaError() const { return lastLuaError; } @@ -240,18 +294,18 @@ class LuaScriptInterface return luaState; } - bool pushFunction(int32_t functionId); + bool pushFunction(int32_t functionId) const; static int luaErrorHandler(lua_State* L); - bool callFunction(int params); - void callVoidFunction(int params); + bool callFunction(int params) const; + void callVoidFunction(int params) const; //push/pop common structures - static void pushThing(lua_State* L, Thing* thing); + static void pushThing(lua_State* L, const ThingPtr& thing); static void pushVariant(lua_State* L, const LuaVariant& var); static void pushString(lua_State* L, std::string_view value); static void pushCallback(lua_State* L, int32_t callback); - static void pushCylinder(lua_State* L, Cylinder* cylinder); + static void pushCylinder(lua_State* L, const CylinderPtr& cylinder); static std::string popString(lua_State* L); static int32_t popCallback(lua_State* L); @@ -275,8 +329,8 @@ class LuaScriptInterface 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); + static void setItemMetatable(lua_State* L, int32_t index, const ItemConstPtr& item); + static void setCreatureMetatable(lua_State* L, int32_t index, const CreatureConstPtr& creature); // Get template @@ -319,6 +373,7 @@ class LuaScriptInterface } return getNumber(L, arg); } + template static T* getUserdata(lua_State* L, int32_t arg) { @@ -328,11 +383,13 @@ class LuaScriptInterface } return *userdata; } + template static T** getRawUserdata(lua_State* L, int32_t arg) { return static_cast(lua_touserdata(L, arg)); } + template static std::shared_ptr& getSharedPtr(lua_State* L, int32_t arg) { @@ -343,6 +400,7 @@ class LuaScriptInterface { return lua_toboolean(L, arg) != 0; } + static bool getBoolean(lua_State* L, int32_t arg, bool defaultValue) { const auto parameters = lua_gettop(L); @@ -360,9 +418,9 @@ class LuaScriptInterface static InstantSpell* getInstantSpell(lua_State* L, int32_t arg); - static Thing* getThing(lua_State* L, int32_t arg); - static Creature* getCreature(lua_State* L, int32_t arg); - static Player* getPlayer(lua_State* L, int32_t arg); + static ThingPtr getThing(lua_State* L, int32_t arg); + static CreaturePtr getCreature(lua_State* L, int32_t arg); + static PlayerPtr getPlayer(lua_State* L, int32_t arg); template static T getField(lua_State* L, int32_t arg, const std::string& key) @@ -387,22 +445,27 @@ class LuaScriptInterface { return lua_type(L, arg) == LUA_TNUMBER; } + static bool isString(lua_State* L, int32_t arg) { return lua_isstring(L, arg) != 0; } + static bool isBoolean(lua_State* L, int32_t arg) { return lua_isboolean(L, arg); } + static bool isTable(lua_State* L, int32_t arg) { return lua_istable(L, arg); } + static bool isFunction(lua_State* L, int32_t arg) { return lua_isfunction(L, arg); } + static bool isUserdata(lua_State* L, int32_t arg) { return lua_isuserdata(L, arg) != 0; @@ -459,7 +522,7 @@ class LuaScriptInterface void registerFunctions(); - void registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func); + void registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func) const; static std::string getErrorDesc(ErrorCode_t code); @@ -472,13 +535,13 @@ class LuaScriptInterface std::map cacheFiles; private: - void registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction = nullptr); - void registerTable(const std::string& tableName); - void registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func); - void registerGlobalMethod(const std::string& functionName, lua_CFunction func); - void registerVariable(const std::string& tableName, const std::string& name, lua_Number value); - void registerGlobalVariable(const std::string& name, lua_Number value); - void registerGlobalBoolean(const std::string& name, bool value); + void registerClass(const std::string& className, const std::string& baseClass, lua_CFunction newFunction = nullptr) const; + void registerTable(const std::string& tableName) const; + void registerMetaMethod(const std::string& className, const std::string& methodName, lua_CFunction func) const; + void registerGlobalMethod(const std::string& functionName, lua_CFunction func) const; + void registerVariable(const std::string& tableName, const std::string& name, lua_Number value) const; + void registerGlobalVariable(const std::string& name, lua_Number value) const; + void registerGlobalBoolean(const std::string& name, bool value) const; static std::string getStackTrace(lua_State* L, const std::string& error_desc); @@ -1714,7 +1777,7 @@ class LuaEnvironment : public LuaScriptInterface { public: LuaEnvironment(); - ~LuaEnvironment(); + ~LuaEnvironment() override; // non-copyable LuaEnvironment(const LuaEnvironment&) = delete; diff --git a/src/mailbox.cpp b/src/mailbox.cpp index a30ab762..c1bb65e1 100644 --- a/src/mailbox.cpp +++ b/src/mailbox.cpp @@ -9,70 +9,69 @@ extern Game g_game; -ReturnValue Mailbox::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t, Creature*) const +ReturnValue Mailbox::queryAdd(int32_t, const ThingPtr& thing, uint32_t, uint32_t, CreaturePtr) { - const Item* item = thing.getItem(); - if (item && Mailbox::canSend(item)) { + if (const auto& item = thing->getItem(); item && Mailbox::canSend(item)) { return RETURNVALUE_NOERROR; } 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 ThingPtr&, const uint32_t count, uint32_t& maxQueryCount, uint32_t) { maxQueryCount = std::max(1, count); return RETURNVALUE_NOERROR; } -ReturnValue Mailbox::queryRemove(const Thing&, uint32_t, uint32_t, Creature* /*= nullptr */) const +ReturnValue Mailbox::queryRemove(const ThingPtr&, uint32_t, uint32_t, CreaturePtr /*= nullptr */) { return RETURNVALUE_NOTPOSSIBLE; } -Cylinder* Mailbox::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) +CylinderPtr Mailbox::queryDestination(int32_t&, const ThingPtr&, ItemPtr*, uint32_t&) { - return this; + return CylinderPtr(this); } -void Mailbox::addThing(Thing* thing) +void Mailbox::addThing(ThingPtr thing) { return addThing(0, thing); } -void Mailbox::addThing(int32_t, Thing* thing) +void Mailbox::addThing(int32_t, ThingPtr thing) { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (item && Mailbox::canSend(item)) { sendItem(item); } } -void Mailbox::updateThing(Thing*, uint16_t, uint32_t) +void Mailbox::updateThing(ThingPtr, uint16_t, uint32_t) { // } -void Mailbox::replaceThing(uint32_t, Thing*) +void Mailbox::replaceThing(uint32_t, ThingPtr) { // } -void Mailbox::removeThing(Thing*, uint32_t) +void Mailbox::removeThing(ThingPtr, uint32_t) { // } -void Mailbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void Mailbox::postAddNotification(ThingPtr thing, CylinderPtr 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(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } -bool Mailbox::sendItem(Item* item) const +bool Mailbox::sendItem(const ItemPtr& item) const { std::string receiver; if (!getReceiver(item, receiver)) { @@ -84,35 +83,36 @@ bool Mailbox::sendItem(Item* item) const return false; } - Player* player = g_game.getPlayerByName(receiver); - if (player) { - if (g_game.internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER, + if (const auto player = g_game.getPlayerByName(receiver)) { + CylinderPtr newParent = CylinderPtr(item->getParent()); + CylinderPtr inbox = CylinderPtr(player->getInbox()); + if (g_game.internalMoveItem(newParent, inbox, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { g_game.transformItem(item, item->getID() + 1); player->onReceiveMail(); return true; } } else { - Player tmpPlayer(nullptr); - if (!IOLoginData::loadPlayerByName(&tmpPlayer, receiver)) { + PlayerPtr tmpPlayer(nullptr); + if (!IOLoginData::loadPlayerByName(tmpPlayer, receiver)) { return false; } - - if (g_game.internalMoveItem(item->getParent(), tmpPlayer.getInbox(), INDEX_WHEREEVER, + CylinderPtr newParent = CylinderPtr(item->getParent()); + CylinderPtr inbox = CylinderPtr(tmpPlayer->getInbox()); + if (g_game.internalMoveItem(newParent, inbox, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { g_game.transformItem(item, item->getID() + 1); - IOLoginData::savePlayer(&tmpPlayer); + IOLoginData::savePlayer(tmpPlayer); return true; } } return false; } -bool Mailbox::getReceiver(Item* item, std::string& name) const +bool Mailbox::getReceiver(const ItemPtr& item, std::string& name) const { - const Container* container = item->getContainer(); - if (container) { - for (Item* containerItem : container->getItemList()) { + if (const auto& container = item->getContainer()) { + for (const auto& containerItem : container->getItemList()) { if (containerItem->getID() == ITEM_LABEL && getReceiver(containerItem, name)) { return true; } @@ -130,7 +130,7 @@ bool Mailbox::getReceiver(Item* item, std::string& name) const return true; } -bool Mailbox::canSend(const Item* item) +bool Mailbox::canSend(const ItemConstPtr& item) { return item->getID() == ITEM_PARCEL || item->getID() == ITEM_LETTER; } diff --git a/src/mailbox.h b/src/mailbox.h index 0bea811d..e5cb01c3 100644 --- a/src/mailbox.h +++ b/src/mailbox.h @@ -6,45 +6,45 @@ #include "item.h" #include "cylinder.h" -#include "const.h" class Mailbox final : public Item, public Cylinder { public: - explicit Mailbox(uint16_t itemId) : Item(itemId) {} + explicit Mailbox(const uint16_t itemId) : Item(itemId) {} - Mailbox* getMailbox() override { - return this; + MailboxPtr getMailbox() override { + return dynamic_shared_this(); } - const Mailbox* getMailbox() const override { - return this; + + MailboxConstPtr getMailbox() const override { + return dynamic_shared_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; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) override; + ReturnValue queryMaxCount(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t& maxQueryCount, uint32_t flags) override; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, + uint32_t& flags) override; // another optional ref wrapper - void addThing(Thing* thing) override; - void addThing(int32_t index, Thing* thing) override; + void addThing(ThingPtr thing) override; + void addThing(int32_t index, ThingPtr thing) override; - void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, Thing* thing) override; + void updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, ThingPtr thing) override; - void removeThing(Thing* thing, uint32_t count) override; + void removeThing(ThingPtr thing, uint32_t count) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; private: - bool getReceiver(Item* item, std::string& name) const; - bool sendItem(Item* item) const; + bool getReceiver(const ItemPtr& item, std::string& name) const; + bool sendItem(const ItemPtr& item) const; - static bool canSend(const Item* item); + static bool canSend(const ItemConstPtr& item); }; #endif diff --git a/src/map.cpp b/src/map.cpp index 1f3b56f1..270f34e0 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -59,25 +59,25 @@ bool Map::save() return saved; } -Tile* Map::getTile(uint16_t x, uint16_t y, uint8_t z) const +TilePtr Map::getTile(const uint16_t x, const uint16_t y, const uint8_t z) { if (z >= MAP_MAX_LAYERS) { return nullptr; } - const QTreeLeafNode* leaf = QTreeNode::getLeafStatic(&root, x, y); + auto leaf = QTreeNode::getLeafStatic< QTreeLeafNode*, QTreeNode*>(&root, x, y); if (!leaf) { return nullptr; } - const Floor* floor = leaf->getFloor(z); + auto floor = leaf->getFloor(z); if (!floor) { return nullptr; } 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(const uint16_t x, const uint16_t y, const uint8_t z, TilePtr& newTile) { if (z >= MAP_MAX_LAYERS) { std::cout << "ERROR: Attempt to set tile on invalid coordinate " << Position(x, y, z) << "!" << std::endl; @@ -85,80 +85,71 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) } QTreeLeafNode::newLeaf = false; - QTreeLeafNode* leaf = root.createLeaf(x, y, 15); + const auto& leaf = root.createLeaf(x, y, 15); if (QTreeLeafNode::newLeaf) { //update north - QTreeLeafNode* northLeaf = root.getLeaf(x, y - FLOOR_SIZE); - if (northLeaf) { + if (const auto& northLeaf = root.getLeaf(x, y - FLOOR_SIZE)) { northLeaf->leafS = leaf; } //update west leaf - QTreeLeafNode* westLeaf = root.getLeaf(x - FLOOR_SIZE, y); - if (westLeaf) { + if (const auto& westLeaf = root.getLeaf(x - FLOOR_SIZE, y)) { westLeaf->leafE = leaf; } //update south - QTreeLeafNode* southLeaf = root.getLeaf(x, y + FLOOR_SIZE); - if (southLeaf) { + if (const auto& southLeaf = root.getLeaf(x, y + FLOOR_SIZE)) { leaf->leafS = southLeaf; } //update east - QTreeLeafNode* eastLeaf = root.getLeaf(x + FLOOR_SIZE, y); - if (eastLeaf) { + if (const auto& eastLeaf = root.getLeaf(x + FLOOR_SIZE, y)) { leaf->leafE = eastLeaf; } } - Floor* floor = leaf->createFloor(z); - uint32_t offsetX = x & FLOOR_MASK; - uint32_t offsetY = y & FLOOR_MASK; + const auto& floor = leaf->createFloor(z); + const uint32_t offsetX = x & FLOOR_MASK; + const uint32_t offsetY = y & FLOOR_MASK; - Tile*& tile = floor->tiles[offsetX][offsetY]; - if (tile) { - TileItemVector* items = newTile->getItemList(); - if (items) { + if (auto& tile = floor->tiles[offsetX][offsetY]) { + if (const auto& items = newTile->getItemList()) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { tile->addThing(*it); } items->clear(); } - Item* ground = newTile->getGround(); - if (ground) { + if (const auto& ground = newTile->getGround()) { tile->addThing(ground); newTile->setGround(nullptr); } - delete newTile; } else { tile = newTile; } } -void Map::removeTile(uint16_t x, uint16_t y, uint8_t z) +void Map::removeTile(const uint16_t x, const uint16_t y, const uint8_t z) const { if (z >= MAP_MAX_LAYERS) { return; } - const QTreeLeafNode* leaf = QTreeNode::getLeafStatic(&root, x, y); + const auto& leaf = QTreeNode::getLeafStatic(&root, x, y); if (!leaf) { return; } - const Floor* floor = leaf->getFloor(z); + const auto& floor = leaf->getFloor(z); if (!floor) { return; } - Tile* tile = floor->tiles[x & FLOOR_MASK][y & FLOOR_MASK]; - if (tile) { - if (const CreatureVector* creatures = tile->getCreatures()) { + if (const auto& tile = floor->tiles[x & FLOOR_MASK][y & FLOOR_MASK]) { + if (const auto& creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { - if (Player* player = (*creatures)[i]->getPlayer()) { + if (const auto& player = (*creatures)[i]->getPlayer()) { g_game.internalTeleport(player, player->getTown()->getTemplePosition(), false, FLAG_NOLIMIT); } else { g_game.removeCreature((*creatures)[i]); @@ -166,29 +157,28 @@ void Map::removeTile(uint16_t x, uint16_t y, uint8_t z) } } - if (TileItemVector* items = tile->getItemList()) { + if (const auto& items = tile->getItemList()) { for (auto it = items->begin(), end = items->end(); it != end; ++it) { g_game.internalRemoveItem(*it); } } - Item* ground = tile->getGround(); - if (ground) { + if (const auto& ground = tile->getGround()) { g_game.internalRemoveItem(ground); tile->setGround(nullptr); } } } -bool Map::placeCreature(const Position& centerPos, Creature* creature, bool extendedPos/* = false*/, bool forceLogin/* = false*/) +bool Map::placeCreature(const Position& centerPos, CreaturePtr creature, bool extendedPos/* = false*/, bool forceLogin/* = false*/) { bool foundTile; bool placeInPZ; - Tile* tile = getTile(centerPos.x, centerPos.y, centerPos.z); + auto tile = getTile(centerPos.x, centerPos.y, centerPos.z); if (tile) { placeInPZ = tile->hasFlag(TILESTATE_PROTECTIONZONE); - ReturnValue ret = tile->queryAdd(*creature, FLAG_IGNOREBLOCKITEM); + const ReturnValue ret = tile->queryAdd(creature, FLAG_IGNOREBLOCKITEM); foundTile = forceLogin || ret == RETURNVALUE_NOERROR || ret == RETURNVALUE_PLAYERISNOTINVITED; } else { placeInPZ = false; @@ -216,7 +206,7 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte std::shuffle(relList.begin(), relList.begin() + 4, getRandomGenerator()); std::shuffle(relList.begin() + 4, relList.end(), getRandomGenerator()); } else { - std::shuffle(relList.begin(), relList.end(), getRandomGenerator()); + std::ranges::shuffle(relList, getRandomGenerator()); } for (const auto& it : relList) { @@ -227,7 +217,7 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte continue; } - if (tile->queryAdd(*creature, 0) == RETURNVALUE_NOERROR) { + if (tile->queryAdd(creature, 0) == RETURNVALUE_NOERROR) { if (!extendedPos || isSightClear(centerPos, tryPos, false)) { foundTile = true; break; @@ -242,9 +232,8 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte int32_t index = 0; uint32_t flags = 0; - Item* toItem = nullptr; - - Cylinder* toCylinder = tile->queryDestination(index, *creature, &toItem, flags); + ItemPtr toItem = nullptr; + auto toCylinder = tile->queryDestination(index, creature, &toItem, flags); toCylinder->internalAddThing(creature); const Position& dest = toCylinder->getPosition(); @@ -252,17 +241,17 @@ bool Map::placeCreature(const Position& centerPos, Creature* creature, bool exte return true; } -void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = false*/) +void Map::moveCreature(CreaturePtr& creature, const TilePtr& newTile, bool forceTeleport/* = false*/) { - Tile& oldTile = *creature.getTile(); + const auto& oldTile = creature->getTile(); // If the tile does not have the creature it means that the creature is ready for elimination, we skip the move. - if (!oldTile.hasCreature(&creature)) { + if (!oldTile->hasCreature(creature)) { return; } - Position oldPos = oldTile.getPosition(); - Position newPos = newTile.getPosition(); + Position oldPos = oldTile->getPosition(); + Position newPos = newTile->getPosition(); - bool teleport = forceTeleport || !newTile.getGround() || !Position::areInRange<1, 1, 0>(oldPos, newPos); + bool teleport = forceTeleport || !newTile->getGround() || !Position::areInRange<1, 1, 0>(oldPos, newPos); SpectatorVec spectators, newPosSpectators; getSpectators(spectators, oldPos, true); @@ -270,10 +259,10 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = spectators.addSpectators(newPosSpectators); std::vector oldStackPosVector; - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { - if (tmpPlayer->canSeeCreature(&creature)) { - oldStackPosVector.push_back(oldTile.getClientIndexOfCreature(tmpPlayer, &creature)); + for (const auto& spectator : spectators) { + if (const auto& tmpPlayer = spectator->getPlayer()) { + if (tmpPlayer->canSeeCreature(creature)) { + oldStackPosVector.push_back(oldTile->getClientIndexOfCreature(tmpPlayer, creature)); } else { oldStackPosVector.push_back(-1); } @@ -281,98 +270,96 @@ void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = } //remove the creature - oldTile.removeThing(&creature, 0); + oldTile->removeThing(creature, 0); - QTreeLeafNode* leaf = getQTNode(oldPos.x, oldPos.y); - QTreeLeafNode* new_leaf = getQTNode(newPos.x, newPos.y); + const auto& leaf = getQTNode(oldPos.x, oldPos.y); + const auto& new_leaf = getQTNode(newPos.x, newPos.y); // Switch the node ownership if (leaf != new_leaf) { - leaf->removeCreature(&creature); - new_leaf->addCreature(&creature); + leaf->removeCreature(creature); + new_leaf->addCreature(creature); } //add the creature - newTile.addThing(&creature); + newTile->addThing(creature); if (!teleport) { if (oldPos.y > newPos.y) { - creature.setDirection(DIRECTION_NORTH); + creature->setDirection(DIRECTION_NORTH); } else if (oldPos.y < newPos.y) { - creature.setDirection(DIRECTION_SOUTH); + creature->setDirection(DIRECTION_SOUTH); } if (oldPos.x < newPos.x) { - creature.setDirection(DIRECTION_EAST); + creature->setDirection(DIRECTION_EAST); } else if (oldPos.x > newPos.x) { - creature.setDirection(DIRECTION_WEST); + creature->setDirection(DIRECTION_WEST); } } //send to client size_t i = 0; - for (Creature* spectator : spectators) { - if (Player* tmpPlayer = spectator->getPlayer()) { + for (const auto& spectator : spectators) { + if (const auto& tmpPlayer = spectator->getPlayer()) { //Use the correct stackpos - int32_t stackpos = oldStackPosVector[i++]; - if (stackpos != -1) { - tmpPlayer->sendCreatureMove(&creature, newPos, newTile.getClientIndexOfCreature(tmpPlayer, &creature), oldPos, stackpos, teleport); + if (const int32_t& stackpos = oldStackPosVector[i++]; stackpos != -1) { + tmpPlayer->sendCreatureMove(creature, newPos, newTile->getClientIndexOfCreature(tmpPlayer, creature), oldPos, stackpos, teleport); } } } //event method - for (Creature* spectator : spectators) { - spectator->onCreatureMove(&creature, &newTile, newPos, &oldTile, oldPos, teleport); + for (const auto& spectator : spectators) { + spectator->onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); } - oldTile.postRemoveNotification(&creature, &newTile, 0); - newTile.postAddNotification(&creature, &oldTile, 0); + oldTile->postRemoveNotification(creature, newTile, 0); + newTile->postAddNotification(creature, oldTile, 0); } -void Map::getSpectatorsInternal(SpectatorVec& 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(SpectatorVec& spectators, const Position& centerPos, const int32_t minRangeX, const int32_t maxRangeX, const int32_t minRangeY, const int32_t maxRangeY, const int32_t minRangeZ, const int32_t maxRangeZ, const bool onlyPlayers) const { - auto min_y = centerPos.y + minRangeY; - auto min_x = centerPos.x + minRangeX; - auto max_y = centerPos.y + maxRangeY; - auto max_x = centerPos.x + maxRangeX; + const auto min_y = centerPos.y + minRangeY; + const auto min_x = centerPos.x + minRangeX; + const auto max_y = centerPos.y + maxRangeY; + const auto max_x = centerPos.x + maxRangeX; - int32_t minoffset = centerPos.getZ() - maxRangeZ; - uint16_t x1 = std::min(0xFFFF, std::max(0, (min_x + minoffset))); - uint16_t y1 = std::min(0xFFFF, std::max(0, (min_y + minoffset))); + const int32_t minoffset = centerPos.getZ() - maxRangeZ; + const uint16_t x1 = std::min(0xFFFF, std::max(0, (min_x + minoffset))); + const uint16_t y1 = std::min(0xFFFF, std::max(0, (min_y + minoffset))); - int32_t maxoffset = centerPos.getZ() - minRangeZ; - uint16_t x2 = std::min(0xFFFF, std::max(0, (max_x + maxoffset))); - uint16_t y2 = std::min(0xFFFF, std::max(0, (max_y + maxoffset))); + const int32_t maxoffset = centerPos.getZ() - minRangeZ; + const uint16_t x2 = std::min(0xFFFF, std::max(0, (max_x + maxoffset))); + const uint16_t y2 = std::min(0xFFFF, std::max(0, (max_y + maxoffset))); - std::array cache_values{ + const std::array cache_values{ min_y + minoffset, max_y + maxoffset, min_x + minoffset, max_x + maxoffset }; - int32_t startx1 = x1 - (x1 % FLOOR_SIZE); - int32_t starty1 = y1 - (y1 % FLOOR_SIZE); - int32_t endx2 = x2 - (x2 % FLOOR_SIZE); - int32_t endy2 = y2 - (y2 % FLOOR_SIZE); + const int32_t startx1 = x1 - (x1 % FLOOR_SIZE); + const int32_t starty1 = y1 - (y1 % FLOOR_SIZE); + const int32_t endx2 = x2 - (x2 % FLOOR_SIZE); + const int32_t endy2 = y2 - (y2 % FLOOR_SIZE); - const QTreeLeafNode* startLeaf = QTreeNode::getLeafStatic(&root, startx1, starty1); - const QTreeLeafNode* leafS = startLeaf; - const QTreeLeafNode* leafE; + const auto& startLeaf = QTreeNode::getLeafStatic(&root, startx1, starty1); + auto leafS = startLeaf; for (int_fast32_t ny = starty1; ny <= endy2; ny += FLOOR_SIZE) { - leafE = leafS; + const QTreeLeafNode* leafE = leafS; for (int_fast32_t nx = startx1; nx <= endx2; nx += FLOOR_SIZE) { if (leafE) { const auto& node_list = (onlyPlayers ? leafE->player_list : leafE->creature_list); - std::ranges::for_each(node_list, [&](Creature* creature) { + std::ranges::for_each(node_list, [&](const CreaturePtr& creature) { const Position& cpos = creature->getPosition(); if (minRangeZ > cpos.z || maxRangeZ < cpos.z) { return; } - int_fast16_t offsetZ = Position::getOffsetZ(centerPos, cpos); + const int_fast16_t offsetZ = Position::getOffsetZ(centerPos, cpos); if ((cache_values[0] + offsetZ) > cpos.y || (cache_values[1] + offsetZ) < cpos.y || (cache_values[2] + offsetZ) > cpos.x || (cache_values[3] + offsetZ) < cpos.x) { return; } @@ -393,7 +380,7 @@ void Map::getSpectatorsInternal(SpectatorVec& spectators, const Position& center } } -void Map::getSpectators(SpectatorVec& 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(SpectatorVec& spectators, const Position& centerPos, const 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; @@ -417,8 +404,7 @@ void Map::getSpectators(SpectatorVec& spectators, const Position& centerPos, boo chunkKey.multifloor = multifloor; chunkKey.onlyPlayers = onlyPlayers; - auto it = chunksSpectatorCache.find(chunkKey); - if (it != chunksSpectatorCache.end()) { + if (const auto it = chunksSpectatorCache.find(chunkKey); it != chunksSpectatorCache.end()) { if (!spectators.empty()) { spectators.addSpectators(it->second); } else { @@ -431,21 +417,19 @@ void Map::getSpectators(SpectatorVec& spectators, const Position& centerPos, boo if (minRangeX == -maxViewportX && maxRangeX == maxViewportX && minRangeY == -maxViewportY && maxRangeY == maxViewportY && multifloor) { if (onlyPlayers) { - auto it = playersSpectatorCache.find(centerPos); - if (it != playersSpectatorCache.end()) { + if (const auto it = playersSpectatorCache.find(centerPos); it != playersSpectatorCache.end()) { spectators.addSpectators(it->second); foundCache = true; } } if (!foundCache) { - auto it = spectatorCache.find(centerPos); - if (it != spectatorCache.end()) { + if (const auto it = spectatorCache.find(centerPos); it != spectatorCache.end()) { if (!onlyPlayers) { const SpectatorVec& cachedSpectators = it->second; spectators.addSpectators(cachedSpectators); } else { - for (Creature* spectator : it->second) { + for (const auto& spectator : it->second) { if (spectator->getPlayer()) { spectators.emplace_back(spectator); } @@ -500,8 +484,8 @@ void Map::clearPlayersSpectatorCache() playersSpectatorCache.clear(); } -bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/, bool sameFloor /*= false*/, - int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/) const +bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, const bool checkLineOfSight /*= true*/, const bool sameFloor /*= false*/, + const int32_t rangex /*= Map::maxClientViewportX*/, const int32_t rangey /*= Map::maxClientViewportY*/) { if (Position::getDistanceX(fromPos, toPos) > rangex || Position::getDistanceY(fromPos, toPos) > rangey) { return false; @@ -510,9 +494,9 @@ bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool return !checkLineOfSight || isSightClear(fromPos, toPos, sameFloor); } -bool Map::isTileClear(uint16_t x, uint16_t y, uint8_t z, bool blockFloor /*= false*/) const +bool Map::isTileClear(const uint16_t x, const uint16_t y, const uint8_t z, const bool blockFloor /*= false*/) { - const Tile* tile = getTile(x, y, z); + auto tile = getTile(x, y, z); if (!tile) { return true; } @@ -526,10 +510,10 @@ bool Map::isTileClear(uint16_t x, uint16_t y, uint8_t z, bool blockFloor /*= fal namespace { -bool checkSteepLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t z) +bool checkSteepLine(const uint16_t x0, const uint16_t y0, const uint16_t x1, const uint16_t y1, const uint8_t z) { - float dx = x1 - x0; - float slope = (dx == 0) ? 1 : (y1 - y0) / dx; + const float dx = x1 - x0; + const float slope = (dx == 0) ? 1 : (y1 - y0) / dx; float yi = y0 + slope; for (uint16_t x = x0 + 1; x < x1; ++x) { @@ -543,10 +527,10 @@ bool checkSteepLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t return true; } -bool checkSlightLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t z) +bool checkSlightLine(const uint16_t x0, const uint16_t y0, const uint16_t x1, const uint16_t y1, const uint8_t z) { - float dx = x1 - x0; - float slope = (dx == 0) ? 1 : (y1 - y0) / dx; + const float dx = x1 - x0; + const float slope = (dx == 0) ? 1 : (y1 - y0) / dx; float yi = y0 + slope; for (uint16_t x = x0 + 1; x < x1; ++x) { @@ -562,7 +546,7 @@ bool checkSlightLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t } -bool Map::checkSightLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t z) const +bool Map::checkSightLine(const uint16_t x0, const uint16_t y0, const uint16_t x1, const uint16_t y1, const uint8_t z) { if (x0 == x1 && y0 == y1) { return true; @@ -582,7 +566,7 @@ bool Map::checkSightLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uin return checkSlightLine(x0, y0, x1, y1, z); } -bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor /*= false*/) const +bool Map::isSightClear(const Position& fromPos, const Position& toPos, const bool sameFloor /*= false*/) { // Return immediately true if the destination is the same as the current location if (fromPos == toPos) { @@ -590,9 +574,9 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool same } // Cache differences to reduce function calls to position::getDistance - auto diffX = std::abs(fromPos.x - toPos.x); - auto diffY = std::abs(fromPos.y - toPos.y); - auto diffZ = std::abs(fromPos.z - toPos.z); + const auto diffX = std::abs(fromPos.x - toPos.x); + const auto diffY = std::abs(fromPos.y - toPos.y); + const auto diffZ = std::abs(fromPos.z - toPos.z); // Destination is on a different floor and sameFloor requirement is true if (sameFloor && diffZ != 0) { @@ -606,7 +590,7 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool same return true; } // Check horizontal line of sight - bool sightClear = checkSightLine(fromPos.x, fromPos.y, toPos.x, toPos.y, fromPos.z); + const bool sightClear = checkSightLine(fromPos.x, fromPos.y, toPos.x, toPos.y, fromPos.z); if (sightClear || sameFloor) { return sightClear; } @@ -640,7 +624,7 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool same } // Check a tile above us and the path to the target - uint8_t newZ = fromPos.z - 1; + const uint8_t newZ = fromPos.z - 1; return isTileClear(fromPos.x, fromPos.y, newZ, true) && checkSightLine(fromPos.x, fromPos.y, toPos.x, toPos.y, newZ); } @@ -656,9 +640,9 @@ bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool same return checkSightLine(fromPos.x, fromPos.y, toPos.x, toPos.y, fromPos.z); } -const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const +TilePtr Map::canWalkTo(CreaturePtr& creature, const Position& pos) { - int32_t walkCache = creature.getWalkCache(pos); + const int32_t& walkCache = creature->getWalkCache(pos); if (walkCache == 0) { return nullptr; } else if (walkCache == 1) { @@ -666,14 +650,14 @@ const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const } //used for non-cached tiles - Tile* tile = getTile(pos.x, pos.y, pos.z); - if (creature.getTile() != tile) { + const auto& tile = getTile(pos.x, pos.y, pos.z); + if (creature->getTile() != tile) { if (!tile) { return nullptr; } uint32_t flags = FLAG_PATHFINDING; - if (!creature.getPlayer()) { + if (!creature->getPlayer()) { flags |= FLAG_IGNOREFIELDDAMAGE; } @@ -684,9 +668,9 @@ const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const return tile; } -bool Map::getPathMatching(const Creature& creature, std::vector& dirList, const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const +bool Map::getPathMatching(CreaturePtr& creature, std::vector& dirList, const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) { - Position pos = creature.getPosition(); + Position pos = creature->getPosition(); Position endPos; AStarNodes nodes(pos.x, pos.y); @@ -711,7 +695,7 @@ bool Map::getPathMatching(const Creature& creature, std::vector& dirL AStarNode* found = nullptr; while (fpp.maxSearchDist != 0 || nodes.getClosedNodes() < 100) { - AStarNode* n = nodes.getBestNode(); + const auto& n = nodes.getBestNode(); if (!n) { if (found) { break; @@ -778,17 +762,14 @@ bool Map::getPathMatching(const Creature& creature, std::vector& dirL continue; } - const Tile* tile; - AStarNode* neighborNode = nodes.getNodeByPosition(pos.x, pos.y); - if (neighborNode) { - tile = getTile(pos.x, pos.y, pos.z); - } else { - tile = canWalkTo(creature, pos); - if (!tile) { - continue; - } - } + auto neighborNode = nodes.getNodeByPosition(pos.x, pos.y); + TilePtr tile = neighborNode ? getTile(pos.x, pos.y, pos.z) : canWalkTo(creature, pos); + if (!tile) + { + continue; + } + //The cost (g) for this neighbor const int_fast32_t cost = AStarNodes::getMapWalkCost(n, pos); const int_fast32_t extraCost = AStarNodes::getTileWalkCost(creature, tile); @@ -830,8 +811,8 @@ bool Map::getPathMatching(const Creature& creature, std::vector& dirL pos.x = found->x; pos.y = found->y; - int_fast32_t dx = pos.getX() - prevx; - int_fast32_t dy = pos.getY() - prevy; + const int_fast32_t dx = pos.getX() - prevx; + const int_fast32_t dy = pos.getY() - prevy; prevx = pos.x; prevy = pos.y; @@ -882,7 +863,7 @@ AStarNode* AStarNodes::createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, return nullptr; } - size_t retNode = curNode++; + const size_t retNode = curNode++; openNodes[retNode] = true; AStarNode* node = nodes + retNode; @@ -915,7 +896,7 @@ AStarNode* AStarNodes::getBestNode() return nullptr; } -void AStarNodes::closeNode(AStarNode* node) +void AStarNodes::closeNode(const AStarNode* node) { size_t index = node - nodes; assert(index < MAX_NODES); @@ -923,7 +904,7 @@ void AStarNodes::closeNode(AStarNode* node) ++closedNodes; } -void AStarNodes::openNode(AStarNode* node) +void AStarNodes::openNode(const AStarNode* node) { size_t index = node - nodes; assert(index < MAX_NODES); @@ -938,7 +919,7 @@ int_fast32_t AStarNodes::getClosedNodes() const return closedNodes; } -AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) +AStarNode* AStarNodes::getNodeByPosition(const uint32_t x, const uint32_t y) { auto it = nodeTable.find((x << 16) | y); if (it == nodeTable.end()) { @@ -947,7 +928,7 @@ AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) return it->second; } -int_fast32_t AStarNodes::getMapWalkCost(AStarNode* node, const Position& neighborPos) +int_fast32_t AStarNodes::getMapWalkCost(const AStarNode* node, const Position& neighborPos) { if (std::abs(node->x - neighborPos.x) == std::abs(node->y - neighborPos.y)) { //diagonal movement extra cost @@ -956,18 +937,17 @@ 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 CreaturePtr creature, const TileConstPtr& tile) { int_fast32_t cost = 0; - if (tile->getTopVisibleCreature(&creature) != nullptr) { + if (tile->getTopVisibleCreature(creature) != nullptr) { //destroy creature cost cost += MAP_NORMALWALKCOST * 3; } - if (const MagicField* field = tile->getFieldItem()) { - CombatType_t combatType = field->getCombatType(); - const Monster* monster = creature.getMonster(); - if (!creature.isImmune(combatType) && !creature.hasCondition(Combat::DamageToConditionType(combatType)) && (monster && !monster->canWalkOnFieldType(combatType))) { + if (const auto& field = tile->getFieldItem()) { + const CombatType_t combatType = field->getCombatType(); + if (const auto& monster = creature->getMonster(); !creature->isImmune(combatType) && !creature->hasCondition(Combat::DamageToConditionType(combatType)) && (monster && !monster->canWalkOnFieldType(combatType))) { cost += MAP_NORMALWALKCOST * 18; } } @@ -978,8 +958,8 @@ int_fast32_t AStarNodes::getTileWalkCost(const Creature& creature, const Tile* t Floor::~Floor() { for (auto& row : tiles) { - for (auto tile : row) { - delete tile; + for (auto& tile : row) { + tile.reset(); } } } @@ -987,28 +967,28 @@ Floor::~Floor() // QTreeNode QTreeNode::~QTreeNode() { - for (auto* ptr : child) { + for (const auto* ptr : child) { delete ptr; } } -QTreeLeafNode* QTreeNode::getLeaf(uint32_t x, uint32_t y) +QTreeLeafNode* QTreeNode::getLeaf(const uint32_t x, const uint32_t y) { if (leaf) { return static_cast(this); } - QTreeNode* node = child[((x & 0x8000) >> 15) | ((y & 0x8000) >> 14)]; + const auto& node = child[((x & 0x8000) >> 15) | ((y & 0x8000) >> 14)]; if (!node) { return nullptr; } return node->getLeaf(x << 1, y << 1); } -QTreeLeafNode* QTreeNode::createLeaf(uint32_t x, uint32_t y, uint32_t level) +QTreeLeafNode* QTreeNode::createLeaf(const uint32_t x, const uint32_t y, const uint32_t level) { if (!isLeaf()) { - uint32_t index = ((x & 0x8000) >> 15) | ((y & 0x8000) >> 14); + const uint32_t index = ((x & 0x8000) >> 15) | ((y & 0x8000) >> 14); if (!child[index]) { if (level != FLOOR_BITS) { child[index] = new QTreeNode(); @@ -1027,12 +1007,12 @@ bool QTreeLeafNode::newLeaf = false; QTreeLeafNode::~QTreeLeafNode() { - for (auto* ptr : array) { + for (const auto* ptr : array) { delete ptr; } } -Floor* QTreeLeafNode::createFloor(uint32_t z) +Floor* QTreeLeafNode::createFloor(const uint32_t z) { if (!array[z]) { array[z] = new Floor(); @@ -1040,7 +1020,7 @@ Floor* QTreeLeafNode::createFloor(uint32_t z) return array[z]; } -void QTreeLeafNode::addCreature(Creature* c) +void QTreeLeafNode::addCreature(const CreaturePtr& c) { creature_list.push_back(c); @@ -1049,40 +1029,40 @@ void QTreeLeafNode::addCreature(Creature* c) } } -void QTreeLeafNode::removeCreature(Creature* c) +void QTreeLeafNode::removeCreature(const CreaturePtr& c) { - auto iter = std::find(creature_list.begin(), creature_list.end(), c); + auto iter = std::ranges::find(creature_list, c); assert(iter != creature_list.end()); *iter = creature_list.back(); creature_list.pop_back(); if (c->getPlayer()) { - iter = std::find(player_list.begin(), player_list.end(), c); + iter = std::ranges::find(player_list, c); assert(iter != player_list.end()); *iter = player_list.back(); player_list.pop_back(); } } -uint32_t Map::clean() const +uint32_t Map::clean() { - uint64_t start = OTSYS_TIME(); + const uint64_t start = OTSYS_TIME(); size_t tiles = 0; if (g_game.getGameState() == GAME_STATE_NORMAL) { g_game.setGameState(GAME_STATE_MAINTAIN); } - std::vector toRemove; + std::vector toRemove; - for (auto tile : g_game.getTilesToClean()) { + for (const auto& tile : g_game.getTilesToClean()) { if (!tile) { continue; } - if (auto items = tile->getItemList()) { + if (const auto& items = tile->getItemList()) { ++tiles; - for (auto item : *items) { + for (const auto& item : *items) { if (item->isCleanable()) { toRemove.emplace_back(item); } @@ -1090,11 +1070,11 @@ uint32_t Map::clean() const } } - for (auto item : toRemove) { + for (const auto& item : toRemove) { g_game.internalRemoveItem(item, -1); } - size_t count = toRemove.size(); + const size_t count = toRemove.size(); g_game.clearTilesToClean(); if (g_game.getGameState() == GAME_STATE_MAINTAIN) { diff --git a/src/map.h b/src/map.h index 243a5b4f..f3433857 100644 --- a/src/map.h +++ b/src/map.h @@ -44,7 +44,9 @@ struct alignas(16) ChunkKey { return std::memcmp(this, &other, sizeof(ChunkKey)) == 0; } }; + static ChunkKey chunkKey; + struct ChunkKeyHash { std::size_t operator()(const ChunkKey& key) const noexcept { std::size_t hash = 0; @@ -80,13 +82,13 @@ class AStarNodes AStarNode* createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, int_fast32_t f); AStarNode* getBestNode(); - void closeNode(AStarNode* node); - void openNode(AStarNode* node); + void closeNode(const AStarNode* node); + void openNode(const AStarNode* node); int_fast32_t getClosedNodes() const; AStarNode* getNodeByPosition(uint32_t x, uint32_t y); - static int_fast32_t getMapWalkCost(AStarNode* node, const Position& neighborPos); - static int_fast32_t getTileWalkCost(const Creature& creature, const Tile* tile); + static int_fast32_t getMapWalkCost(const AStarNode* node, const Position& neighborPos); + static int_fast32_t getTileWalkCost(const CreaturePtr creature, const TileConstPtr& tile); private: AStarNode nodes[MAX_NODES]; @@ -110,7 +112,7 @@ struct Floor { Floor(const Floor&) = delete; Floor& operator=(const Floor&) = delete; - Tile* tiles[FLOOR_SIZE][FLOOR_SIZE] = {}; + TilePtr tiles[FLOOR_SIZE][FLOOR_SIZE] = {}; }; class FrozenPathingConditionCall; @@ -162,19 +164,20 @@ class QTreeLeafNode final : public QTreeNode { public: QTreeLeafNode() { leaf = true; newLeaf = true; } - ~QTreeLeafNode(); + ~QTreeLeafNode() override; // non-copyable QTreeLeafNode(const QTreeLeafNode&) = delete; QTreeLeafNode& operator=(const QTreeLeafNode&) = delete; Floor* createFloor(uint32_t z); + Floor* getFloor(uint8_t z) const { return array[z]; } - void addCreature(Creature* c); - void removeCreature(Creature* c); + void addCreature(const CreaturePtr& c); + void removeCreature(const CreaturePtr& c); private: static bool newLeaf; @@ -201,13 +204,14 @@ class Map static constexpr int32_t maxClientViewportX = 8; static constexpr int32_t maxClientViewportY = 6; - uint32_t clean() const; + static uint32_t clean(); /** * Load a map. * \returns true if the map was loaded successfully */ bool loadMap(const std::string& identifier, bool loadHouses); + void clearChunkSpectatorCache() { playersSpectatorCache.clear(); chunksSpectatorCache.clear(); @@ -223,23 +227,26 @@ class Map * 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 { + TilePtr getTile(uint16_t x, uint16_t y, uint8_t z); + + TilePtr getTile(const Position& pos) { return getTile(pos.x, pos.y, pos.z); } /** * 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(uint16_t x, uint16_t y, uint8_t z, TilePtr& newTile); + + void setTile(const Position& pos, TilePtr& newTile) { setTile(pos.x, pos.y, pos.z, newTile); } /** * Removes a single tile. */ - void removeTile(uint16_t x, uint16_t y, uint8_t z); + void removeTile(uint16_t x, uint16_t y, uint8_t z) const; + void removeTile(const Position& pos) { removeTile(pos.x, pos.y, pos.z); } @@ -251,9 +258,9 @@ class 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 because of obstacles (creatures/chests) */ - bool placeCreature(const Position& centerPos, Creature* creature, bool extendedPos = false, bool forceLogin = false); + bool placeCreature(const Position& centerPos, CreaturePtr creature, bool extendedPos = false, bool forceLogin = false); - void moveCreature(Creature& creature, Tile& newTile, bool forceTeleport = false); + void moveCreature(CreaturePtr& creature, const TilePtr& newTile, bool forceTeleport = false); void getSpectators(SpectatorVec& spectators, const Position& centerPos, bool multifloor = false, bool onlyPlayers = false, int32_t minRangeX = 0, int32_t maxRangeX = 0, @@ -273,14 +280,14 @@ class Map * \returns The result if you can throw there or not */ bool canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight = true, bool sameFloor = false, - int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY) const; + int32_t rangex = Map::maxClientViewportX, int32_t rangey = Map::maxClientViewportY); /** * Checks if there are no obstacles on that position * \param blockFloor counts the ground tile as an obstacle * \returns The result if there is an obstacle or not */ - bool isTileClear(uint16_t x, uint16_t y, uint8_t z, bool blockFloor = false) const; + bool isTileClear(uint16_t x, uint16_t y, uint8_t z, bool blockFloor = false); /** * Checks if path is clear from fromPos to toPos @@ -290,13 +297,13 @@ class Map * \param sameFloor checks if the destination is on same floor * \returns The result if there is no obstacles */ - bool isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor = false) const; - bool checkSightLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t z) const; + bool isSightClear(const Position& fromPos, const Position& toPos, bool sameFloor = false); + static bool checkSightLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint8_t z); - const Tile* canWalkTo(const Creature& creature, const Position& pos) const; + TilePtr canWalkTo(CreaturePtr& creature, const Position& pos); - bool getPathMatching(const Creature& creature, std::vector& dirList, - const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const; + bool getPathMatching(CreaturePtr& creature, std::vector& dirList, + const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp); std::map waypoints; diff --git a/src/matrixarea.cpp b/src/matrixarea.cpp index 086d12de..5f4a8987 100644 --- a/src/matrixarea.cpp +++ b/src/matrixarea.cpp @@ -16,7 +16,7 @@ MatrixArea MatrixArea::rotate90() const MatrixArea MatrixArea::rotate180() const { Container newArr(arr.size()); - std::reverse_copy(std::begin(arr), std::end(arr), std::begin(newArr)); + std::ranges::reverse_copy(arr, std::begin(newArr)); auto &&[centerX, centerY] = center; return {{cols - centerX - 1, rows - centerY - 1}, rows, cols, std::move(newArr)}; } @@ -32,7 +32,7 @@ MatrixArea MatrixArea::rotate270() const return {{centerY, cols - centerX - 1}, cols, rows, std::move(newArr)}; } -MatrixArea createArea(const std::vector &vec, uint32_t rows) +MatrixArea createArea(const std::vector &vec, const uint32_t rows) { uint32_t cols; if (rows == 0) { @@ -46,7 +46,7 @@ MatrixArea createArea(const std::vector &vec, uint32_t rows) uint32_t x = 0; uint32_t y = 0; - for (uint32_t value : vec) { + for (const uint32_t& value : vec) { if (value == 1 || value == 3) { area(y, x) = true; } diff --git a/src/monster.cpp b/src/monster.cpp index 9889ec35..9f6de7d3 100644 --- a/src/monster.cpp +++ b/src/monster.cpp @@ -20,17 +20,16 @@ int32_t Monster::despawnRadius; uint32_t Monster::monsterAutoID = 0x40000000; -Monster* Monster::createMonster(const std::string& name) +MonsterPtr Monster::createMonster(const std::string& name) { - MonsterType* mType = g_monsters.getMonsterType(name); + const auto& mType = g_monsters.getMonsterType(name); if (!mType) { return nullptr; } - return new Monster(mType); + return std::make_shared(mType); } Monster::Monster(MonsterType* mType) : - Creature(), nameDescription(mType->nameDescription), mType(mType) { @@ -59,12 +58,12 @@ Monster::~Monster() void Monster::addList() { - g_game.addMonster(this); + g_game.addMonster(getMonster()); } void Monster::removeList() { - g_game.removeMonster(this); + g_game.removeMonster(getMonster()); } const std::string& Monster::getName() const @@ -85,7 +84,7 @@ void Monster::setName(const std::string& name) // NOTE: Due to how client caches known creatures, // it is not feasible to send creature update to everyone that has ever met it - g_game.notifySpectators(this); + g_game.notifySpectators(CreatureConstPtr(this)); } const std::string& Monster::getNameDescription() const @@ -101,7 +100,7 @@ bool Monster::canSee(const Position& pos) const return Creature::canSee(getPosition(), pos, 9, 9); } -bool Monster::canWalkOnFieldType(CombatType_t combatType) const +bool Monster::canWalkOnFieldType(const CombatType_t combatType) const { switch (combatType) { case COMBAT_ENERGYDAMAGE: @@ -120,7 +119,7 @@ void Monster::onAttackedCreatureDisappear(bool) attackTicks = 0; } -void Monster::onCreatureAppear(Creature* creature, bool isLogin) +void Monster::onCreatureAppear(const CreaturePtr& creature, const bool isLogin) { Creature::onCreatureAppear(creature, isLogin); @@ -138,10 +137,10 @@ void Monster::onCreatureAppear(Creature* creature, bool isLogin) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(mType->info.creatureAppearEvent); - LuaScriptInterface::pushUserdata(L, this); + LuaScriptInterface::pushSharedPtr(L, getMonster()); LuaScriptInterface::setMetatable(L, -1, "Monster"); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); if (scriptInterface->callFunction(2)) { @@ -149,7 +148,7 @@ void Monster::onCreatureAppear(Creature* creature, bool isLogin) } } - if (creature == this) { + if (creature == getCreature()) { //We just spawned lets look around to see who is there. if (isSummon()) { isMasterInRange = canSee(getMaster()->getPosition()); @@ -162,7 +161,7 @@ void Monster::onCreatureAppear(Creature* creature, bool isLogin) } } -void Monster::onRemoveCreature(Creature* creature, bool isLogout) +void Monster::onRemoveCreature(const CreaturePtr& creature, const bool isLogout) { Creature::onRemoveCreature(creature, isLogout); @@ -180,10 +179,10 @@ void Monster::onRemoveCreature(Creature* creature, bool isLogout) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(mType->info.creatureDisappearEvent); - LuaScriptInterface::pushUserdata(L, this); + LuaScriptInterface::pushSharedPtr(L, getMonster()); LuaScriptInterface::setMetatable(L, -1, "Monster"); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); if (scriptInterface->callFunction(2)) { @@ -191,7 +190,7 @@ void Monster::onRemoveCreature(Creature* creature, bool isLogout) } } - if (creature == this) { + if (creature == this->getCreature()) { if (spawn) { spawn->startSpawnCheck(); } @@ -202,8 +201,8 @@ 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(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, + const TilePtr& oldTile, const Position& oldPos, bool teleport) { Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); @@ -221,10 +220,10 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(mType->info.creatureMoveEvent); - LuaScriptInterface::pushUserdata(L, this); + LuaScriptInterface::pushSharedPtr(L, getMonster()); LuaScriptInterface::setMetatable(L, -1, "Monster"); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushPosition(L, oldPos); @@ -235,7 +234,7 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi } } - if (creature == this) { + if (creature == this->getCreature()) { if (isSummon()) { isMasterInRange = canSee(getMaster()->getPosition()); } @@ -243,8 +242,8 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi updateTargetList(); updateIdleStatus(); } else { - bool canSeeNewPos = canSee(newPos); - bool canSeeOldPos = canSee(oldPos); + const bool canSeeNewPos = canSee(newPos); + const bool canSeeOldPos = canSee(oldPos); if (canSeeNewPos && !canSeeOldPos) { onCreatureEnter(creature); @@ -263,15 +262,14 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi const Position& followPosition = followCreature->getPosition(); const Position& position = getPosition(); - int32_t offset_x = Position::getDistanceX(followPosition, position); - int32_t offset_y = Position::getDistanceY(followPosition, position); + const int32_t offset_x = Position::getDistanceX(followPosition, position); + const int32_t offset_y = Position::getDistanceY(followPosition, position); if ((offset_x > 1 || offset_y > 1) && mType->info.changeTargetChance > 0) { Direction dir = getDirectionTo(position, followPosition); const Position& checkPosition = getNextPosition(dir, position); - Tile* tile = g_game.map.getTile(checkPosition); - if (tile) { - Creature* topCreature = tile->getTopCreature(); + if (const auto& tile = g_game.map.getTile(checkPosition)) { + const auto& topCreature = tile->getTopCreature(); if (topCreature && followCreature != topCreature && isOpponent(topCreature)) { selectTarget(topCreature); } @@ -285,7 +283,7 @@ void Monster::onCreatureMove(Creature* creature, const Tile* newTile, const Posi } } -void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) +void Monster::onCreatureSay(const CreaturePtr& creature, SpeakClasses type, const std::string& text) { Creature::onCreatureSay(creature, type, text); @@ -303,10 +301,10 @@ void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::st lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(mType->info.creatureSayEvent); - LuaScriptInterface::pushUserdata(L, this); + LuaScriptInterface::pushSharedPtr(L, getMonster()); LuaScriptInterface::setMetatable(L, -1, "Monster"); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); lua_pushinteger(L, type); @@ -316,29 +314,23 @@ void Monster::onCreatureSay(Creature* creature, SpeakClasses type, const std::st } } -void Monster::addFriend(Creature* creature) +void Monster::addFriend(const CreaturePtr& creature) { - assert(creature != this); - auto result = friendList.insert(creature); - if (result.second) { - creature->incrementReferenceCounter(); - } + assert(creature != this->getCreature()); + const auto& result = friendList.insert(creature); } -void Monster::removeFriend(Creature* creature) +void Monster::removeFriend(const CreaturePtr& creature) { - auto it = friendList.find(creature); - if (it != friendList.end()) { - creature->decrementReferenceCounter(); + if (auto it = friendList.find(creature); it != friendList.end()) { friendList.erase(it); } } -void Monster::addTarget(Creature* creature, bool pushFront/* = false*/) +void Monster::addTarget(const CreaturePtr& creature, bool pushFront/* = false*/) { - assert(creature != this); - if (std::find(targetList.begin(), targetList.end(), creature) == targetList.end()) { - creature->incrementReferenceCounter(); + assert(creature != this->getCreature()); + if (std::ranges::find(targetList, creature) == targetList.end()) { if (pushFront) { targetList.push_front(creature); } else { @@ -347,11 +339,9 @@ void Monster::addTarget(Creature* creature, bool pushFront/* = false*/) } } -void Monster::removeTarget(Creature* creature) +void Monster::removeTarget(const CreaturePtr& creature) { - auto it = std::find(targetList.begin(), targetList.end(), creature); - if (it != targetList.end()) { - creature->decrementReferenceCounter(); + if (const auto& it = std::ranges::find(targetList, creature); it != targetList.end()) { targetList.erase(it); } } @@ -360,9 +350,8 @@ void Monster::updateTargetList() { auto friendIterator = friendList.begin(); while (friendIterator != friendList.end()) { - Creature* creature = *friendIterator; + const auto& creature = *friendIterator; if (creature->getHealth() <= 0 || !canSee(creature->getPosition())) { - creature->decrementReferenceCounter(); friendIterator = friendList.erase(friendIterator); } else { ++friendIterator; @@ -371,9 +360,8 @@ void Monster::updateTargetList() auto targetIterator = targetList.begin(); while (targetIterator != targetList.end()) { - Creature* creature = *targetIterator; + const auto& creature = *targetIterator; if (creature->getHealth() <= 0 || !canSee(creature->getPosition())) { - creature->decrementReferenceCounter(); targetIterator = targetList.erase(targetIterator); } else { ++targetIterator; @@ -382,29 +370,23 @@ void Monster::updateTargetList() SpectatorVec spectators; g_game.map.getSpectators(spectators, position, true); - spectators.erase(this); - for (Creature* spectator : spectators) { + spectators.erase(this->getCreature()); + for (const auto& spectator : spectators) { onCreatureFound(spectator); } } void Monster::clearTargetList() { - for (Creature* creature : targetList) { - creature->decrementReferenceCounter(); - } targetList.clear(); } void Monster::clearFriendList() { - for (Creature* creature : friendList) { - creature->decrementReferenceCounter(); - } friendList.clear(); } -void Monster::onCreatureFound(Creature* creature, bool pushFront/* = false*/) +void Monster::onCreatureFound(const CreaturePtr& creature, bool pushFront/* = false*/) { if (!creature) { return; @@ -425,7 +407,7 @@ void Monster::onCreatureFound(Creature* creature, bool pushFront/* = false*/) updateIdleStatus(); } -void Monster::onCreatureEnter(Creature* creature) +void Monster::onCreatureEnter(const CreaturePtr& creature) { // std::cout << "onCreatureEnter - " << creature->getName() << std::endl; @@ -437,16 +419,16 @@ void Monster::onCreatureEnter(Creature* creature) onCreatureFound(creature, true); } -bool Monster::isFriend(const Creature* creature) const +bool Monster::isFriend(const CreatureConstPtr& creature) const { if (isSummon() && getMaster()->getPlayer()) { - const Player* masterPlayer = getMaster()->getPlayer(); - const Player* tmpPlayer = nullptr; + const auto& masterPlayer = getMaster()->getPlayer(); + PlayerConstPtr tmpPlayer = nullptr; if (creature->getPlayer()) { tmpPlayer = creature->getPlayer(); } else { - const Creature* creatureMaster = creature->getMaster(); + const auto& creatureMaster = creature->getMaster(); if (creatureMaster && creatureMaster->getPlayer()) { tmpPlayer = creatureMaster->getPlayer(); @@ -463,7 +445,7 @@ bool Monster::isFriend(const Creature* creature) const return false; } -bool Monster::isOpponent(const Creature* creature) const +bool Monster::isOpponent(const CreatureConstPtr& creature) const { if (isSummon() && getMaster()->getPlayer()) { if (creature != getMaster()) { @@ -479,7 +461,7 @@ bool Monster::isOpponent(const Creature* creature) const return false; } -void Monster::onCreatureLeave(Creature* creature) +void Monster::onCreatureLeave(const CreaturePtr& creature) { // std::cout << "onCreatureLeave - " << creature->getName() << std::endl; @@ -509,10 +491,10 @@ void Monster::onCreatureLeave(Creature* creature) bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAULT*/) { - std::list resultList; + std::list resultList; const Position& myPos = getPosition(); - for (Creature* creature : targetList) { + for (const auto& creature : targetList) { if (followCreature != creature && isTarget(creature)) { if (searchType == TARGETSEARCH_RANDOM || canUseAttack(myPos, creature)) { resultList.push_back(creature); @@ -522,7 +504,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL switch (searchType) { case TARGETSEARCH_NEAREST: { - Creature* target = nullptr; + CreaturePtr target = nullptr; if (!resultList.empty()) { auto it = resultList.begin(); target = *it; @@ -533,7 +515,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL do { const Position& pos = (*it)->getPosition(); - int32_t distance = Position::getDistanceX(myPos, pos) + Position::getDistanceY(myPos, pos); + const int32_t distance = Position::getDistanceX(myPos, pos) + Position::getDistanceY(myPos, pos); if (distance < minRange) { target = *it; minRange = distance; @@ -542,7 +524,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL } } else { int32_t minRange = std::numeric_limits::max(); - for (Creature* creature : targetList) { + for (const auto& creature : targetList) { if (!isTarget(creature)) { continue; } @@ -581,7 +563,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL } //lets just pick the first target in the list - for (Creature* target : targetList) { + for (const auto& target : targetList) { if (followCreature != target && selectTarget(target)) { return true; } @@ -589,34 +571,30 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL return false; } -void Monster::onFollowCreatureComplete(const Creature* creature) +void Monster::onFollowCreatureComplete(const CreatureConstPtr& creature) { if (creature) { - auto it = std::find(targetList.begin(), targetList.end(), creature); - if (it != targetList.end()) { - Creature* target = (*it); + if (const auto it = std::ranges::find(targetList, creature); it != targetList.end()) { + const CreaturePtr target = (*it); targetList.erase(it); if (hasFollowPath) { targetList.push_front(target); } else if (!isSummon()) { targetList.push_back(target); - } else { - target->decrementReferenceCounter(); } } } } -BlockType_t Monster::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, +BlockType_t Monster::blockHit(const CreaturePtr& attacker, CombatType_t combatType, int32_t& damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool /* field = false */, bool /* ignoreResistances = false */) { BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor); if (damage != 0) { int32_t elementMod = 0; - auto it = mType->info.elementMap.find(combatType); - if (it != mType->info.elementMap.end()) { + if (const auto it = mType->info.elementMap.find(combatType); it != mType->info.elementMap.end()) { elementMod = it->second; } @@ -632,7 +610,7 @@ BlockType_t Monster::blockHit(Creature* attacker, CombatType_t combatType, int32 return blockType; } -bool Monster::isTarget(const Creature* creature) const +bool Monster::isTarget(const CreatureConstPtr& creature) const { if (creature->isRemoved() || !creature->isAttackable() || creature->getZone() == ZONE_PROTECTION || !canSeeCreature(creature)) { @@ -645,14 +623,13 @@ bool Monster::isTarget(const Creature* creature) const return true; } -bool Monster::selectTarget(Creature* creature) +bool Monster::selectTarget(const CreaturePtr& creature) { if (!isTarget(creature)) { return false; } - auto it = std::find(targetList.begin(), targetList.end(), creature); - if (it == targetList.end()) { + if (const auto it = std::ranges::find(targetList, creature); it == targetList.end()) { //Target not found in our target list. return false; } @@ -665,7 +642,7 @@ bool Monster::selectTarget(Creature* creature) return setFollowCreature(creature); } -void Monster::setIdle(bool idle) +void Monster::setIdle(const bool idle) { if (isRemoved() || getHealth() <= 0) { return; @@ -674,12 +651,12 @@ void Monster::setIdle(bool idle) isIdle = idle; if (!isIdle) { - g_game.addCreatureCheck(this); + g_game.addCreatureCheck(this->getCreature()); } else { onIdleStatus(); clearTargetList(); clearFriendList(); - Game::removeCreatureCheck(this); + Game::removeCreatureCheck(this->getCreature()); } } @@ -688,7 +665,7 @@ void Monster::updateIdleStatus() bool idle = false; if (!isSummon() && targetList.empty()) { // check if there are aggressive conditions - idle = std::find_if(conditions.begin(), conditions.end(), [](Condition* condition) { + idle = std::ranges::find_if(conditions, [](const Condition* condition) { return condition->isAggressive(); }) == conditions.end(); } @@ -696,7 +673,7 @@ void Monster::updateIdleStatus() setIdle(idle); } -void Monster::onAddCondition(ConditionType_t type) +void Monster::onAddCondition(const ConditionType_t type) { if (type == CONDITION_FIRE || type == CONDITION_ENERGY || type == CONDITION_POISON) { updateMapCache(); @@ -705,7 +682,7 @@ void Monster::onAddCondition(ConditionType_t type) updateIdleStatus(); } -void Monster::onEndCondition(ConditionType_t type) +void Monster::onEndCondition(const ConditionType_t type) { if (type == CONDITION_FIRE || type == CONDITION_ENERGY || type == CONDITION_POISON) { ignoreFieldDamage = false; @@ -715,7 +692,7 @@ void Monster::onEndCondition(ConditionType_t type) updateIdleStatus(); } -void Monster::onThink(uint32_t interval) +void Monster::onThink(const uint32_t interval) { Creature::onThink(interval); @@ -746,9 +723,9 @@ void Monster::onThink(uint32_t interval) if (!isInSpawnRange(position)) { g_game.addMagicEffect(this->getPosition(), CONST_ME_POFF); if (g_config.getBoolean(ConfigManager::REMOVE_ON_DESPAWN)) { - g_game.removeCreature(this, false); + g_game.removeCreature(this->getCreature(), false); } else { - g_game.internalTeleport(this, masterPos); + g_game.internalTeleport(this->getCreature(), masterPos); setIdle(true); } } else { @@ -766,7 +743,7 @@ void Monster::onThink(uint32_t interval) //Our master has not ordered us to attack anything, lets follow him around instead. setFollowCreature(getMaster()); } - } else if (attackedCreature == this) { + } else if (attackedCreature == this->getCreature()) { setFollowCreature(nullptr); } else if (followCreature != attackedCreature) { //This happens just after a master orders an attack, so lets follow it as well. @@ -789,9 +766,9 @@ void Monster::onThink(uint32_t interval) } } -void Monster::doAttacking(uint32_t interval) +void Monster::doAttacking(const uint32_t interval) { - if (!attackedCreature || (isSummon() && attackedCreature == this)) { + if (!attackedCreature || (isSummon() && attackedCreature == this->getCreature())) { return; } @@ -818,7 +795,7 @@ void Monster::doAttacking(uint32_t interval) minCombatValue = spellBlock.minCombatValue; maxCombatValue = spellBlock.maxCombatValue; - spellBlock.spell->castSpell(this, attackedCreature); + spellBlock.spell->castSpell(this->getCreature(), attackedCreature); if (spellBlock.isMelee) { lastMeleeAttack = OTSYS_TIME(); @@ -842,11 +819,11 @@ void Monster::doAttacking(uint32_t interval) } } -bool Monster::canUseAttack(const Position& pos, const Creature* target) const +bool Monster::canUseAttack(const Position& pos, const CreatureConstPtr& target) const { if (isHostile()) { const Position& targetPos = target->getPosition(); - uint32_t distance = std::max(Position::getDistanceX(pos, targetPos), Position::getDistanceY(pos, targetPos)); + const uint32_t distance = std::max(Position::getDistanceX(pos, targetPos), Position::getDistanceY(pos, targetPos)); for (const spellBlock_t& spellBlock : mType->info.attackSpells) { if (spellBlock.range != 0 && distance <= spellBlock.range) { return g_game.isSightClear(pos, targetPos, true); @@ -858,7 +835,7 @@ bool Monster::canUseAttack(const Position& pos, const Creature* target) const } bool Monster::canUseSpell(const Position& pos, const Position& targetPos, - const spellBlock_t& sb, uint32_t interval, bool& inRange, bool& resetTicks) + const spellBlock_t& sb, const uint32_t interval, bool& inRange, bool& resetTicks) const { inRange = true; @@ -885,7 +862,7 @@ bool Monster::canUseSpell(const Position& pos, const Position& targetPos, return true; } -void Monster::onThinkTarget(uint32_t interval) +void Monster::onThinkTarget(const uint32_t interval) { if (!isSummon()) { if (mType->info.changeTargetSpeed != 0) { @@ -934,7 +911,7 @@ void Monster::onThinkTarget(uint32_t interval) } } -void Monster::onThinkDefense(uint32_t interval) +void Monster::onThinkDefense(const uint32_t interval) { bool resetTicks = true; defenseTicks += interval; @@ -953,7 +930,7 @@ void Monster::onThinkDefense(uint32_t interval) if ((spellBlock.chance >= static_cast(uniform_random(1, 100)))) { minCombatValue = spellBlock.minCombatValue; maxCombatValue = spellBlock.maxCombatValue; - spellBlock.spell->castSpell(this, this); + spellBlock.spell->castSpell(this->getMonster(), this->getCreature()); } } @@ -974,7 +951,7 @@ void Monster::onThinkDefense(uint32_t interval) } uint32_t summonCount = 0; - for (Creature* summon : summons) { + for (const auto& summon : summons) { if (summon->getName() == summonBlock.name) { ++summonCount; } @@ -988,17 +965,14 @@ void Monster::onThinkDefense(uint32_t interval) continue; } - Monster* summon = Monster::createMonster(summonBlock.name); - if (summon) { + if (MonsterPtr summon = Monster::createMonster(summonBlock.name)) { if (g_game.placeCreature(summon, getPosition(), false, summonBlock.force, summonBlock.effect)) { summon->setDropLoot(false); summon->setSkillLoss(false); - summon->setMaster(this); + summon->setMaster(this->getMonster()); if (summonBlock.masterEffect != CONST_ME_NONE) { g_game.addMagicEffect(getPosition(), summonBlock.masterEffect); } - } else { - delete summon; } } } @@ -1009,7 +983,7 @@ void Monster::onThinkDefense(uint32_t interval) } } -void Monster::onThinkYell(uint32_t interval) +void Monster::onThinkYell(const uint32_t interval) { if (mType->info.yellSpeedTicks == 0) { return; @@ -1024,9 +998,9 @@ void Monster::onThinkYell(uint32_t interval) const voiceBlock_t& vb = mType->info.voiceVector[index]; if (vb.yellText) { - g_game.internalCreatureSay(this, TALKTYPE_MONSTER_YELL, vb.text, false); + g_game.internalCreatureSay(this->getMonster(), TALKTYPE_MONSTER_YELL, vb.text, false); } else { - g_game.internalCreatureSay(this, TALKTYPE_MONSTER_SAY, vb.text, false); + g_game.internalCreatureSay(this->getMonster(), TALKTYPE_MONSTER_SAY, vb.text, false); } } } @@ -1067,7 +1041,7 @@ void Monster::onWalkComplete() } } -bool Monster::pushItem(Item* item) +bool Monster::pushItem(const ItemPtr& item) { const Position& centerPos = item->getPosition(); @@ -1077,13 +1051,15 @@ bool Monster::pushItem(Item* item) {-1, 1}, {0, 1}, {1, 1} }; - std::shuffle(relList.begin(), relList.end(), getRandomGenerator()); + std::ranges::shuffle(relList, getRandomGenerator()); for (const auto& it : relList) { Position tryPos(centerPos.x + it.first, centerPos.y + it.second, centerPos.z); - Tile* tile = g_game.map.getTile(tryPos); + const auto& tile = g_game.map.getTile(tryPos); if (tile && g_game.canThrowObjectTo(centerPos, tryPos, true, true)) { - if (g_game.internalMoveItem(item->getParent(), tile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr) == RETURNVALUE_NOERROR) { + CylinderPtr n_parent = item->getParent(); + CylinderPtr t_parent = tile; + if (g_game.internalMoveItem(n_parent, t_parent, INDEX_WHEREEVER, item, item->getItemCount(), nullptr) == RETURNVALUE_NOERROR) { return true; } } @@ -1091,19 +1067,18 @@ bool Monster::pushItem(Item* item) return false; } -void Monster::pushItems(Tile* tile) +void Monster::pushItems(const TilePtr& tile) { //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 - if (TileItemVector* items = tile->getItemList()) { + if (const auto& items = tile->getItemList()) { uint32_t moveCount = 0; uint32_t removeCount = 0; int32_t downItemSize = tile->getDownItemCount(); for (int32_t i = downItemSize; --i >= 0;) { - Item* item = items->at(i); - if (item && item->hasProperty(CONST_PROP_MOVEABLE) && (item->hasProperty(CONST_PROP_BLOCKPATH) + if (ItemPtr item = items->at(i); item && item->hasProperty(CONST_PROP_MOVEABLE) && (item->hasProperty(CONST_PROP_BLOCKPATH) || item->hasProperty(CONST_PROP_BLOCKSOLID))) { if (moveCount < 20 && Monster::pushItem(item)) { ++moveCount; @@ -1119,18 +1094,18 @@ void Monster::pushItems(Tile* tile) } } -bool Monster::pushCreature(Creature* creature) +bool Monster::pushCreature(const CreaturePtr& creature) { static std::vector dirList { DIRECTION_NORTH, DIRECTION_WEST, DIRECTION_EAST, DIRECTION_SOUTH }; - std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); + std::ranges::shuffle(dirList, getRandomGenerator()); - for (Direction dir : dirList) { + for (const Direction dir : dirList) { const Position& tryPos = Spells::getCasterPosition(creature, dir); - Tile* toTile = g_game.map.getTile(tryPos); + const auto& toTile = g_game.map.getTile(tryPos); if (toTile && !toTile->hasFlag(TILESTATE_BLOCKPATH)) { if (g_game.internalMoveCreature(creature, dir) == RETURNVALUE_NOERROR) { return true; @@ -1140,16 +1115,16 @@ bool Monster::pushCreature(Creature* creature) return false; } -void Monster::pushCreatures(Tile* tile) +void Monster::pushCreatures(const TilePtr& 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()) { + if (const auto& creatures = tile->getCreatures()) { uint32_t removeCount = 0; - Monster* lastPushedMonster = nullptr; + MonsterPtr lastPushedMonster = nullptr; for (size_t i = 0; i < creatures->size();) { - Monster* monster = creatures->at(i)->getMonster(); + const auto& monster = creatures->at(i)->getMonster(); if (monster && monster->isPushable()) { if (monster != lastPushedMonster && Monster::pushCreature(monster)) { lastPushedMonster = monster; @@ -1215,9 +1190,8 @@ bool Monster::getNextStep(Direction& direction, uint32_t& flags) } if (result && (canPushItems() || canPushCreatures())) { - const Position& pos = Spells::getCasterPosition(this, direction); - Tile* tile = g_game.map.getTile(pos); - if (tile) { + const Position& pos = Spells::getCasterPosition(this->getMonster(), direction); + if (const auto& tile = g_game.map.getTile(pos)) { if (canPushItems()) { Monster::pushItems(tile); } @@ -1231,9 +1205,9 @@ bool Monster::getNextStep(Direction& direction, uint32_t& flags) return result; } -bool Monster::getRandomStep(const Position& creaturePos, Direction& direction) const +bool Monster::getRandomStep(const Position& creaturePos, Direction& direction) { - for (Direction dir : getShuffleDirections()) { + for (const Direction dir : getShuffleDirections()) { if (canWalkTo(creaturePos, dir)) { direction = dir; return true; @@ -1243,20 +1217,20 @@ bool Monster::getRandomStep(const Position& creaturePos, Direction& direction) c } bool Monster::getDanceStep(const Position& creaturePos, Direction& direction, - bool keepAttack /*= true*/, bool keepDistance /*= true*/) + const bool keepAttack /*= true*/, const bool keepDistance /*= true*/) { - bool canDoAttackNow = canUseAttack(creaturePos, attackedCreature); + const bool canDoAttackNow = canUseAttack(creaturePos, attackedCreature); assert(attackedCreature != nullptr); const Position& centerPos = attackedCreature->getPosition(); - int_fast32_t offset_x = Position::getOffsetX(creaturePos, centerPos); - int_fast32_t offset_y = Position::getOffsetY(creaturePos, centerPos); + const int_fast32_t offset_x = Position::getOffsetX(creaturePos, centerPos); + const int_fast32_t offset_y = Position::getOffsetY(creaturePos, centerPos); - int_fast32_t distance_x = std::abs(offset_x); - int_fast32_t distance_y = std::abs(offset_y); + const int_fast32_t distance_x = std::abs(offset_x); + const int_fast32_t distance_y = std::abs(offset_y); - uint32_t centerToDist = std::max(distance_x, distance_y); + const uint32_t centerToDist = std::max(distance_x, distance_y); std::vector dirList; @@ -1276,8 +1250,7 @@ bool Monster::getDanceStep(const Position& creaturePos, Direction& direction, } if (!keepDistance || offset_y <= 0) { - uint32_t tmpDist = std::max(distance_x, std::abs((creaturePos.getY() + 1) - centerPos.getY())); - if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_SOUTH)) { + if (const uint32_t tmpDist = std::max(distance_x, std::abs((creaturePos.getY() + 1) - centerPos.getY())); tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_SOUTH)) { bool result = true; if (keepAttack) { @@ -1291,8 +1264,7 @@ bool Monster::getDanceStep(const Position& creaturePos, Direction& direction, } if (!keepDistance || offset_x <= 0) { - uint32_t tmpDist = std::max(std::abs((creaturePos.getX() + 1) - centerPos.getX()), distance_y); - if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_EAST)) { + if (const uint32_t tmpDist = std::max(std::abs((creaturePos.getX() + 1) - centerPos.getX()), distance_y); tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_EAST)) { bool result = true; if (keepAttack) { @@ -1306,8 +1278,7 @@ bool Monster::getDanceStep(const Position& creaturePos, Direction& direction, } if (!keepDistance || offset_x >= 0) { - uint32_t tmpDist = std::max(std::abs((creaturePos.getX() - 1) - centerPos.getX()), distance_y); - if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_WEST)) { + if (const uint32_t tmpDist = std::max(std::abs((creaturePos.getX() - 1) - centerPos.getX()), distance_y); tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_WEST)) { bool result = true; if (keepAttack) { @@ -1321,7 +1292,7 @@ bool Monster::getDanceStep(const Position& creaturePos, Direction& direction, } if (!dirList.empty()) { - std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); + std::ranges::shuffle(dirList, getRandomGenerator()); direction = dirList[uniform_random(0, dirList.size() - 1)]; return true; } @@ -1335,9 +1306,7 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& direction, b int_fast32_t dx = Position::getDistanceX(creaturePos, targetPos); int_fast32_t dy = Position::getDistanceY(creaturePos, targetPos); - int32_t distance = std::max(dx, dy); - - if (!flee && (distance > mType->info.targetDistance || !g_game.isSightClear(creaturePos, targetPos, true))) { + if (int32_t distance = std::max(dx, dy); !flee && (distance > mType->info.targetDistance || !g_game.isSightClear(creaturePos, targetPos, true))) { return false; // let the A* calculate it } else if (!flee && distance == mType->info.targetDistance) { return true; // we don't really care here, since it's what we wanted to reach (a dance-step will take of dancing in that position) @@ -1824,7 +1793,7 @@ bool Monster::getDistanceStep(const Position& targetPos, Direction& direction, b return true; } -bool Monster::canWalkTo(Position pos, Direction direction) const +bool Monster::canWalkTo(Position pos, const Direction direction) { pos = getNextPosition(direction, pos); if (isInSpawnRange(pos)) { @@ -1832,20 +1801,18 @@ bool Monster::canWalkTo(Position pos, Direction direction) const return false; } - Tile* tile = g_game.map.getTile(pos); - if (tile && tile->getTopVisibleCreature(this) == nullptr && tile->queryAdd(*this, FLAG_PATHFINDING) == RETURNVALUE_NOERROR) { + if (auto tile = g_game.map.getTile(pos); tile && tile->getTopVisibleCreature(this->getMonster()) == nullptr && tile->queryAdd(this->getMonster(), FLAG_PATHFINDING) == RETURNVALUE_NOERROR) { return true; } } return false; } -void Monster::death(Creature*) +void Monster::death(const CreaturePtr&) { - auto monsterId = getID(); - auto it = g_game.rewardBossTracking.find(monsterId); + const auto monsterId = getID(); // rewardboss - if (it != g_game.rewardBossTracking.end()) { + if (const auto it = g_game.rewardBossTracking.find(monsterId); it != g_game.rewardBossTracking.end()) { if (isRewardBoss()) { auto& bossScoreTable = it->second; uint32_t topContributerId = 0; @@ -1854,10 +1821,10 @@ void Monster::death(Creature*) int32_t totalDamageDone = 0; int32_t totalDamageTaken = 0; int32_t totalHealingDone = 0; - int32_t contributors = bossScoreTable.playerScoreTable.size(); + const int32_t contributors = bossScoreTable.playerScoreTable.size(); for (const auto& [playerId, score] : bossScoreTable.playerScoreTable) { - int32_t playerScore = score.damageDone + score.damageTaken + score.healingDone; + const int32_t playerScore = score.damageDone + score.damageTaken + score.healingDone; totalScore += playerScore; totalDamageDone += score.damageDone; totalDamageTaken += score.damageTaken; @@ -1874,18 +1841,18 @@ void Monster::death(Creature*) for (const auto& [playerId, score] : bossScoreTable.playerScoreTable) { - auto contributionScore = + const auto contributionScore = (score.damageDone * g_config.getFloat(ConfigManager::REWARD_RATE_DAMAGE_DONE)) + (score.damageTaken * g_config.getFloat(ConfigManager::REWARD_RATE_DAMAGE_TAKEN)) + (score.healingDone * (g_config.getFloat(ConfigManager::REWARD_RATE_DAMAGE_DONE))); // we should never see 0's here, but better safe than sorry. - float expectedScore = (contributionScore) ? (totalScore / (contributors * 3.0)) : 0; - int32_t lootRate = std::max(g_config.getFloat(ConfigManager::REWARD_BASE_RATE), 1.0); + const float expectedScore = (contributionScore) ? (totalScore / (contributors * 3.0)) : 0; + const int32_t lootRate = std::max(g_config.getFloat(ConfigManager::REWARD_BASE_RATE), 1.0); - Player* player = g_game.getPlayerByGUID(playerId); - auto rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER)->getContainer(); - rewardContainer->setIntAttr(ITEM_ATTRIBUTE_DATE, currentTime); - rewardContainer->setIntAttr(ITEM_ATTRIBUTE_REWARDID, getMonster()->getID()); + const auto& player = g_game.getPlayerByGUID(playerId); + const auto& rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER)->getContainer(); + rewardContainer->getItem()->setIntAttr(ITEM_ATTRIBUTE_DATE, currentTime); + rewardContainer->getItem()->setIntAttr(ITEM_ATTRIBUTE_REWARDID, getMonster()->getID()); bool hasLoot = false; auto isTopPlayer = (playerId == topContributerId) ? true : false; @@ -1895,9 +1862,9 @@ void Monster::death(Creature*) for (const auto& lootBlock : creatureLoot) { if (!lootBlock.unique || (lootBlock.unique && isTopPlayer)) { int32_t adjustedChance = (static_cast(lootBlock.chance) * lootRate); - - auto chance = uniform_random(1, MAX_LOOTCHANCE); - auto count = uniform_random(1, lootBlock.countmax); + + const auto chance = uniform_random(1, MAX_LOOTCHANCE); + const auto count = uniform_random(1, lootBlock.countmax); if (chance <= adjustedChance) { auto lootItem = Item::CreateItem(lootBlock.id, count); @@ -1905,7 +1872,8 @@ void Monster::death(Creature*) lootItem->setIntAttr(ITEM_ATTRIBUTE_DATE, currentTime); lootItem->setIntAttr(ITEM_ATTRIBUTE_REWARDID, monsterId); } - if (g_game.internalAddItem(rewardContainer, lootItem) == RETURNVALUE_NOERROR) { + CylinderPtr holder = rewardContainer; + if (g_game.internalAddItem(holder, lootItem) == RETURNVALUE_NOERROR) { hasLoot = true; } } @@ -1919,7 +1887,8 @@ void Monster::death(Creature*) } if (hasLoot) { if (player) { - if (g_game.internalAddItem(player->getRewardChest().getContainer(), rewardContainer) == RETURNVALUE_NOERROR) { + CylinderPtr holder = player->getRewardChest()->getContainer(); + if (g_game.internalAddItem(holder, rewardContainer->getItem()) == RETURNVALUE_NOERROR) { player->sendTextMessage(MESSAGE_LOOT, "The following items dropped by " + getMonster()->getName() + " are available in your reward chest: " + rewardContainer->getContentDescription() + "."); } } else { @@ -1928,7 +1897,7 @@ void Monster::death(Creature*) ItemBlockList itemList; int32_t currentPid = 1; - for (Item* subItem : rewardContainer->getItemList()) { + for (const auto& subItem : rewardContainer->getItemList()) { itemList.emplace_back(currentPid, subItem); } @@ -1942,7 +1911,7 @@ void Monster::death(Creature*) setAttackedCreature(nullptr); - for (Creature* summon : summons) { + for (const auto& summon : summons) { summon->changeHealth(-summon->getHealth()); } summons.clear(); @@ -1952,15 +1921,15 @@ void Monster::death(Creature*) onIdleStatus(); } -Item* Monster::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) +ItemPtr Monster::getCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature) { - Item* corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); + const auto& corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse) { if (mostDamageCreature) { if (mostDamageCreature->getPlayer()) { corpse->setCorpseOwner(mostDamageCreature->getID()); } else { - const Creature* mostDamageCreatureMaster = mostDamageCreature->getMaster(); + const auto& mostDamageCreatureMaster = mostDamageCreature->getMaster(); if (mostDamageCreatureMaster && mostDamageCreatureMaster->getPlayer()) { corpse->setCorpseOwner(mostDamageCreatureMaster->getID()); } @@ -2013,11 +1982,11 @@ void Monster::updateLookDirection() if (attackedCreature) { 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); + const int_fast32_t offsetx = Position::getOffsetX(attackedCreaturePos, pos); + const int_fast32_t offsety = Position::getOffsetY(attackedCreaturePos, pos); - int32_t dx = std::abs(offsetx); - int32_t dy = std::abs(offsety); + const int32_t dx = std::abs(offsetx); + const int32_t dy = std::abs(offsety); if (dx > dy) { //look EAST/WEST if (offsetx < 0) { @@ -2047,14 +2016,14 @@ void Monster::updateLookDirection() } } - g_game.internalCreatureTurn(this, newDir); + g_game.internalCreatureTurn(this->getMonster(), newDir); } -void Monster::dropLoot(Container* corpse, Creature*) +void Monster::dropLoot(const ContainerPtr& corpse, const CreaturePtr&) { if (getMonster()->isRewardBoss()) { int64_t currentTime = std::time(nullptr); - Item* rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); + const auto& rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); rewardContainer->setIntAttr(ITEM_ATTRIBUTE_DATE, currentTime); rewardContainer->setIntAttr(ITEM_ATTRIBUTE_REWARDID, getMonster()->getID()); @@ -2062,7 +2031,7 @@ void Monster::dropLoot(Container* corpse, Creature*) corpse->internalAddThing(rewardContainer); } else if (corpse && lootDrop) { - g_events->eventMonsterOnDropLoot(this, corpse); + g_events->eventMonsterOnDropLoot(this->getMonster(), corpse); } } @@ -2071,7 +2040,7 @@ void Monster::setNormalCreatureLight() internalLight = mType->info.light; } -void Monster::drainHealth(Creature* attacker, int32_t damage) +void Monster::drainHealth(const CreaturePtr& attacker, const int32_t damage) { Creature::drainHealth(attacker, damage); @@ -2085,14 +2054,14 @@ void Monster::drainHealth(Creature* attacker, int32_t damage) } } -void Monster::changeHealth(int32_t healthChange, bool sendHealthChange/* = true*/) +void Monster::changeHealth(const int32_t healthChange, const 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 force/* = false*/) +bool Monster::challengeCreature(const CreaturePtr& creature, bool force/* = false*/) { if (isSummon()) { return false; @@ -2111,7 +2080,7 @@ bool Monster::challengeCreature(Creature* creature, bool force/* = false*/) return result; } -void Monster::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const +void Monster::getPathSearchParams(const CreatureConstPtr& creature, FindPathParams& fpp) const { Creature::getPathSearchParams(creature, fpp); @@ -2142,8 +2111,7 @@ void Monster::getPathSearchParams(const Creature* creature, FindPathParams& fpp) bool Monster::canPushItems() const { - Monster* master = this->master ? this->master->getMonster() : nullptr; - if (master) { + if (const auto& master = this->master ? this->master->getMonster() : nullptr) { return master->mType->info.canPushItems; } diff --git a/src/monster.h b/src/monster.h index 73f74bae..8070a240 100644 --- a/src/monster.h +++ b/src/monster.h @@ -11,8 +11,8 @@ class Creature; class Game; class Spawn; -using CreatureHashSet = std::unordered_set; -using CreatureList = std::list; +using CreatureHashSet = std::unordered_set; +using CreatureList = std::list; enum TargetSearchType_t { TARGETSEARCH_DEFAULT, @@ -24,22 +24,23 @@ enum TargetSearchType_t { class Monster final : public Creature { public: - static Monster* createMonster(const std::string& name); + static MonsterPtr createMonster(const std::string& name); static int32_t despawnRange; static int32_t despawnRadius; explicit Monster(MonsterType* mType); - ~Monster(); + ~Monster() override; // non-copyable Monster(const Monster&) = delete; Monster& operator=(const Monster&) = delete; - Monster* getMonster() override { - return this; + MonsterPtr getMonster() override { + return dynamic_shared_this(); } - const Monster* getMonster() const override { - return this; + + MonsterConstPtr getMonster() const override { + return dynamic_shared_this(); } void setID() override { @@ -55,6 +56,7 @@ class Monster final : public Creature void setName(const std::string& name); const std::string& getNameDescription() const override; + void setNameDescription(const std::string& nameDescription) { this->nameDescription = nameDescription; }; @@ -71,6 +73,7 @@ class Monster final : public Creature const Position& getMasterPos() const { return masterPos; } + void setMasterPos(Position pos) { masterPos = pos; } @@ -78,99 +81,118 @@ class Monster final : public Creature RaceType_t getRace() const override { return mType->info.race; } + int32_t getArmor() const override { return mType->info.armor; } + int32_t getDefense() const override { return mType->info.defense; } + bool isPushable() const override { return mType->info.pushable && baseSpeed != 0; } + bool isAttackable() const override { return mType->info.isAttackable; } bool canPushItems() const; + bool canPushCreatures() const { return mType->info.canPushCreatures; } + bool isHostile() const { return mType->info.isHostile; } + bool isRewardBoss() const { return mType->info.isRewardBoss; } + bool canSee(const Position& pos) const override; + bool canSeeInvisibility() const override { return isImmune(CONDITION_INVISIBLE); } + uint32_t getManaCost() const { return mType->info.manaCost; } + void setSpawn(Spawn* spawn) { this->spawn = spawn; } + bool canWalkOnFieldType(CombatType_t combatType) const; void onAttackedCreatureDisappear(bool isLogout) 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 onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) override; + void onCreatureAppear(const CreaturePtr& creature, bool isLogin) override; + void onRemoveCreature(const CreaturePtr& creature, bool isLogout) override; + void onCreatureMove(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, const TilePtr& oldTile, const Position& oldPos, bool teleport) override; + void onCreatureSay(const CreaturePtr& creature, SpeakClasses type, const std::string& text) override; - void drainHealth(Creature* attacker, int32_t damage) override; + void drainHealth(const CreaturePtr& attacker, int32_t damage) override; void changeHealth(int32_t healthChange, bool sendHealthChange = true) override; bool isWalkingToSpawn() const { return walkingToSpawn; } + bool walkToSpawn(); void onWalk() override; void onWalkComplete() override; bool getNextStep(Direction& direction, uint32_t& flags) override; - void onFollowCreatureComplete(const Creature* creature) override; + void onFollowCreatureComplete(const CreatureConstPtr& creature) override; void onThink(uint32_t interval) override; - bool challengeCreature(Creature* creature, bool force = false) override; + bool challengeCreature(const CreaturePtr& creature, bool force = false) override; void setNormalCreatureLight() override; bool getCombatValues(int32_t& min, int32_t& max) override; void doAttacking(uint32_t interval) override; + bool hasExtraSwing() override { return lastMeleeAttack == 0; } bool searchTarget(TargetSearchType_t searchType = TARGETSEARCH_DEFAULT); - bool selectTarget(Creature* creature); + bool selectTarget(const CreaturePtr& creature); const CreatureList& getTargetList() const { return targetList; } + const CreatureHashSet& getFriendList() const { return friendList; } + CreatureHashSet& getFriendList() { return friendList; } - bool isTarget(const Creature* creature) const; + bool isTarget(const CreatureConstPtr& creature) const; + bool isFleeing() const { return !isSummon() && getHealth() <= mType->info.runAwayHealth && challengeFocusDuration <= 0; } bool getDistanceStep(const Position& targetPos, Direction& direction, bool flee = false); + bool isTargetNearby() const { return stepDuration >= 1; } + bool isIgnoringFieldDamage() const { return ignoreFieldDamage; } - BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, + BlockType_t blockHit(const CreaturePtr& attacker, CombatType_t combatType, int32_t& damage, bool checkDefense = false, bool checkArmor = false, bool field = false, bool ignoreResistances = false) override; static uint32_t monsterAutoID; @@ -206,26 +228,27 @@ class Monster final : public Creature bool randomStepping = false; bool walkingToSpawn = false; - void onCreatureEnter(Creature* creature); - void onCreatureLeave(Creature* creature); - void onCreatureFound(Creature* creature, bool pushFront = false); + void onCreatureEnter(const CreaturePtr& creature); + void onCreatureLeave(const CreaturePtr& creature); + void onCreatureFound(const CreaturePtr& creature, bool pushFront = false); void updateLookDirection(); - void addFriend(Creature* creature); - void removeFriend(Creature* creature); - void addTarget(Creature* creature, bool pushFront = false); - void removeTarget(Creature* creature); + void addFriend(const CreaturePtr& creature); + void removeFriend(const CreaturePtr& creature); + void addTarget(const CreaturePtr& creature, bool pushFront = false); + void removeTarget(const CreaturePtr& creature); void updateTargetList(); void clearTargetList(); void clearFriendList(); - void death(Creature* lastHitCreature) override; - Item* getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) override; + void death(const CreaturePtr& lastHitCreature) override; + ItemPtr getCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature) override; void setIdle(bool idle); void updateIdleStatus(); + bool getIdleStatus() const { return isIdle; } @@ -233,41 +256,47 @@ 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 canUseAttack(const Position& pos, const CreatureConstPtr& 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; + const spellBlock_t& sb, uint32_t interval, bool& inRange, bool& resetTicks) const; + bool getRandomStep(const Position& creaturePos, Direction& direction); 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; + bool canWalkTo(Position pos, Direction direction); - static bool pushItem(Item* item); - static void pushItems(Tile* tile); - static bool pushCreature(Creature* creature); - static void pushCreatures(Tile* tile); + static bool pushItem(const ItemPtr& item); + static void pushItems(const TilePtr& tile); + static bool pushCreature(const CreaturePtr& creature); + static void pushCreatures(const TilePtr& tile); void onThinkTarget(uint32_t interval); void onThinkYell(uint32_t interval); void onThinkDefense(uint32_t interval); - bool isFriend(const Creature* creature) const; - bool isOpponent(const Creature* creature) const; + bool isFriend(const CreatureConstPtr& creature) const; + bool isOpponent(const CreatureConstPtr& creature) const; uint64_t getLostExperience() const override { return skillLoss ? mType->info.experience : 0; } + uint16_t getLookCorpse() const override { return mType->info.lookcorpse; } - void dropLoot(Container* corpse, Creature* lastHitCreature) override; + + void dropLoot(const ContainerPtr& corpse, const CreaturePtr& lastHitCreature) override; + uint32_t getDamageImmunities() const override { return mType->info.damageImmunities; } + uint32_t getConditionImmunities() const override { return mType->info.conditionImmunities; } - void getPathSearchParams(const Creature* creature, FindPathParams& fpp) const override; + + void getPathSearchParams(const CreatureConstPtr& creature, FindPathParams& fpp) const override; + bool useCacheMap() const override { return !randomStepping; } diff --git a/src/movement.cpp b/src/movement.cpp index 577cc1dd..4a75b6b1 100644 --- a/src/movement.cpp +++ b/src/movement.cpp @@ -23,7 +23,7 @@ MoveEvents::~MoveEvents() clear(false); } -void MoveEvents::clearMap(MoveListMap& map, bool fromLua) +void MoveEvents::clearMap(MoveListMap& map, const bool fromLua) { for (auto it = map.begin(); it != map.end(); ++it) { for (int eventType = MOVE_EVENT_STEP_IN; eventType < MOVE_EVENT_LAST; ++eventType) { @@ -39,7 +39,7 @@ void MoveEvents::clearMap(MoveListMap& map, bool fromLua) } } -void MoveEvents::clearPosMap(MovePosListMap& map, bool fromLua) +void MoveEvents::clearPosMap(MovePosListMap& map, const bool fromLua) { for (auto it = map.begin(); it != map.end(); ++it) { for (int eventType = MOVE_EVENT_STEP_IN; eventType < MOVE_EVENT_LAST; ++eventType) { @@ -55,7 +55,7 @@ void MoveEvents::clearPosMap(MovePosListMap& map, bool fromLua) } } -void MoveEvents::clear(bool fromLua) +void MoveEvents::clear(const bool fromLua) { clearMap(itemIdMap, fromLua); clearMap(actionIdMap, fromLua); @@ -75,7 +75,7 @@ Event_ptr MoveEvents::getEvent(const std::string& nodeName) if (!caseInsensitiveEqual(nodeName, "movevent")) { return nullptr; } - return Event_ptr(new MoveEvent(&scriptInterface)); + return std::make_unique(&scriptInterface); } bool MoveEvents::registerEvent(Event_ptr event, const pugi::xml_node& node) @@ -115,7 +115,7 @@ bool MoveEvents::registerEvent(Event_ptr event, const pugi::xml_node& node) } } else if ((attr = node.attribute("fromid"))) { uint32_t id = pugi::cast(attr.value()); - uint32_t endId = pugi::cast(node.attribute("toid").value()); + const uint32_t endId = pugi::cast(node.attribute("toid").value()); addEvent(*moveEvent, id, itemIdMap); @@ -141,33 +141,29 @@ bool MoveEvents::registerEvent(Event_ptr event, const pugi::xml_node& node) } } } else if ((attr = node.attribute("uniqueid"))) { - std::vector uidList = vectorAtoi(explodeString(attr.as_string(), ";")); - - for (const auto& uid : uidList) { + for (const std::vector uidList = vectorAtoi(explodeString(attr.as_string(), ";")); const auto& uid : uidList) { addEvent(std::move(*moveEvent), uid, uniqueIdMap); } } else if ((attr = node.attribute("fromuid"))) { uint32_t id = pugi::cast(attr.value()); - uint32_t endId = pugi::cast(node.attribute("touid").value()); + const uint32_t endId = pugi::cast(node.attribute("touid").value()); addEvent(*moveEvent, id, uniqueIdMap); while (++id <= endId) { addEvent(*moveEvent, id, uniqueIdMap); } } else if ((attr = node.attribute("actionid"))) { - std::vector aidList = vectorAtoi(explodeString(attr.as_string(), ";")); - - for (const auto& aid : aidList) { + for (const std::vector aidList = vectorAtoi(explodeString(attr.as_string(), ";")); const auto& aid : aidList) { addEvent(std::move(*moveEvent), aid, actionIdMap); } } else if ((attr = node.attribute("fromaid"))) { uint32_t id = pugi::cast(attr.value()); - uint32_t endId = pugi::cast(node.attribute("toaid").value()); + const uint32_t endId = pugi::cast(node.attribute("toaid").value()); addEvent(*moveEvent, id, actionIdMap); while (++id <= endId) { addEvent(*moveEvent, id, actionIdMap); } } else if ((attr = node.attribute("pos"))) { - std::vector posList = vectorAtoi(explodeString(attr.as_string(), ";")); + const std::vector posList = vectorAtoi(explodeString(attr.as_string(), ";")); if (posList.size() < 3) { return false; } @@ -263,7 +259,7 @@ bool MoveEvents::registerLuaEvent(MoveEvent* event) } } else { auto v = moveEvent->getItemIdRange(); - for (auto i = v.begin(); i != v.end(); i++) { + for (auto i = v.begin(); i != v.end(); ++i) { if (moveEvent->getEventType() == MOVE_EVENT_EQUIP) { ItemType& it = Item::items.getItemType(*i); it.wieldInfo = moveEvent->getWieldInfo(); @@ -280,7 +276,7 @@ bool MoveEvents::registerLuaEvent(MoveEvent* event) addEvent(*moveEvent, id, actionIdMap); } else { auto v = moveEvent->getActionIdRange(); - for (auto i = v.begin(); i != v.end(); i++) { + for (auto i = v.begin(); i != v.end(); ++i) { addEvent(*moveEvent, *i, actionIdMap); } } @@ -290,7 +286,7 @@ bool MoveEvents::registerLuaEvent(MoveEvent* event) addEvent(*moveEvent, id, uniqueIdMap); } else { auto v = moveEvent->getUniqueIdRange(); - for (auto i = v.begin(); i != v.end(); i++) { + for (auto i = v.begin(); i != v.end(); ++i) { addEvent(*moveEvent, *i, uniqueIdMap); } } @@ -300,7 +296,7 @@ bool MoveEvents::registerLuaEvent(MoveEvent* event) addEvent(*moveEvent, pos, positionMap); } else { auto v = moveEvent->getPosList(); - for (auto i = v.begin(); i != v.end(); i++) { + for (auto i = v.begin(); i != v.end(); ++i) { addEvent(*moveEvent, *i, positionMap); } } @@ -329,7 +325,7 @@ void MoveEvents::addEvent(MoveEvent moveEvent, int32_t id, MoveListMap& map) } } -MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType, slots_t slot) +MoveEvent* MoveEvents::getEvent(const ItemPtr& item, MoveEvent_t eventType, slots_t slot) { uint32_t slotp; switch (slot) { @@ -346,8 +342,7 @@ MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType, slots_t slot) default: slotp = 0; break; } - auto it = itemIdMap.find(item->getID()); - if (it != itemIdMap.end()) { + if (const auto it = itemIdMap.find(item->getID()); it != itemIdMap.end()) { std::list& moveEventList = it->second.moveEvent[eventType]; for (MoveEvent& moveEvent : moveEventList) { if ((moveEvent.getSlot() & slotp) != 0) { @@ -358,15 +353,14 @@ MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType, slots_t slot) return nullptr; } -MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType) +MoveEvent* MoveEvents::getEvent(const ItemPtr& item, MoveEvent_t eventType) { MoveListMap::iterator it; if (item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID)) { it = uniqueIdMap.find(item->getUniqueId()); if (it != uniqueIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; - if (!moveEventList.empty()) { + if (std::list& moveEventList = it->second.moveEvent[eventType]; !moveEventList.empty()) { return &(*moveEventList.begin()); } } @@ -375,8 +369,7 @@ MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType) if (item->hasAttribute(ITEM_ATTRIBUTE_ACTIONID)) { it = actionIdMap.find(item->getActionId()); if (it != actionIdMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; - if (!moveEventList.empty()) { + if (std::list& moveEventList = it->second.moveEvent[eventType]; !moveEventList.empty()) { return &(*moveEventList.begin()); } } @@ -384,8 +377,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]; - if (!moveEventList.empty()) { + if (std::list& moveEventList = it->second.moveEvent[eventType]; !moveEventList.empty()) { return &(*moveEventList.begin()); } } @@ -394,8 +386,7 @@ MoveEvent* MoveEvents::getEvent(Item* item, MoveEvent_t eventType) void MoveEvents::addEvent(MoveEvent moveEvent, const Position& pos, MovePosListMap& map) { - auto it = map.find(pos); - if (it == map.end()) { + if (const auto it = map.find(pos); it == map.end()) { MoveEventList moveEventList; moveEventList.moveEvent[moveEvent.getEventType()].push_back(std::move(moveEvent)); map[pos] = moveEventList; @@ -409,19 +400,17 @@ void MoveEvents::addEvent(MoveEvent moveEvent, const Position& pos, MovePosListM } } -MoveEvent* MoveEvents::getEvent(const Tile* tile, MoveEvent_t eventType) +MoveEvent* MoveEvents::getEvent(const TileConstPtr& tile, MoveEvent_t eventType) { - auto it = positionMap.find(tile->getPosition()); - if (it != positionMap.end()) { - std::list& moveEventList = it->second.moveEvent[eventType]; - if (!moveEventList.empty()) { + if (const auto it = positionMap.find(tile->getPosition()); it != positionMap.end()) { + if (std::list& moveEventList = it->second.moveEvent[eventType]; !moveEventList.empty()) { return &(*moveEventList.begin()); } } return nullptr; } -uint32_t MoveEvents::onCreatureMove(Creature* creature, const Tile* tile, MoveEvent_t eventType) +uint32_t MoveEvents::onCreatureMove(const CreaturePtr& creature, const TilePtr& tile, MoveEvent_t eventType) { const Position& pos = tile->getPosition(); @@ -433,12 +422,12 @@ uint32_t MoveEvents::onCreatureMove(Creature* creature, const Tile* tile, MoveEv } for (size_t i = tile->getFirstIndex(), j = tile->getLastIndex(); i < j; ++i) { - Thing* thing = tile->getThing(i); + auto thing = tile->getThing(i); if (!thing) { continue; } - Item* tileItem = thing->getItem(); + const auto& tileItem = thing->getItem(); if (!tileItem) { continue; } @@ -451,7 +440,7 @@ uint32_t MoveEvents::onCreatureMove(Creature* creature, const Tile* tile, MoveEv return ret; } -ReturnValue MoveEvents::onPlayerEquip(Player* player, Item* item, slots_t slot, bool isCheck) +ReturnValue MoveEvents::onPlayerEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck) { MoveEvent* moveEvent = getEvent(item, MOVE_EVENT_EQUIP, slot); if (!moveEvent) { @@ -460,7 +449,7 @@ ReturnValue MoveEvents::onPlayerEquip(Player* player, Item* item, slots_t slot, return moveEvent->fireEquip(player, item, slot, isCheck); } -ReturnValue MoveEvents::onPlayerDeEquip(Player* player, Item* item, slots_t slot) +ReturnValue MoveEvents::onPlayerDeEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot) { MoveEvent* moveEvent = getEvent(item, MOVE_EVENT_DEEQUIP, slot); if (!moveEvent) { @@ -472,7 +461,7 @@ ReturnValue MoveEvents::onPlayerDeEquip(Player* player, Item* item, slots_t slot return moveEvent->fireEquip(player, item, slot, false); } -uint32_t MoveEvents::onItemMove(Item* item, Tile* tile, bool isAdd) +uint32_t MoveEvents::onItemMove(const ItemPtr& item, const TilePtr& tile, bool isAdd) { MoveEvent_t eventType1, eventType2; if (isAdd) { @@ -495,12 +484,12 @@ uint32_t MoveEvents::onItemMove(Item* item, Tile* tile, bool isAdd) } for (size_t i = tile->getFirstIndex(), j = tile->getLastIndex(); i < j; ++i) { - Thing* thing = tile->getThing(i); + const auto& thing = tile->getThing(i); if (!thing) { continue; } - Item* tileItem = thing->getItem(); + const auto& tileItem = thing->getItem(); if (!tileItem || tileItem == item) { continue; } @@ -557,8 +546,7 @@ bool MoveEvent::configureEvent(const pugi::xml_node& node) } if (eventType == MOVE_EVENT_EQUIP || eventType == MOVE_EVENT_DEEQUIP) { - pugi::xml_attribute slotAttribute = node.attribute("slot"); - if (slotAttribute) { + if (const pugi::xml_attribute slotAttribute = node.attribute("slot")) { tmpStr = asLowerCaseString(slotAttribute.as_string()); if (tmpStr == "head") { slot = SLOTP_HEAD; @@ -589,24 +577,21 @@ bool MoveEvent::configureEvent(const pugi::xml_node& node) wieldInfo = 0; - pugi::xml_attribute levelAttribute = node.attribute("level"); - if (levelAttribute) { + if (const pugi::xml_attribute levelAttribute = node.attribute("level")) { reqLevel = pugi::cast(levelAttribute.value()); if (reqLevel > 0) { wieldInfo |= WIELDINFO_LEVEL; } } - pugi::xml_attribute magLevelAttribute = node.attribute("maglevel"); - if (magLevelAttribute) { + if (const pugi::xml_attribute magLevelAttribute = node.attribute("maglevel")) { reqMagLevel = pugi::cast(magLevelAttribute.value()); if (reqMagLevel > 0) { wieldInfo |= WIELDINFO_MAGLV; } } - pugi::xml_attribute premiumAttribute = node.attribute("premium"); - if (premiumAttribute) { + if (const pugi::xml_attribute premiumAttribute = node.attribute("premium")) { premium = premiumAttribute.as_bool(); if (premium) { wieldInfo |= WIELDINFO_PREMIUM; @@ -651,10 +636,9 @@ bool MoveEvent::configureEvent(const pugi::xml_node& node) return true; } -uint32_t MoveEvent::StepInField(Creature* creature, Item* item, const Position&) +uint32_t MoveEvent::StepInField(const CreaturePtr& creature, const ItemPtr& item, const Position&) { - MagicField* field = item->getMagicField(); - if (field) { + if (const auto field = item->getMagicField()) { field->onStepInField(creature); return 1; } @@ -662,17 +646,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(const CreaturePtr&, const ItemPtr&, const Position&) { return 1; } -uint32_t MoveEvent::AddItemField(Item* item, Item*, const Position&) +uint32_t MoveEvent::AddItemField(const ItemPtr& item, const ItemPtr&, const Position&) { - if (MagicField* field = item->getMagicField()) { - Tile* tile = item->getTile(); - if (CreatureVector* creatures = tile->getCreatures()) { - for (Creature* creature : *creatures) { + if (const auto& field = item->getMagicField()) { + const auto& tile = item->getTile(); + if (const auto& creatures = tile->getCreatures()) { + for (const auto& creature : *creatures) { field->onStepInField(creature); } } @@ -681,16 +665,16 @@ 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(const ItemPtr&, const ItemPtr&, const Position&) { return 1; } -ReturnValue MoveEvent::EquipItem(MoveEvent* moveEvent, Player* player, Item* item, slots_t slot, bool isCheck) +ReturnValue MoveEvent::EquipItem(MoveEvent* moveEvent, const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck) { if (!player->hasFlag(PlayerFlag_IgnoreWeaponCheck) && moveEvent->getWieldInfo() != 0) { const VocEquipMap& vocEquipMap = moveEvent->getVocEquipMap(); - if (!vocEquipMap.empty() && vocEquipMap.find(player->getVocationId()) == vocEquipMap.end()) { + if (!vocEquipMap.empty() && !vocEquipMap.contains(player->getVocationId())) { return RETURNVALUE_YOUDONTHAVEREQUIREDPROFESSION; } @@ -717,7 +701,7 @@ ReturnValue MoveEvent::EquipItem(MoveEvent* moveEvent, Player* player, Item* ite const ItemType& it = Item::items[item->getID()]; if (it.transformEquipTo != 0) { - Item* newItem = g_game.transformItem(item, it.transformEquipTo); + const auto& newItem = g_game.transformItem(item, it.transformEquipTo); g_game.startDecay(newItem); } else { player->setItemAbility(slot, true); @@ -813,7 +797,7 @@ ReturnValue MoveEvent::EquipItem(MoveEvent* moveEvent, Player* player, Item* ite return RETURNVALUE_NOERROR; } -ReturnValue MoveEvent::DeEquipItem(MoveEvent*, Player* player, Item* item, slots_t slot, bool) +ReturnValue MoveEvent::DeEquipItem(MoveEvent*, const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool) { if (!player->isItemAbilityEnabled(slot)) { return RETURNVALUE_NOERROR; @@ -934,7 +918,7 @@ void MoveEvent::setEventType(MoveEvent_t type) eventType = type; } -uint32_t MoveEvent::fireStepEvent(Creature* creature, Item* item, const Position& pos) +uint32_t MoveEvent::fireStepEvent(const CreaturePtr& creature, const ItemPtr& item, const Position& pos) { if (scripted) { return executeStep(creature, item, pos); @@ -943,7 +927,7 @@ uint32_t MoveEvent::fireStepEvent(Creature* creature, Item* item, const Position } } -bool MoveEvent::executeStep(Creature* creature, Item* item, const Position& pos) +bool MoveEvent::executeStep(const CreaturePtr& creature, const ItemPtr& item, const Position& pos) { //onStepIn(creature, item, pos, fromPosition) //onStepOut(creature, item, pos, fromPosition) @@ -958,7 +942,7 @@ bool MoveEvent::executeStep(Creature* creature, Item* item, const Position& pos) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushThing(L, item); LuaScriptInterface::pushPosition(L, pos); @@ -968,7 +952,7 @@ bool MoveEvent::executeStep(Creature* creature, Item* item, const Position& pos) } -ReturnValue MoveEvent::fireEquip(Player* player, Item* item, slots_t slot, bool isCheck) +ReturnValue MoveEvent::fireEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck) { ReturnValue ret = RETURNVALUE_NOERROR; if (equipFunction) { @@ -980,7 +964,7 @@ ReturnValue MoveEvent::fireEquip(Player* player, Item* item, slots_t slot, bool return ret; } -bool MoveEvent::executeEquip(Player* player, Item* item, slots_t slot, bool isCheck) +bool MoveEvent::executeEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck) { //onEquip(player, item, slot, isCheck) //onDeEquip(player, item, slot, isCheck) @@ -995,7 +979,7 @@ bool MoveEvent::executeEquip(Player* player, Item* item, slots_t slot, bool isCh lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushThing(L, item); lua_pushinteger(L, slot); @@ -1004,7 +988,7 @@ bool MoveEvent::executeEquip(Player* player, Item* item, slots_t slot, bool isCh return scriptInterface->callFunction(4); } -uint32_t MoveEvent::fireAddRemItem(Item* item, Item* tileItem, const Position& pos) +uint32_t MoveEvent::fireAddRemItem(const ItemPtr& item, const ItemPtr& tileItem, const Position& pos) { if (scripted) { return executeAddRemItem(item, tileItem, pos); @@ -1013,7 +997,7 @@ uint32_t MoveEvent::fireAddRemItem(Item* item, Item* tileItem, const Position& p } } -bool MoveEvent::executeAddRemItem(Item* item, Item* tileItem, const Position& pos) +bool MoveEvent::executeAddRemItem(const ItemPtr& item, const ItemPtr& tileItem, const Position& pos) { //onaddItem(moveitem, tileitem, pos) //onRemoveItem(moveitem, tileitem, pos) diff --git a/src/movement.h b/src/movement.h index 9b5a993c..134ac592 100644 --- a/src/movement.h +++ b/src/movement.h @@ -1,8 +1,8 @@ // Copyright 2024 Black Tek Server Authors. All rights reserved. // Use of this source code is governed by the GPL-2.0 License that can be found in the LICENSE file. -#ifndef FS_MOVEMENT_H_5E0D2626D4634ACA83AC6509518E5F49 -#define FS_MOVEMENT_H_5E0D2626D4634ACA83AC6509518E5F49 +#ifndef FS_MOVEMENT_H_ +#define FS_MOVEMENT_H_ #include "baseevents.h" #include "item.h" @@ -38,18 +38,18 @@ class MoveEvents final : public BaseEvents { public: MoveEvents(); - ~MoveEvents(); + ~MoveEvents() override; // non-copyable MoveEvents(const MoveEvents&) = delete; MoveEvents& operator=(const MoveEvents&) = delete; - uint32_t onCreatureMove(Creature* creature, const Tile* tile, MoveEvent_t eventType); - ReturnValue onPlayerEquip(Player* player, Item* item, slots_t slot, bool isCheck); - ReturnValue onPlayerDeEquip(Player* player, Item* item, slots_t slot); - uint32_t onItemMove(Item* item, Tile* tile, bool isAdd); + uint32_t onCreatureMove(const CreaturePtr& creature, const TilePtr& tile, MoveEvent_t eventType); + ReturnValue onPlayerEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck); + ReturnValue onPlayerDeEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot); + uint32_t onItemMove(const ItemPtr& item, const TilePtr& tile, bool isAdd); - MoveEvent* getEvent(Item* item, MoveEvent_t eventType); + MoveEvent* getEvent(const ItemPtr& item, MoveEvent_t eventType); bool registerLuaEvent(MoveEvent* event); bool registerLuaFunction(MoveEvent* event); @@ -69,9 +69,9 @@ class MoveEvents final : public BaseEvents void addEvent(MoveEvent moveEvent, int32_t id, MoveListMap& map); void addEvent(MoveEvent moveEvent, const Position& pos, MovePosListMap& map); - MoveEvent* getEvent(const Tile* tile, MoveEvent_t eventType); + MoveEvent* getEvent(const TileConstPtr& tile, MoveEvent_t eventType); - MoveEvent* getEvent(Item* item, MoveEvent_t eventType, slots_t slot); + MoveEvent* getEvent(const ItemPtr& item, MoveEvent_t eventType, slots_t slot); MoveListMap uniqueIdMap; MoveListMap actionIdMap; @@ -81,9 +81,9 @@ class MoveEvents final : public BaseEvents LuaScriptInterface scriptInterface; }; -using StepFunction = std::function; -using MoveFunction = std::function; -using EquipFunction = std::function; +using StepFunction = std::function; +using MoveFunction = std::function; +using EquipFunction = std::function; class MoveEvent final : public Event { @@ -96,126 +96,159 @@ class MoveEvent final : public Event bool configureEvent(const pugi::xml_node& node) override; bool loadFunction(const pugi::xml_attribute& attr, bool isScripted) override; - uint32_t fireStepEvent(Creature* creature, Item* item, const Position& pos); - uint32_t fireAddRemItem(Item* item, Item* tileItem, const Position& pos); - ReturnValue fireEquip(Player* player, Item* item, slots_t slot, bool isCheck); + uint32_t fireStepEvent(const CreaturePtr& creature, const ItemPtr& item, const Position& pos); + uint32_t fireAddRemItem(const ItemPtr& item, const ItemPtr& tileItem, const Position& pos); + ReturnValue fireEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck); uint32_t getSlot() const { return slot; } //scripting - bool executeStep(Creature* creature, Item* item, const Position& pos); - bool executeEquip(Player* player, Item* item, slots_t slot, bool isCheck); - bool executeAddRemItem(Item* item, Item* tileItem, const Position& pos); + bool executeStep(const CreaturePtr& creature, const ItemPtr& item, const Position& pos); + bool executeEquip(const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck); + bool executeAddRemItem(const ItemPtr& item, const ItemPtr& tileItem, const Position& pos); // //onEquip information uint32_t getReqLevel() const { return reqLevel; } + uint32_t getReqMagLv() const { return reqMagLevel; } + bool isPremium() const { return premium; } + const std::string& getVocationString() const { return vocationString; } + void setVocationString(const std::string& str) { vocationString = str; } + uint32_t getWieldInfo() const { return wieldInfo; } + const VocEquipMap& getVocEquipMap() const { return vocEquipMap; } - void addVocEquipMap(std::string vocName) { + + void addVocEquipMap(const std::string& vocName) { int32_t vocationId = g_vocations.getVocationId(vocName); if (vocationId != -1) { vocEquipMap[vocationId] = true; } } + bool getTileItem() const { return tileItem; } - void setTileItem(bool b) { + + void setTileItem(const bool b) { tileItem = b; } + void clearItemIdRange() { return itemIdRange.clear(); } + const std::vector& getItemIdRange() const { return itemIdRange; } + void addItemId(uint32_t id) { itemIdRange.emplace_back(id); } + void clearActionIdRange() { return actionIdRange.clear(); } + const std::vector& getActionIdRange() const { return actionIdRange; } + void addActionId(uint32_t id) { actionIdRange.emplace_back(id); } + void clearUniqueIdRange() { return uniqueIdRange.clear(); } + const std::vector& getUniqueIdRange() const { return uniqueIdRange; } + void addUniqueId(uint32_t id) { uniqueIdRange.emplace_back(id); } + void clearPosList() { return posList.clear(); } + const std::vector& getPosList() const { return posList; } + void addPosList(Position pos) { posList.emplace_back(pos); } + void setSlot(uint32_t s) { slot = s; } - uint32_t getRequiredLevel() { + + uint32_t getRequiredLevel() const + { return reqLevel; } + void setRequiredLevel(uint32_t level) { reqLevel = level; } - uint32_t getRequiredMagLevel() { + + uint32_t getRequiredMagLevel() const + { return reqMagLevel; } - void setRequiredMagLevel(uint32_t level) { + + void setRequiredMagLevel(const uint32_t level) { reqMagLevel = level; } - bool needPremium() { + + bool needPremium() const + { return premium; } - void setNeedPremium(bool b) { + + void setNeedPremium(const bool b) { premium = b; } + uint32_t getWieldInfo() { return wieldInfo; } - void setWieldInfo(WieldInfo_t info) { + + void setWieldInfo(const WieldInfo_t info) { 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(const CreaturePtr& creature, const ItemPtr& item, const Position& pos); + static uint32_t StepOutField(const CreaturePtr& creature, const ItemPtr& 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(const ItemPtr& item, const ItemPtr& tileItem, const Position& pos); + static uint32_t RemoveItemField(const ItemPtr& item, const ItemPtr& tileItem, const Position& pos); - static ReturnValue EquipItem(MoveEvent* moveEvent, Player* player, Item* item, slots_t slot, bool isCheck); - static ReturnValue DeEquipItem(MoveEvent* moveEvent, Player* player, Item* item, slots_t slot, bool); + static ReturnValue EquipItem(MoveEvent* moveEvent, const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool isCheck); + static ReturnValue DeEquipItem(MoveEvent* moveEvent, const PlayerPtr& player, const ItemPtr& item, slots_t slot, bool); MoveEvent_t eventType = MOVE_EVENT_NONE; StepFunction stepFunction; diff --git a/src/networkmessage.cpp b/src/networkmessage.cpp index cde6883b..1506c785 100644 --- a/src/networkmessage.cpp +++ b/src/networkmessage.cpp @@ -98,7 +98,7 @@ void NetworkMessage::addItem(uint16_t id, uint8_t count) } } -void NetworkMessage::addItem(const Item* item) +void NetworkMessage::addItem(const ItemConstPtr& item) { const ItemType& it = Item::items[item->getID()]; diff --git a/src/networkmessage.h b/src/networkmessage.h index e6d3b146..7720082c 100644 --- a/src/networkmessage.h +++ b/src/networkmessage.h @@ -5,10 +5,9 @@ #define FS_NETWORKMESSAGE_H #include "const.h" +#include "thing.h" class Item; -class Creature; -class Player; struct Position; class RSA; @@ -33,7 +32,7 @@ class NetworkMessage info = {}; } - // simply read functions for incoming message + // simple read functions for incoming message uint8_t getByte() { if (!canRead(1)) { return 0; @@ -97,7 +96,7 @@ class NetworkMessage // write functions for complex types void addPosition(const Position& pos); void addItem(uint16_t id, uint8_t count); - void addItem(const Item* item); + void addItem(const ItemConstPtr& item); void addItemId(uint16_t itemId); MsgSize_t getLength() const { diff --git a/src/npc.cpp b/src/npc.cpp index 758cded6..5c310b88 100644 --- a/src/npc.cpp +++ b/src/npc.cpp @@ -14,23 +14,23 @@ uint32_t Npc::npcAutoID = 0x80000000; void Npcs::reload() { - const std::map& npcs = g_game.getNpcs(); - for (const auto& it : npcs) { - it.second->closeAllShopWindows(); + const std::map& npcs = g_game.getNpcs(); + for (const auto& val : npcs | std::views::values) { + val->closeAllShopWindows(); } - for (const auto& it : npcs) { - it.second->reload(); + for (const auto& val : npcs | std::views::values) { + val->reload(); } } -Npc* Npc::createNpc(const std::string& name) +NpcPtr Npc::createNpc(const std::string& name) { - std::unique_ptr npc(new Npc(name)); + const auto& npc = std::make_shared(name); if (!npc->load()) { return nullptr; } - return npc.release(); + return npc; } Npc::Npc(const std::string& name) : @@ -49,12 +49,12 @@ Npc::~Npc() void Npc::addList() { - g_game.addNpc(this); + g_game.addNpc(this->getNpc()); } void Npc::removeList() { - g_game.removeNpc(this); + g_game.removeNpc(this->getNpc()); } bool Npc::load() @@ -96,8 +96,8 @@ void Npc::reload() SpectatorVec players; g_game.map.getSpectators(players, getPosition(), true, true); for (const auto& player : players) { - assert(dynamic_cast(player) != nullptr); - spectators.insert(static_cast(player)); + assert(std::dynamic_pointer_cast(player) != nullptr); + spectators.insert(std::static_pointer_cast(player)); } const bool hasSpectators = !spectators.empty(); @@ -109,14 +109,14 @@ void Npc::reload() // Simulate that the creature is placed on the map again. if (npcEventHandler) { - npcEventHandler->onCreatureAppear(this); + npcEventHandler->onCreatureAppear(this->getNpc()); } } bool Npc::loadFromXml() { pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(filename.c_str()); + const pugi::xml_parse_result result = doc.load_file(filename.c_str()); if (!result) { printXMLError("Error - Npc::loadFromXml", filename, result); return false; @@ -163,7 +163,7 @@ bool Npc::loadFromXml() setSkull(getSkullType(asLowerCaseString(attr.as_string()))); } - pugi::xml_node healthNode = npcNode.child("health"); + const pugi::xml_node healthNode = npcNode.child("health"); if (healthNode) { if ((attr = healthNode.attribute("now"))) { health = pugi::cast(attr.value()); @@ -183,9 +183,9 @@ bool Npc::loadFromXml() } } - pugi::xml_node lookNode = npcNode.child("look"); + const pugi::xml_node lookNode = npcNode.child("look"); if (lookNode) { - pugi::xml_attribute lookTypeAttribute = lookNode.attribute("type"); + const pugi::xml_attribute lookTypeAttribute = lookNode.attribute("type"); if (lookTypeAttribute) { defaultOutfit.lookType = pugi::cast(lookTypeAttribute.value()); defaultOutfit.lookHead = pugi::cast(lookNode.attribute("head").value()); @@ -205,9 +205,9 @@ bool Npc::loadFromXml() parameters[parameterNode.attribute("key").as_string()] = parameterNode.attribute("value").as_string(); } - pugi::xml_attribute scriptFile = npcNode.attribute("script"); + const pugi::xml_attribute scriptFile = npcNode.attribute("script"); if (scriptFile) { - auto handler = std::make_unique(scriptFile.as_string(), this); + auto handler = std::make_unique(scriptFile.as_string(), this->getNpc()); if (!handler->isLoaded()) { return false; } @@ -233,16 +233,16 @@ std::string Npc::getDescription(int32_t) const return descr; } -void Npc::onCreatureAppear(Creature* creature, bool isLogin) +void Npc::onCreatureAppear(const CreaturePtr& creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); - if (creature == this) { + if (creature == getCreature()) { SpectatorVec players; g_game.map.getSpectators(players, getPosition(), true, true); for (const auto& player : players) { - assert(dynamic_cast(player) != nullptr); - spectators.insert(static_cast(player)); + assert(std::dynamic_pointer_cast(player) != nullptr); + spectators.insert(std::static_pointer_cast(player)); } const bool hasSpectators = !spectators.empty(); @@ -255,7 +255,7 @@ void Npc::onCreatureAppear(Creature* creature, bool isLogin) if (npcEventHandler) { npcEventHandler->onCreatureAppear(creature); } - } else if (Player* player = creature->getPlayer()) { + } else if (const auto& player = creature->getPlayer()) { if (npcEventHandler) { npcEventHandler->onCreatureAppear(creature); } @@ -265,16 +265,16 @@ void Npc::onCreatureAppear(Creature* creature, bool isLogin) } } -void Npc::onRemoveCreature(Creature* creature, bool isLogout) +void Npc::onRemoveCreature(const CreaturePtr& creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); - if (creature == this) { + if (creature == this->getCreature()) { closeAllShopWindows(); if (npcEventHandler) { npcEventHandler->onCreatureDisappear(creature); } - } else if (Player* player = creature->getPlayer()) { + } else if (const auto player = creature->getPlayer()) { if (npcEventHandler) { npcEventHandler->onCreatureDisappear(creature); } @@ -284,18 +284,18 @@ void Npc::onRemoveCreature(Creature* creature, bool isLogout) } } -void Npc::onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, - const Tile* oldTile, const Position& oldPos, bool teleport) +void Npc::onCreatureMove(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, + const TilePtr& oldTile, const Position& oldPos, bool teleport) { Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); - if (creature == this || creature->getPlayer()) { + if (creature == getCreature() || creature->getPlayer()) { if (npcEventHandler) { npcEventHandler->onCreatureMove(creature, oldPos, newPos); } - if (creature != this) { - Player* player = creature->getPlayer(); + if (creature != this->getCreature()) { + const auto& player = creature->getPlayer(); // if player is now in range, add to spectators list, otherwise erase if (player->canSee(position)) { @@ -309,29 +309,28 @@ void Npc::onCreatureMove(Creature* creature, const Tile* newTile, const Position } } -void Npc::onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) +void Npc::onCreatureSay(const CreaturePtr& creature, SpeakClasses type, const std::string& text) { - if (creature == this) { + if (creature == this->getCreature()) { return; } //only players for script events - Player* player = creature->getPlayer(); - if (player) { + if (const auto& player = creature->getPlayer()) { if (npcEventHandler) { npcEventHandler->onCreatureSay(player, type, text); } } } -void Npc::onPlayerCloseChannel(Player* player) +void Npc::onPlayerCloseChannel(const PlayerPtr& player) const { if (npcEventHandler) { npcEventHandler->onPlayerCloseChannel(player); } } -void Npc::onThink(uint32_t interval) +void Npc::onThink(const uint32_t interval) { Creature::onThink(interval); @@ -346,19 +345,19 @@ void Npc::onThink(uint32_t interval) void Npc::doSay(const std::string& text) { - g_game.internalCreatureSay(this, TALKTYPE_SAY, text, false); + g_game.internalCreatureSay(this->getNpc(), TALKTYPE_SAY, text, false); } -void Npc::doSayToPlayer(Player* player, const std::string& text) +void Npc::doSayToPlayer(const PlayerPtr& player, const std::string& text) { if (player) { - player->sendCreatureSay(this, TALKTYPE_PRIVATE_NP, text); - player->onCreatureSay(this, TALKTYPE_PRIVATE_NP, text); + player->sendCreatureSay(this->getNpc(), TALKTYPE_PRIVATE_NP, text); + player->onCreatureSay(this->getNpc(), TALKTYPE_PRIVATE_NP, text); } } -void Npc::onPlayerTrade(Player* player, int32_t callback, uint16_t itemId, uint8_t count, - uint8_t amount, bool ignore/* = false*/, bool inBackpacks/* = false*/) +void Npc::onPlayerTrade(const PlayerPtr& player, int32_t callback, uint16_t itemId, uint8_t count, + uint8_t amount, bool ignore/* = false*/, bool inBackpacks/* = false*/) const { if (npcEventHandler) { npcEventHandler->onPlayerTrade(player, callback, itemId, count, amount, ignore, inBackpacks); @@ -366,7 +365,7 @@ void Npc::onPlayerTrade(Player* player, int32_t callback, uint16_t itemId, uint8 player->sendSaleItemList(); } -void Npc::onPlayerEndTrade(Player* player, int32_t buyCallback, int32_t sellCallback) +void Npc::onPlayerEndTrade(const PlayerPtr& player, int32_t buyCallback, int32_t sellCallback) { lua_State* L = getScriptInterface()->getLuaState(); @@ -423,7 +422,7 @@ void Npc::setIdle(const bool idle) } } -bool Npc::canWalkTo(const Position& fromPos, Direction dir) const +bool Npc::canWalkTo(const Position& fromPos, Direction dir) { if (masterRadius == 0) { return false; @@ -434,8 +433,8 @@ bool Npc::canWalkTo(const Position& fromPos, Direction dir) const return false; } - Tile* tile = g_game.map.getTile(toPos); - if (!tile || tile->queryAdd(*this, 0) != RETURNVALUE_NOERROR) { + const auto& tile = g_game.map.getTile(toPos); + if (!tile || tile->queryAdd(this->getNpc(), 0) != RETURNVALUE_NOERROR) { return false; } @@ -450,11 +449,11 @@ bool Npc::canWalkTo(const Position& fromPos, Direction dir) const return true; } -bool Npc::getRandomStep(Direction& direction) const +bool Npc::getRandomStep(Direction& direction) { const Position& creaturePos = getPosition(); - for (Direction dir : getShuffleDirections()) { + for (const Direction dir : getShuffleDirections()) { if (canWalkTo(creaturePos, dir)) { direction = dir; return true; @@ -474,7 +473,7 @@ bool Npc::doMoveTo(const Position& pos, int32_t minTargetDist/* = 1*/, int32_t m return false; } -void Npc::turnToCreature(Creature* creature) +void Npc::turnToCreature(const CreaturePtr& creature) { const Position& creaturePos = creature->getPosition(); const Position& myPos = getPosition(); @@ -502,10 +501,10 @@ void Npc::turnToCreature(Creature* creature) dir = DIRECTION_SOUTH; } } - g_game.internalCreatureTurn(this, dir); + g_game.internalCreatureTurn(this->getNpc(), dir); } -void Npc::setCreatureFocus(Creature* creature) +void Npc::setCreatureFocus(const CreaturePtr& creature) { if (creature) { focusCreature = creature->getID(); @@ -515,12 +514,12 @@ void Npc::setCreatureFocus(Creature* creature) } } -void Npc::addShopPlayer(Player* player) +void Npc::addShopPlayer(const PlayerPtr& player) { shopPlayerSet.insert(player); } -void Npc::removeShopPlayer(Player* player) +void Npc::removeShopPlayer(const PlayerPtr& player) { shopPlayerSet.erase(player); } @@ -528,7 +527,7 @@ void Npc::removeShopPlayer(Player* player) void Npc::closeAllShopWindows() { while (!shopPlayerSet.empty()) { - Player* player = *shopPlayerSet.begin(); + const auto& player = *shopPlayerSet.begin(); if (!player->closeShopWindow()) { removeShopPlayer(player); } @@ -579,7 +578,7 @@ bool NpcScriptInterface::loadNpcLib(const std::string& file) return true; } -void NpcScriptInterface::registerFunctions() +void NpcScriptInterface::registerFunctions() const { //npc exclusive functions lua_register(luaState, "selfSay", NpcScriptInterface::luaActionSay); @@ -606,15 +605,14 @@ void NpcScriptInterface::registerFunctions() int NpcScriptInterface::luaActionSay(lua_State* L) { //selfSay(words[, target]) - Npc* npc = getScriptEnv()->getNpc(); + NpcPtr npc = getScriptEnv()->getNpc(); if (!npc) { return 0; } const std::string& text = getString(L, 1); if (lua_gettop(L) >= 2) { - Player* target = getPlayer(L, 2); - if (target) { + if (const auto& target = getPlayer(L, 2)) { npc->doSayToPlayer(target, text); return 0; } @@ -627,8 +625,7 @@ int NpcScriptInterface::luaActionSay(lua_State* L) int NpcScriptInterface::luaActionMove(lua_State* L) { //selfMove(direction) - Npc* npc = getScriptEnv()->getNpc(); - if (npc) { + if (auto npc = getScriptEnv()->getNpc()) { g_game.internalMoveCreature(npc, getNumber(L, 1)); } return 0; @@ -638,7 +635,7 @@ int NpcScriptInterface::luaActionMoveTo(lua_State* L) { //selfMoveTo(x, y, z[, minTargetDist = 1[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]]) //selfMoveTo(position[, minTargetDist = 1[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]]) - Npc* npc = getScriptEnv()->getNpc(); + NpcPtr npc = getScriptEnv()->getNpc(); if (!npc) { return 0; } @@ -668,7 +665,7 @@ int NpcScriptInterface::luaActionMoveTo(lua_State* L) int NpcScriptInterface::luaActionTurn(lua_State* L) { //selfTurn(direction) - Npc* npc = getScriptEnv()->getNpc(); + NpcPtr npc = getScriptEnv()->getNpc(); if (npc) { g_game.internalCreatureTurn(npc, getNumber(L, 1)); } @@ -678,7 +675,7 @@ int NpcScriptInterface::luaActionTurn(lua_State* L) int NpcScriptInterface::luaActionFollow(lua_State* L) { //selfFollow(player) - Npc* npc = getScriptEnv()->getNpc(); + NpcPtr npc = getScriptEnv()->getNpc(); if (!npc) { pushBoolean(L, false); return 1; @@ -693,16 +690,16 @@ int NpcScriptInterface::luagetDistanceTo(lua_State* L) //getDistanceTo(uid) ScriptEnvironment* env = getScriptEnv(); - Npc* npc = env->getNpc(); + const auto& npc = env->getNpc(); if (!npc) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_THING_NOT_FOUND)); lua_pushnil(L); return 1; } - uint32_t uid = getNumber(L, -1); + const uint32_t uid = getNumber(L, -1); - Thing* thing = env->getThingByUID(uid); + const auto& thing = env->getThingByUID(uid); if (!thing) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_THING_NOT_FOUND)); lua_pushnil(L); @@ -714,7 +711,7 @@ int NpcScriptInterface::luagetDistanceTo(lua_State* L) if (npcPos.z != thingPos.z) { lua_pushinteger(L, -1); } else { - int32_t dist = std::max(Position::getDistanceX(npcPos, thingPos), Position::getDistanceY(npcPos, thingPos)); + const int32_t dist = std::max(Position::getDistanceX(npcPos, thingPos), Position::getDistanceY(npcPos, thingPos)); lua_pushinteger(L, dist); } return 1; @@ -723,8 +720,7 @@ int NpcScriptInterface::luagetDistanceTo(lua_State* L) int NpcScriptInterface::luaSetNpcFocus(lua_State* L) { //doNpcSetCreatureFocus(cid) - Npc* npc = getScriptEnv()->getNpc(); - if (npc) { + if (const auto& npc = getScriptEnv()->getNpc()) { npc->setCreatureFocus(getCreature(L, -1)); } return 0; @@ -733,8 +729,7 @@ int NpcScriptInterface::luaSetNpcFocus(lua_State* L) int NpcScriptInterface::luaGetNpcCid(lua_State* L) { //getNpcCid() - Npc* npc = getScriptEnv()->getNpc(); - if (npc) { + if (const auto& npc = getScriptEnv()->getNpc()) { lua_pushinteger(L, npc->getID()); } else { lua_pushnil(L); @@ -745,7 +740,7 @@ int NpcScriptInterface::luaGetNpcCid(lua_State* L) int NpcScriptInterface::luaGetNpcParameter(lua_State* L) { //getNpcParameter(paramKey) - Npc* npc = getScriptEnv()->getNpc(); + const auto& npc = getScriptEnv()->getNpc(); if (!npc) { lua_pushnil(L); return 1; @@ -809,7 +804,7 @@ int NpcScriptInterface::luaOpenShopWindow(lua_State* L) } lua_pop(L, 1); - Player* player = getPlayer(L, -1); + const auto& player = getPlayer(L, -1); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -819,7 +814,7 @@ int NpcScriptInterface::luaOpenShopWindow(lua_State* L) //Close any eventual other shop window currently open. player->closeShopWindow(false); - Npc* npc = getScriptEnv()->getNpc(); + const auto& npc = getScriptEnv()->getNpc(); if (!npc) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -837,14 +832,14 @@ int NpcScriptInterface::luaOpenShopWindow(lua_State* L) int NpcScriptInterface::luaCloseShopWindow(lua_State* L) { //closeShopWindow(cid) - Npc* npc = getScriptEnv()->getNpc(); + const auto& npc = getScriptEnv()->getNpc(); if (!npc) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - Player* player = getPlayer(L, 1); + const auto& player = getPlayer(L, 1); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -854,7 +849,7 @@ int NpcScriptInterface::luaCloseShopWindow(lua_State* L) int32_t buyCallback; int32_t sellCallback; - Npc* merchant = player->getShopOwner(buyCallback, sellCallback); + const auto& merchant = player->getShopOwner(buyCallback, sellCallback); //Check if we actually have a shop window with this player. if (merchant == npc) { @@ -879,7 +874,7 @@ int NpcScriptInterface::luaCloseShopWindow(lua_State* L) int NpcScriptInterface::luaDoSellItem(lua_State* L) { //doSellItem(cid, itemid, amount, subtype, actionid, canDropOnMap) - Player* player = getPlayer(L, 1); + const auto& player = getPlayer(L, 1); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -888,7 +883,7 @@ int NpcScriptInterface::luaDoSellItem(lua_State* L) uint32_t sellCount = 0; - uint32_t itemId = getNumber(L, 2); + const uint32_t itemId = getNumber(L, 2); uint32_t amount = getNumber(L, 3); uint32_t subType; @@ -899,20 +894,19 @@ int NpcScriptInterface::luaDoSellItem(lua_State* L) subType = 1; } - uint32_t actionId = getNumber(L, 5, 0); + const uint32_t actionId = getNumber(L, 5, 0); bool canDropOnMap = getBoolean(L, 6, true); const ItemType& it = Item::items[itemId]; if (it.stackable) { while (amount > 0) { int32_t stackCount = std::min(100, amount); - Item* item = Item::CreateItem(it.id, stackCount); + const auto& item = Item::CreateItem(it.id, stackCount); if (item && actionId != 0) { item->setActionId(actionId); } if (g_game.internalPlayerAddItem(player, item, canDropOnMap) != RETURNVALUE_NOERROR) { - delete item; lua_pushinteger(L, sellCount); return 1; } @@ -922,13 +916,12 @@ int NpcScriptInterface::luaDoSellItem(lua_State* L) } } else { for (uint32_t i = 0; i < amount; ++i) { - Item* item = Item::CreateItem(it.id, subType); + const auto& item = Item::CreateItem(it.id, subType); if (item && actionId != 0) { item->setActionId(actionId); } if (g_game.internalPlayerAddItem(player, item, canDropOnMap) != RETURNVALUE_NOERROR) { - delete item; lua_pushinteger(L, sellCount); return 1; } @@ -945,9 +938,8 @@ int NpcScriptInterface::luaNpcGetParameter(lua_State* L) { // npc:getParameter(key) const std::string& key = getString(L, 2); - Npc* npc = getUserdata(L, 1); - if (npc) { - auto it = npc->parameters.find(key); + if (const auto& npc = getSharedPtr(L, 1)) { + const auto it = npc->parameters.find(key); if (it != npc->parameters.end()) { pushString(L, it->second); } else { @@ -962,9 +954,8 @@ int NpcScriptInterface::luaNpcGetParameter(lua_State* L) int NpcScriptInterface::luaNpcSetFocus(lua_State* L) { // npc:setFocus(creature) - Creature* creature = getCreature(L, 2); - Npc* npc = getUserdata(L, 1); - if (npc) { + const auto& creature = getCreature(L, 2); + if (const auto& npc = getSharedPtr(L, 1)) { npc->setCreatureFocus(creature); pushBoolean(L, true); } else { @@ -982,14 +973,14 @@ int NpcScriptInterface::luaNpcOpenShopWindow(lua_State* L) return 1; } - Player* player = getPlayer(L, 2); + const auto& player = getPlayer(L, 2); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); return 1; } - Npc* npc = getUserdata(L, 1); + const auto& npc = getSharedPtr(L, 1); if (!npc) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1042,14 +1033,14 @@ int NpcScriptInterface::luaNpcOpenShopWindow(lua_State* L) int NpcScriptInterface::luaNpcCloseShopWindow(lua_State* L) { // npc:closeShopWindow(player) - Player* player = getPlayer(L, 2); + const auto& player = getPlayer(L, 2); if (!player) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); return 1; } - Npc* npc = getUserdata(L, 1); + const auto& npc = getSharedPtr(L, 1); if (!npc) { reportErrorFunc(L, getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1059,7 +1050,7 @@ int NpcScriptInterface::luaNpcCloseShopWindow(lua_State* L) int32_t buyCallback; int32_t sellCallback; - Npc* merchant = player->getShopOwner(buyCallback, sellCallback); + const auto& merchant = player->getShopOwner(buyCallback, sellCallback); if (merchant == npc) { player->sendCloseShop(); if (buyCallback != -1) { @@ -1078,8 +1069,8 @@ int NpcScriptInterface::luaNpcCloseShopWindow(lua_State* L) return 1; } -NpcEventsHandler::NpcEventsHandler(const std::string& file, Npc* npc) : - scriptInterface(std::make_unique()), npc(npc) +NpcEventsHandler::NpcEventsHandler(const std::string& file, const NpcPtr& og) : + scriptInterface(std::make_unique()) { if (!scriptInterface->loadNpcLib("data/npc/lib/npc.lua")) { std::cout << "[Warning - NpcLib::NpcLib] Can not load lib: " << file << std::endl; @@ -1099,6 +1090,7 @@ NpcEventsHandler::NpcEventsHandler(const std::string& file, Npc* npc) : playerEndTradeEvent = scriptInterface->getEvent("onPlayerEndTrade"); thinkEvent = scriptInterface->getEvent("onThink"); } + npc = og; } bool NpcEventsHandler::isLoaded() const @@ -1106,7 +1098,7 @@ bool NpcEventsHandler::isLoaded() const return loaded; } -void NpcEventsHandler::onCreatureAppear(Creature* creature) +void NpcEventsHandler::onCreatureAppear(const CreaturePtr& creature) { if (creatureAppearEvent == -1) { return; @@ -1124,12 +1116,12 @@ void NpcEventsHandler::onCreatureAppear(Creature* creature) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(creatureAppearEvent); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); scriptInterface->callFunction(1); } -void NpcEventsHandler::onCreatureDisappear(Creature* creature) +void NpcEventsHandler::onCreatureDisappear(const CreaturePtr& creature) { if (creatureDisappearEvent == -1) { return; @@ -1147,12 +1139,12 @@ void NpcEventsHandler::onCreatureDisappear(Creature* creature) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(creatureDisappearEvent); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); scriptInterface->callFunction(1); } -void NpcEventsHandler::onCreatureMove(Creature* creature, const Position& oldPos, const Position& newPos) +void NpcEventsHandler::onCreatureMove(const CreaturePtr& creature, const Position& oldPos, const Position& newPos) { if (creatureMoveEvent == -1) { return; @@ -1170,14 +1162,14 @@ void NpcEventsHandler::onCreatureMove(Creature* creature, const Position& oldPos lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(creatureMoveEvent); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushPosition(L, oldPos); LuaScriptInterface::pushPosition(L, newPos); scriptInterface->callFunction(3); } -void NpcEventsHandler::onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) +void NpcEventsHandler::onCreatureSay(const CreaturePtr& creature, SpeakClasses type, const std::string& text) { if (creatureSayEvent == -1) { return; @@ -1195,14 +1187,14 @@ void NpcEventsHandler::onCreatureSay(Creature* creature, SpeakClasses type, cons lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(creatureSayEvent); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); lua_pushinteger(L, type); LuaScriptInterface::pushString(L, text); scriptInterface->callFunction(3); } -void NpcEventsHandler::onPlayerTrade(Player* player, int32_t callback, uint16_t itemId, +void NpcEventsHandler::onPlayerTrade(const PlayerPtr& player, int32_t callback, uint16_t itemId, uint8_t count, uint8_t amount, bool ignore, bool inBackpacks) { if (callback == -1) { @@ -1221,7 +1213,7 @@ void NpcEventsHandler::onPlayerTrade(Player* player, int32_t callback, uint16_t lua_State* L = scriptInterface->getLuaState(); LuaScriptInterface::pushCallback(L, callback); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); lua_pushinteger(L, itemId); lua_pushinteger(L, count); @@ -1231,7 +1223,7 @@ void NpcEventsHandler::onPlayerTrade(Player* player, int32_t callback, uint16_t scriptInterface->callFunction(6); } -void NpcEventsHandler::onPlayerCloseChannel(Player* player) +void NpcEventsHandler::onPlayerCloseChannel(const PlayerPtr& player) { if (playerCloseChannelEvent == -1) { return; @@ -1249,12 +1241,12 @@ void NpcEventsHandler::onPlayerCloseChannel(Player* player) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(playerCloseChannelEvent); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); scriptInterface->callFunction(1); } -void NpcEventsHandler::onPlayerEndTrade(Player* player) +void NpcEventsHandler::onPlayerEndTrade(const PlayerPtr& player) { if (playerEndTradeEvent == -1) { return; @@ -1272,7 +1264,7 @@ void NpcEventsHandler::onPlayerEndTrade(Player* player) lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(playerEndTradeEvent); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); scriptInterface->callFunction(1); } diff --git a/src/npc.h b/src/npc.h index c0c8b1a9..092eec05 100644 --- a/src/npc.h +++ b/src/npc.h @@ -26,7 +26,7 @@ class NpcScriptInterface final : public LuaScriptInterface bool loadNpcLib(const std::string& file); private: - void registerFunctions(); + void registerFunctions() const; static int luaActionSay(lua_State* L); static int luaActionMove(lua_State* L); @@ -58,24 +58,24 @@ class NpcScriptInterface final : public LuaScriptInterface class NpcEventsHandler { public: - NpcEventsHandler(const std::string& file, Npc* npc); + NpcEventsHandler(const std::string& file, const NpcPtr& npc); std::unique_ptr scriptInterface; - void onCreatureAppear(Creature* creature); - void onCreatureDisappear(Creature* creature); - void onCreatureMove(Creature* creature, const Position& oldPos, const Position& newPos); - void onCreatureSay(Creature* creature, SpeakClasses, const std::string& text); - void onPlayerTrade(Player* player, int32_t callback, uint16_t itemId, uint8_t count, uint8_t amount, bool ignore = false, bool inBackpacks = false); - void onPlayerCloseChannel(Player* player); - void onPlayerEndTrade(Player* player); + void onCreatureAppear(const CreaturePtr& creature); + void onCreatureDisappear(const CreaturePtr& creature); + void onCreatureMove(const CreaturePtr& creature, const Position& oldPos, const Position& newPos); + void onCreatureSay(const CreaturePtr& creature, SpeakClasses, const std::string& text); + void onPlayerTrade(const PlayerPtr& player, int32_t callback, uint16_t itemId, uint8_t count, uint8_t amount, bool ignore = false, bool inBackpacks = false); + void onPlayerCloseChannel(const PlayerPtr& player); + void onPlayerEndTrade(const PlayerPtr& player); void onThink(); bool isLoaded() const; private: - Npc* npc; + NpcPtr npc; int32_t creatureAppearEvent = -1; int32_t creatureDisappearEvent = -1; int32_t creatureMoveEvent = -1; @@ -89,17 +89,19 @@ class NpcEventsHandler class Npc final : public Creature { public: - ~Npc(); + explicit Npc(const std::string& name); + ~Npc() override; // non-copyable Npc(const Npc&) = delete; Npc& operator=(const Npc&) = delete; - Npc* getNpc() override { - return this; + NpcPtr getNpc() override { + return dynamic_shared_this(); } - const Npc* getNpc() const override { - return this; + + NpcConstPtr getNpc() const override { + return dynamic_shared_this(); } bool isPushable() const override { @@ -115,7 +117,7 @@ class Npc final : public Creature void removeList() override; void addList() override; - static Npc* createNpc(const std::string& name); + static NpcPtr createNpc(const std::string& name); bool canSee(const Position& pos) const override; @@ -125,6 +127,7 @@ class Npc final : public Creature const std::string& getName() const override { return name; } + const std::string& getNameDescription() const override { return name; } @@ -136,6 +139,7 @@ class Npc final : public Creature uint8_t getSpeechBubble() const override { return speechBubble; } + void setSpeechBubble(const uint8_t bubble) { speechBubble = bubble; } @@ -145,7 +149,7 @@ class Npc final : public Creature } void doSay(const std::string& text); - void doSayToPlayer(Player* player, const std::string& text); + void doSayToPlayer(const PlayerPtr& player, const std::string& text); bool doMoveTo(const Position& pos, int32_t minTargetDist = 1, int32_t maxTargetDist = 1, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 0); @@ -153,9 +157,11 @@ class Npc final : public Creature int32_t getMasterRadius() const { return masterRadius; } + const Position& getMasterPos() const { return masterPos; } + void setMasterPos(Position pos, int32_t radius = 1) { masterPos = pos; if (masterRadius == -1) { @@ -163,57 +169,60 @@ class Npc final : public Creature } } - void onPlayerCloseChannel(Player* player); - void onPlayerTrade(Player* player, int32_t callback, uint16_t itemId, uint8_t count, - uint8_t amount, bool ignore = false, bool inBackpacks = false); - void onPlayerEndTrade(Player* player, int32_t buyCallback, int32_t sellCallback); + void onPlayerCloseChannel(const PlayerPtr& player) const; + void onPlayerTrade(const PlayerPtr& player, int32_t callback, uint16_t itemId, uint8_t count, + uint8_t amount, bool ignore = false, bool inBackpacks = false) const; + void onPlayerEndTrade(const PlayerPtr& player, int32_t buyCallback, int32_t sellCallback); - void turnToCreature(Creature* creature); - void setCreatureFocus(Creature* creature); + void turnToCreature(const CreaturePtr& creature); + void setCreatureFocus(const CreaturePtr& creature); - auto& getScriptInterface() { return npcEventHandler->scriptInterface; } + auto& getScriptInterface() const { return npcEventHandler->scriptInterface; } static uint32_t npcAutoID; private: - explicit Npc(const std::string& name); + - 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 onCreatureAppear(const CreaturePtr& creature, bool isLogin) override; + void onRemoveCreature(const CreaturePtr& creature, bool isLogout) override; + void onCreatureMove(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, + const TilePtr& oldTile, const Position& oldPos, bool teleport) override; - void onCreatureSay(Creature* creature, SpeakClasses type, const std::string& text) override; + void onCreatureSay(const CreaturePtr& creature, SpeakClasses type, const std::string& text) override; void onThink(uint32_t interval) override; std::string getDescription(int32_t lookDistance) const override; bool isImmune(CombatType_t) const override { return !attackable; } + bool isImmune(ConditionType_t) const override { return !attackable; } + bool isAttackable() const override { return attackable; } + bool getNextStep(Direction& dir, uint32_t& flags) override; void setIdle(const bool idle); - bool canWalkTo(const Position& fromPos, Direction dir) const; - bool getRandomStep(Direction& direction) const; + bool canWalkTo(const Position& fromPos, Direction dir); + bool getRandomStep(Direction& direction); void reset(); bool loadFromXml(); - void addShopPlayer(Player* player); - void removeShopPlayer(Player* player); + void addShopPlayer(const PlayerPtr& player); + void removeShopPlayer(const PlayerPtr& player); void closeAllShopWindows(); std::map parameters; - std::set shopPlayerSet; - std::set spectators; + std::set shopPlayerSet; + std::set spectators; std::string name; std::string filename; diff --git a/src/party.cpp b/src/party.cpp index 5c2f6923..e1fdde55 100644 --- a/src/party.cpp +++ b/src/party.cpp @@ -14,7 +14,7 @@ extern Game g_game; extern ConfigManager g_config; extern Events* g_events; -Party::Party(Player* leader) : leader(leader) +Party::Party(const PlayerPtr& leader) : leader(leader) { leader->setParty(this); } @@ -25,44 +25,44 @@ void Party::disband() return; } - Player* currentLeader = leader; + PlayerPtr currentLeader = leader; leader = nullptr; currentLeader->setParty(nullptr); currentLeader->sendClosePrivate(CHANNEL_PARTY); g_game.updatePlayerShield(currentLeader); - g_game.updatePlayerHelpers(*currentLeader); + g_game.updatePlayerHelpers(currentLeader); currentLeader->sendCreatureSkull(currentLeader); currentLeader->sendTextMessage(MESSAGE_INFO_DESCR, "Your party has been disbanded."); - for (Player* invitee : inviteList) { + for (const auto& invitee : inviteList) { invitee->removePartyInvitation(this); currentLeader->sendCreatureShield(invitee); } inviteList.clear(); - for (Player* member : memberList) { + for (const auto& member : memberList) { member->setParty(nullptr); member->sendClosePrivate(CHANNEL_PARTY); member->sendTextMessage(MESSAGE_INFO_DESCR, "Your party has been disbanded."); } - for (Player* member : memberList) { + for (const auto& member : memberList) { g_game.updatePlayerShield(member); - for (Player* otherMember : memberList) { + for (const auto& otherMember : memberList) { otherMember->sendCreatureSkull(member); } member->sendCreatureSkull(currentLeader); currentLeader->sendCreatureSkull(member); - g_game.updatePlayerHelpers(*member); + g_game.updatePlayerHelpers(member); } memberList.clear(); delete this; } -bool Party::leaveParty(Player* player, bool forceRemove /* = false */) +bool Party::leaveParty(const PlayerPtr& player, bool forceRemove /* = false */) { if (!player) { return false; @@ -91,20 +91,19 @@ bool Party::leaveParty(Player* player, bool forceRemove /* = false */) } //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()) { + if (const auto& it = std::ranges::find(memberList, player); it != memberList.end()) { memberList.erase(it); } player->setParty(nullptr); player->sendClosePrivate(CHANNEL_PARTY); g_game.updatePlayerShield(player); - g_game.updatePlayerHelpers(*player); + g_game.updatePlayerHelpers(player); - for (Player* member : memberList) { + for (const auto& member : memberList) { member->sendCreatureSkull(player); player->sendPlayerPartyIcons(member); - g_game.updatePlayerHelpers(*member); + g_game.updatePlayerHelpers(member); } leader->sendCreatureSkull(player); @@ -125,7 +124,7 @@ bool Party::leaveParty(Player* player, bool forceRemove /* = false */) return true; } -bool Party::passPartyLeadership(Player* player, bool forceRemove /* = false*/) +bool Party::passPartyLeadership(const PlayerPtr& player, bool forceRemove /* = false*/) { if (!player || leader == player || player->getParty() != this) { return false; @@ -136,26 +135,25 @@ bool Party::passPartyLeadership(Player* player, bool forceRemove /* = false*/) } //Remove it before to broadcast the message correctly - auto it = std::find(memberList.begin(), memberList.end(), player); - if (it != memberList.end()) { + if (const auto it = std::ranges::find(memberList, player); it != memberList.end()) { memberList.erase(it); } broadcastPartyMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} is now the leader of the party.", player->getName()), true); - Player* oldLeader = leader; + PlayerPtr oldLeader = leader; leader = player; memberList.insert(memberList.begin(), oldLeader); updateSharedExperience(); - for (Player* member : memberList) { + for (const auto& member : memberList) { member->sendCreatureShield(oldLeader); member->sendCreatureShield(leader); } - for (Player* invitee : inviteList) { + for (const auto& invitee : inviteList) { invitee->sendCreatureShield(oldLeader); invitee->sendCreatureShield(leader); } @@ -167,124 +165,124 @@ bool Party::passPartyLeadership(Player* player, bool forceRemove /* = false*/) return true; } -bool Party::joinParty(Player& player) +bool Party::joinParty(const PlayerPtr& player) { - if (!g_events->eventPartyOnJoin(this, &player)) { + if (!g_events->eventPartyOnJoin(this, player)) { return false; } - auto it = std::find(inviteList.begin(), inviteList.end(), &player); + const auto it = std::find(inviteList.begin(), inviteList.end(), player); if (it == inviteList.end()) { return false; } inviteList.erase(it); - broadcastPartyMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has joined the party.", player.getName())); + broadcastPartyMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has joined the party.", player->getName())); - player.setParty(this); + player->setParty(this); - g_game.updatePlayerShield(&player); + g_game.updatePlayerShield(player); - for (Player* member : memberList) { - member->sendCreatureSkull(&player); - player.sendPlayerPartyIcons(member); + for (const auto& member : memberList) { + member->sendCreatureSkull(player); + player->sendPlayerPartyIcons(member); } - player.sendCreatureSkull(&player); - leader->sendCreatureSkull(&player); - player.sendPlayerPartyIcons(leader); + player->sendCreatureSkull(player); + leader->sendCreatureSkull(player); + player->sendPlayerPartyIcons(leader); - memberList.push_back(&player); + memberList.push_back(player); g_game.updatePlayerHelpers(player); - player.removePartyInvitation(this); + player->removePartyInvitation(this); updateSharedExperience(); const std::string& leaderName = leader->getName(); - player.sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("You have joined {:s}'{:s} party. Open the party channel to communicate with your companions.", leaderName, leaderName.back() == 's' ? "" : "s")); + player->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("You have joined {:s}'{:s} party. Open the party channel to communicate with your companions.", leaderName, leaderName.back() == 's' ? "" : "s")); return true; } -bool Party::removeInvite(Player& player, bool removeFromPlayer/* = true*/) +bool Party::removeInvite(const PlayerPtr& player, bool removeFromPlayer/* = true*/) { - auto it = std::find(inviteList.begin(), inviteList.end(), &player); + const auto it = std::find(inviteList.begin(), inviteList.end(), player); if (it == inviteList.end()) { return false; } inviteList.erase(it); - leader->sendCreatureShield(&player); - player.sendCreatureShield(leader); + leader->sendCreatureShield(player); + player->sendCreatureShield(leader); if (removeFromPlayer) { - player.removePartyInvitation(this); + player->removePartyInvitation(this); } if (empty()) { disband(); } else { - for (Player* member : memberList) { - g_game.updatePlayerHelpers(*member); + for (const auto& member : memberList) { + g_game.updatePlayerHelpers(member); } - g_game.updatePlayerHelpers(*leader); + g_game.updatePlayerHelpers(leader); } return true; } -void Party::revokeInvitation(Player& player) +void Party::revokeInvitation(const PlayerPtr& player) { - if (!g_events->eventPartyOnRevokeInvitation(this, &player)) { + if (!g_events->eventPartyOnRevokeInvitation(this, player)) { return; } - player.sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has revoked {:s} invitation.", leader->getName(), leader->getSex() == PLAYERSEX_FEMALE ? "her" : "his")); - leader->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("Invitation for {:s} has been revoked.", player.getName())); + player->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has revoked {:s} invitation.", leader->getName(), leader->getSex() == PLAYERSEX_FEMALE ? "her" : "his")); + leader->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("Invitation for {:s} has been revoked.", player->getName())); removeInvite(player); } -bool Party::invitePlayer(Player& player) +bool Party::invitePlayer(const PlayerPtr& player) { - if (isPlayerInvited(&player)) { + if (isPlayerInvited(player)) { return false; } if (empty()) { - leader->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been invited. Open the party channel to communicate with your members.", player.getName())); + leader->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been invited. Open the party channel to communicate with your members.", player->getName())); g_game.updatePlayerShield(leader); leader->sendCreatureSkull(leader); } else { - leader->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been invited.", player.getName())); + leader->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has been invited.", player->getName())); } - inviteList.push_back(&player); + inviteList.push_back(player); - for (Player* member : memberList) { - g_game.updatePlayerHelpers(*member); + for (const auto& member : memberList) { + g_game.updatePlayerHelpers(member); } - g_game.updatePlayerHelpers(*leader); + g_game.updatePlayerHelpers(leader); - leader->sendCreatureShield(&player); - player.sendCreatureShield(leader); + leader->sendCreatureShield(player); + player->sendCreatureShield(leader); - player.addPartyInvitation(this); + player->addPartyInvitation(this); - player.sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has invited you to {:s} party.", leader->getName(), leader->getSex() == PLAYERSEX_FEMALE ? "her" : "his")); + player->sendTextMessage(MESSAGE_INFO_DESCR, fmt::format("{:s} has invited you to {:s} party.", leader->getName(), leader->getSex() == PLAYERSEX_FEMALE ? "her" : "his")); return true; } -bool Party::isPlayerInvited(const Player* player) const +bool Party::isPlayerInvited(const PlayerConstPtr& player) const { - return std::find(inviteList.begin(), inviteList.end(), player) != inviteList.end(); + return std::ranges::find(inviteList, player) != inviteList.end(); } void Party::updateAllPartyIcons() { - for (Player* member : memberList) { - for (Player* otherMember : memberList) { + for (const auto& member : memberList) { + for (const auto& otherMember : memberList) { member->sendCreatureShield(otherMember); } @@ -294,16 +292,16 @@ void Party::updateAllPartyIcons() leader->sendCreatureShield(leader); } -void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string& msg, bool sendToInvitations /*= false*/) +void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string& msg, bool sendToInvitations /*= false*/) const { - for (Player* member : memberList) { + for (const auto& member : memberList) { member->sendTextMessage(msgClass, msg); } leader->sendTextMessage(msgClass, msg); if (sendToInvitations) { - for (Player* invitee : inviteList) { + for (const auto& invitee : inviteList) { invitee->sendTextMessage(msgClass, msg); } } @@ -342,7 +340,7 @@ const char* getSharedExpReturnMessage(SharedExpStatus_t value) } -bool Party::setSharedExperience(Player* player, bool sharedExpActive) +bool Party::setSharedExperience(const PlayerPtr& player, bool sharedExpActive) { if (!player || leader != player) { return false; @@ -355,7 +353,7 @@ bool Party::setSharedExperience(Player* player, bool sharedExpActive) this->sharedExpActive = sharedExpActive; if (sharedExpActive) { - SharedExpStatus_t sharedExpStatus = getSharedExperienceStatus(); + const SharedExpStatus_t sharedExpStatus = getSharedExperienceStatus(); this->sharedExpEnabled = sharedExpStatus == SHAREDEXP_OK; leader->sendTextMessage(MESSAGE_INFO_DESCR, getSharedExpReturnMessage(sharedExpStatus)); } else { @@ -366,30 +364,30 @@ bool Party::setSharedExperience(Player* player, bool sharedExpActive) return true; } -void Party::shareExperience(uint64_t experience, Creature* source/* = nullptr*/) +void Party::shareExperience(const uint64_t experience, const CreaturePtr& source/* = nullptr*/) { uint64_t shareExperience = experience; g_events->eventPartyOnShareExperience(this, shareExperience); - for (Player* member : memberList) { + for (const auto& member : memberList) { member->onGainSharedExperience(shareExperience, source); } leader->onGainSharedExperience(shareExperience, source); } -bool Party::canUseSharedExperience(const Player* player) const +bool Party::canUseSharedExperience(const PlayerConstPtr& player) const { return getMemberSharedExperienceStatus(player) == SHAREDEXP_OK; } -SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) const +SharedExpStatus_t Party::getMemberSharedExperienceStatus(const PlayerConstPtr& player) const { if (memberList.empty()) { return SHAREDEXP_EMPTYPARTY; } uint32_t highestLevel = leader->getLevel(); - for (Player* member : memberList) { + for (const auto& member : memberList) { if (member->getLevel() > highestLevel) { highestLevel = member->getLevel(); } @@ -406,7 +404,7 @@ SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) c if (!player->hasFlag(PlayerFlag_NotGainInFight)) { //check if the player has healed/attacked anything recently - auto it = ticksMap.find(player->getID()); + const auto it = ticksMap.find(player->getID()); if (it == ticksMap.end()) { return SHAREDEXP_MEMBERINACTIVE; } @@ -419,14 +417,14 @@ SharedExpStatus_t Party::getMemberSharedExperienceStatus(const Player* player) c return SHAREDEXP_OK; } -SharedExpStatus_t Party::getSharedExperienceStatus() +SharedExpStatus_t Party::getSharedExperienceStatus() const { SharedExpStatus_t leaderStatus = getMemberSharedExperienceStatus(leader); if (leaderStatus != SHAREDEXP_OK) { return leaderStatus; } - for (Player* member : memberList) { + for (const auto& member : memberList) { SharedExpStatus_t memberStatus = getMemberSharedExperienceStatus(member); if (memberStatus != SHAREDEXP_OK) { return memberStatus; @@ -435,7 +433,7 @@ SharedExpStatus_t Party::getSharedExperienceStatus() return SHAREDEXP_OK; } -void Party::updatePlayerTicks(Player* player, uint32_t points) +void Party::updatePlayerTicks(const PlayerPtr& player, const uint32_t points) { if (points != 0 && !player->hasFlag(PlayerFlag_NotGainInFight)) { ticksMap[player->getID()] = OTSYS_TIME(); @@ -443,18 +441,17 @@ void Party::updatePlayerTicks(Player* player, uint32_t points) } } -void Party::clearPlayerPoints(Player* player) +void Party::clearPlayerPoints(const PlayerPtr& player) { - auto it = ticksMap.find(player->getID()); - if (it != ticksMap.end()) { + if (const auto it = ticksMap.find(player->getID()); it != ticksMap.end()) { ticksMap.erase(it); updateSharedExperience(); } } -bool Party::canOpenCorpse(uint32_t ownerId) const +bool Party::canOpenCorpse(const uint32_t ownerId) const { - if (Player* player = g_game.getPlayerByID(ownerId)) { + if (const auto& player = g_game.getPlayerByID(ownerId)) { return leader->getID() == ownerId || player->getParty() == this; } return false; diff --git a/src/party.h b/src/party.h index 66639ae3..08027883 100644 --- a/src/party.h +++ b/src/party.h @@ -10,7 +10,7 @@ class Player; class Party; -using PlayerVector = std::vector; +using PlayerVector = std::vector; static constexpr int32_t EXPERIENCE_SHARE_RANGE = 30; static constexpr int32_t EXPERIENCE_SHARE_FLOORS = 1; @@ -26,65 +26,74 @@ enum SharedExpStatus_t : uint8_t { class Party { public: - explicit Party(Player* leader); + explicit Party(const PlayerPtr& leader); - Player* getLeader() const { + PlayerPtr getLeader() const { return leader; } + PlayerVector& getMembers() { return memberList; } + const PlayerVector& getInvitees() const { return inviteList; } + size_t getMemberCount() const { return memberList.size(); } + size_t getInvitationCount() const { return inviteList.size(); } void disband(); - bool invitePlayer(Player& player); - bool joinParty(Player& player); - void revokeInvitation(Player& player); - bool passPartyLeadership(Player* player, bool forceRemove = false); - bool leaveParty(Player* player, bool forceRemove = false); + bool invitePlayer(const PlayerPtr& player); + bool joinParty(const PlayerPtr& player); + void revokeInvitation(const PlayerPtr& player); + bool passPartyLeadership(const PlayerPtr& player, bool forceRemove = false); + bool leaveParty(const PlayerPtr& player, bool forceRemove = false); - bool removeInvite(Player& player, bool removeFromPlayer = true); + bool removeInvite(const PlayerPtr& player, bool removeFromPlayer = true); - bool isPlayerInvited(const Player* player) const; + bool isPlayerInvited(const PlayerConstPtr& 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) const; + bool empty() const { return memberList.empty() && inviteList.empty(); } + bool canOpenCorpse(uint32_t ownerId) const; - void shareExperience(uint64_t experience, Creature* source = nullptr); - bool setSharedExperience(Player* player, bool sharedExpActive); + void shareExperience(uint64_t experience, const CreaturePtr& source = nullptr); + bool setSharedExperience(const PlayerPtr& player, bool sharedExpActive); + bool isSharedExperienceActive() const { return sharedExpActive; } + bool isSharedExperienceEnabled() const { return sharedExpEnabled; } - bool canUseSharedExperience(const Player* player) const; - SharedExpStatus_t getMemberSharedExperienceStatus(const Player* player) const; + + bool canUseSharedExperience(const PlayerConstPtr& player) const; + SharedExpStatus_t getMemberSharedExperienceStatus(const PlayerConstPtr& player) const; void updateSharedExperience(); - void updatePlayerTicks(Player* player, uint32_t points); - void clearPlayerPoints(Player* player); + void updatePlayerTicks(const PlayerPtr& player, uint32_t points); + void clearPlayerPoints(const PlayerPtr& player); private: - SharedExpStatus_t getSharedExperienceStatus(); + SharedExpStatus_t getSharedExperienceStatus() const; std::map ticksMap; PlayerVector memberList; PlayerVector inviteList; - Player* leader; + PlayerPtr leader; bool sharedExpActive = false; bool sharedExpEnabled = false; diff --git a/src/player.cpp b/src/player.cpp index 534d2ffe..28376a84 100644 --- a/src/player.cpp +++ b/src/player.cpp @@ -680,39 +680,32 @@ static std::vector GetDiaganolDeflectArea(uint32_t targets) { Player::Player(ProtocolGame_ptr p) : - Creature(), lastPing(OTSYS_TIME()), lastPong(lastPing), client(std::move(p)), inbox(new Inbox(ITEM_INBOX)), storeInbox(new StoreInbox(ITEM_STORE_INBOX)) + lastPing(OTSYS_TIME()), lastPong(lastPing), client(std::move(p)), inbox(std::make_shared(ITEM_INBOX)), storeInbox(std::make_shared(ITEM_STORE_INBOX)) { - inbox->incrementReferenceCounter(); - storeInbox->setParent(this); - storeInbox->incrementReferenceCounter(); } Player::~Player() { - for (Item* item : inventory) { + for (const auto& item : inventory) { if (item) { - item->setParent(nullptr); - item->decrementReferenceCounter(); + item->clearParent(); } } if (depotLocker) { depotLocker->removeInbox(inbox); } - - inbox->decrementReferenceCounter(); - - storeInbox->setParent(nullptr); - storeInbox->decrementReferenceCounter(); + + storeInbox->clearParent(); setWriteItem(nullptr); setEditHouse(nullptr); } -bool Player::setVocation(uint16_t vocId) +bool Player::setVocation(const uint16_t vocId) { - Vocation* voc = g_vocations.getVocation(vocId); + const auto& voc = g_vocations.getVocation(vocId); if (!voc) { return false; } @@ -721,7 +714,7 @@ bool Player::setVocation(uint16_t vocId) updateRegeneration(); setBaseSpeed(voc->getBaseSpeed()); updateBaseSpeed(); - g_game.changeSpeed(this, 0); + g_game.changeSpeed(this->getPlayer(), 0); return true; } @@ -733,7 +726,7 @@ bool Player::isPushable() const return Creature::isPushable(); } -std::string Player::getDescription(int32_t lookDistance) const +std::string Player::getDescription(const int32_t lookDistance) const { std::ostringstream s; @@ -819,7 +812,7 @@ std::string Player::getDescription(int32_t lookDistance) const return s.str(); } -Item* Player::getInventoryItem(slots_t slot) const +ItemPtr Player::getInventoryItem(const slots_t slot) const { if (slot < CONST_SLOT_FIRST || slot > CONST_SLOT_LAST) { return nullptr; @@ -827,7 +820,7 @@ Item* Player::getInventoryItem(slots_t slot) const return inventory[slot]; } -Item* Player::getInventoryItem(uint32_t slot) const +ItemPtr Player::getInventoryItem(const uint32_t slot) const { if (slot < CONST_SLOT_FIRST || slot > CONST_SLOT_LAST) { return nullptr; @@ -835,24 +828,24 @@ Item* Player::getInventoryItem(uint32_t slot) const return inventory[slot]; } -bool Player::isInventorySlot(slots_t slot) const +bool Player::isInventorySlot(const slots_t slot) { return slot >= CONST_SLOT_FIRST && slot <= CONST_SLOT_LAST; } -void Player::addConditionSuppressions(uint32_t conditions) +void Player::addConditionSuppressions(const uint32_t conditions) { conditionSuppressions |= conditions; } -void Player::removeConditionSuppressions(uint32_t conditions) +void Player::removeConditionSuppressions(const uint32_t conditions) { conditionSuppressions &= ~conditions; } -Item* Player::getWeapon(slots_t slot, bool ignoreAmmo) const +ItemPtr Player::getWeapon(const slots_t slot, const bool ignoreAmmo) const { - Item* item = inventory[slot]; + auto item = inventory[slot]; if (!item) { return nullptr; } @@ -865,11 +858,11 @@ Item* Player::getWeapon(slots_t slot, bool ignoreAmmo) const if (!ignoreAmmo && weaponType == WEAPON_DISTANCE) { const ItemType& itemType = Item::items[item->getID()]; if (itemType.ammoType != AMMO_NONE) { - Item* ammoItem = inventory[CONST_SLOT_AMMO]; + const auto& ammoItem = inventory[CONST_SLOT_AMMO]; if (!ammoItem || ammoItem->getAmmoType() != itemType.ammoType) { // no ammo item was found, search for quiver instead - Container* quiver = inventory[CONST_SLOT_RIGHT] ? inventory[CONST_SLOT_RIGHT]->getContainer() : nullptr; - if (!quiver || quiver->getWeaponType() != WEAPON_QUIVER) { + const auto& quiver = inventory[CONST_SLOT_RIGHT] ? inventory[CONST_SLOT_RIGHT]->getContainer() : nullptr; + if (!quiver || quiver->getItem()->getWeaponType() != WEAPON_QUIVER) { // no quiver equipped return nullptr; } @@ -877,8 +870,8 @@ Item* Player::getWeapon(slots_t slot, bool ignoreAmmo) const for (ContainerIterator containerItem = quiver->iterator(); containerItem.hasNext(); containerItem.advance()) { if (itemType.ammoType == (*containerItem)->getAmmoType()) { - const Weapon* weapon = g_weapons->getWeapon(*containerItem); - if (weapon && weapon->ammoCheck(this)) { + const auto& weapon = g_weapons->getWeapon(*containerItem); + if (weapon && weapon->ammoCheck(this->getPlayer())) { return *containerItem; } } @@ -893,30 +886,28 @@ Item* Player::getWeapon(slots_t slot, bool ignoreAmmo) const return item; } -Item* Player::getWeapon(bool ignoreAmmo/* = false*/) const +ItemPtr Player::getWeapon(bool ignoreAmmo/* = false*/) const { - Item* item = getWeapon(CONST_SLOT_LEFT, ignoreAmmo); - if (item) { - return item; + if (const auto& leftHandItem = getWeapon(CONST_SLOT_LEFT, ignoreAmmo)) { + return leftHandItem; } - - item = getWeapon(CONST_SLOT_RIGHT, ignoreAmmo); - if (item) { - return item; + + if (const auto& rightHandItem = getWeapon(CONST_SLOT_RIGHT, ignoreAmmo)) { + return rightHandItem; } return nullptr; } WeaponType_t Player::getWeaponType() const { - Item* item = getWeapon(); + const auto& item = getWeapon(); if (!item) { return WEAPON_NONE; } return item->getWeaponType(); } -int32_t Player::getWeaponSkill(const Item* item) const +int32_t Player::getWeaponSkill(const ItemConstPtr& item) const { if (!item) { return getSkillLevel(SKILL_FIST); @@ -924,7 +915,7 @@ int32_t Player::getWeaponSkill(const Item* item) const int32_t attackSkill; - WeaponType_t weaponType = item->getWeaponType(); + const WeaponType_t weaponType = item->getWeaponType(); switch (weaponType) { case WEAPON_SWORD: { attackSkill = getSkillLevel(SKILL_SWORD); @@ -958,62 +949,54 @@ 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 constexpr 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) { + if (const auto& inventoryItem = inventory[slot]) { armor += inventoryItem->getArmor(); } } return static_cast(armor * vocation->armorMultiplier); } -void Player::getShieldAndWeapon(const Item*& shield, const Item*& weapon) const -{ - shield = nullptr; - weapon = nullptr; - - for (uint32_t slot = CONST_SLOT_RIGHT; slot <= CONST_SLOT_LEFT; slot++) { - Item* item = inventory[slot]; - if (!item) { - continue; - } - - switch (item->getWeaponType()) { - case WEAPON_NONE: - break; - - case WEAPON_SHIELD: - case WEAPON_QUIVER: { - if (!shield || item->getDefense() > shield->getDefense()) { - shield = item; - } - break; - } - - default: { // weapons that are not shields - weapon = item; - break; - } - } - } -} - int32_t Player::getDefense() const { int32_t defenseSkill = getSkillLevel(SKILL_FIST); int32_t defenseValue = 7; - const Item* weapon; - const Item* shield; - getShieldAndWeapon(shield, weapon); - if (weapon) { - defenseValue = weapon->getDefense() + weapon->getExtraDefense(); - defenseSkill = getWeaponSkill(weapon); + std::optional leftHand = inventory[CONST_SLOT_LEFT]; + std::optional rightHand = inventory[CONST_SLOT_RIGHT]; + std::optional shield = std::nullopt; + std::optional weapon = std::nullopt; + + // We aren't going to waste precious CPU cycles or memory trying to determine which item + // has highest defense if you happen to have two shields, two quivers, or a shield + // and a quiver in each hand... in this case we are just gonna end up using left hand + // So if this is something that concerns you, you can go back to looping and using switches + // and storing variables to keep track of highest defense and do the math and all that yourself. + if (leftHand && (leftHand.value()->getWeaponType() == WEAPON_SHIELD || leftHand.value()->getWeaponType() == WEAPON_QUIVER)) + { + shield = leftHand.value(); + if (rightHand) + { + weapon = rightHand.value(); + } + } + else if (rightHand && (rightHand.value()->getWeaponType() == WEAPON_SHIELD || rightHand.value()->getWeaponType() == WEAPON_QUIVER)) + { + shield = rightHand.value(); + if (leftHand) + { + weapon = leftHand.value(); + } + } + + if (weapon.has_value()) { + defenseValue = weapon.value()->getDefense() + weapon.value()->getExtraDefense(); + defenseSkill = getWeaponSkill(weapon.value()); } - if (shield) { - defenseValue = weapon != nullptr ? shield->getDefense() + weapon->getExtraDefense() : shield->getDefense(); + if (shield.has_value()) { + defenseValue = weapon != nullptr ? shield.value()->getDefense() + weapon.value()->getExtraDefense() : shield.value()->getDefense(); defenseSkill = getSkillLevel(SKILL_SHIELD); } @@ -1033,7 +1016,7 @@ int32_t Player::getDefense() const uint32_t Player::getAttackSpeed() const { - const Item* weapon = getWeapon(true); + const auto& weapon = getWeapon(true); if (!weapon || weapon->getAttackSpeed() == 0) { return vocation->getAttackSpeed(); } @@ -1064,7 +1047,7 @@ float Player::getDefenseFactor() const uint16_t Player::getClientIcons() const { uint16_t icons = 0; - for (Condition* condition : conditions) { + for (const auto& condition : conditions) { if (!isSuppress(condition->getType())) { icons |= condition->getIcons(); } @@ -1074,7 +1057,7 @@ uint16_t Player::getClientIcons() const icons |= ICON_REDSWORDS; } - if (tile && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { + if (tile.lock() && tile.lock()->hasFlag(TILESTATE_PROTECTIONZONE)) { icons |= ICON_PIGEON; // Don't show ICON_SWORDS if player is in protection zone. @@ -1101,13 +1084,12 @@ void Player::updateInventoryWeight() inventoryWeight = 0; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const Item* item = inventory[i]; - if (item) { + if (const auto& item = inventory[i]) { inventoryWeight += item->getWeight(); } } - if (StoreInbox* storeInbox = getStoreInbox()) { + if (const auto& storeInbox = getStoreInbox()) { inventoryWeight += storeInbox->getWeight(); } } @@ -1121,7 +1103,7 @@ void Player::addSkillAdvance(skills_t skill, uint64_t count) return; } - g_events->eventPlayerOnGainSkillTries(this, skill, count); + g_events->eventPlayerOnGainSkillTries(this->getPlayer(), skill, count); if (count == 0) { return; } @@ -1135,7 +1117,7 @@ void Player::addSkillAdvance(skills_t skill, uint64_t count) sendTextMessage(MESSAGE_EVENT_ADVANCE, fmt::format("You advanced to {:s} level {:d}.", getSkillName(skill), skills[skill].level)); - g_creatureEvents->playerAdvance(this, skill, (skills[skill].level - 1), skills[skill].level); + g_creatureEvents->playerAdvance(this->getPlayer(), skill, (skills[skill].level - 1), skills[skill].level); sendUpdateSkills = true; currReqTries = nextReqTries; @@ -1165,7 +1147,7 @@ void Player::addSkillAdvance(skills_t skill, uint64_t count) } } -void Player::removeSkillTries(skills_t skill, uint64_t count, bool notify/* = false*/) +void Player::removeSkillTries(const skills_t skill, uint64_t count, const bool notify/* = false*/) { uint16_t oldLevel = skills[skill].level; uint8_t oldPercent = skills[skill].percent; @@ -1200,7 +1182,7 @@ void Player::removeSkillTries(skills_t skill, uint64_t count, bool notify/* = fa } } -void Player::setVarStats(stats_t stat, int32_t modifier) +void Player::setVarStats(const stats_t stat, const int32_t modifier) { varStats[stat] += modifier; @@ -1209,7 +1191,7 @@ void Player::setVarStats(stats_t stat, int32_t modifier) if (getHealth() > getMaxHealth()) { Creature::changeHealth(getMaxHealth() - getHealth()); } else { - g_game.addCreatureHealth(this); + g_game.addCreatureHealth(this->getPlayer()); } break; } @@ -1227,7 +1209,7 @@ void Player::setVarStats(stats_t stat, int32_t modifier) } } -int32_t Player::getDefaultStats(stats_t stat) const +int32_t Player::getDefaultStats(const stats_t stat) const { switch (stat) { case STAT_MAXHITPOINTS: return healthMax; @@ -1237,24 +1219,14 @@ int32_t Player::getDefaultStats(stats_t stat) const } } -void Player::addContainer(uint8_t cid, Container* container) +void Player::addContainer(const uint8_t cid, const ContainerPtr& container) { if (cid > 0xF) { return; } - if (container->getID() == ITEM_BROWSEFIELD) { - container->incrementReferenceCounter(); - } - - auto it = openContainers.find(cid); - if (it != openContainers.end()) { + if (const auto& it = openContainers.find(cid); it != openContainers.end()) { OpenContainer& openContainer = it->second; - Container* oldContainer = openContainer.container; - if (oldContainer->getID() == ITEM_BROWSEFIELD) { - oldContainer->decrementReferenceCounter(); - } - openContainer.container = container; openContainer.index = 0; } else { @@ -1265,41 +1237,37 @@ void Player::addContainer(uint8_t cid, Container* container) } } -void Player::closeContainer(uint8_t cid) +void Player::closeContainer(const uint8_t cid) { - auto it = openContainers.find(cid); + const auto& it = openContainers.find(cid); if (it == openContainers.end()) { return; } OpenContainer openContainer = it->second; - Container* container = openContainer.container; + ContainerPtr container = openContainer.container; openContainers.erase(it); - - if (container && container->getID() == ITEM_BROWSEFIELD) { - container->decrementReferenceCounter(); - } } -void Player::setContainerIndex(uint8_t cid, uint16_t index) +void Player::setContainerIndex(const uint8_t cid, const uint16_t index) { - auto it = openContainers.find(cid); + const auto& it = openContainers.find(cid); if (it == openContainers.end()) { return; } it->second.index = index; } -Container* Player::getContainerByID(uint8_t cid) +ContainerPtr Player::getContainerByID(const uint8_t cid) { - auto it = openContainers.find(cid); + const auto& it = openContainers.find(cid); if (it == openContainers.end()) { return nullptr; } return it->second.container; } -int8_t Player::getContainerID(const Container* container) const +int8_t Player::getContainerID(const ContainerConstPtr& container) const { for (const auto& it : openContainers) { if (it.second.container == container) { @@ -1309,16 +1277,16 @@ int8_t Player::getContainerID(const Container* container) const return -1; } -uint16_t Player::getContainerIndex(uint8_t cid) const +uint16_t Player::getContainerIndex(const uint8_t cid) const { - auto it = openContainers.find(cid); + const auto& it = openContainers.find(cid); if (it == openContainers.end()) { return 0; } return it->second.index; } -bool Player::canOpenCorpse(uint32_t ownerId) const +bool Player::canOpenCorpse(const uint32_t ownerId) const { return getID() == ownerId || (party && party->canOpenCorpse(ownerId)); } @@ -1369,7 +1337,7 @@ void Player::addStorageValue(const uint32_t key, const int32_t value, const bool bool Player::getStorageValue(const uint32_t key, int32_t& value) const { - auto it = storageMap.find(key); + const auto it = storageMap.find(key); if (it == storageMap.end()) { value = -1; return false; @@ -1387,9 +1355,9 @@ bool Player::canSee(const Position& pos) const return client->canSee(pos); } -bool Player::canSeeCreature(const Creature* creature) const +bool Player::canSeeCreature(const CreatureConstPtr& creature) const { - if (creature == this) { + if (creature == getCreature()) { return true; } @@ -1403,33 +1371,33 @@ bool Player::canSeeCreature(const Creature* creature) const return true; } -bool Player::canSeeGhostMode(const Creature*) const +bool Player::canSeeGhostMode(const CreatureConstPtr&) const { return group->access; } -bool Player::canWalkthrough(const Creature* creature) const +bool Player::canWalkthrough(const CreatureConstPtr& creature) const { if (group->access || creature->isInGhostMode() || (g_config.getBoolean(ConfigManager::ALLOW_WALKTHROUGH) && creature->getPlayer() && creature->getPlayer()->isAccessPlayer())) { return true; } - const Player* player = creature->getPlayer(); + const auto& player = creature->getPlayer(); if (!player || !g_config.getBoolean(ConfigManager::ALLOW_WALKTHROUGH)) { return false; } - const Tile* playerTile = player->getTile(); + const auto& playerTile = player->getTile(); if (!playerTile || (!playerTile->hasFlag(TILESTATE_PROTECTIONZONE) && player->getLevel() > static_cast(g_config.getNumber(ConfigManager::PROTECTION_LEVEL)))) { return false; } - const Item* playerTileGround = playerTile->getGround(); + const auto& playerTileGround = playerTile->getGround(); if (!playerTileGround || !playerTileGround->hasWalkStack()) { return false; } - Player* thisPlayer = const_cast(this); + const auto& thisPlayer = const_cast(this); if ((OTSYS_TIME() - lastWalkthroughAttempt) > 2000) { thisPlayer->setLastWalkthroughAttempt(OTSYS_TIME()); return false; @@ -1444,18 +1412,18 @@ bool Player::canWalkthrough(const Creature* creature) const return true; } -bool Player::canWalkthroughEx(const Creature* creature) const +bool Player::canWalkthroughEx(const CreatureConstPtr& creature) const { if (group->access) { return true; } - const Player* player = creature->getPlayer(); + const auto& player = creature->getPlayer(); if (!player || !g_config.getBoolean(ConfigManager::ALLOW_WALKTHROUGH)) { return false; } - const Tile* playerTile = player->getTile(); + const auto& playerTile = player->getTile(); return playerTile && (playerTile->hasFlag(TILESTATE_PROTECTIONZONE) || player->getLevel() <= static_cast(g_config.getNumber(ConfigManager::PROTECTION_LEVEL))); } @@ -1471,7 +1439,7 @@ bool Player::isNearDepotBox() const const Position& pos = getPosition(); for (int32_t cx = -NOTIFY_DEPOT_BOX_RANGE; cx <= NOTIFY_DEPOT_BOX_RANGE; ++cx) { for (int32_t cy = -NOTIFY_DEPOT_BOX_RANGE; cy <= NOTIFY_DEPOT_BOX_RANGE; ++cy) { - Tile* tile = g_game.map.getTile(pos.x + cx, pos.y + cy, pos.z); + const auto& tile = g_game.map.getTile(pos.x + cx, pos.y + cy, pos.z); if (!tile) { continue; } @@ -1484,7 +1452,7 @@ bool Player::isNearDepotBox() const return false; } -DepotChest* Player::getDepotChest(uint32_t depotId, bool autoCreate) +DepotChestPtr Player::getDepotChest(uint32_t depotId, const bool autoCreate) { auto it = depotChests.find(depotId); if (it != depotChests.end()) { @@ -1500,22 +1468,21 @@ DepotChest* Player::getDepotChest(uint32_t depotId, bool autoCreate) return nullptr; } - it = depotChests.emplace(depotId, new DepotChest(depotItemId)).first; + it = depotChests.emplace(depotId, std::make_shared(depotItemId)).first; it->second->setMaxDepotItems(getMaxDepotItems()); return it->second; } -DepotLocker& Player::getDepotLocker() +DepotLockerPtr& Player::getDepotLocker() { if (!depotLocker) { depotLocker = std::make_shared(ITEM_LOCKER1); depotLocker->internalAddThing(Item::CreateItem(ITEM_MARKET)); depotLocker->internalAddThing(inbox); - DepotChest* depotChest = new DepotChest(ITEM_DEPOT, false); - if (depotChest) { + if (const DepotChestPtr depotChest = std::make_shared(ITEM_DEPOT, false)) { // adding in reverse to align them from first to last for (int16_t depotId = depotChest->capacity(); depotId >= 0; --depotId) { - if (DepotChest* box = getDepotChest(depotId, true)) { + if (DepotChestPtr box = getDepotChest(depotId, true)) { depotChest->internalAddThing(box); } } @@ -1523,14 +1490,14 @@ DepotLocker& Player::getDepotLocker() depotLocker->internalAddThing(depotChest); } } - return *depotLocker; + return depotLocker; } uint32_t Player::getDepotItemCount() { uint32_t counter = 0; - for (auto item : getDepotLocker().getItems(true)) { + for (const auto item : getDepotLocker()->getItems(true)) { ++counter; @@ -1549,13 +1516,12 @@ uint32_t Player::getDepotItemCount() return counter; } -RewardChest& Player::getRewardChest() +RewardChestPtr& Player::getRewardChest() { if (!rewardChest) { rewardChest = std::make_shared(ITEM_REWARD_CHEST); - RewardChest* rewardChest = new RewardChest(ITEM_REWARD_CHEST); } - return *rewardChest; + return rewardChest; } void Player::sendCancelMessage(ReturnValue message) const @@ -1600,43 +1566,37 @@ void Player::sendPing() return; } - if (!g_creatureEvents->playerLogout(this)) { + if (!g_creatureEvents->playerLogout(this->getPlayer())) { return; } if (client) { client->logout(true, true); } - g_game.removeCreature(this, true); + g_game.removeCreature(this->getPlayer(), true); } } -Item* Player::getWriteItem(uint32_t& windowTextId, uint16_t& maxWriteLen) +ItemPtr Player::getWriteItem(uint32_t& windowTextId, uint16_t& maxWriteLen) { windowTextId = this->windowTextId; maxWriteLen = this->maxWriteLen; return writeItem; } -void Player::setWriteItem(Item* item, uint16_t maxWriteLen /*= 0*/) +void Player::setWriteItem(const ItemPtr& item, uint16_t maxWriteLen /*= 0*/) { windowTextId++; - - if (writeItem) { - writeItem->decrementReferenceCounter(); - } - if (item) { writeItem = item; this->maxWriteLen = maxWriteLen; - writeItem->incrementReferenceCounter(); } else { writeItem = nullptr; this->maxWriteLen = 0; } } -House* Player::getEditHouse(uint32_t& windowTextId, uint32_t& listId) +House* Player::getEditHouse(uint32_t& windowTextId, uint32_t& listId) const { windowTextId = this->windowTextId; listId = this->editListId; @@ -1663,7 +1623,7 @@ void Player::sendHouseWindow(House* house, uint32_t listId) const } //container -void Player::sendAddContainerItem(const Container* container, const Item* item) +void Player::sendAddContainerItem(const ContainerConstPtr& container, ItemPtr& item) const { if (!client) { return; @@ -1676,7 +1636,7 @@ void Player::sendAddContainerItem(const Container* container, const Item* item) } uint16_t slot = openContainer.index; - if (container->getID() == ITEM_BROWSEFIELD) { + if (container->getItem()->getID() == ITEM_BROWSEFIELD) { uint16_t containerSize = container->size() - 1; uint16_t pageEnd = openContainer.index + container->capacity() - 1; if (containerSize > pageEnd) { @@ -1695,7 +1655,7 @@ 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 ContainerConstPtr& container, uint16_t slot, const ItemConstPtr& newItem) const { if (!client) { return; @@ -1711,8 +1671,7 @@ void Player::sendUpdateContainerItem(const Container* container, uint16_t slot, continue; } - uint16_t pageEnd = openContainer.index + container->capacity(); - if (slot >= pageEnd) { + if (const uint16_t pageEnd = openContainer.index + container->capacity(); slot >= pageEnd) { continue; } @@ -1720,7 +1679,7 @@ void Player::sendUpdateContainerItem(const Container* container, uint16_t slot, } } -void Player::sendRemoveContainerItem(const Container* container, uint16_t slot) +void Player::sendRemoveContainerItem(const ContainerConstPtr& container, const uint16_t slot) { if (!client) { return; @@ -1742,8 +1701,8 @@ void Player::sendRemoveContainerItem(const Container* container, uint16_t slot) } } -void Player::onUpdateTileItem(const Tile* tile, const Position& pos, const Item* oldItem, - const ItemType& oldType, const Item* newItem, const ItemType& newType) +void Player::onUpdateTileItem(const TilePtr& tile, const Position& pos, const ItemPtr& oldItem, + const ItemType& oldType, const ItemPtr& newItem, const ItemType& newType) { Creature::onUpdateTileItem(tile, pos, oldItem, oldType, newItem, newType); @@ -1753,13 +1712,13 @@ void Player::onUpdateTileItem(const Tile* tile, const Position& pos, const Item* if (tradeState != TRADE_TRANSFER) { if (tradeItem && oldItem == tradeItem) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } } } -void Player::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, - const Item* item) +void Player::onRemoveTileItem(const TilePtr& tile, const Position& pos, const ItemType& iType, + const ItemPtr& item) { Creature::onRemoveTileItem(tile, pos, iType, item); @@ -1767,39 +1726,37 @@ void Player::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemT checkTradeState(item); if (tradeItem) { - const Container* container = item->getContainer(); + const auto& container = item->getContainer(); if (container && container->isHoldingItem(tradeItem)) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } } } } -void Player::onCreatureAppear(Creature* creature, bool isLogin) +void Player::onCreatureAppear(const CreaturePtr& creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); - if (isLogin && creature == this) { + if (isLogin && creature == getCreature()) { sendItems(); for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = inventory[slot]; - if (item) { + if (const auto& item = inventory[slot]) { item->startDecaying(); - g_moveEvents->onPlayerEquip(this, item, static_cast(slot), false); + g_moveEvents->onPlayerEquip(this->getPlayer(), item, static_cast(slot), false); } } - for (Condition* condition : storedConditionList) { + for (const auto& condition : storedConditionList) { addCondition(condition); } storedConditionList.clear(); updateRegeneration(); - BedItem* bed = g_game.getBedBySleeper(guid); - if (bed) { - bed->wakeUp(this); + if (const auto& bed = g_game.getBedBySleeper(guid)) { + bed->wakeUp(this->getPlayer()); } Account account = IOLoginData::loadAccount(accountNumber); @@ -1809,7 +1766,7 @@ void Player::onCreatureAppear(Creature* creature, bool isLogin) } if (guild) { - guild->addMember(this); + guild->addMember(this->getPlayer()); } int32_t offlineTime; @@ -1820,7 +1777,7 @@ void Player::onCreatureAppear(Creature* creature, bool isLogin) offlineTime = 0; } - for (Condition* condition : getMuteConditions()) { + for (const auto& condition : getMuteConditions()) { condition->setTicks(condition->getTicks() - (offlineTime * 1000)); if (condition->getTicks() <= 0) { removeCondition(condition); @@ -1832,7 +1789,7 @@ void Player::onCreatureAppear(Creature* creature, bool isLogin) } } -void Player::onAttackedCreatureDisappear(bool isLogout) +void Player::onAttackedCreatureDisappear(const bool isLogout) { sendCancelTarget(); @@ -1841,7 +1798,7 @@ void Player::onAttackedCreatureDisappear(bool isLogout) } } -void Player::onFollowCreatureDisappear(bool isLogout) +void Player::onFollowCreatureDisappear(const bool isLogout) { sendCancelTarget(); @@ -1850,7 +1807,7 @@ void Player::onFollowCreatureDisappear(bool isLogout) } } -void Player::onChangeZone(ZoneType_t zone) +void Player::onChangeZone(const ZoneType_t zone) { if (zone == ZONE_PROTECTION) { if (attackedCreature && !hasFlag(PlayerFlag_IgnoreProtectionZone)) { @@ -1860,7 +1817,7 @@ void Player::onChangeZone(ZoneType_t zone) if (!group->access && isMounted()) { dismount(); - g_game.internalCreatureChangeOutfit(this, defaultOutfit); + g_game.internalCreatureChangeOutfit(this->getPlayer(), defaultOutfit); wasMounted = true; } } else { @@ -1870,11 +1827,11 @@ void Player::onChangeZone(ZoneType_t zone) } } - g_game.updateCreatureWalkthrough(this); + g_game.updateCreatureWalkthrough(this->getPlayer()); sendIcons(); } -void Player::onAttackedCreatureChangeZone(ZoneType_t zone) +void Player::onAttackedCreatureChangeZone(const ZoneType_t zone) { if (zone == ZONE_PROTECTION) { if (!hasFlag(PlayerFlag_IgnoreProtectionZone)) { @@ -1899,15 +1856,14 @@ void Player::onAttackedCreatureChangeZone(ZoneType_t zone) } } -void Player::onRemoveCreature(Creature* creature, bool isLogout) +void Player::onRemoveCreature(const CreaturePtr& creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); - if (creature == this) { + if (creature == getCreature()) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = inventory[slot]; - if (item) { - g_moveEvents->onPlayerDeEquip(this, item, static_cast(slot)); + if (const auto& item = inventory[slot]) { + g_moveEvents->onPlayerDeEquip(this->getPlayer(), item, static_cast(slot)); } } if (isLogout) { @@ -1921,7 +1877,7 @@ void Player::onRemoveCreature(Creature* creature, bool isLogout) } if (tradePartner) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } closeShopWindow(); @@ -1929,24 +1885,24 @@ void Player::onRemoveCreature(Creature* creature, bool isLogout) clearPartyInvitations(); if (party) { - party->leaveParty(this, true); + party->leaveParty(this->getPlayer(), true); } - g_chat->removeUserFromAllChannels(*this); + g_chat->removeUserFromAllChannels(this->getPlayer()); if (g_config.getBoolean(ConfigManager::PLAYER_CONSOLE_LOGS)) { std::cout << getName() << " has logged out." << std::endl; } if (guild) { - guild->removeMember(this); + guild->removeMember(this->getPlayer()); } IOLoginData::updateOnlineStatus(guid, false); bool saved = false; for (uint32_t tries = 0; tries < 3; ++tries) { - if (IOLoginData::savePlayer(this)) { + if (IOLoginData::savePlayer(this->getPlayer())) { saved = true; break; } @@ -1958,7 +1914,7 @@ void Player::onRemoveCreature(Creature* creature, bool isLogout) } } -void Player::openShopWindow(Npc* npc, const std::list& shop) +void Player::openShopWindow(const NpcPtr& npc, const std::list& shop) { shopItemList = shop; sendShop(npc); @@ -1971,14 +1927,14 @@ bool Player::closeShopWindow(bool sendCloseShopWindow /*= true*/) int32_t onBuy; int32_t onSell; - Npc* npc = getShopOwner(onBuy, onSell); + const auto& npc = getShopOwner(onBuy, onSell); if (!npc) { shopItemList.clear(); return false; } setShopOwner(nullptr, -1, -1); - npc->onPlayerEndTrade(this, onBuy, onSell); + npc->onPlayerEndTrade(this->getPlayer(), onBuy, onSell); if (sendCloseShopWindow) { sendCloseShop(); @@ -1995,28 +1951,28 @@ void Player::onWalk(Direction& dir) 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(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, + const TilePtr& oldTile, const Position& oldPos, bool teleport) { Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); - if (hasFollowPath && (creature == followCreature || (creature == this && followCreature))) { + if (hasFollowPath && (creature == followCreature || (creature == this->getPlayer() && followCreature))) { isUpdatingPath = false; g_dispatcher.addTask(createTask([id = getID()]() { g_game.updateCreatureWalk(id); })); } - if (creature != this) { + if (creature != this->getPlayer()) { return; } if (tradeState != TRADE_TRANSFER) { //check if we should close trade if (tradeItem && !Position::areInRange<1, 1, 0>(tradeItem->getPosition(), getPosition())) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } if (tradePartner && !Position::areInRange<2, 2, 0>(tradePartner->getPosition(), getPosition())) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } } @@ -2044,7 +2000,7 @@ void Player::onCreatureMove(Creature* creature, const Tile* newTile, const Posit if (teleport || oldPos.z != newPos.z) { int32_t ticks = g_config.getNumber(ConfigManager::STAIRHOP_DELAY); if (ticks > 0) { - if (Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks, 0)) { + if (const auto& condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks, 0)) { addCondition(condition); } } @@ -2052,12 +2008,12 @@ void Player::onCreatureMove(Creature* creature, const Tile* newTile, const Posit } //container -void Player::onAddContainerItem(const Item* item) +void Player::onAddContainerItem(const ItemPtr& item) { checkTradeState(item); } -void Player::onUpdateContainerItem(const Container* container, const Item* oldItem, const Item* newItem) +void Player::onUpdateContainerItem(const ContainerPtr& container, const ItemPtr& oldItem, const ItemPtr& newItem) { if (oldItem != newItem) { onRemoveContainerItem(container, oldItem); @@ -2068,20 +2024,20 @@ void Player::onUpdateContainerItem(const Container* container, const Item* oldIt } } -void Player::onRemoveContainerItem(const Container* container, const Item* item) +void Player::onRemoveContainerItem(const ContainerPtr& container, const ItemPtr& item) { if (tradeState != TRADE_TRANSFER) { checkTradeState(item); if (tradeItem) { if (tradeItem->getParent() != container && container->isHoldingItem(tradeItem)) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } } } } -void Player::onCloseContainer(const Container* container) +void Player::onCloseContainer(const ContainerConstPtr& container) const { if (!client) { return; @@ -2094,13 +2050,13 @@ void Player::onCloseContainer(const Container* container) } } -void Player::onSendContainer(const Container* container) +void Player::onSendContainer(const ContainerPtr& container) const { if (!client) { return; } - bool hasParent = container->hasParent(); + const bool hasParent = container->hasParent(); for (const auto& it : openContainers) { const OpenContainer& openContainer = it.second; if (openContainer.container == container) { @@ -2110,7 +2066,7 @@ void Player::onSendContainer(const Container* container) } //inventory -void Player::onUpdateInventoryItem(Item* oldItem, Item* newItem) +void Player::onUpdateInventoryItem(const ItemPtr& oldItem, const ItemPtr& newItem) { if (oldItem != newItem) { onRemoveInventoryItem(oldItem); @@ -2121,37 +2077,37 @@ void Player::onUpdateInventoryItem(Item* oldItem, Item* newItem) } } -void Player::onRemoveInventoryItem(Item* item) +void Player::onRemoveInventoryItem(const ItemPtr& item) { if (tradeState != TRADE_TRANSFER) { checkTradeState(item); if (tradeItem) { - const Container* container = item->getContainer(); + const auto& container = item->getContainer(); if (container && container->isHoldingItem(tradeItem)) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } } } } -void Player::checkTradeState(const Item* item) +void Player::checkTradeState(const ItemPtr& item) { if (!tradeItem || tradeState == TRADE_TRANSFER) { return; } if (tradeItem == item) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); } else { - const Container* container = dynamic_cast(item->getParent()); + auto container = std::dynamic_pointer_cast(item->getParent()); while (container) { if (container == tradeItem) { - g_game.internalCloseTrade(this); + g_game.internalCloseTrade(this->getPlayer()); break; } - container = dynamic_cast(container->getParent()); + container = std::dynamic_pointer_cast(container->getParent()); } } } @@ -2187,7 +2143,7 @@ uint32_t Player::getNextActionTime() const return std::max(SCHEDULER_MINTICKS, nextAction - OTSYS_TIME()); } -void Player::onThink(uint32_t interval) +void Player::onThink(const uint32_t interval) { Creature::onThink(interval); @@ -2199,6 +2155,8 @@ void Player::onThink(uint32_t interval) addMessageBuffer(); } + if (!getTile()) { std::cout << "Tile is gone!" << std::endl; } + if (!getTile()->hasFlag(TILESTATE_NOLOGOUT) && !isAccessPlayer()) { idleTime += interval; const int32_t kickAfterMinutes = g_config.getNumber(ConfigManager::KICK_AFTER_MINUTES); @@ -2211,7 +2169,7 @@ void Player::onThink(uint32_t interval) // if (isImbued()) { // TODO: Reimplement a check like this to first see if player has any items, then items with imbuements before decaying. for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = inventory[slot]; + const auto& item = inventory[slot]; if (item && item->hasImbuements()) { item->decayImbuements(hasCondition(CONDITION_INFIGHT)); sendSkills(); @@ -2237,7 +2195,7 @@ uint32_t Player::isMuted() const } int32_t muteTicks = 0; - for (Condition* condition : conditions) { + for (const auto& condition : conditions) { if (condition->getType() == CONDITION_MUTED && condition->getTicks() > muteTicks) { muteTicks = condition->getTicks(); } @@ -2262,14 +2220,13 @@ void Player::removeMessageBuffer() if (maxMessageBuffer != 0 && MessageBufferCount <= maxMessageBuffer + 1) { if (++MessageBufferCount > maxMessageBuffer) { uint32_t muteCount = 1; - auto it = muteCountMap.find(guid); - if (it != muteCountMap.end()) { + if (const auto& it = muteCountMap.find(guid); it != muteCountMap.end()) { muteCount = it->second; } uint32_t muteTime = 5 * muteCount * muteCount; muteCountMap[guid] = muteCount + 1; - Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000, 0); + const auto& condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000, 0); addCondition(condition); sendTextMessage(MESSAGE_STATUS_SMALL, fmt::format("You are muted for {:d} seconds.", muteTime)); @@ -2277,13 +2234,13 @@ void Player::removeMessageBuffer() } } -void Player::drainHealth(Creature* attacker, int32_t damage) +void Player::drainHealth(const CreaturePtr& attacker, const int32_t damage) { Creature::drainHealth(attacker, damage); sendStats(); } -void Player::drainMana(Creature* attacker, int32_t manaLoss) +void Player::drainMana(const CreaturePtr& attacker, const int32_t manaLoss) { onAttacked(); changeMana(-manaLoss); @@ -2308,7 +2265,7 @@ void Player::addManaSpent(uint64_t amount) return; } - g_events->eventPlayerOnGainSkillTries(this, SKILL_MAGLEVEL, amount); + g_events->eventPlayerOnGainSkillTries(this->getPlayer(), SKILL_MAGLEVEL, amount); if (amount == 0) { return; } @@ -2322,7 +2279,7 @@ void Player::addManaSpent(uint64_t amount) sendTextMessage(MESSAGE_EVENT_ADVANCE, fmt::format("You advanced to magic level {:d}.", magLevel)); - g_creatureEvents->playerAdvance(this, SKILL_MAGLEVEL, magLevel - 1, magLevel); + g_creatureEvents->playerAdvance(this->getPlayer(), SKILL_MAGLEVEL, magLevel - 1, magLevel); sendUpdateStats = true; currReqMana = nextReqMana; @@ -2350,14 +2307,14 @@ void Player::addManaSpent(uint64_t amount) } } -void Player::removeManaSpent(uint64_t amount, bool notify/* = false*/) +void Player::removeManaSpent(uint64_t amount, const bool notify/* = false*/) { if (amount == 0) { return; } - uint32_t oldLevel = magLevel; - uint8_t oldPercent = magLevelPercent; + const uint32_t oldLevel = magLevel; + const uint8_t oldPercent = magLevelPercent; while (amount > manaSpent && magLevel > 0) { amount -= manaSpent; @@ -2387,7 +2344,7 @@ void Player::removeManaSpent(uint64_t amount, bool notify/* = false*/) } } -void Player::addExperience(Creature* source, uint64_t exp, bool sendText/* = false*/) +void Player::addExperience(const CreaturePtr& source, uint64_t exp, bool sendText/* = false*/) { uint64_t currLevelExp = Player::getExpForLevel(level); uint64_t nextLevelExp = Player::getExpForLevel(level + 1); @@ -2399,7 +2356,7 @@ void Player::addExperience(Creature* source, uint64_t exp, bool sendText/* = fal return; } - g_events->eventPlayerOnGainExperience(this, source, exp, rawExp); + g_events->eventPlayerOnGainExperience(this->getPlayer(), source, exp, rawExp); if (exp == 0) { return; } @@ -2407,7 +2364,7 @@ void Player::addExperience(Creature* source, uint64_t exp, bool sendText/* = fal experience += exp; if (sendText) { - std::string expString = std::to_string(exp) + (exp != 1 ? " experience points." : " experience point."); + const std::string expString = std::to_string(exp) + (exp != 1 ? " experience points." : " experience point."); TextMessage message(MESSAGE_EXPERIENCE, "You gained " + expString); message.position = position; @@ -2417,13 +2374,13 @@ void Player::addExperience(Creature* source, uint64_t exp, bool sendText/* = fal SpectatorVec spectators; g_game.map.getSpectators(spectators, position, false, true); - spectators.erase(this); + spectators.erase(this->getPlayer()); if (!spectators.empty()) { message.type = MESSAGE_EXPERIENCE_OTHERS; message.text = getName() + " gained " + expString; - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendTextMessage(message); + for (const auto& spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendTextMessage(message); } } } @@ -2452,19 +2409,19 @@ void Player::addExperience(Creature* source, uint64_t exp, bool sendText/* = fal updateBaseSpeed(); setBaseSpeed(getBaseSpeed()); - g_game.changeSpeed(this, 0); - g_game.addCreatureHealth(this); + g_game.changeSpeed(this->getPlayer(), 0); + g_game.addCreatureHealth(this->getPlayer()); const uint32_t protectionLevel = static_cast(g_config.getNumber(ConfigManager::PROTECTION_LEVEL)); if (prevLevel < protectionLevel && level >= protectionLevel) { - g_game.updateCreatureWalkthrough(this); + g_game.updateCreatureWalkthrough(this->getPlayer()); } if (party) { party->updateSharedExperience(); } - g_creatureEvents->playerAdvance(this, SKILL_LEVEL, prevLevel, level); + g_creatureEvents->playerAdvance(this->getPlayer(), SKILL_LEVEL, prevLevel, level); sendTextMessage(MESSAGE_EVENT_ADVANCE, fmt::format("You advanced from Level {:d} to Level {:d}.", prevLevel, level)); } @@ -2477,13 +2434,13 @@ void Player::addExperience(Creature* source, uint64_t exp, bool sendText/* = fal sendStats(); } -void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) +void Player::removeExperience(uint64_t exp, const bool sendText/* = false*/) { if (experience == 0 || exp == 0) { return; } - g_events->eventPlayerOnLoseExperience(this, exp); + g_events->eventPlayerOnLoseExperience(this->getPlayer(), exp); if (exp == 0) { return; } @@ -2494,7 +2451,7 @@ void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) if (sendText) { lostExp -= experience; - std::string expString = std::to_string(lostExp) + (lostExp != 1 ? " experience points." : " experience point."); + const std::string expString = std::to_string(lostExp) + (lostExp != 1 ? " experience points." : " experience point."); TextMessage message(MESSAGE_EXPERIENCE, "You lost " + expString); message.position = position; @@ -2504,13 +2461,13 @@ void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) SpectatorVec spectators; g_game.map.getSpectators(spectators, position, false, true); - spectators.erase(this); + spectators.erase(this->getPlayer()); if (!spectators.empty()) { message.type = MESSAGE_EXPERIENCE_OTHERS; message.text = getName() + " lost " + expString; - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->sendTextMessage(message); + for (const auto& spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendTextMessage(message); } } } @@ -2533,12 +2490,12 @@ void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) updateBaseSpeed(); setBaseSpeed(getBaseSpeed()); - g_game.changeSpeed(this, 0); - g_game.addCreatureHealth(this); + g_game.changeSpeed(this->getPlayer(), 0); + g_game.addCreatureHealth(this->getPlayer()); const uint32_t protectionLevel = static_cast(g_config.getNumber(ConfigManager::PROTECTION_LEVEL)); if (oldLevel >= protectionLevel && level < protectionLevel) { - g_game.updateCreatureWalkthrough(this); + g_game.updateCreatureWalkthrough(this->getPlayer()); } if (party) { @@ -2557,7 +2514,7 @@ void Player::removeExperience(uint64_t exp, bool sendText/* = false*/) sendStats(); } -uint8_t Player::getPercentLevel(uint64_t count, uint64_t nextLevelCount) +uint8_t Player::getPercentLevel(const uint64_t count, uint64_t nextLevelCount) { if (nextLevelCount == 0) { return 0; @@ -2614,7 +2571,7 @@ void Player::onAttackedCreatureBlockHit(BlockType_t blockType) bool Player::hasShield() const { - Item* item = inventory[CONST_SLOT_LEFT]; + auto item = inventory[CONST_SLOT_LEFT]; if (item && item->getWeaponType() == WEAPON_SHIELD) { return true; } @@ -2626,7 +2583,7 @@ bool Player::hasShield() const return false; } -BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, +BlockType_t Player::blockHit(const CreaturePtr& attacker, CombatType_t combatType, int32_t& damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool field /* = false*/, bool ignoreResistances /* = false*/) { BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor, field, ignoreResistances); @@ -2643,13 +2600,12 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ continue; } - Item* item = inventory[slot]; + auto item = inventory[slot]; if (!item) { continue; } - const ItemType& it = Item::items[item->getID()]; - if (!it.abilities) { + if (const ItemType& it = Item::items[item->getID()]; !it.abilities) { if (damage <= 0) { damage = 0; return BLOCK_ARMOR; @@ -2657,8 +2613,7 @@ BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_ continue; } - uint16_t charges = item->getCharges(); - if (charges != 0) { + if (const uint16_t charges = item->getCharges(); charges != 0) { g_game.transformItem(item, item->getID(), charges - 1); } } @@ -2680,13 +2635,13 @@ uint32_t Player::getIP() const return 0; } -void Player::death(Creature* lastHitCreature) +void Player::death(const CreaturePtr& lastHitCreature) { loginPosition = town->getTemplePosition(); if (skillLoss) { uint8_t unfairFightReduction = 100; - bool lastHitPlayer = Player::lastHitIsPlayer(lastHitCreature); + const bool lastHitPlayer = Player::lastHitIsPlayer(lastHitCreature); if (lastHitPlayer) { uint32_t sumLevels = 0; @@ -2694,8 +2649,7 @@ void Player::death(Creature* lastHitCreature) for (const auto& it : damageMap) { CountBlock_t cb = it.second; if ((OTSYS_TIME() - cb.ticks) <= inFightTicks) { - Player* damageDealer = g_game.getPlayerByID(it.first); - if (damageDealer) { + if (const auto& damageDealer = g_game.getPlayerByID(it.first)) { sumLevels += damageDealer->getLevel(); } } @@ -2730,7 +2684,7 @@ void Player::death(Creature* lastHitCreature) //Level loss uint64_t expLoss = static_cast(experience * deathLossPercent); - g_events->eventPlayerOnLoseExperience(this, expLoss); + g_events->eventPlayerOnLoseExperience(this->getPlayer(), expLoss); if (expLoss != 0) { uint32_t oldLevel = level; @@ -2788,7 +2742,7 @@ void Player::death(Creature* lastHitCreature) if (condition->isPersistent()) { it = conditions.erase(it); - condition->endCondition(this); + condition->endCondition(this->getPlayer()); onEndCondition(condition->getType()); delete condition; } else { @@ -2804,7 +2758,7 @@ void Player::death(Creature* lastHitCreature) if (condition->isPersistent()) { it = conditions.erase(it); - condition->endCondition(this); + condition->endCondition(this->getPlayer()); onEndCondition(condition->getType()); delete condition; } else { @@ -2813,15 +2767,15 @@ void Player::death(Creature* lastHitCreature) } health = healthMax; - g_game.internalTeleport(this, getTemplePosition(), true); - g_game.addCreatureHealth(this); + g_game.internalTeleport(this->getPlayer(), getTemplePosition(), true); + g_game.addCreatureHealth(this->getPlayer()); onThink(EVENT_CREATURE_THINK_INTERVAL); onIdleStatus(); sendStats(); } } -bool Player::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) +bool Player::dropCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { if (getZone() != ZONE_PVP || !Player::lastHitIsPlayer(lastHitCreature)) { return Creature::dropCorpse(lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); @@ -2831,9 +2785,9 @@ bool Player::dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, return false; } -Item* Player::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) +ItemPtr Player::getCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature) { - Item* corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); + const auto& corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse && corpse->getContainer()) { size_t killersSize = getKillers().size(); @@ -2858,7 +2812,7 @@ Item* Player::getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) return corpse; } -void Player::addInFightTicks(bool pzlock /*= false*/) +void Player::addInFightTicks(const bool pzlock /*= false*/) { if (hasFlag(PlayerFlag_NotGainInFight)) { return; @@ -2868,46 +2822,45 @@ void Player::addInFightTicks(bool pzlock /*= false*/) pzLocked = true; } - Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_config.getNumber(ConfigManager::PZ_LOCKED), 0); + const auto& condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_config.getNumber(ConfigManager::PZ_LOCKED), 0); addCondition(condition); } void Player::removeList() { - g_game.removePlayer(this); + g_game.removePlayer(this->getPlayer()); for (const auto& it : g_game.getPlayers()) { - it.second->notifyStatusChange(this, VIPSTATUS_OFFLINE); + it.second->notifyStatusChange(this->getPlayer(), VIPSTATUS_OFFLINE); } } void Player::addList() { for (const auto& it : g_game.getPlayers()) { - it.second->notifyStatusChange(this, VIPSTATUS_ONLINE); + it.second->notifyStatusChange(this->getPlayer(), VIPSTATUS_ONLINE); } - g_game.addPlayer(this); + g_game.addPlayer(this->getPlayer()); } void Player::kickPlayer(bool displayEffect) { - g_creatureEvents->playerLogout(this); + g_creatureEvents->playerLogout(this->getPlayer()); if (client) { client->logout(displayEffect, true); } else { - g_game.removeCreature(this); + g_game.removeCreature(this->getPlayer()); } } -void Player::notifyStatusChange(Player* loginPlayer, VipStatus_t status) +void Player::notifyStatusChange(const PlayerPtr& loginPlayer, VipStatus_t status) { if (!client) { return; } - auto it = VIPList.find(loginPlayer->guid); - if (it == VIPList.end()) { + if (const auto& it = VIPList.find(loginPlayer->guid); it == VIPList.end()) { return; } @@ -2920,7 +2873,7 @@ void Player::notifyStatusChange(Player* loginPlayer, VipStatus_t status) } } -bool Player::removeVIP(uint32_t vipGuid) +bool Player::removeVIP(const uint32_t vipGuid) { if (VIPList.erase(vipGuid) == 0) { return false; @@ -2930,15 +2883,14 @@ bool Player::removeVIP(uint32_t vipGuid) return true; } -bool Player::addVIP(uint32_t vipGuid, const std::string& vipName, VipStatus_t status) +bool Player::addVIP(const uint32_t vipGuid, const std::string& vipName, VipStatus_t status) { if (VIPList.size() >= getMaxVIPEntries()) { sendTextMessage(MESSAGE_STATUS_SMALL, "You cannot add more buddies."); return false; } - auto result = VIPList.insert(vipGuid); - if (!result.second) { + if (const auto result = VIPList.insert(vipGuid); !result.second) { sendTextMessage(MESSAGE_STATUS_SMALL, "This player is already in your list."); return false; } @@ -2950,7 +2902,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(const uint32_t vipGuid) { if (VIPList.size() >= getMaxVIPEntries()) { return false; @@ -2959,10 +2911,9 @@ 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(const uint32_t vipGuid, const std::string& description, const uint32_t icon, const bool notify) { - auto it = VIPList.find(vipGuid); - if (it == VIPList.end()) { + if (const auto& it = VIPList.find(vipGuid); it == VIPList.end()) { return false; // player is not in VIP } @@ -2971,18 +2922,18 @@ bool Player::editVIP(uint32_t vipGuid, const std::string& description, uint32_t } //close container and its child containers -void Player::autoCloseContainers(const Container* container) +void Player::autoCloseContainers(const ContainerConstPtr& container) { std::vector closeList; for (const auto& it : openContainers) { - Container* tmpContainer = it.second.container; + auto tmpContainer = it.second.container; while (tmpContainer) { if (tmpContainer->isRemoved() || tmpContainer == container) { closeList.push_back(it.first); break; } - tmpContainer = dynamic_cast(tmpContainer->getParent()); + tmpContainer = std::dynamic_pointer_cast(tmpContainer->getParent()); } } @@ -2994,13 +2945,13 @@ void Player::autoCloseContainers(const Container* container) } } -bool Player::hasCapacity(const Item* item, uint32_t count) const +bool Player::hasCapacity(const ItemPtr& item, uint32_t count) const { if (hasFlag(PlayerFlag_CannotPickupItem)) { return false; } - if (hasFlag(PlayerFlag_HasInfiniteCapacity) || item->getTopParent() == this) { + if (hasFlag(PlayerFlag_HasInfiniteCapacity) || item->getTopParent() == this->getPlayer()) { return true; } @@ -3011,15 +2962,14 @@ 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 ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr) { - const Item* item = thing.getItem(); + const auto& item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } - bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); - if (childIsOwner) { + if (const bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags)) { //a child container is querying the player, just check if enough capacity bool skipLimit = hasBitSet(FLAG_NOLIMIT, flags); if (skipLimit || hasCapacity(item, count)) { @@ -3089,7 +3039,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, if (item->getWeaponType() != WEAPON_SHIELD && item->getWeaponType() != WEAPON_QUIVER) { ret = RETURNVALUE_CANNOTBEDRESSED; } else { - const Item* leftItem = inventory[CONST_SLOT_LEFT]; + const auto& leftItem = inventory[CONST_SLOT_LEFT]; if (leftItem) { if ((leftItem->getSlotPosition() | slotPosition) & SLOTP_TWO_HAND) { if (leftItem->getWeaponType() != WEAPON_DISTANCE || @@ -3106,14 +3056,14 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, } } } else if (slotPosition & SLOTP_TWO_HAND) { - const Item* leftItem = inventory[CONST_SLOT_LEFT]; + const auto& leftItem = inventory[CONST_SLOT_LEFT]; if (leftItem && leftItem != item) { ret = RETURNVALUE_BOTHHANDSNEEDTOBEFREE; } else { ret = RETURNVALUE_NOERROR; } } else if (inventory[CONST_SLOT_LEFT]) { - const Item* leftItem = inventory[CONST_SLOT_LEFT]; + const auto& leftItem = inventory[CONST_SLOT_LEFT]; WeaponType_t type = item->getWeaponType(), leftType = leftItem->getWeaponType(); if (leftItem->getSlotPosition() & SLOTP_TWO_HAND) { @@ -3144,7 +3094,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, if (slotPosition & SLOTP_LEFT) { if (!g_config.getBoolean(ConfigManager::CLASSIC_EQUIPMENT_SLOTS)) { WeaponType_t type = item->getWeaponType(); - const Item* rightItem = inventory[CONST_SLOT_RIGHT]; + const auto& rightItem = inventory[CONST_SLOT_RIGHT]; if (type == WEAPON_NONE || type == WEAPON_SHIELD || type == WEAPON_AMMO || type == WEAPON_QUIVER) { ret = RETURNVALUE_CANNOTBEDRESSED; } else if (rightItem && (slotPosition & SLOTP_TWO_HAND)) { @@ -3157,7 +3107,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, ret = RETURNVALUE_NOERROR; } } else if (slotPosition & SLOTP_TWO_HAND) { - const Item* rightItem = inventory[CONST_SLOT_RIGHT]; + const auto& rightItem = inventory[CONST_SLOT_RIGHT]; if (rightItem && rightItem != item) { if (item->getWeaponType() != WEAPON_DISTANCE || rightItem->getWeaponType() != WEAPON_QUIVER) { ret = RETURNVALUE_BOTHHANDSNEEDTOBEFREE; @@ -3168,7 +3118,7 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, ret = RETURNVALUE_NOERROR; } } else if (inventory[CONST_SLOT_RIGHT]) { - const Item* rightItem = inventory[CONST_SLOT_RIGHT]; + const auto& rightItem = inventory[CONST_SLOT_RIGHT]; WeaponType_t type = item->getWeaponType(), rightType = rightItem->getWeaponType(); if (rightItem->getSlotPosition() & SLOTP_TWO_HAND) { @@ -3243,18 +3193,18 @@ ReturnValue Player::queryAdd(int32_t index, const Thing& thing, uint32_t count, } if (index != CONST_SLOT_WHEREEVER && index != -1) { // we don't try to equip whereever call - ret = g_moveEvents->onPlayerEquip(const_cast(this), const_cast(item), static_cast(index), true); + ret = g_moveEvents->onPlayerEquip(std::const_pointer_cast(this->getPlayer()), std::const_pointer_cast(item), static_cast(index), true); if (ret != RETURNVALUE_NOERROR) { return ret; } } //need an exchange with source? (destination item is swapped with currently moved item) - const Item* inventoryItem = getInventoryItem(static_cast(index)); + const auto& inventoryItem = getInventoryItem(static_cast(index)); if (inventoryItem && (!inventoryItem->isStackable() || inventoryItem->getID() != item->getID())) { if (!g_config.getBoolean(ConfigManager::CLASSIC_EQUIPMENT_SLOTS)) { - const Cylinder* cylinder = item->getTopParent(); - if (cylinder && (dynamic_cast(cylinder) || dynamic_cast(cylinder))) { + const auto& cylinder = item->getTopParent(); + if (cylinder && (std::dynamic_pointer_cast(cylinder) || std::dynamic_pointer_cast(cylinder))) { return RETURNVALUE_NEEDEXCHANGE; } return RETURNVALUE_NOTENOUGHROOM; @@ -3264,10 +3214,10 @@ 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 ThingPtr& thing, uint32_t count, uint32_t& maxQueryCount, + uint32_t flags) { - const Item* item = thing.getItem(); + auto item = thing->getItem(); if (item == nullptr) { maxQueryCount = 0; return RETURNVALUE_NOTPOSSIBLE; @@ -3276,29 +3226,28 @@ ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t co if (index == INDEX_WHEREEVER) { uint32_t n = 0; for (int32_t slotIndex = CONST_SLOT_FIRST; slotIndex <= CONST_SLOT_LAST; ++slotIndex) { - Item* inventoryItem = inventory[slotIndex]; - if (inventoryItem) { - if (Container* subContainer = inventoryItem->getContainer()) { + if (const auto& inventoryItem = inventory[slotIndex]) { + if (auto subContainer = inventoryItem->getContainer()) { uint32_t queryCount = 0; - subContainer->queryMaxCount(INDEX_WHEREEVER, *item, item->getItemCount(), queryCount, flags); + subContainer->queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags); n += queryCount; //iterate through all items, including sub-containers (deep search) for (ContainerIterator it = subContainer->iterator(); it.hasNext(); it.advance()) { - if (Container* tmpContainer = (*it)->getContainer()) { + if (auto tmpContainer = (*it)->getContainer()) { queryCount = 0; - tmpContainer->queryMaxCount(INDEX_WHEREEVER, *item, item->getItemCount(), queryCount, flags); + tmpContainer->queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags); n += queryCount; } } } else if (inventoryItem->isStackable() && item->equals(inventoryItem) && inventoryItem->getItemCount() < 100) { - uint32_t remainder = (100 - inventoryItem->getItemCount()); + const uint32_t remainder = (100 - inventoryItem->getItemCount()); - if (queryAdd(slotIndex, *item, remainder, flags) == RETURNVALUE_NOERROR) { + if (queryAdd(slotIndex, item, remainder, flags) == RETURNVALUE_NOERROR) { 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 { @@ -3309,10 +3258,9 @@ ReturnValue Player::queryMaxCount(int32_t index, const Thing& thing, uint32_t co maxQueryCount = n; } else { - const Item* destItem = nullptr; + ItemPtr destItem = nullptr; - const Thing* destThing = getThing(index); - if (destThing) { + if (const auto& destThing = getThing(index)) { destItem = destThing->getItem(); } @@ -3322,7 +3270,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 { @@ -3340,14 +3288,14 @@ 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 ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr /*= nullptr*/) { - int32_t index = getThingIndex(&thing); + int32_t index = getThingIndex(thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; } - const Item* item = thing.getItem(); + const auto& item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -3363,25 +3311,24 @@ 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, +CylinderPtr Player::queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, uint32_t& flags) { if (index == 0 /*drop to capacity window*/ || index == INDEX_WHEREEVER) { *destItem = nullptr; - const Item* item = thing.getItem(); + ItemPtr item = thing->getItem(); if (item == nullptr) { - return this; + return this->getPlayer(); } - bool autoStack = !((flags & FLAG_IGNOREAUTOSTACK) == FLAG_IGNOREAUTOSTACK); - bool isStackable = item->isStackable(); + const bool autoStack = !((flags & FLAG_IGNOREAUTOSTACK) == FLAG_IGNOREAUTOSTACK); + const bool isStackable = item->isStackable(); - std::vector containers; + std::vector containers; for (uint32_t slotIndex = CONST_SLOT_FIRST; slotIndex <= CONST_SLOT_LAST; ++slotIndex) { - Item* inventoryItem = inventory[slotIndex]; - if (inventoryItem) { + if (auto inventoryItem = inventory[slotIndex]) { if (inventoryItem == tradeItem) { continue; } @@ -3392,35 +3339,35 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de if (autoStack && isStackable) { //try find an already existing item to stack with - if (queryAdd(slotIndex, *item, item->getItemCount(), 0) == RETURNVALUE_NOERROR) { + if (queryAdd(slotIndex, item, item->getItemCount(), 0) == RETURNVALUE_NOERROR) { if (inventoryItem->equals(item) && inventoryItem->getItemCount() < 100) { index = slotIndex; *destItem = inventoryItem; - return this; + return this->getPlayer(); } } - if (Container* subContainer = inventoryItem->getContainer()) { + if (const auto& subContainer = inventoryItem->getContainer()) { containers.push_back(subContainer); } - } else if (Container* subContainer = inventoryItem->getContainer()) { + } else if (const auto& 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; + return this->getPlayer(); } } size_t i = 0; while (i < containers.size()) { - Container* tmpContainer = containers[i++]; + const auto& tmpContainer = containers[i++]; if (!autoStack || !isStackable) { //we need to find first empty container as fast as we can for non-stackable items uint32_t n = tmpContainer->capacity() - std::min(tmpContainer->capacity(), static_cast(tmpContainer->size())); while (n) { - if (tmpContainer->queryAdd(tmpContainer->capacity() - n, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { + if (tmpContainer->queryAdd(tmpContainer->capacity() - n, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { index = tmpContainer->capacity() - n; *destItem = nullptr; return tmpContainer; @@ -3429,8 +3376,8 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de --n; } - for (Item* tmpContainerItem : tmpContainer->getItemList()) { - if (Container* subContainer = tmpContainerItem->getContainer()) { + for (const auto& tmpContainerItem : tmpContainer->getItemList()) { + if (const auto& subContainer = tmpContainerItem->getContainer()) { containers.push_back(subContainer); } } @@ -3440,7 +3387,7 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de uint32_t n = 0; - for (Item* tmpItem : tmpContainer->getItemList()) { + for (auto tmpItem : tmpContainer->getItemList()) { if (tmpItem == tradeItem) { continue; } @@ -3456,64 +3403,63 @@ Cylinder* Player::queryDestination(int32_t& index, const Thing& thing, Item** de return tmpContainer; } - if (Container* subContainer = tmpItem->getContainer()) { + if (const auto& subContainer = tmpItem->getContainer()) { containers.push_back(subContainer); } n++; } - if (n < tmpContainer->capacity() && tmpContainer->queryAdd(n, *item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { + if (n < tmpContainer->capacity() && tmpContainer->queryAdd(n, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { index = n; *destItem = nullptr; return tmpContainer; } } - return this; + return this->getPlayer(); } - Thing* destThing = getThing(index); + const auto& destThing = getThing(index); if (destThing) { *destItem = destThing->getItem(); } - Cylinder* subCylinder = dynamic_cast(destThing); - if (subCylinder) { + if (const auto& subCylinder = std::dynamic_pointer_cast(destThing)) { index = INDEX_WHEREEVER; *destItem = nullptr; return subCylinder; } else { - return this; + return this->getPlayer(); } } -void Player::addThing(int32_t index, Thing* thing) +void Player::addThing(int32_t index, ThingPtr thing) { if (index < CONST_SLOT_FIRST || index > CONST_SLOT_LAST) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - item->setParent(this); + item->setParent(getPlayer()); inventory[index] = item; //send to client sendInventoryItem(static_cast(index), item); } -void Player::updateThing(Thing* thing, uint16_t itemId, uint32_t count) +void Player::updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3528,18 +3474,18 @@ void Player::updateThing(Thing* thing, uint16_t itemId, uint32_t count) onUpdateInventoryItem(item, item); } -void Player::replaceThing(uint32_t index, Thing* thing) +void Player::replaceThing(uint32_t index, ThingPtr thing) { if (index > CONST_SLOT_LAST) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* oldItem = getInventoryItem(static_cast(index)); + const auto& oldItem = getInventoryItem(static_cast(index)); if (!oldItem) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3549,15 +3495,14 @@ void Player::replaceThing(uint32_t index, Thing* thing) //event methods onUpdateInventoryItem(oldItem, item); - - item->setParent(this); + item->setParent(getPlayer()); inventory[index] = item; } -void Player::removeThing(Thing* thing, uint32_t count) +void Player::removeThing(ThingPtr thing, uint32_t count) { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3575,7 +3520,7 @@ void Player::removeThing(Thing* thing, uint32_t count) //event methods onRemoveInventoryItem(item); - item->setParent(nullptr); + item->clearParent(); inventory[index] = nullptr; } else { uint8_t newCount = static_cast(std::max(0, item->getItemCount() - count)); @@ -3593,13 +3538,12 @@ void Player::removeThing(Thing* thing, uint32_t count) //event methods onRemoveInventoryItem(item); - - item->setParent(nullptr); + item->clearParent(); inventory[index] = nullptr; } } -int32_t Player::getThingIndex(const Thing* thing) const +int32_t Player::getThingIndex(ThingPtr thing) { for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { if (inventory[i] == thing) { @@ -3619,11 +3563,11 @@ 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(const 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]; + const auto& item = inventory[i]; if (!item) { continue; } @@ -3632,7 +3576,7 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con count += Item::countByType(item, subType); } - if (Container* container = item->getContainer()) { + if (const auto& container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if ((*it)->getID() == itemId) { count += Item::countByType(*it, subType); @@ -3643,17 +3587,17 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con return count; } -bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, bool ignoreEquipped/* = false*/) const +bool Player::removeItemOfType(const uint16_t itemId, uint32_t amount, int32_t subType, bool ignoreEquipped/* = false*/) const { if (amount == 0) { return true; } - std::vector itemList; + std::vector itemList; uint32_t count = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - Item* item = inventory[i]; + const auto& item = inventory[i]; if (!item) { continue; } @@ -3671,11 +3615,11 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, g_game.internalRemoveItems(std::move(itemList), amount, Item::items[itemId].stackable); return true; } - } else if (Container* container = item->getContainer()) { + } else if (const auto& container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - Item* containerItem = *it; + const auto& containerItem = *it; if (containerItem->getID() == itemId) { - uint32_t itemCount = Item::countByType(containerItem, subType); + const uint32_t itemCount = Item::countByType(containerItem, subType); if (itemCount == 0) { continue; } @@ -3697,14 +3641,14 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, std::map& Player::getAllItemTypeCount(std::map& countMap) const { for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - Item* item = inventory[i]; + const auto& item = inventory[i]; if (!item) { continue; } countMap[item->getID()] += Item::countByType(item, -1); - if (Container* container = item->getContainer()) { + if (const auto& container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { countMap[(*it)->getID()] += Item::countByType(*it, -1); } @@ -3713,7 +3657,7 @@ std::map& Player::getAllItemTypeCount(std::map= CONST_SLOT_FIRST && index <= CONST_SLOT_LAST) { return inventory[index]; @@ -3721,14 +3665,14 @@ Thing* Player::getThing(size_t index) const return nullptr; } -void Player::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t link /*= LINK_OWNER*/) +void Player::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link /*= LINK_OWNER*/) { if (link == LINK_OWNER) { //calling movement scripts - g_moveEvents->onPlayerEquip(this, thing->getItem(), static_cast(index), false); - g_events->eventPlayerOnInventoryUpdate(this, thing->getItem(), static_cast(index), true); + g_moveEvents->onPlayerEquip(this->getPlayer(), thing->getItem(), static_cast(index), false); + g_events->eventPlayerOnInventoryUpdate(this->getPlayer(), thing->getItem(), static_cast(index), true); if (isInventorySlot(static_cast(index))) { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (item && item->hasImbuements()) { addItemImbuements(thing->getItem()); } @@ -3738,58 +3682,58 @@ void Player::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_ bool requireListUpdate = false; if (link == LINK_OWNER || link == LINK_TOPPARENT) { - const Item* i = (oldParent ? oldParent->getItem() : nullptr); + const auto& i = (oldParent ? oldParent->getItem() : nullptr); // Check if we owned the old container too, so we don't need to do anything, // as the list was updated in postRemoveNotification - assert(i ? i->getContainer() != nullptr : true); + /* assert(i ? i->getContainer() != nullptr : true); if (i) { requireListUpdate = static_cast(i)->getHoldingPlayer() != this; } else { requireListUpdate = oldParent != this; - } - + } */ + requireListUpdate = true; updateInventoryWeight(); updateItemsLight(); sendStats(); } - if (const Item* item = thing->getItem()) { - if (const Container* container = item->getContainer()) { + if (const auto& item = thing->getItem()) { + if (const auto& container = item->getContainer()) { onSendContainer(container); } if (shopOwner && requireListUpdate) { updateSaleShopList(item); } - } else if (const Creature* creature = thing->getCreature()) { - if (creature == this) { + } else if (const auto& creature = thing->getCreature()) { + if (creature == getCreature()) { //check containers - std::vector containers; + std::vector containers; - for (const auto& it : openContainers) { - Container* container = it.second.container; + for (const auto& val : openContainers | std::views::values) { + const auto& container = val.container; if (!Position::areInRange<1, 1, 0>(container->getPosition(), getPosition())) { containers.push_back(container); } } - for (const Container* container : containers) { + for (const auto& container : containers) { autoCloseContainers(container); } } } } -void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t link /*= LINK_OWNER*/) +void Player::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link /*= LINK_OWNER*/) { if (link == LINK_OWNER) { //calling movement scripts - g_moveEvents->onPlayerDeEquip(this, thing->getItem(), static_cast(index)); - g_events->eventPlayerOnInventoryUpdate(this, thing->getItem(), static_cast(index), false); + g_moveEvents->onPlayerDeEquip(this->getPlayer(), thing->getItem(), static_cast(index)); + g_events->eventPlayerOnInventoryUpdate(this->getPlayer(), thing->getItem(), static_cast(index), false); if (isInventorySlot(static_cast(index))) { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (item && item->hasImbuements()) { removeItemImbuements(thing->getItem()); } @@ -3799,31 +3743,32 @@ void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int bool requireListUpdate = false; if (link == LINK_OWNER || link == LINK_TOPPARENT) { - const Item* i = (newParent ? newParent->getItem() : nullptr); + // const Item* i = (newParent ? newParent->getItem() : nullptr); // Check if we owned the old container too, so we don't need to do anything, // as the list was updated in postRemoveNotification - assert(i ? i->getContainer() != nullptr : true); + /* assert(i ? i->getContainer() != nullptr : true); if (i) { requireListUpdate = static_cast(i)->getHoldingPlayer() != this; } else { requireListUpdate = newParent != this; - } - + } */ + + requireListUpdate = true; updateInventoryWeight(); updateItemsLight(); sendStats(); } - if (const Item* item = thing->getItem()) { - if (const Container* container = item->getContainer()) { + if (const auto& item = thing->getItem()) { + if (const auto& container = item->getContainer()) { if (container->isRemoved() || !Position::areInRange<1, 1, 0>(getPosition(), container->getPosition())) { autoCloseContainers(container); - } else if (container->getTopParent() == this) { + } else if (container->getItem()->getTopParent() == this->getPlayer()) { onSendContainer(container); - } else if (const Container* topContainer = dynamic_cast(container->getTopParent())) { - if (const DepotChest* depotChest = dynamic_cast(topContainer)) { + } else if (const auto& topContainer = std::dynamic_pointer_cast(container->getItem()->getTopParent())) { + if (const auto& depotChest = std::dynamic_pointer_cast(topContainer)) { bool isOwner = false; for (const auto& it : depotChests) { @@ -3836,7 +3781,7 @@ void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int if (!isOwner) { autoCloseContainers(container); } - } else if (const Inbox* inboxContainer = dynamic_cast(topContainer)) { + } else if (const auto& inboxContainer = std::dynamic_pointer_cast(topContainer)) { if (inboxContainer == inbox) { onSendContainer(container); } else { @@ -3856,7 +3801,7 @@ void Player::postRemoveNotification(Thing* thing, const Cylinder* newParent, int } } -bool Player::updateSaleShopList(const Item* item) +bool Player::updateSaleShopList(const ItemConstPtr& item) { uint16_t itemId = item->getID(); bool isCurrency = false; @@ -3868,15 +3813,15 @@ bool Player::updateSaleShopList(const Item* item) } if (!isCurrency) { - auto it = std::find_if(shopItemList.begin(), shopItemList.end(), [itemId](const ShopInfo& shopInfo) { return shopInfo.itemId == itemId && shopInfo.sellPrice != 0; }); + const auto it = std::ranges::find_if(shopItemList, [itemId](const ShopInfo& shopInfo) { return shopInfo.itemId == itemId && shopInfo.sellPrice != 0; }); if (it == shopItemList.end()) { - const Container* container = item->getContainer(); + const auto& container = item->getContainer(); if (!container) { return false; } const auto& items = container->getItemList(); - return std::any_of(items.begin(), items.end(), [this](const Item* containerItem) { + return std::any_of(items.begin(), items.end(), [this](const ItemPtr& containerItem) { return updateSaleShopList(containerItem); }); } @@ -3896,14 +3841,14 @@ bool Player::hasShopItemForSale(uint32_t itemId, uint8_t subType) const }); } -void Player::internalAddThing(Thing* thing) +void Player::internalAddThing(ThingPtr thing) { internalAddThing(0, thing); } -void Player::internalAddThing(uint32_t index, Thing* thing) +void Player::internalAddThing(uint32_t index, ThingPtr thing) { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (!item) { return; } @@ -3915,11 +3860,11 @@ void Player::internalAddThing(uint32_t index, Thing* thing) } inventory[index] = item; - item->setParent(this); + item->setParent(getPlayer()); } } -bool Player::setFollowCreature(Creature* creature) +bool Player::setFollowCreature(const CreaturePtr& creature) { if (!Creature::setFollowCreature(creature)) { setFollowCreature(nullptr); @@ -3933,7 +3878,7 @@ bool Player::setFollowCreature(Creature* creature) return true; } -bool Player::setAttackedCreature(Creature* creature) +bool Player::setAttackedCreature(const CreaturePtr& creature) { if (!Creature::setAttackedCreature(creature)) { sendCancelTarget(); @@ -3970,7 +3915,7 @@ void Player::goToFollowCreature() } } -void Player::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const +void Player::getPathSearchParams(const CreatureConstPtr& creature, FindPathParams& fpp) const { Creature::getPathSearchParams(creature, fpp); fpp.fullPathSearch = true; @@ -3989,21 +3934,21 @@ void Player::doAttacking(uint32_t) if ((OTSYS_TIME() - lastAttack) >= getAttackSpeed()) { bool result = false; - Item* tool = getWeapon(); - const Weapon* weapon = g_weapons->getWeapon(tool); + const auto& tool = getWeapon(); + const auto& weapon = g_weapons->getWeapon(tool); uint32_t delay = getAttackSpeed(); bool classicSpeed = g_config.getBoolean(ConfigManager::CLASSIC_ATTACK_SPEED); if (weapon) { if (!weapon->interruptSwing()) { - result = weapon->useWeapon(this, tool, attackedCreature); + result = weapon->useWeapon(this->getPlayer(), tool, attackedCreature); } else if (!classicSpeed && !canDoAction()) { delay = getNextActionTime(); } else { - result = weapon->useWeapon(this, tool, attackedCreature); + result = weapon->useWeapon(this->getPlayer(), tool, attackedCreature); } } else { - result = Weapon::useFist(this, attackedCreature); + result = Weapon::useFist(this->getPlayer(), attackedCreature); } SchedulerTask* task = createSchedulerTask(std::max(SCHEDULER_MINTICKS, delay), [id = getID()]() { g_game.checkCreatureAttack(id); }); @@ -4020,25 +3965,25 @@ void Player::doAttacking(uint32_t) } } -uint64_t Player::getGainedExperience(Creature* attacker) const +uint64_t Player::getGainedExperience(const CreaturePtr& attacker) const { if (g_config.getBoolean(ConfigManager::EXPERIENCE_FROM_PLAYERS)) { - Player* attackerPlayer = attacker->getPlayer(); - if (attackerPlayer && attackerPlayer != this && skillLoss && std::abs(static_cast(attackerPlayer->getLevel() - level)) <= g_config.getNumber(ConfigManager::EXP_FROM_PLAYERS_LEVEL_RANGE)) { + const auto attackerPlayer = attacker->getPlayer(); + if (attackerPlayer && attackerPlayer != this->getPlayer() && skillLoss && std::abs(static_cast(attackerPlayer->getLevel() - level)) <= g_config.getNumber(ConfigManager::EXP_FROM_PLAYERS_LEVEL_RANGE)) { return std::max(0, std::floor(getLostExperience() * getDamageRatio(attacker) * 0.75)); } } return 0; } -void Player::onFollowCreature(const Creature* creature) +void Player::onFollowCreature(const CreatureConstPtr& creature) { if (!creature) { stopWalk(); } } -void Player::setChaseMode(bool mode) +void Player::setChaseMode(const bool mode) { bool prevChaseMode = chaseMode; chaseMode = mode; @@ -4088,8 +4033,7 @@ void Player::updateItemsLight(bool internal /*=false*/) LightInfo maxLight; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - Item* item = inventory[i]; - if (item) { + if (const auto& item = inventory[i]) { LightInfo curLight = item->getLightInfo(); if (curLight.level > maxLight.level) { @@ -4102,12 +4046,12 @@ void Player::updateItemsLight(bool internal /*=false*/) itemsLight = maxLight; if (!internal) { - g_game.changeLight(this); + g_game.changeLight(this->getPlayer()); } } } -void Player::onAddCondition(ConditionType_t type) +void Player::onAddCondition(const ConditionType_t type) { Creature::onAddCondition(type); @@ -4118,7 +4062,7 @@ void Player::onAddCondition(ConditionType_t type) sendIcons(); } -void Player::onAddCombatCondition(ConditionType_t type) +void Player::onAddCombatCondition(const ConditionType_t type) { switch (type) { case CONDITION_POISON: @@ -4158,7 +4102,7 @@ void Player::onAddCombatCondition(ConditionType_t type) } } -void Player::onEndCondition(ConditionType_t type) +void Player::onEndCondition(const ConditionType_t type) { Creature::onEndCondition(type); @@ -4181,8 +4125,7 @@ void Player::onCombatRemoveCondition(Condition* condition) if (condition->getId() > 0) { //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) { + if (const auto& item = getInventoryItem(static_cast(condition->getId()))) { //25% chance to destroy the item if (25 >= uniform_random(1, 100)) { g_game.internalRemoveItem(item); @@ -4204,7 +4147,7 @@ void Player::onCombatRemoveCondition(Condition* condition) } } -void Player::onAttackedCreature(Creature* target, bool addFightTicks /* = true */) +void Player::onAttackedCreature(const CreaturePtr& target, bool addFightTicks /* = true */) { Creature::onAttackedCreature(target); @@ -4212,7 +4155,7 @@ void Player::onAttackedCreature(Creature* target, bool addFightTicks /* = true * return; } - if (target == this) { + if (target == getCreature()) { if (addFightTicks) { addInFightTicks(); } @@ -4223,7 +4166,7 @@ void Player::onAttackedCreature(Creature* target, bool addFightTicks /* = true * return; } - Player* targetPlayer = target->getPlayer(); + const auto& targetPlayer = target->getPlayer(); if (targetPlayer && !isPartner(targetPlayer) && !isGuildMate(targetPlayer)) { if (!pzLocked && g_game.getWorldType() == WORLD_TYPE_PVP_ENFORCED) { pzLocked = true; @@ -4234,14 +4177,14 @@ void Player::onAttackedCreature(Creature* target, bool addFightTicks /* = true * if (getSkull() == SKULL_NONE && getSkullClient(targetPlayer) == SKULL_YELLOW) { addAttacked(targetPlayer); - targetPlayer->sendCreatureSkull(this); - } else if (!targetPlayer->hasAttacked(this)) { + targetPlayer->sendCreatureSkull(this->getPlayer()); + } else if (!targetPlayer->hasAttacked(this->getPlayer())) { if (!pzLocked) { pzLocked = true; sendIcons(); } - if (!Combat::isInPvpZone(this, targetPlayer) && !isInWar(targetPlayer)) { + if (!Combat::isInPvpZone(this->getPlayer(), targetPlayer) && !isInWar(targetPlayer)) { addAttacked(targetPlayer); if (targetPlayer->getSkull() == SKULL_NONE && getSkull() == SKULL_NONE) { @@ -4249,7 +4192,7 @@ void Player::onAttackedCreature(Creature* target, bool addFightTicks /* = true * } if (getSkull() == SKULL_NONE) { - targetPlayer->sendCreatureSkull(this); + targetPlayer->sendCreatureSkull(this->getPlayer()); } } } @@ -4272,53 +4215,53 @@ void Player::onIdleStatus() Creature::onIdleStatus(); if (party) { - party->clearPlayerPoints(this); + party->clearPlayerPoints(this->getPlayer()); } } void Player::onPlacedCreature() { //scripting event - onLogin - if (!g_creatureEvents->playerLogin(this)) { + if (!g_creatureEvents->playerLogin(this->getPlayer())) { kickPlayer(true); } } -void Player::onAttackedCreatureDrainHealth(Creature* target, int32_t points) +void Player::onAttackedCreatureDrainHealth(const CreaturePtr& target, int32_t points) { Creature::onAttackedCreatureDrainHealth(target, points); if (target) { if (party && !Combat::isPlayerCombat(target)) { - Monster* tmpMonster = target->getMonster(); + const auto& tmpMonster = target->getMonster(); if (tmpMonster && tmpMonster->isHostile()) { //We have fulfilled a requirement for shared experience - party->updatePlayerTicks(this, points); + party->updatePlayerTicks(this->getPlayer(), points); } } } } -void Player::onTargetCreatureGainHealth(Creature* target, int32_t points) +void Player::onTargetCreatureGainHealth(const CreaturePtr& target, int32_t points) { if (target && party) { - Player* tmpPlayer = nullptr; + PlayerPtr tmpPlayer = nullptr; if (target->getPlayer()) { tmpPlayer = target->getPlayer(); - } else if (Creature* targetMaster = target->getMaster()) { - if (Player* targetMasterPlayer = targetMaster->getPlayer()) { + } else if (const auto& targetMaster = target->getMaster()) { + if (const auto& targetMasterPlayer = targetMaster->getPlayer()) { tmpPlayer = targetMasterPlayer; } } if (isPartner(tmpPlayer)) { - party->updatePlayerTicks(this, points); + party->updatePlayerTicks(this->getPlayer(), points); } } } -bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) +bool Player::onKilledCreature(const CreaturePtr& target, bool lastHit/* = true*/) { bool unjustified = false; @@ -4328,7 +4271,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) Creature::onKilledCreature(target, lastHit); - Player* targetPlayer = target->getPlayer(); + PlayerPtr targetPlayer = target->getPlayer(); if (!targetPlayer) { return false; } @@ -4337,7 +4280,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) targetPlayer->setDropLoot(false); targetPlayer->setSkillLoss(false); } else if (!hasFlag(PlayerFlag_NotGainInFight) && !isPartner(targetPlayer)) { - if (!Combat::isInPvpZone(this, targetPlayer) && hasAttacked(targetPlayer) && !targetPlayer->hasAttacked(this) && !isGuildMate(targetPlayer) && targetPlayer != this) { + if (!Combat::isInPvpZone(this->getPlayer(), targetPlayer) && hasAttacked(targetPlayer) && !targetPlayer->hasAttacked(this->getPlayer()) && !isGuildMate(targetPlayer) && targetPlayer != this->getPlayer()) { if (targetPlayer->getSkull() == SKULL_NONE && !isInWar(targetPlayer)) { unjustified = true; addUnjustifiedDead(targetPlayer); @@ -4354,7 +4297,7 @@ bool Player::onKilledCreature(Creature* target, bool lastHit/* = true*/) return unjustified; } -void Player::gainExperience(uint64_t gainExp, Creature* source) +void Player::gainExperience(uint64_t gainExp, const CreaturePtr& source) { if (hasFlag(PlayerFlag_NotGainExperience) || gainExp == 0 || staminaMinutes == 0) { return; @@ -4363,7 +4306,7 @@ void Player::gainExperience(uint64_t gainExp, Creature* source) addExperience(source, gainExp, true); } -void Player::onGainExperience(uint64_t gainExp, Creature* target) +void Player::onGainExperience(uint64_t gainExp, const CreaturePtr& target) { if (hasFlag(PlayerFlag_NotGainExperience)) { return; @@ -4379,7 +4322,7 @@ void Player::onGainExperience(uint64_t gainExp, Creature* target) gainExperience(gainExp, target); } -void Player::onGainSharedExperience(uint64_t gainExp, Creature* source) +void Player::onGainSharedExperience(uint64_t gainExp, const CreaturePtr& source) { gainExperience(gainExp, source); } @@ -4405,7 +4348,7 @@ bool Player::isAttackable() const return !hasFlag(PlayerFlag_CannotBeAttacked); } -bool Player::lastHitIsPlayer(Creature* lastHitCreature) +bool Player::lastHitIsPlayer(const CreaturePtr& lastHitCreature) { if (!lastHitCreature) { return false; @@ -4415,7 +4358,7 @@ bool Player::lastHitIsPlayer(Creature* lastHitCreature) return true; } - Creature* lastHitMaster = lastHitCreature->getMaster(); + const auto& lastHitMaster = lastHitCreature->getMaster(); return lastHitMaster && lastHitMaster->getPlayer(); } @@ -4505,7 +4448,7 @@ bool Player::canWear(uint32_t lookType, uint8_t addons) const return false; } -bool Player::hasOutfit(uint32_t lookType, uint8_t addons) +bool Player::hasOutfit(uint32_t lookType, uint8_t addons) const { const Outfit* outfit = Outfits::getInstance().getOutfitByLookType(sex, lookType); if (!outfit) { @@ -4598,7 +4541,7 @@ bool Player::getOutfitAddons(const Outfit& outfit, uint8_t& addons) const return true; } -void Player::setSex(PlayerSex_t newSex) +void Player::setSex(const PlayerSex_t newSex) { sex = newSex; } @@ -4611,18 +4554,18 @@ Skulls_t Player::getSkull() const return skull; } -Skulls_t Player::getSkullClient(const Creature* creature) const +Skulls_t Player::getSkullClient(const CreatureConstPtr& creature) const { if (!creature || g_game.getWorldType() != WORLD_TYPE_PVP) { return SKULL_NONE; } - const Player* player = creature->getPlayer(); + const auto& player = creature->getPlayer(); if (!player || player->getSkull() != SKULL_NONE) { return Creature::getSkullClient(creature); } - if (player->hasAttacked(this)) { + if (player->hasAttacked(this->getPlayer())) { return SKULL_YELLOW; } @@ -4632,27 +4575,27 @@ Skulls_t Player::getSkullClient(const Creature* creature) const return Creature::getSkullClient(creature); } -bool Player::hasAttacked(const Player* attacked) const +bool Player::hasAttacked(const PlayerConstPtr& attacked) const { if (hasFlag(PlayerFlag_NotGainInFight) || !attacked) { return false; } - return attackedSet.find(attacked->guid) != attackedSet.end(); + return attackedSet.contains(attacked->guid); } -void Player::addAttacked(const Player* attacked) +void Player::addAttacked(const PlayerConstPtr& attacked) { - if (hasFlag(PlayerFlag_NotGainInFight) || !attacked || attacked == this) { + if (hasFlag(PlayerFlag_NotGainInFight) || !attacked || attacked == this->getPlayer()) { return; } attackedSet.insert(attacked->guid); } -void Player::removeAttacked(const Player* attacked) +void Player::removeAttacked(const PlayerConstPtr& attacked) { - if (!attacked || attacked == this) { + if (!attacked || attacked == this->getPlayer()) { return; } @@ -4667,9 +4610,9 @@ void Player::clearAttacked() attackedSet.clear(); } -void Player::addUnjustifiedDead(const Player* attacked) +void Player::addUnjustifiedDead(const PlayerConstPtr& attacked) { - if (hasFlag(PlayerFlag_NotGainInFight) || attacked == this || g_game.getWorldType() == WORLD_TYPE_PVP_ENFORCED) { + if (hasFlag(PlayerFlag_NotGainInFight) || attacked == this->getPlayer() || g_game.getWorldType() == WORLD_TYPE_PVP_ENFORCED) { return; } @@ -4686,10 +4629,9 @@ void Player::addUnjustifiedDead(const Player* attacked) } } -void Player::checkSkullTicks(int64_t ticks) +void Player::checkSkullTicks(const int64_t ticks) { - int64_t newTicks = skullTicks - ticks; - if (newTicks < 0) { + if (const int64_t newTicks = skullTicks - ticks; newTicks < 0) { skullTicks = 0; } else { skullTicks = newTicks; @@ -4720,7 +4662,7 @@ double Player::getLostPercent() const double lossPercent; if (level >= 25) { - double tmpLevel = level + (levelPercent / 100.); + const double tmpLevel = level + (levelPercent / 100.); lossPercent = static_cast((tmpLevel + 50) * 50 * ((tmpLevel * tmpLevel) - (5 * tmpLevel) + 8)) / experience; } else { lossPercent = 10; @@ -4764,7 +4706,7 @@ bool Player::hasLearnedInstantSpell(const std::string& spellName) const return false; } -bool Player::isInWar(const Player* player) const +bool Player::isInWar(const PlayerConstPtr& player) const { if (!player || !guild) { return false; @@ -4778,9 +4720,9 @@ 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(const uint32_t guildId) const { - return std::find(guildWarVector.begin(), guildWarVector.end(), guildId) != guildWarVector.end(); + return std::ranges::find(guildWarVector, guildId) != guildWarVector.end(); } bool Player::isPremium() const @@ -4792,13 +4734,13 @@ bool Player::isPremium() const return premiumEndsAt > time(nullptr); } -void Player::setPremiumTime(time_t premiumEndsAt) +void Player::setPremiumTime(const time_t premiumEndsAt) { this->premiumEndsAt = premiumEndsAt; sendBasicData(); } -PartyShields_t Player::getPartyShield(const Player* player) const +PartyShields_t Player::getPartyShield(const PlayerConstPtr& player) const { if (!player) { return SHIELD_NONE; @@ -4842,7 +4784,7 @@ PartyShields_t Player::getPartyShield(const Player* player) const } } - if (player->isInviting(this)) { + if (player->isInviting(this->getPlayer())) { return SHIELD_WHITEYELLOW; } @@ -4853,23 +4795,23 @@ PartyShields_t Player::getPartyShield(const Player* player) const return SHIELD_NONE; } -bool Player::isInviting(const Player* player) const +bool Player::isInviting(const PlayerConstPtr& player) const { - if (!player || !party || party->getLeader() != this) { + if (!player || !party || party->getLeader() != this->getPlayer()) { return false; } return party->isPlayerInvited(player); } -bool Player::isPartner(const Player* player) const +bool Player::isPartner(const PlayerConstPtr& player) const { - if (!player || !party || player == this) { + if (!player || !party || player == this->getPlayer()) { return false; } return party == player->party; } -bool Player::isGuildMate(const Player* player) const +bool Player::isGuildMate(const PlayerConstPtr& player) const { if (!player || !guild) { return false; @@ -4877,7 +4819,7 @@ bool Player::isGuildMate(const Player* player) const return guild == player->guild; } -void Player::sendPlayerPartyIcons(Player* player) +void Player::sendPlayerPartyIcons(const PlayerPtr& player) const { sendCreatureShield(player); sendCreatureSkull(player); @@ -4885,8 +4827,7 @@ void Player::sendPlayerPartyIcons(Player* player) bool Player::addPartyInvitation(Party* party) { - auto it = std::find(invitePartyList.begin(), invitePartyList.end(), party); - if (it != invitePartyList.end()) { + if (const auto it = std::ranges::find(invitePartyList, party); it != invitePartyList.end()) { return false; } @@ -4902,12 +4843,12 @@ void Player::removePartyInvitation(Party* party) void Player::clearPartyInvitations() { for (Party* invitingParty : invitePartyList) { - invitingParty->removeInvite(*this, false); + invitingParty->removeInvite(this->getPlayer(), false); } invitePartyList.clear(); } -GuildEmblems_t Player::getGuildEmblem(const Player* player) const +GuildEmblems_t Player::getGuildEmblem(const PlayerConstPtr& player) const { if (!player) { return GUILDEMBLEM_NONE; @@ -4942,12 +4883,12 @@ uint8_t Player::getCurrentMount() const return 0; } -void Player::setCurrentMount(uint8_t mountId) +void Player::setCurrentMount(const uint8_t mountId) { addStorageValue(PSTRG_MOUNTS_CURRENTMOUNT, mountId); } -bool Player::toggleMount(bool mount) +bool Player::toggleMount(const bool mount) { if ((OTSYS_TIME() - lastToggleMount) < 3000 && !wasMounted) { sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); @@ -4959,23 +4900,23 @@ bool Player::toggleMount(bool mount) return false; } - if (!group->access && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { + if (!group->access && tile.lock()->hasFlag(TILESTATE_PROTECTIONZONE)) { sendCancelMessage(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE); return false; } - const Outfit* playerOutfit = Outfits::getInstance().getOutfitByLookType(getSex(), defaultOutfit.lookType); + const auto& playerOutfit = Outfits::getInstance().getOutfitByLookType(getSex(), defaultOutfit.lookType); if (!playerOutfit) { return false; } - uint8_t currentMountId = getCurrentMount(); + const uint8_t currentMountId = getCurrentMount(); if (currentMountId == 0) { sendOutfitWindow(); return false; } - Mount* currentMount = g_game.mounts.getMountByID(currentMountId); + const auto& currentMount = g_game.mounts.getMountByID(currentMountId); if (!currentMount) { return false; } @@ -4999,7 +4940,7 @@ bool Player::toggleMount(bool mount) defaultOutfit.lookMount = currentMount->clientId; if (currentMount->speed != 0) { - g_game.changeSpeed(this, currentMount->speed); + g_game.changeSpeed(this->getPlayer(), currentMount->speed); } } else { if (!isMounted()) { @@ -5009,12 +4950,12 @@ bool Player::toggleMount(bool mount) dismount(); } - g_game.internalCreatureChangeOutfit(this, defaultOutfit); + g_game.internalCreatureChangeOutfit(this->getPlayer(), defaultOutfit); lastToggleMount = OTSYS_TIME(); return true; } -bool Player::tameMount(uint8_t mountId) +bool Player::tameMount(const uint8_t mountId) { if (!g_game.mounts.getMountByID(mountId)) { return false; @@ -5034,7 +4975,7 @@ bool Player::tameMount(uint8_t mountId) return true; } -bool Player::untameMount(uint8_t mountId) +bool Player::untameMount(const uint8_t mountId) { if (!g_game.mounts.getMountByID(mountId)) { return false; @@ -5054,7 +4995,7 @@ bool Player::untameMount(uint8_t mountId) if (getCurrentMount() == mountId) { if (isMounted()) { dismount(); - g_game.internalCreatureChangeOutfit(this, defaultOutfit); + g_game.internalCreatureChangeOutfit(this->getPlayer(), defaultOutfit); } setCurrentMount(0); @@ -5085,9 +5026,9 @@ bool Player::hasMount(const Mount* mount) const void Player::dismount() { - Mount* mount = g_game.mounts.getMountByID(getCurrentMount()); + const auto& mount = g_game.mounts.getMountByID(getCurrentMount()); if (mount && mount->speed > 0) { - g_game.changeSpeed(this, -mount->speed); + g_game.changeSpeed(this->getPlayer(), -mount->speed); } defaultOutfit.lookMount = 0; @@ -5114,7 +5055,7 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) oldSkillValue = magLevel; oldPercentToNextLevel = static_cast(manaSpent * 100) / nextReqMana; - g_events->eventPlayerOnGainSkillTries(this, SKILL_MAGLEVEL, tries); + g_events->eventPlayerOnGainSkillTries(this->getPlayer(), SKILL_MAGLEVEL, tries); uint32_t currMagLevel = magLevel; while ((manaSpent + tries) >= nextReqMana) { @@ -5123,7 +5064,7 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) magLevel++; manaSpent = 0; - g_creatureEvents->playerAdvance(this, SKILL_MAGLEVEL, magLevel - 1, magLevel); + g_creatureEvents->playerAdvance(this->getPlayer(), SKILL_MAGLEVEL, magLevel - 1, magLevel); sendUpdate = true; currReqMana = nextReqMana; @@ -5166,7 +5107,7 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) oldSkillValue = skills[skill].level; oldPercentToNextLevel = static_cast(skills[skill].tries * 100) / nextReqTries; - g_events->eventPlayerOnGainSkillTries(this, skill, tries); + g_events->eventPlayerOnGainSkillTries(this->getPlayer(), skill, tries); uint32_t currSkillLevel = skills[skill].level; while ((skills[skill].tries + tries) >= nextReqTries) { @@ -5176,7 +5117,7 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) skills[skill].tries = 0; skills[skill].percent = 0; - g_creatureEvents->playerAdvance(this, skill, (skills[skill].level - 1), skills[skill].level); + g_creatureEvents->playerAdvance(this->getPlayer(), skill, (skills[skill].level - 1), skills[skill].level); sendUpdate = true; currReqTries = nextReqTries; @@ -5219,12 +5160,12 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) return sendUpdate; } -bool Player::hasModalWindowOpen(uint32_t modalWindowId) const +bool Player::hasModalWindowOpen(const uint32_t modalWindowId) const { - return find(modalWindows.begin(), modalWindows.end(), modalWindowId) != modalWindows.end(); + return std::ranges::find(modalWindows, modalWindowId) != modalWindows.end(); } -void Player::onModalWindowHandled(uint32_t modalWindowId) +void Player::onModalWindowHandled(const uint32_t modalWindowId) { modalWindows.remove(modalWindowId); } @@ -5249,15 +5190,15 @@ uint16_t Player::getHelpers() const uint16_t helpers; if (guild && party) { - std::unordered_set helperSet; + std::unordered_set helperSet; - const auto& guildMembers = guild->getMembersOnline(); + auto guildMembers = guild->getMembersOnline(); helperSet.insert(guildMembers.begin(), guildMembers.end()); - const auto& partyMembers = party->getMembers(); + auto partyMembers = party->getMembers(); helperSet.insert(partyMembers.begin(), partyMembers.end()); - const auto& partyInvitees = party->getInvitees(); + auto partyInvitees = party->getInvitees(); helperSet.insert(partyInvitees.begin(), partyInvitees.end()); helperSet.insert(party->getLeader()); @@ -5274,10 +5215,10 @@ uint16_t Player::getHelpers() const return helpers; } -void Player::sendClosePrivate(uint16_t channelId) +void Player::sendClosePrivate(const uint16_t channelId) { if (channelId == CHANNEL_GUILD || channelId == CHANNEL_PARTY) { - g_chat->removeUserFromChannel(*this, channelId); + g_chat->removeUserFromChannel(this->getPlayer(), channelId); } if (client) { @@ -5287,17 +5228,16 @@ void Player::sendClosePrivate(uint16_t channelId) uint64_t Player::getMoney() const { - std::vector containers; + std::vector containers; uint64_t moneyCount = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - Item* item = inventory[i]; + const auto& item = inventory[i]; if (!item) { continue; } - const Container* container = item->getContainer(); - if (container) { + if (const auto& container = item->getContainer()) { containers.push_back(container); } else { moneyCount += item->getWorth(); @@ -5306,10 +5246,9 @@ uint64_t Player::getMoney() const size_t i = 0; while (i < containers.size()) { - const Container* container = containers[i++]; - for (const Item* item : container->getItemList()) { - const Container* tmpContainer = item->getContainer(); - if (tmpContainer) { + const auto& container = containers[i++]; + for (const auto& item : container->getItemList()) { + if (const auto& tmpContainer = item->getContainer()) { containers.push_back(tmpContainer); } else { moneyCount += item->getWorth(); @@ -5337,36 +5276,35 @@ size_t Player::getMaxDepotItems() const return g_config.getNumber(isPremium() ? ConfigManager::DEPOT_PREMIUM_LIMIT : ConfigManager::DEPOT_FREE_LIMIT); } -const bool Player::addAugment(std::shared_ptr& augment) { - if (std::find(augments.begin(), augments.end(), augment) == augments.end()) { +const bool Player::addAugment(const std::shared_ptr& augment) { + if (std::ranges::find(augments, augment) == augments.end()) { augments.push_back(augment); - g_events->eventPlayerOnAugment(this, augment); + g_events->eventPlayerOnAugment(this->getPlayer(), augment); return true; } return false; } -const bool Player::addAugment(std::string_view augmentName) { +const bool Player::addAugment(const std::string_view augmentName) { if (auto augment = Augments::GetAugment(augmentName)) { augments.emplace_back(augment); - g_events->eventPlayerOnAugment(this, augment); + g_events->eventPlayerOnAugment(this->getPlayer(), augment); return true; } return false; } -const bool Player::removeAugment(std::shared_ptr& augment) { - auto it = std::find(augments.begin(), augments.end(), augment); - if (it != augments.end()) { - g_events->eventPlayerOnRemoveAugment(this, augment); +const bool Player::removeAugment(const std::shared_ptr& augment) { + if (const auto it = std::ranges::find(augments, augment); it != augments.end()) { + g_events->eventPlayerOnRemoveAugment(this->getPlayer(), augment); augments.erase(it); return true; } return false; } -const bool Player::isAugmented() +const bool Player::isAugmented() const { return augments.size() > 0; } @@ -5381,7 +5319,7 @@ const bool Player::hasAugment(const std::string_view augmentName, bool checkItem if (checkItems) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = inventory[slot]; + const auto& item = inventory[slot]; for (const auto& aug : item->getAugments()) { if (aug->getName() == augmentName) { return true; @@ -5403,7 +5341,7 @@ const bool Player::hasAugment(const std::shared_ptr& augment, bool chec if (checkItems) { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = inventory[slot]; + const auto& item = inventory[slot]; for (const auto& aug : item->getAugments()) { if (aug == augment) { return true; @@ -5420,16 +5358,15 @@ const std::vector> Player::getPlayerAugments() const { } const bool Player::removeAugment(std::string_view augmentName) { - auto originalSize = augments.size(); + const auto& originalSize = augments.size(); - augments.erase(std::remove_if(augments.begin(), augments.end(), - [&](const std::shared_ptr& augment) { - auto match = augment->getName() == augmentName; - if (match) { - g_events->eventPlayerOnRemoveAugment(this, augment); - } - return augment->getName() == augmentName; - }), augments.end()); + std::erase_if(augments, + [&](const std::shared_ptr& augment) { + if (const auto match = augment->getName() == augmentName) { + g_events->eventPlayerOnRemoveAugment(this->getPlayer(), augment); + } + return augment->getName() == augmentName; + }); return augments.size() > originalSize; } @@ -5473,15 +5410,15 @@ void Player::setGuild(Guild* guild) this->guild = guild; this->guildRank = rank; - guild->addMember(this); + guild->addMember(this->getPlayer()); } if (oldGuild) { - oldGuild->removeMember(this); + oldGuild->removeMember(this->getPlayer()); } } -void Player::updateRegeneration() +void Player::updateRegeneration() const { if (!vocation) { return; @@ -5496,7 +5433,7 @@ void Player::updateRegeneration() } } -void Player::addItemImbuements(Item* item) { +void Player::addItemImbuements(const ItemPtr& item) { if (item->hasImbuements()) { const std::vector>& imbuementList = item->getImbuements(); for (auto& imbue : imbuementList) { @@ -5552,7 +5489,7 @@ void Player::addItemImbuements(Item* item) { capacity += imbue->value; break; case ImbuementType::IMBUEMENT_TYPE_SPEED_BOOST: - g_game.changeSpeed(this, static_cast(imbue->value)); + g_game.changeSpeed(this->getPlayer(), static_cast(imbue->value)); break; } } @@ -5562,7 +5499,7 @@ void Player::addItemImbuements(Item* item) { sendStats(); } -void Player::removeItemImbuements(Item* item) { +void Player::removeItemImbuements(const ItemPtr& item) { if (item->hasImbuements()) { const std::vector>& imbuementList = item->getImbuements(); for (auto& imbue : imbuementList) { @@ -5618,7 +5555,7 @@ void Player::removeItemImbuements(Item* item) { capacity -= imbue->value; break; case ImbuementType::IMBUEMENT_TYPE_SPEED_BOOST: - g_game.changeSpeed(this, -static_cast(imbue->value)); + g_game.changeSpeed(this->getPlayer(), -static_cast(imbue->value)); break; } } @@ -5629,7 +5566,7 @@ void Player::removeItemImbuements(Item* item) { } -void Player::removeImbuementEffect(std::shared_ptr imbue) { +void Player::removeImbuementEffect(const std::shared_ptr& imbue) { if (imbue->isSkill()) { switch (imbue->imbuetype) { @@ -5683,7 +5620,7 @@ void Player::removeImbuementEffect(std::shared_ptr imbue) { capacity -= imbue->value; break; case ImbuementType::IMBUEMENT_TYPE_SPEED_BOOST: - g_game.changeSpeed(this, -static_cast(imbue->value)); + g_game.changeSpeed(this->getPlayer(), -static_cast(imbue->value)); break; } } @@ -5691,7 +5628,7 @@ void Player::removeImbuementEffect(std::shared_ptr imbue) { sendStats(); } -void Player::addImbuementEffect(std::shared_ptr imbue) { +void Player::addImbuementEffect(const std::shared_ptr& imbue) { if (imbue->isSkill()) { switch (imbue->imbuetype) { @@ -5745,7 +5682,7 @@ void Player::addImbuementEffect(std::shared_ptr imbue) { capacity += imbue->value; break; case ImbuementType::IMBUEMENT_TYPE_SPEED_BOOST: - g_game.changeSpeed(this, static_cast(imbue->value)); + g_game.changeSpeed(this->getPlayer(), static_cast(imbue->value)); break; } } @@ -5753,11 +5690,12 @@ void Player::addImbuementEffect(std::shared_ptr imbue) { sendStats(); } -CreatureType_t Player::getCreatureType(Monster& monster) { +CreatureType_t Player::getCreatureType(const MonsterPtr& monster) const +{ auto creatureType = CREATURETYPE_MONSTER; - if (monster.getFriendList().size() > 0) { - for (auto monsterFriend : monster.getFriendList()) { - if (Player* ally = monsterFriend->getPlayer()) { + if (monster->getFriendList().size() > 0) { + for (auto monsterFriend : monster->getFriendList()) { + if (const auto& ally = monsterFriend->getPlayer()) { if (ally->getGuild() && this->getGuild() && ally->getGuild() == this->getGuild()) { creatureType = CREATURETYPE_SUMMON_GUILD; @@ -5770,13 +5708,13 @@ CreatureType_t Player::getCreatureType(Monster& monster) { } } - if (monster.getMaster() && monster.getMaster()->getID() == this->getID()) { + if (monster->getMaster() && monster->getMaster()->getID() == this->getID()) { creatureType = CREATURETYPE_SUMMON_OWN; } return creatureType; } -static ModifierTotals getValidatedTotals(const std::vector> modifierList, const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName) { +static ModifierTotals getValidatedTotals(const std::vector>& modifierList, const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName) { uint16_t percent = 0; uint16_t flat = 0; // to-do: const and auto& @@ -5808,27 +5746,27 @@ static ModifierTotals getValidatedTotals(const std::vector>> Player::getAttackModifiers() { +std::unordered_map >> Player::getAttackModifiers() const +{ std::unordered_map>> modifierMap; if (!augments.empty()) { - for (auto& aug : augments) { - for (auto mod : aug->getAttackModifiers()) { + for (const auto& aug : augments) { + for (const auto& mod : aug->getAttackModifiers()) { modifierMap[mod->getType()].emplace_back(mod); } } } for (uint8_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_RING; ++slot) { - Item* item = inventory[slot]; - if (item && !item->getAugments().empty()) { - for (auto& aug : item->getAugments()) { + if (const auto& item = inventory[slot]; item && !item->getAugments().empty()) { + for (const auto& aug : item->getAugments()) { if (!g_config.getBoolean(ConfigManager::AUGMENT_SLOT_PROTECTION) || (item->getEquipSlot() == getPositionForSlot(static_cast(slot)))) { - for (auto mod : aug->getAttackModifiers()) { + for (const auto& mod : aug->getAttackModifiers()) { modifierMap[mod->getType()].emplace_back(mod); } } else if ( g_config.getBoolean(ConfigManager::AUGMENT_SLOT_PROTECTION) && (slot == CONST_SLOT_RIGHT || slot == CONST_SLOT_LEFT) && (item->getWeaponType() != WEAPON_NONE && item->getWeaponType() != WEAPON_AMMO)) { - for (auto mod : aug->getAttackModifiers()) { + for (const auto& mod : aug->getAttackModifiers()) { modifierMap[mod->getType()].emplace_back(mod); } } @@ -5839,34 +5777,33 @@ std::unordered_map >> Playe return modifierMap; } -std::unordered_map >> Player::getDefenseModifiers() { +std::unordered_map >> Player::getDefenseModifiers() const +{ std::unordered_map>> modifierMap; if (!augments.empty()) { - for (auto& aug : augments) { - for (auto mod : aug->getDefenseModifiers()) { + for (const auto& aug : augments) { + for (const auto& mod : aug->getDefenseModifiers()) { modifierMap[mod->getType()].emplace_back(mod); } } } for (uint8_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_RING; ++slot) { - Item* item = inventory[slot]; - if (item && !item->getAugments().empty()) { - for (auto& aug : item->getAugments()) { + if (const auto& item = inventory[slot]; item && !item->getAugments().empty()) { + for (const auto& aug : item->getAugments()) { if (!g_config.getBoolean(ConfigManager::AUGMENT_SLOT_PROTECTION) || (item->getEquipSlot() == getPositionForSlot(static_cast(slot)))) { - for (auto mod : aug->getDefenseModifiers()) { + for (const auto& mod : aug->getDefenseModifiers()) { modifierMap[mod->getType()].emplace_back(mod); } } else if (g_config.getBoolean(ConfigManager::AUGMENT_SLOT_PROTECTION) && (slot == CONST_SLOT_RIGHT || slot == CONST_SLOT_LEFT) && (item->getWeaponType() != WEAPON_NONE && item->getWeaponType() != WEAPON_AMMO)) { - for (auto mod : aug->getDefenseModifiers()) { + for (const auto& mod : aug->getDefenseModifiers()) { modifierMap[mod->getType()].emplace_back(mod); } } } } } - return modifierMap; } @@ -5878,7 +5815,8 @@ std::unordered_map Player::getConvertedTotals(const uin std::unordered_map itemList; itemList.reserve(COMBAT_COUNT); - [[unlikely]]if ((modType != ATTACK_MODIFIER_CONVERSION) && (modType != DEFENSE_MODIFIER_REFORM)) { + [[unlikely]] + if ((modType != ATTACK_MODIFIER_CONVERSION) && (modType != DEFENSE_MODIFIER_REFORM)) { std::cout << "::: WARNING Player::getConvertedTotals called with invalid Mod Type! \n"; return playerList; } @@ -5909,9 +5847,8 @@ std::unordered_map Player::getConvertedTotals(const uin } percent = std::min(percent, 100); - auto index = combatTypeToIndex(modifier->getConversionType()); - auto [it, inserted] = playerList.try_emplace(index, ModifierTotals{flat, percent}); - if (!inserted) { + const auto& index = combatTypeToIndex(modifier->getConversionType()); + if (auto [it, inserted] = playerList.try_emplace(index, ModifierTotals{flat, percent}); !inserted) { it->second += ModifierTotals{flat, percent}; } } @@ -5920,8 +5857,7 @@ std::unordered_map Player::getConvertedTotals(const uin } for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = inventory[slot]; - if (item && !item->getAugments().empty()) { + if (const auto& item = inventory[slot]; item && !item->getAugments().empty()) { for (const auto& aug : item->getAugments()) { const auto& modifiers = modType == ATTACK_MODIFIER_CONVERSION ? aug->getAttackModifiers(modType) : aug->getDefenseModifiers(modType); for (const auto& modifier : modifiers) { @@ -5947,9 +5883,8 @@ std::unordered_map Player::getConvertedTotals(const uin } percent = std::min(percent, 100); - auto index = combatTypeToIndex(modifier->getConversionType()); - auto [it, inserted] = playerList.try_emplace(index, ModifierTotals{flat, percent}); - if (!inserted) { + const auto index = combatTypeToIndex(modifier->getConversionType()); + if (auto [it, inserted] = playerList.try_emplace(index, ModifierTotals{flat, percent}); !inserted) { it->second += ModifierTotals{flat, percent}; } } @@ -5961,7 +5896,8 @@ std::unordered_map Player::getConvertedTotals(const uin return playerList; } -std::unordered_map Player::getAttackModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName) { +std::unordered_map Player::getAttackModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName) const +{ std::unordered_map modMap; modMap.reserve(ATTACK_MODIFIER_LAST); @@ -5974,7 +5910,8 @@ std::unordered_map Player::getAttackModifierTotals(cons return modMap; } -std::unordered_map Player::getDefenseModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, std::string_view creatureName) { +std::unordered_map Player::getDefenseModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, std::string_view creatureName) const +{ std::unordered_map modMap; modMap.reserve(DEFENSE_MODIFIER_LAST); @@ -6018,7 +5955,7 @@ std::vector Player::getOpenPositionsInRadius(int radius) const { return openPositions; } -void Player::absorbDamage(std::optional> attacker, +void Player::absorbDamage(const std::optional attacker, CombatDamage& originalDamage, int32_t percent, int32_t flat) { @@ -6048,15 +5985,15 @@ void Player::absorbDamage(std::optional> attack absorbParams.distanceEffect = CONST_ANI_NONE; if (!attacker.has_value()) { - Combat::doTargetCombat(nullptr, this, absorb, absorbParams); + Combat::doTargetCombat(nullptr, this->getPlayer(), absorb, absorbParams); return; } - Combat::doTargetCombat(&attacker.value().get(), this, absorb, absorbParams); + Combat::doTargetCombat(attacker.value(), this->getPlayer(), absorb, absorbParams); } } -void Player::restoreManaFromDamage(std::optional> attacker, +void Player::restoreManaFromDamage(std::optional attacker, CombatDamage& originalDamage, int32_t percent, int32_t flat) { @@ -6086,15 +6023,15 @@ void Player::restoreManaFromDamage(std::optionalgetPlayer(), restore, restoreParams); return; } - Combat::doTargetCombat(&attacker.value().get(), this, restore, restoreParams); + Combat::doTargetCombat(attacker.value(), this->getPlayer(), restore, restoreParams); } } -void Player::reviveSoulFromDamage(std::optional> attacker, +void Player::reviveSoulFromDamage(std::optional attacker, CombatDamage& originalDamage, int32_t percent, int32_t flat) { @@ -6112,7 +6049,7 @@ void Player::reviveSoulFromDamage(std::optional originalDamage.primary.value += reviveDamage; auto message = (attacker.has_value()) ? - "You gained " + std::to_string(reviveDamage) + " soul from " + attacker.value().get().getName() + "'s attack." : + "You gained " + std::to_string(reviveDamage) + " soul from " + attacker.value()->getName() + "'s attack." : "You gained " + std::to_string(reviveDamage) + " soul from revival."; sendTextMessage(MESSAGE_HEALED, message); @@ -6120,7 +6057,7 @@ void Player::reviveSoulFromDamage(std::optional } } -void Player::replenishStaminaFromDamage(std::optional> attacker, +void Player::replenishStaminaFromDamage(std::optional attacker, CombatDamage& originalDamage, int32_t percent, int32_t flat) { @@ -6142,7 +6079,7 @@ void Player::replenishStaminaFromDamage(std::optionalgetName() + "'s attack." : "You gained " + std::to_string(replenishDamage) + " stamina from replenishment."; sendTextMessage(MESSAGE_HEALED, message); @@ -6150,10 +6087,11 @@ void Player::replenishStaminaFromDamage(std::optional> attacker, +void Player::resistDamage(std::optional attacker, CombatDamage& originalDamage, int32_t percent, - int32_t flat) { + int32_t flat) const +{ int32_t resistDamage = 0; const int32_t originalDamageValue = std::abs(originalDamage.primary.value); if (percent) { @@ -6168,14 +6106,14 @@ void Player::resistDamage(std::optional> attack originalDamage.primary.value += resistDamage; auto message = (attacker.has_value()) ? - "You resisted " + std::to_string(resistDamage) + " damage from " + attacker.value().get().getName() + "'s attack." : + "You resisted " + std::to_string(resistDamage) + " damage from " + attacker.value()->getName() + "'s attack." : "You resisted " + std::to_string(resistDamage) + " damage."; sendTextMessage(MESSAGE_HEALED, message); } } -void Player::reflectDamage(std::optional> attacker, +void Player::reflectDamage(std::optional attacker, CombatDamage& originalDamage, int32_t percent, int32_t flat, @@ -6196,7 +6134,7 @@ void Player::reflectDamage(std::optional> attac } if (reflectDamage != 0) { - Creature& target = attacker.value().get(); + const auto& target = attacker.value(); reflectDamage = std::min(reflectDamage, originalDamageValue); originalDamage.primary.value += reflectDamage; @@ -6213,14 +6151,14 @@ void Player::reflectDamage(std::optional> attac sendTextMessage( MESSAGE_DAMAGE_DEALT, - "You reflected " + std::to_string(reflectDamage) + " damage from " + target.getName() + "'s attack back at them." + "You reflected " + std::to_string(reflectDamage) + " damage from " + target->getName() + "'s attack back at them." ); - Combat::doTargetCombat(this, &target, reflect, params); + Combat::doTargetCombat(this->getPlayer(), target, reflect, params); } } -void Player::deflectDamage(std::optional> attackerOpt, +void Player::deflectDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat, @@ -6249,8 +6187,8 @@ void Player::deflectDamage(std::optional> attac ); auto defensePos = getPosition(); - auto attackPos = generateAttackPosition(attackerOpt, defensePos, paramOrigin); - auto damageArea = generateDeflectArea(attackerOpt, calculatedTargets); + const auto attackPos = generateAttackPosition(attackerOpt, defensePos, paramOrigin); + const auto damageArea = generateDeflectArea(attackerOpt, calculatedTargets); auto deflect = CombatDamage{}; deflect.primary.type = originalDamage.primary.type; @@ -6271,7 +6209,7 @@ void Player::deflectDamage(std::optional> attac "You deflected " + std::to_string(deflectDamage) + " total damage." ); - Combat::doAreaCombat(this, attackPos, damageArea.get(), deflect, params); + Combat::doAreaCombat(this->getPlayer(), attackPos, damageArea.get(), deflect, params); } } @@ -6313,23 +6251,23 @@ void Player::ricochetDamage(CombatDamage& originalDamage, params.targetCasterOrTopMost = true; params.impactEffect = (areaEffect == CONST_ME_NONE) ? CombatTypeToAreaEffect(originalDamage.primary.type) : areaEffect; - auto damageArea = std::make_unique(); + const auto& damageArea = std::make_unique(); damageArea->setupArea(Deflect1xArea, 5); - Combat::doAreaCombat(this, targetPos, damageArea.get(), ricochet, params); + Combat::doAreaCombat(this->getPlayer(), targetPos, damageArea.get(), ricochet, params); } } -void Player::convertDamage(Creature* target, CombatDamage& originalDamage, std::unordered_map conversionList) { +void Player::convertDamage(const CreaturePtr& target, CombatDamage& originalDamage, std::unordered_map conversionList) { auto iter = conversionList.begin(); while (originalDamage.primary.value < 0 && iter != conversionList.end()) { - CombatType_t combatType = indexToCombatType(iter->first); - ModifierTotals& totals = iter->second; + const CombatType_t combatType = indexToCombatType(iter->first); + const ModifierTotals& totals = iter->second; int32_t convertedDamage = 0; - int32_t percent = static_cast(totals.percentTotal); - int32_t flat = static_cast(totals.flatTotal); + const int32_t percent = static_cast(totals.percentTotal); + const int32_t flat = static_cast(totals.flatTotal); const int32_t originalDamageValue = std::abs(originalDamage.primary.value); if (percent) { convertedDamage += originalDamageValue * percent / 100; @@ -6353,19 +6291,19 @@ void Player::convertDamage(Creature* target, CombatDamage& originalDamage, std:: auto message = "You converted " + std::to_string(convertedDamage) + " " + getCombatName(originalDamage.primary.type) + " damage to " + getCombatName(combatType) + " during an attack on " + target->getName() + "."; sendTextMessage(MESSAGE_DAMAGE_DEALT, message); - Combat::doTargetCombat(this, target, converted, params); + Combat::doTargetCombat(this->getPlayer(), target, converted, params); } ++iter; } } -void Player::reformDamage(std::optional> attacker, CombatDamage& originalDamage, std::unordered_map conversionList) { +void Player::reformDamage(std::optional attacker, CombatDamage& originalDamage, std::unordered_map conversionList) { auto iter = conversionList.begin(); while (originalDamage.primary.value < 0 && iter != conversionList.end()) { CombatType_t combatType = indexToCombatType(iter->first); - ModifierTotals& totals = iter->second; + const ModifierTotals& totals = iter->second; int32_t reformedDamage = 0; int32_t percent = static_cast(totals.percentTotal); @@ -6392,21 +6330,21 @@ void Player::reformDamage(std::optional> attack params.origin = ORIGIN_AUGMENT; auto message = (attacker.has_value()) ? - "You reformed " + std::to_string(reformedDamage) + " " + getCombatName(originalDamage.primary.type) + " damage from " + getCombatName(combatType) + " during an attack on you by " + attacker.value().get().getName() + "." : + "You reformed " + std::to_string(reformedDamage) + " " + getCombatName(originalDamage.primary.type) + " damage from " + getCombatName(combatType) + " during an attack on you by " + attacker.value()->getName() + "." : "You reformed " + std::to_string(reformedDamage) + " " + getCombatName(originalDamage.primary.type) + " damage from " + getCombatName(combatType) + "."; sendTextMessage(MESSAGE_DAMAGE_DEALT, message); - auto target = (attacker.has_value()) ? &attacker.value().get() : nullptr; - Combat::doTargetCombat(target, this, reform, params); + auto target = (attacker.has_value()) ? attacker.value() : nullptr; + Combat::doTargetCombat(target, this->getPlayer(), reform, params); } ++iter; } } -Position Player::generateAttackPosition(std::optional> attacker, Position& defensePosition, CombatOrigin origin) { +Position Player::generateAttackPosition(std::optional attacker, Position& defensePosition, CombatOrigin origin) { const Direction attackDirection = (attacker.has_value()) - ? getDirectionTo(defensePosition, attacker.value().get().getPosition()) + ? getDirectionTo(defensePosition, attacker.value()->getPosition()) : getOppositeDirection(this->getDirection()); // Offsets @@ -6434,7 +6372,7 @@ Position Player::generateAttackPosition(std::optionalgetZone() == ZONE_PROTECTION @@ -6459,23 +6397,23 @@ Position Player::generateAttackPosition(std::optionalgetDirection())); + return vectorSize ? possibleTargets[index] : Spells::getCasterPosition(this->getPlayer(), getOppositeDirection(this->getDirection())); } -std::unique_ptr Player::generateDeflectArea(std::optional> attacker, int32_t targetCount) { +std::unique_ptr Player::generateDeflectArea(std::optional attacker, int32_t targetCount) const +{ auto combatArea = std::make_unique(); - auto defendersPosition = this->getPosition(); - auto direction = (attacker.has_value()) ? getDirectionTo(defendersPosition, attacker.value().get().getPosition()) : getOppositeDirection(this->getDirection()); - - switch (direction) { + const auto defendersPosition = this->getPosition(); + + switch (const auto direction = (attacker.has_value()) ? getDirectionTo(defendersPosition, attacker.value()->getPosition()) : getOppositeDirection(this->getDirection())) { case DIRECTION_NORTH: case DIRECTION_EAST: case DIRECTION_SOUTH: case DIRECTION_WEST: { - auto targetAreas = _StandardDeflectionMap.find(targetCount)->second; + const auto targetAreas = _StandardDeflectionMap.find(targetCount)->second; if (!targetAreas.empty()) { - auto index = std::rand() % targetAreas.size(); - auto area = targetAreas[index]; + const auto index = std::rand() % targetAreas.size(); + const auto area = targetAreas[index]; combatArea->setupArea(area, 5); } break; @@ -6484,18 +6422,18 @@ std::unique_ptr Player::generateDeflectArea(std::optionalsecond; - if (!targetAreas.empty()) { - auto index = std::rand() % targetAreas.size(); - auto area = targetAreas[index]; + if (const auto targetAreas = _DiagonalDeflectionMap.find(targetCount)->second; !targetAreas.empty()) { + const auto index = std::rand() % targetAreas.size(); + const auto area = targetAreas[index]; combatArea->setupExtArea(area, 5); } break; } - [[unlikely]]default: + [[unlikely]] + default: std::cerr << "Deflection area attempted to be generated from unknown direction!" << std::endl; break; } return combatArea; -} \ No newline at end of file +} diff --git a/src/player.h b/src/player.h index 02c68237..79f3449f 100644 --- a/src/player.h +++ b/src/player.h @@ -102,7 +102,7 @@ struct VIPEntry { }; struct OpenContainer { - Container* container; + ContainerPtr container; uint16_t index; }; @@ -131,17 +131,25 @@ class Player final : public Creature, public Cylinder { public: explicit Player(ProtocolGame_ptr p); - ~Player(); + + static std::shared_ptr makePlayer(ProtocolGame_ptr p) { + auto player = std::shared_ptr(new Player(p)); + player->storeInbox->setParent(player); + return player; + } + + ~Player() override; // non-copyable Player(const Player&) = delete; Player& operator=(const Player&) = delete; - Player* getPlayer() override { - return this; + PlayerPtr getPlayer() override { + return dynamic_shared_this(); } - const Player* getPlayer() const override { - return this; + + PlayerConstPtr getPlayer() const override { + return dynamic_shared_this(); } void setID() override { @@ -155,12 +163,15 @@ class Player final : public Creature, public Cylinder const std::string& getName() const override { return name; } - void setName(std::string_view name) { + + void setName(const std::string_view name) { this->name = name; } + const std::string& getNameDescription() const override { return name; } + std::string getDescription(int32_t lookDistance) const override; CreatureType_t getType() const override { @@ -169,27 +180,32 @@ class Player final : public Creature, public Cylinder uint8_t getCurrentMount() const; void setCurrentMount(uint8_t mountId); + bool isMounted() const { return defaultOutfit.lookMount != 0; } + bool toggleMount(bool mount); bool tameMount(uint8_t mountId); bool untameMount(uint8_t mountId); bool hasMount(const Mount* mount) const; void dismount(); - void sendFYIBox(const std::string& message) { + void sendFYIBox(const std::string& message) const + { if (client) { client->sendFYIBox(message); } } - void setGUID(uint32_t guid) { + void setGUID(const uint32_t guid) { this->guid = guid; } + uint32_t getGUID() const { return guid; } + bool canSeeInvisibility() const override { return hasFlag(PlayerFlag_CanSenseInvisibility) || group->access; } @@ -211,9 +227,11 @@ class Player final : public Creature, public Cylinder void addOfflineTrainingTime(int32_t addTime) { offlineTrainingTime = std::min(12 * 3600 * 1000, offlineTrainingTime + addTime); } + void removeOfflineTrainingTime(int32_t removeTime) { offlineTrainingTime = std::max(0, offlineTrainingTime - removeTime); } + int32_t getOfflineTrainingTime() const { return offlineTrainingTime; } @@ -221,6 +239,7 @@ class Player final : public Creature, public Cylinder int32_t getOfflineTrainingSkill() const { return offlineTrainingSkill; } + void setOfflineTrainingSkill(int32_t skill) { offlineTrainingSkill = skill; } @@ -228,6 +247,7 @@ class Player final : public Creature, public Cylinder uint64_t getBankBalance() const { return bankBalance; } + void setBankBalance(uint64_t balance) { bankBalance = balance; } @@ -235,39 +255,43 @@ class Player final : public Creature, public Cylinder Guild* getGuild() const { return guild; } + void setGuild(Guild* guild); GuildRank_ptr getGuildRank() const { return guildRank; } - void setGuildRank(GuildRank_ptr newGuildRank) { + + void setGuildRank(const GuildRank_ptr& newGuildRank) { guildRank = newGuildRank; } - bool isGuildMate(const Player* player) const; + bool isGuildMate(const PlayerConstPtr& player) const; const std::string& getGuildNick() const { return guildNick; } - void setGuildNick(std::string nick) { + + void setGuildNick(const std::string& nick) { guildNick = nick; } - bool isInWar(const Player* player) const; + bool isInWar(const PlayerConstPtr& player) const; bool isInWarList(uint32_t guildId) const; void setLastWalkthroughAttempt(int64_t walkthroughAttempt) { lastWalkthroughAttempt = walkthroughAttempt; } + void setLastWalkthroughPosition(Position walkthroughPosition) { lastWalkthroughPosition = walkthroughPosition; } - Inbox* getInbox() const { + InboxPtr getInbox() const { return inbox; } - StoreInbox* getStoreInbox() const { + StoreInboxPtr getStoreInbox() const { return storeInbox; } @@ -284,6 +308,7 @@ class Player final : public Creature, public Cylinder OperatingSystem_t getOperatingSystem() const { return operatingSystem; } + void setOperatingSystem(OperatingSystem_t clientos) { operatingSystem = clientos; } @@ -303,18 +328,20 @@ class Player final : public Creature, public Cylinder void setParty(Party* party) { this->party = party; } + Party* getParty() const { return party; } - PartyShields_t getPartyShield(const Player* player) const; - bool isInviting(const Player* player) const; - bool isPartner(const Player* player) const; - void sendPlayerPartyIcons(Player* player); + + PartyShields_t getPartyShield(const PlayerConstPtr& player) const; + bool isInviting(const PlayerConstPtr& player) const; + bool isPartner(const PlayerConstPtr& player) const; + void sendPlayerPartyIcons(const PlayerPtr& player) const; bool addPartyInvitation(Party* party); void removePartyInvitation(Party* party); void clearPartyInvitations(); - GuildEmblems_t getGuildEmblem(const Player* player) const; + GuildEmblems_t getGuildEmblem(const PlayerConstPtr& player) const; uint64_t getSpentMana() const { return manaSpent; @@ -324,19 +351,22 @@ class Player final : public Creature, public Cylinder return (group->flags & value) != 0; } - BedItem* getBedItem() { + BedItemPtr getBedItem() { return bedItem; } - void setBedItem(BedItem* b) { + + void setBedItem(const BedItemPtr& b) { bedItem = b; } void addBlessing(uint8_t blessing) { blessings.set(blessing); } + void removeBlessing(uint8_t blessing) { blessings.reset(blessing); } + bool hasBlessing(uint8_t blessing) const { return blessings.test(blessing); } @@ -344,19 +374,22 @@ class Player final : public Creature, public Cylinder bool isOffline() const { return (getID() == 0); } - void disconnect() { + + void disconnect() const + { if (client) { client->disconnect(); } } + uint32_t getIP() const; - void addContainer(uint8_t cid, Container* container); + void addContainer(uint8_t cid, const ContainerPtr& container); void closeContainer(uint8_t cid); void setContainerIndex(uint8_t cid, uint16_t index); - Container* getContainerByID(uint8_t cid); - int8_t getContainerID(const Container* container) const; + ContainerPtr getContainerByID(uint8_t cid); + int8_t getContainerID(const ContainerConstPtr& container) const; uint16_t getContainerIndex(uint8_t cid) const; bool canOpenCorpse(uint32_t ownerId) const; @@ -368,6 +401,7 @@ class Player final : public Creature, public Cylinder void setGroup(Group* newGroup) { group = newGroup; } + Group* getGroup() const { return group; } @@ -375,9 +409,11 @@ class Player final : public Creature, public Cylinder void setInMarket(bool value) { inMarket = value; } + bool isInMarket() const { return inMarket; } + int32_t getIdleTime() const { return idleTime; } @@ -389,7 +425,9 @@ class Player final : public Creature, public Cylinder bool isInGhostMode() const override { return ghostMode; } - bool canSeeGhostMode(const Creature* creature) const override; + + bool canSeeGhostMode(const CreatureConstPtr& creature) const override; + void switchGhostMode() { ghostMode = !ghostMode; } @@ -397,36 +435,46 @@ class Player final : public Creature, public Cylinder uint32_t getAccount() const { return accountNumber; } + AccountType_t getAccountType() const { return accountType; } + uint32_t getLevel() const { return level; } + uint8_t getLevelPercent() const { return levelPercent; } + uint32_t getMagicLevel() const { return std::max(0, magLevel + varStats[STAT_MAGICPOINTS]); } + uint32_t getBaseMagicLevel() const { return magLevel; } + uint8_t getMagicLevelPercent() const { return magLevelPercent; } + uint8_t getSoul() const { return soul; } + bool isAccessPlayer() const { return group->access; } + bool isPremium() const; void setPremiumTime(time_t premiumEndsAt); uint16_t getHelpers() const; bool setVocation(uint16_t vocId); + uint16_t getVocationId() const { return vocation->getId(); } @@ -434,7 +482,9 @@ class Player final : public Creature, public Cylinder PlayerSex_t getSex() const { return sex; } + void setSex(PlayerSex_t); + uint64_t getExperience() const { return experience; } @@ -450,12 +500,15 @@ class Player final : public Creature, public Cylinder const Position& getLoginPosition() const { return loginPosition; } + const Position& getTemplePosition() const { return town->getTemplePosition(); } + Town* getTown() const { return town; } + void setTown(Town* town) { this->town = town; } @@ -493,20 +546,23 @@ class Player final : public Creature, public Cylinder int32_t getMaxHealth() const override { return std::max(1, healthMax + varStats[STAT_MAXHITPOINTS]); } + uint32_t getMana() const { return mana; } + uint32_t getMaxMana() const { return std::max(0, manaMax + varStats[STAT_MAXMANAPOINTS]); } - Item* getInventoryItem(slots_t slot) const; - Item* getInventoryItem(uint32_t slot) const; - bool isInventorySlot(slots_t slot) const; + ItemPtr getInventoryItem(slots_t slot) const; + ItemPtr getInventoryItem(uint32_t slot) const; + static bool isInventorySlot(slots_t slot); bool isItemAbilityEnabled(slots_t slot) const { return inventoryAbilities[slot]; } + void setItemAbility(slots_t slot, bool enabled) { inventoryAbilities[slot] = enabled; } @@ -525,18 +581,18 @@ class Player final : public Creature, public Cylinder void addConditionSuppressions(uint32_t conditions); void removeConditionSuppressions(uint32_t conditions); - DepotChest* getDepotChest(uint32_t depotId, bool autoCreate); - DepotLocker& getDepotLocker(); + DepotChestPtr getDepotChest(uint32_t depotId, bool autoCreate); + DepotLockerPtr& getDepotLocker(); uint32_t getDepotItemCount(); - RewardChest& getRewardChest(); + RewardChestPtr& getRewardChest(); void onReceiveMail() const; bool isNearDepotBox() const; bool canSee(const Position& pos) const override; - bool canSeeCreature(const Creature* creature) const override; + bool canSeeCreature(const CreatureConstPtr& creature) const override; - bool canWalkthrough(const Creature* creature) const; - bool canWalkthroughEx(const Creature* creature) const; + bool canWalkthrough(const CreatureConstPtr& creature) const; + bool canWalkthroughEx(const CreatureConstPtr& creature) const; RaceType_t getRace() const override { return RACE_BLOOD; @@ -548,45 +604,47 @@ class Player final : public Creature, public Cylinder void setTradeState(tradestate_t state) { tradeState = state; } + tradestate_t getTradeState() const { return tradeState; } - Item* getTradeItem() { + + ItemPtr getTradeItem() { return tradeItem; } //shop functions - void setShopOwner(Npc* owner, int32_t onBuy, int32_t onSell) { + void setShopOwner(const NpcPtr& owner, int32_t onBuy, int32_t onSell) { shopOwner = owner; purchaseCallback = onBuy; saleCallback = onSell; } - Npc* getShopOwner(int32_t& onBuy, int32_t& onSell) { + NpcPtr getShopOwner(int32_t& onBuy, int32_t& onSell) { onBuy = purchaseCallback; onSell = saleCallback; return shopOwner; } - const Npc* getShopOwner(int32_t& onBuy, int32_t& onSell) const { + NpcPtr getShopOwner(int32_t& onBuy, int32_t& onSell) const { onBuy = purchaseCallback; onSell = saleCallback; return shopOwner; } //V.I.P. functions - void notifyStatusChange(Player* loginPlayer, VipStatus_t status); + void notifyStatusChange(const PlayerPtr& loginPlayer, VipStatus_t status); bool removeVIP(uint32_t vipGuid); 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); //follow functions - bool setFollowCreature(Creature* creature) override; + bool setFollowCreature(const CreaturePtr& creature) override; void goToFollowCreature() override; //follow events - void onFollowCreature(const Creature* creature) override; + void onFollowCreature(const CreatureConstPtr& creature) override; //walk events void onWalk(Direction& dir) override; @@ -594,14 +652,14 @@ class Player final : public Creature, public Cylinder void onWalkComplete() override; void stopWalk(); - void openShopWindow(Npc* npc, const std::list& shop); + void openShopWindow(const NpcPtr& npc, const std::list& shop); bool closeShopWindow(bool sendCloseShopWindow = true); - bool updateSaleShopList(const Item* item); + bool updateSaleShopList(const ItemConstPtr& item); bool hasShopItemForSale(uint32_t itemId, uint8_t subType) const; bool isWearingImbuedItem() const { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - Item* item = getInventoryItem(static_cast(slot)); + ItemPtr item = getInventoryItem(static_cast(slot)); if (item && item->hasImbuements()) { return true; } @@ -610,20 +668,22 @@ class Player final : public Creature, public Cylinder } void setChaseMode(bool mode); + void setFightMode(fightMode_t mode) { fightMode = mode; } + void setSecureMode(bool mode) { secureMode = mode; } //combat functions - bool setAttackedCreature(Creature* creature) override; + bool setAttackedCreature(const CreaturePtr& creature) override; bool isImmune(CombatType_t type) const override; bool isImmune(ConditionType_t type) const override; bool hasShield() const; bool isAttackable() const override; - static bool lastHitIsPlayer(Creature* lastHitCreature); + static bool lastHitIsPlayer(const CreaturePtr& lastHitCreature); void changeHealth(int32_t healthChange, bool sendHealthChange = true) override; void changeMana(int32_t manaChange); @@ -635,9 +695,12 @@ class Player final : public Creature, public Cylinder bool isPzLocked() const { return pzLocked; } - BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, + + BlockType_t blockHit(const CreaturePtr& attacker, CombatType_t combatType, int32_t& damage, bool checkDefense = false, bool checkArmor = false, bool field = false, bool ignoreResistances = false) override; + void doAttacking(uint32_t interval) override; + bool hasExtraSwing() override { return lastAttack > 0 && ((OTSYS_TIME() - lastAttack) >= getAttackSpeed()); } @@ -645,12 +708,15 @@ class Player final : public Creature, public Cylinder uint16_t getSpecialSkill(uint8_t skill) const { return std::max(0, varSpecialSkills[skill]); } + uint16_t getSkillLevel(uint8_t skill) const { return std::max(0, skills[skill].level + varSkills[skill]); } + uint16_t getBaseSkill(uint8_t skill) const { return skills[skill].level; } + uint8_t getSkillPercent(uint8_t skill) const { return skills[skill].percent; } @@ -658,18 +724,18 @@ class Player final : public Creature, public Cylinder bool getAddAttackSkill() const { return addAttackSkillPoint; } + BlockType_t getLastAttackBlockType() const { return lastAttackBlockType; } - Item* getWeapon(slots_t slot, bool ignoreAmmo) const; - Item* getWeapon(bool ignoreAmmo = false) const; + ItemPtr getWeapon(slots_t slot, bool ignoreAmmo) const; + ItemPtr 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; + int32_t getWeaponSkill(const ItemConstPtr& item) const; - void drainHealth(Creature* attacker, int32_t damage) override; - void drainMana(Creature* attacker, int32_t manaLoss); + void drainHealth(const CreaturePtr& attacker, int32_t damage) override; + void drainMana(const CreaturePtr& attacker, int32_t manaLoss); void addManaSpent(uint64_t amount); void removeManaSpent(uint64_t amount, bool notify = false); void addSkillAdvance(skills_t skill, uint64_t count); @@ -682,20 +748,20 @@ class Player final : public Creature, public Cylinder void addInFightTicks(bool pzlock = false); - uint64_t getGainedExperience(Creature* attacker) const override; + uint64_t getGainedExperience(const CreaturePtr& attacker) const override; //combat event functions void onAddCondition(ConditionType_t type) override; void onAddCombatCondition(ConditionType_t type) override; void onEndCondition(ConditionType_t type) override; void onCombatRemoveCondition(Condition* condition) override; - void onAttackedCreature(Creature* target, bool addFightTicks = true) override; + void onAttackedCreature(const CreaturePtr& target, bool addFightTicks = true) override; void onAttacked() override; - void onAttackedCreatureDrainHealth(Creature* target, int32_t points) override; - void onTargetCreatureGainHealth(Creature* target, int32_t points) override; - bool onKilledCreature(Creature* target, bool lastHit = true) override; - void onGainExperience(uint64_t gainExp, Creature* target) override; - void onGainSharedExperience(uint64_t gainExp, Creature* source); + void onAttackedCreatureDrainHealth(const CreaturePtr& target, int32_t points) override; + void onTargetCreatureGainHealth(const CreaturePtr& target, int32_t points) override; + bool onKilledCreature(const CreaturePtr& target, bool lastHit = true) override; + void onGainExperience(uint64_t gainExp, const CreaturePtr& target) override; + void onGainSharedExperience(uint64_t gainExp, const CreaturePtr& source); void onAttackedCreatureBlockHit(BlockType_t blockType) override; void onBlockHit() override; void onChangeZone(ZoneType_t zone) override; @@ -706,24 +772,26 @@ class Player final : public Creature, public Cylinder LightInfo getCreatureLight() const override; Skulls_t getSkull() const override; - Skulls_t getSkullClient(const Creature* creature) const override; + Skulls_t getSkullClient(const CreatureConstPtr& creature) const override; int64_t getSkullTicks() const { return skullTicks; } void setSkullTicks(int64_t ticks) { skullTicks = ticks; } - bool hasAttacked(const Player* attacked) const; - void addAttacked(const Player* attacked); - void removeAttacked(const Player* attacked); + bool hasAttacked(const PlayerConstPtr& attacked) const; + void addAttacked(const PlayerConstPtr& attacked); + void removeAttacked(const PlayerConstPtr& attacked); void clearAttacked(); - void addUnjustifiedDead(const Player* attacked); - void sendCreatureSkull(const Creature* creature) const { + void addUnjustifiedDead(const PlayerConstPtr& attacked); + + void sendCreatureSkull(const CreatureConstPtr& creature) const { if (client) { client->sendCreatureSkull(creature); } } + void checkSkullTicks(int64_t ticks); bool canWear(uint32_t lookType, uint8_t addons) const; - bool hasOutfit(uint32_t lookType, uint8_t addons); + bool hasOutfit(uint32_t lookType, uint8_t addons) const; void addOutfit(uint16_t lookType, uint8_t addons); bool removeOutfit(uint16_t lookType); bool removeOutfitAddon(uint16_t lookType, uint8_t addons); @@ -734,92 +802,106 @@ class Player final : public Creature, public Cylinder //tile //send methods - void sendAddTileItem(const Tile* tile, const Position& pos, const Item* item) { + void sendAddTileItem(const TileConstPtr& tile, const Position& pos, const ItemConstPtr& item) const { if (client) { - int32_t stackpos = tile->getStackposOfItem(this, item); + int32_t stackpos = tile->getStackposOfItem(this->getPlayer(), item); if (stackpos != -1) { client->sendAddTileItem(pos, stackpos, item); } } } - void sendUpdateTileItem(const Tile* tile, const Position& pos, const Item* item) { + + void sendUpdateTileItem(const TileConstPtr& tile, const Position& pos, const ItemConstPtr& item) const { if (client) { - int32_t stackpos = tile->getStackposOfItem(this, item); + int32_t stackpos = tile->getStackposOfItem(this->getPlayer(), item); if (stackpos != -1) { client->sendUpdateTileItem(pos, stackpos, item); } } } - void sendRemoveTileThing(const Position& pos, int32_t stackpos) { + + void sendRemoveTileThing(const Position& pos, int32_t stackpos) const { if (stackpos != -1 && client) { client->sendRemoveTileThing(pos, stackpos); } } - void sendUpdateTileCreature(const Creature* creature) { + + void sendUpdateTileCreature(const CreatureConstPtr& creature) const { if (client) { - client->sendUpdateTileCreature(creature->getPosition(), creature->getTile()->getClientIndexOfCreature(this, creature), creature); + client->sendUpdateTileCreature(creature->getPosition(), creature->getTile()->getClientIndexOfCreature(this->getPlayer(), creature), creature); } } - void sendRemoveTileCreature(const Creature* creature, const Position& pos, int32_t stackpos) { + + void sendRemoveTileCreature(const CreatureConstPtr& creature, const Position& pos, int32_t stackpos) const { if (client) { client->sendRemoveTileCreature(creature, pos, stackpos); } } - void sendUpdateTile(const Tile* tile, const Position& pos) { + + void sendUpdateTile(const TileConstPtr& tile, const Position& pos) const { if (client) { client->sendUpdateTile(tile, 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) const { 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) const { if (client) { client->sendChannelEvent(channelId, playerName, channelEvent); } } - void sendCreatureAppear(const Creature* creature, const Position& pos, MagicEffectClasses magicEffect = CONST_ME_NONE) { + + void sendCreatureAppear(const CreatureConstPtr& creature, const Position& pos, MagicEffectClasses magicEffect = CONST_ME_NONE) { if (client) { - client->sendAddCreature(creature, pos, creature->getTile()->getClientIndexOfCreature(this, creature), magicEffect); + client->sendAddCreature(creature, pos, creature->getTile()->getClientIndexOfCreature(this->getPlayer(), creature), magicEffect); } } - void sendCreatureMove(const Creature* creature, const Position& newPos, int32_t newStackPos, const Position& oldPos, int32_t oldStackPos, bool teleport) { + + void sendCreatureMove(const CreatureConstPtr& creature, const Position& newPos, int32_t newStackPos, const Position& oldPos, int32_t oldStackPos, bool teleport) const { if (client) { client->sendMoveCreature(creature, newPos, newStackPos, oldPos, oldStackPos, teleport); } } - void sendCreatureTurn(const Creature* creature) { + + void sendCreatureTurn(const CreatureConstPtr& creature) { if (client && canSeeCreature(creature)) { - int32_t stackpos = creature->getTile()->getClientIndexOfCreature(this, creature); + int32_t stackpos = creature->getTile()->getClientIndexOfCreature(this->getPlayer(), creature); if (stackpos != -1) { client->sendCreatureTurn(creature, stackpos); } } } - void sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string& text, const Position* pos = nullptr) { + + void sendCreatureSay(const CreatureConstPtr& creature, SpeakClasses type, const std::string& text, const Position* pos = nullptr) const { if (client) { client->sendCreatureSay(creature, type, text, pos); } } - void sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string& text) { + + void sendPrivateMessage(const PlayerConstPtr& speaker, SpeakClasses type, const std::string& text) const { if (client) { client->sendPrivateMessage(speaker, type, text); } } - void sendCreatureSquare(const Creature* creature, SquareColor_t color) { + + void sendCreatureSquare(const CreatureConstPtr& creature, SquareColor_t color) const { if (client) { client->sendCreatureSquare(creature, color); } } - void sendCreatureChangeOutfit(const Creature* creature, const Outfit_t& outfit) { + + void sendCreatureChangeOutfit(const CreatureConstPtr& creature, const Outfit_t& outfit) const { if (client) { client->sendCreatureOutfit(creature, outfit); } } - void sendCreatureChangeVisible(const Creature* creature, bool visible) { + + void sendCreatureChangeVisible(const CreatureConstPtr& creature, bool visible) const { if (!client) { return; } @@ -834,7 +916,7 @@ class Player final : public Creature, public Cylinder } else if (canSeeInvisibility()) { client->sendCreatureOutfit(creature, creature->getCurrentOutfit()); } else { - int32_t stackpos = creature->getTile()->getClientIndexOfCreature(this, creature); + int32_t stackpos = creature->getTile()->getClientIndexOfCreature(this->getPlayer(), creature); if (stackpos == -1) { return; } @@ -846,60 +928,70 @@ class Player final : public Creature, public Cylinder } } } - void sendCreatureLight(const Creature* creature) { + + void sendCreatureLight(const CreatureConstPtr& creature) const { if (client) { client->sendCreatureLight(creature); } } - void sendCreatureWalkthrough(const Creature* creature, bool walkthrough) { + + void sendCreatureWalkthrough(const CreatureConstPtr& creature, bool walkthrough) const { if (client) { client->sendCreatureWalkthrough(creature, walkthrough); } } - void sendCreatureShield(const Creature* creature) { + + void sendCreatureShield(const CreatureConstPtr& creature) const { if (client) { client->sendCreatureShield(creature); } } - void sendCreatureType(uint32_t creatureId, uint8_t creatureType) { + + void sendCreatureType(uint32_t creatureId, uint8_t creatureType) const { if (client) { client->sendCreatureType(creatureId, creatureType); } } - void sendCreatureHelpers(uint32_t creatureId, uint16_t helpers) { + + void sendCreatureHelpers(uint32_t creatureId, uint16_t helpers) const { if (client) { client->sendCreatureHelpers(creatureId, helpers); } } - void sendSpellCooldown(uint8_t spellId, uint32_t time) { + + void sendSpellCooldown(uint8_t spellId, uint32_t time) const { if (client) { client->sendSpellCooldown(spellId, time); } } - void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) { + + void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) const { if (client) { client->sendSpellGroupCooldown(groupId, time); } } + void sendModalWindow(const ModalWindow& modalWindow); //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); - void sendContainer(uint8_t cid, const Container* container, bool hasParent, uint16_t firstIndex) { + void sendAddContainerItem(const ContainerConstPtr& container, ItemPtr& item) const; + void sendUpdateContainerItem(const ContainerConstPtr& container, uint16_t slot, const ItemConstPtr& newItem) const; + void sendRemoveContainerItem(const ContainerConstPtr& container, uint16_t slot); + + void sendContainer(uint8_t cid, const ContainerConstPtr& container, bool hasParent, uint16_t firstIndex) const { if (client) { client->sendContainer(cid, container, hasParent, firstIndex); } } //inventory - void sendInventoryItem(slots_t slot, const Item* item) { + void sendInventoryItem(slots_t slot, const ItemConstPtr& item) const { if (client) { client->sendInventoryItem(slot, item); } } - void sendItems() { + + void sendItems() const { if (client) { client->sendItems(); } @@ -908,9 +1000,9 @@ class Player final : public Creature, public Cylinder void sendQuiverUpdate(bool sendAll = false) { if (!sendAll) { // update one slot - Thing* slotThing = getThing(CONST_SLOT_RIGHT); + auto slotThing = getThing(CONST_SLOT_RIGHT); if (slotThing) { - Item* slotItem = slotThing->getItem(); + auto slotItem = slotThing->getItem(); if (slotItem && slotItem->getWeaponType() == WEAPON_QUIVER) { sendInventoryItem(CONST_SLOT_RIGHT, slotItem); } @@ -919,9 +1011,9 @@ class Player final : public Creature, public Cylinder // update all slots std::vector slots = {CONST_SLOT_RIGHT, CONST_SLOT_LEFT, CONST_SLOT_AMMO}; for (auto const& slot : slots) { - Thing* slotThing = getThing(slot); + auto slotThing = getThing(slot); if (slotThing) { - Item* slotItem = slotThing->getItem(); + auto slotItem = slotThing->getItem(); if (slotItem && slotItem->getWeaponType() == WEAPON_QUIVER) { sendInventoryItem(slot, slotItem); } @@ -931,255 +1023,301 @@ 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; + void onUpdateTileItem(const TilePtr& tile, const Position& pos, const ItemPtr& oldItem, + const ItemType& oldType, const ItemPtr& newItem, const ItemType& newType) override; + void onRemoveTileItem(const TilePtr& tile, const Position& pos, const ItemType& iType, + const ItemPtr& 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 onCreatureAppear(const CreaturePtr& creature, bool isLogin) override; + void onRemoveCreature(const CreaturePtr& creature, bool isLogout) override; + void onCreatureMove(const CreaturePtr& creature, const TilePtr& newTile, const Position& newPos, + const TilePtr& oldTile, const Position& oldPos, bool teleport) override; void onAttackedCreatureDisappear(bool isLogout) override; void onFollowCreatureDisappear(bool isLogout) override; //container - void onAddContainerItem(const Item* item); - void onUpdateContainerItem(const Container* container, const Item* oldItem, const Item* newItem); - void onRemoveContainerItem(const Container* container, const Item* item); + void onAddContainerItem(const ItemPtr& item); + void onUpdateContainerItem(const ContainerPtr& container, const ItemPtr& oldItem, const ItemPtr& newItem); + void onRemoveContainerItem(const ContainerPtr& container, const ItemPtr& item); - void onCloseContainer(const Container* container); - void onSendContainer(const Container* container); - void autoCloseContainers(const Container* container); + void onCloseContainer(const ContainerConstPtr& container) const; + void onSendContainer(const ContainerPtr& container) const; + void autoCloseContainers(const ContainerConstPtr& container); //inventory - void onUpdateInventoryItem(Item* oldItem, Item* newItem); - void onRemoveInventoryItem(Item* item); + void onUpdateInventoryItem(const ItemPtr& oldItem, const ItemPtr& newItem); + void onRemoveInventoryItem(const ItemPtr& item); void sendCancelMessage(const std::string& msg) const { if (client) { client->sendTextMessage(TextMessage(MESSAGE_STATUS_SMALL, msg)); } } + void sendCancelMessage(ReturnValue message) const; + void sendCancelTarget() const { if (client) { client->sendCancelTarget(); } } + void sendCancelWalk() const { if (client) { client->sendCancelWalk(); } } - void sendChangeSpeed(const Creature* creature, uint32_t newSpeed) const { + + void sendChangeSpeed(const CreatureConstPtr& creature, uint32_t newSpeed) const { if (client) { client->sendChangeSpeed(creature, newSpeed); } } - void sendCreatureHealth(const Creature* creature) const { + + void sendCreatureHealth(const CreatureConstPtr& creature) const { if (client) { client->sendCreatureHealth(creature); } } + void sendDistanceShoot(const Position& from, const Position& to, unsigned char 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) const { if (client) { client->sendCreatePrivateChannel(channelId, channelName); } } + void sendClosePrivate(uint16_t channelId); + void sendIcons() const { if (client) { client->sendIcons(getClientIcons()); } } + void sendMagicEffect(const Position& pos, uint8_t type) const { if (client) { client->sendMagicEffect(pos, type); } } + void sendPing(); + void sendPingBack() const { if (client) { client->sendPingBack(); } } + void sendStats(); + void sendBasicData() const { if (client) { client->sendBasicData(); } } + void sendSkills() const { if (client) { client->sendSkills(); } } + void sendTextMessage(MessageClasses mclass, const std::string& message) const { if (client) { client->sendTextMessage(TextMessage(mclass, message)); } } + void sendTextMessage(const TextMessage& message) const { if (client) { client->sendTextMessage(message); } } + void sendReLoginWindow(uint8_t unfairFightReduction) const { if (client) { client->sendReLoginWindow(unfairFightReduction); } } - void sendTextWindow(Item* item, uint16_t maxlen, bool canWrite) const { + + void sendTextWindow(const ItemPtr& item, uint16_t maxlen, bool canWrite) const { if (client) { client->sendTextWindow(windowTextId, item, maxlen, canWrite); } } + void sendTextWindow(uint32_t itemId, const std::string& text) const { if (client) { client->sendTextWindow(windowTextId, itemId, text); } } - void sendToChannel(const Creature* creature, SpeakClasses type, const std::string& text, uint16_t channelId) const { + + void sendToChannel(const CreatureConstPtr& creature, SpeakClasses type, const std::string& text, uint16_t channelId) const { if (client) { client->sendToChannel(creature, type, text, channelId); } } - void sendShop(Npc* npc) const { + + void sendShop(const NpcPtr& npc) const { if (client) { client->sendShop(npc, shopItemList); } } + void sendSaleItemList() const { if (client) { client->sendSaleItemList(shopItemList); } } + void sendCloseShop() const { if (client) { client->sendCloseShop(); } } + void sendMarketEnter() const { if (client) { client->sendMarketEnter(); } } + void sendMarketLeave() { inMarket = false; if (client) { client->sendMarketLeave(); } } + void sendMarketBrowseItem(uint16_t itemId, const MarketOfferList& buyOffers, const MarketOfferList& sellOffers) const { if (client) { client->sendMarketBrowseItem(itemId, buyOffers, sellOffers); } } + void sendMarketBrowseOwnOffers(const MarketOfferList& buyOffers, const MarketOfferList& sellOffers) const { if (client) { client->sendMarketBrowseOwnOffers(buyOffers, sellOffers); } } + void sendMarketBrowseOwnHistory(const HistoryMarketOfferList& buyOffers, const HistoryMarketOfferList& sellOffers) const { if (client) { client->sendMarketBrowseOwnHistory(buyOffers, sellOffers); } } + void sendMarketDetail(uint16_t itemId) const { if (client) { client->sendMarketDetail(itemId); } } + void sendMarketAcceptOffer(const MarketOfferEx& offer) const { if (client) { client->sendMarketAcceptOffer(offer); } } + 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 ItemConstPtr& item, bool ack) const { if (client) { client->sendTradeItemRequest(traderName, item, ack); } } + void sendTradeClose() const { if (client) { client->sendCloseTrade(); } } - void sendWorldLight(LightInfo lightInfo) { + + void sendWorldLight(LightInfo lightInfo) const { if (client) { client->sendWorldLight(lightInfo); } } - void sendChannelsDialog() { + + void sendChannelsDialog() const { if (client) { client->sendChannelsDialog(); } } - void sendOpenPrivateChannel(const std::string& receiver) { + + void sendOpenPrivateChannel(const std::string& receiver) const { if (client) { client->sendOpenPrivateChannel(receiver); } } - void sendOutfitWindow() { + + void sendOutfitWindow() const { if (client) { client->sendOutfitWindow(); } } - void sendCloseContainer(uint8_t cid) { + + void sendCloseContainer(uint8_t cid) const { if (client) { client->sendCloseContainer(cid); } } - 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) const { if (client) { client->sendChannel(channelId, channelName, channelUsers, invitedUsers); } } - void sendTutorial(uint8_t tutorialId) { + + void sendTutorial(uint8_t tutorialId) const { if (client) { 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) const { if (client) { client->sendAddMarker(pos, markType, desc); } } - void sendQuestLog() { + + void sendQuestLog() const { if (client) { client->sendQuestLog(); } } - void sendQuestLine(const Quest* quest) { + + void sendQuestLine(const Quest* quest) const { if (client) { client->sendQuestLine(quest); } } - void sendEnterWorld() { + + void sendEnterWorld() const { if (client) { client->sendEnterWorld(); } } - void sendFightModes() { + + void sendFightModes() const { if (client) { client->sendFightModes(); } } - void sendNetworkMessage(const NetworkMessage& message) { + + void sendNetworkMessage(const NetworkMessage& message) const { if (client) { client->writeToOutputBuffer(message); } @@ -1191,84 +1329,86 @@ class Player final : public Creature, public Cylinder 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; void setNextAction(int64_t time) { if (time > nextAction) { nextAction = time; } } + bool canDoAction() const { return nextAction <= OTSYS_TIME(); } + uint32_t getNextActionTime() const; - Item* getWriteItem(uint32_t& windowTextId, uint16_t& maxWriteLen); - void setWriteItem(Item* item, uint16_t maxWriteLen = 0); + ItemPtr getWriteItem(uint32_t& windowTextId, uint16_t& maxWriteLen); + void setWriteItem(const ItemPtr& item, uint16_t maxWriteLen = 0); - House* getEditHouse(uint32_t& windowTextId, uint32_t& listId); + House* getEditHouse(uint32_t& windowTextId, uint32_t& listId) const; 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 updateRegeneration(); + void updateRegeneration() const; - void addItemImbuements(Item* item); - void removeItemImbuements(Item* item); - void addImbuementEffect(std::shared_ptr imbue); - void removeImbuementEffect(std::shared_ptr imbue); + void addItemImbuements(const ItemPtr& item); + void removeItemImbuements(const ItemPtr& item); + void addImbuementEffect(const std::shared_ptr& imbue); + void removeImbuementEffect(const std::shared_ptr& imbue); - CreatureType_t getCreatureType(Monster& monster); + CreatureType_t getCreatureType(const MonsterPtr& monster) const; // To-do : Make all these methods into const - std::unordered_map>> getAttackModifiers(); - std::unordered_map>> getDefenseModifiers(); + std::unordered_map>> getAttackModifiers() const; + std::unordered_map>> getDefenseModifiers() const; std::unordered_map getConvertedTotals(const uint8_t modType, const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName); - std::unordered_map getAttackModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName); - std::unordered_map getDefenseModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName); + std::unordered_map getAttackModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName) const; + std::unordered_map getDefenseModifierTotals(const CombatType_t damageType, const CombatOrigin originType, const CreatureType_t creatureType, const RaceType_t race, const std::string_view creatureName) const; std::vector getOpenPositionsInRadius(int radius) const; const bool addAugment(std::string_view augmentName); - const bool addAugment(std::shared_ptr& augment); + const bool addAugment(const std::shared_ptr& augment); const bool removeAugment(std::string_view augmentName); - const bool removeAugment(std::shared_ptr& augment); + const bool removeAugment(const std::shared_ptr& augment); - const bool isAugmented(); + const bool isAugmented() const; const bool hasAugment(const std::string_view augmentName, const bool checkItems); const bool hasAugment(const std::shared_ptr& augmentName, const bool checkItems); const std::vector> getPlayerAugments() const; // To-do : convert all these params to const and ref. - void absorbDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); - void restoreManaFromDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); - void reviveSoulFromDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); - void replenishStaminaFromDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); - void resistDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); - void reflectDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat, uint8_t areaEffect, uint8_t distanceEffect); - void deflectDamage(std::optional> attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat, CombatOrigin paramOrigin, uint8_t areaEffect, uint8_t distanceEffect); + void absorbDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); + void restoreManaFromDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); + void reviveSoulFromDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); + void replenishStaminaFromDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat); + void resistDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat) const; + void reflectDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat, uint8_t areaEffect, uint8_t distanceEffect); + void deflectDamage(std::optional attackerOpt, CombatDamage& originalDamage, int32_t percent, int32_t flat, CombatOrigin paramOrigin, uint8_t areaEffect, uint8_t distanceEffect); void ricochetDamage(CombatDamage& originalDamage, int32_t percent, int32_t flat, uint8_t areaEffect, uint8_t distanceEffect); - void convertDamage(Creature* target, CombatDamage& originalDamage, std::unordered_map conversionList); - void reformDamage(std::optional> attackerOpt, CombatDamage& originalDamage, std::unordered_map conversionList); + void convertDamage(const CreaturePtr& target, CombatDamage& originalDamage, std::unordered_map conversionList); + void reformDamage(std::optional attackerOpt, CombatDamage& originalDamage, std::unordered_map conversionList); - Position generateAttackPosition(std::optional> attacker, Position& defensePosition, CombatOrigin origin); + Position generateAttackPosition(std::optional attacker, Position& defensePosition, CombatOrigin origin); - std::unique_ptr generateDeflectArea(std::optional> attacker, int32_t targetCount); + std::unique_ptr generateDeflectArea(std::optional attacker, int32_t targetCount) const; private: std::forward_list getMuteConditions() const; - void checkTradeState(const Item* item); - bool hasCapacity(const Item* item, uint32_t count) const; + void checkTradeState(const ItemPtr& item); + bool hasCapacity(const ItemPtr& item, uint32_t count) const; - void gainExperience(uint64_t gainExp, Creature* source); - void addExperience(Creature* source, uint64_t exp, bool sendText = false); + void gainExperience(uint64_t gainExp, const CreaturePtr& source); + void addExperience(const CreaturePtr& source, uint64_t exp, bool sendText = false); void removeExperience(uint64_t exp, bool sendText = false); void updateInventoryWeight(); @@ -1276,42 +1416,42 @@ class Player final : public Creature, public Cylinder void setNextWalkActionTask(SchedulerTask* task); void setNextActionTask(SchedulerTask* task, bool resetIdleTime = true); - void death(Creature* lastHitCreature) override; - bool dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; - Item* getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature) override; + void death(const CreaturePtr& lastHitCreature) override; + bool dropCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; + ItemPtr getCorpse(const CreaturePtr& lastHitCreature, const CreaturePtr& 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; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) override; + ReturnValue queryMaxCount(int32_t index, const ThingPtr& thing, uint32_t count, uint32_t& maxQueryCount, + uint32_t flags) override; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, + uint32_t& flags) override; // another optional ref wrapper - void addThing(Thing*) override {} - void addThing(int32_t index, Thing* thing) override; + void addThing(ThingPtr) override {} + void addThing(int32_t index, ThingPtr thing) override; - void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, Thing* thing) override; + void updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, ThingPtr thing) override; - void removeThing(Thing* thing, uint32_t count) override; + void removeThing(ThingPtr thing, uint32_t count) override; - int32_t getThingIndex(const Thing* thing) const override; + int32_t getThingIndex(ThingPtr thing) override; size_t getFirstIndex() const override; size_t getLastIndex() const override; uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const override; std::map& getAllItemTypeCount(std::map& countMap) const override; - Thing* getThing(size_t index) const override; + ThingPtr getThing(size_t index) override; - void internalAddThing(Thing* thing) override; - void internalAddThing(uint32_t index, Thing* thing) override; + void internalAddThing(ThingPtr thing) override; + void internalAddThing(uint32_t index, ThingPtr thing) override; std::unordered_set attackedSet; std::unordered_set VIPList; std::map openContainers; - std::map depotChests; + std::map depotChests; std::map storageMap; std::vector> augments; @@ -1352,24 +1492,24 @@ class Player final : public Creature, public Cylinder int64_t nextAction = 0; ProtocolGame_ptr client; - BedItem* bedItem = nullptr; + BedItemPtr bedItem = nullptr; Guild* guild = nullptr; GuildRank_ptr guildRank = nullptr; Group* group = nullptr; - Inbox* inbox; - Item* tradeItem = nullptr; - Item* inventory[CONST_SLOT_LAST + 1] = {}; - Item* writeItem = nullptr; + InboxPtr inbox; + ItemPtr tradeItem = nullptr; + ItemPtr inventory[CONST_SLOT_LAST + 1] = {}; + ItemPtr writeItem = nullptr; House* editHouse = nullptr; - Npc* shopOwner = nullptr; + NpcPtr shopOwner = nullptr; Party* party = nullptr; - Player* tradePartner = nullptr; + PlayerPtr tradePartner = nullptr; SchedulerTask* walkTask = nullptr; Town* town = nullptr; Vocation* vocation = nullptr; - StoreInbox* storeInbox = nullptr; - std::shared_ptr rewardChest = nullptr; - DepotLocker_ptr depotLocker = nullptr; + StoreInboxPtr storeInbox = nullptr; + RewardChestPtr rewardChest = nullptr; + DepotLockerPtr depotLocker = nullptr; uint32_t inventoryWeight = 0; uint32_t capacity = 40000; @@ -1447,20 +1587,25 @@ class Player final : public Creature, public Cylinder static uint8_t getPercentLevel(uint64_t count, uint64_t nextLevelCount); double getLostPercent() const; + uint64_t getLostExperience() const override { return skillLoss ? static_cast(experience * getLostPercent()) : 0; } + uint32_t getDamageImmunities() const override { return damageImmunities; } + uint32_t getConditionImmunities() const override { return conditionImmunities; } + uint32_t getConditionSuppressions() const override { return conditionSuppressions; } + uint16_t getLookCorpse() const override; - void getPathSearchParams(const Creature* creature, FindPathParams& fpp) const override; + void getPathSearchParams(const CreatureConstPtr& creature, FindPathParams& fpp) const override; friend class Game; friend class Npc; diff --git a/src/protocol.h b/src/protocol.h index 68836ad9..4d76cd43 100644 --- a/src/protocol.h +++ b/src/protocol.h @@ -10,6 +10,7 @@ class Protocol : public std::enable_shared_from_this { public: + // todo: use reference for connections explicit Protocol(Connection_ptr connection) : connection(connection) {} virtual ~Protocol() = default; @@ -40,7 +41,7 @@ class Protocol : public std::enable_shared_from_this OutputMessage_ptr& getCurrentBuffer() { return outputBuffer; } - + // todo: use reference for message maybe? void send(OutputMessage_ptr msg) const { if (auto connection = getConnection()) { connection->send(msg); @@ -53,12 +54,15 @@ class Protocol : public std::enable_shared_from_this connection->close(); } } + void enableXTEAEncryption() { encryptionEnabled = true; } + void setXTEAKey(const xtea::key& key) { this->key = xtea::expand_key(key); } + void disableChecksum() { checksumEnabled = false; } diff --git a/src/protocolgame.cpp b/src/protocolgame.cpp index a6d69531..149cc928 100644 --- a/src/protocolgame.cpp +++ b/src/protocolgame.cpp @@ -63,9 +63,9 @@ constexpr int64_t getTimeout(std::size_t slot) return getWaitTime(slot) + 15; } -std::size_t clientLogin(const Player& player) +std::size_t clientLogin(const PlayerConstPtr& player) { - if (player.hasFlag(PlayerFlag_CanAlwaysLogin) || player.getAccountType() >= ACCOUNT_TYPE_GAMEMASTER) { + if (player->hasFlag(PlayerFlag_CanAlwaysLogin) || player->getAccountType() >= ACCOUNT_TYPE_GAMEMASTER) { return 0; } @@ -87,7 +87,7 @@ std::size_t clientLogin(const Player& player) } std::size_t slot; - std::tie(it, slot) = findClient(player.getGUID()); + std::tie(it, slot) = findClient(player->getGUID()); if (it != waitList.end()) { // If server has capacity for this client, let him in even though his current slot might be higher than 0. if ((g_game.getPlayersOnline() + slot) <= maxPlayers) { @@ -101,11 +101,11 @@ std::size_t clientLogin(const Player& player) } - if (player.isPremium()) { - priorityEnd = waitList.emplace(priorityEnd, time + (getTimeout(slot + 1) * 1000), player.getGUID()); + if (player->isPremium()) { + priorityEnd = waitList.emplace(priorityEnd, time + (getTimeout(slot + 1) * 1000), player->getGUID()); return std::distance(waitList.begin(), priorityEnd); } - waitList.emplace_back(time + (getTimeout(waitList.size() + 1) * 1000), player.getGUID()); + waitList.emplace_back(time + (getTimeout(waitList.size() + 1) * 1000), player->getGUID()); return waitList.size(); } @@ -116,7 +116,6 @@ void ProtocolGame::release() //dispatcher thread if (player && player->client == shared_from_this()) { player->client.reset(); - player->decrementReferenceCounter(); player = nullptr; } @@ -127,11 +126,10 @@ void ProtocolGame::release() void ProtocolGame::login(uint32_t characterId, uint32_t accountId, OperatingSystem_t operatingSystem) { //dispatcher thread - Player* foundPlayer = g_game.getPlayerByGUID(characterId); + const auto& foundPlayer = g_game.getPlayerByGUID(characterId); if (!foundPlayer || g_config.getBoolean(ConfigManager::ALLOW_CLONES)) { - player = new Player(getThis()); - - player->incrementReferenceCounter(); + player = Player::makePlayer(getThis()); + player->setID(); player->setGUID(characterId); @@ -176,7 +174,7 @@ void ProtocolGame::login(uint32_t characterId, uint32_t accountId, OperatingSyst } } - if (std::size_t currentSlot = clientLogin(*player)) { + if (std::size_t currentSlot = clientLogin(player)) { uint8_t retryTime = getWaitTime(currentSlot); auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x16); @@ -233,7 +231,7 @@ void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem) { eventConnect = 0; - Player* foundPlayer = g_game.getPlayerByID(playerId); + const auto& foundPlayer = g_game.getPlayerByID(playerId); if (!foundPlayer || foundPlayer->client) { disconnectClient("You are already logged in."); return; @@ -246,9 +244,7 @@ void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem) } player = foundPlayer; - player->incrementReferenceCounter(); - - g_chat->removeUserFromAllChannels(*player); + g_chat->removeUserFromAllChannels(player); player->clearModalWindows(); player->setOperatingSystem(operatingSystem); player->isConnecting = false; @@ -569,20 +565,19 @@ void ProtocolGame::parsePacket(NetworkMessage& msg) } } -void ProtocolGame::GetTileDescription(const Tile* tile, NetworkMessage& msg) +void ProtocolGame::GetTileDescription(const TileConstPtr& tile, NetworkMessage& msg) { msg.add(0x00); //environmental effects int32_t count; - Item* ground = tile->getGround(); - if (ground) { + if (const auto& ground = tile->getGround()) { msg.addItem(ground); count = 1; } else { count = 0; } - const TileItemVector* items = tile->getItemList(); + const auto& items = tile->getItemList(); if (items) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { msg.addItem(*it); @@ -593,9 +588,8 @@ void ProtocolGame::GetTileDescription(const Tile* tile, NetworkMessage& msg) } } - const CreatureVector* creatures = tile->getCreatures(); - if (creatures) { - for (const Creature* creature : boost::adaptors::reverse(*creatures)) { + if (const auto& creatures = tile->getCreatures()) { + for (const auto& creature : boost::adaptors::reverse(*creatures)) { if (!player->canSeeCreature(creature) || count >= 10) { continue; } @@ -648,8 +642,7 @@ void ProtocolGame::GetFloorDescription(NetworkMessage& msg, int32_t x, int32_t y { for (int32_t nx = 0; nx < width; nx++) { for (int32_t ny = 0; ny < height; ny++) { - Tile* tile = g_game.map.getTile(x + nx + offset, y + ny + offset, z); - if (tile) { + if (const auto& tile = g_game.map.getTile(x + nx + offset, y + ny + offset, z)) { if (skip >= 0) { msg.addByte(skip); msg.addByte(0xFF); @@ -670,7 +663,7 @@ void ProtocolGame::GetFloorDescription(NetworkMessage& msg, int32_t x, int32_t y void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool& known, uint32_t& removedKnown) { - auto result = knownCreatureSet.insert(id); + const auto result = knownCreatureSet.insert(id); if (!result.second) { known = true; return; @@ -681,7 +674,7 @@ void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool& known, uint32_t& remo if (knownCreatureSet.size() > 1300) { // Look for a creature to remove for (auto it = knownCreatureSet.begin(), end = knownCreatureSet.end(); it != end; ++it) { - Creature* creature = g_game.getCreatureByID(*it); + const auto& creature = g_game.getCreatureByID(*it); if (!canSee(creature)) { removedKnown = *it; knownCreatureSet.erase(it); @@ -702,7 +695,7 @@ void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool& known, uint32_t& remo } } -bool ProtocolGame::canSee(const Creature* c) const +bool ProtocolGame::canSee(const CreatureConstPtr& c) const { if (!c || !player || c->isRemoved()) { return false; @@ -1253,7 +1246,7 @@ void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string& playe writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureOutfit(const Creature* creature, const Outfit_t& outfit) +void ProtocolGame::sendCreatureOutfit(const CreatureConstPtr& creature, const Outfit_t& outfit) { if (!canSee(creature)) { return; @@ -1266,7 +1259,7 @@ void ProtocolGame::sendCreatureOutfit(const Creature* creature, const Outfit_t& writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureLight(const Creature* creature) +void ProtocolGame::sendCreatureLight(const CreatureConstPtr& creature) { if (!canSee(creature)) { return; @@ -1284,7 +1277,7 @@ void ProtocolGame::sendWorldLight(LightInfo lightInfo) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureWalkthrough(const Creature* creature, bool walkthrough) +void ProtocolGame::sendCreatureWalkthrough(const CreatureConstPtr& creature, bool walkthrough) { if (!canSee(creature)) { return; @@ -1297,7 +1290,7 @@ void ProtocolGame::sendCreatureWalkthrough(const Creature* creature, bool walkth writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureShield(const Creature* creature) +void ProtocolGame::sendCreatureShield(const CreatureConstPtr& creature) { if (!canSee(creature)) { return; @@ -1310,7 +1303,7 @@ void ProtocolGame::sendCreatureShield(const Creature* creature) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSkull(const Creature* creature) +void ProtocolGame::sendCreatureSkull(const CreatureConstPtr& creature) { if (g_game.getWorldType() != WORLD_TYPE_PVP) { return; @@ -1345,7 +1338,7 @@ void ProtocolGame::sendCreatureHelpers(uint32_t creatureId, uint16_t helpers) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSquare(const Creature* creature, SquareColor_t color) +void ProtocolGame::sendCreatureSquare(const CreatureConstPtr& creature, SquareColor_t color) { if (!canSee(creature)) { return; @@ -1475,7 +1468,7 @@ void ProtocolGame::sendChannelsDialog() NetworkMessage msg; msg.addByte(0xAB); - const ChannelList& list = g_chat->getChannelList(*player); + const ChannelList& list = g_chat->getChannelList(player); msg.addByte(list.size()); for (ChatChannel* channel : list) { msg.add(channel->getId()); @@ -1534,7 +1527,7 @@ void ProtocolGame::sendIcons(uint16_t icons) writeToOutputBuffer(msg); } -void ProtocolGame::sendContainer(uint8_t cid, const Container* container, bool hasParent, uint16_t firstIndex) +void ProtocolGame::sendContainer(uint8_t cid, const ContainerConstPtr& container, bool hasParent, uint16_t firstIndex) { NetworkMessage msg; msg.addByte(0x6E); @@ -1572,7 +1565,7 @@ void ProtocolGame::sendContainer(uint8_t cid, const Container* container, bool h writeToOutputBuffer(msg); } -void ProtocolGame::sendShop(Npc* npc, const ShopInfoList& itemList) +void ProtocolGame::sendShop(const NpcPtr& npc, const ShopInfoList& itemList) { NetworkMessage msg; msg.addByte(0x7A); @@ -1688,7 +1681,7 @@ void ProtocolGame::sendMarketEnter() player->setInMarket(true); std::map depotItems; - std::forward_list containerList{ player->getInbox() }; + std::forward_list containerList{ player->getInbox() }; for (const auto& chest : player->depotChests) { if (!chest.second->empty()) { @@ -1697,11 +1690,11 @@ void ProtocolGame::sendMarketEnter() } do { - Container* container = containerList.front(); + ContainerPtr& container = containerList.front(); containerList.pop_front(); - for (Item* item : container->getItemList()) { - Container* c = item->getContainer(); + for (const auto& item : container->getItemList()) { + const auto& c = item->getContainer(); if (c && !c->empty()) { containerList.push_front(c); continue; @@ -2099,7 +2092,7 @@ void ProtocolGame::sendQuestLine(const Quest* quest) writeToOutputBuffer(msg); } -void ProtocolGame::sendTradeItemRequest(const std::string& traderName, const Item* item, bool ack) +void ProtocolGame::sendTradeItemRequest(const std::string& traderName, const ItemConstPtr& item, bool ack) { NetworkMessage msg; @@ -2111,16 +2104,15 @@ void ProtocolGame::sendTradeItemRequest(const std::string& traderName, const Ite msg.addString(traderName); - if (const Container* tradeContainer = item->getContainer()) { - std::list listContainer {tradeContainer}; - std::list itemList {tradeContainer}; + if (const auto& tradeContainer = item->getContainer()) { + std::list listContainer {tradeContainer}; + std::list itemList {tradeContainer}; while (!listContainer.empty()) { - const Container* container = listContainer.front(); + const auto& container = listContainer.front(); listContainer.pop_front(); - for (Item* containerItem : container->getItemList()) { - Container* tmpContainer = containerItem->getContainer(); - if (tmpContainer) { + for (const auto& containerItem : container->getItemList()) { + if (const auto& tmpContainer = containerItem->getContainer()) { listContainer.push_back(tmpContainer); } itemList.push_back(containerItem); @@ -2128,7 +2120,7 @@ void ProtocolGame::sendTradeItemRequest(const std::string& traderName, const Ite } msg.addByte(itemList.size()); - for (const Item* listItem : itemList) { + for (const auto& listItem : itemList) { msg.addItem(listItem); } } else { @@ -2153,7 +2145,7 @@ void ProtocolGame::sendCloseContainer(uint8_t cid) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureTurn(const Creature* creature, uint32_t stackPos) +void ProtocolGame::sendCreatureTurn(const CreatureConstPtr& creature, uint32_t stackPos) { if (!canSee(creature) || stackPos >= 10) { return; @@ -2170,7 +2162,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 CreatureConstPtr& creature, SpeakClasses type, const std::string& text, const Position* pos/* = nullptr*/) { NetworkMessage msg; msg.addByte(0xAA); @@ -2181,7 +2173,7 @@ void ProtocolGame::sendCreatureSay(const Creature* creature, SpeakClasses type, msg.addString(creature->getName()); //Add level only for players - if (const Player* speaker = creature->getPlayer()) { + if (const auto& speaker = creature->getPlayer()) { msg.add(speaker->getLevel()); } else { msg.add(0x00); @@ -2198,7 +2190,7 @@ 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 CreatureConstPtr& creature, SpeakClasses type, const std::string& text, uint16_t channelId) { NetworkMessage msg; msg.addByte(0xAA); @@ -2210,7 +2202,7 @@ void ProtocolGame::sendToChannel(const Creature* creature, SpeakClasses type, co } else { msg.addString(creature->getName()); //Add level only for players - if (const Player* speaker = creature->getPlayer()) { + if (const auto& speaker = creature->getPlayer()) { msg.add(speaker->getLevel()); } else { msg.add(0x00); @@ -2223,7 +2215,7 @@ 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 PlayerConstPtr& speaker, SpeakClasses type, const std::string& text) { NetworkMessage msg; msg.addByte(0xAA); @@ -2248,7 +2240,7 @@ void ProtocolGame::sendCancelTarget() writeToOutputBuffer(msg); } -void ProtocolGame::sendChangeSpeed(const Creature* creature, uint32_t speed) +void ProtocolGame::sendChangeSpeed(const CreatureConstPtr& creature, uint32_t speed) { NetworkMessage msg; msg.addByte(0x8F); @@ -2310,7 +2302,7 @@ void ProtocolGame::sendMagicEffect(const Position& pos, uint8_t type) writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureHealth(const Creature* creature) +void ProtocolGame::sendCreatureHealth(const CreatureConstPtr& creature) { NetworkMessage msg; msg.addByte(0x8C); @@ -2342,7 +2334,7 @@ void ProtocolGame::sendMapDescription(const Position& pos) writeToOutputBuffer(msg); } -void ProtocolGame::sendAddTileItem(const Position& pos, uint32_t stackpos, const Item* item) +void ProtocolGame::sendAddTileItem(const Position& pos, uint32_t stackpos, const ItemConstPtr& item) { if (!canSee(pos)) { return; @@ -2356,7 +2348,7 @@ void ProtocolGame::sendAddTileItem(const Position& pos, uint32_t stackpos, const writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTileItem(const Position& pos, uint32_t stackpos, const Item* item) +void ProtocolGame::sendUpdateTileItem(const Position& pos, uint32_t stackpos, const ItemConstPtr& item) { if (!canSee(pos)) { return; @@ -2381,7 +2373,7 @@ void ProtocolGame::sendRemoveTileThing(const Position& pos, uint32_t stackpos) writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTileCreature(const Position& pos, uint32_t stackpos, const Creature* creature) +void ProtocolGame::sendUpdateTileCreature(const Position& pos, uint32_t stackpos, const CreatureConstPtr& creature) { if (!canSee(pos) || stackpos >= 10) { return; @@ -2400,7 +2392,7 @@ void ProtocolGame::sendUpdateTileCreature(const Position& pos, uint32_t stackpos writeToOutputBuffer(msg); } -void ProtocolGame::sendRemoveTileCreature(const Creature* creature, const Position& pos, uint32_t stackpos) +void ProtocolGame::sendRemoveTileCreature(const CreatureConstPtr& creature, const Position& pos, uint32_t stackpos) { if (!canSee(pos) || stackpos >= 10) { return; @@ -2412,7 +2404,7 @@ void ProtocolGame::sendRemoveTileCreature(const Creature* creature, const Positi return; } -void ProtocolGame::sendUpdateTile(const Tile* tile, const Position& pos) +void ProtocolGame::sendUpdateTile(const TileConstPtr& tile, const Position& pos) { if (!canSee(pos)) { return; @@ -2459,7 +2451,7 @@ void ProtocolGame::sendFightModes() writeToOutputBuffer(msg); } -void ProtocolGame::sendAddCreature(const Creature* creature, const Position& pos, int32_t stackpos, MagicEffectClasses magicEffect/*= CONST_ME_NONE*/) +void ProtocolGame::sendAddCreature(const CreatureConstPtr& creature, const Position& pos, int32_t stackpos, MagicEffectClasses magicEffect/*= CONST_ME_NONE*/) { if (!canSee(pos)) { return; @@ -2474,7 +2466,7 @@ void ProtocolGame::sendAddCreature(const Creature* creature, const Position& pos // add creatures to battle list instead of rendering on screen if (stackpos >= 10) { // @todo: should we avoid this check? - if (const Tile* tile = creature->getTile()) { + if (const auto& tile = creature->getTile()) { sendUpdateTile(tile, pos); return; } @@ -2552,7 +2544,7 @@ 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) +void ProtocolGame::sendMoveCreature(const CreatureConstPtr& creature, const Position& newPos, int32_t newStackPos, const Position& oldPos, int32_t oldStackPos, bool teleport) { if (creature == player) { if (oldStackPos >= 10) { @@ -2623,7 +2615,7 @@ void ProtocolGame::sendMoveCreature(const Creature* creature, const Position& ne } } -void ProtocolGame::sendInventoryItem(slots_t slot, const Item* item) +void ProtocolGame::sendInventoryItem(slots_t slot, const ItemConstPtr& item) { NetworkMessage msg; if (item) { @@ -2659,7 +2651,7 @@ void ProtocolGame::sendItems() writeToOutputBuffer(msg); } -void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const Item* item) +void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const ItemConstPtr& item) { NetworkMessage msg; msg.addByte(0x70); @@ -2669,7 +2661,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 ItemConstPtr& item) { NetworkMessage msg; msg.addByte(0x71); @@ -2679,7 +2671,7 @@ 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 ItemConstPtr& lastItem) { NetworkMessage msg; msg.addByte(0x72); @@ -2693,7 +2685,7 @@ void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Ite writeToOutputBuffer(msg); } -void ProtocolGame::sendTextWindow(uint32_t windowTextId, Item* item, uint16_t maxlen, bool canWrite) +void ProtocolGame::sendTextWindow(uint32_t windowTextId, const ItemPtr& item, uint16_t maxlen, bool canWrite) { NetworkMessage msg; msg.addByte(0x96); @@ -2842,7 +2834,7 @@ void ProtocolGame::sendVIPEntries() for (const VIPEntry& entry : vipEntries) { VipStatus_t vipStatus = VIPSTATUS_ONLINE; - Player* vipPlayer = g_game.getPlayerByGUID(entry.guid); + const auto& vipPlayer = g_game.getPlayerByGUID(entry.guid); if (!vipPlayer || !player->canSeeCreature(vipPlayer)) { vipStatus = VIPSTATUS_OFFLINE; @@ -2899,11 +2891,11 @@ 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 CreatureConstPtr& creature, bool known, uint32_t remove) { CreatureType_t creatureType = creature->getType(); - const Player* otherPlayer = creature->getPlayer(); + const auto& otherPlayer = creature->getPlayer(); if (known) { msg.add(0x62); @@ -2945,10 +2937,8 @@ void ProtocolGame::AddCreature(NetworkMessage& msg, const Creature* creature, bo } if (creatureType == CREATURETYPE_MONSTER) { - const Creature* master = creature->getMaster(); - if (master) { - const Player* masterPlayer = master->getPlayer(); - if (masterPlayer) { + if (const auto& master = creature->getMaster()) { + if (const auto& masterPlayer = master->getPlayer()) { if (masterPlayer == player) { creatureType = CREATURETYPE_SUMMON_OWN; } else { @@ -2971,7 +2961,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) const { msg.addByte(0xA0); @@ -3014,7 +3004,7 @@ void ProtocolGame::AddPlayerStats(NetworkMessage& msg) msg.addByte(0); // enables exp boost in the store } -void ProtocolGame::AddPlayerSkills(NetworkMessage& msg) +void ProtocolGame::AddPlayerSkills(NetworkMessage& msg) const { msg.addByte(0xA1); @@ -3047,14 +3037,14 @@ void ProtocolGame::AddOutfit(NetworkMessage& msg, const Outfit_t& outfit) msg.add(outfit.lookMount); } -void ProtocolGame::AddWorldLight(NetworkMessage& msg, LightInfo lightInfo) +void ProtocolGame::AddWorldLight(NetworkMessage& msg, LightInfo lightInfo) const { msg.addByte(0x82); msg.addByte((player->isAccessPlayer() ? 0xFF : lightInfo.level)); msg.addByte(lightInfo.color); } -void ProtocolGame::AddCreatureLight(NetworkMessage& msg, const Creature* creature) +void ProtocolGame::AddCreatureLight(NetworkMessage& msg, const CreatureConstPtr& creature) const { LightInfo lightInfo = creature->getCreatureLight(); @@ -3076,16 +3066,14 @@ void ProtocolGame::RemoveTileThing(NetworkMessage& msg, const Position& pos, uin msg.addByte(stackpos); } -void ProtocolGame::RemoveTileCreature(NetworkMessage& msg, const Creature* creature, const Position& pos, uint32_t stackpos) +void ProtocolGame::RemoveTileCreature(NetworkMessage& msg, const CreatureConstPtr& creature, const Position& pos, uint32_t stackpos) { if (stackpos < 10) { RemoveTileThing(msg, pos, stackpos); - return; } - return; } -void ProtocolGame::MoveUpCreature(NetworkMessage& msg, const Creature* creature, const Position& newPos, const Position& oldPos) +void ProtocolGame::MoveUpCreature(NetworkMessage& msg, const CreatureConstPtr& creature, const Position& newPos, const Position& oldPos) { if (creature != player) { return; @@ -3128,7 +3116,7 @@ void ProtocolGame::MoveUpCreature(NetworkMessage& msg, const Creature* creature, GetMapDescription(oldPos.x - Map::maxClientViewportX, oldPos.y - Map::maxClientViewportY, newPos.z, (Map::maxClientViewportX * 2) + 2, 1, msg); } -void ProtocolGame::MoveDownCreature(NetworkMessage& msg, const Creature* creature, const Position& newPos, const Position& oldPos) +void ProtocolGame::MoveDownCreature(NetworkMessage& msg, const CreatureConstPtr& creature, const Position& newPos, const Position& oldPos) { if (creature != player) { return; diff --git a/src/protocolgame.h b/src/protocolgame.h index 26c64a1b..f1f8b82d 100644 --- a/src/protocolgame.h +++ b/src/protocolgame.h @@ -47,7 +47,7 @@ class ProtocolGame final : public Protocol static const char* protocol_name() { return "gameworld protocol"; } - + // todo: use reference for connection explicit ProtocolGame(Connection_ptr connection) : Protocol(connection) {} void login(uint32_t characterId, uint32_t accountId, OperatingSystem_t operatingSystem); @@ -70,7 +70,7 @@ class ProtocolGame final : public Protocol 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 CreatureConstPtr&) const; bool canSee(const Position& pos) const; // we have all the parse methods @@ -156,27 +156,27 @@ class ProtocolGame final : public Protocol void sendChannelsDialog(); void sendChannel(uint16_t channelId, const std::string& channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers); void sendOpenPrivateChannel(const std::string& receiver); - 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 sendToChannel(const CreatureConstPtr& creature, SpeakClasses type, const std::string& text, uint16_t channelId); + void sendPrivateMessage(const PlayerConstPtr& speaker, SpeakClasses type, const std::string& text); void sendIcons(uint16_t icons); void sendFYIBox(const std::string& message); void sendDistanceShoot(const Position& from, const Position& to, uint8_t type); void sendMagicEffect(const Position& pos, uint8_t type); - void sendCreatureHealth(const Creature* creature); + void sendCreatureHealth(const CreatureConstPtr& creature); 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); + void sendCreatureTurn(const CreatureConstPtr& creature, uint32_t stackPos); + void sendCreatureSay(const CreatureConstPtr& creature, SpeakClasses type, const std::string& text, const Position* pos = nullptr); void sendQuestLog(); void sendQuestLine(const Quest* quest); void sendCancelWalk(); - void sendChangeSpeed(const Creature* creature, uint32_t speed); + void sendChangeSpeed(const CreatureConstPtr& creature, uint32_t speed); void sendCancelTarget(); - void sendCreatureOutfit(const Creature* creature, const Outfit_t& outfit); + void sendCreatureOutfit(const CreatureConstPtr& creature, const Outfit_t& outfit); void sendStats(); void sendBasicData(); void sendTextMessage(const TextMessage& message); @@ -185,13 +185,13 @@ class ProtocolGame final : public Protocol void sendTutorial(uint8_t tutorialId); void sendAddMarker(const Position& pos, uint8_t markType, const std::string& desc); - void sendCreatureWalkthrough(const Creature* creature, bool walkthrough); - void sendCreatureShield(const Creature* creature); - void sendCreatureSkull(const Creature* creature); + void sendCreatureWalkthrough(const CreatureConstPtr& creature, bool walkthrough); + void sendCreatureShield(const CreatureConstPtr& creature); + void sendCreatureSkull(const CreatureConstPtr& creature); void sendCreatureType(uint32_t creatureId, uint8_t creatureType); void sendCreatureHelpers(uint32_t creatureId, uint16_t helpers); - void sendShop(Npc* npc, const ShopInfoList& itemList); + void sendShop(const NpcPtr& npc, const ShopInfoList& itemList); void sendCloseShop(); void sendSaleItemList(const std::list& shop); void sendMarketEnter(); @@ -202,10 +202,10 @@ class ProtocolGame final : public Protocol void sendMarketCancelOffer(const MarketOfferEx& offer); void sendMarketBrowseOwnHistory(const HistoryMarketOfferList& buyOffers, const HistoryMarketOfferList& sellOffers); void sendMarketDetail(uint16_t itemId); - void sendTradeItemRequest(const std::string& traderName, const Item* item, bool ack); + void sendTradeItemRequest(const std::string& traderName, const ItemConstPtr& item, bool ack); void sendCloseTrade(); - void sendTextWindow(uint32_t windowTextId, Item* item, uint16_t maxlen, bool canWrite); + void sendTextWindow(uint32_t windowTextId, const ItemPtr& item, uint16_t maxlen, bool canWrite); void sendTextWindow(uint32_t windowTextId, uint32_t itemId, const std::string& text); void sendHouseWindow(uint32_t windowTextId, const std::string& text); void sendOutfitWindow(); @@ -219,10 +219,10 @@ class ProtocolGame final : public Protocol void sendFightModes(); - void sendCreatureLight(const Creature* creature); + void sendCreatureLight(const CreatureConstPtr& creature); void sendWorldLight(LightInfo lightInfo); - void sendCreatureSquare(const Creature* creature, SquareColor_t color); + void sendCreatureSquare(const CreatureConstPtr& creature, SquareColor_t color); void sendSpellCooldown(uint8_t spellId, uint32_t time); void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time); @@ -230,27 +230,27 @@ class ProtocolGame final : public Protocol //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 sendAddTileItem(const Position& pos, uint32_t stackpos, const ItemConstPtr& item); + void sendUpdateTileItem(const Position& pos, uint32_t stackpos, const ItemConstPtr& item); void sendRemoveTileThing(const Position& pos, uint32_t stackpos); - void sendUpdateTileCreature(const Position& pos, uint32_t stackpos, const Creature* creature); - void sendRemoveTileCreature(const Creature* creature, const Position& pos, uint32_t stackpos); - void sendUpdateTile(const Tile* tile, const Position& pos); + void sendUpdateTileCreature(const Position& pos, uint32_t stackpos, const CreatureConstPtr& creature); + void sendRemoveTileCreature(const CreatureConstPtr& creature, const Position& pos, uint32_t stackpos); + void sendUpdateTile(const TileConstPtr& tile, const Position& pos); - void sendAddCreature(const Creature* creature, const Position& pos, int32_t stackpos, MagicEffectClasses magicEffect = CONST_ME_NONE); - void sendMoveCreature(const Creature* creature, const Position& newPos, int32_t newStackPos, + void sendAddCreature(const CreatureConstPtr& creature, const Position& pos, int32_t stackpos, MagicEffectClasses magicEffect = CONST_ME_NONE); + void sendMoveCreature(const CreatureConstPtr& 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 sendAddContainerItem(uint8_t cid, uint16_t slot, const ItemConstPtr& item); + void sendUpdateContainerItem(uint8_t cid, uint16_t slot, const ItemConstPtr& item); + void sendRemoveContainerItem(uint8_t cid, uint16_t slot, const ItemConstPtr& lastItem); - void sendContainer(uint8_t cid, const Container* container, bool hasParent, uint16_t firstIndex); + void sendContainer(uint8_t cid, const ContainerConstPtr& container, bool hasParent, uint16_t firstIndex); void sendCloseContainer(uint8_t cid); //inventory - void sendInventoryItem(slots_t slot, const Item* item); + void sendInventoryItem(slots_t slot, const ItemConstPtr& item); void sendItems(); //messages @@ -259,7 +259,7 @@ class ProtocolGame final : public Protocol //Help functions // translate a tile to client-readable format - void GetTileDescription(const Tile* tile, NetworkMessage& msg); + void GetTileDescription(const TileConstPtr& tile, NetworkMessage& msg); // translate a floor to client-readable format void GetFloorDescription(NetworkMessage& msg, int32_t x, int32_t y, int32_t z, @@ -269,19 +269,19 @@ class ProtocolGame final : public Protocol void GetMapDescription(int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, NetworkMessage& msg); - void AddCreature(NetworkMessage& msg, const Creature* creature, bool known, uint32_t remove); - void AddPlayerStats(NetworkMessage& msg); + void AddCreature(NetworkMessage& msg, const CreatureConstPtr& creature, bool known, uint32_t remove); + void AddPlayerStats(NetworkMessage& msg) const; void AddOutfit(NetworkMessage& msg, const Outfit_t& outfit); - void AddPlayerSkills(NetworkMessage& msg); - void AddWorldLight(NetworkMessage& msg, LightInfo lightInfo); - void AddCreatureLight(NetworkMessage& msg, const Creature* creature); + void AddPlayerSkills(NetworkMessage& msg) const; + void AddWorldLight(NetworkMessage& msg, LightInfo lightInfo) const; + void AddCreatureLight(NetworkMessage& msg, const CreatureConstPtr& creature) const; //tiles static void RemoveTileThing(NetworkMessage& msg, const Position& pos, uint32_t stackpos); - static void RemoveTileCreature(NetworkMessage& msg, const Creature* creature, const Position& pos, uint32_t stackpos); + static void RemoveTileCreature(NetworkMessage& msg, const CreatureConstPtr& creature, 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 MoveUpCreature(NetworkMessage& msg, const CreatureConstPtr& creature, const Position& newPos, const Position& oldPos); + void MoveDownCreature(NetworkMessage& msg, const CreatureConstPtr& creature, const Position& newPos, const Position& oldPos); //shop void AddShopItem(NetworkMessage& msg, const ShopInfo& item); @@ -303,7 +303,7 @@ class ProtocolGame final : public Protocol } std::unordered_set knownCreatureSet; - Player* player = nullptr; + PlayerPtr player = nullptr; uint32_t eventConnect = 0; uint32_t challengeTimestamp = 0; diff --git a/src/protocollogin.h b/src/protocollogin.h index 9539a348..22335075 100644 --- a/src/protocollogin.h +++ b/src/protocollogin.h @@ -19,7 +19,7 @@ class ProtocolLogin : public Protocol static const char* protocol_name() { return "login protocol"; } - + // todo: use reference on connection explicit ProtocolLogin(Connection_ptr connection) : Protocol(connection) {} void onRecvFirstMessage(NetworkMessage& msg) override; diff --git a/src/protocolold.h b/src/protocolold.h index 5f78a738..df0c5531 100644 --- a/src/protocolold.h +++ b/src/protocolold.h @@ -18,7 +18,7 @@ class ProtocolOld final : public Protocol static const char* protocol_name() { return "old login protocol"; } - + // todo: use reference on connection explicit ProtocolOld(Connection_ptr connection) : Protocol(connection) {} void onRecvFirstMessage(NetworkMessage& msg) override; diff --git a/src/protocolstatus.h b/src/protocolstatus.h index b41273ec..326d8efd 100644 --- a/src/protocolstatus.h +++ b/src/protocolstatus.h @@ -18,6 +18,7 @@ class ProtocolStatus final : public Protocol return "status protocol"; } + // todo: change connection to reference explicit ProtocolStatus(Connection_ptr connection) : Protocol(connection) {} void onRecvFirstMessage(NetworkMessage& msg) override; diff --git a/src/quests.cpp b/src/quests.cpp index c92a8063..592f58c8 100644 --- a/src/quests.cpp +++ b/src/quests.cpp @@ -7,7 +7,7 @@ #include "pugicast.h" -std::string Mission::getDescription(Player* player) const +std::string Mission::getDescription(const PlayerPtr& player) const { int32_t value; player->getStorageValue(storageID, value); @@ -41,7 +41,7 @@ std::string Mission::getDescription(Player* player) const return "An error has occurred, please contact a gamemaster."; } -bool Mission::isStarted(Player* player) const +bool Mission::isStarted(const PlayerPtr& player) const { if (!player) { return false; @@ -63,7 +63,7 @@ bool Mission::isStarted(Player* player) const return true; } -bool Mission::isCompleted(Player* player) const +bool Mission::isCompleted(const PlayerPtr& player) const { if (!player) { return false; @@ -81,7 +81,7 @@ bool Mission::isCompleted(Player* player) const return value == endValue; } -std::string Mission::getName(Player* player) const +std::string Mission::getName(const PlayerPtr& player) const { if (isCompleted(player)) { return name + " (completed)"; @@ -89,7 +89,7 @@ std::string Mission::getName(Player* player) const return name; } -uint16_t Quest::getMissionsCount(Player* player) const +uint16_t Quest::getMissionsCount(const PlayerPtr& player) const { uint16_t count = 0; for (const Mission& mission : missions) { @@ -100,7 +100,7 @@ uint16_t Quest::getMissionsCount(Player* player) const return count; } -bool Quest::isCompleted(Player* player) const +bool Quest::isCompleted(const PlayerPtr& player) const { for (const Mission& mission : missions) { if (!mission.isCompleted(player)) { @@ -110,7 +110,7 @@ bool Quest::isCompleted(Player* player) const return true; } -bool Quest::isStarted(Player* player) const +bool Quest::isStarted(const PlayerPtr& player) const { if (!player) { return false; @@ -184,7 +184,7 @@ Quest* Quests::getQuestByID(uint16_t id) return nullptr; } -uint16_t Quests::getQuestsCount(Player* player) const +uint16_t Quests::getQuestsCount(const PlayerPtr& player) const { uint16_t count = 0; for (const Quest& quest : quests) { diff --git a/src/quests.h b/src/quests.h index ae780ee7..1bd5d271 100644 --- a/src/quests.h +++ b/src/quests.h @@ -19,17 +19,19 @@ class Mission Mission(std::string name, int32_t storageID, int32_t startValue, int32_t endValue, bool ignoreEndValue) : name(std::move(name)), storageID(storageID), startValue(startValue), endValue(endValue), ignoreEndValue(ignoreEndValue) {} - bool isCompleted(Player* player) const; - bool isStarted(Player* player) const; - std::string getName(Player* player) const; - std::string getDescription(Player* player) const; + bool isCompleted(const PlayerPtr& player) const; + bool isStarted(const PlayerPtr& player) const; + std::string getName(const PlayerPtr& player) const; + std::string getDescription(const PlayerPtr& player) const; uint32_t getStorageId() const { return storageID; } + int32_t getStartStorageValue() const { return startValue; } + int32_t getEndStorageValue() const { return endValue; } @@ -50,19 +52,23 @@ class Quest Quest(std::string name, uint16_t id, int32_t startStorageID, int32_t startStorageValue) : name(std::move(name)), startStorageID(startStorageID), startStorageValue(startStorageValue), id(id) {} - bool isCompleted(Player* player) const; - bool isStarted(Player* player) const; + bool isCompleted(const PlayerPtr& player) const; + bool isStarted(const PlayerPtr& player) const; + uint16_t getID() const { return id; } + std::string getName() const { return name; } - uint16_t getMissionsCount(Player* player) const; + + uint16_t getMissionsCount(const PlayerPtr& player) const; uint32_t getStartStorageId() const { return startStorageID; } + int32_t getStartStorageValue() const { return startStorageValue; } @@ -93,7 +99,7 @@ class Quests bool loadFromXml(); Quest* getQuestByID(uint16_t id); bool isQuestStorage(const uint32_t key, const int32_t value, const int32_t oldValue) const; - uint16_t getQuestsCount(Player* player) const; + uint16_t getQuestsCount(const PlayerPtr& player) const; bool reload(); private: diff --git a/src/raids.cpp b/src/raids.cpp index 9cbe2fc7..8bdc4113 100644 --- a/src/raids.cpp +++ b/src/raids.cpp @@ -159,7 +159,7 @@ bool Raids::reload() return loadFromXml(); } -Raid* Raids::getRaidByName(const std::string& name) +Raid* Raids::getRaidByName(const std::string& name) const { for (Raid* raid : raidList) { if (caseInsensitiveEqual(raid->getName(), name)) { @@ -262,7 +262,7 @@ void Raid::stopEvents() } } -RaidEvent* Raid::getNextRaidEvent() +RaidEvent* Raid::getNextRaidEvent() const { if (nextEvent < raidEvents.size()) { return raidEvents[nextEvent]; @@ -368,14 +368,13 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node& eventNode) bool SingleSpawnEvent::executeEvent() { - Monster* monster = Monster::createMonster(monsterName); + auto monster = Monster::createMonster(monsterName); if (!monster) { std::cout << "[Error] Raids: Cant create monster " << monsterName << std::endl; return false; } - if (!g_game.placeCreature(monster, position, false, true)) { - delete monster; + if (!g_game.placeCreature(std::move(monster), position, false, true)) { std::cout << "[Error] Raids: Cant place monster " << monsterName << std::endl; return false; } @@ -509,7 +508,7 @@ bool AreaSpawnEvent::executeEvent() for (const MonsterSpawn& spawn : spawnList) { uint32_t amount = uniform_random(spawn.minAmount, spawn.maxAmount); for (uint32_t i = 0; i < amount; ++i) { - Monster* monster = Monster::createMonster(spawn.name); + auto monster = Monster::createMonster(spawn.name); if (!monster) { std::cout << "[Error - AreaSpawnEvent::executeEvent] Can't create monster " << spawn.name << std::endl; return false; @@ -517,7 +516,7 @@ bool AreaSpawnEvent::executeEvent() bool success = false; for (int32_t tries = 0; tries < MAXIMUM_TRIES_PER_MONSTER; tries++) { - Tile* tile = g_game.map.getTile(uniform_random(fromPos.x, toPos.x), uniform_random(fromPos.y, toPos.y), uniform_random(fromPos.z, toPos.z)); + const auto& tile = g_game.map.getTile(uniform_random(fromPos.x, toPos.x), uniform_random(fromPos.y, toPos.y), uniform_random(fromPos.z, toPos.z)); if (tile && !tile->isMoveableBlocking() && !tile->hasFlag(TILESTATE_PROTECTIONZONE) && tile->getTopCreature() == nullptr && g_game.placeCreature(monster, tile->getPosition(), false, true)) { success = true; break; @@ -525,7 +524,7 @@ bool AreaSpawnEvent::executeEvent() } if (!success) { - delete monster; + monster.reset(); } } } diff --git a/src/raids.h b/src/raids.h index 034e12c1..9c4e0fa1 100644 --- a/src/raids.h +++ b/src/raids.h @@ -49,22 +49,26 @@ class Raids bool isLoaded() const { return loaded; } + bool isStarted() const { return started; } - Raid* getRunning() { + Raid* getRunning() const + { return running; } + void setRunning(Raid* newRunning) { running = newRunning; } - Raid* getRaidByName(const std::string& name); + Raid* getRaidByName(const std::string& name) const; uint64_t getLastRaidEnd() const { return lastRaidEnd; } + void setLastRaidEnd(uint64_t newLastRaidEnd) { lastRaidEnd = newLastRaidEnd; } @@ -104,10 +108,12 @@ class Raid void executeRaidEvent(RaidEvent* raidEvent); void resetRaid(); - RaidEvent* getNextRaidEvent(); + RaidEvent* getNextRaidEvent() const; + void setState(RaidState_t newState) { state = newState; } + const std::string& getName() const { return name; } @@ -115,12 +121,15 @@ class Raid bool isLoaded() const { return loaded; } + uint64_t getMargin() const { return margin; } + uint32_t getInterval() const { return interval; } + bool canBeRepeated() const { return repeat; } diff --git a/src/rewardchest.cpp b/src/rewardchest.cpp index e39d4a7b..8ac27fe7 100644 --- a/src/rewardchest.cpp +++ b/src/rewardchest.cpp @@ -8,7 +8,7 @@ RewardChest::RewardChest(uint16_t type, bool paginated /*= true*/) : Container{ type, items[type].maxItems, true, paginated } { } -ReturnValue RewardChest::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature* actor/* = nullptr*/) const +ReturnValue RewardChest::queryAdd(int32_t, const ThingPtr&, uint32_t, uint32_t, CreaturePtr actor/* = std::nullopt*/) { if (actor) { return RETURNVALUE_NOTPOSSIBLE; @@ -17,16 +17,16 @@ ReturnValue RewardChest::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Cre return RETURNVALUE_NOERROR; } -void RewardChest::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void RewardChest::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - if (parent != nullptr) { - parent->postAddNotification(thing, oldParent, index, LINK_PARENT); + if (parent.lock()) { + parent.lock()->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void RewardChest::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void RewardChest::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - if (parent != nullptr) { - parent->postRemoveNotification(thing, newParent, index, LINK_PARENT); + if (parent.lock()) { + parent.lock()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } diff --git a/src/rewardchest.h b/src/rewardchest.h index 769c4f8d..ce191ec1 100644 --- a/src/rewardchest.h +++ b/src/rewardchest.h @@ -6,26 +6,25 @@ #include "container.h" -using RewardChest_ptr = std::shared_ptr; - class RewardChest final : public Container { public: explicit RewardChest(uint16_t type, bool paginated = true); - RewardChest* getRewardChest() override { - return this; + RewardChestPtr getRewardChest() override { + return {shared_from_this(), this}; } - const RewardChest* getRewardChest() const override { - return this; + + RewardChestConstPtr getRewardChest() const override { + return dynamic_shared_this(); } //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; }; diff --git a/src/scheduler.h b/src/scheduler.h index ab7595be..9e0a712e 100644 --- a/src/scheduler.h +++ b/src/scheduler.h @@ -17,6 +17,7 @@ class SchedulerTask : public Task void setEventId(uint32_t id) { eventId = id; } + uint32_t getEventId() const { return eventId; } @@ -24,6 +25,7 @@ class SchedulerTask : public Task uint32_t getDelay() const { return delay; } + private: SchedulerTask(uint32_t delay, TaskFunc&& f) : Task(std::move(f)), delay(delay) {} diff --git a/src/script.cpp b/src/script.cpp index 7f5e9c26..1edaa226 100644 --- a/src/script.cpp +++ b/src/script.cpp @@ -20,7 +20,7 @@ Scripts::~Scripts() scriptInterface.reInitState(); } -bool Scripts::loadScripts(std::string folderName, bool isLib, bool reload) +bool Scripts::loadScripts(const std::string& folderName, bool isLib, bool reload) { namespace fs = std::filesystem; diff --git a/src/script.h b/src/script.h index 46989292..2b9b8693 100644 --- a/src/script.h +++ b/src/script.h @@ -13,7 +13,7 @@ class Scripts Scripts(); ~Scripts(); - bool loadScripts(std::string folderName, bool isLib, bool reload); + bool loadScripts(const std::string& folderName, bool isLib, bool reload); LuaScriptInterface& getScriptInterface() { return scriptInterface; } diff --git a/src/server.cpp b/src/server.cpp index cc481d21..3605c239 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -86,7 +86,7 @@ void ServicePort::accept() acceptor->async_accept(connection->getSocket(), [=, thisPtr = shared_from_this()](const boost::system::error_code& error) { thisPtr->onAccept(connection, error); }); } -void ServicePort::onAccept(Connection_ptr connection, const boost::system::error_code& error) +void ServicePort::onAccept(const Connection_ptr& connection, const boost::system::error_code& error) { if (!error) { if (services.empty()) { @@ -135,7 +135,7 @@ void ServicePort::onStopServer() close(); } -void ServicePort::openAcceptor(std::weak_ptr weak_service, uint16_t port) +void ServicePort::openAcceptor(const std::weak_ptr& weak_service, uint16_t port) { if (auto service = weak_service.lock()) { service->open(port); @@ -169,7 +169,7 @@ void ServicePort::open(uint16_t port) } } -void ServicePort::close() +void ServicePort::close() const { if (acceptor && acceptor->is_open()) { boost::system::error_code error; diff --git a/src/server.h b/src/server.h index 904f5583..c496a72a 100644 --- a/src/server.h +++ b/src/server.h @@ -53,9 +53,9 @@ class ServicePort : public std::enable_shared_from_this ServicePort(const ServicePort&) = delete; ServicePort& operator=(const ServicePort&) = delete; - static void openAcceptor(std::weak_ptr weak_service, uint16_t port); + static void openAcceptor(const std::weak_ptr& weak_service, uint16_t port); void open(uint16_t port); - void close(); + void close() const; bool is_single_socket() const; std::string get_protocol_names() const; @@ -63,7 +63,7 @@ class ServicePort : public std::enable_shared_from_this Protocol_ptr make_protocol(bool checksummed, NetworkMessage& msg, const Connection_ptr& connection) const; void onStopServer(); - void onAccept(Connection_ptr connection, const boost::system::error_code& error); + void onAccept(const Connection_ptr& connection, const boost::system::error_code& error); private: void accept(); diff --git a/src/sharedobject.h b/src/sharedobject.h new file mode 100644 index 00000000..68700445 --- /dev/null +++ b/src/sharedobject.h @@ -0,0 +1,48 @@ +#ifndef BT_SHARED_OBJECT_H +#define BT_SHARED_OBJECT_H + +#include + +class SharedObject : public std::enable_shared_from_this +{ +public: + virtual ~SharedObject() = default; + + SharedObject& operator=(const SharedObject&) = delete; + + template + static std::shared_ptr Instantiate_Shared(Args... args) { + //std::cout << "## Debug Info : " << typeid(T).name() << " created with Instantiate_Shared()." << "\n"; + return std::make_shared(std::forward(args)...); + } + + template + std::shared_ptr static_shared_this() { + //std::cout << "## Debug Info : " << typeid(T).name() << " created with static_shared_this()." << "\n"; + //std::cout << " # " << typeid(T).name() << " has " << (shared_from_this().use_count() - 1) << " instances." << "\n"; + return std::static_pointer_cast(shared_from_this()); + } + + template + std::shared_ptr static_shared_this() const { + //std::cout << "## Debug Info : " << typeid(T).name() << " created with static_shared_this()." << "\n"; + //std::cout << " # " << typeid(T).name() << " has " << (shared_from_this().use_count() - 1) << " instances." << "\n"; + return std::static_pointer_cast(shared_from_this()); + } + + template + std::shared_ptr dynamic_shared_this() { + //std::cout << "## Debug Info : " << typeid(T).name() << " created with dynamic_shared_this()." << "\n"; + //std::cout << " # " << typeid(T).name() << " has " << (shared_from_this().use_count() - 1) << " instances." << "\n"; + return std::dynamic_pointer_cast(shared_from_this()); + } + + template + std::shared_ptr dynamic_shared_this() const { + //std::cout << "## Debug Info : " << typeid(T).name() << " created with dynamic_shared_this()." << "\n"; + //std::cout << " # " << typeid(T).name() << " has " << (shared_from_this().use_count() - 1) << " instances." << "\n"; + return std::dynamic_pointer_cast(shared_from_this()); + } +}; + +#endif diff --git a/src/spawn.cpp b/src/spawn.cpp index 6b8eb699..6b59708e 100644 --- a/src/spawn.cpp +++ b/src/spawn.cpp @@ -171,7 +171,7 @@ bool Spawns::loadFromXml(const std::string& filename) continue; } - Npc* npc = Npc::createNpc(nameAttribute.as_string()); + const auto& npc = Npc::createNpc(nameAttribute.as_string()); if (!npc) { continue; } @@ -199,10 +199,9 @@ void Spawns::startup() return; } - for (Npc* npc : npcList) { + for (const auto& npc : npcList) { if (!g_game.placeCreature(npc, npc->getMasterPos(), false, true)) { std::cout << "[Warning - Spawns::startup] Couldn't spawn npc \"" << npc->getName() << "\" on position: " << npc->getMasterPos() << '.' << std::endl; - delete npc; } } npcList.clear(); @@ -245,10 +244,9 @@ void Spawn::startSpawnCheck() Spawn::~Spawn() { - for (const auto& it : spawnedMap) { - Monster* monster = it.second; + for (const auto& val : spawnedMap | std::views::values) { + const auto& monster = val; monster->setSpawn(nullptr); - monster->decrementReferenceCounter(); } } @@ -256,10 +254,10 @@ bool Spawn::findPlayer(const Position& pos) { SpectatorVec spectators; g_game.map.getSpectators(spectators, pos, false, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); + for (const auto& spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); - Player* spectatorPlayer = static_cast(spectator); + const auto& spectatorPlayer = std::static_pointer_cast(spectator); if (!spectatorPlayer->hasFlag(PlayerFlag_IgnoredByMonsters)) { return true; } @@ -267,7 +265,7 @@ bool Spawn::findPlayer(const Position& pos) return false; } -bool Spawn::spawnMonster(uint32_t spawnId, spawnBlock_t sb, bool startup/* = false*/) +bool Spawn::spawnMonster(uint32_t spawnId, const spawnBlock_t& sb, bool startup/* = false*/) { bool isBlocked = !startup && findPlayer(sb.pos); size_t monstersCount = sb.mTypes.size(), blockedMonsters = 0; @@ -307,31 +305,27 @@ bool Spawn::spawnMonster(uint32_t spawnId, spawnBlock_t sb, bool startup/* = fal bool Spawn::spawnMonster(uint32_t spawnId, MonsterType* mType, const Position& pos, Direction dir, bool startup/*= false*/) { - std::unique_ptr monster_ptr(new Monster(mType)); - if (!g_events->eventMonsterOnSpawn(monster_ptr.get(), pos, startup, false)) { - monster_ptr.reset(); + + auto monster = std::make_shared(mType); + if (!g_events->eventMonsterOnSpawn(monster, pos, startup, false)) { return false; } if (startup) { //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)) { - std::cout << "[Warning - Spawns::startup] Couldn't spawn monster \"" << monster_ptr->getName() << "\" on position: " << pos << '.' << std::endl; - monster_ptr.reset(); + if (!g_game.internalPlaceCreature(monster, pos, true)) { + std::cout << "[Warning - Spawns::startup] Couldn't spawn monster \"" << monster->getName() << "\" on position: " << pos << '.' << std::endl; return false; } } else { - if (!g_game.placeCreature(monster_ptr.get(), pos, false, true)) { - monster_ptr.reset(); + if (!g_game.placeCreature(monster, pos, false, true)) { return false; } } - - Monster* monster = monster_ptr.release(); + monster->setDirection(dir); monster->setSpawn(this); monster->setMasterPos(pos); - monster->incrementReferenceCounter(); spawnedMap.insert({spawnId, monster}); spawnMap[spawnId].lastSpawn = OTSYS_TIME(); @@ -383,9 +377,8 @@ void Spawn::cleanup() { auto it = spawnedMap.begin(); while (it != spawnedMap.end()) { - Monster* monster = it->second; + const auto& monster = it->second; if (monster->isRemoved()) { - monster->decrementReferenceCounter(); it = spawnedMap.erase(it); } else { ++it; @@ -393,7 +386,7 @@ void Spawn::cleanup() } } -bool Spawn::addBlock(spawnBlock_t sb) +bool Spawn::addBlock(const spawnBlock_t& sb) { interval = std::min(interval, sb.interval); spawnMap[spawnMap.size() + 1] = sb; @@ -419,11 +412,10 @@ bool Spawn::addMonster(const std::string& name, const Position& pos, Direction d return addBlock(sb); } -void Spawn::removeMonster(Monster* monster) +void Spawn::removeMonster(const MonsterPtr& monster) { for (auto it = spawnedMap.begin(), end = spawnedMap.end(); it != end; ++it) { if (it->second == monster) { - monster->decrementReferenceCounter(); spawnedMap.erase(it); break; } diff --git a/src/spawn.h b/src/spawn.h index d3eab8b9..138a2f92 100644 --- a/src/spawn.h +++ b/src/spawn.h @@ -32,9 +32,9 @@ class Spawn Spawn(const Spawn&) = delete; Spawn& operator=(const Spawn&) = delete; - bool addBlock(spawnBlock_t sb); + bool addBlock(const spawnBlock_t& sb); bool addMonster(const std::string& name, const Position& pos, Direction dir, uint32_t interval); - void removeMonster(Monster* monster); + void removeMonster(const MonsterPtr& monster); uint32_t getInterval() const { return interval; @@ -47,7 +47,7 @@ class Spawn private: //map of the spawned creatures - using SpawnedMap = std::multimap; + using SpawnedMap = std::multimap; SpawnedMap spawnedMap; //map of creatures in the spawn @@ -60,7 +60,7 @@ class Spawn uint32_t checkSpawnEvent = 0; static bool findPlayer(const Position& pos); - bool spawnMonster(uint32_t spawnId, spawnBlock_t sb, bool startup = false); + bool spawnMonster(uint32_t spawnId, const spawnBlock_t& sb, bool startup = false); bool spawnMonster(uint32_t spawnId, MonsterType* mType, const Position& pos, Direction dir, bool startup = false); void checkSpawn(); }; @@ -79,7 +79,7 @@ class Spawns } private: - std::forward_list npcList; + std::forward_list npcList; std::forward_list spawnList; std::string filename; bool loaded = false; diff --git a/src/spectators.h b/src/spectators.h index bfce128a..d7b2f0a9 100644 --- a/src/spectators.h +++ b/src/spectators.h @@ -10,7 +10,7 @@ class Creature; class SpectatorVec { - using Vec = std::vector; + using Vec = std::vector; using Iterator = Vec::iterator; using ConstIterator = Vec::const_iterator; public: @@ -19,17 +19,16 @@ class SpectatorVec } void addSpectators(const SpectatorVec& spectators) { - for (Creature* spectator : spectators.vec) { - auto it = std::find(vec.begin(), vec.end(), spectator); - if (it != end()) { + for (CreaturePtr spectator : spectators.vec) { + if (auto it = std::ranges::find(vec, spectator); it != end()) { continue; } vec.emplace_back(spectator); } } - void erase(Creature* spectator) { - auto it = std::find(vec.begin(), vec.end(), spectator); + void erase(const CreaturePtr& spectator) { + const auto it = std::ranges::find(vec, spectator); if (it == end()) { return; } @@ -37,7 +36,7 @@ class SpectatorVec vec.pop_back(); } - Creature* operator[] (uint8_t index) { + CreaturePtr operator[] (const uint8_t index) { return vec[index]; } @@ -47,7 +46,7 @@ class SpectatorVec ConstIterator begin() const { return vec.begin(); } Iterator end() { return vec.end(); } ConstIterator end() const { return vec.end(); } - void emplace_back(Creature* c) { vec.emplace_back(c); } + void emplace_back(CreaturePtr c) { vec.emplace_back(c); } private: Vec vec; diff --git a/src/spells.cpp b/src/spells.cpp index 2ff13468..74ecd95f 100644 --- a/src/spells.cpp +++ b/src/spells.cpp @@ -29,7 +29,7 @@ Spells::~Spells() clear(false); } -TalkActionResult_t Spells::playerSaySpell(Player* player, std::string& words) +TalkActionResult_t Spells::playerSaySpell(const PlayerPtr& player, std::string& words) { std::string str_words = words; @@ -255,12 +255,12 @@ InstantSpell* Spells::getInstantSpellByName(const std::string& name) return nullptr; } -Position Spells::getCasterPosition(Creature* creature, Direction dir) +Position Spells::getCasterPosition(const CreaturePtr& creature, Direction dir) { return getNextPosition(dir, creature->getPosition()); } -CombatSpell::CombatSpell(Combat_ptr combat, bool needTarget, bool needDirection) : +CombatSpell::CombatSpell(const Combat_ptr& combat, bool needTarget, bool needDirection) : Event(&g_spells->getScriptInterface()), combat(combat), needDirection(needDirection), @@ -273,7 +273,7 @@ bool CombatSpell::loadScriptCombat() return combat != nullptr; } -bool CombatSpell::castSpell(Creature* creature) +bool CombatSpell::castSpell(const CreaturePtr& creature) { if (scripted) { LuaVariant var; @@ -298,7 +298,7 @@ bool CombatSpell::castSpell(Creature* creature) return true; } -bool CombatSpell::castSpell(Creature* creature, Creature* target) +bool CombatSpell::castSpell(const CreaturePtr& creature, const CreaturePtr& target) { if (scripted) { LuaVariant var; @@ -330,7 +330,7 @@ bool CombatSpell::castSpell(Creature* creature, Creature* target) return true; } -bool CombatSpell::executeCastSpell(Creature* creature, const LuaVariant& var) +bool CombatSpell::executeCastSpell(const CreaturePtr& creature, const LuaVariant& var) { //onCastSpell(creature, var) if (!scriptInterface->reserveScriptEnv()) { @@ -345,7 +345,7 @@ bool CombatSpell::executeCastSpell(Creature* creature, const LuaVariant& var) scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushVariant(L, var); @@ -546,7 +546,7 @@ bool Spell::configureSpell(const pugi::xml_node& node) return true; } -bool Spell::playerSpellCheck(Player* player) const +bool Spell::playerSpellCheck(const PlayerPtr& player) const { if (player->hasFlag(PlayerFlag_CannotUseSpells)) { return false; @@ -646,7 +646,7 @@ bool Spell::playerSpellCheck(Player* player) const return true; } -bool Spell::playerInstantSpellCheck(Player* player, const Position& toPos) +bool Spell::playerInstantSpellCheck(const PlayerPtr& player, const Position& toPos) { if (toPos.x == 0xFFFF) { return true; @@ -663,9 +663,9 @@ bool Spell::playerInstantSpellCheck(Player* player, const Position& toPos) return false; } - Tile* tile = g_game.map.getTile(toPos); + auto tile = g_game.map.getTile(toPos); if (!tile) { - tile = new StaticTile(toPos.x, toPos.y, toPos.z); + tile = std::make_shared(toPos.x, toPos.y, toPos.z); g_game.map.setTile(toPos, tile); } @@ -688,7 +688,7 @@ bool Spell::playerInstantSpellCheck(Player* player, const Position& toPos) return true; } -bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) +bool Spell::playerRuneSpellCheck(const PlayerPtr& player, const Position& toPos) { if (!playerSpellCheck(player)) { return false; @@ -709,7 +709,7 @@ bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) return false; } - Tile* tile = g_game.map.getTile(toPos); + auto tile = g_game.map.getTile(toPos); if (!tile) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -729,7 +729,7 @@ bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) return false; } - const Creature* topVisibleCreature = tile->getBottomVisibleCreature(player); + const auto& topVisibleCreature = tile->getBottomVisibleCreature(player); if (blockingCreature && topVisibleCreature) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -747,7 +747,7 @@ bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) } if (aggressive && needTarget && topVisibleCreature && player->hasSecureMode()) { - const Player* targetPlayer = topVisibleCreature->getPlayer(); + const auto& targetPlayer = topVisibleCreature->getPlayer(); if (targetPlayer && targetPlayer != player && player->getSkullClient(targetPlayer) == SKULL_NONE && !Combat::isInPvpZone(player, targetPlayer)) { player->sendCancelMessage(RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -762,7 +762,7 @@ bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) return true; } -void Spell::addCooldowns(Player* player) const +void Spell::addCooldowns(const PlayerPtr& player) const { if (cooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, cooldown, 0, false, spellId); @@ -780,7 +780,7 @@ void Spell::addCooldowns(Player* player) const } } -void Spell::postCastSpell(Player* player, bool finishedCast /*= true*/, bool payCost /*= true*/) const +void Spell::postCastSpell(const PlayerPtr& player, bool finishedCast /*= true*/, bool payCost /*= true*/) const { if (finishedCast) { if (!player->hasFlag(PlayerFlag_HasNoExhaustion)) { @@ -797,7 +797,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(const PlayerPtr& player, uint32_t manaCost, uint32_t soulCost) { if (manaCost > 0) { player->addManaSpent(manaCost); @@ -811,7 +811,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 PlayerConstPtr& player) const { if (mana != 0) { return mana; @@ -859,7 +859,7 @@ bool InstantSpell::configureEvent(const pugi::xml_node& node) return true; } -bool InstantSpell::playerCastInstant(Player* player, std::string& param) +bool InstantSpell::playerCastInstant(const PlayerPtr& player, std::string& param) { if (!playerSpellCheck(player)) { return false; @@ -870,12 +870,12 @@ bool InstantSpell::playerCastInstant(Player* player, std::string& param) if (selfTarget) { var.setNumber(player->getID()); } else if (needTarget || casterTargetOrDirection) { - Creature* target = nullptr; + CreaturePtr target = nullptr; bool useDirection = false; if (hasParam) { - Player* playerTarget = nullptr; - ReturnValue ret = g_game.getPlayerByNameWildcard(param, playerTarget); + PlayerPtr playerTarget = nullptr; + ReturnValue ret = g_game.getPlayerByNameWildcard(param); if (playerTarget && playerTarget->isAccessPlayer() && !player->isAccessPlayer()) { playerTarget = nullptr; @@ -927,8 +927,8 @@ bool InstantSpell::playerCastInstant(Player* player, std::string& param) } } else if (hasParam) { if (getHasPlayerNameParam()) { - Player* playerTarget = nullptr; - ReturnValue ret = g_game.getPlayerByNameWildcard(param, playerTarget); + PlayerPtr playerTarget = nullptr; + ReturnValue ret = g_game.getPlayerByNameWildcard(param); if (ret != RETURNVALUE_NOERROR) { addCooldowns(player); @@ -964,7 +964,7 @@ bool InstantSpell::playerCastInstant(Player* player, std::string& param) return result; } -bool InstantSpell::canThrowSpell(const Creature* creature, const Creature* target) const +bool InstantSpell::canThrowSpell(const CreatureConstPtr& creature, const CreatureConstPtr& target) const { const Position& fromPos = creature->getPosition(); const Position& toPos = target->getPosition(); @@ -976,12 +976,12 @@ bool InstantSpell::canThrowSpell(const Creature* creature, const Creature* targe return true; } -bool InstantSpell::castSpell(Creature* creature) +bool InstantSpell::castSpell(const CreaturePtr& creature) { LuaVariant var; if (casterTargetOrDirection) { - Creature* target = creature->getAttackedCreature(); + const auto& target = creature->getAttackedCreature(); if (target && target->getHealth() > 0) { if (!canThrowSpell(creature, target)) { return false; @@ -1001,7 +1001,7 @@ bool InstantSpell::castSpell(Creature* creature) return internalCastSpell(creature, var); } -bool InstantSpell::castSpell(Creature* creature, Creature* target) +bool InstantSpell::castSpell(const CreaturePtr& creature, const CreaturePtr& target) { if (needTarget) { LuaVariant var; @@ -1012,12 +1012,12 @@ bool InstantSpell::castSpell(Creature* creature, Creature* target) } } -bool InstantSpell::internalCastSpell(Creature* creature, const LuaVariant& var) +bool InstantSpell::internalCastSpell(const CreaturePtr& creature, const LuaVariant& var) { return executeCastSpell(creature, var); } -bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant& var) +bool InstantSpell::executeCastSpell(const CreaturePtr& creature, const LuaVariant& var) { //onCastSpell(creature, var) if (!scriptInterface->reserveScriptEnv()) { @@ -1032,7 +1032,7 @@ bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant& var) scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushVariant(L, var); @@ -1040,7 +1040,7 @@ bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant& var) return scriptInterface->callFunction(2); } -bool InstantSpell::canCast(const Player* player) const +bool InstantSpell::canCast(const PlayerConstPtr& player) const { if (player->hasFlag(PlayerFlag_CannotUseSpells)) { return false; @@ -1055,7 +1055,7 @@ bool InstantSpell::canCast(const Player* player) const return true; } } else { - if (vocSpellMap.empty() || vocSpellMap.find(player->getVocationId()) != vocSpellMap.end()) { + if (vocSpellMap.empty() || vocSpellMap.contains(player->getVocationId())) { return true; } } @@ -1100,7 +1100,7 @@ bool RuneSpell::configureEvent(const pugi::xml_node& node) return true; } -ReturnValue RuneSpell::canExecuteAction(const Player* player, const Position& toPos) +ReturnValue RuneSpell::canExecuteAction(const PlayerConstPtr& player, const Position& toPos) { if (player->hasFlag(PlayerFlag_CannotUseSpells)) { return RETURNVALUE_CANNOTUSETHISOBJECT; @@ -1122,7 +1122,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(const PlayerPtr& player, const ItemPtr& item, const Position&, const ThingPtr& target, const Position& toPosition, bool isHotkey) { if (!playerRuneSpellCheck(player, toPosition)) { return false; @@ -1137,10 +1137,8 @@ bool RuneSpell::executeUse(Player* player, Item* item, const Position&, Thing* t if (needTarget) { if (target == nullptr) { - Tile* toTile = g_game.map.getTile(toPosition); - if (toTile) { - const Creature* visibleCreature = toTile->getBottomVisibleCreature(player); - if (visibleCreature) { + if (const auto& toTile = g_game.map.getTile(toPosition)) { + if (const auto& visibleCreature = toTile->getBottomVisibleCreature(player)) { var.setNumber(visibleCreature->getID()); } } @@ -1158,9 +1156,9 @@ bool RuneSpell::executeUse(Player* player, Item* item, const Position&, Thing* t postCastSpell(player); if (var.isNumber()) { - target = g_game.getCreatureByID(var.getNumber()); - if (getPzLock() && target) { - player->onAttackedCreature(target->getCreature()); + auto n_target = g_game.getCreatureByID(var.getNumber()); + if (getPzLock() && n_target) { + player->onAttackedCreature(n_target->getCreature()); } } @@ -1171,21 +1169,21 @@ bool RuneSpell::executeUse(Player* player, Item* item, const Position&, Thing* t return true; } -bool RuneSpell::castSpell(Creature* creature) +bool RuneSpell::castSpell(const CreaturePtr& creature) { LuaVariant var; var.setNumber(creature->getID()); return internalCastSpell(creature, var, false); } -bool RuneSpell::castSpell(Creature* creature, Creature* target) +bool RuneSpell::castSpell(const CreaturePtr& creature, const CreaturePtr& target) { LuaVariant var; var.setNumber(target->getID()); return internalCastSpell(creature, var, false); } -bool RuneSpell::internalCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) +bool RuneSpell::internalCastSpell(const CreaturePtr& creature, const LuaVariant& var, bool isHotkey) { bool result; if (scripted) { @@ -1196,7 +1194,7 @@ bool RuneSpell::internalCastSpell(Creature* creature, const LuaVariant& var, boo return result; } -bool RuneSpell::executeCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) +bool RuneSpell::executeCastSpell(const CreaturePtr& creature, const LuaVariant& var, bool isHotkey) { //onCastSpell(creature, var, isHotkey) if (!scriptInterface->reserveScriptEnv()) { @@ -1211,7 +1209,7 @@ bool RuneSpell::executeCastSpell(Creature* creature, const LuaVariant& var, bool scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, creature); + LuaScriptInterface::pushSharedPtr(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushVariant(L, var); diff --git a/src/spells.h b/src/spells.h index d55b32ea..ac158845 100644 --- a/src/spells.h +++ b/src/spells.h @@ -34,9 +34,9 @@ class Spells final : public BaseEvents InstantSpell* getInstantSpell(const std::string& words); InstantSpell* getInstantSpellByName(const std::string& name); - TalkActionResult_t playerSaySpell(Player* player, std::string& words); + TalkActionResult_t playerSaySpell(const PlayerPtr& player, std::string& words); - static Position getCasterPosition(Creature* creature, Direction dir); + static Position getCasterPosition(const CreaturePtr& creature, Direction dir); std::string_view getScriptBaseName() const override { return "spells"; } const std::map& getInstantSpells() const { @@ -66,27 +66,27 @@ class BaseSpell constexpr BaseSpell() = default; virtual ~BaseSpell() = default; - virtual bool castSpell(Creature* creature) = 0; - virtual bool castSpell(Creature* creature, Creature* target) = 0; + virtual bool castSpell(const CreaturePtr& creature) = 0; + virtual bool castSpell(const CreaturePtr& creature, const CreaturePtr& target) = 0; }; class CombatSpell final : public Event, public BaseSpell { public: - CombatSpell(Combat_ptr combat, bool needTarget, bool needDirection); + CombatSpell(const Combat_ptr& combat, bool needTarget, bool needDirection); // non-copyable CombatSpell(const CombatSpell&) = delete; CombatSpell& operator=(const CombatSpell&) = delete; - bool castSpell(Creature* creature) override; - bool castSpell(Creature* creature, Creature* target) override; + bool castSpell(const CreaturePtr& creature) override; + bool castSpell(const CreaturePtr& creature, const CreaturePtr& target) override; bool configureEvent(const pugi::xml_node&) override { return true; } //scripting - bool executeCastSpell(Creature* creature, const LuaVariant& var); + bool executeCastSpell(const CreaturePtr& creature, const LuaVariant& var); bool loadScriptCombat(); Combat_ptr getCombat() { @@ -111,67 +111,85 @@ class Spell : public BaseSpell const std::string& getName() const { return name; } - void setName(std::string n) { + + void setName(const std::string& n) { name = n; } + uint8_t getId() const { return spellId; } + void setId(uint8_t id) { spellId = id; } - void postCastSpell(Player* player, bool finishedCast = true, bool payCost = true) const; - static void postCastSpell(Player* player, uint32_t manaCost, uint32_t soulCost); + void postCastSpell(const PlayerPtr& player, bool finishedCast = true, bool payCost = true) const; + static void postCastSpell(const PlayerPtr& player, uint32_t manaCost, uint32_t soulCost); - uint32_t getManaCost(const Player* player) const; + uint32_t getManaCost(const PlayerConstPtr& player) const; uint32_t getSoulCost() const { return soul; } + void setSoulCost(uint32_t s) { soul = s; } + uint32_t getLevel() const { return level; } + void setLevel(uint32_t lvl) { level = lvl; } + uint32_t getMagicLevel() const { return magLevel; } + void setMagicLevel(uint32_t lvl) { magLevel = lvl; } + uint32_t getMana() const { return mana; } + void setMana(uint32_t m) { mana = m; } + uint32_t getManaPercent() const { return manaPercent; } + void setManaPercent(uint32_t m) { manaPercent = m; } + bool isPremium() const { return premium; } + void setPremium(bool p) { premium = p; } + bool isEnabled() const { return enabled; } + void setEnabled(bool e) { enabled = e; } virtual bool isInstant() const = 0; + bool isLearnable() const { return learnable; } + void setLearnable(bool l) { learnable = l; } @@ -179,6 +197,7 @@ class Spell : public BaseSpell const VocSpellMap& getVocMap() const { return vocSpellMap; } + void addVocMap(uint16_t n, bool b) { vocSpellMap[n] = b; } @@ -186,15 +205,18 @@ class Spell : public BaseSpell SpellGroup_t getGroup() const { return group; } + void setGroup(SpellGroup_t g) { group = g; if(group == SPELLGROUP_NONE) { groupCooldown = 0; } } + SpellGroup_t getSecondaryGroup() const { return secondaryGroup; } + void setSecondaryGroup(SpellGroup_t g) { secondaryGroup = g; } @@ -202,18 +224,23 @@ class Spell : public BaseSpell uint32_t getCooldown() const { return cooldown; } + void setCooldown(uint32_t cd) { cooldown = cd; } + uint32_t getSecondaryCooldown() const { return secondaryGroupCooldown; } + void setSecondaryCooldown(uint32_t cd) { secondaryGroupCooldown = cd; } + uint32_t getGroupCooldown() const { return groupCooldown; } + void setGroupCooldown(uint32_t cd) { groupCooldown = cd; } @@ -221,6 +248,7 @@ class Spell : public BaseSpell int32_t getRange() const { return range; } + void setRange(int32_t r) { range = r; } @@ -228,48 +256,62 @@ class Spell : public BaseSpell bool getNeedTarget() const { return needTarget; } + void setNeedTarget(bool n) { needTarget = n; } + bool getNeedWeapon() const { return needWeapon; } + void setNeedWeapon(bool n) { needWeapon = n; } + bool getNeedLearn() const { return learnable; } + void setNeedLearn(bool n) { learnable = n; } + bool getSelfTarget() const { return selfTarget; } + void setSelfTarget(bool s) { selfTarget = s; } + bool getBlockingSolid() const { return blockingSolid; } + void setBlockingSolid(bool b) { blockingSolid = b; } + bool getBlockingCreature() const { return blockingCreature; } + void setBlockingCreature(bool b) { blockingCreature = b; } bool getAggressive() const { return aggressive; } + void setAggressive(bool a) { aggressive = a; } + bool getPzLock() const { return pzLock; } + void setPzLock(bool pzLock) { this->pzLock = pzLock; } @@ -277,10 +319,10 @@ class Spell : public BaseSpell SpellType_t spellType = SPELL_UNDEFINED; protected: - bool playerSpellCheck(Player* player) const; - bool playerInstantSpellCheck(Player* player, const Position& toPos); - bool playerRuneSpellCheck(Player* player, const Position& toPos); - void addCooldowns(Player* player) const; + bool playerSpellCheck(const PlayerPtr& player) const; + bool playerInstantSpellCheck(const PlayerPtr& player, const Position& toPos); + bool playerRuneSpellCheck(const PlayerPtr& player, const Position& toPos); + void addCooldowns(const PlayerPtr& player) const; VocSpellMap vocSpellMap; @@ -323,54 +365,65 @@ class InstantSpell final : public TalkAction, public Spell bool configureEvent(const pugi::xml_node& node) override; - virtual bool playerCastInstant(Player* player, std::string& param); + bool playerCastInstant(const PlayerPtr& player, std::string& param); - bool castSpell(Creature* creature) override; - bool castSpell(Creature* creature, Creature* target) override; + bool castSpell(const CreaturePtr& creature) override; + bool castSpell(const CreaturePtr& creature, const CreaturePtr& target) override; //scripting - bool executeCastSpell(Creature* creature, const LuaVariant& var); + bool executeCastSpell(const CreaturePtr& creature, const LuaVariant& var); bool isInstant() const override { return true; } + bool getHasParam() const { return hasParam; } + void setHasParam(bool p) { hasParam = p; } + bool getHasPlayerNameParam() const { return hasPlayerNameParam; } + void setHasPlayerNameParam(bool p) { hasPlayerNameParam = p; } + bool getNeedDirection() const { return needDirection; } + void setNeedDirection(bool n) { needDirection = n; } + bool getNeedCasterTargetOrDirection() const { return casterTargetOrDirection; } + void setNeedCasterTargetOrDirection(bool d) { casterTargetOrDirection = d; } + bool getBlockWalls() const { return checkLineOfSight; } + void setBlockWalls(bool w) { checkLineOfSight = w; } - bool canCast(const Player* player) const; - bool canThrowSpell(const Creature* creature, const Creature* target) const; + + bool canCast(const PlayerConstPtr& player) const; + bool canThrowSpell(const CreatureConstPtr& creature, const CreatureConstPtr& target) const; private: std::string_view getScriptEventName() const override { return "onCastSpell"; } - bool internalCastSpell(Creature* creature, const LuaVariant& var); + bool internalCastSpell(const CreaturePtr& creature, const LuaVariant& var); bool needDirection = false; bool hasParam = false; @@ -386,34 +439,40 @@ class RuneSpell final : public Action, public Spell bool configureEvent(const pugi::xml_node& node) override; - ReturnValue canExecuteAction(const Player* player, const Position& toPos) override; + ReturnValue canExecuteAction(const PlayerConstPtr& player, const Position& toPos) override; + bool hasOwnErrorHandler() override { return true; } - Thing* getTarget(Player*, Creature* targetCreature, const Position&, uint8_t) const override { - return targetCreature; + + ThingPtr getTarget(const PlayerPtr&, const CreaturePtr& targetCreature, const Position&, uint8_t) const override { + return targetCreature; // implicit upcasts are handled automatically } - bool executeUse(Player* player, Item* item, const Position& fromPosition, Thing* target, const Position& toPosition, bool isHotkey) override; + bool executeUse(const PlayerPtr& player, const ItemPtr& item, const Position& fromPosition, const ThingPtr& target, const Position& toPosition, bool isHotkey) override; - bool castSpell(Creature* creature) override; - bool castSpell(Creature* creature, Creature* target) override; + bool castSpell(const CreaturePtr& creature) override; + bool castSpell(const CreaturePtr& creature, const CreaturePtr& target) override; //scripting - bool executeCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey); + bool executeCastSpell(const CreaturePtr& creature, const LuaVariant& var, bool isHotkey); bool isInstant() const override { return false; } + uint16_t getRuneItemId() const { return runeId; } + void setRuneItemId(uint16_t i) { runeId = i; } + uint32_t getCharges() const { return charges; } + void setCharges(uint32_t c) { if (c > 0) { hasCharges = true; @@ -424,7 +483,7 @@ class RuneSpell final : public Action, public Spell private: std::string_view getScriptEventName() const override { return "onCastSpell"; } - bool internalCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey); + bool internalCastSpell(const CreaturePtr& creature, const LuaVariant& var, bool isHotkey); uint16_t runeId = 0; uint32_t charges = 0; diff --git a/src/storeinbox.cpp b/src/storeinbox.cpp index 52be441f..309a617c 100644 --- a/src/storeinbox.cpp +++ b/src/storeinbox.cpp @@ -7,14 +7,14 @@ StoreInbox::StoreInbox(uint16_t type) : Container(type, 20, true, true) {} -ReturnValue StoreInbox::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t flags, Creature*) const +ReturnValue StoreInbox::queryAdd(int32_t, const ThingPtr& thing, uint32_t, uint32_t flags, CreaturePtr) { - const Item* item = thing.getItem(); + const auto& item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } - if (item == this) { + if (item == this->getItem()) { return RETURNVALUE_THISISIMPOSSIBLE; } @@ -27,8 +27,7 @@ ReturnValue StoreInbox::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t return RETURNVALUE_CANNOTMOVEITEMISNOTSTOREITEM; } - const Container* container = item->getContainer(); - if (container && !container->empty()) { + if (const auto& container = item->getContainer(); container && !container->empty()) { return RETURNVALUE_ITEMCANNOTBEMOVEDTHERE; } } @@ -36,17 +35,17 @@ ReturnValue StoreInbox::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t return RETURNVALUE_NOERROR; } -void StoreInbox::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void StoreInbox::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - if (parent != nullptr) { - parent->postAddNotification(thing, oldParent, index, LINK_TOPPARENT); + if (parent.lock()) { + parent.lock()->postAddNotification(thing, oldParent, index, LINK_TOPPARENT); } } -void StoreInbox::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void StoreInbox::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - if (parent != nullptr) { - parent->postRemoveNotification(thing, newParent, index, LINK_TOPPARENT); + if (parent.lock()) { + parent.lock()->postRemoveNotification(thing, newParent, index, LINK_TOPPARENT); } } diff --git a/src/storeinbox.h b/src/storeinbox.h index 27f17b8d..a1e9cf51 100644 --- a/src/storeinbox.h +++ b/src/storeinbox.h @@ -11,19 +11,20 @@ class StoreInbox final : public Container public: explicit StoreInbox(uint16_t type); - StoreInbox* getStoreInbox() override { - return this; + StoreInboxPtr getStoreInbox() override { + return dynamic_shared_this(); } - const StoreInbox* getStoreInbox() const override { - return this; + + StoreInboxConstPtr getStoreInbox() const override { + return dynamic_shared_this(); } //cylinder implementations - ReturnValue queryAdd(int32_t index, const Thing& thing, uint32_t count, - uint32_t flags, Creature* actor = nullptr) const override; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; bool canRemove() const override { return false; diff --git a/src/talkaction.cpp b/src/talkaction.cpp index 38235b68..0dbfadd7 100644 --- a/src/talkaction.cpp +++ b/src/talkaction.cpp @@ -76,7 +76,7 @@ bool TalkActions::registerLuaEvent(TalkAction* event) return true; } -TalkActionResult_t TalkActions::playerSaySpell(Player* player, SpeakClasses type, const std::string& words) const +TalkActionResult_t TalkActions::playerSaySpell(const PlayerPtr& player, SpeakClasses type, const std::string& words) const { size_t wordsLength = words.length(); for (auto it = talkActions.begin(); it != talkActions.end(); ) { @@ -146,7 +146,7 @@ bool TalkAction::configureEvent(const pugi::xml_node& node) return true; } -bool TalkAction::executeSay(Player* player, const std::string& words, const std::string& param, SpeakClasses type) const +bool TalkAction::executeSay(const PlayerPtr& player, const std::string& words, const std::string& param, SpeakClasses type) const { //onSay(player, words, param, type) if (!scriptInterface->reserveScriptEnv()) { @@ -161,7 +161,7 @@ bool TalkAction::executeSay(Player* player, const std::string& words, const std: scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushString(L, words); diff --git a/src/talkaction.h b/src/talkaction.h index 402e6309..4839a077 100644 --- a/src/talkaction.h +++ b/src/talkaction.h @@ -37,12 +37,12 @@ class TalkAction : public Event std::string getSeparator() const { return separator; } - void setSeparator(std::string sep) { + void setSeparator(const std::string& sep) { separator = sep; } //scripting - bool executeSay(Player* player, const std::string& words, const std::string& param, SpeakClasses type) const; + bool executeSay(const PlayerPtr& player, const std::string& words, const std::string& param, SpeakClasses type) const; AccountType_t getRequiredAccountType() const { return requiredAccountType; @@ -74,13 +74,13 @@ class TalkActions final : public BaseEvents { public: TalkActions(); - ~TalkActions(); + ~TalkActions() override; // non-copyable TalkActions(const TalkActions&) = delete; TalkActions& operator=(const TalkActions&) = delete; - TalkActionResult_t playerSaySpell(Player* player, SpeakClasses type, const std::string& words) const; + TalkActionResult_t playerSaySpell(const PlayerPtr& player, SpeakClasses type, const std::string& words) const; bool registerLuaEvent(TalkAction* event); void clear(bool fromLua) override final; diff --git a/src/tasks.h b/src/tasks.h index b6aecb44..7ea1a7fd 100644 --- a/src/tasks.h +++ b/src/tasks.h @@ -21,7 +21,8 @@ class Task expiration(std::chrono::system_clock::now() + std::chrono::milliseconds(ms)), func(std::move(f)) {} virtual ~Task() = default; - void operator()() { + void operator()() const + { func(); } diff --git a/src/teleport.cpp b/src/teleport.cpp index 27a71d8d..e9c4eb43 100644 --- a/src/teleport.cpp +++ b/src/teleport.cpp @@ -29,51 +29,50 @@ 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 ThingPtr&, uint32_t, uint32_t, CreaturePtr) { return RETURNVALUE_NOTPOSSIBLE; } -ReturnValue Teleport::queryMaxCount(int32_t, const Thing&, uint32_t, uint32_t&, uint32_t) const +ReturnValue Teleport::queryMaxCount(int32_t, const ThingPtr&, uint32_t, uint32_t&, uint32_t) { return RETURNVALUE_NOTPOSSIBLE; } -ReturnValue Teleport::queryRemove(const Thing&, uint32_t, uint32_t, Creature* /*= nullptr */) const +ReturnValue Teleport::queryRemove(const ThingPtr&, uint32_t, uint32_t, CreaturePtr /*= nullptr */) { return RETURNVALUE_NOERROR; } -Cylinder* Teleport::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) +CylinderPtr Teleport::queryDestination(int32_t&, const ThingPtr&, ItemPtr*, uint32_t&) { - return this; + return this->getTile(); } -void Teleport::addThing(Thing* thing) +void Teleport::addThing(ThingPtr thing) { return addThing(0, thing); } -void Teleport::addThing(int32_t, Thing* thing) +void Teleport::addThing(int32_t, ThingPtr thing) { - Tile* destTile = g_game.map.getTile(destPos); + const auto destTile = g_game.map.getTile(destPos); if (!destTile) { return; } // Prevent infinite loop - Teleport* destTeleport = destTile->getTeleportItem(); - if (destTeleport) { + if (auto destTeleport = destTile->getTeleportItem()) { std::vector lastPositions = { getPosition() }; while (true) { const Position& nextPos = destTeleport->getDestPos(); - if (std::find(lastPositions.begin(), lastPositions.end(), nextPos) != lastPositions.end()) { + if (std::ranges::find(lastPositions, nextPos) != lastPositions.end()) { std::cout << "Warning: possible infinite loop teleport. " << nextPos << std::endl; return; } - const Tile* tile = g_game.map.getTile(nextPos); + const auto& tile = g_game.map.getTile(nextPos); if (!tile) { break; } @@ -89,44 +88,50 @@ void Teleport::addThing(int32_t, Thing* thing) const MagicEffectClasses effect = Item::items[id].magicEffect; - if (Creature* creature = thing->getCreature()) { + if (auto creature = thing->getCreature()) { Position origPos = creature->getPosition(); g_game.internalCreatureTurn(creature, origPos.x > destPos.x ? DIRECTION_WEST : DIRECTION_EAST); - g_game.map.moveCreature(*creature, *destTile); + g_game.map.moveCreature(creature, destTile); if (effect != CONST_ME_NONE) { g_game.addMagicEffect(origPos, effect); g_game.addMagicEffect(destTile->getPosition(), effect); } - } else if (Item* item = thing->getItem()) { + } else if (const auto& item = thing->getItem()) { if (effect != CONST_ME_NONE) { g_game.addMagicEffect(destTile->getPosition(), effect); g_game.addMagicEffect(item->getPosition(), effect); } - g_game.internalMoveItem(getTile(), destTile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT); + CylinderPtr f_cylinder = getTile(); + CylinderPtr t_cylinder = destTile; + g_game.internalMoveItem(f_cylinder, t_cylinder, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT); } } -void Teleport::updateThing(Thing*, uint16_t, uint32_t) +void Teleport::updateThing(ThingPtr, uint16_t, uint32_t) { // } -void Teleport::replaceThing(uint32_t, Thing*) +void Teleport::replaceThing(uint32_t, ThingPtr) { // } -void Teleport::removeThing(Thing*, uint32_t) +void Teleport::removeThing(ThingPtr, uint32_t) { // } -void Teleport::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void Teleport::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); + if (parent.lock()) { + parent.lock()->postAddNotification(thing, oldParent, index, LINK_PARENT); + } } -void Teleport::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void Teleport::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); + if (parent.lock()) { + parent.lock()->postRemoveNotification(thing, newParent, index, LINK_PARENT); + } } diff --git a/src/teleport.h b/src/teleport.h index 200cbde6..cb3775a9 100644 --- a/src/teleport.h +++ b/src/teleport.h @@ -11,11 +11,12 @@ class Teleport final : public Item, public Cylinder public: explicit Teleport(uint16_t type) : Item(type) {}; - Teleport* getTeleport() override { - return this; + TeleportPtr getTeleport() override { + return {shared_from_this(), this}; } - const Teleport* getTeleport() const override { - return this; + + TeleportConstPtr getTeleport() const override { + return {shared_from_this(), this}; } //serialization @@ -25,29 +26,30 @@ class Teleport final : public Item, public Cylinder const Position& getDestPos() const { return destPos; } + void setDestPos(const Position& pos) { destPos = pos; } //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; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) override; + ReturnValue queryMaxCount(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t& maxQueryCount, uint32_t flags) override; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, + uint32_t& flags) override; // again optional ref wrapper - void addThing(Thing* thing) override; - void addThing(int32_t index, Thing* thing) override; + void addThing(ThingPtr thing) override; + void addThing(int32_t index, ThingPtr thing) override; - void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, Thing* thing) override; + void updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, ThingPtr thing) override; - void removeThing(Thing* thing, uint32_t count) override; + void removeThing(ThingPtr thing, uint32_t count) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; private: Position destPos; diff --git a/src/thing.cpp b/src/thing.cpp index 5b6e35ed..7f8fcca4 100644 --- a/src/thing.cpp +++ b/src/thing.cpp @@ -8,19 +8,17 @@ const Position& Thing::getPosition() const { - const Tile* tile = getTile(); + const auto tile = getTile(); if (!tile) { - return Tile::nullptr_tile.getPosition(); + return std::make_shared(0xFFFF, 0xFFFF, 0xFF)->getPosition(); } return tile->getPosition(); } -Tile* Thing::getTile() -{ - return dynamic_cast(this); +TilePtr Thing::getTile() { + return nullptr; } -const Tile* Thing::getTile() const -{ - return dynamic_cast(this); +TileConstPtr Thing::getTile() const { + return nullptr; } diff --git a/src/thing.h b/src/thing.h index ec723bfb..226c1f89 100644 --- a/src/thing.h +++ b/src/thing.h @@ -5,6 +5,10 @@ #define FS_THING_H #include "position.h" +#include +#include +#include "sharedobject.h" + class Tile; class Cylinder; @@ -12,58 +16,96 @@ class Item; class Creature; class Container; +using ThingPtr = std::shared_ptr; +using ThingConstPtr = std::shared_ptr; + +using TilePtr = std::shared_ptr; +using TileConstPtr = std::shared_ptr; +using TileWeakPtr = std::weak_ptr; + +using CylinderPtr = std::shared_ptr; +using CylinderConstPtr = std::shared_ptr; +using CylinderWeakPtr = std::weak_ptr; + +using ItemPtr = std::shared_ptr; +using ItemConstPtr = std::shared_ptr; + +using CreaturePtr = std::shared_ptr; +using CreatureConstPtr = std::shared_ptr; + +using ContainerPtr = std::shared_ptr; +using ContainerConstPtr = std::shared_ptr; + class Thing { - public: - constexpr Thing() = default; - virtual ~Thing() = default; - - // non-copyable - Thing(const Thing&) = delete; - Thing& operator=(const Thing&) = delete; - - virtual std::string getDescription(int32_t lookDistance) const = 0; - - virtual Cylinder* getParent() const { - return nullptr; - } - virtual Cylinder* getRealParent() const { - return getParent(); - } - - virtual void setParent(Cylinder*) { - // - } - - virtual Tile* getTile(); - virtual const Tile* getTile() const; - - virtual const Position& getPosition() const; - virtual int32_t getThrowRange() const = 0; - virtual bool isPushable() const = 0; - - virtual Container* getContainer() { - return nullptr; - } - virtual const Container* getContainer() const { - return nullptr; - } - virtual Item* getItem() { - return nullptr; - } - virtual const Item* getItem() const { - return nullptr; - } - virtual Creature* getCreature() { - return nullptr; - } - virtual const Creature* getCreature() const { - return nullptr; - } - - virtual bool isRemoved() const { - return true; - } + public: + virtual ~Thing() = default; + + // non-copyable + Thing(const Thing&) = delete; + Thing& operator=(const Thing&) = delete; + + // Factory method to create shared instances + template + static std::shared_ptr createThing(Args&&... args) { + return std::make_shared(std::forward(args)...); + } + + virtual std::string getDescription(int32_t lookDistance) const = 0; + + virtual CylinderPtr getParent() { + return nullptr; + } + + virtual CylinderPtr getRealParent() { + return getParent(); + } + + virtual void setParent(std::weak_ptr cylinder) { + // Implementation in derived classes + } + + virtual void clearParent() { + + } + + virtual TilePtr getTile(); + virtual TileConstPtr getTile() const; + + virtual const Position& getPosition() const; + virtual int32_t getThrowRange() const = 0; + virtual bool isPushable() const = 0; + + virtual ContainerPtr getContainer() { + return nullptr; + } + + virtual ContainerConstPtr getContainer() const { + return nullptr; + } + + virtual ItemPtr getItem() { + return nullptr; + } + + virtual ItemConstPtr getItem() const { + return nullptr; + } + + virtual CreaturePtr getCreature() { + return nullptr; + } + + virtual CreatureConstPtr getCreature() const { + return nullptr; + } + + virtual bool isRemoved() const { + return true; + } + + protected: + constexpr Thing() = default; }; -#endif +#endif \ No newline at end of file diff --git a/src/tile.cpp b/src/tile.cpp index 92c592db..3f5ae4e3 100644 --- a/src/tile.cpp +++ b/src/tile.cpp @@ -22,7 +22,6 @@ extern MoveEvents* g_moveEvents; extern ConfigManager g_config; StaticTile real_nullptr_tile(0xFFFF, 0xFFFF, 0xFF); -Tile& Tile::nullptr_tile = real_nullptr_tile; bool Tile::hasProperty(ITEMPROPERTY prop) const { @@ -30,8 +29,8 @@ bool Tile::hasProperty(ITEMPROPERTY prop) const return true; } - if (const TileItemVector* items = getItemList()) { - for (const Item* item : *items) { + if (const auto items = getItemList()) { + for (const auto item : *items) { if (item->hasProperty(prop)) { return true; } @@ -40,7 +39,7 @@ bool Tile::hasProperty(ITEMPROPERTY prop) const return false; } -bool Tile::hasProperty(const Item* exclude, ITEMPROPERTY prop) const +bool Tile::hasProperty(const ItemPtr& exclude, ITEMPROPERTY prop) const { assert(exclude); @@ -48,8 +47,8 @@ bool Tile::hasProperty(const Item* exclude, ITEMPROPERTY prop) const return true; } - if (const TileItemVector* items = getItemList()) { - for (const Item* item : *items) { + if (const auto items = getItemList()) { + for (const auto item : *items) { if (item != exclude && item->hasProperty(prop)) { return true; } @@ -59,7 +58,7 @@ bool Tile::hasProperty(const Item* exclude, ITEMPROPERTY prop) const return false; } -bool Tile::hasHeight(uint32_t n) const +bool Tile::hasHeight(const uint32_t n) const { uint32_t height = 0; @@ -73,8 +72,8 @@ bool Tile::hasHeight(uint32_t n) const } } - if (const TileItemVector* items = getItemList()) { - for (const Item* item : *items) { + if (const auto items = getItemList()) { + for (const auto item : *items) { if (item->hasProperty(CONST_PROP_HASHEIGHT)) { ++height; } @@ -89,7 +88,7 @@ bool Tile::hasHeight(uint32_t n) const size_t Tile::getCreatureCount() const { - if (const CreatureVector* creatures = getCreatures()) { + if (const auto creatures = getCreatures()) { return creatures->size(); } return 0; @@ -97,7 +96,7 @@ size_t Tile::getCreatureCount() const size_t Tile::getItemCount() const { - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { return items->size(); } return 0; @@ -105,7 +104,7 @@ size_t Tile::getItemCount() const uint32_t Tile::getTopItemCount() const { - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { return items->getTopItemCount(); } return 0; @@ -113,7 +112,7 @@ uint32_t Tile::getTopItemCount() const uint32_t Tile::getDownItemCount() const { - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { return items->getDownItemCount(); } return 0; @@ -124,13 +123,13 @@ std::string Tile::getDescription(int32_t) const return "You dont know why, but you cant see anything!"; } -Teleport* Tile::getTeleportItem() const +TeleportPtr Tile::getTeleportItem() const { if (!hasFlag(TILESTATE_TELEPORT)) { return nullptr; } - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { if ((*it)->getTeleport()) { return (*it)->getTeleport(); @@ -140,7 +139,7 @@ Teleport* Tile::getTeleportItem() const return nullptr; } -MagicField* Tile::getFieldItem() const +MagicFieldPtr Tile::getFieldItem() const { if (!hasFlag(TILESTATE_MAGICFIELD)) { return nullptr; @@ -150,7 +149,7 @@ MagicField* Tile::getFieldItem() const return ground->getMagicField(); } - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { if ((*it)->getMagicField()) { return (*it)->getMagicField(); @@ -160,7 +159,7 @@ MagicField* Tile::getFieldItem() const return nullptr; } -TrashHolder* Tile::getTrashHolder() const +TrashHolderPtr Tile::getTrashHolder() const { if (!hasFlag(TILESTATE_TRASHHOLDER)) { return nullptr; @@ -170,7 +169,7 @@ TrashHolder* Tile::getTrashHolder() const return ground->getTrashHolder(); } - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { if ((*it)->getTrashHolder()) { return (*it)->getTrashHolder(); @@ -180,7 +179,7 @@ TrashHolder* Tile::getTrashHolder() const return nullptr; } -Mailbox* Tile::getMailbox() const +MailboxPtr Tile::getMailbox() const { if (!hasFlag(TILESTATE_MAILBOX)) { return nullptr; @@ -190,7 +189,7 @@ Mailbox* Tile::getMailbox() const return ground->getMailbox(); } - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { if ((*it)->getMailbox()) { return (*it)->getMailbox(); @@ -200,7 +199,7 @@ Mailbox* Tile::getMailbox() const return nullptr; } -BedItem* Tile::getBedItem() const +BedItemPtr Tile::getBedItem() const { if (!hasFlag(TILESTATE_BED)) { return nullptr; @@ -210,7 +209,7 @@ BedItem* Tile::getBedItem() const return ground->getBed(); } - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { if ((*it)->getBed()) { return (*it)->getBed(); @@ -220,9 +219,9 @@ BedItem* Tile::getBedItem() const return nullptr; } -Creature* Tile::getTopCreature() const +CreaturePtr Tile::getTopCreature() const { - if (const CreatureVector* creatures = getCreatures()) { + if (const auto creatures = getCreatures()) { if (!creatures->empty()) { return *creatures->begin(); } @@ -230,9 +229,9 @@ Creature* Tile::getTopCreature() const return nullptr; } -const Creature* Tile::getBottomCreature() const +CreatureConstPtr Tile::getBottomCreature() const { - if (const CreatureVector* creatures = getCreatures()) { + if (const auto creatures = getCreatures()) { if (!creatures->empty()) { return *creatures->rbegin(); } @@ -240,19 +239,19 @@ const Creature* Tile::getBottomCreature() const return nullptr; } -Creature* Tile::getTopVisibleCreature(const Creature* creature) const +CreaturePtr Tile::getTopVisibleCreature(const CreaturePtr creature) const { - if (const CreatureVector* creatures = getCreatures()) { + if (const auto creatures = getCreatures()) { if (creature) { - for (Creature* tileCreature : *creatures) { + for (const auto tileCreature : *creatures) { if (creature->canSeeCreature(tileCreature)) { return tileCreature; } } } else { - for (Creature* tileCreature : *creatures) { + for (const auto tileCreature : *creatures) { if (!tileCreature->isInvisible()) { - const Player* player = tileCreature->getPlayer(); + const auto player = tileCreature->getPlayer(); if (!player || !player->isInGhostMode()) { return tileCreature; } @@ -263,9 +262,9 @@ Creature* Tile::getTopVisibleCreature(const Creature* creature) const return nullptr; } -const Creature* Tile::getBottomVisibleCreature(const Creature* creature) const +CreatureConstPtr Tile::getBottomVisibleCreature(const CreatureConstPtr& creature) const { - if (const CreatureVector* creatures = getCreatures()) { + if (const auto creatures = getCreatures()) { if (creature) { for (auto it = creatures->rbegin(), end = creatures->rend(); it != end; ++it) { if (creature->canSeeCreature(*it)) { @@ -275,8 +274,7 @@ const Creature* Tile::getBottomVisibleCreature(const Creature* creature) const } else { for (auto it = creatures->rbegin(), end = creatures->rend(); it != end; ++it) { if (!(*it)->isInvisible()) { - const Player* player = (*it)->getPlayer(); - if (!player || !player->isInGhostMode()) { + if (const auto player = (*it)->getPlayer(); !player || !player->isInGhostMode()) { return *it; } } @@ -286,30 +284,30 @@ const Creature* Tile::getBottomVisibleCreature(const Creature* creature) const return nullptr; } -Item* Tile::getTopDownItem() const +ItemPtr Tile::getTopDownItem() const { - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { return items->getTopDownItem(); } return nullptr; } -Item* Tile::getTopTopItem() const +ItemPtr Tile::getTopTopItem() const { - if (const TileItemVector* items = getItemList()) { + if (const auto items = getItemList()) { return items->getTopTopItem(); } return nullptr; } -Item* Tile::getItemByTopOrder(int32_t topOrder) +ItemPtr Tile::getItemByTopOrder(int32_t topOrder) { //topOrder: //1: borders //2: ladders, signs, splashes //3: doors etc //4: creatures - if (TileItemVector* items = getItemList()) { + if (const auto 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) { return (*it); @@ -319,25 +317,21 @@ Item* Tile::getItemByTopOrder(int32_t topOrder) return nullptr; } -Thing* Tile::getTopVisibleThing(const Creature* creature) +ThingPtr Tile::getTopVisibleThing(const CreaturePtr creature) { - Thing* thing = getTopVisibleCreature(creature); - if (thing) { + if (const auto thing = getTopVisibleCreature(creature)) { return thing; } - TileItemVector* items = getItemList(); - if (items) { + if (const auto items = getItemList()) { for (ItemVector::const_iterator it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { - const ItemType& iit = Item::items[(*it)->getID()]; - if (!iit.lookThrough) { + if (const ItemType& iit = Item::items[(*it)->getID()]; !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()]; - if (!iit.lookThrough) { + if (const ItemType& iit = Item::items[(*it)->getID()]; !iit.lookThrough) { return (*it); } } @@ -346,11 +340,10 @@ Thing* Tile::getTopVisibleThing(const Creature* creature) return ground; } -void Tile::onAddTileItem(Item* item) +void Tile::onAddTileItem(ItemPtr& item) { if (item->hasProperty(CONST_PROP_MOVEABLE) || item->getContainer()) { - auto it = g_game.browseFields.find(this); - if (it != g_game.browseFields.end()) { + if (const auto it = g_game.browseFields.find(getTile()); it != g_game.browseFields.end()) { it->second->addItemBack(item); item->setParent(it->second); } @@ -364,41 +357,39 @@ void Tile::onAddTileItem(Item* item) g_game.map.getSpectators(spectators, cylinderMapPos, true); //send to client - for (Creature* spectator : spectators) { - if (Player* spectatorPlayer = spectator->getPlayer()) { - spectatorPlayer->sendAddTileItem(this, cylinderMapPos, item); + for (const auto spectator : spectators) { + if (const auto spectatorPlayer = spectator->getPlayer()) { + spectatorPlayer->sendAddTileItem(getTile(), cylinderMapPos, item); } } //event methods - for (Creature* spectator : spectators) { - spectator->onAddTileItem(this, cylinderMapPos); + for (const auto spectator : spectators) { + TilePtr tp = this->getTile(); + spectator->onAddTileItem(tp, cylinderMapPos); } if ((!hasFlag(TILESTATE_PROTECTIONZONE) || g_config.getBoolean(ConfigManager::CLEAN_PROTECTION_ZONES)) && item->isCleanable()) { if (!dynamic_cast(this)) { - g_game.addTileToClean(this); + g_game.addTileToClean(getTile()); } } } -void Tile::onUpdateTileItem(Item* oldItem, const ItemType& oldType, Item* newItem, const ItemType& newType) +void Tile::onUpdateTileItem(const ItemPtr& oldItem, const ItemType& oldType, const ItemPtr& newItem, const ItemType& newType) { if (newItem->hasProperty(CONST_PROP_MOVEABLE) || newItem->getContainer()) { - auto it = g_game.browseFields.find(this); - if (it != g_game.browseFields.end()) { - int32_t index = it->second->getThingIndex(oldItem); - if (index != -1) { + if (const auto it = g_game.browseFields.find(getTile()); it != g_game.browseFields.end()) { + if (int32_t index = it->second->getThingIndex(oldItem); index != -1) { it->second->replaceThing(index, newItem); newItem->setParent(it->second); } } } else if (oldItem->hasProperty(CONST_PROP_MOVEABLE) || oldItem->getContainer()) { - auto it = g_game.browseFields.find(this); + auto it = g_game.browseFields.find(getTile()); if (it != g_game.browseFields.end()) { - Cylinder* oldParent = oldItem->getParent(); it->second->removeThing(oldItem, oldItem->getItemCount()); - oldItem->setParent(oldParent); + oldItem->setParent(oldItem->getParent()); } } @@ -408,23 +399,22 @@ void Tile::onUpdateTileItem(Item* oldItem, const ItemType& oldType, Item* newIte g_game.map.getSpectators(spectators, cylinderMapPos, true); //send to client - for (Creature* spectator : spectators) { - if (Player* spectatorPlayer = spectator->getPlayer()) { - spectatorPlayer->sendUpdateTileItem(this, cylinderMapPos, newItem); + for (const auto spectator : spectators) { + if (const auto spectatorPlayer = spectator->getPlayer()) { + spectatorPlayer->sendUpdateTileItem(getTile(), cylinderMapPos, newItem); } } //event methods - for (Creature* spectator : spectators) { - spectator->onUpdateTileItem(this, cylinderMapPos, oldItem, oldType, newItem, newType); + for (const auto spectator : spectators) { + spectator->onUpdateTileItem(getTile(), cylinderMapPos, oldItem, oldType, newItem, newType); } } -void Tile::onRemoveTileItem(const SpectatorVec& spectators, const std::vector& oldStackPosVector, Item* item) +void Tile::onRemoveTileItem(const SpectatorVec& spectators, const std::vector& oldStackPosVector, const ItemPtr& item) { if (item->hasProperty(CONST_PROP_MOVEABLE) || item->getContainer()) { - auto it = g_game.browseFields.find(this); - if (it != g_game.browseFields.end()) { + if (const auto it = g_game.browseFields.find(getTile()); it != g_game.browseFields.end()) { it->second->removeThing(item, item->getItemCount()); } } @@ -436,26 +426,26 @@ void Tile::onRemoveTileItem(const SpectatorVec& spectators, const std::vectorgetPlayer()) { + for (const auto spectator : spectators) { + if (const auto tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendRemoveTileThing(cylinderMapPos, oldStackPosVector[i++]); } } //event methods - for (Creature* spectator : spectators) { - spectator->onRemoveTileItem(this, cylinderMapPos, iType, item); + for (const auto spectator : spectators) { + spectator->onRemoveTileItem(getTile(), cylinderMapPos, iType, item); } if (!hasFlag(TILESTATE_PROTECTIONZONE) || g_config.getBoolean(ConfigManager::CLEAN_PROTECTION_ZONES)) { - auto items = getItemList(); + const auto items = getItemList(); if (!items || items->empty()) { - g_game.removeTileToClean(this); + g_game.removeTileToClean(getTile()); return; } bool ret = false; - for (auto toCheck : *items) { + for (const auto toCheck : *items) { if (toCheck->isCleanable()) { ret = true; break; @@ -463,7 +453,7 @@ void Tile::onRemoveTileItem(const SpectatorVec& spectators, const std::vector(spectator) != nullptr); - static_cast(spectator)->sendUpdateTile(this, cylinderMapPos); + for (const auto spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->sendUpdateTile(getTile(), cylinderMapPos); } } -ReturnValue Tile::queryAdd(const Creature& creature, uint32_t flags) const +ReturnValue Tile::queryAdd(CreaturePtr creature, uint32_t flags) { ReturnValue results = RETURNVALUE_NOERROR; @@ -495,12 +485,12 @@ ReturnValue Tile::queryAdd(const Creature& creature, uint32_t flags) const return RETURNVALUE_NOTPOSSIBLE; } - const CreatureVector* creatures = getCreatures(); + const auto creatures = getCreatures(); if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, flags)) { - for (const Creature* tileCreature : *creatures) { + for (const auto tileCreature : *creatures) { if (!tileCreature->isInGhostMode() && (tileCreature->getPlayer() && !tileCreature->getPlayer()->isAccessPlayer() )) { - if (creature.getPlayer() && !creature.getPlayer()->isAccessPlayer() && !creature.getPlayer()->canWalkthrough(tileCreature)) { + if (creature->getPlayer() && !creature->getPlayer()->isAccessPlayer() && !creature->getPlayer()->canWalkthrough(tileCreature)) { return RETURNVALUE_NOTENOUGHROOM; } } @@ -515,47 +505,45 @@ ReturnValue Tile::queryAdd(const Creature& creature, uint32_t flags) const } else { //FLAG_IGNOREBLOCKITEM is set if (ground) { - const ItemType& iiType = Item::items[ground->getID()]; - if (iiType.blockSolid && (!iiType.moveable || ground->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID))) { + if (const ItemType& iiType = Item::items[ground->getID()]; iiType.blockSolid && (!iiType.moveable || ground->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID))) { return RETURNVALUE_NOTPOSSIBLE; } } if (const auto items = getItemList()) { - for (const Item* item : *items) { - const ItemType& iiType = Item::items[item->getID()]; - if (iiType.blockSolid && (!iiType.moveable || item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID))) { + for (const auto item : *items) { + if (const ItemType& iiType = Item::items[item->getID()]; iiType.blockSolid && (!iiType.moveable || item->hasAttribute(ITEM_ATTRIBUTE_UNIQUEID))) { return RETURNVALUE_NOTPOSSIBLE; } } } } - if (const Player* player = dynamic_cast(&creature)) { - results = queryAdd(*player, flags); - } else if (const Monster* monster = dynamic_cast(&creature)) { - results = queryAdd(*monster, flags); + if (auto player = std::dynamic_pointer_cast(creature)) { + results = queryAdd(player, flags); + } else if (auto monster = std::dynamic_pointer_cast(creature)) { + results = queryAdd(monster, flags); } return results; } -ReturnValue Tile::queryAdd(const Player& player, uint32_t flags) const { +ReturnValue Tile::queryAdd(PlayerPtr player, uint32_t flags) { - const CreatureVector* creatures = getCreatures(); + const auto creatures = getCreatures(); // If we aren't a GM/Admin can't walk on a tile that has a creature, if we don't have walkthrough enabled. - if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, flags) && !player.isAccessPlayer()) { - for (const Creature* tileCreature : *creatures) { - if (!player.canWalkthrough(tileCreature)) { + if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, flags) && !player->isAccessPlayer()) { + for (const auto tileCreature : *creatures) { + if (!player->canWalkthrough(tileCreature)) { return RETURNVALUE_NOTPOSSIBLE; } } } // We are auto-walking, lets not step on a field that would hurt us. - if (MagicField* field = getFieldItem()) { + if (const auto field = getFieldItem()) { if (field->getDamage() != 0 && hasBitSet(FLAG_PATHFINDING, flags) && !hasBitSet(FLAG_IGNOREFIELDDAMAGE, flags)) { return RETURNVALUE_NOTPOSSIBLE; @@ -563,13 +551,14 @@ ReturnValue Tile::queryAdd(const Player& player, uint32_t flags) const { } // Player is trying to login to a "no logout" tile. - if (player.getParent() == nullptr && hasFlag(TILESTATE_NOLOGOUT)) { + // note: might need to check for std::nullopt here as well actually. + if (player->getParent() == nullptr && hasFlag(TILESTATE_NOLOGOUT)) { return RETURNVALUE_NOTPOSSIBLE; } // Player is pz'd, let do some checks. - const Tile* playerTile = player.getTile(); - if (playerTile && player.isPzLocked()) { + const auto playerTile = player->getTile(); + if (playerTile && player->isPzLocked()) { if (!playerTile->hasFlag(TILESTATE_PVPZONE)) { //player is trying to enter a pvp zone while being pz-locked if (hasFlag(TILESTATE_PVPZONE)) { @@ -591,7 +580,7 @@ ReturnValue Tile::queryAdd(const Player& player, uint32_t flags) const { } -ReturnValue Tile::queryAdd(const Monster& monster, uint32_t flags) const { +ReturnValue Tile::queryAdd(MonsterPtr monster, uint32_t flags) { // Monsters // Monsters cannot enter pz, jump floors, or step into teleports if (hasFlag(TILESTATE_PROTECTIONZONE | TILESTATE_FLOORCHANGE | TILESTATE_TELEPORT)) { @@ -610,28 +599,28 @@ ReturnValue Tile::queryAdd(const Monster& monster, uint32_t flags) const { // Monster is looking for a clear path, some stuff is blocking it. if (hasFlag(TILESTATE_BLOCKSOLID) || (hasBitSet(FLAG_PATHFINDING, flags) && hasFlag(TILESTATE_NOFIELDBLOCKPATH))) { - if (!(monster.canPushItems() || hasBitSet(FLAG_IGNOREBLOCKITEM, flags))) { + if (!(monster->canPushItems() || hasBitSet(FLAG_IGNOREBLOCKITEM, flags))) { return RETURNVALUE_NOTPOSSIBLE; } } - const CreatureVector* creatures = getCreatures(); + const auto creatures = getCreatures(); // We have creatures on the tile we are trying to step on if (creatures && !creatures->empty()) { - for (const Creature* tileCreature : *creatures) { + for (const auto tileCreature : *creatures) { // creature is not in ghost mode if (!tileCreature->isInGhostMode()) { return RETURNVALUE_NOTENOUGHROOM; } - if (monster.canPushCreatures() && !monster.isSummon()) { + if (monster->canPushCreatures() && !monster->isSummon()) { // the creature is a player in ghost mode. if (tileCreature->getPlayer() && tileCreature->getPlayer()->isInGhostMode()) { continue; } // the creature is a monster this monster can't push. - const Monster* creatureMonster = tileCreature->getMonster(); + const auto creatureMonster = tileCreature->getMonster(); if (!creatureMonster || !tileCreature->isPushable() || (creatureMonster->isSummon() && creatureMonster->getMaster()->getPlayer())) { return RETURNVALUE_NOTPOSSIBLE; } @@ -640,7 +629,7 @@ ReturnValue Tile::queryAdd(const Monster& monster, uint32_t flags) const { } // If the magic field is safe, return early - MagicField* field = getFieldItem(); + const auto field = getFieldItem(); if (!field || field->isBlocking() || field->getDamage() == 0) { return RETURNVALUE_NOERROR; } @@ -649,11 +638,11 @@ ReturnValue Tile::queryAdd(const Monster& monster, uint32_t flags) const { //There is 3 options for a monster to enter a magic field //1) Monster is immune - if (!monster.isImmune(combatType)) { + 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 if (hasBitSet(FLAG_IGNOREFIELDDAMAGE, flags)) { - if (!(monster.canWalkOnFieldType(combatType) || monster.isIgnoringFieldDamage())) { + if (!(monster->canWalkOnFieldType(combatType) || monster->isIgnoringFieldDamage())) { return RETURNVALUE_NOTPOSSIBLE; } } else { @@ -664,9 +653,9 @@ ReturnValue Tile::queryAdd(const Monster& monster, uint32_t flags) const { return RETURNVALUE_NOERROR; } -ReturnValue Tile::queryAdd(const Item& item, uint32_t flags) const { +ReturnValue Tile::queryAdd(ItemPtr item, uint32_t flags) { // Tile's item stack is at its numeric limit can't add anything - const TileItemVector* items = getItemList(); + const auto items = getItemList(); if (items && items->size() >= 0xFFFF) { return RETURNVALUE_NOTPOSSIBLE; } @@ -677,20 +666,20 @@ ReturnValue Tile::queryAdd(const Item& item, uint32_t flags) const { } // Can't move store items to tiles - if (item.isStoreItem()) { + if (item->isStoreItem()) { return RETURNVALUE_ITEMCANNOTBEMOVEDTHERE; } // If its a wall, but not a hangable item. - bool itemIsHangable = item.isHangable(); + bool itemIsHangable = item->isHangable(); if (ground == nullptr && !itemIsHangable) { return RETURNVALUE_NOTPOSSIBLE; } // If there is any creature there, who is not in ghost mode... don't think this should be here... - const CreatureVector* creatures = getCreatures(); - if (creatures && !creatures->empty() && item.isBlocking() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, flags)) { - for (const Creature* tileCreature : *creatures) { + const auto creatures = getCreatures(); + if (creatures && !creatures->empty() && item->isBlocking() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, flags)) { + for (const auto tileCreature : *creatures) { if (!tileCreature->isInGhostMode()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -704,7 +693,7 @@ ReturnValue Tile::queryAdd(const Item& item, uint32_t flags) const { // If we have a hangable item and the tile supports hangables if (itemIsHangable && hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { if (items) { - for (const Item* tileItem : *items) { + for (const auto tileItem : *items) { // there is already a hangable there if (tileItem->isHangable()) { return RETURNVALUE_NEEDEXCHANGE; @@ -716,8 +705,8 @@ ReturnValue Tile::queryAdd(const Item& item, uint32_t flags) const { if (ground) { const ItemType& iiType = Item::items[ground->getID()]; if (iiType.blockSolid) { - if (!iiType.allowPickupable || item.isMagicField() || item.isBlocking()) { - if (!item.isPickupable()) { + if (!iiType.allowPickupable || item->isMagicField() || item->isBlocking()) { + if (!item->isPickupable()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -729,17 +718,17 @@ ReturnValue Tile::queryAdd(const Item& item, uint32_t flags) const { } // We can move this into the previous check and combine the loops. if (items) { - for (const Item* tileItem : *items) { + for (const auto tileItem : *items) { const ItemType& iiType = Item::items[tileItem->getID()]; if (!iiType.blockSolid) { continue; } - if (iiType.allowPickupable && !item.isMagicField() && !item.isBlocking()) { + if (iiType.allowPickupable && !item->isMagicField() && !item->isBlocking()) { continue; } - if (!item.isPickupable()) { + if (!item->isPickupable()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -752,13 +741,13 @@ ReturnValue Tile::queryAdd(const Item& item, uint32_t flags) const { return RETURNVALUE_NOERROR; } -ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t flags, Creature*) const { - if (const Creature* creature = dynamic_cast(&thing)) { - return queryAdd(*creature, flags); +ReturnValue Tile::queryAdd(int32_t, const ThingPtr& thing, uint32_t, uint32_t flags, CreaturePtr) { + if (auto creature = std::dynamic_pointer_cast(thing)) { + return queryAdd(creature, flags); } - if (const Item* item = dynamic_cast(&thing)) { - return queryAdd(*item, flags); + if (auto item = std::dynamic_pointer_cast(thing)) { + return queryAdd(item, flags); } std::cout << "|| WARNING || Tile::queryAdd() passed the object "<< typeid(thing).name() << ", that is not a creature or item! " << "\n"; @@ -766,20 +755,20 @@ ReturnValue Tile::queryAdd(int32_t, const Thing& thing, uint32_t, uint32_t flags return RETURNVALUE_NOERROR; } -ReturnValue Tile::queryMaxCount(int32_t, const Thing&, uint32_t count, uint32_t& maxQueryCount, uint32_t) const +ReturnValue Tile::queryMaxCount(int32_t, const ThingPtr&, const uint32_t count, uint32_t& maxQueryCount, uint32_t) { maxQueryCount = std::max(1, count); return RETURNVALUE_NOERROR; } -ReturnValue Tile::queryRemove(const Thing& thing, uint32_t count, uint32_t flags, Creature* /*= nullptr */) const +ReturnValue Tile::queryRemove(const ThingPtr& thing, const uint32_t count, uint32_t flags, CreaturePtr /*= nullptr */) { - int32_t index = getThingIndex(&thing); + int32_t index = getThingIndex(thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; } - const Item* item = thing.getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -795,129 +784,96 @@ ReturnValue Tile::queryRemove(const Thing& thing, uint32_t count, uint32_t flags return RETURNVALUE_NOERROR; } -Tile* Tile::queryDestination(int32_t&, const Thing&, Item** destItem, uint32_t& flags) -{ - Tile* destTile = nullptr; - *destItem = nullptr; +#include // For debug output +CylinderPtr Tile::queryDestination(int32_t& someInt, const ThingPtr& thingPtr, ItemPtr* destItem, uint32_t& flags) { + TilePtr destTile = nullptr; + *destItem = nullptr; + if (hasFlag(TILESTATE_FLOORCHANGE_DOWN)) { uint16_t dx = tilePos.x; uint16_t dy = tilePos.y; uint8_t dz = tilePos.z + 1; - - Tile* southDownTile = g_game.map.getTile(dx, dy - 1, dz); - if (southDownTile && southDownTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) { + + if (const auto southDownTile = g_game.map.getTile(dx, dy - 1, dz); southDownTile && southDownTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) { dy -= 2; destTile = g_game.map.getTile(dx, dy, dz); - } else { - Tile* eastDownTile = g_game.map.getTile(dx - 1, dy, dz); - if (eastDownTile && eastDownTile->hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) { - dx -= 2; - destTile = g_game.map.getTile(dx, dy, dz); - } else { - Tile* downTile = g_game.map.getTile(dx, dy, dz); - if (downTile) { - if (downTile->hasFlag(TILESTATE_FLOORCHANGE_NORTH)) { - ++dy; - } - - if (downTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH)) { - --dy; - } - - if (downTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) { - dy -= 2; - } - - if (downTile->hasFlag(TILESTATE_FLOORCHANGE_EAST)) { - --dx; - } - - if (downTile->hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) { - dx -= 2; - } + } + else if (const auto eastDownTile = g_game.map.getTile(dx - 1, dy, dz); eastDownTile && eastDownTile->hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) { + dx -= 2; + destTile = g_game.map.getTile(dx, dy, dz); + } + else { + if (const auto downTile = g_game.map.getTile(dx, dy, dz)) { - if (downTile->hasFlag(TILESTATE_FLOORCHANGE_WEST)) { - ++dx; - } + if (downTile->hasFlag(TILESTATE_FLOORCHANGE_NORTH)) ++dy; + if (downTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH)) --dy; + if (downTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) dy -= 2; + if (downTile->hasFlag(TILESTATE_FLOORCHANGE_EAST)) --dx; + if (downTile->hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) dx -= 2; + if (downTile->hasFlag(TILESTATE_FLOORCHANGE_WEST)) ++dx; - destTile = g_game.map.getTile(dx, dy, dz); - } + destTile = g_game.map.getTile(dx, dy, dz); } } - } else if (hasFlag(TILESTATE_FLOORCHANGE)) { + } + else if (hasFlag(TILESTATE_FLOORCHANGE)) { uint16_t dx = tilePos.x; uint16_t dy = tilePos.y; uint8_t dz = tilePos.z - 1; - - if (hasFlag(TILESTATE_FLOORCHANGE_NORTH)) { - --dy; - } - - if (hasFlag(TILESTATE_FLOORCHANGE_SOUTH)) { - ++dy; - } - - if (hasFlag(TILESTATE_FLOORCHANGE_EAST)) { - ++dx; - } - - if (hasFlag(TILESTATE_FLOORCHANGE_WEST)) { - --dx; - } - - if (hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) { - dy += 2; - } - - if (hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) { - dx += 2; - } + + if (hasFlag(TILESTATE_FLOORCHANGE_NORTH)) --dy; + if (hasFlag(TILESTATE_FLOORCHANGE_SOUTH)) ++dy; + if (hasFlag(TILESTATE_FLOORCHANGE_EAST)) ++dx; + if (hasFlag(TILESTATE_FLOORCHANGE_WEST)) --dx; + if (hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) dy += 2; + if (hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) dx += 2; destTile = g_game.map.getTile(dx, dy, dz); } if (destTile == nullptr) { - destTile = this; + TilePtr temp = this->getTile(); + if (!temp) { + std::cerr << "Fallback also returned nullptr!" << std::endl; + } + destTile = temp; } else { - flags |= FLAG_NOLIMIT; //Will ignore that there is blocking items/creatures + flags |= FLAG_NOLIMIT; } if (destTile) { - Thing* destThing = destTile->getTopDownItem(); - if (destThing) { + if (const auto& destThing = destTile->getTopDownItem()) { *destItem = destThing->getItem(); } } + return destTile; } -void Tile::addThing(Thing* thing) +void Tile::addThing(ThingPtr thing) { addThing(0, thing); } -void Tile::addThing(int32_t, Thing* thing) +void Tile::addThing(int32_t, ThingPtr thing) { - Creature* creature = thing->getCreature(); - if (creature) { + if (const auto& creature = thing->getCreature()) { g_game.map.clearChunkSpectatorCache(); - - creature->setParent(this); - CreatureVector* creatures = makeCreatures(); + creature->setParent(getTile()); + const auto& creatures = getCreatures(); creatures->insert(creatures->begin(), creature); } else { - Item* item = thing->getItem(); + auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - TileItemVector* items = getItemList(); + TileItemsPtr items = getItemList(); if (items && items->size() >= 0xFFFF) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - - item->setParent(this); + item->setParent(getTile()); const ItemType& itemType = Item::items[item->getID()]; if (itemType.isGroundTile()) { @@ -927,9 +883,9 @@ void Tile::addThing(int32_t, Thing* thing) } else { const ItemType& oldType = Item::items[ground->getID()]; - Item* oldGround = ground; - ground->setParent(nullptr); - g_game.ReleaseItem(ground); + const auto oldGround = ground; + ground->clearParent(); + // g_game.ReleaseItem(ground); ground = item; resetTileFlags(oldGround); setTileFlags(item); @@ -940,14 +896,14 @@ void Tile::addThing(int32_t, Thing* thing) if (itemType.isSplash() && items) { //remove old splash if exists for (ItemVector::const_iterator it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - Item* oldSplash = *it; + const auto oldSplash = *it; if (!Item::items[oldSplash->getID()].isSplash()) { continue; } removeThing(oldSplash, 1); - oldSplash->setParent(nullptr); - g_game.ReleaseItem(oldSplash); + oldSplash->clearParent(); + // g_game.ReleaseItem(oldSplash); postRemoveNotification(oldSplash, nullptr, 0); break; } @@ -965,7 +921,7 @@ void Tile::addThing(int32_t, Thing* thing) } } } else { - items = makeItemList(); + std::cout << "Hitting where should be unreachable in tile addthing!" << std::endl; } if (!isInserted) { @@ -978,19 +934,18 @@ void Tile::addThing(int32_t, Thing* thing) //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(); - if (oldField) { + if (const auto oldField = (*it)->getMagicField()) { if (oldField->isReplaceable()) { removeThing(oldField, 1); - oldField->setParent(nullptr); - g_game.ReleaseItem(oldField); + oldField->clearParent(); + // g_game.ReleaseItem(oldField); postRemoveNotification(oldField, nullptr, 0); break; } else { //This magic field cannot be replaced. - item->setParent(nullptr); - g_game.ReleaseItem(item); + item->clearParent(); + // g_game.ReleaseItem(item); return; } } @@ -998,7 +953,10 @@ void Tile::addThing(int32_t, Thing* thing) } } - items = makeItemList(); + if (!items) { + std::cout << "Getting to end of tile add thing and still not items list!" << std::endl; + } + items->insert(items->getBeginDownItem(), item); items->addDownItemCount(1); onAddTileItem(item); @@ -1006,14 +964,14 @@ void Tile::addThing(int32_t, Thing* thing) } } -void Tile::updateThing(Thing* thing, uint16_t itemId, uint32_t count) +void Tile::updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1027,16 +985,16 @@ 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, ThingPtr thing) { int32_t pos = index; - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - Item* oldItem = nullptr; + ItemPtr oldItem = nullptr; bool isInserted = false; if (ground) { @@ -1049,7 +1007,7 @@ void Tile::replaceThing(uint32_t index, Thing* thing) --pos; } - TileItemVector* items = getItemList(); + const auto items = getItemList(); if (items && !isInserted) { int32_t topItemSize = getTopItemCount(); if (pos < topItemSize) { @@ -1065,8 +1023,7 @@ void Tile::replaceThing(uint32_t index, Thing* thing) pos -= topItemSize; } - CreatureVector* creatures = getCreatures(); - if (creatures) { + if (const auto creatures = getCreatures()) { if (!isInserted && pos < static_cast(creatures->size())) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1086,7 +1043,7 @@ void Tile::replaceThing(uint32_t index, Thing* thing) } if (isInserted) { - item->setParent(this); + item->setParent(getTile()); resetTileFlags(oldItem); setTileFlags(item); @@ -1094,19 +1051,16 @@ void Tile::replaceThing(uint32_t index, Thing* thing) const ItemType& newType = Item::items[item->getID()]; onUpdateTileItem(oldItem, oldType, item, newType); - oldItem->setParent(nullptr); + oldItem->clearParent(); return /*RETURNVALUE_NOERROR*/; } } -void Tile::removeThing(Thing* thing, uint32_t count) +void Tile::removeThing(ThingPtr thing, uint32_t count) { - Creature* creature = thing->getCreature(); - if (creature) { - CreatureVector* creatures = getCreatures(); - if (creatures) { - auto it = std::find(creatures->begin(), creatures->end(), thing); - if (it != creatures->end()) { + if (const auto creature = thing->getCreature()) { + if (const auto creatures = getCreatures()) { + if (const auto it = std::ranges::find(*creatures, thing); it != creatures->end()) { g_game.map.clearChunkSpectatorCache(); creatures->erase(it); @@ -1115,18 +1069,18 @@ void Tile::removeThing(Thing* thing, uint32_t count) return; } - Item* item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return; } - int32_t index = getThingIndex(item); + const int32_t index = getThingIndex(item); if (index == -1) { return; } if (item == ground) { - ground->setParent(nullptr); + ground->clearParent(); ground = nullptr; SpectatorVec spectators; @@ -1135,14 +1089,14 @@ void Tile::removeThing(Thing* thing, uint32_t count) return; } - TileItemVector* items = getItemList(); + const auto items = getItemList(); if (!items) { return; } const ItemType& itemType = Item::items[item->getID()]; if (itemType.alwaysOnTop) { - auto it = std::find(items->getBeginTopItem(), items->getEndTopItem(), item); + const auto it = std::find(items->getBeginTopItem(), items->getEndTopItem(), item); if (it == items->getEndTopItem()) { return; } @@ -1151,23 +1105,23 @@ void Tile::removeThing(Thing* thing, uint32_t count) SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), true); - for (Creature* spectator : spectators) { - if (Player* spectatorPlayer = spectator->getPlayer()) { + for (const auto& spectator : spectators) { + if (const auto& spectatorPlayer = spectator->getPlayer()) { oldStackPosVector.push_back(getStackposOfItem(spectatorPlayer, item)); } } - item->setParent(nullptr); + item->clearParent(); items->erase(it); onRemoveTileItem(spectators, oldStackPosVector, item); } else { - auto it = std::find(items->getBeginDownItem(), items->getEndDownItem(), item); + const auto it = std::find(items->getBeginDownItem(), items->getEndDownItem(), item); if (it == items->getEndDownItem()) { return; } if (itemType.stackable && count != item->getItemCount()) { - uint8_t newCount = static_cast(std::max(0, static_cast(item->getItemCount() - count))); + const uint8_t newCount = static_cast(std::max(0, static_cast(item->getItemCount() - count))); item->setItemCount(newCount); onUpdateTileItem(item, itemType, item, itemType); } else { @@ -1175,13 +1129,13 @@ void Tile::removeThing(Thing* thing, uint32_t count) SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), true); - for (Creature* spectator : spectators) { - if (Player* spectatorPlayer = spectator->getPlayer()) { + for (const auto& spectator : spectators) { + if (const auto& spectatorPlayer = spectator->getPlayer()) { oldStackPosVector.push_back(getStackposOfItem(spectatorPlayer, item)); } } - item->setParent(nullptr); + item->clearParent(); items->erase(it); items->addDownItemCount(-1); onRemoveTileItem(spectators, oldStackPosVector, item); @@ -1189,21 +1143,21 @@ void Tile::removeThing(Thing* thing, uint32_t count) } } -bool Tile::hasCreature(Creature* creature) const +bool Tile::hasCreature(CreaturePtr& creature) { - if (const CreatureVector* creatures = getCreatures()) { - return std::find(creatures->begin(), creatures->end(), creature) != creatures->end(); + if (const auto& creatures = getCreatures()) { + return std::ranges::find(*creatures, creature) != creatures->end(); } return false; } -void Tile::removeCreature(Creature* creature) +void Tile::removeCreature(CreaturePtr& 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(ThingPtr thing) { int32_t n = -1; if (ground) { @@ -1213,10 +1167,9 @@ int32_t Tile::getThingIndex(const Thing* thing) const ++n; } - const TileItemVector* items = getItemList(); + const auto items = getItemList(); if (items) { - const Item* item = thing->getItem(); - if (item && item->isAlwaysOnTop()) { + if (const auto& item = thing->getItem(); item && item->isAlwaysOnTop()) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { ++n; if (*it == item) { @@ -1228,9 +1181,9 @@ int32_t Tile::getThingIndex(const Thing* thing) const } } - if (const CreatureVector* creatures = getCreatures()) { + if (const auto& creatures = getCreatures()) { if (thing->getCreature()) { - for (Creature* creature : *creatures) { + for (const auto& creature : *creatures) { ++n; if (creature == thing) { return n; @@ -1242,7 +1195,7 @@ int32_t Tile::getThingIndex(const Thing* thing) const } if (items) { - const Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (item && !item->isAlwaysOnTop()) { for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { ++n; @@ -1255,7 +1208,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 PlayerConstPtr& player, const CreatureConstPtr& creature) const { int32_t n; if (ground) { @@ -1264,13 +1217,12 @@ int32_t Tile::getClientIndexOfCreature(const Player* player, const Creature* cre n = 0; } - const TileItemVector* items = getItemList(); - if (items) { + if (const auto& items = getItemList()) { n += items->getTopItemCount(); } - if (const CreatureVector* creatures = getCreatures()) { - for (const Creature* c : boost::adaptors::reverse(*creatures)) { + if (const auto& creatures = getCreatures()) { + for (const auto& c : boost::adaptors::reverse(*creatures)) { if (c == creature) { return n; } else if (player->canSeeCreature(c)) { @@ -1281,7 +1233,7 @@ int32_t Tile::getClientIndexOfCreature(const Player* player, const Creature* cre return -1; } -int32_t Tile::getStackposOfItem(const Player* player, const Item* item) const +int32_t Tile::getStackposOfItem(const PlayerConstPtr& player, const ItemConstPtr& item) const { int32_t n = 0; if (ground) { @@ -1291,7 +1243,7 @@ int32_t Tile::getStackposOfItem(const Player* player, const Item* item) const ++n; } - const TileItemVector* items = getItemList(); + const auto& items = getItemList(); if (items) { if (item->isAlwaysOnTop()) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { @@ -1309,8 +1261,8 @@ int32_t Tile::getStackposOfItem(const Player* player, const Item* item) const } } - if (const CreatureVector* creatures = getCreatures()) { - for (const Creature* creature : *creatures) { + if (const auto& creatures = getCreatures()) { + for (const auto& creature : *creatures) { if (player->canSeeCreature(creature)) { if (++n >= 10) { return -1; @@ -1341,16 +1293,15 @@ size_t Tile::getLastIndex() const return getThingCount(); } -uint32_t Tile::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const +uint32_t Tile::getItemTypeCount(const uint16_t itemId, int32_t subType /*= -1*/) const { uint32_t count = 0; if (ground && ground->getID() == itemId) { count += Item::countByType(ground, subType); } - const TileItemVector* items = getItemList(); - if (items) { - for (const Item* item : *items) { + if (const auto& items = getItemList()) { + for (const auto& item : *items) { if (item->getID() == itemId) { count += Item::countByType(item, subType); } @@ -1359,7 +1310,7 @@ uint32_t Tile::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const return count; } -Thing* Tile::getThing(size_t index) const +ThingPtr Tile::getThing(size_t index) { if (ground) { if (index == 0) { @@ -1369,16 +1320,16 @@ Thing* Tile::getThing(size_t index) const --index; } - const TileItemVector* items = getItemList(); + const auto& items = getItemList(); if (items) { - uint32_t topItemSize = items->getTopItemCount(); + const uint32_t topItemSize = items->getTopItemCount(); if (index < topItemSize) { return items->at(items->getDownItemCount() + index); } index -= topItemSize; } - if (const CreatureVector* creatures = getCreatures()) { + if (const auto& creatures = getCreatures()) { if (index < creatures->size()) { return (*creatures)[index]; } @@ -1391,105 +1342,83 @@ 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link /*= LINK_OWNER*/) { SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), true, true); - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->postAddNotification(thing, oldParent, index, LINK_NEAR); + for (const auto& spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->postAddNotification(thing, oldParent, index, LINK_NEAR); } //add a reference to this item, it may be deleted after being added (mailbox for example) - Creature* creature = thing->getCreature(); - Item* item; - if (creature) { - creature->incrementReferenceCounter(); - item = nullptr; - } else { - item = thing->getItem(); - if (item) { - item->incrementReferenceCounter(); - } - } + auto creature = thing->getCreature(); + ItemPtr item = creature ? nullptr : thing->getItem(); if (link == LINK_OWNER) { if (hasFlag(TILESTATE_TELEPORT)) { - Teleport* teleport = getTeleportItem(); - if (teleport) { + if (const auto& teleport = getTeleportItem()) { teleport->addThing(thing); } } else if (hasFlag(TILESTATE_TRASHHOLDER)) { - TrashHolder* trashholder = getTrashHolder(); - if (trashholder) { + if (const auto& trashholder = getTrashHolder()) { trashholder->addThing(thing); } } else if (hasFlag(TILESTATE_MAILBOX)) { - Mailbox* mailbox = getMailbox(); - if (mailbox) { + if (const auto mailbox = getMailbox()) { mailbox->addThing(thing); } } //calling movement scripts if (creature) { - g_moveEvents->onCreatureMove(creature, this, MOVE_EVENT_STEP_IN); + g_moveEvents->onCreatureMove(creature, getTile(), MOVE_EVENT_STEP_IN); } else if (item) { - g_moveEvents->onItemMove(item, this, true); + TilePtr tile = item->getTile(); + g_moveEvents->onItemMove(item, tile, true); } } - - //release the reference to this item onces we are finished - if (creature) { - g_game.ReleaseCreature(creature); - } else if (item) { - g_game.ReleaseItem(item); - } } -void Tile::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void Tile::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { SpectatorVec spectators; g_game.map.getSpectators(spectators, getPosition(), true, true); - if (getThingCount() > 8) { onUpdateTile(spectators); } - for (Creature* spectator : spectators) { - assert(dynamic_cast(spectator) != nullptr); - static_cast(spectator)->postRemoveNotification(thing, newParent, index, LINK_NEAR); + for (const auto& spectator : spectators) { + assert(std::dynamic_pointer_cast(spectator) != nullptr); + std::static_pointer_cast(spectator)->postRemoveNotification(thing, newParent, index, LINK_NEAR); } //calling movement scripts - Creature* creature = thing->getCreature(); - if (creature) { - g_moveEvents->onCreatureMove(creature, this, MOVE_EVENT_STEP_OUT); + if (const auto& creature = thing->getCreature()) { + g_moveEvents->onCreatureMove(creature, getTile(), MOVE_EVENT_STEP_OUT); } else { - Item* item = thing->getItem(); - if (item) { - g_moveEvents->onItemMove(item, this, false); + if (const auto& item = thing->getItem()) { + g_moveEvents->onItemMove(item, getTile(), false); } } } -void Tile::internalAddThing(Thing* thing) +void Tile::internalAddThing(ThingPtr thing) { internalAddThing(0, thing); } -void Tile::internalAddThing(uint32_t, Thing* thing) +void Tile::internalAddThing(uint32_t, ThingPtr thing) { - thing->setParent(this); + thing->setParent(getTile()); - Creature* creature = thing->getCreature(); - if (creature) { + if (const auto& creature = thing->getCreature()) { g_game.map.clearChunkSpectatorCache(); - CreatureVector* creatures = makeCreatures(); + const auto& creatures = getCreatures(); creatures->insert(creatures->begin(), creature); } else { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (item == nullptr) { return; } @@ -1503,7 +1432,7 @@ void Tile::internalAddThing(uint32_t, Thing* thing) return; } - TileItemVector* items = makeItemList(); + auto items = getItemList(); if (items->size() >= 0xFFFF) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1530,11 +1459,10 @@ void Tile::internalAddThing(uint32_t, Thing* thing) } } -void Tile::setTileFlags(const Item* item) +void Tile::setTileFlags(const ItemConstPtr& item) { if (!hasFlag(TILESTATE_FLOORCHANGE)) { - const ItemType& it = Item::items[item->getID()]; - if (it.floorChange != 0) { + if (const ItemType& it = Item::items[item->getID()]; it.floorChange != 0) { setFlag(it.floorChange); } } @@ -1579,7 +1507,7 @@ void Tile::setTileFlags(const Item* item) setFlag(TILESTATE_BED); } - const Container* container = item->getContainer(); + const auto& container = item->getContainer(); if (container && container->getDepotLocker()) { setFlag(TILESTATE_DEPOT); } @@ -1589,10 +1517,9 @@ void Tile::setTileFlags(const Item* item) } } -void Tile::resetTileFlags(const Item* item) +void Tile::resetTileFlags(const ItemPtr& item) { - const ItemType& it = Item::items[item->getID()]; - if (it.floorChange != 0) { + if (const ItemType& it = Item::items[item->getID()]; it.floorChange != 0) { resetFlag(TILESTATE_FLOORCHANGE); } @@ -1640,8 +1567,7 @@ void Tile::resetTileFlags(const Item* item) resetFlag(TILESTATE_BED); } - const Container* container = item->getContainer(); - if (container && container->getDepotLocker()) { + if (const auto& container = item->getContainer(); container && container->getDepotLocker()) { resetFlag(TILESTATE_DEPOT); } @@ -1655,32 +1581,30 @@ bool Tile::isMoveableBlocking() const return !ground || hasFlag(TILESTATE_BLOCKSOLID); } -Item* Tile::getUseItem(int32_t index) const +ItemPtr Tile::getUseItem(const int32_t index) { // no items, get ground - const TileItemVector* items = getItemList(); + const auto& items = getItemList(); if (!items || items->size() == 0) { return ground; } // try getting thing by index - if (Thing* thing = getThing(index)) { - Item* thingItem = thing->getItem(); - if (thingItem) { + if (auto thing = getThing(index)) { + if (const auto& thingItem = thing->getItem()) { return thingItem; } } // try getting top usable item - Item* topDownItem = getTopDownItem(); - if (topDownItem) { + if (const auto& topDownItem = getTopDownItem()) { return topDownItem; } // try getting door for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { if ((*it)->getDoor()) { - return (*it)->getDoor(); + return *it; } } diff --git a/src/tile.h b/src/tile.h index cdef1a43..a7a42611 100644 --- a/src/tile.h +++ b/src/tile.h @@ -16,9 +16,54 @@ class Mailbox; class MagicField; class QTreeLeafNode; class BedItem; +class TileItemVector; -using CreatureVector = std::vector; -using ItemVector = std::vector; +class Creature; +using CreaturePtr = std::shared_ptr; +using CreatureConstPtr = std::shared_ptr; +class Player; +using PlayerPtr = std::shared_ptr; +using PlayerConstPtr = std::shared_ptr; +class Monster; +using MonsterPtr = std::shared_ptr; +using MonsterConstPtr = std::shared_ptr; +class Npc; +using NpcPtr = std::shared_ptr; +using NpcConstPtr = std::shared_ptr; + +using CreatureVector = std::vector; +using ItemVector = std::vector; + +using TileItemsPtr = std::shared_ptr; +using TileItemsConstPtr = std::shared_ptr; +using TileCreaturesPtr = std::shared_ptr; +using TileCreaturesConstPtr = std::shared_ptr; + +class Depot; +using DepotPtr = std::shared_ptr; +using DepotConstPtr = std::shared_ptr; +class Teleport; +using TeleportPtr = std::shared_ptr; +using TeleportConstPtr = std::shared_ptr; +class TrashHolder; +using TrashHolderPtr = std::shared_ptr; +using TrashHolderConstPtr = std::shared_ptr; + +using MailboxPtr = std::shared_ptr; +using MailboxConstPtr = std::shared_ptr; +class Door; +using DoorPtr = std::shared_ptr; +using DoorConstPtr = std::shared_ptr; + +using MagicFieldPtr = std::shared_ptr; +using MagicFieldConstPtr = std::shared_ptr; + +using BedItemPtr = std::shared_ptr; +using BedItemConstPtr = std::shared_ptr; + +class HouseTile; +using HouseTilePtr = std::shared_ptr; +using HouseTileConstPtr = std::shared_ptr; enum tileflags_t : uint32_t { TILESTATE_NONE = 0, @@ -59,7 +104,7 @@ enum ZoneType_t { ZONE_NORMAL, }; -class TileItemVector : private ItemVector +class TileItemVector : public ItemVector { public: using ItemVector::begin; @@ -82,24 +127,31 @@ class TileItemVector : private ItemVector iterator getBeginDownItem() { return begin(); } + const_iterator getBeginDownItem() const { return begin(); } + iterator getEndDownItem() { return begin() + downItemCount; } + const_iterator getEndDownItem() const { return begin() + downItemCount; } + iterator getBeginTopItem() { return getEndDownItem(); } + const_iterator getBeginTopItem() const { return getEndDownItem(); } + iterator getEndTopItem() { return end(); } + const_iterator getEndTopItem() const { return end(); } @@ -107,21 +159,25 @@ class TileItemVector : private ItemVector uint32_t getTopItemCount() const { return size() - downItemCount; } + uint32_t getDownItemCount() const { return downItemCount; } - inline Item* getTopTopItem() const { + + ItemPtr getTopTopItem() const { if (getTopItemCount() == 0) { return nullptr; } return *(getEndTopItem() - 1); } - inline Item* getTopDownItem() const { + + ItemPtr getTopDownItem() const { if (downItemCount == 0) { return nullptr; } return *getBeginDownItem(); } + void addDownItemCount(int32_t increment) { downItemCount += increment; } @@ -130,49 +186,48 @@ class TileItemVector : private ItemVector uint16_t downItemCount = 0; }; -class Tile : public Cylinder + +class Tile : public Cylinder, public SharedObject { public: - static Tile& nullptr_tile; Tile(uint16_t x, uint16_t y, uint8_t z) : tilePos(x, y, z) {} virtual ~Tile() { - delete ground; + ground.reset(); }; // non-copyable Tile(const Tile&) = delete; Tile& operator=(const Tile&) = delete; - virtual TileItemVector* getItemList() = 0; - virtual const TileItemVector* getItemList() const = 0; - virtual TileItemVector* makeItemList() = 0; + virtual TileItemsPtr getItemList() = 0; + virtual TileItemsConstPtr getItemList() const = 0; - virtual CreatureVector* getCreatures() = 0; - virtual const CreatureVector* getCreatures() const = 0; - virtual CreatureVector* makeCreatures() = 0; + virtual TileCreaturesPtr getCreatures() = 0; + virtual TileCreaturesConstPtr getCreatures() const = 0; int32_t getThrowRange() const override final { return 0; } + bool isPushable() const override final { return false; } - MagicField* getFieldItem() const; - Teleport* getTeleportItem() const; - TrashHolder* getTrashHolder() const; - Mailbox* getMailbox() const; - BedItem* getBedItem() const; + MagicFieldPtr getFieldItem() const; + TeleportPtr getTeleportItem() const; + TrashHolderPtr getTrashHolder() const; + MailboxPtr getMailbox() const; + BedItemPtr getBedItem() const; - Creature* getTopCreature() const; - const Creature* getBottomCreature() const; - Creature* getTopVisibleCreature(const Creature* creature) const; - const Creature* getBottomVisibleCreature(const Creature* creature) const; - Item* getTopTopItem() const; - Item* getTopDownItem() const; + CreaturePtr getTopCreature() const; + CreatureConstPtr getBottomCreature() const; + CreaturePtr getTopVisibleCreature(const CreaturePtr creature) const; + CreatureConstPtr getBottomVisibleCreature(const CreatureConstPtr& creature) const; + ItemPtr getTopTopItem() const; + ItemPtr getTopDownItem() const; bool isMoveableBlocking() const; - Thing* getTopVisibleThing(const Creature* creature); - Item* getItemByTopOrder(int32_t topOrder); + ThingPtr getTopVisibleThing(const CreaturePtr creature); + ItemPtr getItemByTopOrder(int32_t topOrder); size_t getThingCount() const { size_t thingCount = getCreatureCount() + getItemCount(); @@ -181,6 +236,7 @@ class Tile : public Cylinder } return thingCount; } + // If these return != 0 the associated vectors are guaranteed to exists size_t getCreatureCount() const; size_t getItemCount() const; @@ -188,14 +244,16 @@ class Tile : public Cylinder uint32_t getDownItemCount() const; bool hasProperty(ITEMPROPERTY prop) const; - bool hasProperty(const Item* exclude, ITEMPROPERTY prop) const; + bool hasProperty(const ItemPtr& exclude, ITEMPROPERTY prop) const; bool hasFlag(uint32_t flag) const { - return hasBitSet(flag, this->flags); + return hasBitSet(flag, flags); } + void setFlag(uint32_t flag) { this->flags |= flag; } + void resetFlag(uint32_t flag) { this->flags &= ~flag; } @@ -218,43 +276,43 @@ class Tile : public Cylinder std::string getDescription(int32_t lookDistance) const override final; - int32_t getClientIndexOfCreature(const Player* player, const Creature* creature) const; - int32_t getStackposOfItem(const Player* player, const Item* item) const; + int32_t getClientIndexOfCreature(const PlayerConstPtr& player, const CreatureConstPtr& creature) const; + int32_t getStackposOfItem(const PlayerConstPtr& player, const ItemConstPtr& 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 flags, Creature* actor = nullptr) const override; - Tile* queryDestination(int32_t& index, const Thing& thing, Item** destItem, uint32_t& flags) override; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t flags, CreaturePtr actor = nullptr) override; + ReturnValue queryMaxCount(int32_t index, const ThingPtr& thing, uint32_t count, + uint32_t& maxQueryCount, uint32_t flags) override final; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, uint32_t& flags) override; // another optional wrap ref - ReturnValue queryAdd(const Creature& creature, uint32_t flags) const; - ReturnValue queryAdd(const Item& item, uint32_t flags) const; - ReturnValue queryAdd(const Player& player, uint32_t flags) const; - ReturnValue queryAdd(const Monster& monster, uint32_t flags) const; + ReturnValue queryAdd(CreaturePtr creature, uint32_t flags); + ReturnValue queryAdd(ItemPtr item, uint32_t flags); + ReturnValue queryAdd(PlayerPtr player, uint32_t flags); + ReturnValue queryAdd(MonsterPtr monster, uint32_t flags); - void addThing(Thing* thing) override final; - void addThing(int32_t index, Thing* thing) override; + void addThing(ThingPtr thing) override final; + void addThing(int32_t index, ThingPtr thing) override; - void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override final; - void replaceThing(uint32_t index, Thing* thing) override final; + void updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) override final; + void replaceThing(uint32_t index, ThingPtr thing) override final; - void removeThing(Thing* thing, uint32_t count) override final; - bool hasCreature(Creature* creature) const; - void removeCreature(Creature* creature); + void removeThing(ThingPtr thing, uint32_t count) override final; + bool hasCreature(CreaturePtr& creature); + void removeCreature(CreaturePtr& creature); - int32_t getThingIndex(const Thing* thing) const override final; + int32_t getThingIndex(ThingPtr thing) override final; 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; - Thing* getThing(size_t index) const override final; + ThingPtr getThing(size_t index) override final; - void postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override final; - void postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override final; + void postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; - void internalAddThing(Thing* thing) override final; - void internalAddThing(uint32_t index, Thing* thing) override; + void internalAddThing(ThingPtr thing) override final; + void internalAddThing(uint32_t index, ThingPtr thing) override; const Position& getPosition() const override final { return tilePos; @@ -264,25 +322,30 @@ class Tile : public Cylinder return false; } - Item* getUseItem(int32_t index) const; + ItemPtr getUseItem(int32_t index); - Item* getGround() const { + ItemPtr getGround() const { return ground; } - void setGround(Item* item) { + + std::shared_ptr getTile() final { + return static_shared_this(); + } + + void setGround(const ItemPtr& item) { ground = item; } private: - void onAddTileItem(Item* item); - void onUpdateTileItem(Item* oldItem, const ItemType& oldType, Item* newItem, const ItemType& newType); - void onRemoveTileItem(const SpectatorVec& spectators, const std::vector& oldStackPosVector, Item* item); + void onAddTileItem(ItemPtr& item); + void onUpdateTileItem(const ItemPtr& oldItem, const ItemType& oldType, const ItemPtr& newItem, const ItemType& newType); + void onRemoveTileItem(const SpectatorVec& spectators, const std::vector& oldStackPosVector, const ItemPtr& item); void onUpdateTile(const SpectatorVec& spectators); - void setTileFlags(const Item* item); - void resetTileFlags(const Item* item); + void setTileFlags(const ItemConstPtr& item); + void resetTileFlags(const ItemPtr& item); - Item* ground = nullptr; + ItemPtr ground = nullptr; Position tilePos; uint32_t flags = 0; }; @@ -291,56 +354,61 @@ class Tile : public Cylinder // items being added/removed class DynamicTile : public Tile { - // By allocating the vectors in-house, we avoid some memory fragmentation - TileItemVector items; - CreatureVector creatures; + TileItemsPtr items; + TileCreaturesPtr creatures; - public: - DynamicTile(uint16_t x, uint16_t y, uint8_t z) : Tile(x, y, z) {} - ~DynamicTile() { - for (Item* item : items) { - item->decrementReferenceCounter(); - } +public: + DynamicTile(uint16_t x, uint16_t y, uint8_t z) : Tile(x, y, z) + { + items = std::make_shared(); + creatures = std::make_shared(); + } + + ~DynamicTile() { + for (auto& item : *items) { + item.reset(); } + } - // non-copyable - DynamicTile(const DynamicTile&) = delete; - DynamicTile& operator=(const DynamicTile&) = delete; + // non-copyable + DynamicTile(const DynamicTile&) = delete; + DynamicTile& operator=(const DynamicTile&) = delete; - TileItemVector* getItemList() override { - return &items; - } - const TileItemVector* getItemList() const override { - return &items; - } - TileItemVector* makeItemList() override { - return &items; - } + TileItemsPtr getItemList() override { + return items; + } - CreatureVector* getCreatures() override { - return &creatures; - } - const CreatureVector* getCreatures() const override { - return &creatures; - } - CreatureVector* makeCreatures() override { - return &creatures; - } + TileItemsConstPtr getItemList() const override { + return items; + } + + TileCreaturesPtr getCreatures() override { + return creatures; + } + + + TileCreaturesConstPtr getCreatures() const override { + return creatures; + } }; // 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; + TileItemsPtr items; + TileCreaturesPtr 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) + { + items = std::make_shared(); + creatures = std::make_shared(); + } + ~StaticTile() { if (items) { - for (Item* item : *items) { - item->decrementReferenceCounter(); + for (auto& item : *items) { + item.reset(); } } } @@ -349,31 +417,30 @@ class StaticTile final : public Tile StaticTile(const StaticTile&) = delete; StaticTile& operator=(const StaticTile&) = delete; - TileItemVector* getItemList() override { - return items.get(); + TileItemsPtr getItemList() override { + return items; } - const TileItemVector* getItemList() const override { - return items.get(); + + TileItemsConstPtr getItemList() const override { + return items; } - TileItemVector* makeItemList() override { - if (!items) { - items.reset(new TileItemVector); - } - return items.get(); + + TileCreaturesPtr getCreatures() override { + return creatures; } - - CreatureVector* getCreatures() override { - return creatures.get(); + + TileCreaturesConstPtr getCreatures() const override { + return creatures; } - const CreatureVector* getCreatures() const override { - return creatures.get(); + + void postAddNotification(ThingPtr, CylinderPtr, int32_t, cylinderlink_t) override { + } - CreatureVector* makeCreatures() override { - if (!creatures) { - creatures.reset(new CreatureVector); - } - return creatures.get(); + + void postRemoveNotification(ThingPtr, CylinderPtr, int32_t, cylinderlink_t) override { + } + }; #endif diff --git a/src/trashholder.cpp b/src/trashholder.cpp index d225f8b2..97f338c9 100644 --- a/src/trashholder.cpp +++ b/src/trashholder.cpp @@ -8,46 +8,46 @@ extern Game g_game; -ReturnValue TrashHolder::queryAdd(int32_t, const Thing&, uint32_t, uint32_t, Creature*) const +ReturnValue TrashHolder::queryAdd(int32_t, const ThingPtr&, uint32_t, uint32_t, CreaturePtr) { return RETURNVALUE_NOERROR; } -ReturnValue TrashHolder::queryMaxCount(int32_t, const Thing&, uint32_t count, uint32_t& maxQueryCount, uint32_t) const +ReturnValue TrashHolder::queryMaxCount(int32_t, const ThingPtr&, uint32_t count, uint32_t& maxQueryCount, uint32_t) { maxQueryCount = std::max(1, count); return RETURNVALUE_NOERROR; } -ReturnValue TrashHolder::queryRemove(const Thing&, uint32_t, uint32_t, Creature* /*= nullptr*/) const +ReturnValue TrashHolder::queryRemove(const ThingPtr&, uint32_t, uint32_t, CreaturePtr /*= nullptr*/) { return RETURNVALUE_NOTPOSSIBLE; } -Cylinder* TrashHolder::queryDestination(int32_t&, const Thing&, Item**, uint32_t&) +CylinderPtr TrashHolder::queryDestination(int32_t&, const ThingPtr&, ItemPtr*, uint32_t&) { - return this; + return CylinderPtr(this); } -void TrashHolder::addThing(Thing* thing) +void TrashHolder::addThing(ThingPtr thing) { return addThing(0, thing); } -void TrashHolder::addThing(int32_t, Thing* thing) +void TrashHolder::addThing(int32_t, ThingPtr thing) { - Item* item = thing->getItem(); + const auto& item = thing->getItem(); if (!item) { return; } - if (item == this || !item->hasProperty(CONST_PROP_MOVEABLE)) { + if (item == this->getItem() || !item->hasProperty(CONST_PROP_MOVEABLE)) { return; } const ItemType& it = Item::items[id]; if (item->isHangable() && it.isGroundTile()) { - Tile* tile = dynamic_cast(getParent()); + const auto& tile = std::dynamic_pointer_cast(getParent()); if (tile && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { return; } @@ -60,27 +60,31 @@ void TrashHolder::addThing(int32_t, Thing* thing) } } -void TrashHolder::updateThing(Thing*, uint16_t, uint32_t) +void TrashHolder::updateThing(ThingPtr, uint16_t, uint32_t) { // } -void TrashHolder::replaceThing(uint32_t, Thing*) +void TrashHolder::replaceThing(uint32_t, ThingPtr) { // } -void TrashHolder::removeThing(Thing*, uint32_t) +void TrashHolder::removeThing(ThingPtr, uint32_t) { // } -void TrashHolder::postAddNotification(Thing* thing, const Cylinder* oldParent, int32_t index, cylinderlink_t) +void TrashHolder::postAddNotification(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t) { - getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); + if (parent.lock()) { + parent.lock()->postAddNotification(thing, oldParent, index, LINK_PARENT); + } } -void TrashHolder::postRemoveNotification(Thing* thing, const Cylinder* newParent, int32_t index, cylinderlink_t) +void TrashHolder::postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t) { - getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); + if (parent.lock()) { + parent.lock()->postRemoveNotification(thing, newParent, index, LINK_PARENT); + } } diff --git a/src/trashholder.h b/src/trashholder.h index 61f2a1a8..424feed9 100644 --- a/src/trashholder.h +++ b/src/trashholder.h @@ -13,29 +13,30 @@ class TrashHolder final : public Item, public Cylinder public: explicit TrashHolder(uint16_t itemId) : Item(itemId) {} - TrashHolder* getTrashHolder() override { - return this; + TrashHolderPtr getTrashHolder() override { + return dynamic_shared_this(); } - const TrashHolder* getTrashHolder() const override { - return this; + + TrashHolderConstPtr getTrashHolder() const override { + return dynamic_shared_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; + ReturnValue queryAdd(int32_t index, const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; + ReturnValue queryMaxCount(int32_t index, const ThingPtr& thing, uint32_t count, uint32_t& maxQueryCount, uint32_t flags) override; + ReturnValue queryRemove(const ThingPtr& thing, uint32_t count, uint32_t flags, CreaturePtr actor = nullptr) override; + CylinderPtr queryDestination(int32_t& index, const ThingPtr& thing, ItemPtr* destItem, uint32_t& flags) override; // another place to put a ref wrapper or optional or both - void addThing(Thing* thing) override; - void addThing(int32_t index, Thing* thing) override; + void addThing(ThingPtr thing) override; + void addThing(int32_t index, ThingPtr thing) override; - void updateThing(Thing* thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, Thing* thing) override; + void updateThing(ThingPtr thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, ThingPtr thing) override; - void removeThing(Thing* thing, uint32_t count) override; + void removeThing(ThingPtr thing, uint32_t count) 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(ThingPtr thing, CylinderPtr oldParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; + void postRemoveNotification(ThingPtr thing, CylinderPtr newParent, int32_t index, cylinderlink_t link = LINK_OWNER) override; }; #endif diff --git a/src/vocation.cpp b/src/vocation.cpp index 06686f05..5cff669e 100644 --- a/src/vocation.cpp +++ b/src/vocation.cpp @@ -151,7 +151,7 @@ uint16_t Vocations::getPromotedVocation(uint16_t id) const static const uint32_t 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) const { if (skill > SKILL_LAST) { return 0; @@ -159,7 +159,7 @@ uint64_t Vocation::getReqSkillTries(uint8_t skill, uint16_t level) return skillBase[skill] * std::pow(skillMultipliers[skill], static_cast(level - (MINIMUM_SKILL_LEVEL + 1))); } -uint64_t Vocation::getReqMana(uint32_t magLevel) +uint64_t Vocation::getReqMana(uint32_t magLevel) const { if (magLevel == 0) { return 0; diff --git a/src/vocation.h b/src/vocation.h index e78052cc..b731aec9 100644 --- a/src/vocation.h +++ b/src/vocation.h @@ -15,11 +15,13 @@ class Vocation const std::string& getVocName() const { return name; } + const std::string& getVocDescription() const { return description; } - uint64_t getReqSkillTries(uint8_t skill, uint16_t level); - uint64_t getReqMana(uint32_t magLevel); + + uint64_t getReqSkillTries(uint8_t skill, uint16_t level) const; + uint64_t getReqMana(uint32_t magLevel) const; uint16_t getId() const { return id; @@ -32,9 +34,11 @@ class Vocation uint32_t getHPGain() const { return gainHP; } + uint32_t getManaGain() const { return gainMana; } + uint32_t getCapGain() const { return gainCap; } @@ -42,12 +46,15 @@ class Vocation uint32_t getManaGainTicks() const { return gainManaTicks; } + uint32_t getManaGainAmount() const { return gainManaAmount; } + uint32_t getHealthGainTicks() const { return gainHealthTicks; } + uint32_t getHealthGainAmount() const { return gainHealthAmount; } @@ -55,6 +62,7 @@ class Vocation uint8_t getSoulMax() const { return soulMax; } + uint16_t getSoulGainTicks() const { return gainSoulTicks; } @@ -62,6 +70,7 @@ class Vocation uint32_t getAttackSpeed() const { return attackSpeed; } + uint32_t getBaseSpeed() const { return baseSpeed; } diff --git a/src/weapons.cpp b/src/weapons.cpp index c3390914..96fe5b23 100644 --- a/src/weapons.cpp +++ b/src/weapons.cpp @@ -27,13 +27,13 @@ Weapons::~Weapons() clear(false); } -const Weapon* Weapons::getWeapon(const Item* item) const +const Weapon* Weapons::getWeapon(const ItemConstPtr& item) const { if (!item) { return nullptr; } - auto it = weapons.find(item->getID()); + const auto it = weapons.find(item->getID()); if (it == weapons.end()) { return nullptr; } @@ -62,7 +62,7 @@ void Weapons::loadDefaults() { for (size_t i = 100, size = Item::items.size(); i < size; ++i) { const ItemType& it = Item::items.getItemType(i); - if (it.id == 0 || weapons.find(i) != weapons.end()) { + if (it.id == 0 || weapons.contains(i)) { continue; } @@ -256,7 +256,7 @@ void Weapon::configureWeapon(const ItemType& it) id = it.id; } -int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const +int32_t Weapon::playerWeaponCheck(const PlayerConstPtr& player, const CreatureConstPtr& target, uint8_t shootRange) const { const Position& playerPos = player->getPosition(); const Position& targetPos = target->getPosition(); @@ -290,7 +290,7 @@ int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shoo } if (!vocWeaponMap.empty()) { - if (vocWeaponMap.find(player->getVocationId()) == vocWeaponMap.end()) { + if (!vocWeaponMap.contains(player->getVocationId())) { return 0; } } @@ -309,7 +309,7 @@ int32_t Weapon::playerWeaponCheck(Player* player, Creature* target, uint8_t shoo return 100; } -bool Weapon::ammoCheck(const Player* player) const +bool Weapon::ammoCheck(const PlayerConstPtr& player) const { if (!player->hasFlag(PlayerFlag_IgnoreWeaponCheck)) { if (!enabled || player->getMana() < getManaCost(player) || player->getHealth() < getHealthCost(player) || @@ -319,7 +319,7 @@ bool Weapon::ammoCheck(const Player* player) const } if (!vocWeaponMap.empty()) { - if (vocWeaponMap.find(player->getVocationId()) == vocWeaponMap.end()) { + if (!vocWeaponMap.contains(player->getVocationId())) { return false; } } @@ -328,9 +328,9 @@ bool Weapon::ammoCheck(const Player* player) const return true; } -bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const +bool Weapon::useWeapon(const PlayerPtr player, const ItemPtr item, const CreaturePtr target) const { - int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); + const auto damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } @@ -339,7 +339,7 @@ bool Weapon::useWeapon(Player* player, Item* item, Creature* target) const return true; } -bool Weapon::useFist(Player* player, Creature* target) +bool Weapon::useFist(const PlayerPtr& player, const CreaturePtr& target) { if (!Position::areInRange<1, 1>(player->getPosition(), target->getPosition())) { return false; @@ -369,7 +369,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(const PlayerPtr& player, const ItemPtr& item, const CreaturePtr& target, int32_t damageModifier) const { if (scripted) { LuaVariant var; @@ -393,7 +393,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(const PlayerPtr& player, const ItemPtr& item, const TilePtr& tile) const { if (scripted) { LuaVariant var; @@ -407,7 +407,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(const PlayerPtr& player, const ItemPtr& item, const TilePtr& destTile) const { if (!player->hasFlag(PlayerFlag_NotGainSkill)) { skills_t skillType; @@ -437,6 +437,8 @@ void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const return; } + CylinderPtr f_holder = item->getParent(); + CylinderPtr t_holder = destTile->getTile(); switch (action) { case WEAPONACTION_REMOVECOUNT: if (g_config.getBoolean(ConfigManager::REMOVE_WEAPON_AMMO)) { @@ -453,7 +455,7 @@ void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const } case WEAPONACTION_MOVE: - g_game.internalMoveItem(item->getParent(), destTile, INDEX_WHEREEVER, item, 1, nullptr, FLAG_NOLIMIT); + g_game.internalMoveItem(f_holder, t_holder, INDEX_WHEREEVER, item, 1, nullptr, FLAG_NOLIMIT); break; default: @@ -461,7 +463,7 @@ void Weapon::onUsedWeapon(Player* player, Item* item, Tile* destTile) const } } -uint32_t Weapon::getManaCost(const Player* player) const +uint32_t Weapon::getManaCost(const PlayerConstPtr& player) const { if (mana != 0) { return mana; @@ -474,7 +476,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 PlayerConstPtr& player) const { if (health != 0) { return health; @@ -487,7 +489,7 @@ int32_t Weapon::getHealthCost(const Player* player) const return (player->getMaxHealth() * healthPercent) / 100; } -bool Weapon::executeUseWeapon(Player* player, const LuaVariant& var) const +bool Weapon::executeUseWeapon(const PlayerPtr& player, const LuaVariant& var) const { //onUseWeapon(player, var) if (!scriptInterface->reserveScriptEnv()) { @@ -501,14 +503,14 @@ bool Weapon::executeUseWeapon(Player* player, const LuaVariant& var) const lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushSharedPtr(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); scriptInterface->pushVariant(L, var); return scriptInterface->callFunction(2); } -void Weapon::decrementItemCount(Item* item) +void Weapon::decrementItemCount(const ItemPtr& item) { uint16_t count = item->getItemCount(); if (count > 1) { @@ -540,7 +542,7 @@ void WeaponMelee::configureWeapon(const ItemType& it) Weapon::configureWeapon(it); } -bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const +bool WeaponMelee::useWeapon(const PlayerPtr player, const ItemPtr item, const CreaturePtr target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { @@ -550,7 +552,7 @@ bool WeaponMelee::useWeapon(Player* player, Item* item, Creature* target) const return true; } -bool WeaponMelee::getSkillType(const Player* player, const Item* item, +bool WeaponMelee::getSkillType(const PlayerConstPtr& player, const ItemConstPtr& item, skills_t& skill, uint32_t& skillpoint) const { if (player->getAddAttackSkill() && player->getLastAttackBlockType() != BLOCK_IMMUNITY) { @@ -559,8 +561,7 @@ bool WeaponMelee::getSkillType(const Player* player, const Item* item, skillpoint = 0; } - WeaponType_t weaponType = item->getWeaponType(); - switch (weaponType) { + switch (const auto weaponType = item->getWeaponType()) { case WEAPON_SWORD: { skill = SKILL_SWORD; return true; @@ -582,7 +583,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 PlayerConstPtr& player, const CreatureConstPtr&, const ItemConstPtr& item) const { if (elementType == COMBAT_NONE) { return 0; @@ -596,7 +597,7 @@ int32_t WeaponMelee::getElementDamage(const Player* player, const Creature*, con return -normal_random(0, static_cast(maxValue * player->getVocation()->meleeDamageMultiplier)); } -int32_t WeaponMelee::getWeaponDamage(const Player* player, const Creature*, const Item* item, bool maxDamage /*= false*/) const +int32_t WeaponMelee::getWeaponDamage(const PlayerConstPtr& player, const CreatureConstPtr&, const ItemConstPtr& item, bool maxDamage /*= false*/) const { int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = std::max(0, item->getAttack()); @@ -634,14 +635,13 @@ void WeaponDistance::configureWeapon(const ItemType& it) Weapon::configureWeapon(it); } -bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) const +bool WeaponDistance::useWeapon(const PlayerPtr player, const ItemPtr item, const CreaturePtr target) const { int32_t damageModifier = 0; const ItemType& it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { - Item* mainWeaponItem = player->getWeapon(true); - const Weapon* mainWeapon = g_weapons->getWeapon(mainWeaponItem); - if (mainWeapon) { + auto mainWeaponItem = player->getWeapon(true); + if (const auto mainWeapon = g_weapons->getWeapon(mainWeaponItem)) { damageModifier = mainWeapon->playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); } else if (mainWeaponItem) { damageModifier = playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); @@ -756,8 +756,7 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con } if (item->getWeaponType() == WEAPON_AMMO) { - Item* bow = player->getWeapon(true); - if (bow && bow->getHitChance() != 0) { + if (const auto bow = player->getWeapon(true); bow && bow->getHitChance() != 0) { chance += bow->getHitChance(); } } @@ -766,7 +765,7 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con Weapon::internalUseWeapon(player, item, target, damageModifier); } else { //miss target - Tile* destTile = target->getTile(); + auto destTile = target->getTile(); if (!Position::areInRange<1, 1, 0>(player->getPosition(), target->getPosition())) { static std::vector> destList { @@ -774,13 +773,13 @@ bool WeaponDistance::useWeapon(Player* player, Item* item, Creature* target) con {-1, 0}, {0, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1} }; - std::shuffle(destList.begin(), destList.end(), getRandomGenerator()); + std::ranges::shuffle(destList, getRandomGenerator()); Position destPos = target->getPosition(); for (const auto& dir : destList) { // Blocking tiles or tiles without ground ain't valid targets for spears - Tile* tmpTile = g_game.map.getTile(destPos.x + dir.first, destPos.y + dir.second, destPos.z); + auto tmpTile = g_game.map.getTile(destPos.x + dir.first, destPos.y + dir.second, destPos.z); if (tmpTile && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID) && tmpTile->getGround() != nullptr) { destTile = tmpTile; break; @@ -792,7 +791,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 PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item) const { if (elementType == COMBAT_NONE) { return 0; @@ -800,8 +799,7 @@ int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* t int32_t attackValue = elementDamage; if (item->getWeaponType() == WEAPON_AMMO) { - Item* weapon = player->getWeapon(true); - if (weapon) { + if (const auto weapon = player->getWeapon(true)) { attackValue += weapon->getAttack(); } } @@ -822,13 +820,12 @@ int32_t WeaponDistance::getElementDamage(const Player* player, const Creature* t return -normal_random(minValue, static_cast(maxValue * player->getVocation()->distDamageMultiplier)); } -int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage /*= false*/) const +int32_t WeaponDistance::getWeaponDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item, bool maxDamage /*= false*/) const { int32_t attackValue = item->getAttack(); if (item->getWeaponType() == WEAPON_AMMO) { - Item* weapon = player->getWeapon(true); - if (weapon) { + if (const auto weapon = player->getWeapon(true)) { attackValue += weapon->getAttack(); } } @@ -854,7 +851,7 @@ int32_t WeaponDistance::getWeaponDamage(const Player* player, const Creature* ta return -normal_random(minValue, maxValue); } -bool WeaponDistance::getSkillType(const Player* player, const Item*, skills_t& skill, uint32_t& skillpoint) const +bool WeaponDistance::getSkillType(const PlayerConstPtr& player, const ItemConstPtr&, skills_t& skill, uint32_t& skillpoint) const { skill = SKILL_DISTANCE; @@ -927,7 +924,7 @@ void WeaponWand::configureWeapon(const ItemType& it) Weapon::configureWeapon(it); } -int32_t WeaponWand::getWeaponDamage(const Player*, const Creature*, const Item*, bool maxDamage /*= false*/) const +int32_t WeaponWand::getWeaponDamage(const PlayerConstPtr&, const CreatureConstPtr&, const ItemConstPtr&, bool maxDamage /*= false*/) const { if (maxDamage) { return -maxChange; diff --git a/src/weapons.h b/src/weapons.h index 2c1f297d..ec00bbf4 100644 --- a/src/weapons.h +++ b/src/weapons.h @@ -30,7 +30,7 @@ class Weapons final : public BaseEvents Weapons& operator=(const Weapons&) = delete; void loadDefaults(); - const Weapon* getWeapon(const Item* item) const; + const Weapon* getWeapon(const ItemConstPtr& item) const; static int32_t getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue); static int32_t getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor); @@ -62,19 +62,20 @@ class Weapon : public Event virtual bool interruptSwing() const { return false; } - bool ammoCheck(const Player* player) const; + bool ammoCheck(const PlayerConstPtr& player) const; - int32_t playerWeaponCheck(Player* player, Creature* target, uint8_t shootRange) const; - static bool useFist(Player* player, Creature* target); - virtual bool useWeapon(Player* player, Item* item, Creature* target) const; + int32_t playerWeaponCheck(const PlayerConstPtr& player,const CreatureConstPtr& target, uint8_t shootRange) const; + static bool useFist(const PlayerPtr& player, const CreaturePtr& target); + virtual bool useWeapon(PlayerPtr player, ItemPtr item, CreaturePtr target) const; - virtual int32_t getWeaponDamage(const Player* player, const Creature* target, const Item* item, bool maxDamage = false) const = 0; - virtual int32_t getElementDamage(const Player* player, const Creature* target, const Item* item) const = 0; + virtual int32_t getWeaponDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item, bool maxDamage = false) const = 0; + virtual int32_t getElementDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item) const = 0; virtual CombatType_t getElementType() const = 0; uint16_t getID() const { return id; } + void setID(uint16_t newId) { id = newId; } @@ -82,6 +83,7 @@ class Weapon : public Event uint32_t getReqLevel() const { return level; } + void setRequiredLevel(uint32_t reqlvl) { level = reqlvl; } @@ -89,6 +91,7 @@ class Weapon : public Event uint32_t getReqMagLv() const { return magLevel; } + void setRequiredMagLevel(uint32_t reqlvl) { magLevel = reqlvl; } @@ -96,6 +99,7 @@ class Weapon : public Event bool isPremium() const { return premium; } + void setNeedPremium(bool prem) { premium = prem; } @@ -103,6 +107,7 @@ class Weapon : public Event bool isWieldedUnproperly() const { return wieldUnproperly; } + void setWieldUnproperly(bool unproperly) { wieldUnproperly = unproperly; } @@ -110,6 +115,7 @@ class Weapon : public Event uint32_t getMana() const { return mana; } + void setMana(uint32_t m) { mana = m; } @@ -117,6 +123,7 @@ class Weapon : public Event uint32_t getManaPercent() const { return manaPercent; } + void setManaPercent(uint32_t m) { manaPercent = m; } @@ -124,6 +131,7 @@ class Weapon : public Event int32_t getHealth() const { return health; } + void setHealth(int32_t h) { health = h; } @@ -131,6 +139,7 @@ class Weapon : public Event uint32_t getHealthPercent() const { return healthPercent; } + void setHealthPercent(uint32_t m) { healthPercent = m; } @@ -138,6 +147,7 @@ class Weapon : public Event uint32_t getSoul() const { return soul; } + void setSoul(uint32_t s) { soul = s; } @@ -145,6 +155,7 @@ class Weapon : public Event uint8_t getBreakChance() const { return breakChance; } + void setBreakChance(uint8_t b) { breakChance = b; } @@ -152,6 +163,7 @@ class Weapon : public Event bool isEnabled() const { return enabled; } + void setIsEnabled(bool e) { enabled = e; } @@ -159,11 +171,12 @@ class Weapon : public Event uint32_t getWieldInfo() const { return wieldInfo; } + void setWieldInfo(uint32_t info) { wieldInfo |= info; } - void addVocWeaponMap(std::string vocName) { + void addVocWeaponMap(const std::string& vocName) { int32_t vocationId = g_vocations.getVocationId(vocName); if (vocationId != -1) { vocWeaponMap[vocationId] = true; @@ -173,6 +186,7 @@ class Weapon : public Event const std::string& getVocationString() const { return vocationString; } + void setVocationString(const std::string& str) { vocationString = str; } @@ -183,18 +197,18 @@ class Weapon : public Event std::map vocWeaponMap; protected: - void internalUseWeapon(Player* player, Item* item, Creature* target, int32_t damageModifier) const; - void internalUseWeapon(Player* player, Item* item, Tile* tile) const; + void internalUseWeapon(const PlayerPtr& player, const ItemPtr& item, const CreaturePtr& target, int32_t damageModifier) const; + void internalUseWeapon(const PlayerPtr& player, const ItemPtr& item, const TilePtr& tile) const; uint16_t id = 0; private: - virtual bool getSkillType(const Player*, const Item*, skills_t&, uint32_t&) const { + virtual bool getSkillType(const PlayerConstPtr&, const ItemConstPtr&, skills_t&, uint32_t&) const { return false; } - uint32_t getManaCost(const Player* player) const; - int32_t getHealthCost(const Player* player) const; + uint32_t getManaCost(const PlayerConstPtr& player) const; + int32_t getHealthCost(const PlayerConstPtr& player) const; uint32_t level = 0; uint32_t magLevel = 0; @@ -212,10 +226,10 @@ class Weapon : public Event std::string_view getScriptEventName() const override final { return "onUseWeapon"; } - bool executeUseWeapon(Player* player, const LuaVariant& var) const; - void onUsedWeapon(Player* player, Item* item, Tile* destTile) const; + bool executeUseWeapon(const PlayerPtr& player, const LuaVariant& var) const; + void onUsedWeapon(const PlayerPtr& player, const ItemPtr& item, const TilePtr& destTile) const; - static void decrementItemCount(Item* item); + static void decrementItemCount(const ItemPtr& item); friend class Combat; }; @@ -227,14 +241,14 @@ class WeaponMelee final : public Weapon void configureWeapon(const ItemType& it) override; - bool useWeapon(Player* player, Item* item, Creature* target) const override; + bool useWeapon(const PlayerPtr player, const ItemPtr item, const CreaturePtr 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; + int32_t getWeaponDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item, bool maxDamage = false) const override; + int32_t getElementDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item) const override; CombatType_t getElementType() const override { return elementType; } private: - bool getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const override; + bool getSkillType(const PlayerConstPtr& player, const ItemConstPtr& item, skills_t& skill, uint32_t& skillpoint) const override; CombatType_t elementType = COMBAT_NONE; uint16_t elementDamage = 0; @@ -250,14 +264,14 @@ class WeaponDistance final : public Weapon return true; } - bool useWeapon(Player* player, Item* item, Creature* target) const override; + bool useWeapon(PlayerPtr player, ItemPtr item, CreaturePtr 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; + int32_t getWeaponDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item, bool maxDamage = false) const override; + int32_t getElementDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item) const override; CombatType_t getElementType() const override { return elementType; } private: - bool getSkillType(const Player* player, const Item* item, skills_t& skill, uint32_t& skillpoint) const override; + bool getSkillType(const PlayerConstPtr& player, const ItemConstPtr& item, skills_t& skill, uint32_t& skillpoint) const override; CombatType_t elementType = COMBAT_NONE; uint16_t elementDamage = 0; @@ -271,8 +285,8 @@ class WeaponWand final : public Weapon bool configureEvent(const pugi::xml_node& node) 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; } + int32_t getWeaponDamage(const PlayerConstPtr& player, const CreatureConstPtr& target, const ItemConstPtr& item, bool maxDamage = false) const override; + int32_t getElementDamage(const PlayerConstPtr&, const CreatureConstPtr&, const ItemConstPtr&) const override { return 0; } CombatType_t getElementType() const override { return COMBAT_NONE; } void setMinChange(int32_t change) { @@ -284,7 +298,7 @@ class WeaponWand final : public Weapon } private: - bool getSkillType(const Player*, const Item*, skills_t&, uint32_t&) const override { + bool getSkillType(const PlayerConstPtr&, const ItemConstPtr&, skills_t&, uint32_t&) const override { return false; }