Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 149.84 KB | None | 0 0
  1. ////////////////////////////////////////////////////////////////////////
  2. // OpenTibia - an opensource roleplaying game
  3. ////////////////////////////////////////////////////////////////////////
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program.  If not, see <http://www.gnu.org/licenses/>.
  16. ////////////////////////////////////////////////////////////////////////
  17. #include "otpch.h"
  18. #include <iostream>
  19. #include <iomanip>
  20.  
  21. #include "player.h"
  22.  
  23. #include "iologindata.h"
  24. #include "ioban.h"
  25.  
  26. #include "town.h"
  27. #include "house.h"
  28. #include "beds.h"
  29. #include "quests.h"
  30.  
  31. #include "combat.h"
  32. #include "movement.h"
  33. #include "weapons.h"
  34. #include "creatureevent.h"
  35.  
  36. #include "configmanager.h"
  37. #include "game.h"
  38. #include "chat.h"
  39. #include "textlogger.h"
  40. #include "outputmessage.h"
  41.  
  42. #if defined(WINDOWS) && !defined(_CONSOLE)
  43. #include "gui.h"
  44. #endif
  45.  
  46. extern ConfigManager g_config;
  47. extern Game g_game;
  48. extern Chat g_chat;
  49. extern MoveEvents* g_moveEvents;
  50. extern Weapons* g_weapons;
  51. extern CreatureEvents* g_creatureEvents;
  52.  
  53. AutoList<Player> Player::autoList;
  54. #ifdef __ENABLE_SERVER_DIAGNOSTIC__
  55. uint32_t Player::playerCount = 0;
  56. #endif
  57. MuteCountMap Player::muteCountMap;
  58.  
  59. Player::Player(const std::string& _name, ProtocolGame* p):
  60.     Creature(), transferContainer(ITEM_LOCKER), name(_name), nameDescription(_name), client(p)
  61. {
  62.     if(client)
  63.         p->setPlayer(this);
  64.  
  65.     pvpBlessing = pzLocked = isConnecting = addAttackSkillPoint = requestedOutfit = outfitAttributes = sentChat = false;
  66.     saving = true;
  67.  
  68.     lastAttackBlockType = BLOCK_NONE;
  69.     chaseMode = CHASEMODE_STANDSTILL;
  70.     fightMode = FIGHTMODE_ATTACK;
  71.     tradeState = TRADE_NONE;
  72.     accountManager = MANAGER_NONE;
  73.     guildLevel = GUILDLEVEL_NONE;
  74.     vocationId = VOCATION_NONE;
  75.  
  76.     promotionLevel = walkTaskEvent = actionTaskEvent = nextStepEvent = bloodHitCount = shieldBlockCount = 0;
  77.     mailAttempts = idleTime = marriage = blessings = balance = premiumDays = mana = manaMax = manaSpent = 0;
  78.     soul = guildId = levelPercent = magLevelPercent = magLevel = experience = damageImmunities = rankId = 0;
  79.     conditionImmunities = conditionSuppressions = groupId = managerNumber2 = town = skullEnd = 0;
  80.     lastLogin = lastLogout = lastIP = messageTicks = messageBuffer = nextAction = editListId = maxWriteLen = 0;
  81.     windowTextId = nextExAction = offlineTrainingTime = lastStatsTrainingTime = 0;
  82.  
  83.     purchaseCallback = saleCallback = offlineTrainingSkill = -1;
  84.     level = 1;
  85.     rates[SKILL__MAGLEVEL] = rates[SKILL__LEVEL] = 1.0f;
  86.     soulMax = 100;
  87.     capacity = 400.00;
  88.     stamina = STAMINA_MAX;
  89.     lastLoad = lastPing = lastPong = lastAttack = lastMail = OTSYS_TIME();
  90.  
  91.     writeItem = NULL;
  92.     group = NULL;
  93.     editHouse = NULL;
  94.     tradeItem = NULL;
  95.     tradePartner = NULL;
  96.     walkTask = NULL;
  97.     weapon = NULL;
  98.     bed = NULL;
  99.  
  100.     setVocation(0);
  101.     setParty(NULL);
  102.  
  103.     transferContainer.setParent(NULL);
  104.     for(int32_t i = 0; i < 11; ++i)
  105.     {
  106.         inventory[i] = NULL;
  107.         inventoryAbilities[i] = false;
  108.     }
  109.  
  110.     for(int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i)
  111.     {
  112.         skills[i][SKILL_LEVEL] = 10;
  113.         skills[i][SKILL_TRIES] = skills[i][SKILL_PERCENT] = 0;
  114.         rates[i] = 1.0f;
  115.     }
  116.  
  117.     for(int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i)
  118.         varSkills[i] = 0;
  119.  
  120.     for(int32_t i = STAT_FIRST; i <= STAT_LAST; ++i)
  121.         varStats[i] = 0;
  122.  
  123.     for(int32_t i = LOSS_FIRST; i <= LOSS_LAST; ++i)
  124.         lossPercent[i] = 100;
  125.  
  126.     for(int32_t i = 0; i <= 12; ++i)
  127.         talkState[i] = false;
  128. #ifdef __ENABLE_SERVER_DIAGNOSTIC__
  129.  
  130.     playerCount++;
  131. #endif
  132. }
  133.  
  134. Player::~Player()
  135. {
  136. #ifdef __ENABLE_SERVER_DIAGNOSTIC__
  137.     playerCount--;
  138. #endif
  139.     for(int32_t i = 0; i < 11; ++i)
  140.     {
  141.         if(!inventory[i])
  142.             continue;
  143.  
  144.         inventory[i]->setParent(NULL);
  145.         inventory[i]->unRef();
  146.  
  147.         inventory[i] = NULL;
  148.         inventoryAbilities[i] = false;
  149.     }
  150.  
  151.     setWriteItem(NULL);
  152.     setNextWalkActionTask(NULL);
  153.  
  154.     transferContainer.setParent(NULL);
  155.     for(DepotMap::iterator it = depots.begin(); it != depots.end(); ++it)
  156.         it->second.first->unRef();
  157. }
  158.  
  159. void Player::setVocation(uint32_t id)
  160. {
  161.     vocationId = id;
  162.     if(!(vocation = Vocations::getInstance()->getVocation(id)))
  163.         return;
  164.  
  165.     Creature::setDropLoot((vocation->getDropLoot() ? LOOT_DROP_FULL : LOOT_DROP_PREVENT));
  166.     Creature::setLossSkill(vocation->getLossSkill());
  167.  
  168.     soulMax = vocation->getGain(GAIN_SOUL);
  169.     if(Condition* condition = getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT))
  170.     {
  171.         condition->setParam(CONDITIONPARAM_HEALTHGAIN, vocation->getGainAmount(GAIN_HEALTH));
  172.         condition->setParam(CONDITIONPARAM_HEALTHTICKS, (vocation->getGainTicks(GAIN_HEALTH) * 1000));
  173.         condition->setParam(CONDITIONPARAM_MANAGAIN, vocation->getGainAmount(GAIN_MANA));
  174.         condition->setParam(CONDITIONPARAM_MANATICKS, (vocation->getGainTicks(GAIN_MANA) * 1000));
  175.     }
  176. }
  177.  
  178. void Player::setDropLoot(lootDrop_t _lootDrop)
  179. {
  180.     if(vocation && !vocation->getDropLoot())
  181.         _lootDrop = LOOT_DROP_PREVENT;
  182.  
  183.     Creature::setDropLoot(_lootDrop);
  184. }
  185.  
  186. void Player::setLossSkill(bool _skillLoss)
  187. {
  188.     if(vocation && !vocation->getLossSkill())
  189.         _skillLoss = false;
  190.  
  191.     Creature::setLossSkill(_skillLoss);
  192. }
  193.  
  194. bool Player::isPushable() const
  195. {
  196.     return accountManager == MANAGER_NONE && !hasFlag(PlayerFlag_CannotBePushed) && Creature::isPushable();
  197. }
  198.  
  199. std::string Player::getDescription(int32_t lookDistance) const
  200. {
  201.     std::stringstream s;
  202.     if(lookDistance == -1)
  203.     {
  204.         s << "yourself.";
  205.         if(hasFlag(PlayerFlag_ShowGroupNameInsteadOfVocation))
  206.             s << " You are " << group->getName();
  207.         else if(vocationId != VOCATION_NONE)
  208.             s << " You are " << vocation->getDescription();
  209.         else
  210.             s << " You have no vocation";
  211.     }
  212.     else
  213.     {
  214.         s << nameDescription;
  215.         if(!hasCustomFlag(PlayerCustomFlag_HideLevel))
  216.             s << " (Level " << level << ")";
  217.  
  218.         s << ". " << (sex % 2 ? "He" : "She");
  219.         if(hasFlag(PlayerFlag_ShowGroupNameInsteadOfVocation))
  220.             s << " is " << group->getName();
  221.         else if(vocationId != VOCATION_NONE)
  222.             s << " is " << vocation->getDescription();
  223.         else
  224.             s << " has no vocation";
  225.     }
  226.  
  227.     std::string tmp;
  228.     if(marriage && IOLoginData::getInstance()->getNameByGuid(marriage, tmp))
  229.     {
  230.         s << ", ";
  231.         if(vocationId == VOCATION_NONE)
  232.         {
  233.             if(lookDistance == -1)
  234.                 s << "and you are";
  235.             else
  236.                 s << "and is";
  237.  
  238.             s << " ";
  239.         }
  240.  
  241.         s << (sex % 2 ? "husband" : "wife") << " of " << tmp;
  242.     }
  243.  
  244.     s << ".";
  245.     if(guildId)
  246.     {
  247.         if(lookDistance == -1)
  248.             s << " You are ";
  249.         else
  250.             s << " " << (sex % 2 ? "He" : "She") << " is ";
  251.  
  252.         s << (rankName.empty() ? "a member" : rankName)<< " of the " << guildName;
  253.         if(!guildNick.empty())
  254.             s << " (" << guildNick << ")";
  255.  
  256.         s << ".";
  257.     }
  258.  
  259.     s << getSpecialDescription();
  260.     return s.str();
  261. }
  262.  
  263. Item* Player::getInventoryItem(slots_t slot) const
  264. {
  265.     if(slot > SLOT_PRE_FIRST && slot < SLOT_LAST)
  266.         return inventory[slot];
  267.  
  268.     if(slot == SLOT_HAND)
  269.         return inventory[SLOT_LEFT] ? inventory[SLOT_LEFT] : inventory[SLOT_RIGHT];
  270.  
  271.     return NULL;
  272. }
  273.  
  274. Item* Player::getEquippedItem(slots_t slot) const
  275. {
  276.     Item* item = getInventoryItem(slot);
  277.     if(!item)
  278.         return NULL;
  279.  
  280.     switch(slot)
  281.     {
  282.         case SLOT_LEFT:
  283.         case SLOT_RIGHT:
  284.             if(item->getWieldPosition() == SLOT_HAND)
  285.                 return item;
  286.  
  287.         default:
  288.             break;
  289.     }
  290.  
  291.     return item->getWieldPosition() == slot ? item : NULL;
  292. }
  293.  
  294. void Player::setConditionSuppressions(uint32_t conditions, bool remove)
  295. {
  296.     if(remove)
  297.         conditionSuppressions &= ~conditions;
  298.     else
  299.         conditionSuppressions |= conditions;
  300. }
  301.  
  302. Item* Player::getWeapon(bool ignoreAmmo)
  303. {
  304.     if(!ignoreAmmo && weapon)
  305.         return weapon;
  306.  
  307.     Item* item = NULL;
  308.     for(int32_t slot = SLOT_RIGHT; slot <= SLOT_LEFT; ++slot)
  309.     {
  310.         if(!(item = getEquippedItem((slots_t)slot)) || item->getWeaponType() != WEAPON_DIST)
  311.             continue;
  312.  
  313.         if(!ignoreAmmo && item->getAmmoType() != AMMO_NONE)
  314.         {
  315.             Item* ammoItem = getInventoryItem(SLOT_AMMO);
  316.             if(ammoItem && ammoItem->getAmmoType() == item->getAmmoType() && ammoItem->getWeaponType() != WEAPON_DIST)
  317.             {
  318.                 if(g_weapons->getWeapon(ammoItem))
  319.                     return ammoItem;
  320.             }
  321.         }
  322.         else if(g_weapons->getWeapon(item))
  323.             return item;
  324.     }
  325.  
  326.     return NULL;
  327. }
  328.  
  329. ItemVector Player::getWeapons() const
  330. {
  331.     Item* item = NULL;
  332.     ItemVector weapons;
  333.     for(int32_t slot = SLOT_RIGHT; slot <= SLOT_LEFT; ++slot)
  334.     {
  335.         if(!(item = getEquippedItem((slots_t)slot)))
  336.             continue;
  337.  
  338.         switch(item->getWeaponType())
  339.         {
  340.             case WEAPON_SHIELD:
  341.                 break;
  342.  
  343.             case WEAPON_DIST:
  344.             {
  345.                 if(item->getAmmoType() != AMMO_NONE)
  346.                 {
  347.                     Item* ammoItem = getInventoryItem(SLOT_AMMO);
  348.                     if(ammoItem && ammoItem->getAmmoType() == item->getAmmoType() && ammoItem->getWeaponType() != WEAPON_DIST)
  349.                         item = ammoItem;
  350.                     else
  351.                         break;
  352.                 }
  353.             }
  354.  
  355.             default:
  356.             {
  357.                 if(g_weapons->getWeapon(item))
  358.                     weapons.push_back(item);
  359.  
  360.                 break;
  361.             }
  362.         }
  363.     }
  364.  
  365.     return weapons;
  366. }
  367.  
  368. void Player::updateWeapon()
  369. {
  370.     ItemVector weapons = getWeapons();
  371.     if(weapons.empty())
  372.         weapon = NULL;
  373.     else if(!weapon || weapons.size() == 1 || weapons[1] == weapon)
  374.         weapon = weapons[0];
  375.     else if(weapons[0] == weapon)
  376.         weapon = weapons[1];
  377.     else
  378.         weapon = NULL;
  379. }
  380.  
  381. WeaponType_t Player::getWeaponType()
  382. {
  383.     if(weapon)
  384.         return weapon->getWeaponType();
  385.  
  386.     return WEAPON_NONE;
  387. }
  388.  
  389. int32_t Player::getWeaponSkill(const Item* item) const
  390. {
  391.     if(!item)
  392.         return getSkill(SKILL_FIST, SKILL_LEVEL);
  393.  
  394.     switch(item->getWeaponType())
  395.     {
  396.         case WEAPON_SWORD:
  397.             return getSkill(SKILL_SWORD, SKILL_LEVEL);
  398.  
  399.         case WEAPON_CLUB:
  400.             return getSkill(SKILL_CLUB, SKILL_LEVEL);
  401.  
  402.         case WEAPON_AXE:
  403.             return getSkill(SKILL_AXE, SKILL_LEVEL);
  404.  
  405.         case WEAPON_FIST:
  406.             return getSkill(SKILL_FIST, SKILL_LEVEL);
  407.  
  408.         case WEAPON_DIST:
  409.         case WEAPON_AMMO:
  410.             return getSkill(SKILL_DIST, SKILL_LEVEL);
  411.  
  412.         default:
  413.             break;
  414.     }
  415.  
  416.     return 0;
  417. }
  418.  
  419. int32_t Player::getArmor() const
  420. {
  421.     int32_t i = SLOT_FIRST, armor = 0;
  422.     for(; i < SLOT_LAST; ++i)
  423.     {
  424.         if(Item* item = getInventoryItem((slots_t)i))
  425.             armor += item->getArmor();
  426.     }
  427.  
  428.     if(vocation->getMultiplier(MULTIPLIER_ARMOR) != 1.0)
  429.         return int32_t(armor * vocation->getMultiplier(MULTIPLIER_ARMOR));
  430.  
  431.     return armor;
  432. }
  433.  
  434. void Player::getShieldAndWeapon(const Item* &_shield, const Item* &_weapon) const
  435. {
  436.     _shield = NULL;
  437.     Item* item = NULL;
  438.     for(uint32_t slot = SLOT_RIGHT; slot <= SLOT_LEFT; ++slot)
  439.     {
  440.         if(!(item = getInventoryItem((slots_t)slot)) || item->getWeaponType() != WEAPON_SHIELD)
  441.             continue;
  442.  
  443.         if(!_shield || (_shield && item->getDefense() > _shield->getDefense()))
  444.             _shield = item;
  445.     }
  446.  
  447.     _weapon = weapon;
  448. }
  449.  
  450. int32_t Player::getDefense() const
  451. {
  452.     int32_t baseDefense = 5, defenseValue = 0, defenseSkill = 0, extraDefense = 0;
  453.     float defenseFactor = getDefenseFactor();
  454.  
  455.     const Item *_weapon = NULL, *_shield = NULL;
  456.     getShieldAndWeapon(_shield, _weapon);
  457.     if(_weapon)
  458.     {
  459.         extraDefense = _weapon->getExtraDefense();
  460.         defenseValue = baseDefense + _weapon->getDefense();
  461.         defenseSkill = getWeaponSkill(_weapon);
  462.     }
  463.  
  464.     if(_shield && _shield->getDefense() > defenseValue)
  465.     {
  466.         if(_shield->getExtraDefense() > extraDefense)
  467.             extraDefense = _shield->getExtraDefense();
  468.  
  469.         defenseValue = baseDefense + _shield->getDefense();
  470.         defenseSkill = getSkill(SKILL_SHIELD, SKILL_LEVEL);
  471.     }
  472.  
  473.     if(!defenseSkill)
  474.         return 0;
  475.  
  476.     defenseValue += extraDefense;
  477.     if(vocation->getMultiplier(MULTIPLIER_DEFENSE) != 1.0)
  478.         defenseValue = int32_t(defenseValue * vocation->getMultiplier(MULTIPLIER_DEFENSE));
  479.  
  480.     return ((int32_t)std::ceil(((float)(defenseSkill * (defenseValue * 0.015)) + (defenseValue * 0.1)) * defenseFactor));
  481. }
  482.  
  483. float Player::getAttackFactor() const
  484. {
  485.     switch(fightMode)
  486.     {
  487.         case FIGHTMODE_BALANCED:
  488.             return 1.2f;
  489.  
  490.         case FIGHTMODE_DEFENSE:
  491.             return 2.0f;
  492.  
  493.         case FIGHTMODE_ATTACK:
  494.         default:
  495.             break;
  496.     }
  497.  
  498.     return 1.0f;
  499. }
  500.  
  501. float Player::getDefenseFactor() const
  502. {
  503.     switch(fightMode)
  504.     {
  505.         case FIGHTMODE_BALANCED:
  506.             return 1.2f;
  507.  
  508.         case FIGHTMODE_DEFENSE:
  509.         {
  510.             if((OTSYS_TIME() - lastAttack) < getAttackSpeed()) //attacking will cause us to get into normal defense
  511.                 return 1.0f;
  512.  
  513.             return 2.0f;
  514.         }
  515.  
  516.         case FIGHTMODE_ATTACK:
  517.         default:
  518.             break;
  519.     }
  520.  
  521.     return 1.0f;
  522. }
  523.  
  524. void Player::sendIcons() const
  525. {
  526.     if(!client)
  527.         return;
  528.  
  529.     uint32_t icons = ICON_NONE;
  530.     for(ConditionList::const_iterator it = conditions.begin(); it != conditions.end(); ++it)
  531.     {
  532.         if(!isSuppress((*it)->getType()))
  533.             icons |= (*it)->getIcons();
  534.     }
  535.  
  536.     if(getZone() == ZONE_PROTECTION)
  537.     {
  538.         icons |= ICON_NONE;
  539.  
  540.         if(hasBitSet(ICON_SWORDS, icons))
  541.             icons &= ~ICON_SWORDS;
  542.     }
  543.  
  544.     if(pzLocked)
  545.         icons |= ICON_NONE;
  546.  
  547.     // Tibia client debugs with 10 or more icons
  548.     // so let's prevent that from happening.
  549.     std::bitset<20> icon_bitset((uint64_t)icons);
  550.     for(size_t i = 0, size = icon_bitset.size(); i < size; ++i)
  551.     {
  552.         if(icon_bitset.count() < 10)
  553.             break;
  554.  
  555.         if(icon_bitset[i])
  556.             icon_bitset.reset(i);
  557.     }
  558.     client->sendIcons(icon_bitset.to_ulong());
  559. }
  560.  
  561. void Player::updateInventoryWeight()
  562. {
  563.     inventoryWeight = 0.00;
  564.     if(hasFlag(PlayerFlag_HasInfiniteCapacity)
  565.         || !g_config.getBool(ConfigManager::USE_CAPACITY))
  566.         return;
  567.  
  568.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  569.     {
  570.         if(Item* item = getInventoryItem((slots_t)i))
  571.             inventoryWeight += item->getWeight();
  572.     }
  573. }
  574.  
  575. int32_t Player::getPlayerInfo(playerinfo_t playerinfo) const
  576. {
  577.     switch(playerinfo)
  578.     {
  579.         case PLAYERINFO_LEVEL:
  580.             return level;
  581.         case PLAYERINFO_LEVELPERCENT:
  582.             return levelPercent;
  583.         case PLAYERINFO_MAGICLEVEL:
  584.             return std::max((int32_t)0, ((int32_t)magLevel + varStats[STAT_MAGICLEVEL]));
  585.         case PLAYERINFO_MAGICLEVELPERCENT:
  586.             return magLevelPercent;
  587.         case PLAYERINFO_HEALTH:
  588.             return health;
  589.         case PLAYERINFO_MAXHEALTH:
  590.             return std::max((int32_t)1, ((int32_t)healthMax + varStats[STAT_MAXHEALTH]));
  591.         case PLAYERINFO_MANA:
  592.             return mana;
  593.         case PLAYERINFO_MAXMANA:
  594.             return std::max((int32_t)0, ((int32_t)manaMax + varStats[STAT_MAXMANA]));
  595.         case PLAYERINFO_SOUL:
  596.             return std::max((int32_t)0, ((int32_t)soul + varStats[STAT_SOUL]));
  597.         default:
  598.             break;
  599.     }
  600.  
  601.     return 0;
  602. }
  603.  
  604. int32_t Player::getSkill(skills_t skilltype, skillsid_t skillinfo) const
  605. {
  606.     int32_t ret = skills[skilltype][skillinfo];
  607.     if(skillinfo == SKILL_LEVEL)
  608.         ret += varSkills[skilltype];
  609.  
  610.     return std::max((int32_t)0, ret);
  611. }
  612.  
  613. void Player::addSkillAdvance(skills_t skill, uint64_t count, bool useMultiplier/* = true*/)
  614. {
  615.     if(!count)
  616.         return;
  617.  
  618.     //player has reached max skill
  619.     uint64_t currReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL]),
  620.         nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  621.     if(currReqTries > nextReqTries)
  622.         return;
  623.  
  624.     if(useMultiplier)
  625.         count = uint64_t((double)count * rates[skill] * g_config.getDouble(ConfigManager::RATE_SKILL));
  626.  
  627.     std::stringstream s;
  628.     while(skills[skill][SKILL_TRIES] + count >= nextReqTries)
  629.     {
  630.         count -= nextReqTries - skills[skill][SKILL_TRIES];
  631.         skills[skill][SKILL_TRIES] = skills[skill][SKILL_PERCENT] = 0;
  632.         skills[skill][SKILL_LEVEL]++;
  633.  
  634.         s.str("");
  635.         s << "You advanced to " << getSkillName(skill) << " level " << skills[skill][SKILL_LEVEL] << ".";
  636.         sendTextMessage(MSG_EVENT_ADVANCE, s.str().c_str());
  637.  
  638.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  639.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  640.             (*it)->executeAdvance(this, skill, (skills[skill][SKILL_LEVEL] - 1), skills[skill][SKILL_LEVEL]);
  641.  
  642.         currReqTries = nextReqTries;
  643.         nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  644.         if(currReqTries > nextReqTries)
  645.         {
  646.             count = 0;
  647.             break;
  648.         }
  649.     }
  650.  
  651.     if(count)
  652.         skills[skill][SKILL_TRIES] += count;
  653.  
  654.     //update percent
  655.     uint16_t newPercent = Player::getPercentLevel(skills[skill][SKILL_TRIES], nextReqTries);
  656.     if(skills[skill][SKILL_PERCENT] != newPercent)
  657.     {
  658.         skills[skill][SKILL_PERCENT] = newPercent;
  659.         sendSkills();
  660.     }
  661.     else if(!s.str().empty())
  662.         sendSkills();
  663. }
  664.  
  665. void Player::setVarStats(stats_t stat, int32_t modifier)
  666. {
  667.     varStats[stat] += modifier;
  668.     switch(stat)
  669.     {
  670.         case STAT_MAXHEALTH:
  671.         {
  672.             if(getHealth() > getMaxHealth())
  673.                 Creature::changeHealth(getMaxHealth() - getHealth());
  674.             else
  675.                 g_game.addCreatureHealth(this);
  676.  
  677.             break;
  678.         }
  679.  
  680.         case STAT_MAXMANA:
  681.         {
  682.             if(getMana() > getMaxMana())
  683.                 Creature::changeMana(getMaxMana() - getMana());
  684.  
  685.             break;
  686.         }
  687.  
  688.         default:
  689.             break;
  690.     }
  691. }
  692.  
  693. int32_t Player::getDefaultStats(stats_t stat)
  694. {
  695.     switch(stat)
  696.     {
  697.         case STAT_MAGICLEVEL:
  698.             return getMagicLevel() - getVarStats(STAT_MAGICLEVEL);
  699.         case STAT_MAXHEALTH:
  700.             return getMaxHealth() - getVarStats(STAT_MAXHEALTH);
  701.         case STAT_MAXMANA:
  702.             return getMaxMana() - getVarStats(STAT_MAXMANA);
  703.         case STAT_SOUL:
  704.             return getSoul() - getVarStats(STAT_SOUL);
  705.         default:
  706.             break;
  707.     }
  708.  
  709.     return 0;
  710. }
  711.  
  712. Container* Player::getContainer(uint32_t cid)
  713. {
  714.     for(ContainerVector::iterator it = containerVec.begin(); it != containerVec.end(); ++it)
  715.     {
  716.         if(it->first == cid)
  717.             return it->second;
  718.     }
  719.  
  720.     return NULL;
  721. }
  722.  
  723. int32_t Player::getContainerID(const Container* container) const
  724. {
  725.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  726.     {
  727.         if(cl->second == container)
  728.             return cl->first;
  729.     }
  730.  
  731.     return -1;
  732. }
  733.  
  734. void Player::addContainer(uint32_t cid, Container* container)
  735. {
  736. #ifdef __DEBUG__
  737.     std::clog << getName() << ", addContainer: " << (int32_t)cid << std::endl;
  738. #endif
  739.     if(cid > 0xF)
  740.         return;
  741.  
  742.     for(ContainerVector::iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  743.     {
  744.         if(cl->first == cid)
  745.         {
  746.             cl->second = container;
  747.             return;
  748.         }
  749.     }
  750.  
  751.     containerVec.push_back(std::make_pair(cid, container));
  752. }
  753.  
  754. void Player::closeContainer(uint32_t cid)
  755. {
  756.     for(ContainerVector::iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  757.     {
  758.         if(cl->first == cid)
  759.         {
  760.             containerVec.erase(cl);
  761.             break;
  762.         }
  763.     }
  764. #ifdef __DEBUG__
  765.  
  766.     std::clog << getName() << ", closeContainer: " << (int32_t)cid << std::endl;
  767. #endif
  768. }
  769.  
  770. bool Player::canOpenCorpse(uint32_t ownerId)
  771. {
  772.     return guid == ownerId || (party && party->canOpenCorpse(ownerId)) || hasCustomFlag(PlayerCustomFlag_GamemasterPrivileges);
  773. }
  774.  
  775. uint16_t Player::getLookCorpse() const
  776. {
  777.     return (sex % 2) ? ITEM_MALE_CORPSE : ITEM_FEMALE_CORPSE;
  778. }
  779.  
  780. void Player::dropLoot(Container* corpse)
  781. {
  782.     if(!corpse || lootDrop != LOOT_DROP_FULL)
  783.         return;
  784.  
  785.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  786.     {
  787.         Item* item = inventory[i];
  788.         if(!item)
  789.             continue;
  790.  
  791.         uint32_t tmp = random_range(1, 100);
  792.         if(skull > SKULL_WHITE || (item->getContainer() && tmp < (lossPercent[LOSS_CONTAINERS])) || (!item->getContainer() && tmp < (lossPercent[LOSS_ITEMS])))
  793.         {
  794.             g_game.internalMoveItem(NULL, this, corpse, INDEX_WHEREEVER, item, item->getItemCount(), 0);
  795.             sendRemoveInventoryItem((slots_t)i, inventory[(slots_t)i]);
  796.         }
  797.     }
  798. }
  799.  
  800. bool Player::setStorage(const std::string& key, const std::string& value)
  801. {
  802.     uint32_t numericKey = atol(key.c_str());
  803.     if(!IS_IN_KEYRANGE(numericKey, RESERVED_RANGE))
  804.     {
  805.         if(!Creature::setStorage(key, value))
  806.             return false;
  807.  
  808.         if(Quests::getInstance()->isQuestStorage(key, value, true))
  809.             onUpdateQuest();
  810.  
  811.         return true;
  812.     }
  813.  
  814.     if(IS_IN_KEYRANGE(numericKey, OUTFITS_RANGE))
  815.     {
  816.         uint32_t lookType = atoi(value.c_str()) >> 16, addons = atoi(value.c_str()) & 0xFF;
  817.         if(addons < 4)
  818.         {
  819.             Outfit outfit;
  820.             if(Outfits::getInstance()->getOutfit(lookType, outfit))
  821.                 return addOutfit(outfit.outfitId, addons);
  822.         }
  823.         else
  824.             std::clog << "[Warning - Player::setStorage] Invalid addons value key: " << key
  825.                 << ", value: " << value << " for player: " << getName() << std::endl;
  826.     }
  827.     else if(IS_IN_KEYRANGE(numericKey, OUTFITSID_RANGE))
  828.     {
  829.         uint32_t outfitId = atoi(value.c_str()) >> 16, addons = atoi(value.c_str()) & 0xFF;
  830.         if(addons < 4)
  831.             return addOutfit(outfitId, addons);
  832.         else
  833.             std::clog << "[Warning - Player::setStorage] Invalid addons value key: " << key
  834.                 << ", value: " << value << " for player: " << getName() << std::endl;
  835.     }
  836.     else
  837.         std::clog << "[Warning - Player::setStorage] Unknown reserved key: " << key << " for player: " << getName() << std::endl;
  838.  
  839.     return false;
  840. }
  841.  
  842. void Player::eraseStorage(const std::string& key)
  843. {
  844.     Creature::eraseStorage(key);
  845.     if(IS_IN_KEYRANGE(atol(key.c_str()), RESERVED_RANGE))
  846.         std::clog << "[Warning - Player::eraseStorage] Unknown reserved key: " << key << " for player: " << name << std::endl;
  847. }
  848.  
  849. bool Player::canSee(const Position& pos) const
  850. {
  851.     if(client)
  852.         return client->canSee(pos);
  853.  
  854.     return false;
  855. }
  856.  
  857. bool Player::canSeeCreature(const Creature* creature) const
  858. {
  859.     if(creature == this)
  860.         return true;
  861.  
  862.     if(const Player* player = creature->getPlayer())
  863.         return !player->isGhost() || getGhostAccess() >= player->getGhostAccess();
  864.  
  865.     return !creature->isInvisible() || canSeeInvisibility();
  866. }
  867.  
  868. bool Player::canWalkthrough(const Creature* creature) const
  869. {
  870.     if(creature == this || hasFlag(PlayerFlag_CanPassThroughAllCreatures) || creature->isWalkable() ||
  871.         (creature->getMaster() && creature->getMaster() != this && canWalkthrough(creature->getMaster())))
  872.         return true;
  873.  
  874.     const Player* player = creature->getPlayer();
  875.     if(!player)
  876.         return false;
  877.  
  878.     if(((g_game.getWorldType() == WORLDTYPE_OPTIONAL &&
  879.         !player->isProtected()) || player->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) || player->isProtected()) && player->getTile()->ground
  880.         && Item::items[player->getTile()->ground->getID()].walkStack && (!player->hasCustomFlag(PlayerCustomFlag_GamemasterPrivileges)
  881.         || player->getAccess() <= getAccess()))
  882.         return true;
  883.  
  884.     return (player->isGhost() && getGhostAccess() < player->getGhostAccess())
  885.         || (isGhost() && getGhostAccess() > player->getGhostAccess());
  886. }
  887.  
  888. Depot* Player::getDepot(uint32_t depotId, bool autoCreateDepot)
  889. {
  890.     DepotMap::iterator it = depots.find(depotId);
  891.     if(it != depots.end())
  892.         return it->second.first;
  893.  
  894.     //create a new depot?
  895.     if(autoCreateDepot)
  896.     {
  897.         Item* locker = Item::CreateItem(ITEM_LOCKER);
  898.         if(Container* container = locker->getContainer())
  899.         {
  900.             if(Depot* depot = container->getDepot())
  901.             {
  902.                 container->__internalAddThing(Item::CreateItem(ITEM_DEPOT));
  903.                 internalAddDepot(depot, depotId);
  904.                 return depot;
  905.             }
  906.         }
  907.  
  908.         g_game.freeThing(locker);
  909.         std::clog << "Failure: Creating a new depot with id: " << depotId <<
  910.             ", for player: " << getName() << std::endl;
  911.     }
  912.  
  913.     return NULL;
  914. }
  915.  
  916. bool Player::addDepot(Depot* depot, uint32_t depotId)
  917. {
  918.     if(getDepot(depotId, false))
  919.         return false;
  920.  
  921.     internalAddDepot(depot, depotId);
  922.     return true;
  923. }
  924.  
  925. void Player::internalAddDepot(Depot* depot, uint32_t depotId)
  926. {
  927.     depots[depotId] = std::make_pair(depot, false);
  928.     depot->setMaxDepotLimit((group != NULL ? group->getDepotLimit(isPremium()) : 1000));
  929. }
  930.  
  931. void Player::useDepot(uint32_t depotId, bool value)
  932. {
  933.     DepotMap::iterator it = depots.find(depotId);
  934.     if(it != depots.end())
  935.         depots[depotId] = std::make_pair(it->second.first, value);
  936. }
  937.  
  938. void Player::sendCancelMessage(ReturnValue message) const
  939. {
  940.     switch(message)
  941.     {
  942.         case RET_DESTINATIONOUTOFREACH:
  943.             sendCancel("Destination is out of reach.");
  944.             break;
  945.  
  946.         case RET_NOTMOVABLE:
  947.             sendCancel("You cannot move this object.");
  948.             break;
  949.  
  950.         case RET_DROPTWOHANDEDITEM:
  951.             sendCancel("Drop the double-handed object first.");
  952.             break;
  953.  
  954.         case RET_BOTHHANDSNEEDTOBEFREE:
  955.             sendCancel("Both hands need to be free.");
  956.             break;
  957.  
  958.         case RET_CANNOTBEDRESSED:
  959.             sendCancel("You cannot dress this object there.");
  960.             break;
  961.  
  962.         case RET_PUTTHISOBJECTINYOURHAND:
  963.             sendCancel("Put this object in your hand.");
  964.             break;
  965.  
  966.         case RET_PUTTHISOBJECTINBOTHHANDS:
  967.             sendCancel("Put this object in both hands.");
  968.             break;
  969.  
  970.         case RET_CANONLYUSEONEWEAPON:
  971.             sendCancel("You may use only one weapon.");
  972.             break;
  973.  
  974.         case RET_TOOFARAWAY:
  975.             sendCancel("Too far away.");
  976.             break;
  977.  
  978.         case RET_FIRSTGODOWNSTAIRS:
  979.             sendCancel("First go downstairs.");
  980.             break;
  981.  
  982.         case RET_FIRSTGOUPSTAIRS:
  983.             sendCancel("First go upstairs.");
  984.             break;
  985.  
  986.         case RET_NOTENOUGHCAPACITY:
  987.             sendCancel("This object is too heavy for you to carry.");
  988.             break;
  989.  
  990.         case RET_CONTAINERNOTENOUGHROOM:
  991.             sendCancel("You cannot put more objects in this container.");
  992.             break;
  993.  
  994.         case RET_NEEDEXCHANGE:
  995.         case RET_NOTENOUGHROOM:
  996.             sendCancel("There is not enough room.");
  997.             break;
  998.  
  999.         case RET_CANNOTPICKUP:
  1000.             sendCancel("You cannot take this object.");
  1001.             break;
  1002.  
  1003.         case RET_CANNOTTHROW:
  1004.             sendCancel("You cannot throw there.");
  1005.             break;
  1006.  
  1007.         case RET_THEREISNOWAY:
  1008.             sendCancel("There is no way.");
  1009.             break;
  1010.  
  1011.         case RET_THISISIMPOSSIBLE:
  1012.             sendCancel("This is impossible.");
  1013.             break;
  1014.  
  1015.         case RET_PLAYERISPZLOCKED:
  1016.             sendCancel("You cannot enter a protection zone after attacking another player.");
  1017.             break;
  1018.  
  1019.         case RET_PLAYERISNOTINVITED:
  1020.             sendCancel("You are not invited.");
  1021.             break;
  1022.  
  1023.         case RET_CREATUREDOESNOTEXIST:
  1024.             sendCancel("Creature does not exist.");
  1025.             break;
  1026.  
  1027.         case RET_DEPOTISFULL:
  1028.             sendCancel("Your depot is full. Remove surplus items before storing new ones.");
  1029.             break;
  1030.  
  1031.         case RET_CANNOTUSETHISOBJECT:
  1032.             sendCancel("You cannot use this object.");
  1033.             break;
  1034.  
  1035.         case RET_PLAYERWITHTHISNAMEISNOTONLINE:
  1036.             sendCancel("A player with this name is not online.");
  1037.             break;
  1038.  
  1039.         case RET_NOTREQUIREDLEVELTOUSERUNE:
  1040.             sendCancel("You do not have the required magic level to use this rune.");
  1041.             break;
  1042.  
  1043.         case RET_YOUAREALREADYTRADING:
  1044.             sendCancel("You are already trading. Finish this trade first.");
  1045.             break;
  1046.  
  1047.         case RET_THISPLAYERISALREADYTRADING:
  1048.             sendCancel("This person is already trading.");
  1049.             break;
  1050.  
  1051.         case RET_YOUMAYNOTLOGOUTDURINGAFIGHT:
  1052.             sendCancel("You may not logout during or immediately after a fight.");
  1053.             break;
  1054.  
  1055.         case RET_DIRECTPLAYERSHOOT:
  1056.             sendCancel("You are not allowed to shoot directly on players.");
  1057.             break;
  1058.  
  1059.         case RET_NOTENOUGHLEVEL:
  1060.             sendCancel("You do not have enough level.");
  1061.             break;
  1062.  
  1063.         case RET_NOTENOUGHMAGICLEVEL:
  1064.             sendCancel("You do not have enough magic level.");
  1065.             break;
  1066.  
  1067.         case RET_NOTENOUGHMANA:
  1068.             sendCancel("You do not have enough mana.");
  1069.             break;
  1070.  
  1071.         case RET_NOTENOUGHSOUL:
  1072.             sendCancel("You do not have enough soul.");
  1073.             break;
  1074.  
  1075.         case RET_YOUAREEXHAUSTED:
  1076.             sendCancel("You are exhausted.");
  1077.             break;
  1078.  
  1079.         case RET_CANONLYUSETHISRUNEONCREATURES:
  1080.             sendCancel("You can only use this rune on creatures.");
  1081.             break;
  1082.  
  1083.         case RET_PLAYERISNOTREACHABLE:
  1084.             sendCancel("Player is not reachable.");
  1085.             break;
  1086.  
  1087.         case RET_CREATUREISNOTREACHABLE:
  1088.             sendCancel("Creature is not reachable.");
  1089.             break;
  1090.  
  1091.         case RET_ACTIONNOTPERMITTEDINPROTECTIONZONE:
  1092.             sendCancel("This action is not permitted in a protection zone.");
  1093.             break;
  1094.  
  1095.         case RET_YOUMAYNOTATTACKTHISPLAYER:
  1096.             sendCancel("You may not attack this player.");
  1097.             break;
  1098.  
  1099.         case RET_YOUMAYNOTATTACKTHISCREATURE:
  1100.             sendCancel("You may not attack this creature.");
  1101.             break;
  1102.  
  1103.         case RET_YOUMAYNOTATTACKAPERSONINPROTECTIONZONE:
  1104.             sendCancel("You may not attack a person in a protection zone.");
  1105.             break;
  1106.  
  1107.         case RET_YOUMAYNOTATTACKAPERSONWHILEINPROTECTIONZONE:
  1108.             sendCancel("You may not attack a person while you are in a protection zone.");
  1109.             break;
  1110.  
  1111.         case RET_YOUCANONLYUSEITONCREATURES:
  1112.             sendCancel("You can only use it on creatures.");
  1113.             break;
  1114.  
  1115.         case RET_TURNSECUREMODETOATTACKUNMARKEDPLAYERS:
  1116.             sendCancel("Turn secure mode off if you really want to attack unmarked players.");
  1117.             break;
  1118.  
  1119.         case RET_YOUNEEDPREMIUMACCOUNT:
  1120.             sendCancel("You need a premium account.");
  1121.             break;
  1122.  
  1123.         case RET_YOUNEEDTOLEARNTHISSPELL:
  1124.             sendCancel("You need to learn this spell first.");
  1125.             break;
  1126.  
  1127.         case RET_YOURVOCATIONCANNOTUSETHISSPELL:
  1128.             sendCancel("Your vocation cannot use this spell.");
  1129.             break;
  1130.  
  1131.         case RET_YOUNEEDAWEAPONTOUSETHISSPELL:
  1132.             sendCancel("You need to equip a weapon to use this spell.");
  1133.             break;
  1134.  
  1135.         case RET_PLAYERISPZLOCKEDLEAVEPVPZONE:
  1136.             sendCancel("You cannot leave a pvp zone after attacking another player.");
  1137.             break;
  1138.  
  1139.         case RET_PLAYERISPZLOCKEDENTERPVPZONE:
  1140.             sendCancel("You cannot enter a pvp zone after attacking another player.");
  1141.             break;
  1142.  
  1143.         case RET_ACTIONNOTPERMITTEDINANOPVPZONE:
  1144.             sendCancel("This action is not permitted in a safe zone.");
  1145.             break;
  1146.  
  1147.         case RET_YOUCANNOTLOGOUTHERE:
  1148.             sendCancel("You cannot logout here.");
  1149.             break;
  1150.  
  1151.         case RET_YOUNEEDAMAGICITEMTOCASTSPELL:
  1152.             sendCancel("You need a magic item to cast this spell.");
  1153.             break;
  1154.  
  1155.         case RET_CANNOTCONJUREITEMHERE:
  1156.             sendCancel("You cannot conjure items here.");
  1157.             break;
  1158.  
  1159.         case RET_NAMEISTOOAMBIGUOUS:
  1160.             sendCancel("Name is too ambiguous.");
  1161.             break;
  1162.  
  1163.         case RET_CANONLYUSEONESHIELD:
  1164.             sendCancel("You may use only one shield.");
  1165.             break;
  1166.  
  1167.         case RET_YOUARENOTTHEOWNER:
  1168.             sendCancel("You are not the owner.");
  1169.             break;
  1170.  
  1171.         case RET_YOUMAYNOTCASTAREAONBLACKSKULL:
  1172.             sendCancel("You may not cast area spells while you have a black skull.");
  1173.             break;
  1174.  
  1175.         case RET_TILEISFULL:
  1176.             sendCancel("You cannot add more items on this tile.");
  1177.             break;
  1178.  
  1179.         case RET_NOTENOUGHSKILL:
  1180.             sendCancel("You do not have enough skill.");
  1181.             break;
  1182.  
  1183.         case RET_NOTPOSSIBLE:
  1184.             sendCancel("Sorry, not possible.");
  1185.             break;
  1186.  
  1187.         case RET_YOUMAYNOTATTACKIMMEDIATELYAFTERLOGGINGIN:
  1188.             sendCancel("You may not attack immediately after logging in.");
  1189.             break;
  1190.  
  1191.         case RET_YOUHAVETOWAIT:
  1192.             sendCancel("Sorry, you have to wait.");
  1193.             break;
  1194.  
  1195.         case RET_YOUCANONLYTRADEUPTOX:
  1196.         {
  1197.             std::stringstream s;
  1198.             s << "You can only trade up to " << g_config.getNumber(ConfigManager::TRADE_LIMIT) << " items at a time.";
  1199.             sendCancel(s.str());
  1200.         }
  1201.             break;
  1202.  
  1203.         default:
  1204.             break;
  1205.     }
  1206. }
  1207.  
  1208. void Player::sendStats()
  1209. {
  1210.     if(client)
  1211.     {
  1212.         client->sendStats();
  1213.         lastStatsTrainingTime = getOfflineTrainingTime() / 60 / 1000;
  1214.     }
  1215. }
  1216.  
  1217. Item* Player::getWriteItem(uint32_t& _windowTextId, uint16_t& _maxWriteLen)
  1218. {
  1219.     _windowTextId = windowTextId;
  1220.     _maxWriteLen = maxWriteLen;
  1221.     return writeItem;
  1222. }
  1223.  
  1224. void Player::setWriteItem(Item* item, uint16_t _maxLen/* = 0*/)
  1225. {
  1226.     windowTextId++;
  1227.     if(writeItem)
  1228.         writeItem->unRef();
  1229.  
  1230.     if(item)
  1231.     {
  1232.         writeItem = item;
  1233.         maxWriteLen = _maxLen;
  1234.         writeItem->addRef();
  1235.     }
  1236.     else
  1237.     {
  1238.         writeItem = NULL;
  1239.         maxWriteLen = 0;
  1240.     }
  1241. }
  1242.  
  1243. House* Player::getEditHouse(uint32_t& _windowTextId, uint32_t& _listId)
  1244. {
  1245.     _windowTextId = windowTextId;
  1246.     _listId = editListId;
  1247.     return editHouse;
  1248. }
  1249.  
  1250. void Player::setEditHouse(House* house, uint32_t listId/* = 0*/)
  1251. {
  1252.     windowTextId++;
  1253.     editHouse = house;
  1254.     editListId = listId;
  1255. }
  1256.  
  1257. void Player::sendHouseWindow(House* house, uint32_t listId) const
  1258. {
  1259.     if(!client)
  1260.         return;
  1261.  
  1262.     std::string text;
  1263.     if(house->getAccessList(listId, text))
  1264.         client->sendHouseWindow(windowTextId, house, listId, text);
  1265. }
  1266.  
  1267. void Player::sendCreatureChangeVisible(const Creature* creature, Visible_t visible)
  1268. {
  1269.     if(!client)
  1270.         return;
  1271.  
  1272.     const Player* player = creature->getPlayer();
  1273.     if(player == this || (player && (visible < VISIBLE_GHOST_APPEAR || getGhostAccess() >= player->getGhostAccess()))
  1274.         || (!player && canSeeInvisibility()))
  1275.         sendCreatureChangeOutfit(creature, creature->getCurrentOutfit());
  1276.     else if(visible == VISIBLE_DISAPPEAR || visible == VISIBLE_GHOST_DISAPPEAR)
  1277.         sendCreatureDisappear(creature, creature->getTile()->getClientIndexOfThing(this, creature));
  1278.     else
  1279.         sendCreatureAppear(creature);
  1280. }
  1281.  
  1282. void Player::sendAddContainerItem(const Container* container, const Item* item)
  1283. {
  1284.     if(!client)
  1285.         return;
  1286.  
  1287.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1288.     {
  1289.         if(cl->second == container)
  1290.             client->sendAddContainerItem(cl->first, item);
  1291.     }
  1292. }
  1293.  
  1294. void Player::sendUpdateContainerItem(const Container* container, uint8_t slot, const Item*, const Item* newItem)
  1295. {
  1296.     if(!client)
  1297.         return;
  1298.  
  1299.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1300.     {
  1301.         if(cl->second == container)
  1302.             client->sendUpdateContainerItem(cl->first, slot, newItem);
  1303.     }
  1304. }
  1305.  
  1306. void Player::sendRemoveContainerItem(const Container* container, uint8_t slot, const Item*)
  1307. {
  1308.     if(!client)
  1309.         return;
  1310.  
  1311.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1312.     {
  1313.         if(cl->second == container)
  1314.             client->sendRemoveContainerItem(cl->first, slot);
  1315.     }
  1316. }
  1317.  
  1318. void Player::onUpdateTileItem(const Tile* tile, const Position& pos, const Item* oldItem,
  1319.     const ItemType& oldType, const Item* newItem, const ItemType& newType)
  1320. {
  1321.     Creature::onUpdateTileItem(tile, pos, oldItem, oldType, newItem, newType);
  1322.     if(oldItem != newItem)
  1323.         onRemoveTileItem(tile, pos, oldType, oldItem);
  1324.  
  1325.     if(tradeState != TRADE_TRANSFER && tradeItem && oldItem == tradeItem)
  1326.         g_game.internalCloseTrade(this);
  1327. }
  1328.  
  1329. void Player::onRemoveTileItem(const Tile* tile, const Position& pos, const ItemType& iType, const Item* item)
  1330. {
  1331.     Creature::onRemoveTileItem(tile, pos, iType, item);
  1332.     if(tradeState == TRADE_TRANSFER)
  1333.         return;
  1334.  
  1335.     checkTradeState(item);
  1336.     if(tradeItem)
  1337.     {
  1338.         const Container* container = item->getContainer();
  1339.         if(container && container->isHoldingItem(tradeItem))
  1340.             g_game.internalCloseTrade(this);
  1341.     }
  1342. }
  1343.  
  1344. void Player::onCreatureAppear(const Creature* creature)
  1345. {
  1346.     Creature::onCreatureAppear(creature);
  1347.     if(creature != this)
  1348.         return;
  1349.  
  1350.     Item* item = NULL;
  1351.     for(int32_t slot = SLOT_FIRST; slot < SLOT_LAST; ++slot)
  1352.     {
  1353.         if(!(item = getInventoryItem((slots_t)slot)))
  1354.             continue;
  1355.  
  1356.         item->__startDecaying();
  1357.         g_moveEvents->onPlayerEquip(this, item, (slots_t)slot, false);
  1358.     }
  1359.  
  1360.     updateWeapon();
  1361.     if(BedItem* _bed = Beds::getInstance()->getBedBySleeper(guid))
  1362.         _bed->wakeUp();
  1363.  
  1364.     Outfit outfit;
  1365.     if(Outfits::getInstance()->getOutfit(defaultOutfit.lookType, outfit))
  1366.         outfitAttributes = Outfits::getInstance()->addAttributes(getID(), outfit.outfitId, sex, defaultOutfit.lookAddons);
  1367.  
  1368.     if(lastLogout && stamina < STAMINA_MAX)
  1369.     {
  1370.         int64_t ticks = (int64_t)time(NULL) - lastLogout - 600;
  1371.         if(ticks > 0)
  1372.         {
  1373.             ticks = (int64_t)((double)(ticks * 1000) / g_config.getDouble(ConfigManager::RATE_STAMINA_GAIN));
  1374.             int64_t premium = g_config.getNumber(ConfigManager::STAMINA_LIMIT_TOP) * STAMINA_MULTIPLIER, period = ticks;
  1375.             if((int64_t)stamina <= premium)
  1376.             {
  1377.                 period += stamina;
  1378.                 if(period > premium)
  1379.                     period -= premium;
  1380.                 else
  1381.                     period = 0;
  1382.  
  1383.                 useStamina(ticks - period);
  1384.             }
  1385.  
  1386.             if(period > 0)
  1387.             {
  1388.                 ticks = (int64_t)((g_config.getDouble(ConfigManager::RATE_STAMINA_GAIN) * period)
  1389.                     / g_config.getDouble(ConfigManager::RATE_STAMINA_THRESHOLD));
  1390.                 if(stamina + ticks > STAMINA_MAX)
  1391.                     ticks = STAMINA_MAX - stamina;
  1392.  
  1393.                 useStamina(ticks);
  1394.             }
  1395.  
  1396.             sendStats();
  1397.         }
  1398.     }
  1399.  
  1400.     int32_t offlineTime;
  1401.     if(getLastLogout())
  1402.         offlineTime = std::min((int32_t)(time(NULL) - getLastLogout()), 86400 * 21);
  1403.     else
  1404.         offlineTime = 0;
  1405.  
  1406.     if(offlineTrainingSkill != SKILL_NONE)
  1407.     {
  1408.         int32_t trainingTime = std::max(0, std::min(offlineTime, std::min(43200, getOfflineTrainingTime() / 1000)));
  1409.         if(offlineTime >= 600)
  1410.         {
  1411.             removeOfflineTrainingTime(trainingTime * 1000);
  1412.             int32_t remainder = offlineTime - trainingTime;
  1413.             if(remainder > 0)
  1414.                 addOfflineTrainingTime(remainder * 1000);
  1415.  
  1416.             if(trainingTime >= 60)
  1417.             {
  1418.                 std::ostringstream ss;
  1419.                 ss << "During your absence you trained for ";
  1420.  
  1421.                 int32_t hours = trainingTime / 3600;
  1422.                 if(hours > 1)
  1423.                     ss << hours << " hours";
  1424.                 else if(hours == 1)
  1425.                     ss << "1 hour";
  1426.  
  1427.                 int32_t minutes = (trainingTime % 3600) / 60;
  1428.                 if(minutes != 0)
  1429.                 {
  1430.                     if(hours != 0)
  1431.                         ss << " and ";
  1432.  
  1433.                     if(minutes > 1)
  1434.                         ss << minutes << " minutes";
  1435.                     else
  1436.                         ss << "1 minute";
  1437.                 }
  1438.    
  1439.                 ss << ".";
  1440.                 sendTextMessage(MSG_EVENT_ADVANCE, ss.str());
  1441.  
  1442.                 Vocation* voc = getVocation();
  1443.                 if(!isPromoted(promotionLevel + 1)) // maybe a configurable?...
  1444.                 {
  1445.                     int32_t vocId = Vocations::getInstance()->getPromotedVocation(voc->getId());
  1446.                     if(vocId > 0)
  1447.                     {
  1448.                         if(Vocation* tmp = Vocations::getInstance()->getVocation(vocId))
  1449.                             voc = tmp;
  1450.                     }
  1451.                 }
  1452.  
  1453.                 if(offlineTrainingSkill == SKILL_CLUB || offlineTrainingSkill == SKILL_SWORD || offlineTrainingSkill == SKILL_AXE)
  1454.                 {
  1455.                     float modifier = voc->getAttackSpeed() / 1000.f;
  1456.                     addOfflineTrainingTries((skills_t)offlineTrainingSkill, (trainingTime / modifier) / 2);
  1457.                 }
  1458.                 else if(offlineTrainingSkill == SKILL_DIST)
  1459.                 {
  1460.                     float modifier = voc->getAttackSpeed() / 1000.f;
  1461.                     addOfflineTrainingTries((skills_t)offlineTrainingSkill, (trainingTime / modifier) / 4);
  1462.                 }
  1463.                 else if(offlineTrainingSkill == SKILL__MAGLEVEL)
  1464.                 {
  1465.                     int32_t gainTicks = voc->getGainTicks(GAIN_MANA) << 1;
  1466.                     if(!gainTicks)
  1467.                         gainTicks = 1;
  1468.                     addOfflineTrainingTries(SKILL__MAGLEVEL, (int32_t)((float) trainingTime * ((float) voc->getGainAmount(GAIN_MANA) / (float) gainTicks)));
  1469.                 }
  1470.  
  1471.                 if(addOfflineTrainingTries(SKILL_SHIELD, trainingTime / 4))
  1472.                     sendSkills();
  1473.             }
  1474.  
  1475.             sendStats();
  1476.         }
  1477.         else
  1478.             sendTextMessage(MSG_EVENT_ADVANCE, "You must be logged out for more than 10 minutes to start offline training.");
  1479.         offlineTrainingSkill = SKILL_NONE;
  1480.     }
  1481.     else
  1482.     {
  1483.         uint16_t oldMinutes = getOfflineTrainingTime() / 60 / 1000;
  1484.         addOfflineTrainingTime(offlineTime * 1000);
  1485.  
  1486.         uint16_t newMinutes = getOfflineTrainingTime() / 60 / 1000;
  1487.         if(oldMinutes != newMinutes)
  1488.             sendStats();
  1489.     }
  1490.  
  1491.     g_game.checkPlayersRecord(this);
  1492.     if(!isGhost())
  1493.     {
  1494.         IOLoginData::getInstance()->updateOnlineStatus(guid, true);
  1495.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  1496.             it->second->notifyLogIn(this);
  1497.     }
  1498.     else
  1499.     {
  1500.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  1501.         {
  1502.             if(it->second->canSeeCreature(this))
  1503.                 it->second->notifyLogIn(this);
  1504.         }
  1505.     }
  1506.  
  1507.     #if defined(WINDOWS) && !defined(_CONSOLE)
  1508.     GUI::getInstance()->m_pBox.addPlayer(this);
  1509.     #endif
  1510.  
  1511.     if(g_config.getBool(ConfigManager::DISPLAY_LOGGING))
  1512.         std::clog << name << " has logged in." << std::endl;
  1513. }
  1514.  
  1515. void Player::onTargetDisappear(bool isLogout)
  1516. {
  1517.     sendCancelTarget();
  1518.     if(!isLogout)
  1519.         sendTextMessage(MSG_STATUS_SMALL, "Target lost.");
  1520. }
  1521.  
  1522. void Player::onFollowCreatureDisappear(bool isLogout)
  1523. {
  1524.     sendCancelTarget();
  1525.     if(!isLogout)
  1526.         sendTextMessage(MSG_STATUS_SMALL, "Target lost.");
  1527. }
  1528.  
  1529. void Player::onChangeZone(ZoneType_t zone)
  1530. {
  1531.     if(zone == ZONE_PROTECTION && !hasFlag(PlayerFlag_IgnoreProtectionZone))
  1532.     {
  1533.         if(attackedCreature)
  1534.         {
  1535.             setAttackedCreature(NULL);
  1536.             onTargetDisappear(false);
  1537.         }
  1538.     }
  1539.  
  1540.     sendIcons();
  1541. }
  1542.  
  1543. void Player::onTargetChangeZone(ZoneType_t zone)
  1544. {
  1545.     if(zone == ZONE_PROTECTION && !hasFlag(PlayerFlag_IgnoreProtectionZone))
  1546.     {
  1547.         setAttackedCreature(NULL);
  1548.         onTargetDisappear(false);
  1549.     }
  1550.     else if(zone == ZONE_OPTIONAL && attackedCreature->getPlayer() && !hasFlag(PlayerFlag_IgnoreProtectionZone))
  1551.     {
  1552.         setAttackedCreature(NULL);
  1553.         onTargetDisappear(false);
  1554.     }
  1555.     else if(zone == ZONE_OPEN && g_game.getWorldType() == WORLDTYPE_OPTIONAL && attackedCreature->getPlayer())
  1556.     {
  1557.         //attackedCreature can leave a pvp zone if not pzlocked
  1558.         setAttackedCreature(NULL);
  1559.         onTargetDisappear(false);
  1560.     }
  1561. }
  1562.  
  1563. void Player::onCreatureDisappear(const Creature* creature, bool isLogout)
  1564. {
  1565.     Creature::onCreatureDisappear(creature, isLogout);
  1566.     if(creature != this)
  1567.         return;
  1568.  
  1569.     if(isLogout)
  1570.         loginPosition = getPosition();
  1571.  
  1572.     lastLogout = time(NULL);
  1573.     Item* item = NULL;
  1574.     for(int32_t slot = SLOT_FIRST; slot < SLOT_LAST; ++slot)
  1575.     {
  1576.         if(!(item = getInventoryItem((slots_t)slot)))
  1577.             continue;
  1578.  
  1579.         g_moveEvents->onPlayerDeEquip(this, item, (slots_t)slot, false);
  1580.     }
  1581.  
  1582.     if(eventWalk)
  1583.         setFollowCreature(NULL);
  1584.  
  1585.     if(tradePartner)
  1586.         g_game.internalCloseTrade(this);
  1587.  
  1588.     clearPartyInvitations();
  1589.     if(party)
  1590.         party->leave(this);
  1591.  
  1592.     g_game.cancelRuleViolation(this);
  1593.     if(hasFlag(PlayerFlag_CanAnswerRuleViolations))
  1594.     {
  1595.         PlayerVector closeReportList;
  1596.         for(RuleViolationsMap::const_iterator it = g_game.getRuleViolations().begin(); it != g_game.getRuleViolations().end(); ++it)
  1597.         {
  1598.             if(it->second->gamemaster == this)
  1599.                 closeReportList.push_back(it->second->reporter);
  1600.         }
  1601.  
  1602.         for(PlayerVector::iterator it = closeReportList.begin(); it != closeReportList.end(); ++it)
  1603.             g_game.closeRuleViolation(*it);
  1604.     }
  1605.  
  1606.     g_chat.removeUserFromChannels(this);
  1607.     if(!isGhost())
  1608.         IOLoginData::getInstance()->updateOnlineStatus(guid, false);
  1609.  
  1610.     #if defined(WINDOWS) && !defined(_CONSOLE)
  1611.     GUI::getInstance()->m_pBox.removePlayer(this);
  1612.     #endif
  1613.  
  1614.     if(g_config.getBool(ConfigManager::DISPLAY_LOGGING))
  1615.         std::clog << getName() << " has logged out." << std::endl;
  1616.  
  1617.     bool saved = false;
  1618.     for(uint32_t tries = 0; !saved && tries < 3; ++tries)
  1619.     {
  1620.         if(IOLoginData::getInstance()->savePlayer(this))
  1621.             saved = true;
  1622. #ifdef __DEBUG__
  1623.         else
  1624.             std::clog << "Error while saving player: " << getName() << ", strike " << tries << "." << std::endl;
  1625. #endif
  1626.     }
  1627.  
  1628.     if(!saved)
  1629. #ifndef __DEBUG__
  1630.         std::clog << "Error while saving player: " << getName() << "." << std::endl;
  1631. #else
  1632.         std::clog << "Player " << getName() << " couldn't be saved." << std::endl;
  1633. #endif
  1634. }
  1635.  
  1636. void Player::onWalk(Direction& dir)
  1637. {
  1638.     Creature::onWalk(dir);
  1639.     setNextActionTask(NULL);
  1640.     setNextAction(OTSYS_TIME() + getStepDuration(dir));
  1641. }
  1642.  
  1643. void Player::onCreatureMove(const Creature* creature, const Tile* newTile, const Position& newPos,
  1644.     const Tile* oldTile, const Position& oldPos, bool teleport)
  1645. {
  1646.     Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport);
  1647.     if(creature != this)
  1648.         return;
  1649.  
  1650.     if(party)
  1651.         party->updateSharedExperience();
  1652.  
  1653.     //check if we should close trade
  1654.     if(tradeState != TRADE_TRANSFER && ((tradeItem && !Position::areInRange<1,1,0>(tradeItem->getPosition(), getPosition()))
  1655.         || (tradePartner && !Position::areInRange<2,2,0>(tradePartner->getPosition(), getPosition()))))
  1656.         g_game.internalCloseTrade(this);
  1657.  
  1658.     if((teleport || oldPos.z != newPos.z) && !hasCustomFlag(PlayerCustomFlag_CanStairhop))
  1659.     {
  1660.         int32_t ticks = g_config.getNumber(ConfigManager::STAIRHOP_DELAY);
  1661.         if(ticks > 0)
  1662.         {
  1663.             addExhaust(ticks, EXHAUST_MELEE);
  1664.             if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks))
  1665.                 addCondition(condition);
  1666.         }
  1667.     }
  1668.  
  1669.     // unset editing house
  1670.     if (editHouse && !newTile->hasFlag(TILESTATE_HOUSE))
  1671.         editHouse = NULL;
  1672. }
  1673.  
  1674. void Player::onAddContainerItem(const Container* container, const Item* item)
  1675. {
  1676.     checkTradeState(item);
  1677.     if(backpack.first && (const_cast<Container*>(container) != backpack.first || backpack.first->full()))
  1678.         backpack.first = NULL;
  1679. }
  1680.  
  1681. void Player::onUpdateContainerItem(const Container* container, uint8_t,
  1682.     const Item* oldItem, const ItemType&, const Item* newItem, const ItemType&)
  1683. {
  1684.     if(tradeState == TRADE_TRANSFER)
  1685.         return;
  1686.  
  1687.     checkTradeState(oldItem);
  1688.     if(oldItem != newItem && tradeItem)
  1689.     {
  1690.         if(tradeItem->getParent() != container && container->isHoldingItem(tradeItem))
  1691.             g_game.internalCloseTrade(this);
  1692.     }
  1693.  
  1694.     if(tradeState != TRADE_TRANSFER)
  1695.         checkTradeState(oldItem);
  1696. }
  1697.  
  1698. void Player::onRemoveContainerItem(const Container* container, uint8_t, const Item* item)
  1699. {
  1700.     backpack.first = NULL;
  1701.     if(tradeState == TRADE_TRANSFER)
  1702.         return;
  1703.  
  1704.     checkTradeState(item);
  1705.     if(tradeItem)
  1706.     {
  1707.         if(tradeItem->getParent() != container && container->isHoldingItem(tradeItem))
  1708.             g_game.internalCloseTrade(this);
  1709.     }
  1710. }
  1711.  
  1712. void Player::onCloseContainer(const Container* container)
  1713. {
  1714.     if(!client)
  1715.         return;
  1716.  
  1717.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1718.     {
  1719.         if(cl->second == container)
  1720.             client->sendCloseContainer(cl->first);
  1721.     }
  1722. }
  1723.  
  1724. void Player::onSendContainer(const Container* container)
  1725. {
  1726.     if(!client)
  1727.         return;
  1728.  
  1729.     bool hasParent = dynamic_cast<const Container*>(container->getParent()) != NULL;
  1730.     for(ContainerVector::const_iterator cl = containerVec.begin(); cl != containerVec.end(); ++cl)
  1731.     {
  1732.         if(cl->second == container)
  1733.             client->sendContainer(cl->first, container, hasParent);
  1734.     }
  1735. }
  1736.  
  1737. void Player::onUpdateInventoryItem(slots_t, Item* oldItem, const ItemType&,
  1738.     Item* newItem, const ItemType&)
  1739. {
  1740.     if(tradeState == TRADE_TRANSFER)
  1741.         return;
  1742.  
  1743.     checkTradeState(oldItem);
  1744.     if(oldItem != newItem && tradeItem)
  1745.     {
  1746.         const Container* container = oldItem->getContainer();
  1747.         if(container && container->isHoldingItem(tradeItem))
  1748.             g_game.internalCloseTrade(this);
  1749.     }
  1750.  
  1751.     if(tradeState != TRADE_TRANSFER)
  1752.         checkTradeState(oldItem);
  1753. }
  1754.  
  1755. void Player::onRemoveInventoryItem(slots_t, Item* item)
  1756. {
  1757.     backpack.first = NULL;
  1758.     if(tradeState == TRADE_TRANSFER)
  1759.         return;
  1760.  
  1761.     checkTradeState(item);
  1762.     if(tradeItem)
  1763.     {
  1764.         const Container* container = item->getContainer();
  1765.         if(container && container->isHoldingItem(tradeItem))
  1766.             g_game.internalCloseTrade(this);
  1767.     }
  1768. }
  1769.  
  1770. void Player::checkTradeState(const Item* item)
  1771. {
  1772.     if(!tradeItem || tradeState == TRADE_TRANSFER)
  1773.         return;
  1774.  
  1775.     if(tradeItem != item)
  1776.     {
  1777.         const Container* container = dynamic_cast<const Container*>(item->getParent());
  1778.         while(container != NULL)
  1779.         {
  1780.             if(container == tradeItem)
  1781.             {
  1782.                 g_game.internalCloseTrade(this);
  1783.                 break;
  1784.             }
  1785.  
  1786.             container = dynamic_cast<const Container*>(container->getParent());
  1787.         }
  1788.     }
  1789.     else
  1790.         g_game.internalCloseTrade(this);
  1791. }
  1792.  
  1793. void Player::setNextWalkActionTask(SchedulerTask* task)
  1794. {
  1795.     if(walkTaskEvent)
  1796.     {
  1797.         Scheduler::getInstance().stopEvent(walkTaskEvent);
  1798.         walkTaskEvent = 0;
  1799.     }
  1800.  
  1801.     delete walkTask;
  1802.     walkTask = task;
  1803.     setIdleTime(0);
  1804. }
  1805.  
  1806. void Player::setNextWalkTask(SchedulerTask* task)
  1807. {
  1808.     if(nextStepEvent)
  1809.     {
  1810.         Scheduler::getInstance().stopEvent(nextStepEvent);
  1811.         nextStepEvent = 0;
  1812.     }
  1813.  
  1814.     if(task)
  1815.     {
  1816.         nextStepEvent = Scheduler::getInstance().addEvent(task);
  1817.         setIdleTime(0);
  1818.     }
  1819. }
  1820.  
  1821. void Player::setNextActionTask(SchedulerTask* task)
  1822. {
  1823.     if(actionTaskEvent)
  1824.     {
  1825.         Scheduler::getInstance().stopEvent(actionTaskEvent);
  1826.         actionTaskEvent = 0;
  1827.     }
  1828.  
  1829.     if(task)
  1830.     {
  1831.         actionTaskEvent = Scheduler::getInstance().addEvent(task);
  1832.         setIdleTime(0);
  1833.     }
  1834. }
  1835.  
  1836. uint32_t Player::getNextActionTime(bool scheduler/* = true*/) const
  1837. {
  1838.     if(!scheduler)
  1839.         return (uint32_t)std::max((int64_t)0, ((int64_t)nextAction - OTSYS_TIME()));
  1840.  
  1841.     return (uint32_t)std::max((int64_t)SCHEDULER_MINTICKS, ((int64_t)nextAction - OTSYS_TIME()));
  1842. }
  1843.  
  1844. void Player::onThink(uint32_t interval)
  1845. {
  1846.     Creature::onThink(interval);
  1847.     int64_t timeNow = OTSYS_TIME();
  1848.     if(timeNow - lastPing >= 5000)
  1849.     {
  1850.         lastPing = timeNow;
  1851.         if(hasClient())
  1852.             client->sendPing();
  1853.         else if(g_config.getBool(ConfigManager::STOP_ATTACK_AT_EXIT))
  1854.             setAttackedCreature(NULL);
  1855.     }
  1856.  
  1857.     if((timeNow - lastPong) >= 60000 && !getTile()->hasFlag(TILESTATE_NOLOGOUT)
  1858.         && !isConnecting && !pzLocked && !hasCondition(CONDITION_INFIGHT))
  1859.     {
  1860.         if(hasClient())
  1861.             client->logout(true, true);
  1862.         else if(g_creatureEvents->playerLogout(this, false))
  1863.             g_game.removeCreature(this, true);
  1864.     }
  1865.  
  1866.     messageTicks += interval;
  1867.     if(messageTicks >= 1500)
  1868.     {
  1869.         messageTicks = 0;
  1870.         addMessageBuffer();
  1871.     }
  1872.  
  1873.     if(lastMail && lastMail < (uint64_t)(OTSYS_TIME() + g_config.getNumber(ConfigManager::MAIL_ATTEMPTS_FADE)))
  1874.         mailAttempts = lastMail = 0;
  1875.  
  1876.     addOfflineTrainingTime(interval);
  1877.     if(lastStatsTrainingTime != getOfflineTrainingTime() / 60 / 1000)
  1878.         sendStats();
  1879. }
  1880.  
  1881. bool Player::isMuted(uint16_t channelId, MessageClasses type, int32_t& time)
  1882. {
  1883.     time = 0;
  1884.     if(hasFlag(PlayerFlag_CannotBeMuted))
  1885.         return false;
  1886.  
  1887.     int32_t muteTicks = 0;
  1888.     for(ConditionList::iterator it = conditions.begin(); it != conditions.end(); ++it)
  1889.     {
  1890.         if((*it)->getType() == CONDITION_MUTED && (*it)->getSubId() == 0)
  1891.         {
  1892.             if((*it)->getTicks() == -1)
  1893.             {
  1894.                 time = -1;
  1895.                 break;
  1896.             }
  1897.  
  1898.             if((*it)->getTicks() > muteTicks)
  1899.                 muteTicks = (*it)->getTicks();
  1900.         }
  1901.     }
  1902.  
  1903.     if(muteTicks)
  1904.         time = (uint32_t)muteTicks / 1000;
  1905.  
  1906.     return (type != MSG_CHANNEL || (channelId != CHANNEL_GUILD && !g_chat.isPrivateChannel(channelId)));
  1907. }
  1908.  
  1909. void Player::addMessageBuffer()
  1910. {
  1911.     if(!hasFlag(PlayerFlag_CannotBeMuted) && g_config.getNumber(ConfigManager::MAX_MESSAGEBUFFER) && messageBuffer)
  1912.         messageBuffer--;
  1913. }
  1914.  
  1915. void Player::removeMessageBuffer()
  1916. {
  1917.     if(hasFlag(PlayerFlag_CannotBeMuted))
  1918.         return;
  1919.  
  1920.     int32_t maxBuffer = g_config.getNumber(ConfigManager::MAX_MESSAGEBUFFER);
  1921.     if(!maxBuffer || messageBuffer > maxBuffer + 1 || ++messageBuffer <= maxBuffer)
  1922.         return;
  1923.  
  1924.     uint32_t muteCount = 1;
  1925.     MuteCountMap::iterator it = muteCountMap.find(guid);
  1926.     if(it != muteCountMap.end())
  1927.         muteCount = it->second;
  1928.  
  1929.     uint32_t muteTime = 5 * muteCount * muteCount;
  1930.     muteCountMap[guid] = muteCount + 1;
  1931.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000))
  1932.         addCondition(condition);
  1933.  
  1934.     char buffer[50];
  1935.     sprintf(buffer, "You are muted for %d seconds.", muteTime);
  1936.     sendTextMessage(MSG_STATUS_SMALL, buffer);
  1937. }
  1938.  
  1939. double Player::getFreeCapacity() const
  1940. {
  1941.     if(hasFlag(PlayerFlag_HasInfiniteCapacity)
  1942.         || !g_config.getBool(ConfigManager::USE_CAPACITY))
  1943.         return 10000.00;
  1944.  
  1945.     return std::max(0.00, capacity - inventoryWeight);
  1946. }
  1947.  
  1948. void Player::drainHealth(Creature* attacker, CombatType_t combatType, int32_t damage)
  1949. {
  1950.     Creature::drainHealth(attacker, combatType, damage);
  1951.     sendStats();
  1952. }
  1953.  
  1954. void Player::drainMana(Creature* attacker, CombatType_t combatType, int32_t damage)
  1955. {
  1956.     Creature::drainMana(attacker, combatType, damage);
  1957.     char buffer[150];
  1958.     if(attacker)
  1959.         sprintf(buffer, "You lose %d mana blocking an attack by %s.", damage, attacker->getNameDescription().c_str());
  1960.     else
  1961.         sprintf(buffer, "You lose %d mana.", damage);
  1962.  
  1963.     sendStats();
  1964.     sendTextMessage(MSG_EVENT_DEFAULT, buffer);
  1965. }
  1966.  
  1967. void Player::addManaSpent(uint64_t amount, bool useMultiplier/* = true*/)
  1968. {
  1969.     if(!amount)
  1970.         return;
  1971.  
  1972.     uint64_t currReqMana = vocation->getReqMana(magLevel), nextReqMana = vocation->getReqMana(magLevel + 1);
  1973.     if(magLevel > 0 && currReqMana > nextReqMana) //player has reached max magic level
  1974.         return;
  1975.  
  1976.     if(useMultiplier)
  1977.         amount = uint64_t((double)amount * rates[SKILL__MAGLEVEL] * g_config.getDouble(ConfigManager::RATE_MAGIC));
  1978.  
  1979.     std::stringstream s;
  1980.     while(manaSpent + amount >= nextReqMana)
  1981.     {
  1982.         amount -= nextReqMana - manaSpent;
  1983.         manaSpent = 0;
  1984.  
  1985.         s.str("");
  1986.         s << "You advanced to magic level " << ++magLevel << ".";
  1987.         sendTextMessage(MSG_EVENT_ADVANCE, s.str());
  1988.  
  1989.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  1990.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  1991.             (*it)->executeAdvance(this, SKILL__MAGLEVEL, (magLevel - 1), magLevel);
  1992.  
  1993.         currReqMana = nextReqMana;
  1994.         nextReqMana = vocation->getReqMana(magLevel + 1);
  1995.         if(currReqMana > nextReqMana)
  1996.         {
  1997.             amount = 0;
  1998.             break;
  1999.         }
  2000.     }
  2001.  
  2002.     if(amount)
  2003.         manaSpent += amount;
  2004.  
  2005.     uint16_t newPercent = Player::getPercentLevel(manaSpent, nextReqMana);
  2006.     if(magLevelPercent != newPercent)
  2007.     {
  2008.         magLevelPercent = newPercent;
  2009.         sendStats();
  2010.     }
  2011.     else if(!s.str().empty())
  2012.         sendStats();
  2013. }
  2014.  
  2015. void Player::addExperience(uint64_t exp)
  2016. {
  2017.     uint32_t prevLevel = level;
  2018.  
  2019.     uint64_t nextLevelExp = Player::getExpForLevel(level + 1);
  2020.     if(Player::getExpForLevel(level) > nextLevelExp)
  2021.     {
  2022.         //player has reached max level
  2023.         levelPercent = 0;
  2024.         sendStats();
  2025.         return;
  2026.     }
  2027.  
  2028.     experience += exp;
  2029.     while(experience >= nextLevelExp)
  2030.     {
  2031.         ++level;
  2032.         Vocation* voc = vocation;
  2033.         if(voc->getId() > 0 && g_config.getBool(ConfigManager::ROOK_SYSTEM) &&
  2034.             level <= (uint32_t)g_config.getNumber(ConfigManager::ROOK_TOLEVEL))
  2035.         {
  2036.             if(Vocation* tmp = Vocations::getInstance()->getVocation(0))
  2037.                 voc = tmp;
  2038.         }
  2039.  
  2040.         healthMax += voc->getGain(GAIN_HEALTH);
  2041.         health += voc->getGain(GAIN_HEALTH);
  2042.         manaMax += voc->getGain(GAIN_MANA);
  2043.         mana += voc->getGain(GAIN_MANA);
  2044.         capacity += voc->getGainCap();
  2045.  
  2046.         nextLevelExp = Player::getExpForLevel(level + 1);
  2047.         if(Player::getExpForLevel(level) > nextLevelExp) //player has reached max level
  2048.             break;
  2049.     }
  2050.  
  2051.     if(prevLevel != level)
  2052.     {
  2053.         updateBaseSpeed();
  2054.         g_game.changeSpeed(this, 0);
  2055.         if(party)
  2056.             party->updateSharedExperience();
  2057.  
  2058.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  2059.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  2060.             (*it)->executeAdvance(this, SKILL__LEVEL, prevLevel, level);
  2061.  
  2062.         std::stringstream s;
  2063.         s << "You advanced from Level " << prevLevel << " to Level " << level << ".";
  2064.  
  2065.         sendTextMessage(MSG_EVENT_ADVANCE, s.str());
  2066.     }
  2067.  
  2068.     uint64_t currLevelExp = Player::getExpForLevel(level);
  2069.     nextLevelExp = Player::getExpForLevel(level + 1);
  2070.     levelPercent = 0;
  2071.     if(nextLevelExp > currLevelExp)
  2072.         levelPercent = Player::getPercentLevel(experience - currLevelExp, nextLevelExp - currLevelExp);
  2073.  
  2074.     sendStats();
  2075. }
  2076.  
  2077. void Player::removeExperience(uint64_t exp, bool updateStats/* = true*/)
  2078. {
  2079.     uint32_t prevLevel = level;
  2080.  
  2081.     experience -= std::min(exp, experience);
  2082.     while(level > 1 && experience < Player::getExpForLevel(level))
  2083.     {
  2084.         --level;
  2085.         Vocation* voc = vocation;
  2086.         if(voc->getId() > 0 && g_config.getBool(ConfigManager::ROOK_SYSTEM) &&
  2087.             level < (uint32_t)g_config.getNumber(ConfigManager::ROOK_TOLEVEL))
  2088.         {
  2089.             if(Vocation* tmp = Vocations::getInstance()->getVocation(0))
  2090.                 voc = tmp;
  2091.         }
  2092.  
  2093.         healthMax = std::max((int32_t)0, (healthMax - (int32_t)voc->getGain(GAIN_HEALTH)));
  2094.         mana = std::max((int32_t)0, (mana - (int32_t)voc->getGain(GAIN_MANA)));
  2095.         manaMax = std::max((int32_t)0, (manaMax - (int32_t)voc->getGain(GAIN_MANA)));
  2096.         capacity = std::max((double)0, (capacity - (double)voc->getGainCap()));
  2097.     }
  2098.  
  2099.     if(prevLevel != level)
  2100.     {
  2101.         if(updateStats)
  2102.         {
  2103.             updateBaseSpeed();
  2104.             g_game.changeSpeed(this, 0);
  2105.             g_game.addCreatureHealth(this);
  2106.         }
  2107.  
  2108.         CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  2109.         for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  2110.             (*it)->executeAdvance(this, SKILL__LEVEL, prevLevel, level);
  2111.  
  2112.         std::stringstream s;
  2113.         s << "You were downgraded from Level " << prevLevel << " to Level " << level << ".";
  2114.  
  2115.         sendTextMessage(MSG_EVENT_ADVANCE, s.str());
  2116.     }
  2117.  
  2118.     uint64_t currLevelExp = Player::getExpForLevel(level),
  2119.         nextLevelExp = Player::getExpForLevel(level + 1);
  2120.     if(nextLevelExp > currLevelExp)
  2121.         levelPercent = Player::getPercentLevel(experience - currLevelExp, nextLevelExp - currLevelExp);
  2122.     else
  2123.         levelPercent = 0;
  2124.  
  2125.     if(updateStats)
  2126.         sendStats();
  2127. }
  2128.  
  2129. uint16_t Player::getPercentLevel(uint64_t count, uint64_t nextLevelCount)
  2130. {
  2131.     if(nextLevelCount > 0)
  2132.         return std::min((uint32_t)100, std::max((uint32_t)0, uint32_t(count * 100 / nextLevelCount)));
  2133.  
  2134.     return 0;
  2135. }
  2136.  
  2137. void Player::onBlockHit(BlockType_t)
  2138. {
  2139.     if(shieldBlockCount > 0)
  2140.     {
  2141.         --shieldBlockCount;
  2142.         if(hasShield())
  2143.             addSkillAdvance(SKILL_SHIELD, 1);
  2144.     }
  2145. }
  2146.  
  2147. void Player::onTargetBlockHit(Creature* target, BlockType_t blockType)
  2148. {
  2149.     Creature::onTargetBlockHit(target, blockType);
  2150.     lastAttackBlockType = blockType;
  2151.     switch(blockType)
  2152.     {
  2153.         case BLOCK_NONE:
  2154.         {
  2155.             bloodHitCount = shieldBlockCount = 30;
  2156.             addAttackSkillPoint = true;
  2157.             break;
  2158.         }
  2159.  
  2160.         case BLOCK_DEFENSE:
  2161.         case BLOCK_ARMOR:
  2162.         {
  2163.             //need to draw blood every 30 hits
  2164.             if(bloodHitCount > 0)
  2165.             {
  2166.                 addAttackSkillPoint = true;
  2167.                 --bloodHitCount;
  2168.             }
  2169.             else
  2170.                 addAttackSkillPoint = false;
  2171.  
  2172.             break;
  2173.         }
  2174.  
  2175.         default:
  2176.         {
  2177.             addAttackSkillPoint = false;
  2178.             break;
  2179.         }
  2180.     }
  2181. }
  2182.  
  2183. bool Player::hasShield() const
  2184. {
  2185.     Item* item = getInventoryItem(SLOT_LEFT);
  2186.     return (item && item->getWeaponType() == WEAPON_SHIELD) || ((item = getInventoryItem(SLOT_RIGHT)) && item->getWeaponType() == WEAPON_SHIELD);
  2187. }
  2188.  
  2189. BlockType_t Player::blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage,
  2190.     bool checkDefense/* = false*/, bool checkArmor/* = false*/, bool reflect/* = true*/, bool field/* = false*/, bool element/* = false*/)
  2191. {
  2192.     BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor, reflect, field);
  2193.     if(attacker && !element)
  2194.     {
  2195.         int16_t color = g_config.getNumber(ConfigManager::SQUARE_COLOR);
  2196.         if(color < 0)
  2197.             color = random_range(0, 254);
  2198.  
  2199.         sendCreatureSquare(attacker, color);
  2200.     }
  2201.  
  2202.     if(blockType != BLOCK_NONE)
  2203.         return blockType;
  2204.  
  2205.     if(vocation->getMultiplier(MULTIPLIER_MAGICDEFENSE) != 1.0 && combatType != COMBAT_PHYSICALDAMAGE &&
  2206.         combatType != COMBAT_NONE && combatType != COMBAT_UNDEFINEDDAMAGE && combatType != COMBAT_DROWNDAMAGE)
  2207.         damage -= (int32_t)std::ceil((double)(damage * vocation->getMultiplier(MULTIPLIER_MAGICDEFENSE)) / 100.);
  2208.  
  2209.     if(damage <= 0)
  2210.         return blockType;
  2211.  
  2212.     int32_t blocked = 0, reflected = 0;
  2213.     if(reflect)
  2214.         reflect = attacker && !attacker->isRemoved() && attacker->getHealth() > 0;
  2215.  
  2216.     Item* item = NULL;
  2217.     for(int32_t slot = SLOT_FIRST; slot < SLOT_LAST; ++slot)
  2218.     {
  2219.         if(!(item = getInventoryItem((slots_t)slot)) || item->isRemoved() ||
  2220.             (g_moveEvents->hasEquipEvent(item) && !isItemAbilityEnabled((slots_t)slot)))
  2221.             continue;
  2222.  
  2223.         const ItemType& it = Item::items[item->getID()];
  2224.         if(!it.hasAbilities())
  2225.             continue;
  2226.  
  2227.         bool transform = false;
  2228.         if(it.abilities->absorb[combatType])
  2229.         {
  2230.             blocked += (int32_t)std::ceil((double)(damage * it.abilities->absorb[combatType]) / 100.);
  2231.             if(item->hasCharges())
  2232.                 transform = true;
  2233.  
  2234.         }
  2235.  
  2236.         if(field && it.abilities->fieldAbsorb[combatType])
  2237.         {
  2238.             blocked += (int32_t)std::ceil((double)(damage * it.abilities->fieldAbsorb[combatType]) / 100.);
  2239.             if(item->hasCharges())
  2240.                 transform = true;
  2241.         }
  2242.  
  2243.         if(reflect && it.abilities->reflect[REFLECT_PERCENT][combatType] && it.abilities->reflect[REFLECT_CHANCE][combatType] >= random_range(1, 100))
  2244.         {
  2245.             reflected += (int32_t)std::ceil((double)(damage * it.abilities->reflect[REFLECT_PERCENT][combatType]) / 100.);
  2246.             if(item->hasCharges())
  2247.                 transform = true;
  2248.         }
  2249.  
  2250.         if(!element && transform)
  2251.             g_game.transformItem(item, item->getID(), std::max((int32_t)0, (int32_t)item->getCharges() - 1));
  2252.     }
  2253.  
  2254.     if(outfitAttributes)
  2255.     {
  2256.         uint32_t tmp = Outfits::getInstance()->getOutfitAbsorb(defaultOutfit.lookType, sex, combatType);
  2257.         if(tmp)
  2258.             blocked += (int32_t)std::ceil((double)(damage * tmp) / 100.);
  2259.  
  2260.         if(reflect)
  2261.         {
  2262.             tmp = Outfits::getInstance()->getOutfitReflect(defaultOutfit.lookType, sex, combatType);
  2263.             if(tmp)
  2264.                 reflected += (int32_t)std::ceil((double)(damage * tmp) / 100.);
  2265.         }
  2266.     }
  2267.  
  2268.     if(vocation->getAbsorb(combatType))
  2269.         blocked += (int32_t)std::ceil((double)(damage * vocation->getAbsorb(combatType)) / 100.);
  2270.  
  2271.     if(reflect && vocation->getReflect(combatType))
  2272.         reflected += (int32_t)std::ceil((double)(damage * vocation->getReflect(combatType)) / 100.);
  2273.  
  2274.     damage -= blocked;
  2275.     if(damage <= 0)
  2276.     {
  2277.         damage = 0;
  2278.         blockType = BLOCK_DEFENSE;
  2279.     }
  2280.  
  2281.     if(reflected && !element)
  2282.     {
  2283.         if(combatType != COMBAT_HEALING)
  2284.             reflected = -reflected;
  2285.  
  2286.         if(!g_game.combatBlockHit(combatType, this, attacker, reflected, false, false, true, false))
  2287.             g_game.combatChangeHealth(combatType, NULL, attacker, reflected);
  2288.     }
  2289.  
  2290.     return blockType;
  2291. }
  2292.  
  2293. uint32_t Player::getIP() const
  2294. {
  2295.     if(client)
  2296.         return client->getIP();
  2297.  
  2298.     return lastIP;
  2299. }
  2300.  
  2301. bool Player::onDeath()
  2302. {
  2303.     Item *preventLoss = NULL, *preventDrop = NULL;
  2304.     if(getZone() == ZONE_HARDCORE)
  2305.     {
  2306.         setDropLoot(LOOT_DROP_NONE);
  2307.         setLossSkill(false);
  2308.     }
  2309.     else if(skull < SKULL_RED)
  2310.     {
  2311.         Item* item = NULL;
  2312.         for(int32_t i = SLOT_FIRST; ((!preventDrop || !preventLoss) && i < SLOT_LAST); ++i)
  2313.         {
  2314.             if(!(item = getInventoryItem((slots_t)i)) || item->isRemoved() ||
  2315.                 (g_moveEvents->hasEquipEvent(item) && !isItemAbilityEnabled((slots_t)i)))
  2316.                 continue;
  2317.  
  2318.             const ItemType& it = Item::items[item->getID()];
  2319.             if(!it.hasAbilities())
  2320.                 continue;
  2321.  
  2322.             if(lootDrop == LOOT_DROP_FULL && it.abilities->preventDrop)
  2323.             {
  2324.                 setDropLoot(LOOT_DROP_PREVENT);
  2325.                 preventDrop = item;
  2326.             }
  2327.  
  2328.             if(skillLoss && !preventLoss && it.abilities->preventLoss)
  2329.                 preventLoss = item;
  2330.         }
  2331.     }
  2332.  
  2333.     if(!Creature::onDeath())
  2334.     {
  2335.         if(preventDrop)
  2336.             setDropLoot(LOOT_DROP_FULL);
  2337.  
  2338.         return false;
  2339.     }
  2340.  
  2341.     uint32_t totalDamage = 0, pvpDamage = 0, opponents = 0;
  2342.     for(CountMap::iterator it = damageMap.begin(); it != damageMap.end(); ++it)
  2343.     {
  2344.         if(((OTSYS_TIME() - it->second.ticks) / 1000) > g_config.getNumber(
  2345.             ConfigManager::FAIRFIGHT_TIMERANGE))
  2346.             continue;
  2347.  
  2348.         totalDamage += it->second.total;
  2349.         if(Creature* creature = g_game.getCreatureByID(it->first))
  2350.         {
  2351.             Player* player = creature->getPlayer();
  2352.             if(!player)
  2353.                 player = creature->getPlayerMaster();
  2354.  
  2355.             if(!player)
  2356.                 continue;
  2357.  
  2358.             opponents += player->getLevel();
  2359.             pvpDamage += it->second.total;
  2360.         }
  2361.     }
  2362.  
  2363.     bool usePVPBlessing = false;
  2364.     if(preventLoss)
  2365.     {
  2366.         setLossSkill(false);
  2367.         g_game.transformItem(preventLoss, preventLoss->getID(), std::max(0, (int32_t)preventLoss->getCharges() - 1));
  2368.     }
  2369.     else if(pvpBlessing && (int32_t)std::floor((100. * pvpDamage) / std::max(
  2370.         1U, totalDamage)) >= g_config.getNumber(ConfigManager::PVP_BLESSING_THRESHOLD))
  2371.         usePVPBlessing = true;
  2372.  
  2373.     if(preventDrop && preventDrop != preventLoss && !usePVPBlessing)
  2374.         g_game.transformItem(preventDrop, preventDrop->getID(), std::max(0, (int32_t)preventDrop->getCharges() - 1));
  2375.  
  2376.     removeConditions(CONDITIONEND_DEATH);
  2377.     sendTextMessage(MSG_EVENT_ADVANCE, "You are dead.");
  2378.  
  2379.     if(skillLoss)
  2380.     {
  2381.         double reduction = 1.;
  2382.         if(g_config.getBool(ConfigManager::FAIRFIGHT_REDUCTION) && opponents > level)
  2383.             reduction -= (double)level / opponents;
  2384.  
  2385.         uint64_t lossExperience = (uint64_t)std::floor(reduction * getLostExperience()), currExperience = experience;
  2386.         removeExperience(lossExperience, false);
  2387.         double percent = 1. - ((double)(currExperience - lossExperience) / std::max((uint64_t)1, currExperience));
  2388.  
  2389.         // magic level loss
  2390.         uint64_t sumMana = 0, lostMana = 0;
  2391.         for(uint32_t i = 1; i <= magLevel; ++i)
  2392.             sumMana += vocation->getReqMana(i);
  2393.  
  2394.         sumMana += manaSpent;
  2395.         lostMana = (uint64_t)std::ceil((percent * lossPercent[LOSS_MANA] / 100.) * sumMana);
  2396.         while(lostMana > manaSpent && magLevel > 0)
  2397.         {
  2398.             lostMana -= manaSpent;
  2399.             manaSpent = vocation->getReqMana(magLevel);
  2400.             magLevel--;
  2401.         }
  2402.  
  2403.         manaSpent -= lostMana;
  2404.         uint64_t nextReqMana = vocation->getReqMana(magLevel + 1);
  2405.         if(nextReqMana > vocation->getReqMana(magLevel))
  2406.             magLevelPercent = Player::getPercentLevel(manaSpent, nextReqMana);
  2407.         else
  2408.             magLevelPercent = 0;
  2409.  
  2410.         // skill loss
  2411.         uint64_t lostSkillTries, sumSkillTries;
  2412.         for(int16_t i = 0; i < 7; ++i) // for each skill
  2413.         {
  2414.             lostSkillTries = sumSkillTries = 0;
  2415.             for(uint32_t c = 11; c <= skills[i][SKILL_LEVEL]; ++c) // sum up all required tries for all skill levels
  2416.                 sumSkillTries += vocation->getReqSkillTries(i, c);
  2417.  
  2418.             sumSkillTries += skills[i][SKILL_TRIES];
  2419.             lostSkillTries = (uint64_t)std::ceil((percent * lossPercent[LOSS_SKILLS] / 100.) * sumSkillTries);
  2420.             while(lostSkillTries > skills[i][SKILL_TRIES] && skills[i][SKILL_LEVEL] > 10)
  2421.             {
  2422.                 lostSkillTries -= skills[i][SKILL_TRIES];
  2423.                 skills[i][SKILL_TRIES] = vocation->getReqSkillTries(i, skills[i][SKILL_LEVEL]);
  2424.                 skills[i][SKILL_LEVEL]--;
  2425.             }
  2426.  
  2427.             skills[i][SKILL_TRIES] -= lostSkillTries;
  2428.         }
  2429.  
  2430.         if(usePVPBlessing)
  2431.             pvpBlessing = false;
  2432.         else
  2433.             blessings = 0;
  2434.  
  2435.         loginPosition = masterPosition;
  2436.         if(vocationId > VOCATION_NONE && g_config.getBool(ConfigManager::ROOK_SYSTEM) &&
  2437.             level <= (uint32_t)g_config.getNumber(ConfigManager::ROOK_LEVELTO))
  2438.         {
  2439.             if(Town* rook = Towns::getInstance()->getTown(g_config.getNumber(ConfigManager::ROOK_TOWN)))
  2440.             {
  2441.                 level = 1;
  2442.                 soulMax = soul = 100;
  2443.                 capacity = 400;
  2444.                 stamina = STAMINA_MAX;
  2445.                 health = healthMax = 150;
  2446.                 loginPosition = masterPosition = rook->getPosition();
  2447.                 experience = magLevel = manaSpent = mana = manaMax = balance = marriage = 0;
  2448.                 promotionLevel = defaultOutfit.lookAddons = 0;
  2449.  
  2450.                 setTown(rook->getID());
  2451.                 setVocation(0);
  2452.                 leaveGuild();
  2453.  
  2454.                 storageMap.clear();
  2455.                 for(uint32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i)
  2456.                 {
  2457.                     skills[i][SKILL_LEVEL] = 10;
  2458.                     skills[i][SKILL_TRIES] = 0;
  2459.                 }
  2460.  
  2461.                 for(uint32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  2462.                 {
  2463.                     if(inventory[i])
  2464.                         g_game.internalRemoveItem(NULL, inventory[i]);
  2465.                 }
  2466.             }
  2467.         }
  2468.         else if(!inventory[SLOT_BACKPACK]) // FIXME: you should receive the bag after you login back...
  2469.             __internalAddThing(SLOT_BACKPACK, Item::CreateItem(g_config.getNumber(ConfigManager::DEATH_CONTAINER)));
  2470.  
  2471.         sendIcons();
  2472.         sendStats();
  2473.         sendSkills();
  2474.  
  2475.         g_creatureEvents->playerLogout(this, true);
  2476.         g_game.removeCreature(this, false);
  2477.     }
  2478.     else
  2479.     {
  2480.         setLossSkill(true);
  2481.         if(preventLoss)
  2482.         {
  2483.             loginPosition = masterPosition;
  2484.             g_creatureEvents->playerLogout(this, true);
  2485.  
  2486.             g_game.removeCreature(this, false);
  2487.         }
  2488.     }
  2489.  
  2490.     return true;
  2491. }
  2492.  
  2493. void Player::dropCorpse(DeathList deathList)
  2494. {
  2495.     if(lootDrop == LOOT_DROP_NONE)
  2496.     {
  2497.         pzLocked = false;
  2498.         if(health <= 0)
  2499.         {
  2500.             health = healthMax;
  2501.             if(getZone() != ZONE_HARDCORE || g_config.getBool(ConfigManager::PVPZONE_RECOVERMANA))
  2502.                 mana = manaMax;
  2503.         }
  2504.  
  2505.         setDropLoot(LOOT_DROP_FULL);
  2506.         sendStats();
  2507.         sendIcons();
  2508.  
  2509.         onIdleStatus();
  2510.         g_game.addCreatureHealth(this);
  2511.         g_game.internalTeleport(this, masterPosition, false);
  2512.     }
  2513.     else
  2514.     {
  2515.         Creature::dropCorpse(deathList);
  2516.         if(g_config.getBool(ConfigManager::DEATH_LIST))
  2517.             IOLoginData::getInstance()->playerDeath(this, deathList);
  2518.     }
  2519. }
  2520.  
  2521. Item* Player::createCorpse(DeathList deathList)
  2522. {
  2523.     Item* corpse = Creature::createCorpse(deathList);
  2524.     if(!corpse)
  2525.         return NULL;
  2526.  
  2527.     std::stringstream ss;
  2528.     ss << "You recognize " << nameDescription << ". " << (sex % 2 ? "He" : "She") << " was killed by ";
  2529.     if(deathList[0].isCreatureKill())
  2530.     {
  2531.         ss << deathList[0].getKillerCreature()->getNameDescription();
  2532.         if(deathList[0].getKillerCreature()->getMaster())
  2533.             ss << " summoned by " << deathList[0].getKillerCreature()->getMaster()->getNameDescription();
  2534.     }
  2535.     else
  2536.         ss << deathList[0].getKillerName();
  2537.  
  2538.     if(deathList.size() > 1 && g_config.getBool(ConfigManager::MULTIPLE_NAME))
  2539.     {
  2540.         if(deathList[0].getKillerType() != deathList[1].getKillerType())
  2541.         {
  2542.             if(deathList[1].isCreatureKill())
  2543.             {
  2544.                 ss << " and by " << deathList[1].getKillerCreature()->getNameDescription();
  2545.                 if(deathList[1].getKillerCreature()->getMaster())
  2546.                     ss << " summoned by " << deathList[1].getKillerCreature()->getMaster()->getNameDescription();
  2547.             }
  2548.             else
  2549.                 ss << " and by " << deathList[1].getKillerName();
  2550.         }
  2551.         else if(deathList[1].isCreatureKill())
  2552.         {
  2553.             if(deathList[0].getKillerCreature()->getName() != deathList[1].getKillerCreature()->getName())
  2554.             {
  2555.                 ss << " and by " << deathList[1].getKillerCreature()->getNameDescription();
  2556.                 if(deathList[1].getKillerCreature()->getMaster())
  2557.                     ss << " summoned by " << deathList[1].getKillerCreature()->getMaster()->getNameDescription();
  2558.             }
  2559.         }
  2560.         else if(asLowerCaseString(deathList[0].getKillerName()) != asLowerCaseString(deathList[1].getKillerName()))
  2561.             ss << " and by " << deathList[1].getKillerName();
  2562.     }
  2563.  
  2564.     ss << ".";
  2565.     corpse->setSpecialDescription(ss.str().c_str());
  2566.     return corpse;
  2567. }
  2568.  
  2569. void Player::addCooldown(uint32_t ticks, uint16_t spellId)
  2570. {
  2571.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT,
  2572.         CONDITION_SPELLCOOLDOWN, ticks, 0, false, spellId))
  2573.         addCondition(condition);
  2574. }
  2575.  
  2576. void Player::addExhaust(uint32_t ticks, Exhaust_t exhaust)
  2577. {
  2578.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT,
  2579.         CONDITION_EXHAUST, ticks, 0, false, (int32_t)exhaust))
  2580.         addCondition(condition);
  2581. }
  2582.  
  2583. void Player::addInFightTicks(bool pzLock, int32_t ticks/* = 0*/)
  2584. {
  2585.     if(hasFlag(PlayerFlag_NotGainInFight))
  2586.         return;
  2587.  
  2588.     if(!ticks)
  2589.         ticks = g_config.getNumber(ConfigManager::PZ_LOCKED);
  2590.     else
  2591.         ticks = std::max(-1, ticks);
  2592.  
  2593.     if(pzLock)
  2594.         pzLocked = true;
  2595.  
  2596.     if(Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT,
  2597.         CONDITION_INFIGHT, ticks))
  2598.         addCondition(condition);
  2599. }
  2600.  
  2601. void Player::addDefaultRegeneration(uint32_t addTicks)
  2602. {
  2603.     Condition* condition = getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT);
  2604.     if(condition)
  2605.         condition->setTicks(condition->getTicks() + addTicks);
  2606.     else if((condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_REGENERATION, addTicks)))
  2607.     {
  2608.         condition->setParam(CONDITIONPARAM_HEALTHGAIN, vocation->getGainAmount(GAIN_HEALTH));
  2609.         condition->setParam(CONDITIONPARAM_HEALTHTICKS, vocation->getGainTicks(GAIN_HEALTH) * 1000);
  2610.         condition->setParam(CONDITIONPARAM_MANAGAIN, vocation->getGainAmount(GAIN_MANA));
  2611.         condition->setParam(CONDITIONPARAM_MANATICKS, vocation->getGainTicks(GAIN_MANA) * 1000);
  2612.         addCondition(condition);
  2613.     }
  2614. }
  2615.  
  2616. void Player::removeList()
  2617. {
  2618.     autoList.erase(id);
  2619.     if(!isGhost())
  2620.     {
  2621.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  2622.             it->second->notifyLogOut(this);
  2623.     }
  2624.     else
  2625.     {
  2626.         for(AutoList<Player>::iterator it = autoList.begin(); it != autoList.end(); ++it)
  2627.         {
  2628.             if(it->second->canSeeCreature(this))
  2629.                 it->second->notifyLogOut(this);
  2630.         }
  2631.     }
  2632. }
  2633.  
  2634. void Player::addList()
  2635. {
  2636.     autoList[id] = this;
  2637. }
  2638.  
  2639. void Player::kick(bool displayEffect, bool forceLogout)
  2640. {
  2641.     if(!hasClient())
  2642.     {
  2643.         if(g_creatureEvents->playerLogout(this, forceLogout))
  2644.             g_game.removeCreature(this);
  2645.     }
  2646.     else
  2647.         client->logout(displayEffect, forceLogout);
  2648. }
  2649.  
  2650. void Player::notifyLogIn(Player* loginPlayer)
  2651. {
  2652.     if(!client)
  2653.         return;
  2654.  
  2655.     VIPSet::iterator it = VIPList.find(loginPlayer->getGUID());
  2656.     if(it != VIPList.end())
  2657.         client->sendVIPLogIn(loginPlayer->getGUID());
  2658. }
  2659.  
  2660. void Player::notifyLogOut(Player* logoutPlayer)
  2661. {
  2662.     if(!client)
  2663.         return;
  2664.  
  2665.     VIPSet::iterator it = VIPList.find(logoutPlayer->getGUID());
  2666.     if(it != VIPList.end())
  2667.         client->sendVIPLogOut(logoutPlayer->getGUID());
  2668. }
  2669.  
  2670. bool Player::removeVIP(uint32_t _guid)
  2671. {
  2672.     VIPSet::iterator it = VIPList.find(_guid);
  2673.     if(it == VIPList.end())
  2674.         return false;
  2675.  
  2676.     VIPList.erase(it);
  2677.     return true;
  2678. }
  2679.  
  2680. bool Player::addVIP(uint32_t _guid, const std::string& name, bool online, bool loading/* = false*/)
  2681. {
  2682.     if(guid == _guid)
  2683.     {
  2684.         if(!loading)
  2685.             sendTextMessage(MSG_STATUS_SMALL, "You cannot add yourself.");
  2686.  
  2687.         return false;
  2688.     }
  2689.  
  2690.     if(!loading && VIPList.size() > (size_t)(group ? group->getMaxVips(isPremium()) : g_config.getNumber(ConfigManager::VIPLIST_DEFAULT_LIMIT)))
  2691.     {
  2692.         sendTextMessage(MSG_STATUS_SMALL, "You cannot add more buddies.");
  2693.         return false;
  2694.     }
  2695.  
  2696.     VIPSet::iterator it = VIPList.find(_guid);
  2697.     if(it != VIPList.end())
  2698.     {
  2699.         if(!loading)
  2700.             sendTextMessage(MSG_STATUS_SMALL, "This player is already in your list.");
  2701.  
  2702.         return false;
  2703.     }
  2704.  
  2705.     VIPList.insert(_guid);
  2706.     if(!loading && client)
  2707.         client->sendVIP(_guid, name, online);
  2708.  
  2709.     return true;
  2710. }
  2711.  
  2712. //close container and its child containers
  2713. void Player::autoCloseContainers(const Container* container)
  2714. {
  2715.     typedef std::vector<uint32_t> CloseList;
  2716.     CloseList closeList;
  2717.     for(ContainerVector::iterator it = containerVec.begin(); it != containerVec.end(); ++it)
  2718.     {
  2719.         Container* tmp = it->second;
  2720.         while(tmp != NULL)
  2721.         {
  2722.             if(tmp->isRemoved() || tmp == container)
  2723.             {
  2724.                 closeList.push_back(it->first);
  2725.                 break;
  2726.             }
  2727.  
  2728.             tmp = dynamic_cast<Container*>(tmp->getParent());
  2729.         }
  2730.     }
  2731.  
  2732.     for(CloseList::iterator it = closeList.begin(); it != closeList.end(); ++it)
  2733.     {
  2734.         closeContainer(*it);
  2735.         if(client)
  2736.             client->sendCloseContainer(*it);
  2737.     }
  2738. }
  2739.  
  2740. bool Player::hasCapacity(const Item* item, uint32_t count) const
  2741. {
  2742.     if(hasFlag(PlayerFlag_HasInfiniteCapacity) || item->getTopParent() == this)
  2743.         return true;
  2744.  
  2745.     double itemWeight = 0;
  2746.     if(item->isStackable())
  2747.         itemWeight = Item::items[item->getID()].weight * count;
  2748.     else
  2749.         itemWeight = item->getWeight();
  2750.  
  2751.     return (itemWeight < getFreeCapacity());
  2752. }
  2753.  
  2754. ReturnValue Player::__queryAdd(int32_t index, const Thing* thing, uint32_t count, uint32_t flags, Creature*) const
  2755. {
  2756.     const Item* item = thing->getItem();
  2757.     if(!item)
  2758.         return RET_NOTPOSSIBLE;
  2759.  
  2760.     if(!item->isPickupable() || (hasFlag(PlayerFlag_CannotPickupItem) &&
  2761.         item->getParent() && item->getParent() != VirtualCylinder::virtualCylinder))
  2762.         return RET_CANNOTPICKUP;
  2763.  
  2764.     bool childOwner = ((flags & FLAG_CHILDISOWNER) == FLAG_CHILDISOWNER), skipLimit = ((flags & FLAG_NOLIMIT) == FLAG_NOLIMIT);
  2765.     if(childOwner)
  2766.     {
  2767.         //a child container is querying the player, just check if enough capacity
  2768.         if(skipLimit || hasCapacity(item, count))
  2769.             return RET_NOERROR;
  2770.  
  2771.         return RET_NOTENOUGHCAPACITY;
  2772.     }
  2773.  
  2774.     ReturnValue ret = RET_NOERROR;
  2775.     if((item->getSlotPosition() & SLOTP_HEAD) || (item->getSlotPosition() & SLOTP_NECKLACE) ||
  2776.         (item->getSlotPosition() & SLOTP_BACKPACK) || (item->getSlotPosition() & SLOTP_ARMOR) ||
  2777.         (item->getSlotPosition() & SLOTP_LEGS) || (item->getSlotPosition() & SLOTP_FEET) ||
  2778.         (item->getSlotPosition() & SLOTP_RING))
  2779.         ret = RET_CANNOTBEDRESSED;
  2780.     else if(item->getSlotPosition() & SLOTP_TWO_HAND)
  2781.         ret = RET_PUTTHISOBJECTINBOTHHANDS;
  2782.     else if((item->getSlotPosition() & SLOTP_RIGHT) || (item->getSlotPosition() & SLOTP_LEFT))
  2783.     {
  2784.         if(!g_config.getBool(ConfigManager::CLASSIC_EQUIPMENT_SLOTS))
  2785.             ret = RET_CANNOTBEDRESSED;
  2786.         else
  2787.             ret = RET_PUTTHISOBJECTINYOURHAND;
  2788.     }
  2789.  
  2790.     switch(index)
  2791.     {
  2792.         case SLOT_HEAD:
  2793.             if(item->getSlotPosition() & SLOTP_HEAD)
  2794.                 ret = RET_NOERROR;
  2795.             break;
  2796.         case SLOT_NECKLACE:
  2797.             if(item->getSlotPosition() & SLOTP_NECKLACE)
  2798.                 ret = RET_NOERROR;
  2799.             break;
  2800.         case SLOT_BACKPACK:
  2801.             if(item->getSlotPosition() & SLOTP_BACKPACK)
  2802.                 ret = RET_NOERROR;
  2803.             break;
  2804.         case SLOT_ARMOR:
  2805.             if(item->getSlotPosition() & SLOTP_ARMOR)
  2806.                 ret = RET_NOERROR;
  2807.             break;
  2808.         case SLOT_RIGHT:
  2809.             if(item->getSlotPosition() & SLOTP_RIGHT)
  2810.             {
  2811.                 if(!g_config.getBool(ConfigManager::CLASSIC_EQUIPMENT_SLOTS))
  2812.                 {
  2813.                     if(!item->isWeapon() || (item->getWeaponType() != WEAPON_SHIELD && !item->isDualWield()))
  2814.                         ret = RET_CANNOTBEDRESSED;
  2815.                     else
  2816.                     {
  2817.                         const Item* leftItem = inventory[SLOT_LEFT];
  2818.                         if(leftItem)
  2819.                         {
  2820.                             if((leftItem->getSlotPosition() | item->getSlotPosition()) & SLOTP_TWO_HAND)
  2821.                                 ret = RET_BOTHHANDSNEEDTOBEFREE;
  2822.                             else
  2823.                                 ret = RET_NOERROR;
  2824.                         }
  2825.                         else
  2826.                             ret = RET_NOERROR;
  2827.                     }
  2828.                 }
  2829.                 else if(item->getSlotPosition() & SLOTP_TWO_HAND)
  2830.                 {
  2831.                     if(inventory[SLOT_LEFT] && inventory[SLOT_LEFT] != item)
  2832.                         ret = RET_BOTHHANDSNEEDTOBEFREE;
  2833.                     else
  2834.                         ret = RET_NOERROR;
  2835.                 }
  2836.                 else if(inventory[SLOT_LEFT])
  2837.                 {
  2838.                     const Item* leftItem = inventory[SLOT_LEFT];
  2839.                     WeaponType_t type = item->getWeaponType(), leftType = leftItem->getWeaponType();
  2840.                     if(leftItem->getSlotPosition() & SLOTP_TWO_HAND)
  2841.                         ret = RET_DROPTWOHANDEDITEM;
  2842.                     else if(item == leftItem && count == item->getItemCount())
  2843.                         ret = RET_NOERROR;
  2844.                     else if(leftType == WEAPON_SHIELD && type == WEAPON_SHIELD)
  2845.                         ret = RET_CANONLYUSEONESHIELD;
  2846.                     else if(!leftItem->isWeapon() || !item->isWeapon() ||
  2847.                         leftType == WEAPON_SHIELD || leftType == WEAPON_AMMO ||
  2848.                         type == WEAPON_SHIELD || type == WEAPON_AMMO ||
  2849.                         (leftItem->isDualWield() && item->isDualWield()))
  2850.                         ret = RET_NOERROR;
  2851.                     else
  2852.                         ret = RET_CANONLYUSEONEWEAPON;
  2853.                 }
  2854.                 else
  2855.                     ret = RET_NOERROR;
  2856.             }
  2857.             break;
  2858.         case SLOT_LEFT:
  2859.             if(item->getSlotPosition() & SLOTP_LEFT)
  2860.             {
  2861.                 if(!g_config.getBool(ConfigManager::CLASSIC_EQUIPMENT_SLOTS))
  2862.                 {
  2863.                     if(!item->isWeapon() || item->getWeaponType() == WEAPON_SHIELD)
  2864.                         ret = RET_CANNOTBEDRESSED;
  2865.                     else if(inventory[SLOT_RIGHT] && (item->getSlotPosition() & SLOTP_TWO_HAND))
  2866.                         ret = RET_BOTHHANDSNEEDTOBEFREE;
  2867.                     else
  2868.                         ret = RET_NOERROR;
  2869.                 }
  2870.                 else if(item->getSlotPosition() & SLOTP_TWO_HAND)
  2871.                 {
  2872.                     if(inventory[SLOT_RIGHT] && inventory[SLOT_RIGHT] != item)
  2873.                         ret = RET_BOTHHANDSNEEDTOBEFREE;
  2874.                     else
  2875.                         ret = RET_NOERROR;
  2876.                 }
  2877.                 else if(inventory[SLOT_RIGHT])
  2878.                 {
  2879.                     const Item* rightItem = inventory[SLOT_RIGHT];
  2880.                     WeaponType_t type = item->getWeaponType(), rightType = rightItem->getWeaponType();
  2881.                     if(rightItem->getSlotPosition() & SLOTP_TWO_HAND)
  2882.                         ret = RET_DROPTWOHANDEDITEM;
  2883.                     else if(item == rightItem && count == item->getItemCount())
  2884.                         ret = RET_NOERROR;
  2885.                     else if(rightType == WEAPON_SHIELD && type == WEAPON_SHIELD)
  2886.                         ret = RET_CANONLYUSEONESHIELD;
  2887.                     else if(!rightItem->isWeapon() || !item->isWeapon() ||
  2888.                         rightType == WEAPON_SHIELD || rightType == WEAPON_AMMO ||
  2889.                         type == WEAPON_SHIELD || type == WEAPON_AMMO ||
  2890.                         (rightItem->isDualWield() && item->isDualWield()))
  2891.                         ret = RET_NOERROR;
  2892.                     else
  2893.                         ret = RET_CANONLYUSEONEWEAPON;
  2894.                 }
  2895.                 else
  2896.                     ret = RET_NOERROR;
  2897.             }
  2898.             break;
  2899.         case SLOT_LEGS:
  2900.             if(item->getSlotPosition() & SLOTP_LEGS)
  2901.                 ret = RET_NOERROR;
  2902.             break;
  2903.         case SLOT_FEET:
  2904.             if(item->getSlotPosition() & SLOTP_FEET)
  2905.                 ret = RET_NOERROR;
  2906.             break;
  2907.         case SLOT_RING:
  2908.             if(item->getSlotPosition() & SLOTP_RING)
  2909.                 ret = RET_NOERROR;
  2910.             break;
  2911.         case SLOT_AMMO:
  2912.             if((item->getSlotPosition() & SLOTP_AMMO) || g_config.getBool(ConfigManager::CLASSIC_EQUIPMENT_SLOTS))
  2913.                 ret = RET_NOERROR;
  2914.             break;
  2915.         case SLOT_WHEREEVER:
  2916.         case -1:
  2917.             ret = RET_NOTENOUGHROOM;
  2918.             break;
  2919.         default:
  2920.             ret = RET_NOTPOSSIBLE;
  2921.             break;
  2922.     }
  2923.  
  2924.     Player* self = const_cast<Player*>(this);
  2925.     if(ret == RET_NOERROR || ret == RET_NOTENOUGHROOM)
  2926.     {
  2927.         //need an exchange with source?
  2928.         Item* tmpItem = NULL;
  2929.         if((tmpItem = getInventoryItem((slots_t)index)) && (!tmpItem->isStackable() || tmpItem->getID() != item->getID()))
  2930.             return RET_NEEDEXCHANGE;
  2931.  
  2932.         if(!hasCapacity(item, count)) //check if enough capacity
  2933.             return RET_NOTENOUGHCAPACITY;
  2934.  
  2935.         if(!g_moveEvents->onPlayerEquip(self, const_cast<Item*>(item), (slots_t)index, true))
  2936.             return RET_CANNOTBEDRESSED;
  2937.     }
  2938.  
  2939.     if(index == SLOT_LEFT || index == SLOT_RIGHT)
  2940.     {
  2941.         if(ret == RET_NOERROR && item->getWeaponType() != WEAPON_NONE)
  2942.             self->setLastAttack(OTSYS_TIME());
  2943.  
  2944.         Item* tmpItem = inventory[(slots_t)index];
  2945.         if(ret == RET_NOTENOUGHROOM && g_game.internalAddItem(NULL, self, tmpItem, INDEX_WHEREEVER) == RET_NOERROR)
  2946.         {
  2947.             self->sendRemoveInventoryItem((slots_t)index, tmpItem);
  2948.             self->onRemoveInventoryItem((slots_t)index, tmpItem);
  2949.  
  2950.             self->inventory[(slots_t)index] = NULL;
  2951.             self->updateWeapon();
  2952.             self->inventoryWeight -= tmpItem->getWeight();
  2953.             self->sendStats();
  2954.         }
  2955.     }
  2956.  
  2957.     return ret;
  2958. }
  2959.  
  2960. ReturnValue Player::__queryMaxCount(int32_t index, const Thing* thing, uint32_t count, uint32_t& maxQueryCount,
  2961.     uint32_t flags) const
  2962. {
  2963.     const Item* item = thing->getItem();
  2964.     if(!item)
  2965.     {
  2966.         maxQueryCount = 0;
  2967.         return RET_NOTPOSSIBLE;
  2968.     }
  2969.  
  2970.     if(index == INDEX_WHEREEVER)
  2971.     {
  2972.         uint32_t n = 0;
  2973.         for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  2974.         {
  2975.             if(Item* inventoryItem = inventory[i])
  2976.             {
  2977.                 if(Container* subContainer = inventoryItem->getContainer())
  2978.                 {
  2979.                     uint32_t queryCount = 0;
  2980.                     subContainer->__queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags);
  2981.  
  2982.                     //iterate through all items, including sub-containers (deep search)
  2983.                     n += queryCount;
  2984.                     for(ContainerIterator cit = subContainer->begin(); cit != subContainer->end(); ++cit)
  2985.                     {
  2986.                         if(Container* tmpContainer  = (*cit)->getContainer())
  2987.                         {
  2988.                             queryCount = 0;
  2989.                             tmpContainer->__queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags);
  2990.                             n += queryCount;
  2991.                         }
  2992.                     }
  2993.                 }
  2994.                 else if(inventoryItem->isStackable() && item->getID() == inventoryItem->getID() && inventoryItem->getItemCount() < 100)
  2995.                 {
  2996.                     uint32_t remainder = (100 - inventoryItem->getItemCount());
  2997.                     if(__queryAdd(i, item, remainder, flags) == RET_NOERROR)
  2998.                         n += remainder;
  2999.                 }
  3000.             }
  3001.             else if(__queryAdd(i, item, item->getItemCount(), flags) == RET_NOERROR)
  3002.             {
  3003.                 if(item->isStackable())
  3004.                     n += 100;
  3005.                 else
  3006.                     n += 1;
  3007.             }
  3008.         }
  3009.  
  3010.         maxQueryCount = n;
  3011.     }
  3012.     else
  3013.     {
  3014.         const Thing* destThing = __getThing(index);
  3015.         const Item* destItem = NULL;
  3016.         if(destThing)
  3017.             destItem = destThing->getItem();
  3018.  
  3019.         if(destItem)
  3020.         {
  3021.             if(destItem->isStackable() && item->getID() == destItem->getID() && destItem->getItemCount() < 100)
  3022.                 maxQueryCount = 100 - destItem->getItemCount();
  3023.             else
  3024.                 maxQueryCount = 0;
  3025.         }
  3026.         else if(__queryAdd(index, item, count, flags) == RET_NOERROR)
  3027.         {
  3028.             if(item->isStackable())
  3029.                 maxQueryCount = 100;
  3030.             else
  3031.                 maxQueryCount = 1;
  3032.  
  3033.             return RET_NOERROR;
  3034.         }
  3035.     }
  3036.  
  3037.     if(maxQueryCount < count)
  3038.         return RET_NOTENOUGHROOM;
  3039.  
  3040.     return RET_NOERROR;
  3041. }
  3042.  
  3043. ReturnValue Player::__queryRemove(const Thing* thing, uint32_t count, uint32_t flags, Creature*) const
  3044. {
  3045.     int32_t index = __getIndexOfThing(thing);
  3046.     if(index == -1)
  3047.         return RET_NOTPOSSIBLE;
  3048.  
  3049.     const Item* item = thing->getItem();
  3050.     if(!item)
  3051.         return RET_NOTPOSSIBLE;
  3052.  
  3053.     if(!count || (item->isStackable() && count > item->getItemCount()))
  3054.         return RET_NOTPOSSIBLE;
  3055.  
  3056.      if(!item->isMovable() && !hasBitSet(FLAG_IGNORENOTMOVABLE, flags))
  3057.         return RET_NOTMOVABLE;
  3058.  
  3059.     return RET_NOERROR;
  3060. }
  3061.  
  3062. Cylinder* Player::__queryDestination(int32_t& index, const Thing* thing, Item** destItem,
  3063.     uint32_t& flags)
  3064. {
  3065.     if(!index /*drop to capacity window*/ || index == INDEX_WHEREEVER)
  3066.     {
  3067.         *destItem = NULL;
  3068.         const Item* item = thing->getItem();
  3069.         if(!item)
  3070.             return this;
  3071.  
  3072.         bool autoStack = (flags & FLAG_IGNOREAUTOSTACK) != FLAG_IGNOREAUTOSTACK;
  3073.         if((!autoStack || !item->isStackable()) && backpack.first &&
  3074.             backpack.first->__queryAdd(backpack.second, item, item->getItemCount(), flags))
  3075.         {
  3076.             index = backpack.second;
  3077.             if(backpack.second != INDEX_WHEREEVER)
  3078.                 ++backpack.second;
  3079.  
  3080.             return backpack.first;
  3081.         }
  3082.  
  3083.         std::list<std::pair<Container*, int32_t> > containers;
  3084.         std::list<std::pair<Cylinder*, int32_t> > freeSlots;
  3085.         for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3086.         {
  3087.             if(Item* invItem = inventory[i])
  3088.             {
  3089.                 if(invItem == item || invItem == tradeItem)
  3090.                     continue;
  3091.  
  3092.                 if(autoStack && item->isStackable() && __queryAdd(i, item, item->getItemCount(), 0)
  3093.                     == RET_NOERROR && invItem->getID() == item->getID() && invItem->getItemCount() < 100)
  3094.                 {
  3095.                     *destItem = invItem;
  3096.                     index = i;
  3097.                     return this;
  3098.                 }
  3099.  
  3100.                 if(Container* container = invItem->getContainer())
  3101.                 {
  3102.                     if(!autoStack && container->__queryAdd(
  3103.                         INDEX_WHEREEVER, item, item->getItemCount(), flags) == RET_NOERROR)
  3104.                     {
  3105.                         index = INDEX_WHEREEVER;
  3106.                         backpack = std::make_pair(container, index + 1);
  3107.                         return container;
  3108.                     }
  3109.  
  3110.                     containers.push_back(std::make_pair(container, 0));
  3111.                 }
  3112.             }
  3113.             else if(!autoStack)
  3114.             {
  3115.                 if(__queryAdd(i, item, item->getItemCount(), 0) == RET_NOERROR)
  3116.                 {
  3117.                     index = i;
  3118.                     return this;
  3119.                 }
  3120.             }
  3121.             else
  3122.                 freeSlots.push_back(std::make_pair(this, i));
  3123.         }
  3124.  
  3125.         int32_t deepness = g_config.getNumber(ConfigManager::PLAYER_DEEPNESS);
  3126.         while(!containers.empty())
  3127.         {
  3128.             Container* tmpContainer = containers.front().first;
  3129.             int32_t level = containers.front().second;
  3130.  
  3131.             containers.pop_front();
  3132.             if(!tmpContainer)
  3133.                 continue;
  3134.  
  3135.             for(uint32_t n = 0; n < tmpContainer->capacity(); ++n)
  3136.             {
  3137.                 if(Item* tmpItem = tmpContainer->getItem(n))
  3138.                 {
  3139.                     if(tmpItem == item || tmpItem == tradeItem)
  3140.                         continue;
  3141.  
  3142.                     if(autoStack && item->isStackable() && tmpContainer->__queryAdd(n, item, item->getItemCount(),
  3143.                         0) == RET_NOERROR && tmpItem->getID() == item->getID() && tmpItem->getItemCount() < 100)
  3144.                     {
  3145.                         index = n;
  3146.                         *destItem = tmpItem;
  3147.                         return tmpContainer;
  3148.                     }
  3149.  
  3150.                     if(Container* container = tmpItem->getContainer())
  3151.                     {
  3152.                         if(!autoStack && container->__queryAdd(INDEX_WHEREEVER,
  3153.                             item, item->getItemCount(), flags) == RET_NOERROR)
  3154.                         {
  3155.                             index = INDEX_WHEREEVER;
  3156.                             backpack = std::make_pair(container, index + 1);
  3157.                             return container;
  3158.                         }
  3159.  
  3160.                         if(deepness < 0 || level < deepness)
  3161.                             containers.push_back(std::make_pair(container, level + 1));
  3162.                     }
  3163.                 }
  3164.                 else
  3165.                 {
  3166.                     if(!autoStack)
  3167.                     {
  3168.                         if(tmpContainer->__queryAdd(n, item, item->getItemCount(), 0) == RET_NOERROR)
  3169.                         {
  3170.                             index = n;
  3171.                             backpack = std::make_pair(tmpContainer, index + 1);
  3172.                             return tmpContainer;
  3173.                         }
  3174.                     }
  3175.                     else
  3176.                         freeSlots.push_back(std::make_pair(tmpContainer, n));
  3177.  
  3178.                     break; // one slot to check is definitely enough.
  3179.                 }
  3180.             }
  3181.         }
  3182.  
  3183.         if(autoStack)
  3184.         {
  3185.             while(!freeSlots.empty())
  3186.             {
  3187.                 Cylinder* tmpCylinder = freeSlots.front().first;
  3188.                 int32_t i = freeSlots.front().second;
  3189.  
  3190.                 freeSlots.pop_front();
  3191.                 if(!tmpCylinder)
  3192.                     continue;
  3193.  
  3194.                 if(tmpCylinder->__queryAdd(i, item, item->getItemCount(), flags) == RET_NOERROR)
  3195.                 {
  3196.                     index = i;
  3197.                     return tmpCylinder;
  3198.                 }
  3199.             }
  3200.         }
  3201.  
  3202.         return this;
  3203.     }
  3204.  
  3205.     Thing* destThing = __getThing(index);
  3206.     if(destThing)
  3207.         *destItem = destThing->getItem();
  3208.  
  3209.     if(Cylinder* subCylinder = dynamic_cast<Cylinder*>(destThing))
  3210.     {
  3211.         index = INDEX_WHEREEVER;
  3212.         *destItem = NULL;
  3213.         return subCylinder;
  3214.     }
  3215.  
  3216.     return this;
  3217. }
  3218.  
  3219. void Player::__addThing(Creature* actor, Thing* thing)
  3220. {
  3221.     __addThing(actor, 0, thing);
  3222. }
  3223.  
  3224. void Player::__addThing(Creature*, int32_t index, Thing* thing)
  3225. {
  3226.     if(index < 0 || index > 11)
  3227.     {
  3228. #ifdef __DEBUG_MOVESYS__
  3229.         std::clog << "Failure: [Player::__addThing], " << "player: " << getName() << ", index: " << index << ", index < 0 || index > 11" << std::endl;
  3230. #endif
  3231.         return /*RET_NOTPOSSIBLE*/;
  3232.     }
  3233.  
  3234.     if(!index)
  3235.     {
  3236. #ifdef __DEBUG_MOVESYS__
  3237.         std::clog << "Failure: [Player::__addThing], " << "player: " << getName() << ", index == 0" << std::endl;
  3238. #endif
  3239.         return /*RET_NOTENOUGHROOM*/;
  3240.     }
  3241.  
  3242.     Item* item = thing->getItem();
  3243.     if(!item)
  3244.     {
  3245. #ifdef __DEBUG_MOVESYS__
  3246.         std::clog << "Failure: [Player::__addThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3247. #endif
  3248.         return /*RET_NOTPOSSIBLE*/;
  3249.     }
  3250.  
  3251.     item->setParent(this);
  3252.     inventory[index] = item;
  3253.  
  3254.     //send to client
  3255.     sendAddInventoryItem((slots_t)index, item);
  3256.     //event methods
  3257.     onAddInventoryItem((slots_t)index, item);
  3258. }
  3259.  
  3260. void Player::__updateThing(Thing* thing, uint16_t itemId, uint32_t count)
  3261. {
  3262.     int32_t index = __getIndexOfThing(thing);
  3263.     if(index == -1)
  3264.     {
  3265. #ifdef __DEBUG_MOVESYS__
  3266.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", index == -1" << std::endl;
  3267. #endif
  3268.         return /*RET_NOTPOSSIBLE*/;
  3269.     }
  3270.  
  3271.     Item* item = thing->getItem();
  3272.     if(!item)
  3273.     {
  3274. #ifdef __DEBUG_MOVESYS__
  3275.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3276. #endif
  3277.         return /*RET_NOTPOSSIBLE*/;
  3278.     }
  3279.  
  3280.     const ItemType& oldType = Item::items[item->getID()];
  3281.     const ItemType& newType = Item::items[itemId];
  3282.  
  3283.     item->setID(itemId);
  3284.     item->setSubType(count);
  3285.  
  3286.     //send to client
  3287.     sendUpdateInventoryItem((slots_t)index, item, item);
  3288.     //event methods
  3289.     onUpdateInventoryItem((slots_t)index, item, oldType, item, newType);
  3290. }
  3291.  
  3292. void Player::__replaceThing(uint32_t index, Thing* thing)
  3293. {
  3294.     if(index > 11)
  3295.     {
  3296. #ifdef __DEBUG_MOVESYS__
  3297.         std::clog << "Failure: [Player::__replaceThing], " << "player: " << getName() << ", index: " << index << ", index < 0 || index > 11" << std::endl;
  3298. #endif
  3299.         return /*RET_NOTPOSSIBLE*/;
  3300.     }
  3301.  
  3302.     Item* oldItem = getInventoryItem((slots_t)index);
  3303.     if(!oldItem)
  3304.     {
  3305. #ifdef __DEBUG_MOVESYS__
  3306.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", oldItem == NULL" << std::endl;
  3307. #endif
  3308.         return /*RET_NOTPOSSIBLE*/;
  3309.     }
  3310.  
  3311.     Item* item = thing->getItem();
  3312.     if(!item)
  3313.     {
  3314. #ifdef __DEBUG_MOVESYS__
  3315.         std::clog << "Failure: [Player::__updateThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3316. #endif
  3317.         return /*RET_NOTPOSSIBLE*/;
  3318.     }
  3319.  
  3320.     const ItemType& oldType = Item::items[oldItem->getID()];
  3321.     const ItemType& newType = Item::items[item->getID()];
  3322.  
  3323.     //send to client
  3324.     sendUpdateInventoryItem((slots_t)index, oldItem, item);
  3325.     //event methods
  3326.     onUpdateInventoryItem((slots_t)index, oldItem, oldType, item, newType);
  3327.  
  3328.     item->setParent(this);
  3329.     inventory[index] = item;
  3330. }
  3331.  
  3332. void Player::__removeThing(Thing* thing, uint32_t count)
  3333. {
  3334.     Item* item = thing->getItem();
  3335.     if(!item)
  3336.     {
  3337. #ifdef __DEBUG_MOVESYS__
  3338.         std::clog << "Failure: [Player::__removeThing], " << "player: " << getName() << ", item == NULL" << std::endl;
  3339. #endif
  3340.         return /*RET_NOTPOSSIBLE*/;
  3341.     }
  3342.  
  3343.     int32_t index = __getIndexOfThing(thing);
  3344.     if(index == -1)
  3345.     {
  3346. #ifdef __DEBUG_MOVESYS__
  3347.         std::clog << "Failure: [Player::__removeThing], " << "player: " << getName() << ", index == -1" << std::endl;
  3348. #endif
  3349.         return /*RET_NOTPOSSIBLE*/;
  3350.     }
  3351.  
  3352.     if(item->isStackable())
  3353.     {
  3354.         if(count == item->getItemCount())
  3355.         {
  3356.             //send change to client
  3357.             sendRemoveInventoryItem((slots_t)index, item);
  3358.             //event methods
  3359.             onRemoveInventoryItem((slots_t)index, item);
  3360.  
  3361.             item->setParent(NULL);
  3362.             inventory[index] = NULL;
  3363.         }
  3364.         else
  3365.         {
  3366.             item->setItemCount(std::max(0, (int32_t)(item->getItemCount() - count)));
  3367.             const ItemType& it = Item::items[item->getID()];
  3368.  
  3369.             //send change to client
  3370.             sendUpdateInventoryItem((slots_t)index, item, item);
  3371.             //event methods
  3372.             onUpdateInventoryItem((slots_t)index, item, it, item, it);
  3373.         }
  3374.     }
  3375.     else
  3376.     {
  3377.         //send change to client
  3378.         sendRemoveInventoryItem((slots_t)index, item);
  3379.         //event methods
  3380.         onRemoveInventoryItem((slots_t)index, item);
  3381.  
  3382.         item->setParent(NULL);
  3383.         inventory[index] = NULL;
  3384.     }
  3385. }
  3386.  
  3387. Thing* Player::__getThing(uint32_t index) const
  3388. {
  3389.     if(index > SLOT_PRE_FIRST && index < SLOT_LAST)
  3390.         return inventory[index];
  3391.  
  3392.     return NULL;
  3393. }
  3394.  
  3395. int32_t Player::__getIndexOfThing(const Thing* thing) const
  3396. {
  3397.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3398.     {
  3399.         if(inventory[i] == thing)
  3400.             return i;
  3401.     }
  3402.  
  3403.     return -1;
  3404. }
  3405.  
  3406. int32_t Player::__getFirstIndex() const
  3407. {
  3408.     return SLOT_FIRST;
  3409. }
  3410.  
  3411. int32_t Player::__getLastIndex() const
  3412. {
  3413.     return SLOT_LAST;
  3414. }
  3415.  
  3416. uint32_t Player::__getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/, bool itemCount /*= true*/) const
  3417. {
  3418.     Item* item = NULL;
  3419.     Container* container = NULL;
  3420.  
  3421.     uint32_t count = 0;
  3422.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3423.     {
  3424.         if(!(item = inventory[i]))
  3425.             continue;
  3426.  
  3427.         if(item->getID() == itemId)
  3428.             count += Item::countByType(item, subType, itemCount);
  3429.  
  3430.         if(!(container = item->getContainer()))
  3431.             continue;
  3432.  
  3433.         for(ContainerIterator it = container->begin(), end = container->end(); it != end; ++it)
  3434.         {
  3435.             if((*it)->getID() == itemId)
  3436.                 count += Item::countByType(*it, subType, itemCount);
  3437.         }
  3438.     }
  3439.  
  3440.     return count;
  3441.  
  3442. }
  3443.  
  3444. std::map<uint32_t, uint32_t>& Player::__getAllItemTypeCount(std::map<uint32_t,
  3445.     uint32_t>& countMap, bool itemCount/* = true*/) const
  3446. {
  3447.     Item* item = NULL;
  3448.     Container* container = NULL;
  3449.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3450.     {
  3451.         if(!(item = inventory[i]))
  3452.             continue;
  3453.  
  3454.         countMap[item->getID()] += Item::countByType(item, -1, itemCount);
  3455.         if(!(container = item->getContainer()))
  3456.             continue;
  3457.  
  3458.         for(ContainerIterator it = container->begin(), end = container->end(); it != end; ++it)
  3459.             countMap[(*it)->getID()] += Item::countByType(*it, -1, itemCount);
  3460.     }
  3461.  
  3462.     return countMap;
  3463. }
  3464.  
  3465. void Player::postAddNotification(Creature*, Thing* thing, const Cylinder* oldParent,
  3466.     int32_t index, CylinderLink_t link /*= LINK_OWNER*/)
  3467. {
  3468.     if(link == LINK_OWNER) //calling movement scripts
  3469.         g_moveEvents->onPlayerEquip(this, thing->getItem(), (slots_t)index, false);
  3470.  
  3471.     bool requireListUpdate = true;
  3472.     if(link == LINK_OWNER || link == LINK_TOPPARENT)
  3473.     {
  3474.         if(const Item* item = (oldParent ? oldParent->getItem() : NULL))
  3475.         {
  3476.             assert(item->getContainer() != NULL);
  3477.             requireListUpdate = item->getContainer()->getHoldingPlayer() != this;
  3478.         }
  3479.         else
  3480.             requireListUpdate = oldParent != this;
  3481.  
  3482.         updateInventoryWeight();
  3483.         updateItemsLight();
  3484.         updateWeapon();
  3485.         sendStats();
  3486.     }
  3487.  
  3488.     if(const Item* item = thing->getItem())
  3489.     {
  3490.         if(const Container* container = item->getContainer())
  3491.             onSendContainer(container);
  3492.     }
  3493.     else if(const Creature* creature = thing->getCreature())
  3494.     {
  3495.         if(creature != this)
  3496.             return;
  3497.  
  3498.         std::vector<Container*> containers;
  3499.         for(ContainerVector::iterator it = containerVec.begin(); it != containerVec.end(); ++it)
  3500.         {
  3501.             if(!Position::areInRange<1,1,0>(it->second->getPosition(), getPosition()))
  3502.                 containers.push_back(it->second);
  3503.         }
  3504.  
  3505.         for(std::vector<Container*>::const_iterator it = containers.begin(); it != containers.end(); ++it)
  3506.             autoCloseContainers(*it);
  3507.     }
  3508. }
  3509.  
  3510. void Player::postRemoveNotification(Creature*, Thing* thing, const Cylinder* newParent,
  3511.     int32_t index, bool isCompleteRemoval, CylinderLink_t link/* = LINK_OWNER*/)
  3512. {
  3513.     if(link == LINK_OWNER) //calling movement scripts
  3514.         g_moveEvents->onPlayerDeEquip(this, thing->getItem(), (slots_t)index, isCompleteRemoval);
  3515.  
  3516.     bool requireListUpdate = true;
  3517.     if(link == LINK_OWNER || link == LINK_TOPPARENT)
  3518.     {
  3519.         if(const Item* item = (newParent ? newParent->getItem() : NULL))
  3520.         {
  3521.             assert(item->getContainer() != NULL);
  3522.             requireListUpdate = item->getContainer()->getHoldingPlayer() == this;
  3523.         }
  3524.         else
  3525.             requireListUpdate = newParent == this;
  3526.  
  3527.         updateInventoryWeight();
  3528.         updateItemsLight();
  3529.         updateWeapon();
  3530.         sendStats();
  3531.     }
  3532.  
  3533.     if(const Item* item = thing->getItem())
  3534.     {
  3535.         if(const Container* container = item->getContainer())
  3536.         {
  3537.             if(container->isRemoved() || !Position::areInRange<1,1,0>(getPosition(), container->getPosition()))
  3538.                 autoCloseContainers(container);
  3539.             else if(container->getTopParent() == this)
  3540.                 onSendContainer(container);
  3541.             else if(const Container* topContainer = dynamic_cast<const Container*>(container->getTopParent()))
  3542.             {
  3543.                 if(const Depot* depot = dynamic_cast<const Depot*>(topContainer))
  3544.                 {
  3545.                     bool isOwner = false;
  3546.                     for(DepotMap::iterator it = depots.begin(); it != depots.end(); ++it)
  3547.                     {
  3548.                         if(it->second.first != depot)
  3549.                             continue;
  3550.  
  3551.                         isOwner = true;
  3552.                         onSendContainer(container);
  3553.                     }
  3554.  
  3555.                     if(!isOwner)
  3556.                         autoCloseContainers(container);
  3557.                 }
  3558.                 else
  3559.                     onSendContainer(container);
  3560.             }
  3561.             else
  3562.                 autoCloseContainers(container);
  3563.         }
  3564.     }
  3565. }
  3566.  
  3567. void Player::__internalAddThing(Thing* thing)
  3568. {
  3569.     __internalAddThing(0, thing);
  3570. }
  3571.  
  3572. void Player::__internalAddThing(uint32_t index, Thing* thing)
  3573. {
  3574. #ifdef __DEBUG_MOVESYS__
  3575.     std::clog << "[Player::__internalAddThing] index: " << index << std::endl;
  3576.  
  3577. #endif
  3578.     if(!index || index > 11)
  3579.     {
  3580. #ifdef __DEBUG_MOVESYS__
  3581.         std::clog << "Failure: [Player::__internalAddThing] index == 0 || index > 11" << std::endl;
  3582. #endif
  3583.         return;
  3584.     }
  3585.  
  3586.     if(inventory[index])
  3587.     {
  3588. #ifdef __DEBUG_MOVESYS__
  3589.         std::clog << "Warning: [Player::__internalAddThing], player: " << getName() << ", items[index] is not empty." << std::endl;
  3590. #endif
  3591.         return;
  3592.     }
  3593.  
  3594.     Item* item = thing->getItem();
  3595.     if(!item)
  3596.     {
  3597. #ifdef __DEBUG_MOVESYS__
  3598.         std::clog << "Failure: [Player::__internalAddThing] item == NULL" << std::endl;
  3599. #endif
  3600.         return;
  3601.     }
  3602.  
  3603.     inventory[index] = item;
  3604.     item->setParent(this);
  3605. }
  3606.  
  3607. bool Player::setFollowCreature(Creature* creature, bool fullPathSearch /*= false*/)
  3608. {
  3609.     bool deny = false;
  3610.     CreatureEventList followEvents = getCreatureEvents(CREATURE_EVENT_FOLLOW);
  3611.     for(CreatureEventList::iterator it = followEvents.begin(); it != followEvents.end(); ++it)
  3612.     {
  3613.         if(!(*it)->executeAction(this, creature) && !deny)
  3614.             deny = true;
  3615.     }
  3616.  
  3617.     if(deny || Creature::setFollowCreature(creature, fullPathSearch))
  3618.         return true;
  3619.  
  3620.     setFollowCreature(NULL);
  3621.     setAttackedCreature(NULL);
  3622.     if(!deny)
  3623.         sendCancelMessage(RET_THEREISNOWAY);
  3624.  
  3625.     sendCancelTarget();
  3626.     cancelNextWalk = true;
  3627.     return false;
  3628. }
  3629.  
  3630. bool Player::setAttackedCreature(Creature* creature)
  3631. {
  3632.     if(!Creature::setAttackedCreature(creature))
  3633.     {
  3634.         sendCancelTarget();
  3635.         return false;
  3636.     }
  3637.  
  3638.     if(chaseMode == CHASEMODE_FOLLOW && creature && !getNoMove())
  3639.     {
  3640.         if(followCreature != creature) //chase opponent
  3641.             setFollowCreature(creature);
  3642.     }
  3643.     else
  3644.         setFollowCreature(NULL);
  3645.  
  3646.     if(creature)
  3647.         Dispatcher::getInstance().addTask(createTask(boost::bind(&Game::checkCreatureAttack, &g_game, getID())));
  3648.  
  3649.     return true;
  3650. }
  3651.  
  3652. void Player::goToFollowCreature()
  3653. {
  3654.     if(!walkTask)
  3655.         Creature::goToFollowCreature();
  3656. }
  3657.  
  3658. void Player::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const
  3659. {
  3660.     Creature::getPathSearchParams(creature, fpp);
  3661.     fpp.fullPathSearch = true;
  3662. }
  3663.  
  3664. void Player::doAttacking(uint32_t)
  3665. {
  3666.     uint32_t attackSpeed = getAttackSpeed();
  3667.     if(attackSpeed == 0 || (hasCondition(CONDITION_PACIFIED) && !hasCustomFlag(PlayerCustomFlag_IgnorePacification)))
  3668.     {
  3669.         lastAttack = OTSYS_TIME();
  3670.         return;
  3671.     }
  3672.  
  3673.     if(!lastAttack)
  3674.         lastAttack = OTSYS_TIME() - attackSpeed - 1;
  3675.     else if((OTSYS_TIME() - lastAttack) < attackSpeed)
  3676.         return;
  3677.  
  3678.     if(const Weapon* _weapon = g_weapons->getWeapon(weapon))
  3679.     {
  3680.         if(_weapon->interruptSwing() && !canDoAction())
  3681.         {
  3682.             SchedulerTask* task = createSchedulerTask(getNextActionTime(),
  3683.                 boost::bind(&Game::checkCreatureAttack, &g_game, getID()));
  3684.             setNextActionTask(task);
  3685.         }
  3686.         else
  3687.         {
  3688.             if((!_weapon->hasExhaustion() || !hasCondition(CONDITION_EXHAUST)) && _weapon->useWeapon(this, weapon, attackedCreature))
  3689.                 lastAttack = OTSYS_TIME();
  3690.  
  3691.             updateWeapon();
  3692.         }
  3693.     }
  3694.     else if(Weapon::useFist(this, attackedCreature))
  3695.         lastAttack = OTSYS_TIME();
  3696. }
  3697.  
  3698. double Player::getGainedExperience(Creature* attacker) const
  3699. {
  3700.     if(!skillLoss)
  3701.         return 0;
  3702.  
  3703.     double rate = g_config.getDouble(ConfigManager::RATE_PVP_EXPERIENCE);
  3704.     if(rate <= 0)
  3705.         return 0;
  3706.  
  3707.     Player* attackerPlayer = attacker->getPlayer();
  3708.     if(!attackerPlayer || attackerPlayer == this)
  3709.         return 0;
  3710.  
  3711.     double attackerLevel = (double)attackerPlayer->getLevel(), min = g_config.getDouble(
  3712.         ConfigManager::EFP_MIN_THRESHOLD), max = g_config.getDouble(ConfigManager::EFP_MAX_THRESHOLD);
  3713.     if((min > 0.0 && level < (uint32_t)std::floor(attackerLevel * min)) || (max > 0.0 &&
  3714.         level > (uint32_t)std::floor(attackerLevel * max)))
  3715.         return 0;
  3716.  
  3717.     /*
  3718.         Formula
  3719.         a = attackers level * 0.9
  3720.         b = victims level
  3721.         c = victims experience
  3722.  
  3723.         result = (1 - (a / b)) * 0.05 * c
  3724.         Not affected by special multipliers(!)
  3725.     */
  3726.     uint32_t a = (uint32_t)std::floor(attackerLevel * 0.9), b = level;
  3727.     uint64_t c = getExperience();
  3728.     return (double)std::max((uint64_t)0, (uint64_t)std::floor(getDamageRatio(attacker)
  3729.         * std::max((double)0, ((double)(1 - (((double)a / b))))) * 0.05 * c)) * rate;
  3730. }
  3731.  
  3732. void Player::onFollowCreature(const Creature* creature)
  3733. {
  3734.     if(!creature)
  3735.         cancelNextWalk = true;
  3736. }
  3737.  
  3738. void Player::setChaseMode(chaseMode_t mode)
  3739. {
  3740.     if(chaseMode == mode)
  3741.         return;
  3742.  
  3743.     chaseMode = mode;
  3744.     if(chaseMode == CHASEMODE_FOLLOW)
  3745.     {
  3746.         if(!followCreature && attackedCreature && !getNoMove()) //chase opponent
  3747.             setFollowCreature(attackedCreature);
  3748.     }
  3749.     else if(attackedCreature)
  3750.     {
  3751.         setFollowCreature(NULL);
  3752.         cancelNextWalk = true;
  3753.     }
  3754. }
  3755.  
  3756. void Player::onWalkAborted()
  3757. {
  3758.     setNextWalkActionTask(NULL);
  3759.     sendCancelWalk();
  3760. }
  3761.  
  3762. void Player::onWalkComplete()
  3763. {
  3764.     if(!walkTask)
  3765.         return;
  3766.  
  3767.     walkTaskEvent = Scheduler::getInstance().addEvent(walkTask);
  3768.     walkTask = NULL;
  3769. }
  3770.  
  3771. void Player::getCreatureLight(LightInfo& light) const
  3772. {
  3773.     if(hasCustomFlag(PlayerCustomFlag_HasFullLight))
  3774.     {
  3775.         light.level = 0xFF;
  3776.         light.color = 215;
  3777.     }
  3778.     else if(internalLight.level > itemsLight.level)
  3779.         light = internalLight;
  3780.     else
  3781.         light = itemsLight;
  3782. }
  3783.  
  3784. void Player::updateItemsLight(bool internal/* = false*/)
  3785. {
  3786.     LightInfo maxLight, curLight;
  3787.     Item* item = NULL;
  3788.     for(int32_t i = SLOT_FIRST; i < SLOT_LAST; ++i)
  3789.     {
  3790.         if(!(item = getInventoryItem((slots_t)i)))
  3791.             continue;
  3792.  
  3793.         item->getLight(curLight);
  3794.         if(curLight.level > maxLight.level)
  3795.             maxLight = curLight;
  3796.     }
  3797.  
  3798.     if(maxLight.level != itemsLight.level || maxLight.color != itemsLight.color)
  3799.     {
  3800.         itemsLight = maxLight;
  3801.         if(!internal)
  3802.             g_game.changeLight(this);
  3803.     }
  3804. }
  3805.  
  3806. void Player::onAddCondition(ConditionType_t type, bool hadCondition)
  3807. {
  3808.     Creature::onAddCondition(type, hadCondition);
  3809.     if(type == CONDITION_GAMEMASTER)
  3810.         return;
  3811.  
  3812.     if(getLastPosition().x) // don't send if player have just logged in (its already done in protocolgame), or condition have no icons
  3813.         sendIcons();
  3814. }
  3815.  
  3816. void Player::onAddCombatCondition(ConditionType_t type, bool)
  3817. {
  3818.     std::string tmp;
  3819.     switch(type)
  3820.     {
  3821.         //client hardcoded
  3822.         case CONDITION_FIRE:
  3823.             tmp = "burning";
  3824.             break;
  3825.         case CONDITION_POISON:
  3826.             tmp = "poisoned";
  3827.             break;
  3828.         case CONDITION_ENERGY:
  3829.             tmp = "electrified";
  3830.             break;
  3831.         case CONDITION_FREEZING:
  3832.             tmp = "freezing";
  3833.             break;
  3834.         case CONDITION_DAZZLED:
  3835.             tmp = "dazzled";
  3836.             break;
  3837.         case CONDITION_CURSED:
  3838.             tmp = "cursed";
  3839.             break;
  3840.         case CONDITION_DROWN:
  3841.             tmp = "drowning";
  3842.             break;
  3843.         case CONDITION_DRUNK:
  3844.             tmp = "drunk";
  3845.             break;
  3846.         case CONDITION_PARALYZE:
  3847.             tmp = "paralyzed";
  3848.             break;
  3849.         case CONDITION_BLEEDING:
  3850.             tmp = "bleeding";
  3851.             break;
  3852.         default:
  3853.             break;
  3854.     }
  3855.  
  3856.     if(!tmp.empty())
  3857.         sendTextMessage(MSG_STATUS_DEFAULT, "You are " + tmp + ".");
  3858. }
  3859.  
  3860. void Player::onEndCondition(ConditionType_t type)
  3861. {
  3862.     Creature::onEndCondition(type);
  3863.     if(type == CONDITION_INFIGHT)
  3864.     {
  3865.         onIdleStatus();
  3866.         clearAttacked();
  3867.  
  3868.         pzLocked = false;
  3869.         if(skull < SKULL_RED)
  3870.             setSkull(SKULL_NONE);
  3871.  
  3872.         g_game.updateCreatureSkull(this);
  3873.     }
  3874.  
  3875.     sendIcons();
  3876. }
  3877.  
  3878. void Player::onCombatRemoveCondition(const Creature*, Condition* condition)
  3879. {
  3880.     //Creature::onCombatRemoveCondition(attacker, condition);
  3881.     bool remove = true;
  3882.     if(condition->getId() > 0)
  3883.     {
  3884.         remove = false;
  3885.         //Means the condition is from an item, id == slot
  3886.         if(g_game.getWorldType() == WORLDTYPE_HARDCORE)
  3887.         {
  3888.             if(Item* item = getInventoryItem((slots_t)condition->getId()))
  3889.             {
  3890.                 //25% chance to destroy the item
  3891.                 if(random_range(1, 100) < 26)
  3892.                     g_game.internalRemoveItem(NULL, item);
  3893.             }
  3894.         }
  3895.     }
  3896.  
  3897.     if(remove)
  3898.     {
  3899.         if(!canDoAction())
  3900.         {
  3901.             int32_t delay = getNextActionTime(false);
  3902.             delay -= (delay % EVENT_CREATURE_THINK_INTERVAL);
  3903.             if(delay < 0)
  3904.                 removeCondition(condition);
  3905.             else
  3906.                 condition->setTicks(delay);
  3907.         }
  3908.         else
  3909.             removeCondition(condition);
  3910.     }
  3911. }
  3912.  
  3913. void Player::onTickCondition(ConditionType_t type, int32_t interval, bool& _remove)
  3914. {
  3915.     Creature::onTickCondition(type, interval, _remove);
  3916.     if(type == CONDITION_HUNTING)
  3917.         useStamina(-(interval * g_config.getNumber(ConfigManager::RATE_STAMINA_LOSS)));
  3918. }
  3919.  
  3920. void Player::onTarget(Creature* target)
  3921. {
  3922.     Creature::onTarget(target);
  3923.  
  3924.     if(target == this)
  3925.     {
  3926.         addInFightTicks(false);
  3927.         return;
  3928.     }
  3929.  
  3930.     if(hasFlag(PlayerFlag_NotGainInFight))
  3931.         return;
  3932.  
  3933.     Player* targetPlayer = target->getPlayer();
  3934.     if(targetPlayer && !isPartner(targetPlayer) && !isAlly(targetPlayer))
  3935.     {
  3936.         if(!pzLocked && g_game.getWorldType() == WORLDTYPE_HARDCORE)
  3937.         {
  3938.             pzLocked = true;
  3939.             sendIcons();
  3940.         }
  3941.  
  3942.         if(getSkull() == SKULL_NONE && getSkullType(targetPlayer) == SKULL_YELLOW)
  3943.         {
  3944.             addAttacked(targetPlayer);
  3945.             targetPlayer->sendCreatureSkull(this);
  3946.         }
  3947.         else if(!targetPlayer->hasAttacked(this))
  3948.         {
  3949.             if(!pzLocked)
  3950.             {
  3951.                 pzLocked = true;
  3952.                 sendIcons();
  3953.             }
  3954.  
  3955.             if(!Combat::isInPvpZone(this, targetPlayer) && !isEnemy(this))
  3956.             {
  3957.                 addAttacked(targetPlayer);
  3958.  
  3959.                 if(targetPlayer->getSkull() == SKULL_NONE && getSkull() == SKULL_NONE)
  3960.                 {
  3961.                     setSkull(SKULL_WHITE);
  3962.                     g_game.updateCreatureSkull(this);
  3963.                 }
  3964.  
  3965.                 if(getSkull() == SKULL_NONE)
  3966.                     targetPlayer->sendCreatureSkull(this);
  3967.             }
  3968.         }
  3969.     }
  3970.  
  3971.     addInFightTicks(false);
  3972. }
  3973.  
  3974. void Player::onSummonTarget(Creature* summon, Creature* target)
  3975. {
  3976.     Creature::onSummonTarget(summon, target);
  3977.     onTarget(target);
  3978. }
  3979.  
  3980. void Player::onAttacked()
  3981. {
  3982.     Creature::onAttacked();
  3983.     addInFightTicks(false);
  3984. }
  3985.  
  3986. bool Player::checkLoginDelay() const
  3987. {
  3988.     return (!hasCustomFlag(PlayerCustomFlag_IgnoreLoginDelay) && OTSYS_TIME() <= (lastLoad + g_config.getNumber(
  3989.         ConfigManager::LOGIN_PROTECTION)));
  3990. }
  3991.  
  3992. void Player::onIdleStatus()
  3993. {
  3994.     Creature::onIdleStatus();
  3995.     if(party)
  3996.         party->clearPlayerPoints(this);
  3997. }
  3998.  
  3999. void Player::onPlacedCreature()
  4000. {
  4001.     //scripting event - onLogin
  4002.     if(!g_creatureEvents->playerLogin(this))
  4003.         kick(true, true);
  4004. }
  4005.  
  4006. void Player::onTargetDrain(Creature* target, int32_t points)
  4007. {
  4008.     if(points < 0)
  4009.         return;
  4010.  
  4011.     Creature::onTargetDrain(target, points);
  4012.     if(party && target && (!target->getMaster() || !target->getMaster()->getPlayer())
  4013.         && target->getMonster() && target->getMonster()->isHostile()) //we have fulfilled a requirement for shared experience
  4014.         party->addPlayerDamageMonster(this, points);
  4015. }
  4016.  
  4017. void Player::onSummonTargetDrain(Creature* summon, Creature* target, int32_t points)
  4018. {
  4019.     if(points < 0)
  4020.         return;
  4021.  
  4022.     Creature::onSummonTargetDrain(summon, target, points);
  4023.     if(party && target && (!target->getMaster() || !target->getMaster()->getPlayer())
  4024.         && target->getMonster() && target->getMonster()->isHostile()) //we have fulfilled a requirement for shared experience
  4025.         party->addPlayerDamageMonster(this, points);
  4026. }
  4027.  
  4028. void Player::onTargetGain(Creature* target, int32_t points)
  4029. {
  4030.     Creature::onTargetGain(target, points);
  4031.     if(!target || !party)
  4032.         return;
  4033.  
  4034.     Player* tmpPlayer = NULL;
  4035.     if(target->getPlayer())
  4036.         tmpPlayer = target->getPlayer();
  4037.     else if(target->getMaster() && target->getMaster()->getPlayer())
  4038.         tmpPlayer = target->getMaster()->getPlayer();
  4039.  
  4040.     if(isPartner(tmpPlayer))
  4041.         party->addPlayerHealedMember(this, points);
  4042. }
  4043.  
  4044. void Player::onUpdateQuest()
  4045. {
  4046.     sendTextMessage(MSG_EVENT_ADVANCE, "Your quest log has been updated.");
  4047. }
  4048.  
  4049. bool Player::getEnemy(const Player* player, War_t& data) const
  4050. {
  4051.     if(!guildId || !player || player->isRemoved())
  4052.         return false;
  4053.  
  4054.     uint32_t guild = player->getGuildId();
  4055.     if(!guild)
  4056.         return false;
  4057.  
  4058.     WarMap::const_iterator it = warMap.find(guild);
  4059.     if(it == warMap.end())
  4060.         return false;
  4061.  
  4062.     data = it->second;
  4063.     return true;
  4064. }
  4065.  
  4066. bool Player::isEnemy(const Player* player) const
  4067. {
  4068.     if(!guildId || !player || player->isRemoved())
  4069.         return false;
  4070.  
  4071.     uint32_t guild = player->getGuildId();
  4072.     if(!guild)
  4073.         return false;
  4074.  
  4075.     return !warMap.empty() && (
  4076.         warMap.find(guild) != warMap.end());
  4077. }
  4078.  
  4079. bool Player::isAlly(const Player* player) const
  4080. {
  4081.     return !warMap.empty() && player && player->getGuildId() == guildId;
  4082. }
  4083.  
  4084. bool Player::onKilledCreature(Creature* target, DeathEntry& entry)
  4085. {
  4086.     if(!Creature::onKilledCreature(target, entry))
  4087.         return false;
  4088.  
  4089.     if(hasFlag(PlayerFlag_NotGenerateLoot))
  4090.         target->setDropLoot(LOOT_DROP_NONE);
  4091.  
  4092.     Condition* condition = NULL;
  4093.     if(target->getMonster() && !target->isPlayerSummon() && !hasFlag(PlayerFlag_HasInfiniteStamina)
  4094.         && (condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_HUNTING,
  4095.         g_config.getNumber(ConfigManager::HUNTING_DURATION))))
  4096.         addCondition(condition);
  4097.  
  4098.     if(hasFlag(PlayerFlag_NotGainInFight) || getZone() != target->getZone())
  4099.         return true;
  4100.  
  4101.     Player* targetPlayer = target->getPlayer();
  4102.     if(!targetPlayer || Combat::isInPvpZone(this, targetPlayer)
  4103.         || isPartner(targetPlayer) || isAlly(targetPlayer))
  4104.         return true;
  4105.  
  4106.     War_t enemy;
  4107.     if(targetPlayer->getEnemy(this, enemy))
  4108.     {
  4109.         if(entry.isLast())
  4110.             IOGuild::getInstance()->updateWar(enemy);
  4111.  
  4112.         entry.setWar(enemy);
  4113.     }
  4114.  
  4115.     if(!entry.isJustify() || !hasCondition(CONDITION_INFIGHT))
  4116.         return true;
  4117.  
  4118.     if(!targetPlayer->hasAttacked(this) && target->getSkull() == SKULL_NONE
  4119.         && targetPlayer != this && (addUnjustifiedKill(targetPlayer, !enemy.war) || entry.isLast()))
  4120.         entry.setUnjustified();
  4121.  
  4122.     if(entry.isLast())
  4123.         addInFightTicks(true, g_config.getNumber(ConfigManager::WHITE_SKULL_TIME));
  4124.     return true;
  4125. }
  4126.  
  4127. bool Player::gainExperience(double& gainExp, Creature* target)
  4128. {
  4129.     if(!rateExperience(gainExp, target))
  4130.         return false;
  4131.  
  4132.     //soul regeneration
  4133.     if(gainExp >= level)
  4134.     {
  4135.         if(Condition* condition = Condition::createCondition(
  4136.             CONDITIONID_DEFAULT, CONDITION_SOUL, 4 * 60 * 1000))
  4137.         {
  4138.             condition->setParam(CONDITIONPARAM_SOULGAIN,
  4139.                 vocation->getGainAmount(GAIN_SOUL));
  4140.             condition->setParam(CONDITIONPARAM_SOULTICKS,
  4141.                 (vocation->getGainTicks(GAIN_SOUL) * 1000));
  4142.             addCondition(condition);
  4143.         }
  4144.     }
  4145.  
  4146.     addExperience((uint64_t)gainExp);
  4147.     return true;
  4148. }
  4149.  
  4150. bool Player::rateExperience(double& gainExp, Creature* target)
  4151. {
  4152.     if(hasFlag(PlayerFlag_NotGainExperience) || gainExp <= 0)
  4153.         return false;
  4154.  
  4155.     if(target->getPlayer())
  4156.         return true;
  4157.  
  4158.     gainExp *= rates[SKILL__LEVEL] * g_game.getExperienceStage(level,
  4159.         vocation->getExperienceMultiplier());
  4160.     if(!hasFlag(PlayerFlag_HasInfiniteStamina))
  4161.     {
  4162.         int32_t minutes = getStaminaMinutes();
  4163.         if(minutes >= g_config.getNumber(ConfigManager::STAMINA_LIMIT_TOP))
  4164.         {
  4165.             if(isPremium() || !g_config.getBool(ConfigManager::STAMINA_BONUS_PREMIUM))
  4166.                 gainExp *= g_config.getDouble(ConfigManager::RATE_STAMINA_ABOVE);
  4167.         }
  4168.         else if(minutes < (g_config.getNumber(ConfigManager::STAMINA_LIMIT_BOTTOM)) && minutes > 0)
  4169.             gainExp *= g_config.getDouble(ConfigManager::RATE_STAMINA_UNDER);
  4170.         else if(minutes <= 0)
  4171.             gainExp = 0;
  4172.     }
  4173.     else if(isPremium() || !g_config.getBool(ConfigManager::STAMINA_BONUS_PREMIUM))
  4174.         gainExp *= g_config.getDouble(ConfigManager::RATE_STAMINA_ABOVE);
  4175.  
  4176.     return true;
  4177. }
  4178.  
  4179. void Player::onGainExperience(double& gainExp, Creature* target, bool multiplied)
  4180. {
  4181.     uint64_t tmp = experience;
  4182.     if(party && party->isSharedExperienceEnabled() && party->isSharedExperienceActive())
  4183.     {
  4184.         party->shareExperience(gainExp, target, multiplied);
  4185.         rateExperience(gainExp, target);
  4186.         return; //we will get a share of the experience through the sharing mechanism
  4187.     }
  4188.  
  4189.     if(gainExperience(gainExp, target))
  4190.         Creature::onGainExperience(gainExp, target, true);
  4191.  
  4192.     CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  4193.     for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  4194.         (*it)->executeAdvance(this, SKILL__EXPERIENCE, tmp, experience);
  4195. }
  4196.  
  4197. void Player::onGainSharedExperience(double& gainExp, Creature* target, bool)
  4198. {
  4199.     if(gainExperience(gainExp, target))
  4200.         Creature::onGainSharedExperience(gainExp, target, true);
  4201. }
  4202.  
  4203. bool Player::isImmune(CombatType_t type) const
  4204. {
  4205.     return hasCustomFlag(PlayerCustomFlag_IsImmune) || Creature::isImmune(type);
  4206. }
  4207.  
  4208. bool Player::isImmune(ConditionType_t type) const
  4209. {
  4210.     return hasCustomFlag(PlayerCustomFlag_IsImmune) || Creature::isImmune(type);
  4211. }
  4212.  
  4213. bool Player::isProtected() const
  4214. {
  4215.     return (vocation && !vocation->isAttackable()) || hasCustomFlag(PlayerCustomFlag_IsProtected) || level < g_config.getNumber(ConfigManager::PROTECTION_LEVEL);
  4216. }
  4217.  
  4218. bool Player::isAttackable() const
  4219. {
  4220.     return !hasFlag(PlayerFlag_CannotBeAttacked) && !isAccountManager();
  4221. }
  4222.  
  4223. void Player::changeHealth(int32_t healthChange)
  4224. {
  4225.     Creature::changeHealth(healthChange);
  4226.     sendStats();
  4227. }
  4228.  
  4229. void Player::changeMana(int32_t manaChange)
  4230. {
  4231.     if(!hasFlag(PlayerFlag_HasInfiniteMana))
  4232.         Creature::changeMana(manaChange);
  4233.  
  4234.     sendStats();
  4235. }
  4236.  
  4237. void Player::changeSoul(int32_t soulChange)
  4238. {
  4239.     if(!hasFlag(PlayerFlag_HasInfiniteSoul))
  4240.         soul = std::min((int32_t)soulMax, (int32_t)soul + soulChange);
  4241.  
  4242.     sendStats();
  4243. }
  4244.  
  4245. bool Player::changeOutfit(Outfit_t outfit, bool checkList)
  4246. {
  4247.     uint32_t outfitId = Outfits::getInstance()->getOutfitId(outfit.lookType);
  4248.     if(checkList && (!canWearOutfit(outfitId, outfit.lookAddons) || !requestedOutfit))
  4249.         return false;
  4250.  
  4251.     requestedOutfit = false;
  4252.     if(outfitAttributes)
  4253.     {
  4254.         uint32_t oldId = Outfits::getInstance()->getOutfitId(defaultOutfit.lookType);
  4255.         outfitAttributes = !Outfits::getInstance()->removeAttributes(getID(), oldId, sex);
  4256.     }
  4257.  
  4258.     defaultOutfit = outfit;
  4259.     outfitAttributes = Outfits::getInstance()->addAttributes(getID(), outfitId, sex, defaultOutfit.lookAddons);
  4260.     return true;
  4261. }
  4262.  
  4263. bool Player::canWearOutfit(uint32_t outfitId, uint32_t addons)
  4264. {
  4265.     OutfitMap::iterator it = outfits.find(outfitId);
  4266.     if(it == outfits.end() || (it->second.isPremium && !isPremium()) || getAccess() < it->second.accessLevel
  4267.         || (!it->second.groups.empty() && std::find(it->second.groups.begin(), it->second.groups.end(), groupId)
  4268.         == it->second.groups.end()) || ((it->second.addons & addons) != addons && !hasCustomFlag(PlayerCustomFlag_CanWearAllAddons)))
  4269.         return false;
  4270.  
  4271.     if(it->second.storageId.empty())
  4272.         return true;
  4273.  
  4274.     std::string value;
  4275.     getStorage(it->second.storageId, value);
  4276.     if(value == it->second.storageValue)
  4277.         return true;
  4278.  
  4279.     int32_t intValue = atoi(value.c_str());
  4280.     if(!intValue && value != "0")
  4281.         return false;
  4282.  
  4283.     int32_t tmp = atoi(it->second.storageValue.c_str());
  4284.     if(!tmp && it->second.storageValue != "0")
  4285.         return false;
  4286.  
  4287.     return intValue >= tmp;
  4288. }
  4289.  
  4290. bool Player::addOutfit(uint32_t outfitId, uint32_t addons)
  4291. {
  4292.     Outfit outfit;
  4293.     if(!Outfits::getInstance()->getOutfit(outfitId, sex, outfit))
  4294.         return false;
  4295.  
  4296.     OutfitMap::iterator it = outfits.find(outfitId);
  4297.     if(it != outfits.end())
  4298.         outfit.addons |= it->second.addons;
  4299.  
  4300.     outfit.addons |= addons;
  4301.     outfits[outfitId] = outfit;
  4302.     return true;
  4303. }
  4304.  
  4305. bool Player::removeOutfit(uint32_t outfitId, uint32_t addons)
  4306. {
  4307.     OutfitMap::iterator it = outfits.find(outfitId);
  4308.     if(it == outfits.end())
  4309.         return false;
  4310.  
  4311.     bool update = false;
  4312.     if(addons == 0xFF) //remove outfit
  4313.     {
  4314.         if(it->second.lookType == defaultOutfit.lookType)
  4315.         {
  4316.             outfits.erase(it);
  4317.             if((it = outfits.begin()) != outfits.end())
  4318.                 defaultOutfit.lookType = it->second.lookType;
  4319.  
  4320.             update = true;
  4321.         }
  4322.         else
  4323.             outfits.erase(it);
  4324.     }
  4325.     else //remove addons
  4326.     {
  4327.         update = it->second.lookType == defaultOutfit.lookType;
  4328.         it->second.addons &= ~addons;
  4329.     }
  4330.  
  4331.     if(update)
  4332.         g_game.internalCreatureChangeOutfit(this, defaultOutfit, true);
  4333.  
  4334.     return true;
  4335. }
  4336.  
  4337. void Player::generateReservedStorage()
  4338. {
  4339.     uint32_t key = PSTRG_OUTFITSID_RANGE_START + 1;
  4340.     const OutfitMap& defaultOutfits = Outfits::getInstance()->getOutfits(sex);
  4341.     for(OutfitMap::const_iterator it = outfits.begin(); it != outfits.end(); ++it)
  4342.     {
  4343.         OutfitMap::const_iterator dit = defaultOutfits.find(it->first);
  4344.         if(dit == defaultOutfits.end() || (dit->second.isDefault && (dit->second.addons
  4345.             & it->second.addons) == it->second.addons))
  4346.             continue;
  4347.  
  4348.         std::stringstream k, v;
  4349.         k << key++; // this may not work as intended, revalidate it
  4350.         v << ((it->first << 16) | (it->second.addons & 0xFF));
  4351.  
  4352.         storageMap[k.str()] = v.str();
  4353.         if(key <= PSTRG_OUTFITSID_RANGE_START + PSTRG_OUTFITSID_RANGE_SIZE)
  4354.             continue;
  4355.  
  4356.         std::clog << "[Warning - Player::genReservedStorageRange] Player " << getName() << " with more than 500 outfits!" << std::endl;
  4357.         break;
  4358.     }
  4359. }
  4360.  
  4361. void Player::setSex(uint16_t newSex)
  4362. {
  4363.     sex = newSex;
  4364.     const OutfitMap& defaultOutfits = Outfits::getInstance()->getOutfits(sex);
  4365.     for(OutfitMap::const_iterator it = defaultOutfits.begin(); it != defaultOutfits.end(); ++it)
  4366.     {
  4367.         if(it->second.isDefault)
  4368.             addOutfit(it->first, it->second.addons);
  4369.     }
  4370. }
  4371.  
  4372. Skulls_t Player::getSkull() const
  4373. {
  4374.     if(hasFlag(PlayerFlag_NotGainInFight) || hasCustomFlag(PlayerCustomFlag_NotGainSkull))
  4375.         return SKULL_NONE;
  4376.  
  4377.     return skull;
  4378. }
  4379.  
  4380. Skulls_t Player::getSkullType(const Creature* creature) const
  4381. {
  4382.     if(const Player* player = creature->getPlayer())
  4383.     {
  4384.         if(g_game.getWorldType() != WORLDTYPE_OPEN)
  4385.             return SKULL_NONE;
  4386.  
  4387.         if((player == this || (skull != SKULL_NONE && player->getSkull() < SKULL_RED)) && player->hasAttacked(this))
  4388.             return SKULL_YELLOW;
  4389.  
  4390.         if(player->getSkull() == SKULL_NONE && (isPartner(player) || isAlly(player)) &&
  4391.             g_game.getWorldType() != WORLDTYPE_OPTIONAL)
  4392.             return SKULL_GREEN;
  4393.     }
  4394.  
  4395.     return Creature::getSkullType(creature);
  4396. }
  4397.  
  4398. bool Player::hasAttacked(const Player* attacked) const
  4399. {
  4400.     if(hasFlag(PlayerFlag_NotGainInFight) || !attacked)
  4401.         return false;
  4402.  
  4403.     AttackedSet::const_iterator it;
  4404.     uint32_t attackedId = attacked->getID();
  4405.     it = attackedSet.find(attackedId);
  4406.     if(it != attackedSet.end())
  4407.         return true;
  4408.  
  4409.     return false;
  4410. }
  4411.  
  4412. void Player::addAttacked(const Player* attacked)
  4413. {
  4414.     if(hasFlag(PlayerFlag_NotGainInFight) || !attacked || attacked == this)
  4415.         return;
  4416.  
  4417.     AttackedSet::iterator it;
  4418.     uint32_t attackedId = attacked->getID();
  4419.     it = attackedSet.find(attackedId);
  4420.     if(it == attackedSet.end())
  4421.         attackedSet.insert(attackedId);
  4422. }
  4423.  
  4424. void Player::setSkullEnd(time_t _time, bool login, Skulls_t _skull)
  4425. {
  4426.     if(g_game.getWorldType() != WORLDTYPE_OPEN
  4427.         || hasFlag(PlayerFlag_NotGainInFight) ||
  4428.         hasCustomFlag(PlayerCustomFlag_NotGainSkull))
  4429.         return;
  4430.  
  4431.     bool requireUpdate = false;
  4432.     if(_time > time(NULL))
  4433.     {
  4434.         requireUpdate = true;
  4435.         setSkull(_skull);
  4436.     }
  4437.     else if(skull == _skull)
  4438.     {
  4439.         requireUpdate = true;
  4440.         setSkull(SKULL_NONE);
  4441.         _time = 0;
  4442.     }
  4443.  
  4444.     if(requireUpdate)
  4445.     {
  4446.         skullEnd = _time;
  4447.         if(!login)
  4448.             g_game.updateCreatureSkull(this);
  4449.     }
  4450. }
  4451.  
  4452. bool Player::addUnjustifiedKill(const Player* attacked, bool countNow)
  4453. {
  4454.     if(!g_config.getBool(ConfigManager::USE_FRAG_HANDLER) || hasFlag(
  4455.         PlayerFlag_NotGainInFight) || g_game.getWorldType() != WORLDTYPE_OPEN
  4456.         || hasCustomFlag(PlayerCustomFlag_NotGainUnjustified) || hasCustomFlag(
  4457.         PlayerCustomFlag_NotGainSkull) || attacked == this)
  4458.         return false;
  4459.  
  4460.     if(countNow)
  4461.     {
  4462.         char buffer[90];
  4463.         sprintf(buffer, "Warning! The murder of %s was not justified.", attacked->getName().c_str());
  4464.         sendTextMessage(MSG_STATUS_WARNING, buffer);
  4465.     }
  4466.  
  4467.     time_t now = time(NULL), first = (now - g_config.getNumber(ConfigManager::FRAG_LIMIT)),
  4468.         second = (now - g_config.getNumber(ConfigManager::FRAG_SECOND_LIMIT));
  4469.     std::vector<time_t> dateList;
  4470.  
  4471.     IOLoginData::getInstance()->getUnjustifiedDates(guid, dateList, now);
  4472.     if(countNow)
  4473.         dateList.push_back(now);
  4474.  
  4475.     uint32_t fc = 0, sc = 0, tc = dateList.size();
  4476.     for(std::vector<time_t>::iterator it = dateList.begin(); it != dateList.end(); ++it)
  4477.     {
  4478.         if(second > 0 && (*it) > second)
  4479.             sc++;
  4480.  
  4481.         if(first > 0 && (*it) > first)
  4482.             fc++;
  4483.     }
  4484.  
  4485.     uint32_t f = g_config.getNumber(ConfigManager::RED_LIMIT), s = g_config.getNumber(
  4486.         ConfigManager::RED_SECOND_LIMIT), t = g_config.getNumber(ConfigManager::RED_THIRD_LIMIT);
  4487.     if(skull < SKULL_RED && ((f > 0 && fc >= f) || (s > 0 && sc >= s) || (t > 0 && tc >= t)))
  4488.         setSkullEnd(now + g_config.getNumber(ConfigManager::RED_SKULL_LENGTH), false, SKULL_RED);
  4489.  
  4490.     if(!g_config.getBool(ConfigManager::USE_BLACK_SKULL))
  4491.     {
  4492.         f += g_config.getNumber(ConfigManager::BAN_LIMIT);
  4493.         s += g_config.getNumber(ConfigManager::BAN_SECOND_LIMIT);
  4494.         t += g_config.getNumber(ConfigManager::BAN_THIRD_LIMIT);
  4495.         if((f <= 0 || fc < f) && (s <= 0 || sc < s) && (t <= 0 || tc < t))
  4496.             return true;
  4497.  
  4498.         if(!IOBan::getInstance()->addAccountBanishment(accountId, (now + g_config.getNumber(
  4499.             ConfigManager::KILLS_BAN_LENGTH)), 28, ACTION_BANISHMENT, "Player Killing (automatic)", 0, guid))
  4500.             return true;
  4501.  
  4502.         sendTextMessage(MSG_INFO_DESCR, "You have been banished.");
  4503.         g_game.addMagicEffect(getPosition(), MAGIC_EFFECT_WRAPS_GREEN);
  4504.         Scheduler::getInstance().addEvent(createSchedulerTask(1000, boost::bind(
  4505.             &Game::kickPlayer, &g_game, getID(), false)));
  4506.     }
  4507.     else
  4508.     {
  4509.         f += g_config.getNumber(ConfigManager::BLACK_LIMIT);
  4510.         s += g_config.getNumber(ConfigManager::BLACK_SECOND_LIMIT);
  4511.         t += g_config.getNumber(ConfigManager::BLACK_THIRD_LIMIT);
  4512.         if(skull < SKULL_BLACK && ((f > 0 && fc >= f) || (s > 0 && sc >= s) || (t > 0 && tc >= t)))
  4513.         {
  4514.             setSkullEnd(now + g_config.getNumber(ConfigManager::BLACK_SKULL_LENGTH), false, SKULL_BLACK);
  4515.             setAttackedCreature(NULL);
  4516.             destroySummons();
  4517.         }
  4518.     }
  4519.  
  4520.     return true;
  4521. }
  4522.  
  4523. void Player::setPromotionLevel(uint32_t pLevel)
  4524. {
  4525.     if(pLevel > promotionLevel)
  4526.     {
  4527.         int32_t tmpLevel = 0, currentVoc = vocationId;
  4528.         for(uint32_t i = promotionLevel; i < pLevel; ++i)
  4529.         {
  4530.             currentVoc = Vocations::getInstance()->getPromotedVocation(currentVoc);
  4531.             if(currentVoc < 1)
  4532.                 break;
  4533.  
  4534.             tmpLevel++;
  4535.             Vocation* voc = Vocations::getInstance()->getVocation(currentVoc);
  4536.             if(voc->isPremiumNeeded() && !isPremium() && g_config.getBool(ConfigManager::PREMIUM_FOR_PROMOTION))
  4537.                 continue;
  4538.  
  4539.             vocationId = currentVoc;
  4540.         }
  4541.  
  4542.         promotionLevel += tmpLevel;
  4543.     }
  4544.     else if(pLevel < promotionLevel)
  4545.     {
  4546.         uint32_t tmpLevel = 0, currentVoc = vocationId;
  4547.         for(uint32_t i = pLevel; i < promotionLevel; ++i)
  4548.         {
  4549.             Vocation* voc = Vocations::getInstance()->getVocation(currentVoc);
  4550.             if(voc->getFromVocation() == currentVoc)
  4551.                 break;
  4552.  
  4553.             tmpLevel++;
  4554.             currentVoc = voc->getFromVocation();
  4555.             if(voc->isPremiumNeeded() && !isPremium() && g_config.getBool(ConfigManager::PREMIUM_FOR_PROMOTION))
  4556.                 continue;
  4557.  
  4558.             vocationId = currentVoc;
  4559.         }
  4560.  
  4561.         promotionLevel -= tmpLevel;
  4562.     }
  4563.  
  4564.     setVocation(vocationId);
  4565. }
  4566.  
  4567. uint16_t Player::getBlessings() const
  4568. {
  4569.     if(!g_config.getBool(ConfigManager::BLESSINGS) || (!isPremium() &&
  4570.         g_config.getBool(ConfigManager::BLESSING_ONLY_PREMIUM)))
  4571.         return 0;
  4572.  
  4573.     uint16_t count = 0;
  4574.     for(int16_t i = 0; i < 16; ++i)
  4575.     {
  4576.         if(hasBlessing(i))
  4577.             count++;
  4578.     }
  4579.  
  4580.     return count;
  4581. }
  4582.  
  4583. uint64_t Player::getLostExperience() const
  4584. {
  4585.     double percent = (double)(lossPercent[LOSS_EXPERIENCE] - vocation->getLessLoss() - (getBlessings() * g_config.getNumber(
  4586.         ConfigManager::BLESS_REDUCTION))) / 100.;
  4587.     if(level <= 25)
  4588.         return (uint64_t)std::floor(percent * experience / 10.);
  4589.  
  4590.     int32_t base = level;
  4591.     double levels = (double)(base + 50) / 100.;
  4592.  
  4593.     uint64_t lost = 0;
  4594.     while(levels > 1.0f)
  4595.     {
  4596.         lost += (getExpForLevel(base) - getExpForLevel(base - 1));
  4597.         base--;
  4598.         levels -= 1.;
  4599.     }
  4600.  
  4601.     if(levels > 0.)
  4602.         lost += (uint64_t)std::floor(levels * (getExpForLevel(base) - getExpForLevel(base - 1)));
  4603.  
  4604.     return (uint64_t)std::floor(percent * lost);
  4605. }
  4606.  
  4607. uint32_t Player::getAttackSpeed() const
  4608. {
  4609.     int32_t modifiers = 0;
  4610.     if(outfitAttributes)
  4611.     {
  4612.         Outfit outfit;
  4613.         if(Outfits::getInstance()->getOutfit(defaultOutfit.lookType, outfit))
  4614.         {
  4615.             if(outfit.attackSpeed == -1)
  4616.                 return 0;
  4617.  
  4618.             modifiers += outfit.attackSpeed;
  4619.         }
  4620.     }
  4621.  
  4622.     Item* _weapon = weapon;
  4623.     if(!weapon || weapon->getWeaponType() == WEAPON_AMMO)
  4624.         _weapon = const_cast<Player*>(this)->getWeapon(true);
  4625.  
  4626.     return (((_weapon && _weapon->getAttackSpeed() != 0) ? _weapon->getAttackSpeed() : (vocation->getAttackSpeed() / std::max((size_t)1, getWeapons().size()))) + modifiers);
  4627. }
  4628.  
  4629. void Player::learnInstantSpell(const std::string& name)
  4630. {
  4631.     if(!hasLearnedInstantSpell(name))
  4632.         learnedInstantSpellList.push_back(name);
  4633. }
  4634.  
  4635. void Player::unlearnInstantSpell(const std::string& name)
  4636. {
  4637.     if(!hasLearnedInstantSpell(name))
  4638.         return;
  4639.  
  4640.     LearnedInstantSpellList::iterator it = std::find(learnedInstantSpellList.begin(), learnedInstantSpellList.end(), name);
  4641.     if(it != learnedInstantSpellList.end())
  4642.         learnedInstantSpellList.erase(it);
  4643. }
  4644.  
  4645. bool Player::hasLearnedInstantSpell(const std::string& name) const
  4646. {
  4647.     if(hasFlag(PlayerFlag_CannotUseSpells))
  4648.         return false;
  4649.  
  4650.     if(hasFlag(PlayerFlag_IgnoreSpellCheck))
  4651.         return true;
  4652.  
  4653.     for(LearnedInstantSpellList::const_iterator it = learnedInstantSpellList.begin(); it != learnedInstantSpellList.end(); ++it)
  4654.     {
  4655.         if(boost::algorithm::iequals(*it, name))
  4656.             return true;
  4657.     }
  4658.  
  4659.     return false;
  4660. }
  4661.  
  4662. void Player::manageAccount(const std::string &text)
  4663. {
  4664.     std::stringstream msg;
  4665.     bool noSwap = true;
  4666.     switch(accountManager)
  4667.     {
  4668.         case MANAGER_NAMELOCK:
  4669.         {
  4670.             if(!talkState[1])
  4671.             {
  4672.                 managerString = text;
  4673.                 trimString(managerString);
  4674.                 if(managerString.length() < 3)
  4675.                     msg << "The name is too short, please select a longer one.";
  4676.                 else if(managerString.length() > 30)
  4677.                     msg << "The name is too long, please select a shorter one.";
  4678.                 else if(!isValidName(managerString))
  4679.                     msg << "Your name seems to contain invalid symbols, please choose another one.";
  4680.                 else if(IOLoginData::getInstance()->playerExists(managerString, true))
  4681.                     msg << "Player with that name already exists, please choose another one.";
  4682.                 else
  4683.                 {
  4684.                     std::string tmp = asLowerCaseString(managerString);
  4685.                     if(tmp.substr(0, 4) != "god " && tmp.substr(0, 3) != "cm " && tmp.substr(0, 3) != "gm ")
  4686.                     {
  4687.                         talkState[1] = talkState[2] = true;
  4688.                         msg << "'" << managerString << "', are you sure? 'yes' or 'no'?";
  4689.                     }
  4690.                     else
  4691.                         msg << "Your character is not a staff member, please choose another name.";
  4692.                 }
  4693.             }
  4694.             else if(checkText(text, "no") && talkState[2])
  4695.             {
  4696.                 talkState[1] = talkState[2] = false;
  4697.                 msg << "What new name would you like have then?";
  4698.             }
  4699.             else if(checkText(text, "yes") && talkState[2])
  4700.             {
  4701.                 if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4702.                 {
  4703.                     uint32_t tmp;
  4704.                     if(IOLoginData::getInstance()->getGuidByName(tmp, managerString2) &&
  4705.                         IOLoginData::getInstance()->changeName(tmp, managerString, managerString2) &&
  4706.                         IOBan::getInstance()->removePlayerBanishment(tmp, PLAYERBAN_LOCK))
  4707.                     {
  4708.                         msg << "Your character '" << managerString << "' has been successfully renamed to '" << managerString2 << "', you should be able to login now.";
  4709.                         if(House* house = Houses::getInstance()->getHouseByPlayerId(tmp))
  4710.                             house->updateDoorDescription(managerString);
  4711.  
  4712.                         talkState[1] = true;
  4713.                         talkState[2] = false;
  4714.                     }
  4715.                     else
  4716.                     {
  4717.                         talkState[1] = talkState[2] = false;
  4718.                         msg << "Failed to change your name, please contact with staff.";
  4719.                     }
  4720.                 }
  4721.                 else
  4722.                 {
  4723.                     talkState[1] = talkState[2] = false;
  4724.                     msg << "Player with that name already exists, please choose another one.";
  4725.                 }
  4726.             }
  4727.             else
  4728.                 msg << "Sorry, but I can't understand you, please try to repeat.";
  4729.  
  4730.             break;
  4731.         }
  4732.         case MANAGER_ACCOUNT:
  4733.         {
  4734.             Account account = IOLoginData::getInstance()->loadAccount(managerNumber);
  4735.             if(checkText(text, "cancel") || (checkText(text, "account") && !talkState[1]))
  4736.             {
  4737.                 talkState[1] = true;
  4738.                 for(int8_t i = 2; i <= 12; ++i)
  4739.                     talkState[i] = false;
  4740.  
  4741.                 msg << "Do you want to change your 'password', generate a 'recovery key', create a 'character', or 'delete' an existing character?";
  4742.             }
  4743.             else if(checkText(text, "delete") && talkState[1])
  4744.             {
  4745.                 talkState[1] = false;
  4746.                 talkState[2] = true;
  4747.                 msg << "Which character would you like to delete?";
  4748.             }
  4749.             else if(talkState[2])
  4750.             {
  4751.                 std::string tmp = text;
  4752.                 trimString(tmp);
  4753.                 if(!isValidName(tmp, false))
  4754.                     msg << "That name to contain invalid symbols, please try again.";
  4755.                 else
  4756.                 {
  4757.                     talkState[2] = false;
  4758.                     talkState[3] = true;
  4759.                     managerString = tmp;
  4760.                     msg << "Do you really want to delete the character '" << managerString << "'? 'yes' or 'no'";
  4761.                 }
  4762.             }
  4763.             else if(checkText(text, "yes") && talkState[3])
  4764.             {
  4765.                 switch(IOLoginData::getInstance()->deleteCharacter(managerNumber, managerString))
  4766.                 {
  4767.                     case DELETE_INTERNAL:
  4768.                         msg << "An error occured while deleting your character. Either the character does not belong to you or it doesn't exist.";
  4769.                         break;
  4770.  
  4771.                     case DELETE_SUCCESS:
  4772.                         msg << "Your character has been deleted.";
  4773.                         break;
  4774.  
  4775.                     case DELETE_HOUSE:
  4776.                         msg << "Your character owns a house. You have to login and leave the house or pass it to someone else to complete.";
  4777.                         break;
  4778.  
  4779.                     case DELETE_LEADER:
  4780.                         msg << "Your character is leader of a guild. You have to disband the guild or pass the leadership to someone else to complete.";
  4781.                         break;
  4782.  
  4783.                     case DELETE_ONLINE:
  4784.                         msg << "Character with that name is currently online, to delete a character it has to be offline.";
  4785.                         break;
  4786.                 }
  4787.  
  4788.                 talkState[1] = true;
  4789.                 for(int8_t i = 2; i <= 12; ++i)
  4790.                     talkState[i] = false;
  4791.             }
  4792.             else if(checkText(text, "no") && talkState[3])
  4793.             {
  4794.                 talkState[1] = true;
  4795.                 talkState[3] = false;
  4796.                 msg << "Which character would you like to delete then?";
  4797.             }
  4798.             else if(checkText(text, "password") && talkState[1])
  4799.             {
  4800.                 talkState[1] = false;
  4801.                 talkState[4] = true;
  4802.                 msg << "What would you like your password to be?";
  4803.             }
  4804.             else if(talkState[4])
  4805.             {
  4806.                 std::string tmp = text;
  4807.                 trimString(tmp);
  4808.                 if(tmp.length() < 6)
  4809.                     msg << "That password is too short, please select a longer one.";
  4810.                 else if(!isValidPassword(tmp))
  4811.                     msg << "Your password seems to contain invalid symbols, please choose another one.";
  4812.                 else
  4813.                 {
  4814.                     talkState[4] = false;
  4815.                     talkState[5] = true;
  4816.                     managerString = tmp;
  4817.                     msg << "'" << managerString << "' is it? 'yes' or 'no'?";
  4818.                 }
  4819.             }
  4820.             else if(checkText(text, "yes") && talkState[5])
  4821.             {
  4822.                 talkState[1] = true;
  4823.                 for(int8_t i = 2; i <= 12; ++i)
  4824.                     talkState[i] = false;
  4825.  
  4826.                 IOLoginData::getInstance()->setPassword(managerNumber, managerString);
  4827.                 msg << "Your password has been changed.";
  4828.             }
  4829.             else if(checkText(text, "no") && talkState[5])
  4830.             {
  4831.                 talkState[1] = true;
  4832.                 for(int8_t i = 2; i <= 12; ++i)
  4833.                     talkState[i] = false;
  4834.  
  4835.                 msg << "Ok, then not.";
  4836.             }
  4837.             else if(checkText(text, "character") && talkState[1])
  4838.             {
  4839.                 if(account.charList.size() <= 15)
  4840.                 {
  4841.                     talkState[1] = false;
  4842.                     talkState[6] = true;
  4843.                     msg << "What would you like as your character name?";
  4844.                 }
  4845.                 else
  4846.                 {
  4847.                     talkState[1] = true;
  4848.                     for(int8_t i = 2; i <= 12; ++i)
  4849.                         talkState[i] = false;
  4850.  
  4851.                     msg << "Your account has reached the limit of 15 characters, you should 'delete' a character if you want to create a new one.";
  4852.                 }
  4853.             }
  4854.             else if(talkState[6])
  4855.             {
  4856.                 managerString = text;
  4857.                 trimString(managerString);
  4858.                 if(managerString.length() < 3)
  4859.                     msg << "That name is too short, please select a longer one.";
  4860.                 else if(managerString.length() > 30)
  4861.                     msg << "That name is too long, please select a shorter one.";
  4862.                 else if(!isValidName(managerString))
  4863.                     msg << "Your name seems to contain invalid symbols, please choose another one.";
  4864.                 else if(IOLoginData::getInstance()->playerExists(managerString, true))
  4865.                     msg << "Player with that name already exists, please choose another one.";
  4866.                 else
  4867.                 {
  4868.                     std::string tmp = asLowerCaseString(managerString);
  4869.                     if(tmp.substr(0, 4) != "god " && tmp.substr(0, 3) != "cm " && tmp.substr(0, 3) != "gm ")
  4870.                     {
  4871.                         talkState[6] = false;
  4872.                         talkState[7] = true;
  4873.                         msg << "'" << managerString << "', are you sure? 'yes' or 'no'";
  4874.                     }
  4875.                     else
  4876.                         msg << "Your character is not a staff member, please choose another name.";
  4877.                 }
  4878.             }
  4879.             else if(checkText(text, "no") && talkState[7])
  4880.             {
  4881.                 talkState[6] = true;
  4882.                 talkState[7] = false;
  4883.                 msg << "What would you like your character name to be then?";
  4884.             }
  4885.             else if(checkText(text, "yes") && talkState[7])
  4886.             {
  4887.                 talkState[7] = false;
  4888.                 talkState[8] = true;
  4889.                 msg << "Would you like to be a 'male' or a 'female'.";
  4890.             }
  4891.             else if(talkState[8] && (checkText(text, "female") || checkText(text, "male")))
  4892.             {
  4893.                 talkState[8] = false;
  4894.                 talkState[9] = true;
  4895.                 if(checkText(text, "female"))
  4896.                 {
  4897.                     msg << "A female, are you sure? 'yes' or 'no'";
  4898.                     managerSex = PLAYERSEX_FEMALE;
  4899.                 }
  4900.                 else
  4901.                 {
  4902.                     msg << "A male, are you sure? 'yes' or 'no'";
  4903.                     managerSex = PLAYERSEX_MALE;
  4904.                 }
  4905.             }
  4906.             else if(checkText(text, "no") && talkState[9])
  4907.             {
  4908.                 talkState[8] = true;
  4909.                 talkState[9] = false;
  4910.                 msg << "Tell me then, would you like to be a 'male' or a 'female'?";
  4911.             }
  4912.             else if(checkText(text, "yes") && talkState[9])
  4913.             {
  4914.                 if(g_config.getBool(ConfigManager::START_CHOOSEVOC))
  4915.                 {
  4916.                     talkState[9] = false;
  4917.                     talkState[11] = true;
  4918.  
  4919.                     std::vector<std::string> vocations;
  4920.                     for(VocationsMap::iterator it = Vocations::getInstance()->getFirstVocation(); it != Vocations::getInstance()->getLastVocation(); ++it)
  4921.                     {
  4922.                         if(it->first == it->second->getFromVocation() && it->first != 0)
  4923.                             vocations.push_back(asLowerCaseString(it->second->getName()));
  4924.                     }
  4925.  
  4926.                     msg << "What would you like to be... ";
  4927.                     for(std::vector<std::string>::const_iterator it = vocations.begin(); it != vocations.end(); ++it)
  4928.                     {
  4929.                         if(it == vocations.begin())
  4930.                             msg << "'" << *it << "'";
  4931.                         else if(*it == *(vocations.rbegin()))
  4932.                             msg << " or '" << *it << "'.";
  4933.                         else
  4934.                             msg << ", '" << *it << "'";
  4935.                     }
  4936.                 }
  4937.                 else if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4938.                 {
  4939.                     talkState[1] = true;
  4940.                     for(int8_t i = 2; i <= 12; ++i)
  4941.                         talkState[i] = false;
  4942.  
  4943.                     if(IOLoginData::getInstance()->createCharacter(managerNumber, managerString, managerNumber2, (uint16_t)managerSex))
  4944.                         msg << "Your character " << managerString << " has been created.";
  4945.                     else
  4946.                         msg << "Your character couldn't be created, please contact with staff.";
  4947.                 }
  4948.                 else
  4949.                 {
  4950.                     talkState[6] = true;
  4951.                     talkState[9] = false;
  4952.                     msg << "Player with that name already exists, please choose another one.";
  4953.                 }
  4954.             }
  4955.             else if(talkState[11])
  4956.             {
  4957.                 for(VocationsMap::iterator it = Vocations::getInstance()->getFirstVocation(); it != Vocations::getInstance()->getLastVocation(); ++it)
  4958.                 {
  4959.                     if(checkText(text, asLowerCaseString(it->second->getName())) &&
  4960.                         it->first == it->second->getFromVocation() && it->first != 0)
  4961.                     {
  4962.                         msg << "So you would like to be " << it->second->getDescription() << ", yes or no?";
  4963.                         managerNumber2 = it->first;
  4964.                         talkState[11] = false;
  4965.                         talkState[12] = true;
  4966.                     }
  4967.                 }
  4968.  
  4969.                 if(msg.str().length() == 17)
  4970.                     msg << "I don't understand what vocation you would like to be... could you please repeat it?";
  4971.             }
  4972.             else if(checkText(text, "yes") && talkState[12])
  4973.             {
  4974.                 if(!IOLoginData::getInstance()->playerExists(managerString, true))
  4975.                 {
  4976.                     talkState[1] = true;
  4977.                     for(int8_t i = 2; i <= 12; ++i)
  4978.                         talkState[i] = false;
  4979.  
  4980.                     if(IOLoginData::getInstance()->createCharacter(managerNumber, managerString, managerNumber2, (uint16_t)managerSex))
  4981.                         msg << "Your character " << managerString << " has been created.";
  4982.                     else
  4983.                         msg << "Your character couldn't be created, please contact with staff.";
  4984.                 }
  4985.                 else
  4986.                 {
  4987.                     talkState[6] = true;
  4988.                     talkState[9] = false;
  4989.                     msg << "Player with that name already exists, please choose another one.";
  4990.                 }
  4991.             }
  4992.             else if(checkText(text, "no") && talkState[12])
  4993.             {
  4994.                 talkState[11] = true;
  4995.                 talkState[12] = false;
  4996.                 msg << "What would you like to be then?";
  4997.             }
  4998.             else if(checkText(text, "recovery key") && talkState[1])
  4999.             {
  5000.                 talkState[1] = false;
  5001.                 talkState[10] = true;
  5002.                 msg << "Would you like to generate a recovery key? yes or no";
  5003.             }
  5004.             else if(checkText(text, "yes") && talkState[10])
  5005.             {
  5006.                 if(account.recoveryKey != "0")
  5007.                     msg << "Sorry, but you already have a recovery key. For security reasons I may not generate for you you a new one.";
  5008.                 else
  5009.                 {
  5010.                     managerString = generateRecoveryKey(4, 4);
  5011.                     IOLoginData::getInstance()->setRecoveryKey(managerNumber, managerString);
  5012.                     msg << "Your recovery key is " << managerString << ".";
  5013.                 }
  5014.  
  5015.                 talkState[1] = true;
  5016.                 for(int8_t i = 2; i <= 12; ++i)
  5017.                     talkState[i] = false;
  5018.             }
  5019.             else if(checkText(text, "no") && talkState[10])
  5020.             {
  5021.                 msg << "Ok, then not.";
  5022.                 talkState[1] = true;
  5023.                 for(int8_t i = 2; i <= 12; ++i)
  5024.                     talkState[i] = false;
  5025.             }
  5026.             else
  5027.                 msg << "Sorry, but I can't understand you, please try to repeat.";
  5028.  
  5029.             break;
  5030.         }
  5031.         case MANAGER_NEW:
  5032.         {
  5033.             if(checkText(text, "account") && !talkState[1])
  5034.             {
  5035.                 msg << "What would you like your password to be?";
  5036.                 talkState[1] = true;
  5037.                 talkState[2] = true;
  5038.             }
  5039.             else if(talkState[2])
  5040.             {
  5041.                 std::string tmp = text;
  5042.                 trimString(tmp);
  5043.                 if(tmp.length() < 6)
  5044.                     msg << "That password is too short, please select a longer one.";
  5045.                 else if(!isValidPassword(tmp))
  5046.                     msg << "Your password seems to contain invalid symbols, please choose another one.";
  5047.                 else
  5048.                 {
  5049.                     talkState[3] = true;
  5050.                     talkState[2] = false;
  5051.                     managerString = tmp;
  5052.                     msg << managerString << " is it? yes or no?";
  5053.                 }
  5054.             }
  5055.             else if(checkText(text, "yes") && talkState[3])
  5056.             {
  5057.                 if(g_config.getBool(ConfigManager::GENERATE_ACCOUNT_NUMBER))
  5058.                 {
  5059.                     do
  5060.                         sprintf(managerChar, "%d%d%d%d%d%d%d", random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9), random_range(2, 9));
  5061.                     while(IOLoginData::getInstance()->accountNameExists(managerChar));
  5062.  
  5063.                     uint32_t id = (uint32_t)IOLoginData::getInstance()->createAccount(managerChar, managerString);
  5064.                     if(id)
  5065.                     {
  5066.                         accountManager = MANAGER_ACCOUNT;
  5067.                         managerNumber = id;
  5068.  
  5069.                         noSwap = talkState[1] = false;
  5070.                         msg << "Your account has been created, you may manage it now, but please remember your account id "
  5071.                             << managerChar << " and password " << managerString << "!";
  5072.                     }
  5073.                     else
  5074.                         msg << "Your account could not be created, please contact with staff.";
  5075.  
  5076.                     for(int8_t i = 2; i <= 5; ++i)
  5077.                         talkState[i] = false;
  5078.                 }
  5079.                 else
  5080.                 {
  5081.                     msg << "What would you like your account id to be?";
  5082.                     talkState[3] = false;
  5083.                     talkState[4] = true;
  5084.                 }
  5085.             }
  5086.             else if(checkText(text, "no") && talkState[3])
  5087.             {
  5088.                 talkState[2] = true;
  5089.                 talkState[3] = false;
  5090.                 msg << "What would you like your password to be then?";
  5091.             }
  5092.             else if(talkState[4])
  5093.             {
  5094.                 std::string tmp = text;
  5095.                 trimString(tmp);
  5096.                 if(tmp.length() < 3)
  5097.                     msg << "That account id is too short, please select a longer one.";
  5098.                 else if(tmp.length() > 32)
  5099.                     msg << "That account id is too long, please select a shorter one.";
  5100.                 else if(!isNumbers(tmp))
  5101.                     msg << "Your account id seems to contain invalid symbols, please choose another one.";
  5102.                 else if(asLowerCaseString(tmp) == asLowerCaseString(managerString))
  5103.                     msg << "Your account id cannot be same as password, please choose another one.";
  5104.                 else
  5105.                 {
  5106.                     sprintf(managerChar, "%s", tmp.c_str());
  5107.                     msg << managerChar << ", is it? yes or no?";
  5108.                     talkState[4] = false;
  5109.                     talkState[5] = true;
  5110.                 }
  5111.             }
  5112.             else if(checkText(text, "yes") && talkState[5])
  5113.             {
  5114.                 if(!IOLoginData::getInstance()->accountNameExists(managerChar))
  5115.                 {
  5116.                     uint32_t id = (uint32_t)IOLoginData::getInstance()->createAccount(managerChar, managerString);
  5117.                     if(id)
  5118.                     {
  5119.                         accountManager = MANAGER_ACCOUNT;
  5120.                         managerNumber = id;
  5121.  
  5122.                         noSwap = talkState[1] = false;
  5123.                         msg << "Your account has been created, you may manage it now, but please remember your account id "
  5124.                             << managerChar << " and password " << managerString << "!";
  5125.                     }
  5126.                     else
  5127.                         msg << "Your account could not be created, please contact with staff.";
  5128.  
  5129.                     for(int8_t i = 2; i <= 5; ++i)
  5130.                         talkState[i] = false;
  5131.                 }
  5132.                 else
  5133.                 {
  5134.                     msg << "Account with that id already exists, please choose another one.";
  5135.                     talkState[4] = true;
  5136.                     talkState[5] = false;
  5137.                 }
  5138.             }
  5139.             else if(checkText(text, "no") && talkState[5])
  5140.             {
  5141.                 talkState[5] = false;
  5142.                 talkState[4] = true;
  5143.                 msg << "What would you like your account id to be then?";
  5144.             }
  5145.             else if(checkText(text, "recover") && !talkState[6])
  5146.             {
  5147.                 talkState[6] = true;
  5148.                 talkState[7] = true;
  5149.                 msg << "What was your account id?";
  5150.             }
  5151.             else if(talkState[7])
  5152.             {
  5153.                 managerString = text;
  5154.                 uint32_t number = atoi(managerString.c_str());
  5155.                 if(IOLoginData::getInstance()->getAccountId(number, (uint32_t&)managerNumber))
  5156.                 {
  5157.                     talkState[7] = false;
  5158.                     talkState[8] = true;
  5159.                     msg << "What was your recovery key?";
  5160.                 }
  5161.                 else
  5162.                 {
  5163.                     msg << "Sorry, but account with id " << managerString << " does not exists.";
  5164.                     talkState[6] = talkState[7] = false;
  5165.                 }
  5166.             }
  5167.             else if(talkState[8])
  5168.             {
  5169.                 managerString2 = text;
  5170.                 if(IOLoginData::getInstance()->validRecoveryKey(managerNumber, managerString2) && managerString2 != "0")
  5171.                 {
  5172.                     sprintf(managerChar, "%s%d", g_config.getString(ConfigManager::SERVER_NAME).c_str(), random_range(100, 999));
  5173.                     IOLoginData::getInstance()->setPassword(managerNumber, managerChar);
  5174.                     msg << "Correct! Your new password is '" << managerChar << "'.";
  5175.                 }
  5176.                 else
  5177.                     msg << "Sorry, but this key does not match to specified account.";
  5178.  
  5179.                 talkState[7] = talkState[8] = false;
  5180.             }
  5181.             else
  5182.                 msg << "Sorry, but I can't understand you, please try to repeat.";
  5183.  
  5184.             break;
  5185.         }
  5186.         default:
  5187.             return;
  5188.             break;
  5189.     }
  5190.  
  5191.     sendTextMessage(MSG_STATUS_CONSOLE_BLUE, msg.str().c_str());
  5192.     if(!noSwap)
  5193.         sendTextMessage(MSG_STATUS_CONSOLE_ORANGE, "Hint: Type 'account' to manage your account and if you want to start over then type 'cancel'.");
  5194. }
  5195.  
  5196. bool Player::isGuildInvited(uint32_t guildId) const
  5197. {
  5198.     for(InvitationsList::const_iterator it = invitationsList.begin(); it != invitationsList.end(); ++it)
  5199.     {
  5200.         if((*it) == guildId)
  5201.             return true;
  5202.     }
  5203.  
  5204.     return false;
  5205. }
  5206.  
  5207. void Player::leaveGuild()
  5208. {
  5209.     sendClosePrivate(CHANNEL_GUILD);
  5210.  
  5211.     guildLevel = GUILDLEVEL_NONE;
  5212.     guildId = rankId = 0;
  5213.     guildName = rankName = guildNick = std::string();
  5214. }
  5215.  
  5216. bool Player::isPremium() const
  5217. {
  5218.     if(g_config.getBool(ConfigManager::FREE_PREMIUM) || hasFlag(PlayerFlag_IsAlwaysPremium))
  5219.         return true;
  5220.  
  5221.     return (premiumDays != 0);
  5222. }
  5223.  
  5224. void Player::addPremiumDays(int32_t days)
  5225. {
  5226.     if(premiumDays < GRATIS_PREMIUM)
  5227.     {
  5228.         Account account = IOLoginData::getInstance()->loadAccount(accountId);
  5229.         if(days < 0)
  5230.         {
  5231.             account.premiumDays = std::max((uint32_t)0, uint32_t(account.premiumDays + (int32_t)days));
  5232.             premiumDays = std::max((uint32_t)0, uint32_t(premiumDays + (int32_t)days));
  5233.         }
  5234.         else
  5235.         {
  5236.             account.premiumDays = std::min((uint32_t)65534, uint32_t(account.premiumDays + (uint32_t)days));
  5237.             premiumDays = std::min((uint32_t)65534, uint32_t(premiumDays + (uint32_t)days));
  5238.         }
  5239.  
  5240.         IOLoginData::getInstance()->saveAccount(account);
  5241.     }
  5242. }
  5243.  
  5244. bool Player::setGuildLevel(GuildLevel_t newLevel, uint32_t rank/* = 0*/)
  5245. {
  5246.     std::string name;
  5247.     if(!IOGuild::getInstance()->getRankEx(rank, name, guildId, newLevel))
  5248.         return false;
  5249.  
  5250.     guildLevel = newLevel;
  5251.     rankName = name;
  5252.     rankId = rank;
  5253.     return true;
  5254. }
  5255.  
  5256. void Player::setGroupId(int32_t newId)
  5257. {
  5258.     if(Group* tmp = Groups::getInstance()->getGroup(newId))
  5259.     {
  5260.         groupId = newId;
  5261.         group = tmp;
  5262.     }
  5263. }
  5264.  
  5265. void Player::setGroup(Group* newGroup)
  5266. {
  5267.     if(!newGroup)
  5268.         return;
  5269.  
  5270.     group = newGroup;
  5271.     groupId = group->getId();
  5272. }
  5273.  
  5274. PartyShields_t Player::getPartyShield(const Creature* creature) const
  5275. {
  5276.     const Player* player = creature->getPlayer();
  5277.     if(!player)
  5278.         return Creature::getPartyShield(creature);
  5279.  
  5280.     if(party)
  5281.     {
  5282.         if(party->getLeader() == player)
  5283.             return SHIELD_YELLOW;
  5284.  
  5285.         if(party->isPlayerMember(player))
  5286.             return SHIELD_BLUE;
  5287.  
  5288.         if(isInviting(player))
  5289.             return SHIELD_WHITEBLUE;
  5290.     }
  5291.  
  5292.     if(player->isInviting(this))
  5293.         return SHIELD_WHITEYELLOW;
  5294.  
  5295.     return SHIELD_NONE;
  5296. }
  5297.  
  5298. bool Player::isInviting(const Player* player) const
  5299. {
  5300.     if(!player || player->isRemoved() || !party || party->getLeader() != this)
  5301.         return false;
  5302.  
  5303.     return party->isPlayerInvited(player);
  5304. }
  5305.  
  5306. bool Player::isPartner(const Player* player) const
  5307. {
  5308.     return player && player->getParty() && player->getParty() == party;
  5309. }
  5310.  
  5311. bool Player::getHideHealth() const
  5312. {
  5313.     if(hasFlag(PlayerFlag_HideHealth))
  5314.         return true;
  5315.  
  5316.     return hideHealth;
  5317. }
  5318.  
  5319. void Player::sendPlayerIcons(Player* player)
  5320. {
  5321.     sendCreatureShield(player);
  5322.     sendCreatureSkull(player);
  5323. }
  5324.  
  5325. bool Player::addPartyInvitation(Party* party)
  5326. {
  5327.     if(!party)
  5328.         return false;
  5329.  
  5330.     PartyList::iterator it = std::find(invitePartyList.begin(), invitePartyList.end(), party);
  5331.     if(it != invitePartyList.end())
  5332.         return false;
  5333.  
  5334.     invitePartyList.push_back(party);
  5335.     return true;
  5336. }
  5337.  
  5338. bool Player::removePartyInvitation(Party* party)
  5339. {
  5340.     if(!party)
  5341.         return false;
  5342.  
  5343.     PartyList::iterator it = std::find(invitePartyList.begin(), invitePartyList.end(), party);
  5344.     if(it != invitePartyList.end())
  5345.     {
  5346.         invitePartyList.erase(it);
  5347.         return true;
  5348.     }
  5349.     return false;
  5350. }
  5351.  
  5352. void Player::clearPartyInvitations()
  5353. {
  5354.     if(invitePartyList.empty())
  5355.         return;
  5356.  
  5357.     PartyList list;
  5358.     for(PartyList::iterator it = invitePartyList.begin(); it != invitePartyList.end(); ++it)
  5359.         list.push_back(*it);
  5360.  
  5361.     invitePartyList.clear();
  5362.     for(PartyList::iterator it = list.begin(); it != list.end(); ++it)
  5363.         (*it)->removeInvite(this);
  5364. }
  5365.  
  5366. void Player::increaseCombatValues(int32_t& min, int32_t& max, bool useCharges, bool countWeapon)
  5367. {
  5368.     if(min > 0)
  5369.         min = (int32_t)(min * vocation->getMultiplier(MULTIPLIER_HEALING));
  5370.     else
  5371.         min = (int32_t)(min * vocation->getMultiplier(MULTIPLIER_MAGIC));
  5372.  
  5373.     if(max > 0)
  5374.         max = (int32_t)(max * vocation->getMultiplier(MULTIPLIER_HEALING));
  5375.     else
  5376.         max = (int32_t)(max * vocation->getMultiplier(MULTIPLIER_MAGIC));
  5377.  
  5378.     Item* item = NULL;
  5379.     int32_t minValue = 0, maxValue = 0, i = SLOT_FIRST;
  5380.     for(; i < SLOT_LAST; ++i)
  5381.     {
  5382.         if(!(item = getInventoryItem((slots_t)i)) || item->isRemoved() ||
  5383.             (g_moveEvents->hasEquipEvent(item) && !isItemAbilityEnabled((slots_t)i)))
  5384.             continue;
  5385.  
  5386.         const ItemType& it = Item::items[item->getID()];
  5387.         if(!it.hasAbilities())
  5388.             continue;
  5389.  
  5390.         if(min > 0)
  5391.         {
  5392.             minValue += it.abilities->increment[HEALING_VALUE];
  5393.             if(it.abilities->increment[HEALING_PERCENT])
  5394.                 min = (int32_t)std::ceil((double)(min * it.abilities->increment[HEALING_PERCENT]) / 100.);
  5395.         }
  5396.         else
  5397.         {
  5398.             minValue -= it.abilities->increment[MAGIC_VALUE];
  5399.             if(it.abilities->increment[MAGIC_PERCENT])
  5400.                 min = (int32_t)std::ceil((double)(min * it.abilities->increment[MAGIC_PERCENT]) / 100.);
  5401.         }
  5402.  
  5403.         if(max > 0)
  5404.         {
  5405.             maxValue += it.abilities->increment[HEALING_VALUE];
  5406.             if(it.abilities->increment[HEALING_PERCENT])
  5407.                 max = (int32_t)std::ceil((double)(max * it.abilities->increment[HEALING_PERCENT]) / 100.);
  5408.         }
  5409.         else
  5410.         {
  5411.             maxValue -= it.abilities->increment[MAGIC_VALUE];
  5412.             if(it.abilities->increment[MAGIC_PERCENT])
  5413.                 max = (int32_t)std::ceil((double)(max * it.abilities->increment[MAGIC_PERCENT]) / 100.);
  5414.         }
  5415.  
  5416.         bool removeCharges = false;
  5417.         for(int32_t j = INCREMENT_FIRST; j <= INCREMENT_LAST; ++j)
  5418.         {
  5419.             if(!it.abilities->increment[(Increment_t)j])
  5420.                 continue;
  5421.  
  5422.             removeCharges = true;
  5423.             break;
  5424.         }
  5425.  
  5426.         if(useCharges && removeCharges && (countWeapon || item != weapon) && item->hasCharges())
  5427.             g_game.transformItem(item, item->getID(), std::max((int32_t)0, (int32_t)item->getCharges() - 1));
  5428.     }
  5429.  
  5430.     min += minValue;
  5431.     max += maxValue;
  5432. }
  5433.  
  5434. bool Player::transferMoneyTo(const std::string& name, uint64_t amount)
  5435. {
  5436.     if(!g_config.getBool(ConfigManager::BANK_SYSTEM) || amount > balance)
  5437.         return false;
  5438.  
  5439.     Player* target = g_game.getPlayerByNameEx(name);
  5440.     if(!target)
  5441.         return false;
  5442.  
  5443.     balance -= amount;
  5444.     target->balance += amount;
  5445.     if(target->isVirtual())
  5446.     {
  5447.         IOLoginData::getInstance()->savePlayer(target);
  5448.         delete target;
  5449.     }
  5450.  
  5451.     return true;
  5452. }
  5453.  
  5454. void Player::sendCritical() const
  5455. {
  5456.     if(g_config.getBool(ConfigManager::DISPLAY_CRITICAL_HIT))
  5457.         g_game.addAnimatedText(getPosition(), COLOR_DARKRED, "CRITICAL!");
  5458. }
  5459.  
  5460. bool Player::addOfflineTrainingTries(skills_t skill, int32_t tries)
  5461. {
  5462.     if(tries <= 0 || skill == SKILL__LEVEL || skill == SKILL__EXPERIENCE)
  5463.         return false;
  5464.  
  5465.     uint32_t oldSkillValue, newSkillValue;
  5466.     long double oldPercentToNextLevel, newPercentToNextLevel;
  5467.  
  5468.     std::ostringstream ss;
  5469.     if(skill == SKILL__MAGLEVEL)
  5470.     {
  5471.         uint64_t currReqMana = vocation->getReqMana(magLevel), nextReqMana = vocation->getReqMana(magLevel + 1);
  5472.         if(currReqMana >= nextReqMana)
  5473.             return false;
  5474.  
  5475.         oldSkillValue = magLevel;
  5476.         oldPercentToNextLevel = (long double)(manaSpent * 100) / nextReqMana;
  5477.  
  5478.         tries *= g_config.getDouble(ConfigManager::RATE_MAGIC_OFFLINE);
  5479.         while((manaSpent + tries) >= nextReqMana)
  5480.         {
  5481.             tries -= nextReqMana - manaSpent;
  5482.             manaSpent = 0;
  5483.             magLevel++;
  5484.  
  5485.             CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  5486.             for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  5487.                 (*it)->executeAdvance(this, SKILL__MAGLEVEL, (magLevel - 1), magLevel);
  5488.  
  5489.             currReqMana = nextReqMana;
  5490.             nextReqMana = vocation->getReqMana(magLevel + 1);
  5491.             if(currReqMana >= nextReqMana)
  5492.             {
  5493.                 tries = 0;
  5494.                 break;
  5495.             }
  5496.         }
  5497.  
  5498.         if(tries)
  5499.             manaSpent += tries;
  5500.  
  5501.         uint32_t newPercent;
  5502.         if(nextReqMana > currReqMana)
  5503.         {
  5504.             newPercent = Player::getPercentLevel(manaSpent, nextReqMana);
  5505.             newPercentToNextLevel = (long double)(manaSpent * 100) / nextReqMana;
  5506.         }
  5507.         else
  5508.             newPercent = newPercentToNextLevel = 0;
  5509.  
  5510.         if(newPercent != magLevelPercent)
  5511.         {
  5512.             magLevelPercent = newPercent;
  5513.             sendStats();
  5514.         }
  5515.  
  5516.         newSkillValue = magLevel;
  5517.         ss << "You advanced to magic level " << magLevel << ".";
  5518.         sendTextMessage(MSG_EVENT_ADVANCE, ss.str().c_str());
  5519.         ss.str("");
  5520.     }
  5521.     else
  5522.     {
  5523.         uint64_t currReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL]),
  5524.             nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  5525.         if(currReqTries >= nextReqTries)
  5526.             return false;
  5527.  
  5528.         oldSkillValue = skills[skill][SKILL_LEVEL];
  5529.         oldPercentToNextLevel = (long double)(skills[skill][SKILL_TRIES] * 100) / nextReqTries;
  5530.  
  5531.         tries *= g_config.getDouble(ConfigManager::RATE_SKILL_OFFLINE);
  5532.         while((skills[skill][SKILL_TRIES] + tries) >= nextReqTries)
  5533.         {
  5534.             tries -= nextReqTries - skills[skill][SKILL_TRIES];
  5535.             skills[skill][SKILL_LEVEL]++;
  5536.             skills[skill][SKILL_TRIES] = skills[skill][SKILL_PERCENT] = 0;         
  5537.  
  5538.             CreatureEventList advanceEvents = getCreatureEvents(CREATURE_EVENT_ADVANCE);
  5539.             for(CreatureEventList::iterator it = advanceEvents.begin(); it != advanceEvents.end(); ++it)
  5540.                 (*it)->executeAdvance(this, skill, (skills[skill][SKILL_LEVEL] - 1), skills[skill][SKILL_LEVEL]);
  5541.  
  5542.             currReqTries = nextReqTries;
  5543.             nextReqTries = vocation->getReqSkillTries(skill, skills[skill][SKILL_LEVEL] + 1);
  5544.             if(currReqTries >= nextReqTries)
  5545.             {
  5546.                 tries = 0;
  5547.                 break;
  5548.             }
  5549.         }
  5550.  
  5551.         if(tries)
  5552.             skills[skill][SKILL_TRIES] += tries;
  5553.  
  5554.         uint32_t newPercent;
  5555.         if(nextReqTries > currReqTries)
  5556.         {
  5557.             newPercent = Player::getPercentLevel(skills[skill][SKILL_TRIES], nextReqTries);
  5558.             newPercentToNextLevel = (long double)(skills[skill][SKILL_TRIES] * 100) / nextReqTries;
  5559.         }
  5560.         else
  5561.             newPercent = newPercentToNextLevel = 0;
  5562.  
  5563.         if(skills[skill][SKILL_PERCENT] != newPercent)
  5564.         {
  5565.             skills[skill][SKILL_PERCENT] = newPercent;
  5566.             sendStats();
  5567.         }
  5568.  
  5569.         newSkillValue = skills[skill][SKILL_LEVEL];
  5570.         ss << "You advanced to " << getSkillName(skill) << " level " << skills[skill][SKILL_LEVEL] << ".";
  5571.         sendTextMessage(MSG_EVENT_ADVANCE, ss.str().c_str());
  5572.         ss.str("");
  5573.     }
  5574.  
  5575.     ss << std::fixed << std::setprecision(2) << "Your " << ucwords(getSkillName(skill)) << " skill changed from level " << oldSkillValue << " (with " << oldPercentToNextLevel << "% progress towards level " << (oldSkillValue + 1) << ") to level " << newSkillValue << " (with " << newPercentToNextLevel << "% progress towards level " << (newSkillValue + 1) << ")";
  5576.     sendTextMessage(MSG_EVENT_ADVANCE, ss.str().c_str());
  5577.     return true;
  5578. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement