Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove shared_ptr from reward #860

Merged
merged 11 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions data-canary/scripts/reward_chest/boss_death.lua
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function bossDeath.onDeath(creature, corpse, killer, mostDamageKiller, lastHitUn
-- Make sure it is a boss
if monsterType and monsterType:isRewardBoss() then
local bossId = creature:getId()
local timestamp = systemTime()
local rewardId = corpse:getAttribute(ITEM_ATTRIBUTE_DATE)

ResetAndSetTargetList(creature)

Expand Down Expand Up @@ -57,7 +57,7 @@ function bossDeath.onDeath(creature, corpse, killer, mostDamageKiller, lastHitUn
-- Ignoring stamina for now because I heard you get receive rewards even when it's depleted
local reward, stamina
if con.player then
reward = con.player:getReward(timestamp, true)
reward = con.player:getReward(rewardId, true)
stamina = con.player:getStamina()
else
stamina = con.stamina or 0
Expand Down Expand Up @@ -87,7 +87,7 @@ function bossDeath.onDeath(creature, corpse, killer, mostDamageKiller, lastHitUn
end
con.player:sendTextMessage(MESSAGE_LOOT, lootMessage)
elseif con.score ~= 0 then
InsertRewardItems(con.guid, timestamp, playerLoot)
InsertRewardItems(con.guid, rewardId, playerLoot)
end
end

Expand Down
94 changes: 45 additions & 49 deletions data-otservbr-global/scripts/reward_chest/boss_death.lua
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function bossDeath.onDeath(creature, corpse, killer, mostDamageKiller, lastHitUn
-- Make sure it is a boss
if monsterType and monsterType:isRewardBoss() then
local bossId = creature:getId()
local timestamp = systemTime()
local rewardId = corpse:getAttribute(ITEM_ATTRIBUTE_DATE)

ResetAndSetTargetList(creature)

Expand Down Expand Up @@ -76,71 +76,67 @@ function bossDeath.onDeath(creature, corpse, killer, mostDamageKiller, lastHitUn

for _, con in ipairs(scores) do
-- Ignoring stamina for now because I heard you get receive rewards even when it's depleted
local reward, stamina
if con.player then
reward = con.player:getReward(timestamp, true)
stamina = con.player:getStamina()
else
stamina = con.stamina or 0
end

local playerLoot
if con.score ~= 0 then
local reward, stamina, player
if con.player then
player = con.player;
else
player = Game.getOfflinePlayer(con.guid)
end
reward = player:getReward(rewardId, true)
stamina = player:getStamina()

local playerLoot
local lootFactor = 1
-- Tone down the loot a notch if there are many participants
lootFactor = lootFactor / participants ^ (1 / 3)
-- Increase the loot multiplicatively by how many times the player surpassed the expected score
lootFactor = lootFactor * (1 + lootFactor) ^ (con.score / expectedScore)
playerLoot = monsterType:getBossReward(lootFactor, _ == 1)

if con.player then
for _, p in ipairs(playerLoot) do
reward:addItem(p[1], p[2])
end
for _, p in ipairs(playerLoot) do
reward:addItem(p[1], p[2])
end
end

-- Bosstiary Loot Bonus
local bonus, boostedMessage
local isBoostedBoss = creature:getName():lower() == (Game.getBoostedBoss()):lower()
local bossRaceIds = {con.player:getSlotBossId(1), con.player:getSlotBossId(2)}
local isBoss = table.contains(bossRaceIds, monsterType:bossRaceId()) or isBoostedBoss
if isBoss then
if monsterType:bossRaceId() == con.player:getSlotBossId(1) then
bonus = con.player:getBossBonus(1)
elseif monsterType:bossRaceId() == con.player:getSlotBossId(2) then
bonus = con.player:getBossBonus(2)
else
bonus = configManager.getNumber(configKeys.BOOSTED_BOSS_LOOT_BONUS)
end
-- Bosstiary Loot Bonus
local bonus, boostedMessage
local isBoostedBoss = creature:getName():lower() == (Game.getBoostedBoss()):lower()
local bossRaceIds = {player:getSlotBossId(1), player:getSlotBossId(2)}
local isBoss = table.contains(bossRaceIds, monsterType:bossRaceId()) or isBoostedBoss
if isBoss and monsterType:bossRaceId() ~= 0 then
if monsterType:bossRaceId() == player:getSlotBossId(1) then
bonus = player:getBossBonus(1)
elseif monsterType:bossRaceId() == player:getSlotBossId(2) then
bonus = player:getBossBonus(2)
else
bonus = configManager.getNumber(configKeys.BOOSTED_BOSS_LOOT_BONUS)
end

for _, p in ipairs(playerLoot) do
local isValidItem = checkItemType(p[1])
if isValidItem then
local realBonus = calculateBonus(bonus)
for _ = 1, realBonus do
reward:addItem(p[1], p[2])
boostedMessage = true
for _, p in ipairs(playerLoot) do
local isValidItem = checkItemType(p[1])
if isValidItem then
local realBonus = calculateBonus(bonus)
for _ = 1, realBonus do
reward:addItem(p[1], p[2])
boostedMessage = true
end
end
end
end
end

if con.player and con.score ~= 0 then
local lootMessage = ("The following items dropped by %s are available in your reward chest: %s"):format(creature:getName(), reward:getContentDescription())
if boostedMessage then
lootMessage = lootMessage .. " (Boss bonus)"
end

if stamina > 840 then
reward:getContentDescription(lootMessage)
if con.player then
local lootMessage = ("The following items dropped by %s are available in your reward chest: %s"):format(creature:getName(), reward:getContentDescription())
if boostedMessage then
lootMessage = lootMessage .. " (Boss bonus)"
end
if stamina > 840 then
reward:getContentDescription(lootMessage)
end
player:sendTextMessage(MESSAGE_LOOT, lootMessage)
else
player:save()
end
con.player:sendTextMessage(MESSAGE_LOOT, lootMessage)
elseif con.score ~= 0 then
InsertRewardItems(con.guid, timestamp, playerLoot)
end
end

GlobalBosses[bossId] = nil
end
return true
Expand Down
6 changes: 3 additions & 3 deletions data/events/scripts/monster.lua
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function Monster:onDropLoot(corpse)
local isBoostedBoss = self:getName():lower() == (Game.getBoostedBoss()):lower()
local bossRaceIds = {player:getSlotBossId(1), player:getSlotBossId(2)}
local isBoss = table.contains(bossRaceIds, mType:bossRaceId()) or isBoostedBoss
if isBoss then
if isBoss and mType:bossRaceId() ~= 0 then
local bonus
if mType:bossRaceId() == player:getSlotBossId(1) then
bonus = player:getBossBonus(1)
Expand Down Expand Up @@ -137,8 +137,8 @@ function Monster:onSpawn(position)

-- We won't run anything from here on down if we're opening the global pack
if IsRunningGlobalDatapack() then
if self:getName():lower() == "cobra scout" or
self:getName():lower() == "cobra vizier" or
if self:getName():lower() == "cobra scout" or
self:getName():lower() == "cobra vizier" or
self:getName():lower() == "cobra assassin" then
if getGlobalStorageValue(GlobalStorage.CobraBastionFlask) >= os.time() then
self:setHealth(self:getMaxHealth() * 0.75)
Expand Down
59 changes: 26 additions & 33 deletions data/libs/reward_boss/reward_boss.lua
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,19 @@ function PushSeparated(buffer, sep, ...)
end
end

function InsertItems(buffer, info, parent, items, bagSid)
function InsertItems(buffer, info, parent, items)
local start = info.running
for _, item in ipairs(items) do
if item ~= nil then
if _ ~= 1 or parent > 100 then
table.insert(buffer, ",")
end
if item:getId() == ITEM_REWARD_CONTAINER then
if item:getId() == ITEM_REWARD_CONTAINER then
table.insert(buffer, "(")
PushSeparated(buffer, ",", info.playerGuid, 0, bagSid, item:getId(), item:getSubType(), db.escapeString(item:serializeAttributes()))
table.insert(buffer, ")")
PushSeparated(buffer, ",", info.playerGuid, 0, parent, item:getId(), item:getSubType(), db.escapeString(item:serializeAttributes()))
table.insert(buffer, "),")
else
info.running = info.running + 1
table.insert(buffer, "(")
PushSeparated(buffer, ",", info.playerGuid, parent, info.running, item:getId(), item:getSubType(), db.escapeString(item:serializeAttributes()))
table.insert(buffer, ")")
table.insert(buffer, "),")
end

if item:isContainer() then
Expand All @@ -47,7 +44,7 @@ function InsertItems(buffer, info, parent, items, bagSid)
table.insert(subItems, item:getItem(i - 1))
end

InsertItems(buffer, info, bagSid, subItems, bagSid)
InsertItems(buffer, info, info.running, subItems)
end
end
end
Expand All @@ -56,31 +53,27 @@ function InsertItems(buffer, info, parent, items, bagSid)
end

function InsertRewardItems(playerGuid, timestamp, itemList)
db.asyncStoreQuery('select max(`sid`) as max_sid from `player_rewards` where player_id = '..playerGuid..';',
function(query)
local lastSid = Result.getDataInt(query, 'max_sid') or 0;
local bagSid = lastSid + 1;
local nextSid = bagId + 1;
local buffer = {'INSERT INTO `player_rewards` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES'}
local info = {
playerGuid = playerGuid,
running = nextSid
}
local bag = Game.createItem(ITEM_REWARD_CONTAINER)
bag:setAttribute(ITEM_ATTRIBUTE_DATE, timestamp)
if itemList then
for _, p in ipairs(itemList) do
bag:addItem(p[1], p[2])
end
end
local total = InsertItems(buffer, info, lastPid + 1, {bag}, bagSid)
table.insert(buffer, ";")

if total ~= 0 then
db.query(table.concat(buffer))
end
local maxSidQueryResult = db.query('select max(`sid`) as max_sid from `player_rewards` where player_id = '..playerGuid..';')
local bagSid = (Result.getDataInt(maxSidQueryResult, 'max_sid') or 0) + 1;
local nextSid = bagSid + 1;
local buffer = {'INSERT INTO `player_rewards` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES'}
local info = {
playerGuid = playerGuid,
running = nextSid
}
local bag = Game.createItem(ITEM_REWARD_CONTAINER)
bag:setAttribute(ITEM_ATTRIBUTE_DATE, timestamp)
if itemList then
for _, p in ipairs(itemList) do
bag:addItem(p[1], p[2])
end
)
end
local total = InsertItems(buffer, info, bagSid, {bag})

if total ~= 0 then
local insertItemsQuery = table.concat(buffer):sub(1, -2)..";";
db.query(insertItemsQuery)
end
end

function GetPlayerStats(bossId, playerGuid, autocreate)
Expand Down
31 changes: 16 additions & 15 deletions src/creatures/players/player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ Player::~Player() {
it.second->decrementReferenceCounter();
}

for (const auto &it : rewardMap) {
it.second->decrementReferenceCounter();
}

for (const auto &it : quickLootContainers) {
it.second->decrementReferenceCounter();
}
Expand Down Expand Up @@ -671,17 +675,12 @@ void Player::closeContainer(uint8_t cid) {

OpenContainer openContainer = it->second;
Container* container = openContainer.container;
openContainers.erase(it);

if (!container) {
return;
}

if (container->isAnykindOfRewardContainer() && !hasAnykindOfRewardContainerOpen()) {
if (container && container->isAnykindOfRewardContainer() && !hasOtherRewardContainerOpen(container)) {
removeEmptyRewards();
}

if (container->getID() == ITEM_BROWSEFIELD) {
openContainers.erase(it);
if (container && container->getID() == ITEM_BROWSEFIELD) {
container->decrementReferenceCounter();
}
}
Expand All @@ -690,16 +689,17 @@ void Player::removeEmptyRewards() {
std::erase_if(rewardMap, [this](const auto &rewardBag) {
auto [id, reward] = rewardBag;
if (reward->empty()) {
this->getRewardChest()->removeThing(reward.get(), 1);
this->getRewardChest()->removeThing(reward, 1);
reward->decrementReferenceCounter();
return true;
}
return false;
});
}

bool Player::hasAnykindOfRewardContainerOpen() const {
return std::ranges::any_of(openContainers.begin(), openContainers.end(), [](const auto &containerPair) {
return containerPair.second.container->isAnykindOfRewardContainer();
bool Player::hasOtherRewardContainerOpen(const Container* container) const {
return std::ranges::any_of(openContainers.begin(), openContainers.end(), [container](const auto &containerPair) {
return containerPair.second.container != container && containerPair.second.container->isAnykindOfRewardContainer();
});
}

Expand Down Expand Up @@ -1072,7 +1072,7 @@ RewardChest* Player::getRewardChest() {
return rewardChest;
}

std::shared_ptr<Reward> Player::getReward(const uint64_t rewardId, const bool autoCreate) {
Reward* Player::getReward(const uint64_t rewardId, const bool autoCreate) {
auto it = rewardMap.find(rewardId);
if (it != rewardMap.end()) {
return it->second;
Expand All @@ -1081,10 +1081,11 @@ std::shared_ptr<Reward> Player::getReward(const uint64_t rewardId, const bool au
return nullptr;
}

const auto reward = std::make_shared<Reward>();
auto reward = new Reward();
reward->incrementReferenceCounter();
reward->setAttribute(ItemAttribute_t::DATE, rewardId);
rewardMap[rewardId] = reward;
g_game().internalAddItem(getRewardChest(), reward.get(), INDEX_WHEREEVER, FLAG_NOLIMIT);
g_game().internalAddItem(getRewardChest(), reward, INDEX_WHEREEVER, FLAG_NOLIMIT);

return reward;
}
Expand Down
6 changes: 3 additions & 3 deletions src/creatures/players/player.h
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ class Player final : public Creature, public Cylinder {
void addConditionSuppressions(uint32_t conditions);
void removeConditionSuppressions(uint32_t conditions);

std::shared_ptr<Reward> getReward(const uint64_t rewardId, const bool autoCreate);
Reward* getReward(const uint64_t rewardId, const bool autoCreate);
void removeReward(uint64_t rewardId);
void getRewardList(std::vector<uint64_t> &rewards) const;
RewardChest* getRewardChest();
Expand Down Expand Up @@ -2350,7 +2350,7 @@ class Player final : public Creature, public Cylinder {
{ SKILL_CRITICAL_HIT_CHANCE, g_configManager().getNumber(CRITICALCHANCE) }
};

std::map<uint64_t, std::shared_ptr<Reward>> rewardMap;
std::map<uint64_t, Reward*> rewardMap;

std::map<ObjectCategory_t, Container*> quickLootContainers;
std::vector<ForgeHistory> forgeHistoryVector;
Expand Down Expand Up @@ -2617,7 +2617,7 @@ class Player final : public Creature, public Cylinder {
double_t calculateDamageReduction(double_t currentTotal, int16_t resistance) const;

void removeEmptyRewards();
bool hasAnykindOfRewardContainerOpen() const;
bool hasOtherRewardContainerOpen(const Container* container) const;
};

#endif // SRC_CREATURES_PLAYERS_PLAYER_H_
6 changes: 3 additions & 3 deletions src/io/functions/iologindata_save_player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ bool IOLoginDataSave::saveRewardItems(Player* player) {
if (!rewardList.empty()) {
for (const auto &rewardId : rewardList) {
auto reward = player->getReward(rewardId, false);
if (!reward->empty() && (getTimeNow() - rewardId / 1000 <= 60 * 60 * 24 * 7)) {
itemList.emplace_back(0, reward.get());
if (!reward->empty() && (getTimeMsNow() - rewardId <= 1000 * 60 * 60 * 24 * 7)) {
itemList.emplace_back(0, reward);
}
}

Expand Down Expand Up @@ -97,4 +97,4 @@ bool IOLoginDataSave::savePlayerBosstiary(const Player* player) {
}

return true;
}
}
Loading