Advertisement
Guest User

player.cpp

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